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 latest main and reconcile group owner labels

shenjiacheng938e79320448
diff --cc apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
index 22c49f2926,c13f270b3a..a7a0fcb336
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@@ -162,25 -171,94 +171,113 @@@ describe('Chat Server result delivery a
service = withChatServer({ listGroups: vi.fn(async () => ({ ok: true, groups: [] })), settleLaneTurn: vi.fn(async () => false), dispose: vi.fn() } as unknown as BotGroupChatService, deps);
});
afterEach(() => { service.dispose(); vi.useRealTimers(); vi.unstubAllEnvs(); fixture.config = ''; vi.clearAllMocks(); });
+ // #6907: getGroup feeds Desktop and remote phones. Existing fixtures never pair group name A
+ // with the bot's account ownerName B; exercise the production projection (unit tier).
+ it.each(['Nickname A', 'Account B', ' ', null] as const)('uses the current room owner name %s with safe account fallback', async name => {
+ const ownerId = '30000000-0000-4000-8000-000000000002';
+ const bot = { id: botId, kind: 'bot', name: 'Companion X', state: 'joined', role: 'member', ownerActorId: ownerId, ownerName: 'Account B' };
+ const members = [bot, ...(name === null ? [] : [{ id: ownerId, kind: 'human', name, state: 'joined', role: 'member', ownerActorId: ownerId }])];
+ const messages = [{ id: execution.source_message_id, seq: '1', authorId: botId, author: { kind: 'bot', name: 'Companion X' },
+ content: [{ type: 'text', text: 'Example reply' }], createdAt: '2026-10-03T00:00:00Z', deleted: false, threadRootId: null }];
+ if (name !== null) messages.push({ ...messages[0], id: '50000000-0000-4000-8000-000000000002', seq: '2', authorId: ownerId,
+ author: { kind: 'human', name: 'Account B' }, content: [{ type: 'text', text: 'Example owner message' }], createdAt: '2026-10-03T00:06:00Z' });
+ fixture.handle.mockImplementation(route => route.endsWith('/snapshot') ? { body: { room: room(roomId), members, messages, cursor: '1' } } : route.includes('/messages?') ? { body: messages } : response(route));
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error(result.errorCode);
+ const owner = name?.trim() || 'Account B';
+ expect(result.group.members.find(m => m.actorId === botId)).toMatchObject({ name: `Companion X (${owner})`, ownerName: owner, ownerActorId: ownerId, isOwned: false });
+ expect(result.group.messages[0]).toMatchObject({ authorName: `Companion X (${owner})`, authorBotId: botId });
+ if (name !== null) expect(result.group.messages[1]).toMatchObject({ authorName: name, authorBotId: ownerId, authorKind: 'user' });
+ expect(bot).toMatchObject({ name: 'Companion X', ownerName: 'Account B', ownerActorId: ownerId });
+ });
+ describe('分工 auto-continue on this computer (bot-group-chat.md §7.4)', () => {
+ const planId = '80000000-0000-4000-8000-000000000009';
+ const otherHuman = '30000000-0000-4000-8000-000000000002';
+ const division = (over: Record<string, unknown> = {}, first = 'done') => ({ id: planId, revision: 3, kind: 'work',
+ source_message_id: execution.source_message_id, request_text: 'build it', organizer_id: botId, creator_id: selfId,
+ status: 'waiting', current_step: 0, created_at: '2026-10-03T00:00:00Z', updated_at: '2026-10-03T00:00:00Z',
+ steps: [{ position: 0, botId, botName: 'Bot', task: 'draft', status: first }, { position: 1, botId, botName: 'Bot', task: 'polish', status: 'pending' }],
+ ...over });
+ const continues = () => fixture.handle.mock.calls.filter(([route, method, body]) =>
+ route === `/conversations/${roomId}/plans/${planId}` && method === 'POST' && (body as { action?: string })?.action === 'continue');
+ const stepEnded = async (cursor: string) => {
+ fixture.sockets[0]!.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor,
+ changes: [{ type: 'execution.updated', entityId: execution.id }] }));
+ await vi.advanceTimersByTimeAsync(0);
+ };
+ async function serve(plan: Record<string, unknown>, settings: { autoContinue?: boolean; startedHere?: string[] } | null,
+ onContinue?: () => { status: number; body: unknown }, onRead?: () => void) {
+ if (settings) workspaceSettings.set(roomId, { projectDir: null, plans: {}, startedHere: [planId], ...settings });
+ // Only a server that tells a 分工 from a queue (groupSingleSpeaker) offers the switch.
+ fixture.handle.mockImplementation((route, method) => route === `/conversations/${roomId}/plans/${planId}` && method === 'POST'
+ ? onContinue?.() ?? { body: {} } : route.startsWith(`/conversations/${roomId}/plans`) ? (onRead?.(), { body: [plan] })
+ : route === '/me' ? { body: { actor: { id: selfId }, capabilities: { groupSingleSpeaker: 1 } } } : response(route));
+ await service.getGroup(roomId);
+ await vi.advanceTimersByTimeAsync(2000);
+ }
+ it('goes on to the next step of a 分工 started here once a step is done', async () => {
+ await serve(division(), { autoContinue: true });
+ await stepEnded('2');
+ expect(continues()).toHaveLength(1);
+ expect(continues()[0]![2]).toMatchObject({ expectedRevision: 3 });
+ });
+ it('goes on with a step that ended before the room was first read (a cold start)', async () => {
+ await serve(division(), { autoContinue: true });
+ expect(continues()).toHaveLength(1);
+ // The same finished step is not continued twice when later changes arrive.
+ await stepEnded('3');
+ expect(continues()).toHaveLength(1);
+ });
+ it.each([
+ ['the switch is off', division(), { autoContinue: false }],
+ ['nothing was chosen on this computer', division(), null],
+ ['the step failed and waits for 重试', division({}, 'failed'), { autoContinue: true }],
+ ['someone else started the 分工', division({ creator_id: otherHuman }), { autoContinue: true }],
+ // The account is the creator on each of its computers: another one of them asked for this 分工.
+ ['it was asked for on another computer', division(), { autoContinue: true, startedHere: [] }],
+ ['it is a discussion queue, not a 分工', division({ kind: 'talk' }), { autoContinue: true }],
+ ['the 分工 was stopped', division({ status: 'stopped' }), { autoContinue: true }],
+ ['the last step is done', division({ current_step: 1, status: 'waiting', steps: [
+ { position: 0, botId, botName: 'Bot', task: 'draft', status: 'done' }, { position: 1, botId, botName: 'Bot', task: 'polish', status: 'done' }] }), { autoContinue: true }],
+ ])('keeps waiting for 继续 when %s', async (_case, plan, settings) => {
+ await serve(plan, settings);
+ await stepEnded('2');
+ expect(continues()).toHaveLength(0);
+ });
+ it('turning it on while a step waits goes on now, and shows the choice on the group and its 分工 card', async () => {
+ await serve(division(), { autoContinue: false });
+ const before = await service.getGroup(roomId);
+ expect(before.ok && [before.group.autoContinue, before.group.plans[0]?.autoContinue]).toEqual([false, false]);
+ expect(await service.updateGroup({ groupId: roomId, autoContinue: true })).toEqual({ ok: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(workspaceSettings.get(roomId)).toMatchObject({ autoContinue: true, projectDir: null });
+ expect(continues()).toHaveLength(1);
+ const after = await service.getGroup(roomId);
+ expect(after.ok && [after.group.autoContinue, after.group.plans[0]?.autoContinue]).toEqual([true, true]);
+ });
+ it('does not go on when the switch is turned off while the 分工 is read', async () => {
+ await serve(division(), { autoContinue: true }, undefined, () => {
+ workspaceSettings.set(roomId, { ...workspaceSettings.get(roomId) as object, autoContinue: false });
+ });
+ await stepEnded('2');
+ expect(continues()).toHaveLength(0);
+ });
+ it('turning it off while the 分工 is read stops the handoff before the group is re-read', async () => {
+ await serve(division(), { autoContinue: true }, undefined, () => { void service.updateGroup({ groupId: roomId, autoContinue: false }); });
+ expect(continues()).toHaveLength(0);
+ });
+ it('does not offer the switch on a server that cannot tell a 分工 from a queue', async () => {
+ workspaceSettings.set(roomId, { projectDir: null, plans: {}, autoContinue: true });
+ const result = await service.getGroup(roomId);
+ expect(result.ok && result.group).not.toHaveProperty('autoContinue');
+ });
+ it('does not try again after someone else went on first', async () => {
+ await serve(division(), { autoContinue: true }, () => ({ status: 409, body: { error: { code: 'REVISION_CONFLICT' } } }));
+ await stepEnded('2');
+ await stepEnded('3');
+ expect(continues()).toHaveLength(1);
+ });
+ });
it('uses the mobile edited revision instead of a newer server snapshot when saving settings', async () => {
await service.updateGroup({ groupId: roomId, name: 'Draft', expectedRevision: 7 });
expect(fixture.handle).toHaveBeenCalledWith(`/conversations/${roomId}`, 'PATCH', expect.objectContaining({ name: 'Draft', expectedRevision: 7 }));
@@@ -1633,17 -1915,169 +1934,170 @@@
expect(deliveries()[0][2]).not.toHaveProperty('continueDiscussion');
});
- it('sends without holding the request for a helper-model arrangement decision', async () => {
- singleSpeaker();
- deps.decidePlan = vi.fn() as typeof deps.decidePlan;
- expect(await service.sendMessage({ groupId: roomId, text: 'Make a draft', clientId: 'single-speaker-send', mentions: { all: false, botIds: [] }, division: true }))
- .toMatchObject({ ok: true });
- await vi.advanceTimersByTimeAsync(0);
- const post = fixture.handle.mock.calls.find(([route, method]) => route === `/conversations/${roomId}/messages` && method === 'POST')!;
- expect(post[2].deferExecution).toBe(false);
- expect(deps.decidePlan).not.toHaveBeenCalled();
+ it.each(['talk', 'work'] as const)('delivers explicit files for talk replies without changing the work pipeline (%s)', async kind => {
+ const planId = '80000000-0000-4000-8000-000000000001';
+ const plan = { id: planId, revision: 1, source_message_id: execution.source_message_id, request_text: 'Report', organizer_id: botId, creator_id: selfId,
+ status: 'running', current_step: 0, kind, steps: [{ position: 0, botId, botName: 'Bot', task: 'report', status: 'running' }] };
+ singleSpeaker(route => {
+ if (route === '/executions/claim' && !claimed) { claimed = true; return { body: { execution: { ...execution, access_mode: kind === 'talk' ? 'owner' : 'chat', plan_id: planId, plan_step: 0 } } }; }
+ if (route.includes('/plans?ids=')) return { body: [plan] };
+ if (route.endsWith(`/messages/${execution.source_message_id}`)) return { body: message(execution.source_message_id, 'Report') };
+ return undefined;
+ });
+ replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [{ id: 'pdf', name: 'report.pdf' }] });
+ fixture.upload.mockImplementationOnce(async () => kind === 'talk' ? [{ type: 'media', mediaId: 'pdf', caption: 'report.pdf' }] : []);
+ if (kind === 'talk') await startFileReply(); else await start();
+ await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });
+ expect(deliveries()[0][2]).not.toHaveProperty('continueDiscussion');
+ if (kind === 'talk') {
+ expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: 'Report' }, { type: 'media', mediaId: 'pdf', caption: 'report.pdf' }]);
+ } else {
+ expect(replyFiles.prepare).not.toHaveBeenCalled();
+ expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: '[Report](./report.pdf)' }]);
+ }
+ });
+
+ // A queue turn builds on the answer just before it (a 分工 hand-off's 2000 characters); older
+ // answers get a main-group message's 600, so a long queue does not resend every answer in full.
+ it('shortens the earlier answers a queue turn reads', async () => {
+ const planId = '80000000-0000-4000-8000-000000000003';
+ const ids = ['50000000-0000-4000-8000-000000000041', '50000000-0000-4000-8000-000000000042', '50000000-0000-4000-8000-000000000043'];
+ const texts = ['a'.repeat(601), 'b'.repeat(600), 'c'.repeat(2001)];
+ const plan = { id: planId, revision: 1, source_message_id: execution.source_message_id, request_text: 'Q', organizer_id: otherBot, creator_id: selfId,
+ note_message_ids: [], status: 'running', current_step: 3, kind: 'talk', created_at: '2026-10-03T00:00:00Z', updated_at: '2026-10-03T00:00:00Z',
+ steps: [...ids.map((resultMessageId, position) => ({ position, botId: otherBot, botName: 'Peer', task: '', status: 'done', resultMessageId })),
+ { position: 3, botId, botName: 'Bot', task: '', status: 'running' }] };
+ singleSpeaker(route => {
+ if (route === '/executions/claim' && !claimed) { claimed = true; return { body: { execution: { ...execution, access_mode: 'owner', plan_id: planId, plan_step: 3 } } }; }
+ if (route.includes('/plans?ids=')) return { body: [plan] };
+ if (route.includes('/messages?all=true')) return { body: ids.map((id, index) => message(id, texts[index]!, { authorId: otherBot, author: { kind: 'bot', name: 'Peer' }, origin: 'bot' })) };
+ if (route.endsWith(`/messages/${execution.source_message_id}`)) return { body: message(execution.source_message_id, 'Q') };
+ return undefined;
+ });
+ await start();
+ const block = prompt().split('<untrusted-data>\n').map(part => part.split('\n</untrusted-data>')[0]!).find(part => part.includes('earlierAnswers'))!;
+ expect(JSON.parse(block).earlierAnswers).toEqual([
+ { from: 'Peer', text: `${'a'.repeat(600)}…`, shortened: true },
+ { from: 'Peer', text: 'b'.repeat(600) },
+ { from: 'Peer', text: `${'c'.repeat(2000)}…`, shortened: true },
+ ]);
});
+ // bot-group-chat.md §7.0 (2026-10-23): 「安排分工」 is back on these servers. A request that writes
+ // out who does what becomes that card and starts, with no helper model; otherwise the organizer
+ // arranges it. The request is held so the server's own queue does not answer it first.
+ describe('安排分工', () => {
+ const sourceId = '50000000-0000-4000-8000-000000000031', planId = '80000000-0000-4000-8000-000000000031';
+ const named = () => members().map(m => m.id === otherBot ? { ...m, name: 'Nova' } : m);
+ function divisionServer(open: object[] = []) {
+ singleSpeaker((route, method) => {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members: named(), messages: [], cursor: '1' } };
+ if (route === `/conversations/${roomId}/messages` && method === 'POST') return { body: { id: sourceId } };
+ if (route === `/conversations/${roomId}/plans` && method === 'POST') return { body: { id: planId, revision: 1 } };
+ if (route === `/conversations/${roomId}/plans`) return { body: open };
+ return undefined;
+ });
+ }
+ const posts = () => fixture.handle.mock.calls.filter(([, method]) => method === 'POST');
+ const send = async (text: string) => {
+ expect(await service.sendMessage({ groupId: roomId, text, clientId: `division-${text.length}`, mentions: { all: false, botIds: [] }, division: true }))
+ .toMatchObject({ ok: true });
+ await vi.advanceTimersByTimeAsync(0);
+ };
+
+ it('starts the card a request writes out, without the organizer', async () => {
+ divisionServer();
+ deps.decidePlan = vi.fn() as typeof deps.decidePlan;
- await send('登录页:@Bot (Owner) 出方案,然后 @Nova (Owner) 按方案实现');
++ // #6907: full labels use the human's group name Peer, not account name Owner.
++ await send('登录页:@Bot (Peer) 出方案,然后 @Nova (Peer) 按方案实现');
+ expect(posts().find(([route]) => route === `/conversations/${roomId}/messages`)![2]).toMatchObject({ deferExecution: true });
+ expect(posts().find(([route]) => route === `/conversations/${roomId}/plans`)![2]).toMatchObject({ sourceMessageId: sourceId,
+ steps: [{ botId, task: '出方案' }, { botId: otherBot, task: '按方案实现' }] });
+ expect(posts().find(([route]) => route === `/conversations/${roomId}/plans/${planId}`)![2]).toMatchObject({ action: 'start', expectedRevision: 1 });
+ expect(deps.decidePlan).not.toHaveBeenCalled();
+ // Only a 分工 asked for here follows this computer's 自动交接.
+ expect(workspaceSettings.get(roomId)).toMatchObject({ startedHere: [planId] });
+ });
+
+ it('lets the organizer arrange it when a picked teammate no longer reads in the text', async () => {
+ divisionServer();
+ deps.decidePlan = vi.fn(async () => ({ needsPlan: true as const, steps: [{ botId, task: 'design' }, { botId: otherBot, task: 'build' }] }));
+ // Bot was picked as @OldName and renamed before sending: its step must not be dropped.
+ expect(await service.sendMessage({ groupId: roomId, text: '@OldName 出方案,然后 @Nova (Owner) 按方案实现', clientId: 'division-renamed',
+ mentions: { all: false, botIds: [botId, otherBot] }, division: true })).toMatchObject({ ok: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(deps.decidePlan).toHaveBeenCalled();
+ expect(posts().some(([route]) => route === `/conversations/${roomId}/plans/${planId}`)).toBe(false);
+ });
+
+ it('answers the request when nobody can arrange it, and later messages still go out', async () => {
+ divisionServer();
+ deps.decidePlan = undefined;
+ await send('Make a draft');
+ expect(posts().some(([route]) => route === `/conversations/${roomId}/messages/${sourceId}/continue`)).toBe(true);
+ expect(await service.sendMessage({ groupId: roomId, text: 'Another thing', clientId: 'after-no-organizer', mentions: { all: false, botIds: [] } }))
+ .toMatchObject({ ok: true });
+ });
+
+ // §4.0: in a mention-only group an unaddressed message wakes nobody, not even the helper revising your proposed card.
+ it.each([['all', true], ['mentioned', false]] as const)('in %s mode, unaddressed words revise your proposed card: %s', async (mode, revises) => {
+ const proposed = { id: planId, revision: 1, source_message_id: execution.source_message_id, request_text: 'Q', organizer_id: botId, creator_id: selfId,
+ note_message_ids: [], status: 'proposed', current_step: null, kind: 'work', created_at: '2026-10-03T00:00:00Z', updated_at: '2026-10-03T00:00:00Z',
+ steps: [{ position: 0, botId, botName: 'Bot', task: 'draft', status: 'pending' }] };
+ singleSpeaker((route, method) => {
+ if (route.endsWith('/snapshot')) return { body: { room: { ...room(roomId), response_mode: mode }, members: named(), messages: [], cursor: '1' } };
+ if (route === `/conversations/${roomId}/messages` && method === 'POST') return { body: { id: sourceId } };
+ if (route === `/conversations/${roomId}/plans`) return { body: [proposed] };
+ return undefined;
+ });
+ deps.decidePlan = vi.fn(async () => null);
+ expect(await service.sendMessage({ groupId: roomId, text: 'Make it shorter', clientId: `revise-${mode}`, mentions: { all: false, botIds: [] } }))
+ .toMatchObject({ ok: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(posts().find(([route]) => route === `/conversations/${roomId}/messages`)![2]).toMatchObject({ deferExecution: revises });
+ expect(vi.mocked(deps.decidePlan!).mock.calls.length > 0).toBe(revises);
+ });
+
+ // The server cannot release a held request, so a newer message must not replace one still being arranged.
+ it('refuses a newer message while the organizer is arranging', async () => {
+ divisionServer();
+ deps.decidePlan = vi.fn(() => new Promise<never>(() => {}));
+ await send('Make a draft');
+ expect(await service.sendMessage({ groupId: roomId, text: 'Another thing', clientId: 'after-division', mentions: { all: false, botIds: [] } }))
+ .toMatchObject({ ok: false, errorCode: 'PLAN_OPEN' });
+ expect(posts().filter(([route]) => route === `/conversations/${roomId}/messages`)).toHaveLength(1);
+ });
+
+ it('asks the organizer when the steps are not written out', async () => {
+ divisionServer();
+ deps.decidePlan = vi.fn(async () => ({ needsPlan: true as const, steps: [{ botId: otherBot, task: 'build' }] }));
+ await send('@Bot (Owner) 和 @Nova (Owner) 一起做登录页');
+ expect(deps.decidePlan).toHaveBeenCalledWith(expect.objectContaining({ mode: 'forced' }), expect.anything());
+ expect(posts().find(([route]) => route === `/conversations/${roomId}/plans`)![2]).toMatchObject({ steps: [{ botId: otherBot, task: 'build' }] });
+ expect(posts().some(([route]) => route === `/conversations/${roomId}/plans/${planId}`)).toBe(false);
+ });
+
+ it('answers the request at once when no card comes of it, instead of a queue two minutes later', async () => {
+ divisionServer();
+ deps.decidePlan = vi.fn(async () => { throw new Error('model unavailable'); });
+ await send('Make a draft');
+ expect(posts().some(([route]) => route === `/conversations/${roomId}/messages/${sourceId}/continue`)).toBe(true);
+ });
+
+ it('ends your queue waiting for 继续 before opening the card', async () => {
+ const queue = { id: '80000000-0000-4000-8000-000000000032', revision: 4, source_message_id: execution.source_message_id, request_text: 'Q', organizer_id: botId,
+ creator_id: selfId, note_message_ids: [], status: 'waiting', current_step: 4, kind: 'talk', created_at: '2026-10-03T00:00:00Z', updated_at: '2026-10-03T00:00:00Z',
+ steps: [{ position: 4, botId, botName: 'Bot', task: '', status: 'done' }] };
+ divisionServer([queue]);
+ await send('@Bot (Owner) 出方案');
+ const routes = posts().map(([route]) => route);
+ expect(routes.indexOf(`/conversations/${roomId}/plans/${queue.id}`)).toBeLessThan(routes.indexOf(`/conversations/${roomId}/plans`));
+ expect(posts().find(([route]) => route === `/conversations/${roomId}/plans/${queue.id}`)![2]).toMatchObject({ action: 'stop', expectedRevision: 4 });
+ });
+ });
+
+ // Words for a card under way reach its current step when they would wake anyone: the requester
+ // adding to a turn, or asking the teammate who just finished a 分工 step to redo it (§4.0, §7.4).
it.each([
['waiting for 继续: a new request replaces it', 'waiting', `/conversations/${roomId}/messages`],
['mid-turn: the words go to the teammate answering', 'running', `/conversations/${roomId}/plans/80000000-0000-4000-8000-000000000002/messages`],
diff --cc apps/desktop/src/main/maker-ipc/chatServer.ts
index 2f0f466e7c,1b98cac22b..3fed9793b6
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@@ -1041,10 -1110,10 +1108,10 @@@ function createChatServer(local: BotGro
planId: null, files: [], attachments: [], createdAt: Date.parse(m.createdAt) };
const quote = m.deleted || planCard ? null : readBotGroupQuote(m.content);
const task = m.deleted || planCard ? null : taskCardOf(m);
- return { id: m.id, sequence: Number(m.seq), deleted: m.deleted, kind: planCard ? 'plan' : 'message', authorKind: legacy?.authorKind === 'system' ? 'system' : m.author.kind === 'human' ? 'user' : 'bot',
+ return { id: m.id, sequence: Number(m.seq), serverSequence: m.seq, deleted: m.deleted, kind: planCard ? 'plan' : 'message', authorKind: legacy?.authorKind === 'system' ? 'system' : m.author.kind === 'human' ? 'user' : 'bot',
isSelf: m.authorId === selfId, threadRootId: m.threadRootId, replyCount: m.replyCount ?? 0, reactions: m.reactions ?? [], ...(quote ? { quote } : {}), ...(task ? { task } : {}),
- authorBotId: localBot(m.authorId)?.id ?? m.authorId, authorName: legacy?.authorKind === 'system' && typeof legacy.authorName === 'string' ? legacy.authorName : member ? memberName(member) : m.author.name, content: displayText(m),
+ authorBotId: localBot(m.authorId)?.id ?? m.authorId, authorName: legacy?.authorKind === 'system' && typeof legacy.authorName === 'string' ? legacy.authorName : member ? memberName(member, members) : m.author.name, content: displayText(m),
- mentions: { all: false, botIds: [] }, noticeCode: null, planId: typeof planCard?.data?.planId === 'string' ? planCard.data.planId : null, files: [], attachments: [], createdAt: Date.parse(m.createdAt) };
+ mentions: { all: false, botIds: (m.mentions ?? []).map(actorId => localBot(actorId)?.id ?? actorId) }, noticeCode: null, planId: typeof planCard?.data?.planId === 'string' ? planCard.data.planId : null, files: [], attachments: [], createdAt: Date.parse(m.createdAt) };
}
/**
* When the newest (up to 99) messages from someone else arrived, oldest first: Bots and other
@@@ -1304,7 -1377,7 +1375,7 @@@
const lastView = last ? messageView(last, s.members) : null;
// The sidebar never resolves shares: it names the sharer and never quotes the card's text.
const lastIsShare = !!last && !!readBotGroupThreadShareCard(last);
- return { serverBacked: true, reactionRevision: reactionRevisions.get(roomId)?.room ?? runtimeReactionRevision, reactionRevisions: { ...reactionRevisions.get(roomId)?.messages }, supportsGroupLeave: true, supportsDissolve, supportsListRemoval, supportsMemberAvatar, dissolvedAt: s.room.dissolved_at ?? null, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: !s.room.dissolved_at && s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), canStopAll: singleSpeaker && !!managementActor(s), ...(singleSpeaker ? { singleSpeaker: true } : {}), id: s.room.id, name: s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,
- return { conversationKind: direct ? 'direct' : 'group', serverBacked: true, reactionRevision: reactionRevisions.get(roomId)?.room ?? runtimeReactionRevision, reactionRevisions: { ...reactionRevisions.get(roomId)?.messages }, supportsGroupLeave: !direct, supportsDissolve: !direct && supportsDissolve, supportsListRemoval, supportsMemberAvatar: !direct && supportsMemberAvatar, dissolvedAt: s.room.dissolved_at ?? null, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: !direct && !s.room.dissolved_at && s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), canStopAll: !direct && singleSpeaker && !!managementActor(s), ...(!direct && singleSpeaker ? { singleSpeaker: true, supportsDivision: true } : {}), id: s.room.id, name: direct ? s.members.filter(m => m.state === 'joined' && m.id !== selfId).map(memberName).join(', ') || s.room.name : s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,
++ return { conversationKind: direct ? 'direct' : 'group', serverBacked: true, reactionRevision: reactionRevisions.get(roomId)?.room ?? runtimeReactionRevision, reactionRevisions: { ...reactionRevisions.get(roomId)?.messages }, supportsGroupLeave: !direct, supportsDissolve: !direct && supportsDissolve, supportsListRemoval, supportsMemberAvatar: !direct && supportsMemberAvatar, dissolvedAt: s.room.dissolved_at ?? null, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: !direct && !s.room.dissolved_at && s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), canStopAll: !direct && singleSpeaker && !!managementActor(s), ...(!direct && singleSpeaker ? { singleSpeaker: true, supportsDivision: true } : {}), id: s.room.id, name: direct ? s.members.filter(m => m.state === 'joined' && m.id !== selfId).map(member => memberName(member, [])).join(', ') || s.room.name : s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,
members: s.members.filter(m => m.state === 'joined').map(m => {
const p = localBot(m.id);
return { botId: p?.id ?? m.id, actorId: m.id, actorKind: m.kind, isSelf: m.id === selfId,
@@@ -1314,10 -1387,12 +1385,12 @@@
// reads the companion's tasks there, not here (bot-group-chat.md §10).
...(m.ownerActorId === selfId && m.kind === 'bot' ? { homeDeviceId: actors.find(a => a.id === m.id)?.homeDeviceId ?? null } : {}),
avatarUrl: m.avatar?.startsWith('https://') ? m.avatar : null,
- name: memberName(m), avatar: m.groupAvatar ? '' : p?.avatar ?? (m.avatar?.startsWith('https://') ? '' : m.avatar) ?? '', avatarColor: p?.avatarColor ?? 'violet', status: p?.status ?? 'active' };
+ name: memberName(m, s.members), avatar: m.groupAvatar ? '' : p?.avatar ?? (m.avatar?.startsWith('https://') ? '' : m.avatar) ?? '', avatarColor: p?.avatarColor ?? 'violet', status: p?.status ?? 'active' };
- }), organizerBotId: s.room.organizer_id ? localBot(s.room.organizer_id)?.id ?? s.room.organizer_id : s.members.find(m => m.kind === 'bot' && m.state === 'joined')?.id ?? null, projectDir: workspace?.projectDir ?? null, lastMessage: last && lastView ? {
+ }), organizerBotId: direct ? null : ((id?: string) => id ? localBot(id)?.id ?? id : null)(s.room.organizer_id ?? s.members.find(m => m.kind === 'bot' && m.state === 'joined')?.id), projectDir: workspace?.projectDir ?? null,
+ // Only servers that tell a 分工 from a queue (kind) can hand one on by itself.
+ ...(singleSpeaker ? { autoContinue: workspace?.autoContinue === true } : {}), lastMessage: last && lastView ? {
isSelf: lastView.isSelf, authorKind: lastView.authorKind, authorName: lastView.authorName, noticeCode: lastView.noticeCode,
- preview: lastIsShare ? '' : (botGroupMessageSummaryText(lastView) || mediaNames(last)).slice(0, 80), createdAt: lastView.createdAt, ...(lastIsShare ? { threadShare: true } : {}),
+ preview: lastIsShare ? '' : notificationPreview(botGroupMessageSummaryText(lastView) || mediaNames(last), 80), createdAt: lastView.createdAt, ...(lastIsShare ? { threadShare: true } : {}),
} : null, speakingBotIds: speakers.map(s => s.botId), planningBotId: planning.get(roomId)?.botId ?? null, openPlan: open ? { id: open.id, status: open.status, currentStep: open.currentStep, stepCount: open.steps.length, currentBotName: open.steps[open.currentStep ?? 0]?.botName ?? null, currentStepStatus: open.steps[open.currentStep ?? 0]?.status ?? null, ...(open.kind ? { kind: open.kind } : {}) } : null,
lastReplyAt: s.messages.reduce((latest, m) => !m.deleted && m.origin !== 'system' && m.authorId !== selfId
? Math.max(latest, Date.parse(m.createdAt)) : latest, 0),
@@@ -1398,6 -1533,54 +1531,54 @@@
}
} finally { delete intent.sourceId; if (planning.get(s.room.id) === pending) { planning.delete(s.room.id); changed(s.room.id); } }
}
+ /** Steps read the plan's request; keep what it quotes beside it when the server's limit allows. */
+ function planRequest(text: string, quote: BotGroupQuoteView | null) {
+ const quoteLine = quote ? buildBotGroupQuoteCard(quote).fallback : '';
+ return quoteLine && text.length + quoteLine.length + 2 <= 8000 ? `${text}\n\n${quoteLine}` : text;
+ }
+ /**
+ * A 分工 with no card. Servers that can cancel a planning hold are told so. A single-speaker
+ * server cannot, and would queue the held request two minutes later; a 「安排分工」 request is
+ * answered right away instead (named teammates, else the first), and a note on your proposed
+ * card stays a note.
+ */
+ async function settleExplicitRequest(roomId: string, sourceId: string, answer: boolean) {
+ if (!singleSpeaker) return cancelPlanning(roomId, sourceId, true);
+ if (answer) await api(`/conversations/${roomId}/messages/${sourceId}/continue`, 'POST', { operationId: `discuss:${sourceId}` });
+ }
+ /** Steps a 分工 request wrote out (§7.0), as teammates this account may give work to. */
+ function writtenPlanSteps(s: Snapshot, text: string, picked: string[]): PlanStepDraft[] | null {
+ const bots = s.members.filter(m => m.kind === 'bot' && m.state === 'joined');
+ const written = splitBotGroupRelaySteps(text, { allLabels: [],
- members: bots.map(m => ({ botId: m.id, name: memberName(m), displayName: m.name, nickname: m.nickname })) });
++ members: bots.map(m => ({ botId: m.id, name: memberName(m, s.members), displayName: m.name, nickname: m.nickname })) });
+ // A picked teammate whose name no longer reads in the text (renamed meanwhile) would silently
+ // drop its step: let the organizer arrange it instead.
+ if (written && !picked.every(target => written.some(step => step.botId === target || localBot(step.botId)?.id === target))) return null;
+ // A step for a teammate you may not give work to goes to the organizer, not into a neighbour's task.
+ const assignable = (botId: string) => bots.some(m => m.id === botId && (m.ownerActorId === selfId || m.guestAccess !== 'none')
+ && (!localBot(m.id) || localBot(m.id)?.status === 'active'));
+ return written?.every(step => assignable(step.botId)) ? draftPlanSteps(written) : null;
+ }
+ /** The user wrote the card, so it starts at once; each step still stops for 继续 (§7.4). */
+ async function openWrittenPlan(s: Snapshot, sourceId: string, request: string, steps: PlanStepDraft[], intent: PlanIntent) {
+ if (!current() || planIntents.get(s.room.id) !== intent) return;
+ // The organizer settings show: the chosen one, else the first companion.
+ const shown = s.room.organizer_id ?? s.members.find(m => m.kind === 'bot' && m.state === 'joined')?.id;
+ const organizerId = steps.some(step => step.botId === shown) ? shown! : steps[0]!.botId;
+ let plan: ServerPlan;
+ try {
+ plan = await api<ServerPlan>(`/conversations/${s.room.id}/plans`, 'POST', {
+ operationId: `plan:${sourceId}`, sourceMessageId: sourceId, organizerId, request, steps });
+ markStartedHere(s.room.id, plan.id);
+ } catch (error) {
+ await settleExplicitRequest(s.room.id, sourceId, true);
+ throw error;
+ } finally { delete intent.sourceId; }
+ // Not started (the card stays proposed with 开始) if a newer action took over meanwhile.
+ if (current() && planIntents.get(s.room.id) === intent) await api(`/conversations/${s.room.id}/plans/${plan.id}`, 'POST', {
+ operationId: `start:${plan.id}`, expectedRevision: plan.revision, action: 'start' });
+ changed(s.room.id);
+ }
async function updateExecution(run: Running, action: string, extra: Record<string, unknown> = {}) {
return api(`/conversations/${run.execution.conversation_id}/executions/${run.execution.id}`, 'POST', {
// Each heartbeat must extend the lease rather than replay a cached receipt.
diff --cc apps/mobile/src/__tests__/chatServerClient.test.ts
index a2b090f1e1,79a2dadaeb..d30499b007
--- a/apps/mobile/src/__tests__/chatServerClient.test.ts
+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts
@@@ -13,26 -14,12 +14,32 @@@ const snapshot = (): ChatSnapshot => (
] });
describe('direct Chat Server client', () => {
+ // #6907: existing fixtures never pair a human's group name A with account ownerName B (unit tier).
+ it('keeps owner labels scoped to each group and follows refreshed names without changing identities', () => {
+ const human = { ...snapshot().members[0], name: 'Nickname A' };
+ const bot = { ...human, id: id(12), kind: 'bot' as const, name: 'Companion X', ownerName: 'Account B' };
+ const messages = [message(20), { ...message(21), authorId: bot.id, author: { kind: 'bot', name: bot.name } }];
+ const group = (name: string, roomNumber = 1) => ({ ...snapshot(), room: room(roomNumber), members: [{ ...human, name }, bot], messages });
+ const project = (s: ChatSnapshot) => chatGroupView({ snapshot: s, messages, before: null }, id(11));
+ const first = group('Nickname A');
+ expect(project(first).messages.map(m => m.authorName)).toEqual(['Nickname A', 'Companion X (Nickname A)']);
+ expect(chatRoomRow(first.room, first).item.display.subtitle).toBe('Nickname A · Companion X (Nickname A)');
+ expect(project(group('Nickname C')).messages[1].authorName).toBe('Companion X (Nickname C)');
+ expect(project(group('Nickname D', 2)).messages[1].authorName).toBe('Companion X (Nickname D)');
+ expect(project(first).messages[1].authorName).toBe('Companion X (Nickname A)');
+ for (const name of ['Account B', ' ']) expect(project(group(name)).messages[1].authorName).toBe('Companion X (Account B)');
+ expect(project({ ...first, members: [bot] }).messages[1].authorName).toBe('Companion X (Account B)');
+ expect(project({ ...first, members: [{ ...human, state: 'left' }, bot] }).messages[1].authorName).toBe('Companion X (Account B)');
+ expect(project({ ...first, members: [{ ...bot, ownerName: ' ' }] }).messages[1].authorName).toBe('Companion X');
+ expect(project(first).members.find(m => m.actorId === bot.id)).toMatchObject({ botId: bot.id, isOwned: false });
+ expect(bot).toMatchObject({ name: 'Companion X', ownerName: 'Account B', ownerActorId: human.id });
+ });
+ it('preserves thread identity through projection into the history new-message counter', () => {
+ const view = chatGroupView({ snapshot: snapshot(), before: null, messages: [message(20),
+ { ...message(21), threadRootId: id(20) }, { ...message(22), threadRootId: id(99) }] }, id(11));
+ expect(botGroupNewMessageCount(view.messages, message(20).seq, id(20))).toBe(1);
+ expect(botGroupNewMessageCount(view.messages, message(20).seq)).toBe(0);
+ });
it('reads a 引用回复 card as the quote, keeps it out of text and previews, and marks a deleted original', () => {
const card = buildBotGroupQuoteCard({ messageId: id(20), authorName: 'Other member', authorKind: 'user', excerpt: 'original words',
attachmentCount: 0, attachmentName: null, sequence: 20 });
@@@ -271,6 -267,45 +287,46 @@@
});
expect(request.mock.calls[0]).toEqual(request.mock.calls[1]);
});
+ // Product rule: quoting a present companion addresses that companion; a deleted
+ // original must not send a stale quote or silently lose the user's reply.
+ it('sends a fresh quote with the companion recipient and rejects a deleted original', async () => {
+ const original = { ...message(20), authorId: id(12), author: { kind: 'bot', name: 'Before rename' } };
- const member = { ...snapshot().members[0], id: id(12), kind: 'bot', state: 'joined', name: 'Current name' };
++ const owner = { ...snapshot().members[0], name: 'Nickname A' };
++ const member = { ...owner, id: id(12), kind: 'bot', state: 'joined', name: 'Current name', ownerName: 'Account B' };
+ const request = vi.fn().mockImplementation(async (path: string, method?: string) => {
+ if (method === 'POST') return { id: id(21) };
- return path.endsWith('/members') ? [member] : original;
++ return path.endsWith('/members') ? [member, owner] : original;
+ });
+ const client = createChatServerClient(request);
+ const input = { clientId: 'quote-reply-operation', text: 'Agreed', mentions: { all: false, botIds: [] }, quote: { messageId: id(20) } };
+ await client.send(id(1), input);
+ expect(request).toHaveBeenLastCalledWith(`/conversations/${id(1)}/messages`, 'POST', expect.objectContaining({
- mentions: [id(12)], content: [expect.objectContaining({ type: 'card' }), { type: 'text', text: 'Agreed' }],
++ mentions: [id(12)], content: [expect.objectContaining({ type: 'card', data: expect.objectContaining({ authorName: 'Current name (Nickname A)' }) }), { type: 'text', text: 'Agreed' }],
+ }));
+ original.deleted = true;
+ request.mockClear();
+ await expect(client.send(id(1), input)).rejects.toThrow('QUOTE_UNAVAILABLE');
+ expect(request.mock.calls.some(([, method]) => method === 'POST')).toBe(false);
+ });
+ it('retries a lost quoted-send response with the identical posted content', async () => {
+ const original = message(20);
+ let lost = true;
+ const request = vi.fn().mockImplementation(async (path: string, method?: string) => {
+ if (method === 'POST') {
+ if (lost) { lost = false; throw new Error('NETWORK_ERROR'); }
+ return { id: id(21) };
+ }
+ return path.endsWith('/members') ? snapshot().members : original;
+ });
+ const client = createChatServerClient(request);
+ const input = { clientId: 'lost-quote-operation', text: 'Agreed', mentions: { all: false, botIds: [] }, quote: { messageId: id(20) } };
+ await expect(client.send(id(1), input)).rejects.toThrow('NETWORK_ERROR');
+ const posted = request.mock.calls.at(-1);
+ original.deleted = true;
+ await client.send(id(1), input);
+ expect(request.mock.calls.at(-1)).toEqual(posted);
+ expect(request.mock.calls.filter(([, method]) => method !== 'POST')).toHaveLength(2);
+ });
it('reauthorizes and replaces loaded older history on refresh instead of retaining deleted text', async () => {
const recent = Array.from({ length: 100 }, (_, n) => message(200 - n));
const request = vi.fn().mockResolvedValueOnce(snapshot()).mockResolvedValueOnce(recent)
diff --cc apps/mobile/src/chat/chatServerClient.ts
index c44cf5896a,680b9467c0..7880f4acdb
--- a/apps/mobile/src/chat/chatServerClient.ts
+++ b/apps/mobile/src/chat/chatServerClient.ts
@@@ -84,14 -92,15 +90,15 @@@ export function chatRoomRow(room: ChatR
.sort((a, b) => BigInt(chatCursor(a.seq)) < BigInt(chatCursor(b.seq)) ? 1 : -1)[0];
return { key: `chat:${room.id}`, host: { deviceId: '', deviceName: '' },
lastReplySequence: snapshot && selfId ? chatLastReplySequence(snapshot.messages, selfId) : undefined,
+ chatUnread: snapshot?.reads && selfId ? chatUnread(snapshot, selfId) : undefined,
- groupMembers: snapshot ? members.map(chatMemberIdentity) : undefined, item: {
+ groupMembers: snapshot ? members.map(member => chatMemberIdentity(member, members)) : undefined, item: {
ref: { collectionId: 'bot-groups', kind: 'bot-group', id: room.id },
revision: String(room.head ?? room.revision), display: { title: room.name,
- subtitle: members.map(memberName).join(' · '),
- ...(snapshot ? { preview: last ? mobileMarkdownPreviewText(botGroupMessageSummaryText({ content: contentText(last), task: taskCardOf(last) ?? undefined, deleted: last.deleted }) || mediaNames(last)).slice(0, 160) || members.map(memberName).join(' · ') : '' } : {}),
+ subtitle: members.map(member => memberName(member, members)).join(' · '),
- ...(snapshot ? { preview: last ? (botGroupMessageSummaryText({ content: contentText(last), task: taskCardOf(last) ?? undefined, deleted: last.deleted }) || mediaNames(last)).slice(0, 160) || members.map(member => memberName(member, members)).join(' · ') : '' } : {}),
++ ...(snapshot ? { preview: last ? mobileMarkdownPreviewText(botGroupMessageSummaryText({ content: contentText(last), task: taskCardOf(last) ?? undefined, deleted: last.deleted }) || mediaNames(last)).slice(0, 160) || members.map(member => memberName(member, members)).join(' · ') : '' } : {}),
timestamp: Date.parse(last?.createdAt ?? room.updated_at),
lastReplyAt: snapshot && selfId ? chatLastReplyAt(snapshot.messages, selfId) : undefined },
- links: members.map(member => ({ rel: 'member', label: memberName(member),
+ links: members.map(member => ({ rel: 'member', label: memberName(member, members),
target: { kind: 'resource', ref: { collectionId: 'teammates', kind: 'bot', id: member.id } } })),
} };
}
@@@ -163,28 -187,26 +185,26 @@@ export function chatGroupView(page: Cha
block.type === 'card' && block.namespace === 'cindy.membership' && block.schemaRevision === 1 && block.data?.type === 'member.joined');
const quote = message.origin === 'system' ? null : readBotGroupQuote(message.content);
const task = message.origin === 'system' ? null : taskCardOf(message);
- return { id: message.id, sequence: index + 1, kind: message.origin === 'system' ? 'notice' : 'message',
- ...(task ? { task } : {}),
+ return { id: message.id, sequence: index + 1, serverSequence: chatCursor(message.seq), kind: message.origin === 'system' ? 'notice' : 'message',
+ ...(task ? { task } : {}), threadRootId: message.threadRootId,
authorKind: message.origin === 'system' ? 'system' : message.author.kind === 'human' ? 'user' : 'bot',
authorBotId: message.authorId, authorName: joined && typeof joined.data?.displayName === 'string' ? joined.data.displayName
- : member ? memberName(member) : message.author.name,
+ : member ? memberName(member, members) : message.author.name,
- isSelf: message.authorId === selfId, content: contentText(message), mentions: { all: false, botIds: [] },
+ isSelf: message.authorId === selfId, content: contentText(message), mentions: { all: false, botIds: message.mentions ?? [] },
...(quote ? { quote: deletedIds.has(quote.messageId) ? { ...quote, originalDeleted: true } : quote } : {}),
noticeCode: joined ? 'member-joined' : null, planId: null, files: [],
- attachments: message.deleted ? [] : message.content.flatMap(block => {
- if (block.type !== 'media' || !block.mediaId) return [];
- return [{ id: block.mediaId, name: attachmentName(block), category: 'file' as const,
- mimeType: '', size: 0, url: null, path: null }];
- }), createdAt: Date.parse(message.createdAt) };
+ attachments: chatMessageAttachments(message), createdAt: Date.parse(message.createdAt) };
});
const last = messages.at(-1);
const failures = (page.failures ?? []).flatMap(row => {
const failure = readBotGroupExecutionFailure(row, room.id);
if (!failure) return [];
const member = members.find(candidate => candidate.id === failure.botId);
- return [{ ...failure, botName: member ? memberName(member) : '' }];
+ return [{ ...failure, botName: member ? memberName(member, members) : '' }];
});
- return { id: room.id, name: room.name, serverBacked: true, supportsGroupLeave: true, dissolvedAt: room.dissolved_at ?? null, archived: room.archived, selfActorId: selfId,
+ return { id: room.id, conversationKind: room.kind === 'direct' ? 'direct' : 'group',
- name: room.kind === 'direct' ? active.filter(member => member.id !== selfId).map(memberName).join(', ') || room.name : room.name,
++ name: room.kind === 'direct' ? active.filter(member => member.id !== selfId).map(member => memberName(member, [])).join(', ') || room.name : room.name,
+ serverBacked: true, supportsGroupLeave: room.kind !== 'direct', dissolvedAt: room.dissolved_at ?? null, archived: room.archived, selfActorId: selfId,
revision: room.revision, members: memberViews, replyMode: room.response_mode, speakingMode: room.speaking_mode,
organizerBotId: room.organizer_id ?? null, projectDir: null, projectDirName: null,
createdAt: Date.parse(room.created_at), updatedAt: Date.parse(room.updated_at),
@@@ -374,9 -404,57 +402,57 @@@ export function createChatServerClient(
return { id: mediaId, name: media.name, mimeType: media.type, size, category: media.type.startsWith('image/') ? 'image' : 'file',
url: chatHttpsUrl(media.url), path: null };
},
- async send(roomId: string, input: { clientId: string; text: string; mentions: { all: boolean; botIds: string[] } }) {
- return request(`/conversations/${chatId(roomId)}/messages`, 'POST', { operationId: input.clientId,
- content: [{ type: 'text', text: input.text }], mentions: input.mentions.botIds.map(chatId) });
+ async markRead(roomId: string, page: ChatPage, messageIds: readonly string[]) {
+ // Old servers omit reads. Never infer a read position from a presentation index.
+ if (!page.snapshot.reads) return;
+ const seen = new Set(messageIds);
+ const key = page.threadRootId ?? 'main';
+ const before = page.snapshot.reads.find(read => read.thread_key === key)?.read_seq ?? '0';
+ const newest = page.messages.reduce((latest, message) => seen.has(message.id) && (message.threadRootId ?? undefined) === page.threadRootId
+ && BigInt(chatCursor(message.seq)) > BigInt(latest) ? message.seq : latest, before);
+ if (BigInt(newest) <= BigInt(before)) return;
+ const saved = await request<{ readSeq: string }>(`/conversations/${chatId(roomId)}/read`, 'POST', {
+ operationId: `read-${key}:${newest}`, readSeq: newest, ...(page.threadRootId ? { threadRootId: page.threadRootId } : {}),
+ });
+ const readSeq = chatCursor(saved.readSeq);
+ const current = page.snapshot.reads.find(read => read.thread_key === key);
+ if (current) { if (BigInt(readSeq) > BigInt(current.read_seq)) current.read_seq = readSeq; }
+ else page.snapshot.reads.push({ thread_key: key, read_seq: readSeq });
+ },
+ async send(roomId: string, input: { clientId: string; text: string; mentions: { all: boolean; botIds: string[] }; quote?: { messageId: string }; threadRootId?: string }) {
+ const key = JSON.stringify([roomId, input.clientId, input.text, input.mentions, input.quote?.messageId, input.threadRootId]);
+ const known = input.quote ? postedQuotes.get(key) : undefined;
+ const content: ChatMessage['content'] = known?.content ?? [{ type: 'text', text: input.text }];
+ const mentions = new Set(known?.mentions ?? input.mentions.botIds.map(chatId));
+ if (input.quote && !known) {
+ const [original, members] = await Promise.all([
+ request<ChatMessage>(`/conversations/${chatId(roomId)}/messages/${chatId(input.quote.messageId)}`),
+ request<ChatMember[]>(`/conversations/${chatId(roomId)}/members`),
+ ]);
+ if (original.deleted || (original.threadRootId && original.threadRootId !== input.threadRootId) || original.origin === 'system') throw new Error('QUOTE_UNAVAILABLE');
+ const member = members.find(member => member.id === original.authorId);
+ const quote = botGroupQuoteFromMessage({ id: original.id, sequence: Number(original.seq), authorKind: original.author.kind === 'human' ? 'user' : 'bot',
- authorName: member ? memberName(member) : original.author.name, content: contentText(original), task: taskCardOf(original) ?? undefined,
++ authorName: member ? memberName(member, members) : original.author.name, content: contentText(original), task: taskCardOf(original) ?? undefined,
+ attachments: original.content.filter(block => block.type === 'media').map(block => ({ name: attachmentName(block) })) });
+ // Quote positions are only an optional UI hint; never round a server cursor into it.
+ if (!Number.isSafeInteger(quote.sequence)) quote.sequence = null;
+ content.unshift(buildBotGroupQuoteCard(quote));
+ if (member?.kind === 'bot' && member.state === 'joined') mentions.add(chatId(member.id));
+ }
+ if (input.quote) {
+ postedQuotes.set(key, { content, mentions: [...mentions] });
+ if (postedQuotes.size > 128) postedQuotes.delete(postedQuotes.keys().next().value!);
+ }
+ try {
+ const result = await request(`/conversations/${chatId(roomId)}/messages`, 'POST', { operationId: input.clientId,
+ content, mentions: [...mentions], ...(input.threadRootId ? { threadRootId: chatId(input.threadRootId) } : {}) });
+ postedQuotes.delete(key);
+ return result;
+ } catch (error) {
+ const status = (error as { status?: number })?.status;
+ if (status && status >= 400 && status < 500 && status !== 408) postedQuotes.delete(key);
+ throw error;
+ }
},
};
}