Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge group-task-home-reply-timeout into bots-ux
Chris4eefe01a8d8b
diff --cc apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex e798bfde83,2c56eb2f62..ddc74d1f61--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@@ -1969,306 -1913,6 +1969,307 @@@ describe('Chat Server result delivery aexpect(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();++ it('reads what a send in a known group needs in one round trip and skips the unaddressed member read', async () => {++ // Opening confirms this is a group before later reads may run in parallel.++ expect((await service.getGroup(roomId)).ok).toBe(true);+ 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';@@@ -2638,6 -2282,134 +2639,141 @@@expect(prompt).not.toContain('forged words');});});++ describe('rooms that are not groups', () => {+ const directId = '70000000-0000-4000-8000-000000000001';+ const channelId = '70000000-0000-4000-8000-000000000002';+ const futureId = '70000000-0000-4000-8000-000000000003';+ const kinds: Record<string, string | undefined> = { [directId]: 'direct', [channelId]: 'channel', [futureId]: 'board' };+ const roomOf = (id: string) => ({ ...room(id), kind: id in kinds ? kinds[id] : 'group' });+ beforeEach(() => {+ fixture.handle.mockImplementation((route, method) => {+ if (route === '/me') return { body: { actor: { id: selfId }, capabilities: { groupLifecycleVersion: 1 } } };+ if (route === '/conversations?limit=100') return { body: [roomOf(directId), roomOf(roomId), roomOf(channelId), roomOf(futureId)] };+ if (route.endsWith('/snapshot')) return { body: { room: roomOf(route.split('/')[2]), cursor: '1', messages: [],+ members: [{ id: selfId, kind: 'human', ownerActorId: selfId, state: 'joined', role: 'owner' }] } };+ if (method !== 'GET') return { body: { id: '80000000-0000-4000-8000-000000000001' } };+ return response(route);+ });+ });+ const writes = () => fixture.handle.mock.calls.filter(([route, method]) => method !== 'GET' && String(route).startsWith(`/conversations/${directId}`));++ it('lists only group rooms, never direct companion chats, channels or unknown kinds', async () => {+ const result = await service.listGroups();+ expect(result.ok && result.groups.map(group => group.id)).toEqual([roomId]);+ for (const other of [directId, channelId, futureId])+ expect(fixture.handle.mock.calls.some(([route]) => String(route).startsWith(`/conversations/${other}/`))).toBe(false);+ });++ it.each([directId, channelId, futureId])('answers a missing group when %s is opened directly', async other => {+ expect(await service.getGroup(other)).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ });++ it.each([directId, channelId, futureId])('rejects dissolution, reactor reads and thread shares for %s without subscriptions or other room access', async groupId => {+ await service.listGroups();+ await vi.advanceTimersByTimeAsync(2000);+ const socket = fixture.sockets[0];+ Object.defineProperty(socket, 'readyState', { value: 1 });+ socket.emit('message', JSON.stringify({ type: 'ready' }));+ await vi.advanceTimersByTimeAsync(0);+ vi.mocked(socket.send).mockClear();+ fixture.handle.mockClear();+ expect(await service.chatServer!.manage({ groupId, action: { type: 'dissolve', expectedRevision: 1 } }))+ .toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ expect(await service.chatServer!.reactors({ groupId, messageId: roomId, emoji: '👍' }))+ .toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ expect(await service.chatServer!.shareToMain({ groupId, messageId: roomId }))+ .toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ expect(fixture.handle.mock.calls.filter(([route]) => String(route).startsWith(`/conversations/${groupId}`) && !String(route).endsWith('/snapshot'))).toEqual([]);+ expect(vi.mocked(socket.send).mock.calls.filter(([raw]) => String(raw).includes(groupId))).toEqual([]);+ });+++ it('rejects a first send to a direct room before reading plans or members', async () => {++ expect(await service.sendMessage({ groupId: directId, text: 'hi', clientId: 'cold-direct-send', mentions: { all: true, botIds: [] } }))++ .toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });++ expect(fixture.handle.mock.calls.filter(([route]) => String(route).startsWith(`/conversations/${directId}`)++ && !String(route).endsWith('/snapshot'))).toEqual([]);++ });+++ it('does not archive, leave, rename, re-member, post into or invite to a direct room through group actions', async () => {+ expect(await service.deleteGroup(directId)).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.updateGroup({ groupId: directId, name: 'Renamed' })).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.setMembers({ groupId: directId, botIds: [] })).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.sendMessage({ groupId: directId, text: 'hi', clientId: 'client-direct-1', mentions: { all: false, botIds: [] } }))+ .toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ // Raw-code entry points answer exactly like a missing room; the internal NOT_A_GROUP never leaves main.+ expect(await service.chatServer!.manage({ groupId: directId, action: { type: 'member', actorId: selfId, action: 'leave' } }))+ .toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ expect(await service.chatServer!.createInvite({ groupId: directId, clientId: 'invite-direct-1' })).toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ expect(await service.chatServer!.revokeInvite({ groupId: directId, link: `cindy://chat-invite/${'a'.repeat(43)}`, clientId: '90000000-0000-4000-8000-000000000001' }))+ .toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ expect(writes()).toEqual([]);+ });++ it('answers a missing group from round, plan, thread, reply and reaction entries without touching the room', async () => {+ const planId = '80000000-0000-4000-8000-000000000002';+ expect(await service.stopRound(directId)).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.continueRound(directId)).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.startPlan({ groupId: directId, planId })).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.dismissPlan({ groupId: directId, planId })).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.continuePlan({ groupId: directId, planId })).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.retryPlan({ groupId: directId, planId })).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.editPlanStep({ groupId: directId, planId, position: 0, action: 'remove' })).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.chatServer!.thread({ groupId: directId, rootId: planId })).toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ expect(await service.chatServer!.reply({ groupId: directId, rootId: planId, text: 'hi', clientId: 'reply-direct-1', mentions: { all: false, botIds: [] } }))+ .toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ expect(await service.chatServer!.react({ groupId: directId, messageId: planId, emoji: '👍', present: true })).toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ // Only the snapshot that answered "missing" was read; nothing else of the room was read or written.+ expect(fixture.handle.mock.calls.filter(([route]) => String(route).startsWith(`/conversations/${directId}`) && !String(route).endsWith('/snapshot'))).toEqual([]);+ });++ it.each([directId, channelId, futureId])('fails a claimed execution in %s instead of running it as a group', async other => {+ fixture.handle.mockImplementation((route, method) => {+ if (route === '/executions/claim') { const next = claimed ? null : { ...execution, conversation_id: other }; claimed = true; return { body: { execution: next } }; }+ if (route.endsWith('/snapshot')) return { body: { room: roomOf(route.split('/')[2]), cursor: '1', messages: [], members: [+ { id: selfId, kind: 'human', ownerActorId: selfId, state: 'joined', role: 'owner' },+ { id: botId, kind: 'bot', ownerActorId: selfId, state: 'joined', role: 'member' }] } };+ if (method !== 'GET') return { body: { id: '80000000-0000-4000-8000-000000000001' } };+ return response(route);+ });+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', status: 'active' }];+ await vi.advanceTimersByTimeAsync(2000);+ expect(deps.ensureLane).not.toHaveBeenCalled();+ expect(deps.dispatch).not.toHaveBeenCalled();+ const results = fixture.handle.mock.calls.filter(([route, , body]) => route === `/conversations/${other}/executions/${execution.id}`+ && ['complete', 'fail'].includes(body?.action));+ expect(results.map(call => call[2].action)).toEqual(['fail']);+ // The rejected room was never subscribed, so a reconnect has nothing to resubscribe.+ const socket = fixture.sockets[0];+ Object.defineProperty(socket, 'readyState', { value: 1 });+ socket.emit('message', JSON.stringify({ type: 'ready' }));+ await vi.advanceTimersByTimeAsync(0);+ const scopes = vi.mocked(socket.send).mock.calls.map(([raw]) => JSON.parse(String(raw)))+ .filter(m => m.type === 'subscribe' && String(m.scope).startsWith('conversation:')).map(m => m.scope);+ expect(scopes).toEqual([]);+ });++ it('never subscribes to a rejected room, so its traffic cannot invalidate the group list', async () => {+ await service.getGroup(roomId);+ await vi.advanceTimersByTimeAsync(2000);+ const socket = fixture.sockets[0];+ Object.defineProperty(socket, 'readyState', { value: 1 });+ socket.emit('message', JSON.stringify({ type: 'ready' }));+ await vi.advanceTimersByTimeAsync(0);+ expect(socket.send).toHaveBeenCalledWith(JSON.stringify({ type: 'subscribe', scope: `conversation:${roomId}`, after: '1' }));+ vi.mocked(socket.send).mockClear();+ expect(await service.getGroup(directId)).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(await service.chatServer!.createInvite({ groupId: channelId, clientId: 'invite-channel-1' })).toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ expect(await service.chatServer!.thread({ groupId: futureId, rootId: roomId })).toMatchObject({ ok: false, errorCode: 'CONVERSATION_NOT_FOUND' });+ expect(vi.mocked(socket.send).mock.calls.filter(([raw]) => String(raw).includes('"subscribe"'))).toEqual([]);+ // A later reconnect resubscribes only the group.+ socket.emit('message', JSON.stringify({ type: 'ready' }));+ await vi.advanceTimersByTimeAsync(0);+ const scopes = vi.mocked(socket.send).mock.calls.map(([raw]) => JSON.parse(String(raw)))+ .filter(m => m.type === 'subscribe' && String(m.scope).startsWith('conversation:')).map(m => m.scope);+ expect(scopes).toEqual([`conversation:${roomId}`]);+ });+ });});diff --cc apps/desktop/src/main/maker-ipc/chatServer.tsindex 0cce5ec156,7758f00e70..60d6acefcc--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@@ -156,9 -119,9 +156,11 @@@ const id = z.string().uuid()const memberJoinedTrigger = z.object({ type: z.literal('member.joined'), messageId: id, actorId: id,displayName: z.string().min(1).refine(value => value.trim().length > 0) }).strict();type ExecutionContext = { kind: 'message' } | { kind: 'member.joined'; trigger: z.infer<typeof memberJoinedTrigger> };+ /** Only `group` rooms are bot groups; direct companion chats, channels and later kinds are not. */+ const isGroupRoom = (room: Pick<Room, 'kind'>) => room.kind === 'group';const ordinaryExecution = (execution: Execution) => execution.trigger === undefined && execution.trigger_type == null;+/** Realtime change types that can never end or revoke an execution lease. */+const CHATTER_CHANGES = new Set(['message.created', 'message.updated', 'reaction.changed', 'pin.changed', 'read.changed']);const groupInput = z.object({ name: z.string().trim().min(1).max(40), botIds: z.array(z.string().min(1)).max(6) });// A recognized quote card is shown as the quote, not as body text; unknown revisions keep their fallback.// A task card is the message's task only on a teammate's own message; a human may not post one for it.@@@ -881,28 -748,29 +887,46 @@@ function createChatServer(local: BotGroreconnectDelay = Math.min(reconnectDelay * 2, 15000);});}- async function snapshot(roomId: string) {+ async function readSnapshot(roomId: string) {- id.parse(roomId); await register();+ id.parse(roomId); await ensureRegistered();+ const read = generation(roomId);const value = await api<Snapshot>(`/conversations/${roomId}/snapshot`);if (value.room.dissolved_at) retirePlanning(roomId);- subscribe(roomId, value.cursor);+ // Only an answer no change notice has overtaken may be reused.+ if (current() && generation(roomId) === read) snapshots.set(roomId, { value, generation: read, at: Date.now() });return value;}+ async function snapshot(roomId: string) {+ const value = await readSnapshot(roomId);+ subscribe(roomId, value.cursor);+ return value;+ }+ /**+ * The last snapshot when the room's subscription is live and has reported nothing since,+ * else a fresh read. The server still validates every write against its current state.+ */- function recentSnapshot(roomId: string) {++ function recentSnapshot(roomId: string, groupOnly = false) {+ id.parse(roomId);+ const known = snapshots.get(roomId);+ if (known && echoes(roomId) && known.generation === generation(roomId) && Date.now() - known.at < SNAPSHOT_REUSE_MS) {++ if (groupOnly && !isGroupRoom(known.value.room)) return Promise.reject(new Error('NOT_A_GROUP'));+ void ensureRegistered();+ return Promise.resolve(known.value);+ }- return snapshot(roomId);++ return groupOnly ? groupSnapshot(roomId) : readSnapshot(roomId);++ }+ /** A room read through a bot-group entry point; any other kind answers as a missing group and is never subscribed. */+ async function groupSnapshot(roomId: string) {+ const value = await readSnapshot(roomId);+ if (!isGroupRoom(value.room)) throw new Error('NOT_A_GROUP');+ subscribe(roomId, value.cursor);+ return value;+ }+ /** Every groupId entry resolves through here: a room that is not a group answers as missing before any other read or write. */+ async function groupRoom(groupId: string) {+ const room = await resolveGroup(groupId);+ await groupSnapshot(room);+ return room;}function managementActor(s: Snapshot) {const eligible = s.members.filter(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role));@@@ -1334,18 -1174,15 +1358,26 @@@|| execution.trigger_type != null && execution.trigger_type !== 'member.joined'|| run.context.trigger.messageId !== execution.source_message_id|| run.context.trigger.actorId !== execution.requester_id)) throw new Error('INVALID_EXECUTION_TRIGGER');- const s = await readSnapshot(execution.conversation_id);+ const roomId = execution.conversation_id;+ const contextBefore = BigInt(execution.context_seq) + 1n;+ // Reads that depend only on the claim start together. Each is awaited where the serial+ // version read it, so a failure still surfaces at the same step (an unreadable history+ // still follows lane creation and is settled with the lane aborted).+ const snapshotRead = recentSnapshot(roomId);+ const historyRead = api<Message[]>(`/conversations/${roomId}/messages?all=true&limit=100&before=${contextBefore}`);+ const planRead = execution.plan_id ? api<ServerPlan[]>(`/conversations/${roomId}/plans?ids=${execution.plan_id}`) : undefined;+ const trigger = run.context.kind === 'member.joined' ? run.context.trigger : undefined;+ const eventSourceRead = trigger ? api<Message>(`/conversations/${roomId}/messages/${trigger.messageId}`) : undefined;+ for (const read of [historyRead, planRead, eventSourceRead]) read?.catch(() => undefined);+ const s = await snapshotRead;+ // A companion's own 1:1 room is not a group: hand the message to its main task instead.+ const joined = new Set(s.members.filter(m => m.state === 'joined').map(m => m.id));+ const ownDirectRoom = companionHome && (companion?.isDirectRoom(s.room.id)+ || (s.room.kind === 'direct' && joined.size === 2 && joined.has(selfId) && joined.has(execution.bot_id)));+ // Every other room must be a group. Someone else's 1:1 room, a channel or an unknown kind is never+ // answered as a group and never subscribed: nothing may run without a visible group entry to watch or stop it.+ if (!ownDirectRoom && !isGroupRoom(s.room)) throw new Error('INVALID_EXECUTION_TRIGGER');+ subscribe(execution.conversation_id, s.cursor);// Claim metadata and the persisted source must agree before creating a lane.// Reading this exact ID also covers sources outside the bounded history page.let eventSource: Message | undefined;@@@ -1360,169 -1198,129 +1392,163 @@@throw new Error('INVALID_EXECUTION_TRIGGER');}if (!current() || running.get(execution.bot_id) !== run) throw new Error('STALE_EXECUTOR');- // A companion's own 1:1 room is not a group: hand the message to its main task instead.- const joined = new Set(s.members.filter(m => m.state === 'joined').map(m => m.id));- const ownDirectRoom = companionHome && (companion?.isDirectRoom(s.room.id)- || (s.room.kind === 'direct' && joined.size === 2 && joined.has(selfId) && joined.has(execution.bot_id)));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) => {@@@ -1623,68 -1421,6 +1649,68 @@@let polling = false;let pollRetryAt = 0;let pollFailures = 0;+ /** The same backoff for the two-second poll and realtime-triggered claims (auth recovery rules). */+ function pollFailed(error: unknown) {+ if (error instanceof ChatResponseError && (error.status === 401 || error.status === 429)) {+ pollRetryAt = Math.max(Date.now() + CHAT_AUTH_RETRY_MS, error.retryAt ?? 0);+ } else if (!(error instanceof ChatResponseError) || error.status >= 500) {+ pollFailures += 1;+ pollRetryAt = Date.now() + Math.min(60_000, 2_000 * 2 ** Math.min(pollFailures - 1, 5));+ }+ }+ const ownedActiveBot = (actorId: string) => actors.some(a => a.id === actorId && a.kind === 'bot' && localBot(a.id)?.status === 'active');+ /** A realtime change announcing work this device may claim: newly queued, for one of its companions or unspecified. */+ function queuedForThisDevice(change: unknown) {+ const value = change as { type?: unknown; data?: { status?: unknown; botId?: unknown } } | null;+ return value?.type === 'execution.changed' && value.data?.status === 'queued'+ && (typeof value.data.botId !== 'string' || ownedActiveBot(value.data.botId));+ }+ /** One claim per idle owned companion, all at once; the first failure in companion order is reported. */+ async function claimOnce() {+ const idle = actors.filter(a => a.kind === 'bot' && localBot(a.id)?.status === 'active' && !running.has(a.id)+ // Only the registered home runs a companion: skip while the home is elsewhere or not yet+ // registered (an unset home would let any copy of the owner claim it).+ && !(companionHome && a.homeDeviceId !== selfDeviceId)+ // Shadowed here (demoted, or run by another installation on this device), or this+ // installation is not yet confirmed to run it (the server only tells devices apart): never claim.+ && !(companionHome && (companion?.isShadowed(a.externalId) || !companion?.installConfirmed(a.externalId))));+ settledValues(await settleBounded(idle, idle.length, async actor => {+ let claim: { execution: Execution | null };- const payload = { operationId: randomUUID(), executorId, accessPolicyVersion: 1, planVersion: 1 };++ const payload = { operationId: randomUUID(), executorId, accessPolicyVersion: 1, planVersion: 1, ...(directRoomClaims ? { directRoomVersion: 1 } : {}) };+ // Parallel claims may see another companion's downgrade; each judges the request it sent.+ const withEvents = memberJoinedClaims;+ try {+ claim = await api('/executions/claim', 'POST', { ...payload, ...(withEvents ? { memberJoinedVersion: 1 } : {}) }, actor.id);+ } catch (error) {+ if (!withEvents || !(error instanceof ChatResponseError) || error.status !== 400 || error.message !== 'INVALID_INPUT') throw error;+ memberJoinedClaims = false;+ claim = await api('/executions/claim', 'POST', payload, actor.id);+ }+ const { execution } = claim;+ if (execution) void runExecution(execution);+ }));+ }+ // Claims never overlap: two claims for one companion could each lease work only one can run.+ let claiming: Promise<void> | undefined;+ let claimAgain = false;+ function claimAll(): Promise<void> {+ claiming ??= (async () => {+ do { claimAgain = false; await claimOnce(); } while (claimAgain && current());+ })().finally(() => { claiming = undefined; });+ return claiming;+ }+ let claimTrigger: ReturnType<typeof setTimeout> | undefined;+ /** Claims newly queued work shortly after its realtime notice; the two-second poll stays the fallback. */+ function triggerClaim() {+ if (claimTrigger || !current()) return;+ claimTrigger = setTimeout(() => {+ claimTrigger = undefined;+ if (!current() || !selfId || Date.now() < pollRetryAt) return;+ // A claim already in flight runs once more; a poll about to claim covers it.+ if (polling || claiming) { claimAgain = true; return; }+ void claimAll().catch(pollFailed);+ }, CLAIM_TRIGGER_MS);+ }const timer = setInterval(() => {if (!current() || polling || Date.now() < pollRetryAt) return;polling = true;@@@ -1845,15 -1597,10 +1871,15 @@@status: async () => ({ enabled: true, connected: current() && connected }),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);+ i.groupId = await groupRoom(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)]);// A share in the main chat can itself be a thread root.const rootViews = await messageViews(i.groupId, [root], members);@@@ -1982,21 -1717,11 +2012,23 @@@if (!i.text.trim() && !i.attachments?.length) throw new Error('INVALID_INPUT');// An attempted send must not cancel a valid decision until its message exists.const intentVersion = ++nextIntentVersion;- const s = await groupSnapshot(i.groupId);- // Read before preparing attachments: an unavailable quote must not stage files.+ // The reads a send needs share one round trip (none for a snapshot the live subscription+ // vouches for). Each is awaited in the former order, so the first failure reported is the+ // one the serial version reported.- const snapshotRead = recentSnapshot(i.groupId);++ const snapshotRead = recentSnapshot(i.groupId, true);++ // An unopened room must be confirmed as a group before reading its other resources.++ if (!rooms.has(i.groupId)) await snapshotRead;const quoteKey = i.quote ? `${i.groupId}:${i.clientId}:${i.quote.messageId}` : '';- const quote = i.quote ? postedQuotes.get(quoteKey) ?? await quoteSnapshot(i.groupId, i.quote.messageId, s.members) : null;- const plans = await api<ServerPlan[]>(`/conversations/${i.groupId}/plans`);+ const knownQuote = i.quote ? postedQuotes.get(quoteKey) : undefined;+ const snapshotMembers = snapshotRead.then(value => value.members);+ const quoteRead = i.quote && !knownQuote ? quoteSnapshot(i.groupId, i.quote.messageId, snapshotMembers) : undefined;+ const plansRead = api<ServerPlan[]>(`/conversations/${i.groupId}/plans`);+ const membersRead = namesNobody(i.mentions) ? undefined : api<Member[]>(`/conversations/${i.groupId}/members`);+ for (const read of [snapshotMembers, quoteRead, plansRead, membersRead]) read?.catch(() => undefined);+ const s = await snapshotRead;+ // Read before preparing attachments: an unavailable quote must not stage files.+ const quote = i.quote ? knownQuote ?? await quoteRead! : null;+ const plans = await plansRead;const openPlan = plans.find(p => ['proposed','running','waiting'].includes(p.status));const proposed = openPlan?.status === 'proposed' && openPlan.creator_id === selfId;if (i.division && openPlan && !proposed) throw new Error('PLAN_OPEN');@@@ -2069,10 -1782,10 +2101,10 @@@const groups: BotGroupDetail[] = [];let after: string | undefined;do {- const page = await api<Array<Room & { state: string }>>(`/conversations?limit=100${after ? `&after=${after}` : ''}`);+ const page = await api<Array<Room & { state: string; head?: unknown }>>(`/conversations?limit=100${after ? `&after=${after}` : ''}`);- // A companion's own 1:1 room is not a group (same rule as the executor).- const joined = page.filter(r => r.state === 'joined' && r.kind !== 'direct' && !personalList.hidden(r.id));++ // Only group rooms belong in the group list.+ const joined = page.filter(r => r.state === 'joined' && isGroupRoom(r) && !personalList.hidden(r.id));- for (let i = 0; i < joined.length; i += 8)- groups.push(...await Promise.all(joined.slice(i, i + 8).map(r => detail(r.id, undefined, true))));+ groups.push(...settledValues(await settleBounded(joined, SUMMARY_CONCURRENCY, room => summary(room))));after = page.length === 100 ? page.at(-1)!.id : undefined;} while (after);return { ok: true as const, groups: groups.filter(group => !personalList.hidden(group.id)) };@@@ -2120,8 -1833,7 +2152,8 @@@const i = z.object({ groupId: id, name: z.string().min(1).max(40).optional(), replyMode: z.enum(['all', 'mentioned']).optional(),speakingMode: z.enum(['auto', 'sequential']).optional(), organizerBotId: z.string().nullable().optional(), projectDir: z.string().max(4096).nullable().optional(), expectedRevision: z.number().int().positive().optional() }).parse(input);i.groupId = await resolveGroup(i.groupId);+ if (i.organizerBotId) await register();- const s = await snapshot(i.groupId);+ const s = await groupSnapshot(i.groupId);let projectDir = i.projectDir;if (projectDir) { const checked = await deps.validateProjectDir?.(projectDir); if (!checked?.ok) throw new Error('INVALID_DIRECTORY'); projectDir = checked.dir; }const organizerId = i.organizerBotId ? actors.find(a => a.externalId === i.organizerBotId)?.id ?? id.parse(i.organizerBotId) : i.organizerBotId;@@@ -2231,7 -1943,7 +2263,7 @@@},setMembers: input => safe(async () => {const i = z.object({ groupId: id, botIds: z.array(z.string()).max(6), addOnly: z.boolean().optional() }).parse(input);- const room = await resolveGroup(i.groupId); await register(); const s = await snapshot(room);- const room = await resolveGroup(i.groupId); const s = await groupSnapshot(room);++ const room = await resolveGroup(i.groupId); await register(); const s = await groupSnapshot(room);const selected = i.botIds.map(bot => actors.find(a => a.externalId === bot)?.id ?? id.parse(bot));for (const m of s.members.filter(m => !i.addOnly && m.kind === 'bot' && m.state === 'joined' && !selected.includes(m.id)))await api(`/conversations/${room}/members`, 'POST', { operationId: randomUUID(), actorId: m.id, action: 'remove' }, managementActor(s));@@@ -2240,10 -1952,9 +2272,10 @@@changed(room); return { ok: true as const };}),deleteGroup: groupId => safe(async () => {- const room = await resolveGroup(id.parse(groupId)); const s = await snapshot(room);+ const room = await resolveGroup(id.parse(groupId)); const s = await groupSnapshot(room);if (s.members.some(m => m.ownerActorId === selfId && m.role === 'owner')) await api(`/conversations/${room}`, 'PATCH', { operationId: randomUUID(), expectedRevision: s.room.revision, archived: true }, managementActor(s));else await api(`/conversations/${room}/members`, 'POST', { operationId: randomUUID(), actorId: selfId, action: 'leave' });+ resolvedGroups.delete(id.parse(groupId));changed(room); return { ok: true as const };}),continueRound: groupId => safe(async () => {