Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(bots): 伙伴交互优化:聊天过程、通讯卡、路由、工作台、群聊时间线

Chris971924916420
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 40cbb014f6..9dab43c79b 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -8210,6 +8210,9 @@ describe('Bot Session task end-to-end runtime', () => {
const trace = readMessage('session-1', `bot-delegation-interject-mirror:${started.delegationId}:follow-up-1`);
expect(trace).toMatchObject({ role: 'assistant', content: '' });
expect(JSON.parse(trace.agentMeta).botCollaboration.role).toBe('interjection');
+ // Only the bounded first line reaches the parent timeline; the rest stays in the child task.
+ expect(JSON.parse(trace.agentMeta).botCollaboration.interjectionPreview).toBe('补充:最后必须带风险清单。');
+ expect(trace.agentMeta).not.toContain('AGENTS.md');
expect(readMessage('session-1', `bot-delegation-request:${started.delegationId}`).content).toBe('');
// Status queries return context to the caller without appending it to the timeline.
const timelineBeforeCheck = h.sqlite!.prepare("SELECT * FROM messages WHERE session_id = 'session-1'").all();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts
index 3dfad1fa16..efbe8b55b2 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts
@@ -291,6 +291,13 @@ describe('botGroupChatService', () => {
}
const group = await waitForIdle(harness, groupId);
expect(group.lastReplyAt).toBe(Math.max(...group.messages.filter(m => m.authorKind === 'bot' && m.kind === 'message').map(m => m.createdAt)));
+ // Incoming times are the Bots' messages, oldest first, without the owner's own or notices.
+ const incoming = group.messages.filter(m => m.authorKind === 'bot' && (m.kind === 'message' || m.kind === 'plan'))
+ .sort((a, b) => a.sequence - b.sequence).map(m => new Date(m.createdAt).toISOString());
+ expect(incoming.length).toBeGreaterThan(0);
+ expect(group.incomingMessageTimes).toEqual(incoming);
+ const listed = await harness.service.listGroups();
+ expect(listed.ok && listed.groups.find(g => g.id === groupId)?.incomingMessageTimes).toEqual(incoming);
// Second circle takes turns and sees the whole first circle.
expect(harness.dispatches.slice(3).map((call) => call.botId)).toEqual(['xiaoman', 'abu', 'mimi']);
expect(harness.dispatches[3]!.prompt).toContain('咪咪的看法');
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupPlanDecider.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupPlanDecider.test.ts
index 899d848b7c..dd06304405 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupPlanDecider.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupPlanDecider.test.ts
@@ -37,7 +37,52 @@ describe('createBotGroupPlanDecider', () => {
needsPlan: true,
steps: [{ botId: 'mimi', task: '策划' }, { botId: 'abu', task: '写代码' }],
});
- expect(requestText.mock.calls[0]![1]).toMatchObject({ disableReasoning: true, timeoutMs: 20_000 });
+ // The automatic gate holds back ordinary replies, so its first candidate gets 5s (was 20s).
+ expect(requestText.mock.calls[0]![1]).toMatchObject({ disableReasoning: true, timeoutMs: 5_000 });
+ });
+
+ it('keeps the longer per-candidate budget for an explicit 分工 request', async () => {
+ const requestText = vi.fn(async () => ({ ok: false as const, reason: 'all_candidates_failed', attempts: [] }));
+ await createBotGroupPlanDecider(requestText as never)({ ...input, mode: 'forced' }, new AbortController().signal);
+ expect((requestText.mock.calls[0] as unknown as [string, { timeoutMs: number }])[1].timeoutMs).toBe(20_000);
+ });
+
+ it('ends the automatic decision after 8 seconds in total and treats it as 「不要」', async () => {
+ vi.useFakeTimers();
+ try {
+ let signal!: AbortSignal;
+ let beforeDispatch!: () => Promise<boolean>;
+ const dispatched: boolean[] = [];
+ const requestText = vi.fn((_prompt: string, opts: { signal: AbortSignal; beforeDispatch: () => Promise<boolean> }) => {
+ signal = opts.signal; beforeDispatch = opts.beforeDispatch;
+ return new Promise(resolve => {
+ // A first candidate that answers too slowly, then a fallback that is still running at the budget.
+ setTimeout(async () => { dispatched.push(await opts.beforeDispatch()); }, 5_000);
+ opts.signal.addEventListener('abort', () => resolve({ ok: false, reason: 'cancelled', attempts: [] }));
+ });
+ });
+ const caller = new AbortController();
+ const decision = createBotGroupPlanDecider(requestText as never)(input, caller.signal);
+ await vi.advanceTimersByTimeAsync(7_999);
+ expect(signal.aborted).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(signal.aborted).toBe(true);
+ expect(await decision).toBeNull();
+ // The fallback was still allowed to start inside the budget; nothing starts after it.
+ expect(dispatched).toEqual([true]);
+ expect(await beforeDispatch()).toBe(false);
+ expect(caller.signal.aborted).toBe(false);
+ } finally { vi.useRealTimers(); }
+ });
+
+ it('follows the caller cancelling a decision', async () => {
+ const requestText = vi.fn((_prompt: string, opts: { signal: AbortSignal }) => new Promise(resolve => {
+ opts.signal.addEventListener('abort', () => resolve({ ok: false, reason: 'cancelled', attempts: [] }));
+ }));
+ const caller = new AbortController();
+ const decision = createBotGroupPlanDecider(requestText as never)({ ...input, mode: 'forced' }, caller.signal);
+ caller.abort();
+ expect(await decision).toBeNull();
});
it('returns null when no candidate answered usably', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts
index 8c4616f3b8..0323636059 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts
@@ -430,6 +430,71 @@ describe('workbench detail reads for the owner', () => {
await expect(hidden.access.readForOwner({ botId: 'bot-1', taskId: 'task-1' }))
.resolves.toMatchObject({ ok: false, errorCode: 'TASK_NOT_ACCESSIBLE' });
});
+
+ it('reads an archived task the teammate is responsible for', async () => {
+ const { deps, access } = setup({
+ readResponsibleSessionIds: vi.fn(async () => ['task-1']),
+ readTarget: vi.fn(async () => target({ status: 'archived' })),
+ });
+ await expect(access.readForOwner({ botId: 'bot-1', taskId: 'task-1' }))
+ .resolves.toEqual({ ok: true, taskId: 'task-1', transcript });
+ expect(deps.readResponsibleSessionIds).toHaveBeenCalledWith('bot-1');
+ expect(deps.readSessionTranscript).toHaveBeenCalledWith('task-1');
+ });
+
+ it('reads a responsible background task outside the handed-over projects', async () => {
+ const { access } = setup({
+ readState: vi.fn(async () => ({ directories: [], tasks: {} })),
+ readResponsibleSessionIds: vi.fn(async () => ['task-1']),
+ readTarget: vi.fn(async () => target({ delegationChild: true, workingDir: '/elsewhere' })),
+ });
+ await expect(access.readForOwner({ botId: 'bot-1', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: true, taskId: 'task-1' });
+ });
+
+ it('keeps unrelated tasks behind the project boundary', async () => {
+ const { deps, access } = setup({
+ readResponsibleSessionIds: vi.fn(async () => ['other-task']),
+ readTarget: vi.fn(async () => target({ workingDir: '/elsewhere' })),
+ });
+ await expect(access.readForOwner({ botId: 'bot-1', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH' });
+ expect(deps.readSessionTranscript).not.toHaveBeenCalled();
+ });
+
+ it('still refuses archived tasks the teammate is not responsible for', async () => {
+ const { deps, access } = setup({ readTarget: vi.fn(async () => target({ status: 'archived' })) });
+ await expect(access.readForOwner({ botId: 'bot-1', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_ARCHIVED' });
+ expect(deps.readSessionTranscript).not.toHaveBeenCalled();
+ });
+
+ it('does not relax tool reads or continuation for responsible archived tasks', async () => {
+ const { deps, access } = setup({
+ readResponsibleSessionIds: vi.fn(async () => ['task-1']),
+ readTarget: vi.fn(async () => target({ status: 'archived' })),
+ });
+ await expect(access.read({ callerSessionId: 'bot-main', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_ARCHIVED' });
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'task-1', message: '继续' }))
+ .resolves.toMatchObject({ ok: false });
+ expect(deps.sendToSession).not.toHaveBeenCalled();
+ });
+
+ it('keeps hidden and remote tasks unreadable even when listed as responsible', async () => {
+ const hidden = setup({
+ readResponsibleSessionIds: vi.fn(async () => ['task-1']),
+ readTarget: vi.fn(async () => target({ botLinked: true })),
+ });
+ await expect(hidden.access.readForOwner({ botId: 'bot-1', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_NOT_ACCESSIBLE' });
+ const remote = setup({
+ readResponsibleSessionIds: vi.fn(async () => ['task-1']),
+ readTarget: vi.fn(async () => target({ remoteHostId: 'ssh-1', status: 'archived' })),
+ });
+ await expect(remote.access.readForOwner({ botId: 'bot-1', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_REMOTE' });
+ });
});
describe('workbench snapshot', () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
index cf6f51903c..d1accd1a6c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -1272,6 +1272,8 @@ describe('Chat Server result delivery and refresh', () => {
socket.emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'RESET_REQUIRED' } }));
await vi.advanceTimersByTimeAsync(0);
expect(socket.send).toHaveBeenCalledWith(JSON.stringify({ type: 'subscribe', scope: `conversation:${roomId}`, after: '42' }));
+ // Change notices leave at the end of the 150ms coalescing window (one push per burst).
+ await vi.advanceTimersByTimeAsync(150);
expect(deps.onChanged).toHaveBeenCalledWith(expect.objectContaining({ groupId: roomId }), undefined);
vi.mocked(socket.send).mockClear();
socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '43', changes: [] }));
@@ -1539,6 +1541,8 @@ describe('Chat Server result delivery and refresh', () => {
expect((await service.getGroup(roomId)).ok).toBe(true);
vi.mocked(deps.onChanged!).mockClear();
expect(await service.chatServer!.refreshProfile()).toMatchObject({ ok: true });
+ // No realtime round trip is awaited; the notices only wait for the 150ms coalescing window.
+ await vi.advanceTimersByTimeAsync(150);
expect(deps.onChanged).toHaveBeenCalledWith({ groupId: roomId, change: 'messages' }, undefined);
expect(deps.onChanged).toHaveBeenCalledWith({ groupId: '', change: 'messages' }, undefined);
});
@@ -1556,6 +1560,234 @@ describe('Chat Server result delivery and refresh', () => {
expect(fixture.handle).toHaveBeenCalledWith(`/conversations?limit=100&after=${firstPage[99].id}`, 'GET', undefined);
expect(fixture.handle.mock.calls.some(([route]) => route.includes('/messages?'))).toBe(false);
});
+
+ describe('latency and push contract', () => {
+ const peerId = '60000000-0000-4000-8000-000000000009';
+ const botMember = { id: botId, kind: 'bot', name: 'Bot', state: 'joined', role: 'member', ownerActorId: selfId, ownerName: 'Me', guestAccess: 'chat' };
+ const selfMember = { id: selfId, kind: 'human', name: 'Me', state: 'joined', role: 'owner', ownerActorId: selfId, ownerName: 'Me' };
+ const snapshotOf = (messages: unknown[] = [], cursor = '1') => ({ body: { room: room(roomId), members: [selfMember, botMember], messages, cursor } });
+ const routesSince = (from: number) => fixture.handle.mock.calls.slice(from).map(([route, method]) => `${method} ${route}`)
+ .filter(call => !call.includes('/executions/claim') && !call.endsWith(' /me') && !call.endsWith(' /actors') && !call.includes('/profile/refresh'));
+ const send = (clientId: string, mentions = { all: false, botIds: [] as string[] }) =>
+ service.sendMessage({ groupId: roomId, text: 'Make a draft', clientId, mentions });
+ /** Opens the realtime connection created by the first poll and follows the room. */
+ async function live() {
+ await vi.advanceTimersByTimeAsync(2000);
+ const socket = fixture.sockets[0]!;
+ Object.defineProperty(socket, 'readyState', { value: 1 });
+ socket.emit('message', JSON.stringify({ type: 'ready' }));
+ expect((await service.getGroup(roomId)).ok).toBe(true);
+ await vi.advanceTimersByTimeAsync(150);
+ vi.mocked(deps.onChanged!).mockClear();
+ return socket;
+ }
+ const pushes = () => vi.mocked(deps.onChanged!).mock.calls.filter(([payload]) => payload.groupId === roomId).length;
+
+ beforeEach(() => {
+ fixture.handle.mockImplementation((route, method) => {
+ if (route.endsWith('/snapshot')) return snapshotOf();
+ if (route.endsWith('/members')) return { body: [selfMember, botMember] };
+ if (route.endsWith('/messages') && method === 'POST') return { body: { id: '90000000-0000-4000-8000-000000000001' } };
+ return response(route);
+ });
+ });
+
+ it('reads what a send needs in one round trip and skips the member read for an unaddressed message', async () => {
+ await service.chatServer!.ownedBots();
+ let release: (() => void) | undefined;
+ fixture.handle.mockImplementation((route, method) => {
+ if (route.endsWith('/snapshot')) return release ? snapshotOf() : new Promise(resolve => { release = () => resolve(snapshotOf()); });
+ if (route.endsWith('/members')) return { body: [selfMember, botMember] };
+ if (route.endsWith('/messages') && method === 'POST') return { body: { id: '90000000-0000-4000-8000-000000000001' } };
+ return response(route);
+ });
+ const from = fixture.handle.mock.calls.length;
+ const sent = send('latency-send-1', { all: false, botIds: [botId] });
+ await vi.advanceTimersByTimeAsync(0);
+ // Plans and members were requested while the snapshot was still unanswered.
+ expect(routesSince(from).sort()).toEqual([`GET /conversations/${roomId}/members`, `GET /conversations/${roomId}/plans`, `GET /conversations/${roomId}/snapshot`]);
+ release!();
+ expect(await sent).toMatchObject({ ok: true });
+ expect(routesSince(from).at(-1)).toBe(`POST /conversations/${roomId}/messages`);
+ expect(routesSince(from)).toHaveLength(4);
+ const plain = fixture.handle.mock.calls.length;
+ expect(await send('latency-send-2')).toMatchObject({ ok: true });
+ expect(routesSince(plain).sort()).toEqual([`GET /conversations/${roomId}/plans`, `GET /conversations/${roomId}/snapshot`, `POST /conversations/${roomId}/messages`]);
+ });
+
+ it('reuses the snapshot a live subscription vouches for and pushes the send once, on its echo', async () => {
+ const socket = await live();
+ const from = fixture.handle.mock.calls.length;
+ expect(await send('latency-send-3')).toMatchObject({ ok: true });
+ expect(routesSince(from)).toEqual([`GET /conversations/${roomId}/plans`, `POST /conversations/${roomId}/messages`]);
+ await vi.advanceTimersByTimeAsync(150);
+ // The followed room reports the stored message itself: no local push before the echo.
+ expect(pushes()).toBe(0);
+ for (const cursor of ['2', '3']) socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor,
+ changes: [{ type: 'message.created', entityId: '90000000-0000-4000-8000-000000000001' }] }));
+ await vi.advanceTimersByTimeAsync(150);
+ expect(pushes()).toBe(1);
+ // A change notice makes the next send read a fresh snapshot.
+ const next = fixture.handle.mock.calls.length;
+ expect(await send('latency-send-4')).toMatchObject({ ok: true });
+ expect(routesSince(next)).toContain(`GET /conversations/${roomId}/snapshot`);
+ });
+
+ it('still pushes a send locally while the realtime connection is down', async () => {
+ expect(await send('latency-send-5')).toMatchObject({ ok: true });
+ expect(pushes()).toBe(0);
+ await vi.advanceTimersByTimeAsync(150);
+ expect(pushes()).toBe(1);
+ });
+
+ it('answers a send before the replaced arrangement is cancelled, and still cancels it', async () => {
+ const base = fixture.handle.getMockImplementation()!;
+ let finishCancel!: () => void;
+ const sources: string[] = [];
+ fixture.handle.mockImplementation((route, method, data) => {
+ if (route === '/me') return { body: { actor: { id: selfId }, capabilities: { groupDiscussionParity: 1 } } };
+ if (route.endsWith('/messages') && method === 'POST') { sources.push(data.operationId); return { body: { id: `5000000${sources.length}-0000-4000-8000-000000000001` } }; }
+ if (route.endsWith('/cancel-planning')) return new Promise(resolve => { finishCancel = () => resolve({ body: {} }); });
+ return base(route, method, data);
+ });
+ deps.decidePlan = vi.fn(() => new Promise(() => {})) as typeof deps.decidePlan;
+ expect(await send('latency-plan-a')).toMatchObject({ ok: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(deps.decidePlan).toHaveBeenCalledOnce();
+ const second = await send('latency-plan-b');
+ expect(second).toMatchObject({ ok: true, messageId: '50000002-0000-4000-8000-000000000001' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(fixture.handle).toHaveBeenCalledWith(`/conversations/${roomId}/messages/50000001-0000-4000-8000-000000000001/cancel-planning`, 'POST',
+ expect.objectContaining({ failed: false }));
+ finishCancel();
+ await vi.advanceTimersByTimeAsync(0);
+ // B's own arrangement starts only after A's cancel has been answered.
+ expect(deps.decidePlan).toHaveBeenCalledTimes(2);
+ });
+
+ it('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);
+ });
+ });
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts
index 9d29a3f3a6..5b37b9ce69 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts
@@ -25,7 +25,8 @@ vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzl
select: () => ({ from: () => ({ where: () => Object.assign(Promise.resolve(fixture.profiles), {
limit: async () => fixture.localGroupIds.map(id => ({ id })),
}) }) }),
-} }) }));
+ insert: () => ({ values: () => ({ onConflictDoNothing: async () => undefined }) }),
+}, tx: async () => undefined }) }));
vi.mock('node:http', async () => {
const { EventEmitter } = await import('node:events');
return { request: (url: string, options: { method: string }, callback: (response: unknown) => void) => {
@@ -140,6 +141,52 @@ describe('Chat Server group open latency (simulated 100ms per request)', () => {
expect(revisit.routes).toHaveLength(5);
});
+ it('answers a send after one parallel read round and its post', async () => {
+ await timed(() => service.getGroup(rooms[0]));
+ await warm();
+ fixture.handle.mockImplementation((route, method) => route.endsWith('/messages') && method === 'POST'
+ ? { body: { id: '50000000-0000-4000-8000-000000000099' } } : route.endsWith('/members') ? { body: [] } : response(route));
+ const plain = await timed(() => service.sendMessage({ groupId: rooms[0], text: 'hello', clientId: 'open-latency-send-1', mentions: { all: false, botIds: [] } }));
+ const everyone = await timed(() => service.sendMessage({ groupId: rooms[0], text: 'hello all', clientId: 'open-latency-send-2', mentions: { all: true, botIds: [] } }));
+ // Before: snapshot → plans → members → post, one after another (400ms each).
+ console.info(`[group-send-latency] ${JSON.stringify({ plainMs: plain.ms, everyoneMs: everyone.ms, plainRequests: plain.routes.length, everyoneRequests: everyone.routes.length })}`);
+ expect([plain.value, everyone.value]).toEqual([{ ok: true, messageId: '50000000-0000-4000-8000-000000000099' }, { ok: true, messageId: '50000000-0000-4000-8000-000000000099' }]);
+ expect(plain.ms).toBe(200);
+ expect(everyone.ms).toBe(200);
+ // An unaddressed message needs no member read.
+ expect(plain.routes).toHaveLength(3);
+ expect(everyone.routes).toHaveLength(4);
+ });
+
+ it('starts a claimed turn after one parallel read round and one lease check', async () => {
+ service.dispose();
+ const botActor = '20000000-0000-4000-8000-000000000001';
+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];
+ const execution = { id: '40000000-0000-4000-8000-000000000001', conversation_id: rooms[0], source_message_id: message.id, bot_id: botActor,
+ context_seq: '1', epoch: 1, status: 'running', access_mode: 'chat', access_revision: 1 };
+ let queued = true;
+ let claimedAt = 0;
+ let dispatchedAt = 0;
+ fixture.handle.mockImplementation(route => {
+ if (route === '/actors') return { body: [{ id: botActor, kind: 'bot', externalId: 'local-bot', name: 'Bot' }] };
+ if (route === '/executions/claim') {
+ if (!queued) return { body: { execution: null } };
+ // Served and answered at once: this is when the claim reaches the client.
+ queued = false; claimedAt = Date.now();
+ return { body: { execution } };
+ }
+ return response(route);
+ });
+ service = withChatServer(local as unknown as BotGroupChatService, { onChanged,
+ ensureLane: async () => ({ ok: true, sessionId: 'lane' }), abortLane: async () => {},
+ dispatch: async () => { dispatchedAt = Date.now(); return { ok: true }; } } as unknown as BotGroupChatServiceDeps);
+ await vi.advanceTimersByTimeAsync(3000);
+ // Before: snapshot → lease check → history → lease check → dispatch (400ms after the claim).
+ console.info(`[group-pickup-latency] ${JSON.stringify({ afterClaimMs: dispatchedAt - claimedAt })}`);
+ expect(dispatchedAt).toBeGreaterThan(0);
+ expect(dispatchedAt - claimedAt).toBe(200);
+ });
+
it('reads a new room only after the snapshot whose cursor it follows from', async () => {
await warm();
const from = fixture.routes.length;
@@ -164,7 +211,8 @@ describe('Chat Server group open latency (simulated 100ms per request)', () => {
onChanged.mockClear();
fixture.sockets[0].emit('message', JSON.stringify({ type: 'ready' }));
expect(sent()).toContainEqual({ type: 'subscribe', scope: `conversation:${rooms[0]}`, after: '58' });
- // A reconnect still re-reads every followed room once.
+ // A reconnect still re-reads every followed room once, after the 150ms coalescing window.
+ await vi.advanceTimersByTimeAsync(150);
expect(onChanged).toHaveBeenCalledWith({ groupId: rooms[0], change: 'messages' }, undefined);
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
index 2d4676bd01..3b682338b2 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
@@ -58,6 +58,23 @@ describe('chat private media', () => {
await expect(media.download('room', 'media')).rejects.toThrow('CONVERSATION_NOT_FOUND');
expect(api).toHaveBeenCalledTimes(2);
});
+ it('uploads a send\'s files three at a time and keeps their order', async () => {
+ f.read.mockResolvedValue({ buffer: Buffer.from('png') });
+ f.fetch.mockResolvedValue(new Response('', { status: 200 }));
+ const files = ['a', 'b', 'c', 'd'].map(id => ({ ...attachment, id, name: `${id}.png` }));
+ let inFlight = 0, most = 0;
+ const api = vi.fn(async (route: string, _method: string, body: { name?: string }) => {
+ if (!route.endsWith('/media')) return {};
+ inFlight += 1; most = Math.max(most, inFlight);
+ // The first file is prepared last.
+ await new Promise(resolve => setTimeout(resolve, body.name === 'a.png' ? 20 : 1));
+ inFlight -= 1;
+ return { id: `media-${body.name}`, uploadUrl: 'https://upload.example.test/signed' };
+ }) as unknown as ChatApi;
+ const blocks = await createChatMedia(api, () => true).upload('room', 'operation', files, 'actor');
+ expect(blocks.map(block => block.caption)).toEqual(['a.png', 'b.png', 'c.png', 'd.png']);
+ expect(most).toBe(3);
+ });
it('permits exact loopback media only for the explicitly isolated adapter', async () => {
f.read.mockResolvedValue({ buffer: Buffer.from('png') });f.fetch.mockResolvedValue(new Response('', { status: 200 }));
let uploadUrl = 'http://127.0.0.1:3018/dev-media/fixture';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts
index 07c1ce9919..b382ae73cb 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts
@@ -132,6 +132,8 @@ describe('Chat Server membership notices', () => {
const result = await service.getGroup(roomId);
expect(result.ok && result.group.messages.map(m => m.id)).toEqual([joined().id]);
}
+ // Duplicate notices coalesce into one push at the end of the 150ms window.
+ await vi.advanceTimersByTimeAsync(150);
expect(changed).toHaveBeenCalled();
expect(dispatch).not.toHaveBeenCalled();
expect(fixture.handle.mock.calls.some(([route, method]) => method === 'POST' && route.includes('/messages'))).toBe(false);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts
index 21f1063fbb..2a5dc45134 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts
@@ -264,7 +264,10 @@ describe('server group feature parity', () => {
expect(fixture.handle.mock.calls.find(([route]) => route.endsWith('/cancel-planning'))?.[2].failed).toBe(true);
expect(fixture.handle.mock.calls.some(([route]) => route.endsWith('/continue'))).toBe(false);
});
- it('keeps a stored quote reply\'s snapshot until the whole send succeeds, so a retry cannot drop the quote', async () => {
+ // The send is answered once its message is stored; replacing the earlier arrangement continues
+ // afterwards. Formerly a failed cancel of that arrangement failed the whole (already stored) send
+ // and relied on the user retrying it with the same quote snapshot.
+ it('answers a stored quote reply at once and retries a failed cancel of the replaced arrangement', async () => {
const quotedId = '80000000-0000-4000-8000-000000000002';
arrange();
const base = fixture.handle.getMockImplementation()!;
@@ -284,15 +287,19 @@ describe('server group feature parity', () => {
deps.decidePlan = vi.fn(() => new Promise(() => {})) as typeof deps.decidePlan;
// A: an ordinary request whose arrangement is still being decided.
expect((await send({ clientId: 'parity:message:a' })).ok).toBe(true); await flush();
- // B: stored by the server, then the bookkeeping that replaces A's intent fails.
+ // B: stored by the server; the bookkeeping that replaces A's intent fails once, after the answer.
const quoteReply = { clientId: 'parity:message:b', text: 'Do this one', quote: { messageId: quotedId } };
- expect(await send(quoteReply)).toMatchObject({ ok: false });
+ expect(await send(quoteReply)).toEqual({ ok: true, messageId: 'stored:parity:message:b' });
+ await flush();
+ const cancels = fixture.handle.mock.calls.filter(([route]) => route === `/conversations/${roomId}/messages/stored:parity:message:a/cancel-planning`);
+ expect(cancels).toHaveLength(2);
+ expect(cancels[1]![2]).toEqual(cancels[0]![2]);
+ // A repeat of the answered send returns its receipt without posting or reading the quote again.
originalVisible = false;
expect(await send(quoteReply)).toEqual({ ok: true, messageId: 'stored:parity:message:b' });
const posts = fixture.handle.mock.calls.filter(([route, method, data]) => route.endsWith('/messages') && method === 'POST' && data.operationId === 'parity:message:b');
- expect(posts).toHaveLength(2);
- expect(posts[1]![2].content).toEqual(posts[0]![2].content);
- expect(posts[1]![2].content[0]).toMatchObject({ namespace: 'cindy.quote' });
+ expect(posts).toHaveLength(1);
+ expect(posts[0]![2].content[0]).toMatchObject({ namespace: 'cindy.quote' });
expect(fixture.handle.mock.calls.filter(([route]) => route === `/conversations/${roomId}/messages/${quotedId}`)).toHaveLength(1);
});
it('keeps legacy servers without a watermark on the bounded text page', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index a7c854e7d7..a5e7207e44 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -46,7 +46,7 @@ import type {
BotCollaborationRole,
BotDelegationInterjectResult,
} from '../../shared/botCollaboration.js';
-import { BOT_DELEGATION_CLIENT_ID } from '../../shared/botCollaboration.js';
+import { BOT_DELEGATION_CLIENT_ID, botInterjectionPreview } from '../../shared/botCollaboration.js';
import { buildBotGroupTaskCard, type BotGroupTaskCardLabels, type BotGroupTaskCardState } from '../../shared/botGroupChat.js';
import { t } from '../i18n.js';
import type { BotGroupTaskPostInput, BotGroupTaskPostResult } from './botGroupChatService.js';
@@ -3060,7 +3060,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
message: dispatched?.message ?? '消息未能送达后台任务',
};
}
- // 父任务只留发送状态;完整指令已经投递并保存在子任务,不再复制到主聊天。
+ // 父任务只留发送状态与首行摘要;完整指令已经投递并保存在子任务,不再复制到主聊天。
// 写不进去不回滚投递——话已经送到了,回滚只会让两边记账不一致。
await persistTimelineMessage({
sessionId: callerSessionId,
@@ -3069,7 +3069,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
content: '',
createdAt: now(),
agentMeta: {
- botCollaboration: await collaborationMeta(row, 'interjection'),
+ botCollaboration: {
+ ...await collaborationMeta(row, 'interjection'),
+ // 只留首行摘要,让主聊天看得出补充了什么;完整指令仍只在子任务里。
+ ...(botInterjectionPreview(trimmed) ? { interjectionPreview: botInterjectionPreview(trimmed) } : {}),
+ },
},
}).catch((error) => {
log.warn('failed to mirror a Session task message into the requesting task', {
diff --git a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
index 82e13f7796..590c22657e 100644
--- a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
+++ b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
@@ -742,11 +742,18 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
.where(and(eq(botGroupMessages.groupId, groupId), eq(botGroupMessages.authorKind, 'bot'),
eq(botGroupMessages.kind, 'message')))
.orderBy(desc(botGroupMessages.sequence)).limit(1);
- return { latest, latestSpoken, lastReplyAt: latestReply?.createdAt ?? 0 };
+ // A local group's only person is its owner, so incoming messages are the Bots' messages.
+ const incoming = await db.select({ createdAt: botGroupMessages.createdAt })
+ .from(botGroupMessages)
+ .where(and(eq(botGroupMessages.groupId, groupId), eq(botGroupMessages.authorKind, 'bot'),
+ inArray(botGroupMessages.kind, ['message', 'plan'])))
+ .orderBy(desc(botGroupMessages.sequence)).limit(99);
+ return { latest, latestSpoken, lastReplyAt: latestReply?.createdAt ?? 0,
+ incomingMessageTimes: incoming.reverse().map((row) => new Date(row.createdAt).toISOString()) };
};
const summarize = async (group: GroupRow): Promise<BotGroupSummary> => {
- const [members, { latestSpoken, lastReplyAt }, openPlan] = await Promise.all([
+ const [members, { latestSpoken, lastReplyAt, incomingMessageTimes }, openPlan] = await Promise.all([
readMembers(group.id),
latestMessages(group.id),
readOpenPlan(group.id),
@@ -776,6 +783,7 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
: null,
planningBotId: planning && !planning.cancelled ? planning.organizerBotId : null,
lastReplyAt,
+ incomingMessageTimes,
lastMessage: latestSpoken
? {
authorKind: latestSpoken.authorKind,
diff --git a/apps/desktop/src/main/maker-ipc/botGroupPlanDecider.ts b/apps/desktop/src/main/maker-ipc/botGroupPlanDecider.ts
index 1e659d45f4..20c36c0c4e 100644
--- a/apps/desktop/src/main/maker-ipc/botGroupPlanDecider.ts
+++ b/apps/desktop/src/main/maker-ipc/botGroupPlanDecider.ts
@@ -14,7 +14,20 @@ import {
type PlanDecisionInput,
} from './botGroupDivision.js';
-const PLAN_DECISION_TIMEOUT_MS = 20_000;
+/**
+ * The automatic decision gates every unaddressed message: its replies wait until it answers.
+ * It is therefore bounded to 8 seconds in total: the first candidate gets at most 5 seconds,
+ * whatever remains (about 3 seconds) is left for a fallback, and no candidate is dispatched
+ * after the budget. Running out counts as 「不要」 like any other failure, so the message is
+ * answered as an ordinary discussion (the rule itself is unchanged).
+ */
+export const AUTO_PLAN_DECISION_CANDIDATE_TIMEOUT_MS = 5_000;
+export const AUTO_PLAN_DECISION_BUDGET_MS = 8_000;
+/**
+ * An explicit 分工 request (or revising a proposal) must produce steps and the user is waiting for
+ * exactly that, so it keeps the longer per-candidate budget.
+ */
+const EXPLICIT_PLAN_DECISION_TIMEOUT_MS = 20_000;
const PLAN_DECISION_MAX_TOKENS = 800;
export function createBotGroupPlanDecider(
@@ -22,15 +35,26 @@ export function createBotGroupPlanDecider(
) {
return async (input: PlanDecisionInput, signal: AbortSignal): Promise<PlanDecision | null> => {
const memberIds = new Set(input.members.map((member) => member.botId));
- const result = await requestText(buildPlanDecisionPrompt(input), {
- systemPrompt: PLAN_DECISION_SYSTEM_PROMPT,
- maxTokens: PLAN_DECISION_MAX_TOKENS,
- timeoutMs: PLAN_DECISION_TIMEOUT_MS,
- disableReasoning: true,
- signal,
- validateResponse: (text) => parsePlanDecision(text, input.mode, memberIds) !== null,
- beforeDispatch: async () => !signal.aborted,
- });
- return result.ok ? parsePlanDecision(result.text, input.mode, memberIds) : null;
+ const automatic = input.mode === 'auto';
+ const controller = new AbortController();
+ const abort = () => controller.abort();
+ if (signal.aborted) abort();
+ else signal.addEventListener('abort', abort, { once: true });
+ const budget = automatic ? setTimeout(abort, AUTO_PLAN_DECISION_BUDGET_MS) : undefined;
+ try {
+ const result = await requestText(buildPlanDecisionPrompt(input), {
+ systemPrompt: PLAN_DECISION_SYSTEM_PROMPT,
+ maxTokens: PLAN_DECISION_MAX_TOKENS,
+ timeoutMs: automatic ? AUTO_PLAN_DECISION_CANDIDATE_TIMEOUT_MS : EXPLICIT_PLAN_DECISION_TIMEOUT_MS,
+ disableReasoning: true,
+ signal: controller.signal,
+ validateResponse: (text) => parsePlanDecision(text, input.mode, memberIds) !== null,
+ beforeDispatch: async () => !controller.signal.aborted,
+ });
+ return result.ok && !controller.signal.aborted ? parsePlanDecision(result.text, input.mode, memberIds) : null;
+ } finally {
+ clearTimeout(budget);
+ signal.removeEventListener('abort', abort);
+ }
};
}
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts
index 2c6e775b64..c69ca87064 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts
@@ -75,10 +75,20 @@ export interface WorkbenchTargetFacts {
export type WorkbenchTargetDecision = { ok: true; projectDir: string } | Failure;
+export interface WorkbenchTargetOptions {
+ /**
+ * 只读、且该伙伴自己的逐任务责任(接手记录或它发起的后台任务)覆盖这件任务:
+ * 主人在工作台详情里看自己负责列表里的任务。归档、后台任务、项目外的任务都可读;
+ * 删除、伙伴隐藏任务、远端与不支持的来源仍拒绝。写入 / 继续 / 停止不使用此项。
+ */
+ responsibleRead?: boolean;
+}
+
export function authorizeWorkbenchTarget(
target: WorkbenchTargetFacts | null,
projectDirs: readonly string[],
caseInsensitive: boolean,
+ options: WorkbenchTargetOptions = {},
): WorkbenchTargetDecision {
if (!target || target.status === 'deleted') {
return { ok: false, errorCode: 'TASK_NOT_FOUND', message: '找不到这件任务,它可能已被删除' };
@@ -89,6 +99,12 @@ export function authorizeWorkbenchTarget(
if (target.remoteHostId) {
return { ok: false, errorCode: 'TASK_REMOTE', message: '远端任务不在工作台的范围内' };
}
+ if (options.responsibleRead) {
+ if (!isWorkbenchTaskSource(target.source) || target.orcaRole === 'worker') {
+ return { ok: false, errorCode: 'TASK_NOT_SUPPORTED', message: '这类任务不在工作台的范围内' };
+ }
+ return { ok: true, projectDir: findWorkbenchProject(target.workingDir, projectDirs, caseInsensitive) ?? target.workingDir ?? '' };
+ }
if (target.status !== 'active') {
return { ok: false, errorCode: 'TASK_ARCHIVED', message: '这件任务已归档,请让主人先恢复它' };
}
@@ -769,7 +785,23 @@ export function createBotWorkbenchAccess(deps: BotWorkbenchAccessDeps) {
*/
async readForOwner(params: { botId: string; taskId: string }) {
const workbench = await deps.readState(params.botId);
- const target = await resolveTarget(params.taskId, workbench);
+ // 负责列表里的任务(含已归档、伙伴开的后台任务、项目外的任务)详情只读可看;
+ // 只认该伙伴自己的责任记录,其余仍按已接手项目判定。
+ const ref = parseWorkbenchTaskId(params.taskId);
+ let target: ResolvedTarget | Failure;
+ if (ref?.kind === 'session' && (await deps.readResponsibleSessionIds(params.botId)).includes(ref.sessionId)) {
+ const decision = authorizeWorkbenchTarget(
+ await deps.readTarget(ref.sessionId),
+ workbench.directories,
+ deps.caseInsensitive,
+ { responsibleRead: true },
+ );
+ target = decision.ok
+ ? { ok: true, kind: 'session', taskId: ref.sessionId, sessionId: ref.sessionId, projectDir: decision.projectDir }
+ : decision;
+ } else {
+ target = await resolveTarget(params.taskId, workbench);
+ }
if (!target.ok) return target;
const transcript = await readTranscript(target);
if (!transcript) return { ok: false as const, errorCode: 'TRANSCRIPT_UNAVAILABLE', message: '读不到这条会话的记录' };
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 2eaf58f388..cd6351e503 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -30,7 +30,7 @@ import {
isBotGroupRuntimeFailureCode, type BotGroupRuntimeFailureCode,
readImportedBotGroupRuntimeFailureCode,
readBotGroupExecutionFailure, type BotGroupExecutionFailureView,
- type BotGroupDetail, type BotGroupPlanView, type BotGroupFailure, type BotGroupMessageView, type BotGroupAttachment, type ChatServerApi,
+ type BotGroupDetail, type BotGroupSpeaker, type BotGroupPlanView, type BotGroupFailure, type BotGroupMessageView, type BotGroupAttachment, type ChatServerApi,
botGroupQuoteAttachmentName, botGroupQuoteExcerpt, botGroupQuoteFromMessage, buildBotGroupQuoteCard, readBotGroupQuote, readBotGroupQuoteCard, type BotGroupQuoteView,
readBotGroupTaskCard,
} from '../../shared/botGroupChat.js';
@@ -88,6 +88,43 @@ const CHAT_AUTH_RETRY_MS = 60_000;
/** Main-group messages kept as background for a Thread request (the Thread itself is read separately). */
const THREAD_BACKGROUND_LIMIT = 30;
const ATTACHMENT_REFRESH_COALESCE_MS = 200;
+/**
+ * One push per change: notices for the same group inside this window (a local write and its
+ * WebSocket echo, an execution and its message, several change batches) leave one broadcast at
+ * the window's end, so the renderer re-reads once, after the burst. Bounded: never postponed further.
+ */
+const CHANGE_COALESCE_MS = 150;
+/** A realtime notice of newly queued work claims it this soon instead of on the next 2s tick. */
+const CLAIM_TRIGGER_MS = 250;
+/** A room snapshot reused for a send while its realtime subscription reports no change since. */
+const SNAPSHOT_REUSE_MS = 30_000;
+/** A sidebar summary reused while the room's change head is unchanged; names can change elsewhere. */
+const SUMMARY_REUSE_MS = 60_000;
+/** Parallel execution-failure batches (100 source IDs each) for one read. */
+const FAILURE_BATCH_CONCURRENCY = 4;
+/** Sidebar summaries read at once. */
+const SUMMARY_CONCURRENCY = 8;
+/** Attachment downloads at once while a Bot prepares its turn. */
+const TURN_DOWNLOAD_CONCURRENCY = 4;
+/** Settles every item a few at a time, in input order; never rejects. */
+async function settleBounded<T, R>(items: readonly T[], limit: number, run: (item: T) => Promise<R>): Promise<Array<PromiseSettledResult<R>>> {
+ const results: Array<PromiseSettledResult<R>> = new Array(items.length);
+ let next = 0;
+ const worker = async () => {
+ while (next < items.length) {
+ const index = next++;
+ results[index] = await run(items[index]!).then(value => ({ status: 'fulfilled' as const, value }), reason => ({ status: 'rejected' as const, reason }));
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
+ return results;
+}
+/** The values in order, or the first failure in input order (the former serial order). */
+function settledValues<R>(results: Array<PromiseSettledResult<R>>): R[] {
+ const failed = results.find(result => result.status === 'rejected');
+ if (failed) throw (failed as PromiseRejectedResult).reason;
+ return results.map(result => (result as PromiseFulfilledResult<R>).value);
+}
const CHAT_REFRESHABLE_ERROR_CODES = new Set(['TOKEN_EXPIRED', 'INVALID_TOKEN', 'AUTH_REQUIRED']);
const recoverableAuth = (error: ChatResponseError) => error.status === 401
&& (CHAT_REFRESHABLE_ERROR_CODES.has(error.message) || error.message === 'INVALID_CHAT_RESPONSE');
@@ -109,6 +146,8 @@ const memberJoinedTrigger = z.object({ type: z.literal('member.joined'), message
displayName: z.string().min(1).refine(value => value.trim().length > 0) }).strict();
type ExecutionContext = { kind: 'message' } | { kind: 'member.joined'; trigger: z.infer<typeof memberJoinedTrigger> };
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.
@@ -240,7 +279,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
pending.delete(sourceId);
if (!pending.size) pendingPlanCancels.delete(roomId);
}
- async function replacePlanIntent(roomId: string, version = ++nextIntentVersion) {
+ /** The synchronous half: a newer intent replaces the room's pending decision at once. */
+ function installPlanIntent(roomId: string, version: number) {
acceptedIntentVersions.set(roomId, version);
const pending = planning.get(roomId);
pending?.controller.abort();
@@ -249,8 +289,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const previous = planIntents.get(roomId);
const intent: PlanIntent = {};
planIntents.set(roomId, intent);
- if (previous?.sourceId) await cancelPlanning(roomId, previous.sourceId);
+ return { intent, previousSourceId: previous?.sourceId };
+ }
+ /** Cancels the replaced decision's deferred message and any cancel that failed before. */
+ async function flushPlanCancels(roomId: string, previousSourceId?: string) {
+ if (previousSourceId) await cancelPlanning(roomId, previousSourceId);
for (const [sourceId, failed] of pendingPlanCancels.get(roomId) ?? []) await cancelPlanning(roomId, sourceId, failed);
+ }
+ async function replacePlanIntent(roomId: string, version = ++nextIntentVersion) {
+ const { intent, previousSourceId } = installPlanIntent(roomId, version);
+ await flushPlanCancels(roomId, previousSourceId);
return intent;
}
// Old servers strictly reject unknown claim fields. Downgrade only after that
@@ -279,13 +327,40 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
let authRefreshPromise: Promise<boolean> | undefined;
let authRefreshRetryAt = 0;
let upgradedGroups = new Map<string, string>();
+ /**
+ * Per room, bumped by every local or realtime change notice. A reused snapshot or sidebar
+ * summary is only valid for the generation it was read in.
+ */
+ const generations = new Map<string, number>();
+ const generation = (roomId: string) => generations.get(roomId) ?? 0;
+ const snapshots = new Map<string, { value: Snapshot; generation: number; at: number }>();
+ const summaries = new Map<string, { key: string; value: BotGroupDetail; at: number }>();
+ const invalidate = (roomId: string) => {
+ generations.set(roomId, generation(roomId) + 1);
+ snapshots.delete(roomId);
+ summaries.delete(roomId);
+ };
+ const pendingChanges = new Map<string, ReturnType<typeof setTimeout>>();
const changed = (roomId: string) => {
if (!current()) return;
- deps.onChanged?.({ groupId: roomId, change: 'messages' }, scope);
- // A restored route may still contain the local ID until the user navigates.
- for (const [sourceId, targetId] of upgradedGroups)
- if (targetId === roomId) deps.onChanged?.({ groupId: sourceId, change: 'messages' }, scope);
+ invalidate(roomId);
+ if (pendingChanges.has(roomId)) return;
+ pendingChanges.set(roomId, setTimeout(() => {
+ pendingChanges.delete(roomId);
+ if (!current()) return;
+ deps.onChanged?.({ groupId: roomId, change: 'messages' }, scope);
+ // A restored route may still contain the local ID until the user navigates.
+ for (const [sourceId, targetId] of upgradedGroups)
+ if (targetId === roomId) deps.onChanged?.({ groupId: sourceId, change: 'messages' }, scope);
+ }, CHANGE_COALESCE_MS));
};
+ /** True when the room's realtime subscription will report a server write made now. */
+ const echoes = (roomId: string) => connected && socket?.readyState === WebSocket.OPEN && rooms.has(roomId);
+ /**
+ * A server write whose own change event the followed room delivers: that event is the one
+ * push. Without a live subscription the local notice stays, so nothing waits for a reconnect.
+ */
+ const changedUnlessEchoed = (roomId: string) => { if (echoes(roomId)) invalidate(roomId); else changed(roomId); };
// TLS for production; explicit loopback is only enabled by the isolated fixture.
// Redirects are never followed and every retry remains in the captured account.
function refreshRejectedToken(token: string): Promise<boolean> {
@@ -444,20 +519,28 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const mirrors = new Set(links.flatMap(link => /^group:([^:]+):access:/.exec(link.routeKey ?? '')?.[1] ?? []));
return result.groups.filter(group => !mirrors.has(group.id) && !workspaces().read(group.id));
}
+ /**
+ * Final group → room answers of this account/endpoint: a server room stays a server room and an
+ * upgraded history keeps its room. A pending upgrade is never cached, so it is asked again.
+ */
+ const resolvedGroups = new Map<string, string>();
/**
* The server room a task started from `groupId` posts into, without touching the network:
* the upgraded room of an old local group, or the id itself for a server room. `null` is an old
* local group that has no room (yet): its local history row exists and is still a local source.
*/
const taskRoomFor = async (groupId: string): Promise<string | null> => {
- if (upgradedGroups.has(groupId)) return upgradedGroups.get(groupId)!;
+ const known = resolvedGroups.get(groupId) ?? upgradedGroups.get(groupId);
+ if (known) return known;
if (!id.safeParse(groupId).success) return null;
const [localRow] = await getDbClient().drizzle.select({ id: botGroups.id }).from(botGroups).where(eq(botGroups.id, groupId)).limit(1);
if (localRow && (await localSources()).some(group => group.id === groupId)) return null;
return groupId;
};
const resolveGroup = async (groupId: string) => {
- await register();
+ const known = resolvedGroups.get(groupId);
+ if (known) { void ensureRegistered(); return known; }
+ await ensureRegistered();
if (upgradedGroups.has(groupId)) return upgradedGroups.get(groupId)!;
// A server room has no local row; only an existing local history may still need its upgrade.
const [localRow] = await getDbClient().drizzle.select({ id: botGroups.id }).from(botGroups).where(eq(botGroups.id, groupId)).limit(1);
@@ -465,7 +548,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
await ensureUpgrade();
if (!upgradedGroups.has(groupId)) throw new Error('IMPORT_PENDING');
}
- return upgradedGroups.get(groupId) ?? groupId;
+ const room = upgradedGroups.get(groupId) ?? groupId;
+ if (current()) resolvedGroups.set(groupId, room);
+ return room;
};
/** Publish one companion's name and avatar to its actor (home copy only). */
async function publishActorProfile(profile: typeof profiles[number], found: Actor) {
@@ -487,6 +572,19 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
await api(`/actors/${found.id}/profile`, 'POST', { name: profile.displayName, avatar, avatarSource: source });
Object.assign(found, { name: profile.displayName, avatar, avatarSource: source });
}
+ /**
+ * Read and send paths use the registration they already have and refresh it in the background
+ * (same five-second throttle, 60-second profile refresh and auth backoff as before); only the
+ * first registration of this account is awaited. Management paths that map local companions to
+ * actors still await `register()`.
+ */
+ function ensureRegistered(): Promise<void> {
+ if (!selfId) return register();
+ void register().catch(() => undefined);
+ return Promise.resolve();
+ }
+ /** Changes to names, avatars or local companions alter every projection, including reused summaries. */
+ let registryKey = '';
async function register() {
if (refreshActors) return refreshActors;
if (Date.now() - registeredAt < 5000 && !actorsStale) return;
@@ -520,6 +618,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
}
profileFailures = failures;
registeredAt = Date.now();
+ const key = JSON.stringify([selfId, actors.map(a => [a.id, a.kind, a.externalId, a.name, a.avatar ?? null]),
+ profiles.map(p => [p.id, p.status, p.displayName, p.avatar, p.avatarColor])]);
+ if (key !== registryKey) { registryKey = key; summaries.clear(); snapshots.clear(); }
})().finally(() => { refreshActors = undefined; });
return refreshActors;
}
@@ -609,7 +710,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const roomId = event.scope.slice(13);
if (rooms.has(roomId)) advanceRoom(roomId, event.cursor);
changed(roomId);
- for (const run of running.values()) if (run.execution.conversation_id === roomId) void checkLease(run);
+ const changes: unknown[] = Array.isArray(event.changes) ? event.changes : [];
+ const types = changes.map(change => (change as { type?: unknown } | null)?.type);
+ // Lease renewals append no change; ordinary chatter cannot revoke a lease, so it does
+ // not renew one either. Any other or unknown change re-checks the room's running work.
+ if (!types.length || types.some(type => typeof type !== 'string' || !CHATTER_CHANGES.has(type)))
+ for (const run of running.values()) if (run.execution.conversation_id === roomId) void checkLease(run);
+ if (changes.some(queuedForThisDevice)) triggerClaim();
}
else {
for (const change of event.changes ?? []) if (change.type === 'membership.changed') changed(change.entityId);
@@ -642,11 +749,27 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
});
}
async function snapshot(roomId: string) {
- id.parse(roomId); await register();
+ id.parse(roomId); await ensureRegistered();
+ const read = generation(roomId);
const value = await api<Snapshot>(`/conversations/${roomId}/snapshot`);
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;
}
+ /**
+ * 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) {
+ id.parse(roomId);
+ const known = snapshots.get(roomId);
+ if (known && echoes(roomId) && known.generation === generation(roomId) && Date.now() - known.at < SNAPSHOT_REUSE_MS) {
+ void ensureRegistered();
+ return Promise.resolve(known.value);
+ }
+ return snapshot(roomId);
+ }
function managementActor(s: Snapshot) {
const eligible = s.members.filter(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role));
return (eligible.find(m => m.role === 'owner') ?? eligible.find(m => m.id === selfId) ?? eligible[0])?.id;
@@ -691,12 +814,28 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
authorBotId: localBot(m.authorId)?.id ?? m.authorId, authorName: legacy?.authorKind === 'system' && typeof legacy.authorName === 'string' ? legacy.authorName : member ? memberName(member) : m.author.name, content: bodyText(m),
mentions: { all: false, botIds: [] }, 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
+ * people, not this account, notices or system events, nor deleted messages. Derived from the
+ * snapshot already read (its newest 100 messages), so it costs no request.
+ */
+ function incomingMessageTimes(messages: Message[], members: Member[]): string[] {
+ const times: Array<{ at: number; iso: string }> = [];
+ for (const m of messages) {
+ if (m.deleted || m.origin === 'system' || m.authorId === selfId) continue;
+ const view = messageView(m, members);
+ if (view.isSelf || view.authorKind === 'system' || (view.kind !== 'message' && view.kind !== 'plan')) continue;
+ const at = Date.parse(m.createdAt);
+ if (Number.isFinite(at)) times.push({ at, iso: new Date(at).toISOString() });
+ }
+ return times.sort((a, b) => b.at - a.at).slice(0, 99).reverse().map(time => time.iso);
+ }
/**
* The quoted message as this member reads it from the server: the room scopes the read,
* so another group's or an invisible message is a 404. Only a live main-timeline chat
* message can be quoted; the snapshot never comes from the controller's input.
*/
- async function quoteSnapshot(roomId: string, messageId: string, members: Member[]): Promise<BotGroupQuoteView> {
+ async function quoteSnapshot(roomId: string, messageId: string, members: Promise<Member[]>): Promise<BotGroupQuoteView> {
let quoted: Message;
try {
quoted = await api<Message>(`/conversations/${roomId}/messages/${messageId}`);
@@ -704,7 +843,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if (error instanceof ChatResponseError && [403, 404].includes(error.status)) throw new Error('QUOTE_UNAVAILABLE');
throw error;
}
- const view = messageView(quoted, members);
+ const view = messageView(quoted, await members);
if (quoted.id !== messageId || quoted.deleted || quoted.threadRootId !== null || quoted.origin === 'system'
|| view.kind !== 'message' || view.authorKind === 'system') throw new Error('QUOTE_UNAVAILABLE');
return botGroupQuoteFromMessage({ ...view, content: quotedText(quoted),
@@ -771,9 +910,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const workspace = workspaces().read(roomId);
const plans = serverPlans.map(plan => planView(plan, s.members, workspace));
const open = plans.find(p => ['proposed', 'running', 'waiting'].includes(p.status));
- const speakers = executions.filter(e => e.status === 'running').map(e => ({
+ const speakers: BotGroupSpeaker[] = executions.filter(e => e.status === 'running').map(e => ({
botId: localBot(e.bot_id)?.id ?? e.bot_id, sessionId: running.get(e.bot_id)?.sessionId ?? null, activity: e.plan_id ? 'step' as const : 'reply' as const,
}));
+ // The organizer is visibly 「正在看」 while this device decides whether to arrange (§7.2),
+ // as the local service showed it. It works on the auxiliary model, not in a lane session.
+ const deciding = planning.get(roomId);
+ if (deciding) speakers.push({ botId: deciding.botId, sessionId: null, activity: 'planning' });
// Sidebar refresh must not download every attachment in every group's history.
const messages = summaryOnly ? [] : (await messageViews(roomId, page, s.members)).sort((a, b) => a.sequence - b.sequence);
const last = s.messages[0];
@@ -792,9 +935,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
} : null, speakingBotIds: speakers.map(s => s.botId), planningBotId: planning.get(roomId)?.botId ?? null, openPlan: open ? { id: open.id, status: open.status, currentStep: open.currentStep, stepCount: open.steps.length, currentBotName: open.steps[open.currentStep ?? 0]?.botName ?? null, currentStepStatus: open.steps[open.currentStep ?? 0]?.status ?? null } : null,
lastReplyAt: s.messages.reduce((latest, m) => !m.deleted && m.origin !== 'system' && m.authorId !== selfId
? Math.max(latest, Date.parse(m.createdAt)) : latest, 0),
+ incomingMessageTimes: incomingMessageTimes(s.messages, s.members),
createdAt: Date.parse(s.room.created_at), updatedAt: Date.parse(s.room.updated_at ?? s.room.created_at),
messages, executionFailures, hasMoreBefore: page.length === (o.limit ?? 100), plans,
- round: { status: executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers, canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id && ordinaryExecution(e)) || s.messages.some(m => !m.deleted && m.origin !== 'system' && m.author.kind === 'human' && !m.content.some(b => b.namespace === 'cindy.plan'))) && !executions.some(e => ['queued','running','stopping'].includes(e.status)) } };
+ round: { status: deciding || executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers, canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id && ordinaryExecution(e)) || s.messages.some(m => !m.deleted && m.origin !== 'system' && m.author.kind === 'human' && !m.content.some(b => b.namespace === 'cindy.plan'))) && !executions.some(e => ['queued','running','stopping'].includes(e.status)) } };
}
function planView(plan: ServerPlan, members: Member[], workspace: ReturnType<ReturnType<typeof chatServerWorkspaces>['read']>): BotGroupPlanView {
return { id: plan.id, status: plan.status, organizerBotId: localBot(plan.organizer_id)?.id ?? plan.organizer_id,
@@ -870,11 +1014,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const sources = new Set(sourceIds);
let rows: unknown[] = [];
try {
- for (const batch of botGroupExecutionFailureBatches(sourceIds)) {
+ // Batches are read a few at a time; the first failing batch in order decides, as serially.
+ const pages = settledValues(await settleBounded(botGroupExecutionFailureBatches(sourceIds), FAILURE_BATCH_CONCURRENCY, async batch => {
const page = await api<unknown[]>(`/conversations/${roomId}/execution-failures?sourceIds=${batch.join(',')}`);
if (!Array.isArray(page)) throw new Error('INVALID_CHAT_RESPONSE');
- rows.push(...page);
- }
+ return page;
+ }));
+ for (const page of pages) rows.push(...page);
}
catch (error) {
// Only a missing route may use the old server's bounded execution list.
@@ -909,6 +1055,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const pending = run.settlement;
if (!pending || !current() || running.get(run.execution.bot_id) !== run || Date.now() < pending.retryAt) return Promise.resolve();
run.delivery = (async () => {
+ let delivered = false;
try {
if (!pending.payload) {
const terminal = pending.terminal;
@@ -934,6 +1081,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
}
if (!current() || running.get(run.execution.bot_id) !== run) return;
await updateExecution(run, pending.terminal.outcome === 'error' ? 'fail' : 'complete', pending.payload);
+ delivered = true;
if (run.plan && deps.onStepSettled) {
const s = await snapshot(run.execution.conversation_id);
const step = run.plan.steps[run.execution.plan_step!];
@@ -959,7 +1107,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if (running.get(run.execution.bot_id) === run) {
run.releaseToolAuthority?.();
running.delete(run.execution.bot_id);
- changed(run.execution.conversation_id);
+ // A delivered terminal result is an execution change the followed room reports itself;
+ // a rejected one changed nothing on the server, so only the local notice shows it.
+ if (delivered) changedUnlessEchoed(run.execution.conversation_id);
+ else changed(run.execution.conversation_id);
}
})();
return run.delivery;
@@ -987,13 +1138,23 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
|| 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 snapshot(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;
// 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;
- if (run.context.kind === 'member.joined') {
- const trigger = run.context.trigger;
- eventSource = await api<Message>(`/conversations/${s.room.id}/messages/${trigger.messageId}`);
+ if (trigger && eventSourceRead) {
+ eventSource = await eventSourceRead;
const card = eventSource.content?.find(block => block.type === 'card' && block.namespace === 'cindy.membership'
&& block.schemaRevision === 1 && block.data?.type === trigger.type
&& block.data.actorId === trigger.actorId && block.data.displayName === trigger.displayName);
@@ -1010,128 +1171,158 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
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 (local) and the turn's context (server reads, attachment downloads) are
+ // independent; both finish before the single lease check that precedes the dispatch.
+ 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);
+ }
+ 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, candidate => 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 };
+ })();
+ const [laneResult, contextResult] = await Promise.allSettled([laneSetup, contextRead]);
+ if (laneResult.status === 'rejected') throw laneResult.reason;
+ if (contextResult.status === 'rejected') throw contextResult.reason;
+ const lane = laneResult.value;
+ const { history, source, threadRootId, thread, focusMessages, attachments, missingAttachments, mediaDelivery } = contextResult.value;
if (!current()) throw new Error('OWNER_CHANGED');
- const history = await api<Message[]>(`/conversations/${s.room.id}/messages?all=true&limit=100&before=${BigInt(execution.context_seq) + 1n}`);
- let page = [...history];
- if (eventSource && !history.some(message => message.id === eventSource.id)) history.push(eventSource);
- if (run.plan) for (const messageId of new Set([run.plan.source_message_id, ...run.plan.steps.flatMap(step => step.resultMessageId ? [step.resultMessageId] : []), ...(run.plan.note_message_ids ?? [])])) {
- if (!history.some(message => message.id === messageId)) history.push(await api<Message>(`/conversations/${s.room.id}/messages/${id.parse(messageId)}`));
- }
- // The request is identified by the execution, not by recency. The mixed
- // room page carries no Thread structure, so a Thread request also reads its
- // root and replies explicitly, even when they predate the bounded page.
- const source = run.context.kind === 'message'
- ? history.find(message => message.id === execution.source_message_id) ?? await readMessage(s.room.id, execution.source_message_id)
- : undefined;
- if (source?.origin === 'system') throw new Error('INVALID_EXECUTION_TRIGGER');
- const threadRootId = source?.threadRootId ?? null;
- let thread: { root?: Message; replies: Message[]; earlierRepliesOmitted: boolean; background: Message[] } | undefined;
- if (threadRootId) {
- const before = BigInt(execution.context_seq) + 1n;
- const replies = await api<Message[]>(`/conversations/${s.room.id}/messages?threadRootId=${id.parse(threadRootId)}&limit=100&before=${before}`);
- // Read the main timeline on its own: busy Threads can fill the mixed page.
- const background = await api<Message[]>(`/conversations/${s.room.id}/messages?limit=${THREAD_BACKGROUND_LIMIT + 1}&before=${before}`);
- thread = { root: await readMessage(s.room.id, threadRootId), replies, earlierRepliesOmitted: replies.length >= 100,
- background: background.filter(message => message.id !== threadRootId).slice(0, THREAD_BACKGROUND_LIMIT) };
- if (source && !replies.some(message => message.id === source.id)) replies.push(source);
- }
- const focusMessages = [source, thread?.root, ...(thread?.replies ?? [])].flatMap(message => message ? [message] : []);
- const focus = new Set(focusMessages.map(message => message.id));
- // Text stays bounded, but unseen attachments may precede the latest text page.
- // The server watermark is scoped to this bot/grant/plan step and advances only on success.
- const attachmentHistory = [...history, ...[...focusMessages, ...(thread?.background ?? [])].filter(message => !history.some(known => known.id === message.id))];
- const after = BigInt(execution.attachment_after_seq ?? '0');
- while (execution.attachment_after_seq !== undefined && page.length === 100) {
- const before = page.reduce((min, m) => BigInt(m.seq) < min ? BigInt(m.seq) : min, BigInt(execution.context_seq) + 1n);
- if (before <= after + 1n) break;
- page = await api<Message[]>(`/conversations/${s.room.id}/messages?all=true&limit=100&before=${before}`);
- attachmentHistory.push(...page);
- }
- const attachments: BotGroupAttachment[] = [];
- const missingAttachments: string[] = [];
- // Attach a bounded newest set, and retain the names of older files in context.
- // The request and its Thread come first so the cap cannot drop the files under discussion.
- // A Thread request never carries other Threads' files, and its own Thread's files are
- // offered again regardless of the watermark, which only records a successful turn.
- const mediaDelivery = new Map<string, 'included' | 'not-included'>();
- const order = (message: Message) => focus.has(message.id) ? 1 : 0;
- for (const message of attachmentHistory.sort((a, b) => order(b) - order(a) || (BigInt(a.seq) < BigInt(b.seq) ? 1 : -1))) for (const block of message.content) {
- if (thread && message.threadRootId && !focus.has(message.id)) continue;
- if (message.deleted || block.type !== 'media' || !block.mediaId || mediaDelivery.has(block.mediaId)) continue;
- if (BigInt(message.seq) <= after && !(thread && focus.has(message.id))) continue;
- mediaDelivery.set(block.mediaId, 'not-included');
- if (attachments.length >= 40) { missingAttachments.push(block.caption ?? block.mediaId); continue; }
- try { attachments.push(await media.download(s.room.id, id.parse(block.mediaId))); mediaDelivery.set(block.mediaId, 'included'); }
- catch { missingAttachments.push(block.caption ?? block.mediaId); }
- }
// A quote resolves against every message this run read; otherwise its card snapshot stands.
const readMessages = [...history, ...focusMessages, ...(thread?.background ?? [])];
const promptMessage = (m: Message) => ({ id: m.id, from: m.author.name, kind: m.origin === 'system' ? 'system' : m.author.kind, text: bodyText(m),
@@ -1227,6 +1418,68 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
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 };
+ // 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;
@@ -1235,34 +1488,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
await register();
beginUpgrade();
if (!socket) connect();
- for (const actor of actors.filter(a => a.kind === 'bot' && localBot(a.id)?.status === 'active')) {
- if (running.has(actor.id)) continue;
- // 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).
- if (companionHome && actor.homeDeviceId !== selfDeviceId) continue;
- // 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.
- if (companionHome && (companion?.isShadowed(actor.externalId) || !companion?.installConfirmed(actor.externalId))) continue;
- let claim: { execution: Execution | null };
- const payload = { operationId: randomUUID(), executorId, accessPolicyVersion: 1, planVersion: 1 };
- try {
- claim = await api('/executions/claim', 'POST', { ...payload, ...(memberJoinedClaims ? { memberJoinedVersion: 1 } : {}) }, actor.id);
- } catch (error) {
- if (!memberJoinedClaims || !(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);
- }
- })().then(() => { pollFailures = 0; pollRetryAt = 0; }).catch(error => {
- 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));
- }
- }).finally(() => { polling = false; });
+ if (claiming) claimAgain = true;
+ else await claimAll();
+ })().then(() => { pollFailures = 0; pollRetryAt = 0; }).catch(pollFailed).finally(() => {
+ polling = false;
+ // A realtime notice that arrived after this poll's claims still claims promptly.
+ if (claimAgain && !claiming) { claimAgain = false; triggerClaim(); }
+ });
}, 2000);
const checking = new Set<Running>();
async function checkLease(run: Running) {
@@ -1313,8 +1545,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
deps.log?.warn('Chat group action failed', chatErrorDiagnostic(error));
return chatGroupFailure(error instanceof z.ZodError ? new Error('INVALID_PARAMS') : error);
});
+ /** A message that names nobody needs no member read: its mention list is empty either way. */
+ const namesNobody = (mentions: { all: boolean; botIds: string[] }) => !mentions.all && !mentions.botIds.length;
async function mentionIds(roomId: string, mentions: { all: boolean; botIds: string[] }) {
- const members = await api<Member[]>(`/conversations/${roomId}/members`);
+ if (namesNobody(mentions)) return [];
+ return resolveMentions(await api<Member[]>(`/conversations/${roomId}/members`), mentions);
+ }
+ function resolveMentions(members: Member[], mentions: { all: boolean; botIds: string[] }) {
const joined = members.filter(m => m.state === 'joined');
// A stale explicit target must never become an unaddressed message. Check
// every pick, including mixed valid/stale picks, before expanding Everyone.
@@ -1376,9 +1613,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
thread: input => result(async () => {
const i = z.object({ groupId: id, rootId: id, before: z.number().int().positive().optional(), sourceMessageIds: z.array(id).optional() }).parse(input);
i.groupId = await resolveGroup(i.groupId); subscribe(i.groupId);
- const members = await api<Member[]>(`/conversations/${i.groupId}/members`);
- const root = await api<Message>(`/conversations/${i.groupId}/messages/${i.rootId}`);
- const page = await api<Message[]>(`/conversations/${i.groupId}/messages?threadRootId=${i.rootId}&limit=50${i.before ? `&before=${i.before}` : ''}`);
+ // One round trip; awaited in the former order so the same failure is reported first.
+ const membersRead = api<Member[]>(`/conversations/${i.groupId}/members`);
+ const rootRead = api<Message>(`/conversations/${i.groupId}/messages/${i.rootId}`);
+ const pageRead = api<Message[]>(`/conversations/${i.groupId}/messages?threadRootId=${i.rootId}&limit=50${i.before ? `&before=${i.before}` : ''}`);
+ for (const read of [rootRead, pageRead]) read.catch(() => undefined);
+ const members = await membersRead;
+ const root = await rootRead;
+ const page = await pageRead;
const executionFailures = await failureSnapshot(i.groupId, members, [...(i.sourceMessageIds ?? []), root.id, ...page.map(m => m.id)]);
return { root: (await messageViews(i.groupId, [root], members))[0], executionFailures,
replies: await messageViews(i.groupId, page.reverse(), members), hasMore: page.length === 50 };
@@ -1386,11 +1628,11 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
reply: input => result(async () => {
const i = z.object({ groupId: id, rootId: id, text: z.string().trim().min(1).max(8000), clientId: operationId,
mentions: z.object({ all: z.boolean(), botIds: z.array(z.string()).max(100) }) }).parse(input);
- await register();
+ await ensureRegistered();
const posted = await api<{ id: string }>(`/conversations/${i.groupId}/messages`, 'POST', {
operationId: i.clientId, threadRootId: i.rootId, content: [{ type: 'text', text: i.text }], mentions: await mentionIds(i.groupId, i.mentions),
});
- changed(i.groupId); return { messageId: posted.id };
+ changedUnlessEchoed(i.groupId); return { messageId: posted.id };
}),
react: input => result(async () => {
const i = z.object({ groupId: id, messageId: id, emoji: z.string().min(1).max(128), present: z.boolean() }).parse(input);
@@ -1430,6 +1672,22 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
* deleted since, so the server returns the message it already stored instead of a second one.
*/
const postedQuotes = new Map<string, BotGroupQuoteView>();
+ /**
+ * A sidebar summary. The room list carries each room's change head, which every message,
+ * execution, plan and membership change advances; a room whose head, revision and local state
+ * (planning, running turns, upgrade notices: its change generation) are unchanged is not
+ * re-read, so a push re-reads only the rooms that changed. Old servers without a head re-read.
+ */
+ async function summary(room: Room & { head?: unknown }): Promise<BotGroupDetail> {
+ const head = typeof room.head === 'string' && /^\d+$/.test(room.head) ? room.head : null;
+ const key = head === null ? null : JSON.stringify([head, room.revision, room.updated_at, generation(room.id), registryKey]);
+ const known = summaries.get(room.id);
+ if (key !== null && known?.key === key && Date.now() - known.at < SUMMARY_REUSE_MS) return known.value;
+ const value = await detail(room.id, undefined, true);
+ if (key !== null && current() && JSON.stringify([head, room.revision, room.updated_at, generation(room.id), registryKey]) === key)
+ summaries.set(room.id, { key, value, at: Date.now() });
+ return value;
+ }
const sendMessage: BotGroupChatService['sendMessage'] = (input, origin) => safe(async () => {
const started = Date.now();
const i = z.object({ groupId: id, text: z.string().max(8000), clientId: z.string().min(8).max(160),
@@ -1439,11 +1697,21 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
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 snapshot(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 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');
@@ -1459,7 +1727,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
let result: { id: string };
let posting = false;
try {
- const mentions = await mentionIds(i.groupId, i.mentions);
+ const mentions = membersRead ? resolveMentions(await membersRead, i.mentions) : [];
const uploaded = await media.upload(i.groupId, i.clientId, prepared?.ok ? prepared.attachments : [], selfId);
// Cached only once the message may reach the server; a failure before this stored nothing.
if (quote) {
@@ -1479,20 +1747,37 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
throw error;
}
if (prepared?.ok) prepared.commit();
- const intent = intentVersion > (acceptedIntentVersions.get(i.groupId) ?? 0)
- ? await replacePlanIntent(i.groupId, intentVersion) : null;
- if (shouldPlan) {
- if (!intent || planIntents.get(i.groupId) !== intent) await cancelPlanning(i.groupId, result.id);
- else {
- intent.sourceId = result.id;
- void decideArrangement(s, result.id, i.text, i.division === true, prepared?.ok ? prepared.attachments : [], intent, quote).catch(() => undefined);
- }
- }
deps.log?.info?.('Chat group send confirmed', { groupId: i.groupId, messageId: result.id,
trace: createHash('sha256').update(i.clientId).digest('hex').slice(0, 16), durationMs: Date.now() - started });
- // Only a send that finished, bookkeeping included, has a receipt; until then a retry needs the same quote.
+ // The message exists: the send is answered now and its receipt answers any retry, so the
+ // quote snapshot is no longer needed. Arrangement bookkeeping continues after the answer.
postedQuotes.delete(quoteKey);
- changed(i.groupId); return { ok: true as const, messageId: result.id };
+ const roomId = i.groupId;
+ const messageId = result.id;
+ void (async () => {
+ // Installing the intent is synchronous, so a newer send or control action still
+ // supersedes this one in order; only the cancels of replaced decisions are awaited.
+ const installed = intentVersion > (acceptedIntentVersions.get(roomId) ?? 0) ? installPlanIntent(roomId, intentVersion) : null;
+ if (installed) {
+ try { await flushPlanCancels(roomId, installed.previousSourceId); }
+ catch (error) {
+ // A failed cancel stays pending and is retried once here (and by the next intent).
+ deps.log?.warn('Group arrangement cancel will retry', { groupId: roomId, ...chatErrorDiagnostic(error) });
+ await flushPlanCancels(roomId).catch(retryError => deps.log?.warn('Group arrangement cancel failed', { groupId: roomId, ...chatErrorDiagnostic(retryError) }));
+ }
+ }
+ const intent = installed?.intent ?? null;
+ if (shouldPlan) {
+ if (!intent || planIntents.get(roomId) !== intent) await cancelPlanning(roomId, messageId);
+ else {
+ intent.sourceId = messageId;
+ void decideArrangement(s, messageId, i.text, i.division === true, prepared?.ok ? prepared.attachments : [], intent, quote).catch(() => undefined);
+ }
+ }
+ })().catch(error => deps.log?.warn('Group send bookkeeping failed', { groupId: roomId, ...chatErrorDiagnostic(error) }));
+ // The followed room reports the new message itself; otherwise announce it here.
+ changedUnlessEchoed(roomId);
+ return { ok: true as const, messageId };
});
// A lost controller ACK must not consume the phone upload or submit the same message twice.
const pendingSends = new Map<string, ReturnType<BotGroupChatService['sendMessage']>>();
@@ -1500,14 +1785,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
return {
chatServer,
listGroups: () => safe(async () => {
- await register(); beginUpgrade();
+ await ensureRegistered(); beginUpgrade();
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');
- 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 };
@@ -1549,6 +1834,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
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);
let projectDir = i.projectDir;
if (projectDir) { const checked = await deps.validateProjectDir?.(projectDir); if (!checked?.ok) throw new Error('INVALID_DIRECTORY'); projectDir = checked.dir; }
@@ -1646,7 +1932,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
},
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); const s = await snapshot(room);
+ const room = await resolveGroup(i.groupId); await register(); const s = await snapshot(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));
@@ -1658,6 +1944,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const room = await resolveGroup(id.parse(groupId)); const s = await snapshot(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 () => {
@@ -1673,10 +1960,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
continuePlan: input => safe(() => actPlan(input, 'continue')), retryPlan: input => safe(() => actPlan(input, 'retry')),
editPlanStep: input => safe(() => actPlan(input, 'reassign')),
dispose: () => {
- disposed = true; clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); socket?.close();
+ disposed = true; clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); clearTimeout(claimTrigger); socket?.close();
companion?.dispose(); companion = undefined; deps.companionCloud?.homes.reset();
for (const refresh of attachmentRefreshes.values()) clearTimeout(refresh);
attachmentRefreshes.clear();
+ for (const pending of pendingChanges.values()) clearTimeout(pending);
+ pendingChanges.clear();
for (const run of running.values()) {
run.releaseToolAuthority?.();
if (run.sessionId) void deps.abortLane(run.sessionId).catch(() => undefined);
diff --git a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
index d287523651..e00c02fcfd 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
@@ -13,6 +13,8 @@ import type { BotGroupAttachment } from '../../shared/botGroupChat.js';
import type { ChatApi, ChatContentBlock } from './chatServerMigration.js';
const MAX_SIZE = 100 * 1024 * 1024;
+/** Files of one send uploaded at once; each holds its bytes in memory until sealed. */
+const UPLOAD_CONCURRENCY = 3;
export function createChatMedia(api: ChatApi, current: () => boolean, log?: { warn(message: string, meta?: Record<string, unknown>): void }, options: { allowLoopback?: boolean } = {}) {
const cache = new Map<string, Promise<BotGroupAttachment>>();
const check = () => { if (!current()) throw new Error('OWNER_CHANGED'); };
@@ -22,9 +24,27 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { wa
return url.href;
};
return {
+ /**
+ * Uploads a send's files a few at a time (prepare → PUT → complete each), keeping the
+ * blocks in the files' order. Every file settles before a failure is reported, so no
+ * upload keeps running after the send has given up; the first failure in order wins.
+ */
async upload(roomId: string, source: string, attachments: BotGroupAttachment[], actorId: string): Promise<ChatContentBlock[]> {
- const blocks: ChatContentBlock[] = [];
- for (const attachment of attachments) {
+ const results: Array<PromiseSettledResult<ChatContentBlock>> = new Array(attachments.length);
+ let next = 0;
+ const worker = async () => {
+ while (next < attachments.length) {
+ const index = next++;
+ results[index] = await uploadOne(attachments[index]!).then(
+ value => ({ status: 'fulfilled' as const, value }), reason => ({ status: 'rejected' as const, reason }));
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(UPLOAD_CONCURRENCY, attachments.length) }, worker));
+ const failed = results.find(result => result.status === 'rejected');
+ if (failed) throw failed.reason;
+ return results.map(result => (result as PromiseFulfilledResult<ChatContentBlock>).value);
+
+ async function uploadOne(attachment: BotGroupAttachment): Promise<ChatContentBlock> {
let stage = 'read';
const started = Date.now();
try {
@@ -61,14 +81,13 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { wa
check();
stage = 'complete';
await api(`/conversations/${roomId}/media/${upload.id}/complete`, 'POST', { operationId: `seal:${upload.id}` }, actorId);
- blocks.push({ type: 'media', mediaId: upload.id, caption: attachment.name });
+ return { type: 'media', mediaId: upload.id, caption: attachment.name };
} catch (error) {
log?.warn('Chat media upload failed', { stage, groupId: roomId,
trace: createHash('sha256').update(source).digest('hex').slice(0, 16), durationMs: Date.now() - started, ...chatErrorDiagnostic(error) });
throw error;
}
}
- return blocks;
},
async download(roomId: string, mediaId: string): Promise<BotGroupAttachment> {
check();
diff --git a/apps/desktop/src/renderer/__tests__/botCollaborationMessages.test.ts b/apps/desktop/src/renderer/__tests__/botCollaborationMessages.test.ts
index 8ac8b2498f..6d373618d0 100644
--- a/apps/desktop/src/renderer/__tests__/botCollaborationMessages.test.ts
+++ b/apps/desktop/src/renderer/__tests__/botCollaborationMessages.test.ts
@@ -140,6 +140,16 @@ describe('mapServerMessages — Bot collaboration', () => {
});
});
+ it('projects the bounded interjection preview while still dropping persisted text', () => {
+ const [mapped] = makerChatStore.__mapServerMessagesForTest([row({
+ clientId: 'bot-delegation-interject-mirror:delegation-1:n2',
+ content: '',
+ agentMeta: { botCollaboration: { ...META, role: 'interjection', interjectionPreview: '测试也要覆盖断网重连' } },
+ })]);
+ expect(mapped.systemCardType).toBe('bot-session-task-message');
+ expect(mapped.systemCardData).toMatchObject({ interjectionPreview: '测试也要覆盖断网重连', text: '' });
+ });
+
it.each(['user', 'assistant'] as const)('preserves ordinary %s content that resembles an internal receipt', (role) => {
const content = '已向后台任务发送消息:读取 /workspace/project/AGENTS.md';
const [plain, invalid] = makerChatStore.__mapServerMessagesForTest([
diff --git a/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx b/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx
index edee8ab802..c9c2de73d4 100644
--- a/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx
@@ -191,7 +191,7 @@ describe('伙伴成果卡', () => {
expect(screen.getByTestId('bot-generated-artifacts')).toBeTruthy();
});
- it.each(['stop', 'error', 'history'])('omits the preamble and process entry once a real generated file is visible: %s', async (ending) => {
+ it.each(['stop', 'error', 'history'])('omits the preamble once a real generated file is visible, keeping only the work fold: %s', async (ending) => {
let finish!: (value: FileStat) => void;
const stat = vi.fn(() => new Promise<FileStat>((resolve) => { finish = resolve; }));
window.electronAPI.fsBrowse.statPath = stat;
@@ -207,7 +207,8 @@ describe('伙伴成果卡', () => {
await act(async () => finish({ kind: 'file', resolvedPath: '/bot/workspace/result.pdf', birthtimeMs: START + 100, mtimeMs: START + 100 }));
expect(screen.getByText('result.pdf')).toBeTruthy();
expect(screen.queryByTestId('main-prose')).toBeNull();
- expect(screen.queryByTestId('public-process')).toBeNull();
+ // The tool run stays in the normal work fold; the preamble never resurfaces there.
+ expect(screen.getByTestId('public-process').textContent).toBe('');
expect(screen.queryByText('Generating the report')).toBeNull();
if (ending === 'error') expect(screen.getByTestId('error').textContent).toBe('Generation interrupted');
expect(stat).toHaveBeenCalledTimes(1);
diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
index e65f6c7105..cebc44a30c 100644
--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
@@ -162,7 +162,7 @@ describe('Bot 流式正文呈现', () => {
expect(visibleProse()).toEqual(['first', 'second']);
});
- it('运行中从首字隐藏未封口正文与工具,不保留过程入口', () => {
+ it('运行中从首字隐藏未封口正文,工具留在普通工作组里', () => {
const messages = [
mkUser('u1'),
mkTool('t1', 'Bash'),
@@ -175,7 +175,10 @@ describe('Bot 流式正文呈现', () => {
expect(
visible.flatMap((item) => (item.type === 'message' ? [item.message.clientId] : [])),
).toEqual(['u1']);
- expect(visible.some((item) => item.type === 'work_group')).toBe(false);
+ // 与普通任务同一个工作组:正文开始后,前面的动作段不再是运行中尾段。
+ const groups = visible.filter((item) => item.type === 'work_group');
+ expect(groups).toHaveLength(1);
+ expect(groups[0].type === 'work_group' && groups[0].children.map((child) => child.type)).toEqual(['tool_segment']);
});
// Contracts: claude-code/translator assistant text blocks; pi/translator
@@ -240,7 +243,10 @@ describe('Bot 流式正文呈现', () => {
expect(project().find(item => item.type === 'message'
&& item.message.clientId === 'answer-2')?.key).toBe(streamingFinalKey);
}
- expect(project().filter((item) => item.type === 'work_group')).toHaveLength(0);
+ // Intermediate prose and both tool runs fold into one normal summary group.
+ const groups = project().filter((item) => item.type === 'work_group');
+ expect(groups).toHaveLength(1);
+ expect(groups[0].key.startsWith('work-summary-')).toBe(true);
expect(state.messages.filter((message) => message.role === 'assistant').map((message) => message.content))
.toEqual(['我查一下:', '已找到线索,继续核实', '这是最终答复']);
state = { ...state, isStreaming: false };
diff --git a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
index 82edb97886..f5d56fbc3b 100644
--- a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
+++ b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
@@ -30,15 +30,17 @@ describe('controlled banner placement', () => {
'const controlledBannerCollapsed = useComposerCollapsed(sessionId ?? null);',
);
expect(sessionViewSource).toContain(
- 'hasControlledBanner && (!controlledBannerCollapsed || Boolean(botChatIdentity));',
+ 'const showCenteredControlledBanner = hasControlledBanner && !controlledBannerCollapsed;',
);
expect(sessionViewSource).toContain('placement="composer"');
expect(sessionViewSource).toContain('sessionId={sessionId ?? null}');
expect(sessionViewSource).toContain('rightLeadingSlot={');
expect(sessionViewSource).toContain('hasControlledBanner && controlledBannerCollapsed ? (');
- expect(sessionViewSource).toMatch(
- /botChatIdentity \? \([\s\S]*?\) : !pendingPlanReview \|\|\s+\(hasControlledBanner && controlledBannerCollapsed\) \? \(/,
+ // 伙伴与普通任务共用 RunningStatusBar;折叠呼吸灯随 token 元数据一起显示。
+ expect(sessionViewSource).toContain(
+ '{!pendingPlanReview || (hasControlledBanner && controlledBannerCollapsed) ? (',
);
+ expect(sessionViewSource).not.toContain('<BotWorkingStatus');
expect(sessionViewSource).toContain('suppressContent={Boolean(pendingPlanReview)}');
expect(sessionViewSource).toContain(
'const isHidden = suppressContent || (!showContent && !visible);',
diff --git a/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts b/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
index ecfef5fd0f..5a8d86214d 100644
--- a/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
@@ -9,6 +9,12 @@ import {
resolveSessionRoute,
} from '@/lib/orcaSessionIdentity';
+const bots = vi.hoisted(() => ({ loaded: true, profiles: [] as unknown[] }));
+vi.mock('@/features/bots/botStore', () => ({
+ hasLoadedBotProfiles: () => bots.loaded,
+ getBotProfiles: () => bots.profiles,
+}));
+
describe('orcaSessionIdentity', () => {
let originalWindow: unknown;
@@ -30,6 +36,8 @@ describe('orcaSessionIdentity', () => {
afterEach(() => {
(globalThis as unknown as { window?: unknown }).window = originalWindow;
+ bots.loaded = true;
+ bots.profiles = [];
vi.restoreAllMocks();
});
@@ -107,6 +115,29 @@ describe('orcaSessionIdentity', () => {
expect(api.localDb.orcaWorkflows.getByWorkerSession).not.toHaveBeenCalled();
});
+ it('opens a Bot chat on its Bot page and keeps a background task on the ordinary route', async () => {
+ bots.profiles = [{
+ id: 'bot-a',
+ sessions: [
+ { id: 'bot-main', role: 'canonical', kind: 'chat' },
+ { id: 'bot-old', role: 'history', kind: 'history' },
+ { id: 'bot-task', role: 'delegation', kind: 'worker' },
+ { id: 'bot-lane', role: 'group', kind: 'group' },
+ ],
+ }];
+ await expect(resolveSessionRoute('bot-main', { orcaRole: null, source: 'bot' })).resolves.toBe('/bots/bot-a');
+ await expect(resolveSessionRoute('bot-old', { orcaRole: null })).resolves.toBe('/bots/bot-a/history/bot-old');
+ await expect(resolveSessionRoute('bot-task', { orcaRole: null, source: 'desktop' })).resolves.toBe('/cc-agent/bot-task');
+ await expect(resolveSessionRoute('bot-lane', { orcaRole: null })).resolves.toBe('/cc-agent/bot-lane');
+ await expect(resolveSessionRoute('plain-3', { orcaRole: null })).resolves.toBe('/cc-agent/plain-3');
+ });
+
+ it('falls back to the ordinary route while Bot profiles are not loaded, without waiting on IPC', async () => {
+ bots.loaded = false;
+ bots.profiles = [{ id: 'bot-a', sessions: [{ id: 'bot-main', role: 'canonical', kind: 'chat' }] }];
+ await expect(resolveSessionRoute('bot-main', { orcaRole: null })).resolves.toBe('/cc-agent/bot-main');
+ });
+
it('routes orphaned Orca workers back through the index fallback', async () => {
const api = electronApiMock();
api.localDb.orcaWorkflows.getByWorkerSession.mockResolvedValue(null);
diff --git a/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts b/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts
index 1aacd8e7f0..79c56f2ea2 100644
--- a/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts
+++ b/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts
@@ -125,13 +125,17 @@ describe('历史窗口空洞 — 跨空洞不合并工作组', () => {
expect(groupContains(beforeGap[0], 't2')).toBe(false);
});
- it.each([false, true])('伙伴投影保留空洞前答复并隐藏两侧过程,active=%s', (streaming) => {
+ it.each([false, true])('伙伴投影保留空洞前答复,两侧过程各自留在普通工作组里,active=%s', (streaming) => {
const { items } = buildRenderItems(gapMessages());
const projected = simplifyBotRenderItems(groupWorkRuns(items, streaming), streaming);
const prose = projected.flatMap((item) => item.type === 'message' && item.message.role === 'assistant'
? [item.message.clientId] : []);
expect(prose).toEqual(streaming ? ['a1'] : ['a1', 'a2']);
- expect(workGroups(projected)).toHaveLength(0);
+ const groups = workGroups(projected);
+ expect(groups.some((group) => groupContains(group, 't1'))).toBe(true);
+ expect(groups.some((group) => groupContains(group, 't2'))).toBe(true);
+ // 与普通任务一样:同一个组不能同时装着空洞两侧的动作。
+ expect(groups.some((group) => groupContains(group, 't1') && groupContains(group, 't2'))).toBe(false);
expect(projected.some(item => item.type === 'tool_segment')).toBe(false);
});
@@ -229,7 +233,8 @@ describe('历史窗口空洞 — 长任务不被误判', () => {
const projected = simplifyBotRenderItems(grouped, false);
expect(projected.flatMap((item) => item.type === 'message' && item.message.role === 'assistant'
? [item.message.clientId] : [])).toEqual(['a1']);
- expect(workGroups(projected)).toHaveLength(0);
+ // 伙伴与普通任务同一个「已工作」组,进度文字留在组内。
+ expect(workGroups(projected)).toEqual(groups);
});
});
diff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
index b1cf40e29b..19e67cdb06 100644
--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
@@ -412,7 +412,7 @@ export const AssistantMessage = memo(function AssistantMessage({
</div>
{simplifiedBotConversation && !isStreaming && content.trim() && <BotLearningFooter receipts={botLearning} />}
{simplifiedBotConversation && !isStreaming && botTaskResults?.length ? (
- <div className="w-full max-w-[440px] min-w-0 space-y-2" data-bot-task-results>
+ <div className="w-full max-w-[560px] min-w-0" data-bot-task-results>
{botTaskResults.map(card => <BotSessionTaskResultCard key={botTaskResultKey(card)}
data={{ ...card }} sessionId={currentSessionId} attached />)}
</div>
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 34233249b7..0fbb4dad76 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -2729,10 +2729,13 @@ export const WorkGroupRenderItemView = memo(function WorkGroupRenderItemView({
item,
context,
compact,
+ replyColumnSpacer,
}: {
item: Extract<RenderItem, { type: 'work_group' }>;
context: WorkGroupRenderContext;
compact: boolean;
+ /** 伙伴聊天:隐形头像占位,让工作过程与回复正文同列对齐。 */
+ replyColumnSpacer?: ReactNode;
}) {
// 完成态外层时间线可包含内层 work_group。递归只负责形状映射,
// 具体折叠 / 直接详情逻辑全部复用 WorkGroupBlock。
@@ -2768,6 +2771,19 @@ export const WorkGroupRenderItemView = memo(function WorkGroupRenderItemView({
};
};
const childItems = item.children.map(toWorkGroupChild);
+ const block = (
+ <WorkGroupBlock
+ // 单层前缀约定 `work:<clientId>` — item.key 形如 `work-<cid>`,
+ // 去掉 `work-` 后拼 `<role>:<id>`,与 agent: / thinking: 同构。
+ blockId={`work:${item.key.slice('work-'.length)}`}
+ durationMs={item.durationMs}
+ isStreaming={item.isStreaming}
+ startedAtMs={item.startedAtMs}
+ childItems={childItems}
+ compact={compact}
+ deferred={item.deferred}
+ />
+ );
return (
// data-message-client-ids:组折叠时子卡片/聚合块整体 unmount,
// 精确锚点消失 —— 后台任务面板「点行跳聊天」经 ~= 回退查询
@@ -2779,17 +2795,7 @@ export const WorkGroupRenderItemView = memo(function WorkGroupRenderItemView({
className="scroll-mt-20"
data-message-client-ids={collectWorkGroupClientIds(item.children).join(' ')}
>
- <WorkGroupBlock
- // 单层前缀约定 `work:<clientId>` — item.key 形如 `work-<cid>`,
- // 去掉 `work-` 后拼 `<role>:<id>`,与 agent: / thinking: 同构。
- blockId={`work:${item.key.slice('work-'.length)}`}
- durationMs={item.durationMs}
- isStreaming={item.isStreaming}
- startedAtMs={item.startedAtMs}
- childItems={childItems}
- compact={compact}
- deferred={item.deferred}
- />
+ {replyColumnSpacer ? withAssistantAvatar(replyColumnSpacer, block) : block}
</div>
);
});
@@ -6136,6 +6142,17 @@ export function MessageStream({
previousLocalFileRefsRef.current = localFileRefs;
}, [localFileRefs]);
+ // 伙伴聊天的工作过程与回复正文同列:只占头像宽度,不重复画脸。memo 住以保持
+ // WorkGroupRenderItemView 的 memo 比较成立。
+ const botReplyColumnSpacer = useMemo(
+ () =>
+ simplifiedBotConversation && assistantAvatar ? (
+ <span aria-hidden="true" className="invisible">
+ {assistantAvatar}
+ </span>
+ ) : undefined,
+ [assistantAvatar, simplifiedBotConversation],
+ );
const workGroupRenderContext = useMemo<WorkGroupRenderContext>(
() => ({
workingDir,
@@ -6455,7 +6472,10 @@ export function MessageStream({
key={item.key}
item={item}
context={workGroupRenderContext}
- compact={simplifiedBotConversation}
+ // 伙伴聊天与普通任务同一套工作过程:运行中露最近 5 条活动与计时,
+ // 完成后收成「已工作 Xs」,不另走 compact 分支。
+ compact={false}
+ replyColumnSpacer={botReplyColumnSpacer}
/>
);
}
@@ -6877,7 +6897,10 @@ const MessageItem = memo(function MessageItem({
workingDir={workingDir}
/>
);
- return simplifiedBotConversation && (message.systemCardType === 'bot-session-task' || message.systemCardType === 'bot-session-task-result')
+ return simplifiedBotConversation && (message.systemCardType === 'bot-session-task'
+ || message.systemCardType === 'bot-session-task-result'
+ || message.systemCardType === 'bot-session-task-message'
+ || message.systemCardType === 'bot-direct-message')
? withAssistantAvatar(
assistantAvatar ? (
<span aria-hidden="true" className="invisible">
diff --git a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx
index 0547633b91..460bc7fbd7 100644
--- a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx
@@ -1,8 +1,39 @@
-import { Megaphone } from 'lucide-react';
+import { useEffect, useId, useState, type ReactNode } from 'react';
+import {
+ ChevronDown,
+ ChevronUp,
+ Eye,
+ FileText,
+ GitPullRequest,
+ Megaphone,
+ Square,
+ SquareArrowOutUpRight,
+ TriangleAlert,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
+
+import { MAX_STATUS_QUERIES, prStatusKey, sessionPrUrl } from '@cindy/maker-shared';
+import { useElementVisible } from '@/cindy-brain/ghostUnreadStore';
+import {
+ ChatSessionFileProvider,
+ useChatSessionFile,
+} from '@/components/chat/ChatSessionFileContext';
+import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
+import { Spinner } from '@/components/ui/spinner';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { usePrActions, usePrRefsForSession, usePrStatuses } from '@/contexts/PrRefsContext';
+import { PR_STATUS_COLOR, PR_STATUS_ICON } from '@/features/cc-agent/gitContextPrVisuals';
+import { makerChatStore } from '@/lib/makerChatStore';
+import { makerApiForSticky } from '@/lib/makerTransport';
+import * as sessionService from '@/lib/sessionService';
+import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
+import { readWorkingPhase, WORKING_PHASE_KEYS } from '../../../shared/workingStatus';
import type { BotCollaborationMeta } from '../../../shared/botCollaboration';
import { readBotCollaborationMeta } from '../../../shared/botCollaboration';
-import { BotSessionTaskLink } from './BotSessionTaskLink';
+import { isActiveDelegationStatus } from './botDelegationLive';
+import { useBotTaskSession } from './BotSessionTaskLink';
+import { useRemoteBots } from './useRemoteBots';
/**
* 「用时」是说给人听的,不是给日志看的:中文界面里 `8s` 和「用时」并排是两套语言。
@@ -45,13 +76,11 @@ interface Props {
sessionId?: string;
}
-/**
- * 伙伴历史位置保留原 session 的轻链接;操作与执行状态仍属于原任务。
- */
+/** The one card for a background task, in the reply column; state changes in place. */
export function BotSessionTaskCard({ data, sessionId }: Props) {
const parsed = readBotCollaborationCardData(data);
if (!parsed || parsed.meta.role !== 'delegation-request') return null;
- return <BotSessionTaskLink card={parsed.meta} sessionId={sessionId} />;
+ return <BotTaskCard card={parsed.meta} sessionId={sessionId} />;
}
/** A quiet persisted trace for a message added to an already-running task. */
@@ -59,12 +88,475 @@ export function BotSessionTaskMessageTrace({ data }: Pick<Props, 'data'>) {
const parsed = readBotCollaborationCardData(data);
const { t } = useTranslation();
if (!parsed || parsed.meta.role !== 'interjection') return null;
+ const preview = parsed.meta.interjectionPreview;
return (
<div className="my-1.5 flex items-start gap-2 text-12 leading-relaxed text-[var(--text-tertiary)]">
<Megaphone size={13} className="mt-[3px] shrink-0" aria-hidden="true" />
- <span className="min-w-0">
- {t('bots.collab.messageSent')}
+ <span className="min-w-0 break-words">
+ {/* Old traces carry no text; they keep the generic copy. */}
+ {preview ? t('bots.collab.messageSentWithText', { text: preview }) : t('bots.collab.messageSent')}
+ </span>
+ </div>
+ );
+}
+
+type CardState = 'starting' | 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled' | 'unknown';
+
+const HARNESS_LABEL: Record<string, string> = { cc: 'Claude Code', codex: 'Codex', pi: 'Pi' };
+
+function Chip({
+ children,
+ onClick,
+ tone = 'default',
+ disabled,
+ expanded,
+ controls,
+}: {
+ children: ReactNode;
+ onClick: () => void;
+ tone?: 'default' | 'danger';
+ disabled?: boolean;
+ expanded?: boolean;
+ controls?: string;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={disabled}
+ aria-expanded={expanded}
+ aria-controls={controls}
+ className={cn(
+ 'inline-flex h-6 max-w-full shrink-0 items-center gap-1 rounded-full bg-[var(--surface-chip)] px-2.5 text-11 transition-colors',
+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus-ring)] disabled:cursor-default disabled:opacity-50',
+ tone === 'danger'
+ ? 'text-[var(--error-fg)]'
+ : 'text-[var(--text-secondary)] enabled:hover:text-[var(--text-primary)]',
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+function StatusGlyph({ state }: { state: CardState }) {
+ if (state === 'starting' || state === 'running') {
+ return <Spinner size={12} className="shrink-0 text-[var(--status-bar-accent)]" aria-hidden="true" />;
+ }
+ return (
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'size-[7px] shrink-0 rounded-full',
+ state === 'waiting' && 'bg-[var(--status-info)]',
+ state === 'completed' && 'bg-[var(--status-success)]',
+ state === 'failed' && 'bg-[var(--error-fg)]',
+ (state === 'cancelled' || state === 'unknown') && 'bg-[var(--text-tertiary)]',
+ )}
+ />
+ );
+}
+
+/** Local bot chats only: the owner adds a line to the original task like typing in it. */
+async function sendToTask(childSessionId: string, text: string): Promise<boolean> {
+ const owner = getDataOwnerGeneration();
+ const row = await sessionService.get(childSessionId);
+ if (!isDataOwnerGenerationCurrent(owner) || !row?.workingDir) return false;
+ return makerChatStore.sendMessage(
+ childSessionId, text, row.model, row.effort, row.permissionMode, row.workingDir,
+ );
+}
+
+/**
+ * Background task card. A `delegation-request` anchor follows the live task row;
+ * a `delegation-result` receipt keeps its frozen status, text, files and error,
+ * reading only the title and PR links from the original task. `attached` is the
+ * receipt under the bot's closing reply: its result starts open.
+ */
+export function BotTaskCard({
+ card,
+ sessionId,
+ attached = false,
+}: {
+ card: BotCollaborationMeta;
+ sessionId?: string;
+ attached?: boolean;
+}) {
+ const { t } = useTranslation();
+ const fileContext = useChatSessionFile();
+ const ref = useBotTaskSession(card, sessionId);
+ const { row, session, activity } = ref;
+ const frozen = card.role === 'delegation-result' ? card.result : undefined;
+ const parentSessionId = sessionId ?? card.parentSessionId ?? null;
+ const childSessionId = ref.targetId;
+ const remoteBots = useRemoteBots();
+ const online =
+ !ref.sourceDeviceId || remoteBots.some((bot) => bot.deviceId === ref.sourceDeviceId && bot.online);
+ const [resultOpen, setResultOpen] = useState(attached);
+ const [noteOpen, setNoteOpen] = useState(false);
+ const [note, setNote] = useState('');
+ const [pending, setPending] = useState(false);
+ const [actionError, setActionError] = useState<string | null>(null);
+ const [now, setNow] = useState(() => Date.now());
+ const resultId = useId();
+
+ const state: CardState = frozen
+ ? frozen.status === 'completed'
+ ? 'completed'
+ : frozen.status === 'cancelled'
+ ? 'cancelled'
+ : 'failed'
+ : row?.status === 'waiting'
+ ? 'waiting'
+ : ref.running || row?.status === 'running'
+ ? 'running'
+ : !row
+ ? ref.resolved ? 'unknown' : 'starting'
+ : row.status === 'queued'
+ ? 'starting'
+ : row.status === 'completed'
+ ? 'completed'
+ : row.status === 'failed' || row.status === 'timed-out'
+ ? 'failed'
+ : row.status === 'cancelled'
+ ? 'cancelled'
+ : 'unknown';
+ const live = state === 'starting' || state === 'running' || state === 'waiting';
+ const active = !frozen && Boolean(row && isActiveDelegationStatus(row.status));
+ const statusLabel = frozen
+ ? t(`bots.collab.status.${frozen.status}`)
+ : state === 'unknown'
+ ? t('bots.collab.status.unknown')
+ : state === 'starting'
+ ? t('bots.collab.status.queued')
+ : t(`bots.collab.status.${state === 'failed' && row ? row.status : state}`);
+
+ // 只在还在干活时起秒级 tick,收拢后不再空转。
+ useEffect(() => {
+ if (!live || frozen) return;
+ setNow(Date.now());
+ const timer = setInterval(() => setNow(Date.now()), 1_000);
+ return () => clearInterval(timer);
+ }, [live, frozen]);
+
+ const { ref: observeCard, visible } = useElementVisible();
+ const { registerPrConsumer, invalidateRemotePrRefs } = usePrActions();
+ const pullRequests = usePrRefsForSession(childSessionId ?? '').slice(0, MAX_STATUS_QUERIES);
+ const { statuses, successfulStatuses, refreshError } = usePrStatuses(childSessionId ?? '');
+ useEffect(() => {
+ if (!visible || !childSessionId) return;
+ return registerPrConsumer(childSessionId, ref.sourceDeviceId);
+ }, [visible, childSessionId, ref.sourceDeviceId, registerPrConsumer]);
+ useEffect(() => {
+ if (visible && childSessionId && ref.sourceDeviceId && row?.updatedAt !== undefined) {
+ invalidateRemotePrRefs(childSessionId);
+ }
+ }, [visible, childSessionId, ref.sourceDeviceId, row?.updatedAt, invalidateRemotePrRefs]);
+
+ const title =
+ (frozen?.title?.trim() ||
+ (frozen ? row?.title?.trim() || session?.title : session?.title || row?.title) ||
+ card.objective.trim().split('\n')[0] ||
+ t('bots.collab.backgroundTask'));
+ const harness = session ? HARNESS_LABEL[session.agentKind] : undefined;
+ const startedAt = row ? (row.acceptedAt ?? row.createdAt) : null;
+ const elapsed =
+ !frozen && live && startedAt !== null ? formatBotCollaborationDuration(t, startedAt, now) : null;
+ const took =
+ !frozen && !live && row && row.completedAt !== null
+ ? formatBotCollaborationDuration(t, row.createdAt, row.completedAt)
+ : null;
+ const phase = readWorkingPhase(activity?.workingPhase);
+ const currentAction =
+ activity?.compactDetail?.trim() || t(WORKING_PHASE_KEYS[phase ?? 'processing']);
+ const resultText = frozen ? frozen.text : (row?.resultSummary ?? '');
+ const errorText = frozen ? frozen.error : row?.lastError?.replace(/^[A-Z_]+:\s*/, '') || undefined;
+ const files: string[] = frozen
+ ? frozen.artifacts.map((file) => file.absolutePath)
+ : (row?.artifacts ?? []).flatMap((file) => (file.absolutePath ? [file.absolutePath] : []));
+ // Older remote hosts may omit the list; never let a missing field break the card.
+ const fileCount = frozen ? frozen.artifacts.length : (row?.artifacts?.length ?? 0);
+ const workingDir = frozen?.workingDir ?? fileContext.workingDir;
+ const canOpen = Boolean(childSessionId) && !ref.originConflict;
+ const canAddNote = state === 'running' && Boolean(childSessionId) && !ref.sourceDeviceId && !frozen;
+ const resultLabel =
+ state === 'completed'
+ ? t(resultOpen ? 'bots.collab.collapseResult' : 'bots.collab.expandResult')
+ : t(resultOpen ? 'bots.collab.collapseDetails' : 'bots.collab.expandDetails');
+ const hasResultBody = Boolean(frozen) || state === 'completed' || state === 'failed' || state === 'cancelled';
+
+ const stop = async () => {
+ if (!parentSessionId || pending || !online) return;
+ setPending(true);
+ setActionError(null);
+ try {
+ const result = await makerApiForSticky(parentSessionId).cancelBotDelegation(
+ parentSessionId,
+ card.delegationId,
+ );
+ if (!result.ok) setActionError(result.message || t('bots.collab.actionFailed'));
+ } catch {
+ setActionError(t('bots.collab.actionFailed'));
+ } finally {
+ setPending(false);
+ }
+ };
+ const submitNote = async () => {
+ const text = note.trim();
+ if (!text || !childSessionId || pending) return;
+ setPending(true);
+ setActionError(null);
+ try {
+ if (await sendToTask(childSessionId, text)) {
+ setNote('');
+ setNoteOpen(false);
+ toast.success(t('bots.collab.addNoteSent'));
+ } else {
+ setActionError(t('bots.collab.actionFailed'));
+ }
+ } catch {
+ setActionError(t('bots.collab.actionFailed'));
+ } finally {
+ setPending(false);
+ }
+ };
+ const openPr = (url: string) => {
+ setActionError(null);
+ void window.electronAPI
+ .openExternal(url)
+ .then((result) => {
+ if (!result.success) setActionError(t('bots.collab.actionFailed'));
+ })
+ .catch(() => setActionError(t('bots.collab.actionFailed')));
+ };
+
+ const meta = [
+ t('bots.collab.backgroundTask'),
+ harness,
+ took ? t('bots.collab.tookTime', { duration: took }) : null,
+ ].filter(Boolean).join(' · ');
+
+ let line2: ReactNode = null;
+ if (state === 'running' || state === 'starting') {
+ line2 = (
+ <>
+ <span className="min-w-0 truncate text-[var(--status-bar-accent)]">
+ {state === 'starting' ? t('bots.collab.status.queued') : currentAction}
+ </span>
+ {elapsed ? (
+ <span className="shrink-0 tabular-nums text-[var(--text-tertiary)]">
+ · {t('bots.collab.elapsed', { duration: elapsed })}
+ </span>
+ ) : null}
+ </>
+ );
+ } else if (state === 'waiting') {
+ const summary = row?.pendingInteraction?.summary?.trim();
+ line2 = (
+ <span className="min-w-0 line-clamp-2 break-words">
+ {summary
+ ? t('bots.collab.awaitingConfirm', { summary })
+ : t('bots.collab.awaitingConfirmGeneric')}
+ </span>
+ );
+ } else if (state === 'completed' && resultText.trim() && !resultOpen) {
+ line2 = (
+ <span className="min-w-0 line-clamp-2 whitespace-pre-wrap break-words text-13 leading-[1.6] text-[var(--text-primary)]">
+ {resultText.trim()}
</span>
+ );
+ } else if (state === 'failed' && errorText && !resultOpen) {
+ line2 = <span className="min-w-0 truncate text-[var(--error-fg)]">{errorText}</span>;
+ }
+
+ const prIcon = (pr: (typeof pullRequests)[number]) => {
+ const result = statuses.get(prStatusKey(pr));
+ const confirmed = result?.ok ? result : successfulStatuses.get(prStatusKey(pr));
+ const kind = confirmed?.ok ? confirmed.status : undefined;
+ const Icon = kind ? PR_STATUS_ICON[kind] : GitPullRequest;
+ return (
+ <Icon
+ size={12}
+ aria-hidden="true"
+ style={{ color: kind ? PR_STATUS_COLOR[kind] : 'var(--text-tertiary)' }}
+ />
+ );
+ };
+ const stale =
+ (ref.stale ||
+ refreshError ||
+ !online ||
+ pullRequests.some((pr) => statuses.get(prStatusKey(pr))?.ok === false)) &&
+ Boolean(row);
+
+ return (
+ <div
+ ref={observeCard}
+ data-bot-task-card={state}
+ className="my-2 w-full min-w-0 max-w-[560px] rounded-xl border border-[var(--msg-tool-card-border)] bg-[var(--msg-tool-card-bg)] px-3 py-2.5"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <StatusGlyph state={state} />
+ <span className="sr-only">{statusLabel}</span>
+ <button
+ type="button"
+ disabled={!canOpen}
+ onClick={ref.open}
+ title={statusLabel}
+ className="min-w-0 flex-1 truncate text-left text-13 font-medium text-[var(--text-primary)] underline-offset-[3px] enabled:hover:underline disabled:cursor-default"
+ >
+ {title}
+ </button>
+ <span className="shrink-0 text-11 text-[var(--text-tertiary)]">{meta}</span>
+ </div>
+ {line2 ? (
+ <div className="mt-1 flex min-w-0 items-center gap-1.5 text-12 text-[var(--text-secondary)]">
+ {line2}
+ </div>
+ ) : null}
+ {stale ? (
+ <p className="mt-1 flex items-center gap-1.5 text-12 text-[var(--text-tertiary)]">
+ <TriangleAlert size={12} aria-hidden="true" />
+ {t('bots.collab.stale')}
+ </p>
+ ) : null}
+ {noteOpen ? (
+ <form
+ className="mt-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submitNote();
+ }}
+ >
+ <input
+ autoFocus
+ value={note}
+ disabled={pending}
+ onChange={(event) => setNote(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ setNoteOpen(false);
+ }
+ }}
+ aria-label={t('bots.collab.addNote')}
+ placeholder={t('bots.collab.addNotePlaceholder')}
+ className="h-8 w-full rounded-full border border-[var(--border-default)] bg-[var(--surface)] px-3 text-12 text-[var(--text-primary)] placeholder:text-[var(--text-tertiary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus-ring)]"
+ />
+ </form>
+ ) : null}
+ {resultOpen && hasResultBody ? (
+ <div
+ id={resultId}
+ className="mt-2 space-y-2 border-t border-[var(--border-default)] pt-2 text-13 text-[var(--text-primary)]"
+ >
+ <ChatSessionFileProvider
+ value={{ ...fileContext, workingDir, sessionId: childSessionId ?? undefined }}
+ >
+ {resultText ? (
+ <MarkdownRenderer
+ workingDir={workingDir}
+ currentSessionId={childSessionId ?? undefined}
+ content={resultText}
+ />
+ ) : (
+ <p className="whitespace-pre-wrap break-words text-[var(--text-secondary)]">
+ {t('bots.collab.noWrittenResult')}
+ </p>
+ )}
+ {files.map((path) => (
+ <MarkdownRenderer
+ key={path}
+ workingDir={workingDir}
+ currentSessionId={childSessionId ?? undefined}
+ content={`[${
+ path
+ .split(/[\\/]/)
+ .pop()
+ ?.replace(/[[\]\\]/g, '\\$&') ?? t('bots.collab.viewResult')
+ }](<${encodeURI(path).replace(/[<>?#]/g, encodeURIComponent)}>)`}
+ />
+ ))}
+ </ChatSessionFileProvider>
+ {errorText ? (
+ <details>
+ <summary className="flex min-h-8 cursor-pointer items-center rounded-lg text-12 text-[var(--text-secondary)] focus-visible:outline focus-visible:outline-2">
+ {t('appError.details')}
+ </summary>
+ <p className="whitespace-pre-wrap break-words text-12 text-[var(--text-secondary)]">
+ {errorText}
+ </p>
+ </details>
+ ) : null}
+ </div>
+ ) : null}
+ <div className="mt-2 flex min-w-0 flex-wrap items-center gap-1.5">
+ {state === 'waiting' && canOpen ? (
+ <Chip onClick={ref.open}>
+ <Eye size={12} aria-hidden="true" />
+ {t('bots.collab.lookAt')}
+ </Chip>
+ ) : null}
+ {(state === 'running' || state === 'starting') && canOpen ? (
+ <Chip onClick={ref.open}>
+ <SquareArrowOutUpRight size={12} aria-hidden="true" />
+ {t('bots.collab.watchWork')}
+ </Chip>
+ ) : null}
+ {canAddNote ? (
+ <Chip onClick={() => setNoteOpen((open) => !open)} expanded={noteOpen} disabled={pending}>
+ <Megaphone size={12} aria-hidden="true" />
+ {t('bots.collab.addNote')}
+ </Chip>
+ ) : null}
+ {!live && fileCount > 0 ? (
+ <Chip onClick={() => setResultOpen(true)} controls={resultId}>
+ <FileText size={12} aria-hidden="true" />
+ {t('bots.collab.artifactCount', { count: fileCount })}
+ </Chip>
+ ) : null}
+ {pullRequests.map((pr) => (
+ <Chip key={pr.url} onClick={() => openPr(sessionPrUrl(pr))}>
+ {prIcon(pr)}
+ <span className="truncate" title={`${pr.owner}/${pr.repo} #${pr.prNumber}`}>
+ PR #{pr.prNumber}
+ </span>
+ </Chip>
+ ))}
+ <span className="ml-auto flex shrink-0 items-center gap-1">
+ {!live && hasResultBody ? (
+ <Chip
+ onClick={() => setResultOpen((open) => !open)}
+ expanded={resultOpen}
+ controls={resultId}
+ >
+ {resultOpen ? <ChevronUp size={12} aria-hidden="true" /> : <ChevronDown size={12} aria-hidden="true" />}
+ {resultLabel}
+ </Chip>
+ ) : null}
+ {!live && canOpen ? (
+ <Chip onClick={ref.open}>
+ <SquareArrowOutUpRight size={12} aria-hidden="true" />
+ {t('bots.collab.watchWork')}
+ </Chip>
+ ) : null}
+ {active ? (
+ <Chip
+ tone="danger"
+ disabled={pending || !parentSessionId || !online}
+ onClick={() => void stop()}
+ >
+ <Square size={12} aria-hidden="true" />
+ {t('bots.collab.stop')}
+ </Chip>
+ ) : null}
+ </span>
+ </div>
+ {actionError ? (
+ <p role="alert" className="mt-1.5 text-11 text-[var(--error-fg)]">
+ {actionError}
+ </p>
+ ) : null}
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx b/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx
index 633ce7c15d..091750edab 100644
--- a/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx
@@ -1,13 +1,22 @@
-import { useMemo, useState } from 'react';
-import { ArrowLeftRight, ChevronRight } from 'lucide-react';
+import { useEffect, useId, useRef, useState } from 'react';
+import { ArrowLeftRight, ChevronDown, ChevronUp, SquareArrowOutUpRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate } from 'react-router-dom';
+import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
+import { Spinner } from '@/components/ui/spinner';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { makerApiForDevice } from '@/lib/makerTransport';
import { cn } from '@/lib/utils';
-import { readBotDirectMessageMeta, type BotDirectMessageMeta } from '../../../shared/botDirectMessage';
+import {
+ readBotDirectMessageMeta,
+ type BotDirectMessageMeta,
+ type BotDirectMessageThreadView,
+} from '../../../shared/botDirectMessage';
import { BotAvatar } from './BotAvatar';
import { useBotProfiles } from './botStore';
+import { formatBotMessageGroupTime } from './botConversationTimeline';
export function BotDirectMessageCard({ data, sessionId }: { data?: Record<string, unknown>; sessionId?: string }) {
const meta = readBotDirectMessageMeta(data);
@@ -15,58 +24,151 @@ export function BotDirectMessageCard({ data, sessionId }: { data?: Record<string
return <BotDirectMessageCardBody meta={meta} sessionId={sessionId} />;
}
+type ThreadState =
+ | { kind: 'idle' }
+ | { kind: 'loading' }
+ | { kind: 'ready'; thread: BotDirectMessageThreadView }
+ | { kind: 'unavailable' };
+
+const chipClass = cn(
+ 'inline-flex h-6 max-w-full shrink-0 items-center gap-1 rounded-full bg-[var(--surface-chip)] px-2.5 text-11',
+ 'text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)]',
+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus-ring)]',
+);
+
+/**
+ * A teammate message trace in the reply column: who, an excerpt, and the
+ * exchange inline on demand. It never adds unread state or a left-list entry.
+ */
function BotDirectMessageCardBody({ meta, sessionId }: { meta: BotDirectMessageMeta; sessionId?: string }) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const allProfiles = useBotProfiles();
const [deviceId] = useState(() => sessionId ? remoteProjectsStore.getSessionDeviceId(sessionId) : null);
const profiles = deviceId ? [] : allProfiles;
+ const [open, setOpen] = useState(false);
+ const [thread, setThread] = useState<ThreadState>({ kind: 'idle' });
+ const threadId = useId();
+ const alive = useRef(true);
+ useEffect(() => {
+ alive.current = true;
+ return () => {
+ alive.current = false;
+ };
+ }, []);
- const peer = useMemo(() => {
- const profile = profiles.find((item) => item.id === meta.peerBotId);
+ const profileFor = (id: string, fallbackName: string) => {
+ const profile = profiles.find((item) => item.id === id);
return {
- name: profile?.name || meta.peerBotName || meta.peerBotId,
+ name: profile?.name || fallbackName || id,
avatar: profile?.avatar ?? null,
avatarColor: profile?.avatarColor ?? null,
};
- }, [meta.peerBotId, meta.peerBotName, profiles]);
+ };
+ const peer = profileFor(meta.peerBotId, meta.peerBotName);
const label = t(
- meta.direction === 'sent'
- ? 'bots.directMessage.sentTo'
- : 'bots.directMessage.receivedFrom',
+ meta.direction === 'sent' ? 'bots.directMessage.sentHeader' : 'bots.directMessage.receivedHeader',
{ name: peer.name },
);
+ const load = async () => {
+ const owner = getDataOwnerGeneration();
+ setThread({ kind: 'loading' });
+ try {
+ const result = await (deviceId ? makerApiForDevice(deviceId) : window.electronAPI.maker)
+ .getBotDirectMessageThread(meta.threadId, meta.viewerBotId);
+ if (!alive.current || !isDataOwnerGenerationCurrent(owner)) return;
+ setThread(result.ok ? { kind: 'ready', thread: result.thread } : { kind: 'unavailable' });
+ } catch {
+ if (alive.current && isDataOwnerGenerationCurrent(owner)) setThread({ kind: 'unavailable' });
+ }
+ };
+ const toggle = () => {
+ const next = !open;
+ setOpen(next);
+ // Each expansion reads the latest exchange; collapsing keeps the last copy.
+ if (next && thread.kind !== 'loading') void load();
+ };
+ const openFull = () =>
+ navigate(
+ `/bots/${encodeURIComponent(meta.viewerBotId)}/direct/${encodeURIComponent(meta.threadId)}${deviceId ? `?deviceId=${encodeURIComponent(deviceId)}` : ''}`,
+ { state: { botDirectMessageReturnTo: `${location.pathname}${location.search}` } },
+ );
+ const loaded = thread.kind === 'ready' ? thread.thread : null;
+ const toggleLabel = loaded
+ ? `${t('bots.directMessage.exchangeCountShort', { count: loaded.messages.length })} · ${t(
+ open ? 'bots.directMessage.collapse' : 'bots.directMessage.expand',
+ )}`
+ : t(open ? 'bots.directMessage.collapse' : 'bots.directMessage.expandThread');
+
return (
- <div className="flex w-full select-none items-center gap-3 py-2" role="separator">
- <div className="h-px flex-1 bg-[var(--msg-tool-card-border)]" />
- <button
- type="button"
- onClick={() =>
- navigate(
- `/bots/${encodeURIComponent(meta.viewerBotId)}/direct/${encodeURIComponent(meta.threadId)}${deviceId ? `?deviceId=${encodeURIComponent(deviceId)}` : ''}`,
- {
- state: {
- botDirectMessageReturnTo: `${location.pathname}${location.search}`,
- },
- },
- )
- }
- className={cn(
- 'flex min-w-0 max-w-full items-center gap-1.5 rounded-full border',
- 'border-[var(--msg-tool-card-border)] bg-[var(--surface)] px-2.5 py-1',
- 'text-11 text-[var(--text-secondary)] transition-colors',
- 'hover:bg-[var(--msg-tool-card-bg)] hover:text-[var(--text-primary)]',
- )}
- title={t('bots.directMessage.open')}
- >
+ <div
+ data-bot-direct-message={meta.direction}
+ className="my-2 w-full min-w-0 max-w-[560px] rounded-xl border border-[var(--msg-tool-card-border)] bg-[var(--msg-tool-card-bg)] px-3 py-2.5"
+ >
+ <div className="flex min-w-0 items-center gap-2">
<BotAvatar bot={peer} size="xs" />
- <ArrowLeftRight size={12} className="shrink-0 text-[var(--text-tertiary)]" aria-hidden />
- <span className="truncate">{label}</span>
- <ChevronRight size={12} className="shrink-0 text-[var(--text-tertiary)]" aria-hidden />
- </button>
- <div className="h-px flex-1 bg-[var(--msg-tool-card-border)]" />
+ <span className="min-w-0 flex-1 truncate text-13 font-medium text-[var(--text-primary)]">{label}</span>
+ </div>
+ {meta.preview.trim() ? (
+ <p className="mt-1.5 line-clamp-2 whitespace-pre-wrap break-words rounded-lg border-l-2 border-[var(--msg-blockquote-border)] bg-[var(--surface-chip)] px-2.5 py-1.5 text-13 leading-[1.6] text-[var(--text-primary)]">
+ {meta.preview.trim()}
+ </p>
+ ) : null}
+ <div className="mt-2 flex min-w-0 flex-wrap items-center gap-1.5">
+ <button type="button" className={chipClass} aria-expanded={open} aria-controls={threadId} onClick={toggle}>
+ <ArrowLeftRight size={12} aria-hidden="true" />
+ {toggleLabel}
+ {open ? <ChevronUp size={12} aria-hidden="true" /> : <ChevronDown size={12} aria-hidden="true" />}
+ </button>
+ <span className="ml-auto flex shrink-0 items-center gap-1">
+ <button type="button" className={chipClass} onClick={openFull} title={t('bots.directMessage.open')}>
+ <SquareArrowOutUpRight size={12} aria-hidden="true" />
+ {t('bots.directMessage.fullThread')}
+ </button>
+ </span>
+ </div>
+ {open ? (
+ <div id={threadId} className="mt-2 border-t border-[var(--border-default)] pt-2">
+ {thread.kind === 'loading' && !loaded ? (
+ <div className="flex justify-center py-2">
+ <Spinner size={14} className="text-[var(--text-tertiary)]" />
+ </div>
+ ) : null}
+ {thread.kind === 'unavailable' ? (
+ <p className="py-1 text-12 text-[var(--text-tertiary)]">{t('bots.directMessage.unavailable')}</p>
+ ) : null}
+ {loaded ? (
+ <div className="flex flex-col gap-2.5">
+ {loaded.messages.map((message) => {
+ const sender = profileFor(message.senderBotId, message.senderBotName);
+ return (
+ <article key={message.id} className="flex min-w-0 items-start gap-2">
+ <BotAvatar bot={sender} size="xs" />
+ <div className="min-w-0 flex-1">
+ <div className="text-11 text-[var(--text-tertiary)]">
+ {sender.name} · {formatBotMessageGroupTime(message.createdAt, i18n.language)}
+ </div>
+ <div className="min-w-0 break-words text-13 text-[var(--text-primary)]">
+ <MarkdownRenderer workingDir="" content={message.content} allowPrivilegedLinks={false} />
+ </div>
+ </div>
+ </article>
+ );
+ })}
+ {loaded.messages.length === 0 ? (
+ <p className="text-12 text-[var(--text-tertiary)]">{t('bots.directMessage.empty')}</p>
+ ) : null}
+ {loaded.status === 'closed' ? (
+ <p className="text-center text-11 text-[var(--text-tertiary)]">
+ {t('bots.directMessage.threadClosed')}
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx b/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx
index 017266ffcb..a10ca0f9fd 100644
--- a/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx
@@ -7,6 +7,7 @@ import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { makerApiForDevice } from '@/lib/makerTransport';
import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
import { Spinner } from '@/components/ui/spinner';
+import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
import {
getDataOwnerGeneration,
isDataOwnerGenerationCurrent,
@@ -171,13 +172,14 @@ export function BotDirectMessageView() {
{sender.name} · {formatBotMessageGroupTime(message.createdAt, i18n.language)}
</div>
<div
- className={`whitespace-pre-wrap break-words rounded-[12px] border px-3.5 py-2.5 text-14 leading-[1.6] text-[var(--text-primary)] ${
+ className={`min-w-0 max-w-full break-words rounded-[12px] border px-3.5 py-2.5 text-14 leading-[1.6] text-[var(--text-primary)] ${
ownSide
? 'border-[var(--msg-user-border)] bg-[var(--msg-user-bg)]'
: 'border-[var(--border-default)] bg-[var(--surface-chip)]'
}`}
>
- {message.content}
+ {/* Teammate-authored text: rendered like chat, never with privileged links. */}
+ <MarkdownRenderer workingDir="" content={message.content} allowPrivilegedLinks={false} />
</div>
</div>
{ownSide ? <BotAvatar bot={sender} size="sm" /> : null}
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index a11644d473..730cc1ad1c 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -1,37 +1,34 @@
-import type { ReactNode } from 'react';
/**
- * 群聊页:顶栏(成员头像、群名、成员名单、群设置入口)+ 多作者时间线 + 输入框。
+ * 群聊页:顶栏(成员头像、群名、成员与负责人、此刻谁在做什么、群设置入口)+ 多作者时间线 +
+ * 进行中条 + 输入框。
*
- * 数据全部来自 main(docs/product-rules/bot-group-chat.md §3):进入时读一页最新消息,
- * 之后每条 `onBotGroupChanged` 推送(含分工的 `'plan'`)都整页重读,renderer 不自己拼
- * 时间线。加载沿用 BotDirectMessageView 的新鲜度护栏:请求代次 + data owner 代次 + 推送
- * owner 戳,过期响应一律丢弃。更早的消息按需翻页,连同其引用的安排合并进当前时间线。
+ * 数据全部来自 main(docs/product-rules/bot-group-chat.md §3):进入时读一页最新消息,之后每条
+ * `onBotGroupChanged` 推送(含分工的 `'plan'`)都重读最新一页。读取同一时刻只有一个在飞,期间
+ * 来的推送合并成一次补读——一阵推送也会边到边显示,较新的结果从不被丢掉。新的一页**并入**
+ * 屏幕上已有的消息(BotGroupTimelineModel.ts):被新消息挤出最新页的旧消息留着,不出缺口、
+ * 不跳;内容没变的消息沿用原对象,memo 过的消息行不重绘。账号(data owner)代次照旧作废
+ * 迟到的回包。更早的消息按需翻页,连同其引用的安排合并进当前时间线。
*
- * 分工(§7):安排卡、交接文件与「下一步 · 继续」「没做完 · 重试」见 BotGroupPlan.tsx;
- * 这里只负责把安排快照接到对应消息上,并调用 main 的安排操作。
+ * 发送是乐观的:按下发送,自己的消息立刻出现在末尾(发送中略淡),main 的详情里出现这条消息
+ * 后原地换成正式那条(同一个 React key,不闪不跳);失败就撤掉、草稿放回。
+ *
+ * 分工(§7):安排卡、交接文件与「下一步 · 继续」「没做完 · 重试」见 BotGroupPlan.tsx;进行中
+ * 条、发言行与顶栏状态见 BotGroupLiveStatus.tsx;这里把安排快照接到对应消息上并调用 main。
*
* 引用回复(§10):页面持有本群的待发引用(随群切换整页重建,不会串群);已发消息上的
* 引用块以已加载的原消息为准,点击跳到原消息并高亮,原消息不在已加载范围时向前翻几页找。
*
* 附件(§3.1):托盘状态(`useAttachments`)由页面持有,文件拖到页面任意位置都进托盘,
- * 与普通任务的整区拖入一致;用户消息上的图片与文件复用普通聊天用户气泡的图片视图与
- * 附件 chip。
+ * 与普通任务的整区拖入一致;消息上的图片与文件复用普通聊天用户气泡的图片视图与附件 chip。
*/
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type DragEvent } from 'react';
-import { ArrowLeft, CircleAlert, RefreshCcw, Settings2, Sparkles } from 'lucide-react';
+import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type DragEvent } from 'react';
+import { ArrowLeft, CircleAlert, RefreshCcw, Settings2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { attachGhostMediaToSession, getGhostMediaHandoverFromDataTransfer } from '@/cindy-brain/ghostMediaHandover';
-import { ChatImageView } from '@/components/chat/ChatImageView';
-import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
import { ShareSelectionBar } from '@/components/chat/ShareSelectionBar';
-import { ShareMessageCheckbox } from '@/components/chat/ShareMessageCheckbox';
import { shareSelectionStore, useShareSelectionActive } from '@/components/chat/shareSelectionStore';
-import { SHARE_SESSION_ATTR, SHARE_MESSAGE_ATTR } from '@/lib/shareConversationImage';
-import { TextLightbox } from '@/components/chat/TextLightbox';
-import { UserAttachmentChip } from '@/components/chat/UserAttachmentChip';
-import { CHAT_BODY_CLASS } from '@/components/chat/chatChrome';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
@@ -50,51 +47,58 @@ import {
} from '@/lib/fileDrop';
import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';
import { toast } from '@/lib/toast';
-import { cn } from '@/lib/utils';
import { ControlledBanner, useControlledBy, useComposerCollapsed } from '@/features/remote-device/ControlledBanner';
import { useAgentIslandActivity } from '@/state/agentIslandActivity';
import type {
- BotGroupAttachment,
- BotGroupDetail,
BotGroupMemberView,
BotGroupMessageView,
BotGroupPlanAction,
BotGroupPlanStepView,
- BotGroupPlanView,
BotGroupQuoteDisplay,
BotGroupQuoteView,
- BotGroupSpeakerActivity,
} from '../../../shared/botGroupChat';
import { botGroupQuoteFromMessage, isBotGroupMessageQuotable, resolveBotGroupQuote } from '../../../shared/botGroupChat';
import { useRegisterContentHeader } from '../feature-context';
-import { BotAvatar } from './BotAvatar';
-import { BotGenerationLabel } from './BotGenerationLabel';
import { BotGroupAvatarStack } from './BotGroupAvatars';
-import { botGroupAttachmentScope, splitBotGroupMessageAttachments } from './botGroupAttachments';
-import { BotGroupComposer } from './BotGroupComposer';
-import { BotGroupQuoteBlock } from './BotGroupQuote';
-import { ChatInviteButton, ChatMessageActions } from './ChatServerControls';
+import { botGroupAttachmentScope } from './botGroupAttachments';
+import { BotGroupComposer, type BotGroupOutgoingMessage, type BotGroupSendOutcome } from './BotGroupComposer';
+import {
+ BotGroupHeaderStatusText,
+ BotGroupProgressStrip,
+ BotGroupSpeakerInteraction,
+ BotGroupSpeakingLine,
+ botGroupHeaderStatus,
+ type BotGroupLiveSpeaker,
+} from './BotGroupLiveStatus';
+import { ChatInviteButton } from './ChatServerControls';
import { animateThreadPanelWidth, ChatThreadPanel } from './ChatThreadPanel';
-import { BotGroupPendingInteraction } from './BotGroupPendingInteraction';
-import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';
-import { BotGroupTaskCard } from './BotGroupTaskCard';
-import { isBotGroupRuntimeFailureCode } from '../../../shared/botGroupChat';
import {
- BotGroupHandoffFiles,
BotGroupOrganizerTag,
- BotGroupPlanCard,
- BotGroupPlanEndDivider,
BotGroupPlanFollowUpRow,
type BotGroupFollowUpAction,
type BotGroupPlanCardAction,
} from './BotGroupPlan';
-import { splitBotGroupMentionSegments } from './botGroupMentions';
+import { BotGroupDateDivider, BotGroupTimelineItem } from './BotGroupTimelineItem';
+import {
+ botGroupHandoffStepNumbers,
+ botGroupMemberDisplayName,
+ botGroupOwnedBotNames,
+ layoutBotGroupTimeline,
+ matchBotGroupPendingSends,
+ mergeBotGroupLatestPage,
+ pendingBotGroupMessage,
+ pendingBotGroupMessageId,
+ runningBotGroupPlanStep,
+ stabilizeById,
+ type BotGroupLoadedTimeline,
+ type BotGroupPendingSend,
+ type BotGroupTimelineMessage,
+} from './BotGroupTimelineModel';
import {
BOT_GROUP_SETTINGS_PARAM,
botGroupComposerPlanState,
botGroupErrorKey,
botGroupMemberNames,
- botGroupNoticeKey,
botGroupPlanFollowUp,
continuableRoundEndId,
mergeBotGroupMessages,
@@ -104,19 +108,10 @@ import {
} from './botGroupPresentation';
import { botGroupApi, editBotGroupPlanStep, runBotGroupPlanAction, useBotGroupSummary } from './botGroupStore';
import { botGroupReadKey, markBotRead } from './botReadState';
-import { collectBotMessageTimeGroups, formatBotMessageGroupTime } from './botConversationTimeline';
type GroupViewState =
| { kind: 'loading' }
- | {
- kind: 'ready';
- group: BotGroupDetail;
- /** Pages loaded through 「查看更早的消息」, merged under the latest page. */
- older: BotGroupMessageView[];
- /** Plans referenced by the older pages; the latest read wins on overlap. */
- olderPlans: BotGroupPlanView[];
- olderHasMore: boolean;
- }
+ | ({ kind: 'ready' } & BotGroupLoadedTimeline)
| { kind: 'missing' }
| { kind: 'error' };
@@ -135,6 +130,10 @@ const TIMELINE_LOADING_REVEAL_MS = 200;
/** Older pages read while looking for a quoted message before saying it is out of reach. */
const QUOTE_LOCATE_MAX_PAGES = 5;
const QUOTE_HIGHLIGHT_MS = 2000;
+/** The reader counts as at the bottom within this distance. */
+const STICK_TO_BOTTOM_PX = 48;
+/** Read marks follow scrolling at most this often (leading edge, plus one trailing mark). */
+const ACKNOWLEDGE_THROTTLE_MS = 150;
const NO_IDS: ReadonlySet<string> = new Set();
/**
@@ -146,7 +145,7 @@ function quotedOlderOriginals(
latest: readonly BotGroupMessageView[],
): BotGroupMessageView[] {
const latestIds = new Set(latest.map((message) => message.id));
- const olderById = new Map(older.map((message) => [message.id, message]));
+ const olderById = new Map(older.filter((message) => !latestIds.has(message.id)).map((message) => [message.id, message]));
const ids = new Set([...older, ...latest].flatMap((message) => {
const target = message.quote?.messageId;
return target && !latestIds.has(target) && olderById.has(target) ? [target] : [];
@@ -154,9 +153,18 @@ function quotedOlderOriginals(
return [...ids].map((id) => olderById.get(id)!).sort((a, b) => b.sequence - a.sequence);
}
-/** Stable identity for header memoization; member arrays are new on every read. */
-function memberKey(members: readonly BotGroupMemberView[]): string {
- return JSON.stringify(members.map((member) => [member.botId, member.name, member.avatar, member.avatarColor]));
+/** The previous value while `key` is unchanged (member arrays are new on every read). */
+function useStableByKey<T>(value: T, key: string): T {
+ const ref = useRef<{ key: string; value: T } | null>(null);
+ if (!ref.current || ref.current.key !== key) ref.current = { key, value };
+ return ref.current.value;
+}
+
+/** Same objects for unchanged rows, so memoized rows skip rendering. */
+function useStableRows<T extends { id: string }>(rows: T[]): T[] {
+ const ref = useRef<T[]>(rows);
+ ref.current = stabilizeById(ref.current, rows);
+ return ref.current;
}
/**
@@ -175,6 +183,7 @@ export function BotGroupChatView() {
function BotGroupChatContent({ groupId }: { groupId: string }) {
const { t, i18n } = useTranslation();
+ const locale = i18n.language;
const controlledBy = useControlledBy();
const hasControlledBanner = controlledBy.length > 0;
// Groups have no single task session; namespace their existing composer UI state.
@@ -193,6 +202,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
const [reloadVersion, setReloadVersion] = useState(0);
const [loadingOlder, setLoadingOlder] = useState(false);
const [continuing, setContinuing] = useState(false);
+ const [stopping, setStopping] = useState(false);
const [planPending, setPlanPending] = useState<PlanPending | null>(null);
const planPendingRef = useRef(false);
const loadRef = useRef<(additionalSources?: string[]) => void>(() => {});
@@ -211,44 +221,48 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
const [highlightId, setHighlightId] = useState<string | null>(null);
/** Quoted originals on older pages not re-read since the last push: quotes use their snapshot. */
const [unverifiedOriginals, setUnverifiedOriginals] = useState<ReadonlySet<string>>(NO_IDS);
+ /** Own messages on their way, shown at the end until main's copy arrives. */
+ const [pendingSends, setPendingSends] = useState<BotGroupPendingSend[]>([]);
const loadingOlderRef = useRef(false);
const locatingRef = useRef(false);
useEffect(() => {
let cancelled = false;
- let requestVersion = 0;
- const load = async (additionalSources: string[] = []) => {
- const version = ++requestVersion;
+ /** Bumped when a read starts (and on delete): re-checks spawned by older reads stop. */
+ let version = 0;
+ let inFlight = false;
+ let queued: string[] | null = null;
+ const run = async (additionalSources: string[]) => {
+ inFlight = true;
+ const current = ++version;
const owner = getDataOwnerGeneration();
const api = botGroupApi();
- const isCurrent = () =>
- !cancelled && version === requestVersion && isDataOwnerGenerationCurrent(owner);
- if (!api || !groupId) {
- if (isCurrent()) setState({ kind: groupId ? 'error' : 'missing' });
- return;
- }
+ const isCurrent = () => !cancelled && current === version && isDataOwnerGenerationCurrent(owner);
+ // Reads run one at a time, so a result is never older than what is on screen; only the
+ // account (data owner) or a delete can make it stale.
+ const isApplicable = () => !cancelled && isDataOwnerGenerationCurrent(owner) && current <= version;
try {
+ if (!api || !groupId) {
+ if (isApplicable()) setState({ kind: groupId ? 'error' : 'missing' });
+ return;
+ }
const displayed = stateRef.current;
const sourceMessageIds = [...new Set([...(displayed.kind === 'ready' && displayed.group.id === groupId
? mergeBotGroupMessages(displayed.older, displayed.group.messages).map(message => message.id) : []), ...additionalSources])];
const result = sourceMessageIds.length ? await api.getBotGroup(groupId, { sourceMessageIds }) : await api.getBotGroup(groupId);
- if (!isCurrent()) return;
+ if (!isApplicable()) return;
if (result.ok) {
readOwner.current = owner;
- setState((previous) =>
- previous.kind === 'ready'
- ? { ...previous, group: result.group }
- : {
- kind: 'ready',
- group: result.group,
- older: [],
- olderPlans: [],
- olderHasMore: result.group.hasMoreBefore,
- },
- );
const shown = stateRef.current;
+ setState((previous) => {
+ if (previous.kind !== 'ready') {
+ return { kind: 'ready', group: result.group, older: [], olderPlans: [], olderHasMore: result.group.hasMoreBefore };
+ }
+ const merged = mergeBotGroupLatestPage(previous, result.group);
+ return merged === previous ? previous : { kind: 'ready', ...merged };
+ });
if (shown.kind === 'ready') {
- const targets = quotedOlderOriginals(shown.older, result.group.messages);
+ const targets = quotedOlderOriginals([...shown.older, ...shown.group.messages], result.group.messages);
if (targets.length > 0) void recheckQuotedOriginals(api, targets, isCurrent);
}
} else if (result.errorCode === 'NOT_FOUND') {
@@ -258,8 +272,23 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
setState((previous) => (previous.kind === 'ready' ? previous : { kind: 'error' }));
}
} catch {
- if (isCurrent()) setState((previous) => (previous.kind === 'ready' ? previous : { kind: 'error' }));
+ if (isApplicable()) setState((previous) => (previous.kind === 'ready' ? previous : { kind: 'error' }));
+ } finally {
+ inFlight = false;
+ if (queued && !cancelled) {
+ const next = queued;
+ queued = null;
+ void run(next);
+ }
+ }
+ };
+ /** One read in flight; pushes meanwhile collapse into one follow-up read. */
+ const load = (additionalSources: string[] = []) => {
+ if (inFlight) {
+ queued = [...(queued ?? []), ...additionalSources];
+ return;
}
+ void run(additionalSources);
};
/**
* Re-reads the older pages holding quoted originals after a push and updates only messages
@@ -300,23 +329,25 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
if (covered.length === 0) return;
}
};
- loadRef.current = additionalSources => void load(additionalSources);
- void load();
+ loadRef.current = additionalSources => load(additionalSources);
+ load();
const unsubscribe =
botGroupApi()?.onBotGroupChanged?.((payload, ownerStamp) => {
if (!isDataOwnerPushCurrent(ownerStamp) || payload.groupId !== groupId) return;
if (payload.change === 'deleted') {
- requestVersion += 1;
+ cancelled = true;
+ queued = null;
// Unsent attachments go with the group (staged copies included).
discardDraft(botGroupAttachmentScope(groupId));
setState({ kind: 'missing' });
return;
}
- void load();
+ load();
}) ?? (() => {});
return () => {
cancelled = true;
- requestVersion += 1;
+ queued = null;
+ version += 1;
loadRef.current = () => {};
unsubscribe();
};
@@ -326,27 +357,98 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
// Until the timeline arrives, the header comes from the group's sidebar row (same account).
const listed = useBotGroupSummary(state.kind === 'loading' || state.kind === 'error' ? groupId : null);
const headerGroup = group ?? listed;
- const messages = useMemo(
+ const members = useStableByKey(headerGroup?.members ?? [], JSON.stringify(headerGroup?.members ?? []));
+ const memberById = useMemo(() => new Map(members.map((member) => [member.botId, member])), [members]);
+ const displayName = useCallback((member: BotGroupMemberView) => botGroupMemberDisplayName(member), []);
+ const avatarById = useMemo(() => new Map(members.map((member) => [member.botId, {
+ name: botGroupMemberDisplayName(member), avatar: member.avatar ?? null, avatarUrl: member.avatarUrl, avatarColor: member.avatarColor ?? null,
+ }])), [members]);
+ const allLabel = t('bots.groupChat.mention.all');
+ const mentionLabels = useMemo(
+ () => [allLabel, ...members.flatMap((member) => [member.name, botGroupMemberDisplayName(member), member.nickname || member.displayName || member.name])],
+ [allLabel, members],
+ );
+
+ const realMessages = useMemo(
() => (state.kind === 'ready' ? projectBotGroupExecutionFailures(mergeBotGroupMessages(state.older, state.group.messages), state.group.executionFailures) : []),
[state],
);
+ const pendingMatches = useMemo(() => matchBotGroupPendingSends(pendingSends, realMessages), [pendingSends, realMessages]);
+ /** Real message id → the key its optimistic copy had, so the row is kept, not remounted. */
+ const adoptedKeysRef = useRef(new Map<string, string>());
+ for (const [clientId, messageId] of pendingMatches) adoptedKeysRef.current.set(messageId, pendingBotGroupMessageId(clientId));
+ useEffect(() => {
+ if (pendingMatches.size === 0) return;
+ setPendingSends((previous) => previous.filter((send) => !pendingMatches.has(send.clientId)));
+ }, [pendingMatches]);
+ const rows = useStableRows(useMemo<BotGroupTimelineMessage[]>(
+ () => [...realMessages, ...pendingSends.filter((send) => !pendingMatches.has(send.clientId)).map(pendingBotGroupMessage)],
+ [realMessages, pendingSends, pendingMatches],
+ ));
+ const messageByIdRef = useRef(new Map<string, BotGroupMessageView>());
+ messageByIdRef.current = new Map(realMessages.map((message) => [message.id, message]));
+ const lastRealSequence = realMessages[realMessages.length - 1]?.sequence ?? 0;
+ const lastRealSequenceRef = useRef(lastRealSequence);
+ lastRealSequenceRef.current = lastRealSequence;
+ /** Rows after this sequence arrived while the page was open: they fade in. */
+ const enterAfterRef = useRef<number | null>(null);
+ if (enterAfterRef.current === null && state.kind === 'ready') enterAfterRef.current = lastRealSequence;
+
// Quotes resolve against verified copies only; an unverified original falls back to the snapshot.
const quoteSources = useMemo(
- () => (unverifiedOriginals.size > 0 ? messages.filter((message) => !unverifiedOriginals.has(message.id)) : messages),
- [messages, unverifiedOriginals],
+ () => (unverifiedOriginals.size > 0 ? realMessages.filter((message) => !unverifiedOriginals.has(message.id)) : realMessages),
+ [realMessages, unverifiedOriginals],
);
+ const quoteDisplayCache = useRef(new Map<string, { key: string; display: BotGroupQuoteDisplay }>());
+ const quoteDisplays = useMemo(() => {
+ const next = new Map<string, { key: string; display: BotGroupQuoteDisplay }>();
+ for (const message of rows) {
+ if (!message.quote) continue;
+ const display = resolveBotGroupQuote(message.quote, quoteSources);
+ const key = JSON.stringify(display);
+ const cached = quoteDisplayCache.current.get(message.id);
+ next.set(message.id, cached && cached.key === key ? cached : { key, display });
+ }
+ quoteDisplayCache.current = next;
+ return next;
+ }, [rows, quoteSources]);
+
+ // Read marks: the newest incoming message (a Bot or another human) once it is in view.
+ const latestIncomingAt = useMemo(() => realMessages.reduce((latest, message) =>
+ message.kind === 'message' && (message.authorKind === 'bot' || message.isSelf === false)
+ ? Math.max(latest, message.createdAt) : latest, 0), [realMessages]);
+ const latestIncomingRef = useRef(latestIncomingAt);
+ latestIncomingRef.current = latestIncomingAt;
const acknowledge = useCallback(() => {
if (!isDataOwnerGenerationCurrent(readOwner.current) || !stickToBottomRef.current || document.visibilityState !== 'visible' || !document.hasFocus()) return;
- const at = messages.reduce((latest, message) => message.kind === 'message' && (message.authorKind === 'bot' || message.isSelf === false)
- ? Math.max(latest, message.createdAt) : latest, 0);
+ const at = latestIncomingRef.current;
if (at > 0) markBotRead(botGroupReadKey(groupId), at);
- }, [groupId, messages]);
+ }, [groupId]);
+ const lastAcknowledgeRef = useRef(0);
+ const acknowledgeTimerRef = useRef<number | null>(null);
+ /** Leading-edge throttle for scroll: the first event marks at once, a burst marks once more after. */
+ const acknowledgeSoon = useCallback(() => {
+ const now = Date.now();
+ if (now - lastAcknowledgeRef.current >= ACKNOWLEDGE_THROTTLE_MS) {
+ lastAcknowledgeRef.current = now;
+ acknowledge();
+ return;
+ }
+ if (acknowledgeTimerRef.current !== null) return;
+ acknowledgeTimerRef.current = window.setTimeout(() => {
+ acknowledgeTimerRef.current = null;
+ lastAcknowledgeRef.current = Date.now();
+ acknowledge();
+ }, ACKNOWLEDGE_THROTTLE_MS);
+ }, [acknowledge]);
+ useEffect(() => () => { if (acknowledgeTimerRef.current !== null) window.clearTimeout(acknowledgeTimerRef.current); }, []);
useEffect(() => {
const frame = requestAnimationFrame(acknowledge);
window.addEventListener('focus', acknowledge);
document.addEventListener('visibilitychange', acknowledge);
return () => { cancelAnimationFrame(frame); window.removeEventListener('focus', acknowledge); document.removeEventListener('visibilitychange', acknowledge); };
- }, [acknowledge]);
+ }, [acknowledge, latestIncomingAt]);
+
const plans = useMemo(
() => (state.kind === 'ready' ? mergeBotGroupPlans(state.olderPlans, state.group.plans) : []),
[state],
@@ -362,6 +464,8 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
const separator = t('bots.groupChat.memberSeparator');
const [threadRootId, setThreadRootId] = useState<string | null>(null);
+ const threadRootIdRef = useRef(threadRootId);
+ threadRootIdRef.current = threadRootId;
const threadOpenerRef = useRef<HTMLElement | null>(null);
const threadLayoutRef = useRef<HTMLDivElement>(null);
const threadHeaderRef = useRef<HTMLDivElement>(null);
@@ -408,23 +512,36 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
document.addEventListener('keydown', onKeyDown);
return () => document.removeEventListener('keydown', onKeyDown);
}, [group?.serverBacked, threadRootId, closeThread, shareScope]);
+
const settingsLabel = t('bots.groupChat.settings.open');
- const headerMembers = headerGroup ? memberKey(headerGroup.members) : '';
+ const headerStatus = headerGroup ? botGroupHeaderStatus(headerGroup, displayName, t) : null;
+ const organizerBotId = headerGroup?.organizerBotId ?? null;
const header = useMemo(() => {
if (!headerGroup) return null;
- const names = botGroupMemberNames(headerGroup.members, separator);
+ const names = botGroupMemberNames(members.map((member) => ({ name: botGroupMemberDisplayName(member) })), separator);
return (
<div ref={threadHeaderRef} data-testid="bot-group-content-header" className="flex h-full w-full min-w-0 items-center gap-2 pr-2">
<button
type="button"
onClick={openSettings}
- className="flex min-w-0 items-center gap-2 rounded-full px-2 py-1 text-left hover:bg-[var(--surface-hover)]"
+ className="flex min-w-0 items-center gap-2 rounded-xl px-2 py-1 text-left hover:bg-[var(--surface-hover)]"
style={WINDOW_NO_DRAG_STYLE}
>
- <BotGroupAvatarStack members={headerGroup.members} />
- <span className="min-w-0 truncate text-13 font-medium text-[var(--text-primary)]">{headerGroup.name}</span>
- <span className="hidden min-w-0 truncate text-12 text-[var(--text-tertiary)] sm:inline" title={names}>
- {names}
+ <BotGroupAvatarStack members={members} />
+ <span className="flex min-w-0 flex-col">
+ <span className="min-w-0 truncate text-13 font-medium leading-5 text-[var(--text-primary)]">{headerGroup.name}</span>
+ <span className="flex min-w-0 items-center gap-2 text-11 leading-4 text-[var(--text-tertiary)]">
+ <span className="hidden min-w-0 items-center gap-1 truncate sm:flex" title={names}>
+ {members.map((member, index) => (
+ <Fragment key={member.botId}>
+ {index > 0 ? <span aria-hidden>{separator}</span> : null}
+ <span className="shrink-0">{botGroupMemberDisplayName(member)}</span>
+ {member.botId === organizerBotId ? <BotGroupOrganizerTag /> : null}
+ </Fragment>
+ ))}
+ </span>
+ {headerStatus ? <BotGroupHeaderStatusText text={headerStatus} /> : null}
+ </span>
</span>
</button>
<div className="ml-auto flex shrink-0 items-center">
@@ -443,29 +560,32 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
</div>
</div>
);
- // headerMembers stands in for the member array, which is new on every read.
- }, [headerGroup?.name, headerGroup?.id, headerGroup?.serverBacked, headerGroup?.canInvite, headerMembers, openSettings, separator, settingsLabel]);
+ }, [headerGroup?.name, headerGroup?.id, headerGroup?.serverBacked, headerGroup?.canInvite, members, organizerBotId, headerStatus, openSettings, separator, settingsLabel]);
useRegisterContentHeader(header);
- // Follow new messages and banner viewport changes only while the reader is at the bottom.
- const lastSequence = messages[messages.length - 1]?.sequence ?? 0;
+ const running = group?.round.status === 'running';
// Several Bots think at once in a broadcast round's first circle; the key follows the set.
- const speakingKey =
- group?.round.status === 'running' ? group.round.speakers.map((speaker) => speaker.botId).join(',') : '';
+ const speakingKey = running && group ? group.round.speakers.map((speaker) => `${speaker.botId}:${speaker.activity}`).join(',') : '';
+ const lastRowKey = rows[rows.length - 1]?.id ?? '';
+ const firstRealSequence = realMessages[0]?.sequence ?? 0;
+
+ // Older rows were prepended: keep the reader's place (applied before the bottom pin below).
useLayoutEffect(() => {
const element = scrollRef.current;
- if (!element) return;
const anchor = prependAnchorRef.current;
- if (anchor) {
- prependAnchorRef.current = null;
- element.scrollTop = anchor.top + (element.scrollHeight - anchor.height);
- return;
- }
+ if (!element || !anchor) return;
+ prependAnchorRef.current = null;
+ element.scrollTop = anchor.top + (element.scrollHeight - anchor.height);
+ }, [firstRealSequence]);
+ // Follow new messages and banner viewport changes only while the reader is at the bottom.
+ useLayoutEffect(() => {
+ const element = scrollRef.current;
+ if (!element || prependAnchorRef.current) return;
if (stickToBottomRef.current) element.scrollTop = element.scrollHeight;
- }, [lastSequence, speakingKey, messages.length, hasControlledBanner, controlledBannerCollapsed]);
+ }, [lastRowKey, speakingKey, rows.length, hasControlledBanner, controlledBannerCollapsed]);
- // Markdown, code blocks and avatars finish layout after the first paint; keep a reader
- // who is at the bottom pinned there while the content grows.
+ // Markdown, code blocks and avatars finish layout after the first paint, and the composer or
+ // progress strip may grow: keep a reader who is at the bottom pinned there.
const ready = state.kind === 'ready';
useEffect(() => {
const scroller = scrollRef.current;
@@ -475,6 +595,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
if (stickToBottomRef.current && !prependAnchorRef.current) scroller.scrollTop = scroller.scrollHeight;
});
observer.observe(content);
+ observer.observe(scroller);
return () => observer.disconnect();
}, [ready]);
@@ -498,8 +619,12 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
return null;
}
const element = scrollRef.current;
- if (element) prependAnchorRef.current = { height: element.scrollHeight, top: element.scrollTop };
- const newerRefresh = stateRef.current.kind === 'ready' && stateRef.current.group !== base.group;
+ const current = stateRef.current;
+ const shownFirst = current.kind === 'ready' ? mergeBotGroupMessages(current.older, current.group.messages)[0]?.sequence : undefined;
+ // Only rows that land above the first one move the content; a re-read in place does not.
+ const prepends = result.group.messages.some((message) => shownFirst === undefined || message.sequence < shownFirst);
+ if (element && prepends) prependAnchorRef.current = { height: element.scrollHeight, top: element.scrollTop };
+ const newerRefresh = current.kind === 'ready' && current.group !== base.group;
setState((previous) => {
if (previous.kind !== 'ready') return previous;
// A newer push refresh wins over an older in-flight pagination request.
@@ -592,7 +717,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
target.scrollIntoView?.({ block: 'center' });
target.focus({ preventScroll: true });
setHighlightId(jumpTarget);
- }, [jumpTarget, messages]);
+ }, [jumpTarget, rows]);
useEffect(() => {
if (!highlightId) return;
const timer = window.setTimeout(() => setHighlightId(null), QUOTE_HIGHLIGHT_MS);
@@ -615,6 +740,20 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
}
};
+ const stopRound = async () => {
+ const api = botGroupApi();
+ if (!api || stopping) return;
+ setStopping(true);
+ try {
+ const result = await api.stopBotGroupRound(groupId);
+ if (!result.ok) toast.error(t('bots.groupChat.composer.stopFailed'));
+ } catch {
+ toast.error(t('bots.groupChat.composer.stopFailed'));
+ } finally {
+ setStopping(false);
+ }
+ };
+
/** 开始 / 不用了 / 继续 / 重试 / 结束分工; main pushes 'plan' and the view re-reads. */
const runPlanAction = async (action: BotGroupPlanAction, planId: string) => {
if (planPendingRef.current) return;
@@ -662,6 +801,87 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
}
};
+ // Stable handlers for the memoized rows; each reads the latest page state through refs.
+ const actionsRef = useRef({ locateQuoted, continueRound, runPlanAction, editPlanStep });
+ actionsRef.current = { locateQuoted, continueRound, runPlanAction, editPlanStep };
+ const onLocateQuote = useCallback((quote: BotGroupQuoteView) => void actionsRef.current.locateQuoted(quote), []);
+ const onContinue = useCallback(() => void actionsRef.current.continueRound(), []);
+ const onPlanAction = useCallback((action: 'start' | 'dismiss', planId: string) => void actionsRef.current.runPlanAction(action, planId), []);
+ const onEditStep = useCallback((planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) =>
+ void actionsRef.current.editPlanStep(planId, step, action, botId), []);
+ const onChanged = useCallback(() => loadRef.current(), []);
+ const onQuote = useCallback((messageId: string) => {
+ const message = messageByIdRef.current.get(messageId);
+ if (message) setQuoteDraft(botGroupQuoteFromMessage(message));
+ }, []);
+ const onOpenThread = useCallback((messageId: string) => {
+ threadOpenerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ if (threadCloseAnimationRef.current) {
+ threadCloseAnimationRef.current.cancel();
+ threadCloseAnimationRef.current = null;
+ const panel = threadLayoutRef.current?.querySelector('aside');
+ if (panel) panel.inert = false;
+ if (messageId === threadRootIdRef.current) {
+ (panel?.querySelector<HTMLTextAreaElement>('textarea:not(:disabled)') ?? panel?.querySelector<HTMLButtonElement>('header button'))?.focus();
+ }
+ }
+ setThreadRootId(messageId);
+ }, []);
+ const onSendStart = useCallback((message: BotGroupOutgoingMessage) => {
+ stickToBottomRef.current = true;
+ setPendingSends((previous) => [
+ ...previous.filter((send) => send.clientId !== message.clientId),
+ { ...message, createdAt: Date.now(), afterSequence: lastRealSequenceRef.current },
+ ]);
+ }, []);
+ const onSendSettled = useCallback((clientId: string, outcome: BotGroupSendOutcome) => {
+ setPendingSends((previous) => outcome.ok
+ ? previous.map((send) => (send.clientId === clientId ? { ...send, messageId: outcome.messageId } : send))
+ : previous.filter((send) => send.clientId !== clientId));
+ }, []);
+ const onSent = useCallback(() => {
+ stickToBottomRef.current = true;
+ loadRef.current();
+ }, []);
+
+ const planById = useMemo(() => new Map(plans.map((plan) => [plan.id, plan])), [plans]);
+ const layout = useMemo(() => layoutBotGroupTimeline(rows), [rows]);
+ const stepNumbers = useMemo(() => botGroupHandoffStepNumbers(realMessages, planById), [realMessages, planById]);
+ /** Finish time of each done step (1-based) per plan, from the hand-off messages; stable per content. */
+ const doneAtCache = useRef(new Map<string, { key: string; value: ReadonlyMap<number, number> }>());
+ const planDoneAt = useMemo(() => {
+ const byPlan = new Map<string, Map<number, number>>();
+ for (const message of realMessages) {
+ const number = stepNumbers.get(message.id);
+ if (number === undefined || !message.planId) continue;
+ const entry = byPlan.get(message.planId) ?? new Map<number, number>();
+ entry.set(number, message.createdAt);
+ byPlan.set(message.planId, entry);
+ }
+ const next = new Map<string, { key: string; value: ReadonlyMap<number, number> }>();
+ for (const [planId, value] of byPlan) {
+ const key = JSON.stringify([...value]);
+ const cached = doneAtCache.current.get(planId);
+ next.set(planId, cached && cached.key === key ? cached : { key, value });
+ }
+ doneAtCache.current = next;
+ return next;
+ }, [realMessages, stepNumbers]);
+
+ const openPlan = group ? openBotGroupPlan({ openPlan: group.openPlan, plans }) : null;
+ const runningStep = runningBotGroupPlanStep(openPlan);
+ const speakers = useMemo<BotGroupLiveSpeaker[]>(() => (running && group
+ ? group.round.speakers.flatMap((speaker) => {
+ const member = memberById.get(speaker.botId);
+ return member ? [{ member, displayName: botGroupMemberDisplayName(member), sessionId: speaker.sessionId, activity: speaker.activity }] : [];
+ })
+ : []), [running, group, memberById]);
+ const stepSpeaker = runningStep
+ ? speakers.find((speaker) => speaker.activity === 'step' && speaker.member.botId === runningStep.step.botId)
+ : undefined;
+ const stepLive = useAgentIslandActivity(stepSpeaker?.sessionId ?? '');
+ const planRunningSince = runningStep ? stepLive?.startedAtMs ?? runningStep.plan.updatedAt : null;
+
const resetDrag = () => {
dragCounterRef.current = 0;
setDragOver(false);
@@ -735,24 +955,12 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
);
}
- const memberById = new Map(group.members.map((member) => [member.botId, member]));
- const planById = new Map(plans.map((plan) => [plan.id, plan]));
- const openPlan = openBotGroupPlan({ openPlan: group.openPlan, plans });
const followUp = botGroupPlanFollowUp(openPlan);
- const continueId = continuableRoundEndId(messages, group.round);
- const timeGroups = collectBotMessageTimeGroups(
- messages.map((message) => ({ clientId: message.id, createdAt: message.createdAt })),
- );
- const mentionLabels = [t('bots.groupChat.mention.all'), ...group.members.flatMap((member) => [member.name, member.nickname || member.displayName || member.name])];
- const running = group.round.status === 'running';
- const speakers = running
- ? group.round.speakers.flatMap((speaker) => {
- const member = memberById.get(speaker.botId);
- return member ? [{ member, sessionId: speaker.sessionId, activity: speaker.activity }] : [];
- })
- : [];
+ const continueId = continuableRoundEndId(realMessages, group.round);
const pendingFor = (planId: string | null) =>
planId && planPending?.planId === planId ? planPending.action : null;
+ const canQuote = !!group.serverBacked && !group.archived;
+ const enterAfter = enterAfterRef.current;
return (
<div ref={threadLayoutRef} className="flex h-full min-w-0 overflow-hidden">
@@ -784,16 +992,17 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
>
<div
ref={scrollRef}
+ data-testid="bot-group-timeline"
onScroll={(event) => {
const element = event.currentTarget;
- stickToBottomRef.current = element.scrollHeight - element.scrollTop - element.clientHeight < 48;
- acknowledge();
+ stickToBottomRef.current = element.scrollHeight - element.scrollTop - element.clientHeight < STICK_TO_BOTTOM_PX;
+ if (stickToBottomRef.current) acknowledgeSoon();
}}
- className="min-h-0 flex-1 overflow-y-auto px-5 pb-4 pt-6"
+ className="min-h-0 flex-1 overflow-y-auto px-5 pb-4 pt-4"
>
- <div ref={contentRef} className="mx-auto flex w-full max-w-[760px] flex-col gap-4">
+ <div ref={contentRef} className="mx-auto flex w-full max-w-[760px] flex-col">
{hasMoreBefore ? (
- <div className="flex justify-center">
+ <div className="mb-2 flex justify-center">
<Button
variant="secondary"
size="sm"
@@ -806,7 +1015,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
</Button>
</div>
) : null}
- {messages.length === 0 && !running ? (
+ {rows.length === 0 && !running ? (
<div className="py-12 text-center">
<p className="text-13 font-medium text-[var(--text-secondary)]">
{t('bots.groupChat.timeline.emptyTitle')}
@@ -816,98 +1025,75 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
</p>
</div>
) : null}
- {messages.map((message) => {
- const groupTime = timeGroups.get(message.id);
+ {rows.map((message) => {
+ const rowLayout = layout.get(message.id);
+ const member = message.authorBotId ? memberById.get(message.authorBotId) : undefined;
+ const isPlanCard = message.kind === 'plan';
+ const plan = message.planId ? planById.get(message.planId) : undefined;
+ const organizer = isPlanCard ? memberById.get(plan?.organizerBotId ?? '') : undefined;
+ const identity = isPlanCard ? organizer : member;
+ const authorName = isPlanCard
+ ? (organizer ? botGroupMemberDisplayName(organizer) : plan?.organizerName ?? '')
+ : (member && message.authorKind !== 'system' ? botGroupMemberDisplayName(member) : '') || message.authorName || member?.name || '';
+ const owned = !isPlanCard && message.authorKind === 'user' && message.isSelf === false
+ ? botGroupOwnedBotNames(member, members).join(separator) : '';
+ const isOpenPlanCard = isPlanCard && openPlan !== null && openPlan.id === message.planId;
+ const quotable = canQuote && !message.pending && isBotGroupMessageQuotable(message);
return (
- <div key={message.id} className="flex flex-col gap-4">
- {groupTime !== undefined ? (
- <p className="select-none text-center text-12 text-[var(--text-tertiary)]">
- {formatBotMessageGroupTime(groupTime, i18n.language)}
- </p>
- ) : null}
- <div
- data-bot-group-message-id={message.id}
- // Focusable only as a jump target, so a click elsewhere keeps its usual focus.
- tabIndex={jumpTarget === message.id || highlightId === message.id ? -1 : undefined}
- className={cn(
- '-m-1.5 rounded-xl p-1.5 outline-none transition-colors',
- highlightId === message.id && 'bg-[hsl(var(--search-match-bg))] ring-1 ring-[var(--border-default)]',
- )}
- >
+ <Fragment key={adoptedKeysRef.current.get(message.id) ?? message.id}>
+ {rowLayout?.dateDivider != null ? <BotGroupDateDivider timestamp={rowLayout.dateDivider} locale={locale} /> : null}
<BotGroupTimelineItem
message={message}
+ continued={rowLayout?.continued ?? false}
+ authorName={authorName}
+ avatar={identity ? avatarById.get(identity.botId) : undefined}
+ ownerOf={owned || undefined}
+ stepNumber={stepNumbers.get(message.id)}
+ members={members}
+ mentionLabels={mentionLabels}
+ locale={locale}
shareScope={shareScope}
sharing={sharing}
- quoteDisplay={message.quote ? resolveBotGroupQuote(message.quote, quoteSources) : undefined}
- onLocateQuote={message.quote ? () => void locateQuoted(message.quote!) : undefined}
- actions={message.kind === 'message' ? <ChatMessageActions
- groupId={group.serverBacked ? group.id : undefined} shareScope={shareScope} message={message}
- align={message.authorKind === 'user' && message.isSelf !== false ? 'right' : 'left'}
- onQuote={group.serverBacked && !group.archived && isBotGroupMessageQuotable(message)
- ? () => setQuoteDraft(botGroupQuoteFromMessage(message)) : undefined}
- onReply={group.serverBacked ? () => {
- threadOpenerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
- if (threadCloseAnimationRef.current) {
- threadCloseAnimationRef.current.cancel();
- threadCloseAnimationRef.current = null;
- const panel = threadLayoutRef.current?.querySelector('aside');
- if (panel) panel.inert = false;
- if (message.id === threadRootId) {
- (panel?.querySelector<HTMLTextAreaElement>('textarea:not(:disabled)') ?? panel?.querySelector<HTMLButtonElement>('header button'))?.focus();
- }
- }
- setThreadRootId(message.id);
- } : undefined}
- onChanged={() => loadRef.current()} /> : undefined}
- member={message.authorBotId ? memberById.get(message.authorBotId) : undefined}
- members={group.members}
- mentionLabels={mentionLabels}
+ reactionGroupId={group.serverBacked ? group.id : undefined}
+ quoteDisplay={quoteDisplays.get(message.id)?.display}
+ onLocateQuote={onLocateQuote}
+ onQuote={quotable ? onQuote : undefined}
+ onOpenThread={group.serverBacked && !message.pending ? onOpenThread : undefined}
+ onChanged={onChanged}
+ highlighted={highlightId === message.id}
+ focusable={jumpTarget === message.id || highlightId === message.id}
+ entering={enterAfter !== null && (message.pending === true || message.sequence > enterAfter)}
canContinue={message.id === continueId}
continuing={continuing}
- onContinue={() => void continueRound()}
- plan={message.planId ? planById.get(message.planId) : undefined}
- planActionable={
- message.kind === 'plan' &&
- openPlan !== null &&
- openPlan.id === message.planId &&
- openPlan.status === 'proposed'
- }
- planReassignable={
- message.kind === 'plan' &&
- openPlan !== null &&
- openPlan.id === message.planId &&
- openPlan.status === 'waiting'
- }
+ onContinue={onContinue}
+ plan={plan}
+ planActionable={isOpenPlanCard && openPlan!.status === 'proposed'}
+ planReassignable={isOpenPlanCard && openPlan!.status === 'waiting'}
planPending={planCardPending(pendingFor(message.planId))}
- onPlanAction={(action) => {
- if (message.planId) void runPlanAction(action, message.planId);
- }}
- onEditStep={(step, action, botId) => {
- if (message.planId) void editPlanStep(message.planId, step, action, botId);
- }}
+ planRunningSince={isOpenPlanCard ? planRunningSince : null}
+ planDoneAt={message.planId ? planDoneAt.get(message.planId)?.value : undefined}
+ onPlanAction={onPlanAction}
+ onEditStep={onEditStep}
/>
- </div>
- </div>
+ </Fragment>
);
})}
{openPlan && followUp ? (
- <BotGroupPlanFollowUpRow
- followUp={followUp}
- members={group.members}
- pending={followUpPending(pendingFor(openPlan.id))}
- onContinue={() => void runPlanAction('continue', openPlan.id)}
- onRetry={() => void runPlanAction('retry', openPlan.id)}
- onEnd={() => void runPlanAction('dismiss', openPlan.id)}
- />
+ <div className="mt-3">
+ <BotGroupPlanFollowUpRow
+ followUp={followUp}
+ members={members}
+ pending={followUpPending(pendingFor(openPlan.id))}
+ onContinue={() => void runPlanAction('continue', openPlan.id)}
+ onRetry={() => void runPlanAction('retry', openPlan.id)}
+ onEnd={() => void runPlanAction('dismiss', openPlan.id)}
+ />
+ </div>
) : null}
- {speakers.map(({ member, sessionId, activity }) => (
- <BotGroupSpeakingRow
- key={`${member.botId}:${activity}`}
- speaker={member}
- sessionId={sessionId}
- activity={activity}
- />
- ))}
+ {speakers.map((speaker) => (runningStep && speaker.activity === 'step'
+ // The progress strip carries a running step's status; only its confirmations stay here.
+ ? <BotGroupSpeakerInteraction key={`${speaker.member.botId}:${speaker.activity}`} speaker={speaker} />
+ : <BotGroupSpeakingLine key={`${speaker.member.botId}:${speaker.activity}`} speaker={speaker} />))}
</div>
</div>
{hasControlledBanner && (
@@ -918,9 +1104,26 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
</div>
</div>
)}
+ {running && (runningStep || speakers.length > 0) && !sharing && !group.archived ? (
+ <BotGroupProgressStrip
+ key={runningStep ? `step:${runningStep.plan.id}:${runningStep.step.position}` : speakingKey}
+ step={runningStep ? {
+ ...runningStep,
+ member: memberById.get(runningStep.step.botId),
+ displayName: (() => {
+ const member = memberById.get(runningStep.step.botId);
+ return member ? botGroupMemberDisplayName(member) : runningStep.step.botName;
+ })(),
+ } : null}
+ speakers={speakers}
+ onStop={() => void stopRound()}
+ stopping={stopping}
+ />
+ ) : null}
{sharing ? <ShareSelectionBar sessionId={shareScope} barWidth="100%"
getContentWidth={() => contentRef.current?.querySelector('article')?.getBoundingClientRect().width ?? 760} /> : group.archived ? <p className="border-t border-[var(--border-default)] p-4 text-center text-13 text-[var(--text-tertiary)]">{t('bots.groupChat.server.settings.archived')}</p> : <BotGroupComposer
groupId={group.id}
+ draftKey={attachmentScope}
members={group.members}
running={running}
planState={botGroupComposerPlanState(openPlan)}
@@ -929,10 +1132,9 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
dragOver={dragOver}
quote={quoteDraft ? { view: quoteDraft, display: resolveBotGroupQuote(quoteDraft, quoteSources) } : null}
onQuoteChange={setQuoteDraft}
- onSent={() => {
- stickToBottomRef.current = true;
- loadRef.current();
- }}
+ onSendStart={onSendStart}
+ onSendSettled={onSendSettled}
+ onSent={onSent}
/>}
{group.migrationPending && <p role="status" className="px-4 py-2 text-13 text-[var(--text-secondary)]">{t('bots.groupChat.migrationPending')}</p>}
{/* Whole-page drop hint, as over a task's chat area; the card repeats it. */}
@@ -978,256 +1180,3 @@ function planCardPending(action: PlanPending['action'] | null): BotGroupPlanCard
function followUpPending(action: PlanPending['action'] | null): BotGroupFollowUpAction | null {
return action === 'continue' || action === 'retry' || action === 'dismiss' ? action : null;
}
-
-function BotGroupTimelineItem({
- message,
- shareScope,
- sharing,
- quoteDisplay,
- onLocateQuote,
- actions,
- member,
- members,
- mentionLabels,
- canContinue,
- continuing,
- onContinue,
- plan,
- planActionable,
- planReassignable,
- planPending,
- onPlanAction,
- onEditStep,
-}: {
- message: BotGroupMessageView;
- shareScope: string;
- sharing: boolean;
- /** 引用回复: how the quoted message reads now; absent when this message quotes nothing. */
- quoteDisplay?: BotGroupQuoteDisplay;
- onLocateQuote?: () => void;
- actions?: ReactNode;
- member: BotGroupMemberView | undefined;
- members: readonly BotGroupMemberView[];
- mentionLabels: readonly string[];
- canContinue: boolean;
- continuing: boolean;
- onContinue: () => void;
- /** Snapshot of the plan this message belongs to (安排卡, hand-off or plan end). */
- plan: BotGroupPlanView | undefined;
- planActionable: boolean;
- /** The open plan stopped after a step: a step not yet done can change hands before 继续 / 重试. */
- planReassignable: boolean;
- planPending: BotGroupPlanCardAction | null;
- onPlanAction: (action: 'start' | 'dismiss') => void;
- onEditStep: (step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) => void;
-}) {
- const { t } = useTranslation();
- if (message.kind === 'round-end') {
- return (
- <div className="flex select-none items-center gap-3 text-12 text-[var(--text-tertiary)]">
- <span aria-hidden className="h-px flex-1 bg-[var(--border-default)]" />
- <span>{t('bots.groupChat.timeline.roundEnded')}</span>
- {canContinue ? (
- <Button variant="secondary" size="sm" compact type="button" loading={continuing} onClick={onContinue}>
- {t('bots.groupChat.timeline.continue')}
- </Button>
- ) : null}
- <span aria-hidden className="h-px flex-1 bg-[var(--border-default)]" />
- </div>
- );
- }
- if (message.kind === 'plan-end') {
- return <BotGroupPlanEndDivider stepCount={plan ? plan.steps.length : null} />;
- }
- if (message.kind === 'notice' || message.authorKind === 'system') {
- const name = message.authorName.trim() || member?.name || '';
- if (isBotGroupRuntimeFailureCode(message.runtimeFailureCode)) {
- return <BotGroupRuntimeFailureNotice name={name} code={message.runtimeFailureCode} />;
- }
- const key = botGroupNoticeKey(message.noticeCode, message.planId !== null);
- const text = key ? t(key, { name }) : message.content;
- return <p className="text-center text-12 text-[var(--text-tertiary)]">{text}</p>;
- }
- if (message.kind === 'message' && message.authorKind === 'user' && message.isSelf !== false) {
- // An attachment-only message shows just its attachments, without an empty bubble.
- const hasText = message.content.trim().length > 0;
- return (
- <article {...{ [SHARE_SESSION_ATTR]: shareScope, [SHARE_MESSAGE_ATTR]: message.id }}
- className={`relative flex justify-end ${sharing ? 'ml-10' : ''}`}>
- {sharing && <ShareMessageCheckbox clientId={message.id} />}
- <div className="flex min-w-0 max-w-[72%] flex-col items-end gap-2">
- {quoteDisplay ? <BotGroupQuoteBlock display={quoteDisplay} onLocate={onLocateQuote} align="right" /> : null}
- <BotGroupUserAttachments attachments={message.attachments} />
- {hasText ? (
- <div
- className={`max-w-full whitespace-pre-wrap break-words rounded-xl border border-[var(--msg-user-border)] bg-[var(--msg-user-bg)] px-3.5 py-2.5 text-[var(--msg-user-text)] ${CHAT_BODY_CLASS}`}
- >
- {splitBotGroupMentionSegments(message.content, mentionLabels).map((segment, index) =>
- segment.mention ? (
- <span
- key={index}
- className="rounded-full bg-[var(--surface-chip)] px-1.5 font-medium"
- >
- {segment.text}
- </span>
- ) : (
- <span key={index}>{segment.text}</span>
- ),
- )}
- </div>
- ) : null}
- {actions}
- </div>
- </article>
- );
- }
- // A server plan is signed by its human creator; present the organizer without changing authorship.
- const isPlanCard = message.kind === 'plan';
- const identity = isPlanCard ? members.find(candidate => candidate.botId === plan?.organizerBotId) : member;
- const author = {
- name: isPlanCard ? identity?.name || plan?.organizerName || '' : message.authorName || identity?.name || '',
- avatar: identity?.avatar ?? null,
- avatarUrl: identity?.avatarUrl,
- avatarColor: identity?.avatarColor ?? null,
- };
- const hasText = message.content.trim().length > 0;
- return (
- <article {...(message.kind === 'message' ? { [SHARE_SESSION_ATTR]: shareScope, [SHARE_MESSAGE_ATTR]: message.id } : {})}
- className={`relative flex min-w-0 items-start gap-2.5 ${sharing ? 'ml-10' : ''}`}>
- {sharing && message.kind === 'message' && <ShareMessageCheckbox clientId={message.id} />}
- <BotAvatar bot={author} size="sm" />
- <div className="flex min-w-0 flex-1 flex-col gap-0.5">
- <span className="flex min-w-0 select-none items-center gap-2">
- <span className="min-w-0 truncate text-13 font-medium leading-7 text-[var(--text-primary)]">
- {author.name}
- </span>
- {isPlanCard ? <BotGroupOrganizerTag /> : null}
- </span>
- {isPlanCard ? (
- <BotGroupPlanCard
- plan={plan}
- members={members}
- actionable={planActionable}
- reassignable={planReassignable}
- pending={planPending}
- onStart={() => onPlanAction('start')}
- onDismiss={() => onPlanAction('dismiss')}
- onEditStep={onEditStep}
- />
- ) : (
- <>
- {quoteDisplay ? <BotGroupQuoteBlock display={quoteDisplay} onLocate={onLocateQuote} /> : null}
- {/* A task this teammate started from the group; mine is live, another owner's is a snapshot.
- An author no longer in the group is unknown: its task may run on another computer, so it
- stays a snapshot rather than a lookup on this one. */}
- {message.task ? <BotGroupTaskCard task={message.task} owned={member !== undefined && member.isOwned !== false} /> : null}
- {hasText ? (
- <div className={`min-w-0 text-[var(--msg-assistant-text)] ${CHAT_BODY_CLASS}`}>
- <MarkdownRenderer workingDir="" content={message.content} allowPrivilegedLinks={false} />
- </div>
- ) : null}
- <BotGroupUserAttachments attachments={message.attachments} />
- <BotGroupHandoffFiles files={message.files} workDir={plan?.workDir ?? null} />
- {actions}
- </>
- )}
- </div>
- </article>
- );
-}
-
-/**
- * A user message's images and files, drawn like a task's user bubble: each image as the
- * same attached-image view (click for the lightbox, right-click to copy or reveal), files
- * as the same chips (text preview or the system app, right-click menu).
- */
-function BotGroupUserAttachments({ attachments }: { attachments: readonly BotGroupAttachment[] }) {
- const [textPreview, setTextPreview] = useState<{ path: string; name: string } | null>(null);
- const chipRef = useRef<HTMLElement | null>(null);
- const { images, files } = splitBotGroupMessageAttachments(attachments);
- if (images.length === 0 && files.length === 0) return null;
- return (
- <>
- {images.map((image) => (
- <ChatImageView key={image.id} src={image.url} filename={image.name} variant="user-attached" />
- ))}
- {files.length > 0 ? (
- <div className="flex flex-wrap items-end justify-end gap-1.5">
- {files.map((file) => (
- <UserAttachmentChip
- key={file.id}
- file={{ name: file.name, path: file.path }}
- onOpenTextPreview={(chip) => {
- chipRef.current = chip;
- setTextPreview({ path: file.path, name: file.name });
- }}
- />
- ))}
- </div>
- ) : null}
- {textPreview ? (
- <TextLightbox
- filePath={textPreview.path}
- fileName={textPreview.name}
- triggerRef={chipRef}
- onClose={() => setTextPreview(null)}
- />
- ) : null}
- </>
- );
-}
-
-function BotGroupSpeakingRow({
- speaker,
- sessionId,
- activity: speakerActivity,
-}: {
- speaker: BotGroupMemberView;
- sessionId: string | null;
- activity: BotGroupSpeakerActivity;
-}) {
- const { t } = useTranslation();
- const activity = useAgentIslandActivity(sessionId ?? '');
- const waiting = activity?.phase === 'needs-interaction';
- return (
- <article
- data-testid="bot-group-speaking"
- data-activity={speakerActivity}
- className="flex min-w-0 items-start gap-2.5"
- >
- <BotAvatar bot={speaker} size="sm" />
- <div className="flex min-w-0 flex-1 flex-col gap-2">
- <span className="select-none text-13 font-medium leading-7 text-[var(--text-primary)]">
- {speaker.name}
- </span>
- {!waiting ? (
- <p
- role="status"
- aria-live="polite"
- className="-mt-2 flex min-w-0 items-center gap-1.5 text-13 text-[var(--status-bar-accent)]"
- >
- <Sparkles size={14} className="shrink-0 -translate-y-px" aria-hidden />
- <span className="min-w-0 truncate">
- {speakerActivity === 'planning' ? (
- // The organizer's decision runs outside any Session, so there is no live phase to show.
- t('bots.groupChat.speaking.planning')
- ) : (
- <BotGenerationLabel
- sessionId={sessionId ?? undefined}
- phase={activity?.workingPhase ?? 'thinking'}
- startedAt={activity?.startedAtMs ?? null}
- />
- )}
- </span>
- </p>
- ) : null}
- {sessionId ? (
- <BotGroupPendingInteraction
- sessionId={sessionId}
- bot={{ id: speaker.botId, name: speaker.name, avatar: speaker.avatar, avatarColor: speaker.avatarColor }}
- />
- ) : null}
- </div>
- </article>
- );
-}
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
index 0b99e1cd6d..36b94cab26 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
@@ -1,6 +1,6 @@
/**
* 群聊输入框:纯文本,Enter 发送、Shift+Enter 换行,IME 组合中不发送
- * (DESIGN.md §14.3)。输入 `@` 弹出点名候选(useBotGroupMentionPicker,与 Thread 回复框同一套)。
+ * (DESIGN.md §14.3)。输入 `@` 弹出点名候选(useBotGroupMentionPicker,主群与话题回复同一套)。
*
* 发送时以正文重新解析点名(见 botGroupMentions.ts),clientId 作为幂等键:同一段
* 文字发送失败后重发沿用同一个 clientId,main 会返回第一次写入的那条消息。一轮进行
@@ -19,6 +19,16 @@
* 加),缩略图与拒收提示复用 ComposerAttachments;「+」→「添加文件、图片或视频…」、粘贴
* 文件或截图都进托盘。有附件时可以不写字。发送前烧录图片标注,发出去之后才从托盘移走
* 这一批;没发出去就原样留着。
+ *
+ * 草稿随群持久(与普通任务一样存进 composerDraftStore,附件已经在同一个键下):切走再回来、
+ * 分享选择时输入框暂时卸载,文字都还在;群被删除时随草稿一起丢弃。
+ *
+ * 乐观发送:按下发送的那一刻 `onSendStart` 交出这条消息的本地副本(页面立刻插进时间线),
+ * main 答复后 `onSendSettled` 带回结果(成功带 messageId,失败页面撤掉副本、草稿放回)。
+ *
+ * 话题模式(`mode="thread"`):同一个输入框用于话题回复——没有「+」菜单(不能安排分工;
+ * Chat Server 的话题回复不带附件)、没有引用回复,发送键是「发送回复」,失败原因写在输入框
+ * 上方;同一段文字、按当次成员解析出的点名目标也不变时,重发沿用同一个 clientId 和点名。
*/
import {
useEffect,
@@ -45,29 +55,34 @@ import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts
import { MENU_ITEM_CLASS } from '@/features/cc-agent/sidebar/menuStyles';
import type { UseAttachmentsReturn } from '@/hooks/useAttachments';
import { isAnnotationBurnInError, materializeAnnotatedAttachmentsForSend } from '@/lib/annotationBurnIn';
+import {
+ captureDraftDiscardToken,
+ getDraft,
+ isDraftDiscardTokenCurrent,
+ saveDraft,
+} from '@/lib/composerDraftStore';
import type { AttachedFile } from '@/lib/fileTypes';
import { toast } from '@/lib/toast';
import { cn } from '@/lib/utils';
import {
BOT_GROUP_ATTACHMENTS_MAX,
BOT_GROUP_MESSAGE_MAX_CHARS,
+ type BotGroupAttachment,
type BotGroupMemberView,
+ type BotGroupMention,
type BotGroupQuoteDisplay,
type BotGroupQuoteView,
+ type ChatServerResult,
} from '../../../shared/botGroupChat';
import { BotGroupQuotePreview } from './BotGroupQuote';
import {
- BOT_GROUP_COMPOSER_CARD,
- BOT_GROUP_COMPOSER_COLUMN,
- BOT_GROUP_COMPOSER_DOCK,
- BOT_GROUP_COMPOSER_FOOTER,
- BOT_GROUP_COMPOSER_FOOTER_START,
- BOT_GROUP_COMPOSER_INPUT,
- fitBotGroupComposerInput,
- keepBotGroupComposerInputFocus,
- useRefitBotGroupComposerInputOnResize,
-} from './botGroupComposerChrome';
-import { botGroupAttachmentSignature, toBotGroupAttachmentInputs } from './botGroupAttachments';
+ botGroupAttachmentPreview,
+ botGroupAttachmentSignature,
+ botGroupDraftDoc,
+ botGroupDraftText,
+ toBotGroupAttachmentInputs,
+} from './botGroupAttachments';
+import { chatErrorKey } from './chatError';
import {
botGroupErrorKey,
isActiveBotGroupMember,
@@ -77,6 +92,12 @@ import {
import { botGroupApi } from './botGroupStore';
import { useBotGroupMentionPicker } from './useBotGroupMentionPicker';
+/** 话题 replies also accept the Chat Server's own 「everyone」 spellings. */
+const THREAD_ALL_ALIASES = ['所有人', 'all', 'everyone'] as const;
+
+const sameBotGroupMentions = (a: BotGroupMention, b: BotGroupMention) =>
+ a.all === b.all && a.botIds.length === b.botIds.length && a.botIds.every((botId, index) => botId === b.botIds[index]);
+
function isComposingKey(event: KeyboardEvent): boolean {
return event.nativeEvent.isComposing || event.keyCode === 229;
}
@@ -104,36 +125,82 @@ function filePathOf(file: File): string {
}
}
+/** The local copy of a message being sent, for the timeline to show at once. */
+export interface BotGroupOutgoingMessage {
+ clientId: string;
+ text: string;
+ mentions: BotGroupMention;
+ attachments: BotGroupAttachment[];
+ quote: BotGroupQuoteView | null;
+}
+
+export type BotGroupSendOutcome = { ok: true; messageId: string } | { ok: false };
+
+/** Drafts are written this long after the last keystroke (and on unmount). */
+const DRAFT_SAVE_DELAY_MS = 300;
+
+const NO_ATTACHMENTS: BotGroupComposerAttachments = {
+ attachments: [],
+ addFiles: async () => undefined,
+ addClipboardImage: async () => undefined,
+ rejections: [],
+ dismissRejection: () => undefined,
+ removeFile: () => undefined,
+ updateFile: () => undefined,
+ restoreFiles: () => undefined,
+ clearFiles: () => undefined,
+} as unknown as BotGroupComposerAttachments;
+
export function BotGroupComposer({
groupId,
+ mode = 'group',
+ draftKey,
members,
running,
+ disabled = false,
planState = null,
- attachments: attachmentState,
- attachmentScope,
+ attachments: attachmentState = NO_ATTACHMENTS,
+ attachmentScope = '',
dragOver = false,
quote = null,
onQuoteChange,
+ sendReply,
+ onSendStart,
+ onSendSettled,
onSent,
}: {
groupId: string;
+ /** `thread`: a 话题's reply box (no 「+」 menu, attachments or quotes). */
+ mode?: 'group' | 'thread';
+ /** Where the unsent text is kept (the group's attachment scope, or the 话题's own key). */
+ draftKey: string;
members: readonly BotGroupMemberView[];
running: boolean;
+ /** Archived group: nothing can be sent. */
+ disabled?: boolean;
/** The group's open plan, for placeholders and the 「安排分工」 gate. */
planState?: BotGroupComposerPlanState | null;
- attachments: BotGroupComposerAttachments;
+ attachments?: BotGroupComposerAttachments;
/** Scope for writing annotated images before send (see botGroupAttachmentScope). */
- attachmentScope: string;
+ attachmentScope?: string;
/** Files are being dragged over the page: the card shows the same drop hint as a task's. */
dragOver?: boolean;
/** 引用回复 waiting to go with the next message, and how its original reads right now. */
quote?: { view: BotGroupQuoteView; display: BotGroupQuoteDisplay } | null;
onQuoteChange?: (quote: BotGroupQuoteView | null) => void;
+ /** Thread mode: posts the reply. */
+ sendReply?: (input: { text: string; clientId: string; mentions: BotGroupMention }) => Promise<ChatServerResult<{ messageId: string }>>;
+ /** The message is on its way: show its local copy now. */
+ onSendStart?: (message: BotGroupOutgoingMessage) => void;
+ /** Main answered (or the send failed before reaching it). */
+ onSendSettled?: (clientId: string, outcome: BotGroupSendOutcome) => void;
/** Called after main accepted the message, so the view can re-read at once. */
- onSent: () => void;
+ onSent?: () => void;
}) {
const { t } = useTranslation();
- const [text, setText] = useState('');
+ const thread = mode === 'thread';
+ const [text, setText] = useState(() => botGroupDraftText(getDraft(draftKey)?.text));
+ const [error, setError] = useState('');
const [stopping, setStopping] = useState(false);
/** A send is in flight: its attachments stay in the tray but cannot change. */
const [sending, setSending] = useState(false);
@@ -142,7 +209,16 @@ export function BotGroupComposer({
const [menuOpen, setMenuOpen] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
- const mention = useBotGroupMentionPicker({ text, onTextChange: setText, members, textareaRef });
+ const allLabel = t('bots.groupChat.mention.all');
+ const threadAllLabels = useMemo(() => [allLabel, ...THREAD_ALL_ALIASES], [allLabel]);
+ // Same @ picker in the group and in a 话题; the 话题 also resolves the server's aliases.
+ const mention = useBotGroupMentionPicker({
+ text,
+ onTextChange: setText,
+ members,
+ textareaRef,
+ allLabels: thread ? threadAllLabels : undefined,
+ });
const textRef = useRef(text);
textRef.current = text;
const attachmentsRef = useRef(attachmentState.attachments);
@@ -161,18 +237,22 @@ export function BotGroupComposer({
attachments: string;
mentionSignature: string;
quoteId: string | null;
+ /** 话题 replies keep the targets resolved on the first attempt, with the roster of that moment. */
+ mentions?: BotGroupMention;
+ roster?: readonly BotGroupMemberView[];
} | null>(null);
const activeMembers = useMemo(() => members.filter(isActiveBotGroupMember), [members]);
const trimmed = text.trim();
const tooLong = trimmed.length > BOT_GROUP_MESSAGE_MAX_CHARS;
- const hasMembers = activeMembers.length > 0;
+ // A 话题 reply goes to the people in it; it does not need an active teammate.
+ const hasMembers = thread || activeMembers.length > 0;
const attachmentCount = attachmentState.attachments.length;
const tooManyAttachments = attachmentCount > BOT_GROUP_ATTACHMENTS_MAX;
const canSend =
- (trimmed.length > 0 || attachmentCount > 0) && !tooLong && !tooManyAttachments && hasMembers;
- const showStop = running && trimmed.length === 0 && attachmentCount === 0;
+ !disabled && (trimmed.length > 0 || attachmentCount > 0) && !tooLong && !tooManyAttachments && hasMembers;
+ const showStop = !thread && running && trimmed.length === 0 && attachmentCount === 0;
const divisionBlocked = isBotGroupDivisionBlocked(planState);
// Picking 引用回复 brings the caret here, ready to type the reply.
@@ -180,15 +260,83 @@ export function BotGroupComposer({
if (quotedMessageId) textareaRef.current?.focus();
}, [quotedMessageId]);
+ // Keep the unsent text with the group (or 话题), like a task's composer draft.
+ const discardTokenRef = useRef(captureDraftDiscardToken(draftKey));
+ const persistDraft = useRef((value: string) => {
+ if (!isDraftDiscardTokenCurrent(discardTokenRef.current)) return;
+ const existing = getDraft(draftKey);
+ if (!existing && !value) return;
+ saveDraft(
+ draftKey,
+ { ...existing, attachments: existing?.attachments ?? [], text: value ? botGroupDraftDoc(value) : null },
+ { silent: true },
+ );
+ }).current;
+ useEffect(() => {
+ const timer = window.setTimeout(() => persistDraft(text), DRAFT_SAVE_DELAY_MS);
+ return () => window.clearTimeout(timer);
+ }, [persistDraft, text]);
+ useEffect(() => () => persistDraft(textRef.current), [persistDraft]);
+
// Auto-grow; the CSS max height caps it and turns on scrolling.
useLayoutEffect(() => {
const element = textareaRef.current;
if (!element) return;
- fitBotGroupComposerInput(element);
+ element.style.height = 'auto';
+ element.style.height = `${element.scrollHeight}px`;
}, [text]);
- useRefitBotGroupComposerInputOnResize(textareaRef);
+
+ /**
+ * 话题 reply: a retry reuses the attempt only for the same text and the same targets
+ * (bot-group-chat.md). Targets are re-resolved against the attempt's own roster: a roster
+ * refresh alone changes nothing and the host still rejects a departed target; re-picking
+ * someone else gets a new clientId.
+ */
+ const sendThreadReply = async () => {
+ if (!canSend || sendingRef.current || !sendReply) return;
+ const previous = attemptRef.current;
+ const attempt =
+ previous?.mentions && previous.roster && previous.text === trimmed
+ && sameBotGroupMentions(mention.resolve(text, previous.roster), previous.mentions)
+ ? previous
+ : {
+ text: trimmed, clientId: crypto.randomUUID(), division: false, attachments: '', mentionSignature: '', quoteId: null,
+ mentions: mention.resolve(text), roster: members,
+ };
+ attemptRef.current = attempt;
+ const draft = text;
+ const mentions = attempt.mentions!;
+ const tracked = mention.tracked;
+ sendingRef.current = true;
+ setSending(true);
+ setError('');
+ setText('');
+ mention.reset();
+ onSendStart?.({ clientId: attempt.clientId, text: attempt.text, mentions, attachments: [], quote: null });
+ const owner = getDataOwnerGeneration();
+ const fail = (message: string) => {
+ onSendSettled?.(attempt.clientId, { ok: false });
+ if (!textRef.current) mention.setTracked(tracked);
+ setText((current) => (current ? current : draft));
+ setError(message);
+ };
+ try {
+ const result = await sendReply({ text: attempt.text, clientId: attempt.clientId, mentions });
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ if (!result.ok) { fail(t(chatErrorKey(result.errorCode))); return; }
+ attemptRef.current = null;
+ onSendSettled?.(attempt.clientId, { ok: true, messageId: result.messageId });
+ onSent?.();
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) fail(t('bots.groupChat.server.requestFailed'));
+ } finally {
+ sendingRef.current = false;
+ setSending(false);
+ }
+ };
const send = async () => {
+ if (thread) { await sendThreadReply(); return; }
if (!canSend || sendingRef.current) return;
const api = botGroupApi();
if (!api) {
@@ -223,8 +371,16 @@ export function BotGroupComposer({
mention.reset();
setDivision(false);
if (sentQuote) onQuoteChange?.(null);
+ onSendStart?.({
+ clientId: attempt.clientId,
+ text: attempt.text,
+ mentions,
+ attachments: files.map(botGroupAttachmentPreview),
+ quote: sentQuote,
+ });
const owner = getDataOwnerGeneration();
const restore = (keepQuote = true) => {
+ onSendSettled?.(attempt.clientId, { ok: false });
// The tag and the quote come back only with their own draft, never onto newly typed
// text; a quote picked meanwhile wins, and an unavailable original is not put back.
if (!textRef.current) {
@@ -270,7 +426,8 @@ export function BotGroupComposer({
attachmentState.clearFiles();
attachmentState.restoreFiles(remaining);
}
- onSent();
+ onSendSettled?.(attempt.clientId, { ok: true, messageId: result.messageId });
+ onSent?.();
} catch (error) {
if (!isDataOwnerGenerationCurrent(owner)) return;
restore();
@@ -285,6 +442,8 @@ export function BotGroupComposer({
/** Files copied in a file manager attach by path; a screenshot or copied image attaches as an image. */
const handlePaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {
+ // A 话题 reply carries text only; pasted files stay out of it.
+ if (thread) return;
const items = event.clipboardData?.items;
if (!items || items.length === 0) return;
const filesWithPath: File[] = [];
@@ -332,10 +491,14 @@ export function BotGroupComposer({
: tooManyAttachments
? t('bots.groupChat.composer.tooManyAttachments', { max: BOT_GROUP_ATTACHMENTS_MAX })
: null;
- const actionLabel = showStop ? t('bots.groupChat.composer.stop') : t('bots.send');
+ const actionLabel = showStop
+ ? t('bots.groupChat.composer.stop')
+ : thread ? t('bots.groupChat.server.sendReply') : t('bots.send');
const moreLabel = t('bots.groupChat.composer.more');
const removeDivisionLabel = t('bots.groupChat.composer.removeDivision');
- const placeholder = !hasMembers
+ const placeholder = thread
+ ? t('bots.groupChat.server.replyPlaceholder')
+ : !hasMembers
? t('bots.groupChat.composer.noMembers')
: division
? t('bots.groupChat.composer.placeholderDivision')
@@ -350,8 +513,9 @@ export function BotGroupComposer({
const noop = () => undefined;
return (
- <div className={BOT_GROUP_COMPOSER_DOCK}>
- <div className={BOT_GROUP_COMPOSER_COLUMN}>
+ <div className={cn('shrink-0 pb-4 pt-2', thread ? 'px-4' : 'px-5')}>
+ <div className="relative mx-auto w-full max-w-[760px]">
+ {error ? <p role="alert" className="mb-2 text-13 text-[var(--error-fg)]">{error}</p> : null}
{/* Same floating slot above the card as a task's composer: files that did not attach. */}
{attachmentState.rejections.length > 0 ? (
<div className="pointer-events-none absolute bottom-full left-0 right-0 z-20 mb-2 flex flex-col items-center gap-1 px-3">
@@ -362,7 +526,7 @@ export function BotGroupComposer({
</div>
) : null}
{mention.list}
- <div className={BOT_GROUP_COMPOSER_CARD}>
+ <div className="relative flex flex-col gap-2 rounded-xl border border-[var(--chat-input-border)] bg-[var(--chat-input-bg)] px-3.5 pb-2.5 pt-3 transition-colors focus-within:border-[var(--chat-input-border-focus)]">
{dragOver ? (
<div
data-testid="bot-group-drop-hint"
@@ -417,7 +581,10 @@ export function BotGroupComposer({
ref={textareaRef}
value={text}
rows={1}
- aria-label={t('bots.groupChat.composer.label')}
+ disabled={disabled}
+ aria-label={thread ? t('bots.groupChat.server.replyPlaceholder') : t('bots.groupChat.composer.label')}
+ // The Chat Server caps a 话题 reply; the field enforces it as typing does (a pick obeys it too).
+ maxLength={thread ? BOT_GROUP_MESSAGE_MAX_CHARS : undefined}
{...mention.textareaProps}
placeholder={placeholder}
onChange={(event) => mention.onChange(event.target.value)}
@@ -442,10 +609,11 @@ export function BotGroupComposer({
setDivision(false);
}
}}
- className={BOT_GROUP_COMPOSER_INPUT}
+ className="max-h-60 min-h-6 w-full resize-none overflow-y-auto bg-transparent text-15 leading-[1.6] text-[var(--chat-input-text)] outline-none placeholder:text-[var(--chat-input-placeholder)] focus-visible:outline-none"
/>
- <div className={BOT_GROUP_COMPOSER_FOOTER}>
- <div className={BOT_GROUP_COMPOSER_FOOTER_START}>
+ <div className="flex min-h-7 items-center justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-2">
+ {thread ? null : (<>
<input
ref={fileInputRef}
type="file"
@@ -520,20 +688,19 @@ export function BotGroupComposer({
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
+ </>)}
<span className="min-w-0 truncate text-12 text-[var(--text-tertiary)]" aria-live="polite">
{hint}
</span>
</div>
- <span className="inline-flex rounded-full" onMouseDown={keepBotGroupComposerInputFocus(textareaRef)}>
- <Tip text={actionLabel}>
- <SendButton
- disabled={showStop ? stopping : !canSend}
- isStreaming={showStop}
- ariaLabel={actionLabel}
- onClick={() => void (showStop ? stop() : send())}
- />
- </Tip>
- </span>
+ <Tip text={actionLabel}>
+ <SendButton
+ disabled={showStop ? stopping : !canSend}
+ isStreaming={showStop}
+ ariaLabel={actionLabel}
+ onClick={() => void (showStop ? stop() : send())}
+ />
+ </Tip>
</div>
</div>
</div>
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupElapsed.tsx b/apps/desktop/src/renderer/features/bots/BotGroupElapsed.tsx
new file mode 100644
index 0000000000..95e3965648
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/BotGroupElapsed.tsx
@@ -0,0 +1,36 @@
+/**
+ * 群聊里「已做 8 分钟」这类走动的用时:一个按需走表的 `now`,和与语言无关的用时格式。
+ * 只有挂着的走表组件会每秒重绘,时间线其它行不受影响。
+ */
+import { useEffect, useState } from 'react';
+import type { TFunction } from 'i18next';
+import { useTranslation } from 'react-i18next';
+
+/** Current time, re-read every `intervalMs` while `enabled`. */
+export function useBotGroupNow(enabled: boolean, intervalMs = 1_000): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!enabled) return;
+ setNow(Date.now());
+ const timer = window.setInterval(() => setNow(Date.now()), intervalMs);
+ return () => window.clearInterval(timer);
+ }, [enabled, intervalMs]);
+ return now;
+}
+
+/** 「12 秒」「8 分钟」「1 小时 5 分」. */
+export function formatBotGroupElapsed(ms: number, t: TFunction): string {
+ const seconds = Math.max(0, Math.floor(ms / 1_000));
+ if (seconds < 60) return t('bots.groupChat.elapsed.seconds', { count: seconds });
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return t('bots.groupChat.elapsed.minutes', { count: minutes });
+ return t('bots.groupChat.elapsed.hours', { hours: Math.floor(minutes / 60), minutes: minutes % 60 });
+}
+
+/** A ticking elapsed time since `since`; nothing when the start is unknown. */
+export function BotGroupElapsed({ since, className }: { since: number | null; className?: string }) {
+ const { t } = useTranslation();
+ const now = useBotGroupNow(since !== null);
+ if (since === null) return null;
+ return <span className={className}>{formatBotGroupElapsed(now - since, t)}</span>;
+}
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx b/apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx
new file mode 100644
index 0000000000..696701c009
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx
@@ -0,0 +1,32 @@
+/**
+ * 正在发言的伙伴此刻写到哪了:群专线(或分工 Session)在这台电脑上跑时,它的流式正文已经
+ * 在 makerChatStore 里(maker 事件按 sessionId 写入,不需要读历史),这里只取最后几行,
+ * 让群里像打字一样逐字出来。专线不在本机运行(服务器群的别的电脑在执行)时没有内容,
+ * 什么也不显示;正文可能还会变成静默标记 NO_REPLY,在那之前不显示。
+ */
+import { useCallback, useSyncExternalStore } from 'react';
+
+import { makerChatStore } from '@/lib/makerChatStore';
+import { cn } from '@/lib/utils';
+import { isBotGroupNoReplyPrefix } from '../../../shared/botGroupChat';
+
+/** The last `lines` non-empty lines of the streaming reply, or ''. */
+export function botGroupLiveTail(text: string, lines: number): string {
+ if (isBotGroupNoReplyPrefix(text)) return '';
+ return text.split('\n').map((line) => line.trim()).filter(Boolean).slice(-lines).join('\n');
+}
+
+export function BotGroupLivePreview({ sessionId, lines = 2, className }: { sessionId: string; lines?: number; className?: string }) {
+ const subscribe = useCallback((listener: () => void) => makerChatStore.subscribe(sessionId, listener), [sessionId]);
+ // A string snapshot: unrelated store updates of this Session do not re-render.
+ const read = useCallback(() => botGroupLiveTail(makerChatStore.getSnapshot(sessionId).streamingText ?? '', lines), [sessionId, lines]);
+ const tail = useSyncExternalStore(subscribe, read, read);
+ if (!tail) return null;
+ return (
+ <div data-testid="bot-group-live-preview" aria-hidden className={cn('flex min-w-0 flex-col text-13 leading-5 text-[var(--text-secondary)]', className)}>
+ {tail.split('\n').map((line, index) => (
+ <span key={index} className="min-w-0 truncate">{line}</span>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx b/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx
new file mode 100644
index 0000000000..332f86f195
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx
@@ -0,0 +1,214 @@
+/**
+ * 群聊的「正在进行」:
+ *
+ * - 时间线末尾每位正在发言的伙伴一行扁平状态「LiZi 正在想…」,本机能读到流式正文时下面
+ * 跟最后两行(逐字出来的感觉);等确认时放确认卡。负责人还在判断要不要分工时写「正在安排…」。
+ * - 输入框上方的进行中条(不随时间线滚走):分工某一步在做,或某位伙伴说了超过三秒时出现,
+ * 写「第 k/n 步 · 谁 做什么 · 已做多久 · 当前动作」,带「看过程」(本机能读到这条专线时)
+ * 与「停止」。分工进行中它替代时间线末尾的发言行。
+ * - 顶栏右侧的一句状态:「Dash 正在做第 2 步」「Dash 正在说…」「LiZi 正在安排…」。
+ */
+import { useState } from 'react';
+import { Sparkles } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { cn } from '@/lib/utils';
+import { useAgentIslandActivity } from '@/state/agentIslandActivity';
+import type { BotGroupMemberView, BotGroupSpeakerActivity, BotGroupSummary } from '../../../shared/botGroupChat';
+import { BotAvatar } from './BotAvatar';
+import { BotGenerationLabel } from './BotGenerationLabel';
+import { formatBotGroupElapsed, useBotGroupNow } from './BotGroupElapsed';
+import { BotGroupLivePreview } from './BotGroupLivePreview';
+import { BotGroupPendingInteraction } from './BotGroupPendingInteraction';
+import type { BotGroupRunningStep } from './BotGroupTimelineModel';
+
+export interface BotGroupLiveSpeaker {
+ member: BotGroupMemberView;
+ displayName: string;
+ sessionId: string | null;
+ activity: BotGroupSpeakerActivity;
+}
+
+/** A speaker active this long earns the progress strip in plain discussion. */
+export const BOT_GROUP_PROGRESS_STRIP_DELAY_MS = 3_000;
+
+function pendingBot(speaker: BotGroupLiveSpeaker) {
+ const { member } = speaker;
+ return { id: member.botId, name: speaker.displayName, avatar: member.avatar, avatarColor: member.avatarColor };
+}
+
+/** The flat 「LiZi 正在…」 line at the end of the timeline, with the live text under it. */
+export function BotGroupSpeakingLine({ speaker, showStatus = true }: { speaker: BotGroupLiveSpeaker; showStatus?: boolean }) {
+ const { t } = useTranslation();
+ const { member, sessionId, activity: speakerActivity } = speaker;
+ const live = useAgentIslandActivity(sessionId ?? '');
+ const waiting = live?.phase === 'needs-interaction';
+ return (
+ <article data-testid="bot-group-speaking" data-activity={speakerActivity} className="mt-3.5 flex min-w-0 items-start gap-2.5">
+ <div className="flex h-5 w-7 shrink-0 items-center justify-end">
+ <BotAvatar bot={member} size="xs" />
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ {showStatus ? (
+ <p role="status" aria-live="polite" className="flex min-w-0 items-center gap-1.5 text-13 leading-5">
+ <span className="shrink-0 font-medium text-[var(--text-primary)]">{speaker.displayName}</span>
+ {!waiting ? (
+ <span className="flex min-w-0 items-center gap-1 text-[var(--status-bar-accent)]">
+ {/* 呼吸只挂在 HTML 包装层上(DESIGN §7:常驻动画 compositor-only)。 */}
+ <span aria-hidden className="session-status-breathing inline-flex shrink-0">
+ <Sparkles size={12} />
+ </span>
+ <span className="min-w-0 truncate">
+ {speakerActivity === 'planning' ? (
+ // The organizer's decision runs outside any Session, so there is no live phase to show.
+ t('bots.groupChat.speaking.planning')
+ ) : (
+ <BotGenerationLabel
+ sessionId={sessionId ?? undefined}
+ phase={live?.workingPhase ?? 'thinking'}
+ startedAt={live?.startedAtMs ?? null}
+ />
+ )}
+ </span>
+ </span>
+ ) : null}
+ </p>
+ ) : null}
+ {sessionId && live?.phase === 'running' ? <BotGroupLivePreview sessionId={sessionId} /> : null}
+ {sessionId ? <BotGroupPendingInteraction sessionId={sessionId} bot={pendingBot(speaker)} /> : null}
+ </div>
+ </article>
+ );
+}
+
+/** Only a speaker's pending confirmation, for steps whose status lives in the progress strip. */
+export function BotGroupSpeakerInteraction({ speaker }: { speaker: BotGroupLiveSpeaker }) {
+ if (!speaker.sessionId) return null;
+ return (
+ <div className="mt-3 pl-[38px]">
+ <BotGroupPendingInteraction sessionId={speaker.sessionId} bot={pendingBot(speaker)} />
+ </div>
+ );
+}
+
+/**
+ * Fixed above the composer while a plan step runs, or a teammate has been speaking for a few
+ * seconds. Remount it (key) when the speaker set changes so 「几秒」 counts from the new turn.
+ */
+export function BotGroupProgressStrip({
+ step,
+ speakers,
+ onStop,
+ stopping,
+}: {
+ step: (BotGroupRunningStep & { member: BotGroupMemberView | undefined; displayName: string }) | null;
+ speakers: readonly BotGroupLiveSpeaker[];
+ onStop: () => void;
+ stopping: boolean;
+}) {
+ const { t } = useTranslation();
+ const [mountedAt] = useState(() => Date.now());
+ const [expanded, setExpanded] = useState(false);
+ const stepSpeaker = step
+ ? speakers.find((speaker) => speaker.activity === 'step' && speaker.member.botId === step.step.botId)
+ ?? speakers.find((speaker) => speaker.member.botId === step.step.botId)
+ : undefined;
+ const lead = step ? stepSpeaker : speakers.find((speaker) => speaker.activity !== 'planning') ?? speakers[0];
+ const sessionId = lead?.sessionId ?? null;
+ const live = useAgentIslandActivity(sessionId ?? '');
+ const since = live?.startedAtMs ?? (step ? step.plan.updatedAt : mountedAt);
+ const now = useBotGroupNow(true);
+ if (!step && (!lead || now - since < BOT_GROUP_PROGRESS_STRIP_DELAY_MS)) return null;
+ const member = step ? step.member : lead?.member;
+ const name = step ? step.displayName : lead?.displayName ?? '';
+ const action = live?.compactDetail?.trim() || '';
+ const canView = !!sessionId && live?.phase === 'running';
+ return (
+ <div className="shrink-0 px-5 pt-2">
+ <div
+ data-testid="bot-group-progress"
+ className="mx-auto flex w-full max-w-[760px] flex-col rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]"
+ >
+ <div className="flex min-h-9 min-w-0 items-center gap-2 px-3 py-1.5">
+ {member ? <BotAvatar bot={member} size="xs" /> : null}
+ <p role="status" aria-live="polite" className="flex min-w-0 flex-1 items-center gap-1 truncate text-12 leading-5 text-[var(--text-secondary)]">
+ {step ? (
+ <span className="shrink-0 font-medium text-[var(--text-primary)]">
+ {t('bots.groupChat.progress.step', { step: step.index, total: step.total })}
+ </span>
+ ) : null}
+ <span className="min-w-0 truncate">
+ {step ? ` · ${name} ${step.step.task}` : t('bots.groupChat.progress.speaking', { name })}
+ </span>
+ <span className="shrink-0 tabular-nums">
+ {' · '}
+ {t('bots.groupChat.progress.elapsed', { time: formatBotGroupElapsed(now - since, t) })}
+ </span>
+ {action ? (
+ <span className="min-w-0 truncate text-[var(--status-bar-accent)]">{` · ${action}`}</span>
+ ) : null}
+ </p>
+ <span className="flex shrink-0 items-center gap-1">
+ {canView ? (
+ <Button type="button" variant="secondary" tone="quiet" size="sm" compact aria-expanded={expanded} onClick={() => setExpanded((value) => !value)}>
+ {t(expanded ? 'bots.groupChat.progress.hideProcess' : 'bots.groupChat.progress.viewProcess')}
+ </Button>
+ ) : null}
+ <Button
+ type="button"
+ variant="secondary"
+ tone="quiet"
+ size="sm"
+ compact
+ loading={stopping}
+ onClick={onStop}
+ className="text-[var(--text-danger)]"
+ >
+ {t('bots.groupChat.progress.stop')}
+ </Button>
+ </span>
+ </div>
+ {expanded && canView && sessionId ? (
+ <div className="flex min-w-0 flex-col gap-1 border-t border-[var(--border-default)] px-3 py-2">
+ {action ? (
+ <p className="min-w-0 truncate text-12 text-[var(--status-bar-accent)]">{action}</p>
+ ) : null}
+ <BotGroupLivePreview sessionId={sessionId} lines={8} className="text-12" />
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+/** Header status: who is doing which step, or who is speaking or planning. */
+export function botGroupHeaderStatus(
+ group: Pick<BotGroupSummary, 'speakingBotIds' | 'planningBotId' | 'openPlan' | 'members'>,
+ displayName: (member: BotGroupMemberView) => string,
+ t: (key: string, options?: Record<string, unknown>) => string,
+): string | null {
+ const nameOf = (botId: string | null) => {
+ const member = group.members.find((candidate) => candidate.botId === botId);
+ return member ? displayName(member) : '';
+ };
+ const plan = group.openPlan;
+ if (plan?.status === 'running' && plan.currentStep !== null && plan.currentStepStatus === 'running') {
+ return t('bots.groupChat.header.stepRunning', { name: plan.currentBotName?.trim() || '', step: plan.currentStep + 1 });
+ }
+ if (group.planningBotId) return t('bots.groupChat.header.planning', { name: nameOf(group.planningBotId) });
+ const speaker = group.speakingBotIds[0];
+ if (speaker) return t('bots.groupChat.header.speaking', { name: nameOf(speaker) });
+ return null;
+}
+
+export function BotGroupHeaderStatusText({ text, className }: { text: string; className?: string }) {
+ return (
+ <span className={cn('flex min-w-0 items-center gap-1 text-[var(--status-bar-accent)]', className)}>
+ <span aria-hidden className="session-status-breathing inline-flex shrink-0">
+ <Sparkles size={11} />
+ </span>
+ <span className="min-w-0 truncate">{text}</span>
+ </span>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx b/apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx
index 1243637ed1..b9007f9185 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx
@@ -13,7 +13,6 @@ import type { ReactNode } from 'react';
import { Check, CircleAlert, CircleCheck, CircleDashed, Sparkles } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { CHAT_BODY_CLASS } from '@/components/chat/chatChrome';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
@@ -34,7 +33,9 @@ import type {
BotGroupPlanStepView,
BotGroupPlanView,
} from '../../../shared/botGroupChat';
+import { formatBotTimelineClock } from '@cindy/maker-shared/botTimeline';
import { BotAvatar } from './BotAvatar';
+import { BotGroupElapsed } from './BotGroupElapsed';
import {
botGroupPathBasename,
botGroupPlanFilePath,
@@ -96,22 +97,33 @@ const STEP_STATUS_KEYS: Partial<Record<BotGroupPlanStepView['status'], string>>
failed: 'bots.groupChat.plan.stepFailed',
};
+/** Live facts for the step status: when the running step started, when done steps finished. */
+interface StepTiming {
+ runningSince: number | null;
+ /** Finish time per 1-based step, from its hand-off message. */
+ doneAt?: ReadonlyMap<number, number>;
+ locale: string;
+}
+
function StepRowContent({
plan,
step,
index,
identity,
muted,
+ timing,
}: {
plan: BotGroupPlanView;
step: BotGroupPlanStepView;
index: number;
identity: AvatarIdentity;
muted: boolean;
+ timing: StepTiming;
}) {
const { t } = useTranslation();
const started = plan.status !== 'proposed' && plan.status !== 'superseded' && plan.status !== 'dismissed';
const statusKey = started ? STEP_STATUS_KEYS[step.status] : undefined;
+ const doneAt = step.status === 'done' ? timing.doneAt?.get(index + 1) : undefined;
return (
<>
<span className="flex w-4 shrink-0 justify-center">
@@ -127,11 +139,18 @@ function StepRowContent({
{statusKey ? (
<span
className={cn(
- 'shrink-0 text-12',
+ 'shrink-0 text-12 tabular-nums',
step.status === 'running' ? 'text-[var(--status-bar-accent)]' : 'text-[var(--text-tertiary)]',
)}
>
{t(statusKey)}
+ {step.status === 'running' && plan.status === 'running' && timing.runningSince !== null ? (
+ <>
+ {' · '}
+ <BotGroupElapsed since={timing.runningSince} />
+ </>
+ ) : null}
+ {doneAt !== undefined ? ` · ${formatBotTimelineClock(doneAt, timing.locale)}` : null}
</span>
) : null}
</>
@@ -150,6 +169,7 @@ function EditableStepRow({
disabled,
allowRemove,
onEdit,
+ timing,
}: {
plan: BotGroupPlanView;
step: BotGroupPlanStepView;
@@ -160,6 +180,7 @@ function EditableStepRow({
/** Steps are removed only before 开始. */
allowRemove: boolean;
onEdit: (step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) => void;
+ timing: StepTiming;
}) {
const { t } = useTranslation();
const candidates = members.filter(member => isActiveBotGroupMember(member) && (!member.actorKind || member.actorKind === 'bot'));
@@ -175,7 +196,7 @@ function EditableStepRow({
'outline-none transition-colors enabled:hover:bg-[var(--model-item-hover)] focus-visible:bg-[var(--model-item-hover)] data-[state=open]:bg-[var(--model-item-hover)] disabled:opacity-60',
)}
>
- <StepRowContent plan={plan} step={step} index={index} identity={identity} muted={false} />
+ <StepRowContent plan={plan} step={step} index={index} identity={identity} muted={false} timing={timing} />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-56">
@@ -238,6 +259,9 @@ export function BotGroupPlanCard({
actionable,
reassignable = false,
pending,
+ runningSince = null,
+ doneAt,
+ locale = 'en',
onStart,
onDismiss,
onEditStep,
@@ -247,6 +271,11 @@ export function BotGroupPlanCard({
actionable: boolean;
reassignable?: boolean;
pending: BotGroupPlanCardAction | null;
+ /** When the running step started (its Session's turn, else the plan's last change). */
+ runningSince?: number | null;
+ /** Finish time of each done step (1-based), from its hand-off message. */
+ doneAt?: ReadonlyMap<number, number>;
+ locale?: string;
onStart: () => void;
onDismiss: () => void;
onEditStep: (step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) => void;
@@ -258,12 +287,15 @@ export function BotGroupPlanCard({
const muted = plan.status === 'superseded' || plan.status === 'dismissed';
const finalNote = FINAL_NOTE_KEYS[plan.status];
const busy = pending !== null;
+ const timing: StepTiming = { runningSince, doneAt, locale };
+ const canReassign = reassignable && plan.steps.some((step) => step.status === 'pending' || step.status === 'failed');
+ const underWay = plan.status === 'running' || plan.status === 'waiting';
return (
<div data-testid="bot-group-plan" data-plan-status={plan.status} className="flex min-w-0 flex-col">
- <p className={`min-w-0 text-[var(--msg-assistant-text)] ${CHAT_BODY_CLASS}`}>
+ <p className="min-w-0 text-14 font-normal leading-relaxed text-[var(--msg-assistant-text)]">
{t('bots.groupChat.plan.intro', { count: plan.steps.length })}
</p>
- <div className="mt-1.5 w-full max-w-[440px] overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]">
+ <div className="mt-1.5 w-full max-w-[520px] overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]">
<ol className="flex flex-col py-1.5">
{plan.steps.map((step, index) => {
const identity = stepIdentity(step, members);
@@ -281,10 +313,11 @@ export function BotGroupPlanCard({
disabled={busy}
allowRemove={actionable}
onEdit={onEditStep}
+ timing={timing}
/>
) : (
<div data-testid="bot-group-plan-step" className={STEP_ROW_CLASS}>
- <StepRowContent plan={plan} step={step} index={index} identity={identity} muted={muted} />
+ <StepRowContent plan={plan} step={step} index={index} identity={identity} muted={muted} timing={timing} />
</div>
)}
</li>
@@ -292,7 +325,7 @@ export function BotGroupPlanCard({
})}
</ol>
{actionable ? (
- <div className="flex flex-wrap items-center gap-2 px-3.5 pb-3 pt-1">
+ <div className="flex flex-wrap items-center gap-2 px-3.5 pb-1 pt-1">
<Button
type="button"
variant="cta"
@@ -316,17 +349,19 @@ export function BotGroupPlanCard({
>
{t('bots.groupChat.plan.dismiss')}
</Button>
- <span className="ml-auto min-w-0 truncate text-12 text-[var(--text-tertiary)]">
- {t('bots.groupChat.plan.editHint')}
- </span>
+ </div>
+ ) : null}
+ {actionable || underWay ? (
+ // Card footer: how it runs on the left, what the steps offer on the right.
+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5 border-t border-[var(--border-default)] px-3.5 py-1.5 text-11 leading-4 text-[var(--text-tertiary)]">
+ <span className="min-w-0">{t('bots.groupChat.plan.pauseNote')}</span>
+ {actionable || canReassign ? (
+ <span className="ml-auto min-w-0 truncate">{t('bots.groupChat.plan.editHint')}</span>
+ ) : null}
</div>
) : null}
</div>
- {actionable ? (
- <p className="mt-1.5 text-12 text-[var(--text-tertiary)]">{t('bots.groupChat.plan.pauseNote')}</p>
- ) : finalNote ? (
- <p className="mt-1.5 text-12 text-[var(--text-tertiary)]">{t(finalNote)}</p>
- ) : null}
+ {finalNote ? <p className="mt-1.5 text-12 text-[var(--text-tertiary)]">{t(finalNote)}</p> : null}
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
index b9e27e5a58..910ba83b1d 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
@@ -9,6 +9,10 @@
* 分工(docs/product-rules/bot-group-chat.md §7):负责人正在安排时写「谁 正在安排…」,
* 某一步进行中写「分工 k/n · 谁 正在做」,两者同样用运行中标记;安排待开始、做完一步
* 等继续或没做完时,第二行换成对应的提示,提醒用户回来看看。
+ *
+ * 未读角标是真实条数:main 随摘要给出最近(至多 99 条)别人发来的消息时间
+ * (`incomingMessageTimes`),与本机读位比较;旧宿主没有这份列表时只显示 1。多人群里
+ * 别人带来的伙伴按「伙伴名 (主人昵称)」显示(与群聊页同一规则)。
*/
import type { ReactNode } from 'react';
import { Sparkles } from 'lucide-react';
@@ -27,7 +31,8 @@ import {
isRunningBotGroupSidebarPreview,
type BotGroupSidebarPlanPreview,
} from './botGroupPresentation';
-import { isBotGroupUnread } from './botReadState';
+import { botGroupMemberDisplayName } from './BotGroupTimelineModel';
+import { botGroupUnreadCount } from './botReadState';
import { NavigationCountBadge } from '@/components/sidebar/NavigationCountBadge';
import { formatBotListTimestamp } from './botListDisplay';
import type { BotProfile } from './botStore';
@@ -97,7 +102,7 @@ export function BotGroupSidebarRow({
speakingLaneActivity(bots.find((bot) => bot.id === member.botId), islandActivity));
const activity = activities[0];
const waiting = activities.some((item) => item?.phase === 'needs-interaction');
- const names = speakers.map((member) => member.name).join(t('bots.groupChat.memberSeparator'));
+ const names = speakers.map(botGroupMemberDisplayName).join(t('bots.groupChat.memberSeparator'));
// Planning and a step in progress read as one line; a step waiting for the user's
// go-ahead keeps the confirmation hint below instead.
const planLine =
@@ -154,6 +159,7 @@ export function BotGroupSidebarRow({
};
const mutedClass = selected ? 'opacity-70' : 'text-[var(--sidebar-list-muted)]';
+ const unread = botGroupUnreadCount(group);
const timestamp = formatBotListTimestamp(
group.speakingBotIds.length > 0 ? now : group.lastMessage?.createdAt ?? group.updatedAt,
now,
@@ -185,7 +191,7 @@ export function BotGroupSidebarRow({
)}
>
{timestamp}
- <NavigationCountBadge count={isBotGroupUnread(group) ? 1 : 0} label={t('sidebar.teammateUnreadCount', { count: 1 })} className="ml-auto mt-1 w-fit" />
+ <NavigationCountBadge count={unread} label={t('sidebar.teammateUnreadCount', { count: unread })} className="ml-auto mt-1 w-fit" />
</span>
</button>
);
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx b/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
new file mode 100644
index 0000000000..f318211c24
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
@@ -0,0 +1,464 @@
+/**
+ * 群聊时间线的一行(主时间线与话题面板共用),Telegram / Slack 式的紧凑排版:
+ *
+ * - 自己的消息靠右、浅色气泡;其他人(伙伴与别的人)一律靠左平铺:28px 头像 + 名字
+ * (text-13)+ 时刻(text-11),正文在下。同一作者五分钟内的连续消息合并:后续行不再带
+ * 头像和名字,时刻只在悬停时出现在左侧槽位。
+ * - 引用块在正文上方,表情回应在正文下方;消息操作栏(复制、分享、引用回复、话题、表情、
+ * 时间)悬停时浮在右上角,键盘聚焦与触屏时常显。
+ * - @ 点名在所有消息里都高亮:正文仍交给 MarkdownRenderer,高亮走 CSS Custom Highlight
+ * (不改 Markdown 的 DOM,也就不会和 React 抢节点)。
+ * - 轮次结束、分工结束与系统提示是居中的一行小字。
+ *
+ * 行用 `memo` 包住:父组件只在这条消息(或它的引用、安排快照、高亮状态)真的变了时才会
+ * 让它重绘;回调一律是父组件的稳定引用,按消息 id 调用。
+ */
+import { memo, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatBotTimelineClock, formatBotTimelineDate } from '@cindy/maker-shared/botTimeline';
+import { ChatImageView } from '@/components/chat/ChatImageView';
+import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
+import { ShareMessageCheckbox } from '@/components/chat/ShareMessageCheckbox';
+import { TextLightbox } from '@/components/chat/TextLightbox';
+import { UserAttachmentChip } from '@/components/chat/UserAttachmentChip';
+import { Button } from '@/components/ui/button';
+import { SHARE_MESSAGE_ATTR, SHARE_SESSION_ATTR } from '@/lib/shareConversationImage';
+import { cn } from '@/lib/utils';
+import type {
+ BotGroupAttachment,
+ BotGroupMemberView,
+ BotGroupPlanStepView,
+ BotGroupPlanView,
+ BotGroupQuoteDisplay,
+ BotGroupQuoteView,
+} from '../../../shared/botGroupChat';
+import { isBotGroupRuntimeFailureCode } from '../../../shared/botGroupChat';
+import { BotAvatar } from './BotAvatar';
+import { splitBotGroupMessageAttachments } from './botGroupAttachments';
+import { splitBotGroupMentionSegments } from './botGroupMentions';
+import { botGroupNoticeKey } from './botGroupPresentation';
+import {
+ BotGroupHandoffFiles,
+ BotGroupOrganizerTag,
+ BotGroupPlanCard,
+ BotGroupPlanEndDivider,
+ type BotGroupPlanCardAction,
+} from './BotGroupPlan';
+import { BotGroupQuoteBlock } from './BotGroupQuote';
+import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';
+import { BotGroupTaskCard } from './BotGroupTaskCard';
+import type { BotGroupTimelineMessage } from './BotGroupTimelineModel';
+import { ChatMessageHoverActions, ChatMessageReactions } from './ChatServerControls';
+
+/** Group chat body: one step smaller than a task's reading text, Slack-dense. */
+export const BOT_GROUP_BODY_CLASS = 'text-14 font-normal leading-relaxed';
+
+// ---- @ mention highlight ----------------------------------------------------------------
+
+const MENTION_HIGHLIGHT = 'bot-group-mention';
+const mentionRanges = new Map<object, Range[]>();
+let highlightSyncQueued = false;
+let highlightStyleInstalled = false;
+
+type HighlightRegistry = { set: (name: string, value: unknown) => void; delete: (name: string) => void };
+function highlightApi(): { registry: HighlightRegistry; Highlight: new (...ranges: Range[]) => unknown } | null {
+ const registry = (globalThis as { CSS?: { highlights?: HighlightRegistry } }).CSS?.highlights;
+ const Highlight = (globalThis as { Highlight?: new (...ranges: Range[]) => unknown }).Highlight;
+ return registry && typeof Highlight === 'function' ? { registry, Highlight } : null;
+}
+
+function installHighlightStyle(): void {
+ if (highlightStyleInstalled || typeof document === 'undefined') return;
+ highlightStyleInstalled = true;
+ const style = document.createElement('style');
+ style.dataset.botGroupMention = '';
+ // Same chip colors as the composer's mention chip; both modes follow the tokens.
+ style.textContent = `::highlight(${MENTION_HIGHLIGHT}) { background-color: var(--surface-chip); color: var(--text-primary); }`;
+ document.head.append(style);
+}
+
+function syncMentionHighlight(): void {
+ if (highlightSyncQueued) return;
+ highlightSyncQueued = true;
+ queueMicrotask(() => {
+ highlightSyncQueued = false;
+ const api = highlightApi();
+ if (!api) return;
+ const ranges = [...mentionRanges.values()].flat();
+ if (ranges.length === 0) api.registry.delete(MENTION_HIGHLIGHT);
+ else api.registry.set(MENTION_HIGHLIGHT, new api.Highlight(...ranges));
+ });
+}
+
+function collectMentionRanges(root: HTMLElement, labels: readonly string[]): Range[] {
+ const ranges: Range[] = [];
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode() as Text | null; node; node = walker.nextNode() as Text | null) {
+ if (!node.data.includes('@') || node.parentElement?.closest('pre, code')) continue;
+ let offset = 0;
+ for (const segment of splitBotGroupMentionSegments(node.data, labels)) {
+ if (segment.mention) {
+ const range = document.createRange();
+ range.setStart(node, offset);
+ range.setEnd(node, offset + segment.text.length);
+ ranges.push(range);
+ }
+ offset += segment.text.length;
+ }
+ }
+ return ranges;
+}
+
+/** Message text as Markdown, with `@名字` of known members highlighted like a chip. */
+function BotGroupMessageText({ content, mentionLabels }: { content: string; mentionLabels: readonly string[] }) {
+ const ref = useRef<HTMLDivElement>(null);
+ const labelsKey = mentionLabels.join('\u0000');
+ useLayoutEffect(() => {
+ const root = ref.current;
+ if (!root || !content.includes('@') || !highlightApi()) return;
+ installHighlightStyle();
+ const owner = {};
+ const refresh = () => {
+ mentionRanges.set(owner, collectMentionRanges(root, mentionLabels));
+ syncMentionHighlight();
+ };
+ refresh();
+ // Markdown may finish later (code highlighting, lazy blocks); follow its DOM.
+ const observer = typeof MutationObserver === 'undefined' ? null : new MutationObserver(refresh);
+ observer?.observe(root, { childList: true, subtree: true, characterData: true });
+ return () => {
+ observer?.disconnect();
+ mentionRanges.delete(owner);
+ syncMentionHighlight();
+ };
+ // labelsKey stands in for the label array.
+ }, [content, labelsKey]);
+ return (
+ <div ref={ref} className="min-w-0 break-words">
+ <MarkdownRenderer workingDir="" content={content} allowPrivilegedLinks={false} />
+ </div>
+ );
+}
+
+// ---- Pieces ----------------------------------------------------------------------------
+
+/** Quiet pill after an author name (负责人, 第 k 步, 某某的主人). */
+export function BotGroupNameTag({ children }: { children: ReactNode }) {
+ return (
+ <span className="inline-flex min-h-[18px] max-w-[12rem] shrink-0 select-none items-center truncate rounded-full bg-[var(--surface-chip)] px-1.5 py-px text-11 font-medium leading-tight text-[var(--text-secondary)]">
+ {children}
+ </span>
+ );
+}
+
+/** One line per local day; it sticks to the top while that day scrolls by. */
+export function BotGroupDateDivider({ timestamp, locale }: { timestamp: number; locale: string }) {
+ return (
+ <div data-testid="bot-group-date-divider" className="sticky top-1 z-[5] mt-4 flex select-none justify-center first:mt-0">
+ <span className="rounded-full border border-[var(--border-default)] bg-[var(--surface)] px-2.5 py-0.5 text-11 leading-4 text-[var(--text-tertiary)]">
+ {formatBotTimelineDate(timestamp, locale)}
+ </span>
+ </div>
+ );
+}
+
+/**
+ * A user message's images and files, drawn like a task's user bubble: each image as the
+ * same attached-image view (click for the lightbox, right-click to copy or reveal), files
+ * as the same chips (text preview or the system app, right-click menu).
+ */
+export function BotGroupUserAttachments({ attachments = [], align = 'left' }: { attachments?: readonly BotGroupAttachment[]; align?: 'left' | 'right' }) {
+ const [textPreview, setTextPreview] = useState<{ path: string; name: string } | null>(null);
+ const chipRef = useRef<HTMLElement | null>(null);
+ const { images, files } = splitBotGroupMessageAttachments(attachments);
+ if (images.length === 0 && files.length === 0) return null;
+ return (
+ <>
+ {images.map((image) => (
+ <ChatImageView key={image.id} src={image.url} filename={image.name} variant="user-attached" />
+ ))}
+ {files.length > 0 ? (
+ <div className={cn('flex flex-wrap items-end gap-1.5', align === 'right' && 'justify-end')}>
+ {files.map((file) => (
+ <UserAttachmentChip
+ key={file.id}
+ file={{ name: file.name, path: file.path }}
+ onOpenTextPreview={(chip) => {
+ chipRef.current = chip;
+ setTextPreview({ path: file.path, name: file.name });
+ }}
+ />
+ ))}
+ </div>
+ ) : null}
+ {textPreview ? (
+ <TextLightbox
+ filePath={textPreview.path}
+ fileName={textPreview.name}
+ triggerRef={chipRef}
+ onClose={() => setTextPreview(null)}
+ />
+ ) : null}
+ </>
+ );
+}
+
+// ---- The row ---------------------------------------------------------------------------
+
+export interface BotGroupTimelineItemProps {
+ message: BotGroupTimelineMessage;
+ /** Same author as the row above within five minutes: no avatar or name. */
+ continued: boolean;
+ /** Author name as this reader sees it (`伙伴名 (主人昵称)` where it applies). */
+ authorName: string;
+ /** Avatar identity of the author (the organizer on a 安排卡). */
+ avatar?: { name: string; avatar: string | null; avatarUrl?: string | null; avatarColor: string | null };
+ /** Bots a human author brought into the group: 「某某的主人」. */
+ ownerOf?: string;
+ /** 「第 k 步」 on a step hand-off. */
+ stepNumber?: number;
+ members: readonly BotGroupMemberView[];
+ mentionLabels: readonly string[];
+ locale: string;
+ shareScope: string;
+ sharing: boolean;
+ /** Server group id: reactions and the toolbar's reaction picker. */
+ reactionGroupId?: string;
+ quoteDisplay?: BotGroupQuoteDisplay;
+ onLocateQuote?: (quote: BotGroupQuoteView) => void;
+ onQuote?: (messageId: string) => void;
+ onOpenThread?: (messageId: string) => void;
+ onChanged: () => void;
+ highlighted?: boolean;
+ /** Focusable only as a jump target, so a click elsewhere keeps its usual focus. */
+ focusable?: boolean;
+ /** Arrived while the reader was watching: fade in (opacity only). */
+ entering?: boolean;
+ // Round and plan pieces; the Thread panel leaves them out.
+ canContinue?: boolean;
+ continuing?: boolean;
+ onContinue?: () => void;
+ plan?: BotGroupPlanView;
+ planActionable?: boolean;
+ planReassignable?: boolean;
+ planPending?: BotGroupPlanCardAction | null;
+ /** Live start of the plan's running step (its Session's turn), for the elapsed time. */
+ planRunningSince?: number | null;
+ /** Finish time of each done step (1-based), read off its hand-off message. */
+ planDoneAt?: ReadonlyMap<number, number>;
+ onPlanAction?: (action: 'start' | 'dismiss', planId: string) => void;
+ onEditStep?: (planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) => void;
+}
+
+function Row({ message, highlighted, focusable, entering, block, children }: {
+ message: BotGroupTimelineMessage; highlighted?: boolean; focusable?: boolean; entering?: boolean;
+ /** Space above: a new author block, a merged line, or a compact system line. */
+ block: 'author' | 'continued' | 'system';
+ children: ReactNode;
+}) {
+ return (
+ <div
+ data-bot-group-message-id={message.id}
+ tabIndex={focusable ? -1 : undefined}
+ className={cn(
+ 'rounded-lg outline-none transition-colors first:mt-0',
+ block === 'continued' ? 'mt-0.5' : block === 'author' ? 'mt-3.5' : 'mt-3',
+ entering && 'animate-fade-in motion-reduce:animate-none',
+ highlighted && 'bg-[hsl(var(--search-match-bg))] ring-1 ring-[var(--border-default)]',
+ )}
+ >
+ {children}
+ </div>
+ );
+}
+
+function SystemLine({ children, testId }: { children: ReactNode; testId?: string }) {
+ return (
+ <div data-testid={testId} className="flex select-none items-center gap-3 text-12 text-[var(--text-tertiary)]">
+ <span aria-hidden className="h-px min-w-6 flex-1 bg-[var(--border-default)]" />
+ {children}
+ <span aria-hidden className="h-px min-w-6 flex-1 bg-[var(--border-default)]" />
+ </div>
+ );
+}
+
+function BotGroupTimelineItemImpl(props: BotGroupTimelineItemProps) {
+ const { t } = useTranslation();
+ const { message, continued, authorName, members, mentionLabels, locale, shareScope, sharing } = props;
+ const rowProps = { message, highlighted: props.highlighted, focusable: props.focusable, entering: props.entering };
+
+ if (message.kind === 'round-end') {
+ return (
+ <Row {...rowProps} block="system">
+ <SystemLine>
+ <span>{t('bots.groupChat.timeline.roundEnded')}</span>
+ {props.canContinue && props.onContinue ? (
+ <Button variant="secondary" tone="quiet" size="sm" compact type="button" loading={props.continuing} onClick={props.onContinue}>
+ {t('bots.groupChat.timeline.continue')}
+ </Button>
+ ) : null}
+ </SystemLine>
+ </Row>
+ );
+ }
+ if (message.kind === 'plan-end') {
+ return (
+ <Row {...rowProps} block="system">
+ <BotGroupPlanEndDivider stepCount={props.plan ? props.plan.steps.length : null} />
+ </Row>
+ );
+ }
+ if (message.kind === 'notice' || message.authorKind === 'system') {
+ const name = message.authorName.trim() || authorName;
+ if (isBotGroupRuntimeFailureCode(message.runtimeFailureCode)) {
+ return (
+ <Row {...rowProps} block="system">
+ <BotGroupRuntimeFailureNotice name={name} code={message.runtimeFailureCode} />
+ </Row>
+ );
+ }
+ const key = botGroupNoticeKey(message.noticeCode, message.planId !== null);
+ return (
+ <Row {...rowProps} block="system">
+ <p className="select-none text-center text-12 leading-5 text-[var(--text-tertiary)]">{key ? t(key, { name }) : message.content}</p>
+ </Row>
+ );
+ }
+
+ const shareable = message.kind === 'message' && !message.pending;
+ const shareAttrs = shareable ? { [SHARE_SESSION_ATTR]: shareScope, [SHARE_MESSAGE_ATTR]: message.id } : {};
+ const hasText = message.content.trim().length > 0;
+ const quote = props.quoteDisplay ? (
+ <BotGroupQuoteBlock
+ display={props.quoteDisplay}
+ onLocate={props.onLocateQuote && message.quote ? () => props.onLocateQuote!(message.quote!) : undefined}
+ align={message.authorKind === 'user' && message.isSelf !== false ? 'right' : 'left'}
+ />
+ ) : null;
+ const actions = shareable ? (
+ <ChatMessageHoverActions
+ groupId={props.reactionGroupId}
+ shareScope={shareScope}
+ message={message}
+ align={message.authorKind === 'user' && message.isSelf !== false ? 'right' : 'left'}
+ onQuote={props.onQuote ? () => props.onQuote!(message.id) : undefined}
+ onReply={props.onOpenThread ? () => props.onOpenThread!(message.id) : undefined}
+ onChanged={props.onChanged}
+ />
+ ) : null;
+
+ if (message.kind === 'message' && message.authorKind === 'user' && message.isSelf !== false) {
+ return (
+ <Row {...rowProps} block={continued ? 'continued' : 'author'}>
+ <article
+ {...shareAttrs}
+ aria-busy={message.pending ? true : undefined}
+ className={cn('group/message relative flex min-w-0 justify-end rounded-lg py-0.5', sharing && 'ml-10')}
+ >
+ {sharing && shareable ? <ShareMessageCheckbox clientId={message.id} /> : null}
+ <div className={cn('flex min-w-0 max-w-[78%] flex-col items-end gap-1.5 transition-opacity', message.pending && 'opacity-60')}>
+ {quote}
+ <BotGroupUserAttachments attachments={message.attachments} align="right" />
+ {hasText ? (
+ <div
+ data-testid="bot-group-self-bubble"
+ className={`max-w-full rounded-xl border border-[var(--msg-user-border)] bg-[var(--msg-user-bg)] px-3 py-1.5 text-[var(--msg-user-text)] ${BOT_GROUP_BODY_CLASS}`}
+ >
+ <BotGroupMessageText content={message.content} mentionLabels={mentionLabels} />
+ </div>
+ ) : null}
+ {message.pending ? <span className="sr-only">{t('bots.groupChat.timeline.sending')}</span> : null}
+ <ChatMessageReactions groupId={props.reactionGroupId} message={message} align="right" onChanged={props.onChanged} />
+ </div>
+ {actions}
+ </article>
+ </Row>
+ );
+ }
+
+ // A server plan is signed by its human creator; present the organizer without changing authorship.
+ const isPlanCard = message.kind === 'plan';
+ const timed = Number.isFinite(message.createdAt) && message.createdAt > 0;
+ const clock = timed ? formatBotTimelineClock(message.createdAt, locale) : '';
+ const dateTime = timed ? new Date(message.createdAt).toISOString() : undefined;
+ return (
+ <Row {...rowProps} block={continued ? 'continued' : 'author'}>
+ <article
+ {...shareAttrs}
+ className={cn(
+ 'group/message relative -mx-2 flex min-w-0 items-start gap-2.5 rounded-lg px-2 py-0.5 transition-colors hover:bg-[var(--surface-hover-soft)]',
+ sharing && 'ml-8',
+ )}
+ >
+ {sharing && shareable ? <ShareMessageCheckbox clientId={message.id} /> : null}
+ <div className="flex w-7 shrink-0 justify-end">
+ {continued ? (
+ <time
+ dateTime={dateTime}
+ className="select-none pt-0.5 text-11 leading-5 tabular-nums text-[var(--text-tertiary)] opacity-0 group-hover/message:opacity-100"
+ >
+ {clock}
+ </time>
+ ) : (
+ <BotAvatar bot={props.avatar ?? { name: authorName, avatar: null, avatarColor: null }} size="sm" />
+ )}
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col">
+ {!continued ? (
+ <span className="flex min-w-0 select-none items-baseline gap-1.5">
+ <span className="min-w-0 truncate text-13 font-medium leading-5 text-[var(--text-primary)]">{authorName}</span>
+ {isPlanCard ? <BotGroupOrganizerTag /> : null}
+ {props.stepNumber ? <BotGroupNameTag>{t('bots.groupChat.timeline.stepTag', { count: props.stepNumber })}</BotGroupNameTag> : null}
+ {props.ownerOf ? <BotGroupNameTag>{t('bots.groupChat.ownerOf', { name: props.ownerOf })}</BotGroupNameTag> : null}
+ {timed ? (
+ <time dateTime={dateTime} className="shrink-0 text-11 tabular-nums text-[var(--text-tertiary)]">
+ {clock}
+ </time>
+ ) : null}
+ </span>
+ ) : null}
+ {isPlanCard ? (
+ <div className="mt-1">
+ <BotGroupPlanCard
+ plan={props.plan}
+ members={members}
+ actionable={props.planActionable ?? false}
+ reassignable={props.planReassignable ?? false}
+ pending={props.planPending ?? null}
+ runningSince={props.planRunningSince ?? null}
+ doneAt={props.planDoneAt}
+ locale={locale}
+ onStart={() => { if (message.planId) props.onPlanAction?.('start', message.planId); }}
+ onDismiss={() => { if (message.planId) props.onPlanAction?.('dismiss', message.planId); }}
+ onEditStep={(step, action, botId) => { if (message.planId) props.onEditStep?.(message.planId, step, action, botId); }}
+ />
+ </div>
+ ) : (
+ <div className="flex min-w-0 flex-col gap-1">
+ {quote}
+ {/* A task this teammate started from the group; mine is live, another owner's is a snapshot. */}
+ {message.task ? (
+ <BotGroupTaskCard
+ task={message.task}
+ owned={props.members.find(m => m.botId === message.authorBotId)?.isOwned !== false}
+ />
+ ) : null}
+ {hasText ? (
+ <div className={`min-w-0 text-[var(--msg-assistant-text)] ${BOT_GROUP_BODY_CLASS}`}>
+ <BotGroupMessageText content={message.content} mentionLabels={mentionLabels} />
+ </div>
+ ) : null}
+ <BotGroupUserAttachments attachments={message.attachments} />
+ <BotGroupHandoffFiles files={message.files ?? []} workDir={props.plan?.workDir ?? null} />
+ <ChatMessageReactions groupId={props.reactionGroupId} message={message} onChanged={props.onChanged} />
+ </div>
+ )}
+ </div>
+ {actions}
+ </article>
+ </Row>
+ );
+}
+
+export const BotGroupTimelineItem = memo(BotGroupTimelineItemImpl);
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts b/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts
new file mode 100644
index 0000000000..011ebb681f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts
@@ -0,0 +1,322 @@
+/**
+ * 群聊时间线的纯数据层(不挂 React,便于单测):
+ *
+ * - 推送刷新的增量合并:main 每次只回最新一页(BOT_GROUP_PAGE_SIZE),这里把它并进屏幕上
+ * 已有的消息,而不是整页替换——被新消息挤出最新页的旧消息留在「更早」里,不会出现缺口或
+ * 顶部跳动;最新页覆盖的序号区间内以 main 为准(编辑、删除、表情、话题数就地更新)。
+ * - 引用稳定:内容没变的消息、安排沿用上一份对象,memo 过的消息行就不会重绘。
+ * - 乐观发送:发出那一刻先插一条「发送中」的自己的消息,main 的详情里出现对应消息
+ * (按 send 返回的 messageId,返回前按序号之后的同文自发消息)后撤掉。
+ * - Telegram / Slack 式排版:同一作者五分钟内的连续消息合并(只首条带头像与名字),
+ * 每个自然日一条日期分隔。
+ * - 多人群的显示名「伙伴名 (主人昵称)」与人类成员的「某某的主人」小标。
+ */
+import { collectBotTimelineDateDividers, isSameBotTimelineDay } from '@cindy/maker-shared/botTimeline';
+import type {
+ BotGroupAttachment,
+ BotGroupDetail,
+ BotGroupMemberView,
+ BotGroupMention,
+ BotGroupMessageView,
+ BotGroupPlanStepView,
+ BotGroupPlanView,
+ BotGroupQuoteView,
+} from '../../../shared/botGroupChat';
+import { mergeBotGroupMessages, mergeBotGroupPlans } from './botGroupPresentation';
+
+/** A timeline row; `pending` marks the optimistic copy of a message still on its way. */
+export type BotGroupTimelineMessage = BotGroupMessageView & { pending?: true };
+
+/** Consecutive messages by one author within this window share one header. */
+export const BOT_GROUP_MERGE_WINDOW_MS = 5 * 60 * 1_000;
+
+export interface BotGroupLoadedTimeline {
+ group: BotGroupDetail;
+ /** Messages on screen that the latest page no longer covers (paged in, or pushed out). */
+ older: BotGroupMessageView[];
+ olderPlans: BotGroupPlanView[];
+ olderHasMore: boolean;
+}
+
+const signatures = new WeakMap<object, string>();
+function signature(value: object): string {
+ let cached = signatures.get(value);
+ if (cached === undefined) {
+ cached = JSON.stringify(value);
+ signatures.set(value, cached);
+ }
+ return cached;
+}
+
+/**
+ * `next` with every entry whose content equals the previous entry of the same id replaced by
+ * that previous object; the previous array itself when nothing changed at all.
+ */
+export function stabilizeById<T extends { id: string }>(
+ previous: readonly T[],
+ next: readonly T[],
+ /** More earlier copies to reuse (e.g. messages that moved between pages). */
+ pool: readonly T[] = [],
+): T[] {
+ if (previous === next) return next as T[];
+ const byId = new Map([...pool, ...previous].map((item) => [item.id, item]));
+ let same = previous.length === next.length;
+ const result = next.map((item, index) => {
+ const old = byId.get(item.id);
+ if (old && (old === item || signature(old) === signature(item))) {
+ if (previous[index] !== old) same = false;
+ return old;
+ }
+ same = false;
+ return item;
+ });
+ return same ? (previous as T[]) : result;
+}
+
+/**
+ * Merges a push refresh's latest page into the timeline on screen. Inside the page's range the
+ * page wins; anything displayed below it stays (as `older`), so a message pushed out of the
+ * newest page by new ones never disappears. A page that is the whole history drops the rest.
+ */
+export function mergeBotGroupLatestPage(
+ previous: BotGroupLoadedTimeline,
+ next: BotGroupDetail,
+): BotGroupLoadedTimeline {
+ const page = next.messages;
+ const floor = page.reduce((min, message) => Math.min(min, message.sequence), Number.POSITIVE_INFINITY);
+ // A page that says nothing comes before it is the whole recent history: whatever the last
+ // latest page showed below it is gone. Pages opened through 「查看更早」 stay as they were;
+ // their quoted originals are re-checked separately.
+ const pushedOut = next.hasMoreBefore
+ ? previous.group.messages.filter((message) => message.sequence < floor)
+ : [];
+ const older = pushedOut.length > 0
+ ? stabilizeById(previous.older, mergeBotGroupMessages(previous.older, pushedOut))
+ : previous.older;
+ // The first rows moving down take over what the old latest page said about earlier history.
+ const olderHasMore = pushedOut.length > 0 && previous.older.length === 0 ? previous.group.hasMoreBefore : previous.olderHasMore;
+ const messages = stabilizeById(previous.group.messages, page, previous.older);
+ const plans = stabilizeById(previous.group.plans, next.plans, previous.olderPlans);
+ // Plans the pushed-out messages point at stay with them.
+ const olderPlans = pushedOut.length > 0
+ ? stabilizeById(previous.olderPlans, mergeBotGroupPlans(previous.olderPlans, previous.group.plans))
+ : previous.olderPlans;
+ // Nothing moved: hand back the same object so the page skips the render entirely.
+ if (messages === previous.group.messages && plans === previous.group.plans && older === previous.older
+ && olderPlans === previous.olderPlans
+ && olderHasMore === previous.olderHasMore
+ && signature({ ...next, messages: null, plans: null }) === signature({ ...previous.group, messages: null, plans: null })) {
+ return previous;
+ }
+ return {
+ group: { ...next, messages, plans },
+ older,
+ olderPlans,
+ olderHasMore,
+ };
+}
+
+// ---- Optimistic sends -------------------------------------------------------------------
+
+export interface BotGroupPendingSend {
+ clientId: string;
+ text: string;
+ mentions: BotGroupMention;
+ attachments: BotGroupAttachment[];
+ quote: BotGroupQuoteView | null;
+ createdAt: number;
+ /** Last real sequence on screen when it was sent; its echo comes after this. */
+ afterSequence: number;
+ /** Set once main accepted it. */
+ messageId?: string;
+}
+
+export function pendingBotGroupMessageId(clientId: string): string {
+ return `pending:${clientId}`;
+}
+
+/** The optimistic row for a send still on its way. */
+export function pendingBotGroupMessage(send: BotGroupPendingSend): BotGroupTimelineMessage {
+ return {
+ id: pendingBotGroupMessageId(send.clientId),
+ // Shown after every real row; never used for paging or failure reconciliation.
+ sequence: Number.MAX_SAFE_INTEGER,
+ kind: 'message',
+ authorKind: 'user',
+ isSelf: true,
+ authorBotId: null,
+ authorName: '',
+ content: send.text,
+ mentions: send.mentions,
+ noticeCode: null,
+ planId: null,
+ files: [],
+ attachments: send.attachments,
+ ...(send.quote ? { quote: send.quote } : {}),
+ createdAt: send.createdAt,
+ pending: true,
+ };
+}
+
+function isOwnMessage(message: BotGroupMessageView): boolean {
+ return message.kind === 'message' && message.authorKind === 'user' && message.isSelf !== false;
+}
+
+const NO_MATCHES: ReadonlyMap<string, string> = new Map();
+
+/**
+ * Which pending sends have shown up, as clientId → message id. A send main accepted matches its
+ * message id; before the answer it matches the first own message after it with the same text and
+ * as many attachments (each message settles one send).
+ */
+export function matchBotGroupPendingSends(
+ pending: readonly BotGroupPendingSend[],
+ displayed: readonly BotGroupMessageView[],
+): ReadonlyMap<string, string> {
+ if (pending.length === 0) return NO_MATCHES;
+ const ids = new Set(displayed.map((message) => message.id));
+ const claimed = new Set<string>();
+ const matches = new Map<string, string>();
+ for (const send of pending) {
+ if (send.messageId && ids.has(send.messageId)) {
+ claimed.add(send.messageId);
+ matches.set(send.clientId, send.messageId);
+ }
+ }
+ for (const send of pending) {
+ if (send.messageId) continue;
+ const text = send.text.trim();
+ const echo = displayed.find((message) => !claimed.has(message.id) && isOwnMessage(message)
+ && message.sequence > send.afterSequence && message.content.trim() === text
+ && message.attachments.length === send.attachments.length);
+ if (!echo) continue;
+ claimed.add(echo.id);
+ matches.set(send.clientId, echo.id);
+ }
+ return matches.size === 0 ? NO_MATCHES : matches;
+}
+
+/** Pending sends whose message has not shown up yet; the same array when nothing settled. */
+export function settleBotGroupPendingSends<T extends BotGroupPendingSend>(
+ pending: readonly T[],
+ displayed: readonly BotGroupMessageView[],
+): T[] {
+ const matches = matchBotGroupPendingSends(pending, displayed);
+ if (matches.size === 0) return pending as T[];
+ return pending.filter((send) => !matches.has(send.clientId));
+}
+
+// ---- Layout ----------------------------------------------------------------------------
+
+export interface BotGroupRowLayout {
+ /** Same author as the row above, within the merge window: no avatar or name. */
+ continued: boolean;
+ /** First message of a local day: the date to show above it. */
+ dateDivider: number | null;
+}
+
+function authorKey(message: BotGroupTimelineMessage): string | null {
+ // Notices, dividers, plan cards and step hand-offs (which carry a step tag) always open a block.
+ if (message.kind !== 'message' || message.authorKind === 'system' || message.planId) return null;
+ if (isOwnMessage(message)) return 'self';
+ return `${message.authorKind}:${message.authorBotId ?? ''}:${message.authorName}`;
+}
+
+export function layoutBotGroupTimeline(
+ messages: readonly BotGroupTimelineMessage[],
+): ReadonlyMap<string, BotGroupRowLayout> {
+ const dividers = collectBotTimelineDateDividers(messages.map((message) => ({ clientId: message.id, createdAt: message.createdAt })));
+ const layout = new Map<string, BotGroupRowLayout>();
+ let previous: BotGroupTimelineMessage | null = null;
+ for (const message of messages) {
+ const dateDivider = dividers.get(message.id) ?? null;
+ const key = authorKey(message);
+ const continued = previous !== null && dateDivider === null && key !== null && key === authorKey(previous)
+ && message.createdAt - previous.createdAt >= 0
+ && message.createdAt - previous.createdAt < BOT_GROUP_MERGE_WINDOW_MS
+ && isSameBotTimelineDay(previous.createdAt, message.createdAt);
+ layout.set(message.id, { continued, dateDivider });
+ previous = message;
+ }
+ return layout;
+}
+
+// ---- Names -----------------------------------------------------------------------------
+
+type NamedMember = Pick<BotGroupMemberView, 'name' | 'ownerName' | 'isOwned' | 'actorKind'>;
+
+function ownerSuffix(member: NamedMember): string | null {
+ const owner = member.ownerName?.trim();
+ return owner ? ` (${owner})` : null;
+}
+
+/** The member's own name without a 「 (主人昵称)」 suffix the host may already have added. */
+export function botGroupMemberBaseName(member: NamedMember): string {
+ const name = member.name.trim();
+ const suffix = ownerSuffix(member);
+ return suffix && name.endsWith(suffix) && name.length > suffix.length ? name.slice(0, -suffix.length) : name;
+}
+
+/**
+ * 多人群里别人带来的伙伴显示为 `伙伴名 (主人昵称)`(bot-group-chat.md §10);自己的伙伴、
+ * 人类成员与本地群照常显示名字。只用于展示,点名与身份仍按 id。
+ */
+export function botGroupMemberDisplayName(member: NamedMember): string {
+ const suffix = ownerSuffix(member);
+ if (suffix && member.isOwned === false && member.actorKind !== 'human') return `${botGroupMemberBaseName(member)}${suffix}`;
+ return member.name.trim();
+}
+
+/** Names of the bots a human member brought into the group (for 「某某的主人」). */
+export function botGroupOwnedBotNames(
+ member: Pick<BotGroupMemberView, 'actorId' | 'actorKind'> | undefined,
+ members: readonly BotGroupMemberView[],
+): string[] {
+ if (!member?.actorId || member.actorKind !== 'human') return [];
+ return members
+ .filter((candidate) => candidate.actorKind === 'bot' && candidate.ownerActorId === member.actorId)
+ .map(botGroupMemberBaseName)
+ .filter(Boolean);
+}
+
+// ---- Plans -----------------------------------------------------------------------------
+
+export interface BotGroupRunningStep {
+ plan: BotGroupPlanView;
+ step: BotGroupPlanStepView;
+ /** 1-based place in the plan, as shown to the user. */
+ index: number;
+ total: number;
+}
+
+/** The step of an open plan that is in progress right now. */
+export function runningBotGroupPlanStep(plan: BotGroupPlanView | null): BotGroupRunningStep | null {
+ if (!plan || plan.status !== 'running') return null;
+ const index = plan.steps.findIndex((step) => step.status === 'running');
+ if (index < 0) return null;
+ return { plan, step: plan.steps[index]!, index: index + 1, total: plan.steps.length };
+}
+
+/**
+ * 「第 k 步」 on a step's hand-off message: the plan step done by the message's author. When the
+ * author has several steps in the plan, the hand-offs are matched to them in order.
+ */
+export function botGroupHandoffStepNumbers(
+ messages: readonly BotGroupMessageView[],
+ plans: ReadonlyMap<string, BotGroupPlanView>,
+): ReadonlyMap<string, number> {
+ const numbers = new Map<string, number>();
+ const seen = new Map<string, number>();
+ for (const message of messages) {
+ if (message.kind !== 'message' || message.authorKind !== 'bot' || !message.planId || !message.authorBotId) continue;
+ const plan = plans.get(message.planId);
+ if (!plan) continue;
+ const key = `${plan.id}:${message.authorBotId}`;
+ const nth = seen.get(key) ?? 0;
+ const positions = plan.steps.flatMap((step, index) => (step.botId === message.authorBotId ? [index + 1] : []));
+ const number = positions[Math.min(nth, positions.length - 1)];
+ if (number !== undefined) numbers.set(message.id, number);
+ seen.set(key, nth + 1);
+ }
+ return numbers;
+}
diff --git a/apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx b/apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx
index 8abaa03ae6..f169f38e51 100644
--- a/apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx
@@ -1,8 +1,5 @@
-import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
+import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';
import { useNavigate } from 'react-router-dom';
-import { useTranslation } from 'react-i18next';
-import { Tip } from '@/components/ui/tooltip';
-import { SessionStatusIcon } from '@/features/cc-agent/sidebar/SessionStatusIcon';
import { useAgentIslandActivity } from '@/state/agentIslandActivity';
import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
import { makerChatStore } from '@/lib/makerChatStore';
@@ -19,19 +16,28 @@ import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import * as sessionService from '@/lib/sessionService';
import type { Session } from '@/lib/ccAgent.types';
import type { BotCollaborationMeta } from '../../../shared/botCollaboration';
+import type { BotDelegationView } from '../../../shared/botDelegation';
import { useBotDelegation } from './botDelegationLive';
-/** A reference to the original session, never a second task or completion state. */
-export function BotSessionTaskLink({
- card,
- sessionId,
-}: {
- card: BotCollaborationMeta;
- sessionId?: string;
-}) {
- const { t } = useTranslation();
+/** Live identity of the original session behind a task card; never a second task. */
+export interface BotTaskSessionRef {
+ row: BotDelegationView | null;
+ resolved: boolean;
+ stale: boolean;
+ targetId: string | null;
+ session: Session | null;
+ /** The parent's device when the bot chat is remote; local controls stay hidden there. */
+ sourceDeviceId: string | undefined;
+ activity: { compactDetail?: string; workingPhase?: string; startedAtMs?: number | null } | null;
+ /** Actual runtime state of the original session, independent of the delegation status. */
+ running: boolean;
+ originConflict: boolean;
+ open: () => void;
+}
+
+export function useBotTaskSession(card: BotCollaborationMeta, sessionId?: string): BotTaskSessionRef {
const navigate = useNavigate();
- const { row } = useBotDelegation(sessionId ?? card.parentSessionId, card.delegationId);
+ const { row, resolved, stale } = useBotDelegation(sessionId ?? card.parentSessionId, card.delegationId);
const targetId = row?.childSessionId ?? card.childSessionId;
const [session, setSession] = useState<Session | null>(null);
const activity = useAgentIslandActivity(targetId ?? '');
@@ -46,7 +52,6 @@ export function BotSessionTaskLink({
const rows = useMemo(() => (session ? [session] : []), [session]);
const { displayRunningSessionIds } = useSessionDisplayRunningState(rows, running);
const attention = useSessionAttentionKind(targetId ?? '');
- const [attached, setAttached] = useState(false);
useEffect(() => {
setSession(null);
if (!targetId) return;
@@ -96,30 +101,16 @@ export function BotSessionTaskLink({
if (!sourceDeviceId && id === targetId && isDataOwnerGenerationCurrent(owner))
setSession((current) => (current ? { ...current, ...patch } : current));
});
- const refreshAttached = () => {
- if (sourceDeviceId) return;
- void window.electronAPI.binding
- .resolveSession(targetId)
- .then((value) => {
- if (alive && isDataOwnerGenerationCurrent(owner)) setAttached(value.attached);
- })
- .catch(() => {});
- };
- setAttached(false);
- refreshAttached();
const offReset = sessionsStore.subscribe((change) => {
if (change === 'reset') {
alive = false;
setSession(null);
- setAttached(false);
}
});
- const offBinding = window.electronAPI.binding.onChanged(refreshAttached);
return () => {
alive = false;
offPatch();
offRemote();
- offBinding();
offReset();
};
}, [targetId, sessionId, card.parentSessionId]);
@@ -143,44 +134,21 @@ export function BotSessionTaskLink({
);
const targetDevice = targetId ? remoteProjectsStore.getSessionDeviceId(targetId) : undefined;
const originConflict = Boolean(targetDevice && targetDevice !== sourceDevice);
- const title =
- session?.title ||
- row?.title ||
- card.result?.title ||
- card.objective.split('\n')[0] ||
- t('bots.collab.backgroundTask');
- const preview = card.result?.text || session?.preview || row?.resultSummary || title;
- return (
- <Tip
- text={
- <span className="block max-w-xs whitespace-pre-wrap break-words text-12">
- {preview.slice(0, 500)}
- </span>
- }
- >
- <button
- type="button"
- disabled={!targetId || originConflict}
- className="inline-flex max-w-full items-baseline gap-1 text-left text-14 leading-6 text-[var(--text-primary)] underline decoration-[var(--border-default)] underline-offset-4 disabled:cursor-default"
- onClick={() => {
- if (targetId && !originConflict)
- void resolveSessionRoute(targetId, session ?? undefined).then((route) =>
- navigate(route),
- );
- }}
- >
- {session && (
- <SessionStatusIcon
- session={session}
- isRunning={currentActivity?.currentTurnActive === true}
- isAttached={attached}
- isActive={false}
- hasAttentionNotification={Boolean(attention)}
- size={13}
- />
- )}
- <span className="min-w-0 break-words">{title}</span>
- </button>
- </Tip>
- );
+ const live = session?.deviceLinkDeviceId ? remoteActivity : activity;
+ const open = useCallback(() => {
+ if (!targetId || originConflict) return;
+ void resolveSessionRoute(targetId, session ?? undefined).then((route) => navigate(route));
+ }, [navigate, originConflict, session, targetId]);
+ return {
+ row: row ?? null,
+ resolved: resolved === true,
+ stale: stale === true,
+ targetId: targetId ?? null,
+ session,
+ sourceDeviceId: sourceDevice,
+ activity: live ?? null,
+ running: currentActivity?.currentTurnActive === true,
+ originConflict,
+ open,
+ };
}
diff --git a/apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx b/apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx
index 802b89f433..e1abe780af 100644
--- a/apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx
@@ -1,19 +1,16 @@
-import { useBotDelegation } from './botDelegationLive';
-import { BotSessionTaskLink } from './BotSessionTaskLink';
-import { useId, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import type { BotCollaborationMeta } from '../../../shared/botCollaboration';
import { readBotCollaborationMeta } from '../../../shared/botCollaboration';
-import {
- ChatSessionFileProvider,
- useChatSessionFile,
-} from '@/components/chat/ChatSessionFileContext';
-import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
+import { BotTaskCard } from './BotCollaborationCard';
-/** Frozen result data; legacy receipts may read the existing task title only. */
+/**
+ * Frozen execution receipt rendered as the same background-task card in its
+ * terminal state. Under the bot's closing reply (`attached`) the result starts
+ * open; a standalone fallback receipt starts collapsed. Legacy receipts may read
+ * the existing task title only.
+ */
export function BotSessionTaskResultCard({
data,
sessionId,
+ attached = false,
}: {
data?: Record<string, unknown>;
sessionId?: string;
@@ -21,89 +18,5 @@ export function BotSessionTaskResultCard({
}) {
const card = readBotCollaborationMeta(data);
if (card?.role !== 'delegation-result' || !card.result) return null;
- return <TaskResultBody card={card} result={card.result} sessionId={sessionId} />;
-}
-
-function TaskResultBody({
- card,
- result,
- sessionId,
-}: {
- card: BotCollaborationMeta;
- result: NonNullable<BotCollaborationMeta['result']>;
- sessionId?: string;
-}) {
- const { t } = useTranslation();
- const fileContext = useChatSessionFile();
- const [expanded, setExpanded] = useState(false);
- const contentId = useId();
- const { row } = useBotDelegation(
- result.title?.trim() ? null : (sessionId ?? card.parentSessionId),
- card.delegationId,
- );
- const title =
- result.title?.trim() ||
- row?.title?.trim() ||
- card.objective.trim().split('\n')[0] ||
- t('bots.collab.backgroundTask');
- const workingDir = result.workingDir ?? fileContext.workingDir;
- return (
- <div className="min-w-0 text-14 leading-6">
- <BotSessionTaskLink card={card} sessionId={sessionId} />
- <button
- type="button"
- className="ml-2 inline-flex max-w-full text-12 text-[var(--text-secondary)] underline underline-offset-4"
- aria-expanded={expanded}
- aria-controls={contentId}
- onClick={() => setExpanded(!expanded)}
- >
- {t('bots.collab.viewResult')}
- </button>
- <div
- id={contentId}
- hidden={!expanded}
- className="mt-3 space-y-2 border-t border-[var(--border-default)] pt-3 text-14 text-[var(--text-primary)]"
- >
- <p className="text-12 text-[var(--text-secondary)]">
- <span>{title}</span> · <span>{t(`bots.collab.status.${result.status}`)}</span>
- </p>
- <ChatSessionFileProvider
- value={{ ...fileContext, workingDir, sessionId: card.childSessionId ?? undefined }}
- >
- {result.text ? (
- <MarkdownRenderer
- workingDir={workingDir}
- currentSessionId={card.childSessionId ?? undefined}
- content={result.text}
- />
- ) : (
- <p className="whitespace-pre-wrap break-words">{t('bots.collab.noWrittenResult')}</p>
- )}
- {result.artifacts.map((artifact) => (
- <MarkdownRenderer
- key={artifact.absolutePath}
- workingDir={workingDir}
- currentSessionId={card.childSessionId ?? undefined}
- content={`[${
- artifact.absolutePath
- .split(/[\\/]/)
- .pop()
- ?.replace(/[[\]\\]/g, '\\$&') ?? t('bots.collab.viewResult')
- }](<${encodeURI(artifact.absolutePath).replace(/[<>?#]/g, encodeURIComponent)}>)`}
- />
- ))}
- </ChatSessionFileProvider>
- {result.error && (
- <details>
- <summary className="flex min-h-11 cursor-pointer items-center rounded-xl text-[var(--text-secondary)] focus-visible:outline focus-visible:outline-2">
- {t('appError.details')}
- </summary>
- <p className="whitespace-pre-wrap break-words text-12 text-[var(--text-secondary)]">
- {result.error}
- </p>
- </details>
- )}
- </div>
- </div>
- );
+ return <BotTaskCard card={card} sessionId={sessionId} attached={attached} />;
}
diff --git a/apps/desktop/src/renderer/features/bots/BotTaskCardHeader.tsx b/apps/desktop/src/renderer/features/bots/BotTaskCardHeader.tsx
deleted file mode 100644
index 7cf79b95b8..0000000000
--- a/apps/desktop/src/renderer/features/bots/BotTaskCardHeader.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { cn } from '@/lib/utils';
-
-// The existing delegation card's reading width and container, shared by its receipt.
-export const BOT_TASK_CARD_CLASS =
- 'my-2 w-full max-w-[560px] rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3 text-12';
-
-export function BotTaskCardHeader({
- title,
- status,
- statusClass,
-}: {
- title: string;
- status: string;
- statusClass: string;
-}) {
- return (
- <div className="flex items-start gap-3">
- <div
- title={title}
- className="min-w-0 flex-1 line-clamp-2 break-words text-14 font-medium leading-5 text-[var(--text-primary)]"
- >
- {title}
- </div>
- <span className={cn('flex shrink-0 items-center gap-1.5 text-12 leading-5', statusClass)}>
- <span aria-hidden="true" className="size-1.5 rounded-full bg-current" />
- {status}
- </span>
- </div>
- );
-}
diff --git a/apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx b/apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx
new file mode 100644
index 0000000000..262563aab1
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx
@@ -0,0 +1,38 @@
+import { useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
+import { BotAvatar } from './BotAvatar';
+import { findBotProfileForSession } from './botSessionOwners';
+import { ensureBotProfilesLoaded, useBotProfiles } from './botStore';
+
+/**
+ * A Bot's background task opens in the ordinary task view; this quiet chip in
+ * its header says whose task it is and leads back to that Bot. Ownership comes
+ * only from the `bot_session_links` projection, never from the session row.
+ */
+export function BotTaskOwnerChip({ sessionId }: { sessionId: string }) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const profiles = useBotProfiles();
+ useEffect(() => {
+ void ensureBotProfilesLoaded().catch(() => {});
+ }, []);
+ const bot = findBotProfileForSession(profiles, sessionId);
+ const projection = bot?.sessions.find((session) => session.id === sessionId);
+ if (!bot || (projection?.role !== 'delegation' && projection?.kind !== 'worker')) return null;
+ return (
+ <button
+ type="button"
+ onClick={() => navigate(`/bots/${encodeURIComponent(bot.id)}`)}
+ aria-label={t('bots.session.backToBot', { name: bot.name })}
+ title={t('bots.session.backToBot', { name: bot.name })}
+ className="ml-1.5 inline-flex h-6 min-w-0 max-w-[200px] shrink items-center gap-1.5 rounded-full px-2 text-12 text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus-ring)]"
+ style={WINDOW_NO_DRAG_STYLE}
+ >
+ <BotAvatar bot={bot} size="xs" />
+ <span className="truncate">{t('bots.session.ownedByBot', { name: bot.name })}</span>
+ </button>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/bots/BotTodoList.tsx b/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
index b2fe6d1fb7..09310e8bc5 100644
--- a/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
@@ -1,12 +1,16 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { Fragment, useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
-import { MoreHorizontal, Plus, ChevronDown, ChevronRight } from 'lucide-react';
+import { Check, ChevronRight, MoreHorizontal, Plus, Search, SlidersHorizontal } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
@@ -77,7 +81,12 @@ export function TodoPanel({ transport, botId }: { transport: TodoTransport; botI
[order, setOrder] = useState('dueOrder'),
[page, setPage] = useState(0),
[doneOpen, setDoneOpen] = useState(false),
- [donePage, setDonePage] = useState(0);
+ [donePage, setDonePage] = useState(0),
+ [searchOpen, setSearchOpen] = useState(false),
+ // 删除 / 不再提示虽可恢复,仍先确认一次。
+ [confirming, setConfirming] = useState<{ item: TeammateTodo; operation: 'delete' | 'mute' } | null>(
+ null,
+ );
const [detail, setDetail] = useState<string | null>(null),
[form, setForm] = useState<Partial<
Record<
@@ -247,6 +256,52 @@ export function TodoPanel({ transport, botId }: { transport: TodoTransport; botI
: x.legacyId && x.next?.label === 'Continue'
? tr('continue')
: (x.next?.label ?? tr('view'));
+ /** 能直接推进的下一步(原来的操作按钮):放在「…」菜单第一项。 */
+ const actionable = (x: TeammateTodo) =>
+ x.status === 'open' &&
+ !!x.next &&
+ x.next.kind !== 'view' &&
+ (!x.action || x.action.state === 'failed');
+ /** 第二行:到期 · 来源(交办 / 发现 · 来源名)· 推进状态;不写进展,进展在详情里。 */
+ const meta = (x: TeammateTodo) => {
+ const parts: ReactNode[] = [];
+ if (!todoVisible(x) && x.decision) {
+ parts.push(
+ tr(
+ x.decision.kind === 'deleted'
+ ? 'deleted'
+ : x.decision.kind === 'muted'
+ ? 'muted'
+ : 'deferred',
+ ),
+ );
+ }
+ const date = todoDateLabel(x, i18n.language);
+ if (date) {
+ const deadline = effectiveTodoDeadline(x);
+ const overdue = todoOverdue(x) && x.status !== 'done';
+ parts.push(
+ <span key="date" className={overdue ? 'todo-overdue' : undefined}>
+ {!deadline && x.deadlineCandidate
+ ? tr('candidate') + ' '
+ : !deadline && x.suggestedDate
+ ? tr('suggested') + ' '
+ : ''}
+ {date}
+ {overdue ? ' · ' + tr('overdue') : ''}
+ </span>,
+ );
+ }
+ parts.push(tr(x.origin));
+ if (x.sources[0]?.label) parts.push(x.sources[0].label);
+ if (x.action && x.status === 'open') parts.push(label(x));
+ return parts.map((part, index) => (
+ <Fragment key={index}>
+ {index > 0 ? ' · ' : null}
+ {part}
+ </Fragment>
+ ));
+ };
const list = (data: TeammateTodo[]) =>
data.map((x) => (
<li className="todo-row" key={x.id} data-todo-id={x.id}>
@@ -259,89 +314,59 @@ export function TodoPanel({ transport, botId }: { transport: TodoTransport; botI
title={x.title}
aria-label={x.title}
>
- <span className="todo-title">{x.title}</span>
- <span className="todo-progress">
- {!todoVisible(x) && x.decision
- ? tr(
- x.decision.kind === 'deleted'
- ? 'deleted'
- : x.decision.kind === 'muted'
- ? 'muted'
- : 'deferred',
- ) + ' · '
- : ''}
- {x.origin === 'discovered' ? tr('discovered') + ' · ' : ''}
- {x.progress || x.next?.instruction || x.outcome}
+ <span className="todo-lead" aria-hidden>
+ {x.status === 'done' ? (
+ <Check size={12} strokeWidth={2} />
+ ) : (
+ <span className={'todo-circle' + (todoVisible(x) ? '' : ' todo-circle-hidden')} />
+ )}
+ </span>
+ <span className="todo-copy">
+ <span className="todo-title">{x.title}</span>
+ <span className="todo-meta">{meta(x)}</span>
</span>
</button>
- <div className="todo-rail">
- <button
- className={'todo-date' + (todoOverdue(x) && x.status !== 'done' ? ' todo-overdue' : '')}
- aria-label={tr('deadline')}
- onClick={() => edit(x, 'deadline')}
- >
- {!effectiveTodoDeadline(x) && x.deadlineCandidate
- ? tr('candidate') + ' '
- : !effectiveTodoDeadline(x) && x.suggestedDate
- ? tr('suggested') + ' '
- : ''}
- {todoDateLabel(x, i18n.language)}
- {todoOverdue(x) && x.status !== 'done' ? ' · ' + tr('overdue') : ''}
- </button>
- <Button
- className="todo-action"
- variant="secondary"
- title={label(x)}
- disabled={busy}
- onClick={() => act(x)}
- >
- <span>{label(x)}</span>
- </Button>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- className="todo-more"
- variant="secondary"
- tone="quiet"
- aria-label={tr('more')}
- >
- <MoreHorizontal size={16} />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onSelect={() => edit(x, 'edit')}>{tr('edit')}</DropdownMenuItem>
- <DropdownMenuItem onSelect={() => edit(x, 'deadline')}>
- {tr('deadline')}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button type="button" className="todo-more" aria-label={tr('more')}>
+ <MoreHorizontal size={14} />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {actionable(x) ? (
+ <DropdownMenuItem disabled={busy} onSelect={() => act(x)}>
+ {label(x)}
</DropdownMenuItem>
- {x.status === 'done' ? (
- <DropdownMenuItem onSelect={() => void update(x, { operation: 'reopen' })}>
- {tr('reopen')}
- </DropdownMenuItem>
- ) : (
- <DropdownMenuItem onSelect={() => edit(x, 'complete')}>
- {tr('complete')}
+ ) : null}
+ <DropdownMenuItem onSelect={() => edit(x, 'edit')}>{tr('edit')}</DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => edit(x, 'deadline')}>{tr('deadline')}</DropdownMenuItem>
+ {x.status === 'done' ? (
+ <DropdownMenuItem onSelect={() => void update(x, { operation: 'reopen' })}>
+ {tr('reopen')}
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuItem onSelect={() => edit(x, 'complete')}>{tr('complete')}</DropdownMenuItem>
+ )}
+ {x.decision ? (
+ <DropdownMenuItem onSelect={() => void update(x, { operation: 'restore' })}>
+ {tr('restore')}
+ </DropdownMenuItem>
+ ) : (
+ <>
+ <DropdownMenuItem onSelect={() => edit(x, 'later')}>{tr('later')}</DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => setConfirming({ item: x, operation: 'mute' })}>
+ {tr('mute')}
</DropdownMenuItem>
- )}
- {x.decision ? (
- <DropdownMenuItem onSelect={() => void update(x, { operation: 'restore' })}>
- {tr('restore')}
+ <DropdownMenuItem
+ variant="danger"
+ onSelect={() => setConfirming({ item: x, operation: 'delete' })}
+ >
+ {tr('delete')}
</DropdownMenuItem>
- ) : (
- <>
- <DropdownMenuItem onSelect={() => edit(x, 'later')}>
- {tr('later')}
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => void update(x, { operation: 'delete' })}>
- {tr('delete')}
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => void update(x, { operation: 'mute' })}>
- {tr('mute')}
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
</li>
));
const localInput = (value: string | undefined) => {
@@ -394,7 +419,7 @@ export function TodoPanel({ transport, botId }: { transport: TodoTransport; botI
);
const save = () => {
if (!form) return;
- let patch: TodoPatch =
+ const patch: TodoPatch =
mode === 'edit'
? { title: form.title, outcome: form.outcome, progress: form.progress }
: mode === 'deadline'
@@ -470,75 +495,118 @@ export function TodoPanel({ transport, botId }: { transport: TodoTransport; botI
return (
<section className="todo-panel" aria-label={tr('title')}>
<header className="todo-header">
- <h2>{tr('title')}</h2>
- <Button
- variant="secondary"
- tone="quiet"
- aria-label={tr('new')}
- onClick={() => edit(undefined, 'edit')}
- >
- <Plus size={16} />
- </Button>
+ <h2>
+ {tr('title')}
+ {rows.length > 0 ? <span className="todo-count">{rows.length}</span> : null}
+ </h2>
+ <div className="todo-header-actions">
+ <button
+ type="button"
+ className="todo-icon"
+ aria-label={tr('search')}
+ aria-pressed={searchOpen}
+ onClick={() => {
+ if (searchOpen && query) {
+ setQuery('');
+ setPage(0);
+ setDonePage(0);
+ }
+ setSearchOpen(!searchOpen);
+ }}
+ >
+ <Search size={13} />
+ </button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ className="todo-icon"
+ aria-label={tr('filter')}
+ data-active={view !== 'open' || origin !== 'all' || order !== 'dueOrder' ? '' : undefined}
+ >
+ <SlidersHorizontal size={13} />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuRadioGroup
+ value={view}
+ onValueChange={(value) => {
+ setView(value as typeof view);
+ setPage(0);
+ setDonePage(0);
+ }}
+ >
+ <DropdownMenuRadioItem value="open">{tr('open')}</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="hidden">{tr('hidden')}</DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>{tr('origin')}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={origin}
+ onValueChange={(value) => {
+ setOrigin(value);
+ setPage(0);
+ setDonePage(0);
+ }}
+ >
+ {['all', 'assigned', 'discovered'].map((k) => (
+ <DropdownMenuRadioItem key={k} value={k}>
+ {tr(k)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>{tr('order')}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={order}
+ onValueChange={(value) => {
+ setOrder(value);
+ initialOrder.current = new Map(
+ sorted(items, value).map((x, rank) => [x.id, rank]),
+ );
+ setPage(0);
+ setDonePage(0);
+ }}
+ >
+ {['dueOrder', 'createdOrder'].map((k) => (
+ <DropdownMenuRadioItem key={k} value={k}>
+ {tr(k)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <button
+ type="button"
+ className="todo-icon"
+ aria-label={tr('new')}
+ onClick={() => edit(undefined, 'edit')}
+ >
+ <Plus size={14} />
+ </button>
+ </div>
</header>
- <div className="todo-tools">
- <input
- aria-label={tr('search')}
- placeholder={tr('search')}
- value={query}
- onChange={(e) => {
- setQuery(e.target.value);
- setPage(0);
- setDonePage(0);
- }}
- />
- <select
- aria-label={tr('open')}
- value={view}
- onChange={(e) => {
- setView(e.target.value as typeof view);
- setPage(0);
- setDonePage(0);
- }}
- >
- <option value="open">{tr('open')}</option>
- <option value="hidden">{tr('hidden')}</option>
- </select>
- </div>
- <div className="todo-filters">
- <select
- aria-label={tr('origin')}
- value={origin}
- onChange={(e) => {
- setOrigin(e.target.value);
- setPage(0);
- setDonePage(0);
- }}
- >
- {['all', 'assigned', 'discovered'].map((k) => (
- <option key={k} value={k}>
- {tr(k)}
- </option>
- ))}
- </select>
- <select
- aria-label={tr('order')}
- value={order}
- onChange={(e) => {
- setOrder(e.target.value);
- initialOrder.current = new Map(
- sorted(items, e.target.value).map((x, rank) => [x.id, rank]),
- );
- setPage(0);
- setDonePage(0);
- }}
- >
- {['dueOrder', 'createdOrder'].map((k) => (
- <option key={k} value={k}>
- {tr(k)}
- </option>
- ))}
- </select>
- </div>
+ {searchOpen && (
+ <div className="todo-search">
+ <input
+ autoFocus
+ aria-label={tr('search')}
+ placeholder={tr('search')}
+ value={query}
+ onChange={(e) => {
+ setQuery(e.target.value);
+ setPage(0);
+ setDonePage(0);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ setQuery('');
+ setSearchOpen(false);
+ }
+ }}
+ />
+ </div>
+ )}
{error && (
<p role="alert" className="todo-error">
{tr(error)}{' '}
@@ -556,12 +624,14 @@ export function TodoPanel({ transport, botId }: { transport: TodoTransport; botI
)}
{pagination(rows.length, visiblePage, setPage, tr('title'))}
<button
+ type="button"
className="todo-done-toggle"
aria-expanded={doneOpen}
onClick={() => setDoneOpen(!doneOpen)}
>
- {doneOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />} {tr('done')} ·{' '}
- {completed.length}
+ <ChevronRight size={13} className={doneOpen ? 'todo-chevron-open' : undefined} />
+ <span>{tr('done')}</span>
+ <span className="todo-count">{completed.length}</span>
</button>
{doneOpen && (
<>
@@ -571,6 +641,25 @@ export function TodoPanel({ transport, botId }: { transport: TodoTransport; botI
{pagination(completed.length, visibleDonePage, setDonePage, tr('done'))}
</>
)}
+ <ConfirmDialog
+ open={confirming !== null}
+ onOpenChange={(open) => {
+ if (!open && !pending.current) setConfirming(null);
+ }}
+ title={confirming ? tr(confirming.operation + 'ConfirmTitle') : ''}
+ description={confirming ? tr(confirming.operation + 'ConfirmBody') : undefined}
+ confirmText={confirming ? tr(confirming.operation) : undefined}
+ cancelText={tr('cancel')}
+ confirmVariant={confirming?.operation === 'delete' ? 'destructive' : 'default'}
+ loading={busy}
+ onConfirm={() => {
+ const target = confirming;
+ if (!target) return;
+ void update(target.item, { operation: target.operation }).then(() => {
+ if (current()) setConfirming(null);
+ });
+ }}
+ />
<ConfirmDialog
open={detail !== null}
onOpenChange={(open) => {
diff --git a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
index e70416bf05..528b27a869 100644
--- a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
@@ -1,12 +1,11 @@
import { BotTodoList } from './BotTodoList';
-import { WorkbenchSessionList } from './WorkbenchSessionList';
import { useWorkbenchSessionPages } from './useWorkbenchSessionPages';
-import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';
+import { useWorkbenchSessionActions } from './useWorkbenchSessionActions';
+import { useCallback, useEffect, useMemo, useState, useSyncExternalStore, type ReactNode } from 'react';
import {
ArrowLeft,
ArrowUp,
ChevronRight,
- ChevronDown,
CircleCheck,
CircleDot,
CirclePause,
@@ -17,6 +16,7 @@ import {
GitPullRequest,
Lightbulb,
Link2,
+ MoreHorizontal,
Plus,
Square,
SquareArrowOutUpRight,
@@ -28,6 +28,12 @@ import { useNavigate } from 'react-router-dom';
import type { Routine, RoutineRun } from '@cindy/maker-scheduler';
import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
import { FileTypeTile } from '@/components/ui/file-type-tile';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
@@ -36,6 +42,7 @@ import { collectCachedGeneratedFiles } from '@/components/chat/generatedFilesPro
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { usePrActions, usePrRefsForSession, usePrStatuses } from '@/contexts/PrRefsContext';
import { useElementVisible } from '@/cindy-brain/ghostUnreadStore';
+import type { Session } from '@/lib/ccAgent.types';
import type { PrStatusKind } from '@/lib/gitContext.types';
import { PR_STATUS_COLOR, PR_STATUS_ICON } from '@/features/cc-agent/gitContextPrVisuals';
import { useCCSessions } from '@/hooks/useCCSessions';
@@ -66,13 +73,12 @@ import { isBotPrimaryGeneratedFile } from './botGeneratedArtifacts';
import { useBotProfiles } from './botStore';
import {
buildWorkbenchProjectOptions,
- isWorkbenchCandidateSession,
buildWorkbenchTiles,
collectBotHiddenSessionIds,
countUnjudgedCandidates,
groupWorkbenchTiles,
+ summarizeWorkbenchGroups,
workbenchGroupHasFollowUp,
- workbenchItemNeedsLocalReference,
tierWorkbenchProjectOptions,
type ExternalSessionCandidate,
type WorkbenchPathHints,
@@ -80,6 +86,7 @@ import {
type WorkbenchProjectOption,
type WorkbenchRoutineInput,
type WorkbenchTile,
+ type WorkbenchTileGroup,
} from './botWorkbenchProjection';
/**
@@ -87,11 +94,12 @@ import {
*
* - 没接手项目时:从已有项目里选一个 →「交给<伙伴>」,两次点击完成接手。接手 = 理解:
* 只记下目录、告诉伙伴一声,不批量导入;伙伴随后读候选、写判断,条目随之出现。
- * - 接手后:项目胶囊、伙伴还在读时一行「正在了解…」、单列任务列表、最近产出。
- * 由伙伴创建或逐件明确接手的 Cindy 任务在此显示,随任务列表实时更新。列表按 等你 / 在做 / 待做 /
- * 做完 分组(做完默认折叠),每条两层:完整标题 + 伙伴的意见(末尾可带 PR 状态标)。
+ * - 接手后一列到底:项目胶囊 → 一句汇总 → 任务列表 → 待办 → 产出。
+ * 任务列表只有一套:伙伴负责的 Cindy 任务、PR / issue / 建议、项目自动化与伙伴的例行任务,
+ * 按 等你 / 在做 / 待做 / 做完 分组(空组不出,做完默认折叠,已归档的负责任务按页接在做完最底部),
+ * 每条两层:完整标题 + 伙伴的意见(末尾可带 PR 状态标)。
* - 推进:待做 / 等你 两组的「跟进」以主人身份让伙伴在左边接着干;点一条在本标签内打开详情:
- * 伙伴的判断、PR、最近内容、补一句让伙伴接着做。
+ * 伙伴的判断、正在做、产出、最近内容、补一句让伙伴接着做;任务操作收在条目的「…」里。
*/
/** 默认展示几格;「全部 N」展开其余。 */
@@ -324,14 +332,16 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
const judgments = useMemo(() => workbench?.tasks ?? {}, [workbench]);
const projectDirs = useMemo(() => directories.map((dir) => dir.path), [directories]);
const candidates = useExternalCandidates(botId, projectDirs.join('\n'));
- const [archivedOpen, setArchivedOpen] = useState(false);
const [listRevision, setListRevision] = useState(0);
const responsibleIds = useMemo(() => workbench?.responsibleSessionIds ?? [], [workbench]);
const listScope = `${botId}:${projectDirs.join('\n')}:${listRevision}`;
+ // 活跃与归档按同一责任 ID 集合分别有界读取;归档的接在「做完」最底部,按页加载。
const activePages = useWorkbenchSessionPages(listScope, 'active', Boolean(workbench), responsibleIds);
- const archivedPages = useWorkbenchSessionPages(listScope, 'archived', archivedOpen, responsibleIds);
+ const archivedPages = useWorkbenchSessionPages(listScope, 'archived', Boolean(workbench), responsibleIds);
const sessionRows = activePages.rows;
const refreshList = useCallback(() => { setListRevision(value => value + 1); emitRefresh(); }, []);
+ const actionRows = useMemo(() => [...activePages.rows, ...archivedPages.rows], [activePages.rows, archivedPages.rows]);
+ const sessionActions = useWorkbenchSessionActions(actionRows, refreshList);
const hiddenIds = useMemo(() => collectBotHiddenSessionIds(profiles), [profiles]);
const erroredIds = useMemo(
@@ -343,6 +353,7 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
() =>
buildWorkbenchTiles({
sessions: sessionRows,
+ archivedSessions: archivedPages.rows,
responsibleSessionIds: responsibleIds,
hiddenIds,
projectDirs,
@@ -357,6 +368,7 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
}),
[
sessionRows,
+ archivedPages.rows,
responsibleIds,
hiddenIds,
projectDirs,
@@ -371,16 +383,6 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
],
);
- const listedIds = useMemo(() => new Set(tiles.filter(tile => tile.type === 'session').map(tile => tile.id)), [tiles]);
- const activeSessionRows = useMemo(() => sessionRows.filter(row => listedIds.has(row.id)), [sessionRows, listedIds]);
- const responsibleIdSet = useMemo(() => new Set(responsibleIds), [responsibleIds]);
- const archivedSessionRows = useMemo(() => archivedPages.rows.filter(row =>
- row.status === 'archived' && isWorkbenchCandidateSession({ ...row, status: 'active' }, hiddenIds, responsibleIdSet)
- && responsibleIdSet.has(row.id)), [archivedPages.rows, hiddenIds, responsibleIdSet]);
- const pageAction = (page: typeof activePages) => page.loading
- ? <Spinner size={14} className="mx-5 my-3" role="status" aria-label={t('ccAgent.common.loading')} />
- : page.error || page.hasMore ? <Button size="sm" variant="secondary" className="mx-4 my-2" onClick={() => void page.load()}>{t(page.error ? 'commonUi.retry' : 'settings.contacts.list.loadMore')}</Button> : null;
-
// 伙伴正在读这些项目:还有本机外部会话没写判断,且伙伴主任务正在跑。
const unjudged = useMemo(
() => countUnjudgedCandidates({ projectDirs, caseInsensitive, candidates, judgments }),
@@ -393,14 +395,18 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
const [adding, setAdding] = useState(false);
const picking = workbench !== null && (directories.length === 0 || adding);
+ // 还没接手项目(或正在加项目)时,伙伴负责的任务与例行任务照常列出;项目来的条目等接手后再出。
+ const listTiles = useMemo(
+ () => (picking ? tiles.filter((tile) => tile.type === 'routine' || tile.type === 'session') : tiles),
+ [picking, tiles],
+ );
+ const groups = useMemo(() => groupWorkbenchTiles(listTiles), [listTiles]);
const now = useNow(tiles.some((tile) => tile.state === 'running' && tile.startedAtMs !== null));
const openTile = useCallback(
(tile: WorkbenchTile) => {
- if (tile.type === 'session') {
- void resolveSessionRoute(tile.id).then(route => navigate(route));
- } else if (tile.type === 'external' || tile.type === 'item') {
- // 任务在本标签内打开详情,不换路由、不跳任务页。
+ if (tile.type === 'session' || tile.type === 'external' || tile.type === 'item') {
+ // 任务在本标签内打开详情,不换路由、不跳任务页;归档的也只是看,不恢复。
setDetailOpened(tile);
} else if (tile.type === 'schedule') {
if (!inSidebarWindow) navigate(scheduleFocusPath(tile.id));
@@ -464,18 +470,12 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
const out: Array<{ path: string; name: string }> = [];
const seen = new Set<string>();
const push = (file: { path: string; name: string }) => {
- if (out.length >= MAX_OUTPUTS || seen.has(file.path)) return;
+ if (out.length >= MAX_OUTPUTS_LISTED || seen.has(file.path)) return;
seen.add(file.path);
out.push(file);
};
for (const task of [...delegations].sort((a, b) => b.createdAt - a.createdAt)) {
- for (const artifact of task.artifacts) {
- if (!artifact.absolutePath || artifact.status === 'deleted') continue;
- const name = artifact.absolutePath.split(/[\\/]/).pop() ?? artifact.path;
- if (isBotPrimaryGeneratedFile({ path: artifact.absolutePath, name, source: 'tool' })) {
- push({ path: artifact.absolutePath, name });
- }
- }
+ for (const file of delegationOutputs(task)) push(file);
}
if (chat && chatWorkingDir && chat.messages.length > 0) {
const files = collectCachedGeneratedFiles(chat.messages, chatWorkingDir);
@@ -496,9 +496,10 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
);
}
- const routineTiles = tiles.filter((tile) => tile.type === 'routine');
-
if (detailTile && (detailTile.type === 'session' || detailTile.type === 'external' || detailTile.type === 'item')) {
+ const delegation = detailTile.type === 'session'
+ ? delegations.find((task) => task.childSessionId === detailTile.id) ?? null
+ : null;
return (
<TaskDetail
botId={botId}
@@ -509,6 +510,7 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
canNavigate={!inSidebarWindow}
projectDirs={projectDirs}
caseInsensitive={caseInsensitive}
+ outputs={delegation ? delegationOutputs(delegation) : []}
onBack={() => setDetailOpened(null)}
/>
);
@@ -516,10 +518,25 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
// 最近交给伙伴的项目排在最前,正在了解的通常就是它。
const understandingProject = understanding ? (directories[0]?.name ?? '') : '';
+ const pageControl = (page: typeof activePages, showLoading: boolean) =>
+ page.loading
+ ? showLoading
+ ? <Spinner size={14} className="my-2 ml-2" role="status" aria-label={t('ccAgent.common.loading')} />
+ : null
+ : page.error || page.hasMore
+ ? (
+ <Button variant="secondary" size="sm" tone="quiet" compact className="my-1" onClick={() => void page.load()}>
+ {t(page.error ? 'commonUi.retry' : 'settings.contacts.list.loadMore')}
+ </Button>
+ )
+ : null;
+ const rowMenu = (tile: WorkbenchTile) => {
+ const row = tile.type === 'session' ? sessionActions.byId.get(tile.id) : undefined;
+ return row ? <SessionRowMenu row={row} canNavigate={!inSidebarWindow} actions={sessionActions} /> : null;
+ };
return (
<div className="h-full min-h-0 overflow-y-auto overflow-x-hidden bg-[var(--surface)]">
- <BotTodoList botId={botId} />
{picking ? (
<ProjectPicker
botId={botId}
@@ -541,78 +558,115 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
onAdd={directories.length < BOT_WORKBENCH_MAX_DIRECTORIES ? () => setAdding(true) : undefined}
/>
{understanding ? (
- <p className="flex items-center gap-1.5 px-5 pb-3 pt-1 text-13 leading-5 text-[var(--text-secondary)]">
+ <p className="flex items-center gap-1.5 px-5 pt-2.5 text-12 leading-[1.5] text-[var(--text-secondary)]">
<Spinner size={12} aria-hidden className="shrink-0" />
<span className="min-w-0 truncate">
{t('bots.workbench.understanding', { name: botName, project: understandingProject })}
</span>
</p>
) : null}
+ <WorkbenchSummary groups={groups} />
</>
)}
- {(!picking || responsibleIds.length > 0) && <>
- <WorkbenchSessionList sessions={activeSessionRows} onChanged={refreshList} />
- {pageAction(activePages)}
- <section className="pb-3 pt-2">
- <button type="button" className="mx-3 flex min-h-9 items-center gap-1.5 rounded-lg px-2 text-12 text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]" aria-expanded={archivedOpen} onClick={() => setArchivedOpen(value => !value)}>
- {archivedOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />}{t('ccAgent.sidebar.filterStatus.archived')}
- </button>
- {archivedOpen && <><WorkbenchSessionList sessions={archivedSessionRows} onChanged={refreshList} />{pageAction(archivedPages)}</>}
- </section>
- </>}
-
- {/* 还没接手项目时,伙伴已有的自动化(例行任务、导入来的自动化)照常列在下面。 */}
- {!picking || routineTiles.length > 0 ? (
- <TaskGroups
- tiles={picking ? routineTiles : tiles.filter(tile =>
- tile.type !== 'session' &&
- (tile.type !== 'item' || workbenchItemNeedsLocalReference(tile, projectDirs, caseInsensitive))
- )}
- now={now}
- language={i18n.language}
- showEmpty={false}
- followingKey={followingKey}
- onOpen={openTile}
- onFollowUp={followUp}
- />
+ <TaskGroups
+ groups={groups}
+ now={now}
+ language={i18n.language}
+ followingKey={followingKey}
+ onOpen={openTile}
+ onFollowUp={followUp}
+ rowMenu={rowMenu}
+ archivedFooter={pageControl(archivedPages, true)}
+ />
+ {activePages.error || (activePages.hasMore && !activePages.loading) ? (
+ <div className="px-5">{pageControl(activePages, false)}</div>
) : null}
- {!picking ? (
- <section className="border-t border-[var(--border-default)] px-5 pb-5">
- <h3 className="flex h-11 items-center text-16 font-medium leading-6 text-[var(--text-primary)]">
- {t('bots.workbench.outputs')}
- </h3>
- {outputs.length === 0 ? (
- <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">
- {t('bots.workbench.outputsEmpty', { name: botName })}
- </p>
- ) : (
- <div className="grid grid-cols-4 gap-2.5">
- {outputs.map((file) => (
- <button
- key={file.path}
- type="button"
- title={file.path}
- onClick={() => void window.electronAPI.openPath?.(file.path)}
- className="group flex min-w-0 flex-col items-center gap-1.5 rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
- >
- <span className="flex h-[52px] w-full items-center justify-center rounded-xl border border-[var(--border-default)] transition-colors group-hover:bg-[var(--surface-hover)]">
- <FileTypeTile name={file.name} />
- </span>
- <span className="w-full truncate text-center text-12 leading-4 text-[var(--text-secondary)]">
- {file.name}
- </span>
- </button>
- ))}
- </div>
- )}
- </section>
- ) : null}
+ <BotTodoList botId={botId} />
+
+ {!picking ? <WorkbenchOutputs outputs={outputs} botName={botName} /> : null}
</div>
);
}
+/** 产出区最多收集多少个文件(默认只显示前 4 个,「全部」展开其余)。 */
+const MAX_OUTPUTS_LISTED = 60;
+
+type DelegationLike = ReturnType<typeof useBotDelegations>[number];
+
+/** 一件后台任务交回的主要文件(已删除的不算)。 */
+function delegationOutputs(task: DelegationLike): Array<{ path: string; name: string }> {
+ const out: Array<{ path: string; name: string }> = [];
+ for (const artifact of task.artifacts) {
+ if (!artifact.absolutePath || artifact.status === 'deleted') continue;
+ const name = artifact.absolutePath.split(/[\\/]/).pop() ?? artifact.path;
+ if (isBotPrimaryGeneratedFile({ path: artifact.absolutePath, name, source: 'tool' })) {
+ out.push({ path: artifact.absolutePath, name });
+ }
+ }
+ return out;
+}
+
+/** 胶囊下面的一句汇总:「1 件等你 · 2 件在做 · 4 件待做」,为 0 的不说。 */
+function WorkbenchSummary({ groups }: { groups: readonly WorkbenchTileGroup[] }) {
+ const { t } = useTranslation();
+ const counts = summarizeWorkbenchGroups(groups);
+ const parts = (['waiting', 'running', 'todo'] as const)
+ .filter((key) => counts[key] > 0)
+ .map((key) => t(`bots.workbench.summary.${key}`, { count: counts[key] }));
+ if (parts.length === 0) return null;
+ return <p className="px-5 pt-2.5 text-12 leading-[1.5] text-[var(--text-secondary)]">{parts.join(' · ')}</p>;
+}
+
+function WorkbenchOutputs({ outputs, botName }: { outputs: ReadonlyArray<{ path: string; name: string }>; botName: string }) {
+ const { t } = useTranslation();
+ const [all, setAll] = useState(false);
+ const shown = all ? outputs : outputs.slice(0, MAX_OUTPUTS);
+ return (
+ <section className="px-5 pb-5" aria-label={t('bots.workbench.outputs')}>
+ <div className="mb-1.5 mt-3.5 flex min-h-[22px] items-center gap-1.5 text-12 leading-[1.5] text-[var(--text-secondary)]">
+ <h3>{t('bots.workbench.outputs')}</h3>
+ {outputs.length > 0 ? <span className="tabular-nums text-[var(--text-tertiary)]">{outputs.length}</span> : null}
+ {outputs.length > MAX_OUTPUTS ? (
+ <button
+ type="button"
+ aria-expanded={all}
+ onClick={() => setAll((value) => !value)}
+ className="ml-auto flex h-6 items-center rounded-[8px] px-1.5 text-12 text-[var(--text-secondary)] outline-none transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t(all ? 'bots.workbench.outputsLess' : 'bots.workbench.outputsAll')}
+ </button>
+ ) : null}
+ </div>
+ {outputs.length === 0 ? (
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('bots.workbench.outputsEmpty', { name: botName })}
+ </p>
+ ) : (
+ <div className="grid grid-cols-4 gap-2">
+ {shown.map((file) => (
+ <button
+ key={file.path}
+ type="button"
+ title={file.path}
+ onClick={() => void window.electronAPI.openPath?.(file.path)}
+ className="group flex min-w-0 flex-col items-center gap-1.5 rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <span className="flex h-[52px] w-full items-center justify-center rounded-xl border border-[var(--border-default)] transition-colors group-hover:bg-[var(--surface-hover)]">
+ <FileTypeTile name={file.name} />
+ </span>
+ <span className="w-full truncate text-center text-12 leading-4 text-[var(--text-secondary)]">
+ {file.name}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ </section>
+ );
+}
+
// ─── 空状态:把一个项目交给伙伴 ─────────────────────────────────────
type ScanState =
@@ -961,11 +1015,30 @@ function ProjectCapsules({
// ─── 任务列表:单列、按四组、每条两层 ─────────────────────────────────
-/** 「等你」组第二层写等的是什么;其它组不写状态词。 */
+/** 「等你」第二层:状态 + 等的是什么(权限 / 提问 / 方案…,有具体内容时带上)。 */
function waitingText(tile: WorkbenchTile, t: Translate): string {
- if (tile.state === 'waiting') return t('bots.workbench.line.waiting');
- const kind = tile.line.kind;
- if (kind === 'interrupted' || kind === 'errored' || kind === 'failed') return t(`bots.workbench.line.${kind}`);
+ const line = tile.line;
+ if (tile.state === 'waiting') {
+ const interaction = line.kind === 'waiting' ? line.interaction : null;
+ const label = t(
+ interaction === 'permission'
+ ? 'bots.workbench.line.waitingPermission'
+ : interaction === 'ask_user_question'
+ ? 'bots.workbench.line.waitingQuestion'
+ : interaction === 'plan_review'
+ ? 'bots.workbench.line.waitingPlan'
+ : interaction === 'plugin_setup' || interaction === 'input_handoff'
+ ? 'bots.workbench.line.waitingAction'
+ : 'bots.workbench.line.waiting',
+ );
+ const text = line.kind === 'waiting' ? line.text : null;
+ return text ? t('bots.workbench.line.waitingFor', { label, text }) : label;
+ }
+ if (line.kind === 'failed') {
+ const label = t('bots.workbench.line.failed');
+ return line.text ? t('bots.workbench.line.waitingFor', { label, text: line.text }) : label;
+ }
+ if (line.kind === 'interrupted' || line.kind === 'errored') return t(`bots.workbench.line.${line.kind}`);
return t('bots.workbench.line.errored');
}
@@ -985,85 +1058,78 @@ function automationLine(tile: WorkbenchTile, t: Translate, language: string, now
return extra ? `${cycle} · ${extra}` : cycle;
}
+type RowNote = { text: string; accent?: string | null } | null;
+
/**
- * 第二层只写「伙伴的意见」:伙伴写的下一步;没有时在做的写「在做 · 用时」,自动化写周期与下次运行,
- * 排队的写「排队中」,做完的不写。来源与相对时间都不显示(在详情里)。
+ * 第二层只写「伙伴的意见」:
+ * - 等你:状态 + 等的是什么(伙伴另写了下一步时接在后面);
+ * - 在做:当前动作(运行色)+ 用时;没有动作时「在做 · 用时」;
+ * - 待做:伙伴写的下一步;没有时「排队中」/「没做完」/「聊过没下文」;
+ * - 做完:不写;自动化写周期与下次运行,已归档的写「已归档」。
+ * 来源与相对时间都不显示(在详情里)。
*/
-function tileNote(tile: WorkbenchTile, group: WorkbenchGroupKey, t: Translate, language: string, now: number): string | null {
- if ('next' in tile && tile.next) return tile.next;
+function rowNote(tile: WorkbenchTile, group: WorkbenchGroupKey, t: Translate, language: string, now: number): RowNote {
+ const next = 'next' in tile && tile.next ? tile.next : null;
const automation = automationLine(tile, t, language, now);
- if (automation) return automation;
+ if (group === 'waiting') {
+ const waiting = waitingText(tile, t);
+ return { text: next ? `${waiting} · ${next}` : waiting };
+ }
if (group === 'running') {
- return tile.startedAtMs
- ? `${t('bots.workbench.state.running')} · ${elapsed(tile.startedAtMs, now)}`
- : t('bots.workbench.state.running');
+ const time = tile.startedAtMs ? elapsed(tile.startedAtMs, now) : null;
+ if (tile.line.kind === 'action') return { accent: tile.line.text, text: time ?? '' };
+ if (automation && !time) return { text: `${t('bots.workbench.state.running')} · ${automation}` };
+ return { text: time ? `${t('bots.workbench.state.running')} · ${time}` : t('bots.workbench.state.running') };
}
- if (tile.state === 'queued') return t('bots.workbench.line.queued');
- return null;
-}
-
-type TilePr = { number: number; kind: PrStatusKind | null; url: string };
-
-/**
- * 条目关联的 PR 与状态:
- * - Cindy 任务:任务里出现过的 PR 引用(取最近一条),状态与刷新复用 PrRefsContext——条目可见时
- * `registerPrConsumer`,跟侧栏 / 顶栏同一套周期与聚焦刷新,不另起轮询;
- * - `pr:` 条目:可见时用同一个 `gitContext.getPrStatuses` 查一次(main 侧 60 秒缓存与去重);
- * 拿不到(没有 gh 登录等)就只显示编号。
- */
-function useTilePr(tile: WorkbenchTile, visible: boolean): TilePr | null {
- const sessionId = tile.type === 'session' ? tile.id : '';
- const { registerPrConsumer } = usePrActions();
- const refs = usePrRefsForSession(sessionId);
- const { statuses, successfulStatuses } = usePrStatuses(sessionId);
- useEffect(() => {
- if (!visible || !sessionId) return;
- return registerPrConsumer(sessionId);
- }, [visible, sessionId, registerPrConsumer]);
-
- const github = tile.type === 'item' && tile.itemKind === 'pr' ? parseWorkbenchTaskId(tile.id) : null;
- const itemRef = github?.kind === 'github' ? github : null;
- const [itemKind, setItemKind] = useState<PrStatusKind | null>(null);
- useEffect(() => {
- if (!visible || !itemRef) return;
- let alive = true;
- void window.electronAPI?.gitContext
- ?.getPrStatuses([{ owner: itemRef.owner, repo: itemRef.repo, prNumber: itemRef.number }])
- .then((results) => {
- const result = results?.[0];
- if (alive && result?.ok) setItemKind(result.status);
- })
- .catch(() => {});
- return () => {
- alive = false;
- };
- // itemRef 由 tile.id 决定。
- }, [visible, tile.id]);
-
- if (itemRef) {
- return { number: itemRef.number, kind: itemKind, url: sessionPrUrl({ owner: itemRef.owner, repo: itemRef.repo, prNumber: itemRef.number }) };
+ if (group === 'todo') {
+ if (next) return { text: next };
+ if (tile.state === 'queued') return { text: t('bots.workbench.line.queued') };
+ if ('verdict' in tile && tile.verdict) return { text: t(`bots.workbench.verdict.${tile.verdict}`) };
+ return automation ? { text: automation } : null;
}
- if (refs.length === 0) return null;
- const latest = refs.reduce((best, ref) => (ref.lastSeenAt > best.lastSeenAt ? ref : best));
- const key = prStatusKey(latest);
- const result = statuses.get(key);
- const confirmed = result?.ok ? result : successfulStatuses.get(key);
- return { number: latest.prNumber, kind: confirmed?.ok ? confirmed.status : null, url: sessionPrUrl(latest) };
+ if (tile.type === 'session' && tile.archived) return { text: t('ccAgent.sidebar.filterStatus.archived') };
+ return automation ? { text: automation } : null;
}
-/** 小的 PR 状态标:图标 + 「#5292 · 已合并」,颜色与侧栏 / 顶栏同一套 PR_STATUS_*。 */
-function PrTag({ pr }: { pr: TilePr }) {
+/** 行首 16px 的状态字形:在做转圈、等你蓝点、待做空心圈、做完勾(自动化为时钟)。 */
+function LeadGlyph({ tile, group }: { tile: WorkbenchTile; group: WorkbenchGroupKey }) {
const { t } = useTranslation();
- const Icon = pr.kind ? PR_STATUS_ICON[pr.kind] : GitPullRequest;
- return (
- <span className="inline-flex shrink-0 items-center gap-1 text-12 leading-5 text-[var(--text-tertiary)]">
- <Icon size={12} aria-hidden style={{ color: pr.kind ? PR_STATUS_COLOR[pr.kind] : 'var(--text-tertiary)' }} />
- <span className="tabular-nums">
- #{pr.number}
- {pr.kind ? ` · ${t(`ccAgent.gitContext.pr.status.${pr.kind}`)}` : ''}
+ const label = t(`bots.workbench.group.${group}`);
+ let glyph: ReactNode;
+ if (group === 'running') {
+ glyph = <Spinner size={14} strokeWidth={2} role="img" aria-label={label} className="text-[var(--text-secondary)]" />;
+ } else if (group === 'waiting') {
+ glyph = <span role="img" aria-label={label} className="size-2 rounded-full bg-[var(--card-status-awaiting)]" />;
+ } else if (group === 'todo') {
+ glyph = (
+ <span
+ role="img"
+ aria-label={tile.state === 'queued' ? t('bots.workbench.state.queued') : label}
+ className={cn(
+ 'size-3.5 rounded-full border-[1.5px] border-[var(--text-tertiary)]',
+ tile.state === 'queued' && 'border-dashed',
+ )}
+ />
+ );
+ } else {
+ const automation = tile.type === 'schedule' || tile.type === 'routine';
+ const Icon = automation ? Clock3 : CircleCheck;
+ glyph = (
+ <span role="img" aria-label={label} className="flex">
+ <Icon
+ size={14}
+ strokeWidth={1.8}
+ aria-hidden
+ className={
+ automation || (tile.type === 'session' && tile.archived)
+ ? 'text-[var(--text-tertiary)]'
+ : 'text-[var(--card-status-done)]'
+ }
+ />
</span>
- </span>
- );
+ );
+ }
+ return <span className="flex h-5 w-4 shrink-0 items-center justify-center">{glyph}</span>;
}
function TaskRow({
@@ -1074,6 +1140,7 @@ function TaskRow({
following,
onOpen,
onFollowUp,
+ menu,
}: {
tile: WorkbenchTile;
group: WorkbenchGroupKey;
@@ -1083,93 +1150,151 @@ function TaskRow({
following: boolean;
onOpen: (tile: WorkbenchTile) => void;
onFollowUp?: (tile: WorkbenchTile) => void;
+ /** 悬停才出现的「…」(Cindy 任务的打开 / 置顶 / 归档 / 删除)。 */
+ menu?: ReactNode;
}) {
const { t } = useTranslation();
const title = tile.title || t('bots.workbench.untitled');
- const waiting = group === 'waiting' ? waitingText(tile, t) : null;
- const note = tileNote(tile, group, t, language, now);
- const second = waiting ? (note ? `${waiting} · ${note}` : waiting) : note;
+ const note = rowNote(tile, group, t, language, now);
const { ref: observe, visible } = useElementVisible();
const pr = useTilePr(tile, visible);
return (
<li
ref={observe}
- className="group flex min-w-0 items-start rounded-xl bg-[var(--surface-elevated)] transition-colors hover:bg-[var(--surface-hover)]">
+ data-workbench-row={tile.key}
+ className="group -mx-2 flex min-w-0 items-start gap-1 rounded-[8px] transition-colors hover:bg-[var(--surface-hover)]"
+ >
<button
type="button"
onClick={() => onOpen(tile)}
aria-label={t('bots.workbench.openTask', { title, state: t(`bots.workbench.group.${group}`) })}
- className={cn(
- 'flex min-w-0 flex-1 flex-col rounded-xl py-3 pl-3.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- onFollowUp ? 'pr-2' : 'pr-3.5',
- )}
+ className="flex min-w-0 flex-1 items-start gap-2 rounded-[8px] py-2 pl-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
>
- <span className="line-clamp-3 text-14 font-medium leading-5 text-[var(--text-primary)] [overflow-wrap:anywhere]">
- {title}
- </span>
- {second || pr ? (
- <span className="mt-1.5 flex min-w-0 items-start gap-1.5 text-13 leading-5 text-[var(--text-secondary)]">
- {waiting ? (
- <span aria-hidden className="mt-[7px] size-1.5 shrink-0 rounded-full bg-[var(--card-status-awaiting)]" />
- ) : null}
- {second ? <span className="line-clamp-2 min-w-0 flex-1 [overflow-wrap:anywhere]">{second}</span> : null}
- {pr ? <PrTag pr={pr} /> : null}
+ <LeadGlyph tile={tile} group={group} />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="line-clamp-3 text-13 leading-5 text-[var(--text-primary)] [overflow-wrap:anywhere]">
+ {title}
</span>
- ) : null}
+ {note || pr ? (
+ <span className="mt-0.5 flex min-w-0 items-start gap-1.5 text-12 leading-[1.5] text-[var(--text-secondary)]">
+ {note ? (
+ <span className="line-clamp-2 min-w-0 flex-1 [overflow-wrap:anywhere]">
+ {note.accent ? <span className="text-[var(--status-bar-accent)]">{note.accent}</span> : null}
+ {note.accent && note.text ? ' · ' : null}
+ {note.text}
+ </span>
+ ) : null}
+ {pr ? <PrTag pr={pr} /> : null}
+ </span>
+ ) : null}
+ </span>
</button>
- {onFollowUp ? (
+ <span className="flex shrink-0 items-center gap-0.5 pr-1.5 pt-1.5">
+ {menu}
+ {onFollowUp ? (
+ <button
+ type="button"
+ onClick={() => onFollowUp(tile)}
+ disabled={following}
+ aria-label={t('bots.workbench.followUp.aria', { title })}
+ className="flex h-6 items-center gap-1 rounded-full border border-[var(--border-default)] px-2.5 text-12 leading-4 text-[var(--text-secondary)] outline-none transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-default"
+ >
+ {following ? <Spinner size={12} aria-hidden /> : null}
+ {t('bots.workbench.followUp.label')}
+ </button>
+ ) : null}
+ </span>
+ </li>
+ );
+}
+
+type SessionActions = ReturnType<typeof useWorkbenchSessionActions>;
+
+/** Cindy 任务条目的「…」:与任务侧栏同一套操作与守卫;悬停或键盘聚焦时出现。 */
+function SessionRowMenu({ row, canNavigate, actions }: { row: Session; canNavigate: boolean; actions: SessionActions }) {
+ const { t } = useTranslation();
+ const archived = row.status === 'archived';
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
<button
type="button"
- onClick={() => onFollowUp(tile)}
- disabled={following}
- aria-label={t('bots.workbench.followUp.aria', { title })}
- className="mr-2.5 mt-2.5 flex h-7 shrink-0 items-center gap-1 rounded-[8px] px-2.5 text-12 font-medium leading-4 text-[var(--text-tertiary)] outline-none transition-colors hover:bg-[var(--surface-chip)] hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] group-hover:text-[var(--text-secondary)] disabled:cursor-default"
+ aria-label={t('ccAgent.sidebar.sessionMenu.moreActions')}
+ className="flex size-6 items-center justify-center rounded-[8px] text-[var(--text-tertiary)] opacity-0 outline-none transition-colors hover:bg-[var(--surface-chip)] hover:text-[var(--text-primary)] focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] group-hover:opacity-100 data-[state=open]:opacity-100"
>
- {following ? <Spinner size={12} aria-hidden /> : null}
- {t('bots.workbench.followUp.label')}
+ <MoreHorizontal size={14} aria-hidden />
</button>
- ) : null}
- </li>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {canNavigate ? (
+ <DropdownMenuItem onSelect={() => actions.open(row.id)}>{t('bots.workbench.detail.openInTasks')}</DropdownMenuItem>
+ ) : null}
+ {!archived ? (
+ <DropdownMenuItem onSelect={() => void actions.togglePin(row.id)}>
+ {t(row.pinnedAt ? 'ccAgent.sidebar.sessionMenu.unpin' : 'ccAgent.sidebar.sessionMenu.pin')}
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem onSelect={() => void actions.action(row.id, archived ? 'unarchive' : 'archive')}>
+ {t(archived ? 'ccAgent.sidebar.sessionMenu.unarchive' : 'ccAgent.sidebar.sessionMenu.archived')}
+ </DropdownMenuItem>
+ <DropdownMenuItem variant="danger" onSelect={() => void actions.action(row.id, 'delete')}>
+ {t('ccAgent.sidebar.sessionMenu.delete')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
);
}
+const GROUP_HEADING_CLASS = 'mb-0.5 mt-3.5 flex min-h-[22px] items-center gap-1.5 text-12 leading-[1.5] text-[var(--text-secondary)]';
+
function TaskGroups({
- tiles,
+ groups,
now,
language,
- showEmpty,
followingKey,
onOpen,
onFollowUp,
+ rowMenu,
+ archivedFooter,
}: {
- tiles: readonly WorkbenchTile[];
+ groups: readonly WorkbenchTileGroup[];
now: number;
language: string;
- showEmpty: boolean;
followingKey: string | null;
onOpen: (tile: WorkbenchTile) => void;
onFollowUp?: (tile: WorkbenchTile) => void;
+ rowMenu?: (tile: WorkbenchTile) => ReactNode;
+ /** 「做完」展开后接在归档条目下面的加载更多 / 重试。 */
+ archivedFooter?: ReactNode;
}) {
const { t } = useTranslation();
- const groups = useMemo(() => groupWorkbenchTiles(tiles), [tiles]);
const [openDone, setOpenDone] = useState(false);
- if (groups.length === 0) {
- return showEmpty ? (
- <p className="px-5 pb-5 pt-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.tasksEmpty')}</p>
- ) : null;
- }
+ if (groups.length === 0) return null;
return (
- <div className="flex flex-col gap-5 px-5 pb-5 pt-1">
+ <div className="flex flex-col px-5 pb-1">
{groups.map((group) => {
const open = !group.defaultCollapsed || openDone;
const label = t(`bots.workbench.group.${group.key}`);
const heading = (
<>
<span>{label}</span>
- <span className="font-normal tabular-nums text-[var(--text-tertiary)]">{group.total}</span>
+ <span className="tabular-nums text-[var(--text-tertiary)]">{group.total}</span>
</>
);
const followUp = onFollowUp && workbenchGroupHasFollowUp(group.key) ? onFollowUp : undefined;
+ const row = (tile: WorkbenchTile) => (
+ <TaskRow
+ key={tile.key}
+ tile={tile}
+ group={group.key}
+ now={now}
+ language={language}
+ following={followingKey === tile.key}
+ onOpen={onOpen}
+ onFollowUp={followUp}
+ menu={rowMenu?.(tile)}
+ />
+ );
return (
<section key={group.key} aria-label={label}>
{group.defaultCollapsed ? (
@@ -1177,39 +1302,31 @@ function TaskGroups({
type="button"
aria-expanded={open}
onClick={() => setOpenDone((value) => !value)}
- className="-mx-1 flex h-6 items-center gap-1.5 rounded-[8px] px-1 text-13 font-medium leading-5 text-[var(--text-secondary)] outline-none transition-colors hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ className={cn(
+ GROUP_HEADING_CLASS,
+ '-mx-1 rounded-[8px] px-1 outline-none transition-colors hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
>
- {heading}
<ChevronRight
- size={14}
+ size={13}
aria-hidden
className={cn('text-[var(--text-tertiary)] transition-transform', open && 'rotate-90')}
/>
+ {heading}
</button>
) : (
- <h3 className="flex h-6 items-center gap-1.5 text-13 font-medium leading-5 text-[var(--text-secondary)]">
- {heading}
- </h3>
+ <h3 className={GROUP_HEADING_CLASS}>{heading}</h3>
)}
{open ? (
- <ul className="mt-2 flex flex-col gap-2">
- {group.tiles.map((tile) => (
- <TaskRow
- key={tile.key}
- tile={tile}
- group={group.key}
- now={now}
- language={language}
- following={followingKey === tile.key}
- onOpen={onOpen}
- onFollowUp={followUp}
- />
- ))}
+ <ul className="flex flex-col">
+ {group.tiles.map(row)}
{group.hiddenCount > 0 ? (
- <li className="px-3.5 pt-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ <li className="py-1 pl-6 text-12 leading-[1.5] text-[var(--text-tertiary)]">
{t('bots.workbench.olderCount', { count: group.hiddenCount })}
</li>
) : null}
+ {group.archivedTiles.map(row)}
+ {group.key === 'done' && archivedFooter ? <li className="pl-4">{archivedFooter}</li> : null}
</ul>
) : null}
</section>
@@ -1219,6 +1336,70 @@ function TaskGroups({
);
}
+type TilePr = { number: number; kind: PrStatusKind | null; url: string };
+
+/**
+ * 条目关联的 PR 与状态:
+ * - Cindy 任务:任务里出现过的 PR 引用(取最近一条),状态与刷新复用 PrRefsContext——条目可见时
+ * `registerPrConsumer`,跟侧栏 / 顶栏同一套周期与聚焦刷新,不另起轮询;
+ * - `pr:` 条目:可见时用同一个 `gitContext.getPrStatuses` 查一次(main 侧 60 秒缓存与去重);
+ * 拿不到(没有 gh 登录等)就只显示编号。
+ */
+function useTilePr(tile: WorkbenchTile, visible: boolean): TilePr | null {
+ const sessionId = tile.type === 'session' ? tile.id : '';
+ const { registerPrConsumer } = usePrActions();
+ const refs = usePrRefsForSession(sessionId);
+ const { statuses, successfulStatuses } = usePrStatuses(sessionId);
+ useEffect(() => {
+ if (!visible || !sessionId) return;
+ return registerPrConsumer(sessionId);
+ }, [visible, sessionId, registerPrConsumer]);
+
+ const github = tile.type === 'item' && tile.itemKind === 'pr' ? parseWorkbenchTaskId(tile.id) : null;
+ const itemRef = github?.kind === 'github' ? github : null;
+ const [itemKind, setItemKind] = useState<PrStatusKind | null>(null);
+ useEffect(() => {
+ if (!visible || !itemRef) return;
+ let alive = true;
+ void window.electronAPI?.gitContext
+ ?.getPrStatuses([{ owner: itemRef.owner, repo: itemRef.repo, prNumber: itemRef.number }])
+ .then((results) => {
+ const result = results?.[0];
+ if (alive && result?.ok) setItemKind(result.status);
+ })
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ // itemRef 由 tile.id 决定。
+ }, [visible, tile.id]);
+
+ if (itemRef) {
+ return { number: itemRef.number, kind: itemKind, url: sessionPrUrl({ owner: itemRef.owner, repo: itemRef.repo, prNumber: itemRef.number }) };
+ }
+ if (refs.length === 0) return null;
+ const latest = refs.reduce((best, ref) => (ref.lastSeenAt > best.lastSeenAt ? ref : best));
+ const key = prStatusKey(latest);
+ const result = statuses.get(key);
+ const confirmed = result?.ok ? result : successfulStatuses.get(key);
+ return { number: latest.prNumber, kind: confirmed?.ok ? confirmed.status : null, url: sessionPrUrl(latest) };
+}
+
+/** 小的 PR 状态标:图标 + 「#5292 · 已合并」,颜色与侧栏 / 顶栏同一套 PR_STATUS_*。 */
+function PrTag({ pr }: { pr: TilePr }) {
+ const { t } = useTranslation();
+ const Icon = pr.kind ? PR_STATUS_ICON[pr.kind] : GitPullRequest;
+ return (
+ <span className="inline-flex shrink-0 items-center gap-1 text-12 leading-5 text-[var(--text-tertiary)]">
+ <Icon size={12} aria-hidden style={{ color: pr.kind ? PR_STATUS_COLOR[pr.kind] : 'var(--text-tertiary)' }} />
+ <span className="tabular-nums">
+ #{pr.number}
+ {pr.kind ? ` · ${t(`ccAgent.gitContext.pr.status.${pr.kind}`)}` : ''}
+ </span>
+ </span>
+ );
+}
+
function StateIcon({ state, verdict }: { state: WorkbenchTaskState; verdict?: 'unfinished' | 'idea' | null }) {
const { t } = useTranslation();
const live = state === 'running' || state === 'waiting' || state === 'queued';
@@ -1329,9 +1510,22 @@ type TranscriptState =
| { kind: 'ready'; transcript: WorkbenchTranscript }
| { kind: 'failed' };
+const DETAIL_ACTION_CLASS =
+ 'inline-flex h-7 shrink-0 items-center gap-1 rounded-[8px] px-2 text-12 text-[var(--text-secondary)] outline-none transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]';
+
+function DetailSection({ title, children }: { title: string; children: ReactNode }) {
+ return (
+ <section className="mb-4">
+ <h4 className="mb-1.5 text-11 font-medium leading-[1.45] text-[var(--text-tertiary)]">{title}</h4>
+ {children}
+ </section>
+ );
+}
+
/**
- * 详情视图:不换路由、不跳任务页。伙伴的判断在上,最近内容(同一份有界只读摘录)在中,
- * 底部「补一句」以主人身份发给伙伴,由伙伴决定怎么继续——不绕过伙伴直接投给任务。
+ * 详情视图:不换路由、不跳任务页。面包屑「工作台 › 标题」,状态行(状态 · 用时 · 来源 · PR),
+ * 伙伴的判断,正在做,到现在的产出,最近内容(同一份有界只读摘录);底部「补一句」以主人身份
+ * 发给伙伴,由伙伴决定怎么继续——不绕过伙伴直接投给任务。已归档的任务只读,不给「补一句」。
*/
function TaskDetail({
botId,
@@ -1342,6 +1536,7 @@ function TaskDetail({
canNavigate,
projectDirs,
caseInsensitive,
+ outputs,
onBack,
}: {
botId: string;
@@ -1352,6 +1547,8 @@ function TaskDetail({
canNavigate: boolean;
projectDirs: readonly string[];
caseInsensitive: boolean;
+ /** 这件任务(伙伴的后台任务)交回的文件。 */
+ outputs: ReadonlyArray<{ path: string; name: string }>;
onBack: () => void;
}) {
const { t, i18n } = useTranslation();
@@ -1360,8 +1557,14 @@ function TaskDetail({
const [draft, setDraft] = useState('');
const [sending, setSending] = useState(false);
const title = tile.title || t('bots.workbench.untitled');
+ const archived = tile.type === 'session' && tile.archived === true;
const live = tile.state === 'running' || tile.state === 'waiting' || tile.state === 'queued';
- const statusText = live || !tile.verdict ? t(`bots.workbench.state.${tile.state}`) : t(`bots.workbench.verdict.${tile.verdict}`);
+ const statusText = archived
+ ? t('ccAgent.sidebar.filterStatus.archived')
+ : live || !tile.verdict
+ ? t(`bots.workbench.state.${tile.state}`)
+ : t(`bots.workbench.verdict.${tile.verdict}`);
+ const currentAction = tile.state === 'running' && tile.line.kind === 'action' ? tile.line.text : null;
// 运行中的任务内容在变:状态变化时重读一次,不轮询。
const reloadKey = `${tile.type}:${tile.id}:${tile.state}:${tile.lastActiveMs}`;
@@ -1435,166 +1638,196 @@ function TaskDetail({
void resolveSessionRoute(tile.id).then((target) => navigate(target));
}, [navigate, tile]);
+ const transcriptBody =
+ transcript.kind === 'loading' ? (
+ <div className="flex justify-center py-6">
+ <Spinner size={16} className="text-[var(--text-tertiary)]" role="status" aria-label={t('ccAgent.common.loading')} />
+ </div>
+ ) : transcript.kind === 'failed' ? (
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.detail.loadFailed')}</p>
+ ) : transcript.transcript.items.length === 0 ? (
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.detail.empty')}</p>
+ ) : (
+ <div className="flex flex-col gap-3">
+ {transcript.transcript.truncated ? (
+ <p className="text-center text-11 text-[var(--text-tertiary)]">{t('bots.workbench.detail.truncated')}</p>
+ ) : null}
+ {transcript.transcript.items.map((item, index) =>
+ item.role === 'user' ? (
+ <div
+ key={`${item.at}-${index}`}
+ className="max-w-[90%] self-end whitespace-pre-wrap break-words rounded-xl border border-[var(--msg-user-border)] bg-[var(--msg-user-bg)] px-3.5 py-2.5 text-13 leading-5 text-[var(--text-primary)] [overflow-wrap:anywhere]"
+ >
+ {item.text}
+ </div>
+ ) : (
+ <div
+ key={`${item.at}-${index}`}
+ className="whitespace-pre-wrap break-words text-13 leading-[1.69] text-[var(--text-primary)] [overflow-wrap:anywhere]"
+ >
+ {item.text}
+ </div>
+ ),
+ )}
+ <p className="text-11 text-[var(--text-tertiary)]">
+ {relativeTime(transcript.transcript.items.at(-1)?.at ?? 0, i18n.language, now)}
+ </p>
+ </div>
+ );
+
return (
<div className="flex h-full min-h-0 flex-col bg-[var(--surface)]">
- <div className="flex h-[52px] shrink-0 items-center gap-1 pl-2 pr-2.5">
+ <div className="flex min-h-11 shrink-0 items-center gap-1 border-b border-[var(--border-default)] py-2 pl-1.5 pr-2.5">
<Tip text={t('bots.workbench.detail.back')}>
<button
type="button"
onClick={onBack}
aria-label={t('bots.workbench.detail.back')}
- className={cn(ICON_BUTTON_CLASS, 'size-8 text-[var(--text-secondary)]')}
+ className={cn(ICON_BUTTON_CLASS, 'size-7 text-[var(--text-secondary)]')}
>
- <ArrowLeft size={16} aria-hidden />
+ <ArrowLeft size={15} aria-hidden />
</button>
</Tip>
- <h3 className="min-w-0 flex-1 truncate text-15 font-medium leading-[1.47] text-[var(--text-primary)]">{title}</h3>
+ <nav aria-label={t('bots.workbench.title')} className="flex min-w-0 flex-1 items-center gap-1 text-12 text-[var(--text-secondary)]">
+ <button
+ type="button"
+ onClick={onBack}
+ className="shrink-0 rounded-[8px] px-1 outline-none transition-colors hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t('bots.workbench.title')}
+ </button>
+ <ChevronRight size={12} aria-hidden className="shrink-0 text-[var(--text-tertiary)]" />
+ <h3 title={title} aria-current="page" className="min-w-0 truncate text-13 font-medium leading-5 text-[var(--text-primary)]">
+ {title}
+ </h3>
+ </nav>
+ {tile.type === 'session' && canNavigate ? (
+ <button type="button" onClick={openInTasks} className={DETAIL_ACTION_CLASS}>
+ <SquareArrowOutUpRight size={13} aria-hidden />
+ {t('bots.workbench.detail.openInTasks')}
+ </button>
+ ) : null}
{tile.type === 'session' && tile.state === 'running' ? (
- <Tip text={t('bots.workbench.detail.stop')}>
- <button
- type="button"
- onClick={stop}
- aria-label={t('bots.workbench.detail.stop')}
- className={cn(ICON_BUTTON_CLASS, 'size-8 text-[var(--text-secondary)]')}
- >
- <Square size={12} fill="currentColor" aria-hidden />
- </button>
- </Tip>
+ <button type="button" onClick={stop} aria-label={t('bots.workbench.detail.stop')} className={DETAIL_ACTION_CLASS}>
+ <Square size={10} fill="currentColor" aria-hidden />
+ {t('bots.workbench.detail.stopLabel')}
+ </button>
) : null}
- {tile.type === 'session' && canNavigate ? (
- <Tip text={t('bots.workbench.detail.openInTasks')}>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-3">
+ <div className="mb-4 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {tile.type === 'item' ? <ItemIcon tile={tile} /> : <StateIcon state={tile.state} verdict={tile.verdict} />}
+ <span className="text-[var(--text-secondary)]">
+ {statusText}
+ {tile.state === 'running' && tile.startedAtMs ? ` · ${elapsed(tile.startedAtMs, now)}` : ''}
+ </span>
+ <span aria-hidden>·</span>
+ <span className="min-w-0 truncate">{tile.type === 'item' ? itemLabel(tile, t) : originLabel(tile.origin, t)}</span>
+ {pr ? (
<button
type="button"
- onClick={openInTasks}
- aria-label={t('bots.workbench.detail.openInTasks')}
- className={cn(ICON_BUTTON_CLASS, 'size-8 text-[var(--text-secondary)]')}
+ onClick={() => void window.electronAPI.openExternal?.(pr.url)}
+ aria-label={t('bots.workbench.detail.openPr', { number: pr.number })}
+ className="inline-flex h-6 items-center rounded-full border border-[var(--border-default)] px-2 outline-none transition-colors hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
>
- <SquareArrowOutUpRight size={14} aria-hidden />
+ <PrTag pr={pr} />
</button>
- </Tip>
+ ) : null}
+ </div>
+ {tile.next ? (
+ <DetailSection title={t('bots.workbench.detail.judgment', { name: botName })}>
+ <p className="border-l-2 border-[var(--border-default)] py-1 pl-2.5 text-13 leading-[1.65] text-[var(--text-primary)] [overflow-wrap:anywhere]">
+ {tile.next}
+ </p>
+ </DetailSection>
) : null}
- </div>
- <div className="flex shrink-0 items-center gap-2 px-5 pb-3 text-12 leading-[1.5] text-[var(--text-tertiary)]">
- {tile.type === 'item' ? <ItemIcon tile={tile} /> : <StateIcon state={tile.state} verdict={tile.verdict} />}
- <span className="text-[var(--text-secondary)]">
- {statusText}
- {tile.state === 'running' && tile.startedAtMs ? ` ${elapsed(tile.startedAtMs, now)}` : ''}
- </span>
- <span aria-hidden>·</span>
- <span className="min-w-0 truncate">{tile.type === 'item' ? itemLabel(tile, t) : originLabel(tile.origin, t)}</span>
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto border-t border-[var(--border-default)] px-5 py-4">
- {tile.verdict && tile.next ? (
- <section className="mb-4 rounded-xl border border-[var(--border-default)] px-3.5 py-3">
- <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">
- {t('bots.workbench.detail.judgment', { name: botName })}
+ {currentAction ? (
+ <DetailSection title={t('bots.workbench.detail.doing')}>
+ <p className="flex min-w-0 items-start gap-2 text-12 leading-[1.5]">
+ <span className="flex h-[18px] shrink-0 items-center">
+ <Spinner size={12} aria-hidden className="text-[var(--text-secondary)]" />
+ </span>
+ <span className="min-w-0 text-[var(--status-bar-accent)] [overflow-wrap:anywhere]">{currentAction}</span>
</p>
- <p className="mt-1 text-13 leading-5 text-[var(--text-primary)]">{tile.next}</p>
- </section>
+ </DetailSection>
) : null}
- {pr ? (
- <button
- type="button"
- onClick={() => void window.electronAPI.openExternal?.(pr.url)}
- aria-label={t('bots.workbench.detail.openPr', { number: pr.number })}
- className="mb-3 flex w-full min-w-0 items-center gap-2 rounded-xl border border-[var(--border-default)] px-3.5 py-2.5 text-left outline-none transition-colors hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
- >
- <span className="min-w-0 flex-1">
- <PrTag pr={pr} />
- </span>
- <SquareArrowOutUpRight size={13} aria-hidden className="shrink-0 text-[var(--text-tertiary)]" />
- </button>
+ {outputs.length > 0 ? (
+ <DetailSection title={t('bots.workbench.detail.outputs')}>
+ <div className="flex flex-wrap gap-1.5">
+ {outputs.map((file) => (
+ <button
+ key={file.path}
+ type="button"
+ title={file.path}
+ onClick={() => void window.electronAPI.openPath?.(file.path)}
+ className="inline-flex h-6 min-w-0 max-w-full items-center gap-1 rounded-full bg-[var(--surface-chip)] px-2 text-12 text-[var(--text-secondary)] outline-none transition-colors hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <FileText size={12} aria-hidden className="shrink-0" />
+ <span className="min-w-0 truncate">{file.name}</span>
+ </button>
+ ))}
+ </div>
+ </DetailSection>
) : null}
{tile.type === 'item' ? (
- reference || pr ? (reference ? (
- <button
- type="button"
- onClick={openReference}
- className="flex w-full min-w-0 items-center gap-2 rounded-xl border border-[var(--border-default)] px-3.5 py-2.5 text-left outline-none transition-colors hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
- >
- {/^https:\/\//i.test(reference) ? (
- <Link2 size={14} aria-hidden className="shrink-0 text-[var(--text-tertiary)]" />
- ) : (
- <FileText size={14} aria-hidden className="shrink-0 text-[var(--text-tertiary)]" />
- )}
- <span className="min-w-0 flex-1">
- <span className="block text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.detail.ref')}</span>
- <span className="block truncate text-13 leading-5 text-[var(--text-primary)]">{reference}</span>
- </span>
- </button>
- ) : null) : (
+ reference ? (
+ <DetailSection title={t('bots.workbench.detail.ref')}>
+ <button
+ type="button"
+ onClick={openReference}
+ className="flex w-full min-w-0 items-center gap-2 rounded-xl border border-[var(--border-default)] px-3.5 py-2.5 text-left outline-none transition-colors hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {/^https:\/\//i.test(reference) ? (
+ <Link2 size={14} aria-hidden className="shrink-0 text-[var(--text-tertiary)]" />
+ ) : (
+ <FileText size={14} aria-hidden className="shrink-0 text-[var(--text-tertiary)]" />
+ )}
+ <span className="min-w-0 flex-1 truncate text-13 leading-5 text-[var(--text-primary)]">{reference}</span>
+ </button>
+ </DetailSection>
+ ) : pr ? null : (
<p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.detail.noRef')}</p>
)
- ) : transcript.kind === 'loading' ? (
- <div className="flex justify-center py-6">
- <Spinner size={16} className="text-[var(--text-tertiary)]" role="status" aria-label={t('ccAgent.common.loading')} />
- </div>
- ) : transcript.kind === 'failed' ? (
- <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.detail.loadFailed')}</p>
- ) : transcript.transcript.items.length === 0 ? (
- <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.detail.empty')}</p>
) : (
- <div className="flex flex-col gap-3">
- {transcript.transcript.truncated ? (
- <p className="text-center text-11 text-[var(--text-tertiary)]">{t('bots.workbench.detail.truncated')}</p>
- ) : null}
- {transcript.transcript.items.map((item, index) =>
- item.role === 'user' ? (
- <div
- key={`${item.at}-${index}`}
- className="max-w-[90%] self-end whitespace-pre-wrap break-words rounded-xl border border-[var(--msg-user-border)] bg-[var(--msg-user-bg)] px-3.5 py-2.5 text-13 leading-5 text-[var(--text-primary)] [overflow-wrap:anywhere]"
- >
- {item.text}
- </div>
- ) : (
- <div
- key={`${item.at}-${index}`}
- className="whitespace-pre-wrap break-words text-13 leading-[1.69] text-[var(--text-primary)] [overflow-wrap:anywhere]"
- >
- {item.text}
- </div>
- ),
- )}
- <p className="text-11 text-[var(--text-tertiary)]">
- {relativeTime(transcript.transcript.items.at(-1)?.at ?? 0, i18n.language, now)}
- </p>
- </div>
+ <DetailSection title={t('bots.workbench.detail.recent')}>{transcriptBody}</DetailSection>
)}
</div>
- <form
- className="flex shrink-0 items-center gap-2 px-3 pb-3 pt-2"
- onSubmit={(event) => {
- event.preventDefault();
- void send();
- }}
- >
- <Input
- value={draft}
- onChange={setDraft}
- size="md"
- className="min-w-0 flex-1"
- placeholder={t('bots.workbench.detail.placeholder', { name: botName })}
- ariaLabel={t('bots.workbench.detail.placeholder', { name: botName })}
- disabled={sending}
- onKeyDown={(event) => {
- // 输入法组字时回车只确认候选,不发送。
- if (event.key === 'Enter' && (event.nativeEvent.isComposing || event.keyCode === 229)) event.preventDefault();
+ {archived ? null : (
+ <form
+ className="flex shrink-0 items-center gap-2 border-t border-[var(--border-default)] px-3 pb-3 pt-2.5"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void send();
}}
- />
- <Tip text={t('bots.workbench.detail.send')}>
- <button
- type="submit"
- disabled={sending || !draft.trim()}
- aria-label={t('bots.workbench.detail.send')}
- className={cn(
- ICON_BUTTON_CLASS,
- 'size-8 border border-[var(--border-default)] text-[var(--text-secondary)] disabled:opacity-50',
- )}
- >
- {sending ? <Spinner size={12} aria-hidden /> : <ArrowUp size={14} aria-hidden />}
- </button>
- </Tip>
- </form>
+ >
+ <Input
+ value={draft}
+ onChange={setDraft}
+ size="md"
+ className="min-w-0 flex-1"
+ placeholder={t('bots.workbench.detail.placeholder', { name: botName })}
+ ariaLabel={t('bots.workbench.detail.placeholder', { name: botName })}
+ disabled={sending}
+ onKeyDown={(event) => {
+ // 输入法组字时回车只确认候选,不发送。
+ if (event.key === 'Enter' && (event.nativeEvent.isComposing || event.keyCode === 229)) event.preventDefault();
+ }}
+ />
+ <Tip text={t('bots.workbench.detail.send')}>
+ <button
+ type="submit"
+ disabled={sending || !draft.trim()}
+ aria-label={t('bots.workbench.detail.send')}
+ className={cn(
+ ICON_BUTTON_CLASS,
+ 'size-8 border border-[var(--border-default)] text-[var(--text-secondary)] disabled:opacity-50',
+ )}
+ >
+ {sending ? <Spinner size={12} aria-hidden /> : <ArrowUp size={14} aria-hidden />}
+ </button>
+ </Tip>
+ </form>
+ )}
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx b/apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx
deleted file mode 100644
index 40a52345e6..0000000000
--- a/apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useAgentIslandActivity } from '@/state/agentIslandActivity';
-import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
-import { readWorkingPhase, WORKING_PHASE_KEYS } from '../../../shared/workingStatus';
-import type { CSSProperties, ReactNode } from 'react';
-import { useTranslation } from 'react-i18next';
-import type { ChatMessage as Message } from '@/lib/makerChatStore';
-import { Spinner } from '@/components/ui/spinner';
-import { useWorkingStatusCopy } from './useWorkingStatusCopy';
-import { localizePlainAgentStatus, resolvePlainAgentPhase } from '@/features/cc-agent/lib/localizeAgentStatus';
-import { WorkingStatusText } from '@/features/cc-agent/WorkingStatusText';
-
-export function BotWorkingStatus({
- visible, status, messages, startedAt, foregroundRunning, backgroundWorkActive, avatar, inputWidth, sessionId, remote,
-}: {
- sessionId?: string;
- remote?: { deviceId: string; botId: string };
- visible: boolean;
- status: string;
- messages: readonly Message[];
- startedAt: number | null;
- foregroundRunning: boolean;
- backgroundWorkActive: boolean;
- avatar: ReactNode;
- inputWidth?: CSSProperties['width'];
-}) {
- const { t } = useTranslation();
- // A Workflow can run alongside the foreground turn. Only background-only
- // work lacks reliable foreground events for a more specific caption.
- const processingOnly = backgroundWorkActive && !foregroundRunning;
- const localActivity = useAgentIslandActivity(sessionId ?? '');
- const remoteActivity = useRemoteSessionActivity(sessionId ?? '', remote?.deviceId);
- const activity = remote ? remoteActivity : localActivity;
- const waiting = status === 'Waiting on approval' || status === 'Waiting on input';
- const sharedPhase = !waiting && activity?.phase === 'running' ? readWorkingPhase(activity.workingPhase) : null;
- const phase = processingOnly ? 'processing' : sharedPhase ?? resolvePlainAgentPhase(status, messages, startedAt);
- const polished = useWorkingStatusCopy(sessionId, startedAt, phase, visible && !processingOnly, remote);
- // Terminal events bypass cadence and opacity: never linger with working copy.
- if (!visible) return null;
- const text = processingOnly
- ? t('ccAgent.agentStatus.processing')
- : sharedPhase ? t(WORKING_PHASE_KEYS[sharedPhase]) : localizePlainAgentStatus(status, messages, startedAt, t);
- return (
- <div
- data-testid="bot-working-indicator"
- data-working-phase={phase}
- data-working-copy-source={polished ? 'generated' : 'default'}
- role="status"
- aria-live="polite"
- className="mx-auto flex min-w-0 select-none items-center gap-2 px-2 py-[6px] text-12 text-[var(--text-tertiary)]"
- style={{ width: inputWidth }}
- >
- {avatar}
- <Spinner size={12} />
- <WorkingStatusText key={startedAt} text={polished ?? text} />
- </div>
- );
-}
diff --git a/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx b/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx
index ebe3e0f1dd..d1fb970167 100644
--- a/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx
@@ -17,6 +17,10 @@ import { chatErrorKey } from './ChatServerControls';
import { refreshBotGroups } from './botGroupStore';
const key = (name: string) => `bots.groupChat.server.settings.${name}`;
+/** Labels shared with the local group settings, so both read the same. */
+const shared = (name: string) => `bots.groupChat.settings.${name}`;
+const REPLY_MODE_LABELS = { all: shared('replyModeAll'), mentioned: shared('replyModeMentioned') } as const;
+const SPEAKING_MODE_LABELS = { auto: shared('speakingModeAuto'), sequential: shared('speakingModeSequential') } as const;
const api = () => window.electronAPI.maker.chatServer;
/** Shared group identity and companion grants are server-authoritative. */
@@ -117,11 +121,11 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {
onChange={event => { editGroup(); setTopic(event); }} />}</FormField>
<FormField label={t(key('description'))}>{props => <Input {...props} value={description} maxLength={2000} disabled={!manager || busy}
onChange={event => { editGroup(); setDescription(event); }} />}</FormField>
- <FormField label={t(key('replyMode'))}>{props => <Select {...props} label={t(key('replyMode'))} value={replyMode}
- disabled={!manager || busy} options={['all', 'mentioned'].map(value => ({ value, label: t(key(value)) }))}
+ <FormField label={t(shared('replyMode'))}>{props => <Select {...props} label={t(shared('replyMode'))} value={replyMode}
+ disabled={!manager || busy} options={(['all', 'mentioned'] as const).map(value => ({ value, label: t(REPLY_MODE_LABELS[value]) }))}
onValueChange={value => { editGroup(); setReplyMode(value as typeof replyMode); }} />}</FormField>
- <FormField label={t(key('speakingMode'))}>{props => <Select {...props} label={t(key('speakingMode'))} value={speakingMode}
- disabled={!manager || busy} options={['auto', 'sequential'].map(value => ({ value, label: t(key(value)) }))}
+ <FormField label={t(shared('speakingMode'))}>{props => <Select {...props} label={t(shared('speakingMode'))} value={speakingMode}
+ disabled={!manager || busy} options={(['auto', 'sequential'] as const).map(value => ({ value, label: t(SPEAKING_MODE_LABELS[value]) }))}
onValueChange={value => { editGroup(); setSpeakingMode(value as typeof speakingMode); }} />}</FormField>
{manager && <Button type="submit" size="sm" variant="secondary" disabled={busy || !name.trim()}>{t(key('save'))}</Button>}
</form>
@@ -193,7 +197,7 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {
{manageable && <div className="flex flex-wrap gap-2">
<Button size="sm" variant="secondary" disabled={busy} onClick={() => void mutate({ type: 'member', actorId, action: 'role', role: member.role === 'admin' ? 'member' : 'admin' })}>
{t(key(member.role === 'admin' ? 'removeAdmin' : 'makeAdmin'))}</Button>
- <Button size="sm" variant="secondary" disabled={busy} onClick={() => void confirmed({ type: 'member', actorId, action: 'remove' }, t(key('removeTitle'), { name: member.name }), t(key('removeHint')))}>{t(key('remove'))}</Button>
+ <Button size="sm" variant="secondary" disabled={busy} onClick={() => void confirmed({ type: 'member', actorId, action: 'remove' }, t(key('removeTitle'), { name: member.name }), t(key('removeHint')))}>{t(shared('remove'))}</Button>
</div>}
</div>}
</div>;
diff --git a/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx b/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
index de2411464b..fa07ac6fff 100644
--- a/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
@@ -19,52 +19,97 @@ const emojiChoices = ['👍', '❤️', '😂', '🎉', '👀', '🙏', '✅', '
const iconClass = 'flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] disabled:opacity-50';
export { chatErrorKey } from './chatError';
-/**
- * `onQuote` is 引用回复: a new main-timeline message that quotes this one. `onReply` opens the
- * message's Thread (话题) — 创建话题 before anyone answered, 查看话题 after.
- */
-export function ChatMessageActions({ groupId, shareScope, message, align = message.isSelf ? 'right' : 'left', onQuote, onReply, onChanged }: {
- groupId?: string; shareScope: string; message: BotGroupMessageView; align?: 'left' | 'right'; onQuote?: () => void; onReply?: () => void; onChanged: () => void;
-}) {
+/** Adds or removes the current actor's reaction; the caller re-reads the authoritative message. */
+function useChatReaction(groupId: string | undefined, messageId: string, onChanged: () => void) {
const { t } = useTranslation();
const [busy, setBusy] = useState(false);
const busyRef = useRef(false);
- const [picker, setPicker] = useState(false);
async function react(emoji: string, present: boolean) {
if (!groupId || busyRef.current) return;
- busyRef.current = true; setBusy(true); setPicker(false);
+ busyRef.current = true; setBusy(true);
const owner = getDataOwnerGeneration();
try {
- const result = await api().react({ groupId, messageId: message.id, emoji, present });
+ const result = await api().react({ groupId, messageId, emoji, present });
if (!isDataOwnerGenerationCurrent(owner)) return;
if (!result.ok) toast.error(t(chatErrorKey(result.errorCode)));
else onChanged();
} catch { if (isDataOwnerGenerationCurrent(owner)) toast.error(t(key('requestFailed'))); }
finally { busyRef.current = false; setBusy(false); }
}
+ return { busy, react };
+}
+
+interface ChatMessageActionProps {
+ groupId?: string; shareScope: string; message: BotGroupMessageView; align?: 'left' | 'right';
+ /** 引用回复: a new main-timeline message that quotes this one. */
+ onQuote?: () => void;
+ /** Opens the message's Thread (话题) — 创建话题 before anyone answered, 查看话题 after. */
+ onReply?: () => void;
+ onChanged: () => void;
+}
+
+/** The reactions under a message's text; each chip toggles the current actor's reaction. */
+export function ChatMessageReactions({ groupId, message, align = 'left', onChanged }: Pick<ChatMessageActionProps, 'groupId' | 'message' | 'align' | 'onChanged'>) {
+ const { t } = useTranslation();
+ const { busy, react } = useChatReaction(groupId, message.id, onChanged);
+ if (!message.reactions?.length) return null;
+ return (
+ <div {...{ [SHARE_EXCLUDE_ATTR]: '' }} className={`mt-1 flex flex-wrap items-center gap-1 ${align === 'right' ? 'justify-end' : ''}`}>
+ {message.reactions.map(reaction => (
+ <Button key={reaction.emoji} variant={reaction.me ? 'primary' : 'secondary'} size="sm" compact
+ disabled={busy || !groupId} aria-pressed={reaction.me}
+ aria-label={t(key('reactionCount'), { emoji: reaction.emoji, count: reaction.count })}
+ onClick={() => void react(reaction.emoji, !reaction.me)}>
+ <span>{reaction.emoji}</span><span>{reaction.count}</span>
+ </Button>
+ ))}
+ </div>
+ );
+}
+
+function ChatMessageToolbar({ groupId, shareScope, message, align = 'left', onQuote, onReply, onChanged, picker, onPickerChange }: ChatMessageActionProps & {
+ picker: boolean; onPickerChange: (open: boolean) => void;
+}) {
+ const { t } = useTranslation();
+ const { busy, react } = useChatReaction(groupId, message.id, onChanged);
+ return (
+ <MessageActionBar copyText={message.content} createdAt={message.createdAt ? new Date(message.createdAt).toISOString() : undefined}
+ align={align} hovered simplifiedBotConversation
+ onShareAsImage={() => shareSelectionStore.enter(shareScope, message.id)}
+ quoteAction={onQuote ? { onClick: onQuote, label: t(key('quoteReply')) } : undefined}
+ replyAction={onReply ? { onClick: onReply, count: message.replyCount,
+ label: message.replyCount ? t(key('openTopic'), { count: message.replyCount }) : t(key('startTopic')) } : undefined}
+ reactionAction={groupId ? { label: t(key('addReaction')), open: picker, onOpenChange: onPickerChange, disabled: busy,
+ content: <div className="grid grid-cols-6 gap-1">{emojiChoices.map(emoji =>
+ <button type="button" key={emoji} className={iconClass} aria-label={emoji}
+ onClick={() => { onPickerChange(false); void react(emoji, !message.reactions?.some(r => r.emoji === emoji && r.me)); }}>{emoji}</button>)}</div>,
+ } : undefined} />
+ );
+}
+
+/**
+ * The message toolbar (copy, share, 引用回复, 话题, reaction, time) floating at the top right of
+ * its message, Slack-style. It shows while the message (`group/message`) is hovered, while
+ * keyboard focus is inside, while its reaction picker is open, and always on touch screens.
+ */
+export function ChatMessageHoverActions(props: ChatMessageActionProps) {
+ const [picker, setPicker] = useState(false);
+ return (
+ <div {...{ [SHARE_EXCLUDE_ATTR]: '' }} data-bot-group-message-actions="" data-open={picker ? '' : undefined}
+ className="pointer-events-none absolute -top-3.5 right-1 z-10 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-1 py-0.5 opacity-0 transition-opacity duration-[var(--motion-fast)] ease-[var(--motion-ease-out)] focus-within:pointer-events-auto focus-within:opacity-100 group-hover/message:pointer-events-auto group-hover/message:opacity-100 data-[open]:pointer-events-auto data-[open]:opacity-100 motion-reduce:transition-none [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">
+ <ChatMessageToolbar {...props} picker={picker} onPickerChange={setPicker} />
+ </div>
+ );
+}
+
+/** Reactions and the toolbar stacked under the text, always visible. */
+export function ChatMessageActions(props: ChatMessageActionProps) {
+ const [picker, setPicker] = useState(false);
+ const align = props.align ?? (props.message.isSelf ? 'right' : 'left');
return (
<div {...{ [SHARE_EXCLUDE_ATTR]: '' }} className="mt-1 flex flex-col gap-1">
- {!!message.reactions?.length && <div className={`flex flex-wrap items-center gap-1 ${align === 'right' ? 'justify-end' : ''}`}>
- {message.reactions.map(reaction => (
- <Button key={reaction.emoji} variant={reaction.me ? 'primary' : 'secondary'} size="sm" compact
- disabled={busy || !groupId} aria-pressed={reaction.me}
- aria-label={t(key('reactionCount'), { emoji: reaction.emoji, count: reaction.count })}
- onClick={() => void react(reaction.emoji, !reaction.me)}>
- <span>{reaction.emoji}</span><span>{reaction.count}</span>
- </Button>
- ))}
- </div>}
- <MessageActionBar copyText={message.content} createdAt={message.createdAt ? new Date(message.createdAt).toISOString() : undefined}
- align={align} hovered simplifiedBotConversation
- onShareAsImage={() => shareSelectionStore.enter(shareScope, message.id)}
- quoteAction={onQuote ? { onClick: onQuote, label: t(key('quoteReply')) } : undefined}
- replyAction={onReply ? { onClick: onReply, count: message.replyCount,
- label: message.replyCount ? t(key('openTopic'), { count: message.replyCount }) : t(key('startTopic')) } : undefined}
- reactionAction={groupId ? { label: t(key('addReaction')), open: picker, onOpenChange: setPicker, disabled: busy,
- content: <div className="grid grid-cols-6 gap-1">{emojiChoices.map(emoji =>
- <button type="button" key={emoji} className={iconClass} aria-label={emoji}
- onClick={() => void react(emoji, !message.reactions?.some(r => r.emoji === emoji && r.me))}>{emoji}</button>)}</div>,
- } : undefined} />
+ <ChatMessageReactions {...props} align={align} />
+ <ChatMessageToolbar {...props} align={align} picker={picker} onPickerChange={setPicker} />
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
index 2c83422814..3aee5dbbb8 100644
--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
@@ -1,32 +1,41 @@
-import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';
+/**
+ * 话题(Thread)面板:与主时间线同一套消息行(BotGroupTimelineItem)与密度规则——根消息、
+ * 「N 条回复」分隔、回复按作者五分钟合并;有新回复且读者在底部时跟到底。
+ *
+ * 读取:进入读一次,之后本群每条推送重读;同一时刻只有一个读取在飞,期间的推送合并成一次
+ * 补读。回复用群聊同一个输入框的话题模式(BotGroupComposer `mode="thread"`),发出即乐观插入,
+ * 服务器的回复到了原地替换;失败撤掉、文字放回,原因写在输入框上方。
+ */
+import { Fragment, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { SendButton } from '@/components/new-chat/SendButton';
import { Button } from '@/components/ui/button';
import { Tip } from '@/components/ui/tooltip';
-import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
import { ShareSelectionBar } from '@/components/chat/ShareSelectionBar';
-import { ShareMessageCheckbox } from '@/components/chat/ShareMessageCheckbox';
import { shareSelectionStore, useShareSelectionActive } from '@/components/chat/shareSelectionStore';
-import { SHARE_SESSION_ATTR, SHARE_MESSAGE_ATTR } from '@/lib/shareConversationImage';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent, isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';
-import type { BotGroupDetail, BotGroupExecutionFailureView, BotGroupMention, BotGroupMessageView } from '../../../shared/botGroupChat';
-import { isBotGroupRuntimeFailureCode, resolveBotGroupQuote } from '../../../shared/botGroupChat';
+import type { BotGroupDetail, BotGroupExecutionFailureView, BotGroupMessageView } from '../../../shared/botGroupChat';
+import { resolveBotGroupQuote } from '../../../shared/botGroupChat';
+import { botGroupThreadDraftKey } from './botGroupAttachments';
import { refreshBotGroups } from './botGroupStore';
import { mergeBotGroupMessages, projectBotGroupExecutionFailures } from './botGroupPresentation';
-import { BotAvatar } from './BotAvatar';
-import { BotGroupQuoteBlock } from './BotGroupQuote';
+import { BotGroupComposer, type BotGroupOutgoingMessage, type BotGroupSendOutcome } from './BotGroupComposer';
+import { BotGroupTimelineItem } from './BotGroupTimelineItem';
import {
- BOT_GROUP_COMPOSER_CARD, BOT_GROUP_COMPOSER_COLUMN, BOT_GROUP_COMPOSER_DOCK, BOT_GROUP_COMPOSER_FOOTER, BOT_GROUP_COMPOSER_FOOTER_START, BOT_GROUP_COMPOSER_INPUT,
- fitBotGroupComposerInput, keepBotGroupComposerInputFocus, useRefitBotGroupComposerInputOnResize,
-} from './botGroupComposerChrome';
-import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';
-import { ChatMessageActions, chatErrorKey } from './ChatServerControls';
-import { useBotGroupMentionPicker } from './useBotGroupMentionPicker';
+ botGroupMemberDisplayName,
+ botGroupOwnedBotNames,
+ layoutBotGroupTimeline,
+ matchBotGroupPendingSends,
+ pendingBotGroupMessage,
+ pendingBotGroupMessageId,
+ stabilizeById,
+ type BotGroupPendingSend,
+ type BotGroupTimelineMessage,
+} from './BotGroupTimelineModel';
+import { chatErrorKey } from './ChatServerControls';
const key = (name: string) => `bots.groupChat.server.${name}`;
-const sameBotGroupMentions = (a: BotGroupMention, b: BotGroupMention) =>
- a.all === b.all && a.botIds.length === b.botIds.length && a.botIds.every((botId, index) => botId === b.botIds[index]);
const api = () => window.electronAPI.maker.chatServer;
+const STICK_TO_BOTTOM_PX = 48;
export function animateThreadPanelWidth(panel: HTMLElement, from: string, to: string): Animation | null {
const style = getComputedStyle(panel);
@@ -38,35 +47,19 @@ export function animateThreadPanelWidth(panel: HTMLElement, from: string, to: st
});
}
-function ThreadMessage({ group, message, quoteSources, shareScope, sharing, onChanged }: { group: BotGroupDetail; message: BotGroupMessageView; quoteSources: readonly BotGroupMessageView[]; shareScope: string; sharing: boolean; onChanged: () => void }) {
- const member = group.members.find(m => m.botId === message.authorBotId);
- if (message.kind === 'notice' && isBotGroupRuntimeFailureCode(message.runtimeFailureCode)) return <BotGroupRuntimeFailureNotice name={message.authorName || member?.name || ''} code={message.runtimeFailureCode} />;
- return <article {...{ [SHARE_SESSION_ATTR]: shareScope, [SHARE_MESSAGE_ATTR]: message.id }}
- className={`relative flex min-w-0 gap-2.5 ${sharing ? 'ml-10' : ''}`}>
- {sharing && <ShareMessageCheckbox clientId={message.id} />}
- <BotAvatar bot={{ name: message.authorName, avatar: member?.avatar ?? null, avatarUrl: member?.avatarUrl, avatarColor: member?.avatarColor ?? null }} size="sm" />
- <div className="min-w-0 flex-1 space-y-1">
- <p className="text-13 font-medium leading-7 text-[var(--text-primary)]">{message.authorName}</p>
- {/* A 话题 root may itself be a 引用回复; its original lives in the main timeline. */}
- {message.quote ? <BotGroupQuoteBlock display={resolveBotGroupQuote(message.quote, quoteSources)} /> : null}
- <div className="break-words text-14 leading-relaxed text-[var(--text-primary)]">
- <MarkdownRenderer workingDir="" content={message.content} allowPrivilegedLinks={false} />
- </div>
- <ChatMessageActions groupId={group.id} shareScope={shareScope} message={message} align="left" onChanged={onChanged} />
- </div>
- </article>;
-}
-
/**
* `quoteSources` are the main timeline's verified messages (older pages included), so a
* 话题 root's quote reads the same as it does in the timeline; without them, the latest page.
*/
export function ChatThreadPanel({ group, rootId, quoteSources = group.messages, onClose }: { group: BotGroupDetail; rootId: string; quoteSources?: readonly BotGroupMessageView[]; onClose: () => void }) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
+ const locale = i18n.language;
const titleId = useId();
const shareScope = `bot-group:${group.id}:thread:${rootId}`;
const sharing = useShareSelectionActive(shareScope);
const contentRef = useRef<HTMLDivElement>(null);
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const stickToBottomRef = useRef(true);
const panelRef = useRef<HTMLElement>(null);
useEffect(() => {
const panel = panelRef.current;
@@ -80,63 +73,139 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,
const [executionFailures, setExecutionFailures] = useState<BotGroupExecutionFailureView[]>([]);
const [replies, setReplies] = useState<BotGroupMessageView[]>([]);
const [hasMore, setHasMore] = useState(false);
- const [text, setText] = useState('');
- const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
- const request = useRef(0);
- const attempt = useRef<{ text: string; roster: BotGroupDetail['members']; id: string; mentions: BotGroupMention } | null>(null);
- const sending = useRef(false);
- const inputRef = useRef<HTMLTextAreaElement>(null);
- const allLabel = t('bots.groupChat.mention.all');
- const allLabels = useMemo(() => [allLabel, '所有人', 'all', 'everyone'], [allLabel]);
- // Same @ picker as the main composer.
- const mention = useBotGroupMentionPicker({ text, members: group.members, textareaRef: inputRef, allLabels, onTextChange: value => {
- setText(value);
- if (attempt.current?.text !== value) attempt.current = null;
- } });
- useLayoutEffect(() => { if (inputRef.current) fitBotGroupComposerInput(inputRef.current); }, [text, sharing]);
- useRefitBotGroupComposerInputOnResize(inputRef, !sharing);
- const load = useCallback(async (before?: number) => {
- const version = ++request.current, owner = getDataOwnerGeneration();
- const current = () => version === request.current && isDataOwnerGenerationCurrent(owner);
+ const [pendingSends, setPendingSends] = useState<BotGroupPendingSend[]>([]);
+ const repliesRef = useRef(replies);
+ repliesRef.current = replies;
+ const aliveRef = useRef(true);
+ const inFlightRef = useRef(false);
+ const queuedRef = useRef(false);
+
+ const read = useCallback(async (before?: number) => {
+ const owner = getDataOwnerGeneration();
+ const current = () => aliveRef.current && isDataOwnerGenerationCurrent(owner);
+ const shown = repliesRef.current;
try {
- const result = await api().thread({ groupId: group.id, rootId, before, sourceMessageIds: replies.map(message => message.id) });
+ const result = await api().thread({ groupId: group.id, rootId, before, sourceMessageIds: shown.map(message => message.id) });
if (!current()) return;
if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }
- setRoot(result.root); setError('');
+ setRoot(previous => (previous && JSON.stringify(previous) === JSON.stringify(result.root) ? previous : result.root));
+ setError('');
setExecutionFailures(result.executionFailures ?? []);
- setReplies(previous => mergeBotGroupMessages(previous, result.replies));
- if (before || replies.length === 0) setHasMore(result.hasMore);
+ setReplies(previous => stabilizeById(previous, mergeBotGroupMessages(previous, result.replies)));
+ if (before || shown.length === 0) setHasMore(result.hasMore);
} catch { if (current()) setError(t(key('requestFailed'))); }
- }, [group.id, rootId, t, replies]);
- const loadRef = useRef(load); loadRef.current = load;
+ }, [group.id, rootId, t]);
+ /** One refresh in flight; pushes meanwhile collapse into one follow-up read. */
+ const refresh = useCallback(() => {
+ if (inFlightRef.current) { queuedRef.current = true; return; }
+ inFlightRef.current = true;
+ void read().finally(() => {
+ inFlightRef.current = false;
+ if (queuedRef.current && aliveRef.current) {
+ queuedRef.current = false;
+ refresh();
+ }
+ });
+ }, [read]);
+ const refreshRef = useRef(refresh);
+ refreshRef.current = refresh;
useEffect(() => {
- void loadRef.current();
+ aliveRef.current = true;
+ refreshRef.current();
const stop = window.electronAPI.maker.onBotGroupChanged((event, stamp) => {
- if (isDataOwnerPushCurrent(stamp) && event.groupId === group.id) void loadRef.current();
+ if (isDataOwnerPushCurrent(stamp) && event.groupId === group.id) refreshRef.current();
});
- return () => { request.current++; stop(); };
+ return () => { aliveRef.current = false; stop(); };
}, [group.id, rootId]);
- async function send() {
- if (group.archived || sending.current || !text.trim()) return;
- sending.current = true; setBusy(true); setError('');
- const owner = getDataOwnerGeneration();
- // A retry reuses the attempt only for the same text and the same targets (bot-group-chat.md).
- // Targets are re-resolved against the attempt's own roster: a roster refresh alone changes nothing
- // and the host still rejects a departed target; re-picking someone else gets a new clientId.
- const previous = attempt.current;
- const current = previous && previous.text === text && sameBotGroupMentions(mention.resolve(text, previous.roster), previous.mentions)
- ? previous : { text, roster: group.members, id: crypto.randomUUID(), mentions: mention.resolve(text) };
- attempt.current = current;
- try {
- const result = await api().reply({ groupId: group.id, rootId, text: current.text, clientId: current.id,
- mentions: current.mentions });
- if (!isDataOwnerGenerationCurrent(owner)) return;
- if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }
- setText(''); mention.reset(); attempt.current = null; void loadRef.current(); refreshBotGroups();
- } catch { if (isDataOwnerGenerationCurrent(owner)) setError(t(key('requestFailed'))); }
- finally { sending.current = false; setBusy(false); }
- }
+
+ const members = group.members;
+ const mentionLabels = useMemo(
+ () => [t('bots.groupChat.mention.all'), ...members.flatMap((member) => [member.name, botGroupMemberDisplayName(member), member.nickname || member.displayName || member.name])],
+ [members, t],
+ );
+ const memberById = useMemo(() => new Map(members.map((member) => [member.botId, member])), [members]);
+ const separator = t('bots.groupChat.memberSeparator');
+
+ const realReplies = useMemo(() => projectBotGroupExecutionFailures(replies, executionFailures), [replies, executionFailures]);
+ const pendingMatches = useMemo(() => matchBotGroupPendingSends(pendingSends, realReplies), [pendingSends, realReplies]);
+ const adoptedKeysRef = useRef(new Map<string, string>());
+ for (const [clientId, messageId] of pendingMatches) adoptedKeysRef.current.set(messageId, pendingBotGroupMessageId(clientId));
+ useEffect(() => {
+ if (pendingMatches.size === 0) return;
+ setPendingSends((previous) => previous.filter((send) => !pendingMatches.has(send.clientId)));
+ }, [pendingMatches]);
+ const replyRows = useMemo<BotGroupTimelineMessage[]>(
+ () => [...realReplies, ...pendingSends.filter((send) => !pendingMatches.has(send.clientId)).map(pendingBotGroupMessage)],
+ [realReplies, pendingSends, pendingMatches],
+ );
+ const rootRows = useMemo(() => projectBotGroupExecutionFailures(root ? [root] : [], executionFailures), [root, executionFailures]);
+ const layout = useMemo(() => layoutBotGroupTimeline(replyRows), [replyRows]);
+ const lastRealSequenceRef = useRef(0);
+ lastRealSequenceRef.current = realReplies[realReplies.length - 1]?.sequence ?? 0;
+
+ const onChanged = useCallback(() => refreshRef.current(), []);
+ const onSendStart = useCallback((message: BotGroupOutgoingMessage) => {
+ stickToBottomRef.current = true;
+ setPendingSends((previous) => [
+ ...previous.filter((send) => send.clientId !== message.clientId),
+ { ...message, createdAt: Date.now(), afterSequence: lastRealSequenceRef.current },
+ ]);
+ }, []);
+ const onSendSettled = useCallback((clientId: string, outcome: BotGroupSendOutcome) => {
+ setPendingSends((previous) => outcome.ok
+ ? previous.map((send) => (send.clientId === clientId ? { ...send, messageId: outcome.messageId } : send))
+ : previous.filter((send) => send.clientId !== clientId));
+ }, []);
+ const sendReply = useCallback(
+ (input: { text: string; clientId: string; mentions: BotGroupMessageView['mentions'] }) => api().reply({ groupId: group.id, rootId, ...input }),
+ [group.id, rootId],
+ );
+ const onSent = useCallback(() => { refreshRef.current(); refreshBotGroups(); }, []);
+
+ // Follow new replies while the reader is at the bottom, including content that grows later.
+ const lastKey = replyRows[replyRows.length - 1]?.id ?? '';
+ useLayoutEffect(() => {
+ const element = scrollRef.current;
+ if (element && stickToBottomRef.current) element.scrollTop = element.scrollHeight;
+ }, [lastKey, replyRows.length, root]);
+ useEffect(() => {
+ const scroller = scrollRef.current;
+ const content = contentRef.current;
+ if (!scroller || !content || typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(() => {
+ if (stickToBottomRef.current) scroller.scrollTop = scroller.scrollHeight;
+ });
+ observer.observe(content);
+ observer.observe(scroller);
+ return () => observer.disconnect();
+ }, []);
+
+ const renderRow = (message: BotGroupTimelineMessage, continued: boolean) => {
+ const member = message.authorBotId ? memberById.get(message.authorBotId) : undefined;
+ const authorName = (member && message.authorKind !== 'system' ? botGroupMemberDisplayName(member) : '') || message.authorName || member?.name || '';
+ const owned = message.authorKind === 'user' && message.isSelf === false ? botGroupOwnedBotNames(member, members).join(separator) : '';
+ return (
+ <BotGroupTimelineItem
+ message={message}
+ continued={continued}
+ authorName={authorName}
+ avatar={{ name: authorName, avatar: member?.avatar ?? null, avatarUrl: member?.avatarUrl, avatarColor: member?.avatarColor ?? null }}
+ ownerOf={owned || undefined}
+ members={members}
+ mentionLabels={mentionLabels}
+ locale={locale}
+ shareScope={shareScope}
+ sharing={sharing}
+ reactionGroupId={group.id}
+ // A 话题 root may itself be a 引用回复; its original lives in the main timeline.
+ quoteDisplay={message.quote ? resolveBotGroupQuote(message.quote, quoteSources) : undefined}
+ onChanged={onChanged}
+ />
+ );
+ };
+ const replyCount = Math.max(root?.replyCount ?? 0, realReplies.filter(reply => reply.kind === 'message').length);
+
return <aside ref={panelRef} aria-labelledby={titleId}
className="flex h-full min-w-0 w-1/2 max-w-[min(50%,28rem)] shrink-0 flex-col overflow-hidden border-l border-[var(--border-default)] bg-[var(--surface)]">
<header className="flex h-14 shrink-0 items-center justify-between border-b border-[var(--border-default)] px-5">
@@ -147,35 +216,42 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,
aria-label={t('bots.close')} onClick={onClose}><X size={17} aria-hidden /></Button>
</Tip>
</header>
- <div ref={contentRef} className="min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4">
- {projectBotGroupExecutionFailures(root ? [root] : [], executionFailures).map(message => <ThreadMessage key={message.id} quoteSources={quoteSources} shareScope={shareScope} sharing={sharing} group={group} message={message} onChanged={() => void loadRef.current()} />)}
- <div className="border-t border-[var(--border-default)] pt-3 text-12 text-[var(--text-tertiary)]">{t(key('replies'))}</div>
- {hasMore && <Button variant="secondary" size="sm" onClick={() => void loadRef.current(replies[0]?.sequence)}>{t('bots.groupChat.timeline.loadEarlier')}</Button>}
- {projectBotGroupExecutionFailures(replies, executionFailures).map(message => <ThreadMessage key={message.id} quoteSources={quoteSources} shareScope={shareScope} sharing={sharing} group={group} message={message} onChanged={() => void loadRef.current()} />)}
+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto px-5 pb-4 pt-3"
+ onScroll={(event) => {
+ const element = event.currentTarget;
+ stickToBottomRef.current = element.scrollHeight - element.scrollTop - element.clientHeight < STICK_TO_BOTTOM_PX;
+ }}>
+ <div ref={contentRef} className="flex min-w-0 flex-col">
+ {rootRows.map(message => <Fragment key={message.id}>{renderRow(message, false)}</Fragment>)}
+ <div data-testid="bot-group-thread-replies" className="mt-3 flex select-none items-center gap-3 text-12 text-[var(--text-tertiary)]">
+ <span className="shrink-0">{replyCount > 0 ? t(key('replyCount'), { count: replyCount }) : t(key('replies'))}</span>
+ <span aria-hidden className="h-px flex-1 bg-[var(--border-default)]" />
+ </div>
+ {hasMore && <div className="mt-2"><Button variant="secondary" size="sm" onClick={() => void read(replies[0]?.sequence)}>{t('bots.groupChat.timeline.loadEarlier')}</Button></div>}
+ {replyRows.map(message => (
+ <Fragment key={adoptedKeysRef.current.get(message.id) ?? message.id}>
+ {renderRow(message, layout.get(message.id)?.continued ?? false)}
+ </Fragment>
+ ))}
+ </div>
</div>
{sharing ? <ShareSelectionBar sessionId={shareScope} barWidth="100%"
- getContentWidth={() => contentRef.current?.querySelector('article')?.getBoundingClientRect().width ?? 400} /> : <div className={BOT_GROUP_COMPOSER_DOCK}><div className={BOT_GROUP_COMPOSER_COLUMN}>
- {error && <p role="alert" className="mb-2 px-1 text-13 leading-5 text-[var(--error-fg)]">{error}</p>}
- {/* Read-only also means no @ picks while sending. */}
- {busy ? null : mention.list}
- {/* Same card as the main group's composer; a sending reply stays read-only (and focused) until main answers. */}
- <div className={BOT_GROUP_COMPOSER_CARD} aria-busy={busy || undefined}>
- <textarea ref={inputRef} rows={1} aria-label={t(key('replyPlaceholder'))} placeholder={t(key('replyPlaceholder'))} value={text}
- {...mention.textareaProps} onChange={e => mention.onChange(e.target.value)}
- maxLength={8000} readOnly={busy} disabled={group.archived} className={BOT_GROUP_COMPOSER_INPUT} onKeyDown={e => {
- if (e.nativeEvent.isComposing || e.keyCode === 229 || (!busy && mention.onKeyDown(e))) return;
- if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(); }
- }} />
- <div className={BOT_GROUP_COMPOSER_FOOTER}>
- {/* Send options for this reply go here, before the button. */}
- <div className={BOT_GROUP_COMPOSER_FOOTER_START} />
- <span className="inline-flex rounded-full" onMouseDown={keepBotGroupComposerInputFocus(inputRef)}>
- <Tip text={t(key('sendReply'))}>
- <SendButton ariaLabel={t(key('sendReply'))} disabled={group.archived || busy || !text.trim()} onClick={() => void send()} />
- </Tip>
- </span>
- </div>
+ getContentWidth={() => contentRef.current?.querySelector('article')?.getBoundingClientRect().width ?? 400} /> : <>
+ {error && <p role="alert" className="px-4 pt-3 text-13 text-[var(--error-fg)]">{error}</p>}
+ <div className="border-t border-[var(--border-default)]">
+ <BotGroupComposer
+ mode="thread"
+ groupId={group.id}
+ draftKey={botGroupThreadDraftKey(group.id, rootId)}
+ members={members}
+ running={false}
+ disabled={!!group.archived}
+ sendReply={sendReply}
+ onSendStart={onSendStart}
+ onSendSettled={onSendSettled}
+ onSent={onSent}
+ />
</div>
- </div></div>}
+ </>}
</aside>;
}
diff --git a/apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx b/apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx
deleted file mode 100644
index d8d9377a39..0000000000
--- a/apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx
+++ /dev/null
@@ -1,233 +0,0 @@
-import { useCallback, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
-import type { Session } from '@/lib/ccAgent.types';
-import { SessionCard } from '@/features/cc-agent/sidebar/SessionCard';
-import type { SessionMoveTarget } from '@/features/cc-agent/sidebar/sessionMoveTarget';
-import { toStoredSessionTitle } from '@/features/cc-agent/lib/sessionDisplayTitle';
-import { useSessionLifecycleActions } from '@/features/cc-agent/hooks/useSessionLifecycleActions';
-import { useSessionDisplayRunningState } from '@/features/cc-agent/hooks/useSessionDisplayRunningState';
-import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';
-import { useAttachedSessionIds } from '@/hooks/useAttachedSessionIds';
-import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
-import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
-import { resolveWorktreeRemovalPreflight } from '@/lib/worktreeRemovalWarning';
-import { sessionsStore } from '@/lib/sessionsStore';
-import * as service from '@/lib/sessionService';
-import { isRemoteSessionWriteBlocked } from '@/features/cc-agent/lib/remoteSessionWriteGuard';
-import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
-import { persistManualPinnedOrder } from '@/features/cc-agent/hooks/helpers/sidebarFilterCore';
-import { toast } from '@/lib/toast';
-
-/** Same row and lifecycle APIs as the task sidebar; this view owns no task state. */
-export function WorkbenchSessionList({
- sessions,
- onChanged,
-}: {
- sessions: Session[];
- onChanged: () => void;
-}) {
- const { t } = useTranslation();
- const navigate = useNavigate();
- const { confirm } = useConfirmDialog();
- const { runningSessionIds, notifications, clearNotification } =
- useSessionRunningStatus(undefined);
- const attached = useAttachedSessionIds();
- const { displayRunningSessionIds } = useSessionDisplayRunningState(sessions, runningSessionIds);
- const { runSessionAction, unarchiveSession } = useSessionLifecycleActions({
- includeArchived: 'all',
- });
- const byId = useMemo(() => new Map(sessions.map((row) => [row.id, row])), [sessions]);
- const open = useCallback(
- (id: string) => {
- clearNotification(id);
- void resolveSessionRoute(id, byId.get(id)).then((route) => navigate(route));
- },
- [byId, clearNotification, navigate],
- );
- const action = useCallback(
- async (
- id: string,
- kind: 'archive' | 'archive-now' | 'unarchive' | 'delete',
- sharedTaskId?: string,
- ) => {
- try {
- if (isRemoteSessionWriteBlocked(byId.get(id))) {
- toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
- return;
- }
- if (kind === 'unarchive') {
- await unarchiveSession(id);
- onChanged();
- return;
- }
- const archive = kind !== 'delete';
- if (archive && runningSessionIds.has(id)) {
- toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));
- return;
- }
- if (
- archive &&
- (attached.has(id) ||
- (await window.electronAPI.binding.resolveSession(id).catch(() => ({ attached: false })))
- .attached)
- ) {
- toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));
- return;
- }
- const preflight = await resolveWorktreeRemovalPreflight(
- id,
- byId.get(id)?.deviceLinkDeviceId,
- );
- const prefix = archive ? 'ccAgent.sidebar.confirmArchive' : 'ccAgent.sidebar.confirmDelete';
- if (
- (!archive || preflight !== 'clean') &&
- !(await confirm({
- title: t(prefix + '.title'),
- description:
- t(prefix + '.description') +
- (preflight === 'dirty' ? ' ' + t(prefix + '.dirtyWorktreeWarning') : ''),
- confirmText: t(prefix + '.confirm'),
- cancelText: t(prefix + '.cancel'),
- }))
- )
- return;
- if (sharedTaskId) {
- const result = (await window.electronAPI.sharedTask.account({
- action: 'close',
- sharedTaskId,
- })) as { closed?: string[] };
- if (!result.closed?.includes(sharedTaskId)) {
- toast.error(t('sharedTask.closeFailedToast', { count: 1 }));
- return;
- }
- }
- await runSessionAction(id, archive ? 'archive' : 'delete', { activeSessionId: null });
- onChanged();
- } catch {
- toast.error(
- t(kind === 'delete' ? 'ccAgent.sidebar.deleteFailed' : 'ccAgent.sidebar.archiveFailed'),
- );
- }
- },
- [byId, attached, confirm, onChanged, runSessionAction, runningSessionIds, t, unarchiveSession],
- );
- const rename = useCallback(
- async (id: string, title: string) => {
- const row = byId.get(id);
- if (!row) return;
- if (isRemoteSessionWriteBlocked(row)) {
- toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
- return;
- }
- try {
- const patch = { title: toStoredSessionTitle(row, title) };
- await service.patchMeta(id, patch);
- sessionsStore.patchLocal(id, patch);
- onChanged();
- } catch {
- toast.error(t('ccAgent.sidebar.renameFailed'));
- }
- },
- [byId, onChanged, t],
- );
- const pin = useCallback(
- async (id: string, pinned: boolean) => {
- if (isRemoteSessionWriteBlocked(byId.get(id))) {
- toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
- return;
- }
- const owner = getDataOwnerGeneration();
- try {
- const patch = { pinnedAt: pinned ? null : new Date().toISOString() };
- await service.patchMeta(id, patch);
- sessionsStore.patchLocal(id, pinned ? { ...patch, summary: null } : patch);
- if (!pinned)
- await persistManualPinnedOrder(
- { kind: 'promote', entryId: id },
- { dataOwnerId: owner.dataOwnerId, ownerGeneration: owner.generation },
- );
- onChanged();
- } catch {
- toast.error(t('ccAgent.sidebar.pinFailed'));
- }
- },
- [byId, onChanged, t],
- );
- const move = useCallback(
- async (id: string, target: SessionMoveTarget) => {
- const row = byId.get(id);
- if (row?.remoteHostId || row?.deviceLinkDeviceId) {
- toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectRemoteUnsupported'));
- return;
- }
- if (runningSessionIds.has(id)) {
- toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectRunningBlocked'));
- return;
- }
- try {
- if (
- (await window.electronAPI.binding.resolveSession(id).catch(() => ({ attached: false })))
- .attached
- ) {
- toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectAttachedBlocked'));
- return;
- }
- let workingDir = target.kind === 'project' ? target.workingDir : undefined;
- if (target.kind === 'browseProject') {
- const result = await window.electronAPI.showOpenDirectoryDialog();
- if (result.canceled || !result.path) return;
- workingDir = result.path;
- }
- if (target.kind !== 'dialogue' && !workingDir) return;
- const patch =
- target.kind === 'dialogue'
- ? { workspaceKind: 'dialogue' as const }
- : { workingDir, workspaceKind: 'project' as const };
- await service.update(id, patch);
- sessionsStore.patchLocal(id, patch);
- onChanged();
- } catch {
- toast.error(t('ccAgent.sidebar.sessionMenu.moveToProjectFailed'));
- }
- },
- [byId, onChanged, runningSessionIds, t],
- );
- const projectOptions = useMemo(
- () =>
- [
- ...new Set(
- sessions
- .filter((row) => !row.deviceLinkDeviceId && !row.remoteHostId)
- .map((row) => row.workingDir)
- .filter((path): path is string => Boolean(path)),
- ),
- ].map((path) => ({
- path,
- name: path.replace(/\\/g, '/').split('/').filter(Boolean).at(-1) ?? path,
- })),
- [sessions],
- );
- return (
- <div className="px-3" data-workbench-session-list>
- {sessions.map((session, index) => (
- <SessionCard
- key={session.id}
- session={session}
- variant="list"
- isFirst={index === 0}
- isActive={false}
- isRunning={displayRunningSessionIds.has(session.id)}
- isAttached={attached.has(session.id)}
- hasAttentionNotification={notifications.has(session.id)}
- onClick={open}
- onAction={action}
- projectOptions={projectOptions}
- onRename={rename}
- onTogglePin={pin}
- onMoveSession={move}
- />
- ))}
- </div>
- );
-}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx
index 1851aabee3..2632527ca9 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx
@@ -16,23 +16,58 @@ const mocks = vi.hoisted(() => ({
pin: vi.fn(),
running: new Map(),
activity: null as any,
- attached: false,
+ resolved: true,
+ stale: false,
+ cancel: vi.fn(),
+ send: vi.fn(),
+ toast: vi.fn(),
+ prs: [] as any[],
+}));
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...await importOriginal<typeof import('react-i18next')>(),
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options && Object.keys(options).length ? `${key}:${JSON.stringify(options)}` : key,
+ }),
}));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.navigate }));
-vi.mock('../botDelegationLive', () => ({ useBotDelegation: () => ({ row: mocks.row }) }));
+vi.mock('../botDelegationLive', () => ({
+ useBotDelegation: () => ({ row: mocks.row, resolved: mocks.resolved, stale: mocks.stale }),
+ isActiveDelegationStatus: (status: string) => ['queued', 'running', 'waiting'].includes(status),
+}));
+vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => [] }));
+vi.mock('@/lib/makerTransport', () => ({
+ makerApiForSticky: () => ({ cancelBotDelegation: mocks.cancel }),
+}));
+vi.mock('@/lib/toast', () => ({ toast: { success: mocks.toast } }));
+vi.mock('@/cindy-brain/ghostUnreadStore', () => ({ useElementVisible: () => ({ ref: () => {}, visible: false }) }));
+vi.mock('@/contexts/PrRefsContext', () => ({
+ usePrActions: () => ({ registerPrConsumer: () => () => {}, invalidateRemotePrRefs: () => {} }),
+ usePrRefsForSession: () => mocks.prs,
+ usePrStatuses: () => ({ statuses: new Map(), successfulStatuses: new Map(), refreshError: false }),
+}));
+vi.mock('@/components/chat/MarkdownRenderer', () => ({
+ MarkdownRenderer: ({ content }: any) => <div data-testid="markdown">{content}</div>,
+}));
+vi.mock('@/components/chat/ChatSessionFileContext', () => ({
+ useChatSessionFile: () => ({ origin: { kind: 'local' }, sessionId: 'parent', workingDir: '/parent' }),
+ ChatSessionFileProvider: ({ children }: any) => children,
+}));
vi.mock('@/lib/sessionService', () => ({ get: mocks.get }));
vi.mock('@/lib/orcaSessionIdentity', () => ({ resolveSessionRoute: mocks.route }));
vi.mock('@/lib/sessionsStore', () => ({
sessionsStore: { subscribe: () => () => {}, subscribePatches: () => () => {} },
}));
-vi.mock('@/components/ui/tooltip', () => ({ Tip: ({ children }: any) => children }));
vi.mock('@/state/agentIslandActivity', () => ({ useAgentIslandActivity: () => mocks.activity }));
vi.mock('@/features/device-link/remoteSessionActivityStore', () => ({
useRemoteSessionActivity: () => null,
}));
vi.mock('@/lib/makerChatStore', () => ({
- makerChatStore: { subscribeAll: () => () => {}, getRunningSnapshot: () => mocks.running },
+ makerChatStore: {
+ subscribeAll: () => () => {},
+ getRunningSnapshot: () => mocks.running,
+ sendMessage: mocks.send,
+ },
}));
vi.mock('@/lib/sessionAttentionStore', () => ({ useSessionAttentionKind: () => undefined }));
vi.mock('@/features/cc-agent/hooks/useSessionDisplayRunningState', () => ({
@@ -62,16 +97,6 @@ vi.mock('@/features/device-link/remoteProjectsStore', () => ({
},
},
}));
-vi.mock('@/features/cc-agent/sidebar/SessionStatusIcon', () => ({
- SessionStatusIcon: ({ session, isRunning, isAttached }: any) => (
- <i
- data-testid="original-harness"
- data-kind={session.agentKind}
- data-running={isRunning}
- data-attached={isAttached}
- />
- ),
-}));
const card: BotCollaborationMeta = {
v: 1,
role: 'delegation-request',
@@ -88,6 +113,11 @@ const data = (value = card) => ({ ...value });
beforeEach(() => {
vi.clearAllMocks();
mocks.row = null;
+ mocks.resolved = true;
+ mocks.stale = false;
+ mocks.prs = [];
+ mocks.cancel.mockResolvedValue({ ok: true, delegationId: 'd', childSessionId: 'child' });
+ mocks.send.mockResolvedValue(true);
mocks.remoteRows = [];
mocks.remoteReadCurrent = true;
mocks.remoteGet.mockResolvedValue({
@@ -104,16 +134,17 @@ beforeEach(() => {
title: 'Current title',
agentKind: 'codex',
status: 'active',
+ workingDir: '/child',
+ model: 'gpt-x',
+ effort: 'high',
+ permissionMode: 'default',
});
mocks.route.mockResolvedValue('/cc-agent/child');
Object.defineProperty(window, 'electronAPI', {
configurable: true,
value: {
deviceLink: { invoke: mocks.remoteGet },
- binding: {
- resolveSession: vi.fn(async () => ({ attached: false })),
- onChanged: () => () => {},
- },
+ openExternal: vi.fn(async () => ({ success: true })),
},
});
});
@@ -124,22 +155,107 @@ it('only renders valid requesting-side task references', () => {
rerender(<BotSessionTaskCard data={data({ ...card, role: 'guest-request' })} />);
expect(container.firstChild).toBeNull();
});
-it('uses the actual session title and native harness, and opens that same session without mutating it', async () => {
+const cardState = () => document.querySelector('[data-bot-task-card]')?.getAttribute('data-bot-task-card');
+const at = Date.parse('2026-10-15T08:00:00Z');
+const delegation = (fields: Record<string, unknown>) => ({
+ id: 'd', childSessionId: 'child', title: 'Row title', status: 'running', pendingInteraction: null,
+ resultSummary: null, artifacts: [], lastError: null, createdAt: at, acceptedAt: at, completedAt: null,
+ updatedAt: at, ...fields,
+});
+it('uses the actual session title and harness, and opens that same session without mutating it', async () => {
render(<BotSessionTaskCard data={data()} />);
fireEvent.click(await screen.findByRole('button', { name: 'Current title' }));
await waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/child'));
expect(mocks.route).toHaveBeenCalledWith('child', expect.objectContaining({ id: 'child' }));
- expect(screen.getByTestId('original-harness').getAttribute('data-kind')).toBe('codex');
- expect(screen.getAllByRole('button')).toHaveLength(1);
+ expect(screen.getByText('bots.collab.backgroundTask · Codex')).toBeTruthy();
});
it('takes actual runtime state instead of treating an ended delegation as completed work', async () => {
mocks.row = { childSessionId: 'child', status: 'done' };
mocks.running.set('child', { isRunning: true });
render(<BotSessionTaskCard data={data()} />);
await screen.findByRole('button', { name: 'Current title' });
- expect(screen.getByTestId('original-harness').getAttribute('data-running')).toBe('true');
+ await waitFor(() => expect(cardState()).toBe('running'));
expect(screen.queryByText('bots.collab.status.done')).toBeNull();
});
+it('shows the current action and elapsed time while running, and stops through the delegation', async () => {
+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] });
+ vi.setSystemTime(at + 65_000);
+ try {
+ mocks.row = delegation({ status: 'running' });
+ mocks.activity = { phase: 'running', compactDetail: 'Running pnpm test', currentTurnActive: true };
+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);
+ expect(cardState()).toBe('running');
+ expect(screen.getByText('Running pnpm test')).toBeTruthy();
+ expect(screen.getByText(/bots\.collab\.elapsed/).textContent).toContain('bots.collab.duration.minutes');
+ expect(screen.getByRole('button', { name: /bots\.collab\.watchWork/ })).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.stop/ }));
+ await act(async () => {});
+ expect(mocks.cancel).toHaveBeenCalledWith('parent', 'd');
+ } finally {
+ vi.useRealTimers();
+ }
+});
+it('reports a failed stop without pretending the task stopped', async () => {
+ mocks.row = delegation({ status: 'running' });
+ mocks.cancel.mockResolvedValue({ ok: false, errorCode: 'X', message: 'Could not stop' });
+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);
+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.stop/ }));
+ expect((await screen.findByRole('alert')).textContent).toBe('Could not stop');
+ expect(cardState()).toBe('running');
+});
+it('adds a note to a local running task as the owner, with the task runtime settings', async () => {
+ mocks.row = delegation({ status: 'running' });
+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);
+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.addNote/ }));
+ const input = screen.getByRole('textbox', { name: 'bots.collab.addNote' });
+ fireEvent.change(input, { target: { value: ' Cover offline reconnect ' } });
+ fireEvent.submit(input.closest('form')!);
+ await waitFor(() => expect(mocks.send).toHaveBeenCalledWith(
+ 'child', 'Cover offline reconnect', 'gpt-x', 'high', 'default', '/child',
+ ));
+ await waitFor(() => expect(screen.queryByRole('textbox')).toBeNull());
+ expect(mocks.toast).toHaveBeenCalledWith('bots.collab.addNoteSent');
+});
+it('shows what the task waits for and lets the user look at it', async () => {
+ mocks.row = delegation({ status: 'waiting', pendingInteraction: { summary: 'Allow npm install', kind: 'permission' } });
+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);
+ expect(cardState()).toBe('waiting');
+ expect(screen.getByText(/bots\.collab\.awaitingConfirm:.*Allow npm install/)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.lookAt/ }));
+ await waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/child'));
+ expect(screen.getByRole('button', { name: /bots\.collab\.stop/ })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /bots\.collab\.addNote/ })).toBeNull();
+});
+it('shows the result summary when completed and expands the result in place', async () => {
+ mocks.row = delegation({ status: 'completed', completedAt: at + 14 * 60_000, resultSummary: 'Retry capped at 3.',
+ artifacts: [{ path: 'a.ts', absolutePath: '/child/a.ts', status: 'modified' }] });
+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);
+ expect(cardState()).toBe('completed');
+ expect(screen.getByText('Retry capped at 3.')).toBeTruthy();
+ expect(screen.getByText(/bots\.collab\.tookTime/)).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /bots\.collab\.stop/ })).toBeNull();
+ const toggle = screen.getByRole('button', { name: /bots\.collab\.expandResult/ });
+ expect(toggle.getAttribute('aria-expanded')).toBe('false');
+ fireEvent.click(toggle);
+ expect(screen.getAllByTestId('markdown').map((node) => node.textContent))
+ .toEqual(['Retry capped at 3.', '[a.ts](</child/a.ts>)']);
+ expect(screen.getByRole('button', { name: /bots\.collab\.collapseResult/ }).getAttribute('aria-expanded')).toBe('true');
+ expect(screen.getByRole('button', { name: /bots\.collab\.artifactCount/ })).toBeTruthy();
+});
+it('shows the failure reason in one line', () => {
+ mocks.row = delegation({ status: 'timed-out', lastError: 'TIMEOUT: upstream did not finish' });
+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);
+ expect(cardState()).toBe('failed');
+ expect(screen.getByText('upstream did not finish')).toBeTruthy();
+ expect(screen.getByText('bots.collab.status.timed-out')).toBeTruthy();
+ expect(screen.getByRole('button', { name: /bots\.collab\.expandDetails/ })).toBeTruthy();
+});
+it('keeps the stale warning when the task row cannot refresh', () => {
+ mocks.row = delegation({ status: 'running' });
+ mocks.stale = true;
+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);
+ expect(screen.getByText('bots.collab.stale')).toBeTruthy();
+});
it('preserves archived identity when opening; viewing never calls unarchive', async () => {
mocks.get.mockResolvedValue({
id: 'child',
@@ -163,15 +279,18 @@ it('keeps a readable fallback when metadata is unavailable without inventing a h
expect(
(screen.getByRole('button', { name: 'Original request' }) as HTMLButtonElement).disabled,
).toBe(false);
- expect(screen.queryByTestId('original-harness')).toBeNull();
+ expect(screen.getByText('bots.collab.backgroundTask')).toBeTruthy();
});
it('pins remote child reads and navigation to the parent device', async () => {
mocks.origin.mockImplementation((id: string) => (id === 'parent' ? 'mac-a' : undefined));
+ mocks.row = delegation({ status: 'running' });
render(<BotSessionTaskCard data={data()} />);
await screen.findByRole('button', { name: 'Remote title' });
expect(mocks.remoteGet).toHaveBeenCalledWith('mac-a', 'local-db:sessions:get', ['child']);
expect(mocks.get).not.toHaveBeenCalled();
- expect(screen.getByTestId('original-harness').getAttribute('data-kind')).toBe('pi');
+ expect(screen.getByText('bots.collab.backgroundTask · Pi')).toBeTruthy();
+ // Sending as the owner is local-only; a remote task keeps open/stop.
+ expect(screen.queryByRole('button', { name: /bots\.collab\.addNote/ })).toBeNull();
act(() => {
mocks.remoteRows = [{ ...mocks.remoteRows[0], title: 'Remote renamed' }];
mocks.remoteChanged();
@@ -184,11 +303,16 @@ it('does not read a conflicting child origin', () => {
render(<BotSessionTaskCard data={data()} />);
expect(mocks.get).not.toHaveBeenCalled();
});
-it('keeps interjections as quiet traces', () => {
+it('keeps legacy interjections as quiet traces', () => {
render(<BotSessionTaskMessageTrace data={data({ ...card, role: 'interjection' })} />);
expect(screen.getByText('bots.collab.messageSent')).toBeTruthy();
expect(screen.queryByRole('button')).toBeNull();
});
+it('shows what was told to the task when the trace carries a preview', () => {
+ render(<BotSessionTaskMessageTrace data={data({ ...card, role: 'interjection', interjectionPreview: 'Cover offline reconnect' })} />);
+ expect(screen.getByText('bots.collab.messageSentWithText:{"text":"Cover offline reconnect"}')).toBeTruthy();
+ expect(screen.queryByText('bots.collab.messageSent')).toBeNull();
+});
it('keeps a newer remote mirror instead of publishing a stale GET', async () => {
let resolve!: (row: any) => void;
@@ -209,5 +333,5 @@ it('keeps a newer remote mirror instead of publishing a stale GET', async () =>
});
await act(async () => resolve({ id: 'child', title: 'Stale title', agentKind: 'pi' }));
expect(screen.getByRole('button', { name: 'New remote title' })).toBeTruthy();
- expect(screen.getByTestId('original-harness').getAttribute('data-kind')).toBe('codex');
+ expect(screen.getByText('bots.collab.backgroundTask · Codex')).toBeTruthy();
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageCard.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageCard.test.tsx
index 8442ca6e20..b80b010488 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageCard.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageCard.test.tsx
@@ -1,16 +1,18 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BotDirectMessageCard } from '../BotDirectMessageCard';
-const mocks = vi.hoisted(() => ({ navigate: vi.fn() }));
+const mocks = vi.hoisted(() => ({ navigate: vi.fn(), getThread: vi.fn(), remoteGetThread: vi.fn(), device: undefined as string | undefined }));
-vi.mock('react-i18next', () => ({
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...await importOriginal<typeof import('react-i18next')>(),
useTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) =>
options ? `${key}:${JSON.stringify(options)}` : key,
+ i18n: { language: 'en-US' },
}),
}));
vi.mock('react-router-dom', () => ({
@@ -18,14 +20,47 @@ vi.mock('react-router-dom', () => ({
useNavigate: () => mocks.navigate,
}));
vi.mock('../botStore', () => ({
- useBotProfiles: () => [{ id: 'bot-b', name: 'Planner', avatar: '', avatarColor: 'blue' }],
+ useBotProfiles: () => [
+ { id: 'bot-a', name: 'LiZi', avatar: '', avatarColor: 'red' },
+ { id: 'bot-b', name: 'Planner', avatar: '', avatarColor: 'blue' },
+ ],
}));
vi.mock('../BotAvatar', () => ({
BotAvatar: ({ bot }: { bot: { name: string } }) => <span data-avatar={bot.name} />,
}));
+vi.mock('@/components/chat/MarkdownRenderer', () => ({
+ MarkdownRenderer: ({ content, allowPrivilegedLinks }: any) => (
+ <div data-testid="markdown" data-privileged={String(allowPrivilegedLinks)}>{content}</div>
+ ),
+}));
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ remoteProjectsStore: { getSessionDeviceId: () => mocks.device },
+}));
+vi.mock('@/lib/makerTransport', () => ({
+ makerApiForDevice: () => ({ getBotDirectMessageThread: mocks.remoteGetThread }),
+}));
+
+const thread = {
+ id: 'dm-1', botAId: 'bot-a', botAName: 'LiZi', botBId: 'bot-b', botBName: 'Planner',
+ status: 'closed', closeReason: 'idle-timeout', messageCount: 2, maxMessages: 12,
+ createdAt: 1, updatedAt: 2, closedAt: 2,
+ messages: [
+ { id: 'm1', sequence: 1, senderBotId: 'bot-a', senderBotName: 'LiZi', recipientBotId: 'bot-b',
+ recipientBotName: 'Planner', content: 'Does **PR 6051** conflict?', createdAt: 1 },
+ { id: 'm2', sequence: 2, senderBotId: 'bot-b', senderBotName: 'Planner', recipientBotId: 'bot-a',
+ recipientBotName: 'LiZi', content: 'No conflict.', createdAt: 2 },
+ ],
+};
beforeEach(() => {
mocks.navigate.mockClear();
+ mocks.device = undefined;
+ mocks.getThread.mockReset().mockResolvedValue({ ok: true, thread });
+ mocks.remoteGetThread.mockReset().mockResolvedValue({ ok: true, thread });
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { maker: { getBotDirectMessageThread: mocks.getThread } },
+ });
});
afterEach(cleanup);
@@ -38,8 +73,8 @@ describe('BotDirectMessageCard', () => {
peerBotId: 'bot-b',
peerBotName: 'Planner',
direction: 'sent',
- sequence: 3,
- preview: 'hello',
+ sequence: 1,
+ preview: 'Does **PR 6051** conflict?',
};
it('renders nothing for malformed timeline metadata', () => {
@@ -47,12 +82,58 @@ describe('BotDirectMessageCard', () => {
expect(container.firstChild).toBeNull();
});
- it('opens the hidden route and carries the exact timeline return path', () => {
+ it('is a card with the peer, direction and an excerpt, not a separator', () => {
+ render(<BotDirectMessageCard data={data} />);
+ expect(screen.getByText('bots.directMessage.sentHeader:{"name":"Planner"}')).toBeTruthy();
+ expect(screen.getByText('Does **PR 6051** conflict?')).toBeTruthy();
+ expect(screen.queryByRole('separator')).toBeNull();
+ expect(mocks.getThread).not.toHaveBeenCalled();
+ });
+
+ it('labels a received message by its sender', () => {
+ render(<BotDirectMessageCard data={{ ...data, direction: 'received' }} />);
+ expect(screen.getByText('bots.directMessage.receivedHeader:{"name":"Planner"}')).toBeTruthy();
+ });
+
+ it('opens the full read-only page and carries the exact timeline return path', () => {
render(<BotDirectMessageCard data={data} />);
- const label = screen.getByText(/bots\.directMessage\.sentTo/);
- fireEvent.click(label);
+ fireEvent.click(screen.getByRole('button', { name: /bots\.directMessage\.fullThread/ }));
expect(mocks.navigate).toHaveBeenCalledWith('/bots/bot-a/direct/dm-1', {
state: { botDirectMessageReturnTo: '/bots/bot-a/session/a-main?from=chat' },
});
});
+
+ it('expands the exchange inline from the thread IPC with Markdown and the closed ending', async () => {
+ render(<BotDirectMessageCard data={data} />);
+ const toggle = screen.getByRole('button', { name: /bots\.directMessage\.expandThread/ });
+ expect(toggle.getAttribute('aria-expanded')).toBe('false');
+ fireEvent.click(toggle);
+ expect(mocks.getThread).toHaveBeenCalledWith('dm-1', 'bot-a');
+ await waitFor(() => expect(screen.getAllByTestId('markdown')).toHaveLength(2));
+ expect(screen.getAllByTestId('markdown').map((node) => node.textContent))
+ .toEqual(['Does **PR 6051** conflict?', 'No conflict.']);
+ expect(screen.getAllByTestId('markdown').every((node) => node.dataset.privileged === 'false')).toBe(true);
+ expect(screen.getByText('bots.directMessage.threadClosed')).toBeTruthy();
+ const collapse = screen.getByRole('button', { name: /bots\.directMessage\.exchangeCountShort.*bots\.directMessage\.collapse/ });
+ expect(collapse.getAttribute('aria-expanded')).toBe('true');
+ fireEvent.click(collapse);
+ expect(screen.queryByTestId('markdown')).toBeNull();
+ });
+
+ it('reads a remote thread from the device that owns the bot chat', async () => {
+ mocks.device = 'home';
+ render(<BotDirectMessageCard data={data} sessionId="remote-main" />);
+ fireEvent.click(screen.getByRole('button', { name: /bots\.directMessage\.expandThread/ }));
+ await waitFor(() => expect(mocks.remoteGetThread).toHaveBeenCalledWith('dm-1', 'bot-a'));
+ expect(mocks.getThread).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: /bots\.directMessage\.fullThread/ }));
+ expect(mocks.navigate.mock.calls[0][0]).toBe('/bots/bot-a/direct/dm-1?deviceId=home');
+ });
+
+ it('fails closed when the thread is unavailable', async () => {
+ mocks.getThread.mockResolvedValue({ ok: false, errorCode: 'NOT_FOUND', message: 'missing' });
+ render(<BotDirectMessageCard data={data} />);
+ fireEvent.click(screen.getByRole('button', { name: /bots\.directMessage\.expandThread/ }));
+ expect(await screen.findByText('bots.directMessage.unavailable')).toBeTruthy();
+ });
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx
index ca49f494c3..5513467450 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx
@@ -37,6 +37,11 @@ vi.mock('../botStore', () => ({ useBotProfiles: () => mocks.profiles }));
vi.mock('../BotAvatar', () => ({
BotAvatar: ({ bot }: { bot: { name: string } }) => <span data-avatar={bot.name} />,
}));
+vi.mock('@/components/chat/MarkdownRenderer', () => ({
+ MarkdownRenderer: ({ content, allowPrivilegedLinks }: any) => (
+ <div data-markdown={String(allowPrivilegedLinks)}>{content}</div>
+ ),
+}));
function HeaderSlot() {
return <header data-testid="content-header">{useFeatureContentHeader()}</header>;
@@ -112,6 +117,8 @@ describe('BotDirectMessageView', () => {
render(<TestPage />, { reactStrictMode: true });
expect(await screen.findByText('Can you check this?')).toBeTruthy();
expect(screen.getByText('Checked.')).toBeTruthy();
+ // Messages render as Markdown, never with privileged links.
+ expect(screen.getByText('Checked.').getAttribute('data-markdown')).toBe('false');
expect(screen.queryByRole('textbox')).toBeNull();
expect(screen.getByText('bots.directMessage.limitReached')).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'bots.directMessage.close' }));
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
index a27bb57709..aa2a46ee2a 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -11,7 +11,7 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vite
import { clearDraft, getDraft } from '@/lib/composerDraftStore';
import { FeatureSidebarSlotProvider, useFeatureContentHeader } from '../../feature-context';
import { markBotRead, getBotLastReadAt, botGroupReadKey, resetBotReadStateForTests } from '../botReadState';
-import { botGroupAttachmentScope } from '../botGroupAttachments';
+import { botGroupAttachmentScope, botGroupThreadDraftKey } from '../botGroupAttachments';
import { getBotGroupListSnapshot, refreshBotGroups, resetBotGroupStoreForTests } from '../botGroupStore';
import { BotGroupChatView } from '../BotGroupChatView';
import { ControlledBanner, __resetControlledBannerForTests } from '../../remote-device/ControlledBanner';
@@ -259,6 +259,8 @@ function renderView() {
beforeEach(() => {
window.localStorage.clear();
for (const id of ['g1', 'g2']) clearDraft(botGroupAttachmentScope(id));
+ // 话题 reply drafts persist like the group's own; start every test without one.
+ for (const root of ['u1', 'b1', 'q1', 'm']) clearDraft(botGroupThreadDraftKey('g1', root));
mocks.toastWarning.mockReset();
mocks.filePaths = new Map();
mocks.cacheImageFromBuffer.mockReset().mockResolvedValue({ url: 'cindy-media://blobs/pasted.png', filename: 'pasted.png' });
@@ -869,8 +871,9 @@ describe('BotGroupChatView', () => {
it('renders user, teammate, notice and round-end rows with the header lockup', async () => {
renderView();
expect(await screen.findByText('周六 8:10 有票')).toBeTruthy();
- // The user's mention renders as a chip inside the right-aligned bubble.
- expect(screen.getByText('@小满').className).toContain('rounded-full');
+ // The user's own message is a right-aligned bubble rendered as Markdown.
+ expect(screen.getByTestId('bot-group-self-bubble').textContent).toBe('@小满 帮我查余票');
+ expect(screen.getByTestId('bot-group-self-bubble').querySelector('[data-markdown]')).toBeTruthy();
expect(screen.getByText('bots.groupChat.notice.memberTimeout:咪咪')).toBeTruthy();
expect(screen.getByText('bots.groupChat.timeline.roundEnded')).toBeTruthy();
const header = screen.getByTestId('content-header');
@@ -1208,7 +1211,7 @@ describe('BotGroupChatView', () => {
messageId, authorName: '小满', authorKind: 'bot' as const, excerpt: '周六 8:10 有票', attachmentCount: 0, attachmentName: null, sequence: 2, ...overrides,
});
const quoteButton = async (id = 'b1') => {
- await screen.findByText('周六 8:10 有票');
+ await screen.findAllByText('周六 8:10 有票');
const row = document.querySelector(`[data-bot-group-message-id="${id}"]`) as HTMLElement;
return within(row).getByRole('button', { name: 'bots.groupChat.server.quoteReply' });
};
@@ -1533,7 +1536,8 @@ describe('BotGroupChatView', () => {
expect(card.textContent).toContain('bots.groupChat.plan.intro');
expect(card.textContent).toContain('想清楚这页讲什么');
expect(card.textContent).toContain('画设计稿');
- expect(screen.getByText('bots.groupChat.organizer')).toBeTruthy();
+ // The organizer tag sits next to the plan card's author (the header shows it too).
+ expect(within(card.closest('article')!).getByText('bots.groupChat.organizer')).toBeTruthy();
expect(screen.getByText('bots.groupChat.plan.editHint')).toBeTruthy();
expect(screen.getByText('bots.groupChat.plan.pauseNote')).toBeTruthy();
expect(screen.getByRole('textbox').getAttribute('placeholder')).toBe(
@@ -1957,7 +1961,8 @@ describe('BotGroupChatView', () => {
},
],
});
- await waitFor(() => expect(screen.queryByText('report.pdf')).toBeNull());
+ // The tray is empty; the optimistic copy of the message shows the file until main's copy arrives.
+ await waitFor(() => expect(within(input.parentElement!).queryByText('report.pdf')).toBeNull());
expect(getDraft(botGroupAttachmentScope('g1'))?.attachments ?? []).toEqual([]);
});
@@ -2003,7 +2008,8 @@ describe('BotGroupChatView', () => {
fireEvent.keyDown(input, { key: 'Enter' });
await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(2));
expect(lastSend().clientId).toBe(firstClientId);
- await waitFor(() => expect(screen.queryByText('report.pdf')).toBeNull());
+ // The tray is empty; the optimistic copy of the message shows the file until main's copy arrives.
+ await waitFor(() => expect(within(input.parentElement!).queryByText('report.pdf')).toBeNull());
});
it('holds a message over the attachment limit with a hint', async () => {
@@ -2090,7 +2096,7 @@ describe('BotGroupChatView', () => {
const image = await screen.findByAltText('截图.png');
expect(image.getAttribute('src')).toBe('cindy-media://blobs/abc.png');
const article = image.closest('article')!;
- expect(article.querySelector('.whitespace-pre-wrap')).toBeNull();
+ expect(article.querySelector('[data-testid="bot-group-self-bubble"]')).toBeNull();
const chip = screen.getByRole('button', { name: '报告.pdf' });
expect(article.contains(chip)).toBe(true);
// A PDF is not text: it opens in the system app, as from a task's chip.
@@ -2098,7 +2104,7 @@ describe('BotGroupChatView', () => {
await waitFor(() => expect(mocks.openPath).toHaveBeenCalledWith('/Users/me/报告.pdf'));
const withText = screen.getByAltText('草图.png').closest('article')!;
- expect(withText.querySelector('.whitespace-pre-wrap')?.textContent).toBe('再看这张');
+ expect(withText.querySelector('[data-testid="bot-group-self-bubble"]')?.textContent).toBe('再看这张');
});
});
});
@@ -2151,3 +2157,207 @@ it('keeps copy/share in each author row and shares only message content through
expect(getBotLastReadAt(botGroupReadKey('g1'))).toBe(1200);
} finally { focus.mockRestore(); resetBotReadStateForTests(); }
});
+
+describe('Telegram / Slack-grade timeline', () => {
+ function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+ }
+ const push = (change: BotGroupChangedPayload['change'] = 'messages') =>
+ act(async () => { mocks.pushes.forEach((listener) => listener({ groupId: 'g1', change })); });
+ const own = (id: string, sequence: number, content: string, createdAt = 1_700_000_000_000) =>
+ msg({ id, sequence, content, createdAt, isSelf: true });
+
+ it('shows a sent message at once and swaps in main’s copy in place', async () => {
+ const sent = deferred<{ ok: true; messageId: string }>();
+ mocks.sendBotGroupMessage.mockReturnValue(sent.promise);
+ renderView();
+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;
+ fireEvent.change(input, { target: { value: '在吗' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(input.value).toBe('');
+ const bubble = await screen.findByText('在吗');
+ const row = bubble.closest('[data-bot-group-message-id]') as HTMLElement;
+ expect(row.dataset.botGroupMessageId).toMatch(/^pending:/);
+ expect(row.querySelector('article')?.getAttribute('aria-busy')).toBe('true');
+ // The pending copy has no toolbar: it cannot be quoted, shared or answered yet.
+ expect(within(row).queryByRole('button', { name: 'chat.messageActionBar.copy' })).toBeNull();
+ const base = detail();
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: { ...base, messages: [...base.messages, own('u9', 5, '在吗')] } });
+ await act(async () => sent.resolve({ ok: true, messageId: 'u9' }));
+ await waitFor(() => expect(row.dataset.botGroupMessageId).toBe('u9'));
+ // Same row element: no remount, no flash.
+ expect(document.contains(row)).toBe(true);
+ expect(screen.getAllByText('在吗')).toHaveLength(1);
+ });
+
+ it('takes the pending copy back and restores the draft when the send fails', async () => {
+ mocks.sendBotGroupMessage.mockResolvedValue({ ok: false, errorCode: 'SERVICE_ERROR', message: '' });
+ renderView();
+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;
+ fireEvent.change(input, { target: { value: '没发出去' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ await waitFor(() => expect(input.value).toBe('没发出去'));
+ expect(document.querySelector('[data-bot-group-message-id^="pending:"]')).toBeNull();
+ });
+
+ it('collapses pushes during a read into one follow-up read and shows every result', async () => {
+ renderView();
+ await screen.findByText('周六 8:10 有票');
+ const first = deferred<{ ok: true; group: BotGroupDetail }>();
+ const second = deferred<{ ok: true; group: BotGroupDetail }>();
+ mocks.getBotGroup.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
+ await push();
+ await push();
+ await push();
+ // One read in flight; the later pushes wait for it instead of discarding it.
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(2);
+ const base = detail();
+ await act(async () => first.resolve({ ok: true, group: { ...base, messages: [...base.messages, msg({ id: 'x1', sequence: 5, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满', content: '第一条回复' })] } }));
+ expect(screen.getByText('第一条回复')).toBeTruthy();
+ await waitFor(() => expect(mocks.getBotGroup).toHaveBeenCalledTimes(3));
+ await act(async () => second.resolve({ ok: true, group: { ...base, messages: [...base.messages,
+ msg({ id: 'x1', sequence: 5, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满', content: '第一条回复' }),
+ msg({ id: 'x2', sequence: 6, authorKind: 'bot', authorBotId: 'mimi', authorName: '咪咪', content: '第二条回复' })] } }));
+ expect(screen.getByText('第一条回复')).toBeTruthy();
+ expect(screen.getByText('第二条回复')).toBeTruthy();
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(3);
+ });
+
+ it('keeps messages pushed out of the newest page on screen', async () => {
+ const rows = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, index) =>
+ msg({ id: `r${from + index}`, sequence: from + index, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满', content: `第${from + index}条` }));
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: rows(1, 3), hasMoreBefore: true }) });
+ renderView();
+ await screen.findByText('第1条');
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: rows(3, 5), hasMoreBefore: true }) });
+ await push();
+ await screen.findByText('第5条');
+ expect(screen.getByText('第1条')).toBeTruthy();
+ expect(screen.getByText('第2条')).toBeTruthy();
+ // Older history is still offered above them.
+ expect(screen.getByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' })).toBeTruthy();
+ });
+
+ it('merges consecutive messages by one author and divides days', async () => {
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ yesterday.setHours(12, 0, 0, 0);
+ const today = new Date();
+ today.setHours(0, 30, 0, 0);
+ const bot = (id: string, sequence: number, createdAt: number, content: string) =>
+ msg({ id, sequence, createdAt, content, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满' });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: [
+ bot('a', 1, yesterday.getTime(), '昨天第一条'),
+ bot('b', 2, yesterday.getTime() + 60_000, '昨天第二条'),
+ bot('c', 3, today.getTime(), '今天第一条'),
+ ] }) });
+ renderView();
+ await screen.findByText('今天第一条');
+ const article = (text: string) => screen.getByText(text).closest('article')!;
+ expect(article('昨天第一条').querySelector('[data-avatar]')).toBeTruthy();
+ expect(within(article('昨天第一条')).getByText('小满')).toBeTruthy();
+ // The merged line has no avatar or name, only a time in its gutter.
+ expect(article('昨天第二条').querySelector('[data-avatar]')).toBeNull();
+ expect(within(article('昨天第二条')).queryByText('小满')).toBeNull();
+ expect(article('昨天第二条').querySelector('time')).toBeTruthy();
+ // A new day starts a new block under its own date line.
+ expect(article('今天第一条').querySelector('[data-avatar]')).toBeTruthy();
+ expect(screen.getAllByTestId('bot-group-date-divider')).toHaveLength(2);
+ });
+
+ it('keeps the unsent text with the group across a remount', async () => {
+ let view = renderView();
+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;
+ fireEvent.change(input, { target: { value: '写了一半的话\n第二行' } });
+ view.unmount();
+ view = renderView();
+ expect(((await screen.findByRole('textbox')) as HTMLTextAreaElement).value).toBe('写了一半的话\n第二行');
+ view.unmount();
+ // Another group starts empty.
+ mocks.groupId = 'g2';
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ id: 'g2' }) });
+ renderView();
+ expect(((await screen.findByRole('textbox')) as HTMLTextAreaElement).value).toBe('');
+ });
+
+ it('shows the organizer deciding about a split in the header and as a speaking line', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({
+ speakingBotIds: ['mimi'],
+ planningBotId: 'mimi',
+ round: { status: 'running', speakers: [{ botId: 'mimi', sessionId: null, activity: 'planning' }], canContinue: false },
+ }) });
+ renderView();
+ const row = await screen.findByTestId('bot-group-speaking');
+ expect(row.getAttribute('data-activity')).toBe('planning');
+ expect(row.textContent).toContain('咪咪');
+ expect(row.textContent).toContain('bots.groupChat.speaking.planning');
+ expect(screen.getByTestId('content-header').textContent).toContain('bots.groupChat.header.planning:咪咪');
+ });
+
+ it('pins a progress strip above the composer while a plan step runs', async () => {
+ const running = plan({
+ status: 'running',
+ currentStep: 0,
+ updatedAt: Date.now() - 125_000,
+ steps: [{ ...plan().steps[0]!, status: 'running' }, plan().steps[1]!],
+ });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withPlan(running, [], {
+ speakingBotIds: ['mimi'],
+ round: { status: 'running', speakers: [{ botId: 'mimi', sessionId: 'plan-mimi', activity: 'step' }], canContinue: false },
+ }) });
+ renderView();
+ const strip = await screen.findByTestId('bot-group-progress');
+ expect(strip.textContent).toContain('bots.groupChat.progress.step');
+ expect(strip.textContent).toContain('想清楚这页讲什么');
+ expect(strip.textContent).toContain('bots.groupChat.progress.elapsed');
+ // The strip stands in for the step's speaking line; its confirmations stay in the timeline.
+ expect(screen.queryByTestId('bot-group-speaking')).toBeNull();
+ expect(screen.getByTestId('pending-interaction').textContent).toBe('plan-mimi');
+ // It sits between the timeline and the composer.
+ expect(strip.compareDocumentPosition(screen.getByRole('textbox')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.getByTestId('content-header').textContent).toContain('bots.groupChat.header.stepRunning:咪咪');
+ // The running step shows how long it has been going.
+ expect(screen.getByTestId('bot-group-plan').textContent).toContain('bots.groupChat.elapsed.minutes');
+ fireEvent.click(within(strip).getByRole('button', { name: 'bots.groupChat.progress.stop' }));
+ await waitFor(() => expect(mocks.stopBotGroupRound).toHaveBeenCalledWith('g1'));
+ });
+
+ it('highlights @mentions of members in teammates’ messages too', async () => {
+ const registry = new Map<string, { ranges: Range[] }>();
+ vi.stubGlobal('Highlight', class { ranges: Range[]; constructor(...ranges: Range[]) { this.ranges = ranges; } });
+ const originalCss = globalThis.CSS;
+ vi.stubGlobal('CSS', { ...(originalCss ?? {}), highlights: registry });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: [
+ msg({ id: 'u1', sequence: 1, content: '@小满 帮我查余票' }),
+ msg({ id: 'b1', sequence: 2, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满', content: '@咪咪 你来订 `@nobody`' }),
+ ] }) });
+ renderView();
+ await screen.findByText('@小满 帮我查余票');
+ await waitFor(() => expect(registry.get('bot-group-mention')?.ranges.map((range) => range.toString()).sort()).toEqual(['@咪咪', '@小满']));
+ });
+
+ it('shows a 话题 reply at once and keeps one copy when the server’s reply arrives', async () => {
+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
+ const sent = deferred<{ ok: true; messageId: string }>();
+ const reply = vi.fn(() => sent.promise);
+ Object.assign((window.electronAPI as unknown as { maker: { chatServer: Record<string, unknown> } }).maker.chatServer, { reply });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true }) });
+ const user = userEvent.setup();
+ renderView();
+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);
+ const panel = screen.getByRole('complementary');
+ await within(panel).findByText('Reply to u1');
+ const input = within(panel).getByRole('textbox') as HTMLTextAreaElement;
+ await user.type(input, '我也去{Enter}');
+ expect(input.value).toBe('');
+ expect(within(panel).getByText('我也去')).toBeTruthy();
+ expect(reply).toHaveBeenCalledWith(expect.objectContaining({ groupId: 'g1', rootId: 'u1', text: '我也去' }));
+ mocks.thread.mockResolvedValue({ ok: true, root: msg({ id: 'u1', content: 'Thread root u1' }),
+ replies: [msg({ id: 'reply-u1', content: 'Reply to u1' }), msg({ id: 'r9', sequence: 2, content: '我也去', isSelf: true })], hasMore: false });
+ await act(async () => sent.resolve({ ok: true, messageId: 'r9' }));
+ await waitFor(() => expect(panel.querySelector('[data-bot-group-message-id="r9"]')).toBeTruthy());
+ expect(within(panel).getAllByText('我也去')).toHaveLength(1);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.ts
new file mode 100644
index 0000000000..5d9ec576eb
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.ts
@@ -0,0 +1,174 @@
+import { describe, expect, it } from 'vitest';
+
+import { collectBotTimelineDateDividers, formatBotTimelineDate } from '@cindy/maker-shared/botTimeline';
+import type { BotGroupDetail, BotGroupMessageView, BotGroupPlanView } from '../../../../shared/botGroupChat';
+import {
+ BOT_GROUP_MERGE_WINDOW_MS,
+ botGroupHandoffStepNumbers,
+ botGroupMemberBaseName,
+ botGroupMemberDisplayName,
+ botGroupOwnedBotNames,
+ layoutBotGroupTimeline,
+ matchBotGroupPendingSends,
+ mergeBotGroupLatestPage,
+ pendingBotGroupMessage,
+ settleBotGroupPendingSends,
+ stabilizeById,
+ type BotGroupLoadedTimeline,
+ type BotGroupPendingSend,
+} from '../BotGroupTimelineModel';
+
+const DAY = new Date(2026, 9, 15, 10, 0).getTime();
+
+function msg(overrides: Partial<BotGroupMessageView>): BotGroupMessageView {
+ return {
+ id: 'm', sequence: 1, kind: 'message', authorKind: 'bot', authorBotId: 'mimi', authorName: '咪咪', content: '',
+ mentions: { all: false, botIds: [] }, noticeCode: null, planId: null, files: [], attachments: [], createdAt: DAY,
+ ...overrides,
+ };
+}
+
+function detail(messages: BotGroupMessageView[], hasMoreBefore: boolean, plans: BotGroupPlanView[] = []): BotGroupDetail {
+ return {
+ id: 'g1', name: 'g', replyMode: 'all', speakingMode: 'auto', members: [], organizerBotId: null, projectDir: null,
+ lastMessage: null, speakingBotIds: [], planningBotId: null, openPlan: null, createdAt: 1, updatedAt: 1,
+ messages, hasMoreBefore, plans, round: { status: 'idle', speakers: [], canContinue: false },
+ };
+}
+
+const page = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, index) =>
+ msg({ id: `m${from + index}`, sequence: from + index, content: `第 ${from + index} 条` }));
+
+describe('push refresh merge', () => {
+ it('keeps rows pushed out of the latest page instead of leaving a gap', () => {
+ const first: BotGroupLoadedTimeline = { group: detail(page(1, 3), true), older: [], olderPlans: [], olderHasMore: false };
+ // Two new messages arrive; a three-message page no longer covers 1 and 2.
+ const merged = mergeBotGroupLatestPage(first, detail(page(3, 5), true));
+ expect(merged.group.messages.map((message) => message.id)).toEqual(['m3', 'm4', 'm5']);
+ expect(merged.older.map((message) => message.id)).toEqual(['m1', 'm2']);
+ // What the old latest page said about earlier history moves with them.
+ expect(merged.olderHasMore).toBe(true);
+ // Unchanged rows keep their objects (memoized rows do not re-render).
+ expect(merged.older[0]).toBe(first.group.messages[0]);
+ expect(merged.group.messages[0]).toBe(first.group.messages[2]);
+ });
+
+ it('updates rows inside the page range in place and hands back the same state when nothing changed', () => {
+ const first: BotGroupLoadedTimeline = { group: detail(page(1, 3), false), older: [], olderPlans: [], olderHasMore: false };
+ expect(mergeBotGroupLatestPage(first, detail(page(1, 3), false))).toBe(first);
+ const edited = page(1, 3).map((message) => (message.id === 'm2' ? { ...message, reactions: [{ emoji: '👍', count: 1, me: true }] } : message));
+ const merged = mergeBotGroupLatestPage(first, detail(edited, false));
+ expect(merged).not.toBe(first);
+ expect(merged.group.messages[0]).toBe(first.group.messages[0]);
+ expect(merged.group.messages[1]!.reactions).toEqual([{ emoji: '👍', count: 1, me: true }]);
+ });
+
+ it('never drops pages opened with 「查看更早」', () => {
+ const first: BotGroupLoadedTimeline = { group: detail(page(10, 12), true), older: page(1, 3), olderPlans: [], olderHasMore: true };
+ const merged = mergeBotGroupLatestPage(first, detail(page(11, 13), false));
+ expect(merged.older.map((message) => message.id)).toEqual(['m1', 'm2', 'm3']);
+ expect(merged.older).toBe(first.older);
+ });
+
+ it('reuses an unchanged array as is', () => {
+ const items = page(1, 2);
+ expect(stabilizeById(items, items.map((item) => ({ ...item })))).toBe(items);
+ });
+});
+
+describe('optimistic sends', () => {
+ const send = (clientId: string, text: string, afterSequence = 2, messageId?: string): BotGroupPendingSend => ({
+ clientId, text, mentions: { all: false, botIds: [] }, attachments: [], quote: null, createdAt: DAY, afterSequence,
+ ...(messageId ? { messageId } : {}),
+ });
+ const own = (id: string, sequence: number, content: string) => msg({ id, sequence, content, authorKind: 'user', authorBotId: null, isSelf: true });
+
+ it('matches an accepted send by message id and an unanswered one by its echo after it', () => {
+ const pending = [send('a', '好', 2, 'srv-a'), send('b', '好')];
+ const displayed = [own('old', 1, '好'), own('srv-a', 3, '好'), own('srv-b', 4, '好')];
+ expect([...matchBotGroupPendingSends(pending, displayed)]).toEqual([['a', 'srv-a'], ['b', 'srv-b']]);
+ expect(settleBotGroupPendingSends(pending, displayed)).toEqual([]);
+ });
+
+ it('keeps a send whose message has not arrived, and the same array when nothing settled', () => {
+ const pending = [send('a', '好')];
+ expect(settleBotGroupPendingSends(pending, [own('old', 1, '好')])).toBe(pending);
+ });
+
+ it('shows the pending copy as the reader’s own message', () => {
+ const row = pendingBotGroupMessage(send('a', '你好'));
+ expect(row).toMatchObject({ id: 'pending:a', pending: true, isSelf: true, authorKind: 'user', content: '你好' });
+ });
+});
+
+describe('Telegram-style layout', () => {
+ it('merges consecutive messages by one author within five minutes', () => {
+ const rows = [
+ msg({ id: 'a', createdAt: DAY }),
+ msg({ id: 'b', createdAt: DAY + 60_000 }),
+ msg({ id: 'c', createdAt: DAY + 60_000 + BOT_GROUP_MERGE_WINDOW_MS }),
+ msg({ id: 'd', createdAt: DAY + 70_000 + BOT_GROUP_MERGE_WINDOW_MS, authorBotId: 'xiaoman', authorName: '小满' }),
+ msg({ id: 'e', kind: 'notice', authorKind: 'system', createdAt: DAY + 80_000 + BOT_GROUP_MERGE_WINDOW_MS }),
+ msg({ id: 'f', createdAt: DAY + 90_000 + BOT_GROUP_MERGE_WINDOW_MS, authorBotId: 'xiaoman', authorName: '小满' }),
+ msg({ id: 'g', createdAt: DAY + 95_000 + BOT_GROUP_MERGE_WINDOW_MS, authorBotId: 'xiaoman', authorName: '小满', planId: 'p1' }),
+ ];
+ const layout = layoutBotGroupTimeline(rows);
+ expect(rows.map((row) => layout.get(row.id)!.continued)).toEqual([false, true, false, false, false, false, false]);
+ });
+
+ it('starts every local day with a date divider and never merges across it', () => {
+ const late = new Date(2026, 9, 14, 23, 58).getTime();
+ const rows = [msg({ id: 'a', createdAt: late }), msg({ id: 'b', createdAt: late + 4 * 60_000 })];
+ const layout = layoutBotGroupTimeline(rows);
+ expect(layout.get('a')!.dateDivider).toBe(late);
+ expect(layout.get('b')!.dateDivider).toBe(late + 4 * 60_000);
+ expect(layout.get('b')!.continued).toBe(false);
+ expect([...collectBotTimelineDateDividers([{ clientId: 'x', createdAt: DAY }, { clientId: 'y', createdAt: DAY + 1 }]).keys()]).toEqual(['x']);
+ });
+
+ it('names today and yesterday, and dates other days', () => {
+ expect(formatBotTimelineDate(DAY, 'en', DAY + 60_000)).toBe('Today');
+ expect(formatBotTimelineDate(DAY - 86_400_000, 'zh-CN', DAY)).toBe('昨天');
+ expect(formatBotTimelineDate(DAY - 5 * 86_400_000, 'en', DAY)).toContain('10');
+ });
+});
+
+describe('names in multi-owner groups', () => {
+ const human = { botId: 'h', actorId: 'h', actorKind: 'human' as const, name: 'Chris', avatar: '', avatarColor: '', status: 'active' as const };
+ const theirs = { botId: 'c', actorId: 'c', actorKind: 'bot' as const, name: 'Cindy (Chris)', ownerName: 'Chris', ownerActorId: 'h', isOwned: false, avatar: '', avatarColor: '', status: 'active' as const };
+ const plain = { ...theirs, name: 'Dash', ownerName: 'Chris', isOwned: false };
+ const mine = { ...theirs, name: 'LiZi', ownerName: 'Me', isOwned: true };
+
+ it('shows another owner’s teammate as 伙伴名 (主人昵称), once', () => {
+ expect(botGroupMemberDisplayName(theirs)).toBe('Cindy (Chris)');
+ expect(botGroupMemberDisplayName(plain)).toBe('Dash (Chris)');
+ expect(botGroupMemberDisplayName(mine)).toBe('LiZi');
+ expect(botGroupMemberDisplayName(human)).toBe('Chris');
+ expect(botGroupMemberBaseName(theirs)).toBe('Cindy');
+ });
+
+ it('lists the teammates a human brought in', () => {
+ expect(botGroupOwnedBotNames(human, [human, theirs, mine])).toEqual(['Cindy', 'LiZi']);
+ expect(botGroupOwnedBotNames(theirs, [human, theirs])).toEqual([]);
+ });
+});
+
+describe('plan hand-offs', () => {
+ it('tags each hand-off with its step, in order for a teammate with several steps', () => {
+ const plan: BotGroupPlanView = {
+ id: 'p1', status: 'running', organizerBotId: 'mimi', organizerName: '咪咪', currentStep: 2, workDir: null, branch: null, createdAt: 1, updatedAt: 1,
+ steps: [
+ { position: 0, botId: 'mimi', botName: '咪咪', task: 'a', status: 'done' },
+ { position: 1, botId: 'xiaoman', botName: '小满', task: 'b', status: 'done' },
+ { position: 2, botId: 'mimi', botName: '咪咪', task: 'c', status: 'running' },
+ ],
+ };
+ const numbers = botGroupHandoffStepNumbers([
+ msg({ id: 'h1', planId: 'p1' }),
+ msg({ id: 'h2', planId: 'p1', authorBotId: 'xiaoman' }),
+ msg({ id: 'h3', planId: 'p1' }),
+ msg({ id: 'chat' }),
+ ], new Map([['p1', plan]]));
+ expect([...numbers]).toEqual([['h1', 1], ['h2', 2], ['h3', 3]]);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotSessionTaskResultCard.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotSessionTaskResultCard.test.tsx
index cb81f8d8ed..66662d11ec 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotSessionTaskResultCard.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotSessionTaskResultCard.test.tsx
@@ -1,25 +1,44 @@
-vi.mock('../BotSessionTaskLink', () => ({ BotSessionTaskLink: () => <span data-testid="original-session-link" /> }));
-import { readBotCollaborationMeta } from '../../../../shared/botCollaboration';
// @vitest-environment jsdom
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { readBotCollaborationMeta } from '../../../../shared/botCollaboration';
import { BotSessionTaskResultCard } from '../BotSessionTaskResultCard';
import { SystemCard } from '@/components/chat/SystemCard';
import { makerChatStore } from '@/lib/makerChatStore';
import type { Message } from '@/lib/ccAgent.types';
+
+const live = vi.hoisted(() => ({ row: null as any, open: (() => {}) as () => void }));
vi.mock('react-i18next', async (importOriginal) => ({
...await importOriginal<typeof import('react-i18next')>(),
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock('@/components/chat/MarkdownRenderer', () => ({ MarkdownRenderer: ({ content, currentSessionId, workingDir }: any) => <a data-session={currentSessionId} data-workdir={workingDir}>{content}</a> }));
vi.mock('@/components/chat/ChatSessionFileContext', () => ({ useChatSessionFile: () => ({ origin: { kind: 'device', deviceId: 'home' }, sessionId: 'parent', workingDir: '/parent-task' }), ChatSessionFileProvider: ({ children }: any) => children }));
-vi.mock('@/features/bots/BotCollaborationCard', () => ({ BotSessionTaskCard: () => null, BotSessionTaskMessageTrace: () => null }));
+vi.mock('@/features/bots/BotCollaborationCard', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../BotCollaborationCard')>(),
+ BotSessionTaskCard: () => null,
+ BotSessionTaskMessageTrace: () => null,
+}));
vi.mock('@/features/learn/LearnStatusCard', () => ({ LearnStatusCard: () => null }));
-const live = vi.hoisted(() => ({ row: null as any }));
-vi.mock('../botDelegationLive', () => ({ useBotDelegation: vi.fn(() => live) }));
-beforeEach(() => { live.row = null; });
+// The original task's live identity; the receipt must not take status or text from it.
+vi.mock('../BotSessionTaskLink', () => ({
+ useBotTaskSession: () => ({
+ row: live.row, resolved: true, stale: false, targetId: 'child', session: null, sourceDeviceId: undefined,
+ activity: null, running: live.row?.status === 'running', originConflict: false, open: live.open,
+ }),
+}));
+vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => [] }));
+vi.mock('@/cindy-brain/ghostUnreadStore', () => ({ useElementVisible: () => ({ ref: () => {}, visible: false }) }));
+vi.mock('@/contexts/PrRefsContext', () => ({
+ usePrActions: () => ({ registerPrConsumer: () => () => {}, invalidateRemotePrRefs: () => {} }),
+ usePrRefsForSession: () => [],
+ usePrStatuses: () => ({ statuses: new Map(), successfulStatuses: new Map(), refreshError: false }),
+}));
+beforeEach(() => { live.row = null; live.open = vi.fn(); });
afterEach(cleanup);
const card = { v: 1, role: 'delegation-result', delegationId: 'task-1', fromBotId: 'cindy', fromBotName: 'Cindy', toBotId: null, toBotName: 'Cindy', parentSessionId: 'parent', childSessionId: 'child', objective: 'Report', result: { workingDir: '/child-task', runSequence: 2, status: 'completed', text: 'Second result', artifacts: [{ absolutePath: '/reports/second.pdf' }] } };
+const resultLinks = (container: HTMLElement) => [...container.querySelectorAll('a')];
+
it('keeps the execution result and its files in the receipt, without replacing it with live execution data', () => {
expect(readBotCollaborationMeta(card)).toMatchObject({ role: 'delegation-result' });
const [mapped] = makerChatStore.__mapServerMessagesForTest([{
@@ -29,52 +48,69 @@ it('keeps the execution result and its files in the receipt, without replacing i
expect(mapped.systemCardType).toBe('bot-session-task-result');
expect(mapped.systemCardData).toMatchObject({ role: 'delegation-result', delegationId: 'task-1' });
const { container } = render(<SystemCard cardType={mapped.systemCardType!} data={mapped.systemCardData} />);
- expect(screen.getByRole('button', { name: 'bots.collab.viewResult' }).getAttribute('aria-expanded')).toBe('false');
- expect(container.querySelector('[hidden]')).toBeTruthy();
- fireEvent.click(screen.getByRole('button', { name: 'bots.collab.viewResult' }));
- expect(container.querySelector('[hidden]')).toBeNull();
+ // A standalone fallback receipt starts collapsed: the summary line, then the result on demand.
+ const toggle = screen.getByRole('button', { name: /bots\.collab\.expandResult/ });
+ expect(toggle.getAttribute('aria-expanded')).toBe('false');
+ expect(resultLinks(container)).toHaveLength(0);
expect(screen.getByText('Second result')).toBeTruthy();
- expect(container.querySelector('a')?.dataset.session).toBe('child');
- expect(container.querySelector('a')?.dataset.workdir).toBe('/child-task');
- expect([...container.querySelectorAll('a')].some(link => link.textContent?.includes('/reports/second.pdf'))).toBe(true);
+ fireEvent.click(toggle);
+ expect(resultLinks(container)[0].textContent).toBe('Second result');
+ expect(resultLinks(container)[0].dataset.session).toBe('child');
+ expect(resultLinks(container)[0].dataset.workdir).toBe('/child-task');
+ expect(resultLinks(container).some(link => link.textContent?.includes('/reports/second.pdf'))).toBe(true);
+ expect(screen.getByRole('button', { name: /bots\.collab\.artifactCount/ })).toBeTruthy();
+});
+
+it('opens the result by default under the closing reply and names the task once', () => {
+ const { container } = render(<BotSessionTaskResultCard data={{ ...card, result: { ...card.result, title: 'Prepare report' } }} attached />);
+ expect(screen.getByRole('button', { name: /bots\.collab\.collapseResult/ }).getAttribute('aria-expanded')).toBe('true');
+ expect(resultLinks(container)[0].textContent).toBe('Second result');
+ expect(screen.getAllByText('Prepare report')).toHaveLength(1);
+ fireEvent.click(screen.getByRole('button', { name: 'Prepare report' }));
+ expect(live.open).toHaveBeenCalled();
});
+
it('renders image-only and linked results in the child file context', () => {
const text = '![chart](/child-task/chart.png) [Report](https://example.com/report.pdf)';
- const { container } = render(<BotSessionTaskResultCard data={{ ...card, result: { ...card.result, text, artifacts: [] } }} />);
+ const { container } = render(<BotSessionTaskResultCard data={{ ...card, result: { ...card.result, text, artifacts: [] } }} attached />);
const result = container.querySelector('a');
expect(result?.textContent).toBe(text);
expect(result?.dataset.session).toBe('child');
expect(result?.dataset.workdir).toBe('/child-task');
expect(screen.queryByText('bots.collab.noWrittenResult')).toBeNull();
});
+
it('uses human fallback for a stopped task with no result and rejects malformed receipts', () => {
const { rerender } = render(<BotSessionTaskResultCard data={{ ...card, result: { ...card.result, status: 'cancelled', text: '', artifacts: [] } }} />);
+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.expandDetails/ }));
expect(screen.getByText('bots.collab.noWrittenResult')).toBeTruthy();
rerender(<BotSessionTaskResultCard data={{ ...card, result: {} }} />);
expect(screen.queryByText('Report')).toBeNull();
});
it('keeps frozen failure details behind their own disclosure', () => {
- const { container } = render(<BotSessionTaskResultCard data={{ ...card, result: { ...card.result, status: 'timed-out', error: 'TIMEOUT: upstream did not finish' } }} />);
+ render(<BotSessionTaskResultCard data={{ ...card, result: { ...card.result, status: 'timed-out', error: 'TIMEOUT: upstream did not finish' } }} />);
expect(screen.getByText('bots.collab.status.timed-out')).toBeTruthy();
- fireEvent.click(screen.getByRole('button', { name: 'bots.collab.viewResult' }));
- const details = screen.getByText('TIMEOUT: upstream did not finish').closest('details');
+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.expandDetails/ }));
+ const details = screen.getByText('TIMEOUT: upstream did not finish', { selector: 'p' }).closest('details');
expect(details?.open).toBe(false);
expect(details?.querySelector('summary')?.textContent).toBe('appError.details');
});
it('uses the explicit frozen title ahead of the current task and instruction', () => {
- live.row = { title: 'Renamed task', status: 'running', resultSummary: 'New output' };
+ live.row = { title: 'Renamed task', status: 'running', resultSummary: 'New output', artifacts: [] };
render(<BotSessionTaskResultCard data={{ ...card, objective: 'Long execution instruction', result: { ...card.result, title: 'Prepare report' } }} />);
expect(screen.getByText('Prepare report')).toBeTruthy();
expect(screen.queryByText('Long execution instruction')).toBeNull();
expect(screen.queryByText('Renamed task')).toBeNull();
expect(screen.getByText('bots.collab.status.completed')).toBeTruthy();
expect(screen.getByText('Second result')).toBeTruthy();
+ expect(screen.queryByText('New output')).toBeNull();
+ expect(screen.queryByRole('button', { name: /bots\.collab\.stop/ })).toBeNull();
});
it('recovers a legacy receipt title without taking the live status or result', () => {
- live.row = { title: 'Prepare report', status: 'running', resultSummary: 'New output' };
+ live.row = { title: 'Prepare report', status: 'running', resultSummary: 'New output', artifacts: [] };
const { rerender } = render(<BotSessionTaskResultCard data={{ ...card, objective: 'Long instruction' }} />);
expect(screen.getByText('Prepare report')).toBeTruthy();
expect(screen.getByText('bots.collab.status.completed')).toBeTruthy();
@@ -83,15 +119,19 @@ it('recovers a legacy receipt title without taking the live status or result', (
rerender(<BotSessionTaskResultCard data={{ ...card, objective: 'First line\nFull instruction' }} />);
expect(screen.getByText('First line')).toBeTruthy();
rerender(<BotSessionTaskResultCard data={{ ...card, objective: ' ' }} />);
- expect(screen.getByText('bots.collab.backgroundTask')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'bots.collab.backgroundTask' })).toBeTruthy();
});
-it.each(['completed', 'failed', 'cancelled', 'timed-out'])('keeps %s readable and expandable', (status) => {
+it.each([
+ ['completed', 'expandResult', 'collapseResult'],
+ ['failed', 'expandDetails', 'collapseDetails'],
+ ['cancelled', 'expandDetails', 'collapseDetails'],
+ ['timed-out', 'expandDetails', 'collapseDetails'],
+])('keeps %s readable and expandable', (status, expand, collapse) => {
const { container } = render(<BotSessionTaskResultCard data={{ ...card, result: { ...card.result, status } }} />);
expect(screen.getByText(`bots.collab.status.${status}`)).toBeTruthy();
- const button = screen.getByRole('button', { name: 'bots.collab.viewResult' });
- fireEvent.click(button);
- expect(container.querySelector('[hidden]')).toBeNull();
- fireEvent.click(button);
- expect(container.querySelector('[hidden]')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: new RegExp(`bots\\.collab\\.${expand}`) }));
+ expect(resultLinks(container).length).toBeGreaterThan(0);
+ fireEvent.click(screen.getByRole('button', { name: new RegExp(`bots\\.collab\\.${collapse}`) }));
+ expect(resultLinks(container)).toHaveLength(0);
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotTaskOwnerChip.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotTaskOwnerChip.test.tsx
new file mode 100644
index 0000000000..53f9eb7f60
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotTaskOwnerChip.test.tsx
@@ -0,0 +1,52 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+import { BotTaskOwnerChip } from '../BotTaskOwnerChip';
+
+const mocks = vi.hoisted(() => ({ navigate: vi.fn(), ensure: vi.fn(), profiles: [] as unknown[] }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string, options?: Record<string, unknown>) => `${key}:${JSON.stringify(options)}` }),
+}));
+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.navigate }));
+vi.mock('../BotAvatar', () => ({ BotAvatar: ({ bot }: any) => <span data-avatar={bot.name} /> }));
+vi.mock('../botStore', () => ({
+ useBotProfiles: () => mocks.profiles,
+ ensureBotProfilesLoaded: mocks.ensure,
+}));
+
+const profile = {
+ id: 'bot/a',
+ name: 'LiZi',
+ sessions: [
+ { id: 'main', role: 'canonical', kind: 'chat' },
+ { id: 'task', role: 'delegation', kind: 'worker' },
+ { id: 'old', role: 'history', kind: 'history' },
+ ],
+};
+beforeEach(() => {
+ mocks.profiles = [profile];
+ mocks.ensure.mockReset().mockResolvedValue([]);
+ mocks.navigate.mockReset();
+});
+afterEach(cleanup);
+
+it("names a Bot's background task in its ordinary header and leads back to that Bot", () => {
+ render(<BotTaskOwnerChip sessionId="task" />);
+ expect(mocks.ensure).toHaveBeenCalledTimes(1);
+ expect(screen.getByText('bots.session.ownedByBot:{"name":"LiZi"}')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'bots.session.backToBot:{"name":"LiZi"}' }));
+ expect(mocks.navigate).toHaveBeenCalledWith('/bots/bot%2Fa');
+});
+
+it.each(['main', 'old', 'plain'])('stays out of the way for %s', (sessionId) => {
+ const { container } = render(<BotTaskOwnerChip sessionId={sessionId} />);
+ expect(container.firstChild).toBeNull();
+});
+
+it('is mounted next to the ordinary task title', () => {
+ const header = readFileSync(resolve(__dirname, '../../cc-agent/SessionContentHeader.tsx'), 'utf8');
+ expect(header).toContain('{!isEditing && <BotTaskOwnerChip sessionId={session.id} />}');
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotTodoList.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotTodoList.test.tsx
new file mode 100644
index 0000000000..82a4c30dec
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotTodoList.test.tsx
@@ -0,0 +1,133 @@
+// @vitest-environment jsdom
+import type { ReactNode } from 'react';
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { TeammateTodo } from '@cindy/maker-shared/teammate-todo';
+import { TodoPanel, type TodoTransport } from '../BotTodoList';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+}));
+// Radix 浮层在 jsdom 里不真的开合:菜单摊平成按钮,确认框只在 open 时渲染标题与两个按钮。
+vi.mock('@/components/ui/dropdown-menu', () => {
+ const Pass = ({ children }: { children?: ReactNode }) => <>{children}</>;
+ return {
+ DropdownMenu: Pass,
+ DropdownMenuTrigger: Pass,
+ DropdownMenuContent: ({ children }: { children: ReactNode }) => <div role="menu">{children}</div>,
+ DropdownMenuItem: ({ children, onSelect }: { children: ReactNode; onSelect?: () => void }) => (
+ <button type="button" role="menuitem" onClick={onSelect}>
+ {children}
+ </button>
+ ),
+ DropdownMenuLabel: Pass,
+ DropdownMenuSeparator: () => null,
+ DropdownMenuRadioGroup: Pass,
+ DropdownMenuRadioItem: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+ };
+});
+vi.mock('@/components/ui/confirm-dialog', () => ({
+ ConfirmDialog: (p: {
+ open: boolean;
+ title: string;
+ description?: string;
+ confirmText?: string;
+ cancelText?: string;
+ onConfirm?: () => void;
+ onOpenChange: (open: boolean) => void;
+ }) =>
+ p.open ? (
+ <div role="dialog" aria-label={p.title}>
+ <p>{p.description}</p>
+ <button type="button" onClick={() => p.onConfirm?.()}>
+ {p.confirmText}
+ </button>
+ <button type="button" onClick={() => p.onOpenChange(false)}>
+ {p.cancelText}
+ </button>
+ </div>
+ ) : null,
+}));
+
+function todo(patch: Partial<TeammateTodo> = {}): TeammateTodo {
+ return {
+ id: 'todo-1',
+ revision: 3,
+ key: 'user:1',
+ origin: 'assigned',
+ title: '回复 Dash 的部署窗口问题',
+ progress: '',
+ outcome: '',
+ value: '',
+ next: null,
+ sources: [{ kind: 'feishu', id: 'm1', label: '飞书' }] as TeammateTodo['sources'],
+ associations: [],
+ status: 'open',
+ createdAt: '2026-10-01T00:00:00.000Z',
+ updatedAt: '2026-10-01T00:00:00.000Z',
+ sourceDeadline: null,
+ deadlineCandidate: null,
+ suggestedDate: null,
+ decision: null,
+ history: [],
+ action: null,
+ ...patch,
+ };
+}
+
+let transport: TodoTransport & { update: ReturnType<typeof vi.fn> };
+beforeEach(() => {
+ transport = {
+ list: vi.fn(async () => ({ items: [todo()] })),
+ update: vi.fn(async () => todo()),
+ act: vi.fn(async () => null),
+ };
+});
+afterEach(cleanup);
+
+async function openRow() {
+ render(<TodoPanel transport={transport} />);
+ return within(await screen.findByRole('listitem'));
+}
+
+it('shows one title line and a due · origin · source meta line, without an empty date button', async () => {
+ const row = await openRow();
+ expect(row.getByText('回复 Dash 的部署窗口问题')).toBeTruthy();
+ expect(row.getByText('teammateTodo.assigned · 飞书')).toBeTruthy();
+ expect(row.queryByRole('button', { name: 'teammateTodo.deadline' })).toBeNull();
+});
+
+it.each([
+ ['delete', 'teammateTodo.deleteConfirmTitle'],
+ ['mute', 'teammateTodo.muteConfirmTitle'],
+] as const)('asks before %s and only writes after confirming', async (operation, title) => {
+ const row = await openRow();
+ fireEvent.click(row.getByRole('menuitem', { name: `teammateTodo.${operation}` }));
+ const dialog = await screen.findByRole('dialog', { name: title });
+ expect(transport.update).not.toHaveBeenCalled();
+ fireEvent.click(within(dialog).getByRole('button', { name: `teammateTodo.${operation}` }));
+ await waitFor(() =>
+ expect(transport.update).toHaveBeenCalledWith({ operation, id: 'todo-1', expectedRevision: 3 }),
+ );
+ await waitFor(() => expect(screen.queryByRole('dialog', { name: title })).toBeNull());
+});
+
+it.each(['delete', 'mute'] as const)('cancelling %s writes nothing', async (operation) => {
+ const row = await openRow();
+ fireEvent.click(row.getByRole('menuitem', { name: `teammateTodo.${operation}` }));
+ const dialog = await screen.findByRole('dialog');
+ fireEvent.click(within(dialog).getByRole('button', { name: 'teammateTodo.cancel' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(transport.update).not.toHaveBeenCalled();
+});
+
+it('puts the next action first in the row menu instead of a separate pill', async () => {
+ transport.list = vi.fn(async () => ({
+ items: [todo({ next: { kind: 'advance', label: '让伙伴接着做', instruction: '回复' } as TeammateTodo['next'] })],
+ }));
+ const row = await openRow();
+ const items = row.getAllByRole('menuitem');
+ expect(items[0]!.textContent).toBe('让伙伴接着做');
+ fireEvent.click(items[0]!);
+ await waitFor(() => expect(transport.act).toHaveBeenCalledWith(expect.objectContaining({ id: 'todo-1', revision: 3 })));
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx
new file mode 100644
index 0000000000..1332ffd1f4
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx
@@ -0,0 +1,206 @@
+// @vitest-environment jsdom
+import type { ReactNode } from 'react';
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { Session } from '@/lib/ccAgent.types';
+
+// 真实的工作台组件、投影与分组;只隔离宿主数据、任务列表读取与浮层。
+const m = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ readTask: vi.fn(),
+ sendMessage: vi.fn(async () => true),
+ rows: { active: [] as Session[], archived: [] as Session[] },
+ activity: new Map<string, unknown>(),
+}));
+vi.mock('react-router-dom', () => ({ useNavigate: () => m.navigate }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) =>
+ values && 'count' in values ? `${key}:${String(values.count)}` : key,
+ i18n: { language: 'en' },
+ }),
+}));
+vi.mock('../BotTodoList', () => ({ BotTodoList: () => <section aria-label="todos" /> }));
+vi.mock('../useWorkbenchSessionPages', () => ({
+ useWorkbenchSessionPages: (_scope: string, status: 'active' | 'archived') => ({
+ rows: m.rows[status],
+ loading: false,
+ error: false,
+ hasMore: false,
+ load: vi.fn(),
+ }),
+}));
+vi.mock('../useWorkbenchSessionActions', () => ({
+ useWorkbenchSessionActions: (rows: Session[]) => ({
+ open: vi.fn(),
+ action: vi.fn(),
+ togglePin: vi.fn(),
+ byId: new Map(rows.map((row) => [row.id, row])),
+ }),
+}));
+vi.mock('../botStore', () => ({ useBotProfiles: () => [{ id: 'bot-1', name: 'LiZi', sessions: [] }] }));
+vi.mock('../botDelegationLive', () => ({ useBotDelegations: () => [] }));
+vi.mock('@/hooks/useCCSessions', () => ({ useCCSessions: () => ({ sessions: [] }) }));
+vi.mock('@/state/agentIslandActivity', () => ({ useAgentIslandActivityMap: () => m.activity }));
+vi.mock('@/lib/sessionAttentionStore', () => ({ useSessionAttentionKinds: () => new Map() }));
+vi.mock('@/features/scheduler/lib/schedulesStore', () => ({
+ useSchedulesSnapshot: () => [],
+ schedulesStore: { ensure: async () => undefined },
+}));
+vi.mock('@/contexts/PrRefsContext', () => ({
+ usePrActions: () => ({ registerPrConsumer: () => () => undefined }),
+ usePrRefsForSession: () => [],
+ usePrStatuses: () => ({ statuses: new Map(), successfulStatuses: new Map() }),
+}));
+vi.mock('@/cindy-brain/ghostUnreadStore', () => ({ useElementVisible: () => ({ ref: () => undefined, visible: false }) }));
+vi.mock('@/lib/sessionService', () => ({ get: async () => ({ workingDir: '/p', model: 'm' }) }));
+vi.mock('@/lib/sessionsBus', () => ({ emitRefresh: vi.fn() }));
+vi.mock('@/lib/sidebarWindow', () => ({ isSidebarWindow: () => false }));
+vi.mock('@/lib/orcaSessionIdentity', () => ({ resolveSessionRoute: async (id: string) => '/cc-agent/' + id }));
+vi.mock('@/lib/makerChatStore', () => ({
+ makerChatStore: {
+ subscribe: () => () => undefined,
+ getSnapshot: () => null,
+ sendMessage: m.sendMessage,
+ stopSession: vi.fn(),
+ },
+}));
+vi.mock('@/components/ui/tooltip', () => ({ Tip: ({ children }: { children: ReactNode }) => <>{children}</> }));
+vi.mock('@/components/ui/dropdown-menu', () => {
+ const Pass = ({ children }: { children?: ReactNode }) => <>{children}</>;
+ return {
+ DropdownMenu: Pass,
+ DropdownMenuTrigger: Pass,
+ DropdownMenuContent: ({ children }: { children: ReactNode }) => <div role="menu">{children}</div>,
+ DropdownMenuItem: ({ children, onSelect }: { children: ReactNode; onSelect?: () => void }) => (
+ <button type="button" role="menuitem" onClick={onSelect}>
+ {children}
+ </button>
+ ),
+ };
+});
+
+import { BotWorkbench } from '../BotWorkbench';
+
+function session(id: string, patch: Partial<Session> = {}): Session {
+ return {
+ id,
+ title: id,
+ workingDir: '/p',
+ workspaceKind: 'project',
+ status: 'active',
+ agentKind: 'cc',
+ source: 'desktop',
+ userSendAt: '2026-10-01T01:00:00.000Z',
+ updatedAt: '2026-10-01T01:00:00.000Z',
+ createdAt: '2026-10-01T00:00:00.000Z',
+ ...patch,
+ } as Session;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ m.rows = {
+ active: [session('s-wait'), session('s-run'), session('s-todo'), session('s-idle')],
+ archived: [session('s-old', { status: 'archived', title: '旧任务' })],
+ };
+ m.activity = new Map<string, unknown>([
+ ['s-wait', { phase: 'needs-interaction', interactionKind: 'permission', currentActionSummary: '删旧迁移' }],
+ ['s-run', { phase: 'running', startedAtMs: Date.now() - 5_000, currentActionSummary: 'pnpm test' }],
+ ]);
+ m.readTask.mockResolvedValue({
+ ok: true,
+ transcript: { items: [{ role: 'assistant', text: '测试也要覆盖断网重连。', at: Date.now() }], truncated: false },
+ });
+ window.electronAPI = {
+ platform: 'darwin',
+ localDb: {
+ bots: {
+ workbench: {
+ get: async () => ({
+ directories: [{ path: '/p', name: 'p', exists: true }],
+ tasks: {
+ 's-todo': {
+ title: '修复登录超时',
+ verdict: 'unfinished',
+ next: '刷新重试没有上限,改成 3 次',
+ project: '/p',
+ updatedAt: '2026-10-01T00:00:00.000Z',
+ },
+ },
+ responsibleSessionIds: ['s-wait', 's-run', 's-todo', 's-idle', 's-old'],
+ }),
+ candidates: async () => ({ ok: true, candidates: [] }),
+ readTask: m.readTask,
+ },
+ },
+ },
+ maker: { onBotWorkbenchChanged: () => () => undefined, onBotDelegationChanged: () => () => undefined },
+ } as unknown as Window['electronAPI'];
+});
+afterEach(cleanup);
+
+it('lists Cindy tasks in one column with a summary, groups, 跟进 only where it belongs, and archived at the bottom of done', async () => {
+ render(<BotWorkbench botId="bot-1" sessionId="bot-main" />);
+ expect(await screen.findByText(
+ 'bots.workbench.summary.waiting:1 · bots.workbench.summary.running:1 · bots.workbench.summary.todo:1',
+ )).toBeTruthy();
+
+ const waiting = screen.getByRole('region', { name: 'bots.workbench.group.waiting' });
+ expect(within(waiting).getByText('bots.workbench.line.waitingFor')).toBeTruthy();
+ expect(within(waiting).getByRole('button', { name: 'bots.workbench.followUp.aria' })).toBeTruthy();
+
+ const running = screen.getByRole('region', { name: 'bots.workbench.group.running' });
+ expect(within(running).getByText('pnpm test')).toBeTruthy();
+ expect(within(running).queryByRole('button', { name: 'bots.workbench.followUp.aria' })).toBeNull();
+
+ const todo = screen.getByRole('region', { name: 'bots.workbench.group.todo' });
+ expect(within(todo).getByText('修复登录超时')).toBeTruthy();
+ expect(within(todo).getByText('刷新重试没有上限,改成 3 次')).toBeTruthy();
+ expect(within(todo).getByRole('button', { name: 'bots.workbench.followUp.aria' })).toBeTruthy();
+
+ const done = screen.getByRole('region', { name: 'bots.workbench.group.done' });
+ expect(within(done).queryByText('旧任务')).toBeNull();
+ fireEvent.click(within(done).getByRole('button', { expanded: false }));
+ expect(within(done).getByText('s-idle')).toBeTruthy();
+ expect(within(done).getByText('旧任务')).toBeTruthy();
+ expect(within(done).getByText('ccAgent.sidebar.filterStatus.archived')).toBeTruthy();
+ expect(within(done).queryByRole('button', { name: 'bots.workbench.followUp.aria' })).toBeNull();
+ // 每条 Cindy 任务都带任务菜单;归档的给「取消归档」。
+ expect(within(done).getAllByRole('menuitem', { name: 'ccAgent.sidebar.sessionMenu.unarchive' })).toHaveLength(1);
+});
+
+it('opens a Cindy task inside the panel, reads it, and returns to the list', async () => {
+ render(<BotWorkbench botId="bot-1" sessionId="bot-main" />);
+ const todo = await screen.findByRole('region', { name: 'bots.workbench.group.todo' });
+ fireEvent.click(within(todo).getByRole('button', { name: 'bots.workbench.openTask' }));
+
+ const crumb = await screen.findByRole('navigation', { name: 'bots.workbench.title' });
+ expect(within(crumb).getByText('修复登录超时')).toBeTruthy();
+ expect(m.navigate).not.toHaveBeenCalled();
+ await waitFor(() => expect(m.readTask).toHaveBeenCalledWith('bot-1', 's-todo'));
+ expect(await screen.findByText('测试也要覆盖断网重连。')).toBeTruthy();
+ expect(screen.getByText('bots.workbench.detail.judgment')).toBeTruthy();
+ expect(screen.getByRole('button', { name: /bots.workbench.detail.openInTasks/ })).toBeTruthy();
+
+ fireEvent.click(within(crumb).getByRole('button', { name: 'bots.workbench.title' }));
+ expect(await screen.findByRole('region', { name: 'bots.workbench.group.todo' })).toBeTruthy();
+});
+
+it('opens an archived task read-only, without restoring it or offering 补一句', async () => {
+ render(<BotWorkbench botId="bot-1" sessionId="bot-main" />);
+ const done = await screen.findByRole('region', { name: 'bots.workbench.group.done' });
+ fireEvent.click(within(done).getByRole('button', { expanded: false }));
+ fireEvent.click(within(done).getAllByRole('button', { name: 'bots.workbench.openTask' }).at(-1)!);
+ await waitFor(() => expect(m.readTask).toHaveBeenCalledWith('bot-1', 's-old'));
+ expect(screen.queryByRole('textbox')).toBeNull();
+ expect(m.navigate).not.toHaveBeenCalled();
+});
+
+it('shows the live action and a stop control for a running Cindy task', async () => {
+ render(<BotWorkbench botId="bot-1" sessionId="bot-main" />);
+ const running = await screen.findByRole('region', { name: 'bots.workbench.group.running' });
+ fireEvent.click(within(running).getByRole('button', { name: 'bots.workbench.openTask' }));
+ expect(await screen.findByText('bots.workbench.detail.doing')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'bots.workbench.detail.stop' })).toBeTruthy();
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx
index ad11d8bf9d..5678ee7d72 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx
@@ -42,3 +42,9 @@ it('lets a companion owner manage a group owned by their companion', async () =>
expect(screen.getByRole('button', { name: key('transfer') })).toBeTruthy();
await waitFor(() => expect(mocks.ownedBots).toHaveBeenCalled());
});
+it('labels reply and speaking modes with the same words as the local group settings', () => {
+ render(<MemoryRouter><ChatGroupSettings group={{ ...group(true), replyMode: 'all', speakingMode: 'auto' }} /></MemoryRouter>);
+ expect(screen.getByRole('combobox', { name: 'bots.groupChat.settings.replyMode' }).textContent).toContain('bots.groupChat.settings.replyModeAll');
+ expect(screen.getByRole('combobox', { name: 'bots.groupChat.settings.speakingMode' }).textContent).toContain('bots.groupChat.settings.speakingModeAuto');
+ expect(screen.queryByText(key('replyMode'))).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
index bc9ceb2032..3a9fe2dcf9 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
@@ -13,7 +13,11 @@ const mocks = vi.hoisted(() => ({
status: vi.fn(), react: vi.fn(), thread: vi.fn(), reply: vi.fn(), createInvite: vi.fn(), previewInvite: vi.fn(), acceptInvite: vi.fn(),
refresh: vi.fn(), ownerCurrent: true,
}));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));
+// Partial: the 话题 reply box shares the group composer, whose attachment pieces pull in the app i18n instance.
+vi.mock('react-i18next', async (original) => ({
+ ...(await original<typeof import('react-i18next')>()),
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+}));
vi.mock('@/components/chat/MarkdownRenderer', () => ({ MarkdownRenderer: ({ content }: { content: string }) => <div>{content}</div> }));
vi.mock('../BotAvatar', () => ({ BotAvatar: () => null }));
vi.mock('../botGroupStore', () => ({ refreshBotGroups: mocks.refresh }));
@@ -22,7 +26,7 @@ vi.mock('@/contexts/dataOwnerGeneration', () => ({
getDataOwnerGeneration: () => 1, isDataOwnerGenerationCurrent: () => mocks.ownerCurrent, isDataOwnerPushCurrent: () => true,
}));
const k = (name: string) => `bots.groupChat.server.${name}`;
-const message = { id: 'root', authorName: 'Human', content: 'Root message', reactions: [{ emoji: '👍', count: 2, me: true }] } as BotGroupMessageView;
+const message = { id: 'root', kind: 'message', authorKind: 'user', isSelf: false, authorName: 'Human', content: 'Root message', reactions: [{ emoji: '👍', count: 2, me: true }] } as BotGroupMessageView;
const group = { id: 'room', members: [], messages: [message] } as unknown as BotGroupDetail;
const render = (ui: ReactNode) => renderUI(<Tooltip.Provider>{ui}</Tooltip.Provider>);
beforeEach(() => {
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts
index 66307d8995..aa7cd1b291 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts
@@ -49,11 +49,12 @@ describe('消息流的头像挂载', () => {
it('只有 assistant 分支挂头像', () => {
expect(messageStream).toContain('return withAssistantAvatar(\n assistantAvatar,');
- // Assistant text shows the avatar; both task references reserve the same
- // space invisibly. User messages and internal tool/work cards still bypass it.
- expect(messageStream.match(/withAssistantAvatar\(/g)?.length).toBe(3);
- expect(messageStream).toMatch(/simplifiedBotConversation\s*&&\s*\(message\.systemCardType === 'bot-session-task'\s*\|\|\s*message\.systemCardType === 'bot-session-task-result'\)\s*\? withAssistantAvatar\(/);
+ // Assistant text shows the avatar; task and teammate-message cards plus the
+ // work fold reserve the same space invisibly. User messages bypass it.
+ expect(messageStream.match(/withAssistantAvatar\(/g)?.length).toBe(4);
+ expect(messageStream).toMatch(/simplifiedBotConversation\s*&&\s*\(message\.systemCardType === 'bot-session-task'\s*\|\|\s*message\.systemCardType === 'bot-session-task-result'\s*\|\|\s*message\.systemCardType === 'bot-session-task-message'\s*\|\|\s*message\.systemCardType === 'bot-direct-message'\)\s*\? withAssistantAvatar\(/);
expect(messageStream).toMatch(/<span aria-hidden="true" className="invisible">\s*\{assistantAvatar\}\s*<\/span>/);
+ expect(messageStream).toContain('{replyColumnSpacer ? withAssistantAvatar(replyColumnSpacer, block) : block}');
});
});
@@ -87,16 +88,19 @@ describe('伙伴设置包含独立能力选择入口', () => {
});
});
-describe('伙伴消息流收起内部工作过程', () => {
- it('只对伙伴收拢过程,运行期间保留单一状态出口', () => {
+describe('伙伴消息流与普通任务同一套工作过程', () => {
+ it('工作组按普通任务渲染,输入框上方只保留普通状态栏', () => {
expect(sessionView).toContain('simplifiedBotConversation={Boolean(botChatIdentity)}');
expect(messageStream).toContain('simplifyBotRenderItems(grouped, isSessionStreaming, visibleGeneratedFileKeys)');
// Text/tool grouping is covered by botConversationPresentation behavioral tests.
expect(messageStream).toContain("from '@/features/bots/botConversationPresentation'");
- expect(messageStream).toContain('compact={simplifiedBotConversation}');
+ expect(messageStream).toContain('compact={false}');
+ expect(messageStream).not.toContain('compact={simplifiedBotConversation}');
+ expect(messageStream).toContain('replyColumnSpacer={botReplyColumnSpacer}');
expect(messageStream).not.toContain('data-testid="bot-thinking-indicator"');
- expect(sessionView).toContain('<BotWorkingStatus');
- expect(sessionView).toContain('visible={composerRuntimeVisible}');
+ expect(sessionView).not.toContain('<BotWorkingStatus');
+ expect(sessionView).toContain('<RunningStatusBar');
+ expect(sessionView).toContain('visible={composerRuntimeVisible');
expect(sessionView).not.toContain('botAssistantOutputStarted');
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts
index 3f3bc4206e..13d9d3939c 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts
@@ -15,37 +15,42 @@ const proseIds = (items: RenderItem[]) => items.flatMap((item) =>
item.type === 'message' && item.message.role === 'assistant' ? [item.message.clientId] : []);
const allKeys = (items: readonly RenderItem[]): string[] => items.flatMap((item) =>
item.type === 'work_group' ? allKeys(item.children) : [item.key]);
+/** Top-level shape: groups render as key[children], `*` marks a live tail group. */
+const shape = (items: readonly RenderItem[]): string => items.map((item) => item.type === 'work_group'
+ ? `${item.key}${item.isStreaming ? '*' : ''}[${shape(item.children)}]` : item.key).join(', ');
const project = (items: RenderItem[], streaming: boolean) =>
simplifyBotRenderItems(groupWorkRuns(items, streaming), streaming);
describe('teammate final-result presentation', () => {
- it('keeps coordination input hidden while explicit inputs, results and errors remain visible', () => {
+ it('keeps coordination input hidden while process, explicit inputs, results and errors remain visible', () => {
const rows = [message('coordination', 'user', '[UI_ACTION_TRIGGER]File agreement', { isSyntheticTrigger: true }),
tool('audit'), message('visible-input', 'user', 'Requested status'),
message('result', 'assistant', 'Final result', { turnCompleted: true }), message('error', 'error', 'Action required')];
- expect(allKeys(project(rows, false))).toEqual(['msg-visible-input', 'msg-result', 'msg-error']);
+ expect(shape(project(rows, false))).toBe('work-audit[tools-audit], msg-visible-input, msg-result, msg-error');
});
- it('omits all process rows and keeps final answers without mutating history', () => {
+ it('folds process rows into the normal work summary and keeps final answers without mutating history', () => {
const input = [message('u', 'user'), message('a', 'assistant'), tool('t1'),
message('b', 'assistant'), tool('t2'), message('final', 'assistant', 'Result', { turnCompleted: true })];
const result = project(input, false);
expect(proseIds(result)).toEqual(['final']);
- expect(result.filter((item) => item.type === 'work_group')).toHaveLength(0);
- expect(allKeys(result)).toEqual(['msg-u', 'msg-final']);
+ // Same shape as a normal session: one outer summary with intermediate prose and inner groups.
+ expect(shape(result)).toBe('msg-u, work-summary-t1[msg-a, work-t1[tools-t1], msg-b, work-t2[tools-t2]], msg-final');
expect(input[1]).toEqual(message('a', 'assistant'));
});
- it('keeps every unsealed segment collapsed from its first delta, before any tool arrives', () => {
+ it('keeps every unsealed segment out of the top level from its first delta while activity stays live', () => {
const start = [message('u', 'user'), message('a', 'assistant', 'A', { isStreaming: true })];
expect(proseIds(project(start, true))).toEqual([]);
const work = [...start, tool('t1')];
expect(proseIds(project(work, true))).toEqual([]);
- expect(project(work, true).some(item => item.type === 'work_group')).toBe(false);
+ expect(shape(project(work, true))).toBe('msg-u, work-t1*[tools-t1]');
const continued = project([...work, message('b', 'assistant', 'B', { isStreaming: true })], true);
expect(proseIds(continued)).toEqual([]);
- expect(proseIds(project([...work, message('b', 'assistant', 'B', { turnCompleted: true })], false))).toEqual(['b']);
- expect(continued.some(item => item.type === 'work_group')).toBe(false);
+ expect(shape(continued)).toBe('msg-u, work-t1[tools-t1]');
+ const done = project([...work, message('b', 'assistant', 'B', { turnCompleted: true })], false);
+ expect(proseIds(done)).toEqual(['b']);
+ expect(shape(done)).toBe('msg-u, work-summary-t1[msg-a, work-t1[tools-t1]], msg-b');
});
it.each(['stopped', 'failed', 'history'])('retains the last useful text with no final: %s', () => {
@@ -53,8 +58,7 @@ describe('teammate final-result presentation', () => {
message('last', 'assistant'), tool('t2'), message('err', 'error')];
const result = project(input, false);
expect(proseIds(result)).toEqual(['last']);
- expect(allKeys(result)).toContain('msg-err');
- expect(allKeys(result)).not.toContain('tools-t2');
+ expect(shape(result)).toBe('msg-u, work-t1[tools-t1], msg-last, work-t2[tools-t2], msg-err');
});
it('keeps all blocks of sealed replies across continuation tools and history reloads', () => {
@@ -65,7 +69,10 @@ describe('teammate final-result presentation', () => {
for (const streaming of [true, false]) {
const result = project(input, streaming);
expect(proseIds(result)).toEqual(['first', 'second', 'third', 'fourth']);
- expect(allKeys(result)).toEqual(['msg-u', 'msg-first', 'msg-second', 'msg-third', 'msg-fourth']);
+ // An earlier background-wake reply is lifted out of the fold; the summary keeps
+ // its key and the following activity group stays the same inner group.
+ expect(shape(result)).toBe('msg-u, work-summary-t1[msg-progress, work-t1[tools-t1]], msg-first, '
+ + 'msg-second, work-t2[tools-t2], msg-third, msg-fourth');
}
});
@@ -95,15 +102,14 @@ describe('teammate final-result presentation', () => {
}
});
- it('keeps a persisted task result receipt visible while process rows are hidden', () => {
+ it('keeps a persisted task result receipt visible next to the work fold', () => {
const receipt = message('receipt', 'assistant', '', {
systemCardType: 'bot-session-task-result',
systemCardData: { botCollaboration: { role: 'delegation-result' } },
});
const input = [message('u', 'user'), message('progress', 'assistant'), tool('t'), receipt];
- for (const streaming of [true, false]) {
- expect(allKeys(project(input, streaming))).toEqual(['msg-u', 'msg-receipt']);
- }
+ expect(shape(project(input, true))).toBe('msg-u, work-t*[tools-t], msg-receipt');
+ expect(shape(project(input, false))).toBe('msg-u, work-t[tools-t], msg-receipt');
});
it('retains a later explanation after partial delivery and ignores unverified file candidates', () => {
@@ -125,7 +131,8 @@ describe('teammate final-result presentation', () => {
message('u2', 'user'), message('explanation', 'assistant'), tool('failed')];
const result = simplifyBotRenderItems(groupWorkRuns(input, false), false, new Set(['files']));
expect(proseIds(result)).toEqual(['final', 'explanation']);
- expect(allKeys(result)).toEqual(['msg-u', 'msg-final', 'files', 'msg-u2', 'msg-explanation']);
+ expect(shape(result)).toBe('msg-u, work-summary-t[msg-progress, work-t[tools-t]], msg-final, files, '
+ + 'msg-u2, msg-explanation, work-failed[tools-failed]');
});
it('does not extend a final seal or delivery fallback across a history gap without tools', () => {
@@ -172,29 +179,68 @@ describe('teammate final-result presentation', () => {
for (const card of cards) expect(result.some((item) => item.key === card.key)).toBe(true);
});
- it('removes empty avatar rows and thinking from nested work without changing stored content', () => {
+ it('drops empty avatar rows but keeps thinking inside the work fold without changing stored content', () => {
const thinking = message('private', 'thinking', 'Not public execution');
const input: RenderItem[] = [message('u', 'user'), message('empty', 'assistant', ' '),
{ type: 'work_group', key: 'work-nested', isStreaming: false, children: [thinking, tool('t')] },
message('answer', 'assistant')];
- expect(allKeys(project(input, false))).toEqual(['msg-u', 'msg-answer']);
+ expect(shape(project(input, false))).toBe('msg-u, work-nested[msg-private, tools-t], msg-answer');
expect(thinking).toEqual(message('private', 'thinking', 'Not public execution'));
});
- it('omits unloaded technical history without calling its expansion or retry API', () => {
+ it('passes unloaded technical history to the normal work fold without calling its expansion or retry API', () => {
const deferred = { owner: {}, key: 'range', expanded: false, loading: false, failed: false,
toggle: vi.fn(), retry: vi.fn(), setVisible: vi.fn() };
const group: RenderItem = { type: 'work_group', key: 'work-history', isStreaming: false,
children: [], deferred };
const input = [message('u', 'user'), group, message('final', 'assistant')];
- expect(allKeys(simplifyBotRenderItems(input, false))).toEqual(['msg-u', 'msg-final']);
+ const unloaded = simplifyBotRenderItems(input, false);
+ expect(shape(unloaded)).toBe('msg-u, work-history[], msg-final');
+ expect(unloaded[1]).toBe(group);
const loaded = { ...group, children: [message('thinking', 'thinking'), message('public', 'assistant'), tool('t')] };
const result = simplifyBotRenderItems([input[0], loaded as RenderItem, input[2]], false);
- expect(allKeys(result)).toEqual(['msg-u', 'msg-final']);
+ expect(shape(result)).toBe('msg-u, work-history[msg-thinking, msg-public, tools-t], msg-final');
expect(deferred.toggle).not.toHaveBeenCalled();
expect(deferred.retry).not.toHaveBeenCalled();
expect(group.deferred).toBe(deferred);
});
+
+ it('shows a running turn as a live work group and a finished turn as the summary with the answer outside', () => {
+ const at = (offset: number) => new Date(Date.parse('2026-10-15T08:00:00Z') + offset).toISOString();
+ const running = [message('u', 'user', 'Fix it', { createdAt: at(0) }),
+ message('think', 'thinking', 'Looking at refresh', { createdAt: at(1000) }),
+ { ...tool('read'), toolCalls: [{ ...tool('read').toolCalls[0], createdAt: at(2000) }] }];
+ const live = project(running, true);
+ expect(shape(live)).toBe('msg-u, work-think*[msg-think, tools-read]');
+ const liveGroup = live[1];
+ expect(liveGroup.type === 'work_group' && liveGroup.startedAtMs).toBe(Date.parse(at(0)));
+
+ const finished = project([...running,
+ message('answer', 'assistant', 'Done', { createdAt: at(9000), turnCompleted: true })], false);
+ expect(shape(finished)).toBe('msg-u, work-think[msg-think, tools-read], msg-answer');
+ const doneGroup = finished[1];
+ expect(doneGroup.type === 'work_group' && doneGroup.durationMs).toBe(9000);
+ expect(proseIds(finished)).toEqual(['answer']);
+ });
+
+ it('splits a folded summary around an explicitly delivered reply and keeps the original key first', () => {
+ const at = (offset: number) => new Date(Date.parse('2026-10-15T08:00:00Z') + offset).toISOString();
+ const summary: RenderItem = { type: 'work_group', key: 'work-summary-x', isStreaming: false,
+ startedAtMs: Date.parse(at(0)), durationMs: 10_000, children: [
+ message('note', 'assistant', 'Checking', { createdAt: at(1000) }),
+ { type: 'work_group', key: 'work-a', isStreaming: false, children: [tool('a')] },
+ message('told', 'assistant', 'Sent to the group', { createdAt: at(4000), explicitDelivery: true }),
+ message('after', 'assistant', 'Continuing', { createdAt: at(6000) }),
+ { type: 'work_group', key: 'work-b', isStreaming: false, children: [tool('b')] },
+ ] };
+ const result = simplifyBotRenderItems([message('u', 'user'), summary,
+ message('final', 'assistant', 'Final', { turnCompleted: true })], false);
+ expect(shape(result)).toBe('msg-u, work-summary-x[msg-note, work-a[tools-a]], msg-told, '
+ + 'work-summary-x~msg-after[msg-after, work-b[tools-b]], msg-final');
+ const [first, , second] = result.slice(1);
+ expect(first.type === 'work_group' && [first.startedAtMs, first.durationMs]).toEqual([Date.parse(at(0)), 4000]);
+ expect(second.type === 'work_group' && [second.startedAtMs, second.durationMs]).toEqual([Date.parse(at(4000)), 6000]);
+ });
});
it('keeps appended result receipts visible while the teammate is busy, across hidden wakeups', () => {
@@ -217,7 +263,7 @@ it('nests only explicitly bound results, preserving original anchor and human me
const anchor = message('anchor', 'assistant', '', { systemCardType: 'bot-session-task' });
const final = message('final', 'assistant', 'Summary', { turnCompleted: true, botTaskResults: [card] });
const input = [anchor, receipt, message('human', 'user'), message('progress', 'assistant'), tool('t'), final];
- expect(allKeys(project(input, false))).toEqual(['msg-anchor', 'msg-human', 'msg-final']);
+ expect(shape(project(input, false))).toBe('msg-anchor, msg-human, work-summary-t[msg-progress, work-t[tools-t]], msg-final');
expect(final.message.botTaskResults).toEqual([card]);
expect(allKeys(project(input.slice(0, -1), false))).toContain('msg-receipt');
expect(allKeys(project([receipt, message('unrelated', 'assistant', 'Other', { turnCompleted: true })], false))).toContain('msg-receipt');
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
index 5ac012815b..e16fe49059 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
@@ -5,6 +5,7 @@ import { cloneElement, type ReactElement, type ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BotGroupOpenPlanSummary, BotGroupSummary } from '../../../../shared/botGroupChat';
+import { botGroupReadKey, markBotRead, resetBotReadStateForTests } from '../botReadState';
vi.mock('@/hooks/useProviderOnboarding', () => ({
useProviderOnboarding: () => ({ visible: false }),
@@ -349,3 +350,23 @@ it('localizes the join preview without presenting its subject as a chat author',
expect(screen.getByText('bots.groupChat.notice.memberJoined:{"name":"Taylor"}')).toBeTruthy();
expect(screen.queryByText(/Fallback text/)).toBeNull();
});
+
+it('badges the real number of unread group messages, falling back to one on older hosts', async () => {
+ window.localStorage.clear();
+ resetBotReadStateForTests();
+ markBotRead(botGroupReadKey('g1'), 15);
+ markBotRead(botGroupReadKey('g2'), 15);
+ const at = (ms: number) => new Date(ms).toISOString();
+ mocks.groups = [
+ group({ lastReplyAt: 30, incomingMessageTimes: [at(10), at(20), at(30)] } as Partial<BotGroupSummary>),
+ group({ id: 'g2', name: '读书会', lastReplyAt: 30 }),
+ ];
+ try {
+ await renderSidebar();
+ expect(screen.getByLabelText('sidebar.teammateUnreadCount:{"count":2}').textContent).toBe('2');
+ expect(screen.getByLabelText('sidebar.teammateUnreadCount:{"count":1}').textContent).toBe('1');
+ } finally {
+ resetBotReadStateForTests();
+ window.localStorage.clear();
+ }
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts
new file mode 100644
index 0000000000..30be947bd6
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts
@@ -0,0 +1,59 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { BotGroupChangedPayload, BotGroupSummary } from '../../../../shared/botGroupChat';
+import { getBotGroupListSnapshot, resetBotGroupStoreForTests, startBotGroupSync, subscribeBotGroups } from '../botGroupStore';
+
+vi.mock('@/contexts/dataOwnerGeneration', () => ({
+ getDataOwnerGeneration: () => 1,
+ isDataOwnerGenerationCurrent: () => true,
+ isDataOwnerPushCurrent: () => true,
+}));
+
+const summary = (name: string): BotGroupSummary => ({
+ id: 'g1', name, replyMode: 'all', speakingMode: 'auto', members: [], organizerBotId: null, projectDir: null,
+ lastMessage: null, speakingBotIds: [], planningBotId: null, openPlan: null, createdAt: 1, updatedAt: 1,
+});
+
+let push: (payload: BotGroupChangedPayload, stamp?: unknown) => void = () => {};
+const listBotGroups = vi.fn();
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ resetBotGroupStoreForTests();
+ listBotGroups.mockReset().mockResolvedValue({ ok: true, groups: [summary('周末出游')] });
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { maker: { listBotGroups, onBotGroupChanged: (cb: typeof push) => { push = cb; return () => {}; } } },
+ });
+});
+
+afterEach(() => {
+ resetBotGroupStoreForTests();
+ vi.useRealTimers();
+});
+
+describe('group list mirror', () => {
+ it('reads once per burst of pushes and keeps the snapshot when nothing changed', async () => {
+ const stop = startBotGroupSync();
+ await vi.runAllTimersAsync();
+ expect(listBotGroups).toHaveBeenCalledTimes(1);
+ const first = getBotGroupListSnapshot();
+ const listener = vi.fn();
+ const unsubscribe = subscribeBotGroups(listener);
+ for (let index = 0; index < 5; index += 1) push({ groupId: 'g1', change: 'messages' });
+ expect(listBotGroups).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(300);
+ expect(listBotGroups).toHaveBeenCalledTimes(2);
+ // Same list: no re-render for the sidebar or the Dock badge.
+ expect(listener).not.toHaveBeenCalled();
+ expect(getBotGroupListSnapshot()).toBe(first);
+ listBotGroups.mockResolvedValue({ ok: true, groups: [summary('读书会')] });
+ push({ groupId: 'g1', change: 'updated' });
+ await vi.advanceTimersByTimeAsync(300);
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(getBotGroupListSnapshot().groups[0]!.name).toBe('读书会');
+ unsubscribe();
+ stop();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botReadState.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botReadState.test.ts
index 2c94994af7..39025a6c83 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botReadState.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botReadState.test.ts
@@ -1,4 +1,4 @@
-import { botGroupReadKey, isBotGroupUnread, seedBotGroupReadState } from '../botReadState';
+import { botGroupReadKey, botGroupUnreadCount, isBotGroupUnread, seedBotGroupReadState } from '../botReadState';
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -152,4 +152,26 @@ describe('Bot read positions', () => {
expect(getBotLastReadAtMap()).toEqual({});
expect(markBotRead('bot-1', 5_000)).toBe(true);
});
+
+ it('counts a group\'s unread messages from the host\'s incoming times, and falls back to one without them', () => {
+ setBotReadStateOwner('owner-1');
+ const at = (ms: number) => new Date(ms).toISOString();
+ const group = { id: 'g', lastReplyAt: 4_000, incomingMessageTimes: [at(1_000), at(2_000), at(3_000), at(4_000)] };
+ // Never read before: seeding marks the existing history as read.
+ seedBotGroupReadState([group]);
+ expect(botGroupUnreadCount(group)).toBe(0);
+ // Read up to the second message (as stored by an earlier visit).
+ window.localStorage.setItem('cindy.bots.readState.v1.owner-1', JSON.stringify({ [botGroupReadKey('g')]: 2_000 }));
+ resetBotReadStateForTests();
+ setBotReadStateOwner('owner-1');
+ expect(botGroupUnreadCount(group)).toBe(2);
+ expect(isBotGroupUnread(group)).toBe(true);
+ // An older host sends no list: anything newer reads as one.
+ expect(botGroupUnreadCount({ id: 'g', lastReplyAt: 4_000 })).toBe(1);
+ // The list and the latest reply disagreeing still never hides a new reply.
+ expect(botGroupUnreadCount({ id: 'g', lastReplyAt: 4_000, incomingMessageTimes: [] })).toBe(1);
+ markBotRead(botGroupReadKey('g'), 4_000);
+ expect(botGroupUnreadCount(group)).toBe(0);
+ expect(isBotGroupUnread(group)).toBe(false);
+ });
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts
index 806f437787..32542476f4 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts
@@ -78,12 +78,26 @@ describe('伙伴归属表', () => {
expect(findBotProfileForSession([bot], 'stale-mirror')).toBeUndefined();
});
- it('通知点击把主任务送回伙伴页,子任务保留自己的任务地址', () => {
- const bot = profile({ id: 'bot/a' });
+ it('同一个任务只有一个地址:主任务回伙伴页,历史走历史页,后台任务走普通任务页', () => {
+ const bot = profile({
+ id: 'bot/a',
+ sessions: [
+ { id: 's-main', role: 'canonical', kind: 'chat' },
+ { id: 's-telegram', role: 'route' },
+ { id: 's-old', role: 'history', kind: 'history' },
+ { id: 's-task', role: 'delegation', kind: 'worker' },
+ { id: 's-worker', kind: 'worker' },
+ { id: 's-lane', role: 'group', kind: 'group' },
+ ] as unknown as BotProfile['sessions'],
+ });
expect(botRouteForOwnedSession([bot], 's-main')).toBe('/bots/bot%2Fa');
expect(botRouteForOwnedSession([bot], 's-telegram')).toBe(
'/bots/bot%2Fa/session/s-telegram',
);
+ expect(botRouteForOwnedSession([bot], 's-old')).toBe('/bots/bot%2Fa/history/s-old');
+ expect(botRouteForOwnedSession([bot], 's-task')).toBe('/cc-agent/s-task');
+ expect(botRouteForOwnedSession([bot], 's-worker')).toBe('/cc-agent/s-worker');
+ expect(botRouteForOwnedSession([bot], 's-lane')).toBeNull();
expect(botRouteForOwnedSession([bot], 'not-owned')).toBeNull();
});
});
@@ -111,11 +125,11 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
it('启动后从未进过伙伴页时先加载投影,再回伙伴页', async () => {
const { deps: d, loadProfiles } = deps({ loaded: [profile()] });
- await expect(resolveBotRouteForSessionEntry('s-old', d)).resolves.toBe('/bots/bot-a/session/s-old');
+ await expect(resolveBotRouteForSessionEntry('s-old', d)).resolves.toBe('/bots/bot-a/history/s-old');
expect(loadProfiles).toHaveBeenCalledWith(true);
});
- it('投影已加载后新委派出去的任务(行上仍是 desktop)也会重读投影,回到接手伙伴', async () => {
+ it('投影已加载后新委派出去的任务(行上仍是 desktop)也会重读投影,打开普通任务页', async () => {
const stale = profile();
const delegated = profile({
id: 'bot-b',
@@ -127,7 +141,7 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
});
const { deps: d, loadProfiles } = deps({ current: [stale], loaded: [stale, delegated] });
await expect(resolveBotRouteForSessionEntry('s-delegated', d)).resolves.toBe(
- '/bots/bot-b/session/s-delegated',
+ '/cc-agent/s-delegated',
);
expect(loadProfiles).toHaveBeenCalledWith(true);
});
@@ -162,6 +176,21 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
expect(isLatest()).toBe(false);
});
+ it('后台任务走普通任务入口,保留消息锚点与灵动岛上报', async () => {
+ const openBotRoute = vi.fn();
+ const openOrdinary = vi.fn();
+ const open = createSessionEntryNavigator({
+ resolveBotRoute: async () => '/cc-agent/s-task',
+ openBotRoute,
+ openOrdinary,
+ });
+ open('s-task', 'message-9');
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(openBotRoute).not.toHaveBeenCalled();
+ expect(openOrdinary).toHaveBeenCalledWith('s-task', 'message-9', expect.any(Function));
+ });
+
it('加载投影失败时退回普通任务路由,不吞掉这次点击', async () => {
const d = {
readProfiles: () => [],
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
index 56e1c37b62..43eaf848d4 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
@@ -9,10 +9,10 @@ import {
looksGeneratedDirName,
countUnjudgedCandidates,
groupWorkbenchTiles,
+ summarizeWorkbenchGroups,
tierWorkbenchProjectOptions,
workbenchGroupHasFollowUp,
workbenchTileGroup,
- workbenchItemNeedsLocalReference,
type WorkbenchProjectOption,
type WorkbenchDelegationInput,
} from '../botWorkbenchProjection';
@@ -97,7 +97,7 @@ describe('buildWorkbenchTiles', () => {
delegations: [delegation('bg-queued', 'queued')],
activity: new Map([
['running', { phase: 'running', startedAtMs: 500, currentActionSummary: '导出 xhdpi 尺寸' }],
- ['asking', { phase: 'needs-interaction' }],
+ ['asking', { phase: 'needs-interaction', interactionKind: 'permission', currentActionSummary: '删掉旧迁移文件 007?' }],
]),
});
const byId = new Map(tiles.map((tile) => [tile.id, tile]));
@@ -106,7 +106,10 @@ describe('buildWorkbenchTiles', () => {
startedAtMs: 500,
line: { kind: 'action', text: '导出 xhdpi 尺寸' },
});
- expect(byId.get('asking')).toMatchObject({ state: 'waiting', line: { kind: 'waiting' } });
+ expect(byId.get('asking')).toMatchObject({
+ state: 'waiting',
+ line: { kind: 'waiting', interaction: 'permission', text: '删掉旧迁移文件 007?' },
+ });
expect(byId.get('bg-queued')).toMatchObject({ state: 'queued', origin: 'delegated' });
});
@@ -415,6 +418,50 @@ describe('groupWorkbenchTiles', () => {
expect([groupOf.get('queued-bg'), groupOf.get('failed-bg'), groupOf.get('finished-bg')]).toEqual(['todo', 'waiting', 'done']);
});
+ it('puts archived responsible tasks at the bottom of done, never offering 跟进', () => {
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ responsibleSessionIds: ['idle', 'old-judged', 'old-plain', 'not-mine'],
+ sessions: [session('idle', { updatedAt: '2026-09-01T00:00:00.000Z', userSendAt: '2026-09-01T00:00:00.000Z' })],
+ archivedSessions: [
+ session('old-plain', { status: 'archived', updatedAt: '2026-10-01T05:00:00.000Z', userSendAt: '2026-10-01T05:00:00.000Z' }),
+ session('old-judged', { status: 'archived', title: '原始', updatedAt: '2026-10-01T04:00:00.000Z' }),
+ session('not-mine-either', { status: 'archived' }),
+ session('active-row', { status: 'active' }),
+ ],
+ judgments: { 'old-judged': judgment('unfinished', '补描边') },
+ });
+ const archived = tiles.filter((tile) => tile.type === 'session' && tile.archived);
+ expect(archived.map((tile) => tile.id).sort()).toEqual(['old-judged', 'old-plain']);
+ expect(archived.find((tile) => tile.id === 'old-judged')).toMatchObject({
+ title: '补描边', state: 'done', verdict: null, next: null,
+ });
+ expect(archived.every((tile) => workbenchTileGroup(tile) === 'done')).toBe(true);
+ const groups = groupWorkbenchTiles(tiles);
+ expect(groups.map((group) => group.key)).toEqual(['done']);
+ const done = groups[0]!;
+ // 较新的归档也排在未归档的做完条目之后。
+ expect(done.tiles.map((tile) => tile.id)).toEqual(['idle']);
+ expect(done.archivedTiles.map((tile) => tile.id)).toEqual(['old-plain', 'old-judged']);
+ expect(done).toMatchObject({ total: 3, hiddenCount: 0, defaultCollapsed: true });
+ expect(workbenchGroupHasFollowUp(done.key)).toBe(false);
+ });
+
+ it('shows a done group made only of archived tasks', () => {
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ responsibleSessionIds: ['old'],
+ sessions: [],
+ archivedSessions: [session('old', { status: 'archived' })],
+ });
+ expect(groupWorkbenchTiles(tiles)).toMatchObject([{ key: 'done', tiles: [], total: 1 }]);
+ });
+
+ it('summarizes the open groups for the line above the list', () => {
+ expect(summarizeWorkbenchGroups(groupWorkbenchTiles(fixture()))).toEqual({ waiting: 3, running: 2, todo: 4 });
+ expect(summarizeWorkbenchGroups([])).toEqual({ waiting: 0, running: 0, todo: 0 });
+ });
+
it('leaves empty groups out', () => {
const tiles = buildWorkbenchTiles({
...base,
@@ -578,7 +625,7 @@ describe('project picker filtering and tiers', () => {
});
});
-it('retains an entrusted legacy local reference entrance until equivalent migration', () => {
+it('lists PR / issue / idea entries under to-do whatever their reference is', () => {
const tiles = buildWorkbenchTiles({
...base,
projectDirs: [CINDY],
@@ -610,7 +657,10 @@ it('retains an entrusted legacy local reference entrance until equivalent migrat
},
},
});
- const kept = tiles.filter((tile) => workbenchItemNeedsLocalReference(tile, [CINDY], false));
- expect(kept.map((tile) => tile.id)).toEqual(['idea:local']);
- expect(workbenchItemNeedsLocalReference(kept[0], [], false)).toBe(false);
+ // 参考是什么都不影响上列表:https 交给系统浏览器,本地路径在详情里打开前再校验。
+ expect(tiles.map((tile) => [tile.id, workbenchTileGroup(tile)]).sort()).toEqual([
+ ['idea:local', 'todo'],
+ ['idea:outside', 'todo'],
+ ['idea:web', 'todo'],
+ ]);
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/WorkbenchSessionList.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionActions.test.tsx
similarity index 53%
rename from apps/desktop/src/renderer/features/bots/__tests__/WorkbenchSessionList.test.tsx
rename to apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionActions.test.tsx
index da5d6a46a0..bbb40af715 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/WorkbenchSessionList.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionActions.test.tsx
@@ -1,7 +1,8 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { WorkbenchSessionList } from '../WorkbenchSessionList';
+import { useWorkbenchSessionActions } from '../useWorkbenchSessionActions';
+
const m = vi.hoisted(() => ({
run: vi.fn(),
unarchive: vi.fn(),
@@ -10,34 +11,20 @@ const m = vi.hoisted(() => ({
preflight: vi.fn(),
close: vi.fn(),
binding: vi.fn(),
+ patchMeta: vi.fn(),
running: new Set<string>(),
attached: new Set<string>(),
changed: vi.fn(),
warning: vi.fn(),
+ error: vi.fn(),
}));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (s: string) => s }) }));
vi.mock('react-router-dom', () => ({ useNavigate: () => m.navigate }));
-vi.mock('@/features/cc-agent/sidebar/SessionCard', () => ({
- SessionCard: (p: any) => (
- <div data-testid="native-row" data-variant={p.variant} data-status={p.session.status}>
- <button onClick={() => p.onClick(p.session.id)}>open</button>
- <button onClick={() => p.onAction(p.session.id, 'unarchive')}>restore</button>
- <button onClick={() => p.onAction(p.session.id, 'archive', 'shared')}>archive</button>
- </div>
- ),
-}));
vi.mock('@/features/cc-agent/hooks/useSessionLifecycleActions', () => ({
useSessionLifecycleActions: () => ({ runSessionAction: m.run, unarchiveSession: m.unarchive }),
}));
-vi.mock('@/features/cc-agent/hooks/useSessionDisplayRunningState', () => ({
- useSessionDisplayRunningState: () => ({ displayRunningSessionIds: m.running }),
-}));
vi.mock('@/hooks/useSessionRunningStatus', () => ({
- useSessionRunningStatus: () => ({
- runningSessionIds: m.running,
- notifications: new Set(),
- clearNotification: vi.fn(),
- }),
+ useSessionRunningStatus: () => ({ runningSessionIds: m.running, clearNotification: vi.fn() }),
}));
vi.mock('@/hooks/useAttachedSessionIds', () => ({ useAttachedSessionIds: () => m.attached }));
vi.mock('@/components/ui/confirm-dialog-provider', () => ({
@@ -48,18 +35,25 @@ vi.mock('@/lib/orcaSessionIdentity', () => ({
}));
vi.mock('@/lib/worktreeRemovalWarning', () => ({ resolveWorktreeRemovalPreflight: m.preflight }));
vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: { patchLocal: vi.fn() } }));
-vi.mock('@/lib/sessionService', () => ({ patchMeta: vi.fn(), update: vi.fn() }));
+vi.mock('@/lib/sessionService', () => ({ patchMeta: m.patchMeta }));
vi.mock('@/features/cc-agent/hooks/helpers/sidebarFilterCore', () => ({
persistManualPinnedOrder: vi.fn(),
}));
-vi.mock('@/lib/toast', () => ({ toast: { warning: m.warning, error: vi.fn() } }));
-const row = {
+vi.mock('@/lib/toast', () => ({ toast: { warning: m.warning, error: m.error } }));
+
+const archivedRow = {
id: 'original',
title: 'Original',
status: 'archived',
agentKind: 'codex',
workingDir: '/project',
} as any;
+const activeRow = { ...archivedRow, id: 'live', status: 'active', pinnedAt: null } as any;
+
+function setup(rows = [archivedRow, activeRow]) {
+ return renderHook(() => useWorkbenchSessionActions(rows, m.changed)).result;
+}
+
beforeEach(() => {
vi.clearAllMocks();
m.running = new Set();
@@ -68,45 +62,77 @@ beforeEach(() => {
m.preflight.mockResolvedValue('clean');
m.close.mockResolvedValue({ closed: ['shared'] });
m.binding.mockResolvedValue({ attached: false });
+ m.patchMeta.mockResolvedValue(undefined);
Object.defineProperty(window, 'electronAPI', {
configurable: true,
value: { binding: { resolveSession: m.binding }, sharedTask: { account: m.close } },
});
});
afterEach(cleanup);
-it('opens the original archived session through the native row without restoring it', async () => {
- render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);
- expect(screen.getByTestId('native-row').getAttribute('data-variant')).toBe('list');
- fireEvent.click(screen.getByText('open'));
+
+it('opens the original archived session in the task page without restoring it', async () => {
+ const result = setup();
+ act(() => result.current.open('original'));
await waitFor(() => expect(m.navigate).toHaveBeenCalledWith('/cc-agent/original'));
expect(m.unarchive).not.toHaveBeenCalled();
expect(m.run).not.toHaveBeenCalled();
});
+
it('restores only through the explicit existing lifecycle action', async () => {
- render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);
- fireEvent.click(screen.getByText('restore'));
- await waitFor(() => expect(m.unarchive).toHaveBeenCalledWith('original'));
+ const result = setup();
+ await act(() => result.current.action('original', 'unarchive'));
+ expect(m.unarchive).toHaveBeenCalledWith('original');
+ expect(m.changed).toHaveBeenCalled();
});
+
it.each(['running', 'attached'] as const)('retains the %s archive guard', async (kind) => {
- m[kind].add('original');
- render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);
- fireEvent.click(screen.getByText('archive'));
- await waitFor(() => expect(m.warning).toHaveBeenCalled());
+ m[kind].add('live');
+ const result = setup();
+ await act(() => result.current.action('live', 'archive'));
+ expect(m.warning).toHaveBeenCalled();
expect(m.run).not.toHaveBeenCalled();
});
+
+it('archives a clean task without asking and refreshes the list', async () => {
+ const result = setup();
+ await act(() => result.current.action('live', 'archive'));
+ expect(m.confirm).not.toHaveBeenCalled();
+ expect(m.run).toHaveBeenCalledWith('live', 'archive', { activeSessionId: null });
+ expect(m.changed).toHaveBeenCalled();
+});
+
+it('always confirms delete, and cancelling deletes nothing', async () => {
+ m.confirm.mockResolvedValue(false);
+ const result = setup();
+ await act(() => result.current.action('live', 'delete'));
+ expect(m.confirm).toHaveBeenCalled();
+ expect(m.run).not.toHaveBeenCalled();
+});
+
it('cancelling unknown worktree confirmation does not close sharing or archive', async () => {
m.preflight.mockResolvedValue('unknown');
m.confirm.mockResolvedValue(false);
- render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);
- fireEvent.click(screen.getByText('archive'));
- await waitFor(() => expect(m.confirm).toHaveBeenCalled());
+ const result = setup();
+ await act(() => result.current.action('live', 'archive', 'shared'));
+ expect(m.confirm).toHaveBeenCalled();
expect(m.close).not.toHaveBeenCalled();
expect(m.run).not.toHaveBeenCalled();
});
+
it('does not archive a shared task when existing shared close fails', async () => {
m.close.mockResolvedValue({ closed: [] });
- render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);
- fireEvent.click(screen.getByText('archive'));
- await waitFor(() => expect(m.close).toHaveBeenCalled());
+ const result = setup();
+ await act(() => result.current.action('live', 'archive', 'shared'));
+ expect(m.close).toHaveBeenCalled();
expect(m.run).not.toHaveBeenCalled();
+ expect(m.error).toHaveBeenCalled();
+});
+
+it('pins and unpins through the shared session metadata path', async () => {
+ const result = setup();
+ await act(() => result.current.togglePin('live'));
+ expect(m.patchMeta).toHaveBeenCalledWith('live', { pinnedAt: expect.any(String) });
+ const pinned = setup([{ ...activeRow, pinnedAt: '2026-10-01T00:00:00.000Z' }]);
+ await act(() => pinned.current.togglePin('live'));
+ expect(m.patchMeta).toHaveBeenLastCalledWith('live', { pinnedAt: null });
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/workingStatusPolish.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/workingStatusPolish.test.tsx
index 60a8f73fe1..d36f109ff6 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/workingStatusPolish.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/workingStatusPolish.test.tsx
@@ -4,12 +4,11 @@ import { act, cleanup, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import { BotGenerationLabel } from '../BotGenerationLabel';
-import { BotWorkingStatus } from '../BotWorkingStatus';
-import type { ChatMessage } from '@/lib/makerChatStore';
+// The composer-top bot status line was retired (bot chats now show the normal
+// work group and RunningStatusBar). Sidebar/group rows keep the polished copy.
const request = vi.fn();
-const props = { sessionId: 'test', visible: true, status: 'Thinking', startedAt: 1000, messages: [] as ChatMessage[], foregroundRunning: true, backgroundWorkActive: false, avatar: null };
-const tool = (name: string, input: unknown): ChatMessage => ({ clientId: 'tool', role: 'tool_use', content: '', toolName: name, toolInput: input });
+const props = { sessionId: 'test', startedAt: 1000 };
beforeEach(async () => {
await i18n.changeLanguage('zh-CN');
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });
@@ -23,10 +22,10 @@ const tick = () => act(() => { vi.advanceTimersByTime(1150); });
it('displays specific default immediately, then model copy with the existing cadence and opacity', async () => {
let resolve!: (value: { text: string }) => void;
request.mockReturnValue(new Promise((r) => { resolve = r; }));
- render(<BotWorkingStatus {...props} messages={[tool('bot_memory', { action: 'read' })]} />);
- expect(screen.getByRole('status').textContent).toBe('正在读取记忆…');
+ render(<BotGenerationLabel {...props} phase="reading-memory" />);
+ expect(screen.getByText('正在读取记忆…')).toBeTruthy();
await act(async () => resolve({ text: '翻翻之前记下的事…' }));
- expect(screen.getByRole('status').textContent).toBe('正在读取记忆…');
+ expect(screen.getByText('正在读取记忆…')).toBeTruthy();
act(() => { vi.advanceTimersByTime(1000); });
expect(screen.getByText('正在读取记忆…').style.opacity).toBe('0');
act(() => { vi.advanceTimersByTime(150); });
@@ -34,93 +33,37 @@ it('displays specific default immediately, then model copy with the existing cad
expect(request).toHaveBeenCalledWith({ sessionId: 'test', phase: 'reading-memory', locale: 'zh-CN' });
});
-it('changes matters, keeps defaults between them, and discards obsolete or terminal model results', async () => {
+it('discards obsolete model results after the phase changes', async () => {
const resolves: Array<(v: { text: string | null }) => void> = [];
request.mockImplementation(() => new Promise((r) => resolves.push(r)));
- const memory = tool('bot_memory', { action: 'write', body: 'PRIVATE' });
- const file = tool('read', { path: 'PRIVATE' });
- const view = render(<BotWorkingStatus {...props} messages={[memory]} />);
- view.rerender(<BotWorkingStatus {...props} messages={[file]} />);
+ const view = render(<BotGenerationLabel {...props} phase="saving-memory" />);
+ view.rerender(<BotGenerationLabel {...props} phase="reading-file" />);
await act(async () => resolves[0]({ text: '把这件事记下来…' }));
tick();
- expect(screen.getByRole('status').textContent).toBe('正在读取文件…');
+ expect(screen.getByText('正在读取文件…')).toBeTruthy();
+ expect(screen.queryByText('把这件事记下来…')).toBeNull();
await act(async () => resolves[1]({ text: '翻翻文件里的内容…' }));
tick();
- expect(screen.getByRole('status').textContent).toBe('翻翻文件里的内容…');
- view.rerender(<BotWorkingStatus {...props} />);
- tick();
- expect(screen.getByRole('status').textContent).toBe('正在思考…');
- view.rerender(<BotWorkingStatus {...props} messages={[memory]} />);
- view.rerender(<BotWorkingStatus {...props} visible={false} />);
- await act(async () => resolves[2]({ text: '迟到的记忆文案' }));
- tick();
- expect(screen.queryByRole('status')).toBeNull();
+ expect(screen.getByText('翻翻文件里的内容…')).toBeTruthy();
});
-it('keeps specific default on model failure and avoids requests without a public subject or local active turn', async () => {
+it('keeps the specific default on model failure and avoids requests without a session', async () => {
request.mockRejectedValue(new Error('unavailable'));
- const messages = [tool('read', { path: 'PRIVATE' })];
- const view = render(<BotWorkingStatus {...props} messages={messages} />);
- await act(async () => {});
- tick();
- expect(screen.getByRole('status').textContent).toBe('正在读取文件…');
- view.rerender(<BotWorkingStatus {...props} sessionId={undefined} messages={messages} />);
- view.rerender(<BotWorkingStatus {...props} foregroundRunning={false} backgroundWorkActive messages={messages} />);
- view.rerender(<BotWorkingStatus {...props} status="Waiting on input" />);
- view.rerender(<BotWorkingStatus {...props} />);
- expect(request).toHaveBeenCalledTimes(1);
-});
-
-it('keeps the memory subject while consuming the returned feedback', async () => {
- request.mockResolvedValue({ text: null });
- render(<BotWorkingStatus {...props} messages={[
- { ...tool('bot_memory', { action: 'read', filename: 'PRIVATE' }), toolUseId: 't' },
- { clientId: 'r', role: 'tool_result', content: 'PRIVATE', toolUseId: 't' },
- { clientId: 'th', role: 'thinking', content: 'PRIVATE', isStreaming: true },
- ]} />);
- expect(screen.getByRole('status').textContent).toBe('正在核对记忆…');
- expect(request).toHaveBeenCalledWith({ sessionId: 'test', phase: 'reviewing-memory', locale: 'zh-CN' });
- await act(async () => {});
-});
-
-it('keeps foreground workflow copy specific, then falls back only when background work remains', async () => {
- request.mockResolvedValue({ text: '翻翻之前记下的事…' });
- const messages = [tool('bot_memory', { action: 'read' })];
- const view = render(<BotWorkingStatus {...props} backgroundWorkActive messages={messages} />);
- expect(screen.getByRole('status').textContent).toBe('正在读取记忆…');
+ const view = render(<BotGenerationLabel {...props} phase="reading-file" />);
await act(async () => {});
tick();
- expect(screen.getByRole('status').textContent).toBe('翻翻之前记下的事…');
+ expect(screen.getByText('正在读取文件…')).toBeTruthy();
+ view.rerender(<BotGenerationLabel {...props} sessionId={undefined} phase="reading-file" />);
expect(request).toHaveBeenCalledTimes(1);
- view.rerender(<BotWorkingStatus {...props} backgroundWorkActive foregroundRunning={false} messages={messages} />);
- tick();
- expect(screen.getByRole('status').textContent).toBe('正在处理…');
- expect(request).toHaveBeenCalledTimes(1);
- view.rerender(<BotWorkingStatus {...props} visible={false} foregroundRunning={false} />);
- expect(screen.queryByRole('status')).toBeNull();
});
-it.each([
- ['delete', 'deleting-memory', '正在删除记忆…'],
- ['review', 'reviewing-memory', '正在核对记忆…'],
- ['consolidate', 'organizing-memory', '正在整理记忆…'],
-] as const)('keeps an accurate memory %s fallback and requests polishing', async (action, phase, text) => {
- request.mockRejectedValue(new Error('unavailable'));
- render(<BotWorkingStatus {...props} messages={[tool('bot_memory', { action })]} />);
- expect(screen.getByRole('status').textContent).toBe(text);
- expect(request).toHaveBeenCalledWith({ sessionId: 'test', phase, locale: 'zh-CN' });
- await act(async () => {});
- tick();
- expect(screen.getByRole('status').textContent).toBe(text);
-});
-
-it('remote chat gets polished copy from the host resource, never a local model request', async () => {
+it('remote rows get polished copy from the host resource, never a local model request', async () => {
const invoke = vi.fn().mockResolvedValue({ blocks: [{ id: 'working', fallbackMarkdown: '翻翻文件里的内容…' }] });
Object.assign(window.electronAPI, { deviceLink: { invoke } });
- render(<BotWorkingStatus {...props} remote={{ deviceId: 'host', botId: 'writer' }} messages={[tool('read', { path: 'PRIVATE' })]} />);
+ render(<BotGenerationLabel {...props} phase="reading-file" remote={{ deviceId: 'host', botId: 'writer' }} />);
await act(async () => {});
tick();
- expect(screen.getByRole('status').textContent).toBe('翻翻文件里的内容…');
+ expect(screen.getByText('翻翻文件里的内容…')).toBeTruthy();
expect(request).not.toHaveBeenCalled();
expect(invoke).toHaveBeenCalledWith('host', expect.any(String), [{
client: { protocolVersion: 1, primitives: ['status'], locale: 'zh-CN' },
@@ -128,32 +71,12 @@ it('remote chat gets polished copy from the host resource, never a local model r
}]);
});
-
-it.each(['Compacting...', 'Compacting context…'])('localizes %s before old live blocks and clears late copy through stop/resume', async (status) => {
- let resolve!: (value: { text: string }) => void;
- request.mockReturnValue(new Promise(r => { resolve = r; }));
- const messages = [tool('bot_memory', { action: 'read' })];
- const view = render(<BotWorkingStatus {...props} messages={messages} />);
- view.rerender(<BotWorkingStatus {...props} status={status} messages={messages} />);
- await act(async () => resolve({ text: '翻翻之前记下的事…' }));
- tick();
- expect(screen.getByRole('status').textContent).toBe('正在整理对话…');
- expect(request).toHaveBeenCalledTimes(1);
- view.rerender(<BotWorkingStatus {...props} />);
- tick();
- expect(screen.getByRole('status').textContent).toBe('正在思考…');
- view.rerender(<BotWorkingStatus {...props} visible={false} />);
- expect(screen.queryByRole('status')).toBeNull();
-});
-
-
it.each([
['en', 'Organizing the conversation…'], ['zh-CN', '正在整理对话…'],
['zh-TW', '正在整理對話…'], ['ja', '会話を整理しています…'], ['ko', '대화를 정리하는 중…'],
-])('keeps the list and composer compaction caption identical in %s', async (locale, caption) => {
+])('localizes the compaction caption in %s without a model request', async (locale, caption) => {
await i18n.changeLanguage(locale);
- render(<><BotGenerationLabel sessionId="test" phase="compacting" startedAt={1000}/>
- <BotWorkingStatus {...props} status="Compacting context…" /></>);
- expect(screen.getAllByText(caption)).toHaveLength(2);
+ render(<BotGenerationLabel sessionId="test" phase="compacting" startedAt={1000} />);
+ expect(screen.getByText(caption)).toBeTruthy();
expect(request).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotWorkingStatus.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/workingStatusText.test.tsx
similarity index 68%
rename from apps/desktop/src/renderer/features/bots/__tests__/BotWorkingStatus.test.tsx
rename to apps/desktop/src/renderer/features/bots/__tests__/workingStatusText.test.tsx
index 8a84f541a3..70c0f61f82 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotWorkingStatus.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/workingStatusText.test.tsx
@@ -4,7 +4,6 @@ import { act, cleanup, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import type { ChatMessage as Message } from '@/lib/makerChatStore';
-import { BotWorkingStatus } from '../BotWorkingStatus';
import { WorkingStatusText, WORKING_STATUS_MIN_INTERVAL_MS } from '@/features/cc-agent/WorkingStatusText';
import { localizePlainAgentStatus } from '@/features/cc-agent/lib/localizeAgentStatus';
@@ -14,7 +13,6 @@ const startedAt = Date.parse('2026-09-17T00:00:00Z');
const message = (role: Message['role'], fields: Partial<Message> = {}): Message => ({
clientId: role, role, content: '', createdAt: new Date(startedAt + 10).toISOString(), ...fields,
});
-const props = { visible: true, status: 'Working…', messages: [] as Message[], startedAt, foregroundRunning: true, backgroundWorkActive: false, avatar: null };
const advance = (ms: number) => act(() => { vi.advanceTimersByTime(ms); });
beforeEach(async () => {
@@ -27,41 +25,7 @@ beforeEach(async () => {
});
afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.useRealTimers(); });
-describe('Bot working lifecycle', () => {
- it('keeps the indicator through thinking → text → memory tool → thinking → reply → done', () => {
- const thinking = message('thinking', { isStreaming: true });
- const text = message('assistant', { content: '记住了…', isStreaming: true });
- const tool = message('tool_use', { toolName: 'mcp__cindy_memory__call_tool' });
- const view = render(<BotWorkingStatus {...props} messages={[thinking]} />);
- expect(screen.getByRole('status').textContent).toBe('正在思考…');
- const change = (messages: Message[], expected: string) => {
- view.rerender(<BotWorkingStatus {...props} messages={messages} />);
- expect(screen.getByRole('status')).toBeTruthy();
- advance(WORKING_STATUS_MIN_INTERVAL_MS);
- advance(150);
- expect(screen.getByRole('status').textContent).toBe(expected);
- };
- change([text], '正在回复…');
- change([{ ...text, isStreaming: false }, tool], '正在处理…');
- change([text, tool, message('tool_result'), thinking], '正在思考…');
- change([text, tool, message('tool_result'), { ...thinking, isStreaming: false }, text], '正在回复…');
- view.rerender(<BotWorkingStatus {...props} visible={false} status="Done" />);
- expect(screen.queryByRole('status')).toBeNull();
- advance(5000);
- expect(screen.queryByRole('status')).toBeNull();
- });
-
- it.each(['Done', 'Error', 'Stopped'])('immediately clears %s even during fade-out', (status) => {
- const view = render(<BotWorkingStatus {...props} status="Thinking…" />);
- view.rerender(<BotWorkingStatus {...props} />);
- advance(1000);
- view.rerender(<BotWorkingStatus {...props} visible={false} status={status} />);
- expect(screen.queryByRole('status')).toBeNull();
- advance(2000);
- view.rerender(<BotWorkingStatus {...props} startedAt={startedAt + 5000} status="Thinking…" />);
- expect(screen.getByRole('status').textContent).toBe('正在思考…');
- });
-
+describe('plain agent status copy', () => {
it('ignores old turns, hidden subagent output, system cards and completed text', () => {
const messages = [
message('assistant', { content: '旧正文', isStreaming: true, createdAt: new Date(startedAt - 1000).toISOString() }),
@@ -86,11 +50,9 @@ describe('Bot working lifecycle', () => {
], startedAt, i18n.t)).toBe('正在回复…');
});
- it('preserves pending-input semantics and background work after the turn', () => {
+ it('preserves pending-input semantics', () => {
expect(localizePlainAgentStatus('Waiting on input', [], startedAt, i18n.t))
.toBe(i18n.t('ccAgent.sidebar.card.awaitingQuestion'));
- render(<BotWorkingStatus {...props} status="Done" foregroundRunning={false} backgroundWorkActive />);
- expect(screen.getByRole('status').textContent).toBe('正在处理…');
});
});
diff --git a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts b/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts
index 65753c38f7..03d53cda67 100644
--- a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts
+++ b/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts
@@ -11,6 +11,8 @@ import {
type WorkGroupChildItem,
} from '@/components/chat/messageWorkGroups';
+type WorkGroupItem = Extract<RenderItem, { type: 'work_group' }>;
+
function isProse(item: RenderItem): item is MessageRenderItem {
return item.type === 'message' && item.message.role === 'assistant'
&& !item.message.systemCardType;
@@ -20,16 +22,6 @@ function hasAttachments(message: ChatMessage): boolean {
return Boolean(message.images?.length || message.files?.length);
}
-/** Read already loaded delivery/interaction children; technical history stays persisted. */
-function publicItems(items: readonly RenderItem[]): RenderItem[] {
- return items.flatMap((item): RenderItem[] => {
- if (item.type === 'message' && item.message.role === 'thinking') return [];
- if (item.type !== 'work_group') return [item];
- const children = publicItems(item.children) as WorkGroupChildItem[];
- return children;
- });
-}
-
function expandWorkGroups(items: readonly RenderItem[]): RenderItem[] {
return items.flatMap((item): RenderItem[] =>
item.type === 'work_group' ? expandWorkGroups(item.children) : [item]);
@@ -38,8 +30,10 @@ function expandWorkGroups(items: readonly RenderItem[]): RenderItem[] {
/** A presentation-only projection. Never mutate messages or infer intent from prose.
* isFinal from the adapters closes a text block, not a turn (Pi/Claude can call
* another tool afterwards). Reuse the normal work-group turn seal, showing provider-marked final prose immediately while keeping
- * unclassified intermediate prose hidden. The composer owns live action
- * feedback. On stop/error or old history without a seal, expose the last useful
+ * unclassified top-level intermediate prose hidden. Work groups (live activity and
+ * the completed "worked Xs" summary), running agent tasks and workflow cards pass
+ * through untouched so the bot chat shows its work exactly like a normal session.
+ * On stop/error or old history without a seal, expose the last useful
* prose so an answer or plain-text question cannot disappear permanently.
*/
export function simplifyBotRenderItems(
@@ -47,9 +41,9 @@ export function simplifyBotRenderItems(
isStreaming: boolean,
visibleGeneratedFileKeys?: ReadonlySet<string>,
): RenderItem[] {
- // Preserve the shared grouping's history-window boundary before unwrapping
- // groups or removing thinking (both can carry timestamp anchors). Only the
- // final window is active; earlier legacy answers retain their own fallback.
+ // Preserve the shared grouping's history-window boundary before filtering
+ // prose (work groups carry timestamp anchors). Only the final window is
+ // active; earlier legacy answers retain their own fallback.
const result: RenderItem[] = [];
let window: RenderItem[] = [];
let previousEnd: number | null = null;
@@ -88,6 +82,71 @@ export function simplifyBotRenderItems(
return [...visible, ...fallbackReceipts];
}
+/** Empty avatar rows never make a fold on their own; unloaded history still does. */
+function hasWorkContent(item: RenderItem): boolean {
+ if (item.type === 'work_group') return Boolean(item.deferred) || item.children.some(hasWorkContent);
+ if (isProse(item)) return Boolean(item.message.content.trim()) || hasAttachments(item.message);
+ return true;
+}
+
+/**
+ * Work groups pass through like a normal session, except that a reply the bot
+ * deliberately addressed to the user (an earlier background-wake seal, provider
+ * final, group delivery or explicit delivery) never hides inside the fold. The
+ * group is split around such replies; inner activity groups keep their keys.
+ */
+function liftRepliesFromWorkGroup(
+ group: WorkGroupItem,
+ isReply: (message: ChatMessage) => boolean,
+): RenderItem[] {
+ if (!group.children.some((child) => isProse(child) && isReply(child.message))) return [group];
+ const out: RenderItem[] = [];
+ let pending: WorkGroupChildItem[] = [];
+ let chunk = 0;
+ let previousReplyEnd: number | null = null;
+ const groupEnd = group.startedAtMs !== undefined && group.durationMs !== undefined
+ ? group.startedAtMs + group.durationMs : null;
+ const flush = (nextReply: MessageRenderItem | null) => {
+ if (pending.length === 0) return;
+ if (pending.length === 1 && pending[0].type === 'work_group') {
+ out.push(pending[0]);
+ } else {
+ const starts = pending.map(renderItemStartMs).filter((ms): ms is number => ms !== null);
+ const ends = pending.map(renderItemEndMs).filter((ms): ms is number => ms !== null);
+ const start = chunk === 0
+ ? group.startedAtMs ?? (starts.length ? Math.min(...starts) : null)
+ : previousReplyEnd ?? (starts.length ? Math.min(...starts) : null);
+ const end = nextReply
+ ? renderItemStartMs(nextReply)
+ : groupEnd ?? (ends.length ? Math.max(...ends) : null);
+ const durationMs = start !== null && end !== null && end >= start ? end - start : undefined;
+ out.push({
+ type: 'work_group',
+ // The first chunk keeps the original key so its expansion memory survives.
+ key: chunk === 0 ? group.key : `${group.key}~${pending[0].key}`,
+ children: pending,
+ isStreaming: group.isStreaming,
+ ...(durationMs !== undefined ? { durationMs } : {}),
+ ...(start !== null ? { startedAtMs: start } : {}),
+ ...(chunk === 0 && group.deferred ? { deferred: group.deferred } : {}),
+ });
+ }
+ chunk += 1;
+ pending = [];
+ };
+ for (const child of group.children) {
+ if (isProse(child) && isReply(child.message)) {
+ flush(child);
+ out.push(child);
+ previousReplyEnd = renderItemEndMs(child);
+ } else {
+ pending.push(child);
+ }
+ }
+ flush(null);
+ return out;
+}
+
function projectWindow(
items: readonly RenderItem[],
isStreaming: boolean,
@@ -108,6 +167,10 @@ function projectWindow(
sealedRun ||= isCompletedAssistantMessage(item.message);
if (sealedRun) sealedAnswers.add(item.message);
}
+ const isAddressedReply = (message: ChatMessage) => Boolean(message.content.trim())
+ && !(message.assistantPhase === 'commentary' && !message.explicitDelivery)
+ && (message.assistantPhase === 'final_answer' || Boolean(message.sourceGroup)
+ || Boolean(message.explicitDelivery) || isCompletedAssistantMessage(message) || sealedAnswers.has(message));
const result: RenderItem[] = [];
let turn: RenderItem[] = [];
const flushTurn = (active: boolean) => {
@@ -130,7 +193,10 @@ function projectWindow(
// Keep later explanatory text after a partial delivery on stop/error/history.
const fallbackProse = !active && lastProse > lastDelivery ? lastProse : -1;
turn.forEach((item, index) => {
- if (item.type === 'agent_plan' || item.type === 'turn_changes') return;
+ // Bots never produce change cards; keep them out like before. Thinking is
+ // always folded into a work group by the shared grouping, never top level.
+ if (item.type === 'turn_changes') return;
+ if (item.type === 'message' && item.message.role === 'thinking') return;
if (item.type === 'message' && item.message.isSyntheticTrigger) return;
if (isProse(item)) {
if (!item.message.content.trim() && !hasAttachments(item.message)) return;
@@ -141,16 +207,16 @@ function projectWindow(
return;
}
}
- if (item.type === 'tool_segment' || item.type === 'agent_task' || item.type === 'work_group') {
- return;
- }
- // Includes authorization, answered questions, errors and all delivery cards.
+ // Includes work groups, agent tasks, plans, authorization, answered
+ // questions, errors and all delivery cards.
result.push(item);
});
turn = [];
};
- for (const item of publicItems(items)) {
+ const lifted = items.flatMap((item) => item.type !== 'work_group' ? [item]
+ : hasWorkContent(item) ? liftRepliesFromWorkGroup(item, isAddressedReply) : []);
+ for (const item of lifted) {
if (item.type === 'message' && item.message.role === 'user'
&& item.message.delivery !== 'steer') {
flushTurn(false);
diff --git a/apps/desktop/src/renderer/features/bots/botGroupAttachments.ts b/apps/desktop/src/renderer/features/bots/botGroupAttachments.ts
index 520054822d..db4814eeb7 100644
--- a/apps/desktop/src/renderer/features/bots/botGroupAttachments.ts
+++ b/apps/desktop/src/renderer/features/bots/botGroupAttachments.ts
@@ -6,6 +6,7 @@
* base64,main 会拒收),而 main 的图片缓存并不按 scope 落盘——所以给每个群一个
* 稳定、不会与真实任务 id 撞上的 scope,同时用作输入框草稿键。
*/
+import type { JSONContent } from '@tiptap/core';
import { serializeAttachedFiles } from '@/lib/messageAttachmentPayload';
import type { AttachedFile } from '@/lib/fileTypes';
import type { BotGroupAttachment, BotGroupAttachmentInput } from '../../../shared/botGroupChat';
@@ -15,6 +16,43 @@ export function botGroupAttachmentScope(groupId: string): string {
return `bot-group:${groupId}`;
}
+/** Draft key of a 话题's reply box; text only (thread replies carry no attachments). */
+export function botGroupThreadDraftKey(groupId: string, rootId: string): string {
+ return `${botGroupAttachmentScope(groupId)}:thread:${rootId}`;
+}
+
+/**
+ * The group composer is a plain textarea, so its draft text is stored in the shared draft
+ * store as one paragraph per line — a document the store understands (draft presence, owner
+ * scoping) and that reads back to exactly the same text.
+ */
+export function botGroupDraftDoc(text: string): JSONContent {
+ return {
+ type: 'doc',
+ content: text.split('\n').map((line) => (line ? { type: 'paragraph', content: [{ type: 'text', text: line }] } : { type: 'paragraph' })),
+ };
+}
+
+export function botGroupDraftText(doc: JSONContent | null | undefined): string {
+ if (!doc) return '';
+ const textOf = (node: JSONContent): string =>
+ node.type === 'text' ? node.text ?? '' : node.type === 'hardBreak' ? '\n' : (node.content ?? []).map(textOf).join('');
+ return (doc.content ?? []).map(textOf).join('\n');
+}
+
+/** A tray file as the optimistic copy of a message shows it before main has it. */
+export function botGroupAttachmentPreview(file: AttachedFile): BotGroupAttachment {
+ return {
+ id: file.id,
+ name: file.name,
+ category: file.category,
+ mimeType: file.mimeType,
+ size: file.size,
+ url: file.url ?? null,
+ path: file.path || null,
+ };
+}
+
/** The tray's files in the shape `sendBotGroupMessage` takes. */
export function toBotGroupAttachmentInputs(files: readonly AttachedFile[]): BotGroupAttachmentInput[] {
return (serializeAttachedFiles(files) ?? []).map((file) => ({
diff --git a/apps/desktop/src/renderer/features/bots/botGroupStore.ts b/apps/desktop/src/renderer/features/bots/botGroupStore.ts
index 37581c9f28..516521dd1d 100644
--- a/apps/desktop/src/renderer/features/bots/botGroupStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botGroupStore.ts
@@ -3,9 +3,11 @@
*
* 权威数据在 main(当前账号本地库的 bot_groups / members / messages),这里只缓存
* `listBotGroups()` 的最新一份摘要,供统一侧栏与群设置抽屉读取。main 每次
- * 变更都会推 `onBotGroupChanged`,收到后整表重取;同一时刻只有一个请求在飞,期间
- * 再来的推送合并成一次补取。账号(data owner)切换时立即清空,旧账号的迟到响应
- * 一律丢弃(electron-security-and-process-boundaries §4–5:renderer 不持有真相)。
+ * 变更都会推 `onBotGroupChanged`,收到后整表重取(IPC 没有单群摘要读取):推送先攒
+ * 300ms 再读一次,一段对话里连发的推送只读一两次;同一时刻只有一个请求在飞,期间再来的
+ * 合并成一次补取;读回的摘要与当前一致时不通知订阅者,侧栏与角标不重绘。账号(data
+ * owner)切换时立即清空,旧账号的迟到响应一律丢弃(electron-security-and-process-boundaries
+ * §4–5:renderer 不持有真相)。
*/
import { useCallback, useSyncExternalStore } from 'react';
import { seedBotGroupReadState } from './botReadState';
@@ -38,7 +40,10 @@ let owner = getDataOwnerGeneration();
let generation = 0;
let inFlight: Promise<void> | null = null;
let refreshQueued = false;
+let pushTimer: ReturnType<typeof setTimeout> | null = null;
let syncUsers = 0;
+/** Pushes within this window collapse into one list read. */
+const PUSH_REFRESH_DELAY_MS = 300;
let unsubscribePush: (() => void) | null = null;
const listeners = new Set<() => void>();
@@ -62,9 +67,24 @@ function ensureOwner(): void {
generation += 1;
inFlight = null;
refreshQueued = false;
+ cancelPushRefresh();
snapshot = EMPTY_SNAPSHOT;
}
+function cancelPushRefresh(): void {
+ if (pushTimer !== null) clearTimeout(pushTimer);
+ pushTimer = null;
+}
+
+/** A push changed something: read the list once the burst has settled. */
+function schedulePushRefresh(): void {
+ if (pushTimer !== null) return;
+ pushTimer = setTimeout(() => {
+ pushTimer = null;
+ refreshBotGroups();
+ }, PUSH_REFRESH_DELAY_MS);
+}
+
function applySnapshot(next: BotGroupListSnapshot): void {
snapshot = next;
emit();
@@ -89,6 +109,8 @@ export function refreshBotGroups(): void {
const result = await api.listBotGroups();
if (!isCurrent()) return;
if (result.ok) seedBotGroupReadState(result.groups);
+ // An unchanged list keeps its snapshot: subscribers (sidebar, Dock badge) do not re-render.
+ if (result.ok && snapshot.loaded && JSON.stringify(result.groups) === JSON.stringify(snapshot.groups)) return;
// 失败时保留上一份列表:侧栏不因一次读失败把所有群清空。
applySnapshot(result.ok ? { groups: result.groups, loaded: true } : { ...snapshot, loaded: true });
} catch {
@@ -117,7 +139,7 @@ export function startBotGroupSync(): () => void {
if (api && typeof api.onBotGroupChanged === 'function') {
unsubscribePush = api.onBotGroupChanged((_payload, ownerStamp) => {
if (!isDataOwnerPushCurrent(ownerStamp)) return;
- refreshBotGroups();
+ schedulePushRefresh();
});
}
}
@@ -127,6 +149,7 @@ export function startBotGroupSync(): () => void {
if (syncUsers === 0) {
unsubscribePush?.();
unsubscribePush = null;
+ cancelPushRefresh();
}
};
}
@@ -204,6 +227,7 @@ export function resetBotGroupStoreForTests(): void {
generation += 1;
inFlight = null;
refreshQueued = false;
+ cancelPushRefresh();
owner = getDataOwnerGeneration();
snapshot = EMPTY_SNAPSHOT;
listeners.clear();
diff --git a/apps/desktop/src/renderer/features/bots/botReadState.ts b/apps/desktop/src/renderer/features/bots/botReadState.ts
index c524fe6539..d183aba3bc 100644
--- a/apps/desktop/src/renderer/features/bots/botReadState.ts
+++ b/apps/desktop/src/renderer/features/bots/botReadState.ts
@@ -146,7 +146,13 @@ export function resetBotReadStateForTests(): void {
/** Group replies use the same owner-scoped, monotonic local read positions. */
export const botGroupReadKey = (groupId: string) => `group:${groupId}`;
-type GroupReadSummary = Pick<BotGroupSummary, 'id' | 'lastReplyAt'> & Partial<Pick<BotGroupSummary, 'lastMessage'>>;
+type GroupReadSummary = Pick<BotGroupSummary, 'id' | 'lastReplyAt'> & Partial<Pick<BotGroupSummary, 'lastMessage'>> & {
+ /**
+ * ISO times of the group's latest (up to 99) messages from others — Bots and other humans,
+ * never the reader's own or notices — oldest first. Older hosts omit it.
+ */
+ incomingMessageTimes?: readonly string[];
+};
function latestGroupReplyAt(group: GroupReadSummary): number {
// Older hosts may omit lastReplyAt; other humans count just like companions.
@@ -155,9 +161,26 @@ function latestGroupReplyAt(group: GroupReadSummary): number {
last && last.authorKind !== 'system' && (last.authorKind === 'bot' || last.isSelf === false) ? last.createdAt : 0);
}
-export function isBotGroupUnread(group: GroupReadSummary): boolean {
+/**
+ * Messages from others after the local read mark: counted from `incomingMessageTimes` (so at
+ * most 99); a host without the list only says whether anything is new (1).
+ */
+export function botGroupUnreadCount(group: GroupReadSummary): number {
const readAt = getBotLastReadAt(botGroupReadKey(group.id));
- return readAt !== null && latestGroupReplyAt(group) > readAt;
+ if (readAt === null) return 0;
+ const latestUnread = latestGroupReplyAt(group) > readAt ? 1 : 0;
+ const times = group.incomingMessageTimes;
+ if (!Array.isArray(times)) return latestUnread;
+ let count = 0;
+ for (const time of times) {
+ const at = Date.parse(time);
+ if (Number.isFinite(at) && at > readAt) count += 1;
+ }
+ return Math.max(count, latestUnread);
+}
+
+export function isBotGroupUnread(group: GroupReadSummary): boolean {
+ return botGroupUnreadCount(group) > 0;
}
export function seedBotGroupReadState(groups: readonly GroupReadSummary[]): void {
const current = readStorage();
diff --git a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts b/apps/desktop/src/renderer/features/bots/botSessionOwners.ts
index cdb330b5c2..92efd24738 100644
--- a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts
+++ b/apps/desktop/src/renderer/features/bots/botSessionOwners.ts
@@ -28,9 +28,14 @@ export function findBotProfileForSession(
}
/**
- * Resolve the public Bot route for a notification or other session-only entry.
- * The stable main task stays on the short Bot route; child and historical tasks
- * retain their own session id so opening a notification never loses context.
+ * The one route for a Bot-owned session, shared by notifications, task cards and
+ * the main sidebar so every entry reaches the same page:
+ * - the stable main task → `/bots/:id`;
+ * - archived history → `/bots/:id/history/:sid`;
+ * - a background (delegation) task → `/cc-agent/:sid`, the ordinary task view it
+ * really is (diffs, model picker), never a Bot skin that cannot open it;
+ * - a hidden group-chat lane → null: it is not navigable on its own;
+ * - other Bot chats (e.g. channel tasks) → `/bots/:id/session/:sid`.
*/
export function botRouteForOwnedSession(
profiles: readonly BotProfile[],
@@ -38,12 +43,17 @@ export function botRouteForOwnedSession(
): string | null {
const bot = findBotProfileForSession(profiles, sessionId);
if (!bot) return null;
+ const projection = bot.sessions.find((session) => session.id === sessionId);
const canonicalSessionId = bot.sessions.find(
(session) => session.role === 'canonical' || session.kind === 'chat',
)?.id;
- return canonicalSessionId === sessionId
- ? `/bots/${encodeURIComponent(bot.id)}`
- : `/bots/${encodeURIComponent(bot.id)}/session/${encodeURIComponent(sessionId)}`;
+ const botId = encodeURIComponent(bot.id);
+ const id = encodeURIComponent(sessionId);
+ if (canonicalSessionId === sessionId) return `/bots/${botId}`;
+ if (projection?.role === 'group' || projection?.kind === 'group') return null;
+ if (projection?.role === 'delegation' || projection?.kind === 'worker') return `/cc-agent/${id}`;
+ if (projection?.role === 'history' || projection?.kind === 'history') return `/bots/${botId}/history/${id}`;
+ return `/bots/${botId}/session/${id}`;
}
export interface BotSessionEntryRouteDeps {
@@ -91,7 +101,9 @@ export function createSessionEntryNavigator(
const isLatest = () => sequence === entry;
void deps.resolveBotRoute(sessionId).then((route) => {
if (!isLatest()) return;
- if (route) deps.openBotRoute(route);
+ // A background task opens like any ordinary task, so message anchors and
+ // the Agent Island visible-session report still apply.
+ if (route && !route.startsWith('/cc-agent/')) deps.openBotRoute(route);
else deps.openOrdinary(sessionId, messageClientId, isLatest);
});
};
diff --git a/apps/desktop/src/renderer/features/bots/botTodo.css b/apps/desktop/src/renderer/features/bots/botTodo.css
index 2e382d4b0b..2d643274ec 100644
--- a/apps/desktop/src/renderer/features/bots/botTodo.css
+++ b/apps/desktop/src/renderer/features/bots/botTodo.css
@@ -1,49 +1,70 @@
+/* 伙伴待办:工作台单列里的一组(标题行同任务分组,一行标题 + 一行「到期 · 来源」)。 */
.todo-panel {
- padding: 12px 16px;
+ padding: 0 20px 8px;
color: var(--text-primary);
- border-bottom: 1px solid var(--border-default);
}
.todo-header {
display: flex;
align-items: center;
- justify-content: space-between;
- margin-bottom: 8px;
+ gap: 6px;
+ min-height: 22px;
+ margin: 14px 0 2px;
}
.todo-header h2 {
- font-size: 14px;
- line-height: 22px;
- font-weight: 600;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: var(--text-12);
+ line-height: 1.5;
+ font-weight: 400;
+ color: var(--text-secondary);
}
-.todo-tools {
- display: grid;
- grid-template-columns: minmax(0, 1fr) 112px;
- gap: 8px;
+.todo-count {
+ color: var(--text-tertiary);
+ font-variant-numeric: tabular-nums;
}
-.todo-tools input,
-.todo-tools select,
-.todo-filters select,
+.todo-header-actions {
+ margin-left: auto;
+ display: flex;
+ gap: 2px;
+}
+.todo-icon,
+.todo-more {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ flex-shrink: 0;
+ border-radius: 8px;
+ color: var(--text-tertiary);
+ transition:
+ background-color var(--motion-instant),
+ color var(--motion-instant);
+}
+.todo-icon:hover,
+.todo-more:hover,
+.todo-icon[aria-pressed='true'],
+.todo-icon[data-active],
+.todo-more[data-state='open'] {
+ background: var(--surface-hover);
+ color: var(--text-primary);
+}
+.todo-search {
+ margin: 4px 0 6px;
+}
+.todo-search input,
.todo-field input,
.todo-field textarea {
+ width: 100%;
min-width: 0;
background: var(--surface-elevated);
color: var(--text-primary);
border: 1px solid var(--border-default);
border-radius: 8px;
- padding: 7px 8px;
- font-size: 13px;
- line-height: 20px;
-}
-.todo-filters {
- display: flex;
- justify-content: space-between;
- gap: 8px;
- margin: 8px 0;
-}
-.todo-filters select {
- max-width: 50%;
- border-color: transparent;
- background: transparent;
- padding: 2px;
+ padding: 5px 8px;
+ font-size: var(--text-13);
+ line-height: 1.54;
}
.todo-list {
list-style: none;
@@ -51,20 +72,52 @@
padding: 0;
}
.todo-row {
- padding: 10px 0;
- border-bottom: 1px solid var(--border-default);
+ display: flex;
+ align-items: flex-start;
+ gap: 4px;
+ margin: 0 -8px;
min-width: 0;
+ border-radius: 8px;
+}
+.todo-row:hover {
+ background: var(--surface-hover);
}
.todo-heading {
display: flex;
- flex-direction: column;
+ flex: 1;
+ align-items: flex-start;
+ gap: 8px;
+ min-width: 0;
+ padding: 6px 0 6px 8px;
text-align: left;
- width: 100%;
+ border-radius: 8px;
+}
+.todo-lead {
+ display: flex;
+ width: 16px;
+ height: 20px;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ color: var(--card-status-done);
+}
+.todo-circle {
+ width: 14px;
+ height: 14px;
+ border-radius: 9999px;
+ border: 1.5px solid var(--text-tertiary);
+}
+.todo-circle-hidden {
+ border-style: dashed;
+}
+.todo-copy {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
min-width: 0;
- border-radius: 4px;
}
.todo-title,
-.todo-progress {
+.todo-meta {
display: block;
max-width: 100%;
overflow: hidden;
@@ -72,102 +125,72 @@
white-space: nowrap;
}
.todo-title {
- font-size: 14px;
- line-height: 22px;
- font-weight: 500;
+ font-size: var(--text-13);
+ line-height: 1.54;
}
-.todo-progress {
- font-size: 13px;
- line-height: 20px;
- font-weight: 400;
+.todo-meta {
+ font-size: var(--text-12);
+ line-height: 1.5;
color: var(--text-secondary);
}
-.todo-rail {
- display: grid;
- grid-template-columns: minmax(0, 1fr) 132px 32px;
- gap: 8px;
- align-items: center;
- margin-top: 8px;
- height: 32px;
-}
-.todo-date {
- min-width: 0;
- text-align: left;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- font-size: 12px;
- line-height: 18px;
- height: 32px;
- color: var(--text-secondary);
- border-radius: 4px;
-}
.todo-overdue {
color: var(--text-danger);
}
-.todo-rail .todo-action {
- width: 132px;
- min-width: 0;
- height: 32px;
- min-height: 32px;
- padding: 0 10px;
- display: flex;
- align-items: center;
- font-size: 13px;
- line-height: 20px;
- border-radius: 999px;
-}
-.todo-action span {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- min-width: 0;
-}
-.todo-rail .todo-more {
- width: 32px;
- height: 32px;
- min-height: 32px;
- padding: 0;
- border-radius: 8px;
+.todo-row .todo-more {
+ margin: 4px 6px 0 0;
}
.todo-done-toggle {
display: flex;
align-items: center;
gap: 6px;
- font-size: 12px;
- line-height: 18px;
+ min-height: 22px;
+ margin-top: 10px;
+ font-size: var(--text-12);
+ line-height: 1.5;
color: var(--text-secondary);
- padding: 12px 0;
+ border-radius: 8px;
+}
+.todo-done-toggle:hover {
+ color: var(--text-primary);
+}
+.todo-done-toggle svg {
+ color: var(--text-tertiary);
+ transition: transform var(--motion-fast);
+}
+.todo-done-toggle .todo-chevron-open {
+ transform: rotate(90deg);
}
.todo-pages {
display: flex;
align-items: center;
justify-content: space-between;
- font-size: 12px;
- line-height: 18px;
-}
-.todo-empty {
- padding: 16px 0;
- font-size: 13px;
- line-height: 20px;
+ font-size: var(--text-12);
+ line-height: 1.5;
color: var(--text-secondary);
}
+.todo-empty,
+.todo-panel > p[role='status'] {
+ padding: 4px 0;
+ font-size: var(--text-12);
+ line-height: 1.5;
+ color: var(--text-tertiary);
+}
.todo-error {
- font-size: 13px;
- line-height: 20px;
+ font-size: var(--text-13);
+ line-height: 1.54;
color: var(--text-danger);
overflow-wrap: anywhere;
}
.todo-detail {
display: grid;
gap: 12px;
- font-size: 14px;
- line-height: 22px;
+ font-size: var(--text-14);
+ line-height: 1.57;
overflow-wrap: anywhere;
}
.todo-detail h3 {
- font-size: 13px;
- line-height: 20px;
+ font-size: var(--text-13);
+ line-height: 1.54;
color: var(--text-secondary);
font-weight: 500;
}
@@ -178,14 +201,10 @@
.todo-field {
display: grid;
gap: 4px;
- font-size: 13px;
- line-height: 20px;
-}
-.todo-field input,
-.todo-field textarea {
- width: 100%;
+ font-size: var(--text-13);
+ line-height: 1.54;
}
.todo-panel :focus-visible {
- outline: 2px solid var(--text-primary);
+ outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
diff --git a/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts b/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
index ebb85417fc..8a01a1048d 100644
--- a/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
+++ b/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
@@ -26,7 +26,6 @@ import {
isWorkbenchTaskSource,
parseWorkbenchTaskId,
workbenchProjectKey,
- validateWorkbenchRef,
type WorkbenchDelegationStatus,
type WorkbenchTaskJudgment,
type WorkbenchTaskOrigin,
@@ -39,6 +38,8 @@ export interface WorkbenchActivity {
startedAtMs?: number | null;
currentActionSummary?: string | null;
compactDetail?: string | null;
+ /** 等你时在等什么(权限 / 提问 / 方案 / 插件设置 / 代输入);来自灵动岛同源快照。 */
+ interactionKind?: string | null;
}
export interface WorkbenchDelegationInput {
@@ -88,7 +89,7 @@ export interface ExternalSessionCandidate {
/** 格子底部那一行说的是什么;具体文案由界面按语言拼。 */
export type WorkbenchTileLine =
| { kind: 'action'; text: string }
- | { kind: 'waiting' }
+ | { kind: 'waiting'; interaction?: string | null; text?: string | null }
| { kind: 'queued' }
| { kind: 'interrupted' }
| { kind: 'errored' }
@@ -122,6 +123,8 @@ export type WorkbenchTile =
startedAtMs: number | null;
lastActiveMs: number;
line: WorkbenchTileLine;
+ /** 已归档的负责任务:列在「做完」最底部,打开只看,不恢复。 */
+ archived?: boolean;
}
| {
/** 还没接过来的本机 Claude Code / Codex / Pi 会话,只因伙伴的判断而出现。 */
@@ -366,7 +369,13 @@ function sessionLine(
const text = boundWorkbenchSummary(activity?.currentActionSummary ?? activity?.compactDetail);
return text ? { kind: 'action', text } : { kind: 'none' };
}
- if (state === 'waiting') return { kind: 'waiting' };
+ if (state === 'waiting') {
+ return {
+ kind: 'waiting',
+ interaction: activity?.interactionKind ?? null,
+ text: boundWorkbenchSummary(activity?.currentActionSummary ?? activity?.compactDetail),
+ };
+ }
if (state === 'queued') return { kind: 'queued' };
if (state === 'stopped') {
if (delegation && ['failed', 'timed-out', 'cancelled'].includes(delegation.status)) {
@@ -397,6 +406,8 @@ export function buildWorkbenchTiles(input: {
judgments?: Readonly<Record<string, WorkbenchTaskJudgment>>;
/** 渲染层扫描到的本机会话,只用来补最近活动时间。 */
candidates?: readonly ExternalSessionCandidate[];
+ /** 已归档的负责任务(按页读取):一律进「做完」底部,不带跟进。 */
+ archivedSessions?: readonly Session[];
/** 保留旧调用方签名;逐任务责任不按活动时间排除。 */
now?: number;
}): WorkbenchTile[] {
@@ -444,6 +455,26 @@ export function buildWorkbenchTiles(input: {
});
}
+ for (const session of input.archivedSessions ?? []) {
+ if (session.status !== 'archived' || !responsibleIds.has(session.id)) continue;
+ if (!isWorkbenchCandidateSession({ ...session, status: 'active' }, input.hiddenIds, responsibleIds)) continue;
+ const delegation = delegationByChild.get(session.id) ?? null;
+ tiles.push({
+ type: 'session',
+ key: `session:${session.id}`,
+ id: session.id,
+ title: judgments[session.id]?.title ?? cleanWorkbenchTitle(session.title),
+ state: 'done',
+ origin: delegation ? 'delegated' : (importedSessionOrigin(session.id, session.agentKind) ?? 'existing'),
+ verdict: null,
+ next: null,
+ startedAtMs: null,
+ lastActiveMs: Math.max(toMs(session.userSendAt), toMs(session.updatedAt), delegation?.updatedAt ?? 0),
+ line: sessionLine('done', session, null, delegation, false),
+ archived: true,
+ });
+ }
+
for (const [taskId, judgment] of Object.entries(judgments)) {
const ref = parseWorkbenchTaskId(taskId);
const verdict = shownVerdict(judgment);
@@ -542,9 +573,10 @@ export const WORKBENCH_GROUP_ORDER: readonly WorkbenchGroupKey[] = ['waiting', '
* - 等你:在等主人回复,或任务停在出错 / 被打断 / 后台任务失败(要主人拿主意);
* - 在做:正在跑的任务与自动化;
* - 待做:伙伴判为没做完 / 聊过没下文的、排队中的、PR / issue / 建议条目;
- * - 做完:其余——收尾了的后台任务、待命或停用的自动化。
+ * - 做完:其余——收尾了的后台任务、待命或停用的自动化;已归档的负责任务也在这里(列在最底部)。
*/
export function workbenchTileGroup(tile: WorkbenchTile): WorkbenchGroupKey {
+ if (tile.type === 'session' && tile.archived) return 'done';
if (tile.state === 'waiting') return 'waiting';
if (tile.state === 'stopped' && (tile.type === 'session' || tile.type === 'external')) return 'waiting';
if (tile.state === 'running') return 'running';
@@ -571,30 +603,53 @@ export interface WorkbenchTileGroup {
hiddenCount: number;
/** 做完一组默认折叠,只在标题旁显示数量。 */
defaultCollapsed: boolean;
+ /** 只在「做完」:已读到的归档负责任务,排在其余做完条目之后(按页加载,不受 30 条上限)。 */
+ archivedTiles: WorkbenchTile[];
}
/** 做完一组最多列出的条数。 */
export const WORKBENCH_DONE_MAX = 30;
-/** 按固定顺序分组,组内保持输入顺序(`buildWorkbenchTiles` 已按最近活动排好);空组不出。 */
+/**
+ * 按固定顺序分组,组内保持输入顺序(`buildWorkbenchTiles` 已按最近活动排好);空组不出。
+ * 已归档的负责任务单独放进「做完」的 `archivedTiles`,接在其余做完条目之后。
+ */
export function groupWorkbenchTiles(tiles: readonly WorkbenchTile[]): WorkbenchTileGroup[] {
const buckets = new Map<WorkbenchGroupKey, WorkbenchTile[]>(WORKBENCH_GROUP_ORDER.map((key) => [key, []]));
- for (const tile of tiles) buckets.get(workbenchTileGroup(tile))!.push(tile);
+ const archived: WorkbenchTile[] = [];
+ for (const tile of tiles) {
+ if (tile.type === 'session' && tile.archived) archived.push(tile);
+ else buckets.get(workbenchTileGroup(tile))!.push(tile);
+ }
return WORKBENCH_GROUP_ORDER.flatMap((key): WorkbenchTileGroup[] => {
const grouped = buckets.get(key)!;
- if (grouped.length === 0) return [];
- if (key !== 'done') return [{ key, tiles: grouped, total: grouped.length, hiddenCount: 0, defaultCollapsed: false }];
+ if (key !== 'done') {
+ return grouped.length === 0
+ ? []
+ : [{ key, tiles: grouped, total: grouped.length, hiddenCount: 0, defaultCollapsed: false, archivedTiles: [] }];
+ }
+ if (grouped.length + archived.length === 0) return [];
grouped.sort((a, b) => b.lastActiveMs - a.lastActiveMs);
+ archived.sort((a, b) => b.lastActiveMs - a.lastActiveMs);
return [{
key,
tiles: grouped.slice(0, WORKBENCH_DONE_MAX),
- total: grouped.length,
+ total: grouped.length + archived.length,
hiddenCount: Math.max(0, grouped.length - WORKBENCH_DONE_MAX),
defaultCollapsed: true,
+ archivedTiles: archived,
}];
});
}
+/** 列表上方的一句汇总:各组条数(做完不计)。 */
+export function summarizeWorkbenchGroups(
+ groups: readonly WorkbenchTileGroup[],
+): Record<Exclude<WorkbenchGroupKey, 'done'>, number> {
+ const count = (key: WorkbenchGroupKey) => groups.find((group) => group.key === key)?.total ?? 0;
+ return { waiting: count('waiting'), running: count('running'), todo: count('todo') };
+}
+
// ─── 空状态项目清单的过滤与分档 ─────────────────────────────────────
/** 主进程给的本机路径(主目录、应用数据目录、系统临时目录);拿不到时为 null。 */
@@ -706,15 +761,3 @@ export function tierWorkbenchProjectOptions(
const max = input.maxPrimary ?? WORKBENCH_PRIMARY_PROJECTS;
return { primary: primary.slice(0, max), folded: [...primary.slice(max), ...folded].sort(byRecency) };
}
-
-/** Retain the existing safe local-file entrance until its Todo source has an equivalent opener. */
-export function workbenchItemNeedsLocalReference(
- tile: WorkbenchTile,
- projectDirs: readonly string[],
- caseInsensitive: boolean,
-): boolean {
- return (
- tile.type === 'item' && !!tile.ref && !/^https:\/\//i.test(tile.ref) &&
- validateWorkbenchRef(tile.ref, projectDirs, caseInsensitive).ok
- );
-}
diff --git a/apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts b/apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts
new file mode 100644
index 0000000000..a249ceda08
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts
@@ -0,0 +1,127 @@
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import type { Session } from '@/lib/ccAgent.types';
+import { useSessionLifecycleActions } from '@/features/cc-agent/hooks/useSessionLifecycleActions';
+import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';
+import { useAttachedSessionIds } from '@/hooks/useAttachedSessionIds';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
+import { resolveWorktreeRemovalPreflight } from '@/lib/worktreeRemovalWarning';
+import { sessionsStore } from '@/lib/sessionsStore';
+import * as service from '@/lib/sessionService';
+import { isRemoteSessionWriteBlocked } from '@/features/cc-agent/lib/remoteSessionWriteGuard';
+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { persistManualPinnedOrder } from '@/features/cc-agent/hooks/helpers/sidebarFilterCore';
+import { toast } from '@/lib/toast';
+
+export type WorkbenchSessionActionKind = 'archive' | 'unarchive' | 'delete';
+
+/**
+ * 工作台条目「…」里的任务操作:与任务侧栏同一套生命周期 API 与守卫(运行中 / 被终端占用时
+ * 不归档、worktree 有改动或未知时先确认、共享任务先关闭共享),本身不持有任何任务状态。
+ * 打开只是看,不恢复归档;恢复只走明确的「恢复」。
+ */
+export function useWorkbenchSessionActions(sessions: readonly Session[], onChanged: () => void) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { confirm } = useConfirmDialog();
+ const { runningSessionIds, clearNotification } = useSessionRunningStatus(undefined);
+ const attached = useAttachedSessionIds();
+ const { runSessionAction, unarchiveSession } = useSessionLifecycleActions({ includeArchived: 'all' });
+ const byId = useMemo(() => new Map(sessions.map((row) => [row.id, row])), [sessions]);
+
+ const open = useCallback(
+ (id: string) => {
+ clearNotification(id);
+ void resolveSessionRoute(id, byId.get(id)).then((route) => navigate(route));
+ },
+ [byId, clearNotification, navigate],
+ );
+
+ const action = useCallback(
+ async (id: string, kind: WorkbenchSessionActionKind, sharedTaskId?: string) => {
+ try {
+ if (isRemoteSessionWriteBlocked(byId.get(id))) {
+ toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
+ return;
+ }
+ if (kind === 'unarchive') {
+ await unarchiveSession(id);
+ onChanged();
+ return;
+ }
+ const archive = kind === 'archive';
+ if (archive && runningSessionIds.has(id)) {
+ toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));
+ return;
+ }
+ if (
+ archive &&
+ (attached.has(id) ||
+ (await window.electronAPI.binding.resolveSession(id).catch(() => ({ attached: false }))).attached)
+ ) {
+ toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));
+ return;
+ }
+ const preflight = await resolveWorktreeRemovalPreflight(id, byId.get(id)?.deviceLinkDeviceId);
+ const prefix = archive ? 'ccAgent.sidebar.confirmArchive' : 'ccAgent.sidebar.confirmDelete';
+ if (
+ (!archive || preflight !== 'clean') &&
+ !(await confirm({
+ title: t(prefix + '.title'),
+ description:
+ t(prefix + '.description') + (preflight === 'dirty' ? ' ' + t(prefix + '.dirtyWorktreeWarning') : ''),
+ confirmText: t(prefix + '.confirm'),
+ cancelText: t(prefix + '.cancel'),
+ }))
+ )
+ return;
+ if (sharedTaskId) {
+ const result = (await window.electronAPI.sharedTask.account({ action: 'close', sharedTaskId })) as {
+ closed?: string[];
+ };
+ if (!result.closed?.includes(sharedTaskId)) {
+ toast.error(t('sharedTask.closeFailedToast', { count: 1 }));
+ return;
+ }
+ }
+ await runSessionAction(id, archive ? 'archive' : 'delete', { activeSessionId: null });
+ onChanged();
+ } catch {
+ toast.error(t(kind === 'delete' ? 'ccAgent.sidebar.deleteFailed' : 'ccAgent.sidebar.archiveFailed'));
+ }
+ },
+ [byId, attached, confirm, onChanged, runSessionAction, runningSessionIds, t, unarchiveSession],
+ );
+
+ const togglePin = useCallback(
+ async (id: string) => {
+ const row = byId.get(id);
+ if (!row) return;
+ if (isRemoteSessionWriteBlocked(row)) {
+ toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
+ return;
+ }
+ const pinned = Boolean(row.pinnedAt);
+ const owner = getDataOwnerGeneration();
+ try {
+ const patch = { pinnedAt: pinned ? null : new Date().toISOString() };
+ await service.patchMeta(id, patch);
+ sessionsStore.patchLocal(id, pinned ? { ...patch, summary: null } : patch);
+ if (!pinned) {
+ await persistManualPinnedOrder(
+ { kind: 'promote', entryId: id },
+ { dataOwnerId: owner.dataOwnerId, ownerGeneration: owner.generation },
+ );
+ }
+ onChanged();
+ } catch {
+ toast.error(t('ccAgent.sidebar.pinFailed'));
+ }
+ },
+ [byId, onChanged, t],
+ );
+
+ return { open, action, togglePin, byId };
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 92f421ee26..b86e1c05c0 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -61,7 +61,6 @@ import {
import { cn, basename } from '@/lib/utils';
import { Spinner } from '@/components/ui/spinner';
-import { BotWorkingStatus } from '@/features/bots/BotWorkingStatus';
import { setRemoteReceiptDisplayReady } from '@/lib/sessionAttentionStore';
import { shortSessionId } from '@/lib/sessionId';
import { ChatInput } from '@/components/new-chat/ChatInput';
@@ -1003,9 +1002,7 @@ function CCAgentSessionContent({
// Bot route gates have already checked durable ownership. The async runtime
// snapshot may be absent during load/reconnect; it must never change the skin.
const botChatIdentity = resolveBotChatIdentity(botIdentity, sessionId);
- // 伙伴没有 RunningStatusBar,折叠呼吸灯继续留在输入框上方,不能随状态行一起消失。
- const showCenteredControlledBanner =
- hasControlledBanner && (!controlledBannerCollapsed || Boolean(botChatIdentity));
+ const showCenteredControlledBanner = hasControlledBanner && !controlledBannerCollapsed;
// assistant 气泡左侧的伙伴头像。节点在整场对话里是同一个,memo 住让 MessageItem
// 的 memo 比较仍然成立(否则每帧新节点 = 全流重渲染)。
const botAssistantAvatar = useMemo(
@@ -5173,27 +5170,7 @@ function CCAgentSessionContent({
className="mx-auto grid grid-cols-1 grid-rows-1 items-center"
style={{ width: inputWidth }}
>
- {botChatIdentity ? (
- <BotWorkingStatus
- key={sessionId}
- sessionId={sessionId ?? undefined}
- remote={remoteDeviceId ? { deviceId: remoteDeviceId, botId: botChatIdentity.id } : undefined}
- visible={composerRuntimeVisible}
- status={
- pendingPermission ? 'Waiting on approval'
- : pendingAskUser ? 'Waiting on input'
- : composerStatus
- }
- messages={messages}
- startedAt={agentStatus.startedAt}
- foregroundRunning={agentStatus.isRunning || isStreaming}
- backgroundWorkActive={
- backgroundTasksActive || runningWorkflow !== null || Boolean(agentStatus.sideTaskRunning)
- }
- avatar={botAssistantAvatar}
- inputWidth={inputWidth}
- />
- ) : !pendingPlanReview || (hasControlledBanner && controlledBannerCollapsed) ? (
+ {!pendingPlanReview || (hasControlledBanner && controlledBannerCollapsed) ? (
<RunningStatusBar
key={sessionId}
sessionKey={sessionId ?? null}
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
index f505a72eba..7bca5be8a1 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
@@ -65,6 +65,7 @@ import { isOrcaLeadSession, resolveSessionRoute } from '@/lib/orcaSessionIdentit
import { revalidateWorkersProjection } from './hooks/workerProjectionStore';
import { GitContextBadge } from './GitContextBadge';
import { OrcaRemoteLeadBadge } from './OrcaRemoteLeadBadge';
+import { BotTaskOwnerChip } from '@/features/bots/BotTaskOwnerChip';
import { SessionRenameInput } from './SessionRenameInput';
import { useSessionBoundSchedules } from '@/features/scheduler/lib/scheduleSessionBinding';
import { ScheduleBindingBadge } from './sidebar/ScheduleBindingBadge';
@@ -655,6 +656,8 @@ export function SessionContentHeader({
{!isEditing && <OrcaRemoteLeadBadge session={session} />}
+ {!isEditing && <BotTaskOwnerChip sessionId={session.id} />}
+
{!isEditing && !readOnly && (!sharedGuest || session.status === 'active') && (
// 菜单打开就把归档/删除的 dirty 预检发出去:用户从展开菜单到点条目至少
// 一次反应时间,足够这次 git status 跑完,点下去时命中缓存、零等待。
diff --git a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
index 9120e1855c..b788e63314 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
@@ -10,7 +10,7 @@
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
-import { Bot, FileDiff, FolderTree, Globe, ListTodo, Terminal } from 'lucide-react';
+import { Bot, FileDiff, FolderTree, Globe, LayoutGrid, ListTodo, Terminal } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import {
DropdownMenuContent,
@@ -18,8 +18,10 @@ import {
DropdownMenuLabel,
DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
-import { useBotProfiles } from '@/features/bots/botStore';
+import { canonicalBotSessionId, useBotProfiles } from '@/features/bots/botStore';
import { findBotProfileForSession } from '@/features/bots/botSessionOwners';
+import { sessionsStore } from '@/lib/sessionsStore';
+import { openBotWorkbenchTab } from './lib/openBotWorkbenchTab';
import type { TabKindId, TabKindMenuMeta } from './types';
const BOT_SECONDARY_KINDS = new Set<TabKindId>([
@@ -53,6 +55,15 @@ interface AddTabDropdownProps {
// Phase 1 硬编码。Phase 2 之后由 plugin registry 自动汇总。
const MENU_ITEMS: TabKindMenuMeta[] = [
+ {
+ // 伙伴工作台:只在本机伙伴主任务里出现,关掉后可从这里重新打开。
+ kind: 'bot-workbench',
+ labelKey: 'bots.workbench.title',
+ icon: LayoutGrid,
+ order: 0,
+ enabled: true,
+ singleton: true,
+ },
{
kind: 'file-browser',
labelKey: 'rightSidebar.tabs.kinds.fileBrowser',
@@ -111,7 +122,18 @@ export function AddTabDropdown({
}: AddTabDropdownProps) {
const { t } = useTranslation();
const bots = useBotProfiles();
- const isBotSession = Boolean(sessionId && findBotProfileForSession(bots, sessionId));
+ const bot = sessionId ? findBotProfileForSession(bots, sessionId) : undefined;
+ const isBotSession = Boolean(bot);
+ // 工作台只属于本机伙伴的主任务(渠道 / 历史 / 群专线任务与远端任务都没有)。
+ const sessionRow = sessionId ? sessionsStore.findById(sessionId) : null;
+ const workbenchBotId =
+ bot &&
+ sessionId &&
+ canonicalBotSessionId(bot) === sessionId &&
+ !sessionRow?.remoteHostId &&
+ !sessionRow?.deviceLinkDeviceId
+ ? bot.id
+ : null;
// 跟随:Radix Popper 负责摆位与视口碰撞。打开期间用 rAF 轮询 anchor —— 从布局中
// 消失(关掉最后一个 tab 面板收起)直接关闭,避免菜单悬空残留在旧坐标。
//
@@ -140,6 +162,7 @@ export function AddTabDropdown({
}, [open, anchorRef, onClose]);
const visibleItems = MENU_ITEMS.filter((item) => {
+ if (item.kind === 'bot-workbench' && !workbenchBotId) return false;
if (item.kind === 'subagents' && !subagentsAvailable) return false;
if (isBotSession && BOT_SECONDARY_KINDS.has(item.kind)) return false;
return true;
@@ -169,7 +192,14 @@ export function AddTabDropdown({
icon={m.icon}
label={t(m.labelKey)}
trailing={alreadyOpen ? t('rightSidebar.tabs.menu.alreadyOpen') : undefined}
- onSelect={() => onSelect(m.kind)}
+ onSelect={() => {
+ // 工作台标签需要伙伴 id,走与聊天头部入口同一个打开器(重建并排到最前、展开侧栏)。
+ if (m.kind === 'bot-workbench' && sessionId && workbenchBotId) {
+ void openBotWorkbenchTab(sessionId, workbenchBotId).catch(() => undefined);
+ return;
+ }
+ onSelect(m.kind);
+ }}
/>
);
})}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/AddTabDropdown.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/AddTabDropdown.test.tsx
new file mode 100644
index 0000000000..31656107ff
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/AddTabDropdown.test.tsx
@@ -0,0 +1,82 @@
+// @vitest-environment jsdom
+import { createRef, type ReactNode } from 'react';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { AddTabDropdown } from '../AddTabDropdown';
+
+const m = vi.hoisted(() => ({
+ open: vi.fn(async () => undefined),
+ rows: new Map<string, { remoteHostId?: string | null; deviceLinkDeviceId?: string | null }>(),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+// Radix 浮层在 jsdom 里不需要真的开合:菜单摊平成按钮,只验证有哪些项、点了做什么。
+vi.mock('@/components/ui/dropdown-menu', () => ({
+ DropdownMenuContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuLabel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuSeparator: () => <hr />,
+ DropdownMenuItem: ({ children, onSelect, disabled }: { children: ReactNode; onSelect?: () => void; disabled?: boolean }) => (
+ <button type="button" disabled={disabled} onClick={onSelect}>
+ {children}
+ </button>
+ ),
+}));
+vi.mock('@/features/bots/botStore', () => ({
+ useBotProfiles: () => [
+ {
+ id: 'bot-1',
+ sessions: [
+ { id: 'bot-main', role: 'canonical' },
+ { id: 'bot-history', role: 'history' },
+ ],
+ },
+ ],
+ canonicalBotSessionId: (bot: { sessions: Array<{ id: string; role: string }> }) =>
+ bot.sessions.find((session) => session.role === 'canonical')?.id,
+}));
+vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: { findById: (id: string) => m.rows.get(id) ?? null } }));
+vi.mock('../lib/openBotWorkbenchTab', () => ({ openBotWorkbenchTab: m.open }));
+
+function renderMenu(sessionId: string, onSelect = vi.fn()) {
+ const anchorRef = createRef<HTMLElement>();
+ render(
+ <AddTabDropdown open={false} anchorRef={anchorRef} sessionId={sessionId} onClose={vi.fn()} onSelect={onSelect} />,
+ );
+ return onSelect;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ m.rows = new Map();
+});
+afterEach(cleanup);
+
+it('offers the workbench in a local teammate main task and reopens it with the teammate id', () => {
+ const onSelect = renderMenu('bot-main');
+ fireEvent.click(screen.getByText('bots.workbench.title'));
+ expect(m.open).toHaveBeenCalledWith('bot-main', 'bot-1');
+ expect(onSelect).not.toHaveBeenCalled();
+});
+
+it('keeps the other entries on the generic add path', () => {
+ const onSelect = renderMenu('bot-main');
+ fireEvent.click(screen.getByText('rightSidebar.tabs.kinds.fileBrowser'));
+ expect(onSelect).toHaveBeenCalledWith('file-browser');
+ expect(m.open).not.toHaveBeenCalled();
+});
+
+it.each([
+ ['an ordinary task', 'task-1'],
+ ['a teammate history task', 'bot-history'],
+])('does not offer the workbench in %s', (_label, sessionId) => {
+ renderMenu(sessionId);
+ expect(screen.queryByText('bots.workbench.title')).toBeNull();
+});
+
+it.each([
+ ['SSH remote', { remoteHostId: 'ssh-1' }],
+ ['device-link', { deviceLinkDeviceId: 'device-2' }],
+])('does not offer the workbench for a %s mirror', (_label, row) => {
+ m.rows.set('bot-main', row);
+ renderMenu('bot-main');
+ expect(screen.queryByText('bots.workbench.title')).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx
index faac8f861c..ac9928c00c 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx
@@ -8,7 +8,8 @@ interface BotWorkbenchTabState {
}
/**
- * 伙伴工作台:只由伙伴主任务页自动创建(不进「+」菜单),每个任务至多一个。
+ * 伙伴工作台:伙伴主任务页首次进入时自动创建,每个任务至多一个。关掉后可从聊天头部入口或
+ * 「+」菜单重新打开(菜单项只在本机伙伴主任务里出现,由 AddTabDropdown 带上伙伴 id 打开)。
* 只在已确认是本机的任务里渲染;device-link 远程或归属未解析时不显示内容。
*/
const plugin: TabKindPlugin<BotWorkbenchTabState> = {
@@ -20,7 +21,6 @@ const plugin: TabKindPlugin<BotWorkbenchTabState> = {
order: 0,
enabled: true,
singleton: true,
- hiddenFromMenu: true,
},
TabPillTitle: ({ t }) => <>{t('bots.workbench.title')}</>,
TabPillIcon: () => <LayoutGrid size={13} />,
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 151468f1d5..c8f031aaad 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8655,11 +8655,25 @@
"ref": "Reference",
"noRef": "No reference attached.",
"openPr": "Open PR #{{number}} on GitHub",
- "refBlocked": "This path is outside the handed-over projects, so it wasn't opened."
+ "refBlocked": "This path is outside the handed-over projects, so it wasn't opened.",
+ "stopLabel": "Stop",
+ "doing": "Working on",
+ "outputs": "Outputs so far",
+ "recent": "Recent activity"
},
"openTask": "Open “{{title}}” ({{state}})",
"outputs": "Outputs",
"outputsEmpty": "Files {{name}} makes will show up here.",
+ "outputsAll": "All",
+ "outputsLess": "Show less",
+ "summary": {
+ "waiting_one": "{{count}} waiting on you",
+ "waiting_other": "{{count}} waiting on you",
+ "running_one": "{{count}} running",
+ "running_other": "{{count}} running",
+ "todo_one": "{{count}} to do",
+ "todo_other": "{{count}} to do"
+ },
"state": {
"running": "Running",
"waiting": "Waiting on you",
@@ -8700,6 +8714,11 @@
},
"line": {
"waiting": "Waiting for your reply",
+ "waitingPermission": "Waiting for your approval",
+ "waitingQuestion": "Waiting for your answer",
+ "waitingPlan": "Waiting for you to review the plan",
+ "waitingAction": "Waiting for you to take action",
+ "waitingFor": "{{label}}: {{text}}",
"queued": "Queued",
"interrupted": "Last run didn't finish",
"errored": "Last run hit an error",
@@ -8916,6 +8935,10 @@
"description": "Settings shared by all teammates. Anything about one teammate lives on their own page.",
"rosterNote": "The shipped roster grows with each release."
},
+ "session": {
+ "ownedByBot": "{{name}}'s background task",
+ "backToBot": "Back to {{name}}"
+ },
"collab": {
"backgroundTask": "Background task",
"trackedTask": "Runs independently and returns its result",
@@ -8949,7 +8972,21 @@
"daysHoursMinutes": "{{d}}d {{h}}h {{m}}m"
},
"viewResult": "View Result",
- "noWrittenResult": "No written result."
+ "noWrittenResult": "No written result.",
+ "addNote": "Add a note",
+ "addNotePlaceholder": "Tell the background task… press Enter to send",
+ "addNoteSent": "Sent to the background task",
+ "stop": "Stop",
+ "lookAt": "Take a look",
+ "awaitingConfirm": "Waiting for you: {{summary}}",
+ "awaitingConfirmGeneric": "Waiting for you",
+ "elapsed": "{{duration}} so far",
+ "tookTime": "Took {{duration}}",
+ "expandResult": "Show result",
+ "collapseResult": "Hide result",
+ "expandDetails": "Show details",
+ "collapseDetails": "Hide details",
+ "messageSentWithText": "Told the background task: “{{text}}”"
},
"directMessage": {
"sentTo": "Sent a message to {{name}}",
@@ -8960,11 +8997,40 @@
"close": "Close conversation",
"unavailable": "This teammate conversation is no longer available.",
"empty": "There are no messages to view yet.",
- "limitReached": "This teammate conversation reached its limit; both teammates returned to their main tasks"
+ "limitReached": "This teammate conversation reached its limit; both teammates returned to their main tasks",
+ "sentHeader": "To {{name}}",
+ "receivedHeader": "From {{name}}",
+ "expandThread": "Show exchange",
+ "exchangeCountShort": "{{count}} messages",
+ "exchangeCountShort_one": "{{count}} message",
+ "exchangeCountShort_other": "{{count}} messages",
+ "expand": "Show",
+ "collapse": "Hide",
+ "fullThread": "Full conversation",
+ "threadClosed": "This teammate conversation has ended · view only"
},
"groupChat": {
"migrationPending": "Some earlier history is still uploading. It will retry automatically; this chat remains available.",
"memberSeparator": ", ",
+ "ownerOf": "{{name}}’s owner",
+ "elapsed": {
+ "seconds": "{{count}} sec",
+ "minutes": "{{count}} min",
+ "hours": "{{hours}} hr {{minutes}} min"
+ },
+ "progress": {
+ "step": "Step {{step}}/{{total}}",
+ "speaking": "{{name}} is replying…",
+ "elapsed": "{{time}} so far",
+ "viewProcess": "Show work",
+ "hideProcess": "Hide work",
+ "stop": "Stop"
+ },
+ "header": {
+ "stepRunning": "{{name}} is on step {{step}}",
+ "speaking": "{{name}} is replying…",
+ "planning": "{{name}} is splitting the work…"
+ },
"memberCount_one": "{{count}} teammate",
"memberCount_other": "{{count}} teammates",
"nameLabel": "Group Name",
@@ -9046,6 +9112,8 @@
"emptyTitle": "No messages in this group yet",
"emptyDescription": "Say something to get started and your teammates will join in. @ a teammate to have only them reply.",
"roundEnded": "Teammates are done",
+ "stepTag": "Step {{count}}",
+ "sending": "Sending",
"continue": "Continue Discussion",
"continueFailed": "Couldn’t continue the discussion. Try again.",
"nextStep": "Next:",
@@ -9148,7 +9216,7 @@
"missing": "This plan is no longer available",
"start": "Start Plan",
"dismiss": "Skip Plan",
- "editHint": "To change who does what, just say so",
+ "editHint": "Click a step to hand it to someone else",
"pauseNote": "Work pauses after each step until you click “Start Next Step”.",
"superseded": "Updated",
"dismissed": "Skipped",
@@ -9187,6 +9255,8 @@
"openTopic": "View thread · {{count}} replies",
"topic": "Thread",
"replies": "Replies",
+ "replyCount_one": "{{count}} reply",
+ "replyCount_other": "{{count}} replies",
"replyPlaceholder": "Reply to this message; use @ to mention a companion…",
"sendReply": "Send reply",
"addReaction": "Add reaction",
@@ -9245,7 +9315,6 @@
"transfer": "Transfer ownership",
"transferTitle": "Transfer ownership to {{name}}?",
"transferHint": "They will become the owner and you will become an admin. Companions can also own groups.",
- "remove": "Remove from group",
"removeTitle": "Remove {{name}} from this group?",
"removeHint": "They will lose access to messages. Their companions will also leave.",
"addCompanion": "Invite my companion",
@@ -9256,12 +9325,6 @@
"confirm": "Confirm",
"lastOwner": "Transfer ownership to another member before leaving or removing the current owner.",
"conflict": "Someone updated this group. Refresh and try again.",
- "replyMode": "Without a mention",
- "speakingMode": "Speaking order",
- "all": "All companions may reply",
- "mentioned": "Only when mentioned",
- "auto": "Together",
- "sequential": "One at a time",
"unarchive": "Unarchive group",
"unarchiveHint": "Resume messages and companion activity.",
"archived": "This group is archived. History is still available.",
@@ -15988,7 +16051,6 @@
"suggested": "Suggested",
"candidate": "Confirm date",
"overdue": "Overdue",
- "today": "Today",
"next": "Next step",
"outcome": "Completion condition",
"value": "Why it matters",
@@ -16018,7 +16080,6 @@
"name": "Title",
"progress": "Progress",
"link": "Evidence link (optional)",
- "saved": "Saved",
"page": "{{start}}–{{end}} / {{count}}",
"previous": "Previous",
"following": "Next",
@@ -16030,17 +16091,16 @@
"close": "Close",
"laterConflict": "Deferring does not extend the deadline",
"legacyEvidence": "Legacy completion evidence needs verification",
- "noPermission": "This source is not connected or authorized",
- "copy": "Copy",
- "undo": "Undo",
"history": "Completion history",
- "clockNote": "Date-only deadlines end in the shown time zone; exact times retain their zone.",
"deleted": "Deleted",
"muted": "Not suggested again",
"deferred": "Deferred",
"continue": "Continue",
- "addTime": "Add time",
- "dateOnly": "Date only"
+ "filter": "Filter",
+ "deleteConfirmTitle": "Delete this todo?",
+ "deleteConfirmBody": "It won't show again, and the same issue won't be raised again. You can restore it from Dismissed / later.",
+ "muteConfirmTitle": "Stop suggesting this issue?",
+ "muteConfirmBody": "The same issue won't come back to your todos. You can restore it from Dismissed / later."
},
"codexResets": {
"retryReset": "Retry Reset",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 55fea727db..46eb4915b0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8619,11 +8619,22 @@
"ref": "参考",
"noRef": "参考リンクはありません。",
"openPr": "GitHub で PR #{{number}} を開く",
- "refBlocked": "このパスは任せたプロジェクトの外にあるため開きませんでした。"
+ "refBlocked": "このパスは任せたプロジェクトの外にあるため開きませんでした。",
+ "stopLabel": "停止",
+ "doing": "実行中の作業",
+ "outputs": "これまでの成果物",
+ "recent": "最近の内容"
},
"openTask": "「{{title}}」を開く({{state}})",
"outputs": "成果物",
"outputsEmpty": "{{name}} が作ったファイルはここに表示されます。",
+ "outputsAll": "すべて",
+ "outputsLess": "折りたたむ",
+ "summary": {
+ "waiting_other": "返信待ち {{count}} 件",
+ "running_other": "実行中 {{count}} 件",
+ "todo_other": "やること {{count}} 件"
+ },
"state": {
"running": "実行中",
"waiting": "返信待ち",
@@ -8663,6 +8674,11 @@
},
"line": {
"waiting": "あなたの返信を待っています",
+ "waitingPermission": "あなたの承認を待っています",
+ "waitingQuestion": "あなたの回答を待っています",
+ "waitingPlan": "プランの確認を待っています",
+ "waitingAction": "あなたの操作を待っています",
+ "waitingFor": "{{label}}:{{text}}",
"queued": "待機中",
"interrupted": "前回は最後まで実行されませんでした",
"errored": "前回エラーが発生しました",
@@ -8879,6 +8895,10 @@
"description": "パートナー全体に共通する設定です。個々のパートナーの設定は、その子のページにあります。",
"rosterNote": "あらかじめ用意された顔ぶれは、バージョンごとに増えていきます。"
},
+ "session": {
+ "ownedByBot": "{{name}} のバックグラウンドタスク",
+ "backToBot": "{{name}} に戻る"
+ },
"collab": {
"backgroundTask": "バックグラウンドタスク",
"trackedTask": "独立して実行し、結果を自動で返します",
@@ -8912,7 +8932,21 @@
"daysHoursMinutes": "{{d}}日{{h}}時間{{m}}分"
},
"viewResult": "結果を見る",
- "noWrittenResult": "テキストの結果はありません。"
+ "noWrittenResult": "テキストの結果はありません。",
+ "addNote": "ひとこと追加",
+ "addNotePlaceholder": "バックグラウンドタスクに伝える内容(Enter で送信)",
+ "addNoteSent": "バックグラウンドタスクに送信しました",
+ "stop": "停止",
+ "lookAt": "確認する",
+ "awaitingConfirm": "あなたの確認待ち:{{summary}}",
+ "awaitingConfirmGeneric": "あなたの確認待ち",
+ "elapsed": "経過 {{duration}}",
+ "tookTime": "所要 {{duration}}",
+ "expandResult": "結果を表示",
+ "collapseResult": "結果を閉じる",
+ "expandDetails": "詳細を表示",
+ "collapseDetails": "詳細を閉じる",
+ "messageSentWithText": "バックグラウンドタスクに伝えました:「{{text}}」"
},
"directMessage": {
"sentTo": "{{name}} にメッセージを送信",
@@ -8923,11 +8957,40 @@
"close": "会話を閉じる",
"unavailable": "この仲間同士の会話は利用できません。",
"empty": "表示できるメッセージはまだありません。",
- "limitReached": "今回の会話は上限に達し、双方がそれぞれのメインタスクに戻りました"
+ "limitReached": "今回の会話は上限に達し、双方がそれぞれのメインタスクに戻りました",
+ "sentHeader": "{{name}} へ送信",
+ "receivedHeader": "{{name}} から",
+ "expandThread": "やり取りを表示",
+ "exchangeCountShort": "{{count}} 件のやり取り",
+ "exchangeCountShort_one": "{{count}} 件のやり取り",
+ "exchangeCountShort_other": "{{count}} 件のやり取り",
+ "expand": "表示",
+ "collapse": "閉じる",
+ "fullThread": "会話全体",
+ "threadClosed": "今回の仲間同士の会話は終了しました · 閲覧のみ"
},
"groupChat": {
"migrationPending": "過去の履歴の一部をアップロード中です。自動的に再試行します。このチャットは引き続き利用できます。",
"memberSeparator": "、",
+ "ownerOf": "{{name}} のオーナー",
+ "elapsed": {
+ "seconds": "{{count}} 秒",
+ "minutes": "{{count}} 分",
+ "hours": "{{hours}} 時間 {{minutes}} 分"
+ },
+ "progress": {
+ "step": "ステップ {{step}}/{{total}}",
+ "speaking": "{{name}} が返信中…",
+ "elapsed": "経過 {{time}}",
+ "viewProcess": "経過を見る",
+ "hideProcess": "経過を閉じる",
+ "stop": "停止"
+ },
+ "header": {
+ "stepRunning": "{{name}} がステップ {{step}} を作業中",
+ "speaking": "{{name}} が返信中…",
+ "planning": "{{name}} が役割分担を考え中…"
+ },
"memberCount_one": "仲間 {{count}} 人",
"memberCount_other": "仲間 {{count}} 人",
"nameLabel": "グループ名",
@@ -9009,6 +9072,8 @@
"emptyTitle": "このグループにはまだメッセージがありません",
"emptyDescription": "話しかけると仲間たちが会話を続けます。@ で仲間を指名すると、その仲間だけが返信します。",
"roundEnded": "仲間たちの発言が終わりました",
+ "stepTag": "ステップ {{count}}",
+ "sending": "送信中",
"continue": "議論を続ける",
"continueFailed": "議論を続けられませんでした。もう一度お試しください",
"nextStep": "次のステップ:",
@@ -9111,7 +9176,7 @@
"missing": "この計画は読み込めなくなりました",
"start": "開始する",
"dismiss": "今回はやめる",
- "editHint": "担当や手順を変えたいときは、そのまま話しかけてください",
+ "editHint": "ステップをクリックすると担当を変えられます",
"pauseNote": "1 ステップ終わるごとに止まり、「次へ進む」を押すまで待ちます。",
"superseded": "更新済み",
"dismissed": "見送りました",
@@ -9150,6 +9215,7 @@
"openTopic": "スレッドを表示 · {{count}} 件の返信",
"topic": "スレッド",
"replies": "返信",
+ "replyCount": "返信 {{count}} 件",
"replyPlaceholder": "このメッセージに返信。@ でパートナーを指定できます…",
"sendReply": "返信を送信",
"addReaction": "リアクションを追加",
@@ -9208,7 +9274,6 @@
"transfer": "所有権を譲渡",
"transferTitle": "{{name}} に所有権を譲渡しますか?",
"transferHint": "相手がオーナーになり、あなたは管理者になります。パートナーもオーナーになれます。",
- "remove": "グループから削除",
"removeTitle": "{{name}} をグループから削除しますか?",
"removeHint": "メッセージの閲覧と送信ができなくなります。そのメンバーのパートナーも退出します。",
"addCompanion": "自分のパートナーを招待",
@@ -9219,12 +9284,6 @@
"confirm": "確認",
"lastOwner": "退出またはオーナーを削除する前に、別のメンバーに所有権を譲渡してください。",
"conflict": "設定が更新されました。再読み込みしてお試しください。",
- "replyMode": "メンションがない場合",
- "speakingMode": "発言順",
- "all": "全パートナーが返信可能",
- "mentioned": "メンション時のみ",
- "auto": "同時に発言",
- "sequential": "順番に発言",
"unarchive": "アーカイブを解除",
"unarchiveHint": "メッセージとパートナーの実行を再開します。",
"archived": "アーカイブ済みです。履歴は引き続き閲覧できます。",
@@ -15932,7 +15991,6 @@
"suggested": "提案",
"candidate": "日付を確認",
"overdue": "期限超過",
- "today": "今日",
"next": "次の手順",
"outcome": "完了条件",
"value": "取り組む理由",
@@ -15962,7 +16020,6 @@
"name": "タイトル",
"progress": "進捗",
"link": "根拠のリンク(任意)",
- "saved": "保存済み",
"page": "{{start}}–{{end}} / {{count}}",
"previous": "前へ",
"following": "次へ",
@@ -15974,17 +16031,16 @@
"close": "閉じる",
"laterConflict": "延期しても期限は変わりません",
"legacyEvidence": "旧記録の完了の根拠は未確認です",
- "noPermission": "未接続または未承認の情報源です",
- "copy": "コピー",
- "undo": "元に戻す",
"history": "完了履歴",
- "clockNote": "日付のみの期限は表示されたタイムゾーンの一日の終わりです。日時にはタイムゾーンが保持されます。",
"deleted": "削除済み",
"muted": "今後提案しない",
"deferred": "延期中",
"continue": "続ける",
- "addTime": "時刻を追加",
- "dateOnly": "日付のみ"
+ "filter": "絞り込み",
+ "deleteConfirmTitle": "この項目を削除しますか?",
+ "deleteConfirmBody": "今後は表示されず、同じ問題も再び挙がりません。「非表示 / あとで」から元に戻せます。",
+ "muteConfirmTitle": "この問題を今後提案しないようにしますか?",
+ "muteConfirmBody": "同じ問題は今後 Todo に表示されません。「非表示 / あとで」から元に戻せます。"
},
"codexResets": {
"retryReset": "リセットを再試行",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index d848794c10..a57b045ceb 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8619,11 +8619,22 @@
"ref": "참고",
"noRef": "첨부된 참고 링크가 없습니다.",
"openPr": "GitHub에서 PR #{{number}} 열기",
- "refBlocked": "맡긴 프로젝트 밖의 경로라서 열지 않았습니다."
+ "refBlocked": "맡긴 프로젝트 밖의 경로라서 열지 않았습니다.",
+ "stopLabel": "중지",
+ "doing": "지금 하는 일",
+ "outputs": "지금까지의 결과물",
+ "recent": "최근 내용"
},
"openTask": "‘{{title}}’ 열기({{state}})",
"outputs": "결과물",
"outputsEmpty": "{{name}}이(가) 만든 파일이 여기에 표시됩니다.",
+ "outputsAll": "전체",
+ "outputsLess": "접기",
+ "summary": {
+ "waiting_other": "응답 대기 {{count}}개",
+ "running_other": "실행 중 {{count}}개",
+ "todo_other": "할 일 {{count}}개"
+ },
"state": {
"running": "실행 중",
"waiting": "응답 대기",
@@ -8663,6 +8674,11 @@
},
"line": {
"waiting": "응답을 기다리는 중",
+ "waitingPermission": "승인을 기다리는 중",
+ "waitingQuestion": "답변을 기다리는 중",
+ "waitingPlan": "계획 검토를 기다리는 중",
+ "waitingAction": "작업을 기다리는 중",
+ "waitingFor": "{{label}}: {{text}}",
"queued": "대기 중",
"interrupted": "지난번 실행이 끝나지 않았습니다",
"errored": "지난번 실행에서 오류가 났습니다",
@@ -8879,6 +8895,10 @@
"description": "파트너 전체에 적용되는 설정입니다. 개별 파트너 설정은 각자의 페이지에 있어요.",
"rosterNote": "기본 제공되는 구성원은 버전마다 늘어납니다."
},
+ "session": {
+ "ownedByBot": "{{name}}의 백그라운드 작업",
+ "backToBot": "{{name}}(으)로 돌아가기"
+ },
"collab": {
"backgroundTask": "백그라운드 작업",
"trackedTask": "독립적으로 실행하고 결과를 자동 반환",
@@ -8912,7 +8932,21 @@
"daysHoursMinutes": "{{d}}일 {{h}}시간 {{m}}분"
},
"viewResult": "결과 보기",
- "noWrittenResult": "텍스트 결과가 없습니다."
+ "noWrittenResult": "텍스트 결과가 없습니다.",
+ "addNote": "한마디 추가",
+ "addNotePlaceholder": "백그라운드 작업에 전할 말 (Enter로 보내기)",
+ "addNoteSent": "백그라운드 작업에 보냈습니다",
+ "stop": "중지",
+ "lookAt": "살펴보기",
+ "awaitingConfirm": "확인 대기 중: {{summary}}",
+ "awaitingConfirmGeneric": "확인 대기 중",
+ "elapsed": "{{duration}} 진행 중",
+ "tookTime": "소요 {{duration}}",
+ "expandResult": "결과 펼치기",
+ "collapseResult": "결과 접기",
+ "expandDetails": "자세히 펼치기",
+ "collapseDetails": "자세히 접기",
+ "messageSentWithText": "백그라운드 작업에 전달함: “{{text}}”"
},
"directMessage": {
"sentTo": "{{name}}에게 메시지를 보냄",
@@ -8923,11 +8957,40 @@
"close": "대화 닫기",
"unavailable": "이 동료 간 대화를 더 이상 사용할 수 없습니다.",
"empty": "아직 볼 수 있는 메시지가 없습니다.",
- "limitReached": "이번 동료 간 대화가 한도에 도달해 양쪽 모두 각자의 기본 작업으로 돌아갔습니다"
+ "limitReached": "이번 동료 간 대화가 한도에 도달해 양쪽 모두 각자의 기본 작업으로 돌아갔습니다",
+ "sentHeader": "{{name}}에게 보냄",
+ "receivedHeader": "{{name}}의 메시지",
+ "expandThread": "주고받은 메시지 펼치기",
+ "exchangeCountShort": "메시지 {{count}}개",
+ "exchangeCountShort_one": "메시지 {{count}}개",
+ "exchangeCountShort_other": "메시지 {{count}}개",
+ "expand": "펼치기",
+ "collapse": "접기",
+ "fullThread": "전체 대화",
+ "threadClosed": "이번 동료 간 대화가 끝났습니다 · 보기 전용"
},
"groupChat": {
"migrationPending": "이전 기록 일부가 아직 업로드되지 않았습니다. 자동으로 다시 시도하며 채팅은 계속 사용할 수 있습니다.",
"memberSeparator": ", ",
+ "ownerOf": "{{name}}의 소유자",
+ "elapsed": {
+ "seconds": "{{count}}초",
+ "minutes": "{{count}}분",
+ "hours": "{{hours}}시간 {{minutes}}분"
+ },
+ "progress": {
+ "step": "{{step}}/{{total}}단계",
+ "speaking": "{{name}} 님이 답하는 중…",
+ "elapsed": "{{time}} 경과",
+ "viewProcess": "과정 보기",
+ "hideProcess": "과정 접기",
+ "stop": "중지"
+ },
+ "header": {
+ "stepRunning": "{{name}} 님이 {{step}}단계 작업 중",
+ "speaking": "{{name}} 님이 답하는 중…",
+ "planning": "{{name}} 님이 역할을 나누는 중…"
+ },
"memberCount_one": "동료 {{count}}명",
"memberCount_other": "동료 {{count}}명",
"nameLabel": "그룹 이름",
@@ -9009,6 +9072,8 @@
"emptyTitle": "이 그룹에는 아직 메시지가 없습니다",
"emptyDescription": "한마디 하면 동료들이 이어서 대화합니다. @로 동료를 지정하면 그 동료만 답합니다.",
"roundEnded": "동료들이 말을 마쳤습니다",
+ "stepTag": "{{count}}단계",
+ "sending": "보내는 중",
"continue": "토론 계속하기",
"continueFailed": "토론을 이어 가지 못했습니다. 다시 시도하세요",
"nextStep": "다음 단계:",
@@ -9111,7 +9176,7 @@
"missing": "이 계획을 더 이상 불러올 수 없습니다",
"start": "시작하기",
"dismiss": "필요 없어요",
- "editHint": "담당이나 단계를 바꾸려면 그냥 말해 주세요",
+ "editHint": "단계를 누르면 담당을 바꿀 수 있습니다",
"pauseNote": "한 단계가 끝날 때마다 멈추고, ‘다음 단계 시작’을 누를 때까지 기다립니다.",
"superseded": "업데이트됨",
"dismissed": "사용 안 함",
@@ -9150,6 +9215,7 @@
"openTopic": "스레드 보기 · 답글 {{count}}개",
"topic": "스레드",
"replies": "답글",
+ "replyCount": "답글 {{count}}개",
"replyPlaceholder": "이 메시지에 답글을 쓰세요. @로 파트너를 멘션할 수 있어요…",
"sendReply": "답글 보내기",
"addReaction": "이모지 반응 추가",
@@ -9208,7 +9274,6 @@
"transfer": "소유권 이전",
"transferTitle": "{{name}}에게 소유권을 이전할까요?",
"transferHint": "상대가 소유자가 되고 본인은 관리자가 됩니다. 파트너도 소유자가 될 수 있습니다.",
- "remove": "그룹에서 내보내기",
"removeTitle": "{{name}}을 그룹에서 내보낼까요?",
"removeHint": "메시지를 읽거나 보낼 수 없게 됩니다. 해당 멤버의 파트너도 나갑니다.",
"addCompanion": "내 파트너 초대",
@@ -9219,12 +9284,6 @@
"confirm": "확인",
"lastOwner": "나가거나 소유자를 내보내기 전에 다른 멤버에게 소유권을 이전하세요.",
"conflict": "다른 멤버가 설정을 변경했습니다. 새로 고침 후 다시 시도하세요.",
- "replyMode": "멘션이 없을 때",
- "speakingMode": "발언 순서",
- "all": "모든 파트너 응답 가능",
- "mentioned": "멘션이 있을 때만",
- "auto": "동시에 발언",
- "sequential": "차례로 발언",
"unarchive": "그룹 보관 해제",
"unarchiveHint": "메시지와 파트너 실행을 재개합니다.",
"archived": "보관된 그룹입니다. 기록은 계속 볼 수 있습니다.",
@@ -15932,7 +15991,6 @@
"suggested": "제안",
"candidate": "날짜 확인",
"overdue": "기한 지남",
- "today": "오늘",
"next": "다음 단계",
"outcome": "완료 조건",
"value": "처리할 이유",
@@ -15962,7 +16020,6 @@
"name": "제목",
"progress": "진행 상황",
"link": "근거 링크 (선택)",
- "saved": "저장됨",
"page": "{{start}}–{{end}} / {{count}}",
"previous": "이전",
"following": "다음",
@@ -15974,17 +16031,16 @@
"close": "닫기",
"laterConflict": "미루어도 실제 기한은 연장되지 않습니다",
"legacyEvidence": "이전 완료 기록의 근거를 확인해야 합니다",
- "noPermission": "연결되지 않았거나 승인되지 않은 출처입니다",
- "copy": "복사",
- "undo": "실행 취소",
"history": "완료 기록",
- "clockNote": "날짜만 있는 기한은 표시된 시간대의 하루가 끝날 때입니다. 정확한 시각은 시간대를 유지합니다.",
"deleted": "삭제됨",
"muted": "다시 제안하지 않음",
"deferred": "미뤄짐",
"continue": "계속",
- "addTime": "시각 추가",
- "dateOnly": "날짜만"
+ "filter": "필터",
+ "deleteConfirmTitle": "이 항목을 삭제할까요?",
+ "deleteConfirmBody": "더 이상 표시되지 않고 같은 문제도 다시 제안되지 않습니다. '숨김 / 나중에'에서 복원할 수 있습니다.",
+ "muteConfirmTitle": "이 문제를 다시 제안하지 않을까요?",
+ "muteConfirmBody": "같은 문제가 다시 할 일에 나타나지 않습니다. '숨김 / 나중에'에서 복원할 수 있습니다."
},
"codexResets": {
"retryReset": "초기화 다시 시도",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index e6c1f1e36c..22585b8bfb 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8619,11 +8619,22 @@
"ref": "参考",
"noRef": "没有附参考链接。",
"openPr": "在 GitHub 打开 PR #{{number}}",
- "refBlocked": "这个路径不在交给伙伴的项目里,没有打开。"
+ "refBlocked": "这个路径不在交给伙伴的项目里,没有打开。",
+ "stopLabel": "停止",
+ "doing": "正在做",
+ "outputs": "到现在的产出",
+ "recent": "最近内容"
},
"openTask": "打开「{{title}}」({{state}})",
"outputs": "产出",
"outputsEmpty": "{{name}}做出的文件会放在这里。",
+ "outputsAll": "全部",
+ "outputsLess": "收起",
+ "summary": {
+ "waiting_other": "{{count}} 件等你",
+ "running_other": "{{count}} 件在做",
+ "todo_other": "{{count}} 件待做"
+ },
"state": {
"running": "在做",
"waiting": "等你",
@@ -8663,6 +8674,11 @@
},
"line": {
"waiting": "等你回复",
+ "waitingPermission": "等你确认",
+ "waitingQuestion": "等你回答",
+ "waitingPlan": "等你看方案",
+ "waitingAction": "等你操作",
+ "waitingFor": "{{label}}:{{text}}",
"queued": "排队中",
"interrupted": "上次没跑完",
"errored": "上次出错了",
@@ -8879,6 +8895,10 @@
"description": "和伙伴有关的通用设置。单个伙伴的设置在{{pronoun}}自己的页面里。",
"rosterNote": "预置阵容会随版本更新。"
},
+ "session": {
+ "ownedByBot": "{{name}} 的后台任务",
+ "backToBot": "回到 {{name}}"
+ },
"collab": {
"backgroundTask": "后台任务",
"trackedTask": "独立运行并自动回传结果",
@@ -8912,7 +8932,21 @@
"daysHoursMinutes": "{{d}} 天 {{h}} 小时 {{m}} 分"
},
"viewResult": "查看结果",
- "noWrittenResult": "没有文字结果。"
+ "noWrittenResult": "没有文字结果。",
+ "addNote": "补一句",
+ "addNotePlaceholder": "补充给后台任务的话,回车发送",
+ "addNoteSent": "已发给后台任务",
+ "stop": "停止",
+ "lookAt": "看看",
+ "awaitingConfirm": "等你确认:{{summary}}",
+ "awaitingConfirmGeneric": "等你确认",
+ "elapsed": "已做 {{duration}}",
+ "tookTime": "用时 {{duration}}",
+ "expandResult": "展开结果",
+ "collapseResult": "收起结果",
+ "expandDetails": "展开详情",
+ "collapseDetails": "收起详情",
+ "messageSentWithText": "已告诉后台任务:「{{text}}」"
},
"directMessage": {
"sentTo": "已发消息给 {{name}}",
@@ -8923,11 +8957,40 @@
"close": "关闭对话",
"unavailable": "这条伙伴对话已不可用。",
"empty": "还没有可查看的消息。",
- "limitReached": "本轮伙伴对话已到上限,双方已回到各自的主任务"
+ "limitReached": "本轮伙伴对话已到上限,双方已回到各自的主任务",
+ "sentHeader": "发给 {{name}}",
+ "receivedHeader": "{{name}} 发来",
+ "expandThread": "展开往来",
+ "exchangeCountShort": "{{count}} 条往来",
+ "exchangeCountShort_one": "{{count}} 条往来",
+ "exchangeCountShort_other": "{{count}} 条往来",
+ "expand": "展开",
+ "collapse": "收起",
+ "fullThread": "完整对话",
+ "threadClosed": "本轮伙伴对话已结束 · 只供查看"
},
"groupChat": {
"migrationPending": "部分旧记录尚未上传完成,将自动重试。当前群聊可继续使用。",
"memberSeparator": "、",
+ "ownerOf": "{{name}} 的主人",
+ "elapsed": {
+ "seconds": "{{count}} 秒",
+ "minutes": "{{count}} 分钟",
+ "hours": "{{hours}} 小时 {{minutes}} 分"
+ },
+ "progress": {
+ "step": "第 {{step}}/{{total}} 步",
+ "speaking": "{{name}} 正在说…",
+ "elapsed": "已做 {{time}}",
+ "viewProcess": "看过程",
+ "hideProcess": "收起过程",
+ "stop": "停止"
+ },
+ "header": {
+ "stepRunning": "{{name}} 正在做第 {{step}} 步",
+ "speaking": "{{name}} 正在说…",
+ "planning": "{{name}} 正在安排…"
+ },
"memberCount_one": "{{count}} 位伙伴",
"memberCount_other": "{{count}} 位伙伴",
"nameLabel": "群名称",
@@ -9009,6 +9072,8 @@
"emptyTitle": "群里还没有消息",
"emptyDescription": "说一句话开始,伙伴们会接着聊。@ 某位伙伴就只让它回答。",
"roundEnded": "伙伴们说完了",
+ "stepTag": "第 {{count}} 步",
+ "sending": "发送中",
"continue": "继续讨论",
"continueFailed": "没能继续讨论,请再试一次",
"nextStep": "下一步:",
@@ -9111,7 +9176,7 @@
"missing": "这个安排已经读不到了",
"start": "开始",
"dismiss": "不用了",
- "editHint": "想换人或改步骤,直接说",
+ "editHint": "点某一步可以换人",
"pauseNote": "每做完一步会停下来,等你点「继续」。",
"superseded": "已更新",
"dismissed": "不用了",
@@ -9150,6 +9215,7 @@
"openTopic": "查看话题 · {{count}} 条回复",
"topic": "话题",
"replies": "回复",
+ "replyCount": "{{count}} 条回复",
"replyPlaceholder": "回复这条消息,可用 @ 点名伙伴…",
"sendReply": "发送回复",
"addReaction": "添加表情回应",
@@ -9208,7 +9274,6 @@
"transfer": "转让群主",
"transferTitle": "将群主转让给 {{name}}?",
"transferHint": "对方成为群主,你将成为管理员。伙伴也可以担任群主。",
- "remove": "移出群",
"removeTitle": "将 {{name}} 移出群?",
"removeHint": "该成员将无法继续查看或发消息;如果是伙伴的主人,其伙伴也会退出。",
"addCompanion": "邀请我的伙伴",
@@ -9219,12 +9284,6 @@
"confirm": "确认",
"lastOwner": "请先将群主转让给其他成员,再退出或移除当前群主。",
"conflict": "群设置已被其他成员更新,请刷新后重试。",
- "replyMode": "没有 @ 时",
- "speakingMode": "发言方式",
- "all": "伙伴都可接话",
- "mentioned": "仅被 @ 时接话",
- "auto": "同时发言",
- "sequential": "依次发言",
"unarchive": "取消归档",
"unarchiveHint": "恢复新消息和伙伴执行。",
"archived": "本群已归档,可继续查看历史记录。",
@@ -15932,7 +15991,6 @@
"suggested": "建议",
"candidate": "待确认",
"overdue": "已逾期",
- "today": "今天",
"next": "下一步",
"outcome": "完成条件",
"value": "为什么值得处理",
@@ -15962,7 +16020,6 @@
"name": "标题",
"progress": "当前进展",
"link": "依据链接(可选)",
- "saved": "已保存",
"page": "{{start}}–{{end}} / {{count}}",
"previous": "上一页",
"following": "下一页",
@@ -15974,17 +16031,16 @@
"close": "关闭",
"laterConflict": "稍后处理不延长真实期限",
"legacyEvidence": "旧记录的完成依据待核实",
- "noPermission": "此来源未连接或尚未授权",
- "copy": "复制",
- "undo": "撤销",
"history": "完成记录",
- "clockNote": "仅日期按所示时区当天结束;确切时刻保留时区。",
"deleted": "已删除",
"muted": "不再提示",
"deferred": "稍后处理",
"continue": "继续",
- "addTime": "添加时间",
- "dateOnly": "仅日期"
+ "filter": "筛选",
+ "deleteConfirmTitle": "删除这条待办?",
+ "deleteConfirmBody": "删除后不再显示,同一问题也不会再被提起;可以在「已忽略 / 稍后」里恢复。",
+ "muteConfirmTitle": "此问题不再提示?",
+ "muteConfirmBody": "同一问题以后不会再出现在待办里;可以在「已忽略 / 稍后」里恢复。"
},
"codexResets": {
"retryReset": "重试重置",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 6506d654f9..c0e122ea59 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8619,11 +8619,22 @@
"ref": "參考",
"noRef": "沒有附參考連結。",
"openPr": "在 GitHub 開啟 PR #{{number}}",
- "refBlocked": "這個路徑不在交給夥伴的專案裡,沒有開啟。"
+ "refBlocked": "這個路徑不在交給夥伴的專案裡,沒有開啟。",
+ "stopLabel": "停止",
+ "doing": "正在做",
+ "outputs": "到現在的產出",
+ "recent": "最近內容"
},
"openTask": "開啟「{{title}}」({{state}})",
"outputs": "產出",
"outputsEmpty": "{{name}}做出的檔案會放在這裡。",
+ "outputsAll": "全部",
+ "outputsLess": "收起",
+ "summary": {
+ "waiting_other": "{{count}} 件等你",
+ "running_other": "{{count}} 件在做",
+ "todo_other": "{{count}} 件待做"
+ },
"state": {
"running": "在做",
"waiting": "等你",
@@ -8663,6 +8674,11 @@
},
"line": {
"waiting": "等你回覆",
+ "waitingPermission": "等你確認",
+ "waitingQuestion": "等你回答",
+ "waitingPlan": "等你看方案",
+ "waitingAction": "等你操作",
+ "waitingFor": "{{label}}:{{text}}",
"queued": "排隊中",
"interrupted": "上次沒跑完",
"errored": "上次出錯了",
@@ -8879,6 +8895,10 @@
"description": "和伙伴有關的通用設定。單個伙伴的設定在{{pronoun}}自己的頁面裡。",
"rosterNote": "預置陣容會隨版本更新。"
},
+ "session": {
+ "ownedByBot": "{{name}} 的背景任務",
+ "backToBot": "回到 {{name}}"
+ },
"collab": {
"backgroundTask": "背景任務",
"trackedTask": "獨立執行並自動回傳結果",
@@ -8912,7 +8932,21 @@
"daysHoursMinutes": "{{d}} 天 {{h}} 小時 {{m}} 分"
},
"viewResult": "查看結果",
- "noWrittenResult": "沒有文字結果。"
+ "noWrittenResult": "沒有文字結果。",
+ "addNote": "補一句",
+ "addNotePlaceholder": "補充給背景任務的話,按 Enter 傳送",
+ "addNoteSent": "已傳給背景任務",
+ "stop": "停止",
+ "lookAt": "看看",
+ "awaitingConfirm": "等你確認:{{summary}}",
+ "awaitingConfirmGeneric": "等你確認",
+ "elapsed": "已做 {{duration}}",
+ "tookTime": "用時 {{duration}}",
+ "expandResult": "展開結果",
+ "collapseResult": "收起結果",
+ "expandDetails": "展開詳情",
+ "collapseDetails": "收起詳情",
+ "messageSentWithText": "已告訴背景任務:「{{text}}」"
},
"directMessage": {
"sentTo": "已傳訊息給 {{name}}",
@@ -8923,11 +8957,40 @@
"close": "關閉對話",
"unavailable": "這則夥伴對話已無法使用。",
"empty": "還沒有可查看的訊息。",
- "limitReached": "本輪夥伴對話已達上限,雙方已回到各自的主任務"
+ "limitReached": "本輪夥伴對話已達上限,雙方已回到各自的主任務",
+ "sentHeader": "傳給 {{name}}",
+ "receivedHeader": "{{name}} 傳來",
+ "expandThread": "展開往來",
+ "exchangeCountShort": "{{count}} 則往來",
+ "exchangeCountShort_one": "{{count}} 則往來",
+ "exchangeCountShort_other": "{{count}} 則往來",
+ "expand": "展開",
+ "collapse": "收起",
+ "fullThread": "完整對話",
+ "threadClosed": "本輪夥伴對話已結束 · 僅供查看"
},
"groupChat": {
"migrationPending": "部分舊記錄尚未上傳完成,將自動重試。目前群聊可繼續使用。",
"memberSeparator": "、",
+ "ownerOf": "{{name}} 的主人",
+ "elapsed": {
+ "seconds": "{{count}} 秒",
+ "minutes": "{{count}} 分鐘",
+ "hours": "{{hours}} 小時 {{minutes}} 分"
+ },
+ "progress": {
+ "step": "第 {{step}}/{{total}} 步",
+ "speaking": "{{name}} 正在說…",
+ "elapsed": "已做 {{time}}",
+ "viewProcess": "看過程",
+ "hideProcess": "收起過程",
+ "stop": "停止"
+ },
+ "header": {
+ "stepRunning": "{{name}} 正在做第 {{step}} 步",
+ "speaking": "{{name}} 正在說…",
+ "planning": "{{name}} 正在安排…"
+ },
"memberCount_one": "{{count}} 位夥伴",
"memberCount_other": "{{count}} 位夥伴",
"nameLabel": "群聊名稱",
@@ -9009,6 +9072,8 @@
"emptyTitle": "群聊裡還沒有訊息",
"emptyDescription": "說一句話開始,夥伴們會接著聊。@ 某位夥伴就只讓它回答。",
"roundEnded": "夥伴們說完了",
+ "stepTag": "第 {{count}} 步",
+ "sending": "傳送中",
"continue": "繼續討論",
"continueFailed": "沒能繼續討論,請再試一次",
"nextStep": "下一步:",
@@ -9111,7 +9176,7 @@
"missing": "這個安排已經讀不到了",
"start": "開始",
"dismiss": "不用了",
- "editHint": "想換人或改步驟,直接說",
+ "editHint": "點某一步可以換人",
"pauseNote": "每做完一步會停下來,等你點「繼續」。",
"superseded": "已更新",
"dismissed": "不用了",
@@ -9150,6 +9215,7 @@
"openTopic": "查看話題 · {{count}} 則回覆",
"topic": "話題",
"replies": "回覆",
+ "replyCount": "{{count}} 則回覆",
"replyPlaceholder": "回覆這則訊息,可用 @ 點名夥伴…",
"sendReply": "傳送回覆",
"addReaction": "新增表情回應",
@@ -9208,7 +9274,6 @@
"transfer": "轉讓群主",
"transferTitle": "將群主轉讓給 {{name}}?",
"transferHint": "對方成為群主,你將成為管理員。夥伴也可以擔任群主。",
- "remove": "移出群組",
"removeTitle": "將 {{name}} 移出群組?",
"removeHint": "該成員將無法繼續查看或傳送訊息;其夥伴也會退出。",
"addCompanion": "邀請我的夥伴",
@@ -9219,12 +9284,6 @@
"confirm": "確認",
"lastOwner": "請先將群主轉讓給其他成員,再退出或移除目前的群主。",
"conflict": "群組設定已更新,請重新整理後再試。",
- "replyMode": "沒有 @ 時",
- "speakingMode": "發言方式",
- "all": "夥伴都可接話",
- "mentioned": "僅被 @ 時接話",
- "auto": "同時發言",
- "sequential": "依序發言",
"unarchive": "取消封存",
"unarchiveHint": "恢復新訊息與夥伴執行。",
"archived": "本群已封存,可繼續查看歷史記錄。",
@@ -15932,7 +15991,6 @@
"suggested": "建議",
"candidate": "待確認",
"overdue": "已逾期",
- "today": "今天",
"next": "下一步",
"outcome": "完成條件",
"value": "為何值得處理",
@@ -15962,7 +16020,6 @@
"name": "標題",
"progress": "目前進度",
"link": "依據連結(選填)",
- "saved": "已儲存",
"page": "{{start}}–{{end}} / {{count}}",
"previous": "上一頁",
"following": "下一頁",
@@ -15974,17 +16031,16 @@
"close": "關閉",
"laterConflict": "稍後處理不延長真實期限",
"legacyEvidence": "舊記錄的完成依據待核實",
- "noPermission": "此來源未連接或尚未授權",
- "copy": "複製",
- "undo": "復原",
"history": "完成記錄",
- "clockNote": "僅日期按所示時區當天結束;確切時刻保留時區。",
"deleted": "已刪除",
"muted": "不再提示",
"deferred": "稍後處理",
"continue": "繼續",
- "addTime": "新增時間",
- "dateOnly": "僅日期"
+ "filter": "篩選",
+ "deleteConfirmTitle": "刪除這條待辦?",
+ "deleteConfirmBody": "刪除後不再顯示,同一問題也不會再被提起;可以在「已忽略 / 稍後」裡恢復。",
+ "muteConfirmTitle": "此問題不再提示?",
+ "muteConfirmBody": "同一問題以後不會再出現在待辦裡;可以在「已忽略 / 稍後」裡恢復。"
},
"codexResets": {
"retryReset": "重試重置",
diff --git a/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts b/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts
index 770ced0104..e8a870944e 100644
--- a/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts
+++ b/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts
@@ -1,6 +1,7 @@
import type { OrcaRole, Session } from '@/lib/ccAgent.types';
import { getSessionFor, orcaWorkflowsFor } from '@/lib/makerTransport';
import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
+import { botRouteForOwnedSession } from '@/features/bots/botSessionOwners';
export function isOrcaLeadSession(session: { orcaRole?: OrcaRole | null }): boolean {
return session.orcaRole === 'lead';
@@ -31,6 +32,24 @@ export function getSessionRouteOwnerId(route: string): string | null {
}
}
+/**
+ * The Bot page for a Bot's own chat (main task, history, channel chat), read from
+ * the in-memory profile projection only: no IPC wait on a click. A background
+ * task stays on its ordinary `/cc-agent/:id` route; an unloaded projection falls
+ * back to the ordinary route too (the notification entry reloads it first).
+ */
+async function loadedBotChatRoute(sessionId: string): Promise<string | null> {
+ try {
+ // Lazy: botStore is already loaded by the shell; this keeps lib free of its graph.
+ const store = await import('@/features/bots/botStore');
+ if (!store.hasLoadedBotProfiles()) return null;
+ const route = botRouteForOwnedSession(store.getBotProfiles(), sessionId);
+ return route && !route.startsWith('/cc-agent/') ? route : null;
+ } catch {
+ return null;
+ }
+}
+
/**
* Resolve the canonical chat route for a session before navigating from generic
* entry points such as notifications, deep links, and sidebar clicks. Orca lead
@@ -55,5 +74,9 @@ export async function resolveSessionRoute(
return workflow ? `/cc-agent/${workflow.leadSessionId}?worker=${sessionId}` : '/cc-agent';
}
+ // Notifications, task cards and the main sidebar agree on one page per task.
+ const botRoute = await loadedBotChatRoute(sessionId);
+ if (botRoute) return botRoute;
+
return `/cc-agent/${sessionId}`;
}
diff --git a/packages/maker-shared/src/botCollaboration.test.ts b/packages/maker-shared/src/botCollaboration.test.ts
index 420cf55cf0..cfe513854d 100644
--- a/packages/maker-shared/src/botCollaboration.test.ts
+++ b/packages/maker-shared/src/botCollaboration.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { placeBotTaskCardsAfterIntroduction, readBotCollaborationMeta } from './botCollaboration.js';
+import {
+ BOT_INTERJECTION_PREVIEW_MAX,
+ botInterjectionPreview,
+ placeBotTaskCardsAfterIntroduction,
+ readBotCollaborationMeta,
+} from './botCollaboration.js';
describe('task card placement', () => {
const classify = (s: string) =>
@@ -60,3 +65,25 @@ it('validates exact completion identities and deduplicates frozen attachments',
result: { runSequence: 1, status: 'completed', text: 'Saved', artifacts: [] } };
expect(readBotTaskResults([card, {}, card])).toEqual([card]);
});
+
+describe('interjection preview', () => {
+ const trace = { v: 1, role: 'interjection', delegationId: 'job', fromBotId: 'bot', fromBotName: 'Cindy',
+ toBotId: null, toBotName: 'Cindy', parentSessionId: 'parent', childSessionId: 'child', objective: 'Report' };
+ it('keeps old traces without a preview readable', () => {
+ expect(readBotCollaborationMeta(trace)).not.toHaveProperty('interjectionPreview');
+ });
+ it('keeps only a bounded first line, and only on interjection traces', () => {
+ expect(readBotCollaborationMeta({ ...trace, interjectionPreview: '\n 测试也要覆盖断网重连 \n私有第二行' })?.interjectionPreview)
+ .toBe('测试也要覆盖断网重连');
+ expect(Array.from(readBotCollaborationMeta({ ...trace, interjectionPreview: '长'.repeat(500) })!.interjectionPreview!))
+ .toHaveLength(BOT_INTERJECTION_PREVIEW_MAX);
+ expect(readBotCollaborationMeta({ ...trace, interjectionPreview: 42 })).not.toHaveProperty('interjectionPreview');
+ expect(readBotCollaborationMeta({ ...trace, interjectionPreview: ' ' })).not.toHaveProperty('interjectionPreview');
+ expect(readBotCollaborationMeta({ ...trace, role: 'delegation-request', interjectionPreview: 'x' }))
+ .not.toHaveProperty('interjectionPreview');
+ });
+ it('derives the persisted preview from the first non-empty line', () => {
+ expect(botInterjectionPreview('\n\n补充:带风险清单。\n读取 /workspace/AGENTS.md')).toBe('补充:带风险清单。');
+ expect(botInterjectionPreview('')).toBe('');
+ });
+});
diff --git a/packages/maker-shared/src/botCollaboration.ts b/packages/maker-shared/src/botCollaboration.ts
index f7ed88adca..4f8054f54d 100644
--- a/packages/maker-shared/src/botCollaboration.ts
+++ b/packages/maker-shared/src/botCollaboration.ts
@@ -42,6 +42,12 @@ export interface BotCollaborationMeta {
childSessionId: string | null;
/** 委派目标摘要,用于卡片折叠态文案。 */
objective: string;
+ /**
+ * 仅 `interjection`:补充消息的首行摘要(≤ BOT_INTERJECTION_PREVIEW_MAX 字),
+ * 让主聊天留痕说清楚「告诉了后台任务什么」。完整指令仍只保存在后台任务里;
+ * 旧记录没有此字段,留痕回退为通用文案。
+ */
+ interjectionPreview?: string;
result?: {
/** Task title at completion; older receipts fall back to the known task title. */
title?: string;
@@ -56,6 +62,15 @@ export interface BotCollaborationMeta {
};
}
+/** 补充消息留痕摘要的上限:只取首行,主聊天不复制完整指令。 */
+export const BOT_INTERJECTION_PREVIEW_MAX = 200;
+
+/** First non-empty line, bounded; never the full instruction. */
+export function botInterjectionPreview(text: string): string {
+ const line = text.split(/\r?\n/).map((value) => value.trim()).find(Boolean) ?? '';
+ return Array.from(line).slice(0, BOT_INTERJECTION_PREVIEW_MAX).join('');
+}
+
const ROLES = new Set<BotCollaborationRole>([
'delegation-request',
'delegation-result',
@@ -108,6 +123,10 @@ export function readBotCollaborationMeta(value: unknown): BotCollaborationMeta |
childSessionId,
...(receipt.result ? { result: receipt.result } : {}),
objective: raw.objective,
+ ...(raw.role === 'interjection' && typeof raw.interjectionPreview === 'string'
+ && botInterjectionPreview(raw.interjectionPreview)
+ ? { interjectionPreview: botInterjectionPreview(raw.interjectionPreview) }
+ : {}),
};
}
diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.ts
index 5dfb92cbac..0be4bfe10c 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -309,6 +309,12 @@ export interface BotGroupSummary {
lastMessage: BotGroupLastMessage | null;
/** Latest visible incoming message (Bot or another human), excluding self and runtime activity. Older hosts omit it. */
lastReplyAt?: number;
+ /**
+ * ISO `createdAt` of the newest (up to 99) messages from someone else — Bots and other people,
+ * not this account, notices, round/plan endings or system events — oldest first. Derived from
+ * the messages the host already read. Older hosts omit it.
+ */
+ incomingMessageTimes?: string[];
speakingBotIds: string[];
/** The organizer while it works out a plan (sidebar 「正在安排」). */
planningBotId: string | null;
diff --git a/packages/maker-shared/src/botTimeline.ts b/packages/maker-shared/src/botTimeline.ts
index 16ecf114e2..53630e6ff5 100644
--- a/packages/maker-shared/src/botTimeline.ts
+++ b/packages/maker-shared/src/botTimeline.ts
@@ -66,6 +66,51 @@ function isSameLocalDay(left: Date, right: Date): boolean {
);
}
+/**
+ * 群聊时间线的日期分隔:返回每个本地自然日第一条消息的时间。群聊不按五分钟切时间组,
+ * 一天只出一条日期线,具体时刻放在消息上(连续消息悬停可见)。
+ */
+export function collectBotTimelineDateDividers(
+ messages: readonly BotTimelineMessage[],
+): ReadonlyMap<string, number> {
+ const dividers = new Map<string, number>();
+ let previous: Date | null = null;
+ for (const message of messages) {
+ const timestamp = timestampOf(message.createdAt);
+ if (timestamp === null) continue;
+ const value = new Date(timestamp);
+ if (previous === null || !isSameLocalDay(previous, value)) dividers.set(message.clientId, timestamp);
+ previous = value;
+ }
+ return dividers;
+}
+
+/** Same local calendar day; invalid input never matches. */
+export function isSameBotTimelineDay(left: number, right: number): boolean {
+ if (!Number.isFinite(left) || !Number.isFinite(right)) return false;
+ return isSameLocalDay(new Date(left), new Date(right));
+}
+
+/** 「今天」「昨天」, else a short date (with the year when it is not this year). */
+export function formatBotTimelineDate(timestamp: number, locale: string, now = Date.now()): string {
+ const value = new Date(timestamp);
+ const current = new Date(now);
+ const yesterday = new Date(current.getFullYear(), current.getMonth(), current.getDate() - 1);
+ const relative = isSameLocalDay(value, current) ? 0 : isSameLocalDay(value, yesterday) ? -1 : null;
+ if (relative !== null) {
+ const text = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(relative, 'day');
+ return text.charAt(0).toLocaleUpperCase(locale) + text.slice(1);
+ }
+ return new Intl.DateTimeFormat(locale, value.getFullYear() === current.getFullYear()
+ ? { month: 'short', day: 'numeric', weekday: 'short' }
+ : { year: 'numeric', month: 'short', day: 'numeric' }).format(value);
+}
+
+/** Time of day only, for the time beside an author or in a merged line's gutter. */
+export function formatBotTimelineClock(timestamp: number, locale: string): string {
+ return new Intl.DateTimeFormat(locale, { hour: '2-digit', minute: '2-digit' }).format(new Date(timestamp));
+}
+
export function formatBotMessageGroupTime(
timestamp: number,
locale: string,