Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): show execution progress and open original tasks across devices
Chris35d1f77dfdd4
diff --git a/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx b/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsxindex c31a0191e1..c279cfe6ec 100644--- a/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx+++ b/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx@@ -6,8 +6,12 @@ import { BotGroupSettingsDrawer } from '../../../src/renderer/features/bots/BotGimport { BOT_GROUP_SETTINGS_PARAM } from '../../../src/renderer/features/bots/botGroupPresentation';import { refreshBotGroups } from '../../../src/renderer/features/bots/botGroupStore';import { ControlledBanner } from '../../../src/renderer/features/remote-device/ControlledBanner';+import { applyRemoteSessionActivity } from '../../../src/renderer/features/device-link/remoteSessionActivityStore';interface GroupData {+ workState?: 'thinking' | 'reading-file' | 'testing' | 'waiting' | 'stopping' | 'unknown';+ workRemote?: boolean;+ workParallel?: boolean;bodyAnswer?: boolean;name: string;members: Array<{ botId: string; name: string }>;@@ -262,7 +266,7 @@ function groupFrom(data: GroupData) {authorKind: 'user',authorBotId: null,authorName: '',- content: `Layout message ${i + 1}`,+ content: data.workState ? ["帮我检查群聊里的工作状态和任务入口。", "过程放在下面的动态区,完成后告诉我结果。"][i % 2] : `Layout message ${i + 1}`,mentions: { all: false, botIds: [] },noticeCode: null,planId: null,@@ -270,7 +274,9 @@ function groupFrom(data: GroupData) {createdAt: 1700000000000 + i,})),hasMoreBefore: false,- round: { status: 'idle', speakers: [], canContinue: false },+ round: data.workState ? { status: 'running', speakers: [{ botId: 'a', executionId: 'fixture-execution', sessionId: data.workRemote || data.workState === 'unknown' ? null : 'fixture-work', activity: 'reply', executionStatus: data.workState === 'waiting' ? 'needs_input' : 'running', startedAt: Date.now() - 83_000, stopping: data.workState === 'stopping' },+ ...(data.workParallel ? [{ botId: 'b', executionId: 'fixture-second', sessionId: 'fixture-second-work', activity: 'reply', startedAt: Date.now() - 41_000 }] : [])], canContinue: false }+ : { status: 'idle', speakers: [], canContinue: false },};}@@ -279,6 +285,7 @@ void mountPage({host: (ctx) => {const data = ctx.data as unknown as GroupData;const group = groupFrom(data);+ if (data.workRemote) applyRemoteSessionActivity('fixture-mac', { sessionId: 'fixture-work', phase: 'running', workingPhase: 'testing', compactDetail: '正在运行群聊回归检查', attention: false });let following = false;const followThread = async (input: { following: boolean }) => {following = input.following;@@ -293,7 +300,11 @@ void mountPage({return { ok: true, root, replies, hasMore: false, following };};return {+ agentIsland: { onSessionActivity: subscription('sessionActivity') },maker: {+ getCompanionCloudState: async () => ({ enabled: !!data.workRemote, selfDeviceId: null, humanActorId: null, actors: data.workRemote ? [{ id: 'a', externalId: 'a', name: 'Aster', avatar: null, homeDeviceId: 'fixture-mac', homeDevice: { deviceId: 'fixture-mac', name: 'Mac Studio', online: true, remoteControlEnabled: true, isSelf: false } }] : [], demotedBotIds: [] }),+ onCompanionCloudChanged: subscription('companionCloudChanged'),+ polishWorkingStatus: async () => null,listBotGroups: async () => ({ ok: true, groups: (ctx.data as unknown as GroupData).settings ? [group] : [] }),getBotGroup: async () => ({ ok: true, group }),onBotGroupChanged: subscription('botGroupChanged'),@@ -309,6 +320,11 @@ void mountPage({updateBotGroup: forbid('maker.updateBotGroup'),},deviceLink: {+ invoke: async (_device: string, _channel: string, args: Array<{ ref?: { collectionId?: string } }>) => args[0]?.ref?.collectionId === 'bot-groups' ? {+ ref: { collectionId: 'bot-groups', kind: 'bot-group', id: group.id },+ blocks: [{ primitive: 'bot-group-chat', data: { ...group, round: { ...group.round, speakers: [{ ...group.round.speakers[0], sessionId: 'fixture-work' }] } } }],+ } : { blocks: [] },+ onRemotePush: subscription('remotePush'),getState: async () => ({ controlledBy: [] }),onControlledState: subscription('controlledState'),revoke: forbid('deviceLink.revoke'),diff --git a/apps/desktop/scripts/fixtures/group-control/ui-page.mjs b/apps/desktop/scripts/fixtures/group-control/ui-page.mjsindex 0fbb410c5f..3c673b88e6 100644--- a/apps/desktop/scripts/fixtures/group-control/ui-page.mjs+++ b/apps/desktop/scripts/fixtures/group-control/ui-page.mjs@@ -21,6 +21,14 @@ export default {notCovered:'Sending, round control, real device-link control and revocation, pending interactions, plans and attachments; the bubbles case shows a task snapshot, not a live task; the sidebar is an empty frame',cases: {+ 'work-thinking': { about: 'Actual group work status, scenario data: thinking', data: { ...base, messages: 2, workState: 'thinking' } },+ 'work-tools': { about: 'Actual group work status, scenario data: command execution', data: { ...base, messages: 2, workState: 'testing' } },+ 'work-reading': { about: 'Actual group work status, scenario data: file reading', data: { ...base, messages: 2, workState: 'reading-file' } },+ 'work-waiting': { about: 'Actual group work status, scenario data: needs confirmation', data: { ...base, messages: 2, workState: 'waiting' } },+ 'work-stopping': { about: 'Actual group work status, scenario data: stop requested', data: { ...base, messages: 2, workState: 'stopping' } },+ 'work-unknown': { about: 'Remote work with no readable task: generic activity, no invented thinking', data: { ...base, messages: 2, workState: 'unknown' } },+ 'work-remote': { about: 'Authenticated remote target projection, scenario data (not a live device-link run)', data: { ...base, messages: 2, workState: 'testing', workRemote: true } },+ 'work-parallel': { about: 'Two concurrent execution rows, separate task entries and one group stop', data: { ...base, messages: 2, workState: 'testing', workParallel: true } },'body-answer': {about: '#6550: component body is readable; literal punctuation and surrounding Markdown are retained',viewport: { width: 720, height: 700 },@@ -96,6 +104,17 @@ export default {},async check(page, ui) {const definition = this.cases[ui.case];+ if (definition.data.workState) {+ const state = definition.data.workState;+ await ui.emit('sessionActivity', [{ sessionId: 'fixture-work', phase: 'running',+ workingPhase: ['thinking', 'reading-file', 'testing'].includes(state) ? state : 'processing',+ compactDetail: state === 'testing' ? '检查私聊与群聊的回归结果' : state === 'reading-file' ? '核对群聊状态与任务入口' : '',+ startedAtMs: Date.now() - 83_000, lastActivityAtMs: Date.now(), attention: false,+ gracefulStopState: state === 'stopping' ? 'requested' : 'none', source: 'live' }]);+ await page.getByTestId('bot-group-progress').first().waitFor();+ await ui.capture('work');+ return;+ }if (ui.case === 'body-answer') {const timeline = page.getByTestId('bot-group-timeline');assert.ok((await timeline.innerText()).includes('保留 <name>、*literal* 和 & 符号'));diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.tsindex fe8c9c7a6a..d860811372 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts@@ -80,6 +80,20 @@ describe('server group feature parity', () => {} as unknown as BotGroupChatServiceDeps;service = withChatServer({ listGroups: vi.fn(async () => ({ ok: true, groups: [] })), settleLaneTurn: vi.fn(async () => false), dispose: vi.fn() } as unknown as BotGroupChatService, deps);});+ // Unit regression: remote executions have no local lane but must keep their+ // exact identity and waiting/stopping state; concurrent turns cannot be deduped.+ it('retains remote waiting and stopping executions in the group projection', async () => {+ fixture.handle.mockImplementation((route: string) => route.endsWith('/executions') ? { body: [+ { ...execution, status: 'needs_input' },+ { ...execution, id: '40000000-0000-4000-8000-000000000002', status: 'stopping' },+ ] } : response(route));+ const result = await service.getGroup(roomId);+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.group.round.speakers.map(speaker => [speaker.executionId, speaker.executionStatus, speaker.sessionId])).toEqual([+ [execution.id, 'needs_input', null], ['40000000-0000-4000-8000-000000000002', 'stopping', null],+ ]);+ });afterEach(() => { service.dispose(); vi.useRealTimers(); vi.unstubAllEnvs(); fixture.config = ''; vi.clearAllMocks(); });const secondBotId = '20000000-0000-4000-8000-000000000002';const planId = '70000000-0000-4000-8000-000000000001';@@ -282,6 +296,45 @@ describe('server group feature parity', () => {expect(input.message).toContain('file-0');expect(input.attachments![0].id).toBe(messages[0].content[0].mediaId);});+ // Runtime regression: stopping a running group reply used to forget the lane+ // without acknowledging cancel, leaving every device spinning until lease expiry.+ it.each(['local', 'remote', 'retry'] as const)('acknowledges %s stop without publishing a reply or losing the task during retry', async origin => {+ arrange();+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ let state = 'running';+ let cancels = 0;+ const base = fixture.handle.getMockImplementation()!;+ fixture.handle.mockImplementation((route, method, data) => {+ if (route.endsWith('/executions')) return { body: [{ ...execution, status: state }] };+ if (route.endsWith('/control')) { state = 'stopping'; return { body: {} }; }+ if (route.endsWith(`/executions/${execution.id}`)) {+ if (data.action === 'heartbeat' && state === 'stopping') return { status: 409, body: { error: { code: 'STOP_REQUESTED' } } };+ if (data.action === 'cancel') {+ cancels++;+ if (origin === 'retry' && cancels === 1) return { status: 503, body: { error: { code: 'UNAVAILABLE' } } };+ state = 'cancelled';+ }+ }+ return base(route, method, data);+ });+ await vi.advanceTimersByTimeAsync(2000);+ expect(deps.dispatch).toHaveBeenCalledOnce();+ if (origin === 'remote') {+ state = 'stopping';+ await vi.advanceTimersByTimeAsync(13000);+ } else await service.stopRound(roomId);+ if (origin === 'retry') {+ expect(await service.getGroup(roomId)).toMatchObject({ group: { round: { speakers: [{ sessionId: 'lane', executionStatus: 'stopping' }] } } });+ await vi.advanceTimersByTimeAsync(16000);+ }+ expect(state).toBe('cancelled');+ expect(deps.abortLane).toHaveBeenCalledOnce();+ expect(deps.dispatch).toHaveBeenCalledOnce();+ const writes = fixture.handle.mock.calls.filter(([route, method]) => route.endsWith(`/executions/${execution.id}`) && method === 'POST');+ expect(writes.some(([, , data]) => data.action === 'complete')).toBe(false);+ expect(writes.filter(([, , data]) => data.action === 'cancel').every(([, , data]) => !data.content)).toBe(true);+ expect(await service.getGroup(roomId)).toMatchObject({ group: { round: { status: 'idle', speakers: [] } } });+ });it('negotiates broadcast and cancels the server deferred source on stop', async () => {arrange();const base = fixture.handle.getMockImplementation()!;diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex ba19aa364e..0e0f5ac978 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -100,7 +100,7 @@ interface Running {lane?: string;laneLookup?: Promise<void>;context?: ExecutionContext;- settlement?: { terminal: BotGroupLaneTerminal; payload?: Record<string, unknown>; reply?: { sourceText: string; text: string; attachments: ChatUploadAttachment[] }; fileReply?: Awaited<ReturnType<typeof prepareChatReplyFiles>>; retryAt: number; keepLease?: boolean };+ settlement?: { terminal: BotGroupLaneTerminal; cancelled?: boolean; payload?: Record<string, unknown>; reply?: { sourceText: string; text: string; attachments: ChatUploadAttachment[] }; fileReply?: Awaited<ReturnType<typeof prepareChatReplyFiles>>; retryAt: number; keepLease?: boolean };delivery?: Promise<void>;plan?: ServerPlan;workspace?: { workDir: string; branch: string | null; ownerSessionId: string | null };@@ -1349,14 +1349,17 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst 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));- // A companion answering in several Threads at once is still one speaker per activity; the one- // whose turn runs on this computer is shown, so its Session can be opened.+ // Keep execution identity across computers and concurrent threads. Only the executing+ // computer resolves a lane; authenticated peers retrieve it through the group resource.const speakers: BotGroupSpeaker[] = [];- for (const e of executions.filter(e => e.status === 'running')) {- const speaker = { botId: localBot(e.bot_id)?.id ?? e.bot_id, sessionId: running.get(e.id)?.sessionId ?? null, activity: e.plan_id ? 'step' as const : 'reply' as const };- const known = speakers.findIndex(other => other.botId === speaker.botId && other.activity === speaker.activity);- if (known < 0) speakers.push(speaker);- else if (!speakers[known]!.sessionId && speaker.sessionId) speakers[known] = speaker;+ for (const e of executions.filter(e => ['queued', 'running', 'needs_input', 'stopping'].includes(e.status))) {+ const run = running.get(e.id);+ const startedAt = run?.started ?? (e.created_at ? Date.parse(e.created_at) : undefined);+ const speaker: BotGroupSpeaker = { botId: localBot(e.bot_id)?.id ?? e.bot_id, sessionId: run?.sessionId || null,+ executionId: e.id, ...(Number.isFinite(startedAt) ? { startedAt } : {}), stopping: e.status === 'stopping',+ executionStatus: e.status as BotGroupSpeaker['executionStatus'],+ activity: e.plan_id ? 'step' : 'reply' };+ speakers.push(speaker);}// 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.@@ -1401,7 +1404,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDcreatedAt: Date.parse(s.room.created_at), updatedAt: Date.parse(s.room.updated_at ?? s.room.created_at),messages, executionFailures, ...(threadShareUpdates && Object.keys(threadShareUpdates).length ? { threadShareUpdates } : {}),...(shares ? { threadShareVersion: shares.version } : {}), ...(threadList ? { threads: threadList } : {}), hasMoreBefore: page.length === (o.limit ?? 100), plans,- round: { status: deciding || executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers,+ round: { status: deciding || executions.some(e => ['queued', 'running', 'needs_input', 'stopping'].includes(e.status)) ? 'running' : 'idle', speakers,othersActive: executions.some(e => ['queued', 'running', 'needs_input'].includes(e.status) && e.requester_id !== selfId&& !localBot(e.bot_id) && !s.members.some(m => m.id === e.bot_id && m.ownerActorId === selfId)), canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id && ordinaryExecution(e)) || s.messages.some(discussionSource)) && !executions.some(e => ['queued','running','stopping'].includes(e.status)) } };}@@ -1647,6 +1650,17 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD});}/** One execution gets one immutable terminal result, regardless of which boundary ends it. */+ async function cancelExecution(run: Running): Promise<void> {+ if (!current() || running.get(run.execution.id) !== run) return;+ if (!run.settlement?.cancelled) {+ run.settlement = { terminal: { sessionId: run.sessionId, activeInputClientId: run.clientId, outcome: 'done', resultText: '' }, cancelled: true, payload: {}, retryAt: 0 };+ run.releaseToolAuthority?.();+ if (run.sessionId) await deps.abortLane(run.sessionId).catch(() => undefined);+ }+ // Keep the lane resolvable while the existing cancel receipt is being delivered.+ // A transport failure retries this receipt, never the model or a completion reply.+ await deliverSettlement(run);+ }async function settleExecution(run: Running, terminal: BotGroupLaneTerminal, abort = false): Promise<void> {if (!current() || running.get(run.execution.id) !== run) return;if (!run.settlement) {@@ -1737,9 +1751,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// A single-speaker server never chains rounds, so there is nothing to continue....(singleSpeaker ? {} : { continueDiscussion: run.context?.kind !== 'member.joined' && !run.plan && !isBotGroupNoReplyText(text) }) };}- if (!current() || running.get(run.execution.id) !== run) return;- await updateExecution(run, pending.terminal.outcome === 'error' ? 'fail' : 'complete', pending.payload);- if (run.plan && deps.onStepSettled) {+ if (!current() || running.get(run.execution.id) !== run || run.settlement !== pending) return;+ await updateExecution(run, pending.cancelled ? 'cancel' : pending.terminal.outcome === 'error' ? 'fail' : 'complete', pending.payload);+ if (!pending.cancelled && run.plan && deps.onStepSettled) {const s = await snapshot(run.execution.conversation_id);const step = run.plan.steps[run.execution.plan_step!];const latest = (await api<ServerPlan[]>(`/conversations/${s.room.id}/plans?ids=${run.plan.id}`)).find(p => p.id === run.plan!.id);@@ -1748,6 +1762,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDbotName: step.botName, task: step.task, outcome: pending.terminal.outcome === 'error' ? 'failed' : 'done', planDone: latest?.status === 'done' }, scope);}} catch (error) {+ if (error instanceof ChatResponseError && error.message === 'STOP_REQUESTED' && !pending.cancelled) {+ // A remote stop can race the final reply. Retire the lease with cancel,+ // without publishing that reply or waiting for the server's lease expiry.+ run.settlement = { terminal: pending.terminal, cancelled: true, payload: {}, retryAt: 0 };+ run.releaseToolAuthority?.();+ if (run.sessionId) await deps.abortLane(run.sessionId).catch(() => undefined);+ return;+ }// Keep the result during transport/temporary service failures. A definitive// rejection (including revoked/expired leases) must never rerun the Agent// or post the private result under a new execution identity.@@ -1763,7 +1785,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDreturn;}} finally { run.delivery = undefined; }- if (running.get(run.execution.id) === run) {+ if (running.get(run.execution.id) === run && run.settlement === pending) {run.releaseToolAuthority?.();forgetRun(run);// Refresh both delivered results and local failures without waiting for an echo.@@ -2267,9 +2289,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (run.settlement) {// Auth/rate-limit waits need lease renewal; ordinary lost-response retries// preserve the existing receipt lookup without an intervening heartbeat.- if (!run.settlement.payload || run.settlement.keepLease) {+ if (!run.settlement.cancelled && (!run.settlement.payload || run.settlement.keepLease)) {try { await updateExecution(run, 'heartbeat'); }catch (error) {+ if (error instanceof ChatResponseError && error.message === 'STOP_REQUESTED') {+ await cancelExecution(run);+ return;+ }if (error instanceof ChatResponseError && !retryableResponse(error)) {if (running.get(run.execution.id) === run) {run.releaseToolAuthority?.();@@ -2295,7 +2321,11 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDawait settleExecution(run, { sessionId: run.sessionId, activeInputClientId: run.clientId,outcome: 'error', resultText: '', failureCode: 'RUNTIME_TIMEOUT' }, true);} else await updateExecution(run, 'heartbeat');- } catch {+ } catch (error) {+ if (error instanceof ChatResponseError && error.message === 'STOP_REQUESTED') {+ await cancelExecution(run);+ return;+ }// An in-flight heartbeat must not discard a result that became ready while// it was awaiting its response; retry the terminal operation for its receipt.if (!run.settlement && running.get(run.execution.id) === run) {@@ -2824,7 +2854,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDfor (const e of executions.filter(e => ['queued', 'running', 'needs_input'].includes(e.status) && !e.plan_id)) {await api(`/conversations/${room}/executions/${e.id}/control`, 'POST', { operationId: randomUUID(), action: 'stop' });const run = running.get(e.id);- if (run) { forgetRun(run); if (run.sessionId) await deps.abortLane(run.sessionId); }+ if (run) await cancelExecution(run);}changed(room); return { ok: true as const };}@@ -2849,7 +2879,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDtry { await api(`/conversations/${room}/executions/${e.id}/control`, 'POST', { operationId: randomUUID(), action: 'stop' }, asBot ? e.bot_id : everything && e.requester_id !== selfId ? asManager : undefined); }catch (error) { if (refused(error)) continue; throw error; }const run = running.get(e.id);- if (run) { forgetRun(run); if (run.sessionId) await deps.abortLane(run.sessionId); }+ if (run) await cancelExecution(run);}changed(room); return { ok: true as const };}),diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsxindex c6946d66fe..0d3eb47fd4 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx@@ -28,6 +28,7 @@ import { cn } from '@/lib/utils';*/import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type DragEvent } from 'react';import { ArrowLeft, CircleAlert, RefreshCcw, Settings2 } from 'lucide-react';+import { useBotGroupWorkTargets } from './useBotGroupWorkTargets';import { useTranslation } from 'react-i18next';import { useLocation, useNavigate, useParams } from 'react-router-dom';@@ -739,7 +740,7 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: booconst running = group?.round.status === 'running';// Several Bots think at once in a broadcast round's first circle; the key follows the set.- const speakingKey = running && group ? group.round.speakers.map((speaker) => `${speaker.botId}:${speaker.activity}`).join(',') : '';+ const speakingKey = running && group ? group.round.speakers.map((speaker) => (speaker.executionId ?? `${speaker.botId}:${speaker.activity}`)).join(',') : '';const lastRowKey = rows[rows.length - 1]?.id ?? '';const firstRealSequence = realMessages[0]?.sequence ?? 0;@@ -1057,12 +1058,14 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: booconst openPlan = group ? openBotGroupPlan({ openPlan: group.openPlan, plans }) : null;const runningStep = runningBotGroupPlanStep(openPlan);+ const workTargets = useBotGroupWorkTargets(group);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 }] : [];+ const target = speaker.executionId ? workTargets.get(speaker.executionId) : undefined;+ return member ? [{ ...speaker, member, displayName: botGroupMemberDisplayName(member), sessionId: speaker.sessionId || target?.sessionId || null, target }] : [];})- : []), [running, group, memberById]);+ : []), [running, group, memberById, workTargets]);const stepSpeaker = runningStep? speakers.find((speaker) => speaker.activity === 'step' && speaker.member.botId === runningStep.step.botId): undefined;@@ -1289,8 +1292,8 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boo) : null}{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} />))}+ ? <BotGroupSpeakerInteraction key={speaker.executionId ?? `${speaker.member.botId}:${speaker.activity}`} speaker={speaker} />+ : <BotGroupSpeakingLine key={speaker.executionId ?? `${speaker.member.botId}:${speaker.activity}`} speaker={speaker} />))}</div></div></div>diff --git a/apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx b/apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsxindex 696701c009..771912a971 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx@@ -1,12 +1,8 @@-/**- * 正在发言的伙伴此刻写到哪了:群专线(或分工 Session)在这台电脑上跑时,它的流式正文已经- * 在 makerChatStore 里(maker 事件按 sessionId 写入,不需要读历史),这里只取最后几行,- * 让群里像打字一样逐字出来。专线不在本机运行(服务器群的别的电脑在执行)时没有内容,- * 什么也不显示;正文可能还会变成静默标记 NO_REPLY,在那之前不显示。- */+/** Latest public progress in the current turn, including the note before a tool call.+ * Remote work uses the authenticated activity summary and opens the original task. */import { useCallback, useSyncExternalStore } from 'react';-import { makerChatStore } from '@/lib/makerChatStore';+import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';import { cn } from '@/lib/utils';import { isBotGroupNoReplyPrefix } from '../../../shared/botGroupChat';@@ -16,14 +12,34 @@ export function botGroupLiveTail(text: string, lines: number): string {return text.split('\n').map((line) => line.trim()).filter(Boolean).slice(-lines).join('\n');}+/** Keep the latest progress note visible while tools run; never revive an older turn,+ * private reply or reasoning block when streamingText is cleared between messages. */+export function botGroupWorkPreview(state: {+ streamingText: string;+ messages: readonly ChatMessage[];+ agentStatus: { startedAt: number | null };+}, lines: number): string {+ if (state.streamingText.trim()) return botGroupLiveTail(state.streamingText, lines);+ const since = state.agentStatus.startedAt;+ if (since === null) return '';+ for (let i = state.messages.length - 1; i >= 0; i--) {+ const message = state.messages[i]!;+ const createdAt = message.createdAt ? Date.parse(message.createdAt) : NaN;+ if (message.role !== 'assistant' || message.assistantPhase !== 'commentary'+ || message.botPrivateReply || message.failedSamplingAttempt || !Number.isFinite(createdAt) || createdAt < since) continue;+ return botGroupLiveTail(message.content, lines);+ }+ return '';+}+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 read = useCallback(() => botGroupWorkPreview(makerChatStore.getSnapshot(sessionId), 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)}>+ <div data-testid="bot-group-live-preview" 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>))}diff --git a/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx b/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsxindex a204b92ad5..42695187c6 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx@@ -1,15 +1,7 @@import { useNavigate } from 'react-router-dom';import { standardSessionRoute } from '@/lib/orcaSessionIdentity';-/**- * 群聊的「正在进行」:- *- * - 时间线末尾每位正在发言的伙伴一行扁平状态「LiZi 正在想…」,本机能读到流式正文时下面- * 跟最后两行(逐字出来的感觉);等确认时放确认卡。负责人还在判断要不要分工时写「正在安排…」。- * - 输入框上方的进行中条(不随时间线滚走):分工某一步在做,或某位伙伴说了超过三秒时出现,- * 写「第 k/n 步 · 谁 做什么 · 已做多久 · 当前动作」,带「看过程」(本机能读到这条专线时)- * 与「停止」。分工进行中它替代时间线末尾的发言行。- * - 顶栏右侧的一句状态:「Dash 正在做第 2 步」「Dash 正在说…」「LiZi 正在安排…」。- */+/** Group progress stays above the composer. Each execution opens its original standard+ * task, locally or on its authenticated home computer; confirmations stay inline. */import { useState } from 'react';import { Sparkles } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -19,6 +11,9 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTriggeimport { MENU_ITEM_CLASS } from '@/features/cc-agent/sidebar/menuStyles';import { cn } from '@/lib/utils';import { useAgentIslandActivity } from '@/state/agentIslandActivity';+import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';+import { readWorkingPhase } from '../../../shared/workingStatus';+import type { BotGroupWorkTarget } from './useBotGroupWorkTargets';import { isBotGroupNoReplyText, type BotGroupMemberView, type BotGroupSpeakerActivity, type BotGroupSummary } from '../../../shared/botGroupChat';import { BotAvatar } from './BotAvatar';import { BotGenerationLabel } from './BotGenerationLabel';@@ -32,6 +27,20 @@ export interface BotGroupLiveSpeaker {displayName: string;sessionId: string | null;activity: BotGroupSpeakerActivity;+ target?: BotGroupWorkTarget;+ startedAt?: number;+ stopping?: boolean;+ executionId?: string;+ executionStatus?: 'queued' | 'running' | 'needs_input' | 'stopping';+}++function useSpeakerActivity(speaker: BotGroupLiveSpeaker | undefined) {+ const local = useAgentIslandActivity(speaker?.target ? '' : speaker?.sessionId ?? '');+ const remote = useRemoteSessionActivity(speaker?.sessionId ?? '', speaker?.target?.deviceId);+ return speaker?.target ? remote ? {+ ...remote, workingPhase: readWorkingPhase(remote.workingPhase) ?? undefined,+ startedAtMs: speaker.startedAt ?? null, currentActionSummary: remote.compactDetail, gracefulStopState: 'none',+ } : null : local;}/** A speaker active this long earns the progress strip in plain discussion. */@@ -42,13 +51,19 @@ function pendingBot(speaker: BotGroupLiveSpeaker) {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. */+/** Brief initial status; longer work moves to the composer progress area. */export function BotGroupSpeakingLine({ speaker, showStatus = true }: { speaker: BotGroupLiveSpeaker; showStatus?: boolean }) {const { t } = useTranslation();const { member, sessionId, activity: speakerActivity } = speaker;const navigate = useNavigate();- const live = useAgentIslandActivity(sessionId ?? '');- const waiting = live?.phase === 'needs-interaction';+ const live = useSpeakerActivity(speaker);+ const waiting = live?.phase === 'needs-interaction' || speaker.executionStatus === 'needs_input';+ const [mountedAt] = useState(() => Date.now());+ const now = useBotGroupNow(true);+ const since = live?.startedAtMs ?? speaker.startedAt ?? mountedAt;+ if (speakerActivity !== 'planning' && now - since >= BOT_GROUP_PROGRESS_STRIP_DELAY_MS) {+ return <BotGroupSpeakerInteraction speaker={speaker} />;+ }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">@@ -59,7 +74,7 @@ export function BotGroupSpeakingLine({ speaker, showStatus = true }: { speaker:<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)]">+ <span className="flex min-w-0 items-center gap-1 text-[var(--text-secondary)]">{/* 呼吸只挂在 HTML 包装层上(DESIGN §7:常驻动画 compositor-only)。 */}<span aria-hidden className="session-status-breathing inline-flex shrink-0"><Sparkles size={12} />@@ -71,7 +86,8 @@ export function BotGroupSpeakingLine({ speaker, showStatus = true }: { speaker:) : (<BotGenerationLabelsessionId={sessionId ?? undefined}- phase={live?.workingPhase ?? 'thinking'}+ remote={speaker.target ? { deviceId: speaker.target.deviceId, botId: speaker.target.botId } : undefined}+ phase={live?.workingPhase ?? 'processing'}startedAt={live?.startedAtMs ?? null}/>)}@@ -80,11 +96,10 @@ export function BotGroupSpeakingLine({ speaker, showStatus = true }: { speaker:) : null}</p>) : null}- {sessionId ? <Button type="button" variant="secondary" tone="quiet" size="sm" compact className="self-start" onClick={() => navigate(standardSessionRoute(sessionId))}>+ {sessionId ? <Button type="button" variant="secondary" tone="quiet" size="sm" compact className="self-start" onClick={() => navigate(standardSessionRoute(sessionId, speaker.target?.deviceId))}>{t('bots.groupChat.progress.viewProcess')}</Button> : null}- {sessionId && live?.phase === 'running' ? <BotGroupLivePreview sessionId={sessionId} /> : null}- {sessionId ? <BotGroupPendingInteraction sessionId={sessionId} bot={pendingBot(speaker)} /> : null}+ {sessionId && !speaker.target ? <BotGroupPendingInteraction sessionId={sessionId} bot={pendingBot(speaker)} /> : null}</div></article>);@@ -92,7 +107,7 @@ export function BotGroupSpeakingLine({ speaker, showStatus = true }: { speaker:/** 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;+ if (!speaker.sessionId || speaker.target) return null;return (<div className="mt-3 pl-[38px]"><BotGroupPendingInteraction sessionId={speaker.sessionId} bot={pendingBot(speaker)} />@@ -104,21 +119,31 @@ export function BotGroupSpeakerInteraction({ speaker }: { speaker: BotGroupLiveS* 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,- canStopAll = false,- stopping,-}: {+export function BotGroupProgressStrip(props: BotGroupProgressStripProps) {+ const active = props.speakers.filter(speaker => speaker.activity !== 'planning');+ if (active.length <= 1) return <BotGroupSingleProgressStrip {...props} />;+ return <>{active.map((speaker, index) => <BotGroupSingleProgressStrip+ key={speaker.executionId ?? `${speaker.member.botId}:${speaker.activity}`}+ {...props} step={props.step?.step.botId === speaker.member.botId && speaker.activity === 'step' ? props.step : null} speakers={[speaker]} showStop={index === active.length - 1}+ />)}</>;+}++interface BotGroupProgressStripProps {step: (BotGroupRunningStep & { member: BotGroupMemberView | undefined; displayName: string }) | null;speakers: readonly BotGroupLiveSpeaker[];- /** Stops your own work; `all` also stops other people's (owners and admins only). */onStop: (scope?: 'all') => void;- /** Someone else's work is also running and you may stop it: Stop asks which. */canStopAll?: boolean;stopping: boolean;-}) {+}++function BotGroupSingleProgressStrip({+ step,+ speakers,+ onStop,+ canStopAll = false,+ stopping,+ showStop = true,+}: BotGroupProgressStripProps & { showStop?: boolean }) {const { t } = useTranslation();const [mountedAt] = useState(() => Date.now());const navigate = useNavigate();@@ -130,8 +155,9 @@ export function BotGroupProgressStrip({// pins the strip, so an organizer still deciding after a few seconds is not shown as talking.const lead = step ? stepSpeaker : speakers.find((speaker) => speaker.activity !== 'planning');const sessionId = lead?.sessionId ?? null;- const live = useAgentIslandActivity(sessionId ?? '');- const since = live?.startedAtMs ?? (step ? step.plan.updatedAt : mountedAt);+ const live = useSpeakerActivity(lead);+ const since = live?.startedAtMs ?? lead?.startedAt ?? (step ? step.plan.updatedAt : mountedAt);+ const isStopping = stopping || lead?.stopping === true || (!!live?.gracefulStopState && live.gracefulStopState !== 'none');const now = useBotGroupNow(true);if (!step && (!lead || now - since < BOT_GROUP_PROGRESS_STRIP_DELAY_MS)) return null;const member = step ? step.member : lead?.member;@@ -140,11 +166,11 @@ export function BotGroupProgressStrip({const workStep = step && step.plan.kind !== 'talk' ? step : null;// The Session's compact detail may still be the previous turn's silence marker (NO_REPLY);// that is not an action anyone should read.- const rawAction = live?.compactDetail?.trim() || '';+ const rawAction = live?.currentActionSummary?.trim() || live?.compactDetail?.trim() || '';const action = isBotGroupNoReplyText(rawAction) ? '' : rawAction;const canView = !!sessionId;return (- <div className="shrink-0 px-5 pt-2">+ <div data-testid="bot-group-work" className="shrink-0 px-5 pt-2"><divdata-testid="bot-group-progress"// Process opens the existing task page; the strip stays compact.@@ -159,26 +185,32 @@ export function BotGroupProgressStrip({</span>) : null}<span className="min-w-0 truncate">- {workStep ? ` · ${name} ${workStep.step.task}` : t('bots.groupChat.progress.speaking', { name })}+ {workStep ? ` · ${name} ${workStep.step.task}` : name}</span>+ {!workStep || isStopping || live?.phase === 'needs-interaction' || lead?.executionStatus === 'needs_input' ? <span className="min-w-0 truncate">+ {isStopping+ ? t('bots.groupChat.progress.stopping')+ : lead?.executionStatus === 'queued'+ ? t('bots.groupChat.progress.queued')+ : live?.phase === 'needs-interaction' || lead?.executionStatus === 'needs_input'+ ? t('bots.groupChat.waitingConfirm', { name: '' })+ : <BotGenerationLabel sessionId={sessionId ?? undefined} remote={lead?.target ? { deviceId: lead.target.deviceId, botId: lead.target.botId } : undefined} phase={live?.workingPhase ?? 'processing'} startedAt={live?.startedAtMs ?? null} />}+ </span> : null}<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 onClick={() => sessionId && navigate(standardSessionRoute(sessionId))}>+ <Button type="button" variant="secondary" tone="quiet" size="sm" compact onClick={() => sessionId && navigate(standardSessionRoute(sessionId, lead?.target?.deviceId))}>{t('bots.groupChat.progress.viewProcess')}</Button>) : null}- {canStopAll ? (+ {!showStop ? null : canStopAll ? (<DropdownMenu><DropdownMenuTrigger asChild>- <Button type="button" variant="secondary" tone="quiet" size="sm" compact loading={stopping} className="text-[var(--text-danger)]">+ <Button type="button" variant="secondary" tone="quiet" size="sm" compact loading={isStopping} className="text-[var(--text-danger)]">{t('bots.groupChat.progress.stop')}</Button></DropdownMenuTrigger>@@ -201,7 +233,7 @@ export function BotGroupProgressStrip({tone="quiet"size="sm"compact- loading={stopping}+ loading={isStopping}onClick={() => onStop()}className="text-[var(--text-danger)]">@@ -211,6 +243,9 @@ export function BotGroupProgressStrip({</span></div></div>+ {action ? <p data-testid="bot-group-work-action" className="mx-auto mt-1 max-w-[760px] truncate px-2 text-center text-13 leading-5 text-[var(--text-secondary)]" title={action}>{action}</p> : null}+ {lead?.target ? <p className="mt-1 text-center text-12 leading-5 text-[var(--text-secondary)]">{lead.target.deviceName}</p> : null}+ {sessionId && !lead?.target && live?.phase === 'running' ? <BotGroupLivePreview sessionId={sessionId} className="mx-auto mt-1 max-w-[760px] px-2" /> : null}</div>);}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsxindex 582acdca9b..c694ca9826 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx@@ -14,6 +14,8 @@ import { markBotRead, getBotLastReadAt, botGroupReadKey, resetBotReadStateForTesimport { botGroupAttachmentScope, botGroupThreadDraftKey } from '../botGroupAttachments';import { getBotGroupListSnapshot, refreshBotGroups, resetBotGroupStoreForTests } from '../botGroupStore';import { getBotGroupOutbox, getBotGroupOutboxPreviews, resetBotGroupOutboxForTests } from '../botGroupOutbox';+import { resetCompanionCloudStoreForTests } from '../companionCloudStore';+import { botGroupWorkPreview } from '../BotGroupLivePreview';import { BotGroupChatView } from '../BotGroupChatView';import { ControlledBanner, __resetControlledBannerForTests } from '../../remote-device/ControlledBanner';import type {@@ -54,6 +56,7 @@ const mocks = vi.hoisted(() => ({/** Live activity of the speaking Session (null = not running on this machine). */activity: null as null | { compactDetail: string; startedAtMs: number | null; phase: string },ownerGeneration: { dataOwnerId: 'account-a', generation: 1 },+ remoteInvoke: vi.fn(),reply: vi.fn(),shareToMain: vi.fn(),}));@@ -266,6 +269,8 @@ function renderView() {}beforeEach(() => {+ resetCompanionCloudStoreForTests();+ mocks.remoteInvoke.mockReset();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.@@ -308,6 +313,8 @@ beforeEach(() => {configurable: true,value: {deviceLink: {+ invoke: mocks.remoteInvoke,+ onRemotePush: () => () => {},getState: mocks.getControlledState,onControlledState: (callback: NonNullable<typeof mocks.controlledPush>) => {mocks.controlledPush = callback;@@ -1184,7 +1191,7 @@ describe('BotGroupChatView', () => {renderView();const speaking = await screen.findByTestId('bot-group-speaking');expect(speaking.textContent).toContain('咪咪');- expect(speaking.textContent).toContain('phase:thinking');+ expect(speaking.textContent).toContain('phase:processing');expect(screen.getByTestId('pending-interaction').textContent).toBe('lane-mimi');expect(screen.queryByRole('button', { name: 'bots.groupChat.timeline.continue' })).toBeNull();@@ -3226,7 +3233,7 @@ describe('Telegram / Slack-grade timeline', () => {}) });renderView();const strip = await screen.findByTestId('bot-group-progress');- expect(strip.textContent).toContain('bots.groupChat.progress.speaking');+ expect(strip.textContent).toContain('phase:processing');expect(strip.textContent).not.toContain('bots.groupChat.progress.step');});@@ -3948,3 +3955,39 @@ it('renders component body as readable text without changing the message', asyncexpect(body.textContent).not.toContain('"op":"create"');expect(reply.content).toBe(content);});++// Regression: tool boundaries clear streaming text; keep this turn's public progress,+// without reviving old turns, private replies or reasoning. Unit tier, no clock waits.+it('keeps only the current public progress note between tool calls', () => {+ const note = { clientId: 'public-progress', role: 'assistant', content: 'Checking the result', assistantPhase: 'commentary', createdAt: '2026-10-26T01:00:01Z' };+ const state = { streamingText: '', messages: [note], agentStatus: { startedAt: Date.parse('2026-10-26T01:00:00Z') } } as Parameters<typeof botGroupWorkPreview>[0];+ expect(botGroupWorkPreview(state, 2)).toBe('Checking the result');+ for (const patch of [{ botPrivateReply: true }, { failedSamplingAttempt: true }, { assistantPhase: 'analysis' }, { createdAt: '2026-10-25T01:00:00Z' }]) {+ expect(botGroupWorkPreview({ ...state, messages: [{ ...note, ...patch }] } as Parameters<typeof botGroupWorkPreview>[0], 2)).toBe('');+ }+ expect(botGroupWorkPreview({ ...state, streamingText: 'NO_REPLY' }, 2)).toBe('');+});++// Group work identity: the source computer returns two concurrent executions of the+// same companion. Open only the requested execution on its original host (unit tier).+it('opens the exact remote execution and leaves other members’ private tasks unavailable', async () => {+ resetCompanionCloudStoreForTests({ enabled: true, selfDeviceId: 'here', humanActorId: 'me', demotedBotIds: [], actors: [{+ id: 'actor-mimi', externalId: 'mimi', name: '咪咪', avatar: null, homeDeviceId: 'studio',+ homeDevice: { deviceId: 'studio', name: 'Studio', online: true, isSelf: false, remoteControlEnabled: true },+ }] });+ mocks.remoteInvoke.mockResolvedValue({ ref: { collectionId: 'bot-groups', kind: 'bot-group', id: 'g1' }, blocks: [{ primitive: 'bot-group-chat', data: {+ id: 'g1', round: { speakers: [{ executionId: 'other-thread', sessionId: 'wrong-lane' }, { executionId: 'this-turn', sessionId: 'correct-lane' }] },+ } }] });+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ speakingBotIds: ['mimi', 'xiaoman'], round: {+ status: 'running', canContinue: false, speakers: [+ { botId: 'mimi', activity: 'reply', executionId: 'this-turn', sessionId: null, startedAt: Date.now() - 10_000 },+ { botId: 'xiaoman', activity: 'reply', executionId: 'theirs', sessionId: null, startedAt: Date.now() - 10_000 },+ ],+ } }) });+ renderView();+ const process = await screen.findByRole('button', { name: 'bots.groupChat.progress.viewProcess' });+ expect(screen.getAllByTestId('bot-group-progress')).toHaveLength(2);+ fireEvent.click(process);+ expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/correct-lane?device=studio');+ expect(mocks.remoteInvoke.mock.calls.every(([device]) => device === 'studio')).toBe(true);+});diff --git a/apps/desktop/src/renderer/features/bots/useBotGroupWorkTargets.ts b/apps/desktop/src/renderer/features/bots/useBotGroupWorkTargets.tsnew file mode 100644index 0000000000..f817498eeb--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/useBotGroupWorkTargets.ts@@ -0,0 +1,78 @@+import { useEffect, useMemo, useState } from 'react';+import { REMOTE_RESOURCE_GET_CHANNEL, REMOTE_RESOURCE_CHANGED_CHANNEL, parseRemoteResourceChangedPayload } from '@cindy/device-link';+import type { BotGroupDetail, BotGroupSpeaker } from '../../../shared/botGroupChat';+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';+import { useCompanionCloud } from './companionCloudStore';++export interface BotGroupWorkTarget {+ sessionId: string;+ deviceId: string;+ deviceName: string;+ botId: string;+}++const EMPTY_TARGETS: ReadonlyMap<string, BotGroupWorkTarget> = new Map();++/** Resolve only our companions, through the existing authenticated group resource.+ * Execution IDs prevent another thread/turn (or the companion's private chat) being opened.+ * Other members' computers are never queried. No work text is sent to Chat Server.+ */+export function useBotGroupWorkTargets(group: BotGroupDetail | null): ReadonlyMap<string, BotGroupWorkTarget> {+ const cloud = useCompanionCloud();+ const candidates = useMemo(() => (group?.round.speakers ?? []).flatMap(speaker => {+ if (speaker.sessionId || !speaker.executionId) return [];+ const actor = cloud.actors.find(actor => actor.id === speaker.botId || actor.externalId === speaker.botId);+ const home = actor?.homeDevice;+ return home && !home.isSelf && home.online && home.remoteControlEnabled+ ? [{ executionId: speaker.executionId, deviceId: home.deviceId, deviceName: home.name, botId: actor.externalId }] : [];+ }), [group?.round.speakers, cloud]);+ const key = JSON.stringify([getDataOwnerGeneration(), group?.id, candidates]);+ const [resolved, setResolved] = useState<{ key: string; targets: ReadonlyMap<string, BotGroupWorkTarget> }>({ key: '', targets: new Map() });+ useEffect(() => {+ if (!group || candidates.length === 0) return;+ const owner = getDataOwnerGeneration();+ let cancelled = false;+ let reading = false;+ let queued = false;+ const current = () => !cancelled && isDataOwnerGenerationCurrent(owner);+ const read = async () => {+ if (!current()) return;+ if (reading) { queued = true; return; }+ reading = true;+ const targets = new Map<string, BotGroupWorkTarget>();+ await Promise.all([...new Set(candidates.map(candidate => candidate.deviceId))].map(async deviceId => {+ try {+ const resource = await window.electronAPI.deviceLink.invoke(deviceId, REMOTE_RESOURCE_GET_CHANNEL, [{+ client: { protocolVersion: 1, primitives: ['bot-group-chat'] },+ ref: { collectionId: 'bot-groups', kind: 'bot-group', id: group.id },+ }]) as { ref?: { id?: string }; blocks?: Array<{ primitive?: string; data?: { id?: string; round?: { speakers?: BotGroupSpeaker[] } } }> };+ const data = resource?.blocks?.find(block => block.primitive === 'bot-group-chat')?.data;+ if (resource?.ref?.id !== group.id || data?.id !== group.id || !Array.isArray(data.round?.speakers)) return;+ for (const candidate of candidates.filter(candidate => candidate.deviceId === deviceId)) {+ const speaker = data.round.speakers.find(speaker => speaker.executionId === candidate.executionId);+ if (typeof speaker?.sessionId === 'string' && speaker.sessionId) targets.set(candidate.executionId, {+ sessionId: speaker.sessionId, deviceId, deviceName: candidate.deviceName, botId: candidate.botId,+ });+ }+ } catch { /* Unknown/old/offline hosts leave the truthful generic status and group stop available. */ }+ }));+ if (current()) setResolved({ key, targets });+ reading = false;+ if (queued) { queued = false; void read(); }+ };+ void read();+ const off = window.electronAPI.deviceLink.onRemotePush((push, stamp) => {+ if (!isDeviceLinkRemotePushCurrent(push, stamp) || push.channel !== REMOTE_RESOURCE_CHANGED_CHANNEL+ || !candidates.some(candidate => candidate.deviceId === push.deviceId)) return;+ const changed = parseRemoteResourceChangedPayload(push.payload);+ if (!changed || changed.collectionId !== 'bot-groups' || (changed.resourceRefs?.length && !changed.resourceRefs.some(ref => ref.id === group.id))) return;+ void read();+ });+ const offReopened = window.electronAPI.deviceLink.onPeerLinkReopened?.(event => {+ if (candidates.some(candidate => candidate.deviceId === event.deviceId)) void read();+ });+ return () => { cancelled = true; off(); offReopened?.(); };+ }, [key]); // key contains the exact group, execution and reachable home identities.+ return resolved.key === key ? resolved.targets : EMPTY_TARGETS;+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 946fbe7e8b..42c682fd8a 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9493,6 +9493,8 @@"viewProcess": "Show work","hideProcess": "Hide work","stop": "Stop",+ "stopping": "Stopping…",+ "queued": "Waiting to start…","stopMine": "Stop Mine","stopAll": "Stop All","stopAllHint": "Includes other people’s requests"diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 4f6beedfe0..d4f0130ac8 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9459,6 +9459,8 @@"viewProcess": "経過を見る","hideProcess": "経過を閉じる","stop": "停止",+ "stopping": "停止中…",+ "queued": "開始待ち…","stopMine": "自分の依頼を停止","stopAll": "すべて停止","stopAllHint": "他の人の依頼も含みます"diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex df8840ac90..9429e9cfdc 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9459,6 +9459,8 @@"viewProcess": "과정 보기","hideProcess": "과정 접기","stop": "중지",+ "stopping": "중지 중…",+ "queued": "시작 대기 중…","stopMine": "내 요청 중지","stopAll": "모두 중지","stopAllHint": "다른 사람의 요청도 포함"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 527c8e1ccc..9a3487f2f0 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9459,6 +9459,8 @@"viewProcess": "看过程","hideProcess": "收起过程","stop": "停止",+ "stopping": "正在停止…",+ "queued": "等待开始…","stopMine": "停止我发起的","stopAll": "全部停止","stopAllHint": "包括其他人发起的"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 9a36a0369a..7483e6b81f 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9459,6 +9459,8 @@"viewProcess": "看過程","hideProcess": "收起過程","stop": "停止",+ "stopping": "正在停止…",+ "queued": "等待開始…","stopMine": "停止我發起的","stopAll": "全部停止","stopAllHint": "包括其他人發起的"diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsxindex a51e8813af..877e0465c4 100644--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx@@ -125,6 +125,7 @@ vi.mock('lucide-react-native', () => Object.fromEntries(vi.mock('@/theme', async () => ({...await import('@/theme/tokens'), useThemedStyles: (makeStyles: any) => makeStyles({}), useTheme: () => ({ colors: {} }), monoFont: 'mono',}));+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ getPresenceAvailability: () => true }) }));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({user: { id: 'owner' }, accountGeneration: 1, getAccessToken: async () => 'token', apiFetch: async () => ({}),}) }));diff --git a/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsx b/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsxindex 37f585eb3a..1c657770b1 100644--- a/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsx@@ -65,8 +65,8 @@ it('follows the speaking lane while focused and seeds its pending prompts', asynexpect(h.subscribe).toHaveBeenCalledWith(expect.stringMatching(/^bot-group-speaker:s1:focus:/), 'mac', ['session:s1']);expect(h.invoke).toHaveBeenCalledWith('mac', 'maker:get-pending-interactions', ['s1']);expect(h.setPending).toHaveBeenCalledWith('s1', [{ request: { requestId: 'r1' } }], { deviceId: 'mac' });- // No live phase yet: a reply reads 「正在思考…」.- expect(node.textContent).toContain('copy:thinking');+ // No observed phase must not falsely claim thinking.+ expect(node.textContent).toContain('copy:processing');await act(async () => root.unmount());expect(h.unsubscribe).toHaveBeenCalledWith(expect.stringMatching(/^bot-group-speaker:s1:focus:/), 'mac', ['session:s1']);root = createRoot(node);diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.tsindex aed21db3ec..8a9f4c8f4d 100644--- a/apps/mobile/src/__tests__/chatServerClient.test.ts+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts@@ -213,7 +213,7 @@ describe('direct Chat Server client', () => {});it('falls back only for a missing endpoint on an older server', async () => {const source = message(20);- const request = vi.fn().mockResolvedValueOnce(snapshot()).mockResolvedValueOnce([source])+ const request = vi.fn().mockResolvedValueOnce(snapshot()).mockResolvedValueOnce([source]).mockResolvedValueOnce([]).mockRejectedValueOnce(Object.assign(new Error('NOT_FOUND'), { status: 404 })).mockResolvedValueOnce([{ id: id(30), source_message_id: source.id, bot_id: id(10), epoch: 1, status: 'failed', failure_code: 'AUTH_REQUIRED' }]);const page = await createChatServerClient(request).load(id(1));@@ -253,13 +253,13 @@ describe('direct Chat Server client', () => {});it('opens and paginates main history, preserving exact sequence cursors and author identity', async () => {const messages = Array.from({ length: 100 }, (_, n) => message(200 - n));- const request = vi.fn().mockResolvedValueOnce(snapshot()).mockResolvedValueOnce(messages).mockResolvedValueOnce([])+ const request = vi.fn().mockResolvedValueOnce(snapshot()).mockResolvedValueOnce(messages).mockResolvedValueOnce([]).mockResolvedValueOnce([]).mockResolvedValueOnce([message(100)]).mockResolvedValueOnce([]).mockResolvedValueOnce([]);const client = createChatServerClient(request);const page = await client.load(id(1));expect(page.before).toBe(messages.at(-1)!.seq);const older = await client.older(id(1), page);- expect(request.mock.calls[3][0]).toBe(`/conversations/${id(1)}/messages?limit=100&before=${messages.at(-1)!.seq}`);+ expect(request.mock.calls[4][0]).toBe(`/conversations/${id(1)}/messages?limit=100&before=${messages.at(-1)!.seq}`);expect(older.before).toBeNull();const view = chatGroupView(older, id(11));expect(view.messages).toHaveLength(101);@@ -341,7 +341,7 @@ describe('direct Chat Server client', () => {it('reauthorizes and replaces loaded older history on refresh instead of retaining deleted text', async () => {const recent = Array.from({ length: 100 }, (_, n) => message(200 - n));const request = vi.fn().mockResolvedValueOnce(snapshot()).mockResolvedValueOnce(recent)- .mockResolvedValueOnce([{ ...message(100), content: [{ type: 'text', text: 'edited' }] }]).mockResolvedValueOnce([]).mockResolvedValueOnce([]);+ .mockResolvedValueOnce([{ ...message(100), content: [{ type: 'text', text: 'edited' }] }]).mockResolvedValueOnce([]).mockResolvedValueOnce([]).mockResolvedValueOnce([]);const page = await createChatServerClient(request).load(id(1), message(100).seq);expect(chatGroupView(page, id(10)).messages[0].content).toBe('edited');expect(request.mock.calls[2][0]).toContain(`before=${message(101).seq}`);@@ -404,3 +404,38 @@ describe('group lifecycle contract', () => {expect(request).toHaveBeenLastCalledWith(`/conversations/${id(1)}/list-state`, 'POST', { operationId: 'fixture-hide', hidden: true, expectedRevision: 0 });});});++// Missing mobile stop path: preserve server revision and actor ownership; unit tier.+it('stops my requests and companions without stopping another member’s work', async () => {+ const ownBot = { ...snapshot().members[0], id: id(12), kind: 'bot', ownerActorId: id(11) };+ const planId = id(40);+ const execution = (n: number, bot: number, requester: number, plan_id: string | null = null) => ({ id: id(n), bot_id: id(bot), requester_id: id(requester), status: 'running', plan_id });+ const request = vi.fn(async (path: string, method?: string) => {+ if (method === 'POST') return {};+ if (path === '/me') return { actor: { id: id(11), kind: 'human' } };+ if (path.endsWith('/snapshot')) return { ...snapshot(), members: [...snapshot().members, ownBot] };+ if (path.endsWith('/plans')) return [{ id: planId, creator_id: id(11), status: 'running', revision: 7 }];+ if (path.endsWith('/executions')) return [execution(30, 12, 10), execution(31, 13, 11), execution(32, 13, 10), execution(33, 12, 11, planId)];+ throw new Error(path);+ });+ await createChatServerClient(request as any).stop(id(1), 'stop-operation');+ const writes = request.mock.calls.filter(([, method]) => method === 'POST');+ expect(writes).toEqual([+ [`/conversations/${id(1)}/plans/${planId}`, 'POST', { operationId: `stop-operation:plan:${planId}`, expectedRevision: 7, action: 'stop' }],+ [`/conversations/${id(1)}/executions/${id(30)}/control`, 'POST', { operationId: `stop-operation:execution:${id(30)}`, action: 'stop' }, id(12)],+ [`/conversations/${id(1)}/executions/${id(31)}/control`, 'POST', { operationId: `stop-operation:execution:${id(31)}`, action: 'stop' }, undefined],+ ]);+});++it('projects waiting and stopping executions without inventing task IDs or losing concurrent turns', () => {+ const common = { source_message_id: id(20), bot_id: id(12), epoch: 1 };+ const page = { snapshot: snapshot(), messages: [], before: null, executions: [+ { ...common, id: id(30), status: 'needs_input' }, { ...common, id: id(31), status: 'stopping' },+ { ...common, id: id(32), status: 'succeeded' },+ ] };+ const view = chatGroupView(page, id(11));+ expect(view.round.status).toBe('running');+ expect(view.round.speakers.map(speaker => [speaker.executionId, speaker.executionStatus, speaker.sessionId])).toEqual([+ [id(30), 'needs_input', null], [id(31), 'stopping', null],+ ]);+});diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.tsindex 90a0d6658b..0bc24fd3eb 100644--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@ -30,7 +30,8 @@ export interface ChatExecutionFailure {id: string; conversation_id?: string; source_message_id: string; bot_id: string; epoch: number; status?: string;failure_code?: unknown; updated_at?: string; plan_id?: string | null;}-export interface ChatPage { threadRootId?: string; snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null; failures?: ChatExecutionFailure[] }+export interface ChatExecution extends ChatExecutionFailure { requester_id?: string; created_at?: string; status: string }+export interface ChatPage { threadRootId?: string; snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null; failures?: ChatExecutionFailure[]; executions?: ChatExecution[] }/** `actorId` acts as one of the account's own actors (Chat Server `X-Chat-Actor`). */export type ChatRequest = <T>(path: string, method?: 'GET' | 'POST' | 'PATCH', body?: unknown, actorId?: string, signal?: AbortSignal) => Promise<T>;/** An actor the account owns; a companion's `externalId` is its bot id on every computer. */@@ -215,6 +216,11 @@ export function chatGroupView(page: ChatPage, selfId: string, actors: readonly Cconst member = members.find(candidate => candidate.id === failure.botId);return [{ ...failure, botName: member ? memberName(member, ownerMembers) : '' }];});+ const executions = (page.executions ?? []).filter(row => ['queued', 'running', 'needs_input', 'stopping'].includes(row.status));+ const speakers = executions.map(row => ({ botId: row.bot_id, sessionId: null, executionId: row.id,+ ...(row.created_at && Number.isFinite(Date.parse(row.created_at)) ? { startedAt: Date.parse(row.created_at) } : {}),+ executionStatus: row.status as 'queued' | 'running' | 'needs_input' | 'stopping', stopping: row.status === 'stopping',+ activity: row.plan_id ? 'step' as const : 'reply' as const }));return { id: room.id, conversationKind: room.kind === 'direct' ? 'direct' : 'group',name: room.kind === 'direct' ? active.filter(member => member.id !== selfId).map(member => memberName(member, [])).join(', ') || room.name : room.name,serverBacked: true, supportsGroupLeave: room.kind !== 'direct', dissolvedAt: room.dissolved_at ?? null, archived: room.archived, selfActorId: selfId,@@ -224,8 +230,8 @@ export function chatGroupView(page: ChatPage, selfId: string, actors: readonly CorganizerBotId: room.organizer_id ?? null, projectDir: null, projectDirName: null,createdAt: Date.parse(room.created_at), updatedAt: Date.parse(room.updated_at),lastMessage: last ? { authorKind: last.authorKind, authorName: last.authorName, preview: mobileMarkdownPreviewText(botGroupMessageSummaryText(last)).slice(0, 80), createdAt: last.createdAt } : null,- speakingBotIds: [], planningBotId: null, openPlan: null, plans: [], messages: projectBotGroupExecutionFailures(messages, failures),- hasMoreBefore: page.before !== null, round: { status: 'idle', speakers: [], canContinue: false }, supportsAttachments: false };+ speakingBotIds: speakers.map(speaker => speaker.botId), planningBotId: null, openPlan: null, plans: [], messages: projectBotGroupExecutionFailures(messages, failures),+ hasMoreBefore: page.before !== null, round: { status: speakers.length ? 'running' : 'idle', speakers, canContinue: false }, supportsAttachments: false };}export function createChatServerClient(request: ChatRequest, personalList = createConversationListState()) {@@ -417,7 +423,36 @@ export function createChatServerClient(request: ChatRequest, personalList = creaconst root = await request<ChatMessage>(`/conversations/${room}/messages/${chatId(threadRootId)}`);messages.push(root);}- return { snapshot, messages, before, ...(threadRootId ? { threadRootId } : {}), failures: await failures(room, messages) };+ // Use the same execution snapshot for running status and stop controls.+ const executions = await request<ChatExecution[]>(`/conversations/${room}/executions`);+ return { snapshot, messages, before, ...(threadRootId ? { threadRootId } : {}), failures: await failures(room, messages),+ ...(Array.isArray(executions) ? { executions } : {}) };+ },+ async stop(roomId: string, operationId: string) {+ const room = chatId(roomId);+ const self = await identity();+ const snapshot = await request<ChatSnapshot>(`/conversations/${room}/snapshot`);+ const ownBots = new Set(snapshot.members.filter(member => member.state === 'joined' && member.kind === 'bot' && member.ownerActorId === self).map(member => member.id));+ const plans = await request<Array<{ id: string; status: string; creator_id: string; revision: number }>>(`/conversations/${room}/plans`);+ const stoppedPlans = new Set<string>();+ const refused = (error: unknown) => !!error && typeof error === 'object' && 'status' in error && [403, 404, 409].includes(Number(error.status));+ for (const plan of plans.filter(plan => plan.creator_id === self && ['proposed', 'running', 'waiting'].includes(plan.status))) {+ try {+ await request(`/conversations/${room}/plans/${chatId(plan.id)}`, 'POST', { operationId: `${operationId}:plan:${plan.id}`, expectedRevision: plan.revision, action: 'stop' });+ stoppedPlans.add(plan.id);+ } catch (error) { if (!refused(error)) throw error; }+ }+ const executions = await request<ChatExecution[]>(`/conversations/${room}/executions`);+ for (const execution of executions.filter(execution => ['queued', 'running', 'needs_input'].includes(execution.status) && !(execution.plan_id && stoppedPlans.has(execution.plan_id)))) {+ const asBot = execution.requester_id !== self && ownBots.has(execution.bot_id);+ if (execution.requester_id !== self && !asBot) continue;+ try {+ await request(`/conversations/${room}/executions/${chatId(execution.id)}/control`, 'POST',+ { operationId: `${operationId}:execution:${execution.id}`, action: 'stop' }, asBot ? execution.bot_id : undefined);+ } catch (error) {+ if (!refused(error)) throw error;+ }+ }},async older(roomId: string, page: ChatPage): Promise<ChatPage> {if (!page.before) return page;diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.tsindex 60ce9ec3be..76b090a835 100644--- a/apps/mobile/src/chat/useChatServer.ts+++ b/apps/mobile/src/chat/useChatServer.ts@@ -268,6 +268,11 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot} finally { olderPending.current = false; if (valid()) setState(old => ({ ...old, loadingOlder: false })); }};const act = async (action: BotGroupRemoteActionId, input?: Record<string, unknown>): Promise<RemoteActionInvokeResponse> => {+ if (action === 'stop') {+ const operationId = (await import('expo-crypto')).randomUUID();+ try { await api.client.stop(groupId, operationId); } finally { if (valid()) reload(); }+ return { effects: [] };+ }if (action === 'dissolve' || action === 'leave' || action === 'hide') {const operationId = (await import('expo-crypto')).randomUUID();if (action === 'hide') {diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.jsonindex 773617f382..7dc1a754df 100644--- a/apps/mobile/src/i18n/locales/en/groupChat.json+++ b/apps/mobile/src/i18n/locales/en/groupChat.json@@ -141,6 +141,7 @@"allDone": "All done"},"speaking": {+ "stopping": "Stopping…","planning": "Splitting the work…","step": "Working on it…"},diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.jsonindex 12655f629c..90ac26fb6b 100644--- a/apps/mobile/src/i18n/locales/ja/groupChat.json+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json@@ -141,6 +141,7 @@"allDone": "すべて完了"},"speaking": {+ "stopping": "停止中…","planning": "役割分担を考えています…","step": "作業中…"},diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.jsonindex 2c1087f444..174469fd3b 100644--- a/apps/mobile/src/i18n/locales/ko/groupChat.json+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json@@ -141,6 +141,7 @@"allDone": "모두 완료"},"speaking": {+ "stopping": "중지 중…","planning": "역할을 나누는 중…","step": "작업 중…"},diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.jsonindex afbb4460b3..7e30fcbd48 100644--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json@@ -141,6 +141,7 @@"allDone": "都做完了"},"speaking": {+ "stopping": "正在停止…","planning": "正在安排…","step": "正在做…"},diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.jsonindex d56355beb2..39ae9c1bbf 100644--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json@@ -141,6 +141,7 @@"allDone": "都做完了"},"speaking": {+ "stopping": "正在停止…","planning": "正在安排…","step": "正在做…"},diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsxindex b7d6d892c3..a3f9f28a81 100644--- a/apps/mobile/src/session/BotGroupChatScreen.tsx+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx@@ -101,7 +101,7 @@ import {type BotGroupPlanCardAction,} from './BotGroupPlan';import { BotGroupSettingsSheet } from './BotGroupSettingsSheet';-import { BotGroupSpeakerRow } from './BotGroupSpeakerRow';+import { BotGroupWorkArea } from './BotGroupWorkArea';import { botGroupActionErrorText } from './botGroupCopy';import { keyboardAvoidingBehaviorForPlatform } from './mobileNativeShellLayout';import type { ResolveRemoteMediaFn } from './remoteMedia';@@ -573,6 +573,8 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n<View style={styles.flex}><BotGroupQuote display={resolveBotGroupQuote(replyTo, group.messages)} onPress={() => locateMessage(replyTo.messageId)} /></View><MainWindowActionButton density="compact" action={{ label: t('message.quote.remove'), onPress: () => setReplyTo(null), testID: 'botGroup.cancelReply' }} /></View> : null}+ <BotGroupWorkArea group={group} deviceId={deviceId} online={chat.online} identityFor={identityFor}+ onError={message => { if (message) Alert.alert(message); }} /><BotGroupComposer members={group.members} identityFor={identityFor} deviceId={deviceId} online={chat.online && !group.archived && !group.dissolvedAt}focusKey={replyTo?.messageId}running={group.round.status === 'running'} planState={botGroupComposerPlanState(openBotGroupPlan(group), group.replyMode)}@@ -653,9 +655,6 @@ export function BotGroupTimeline({const mentionLabels = useMemo(() => [allLabel, ...group.members.map((member) => member.name)], [allLabel, group.members]);const running = group.round.status === 'running';const memberById = new Map(group.members.map((member) => [member.botId, member]));- const speakers = running- ? group.round.speakers.filter((speaker) => memberById.has(speaker.botId))- : [];const pendingFor = (planId: string | null) => planId && planPending?.planId === planId ? planPending.action : null;return <>{group.hasMoreBefore && loadOlder ? <MainWindowActionButton action={{ label: t('groupChat.server.loadOlder'), busy: loadingOlder, onPress: loadOlder, testID: 'botGroup.loadOlder' }} /> : group.hasMoreBefore ? <Text style={styles.olderNote} testID="botGroup.olderOnComputer">{t('groupChat.timeline.olderOnComputer')}</Text> : null}@@ -704,16 +703,7 @@ export function BotGroupTimeline({onEnd={() => onPlanAction('dismiss', openPlan.id)} /></View> : null}</AnimatedContentHeight>- <AnimatedContentHeight open={speakers.length > 0}>- <View style={[styles.item, (messages.length > 0 || group.hasMoreBefore || !!(openPlan && followUp)) && { paddingTop: spacing.lg }]}>- {speakers.map((speaker) => {- const member = memberById.get(speaker.botId)!;- return <BotGroupSpeakerRow key={speaker.botId} deviceId={deviceId} online={online}- identity={identityFor(member.botId, member.name)} sessionId={speaker.sessionId} activity={speaker.activity}- onError={onInteractionError} />;- })}- </View>- </AnimatedContentHeight>+</>;}diff --git a/apps/mobile/src/session/BotGroupSpeakerRow.tsx b/apps/mobile/src/session/BotGroupSpeakerRow.tsxindex d076e582fb..e157f7d98c 100644--- a/apps/mobile/src/session/BotGroupSpeakerRow.tsx+++ b/apps/mobile/src/session/BotGroupSpeakerRow.tsx@@ -11,7 +11,7 @@ import { StyleSheet, View } from 'react-native';import { useFocusEffect, useRouter } from 'expo-router';import { useTranslation } from 'react-i18next';import { readWorkingPhase } from '@cindy/maker-shared';-import type { BotGroupSpeakerActivity } from '@cindy/maker-shared/botGroupChat';+import type { BotGroupSpeakerActivity, BotGroupSpeaker } from '@cindy/maker-shared/botGroupChat';import { Text } from '@/components/AppText';import { MainWindowActionButton } from '@/components/MobilePrimitives';import { useDeviceLink } from '@/device-link/DeviceLinkContext';@@ -32,12 +32,14 @@ import { CompanionPresenceRing } from './CompanionPresenceRing';import { ThinkingDots } from './ThinkingDots';import { WorkingStatusText } from './WorkingStatusText';-export function BotGroupSpeakerRow({ deviceId, identity, sessionId, activity, online, onError }: {+export function BotGroupSpeakerRow({ deviceId, identity, sessionId, activity, online, executionStatus, stopping, onError }: {deviceId: string;identity: BotGroupIdentity;sessionId: string | null;activity: BotGroupSpeakerActivity;online: boolean;+ executionStatus?: BotGroupSpeaker['executionStatus'];+ stopping?: boolean;onError(message: string | null): void;}) {const { t } = useTranslation();@@ -56,20 +58,22 @@ export function BotGroupSpeakerRow({ deviceId, identity, sessionId, activity, onreturn () => { cancelled = true; offTopic(); };}, [deviceId, invoke, lane, online, subscribe, unsubscribe]));const pending = useSessionPendingInteractions(lane);- const live = useSyncExternalStore(remoteSessionStore.subscribe, () => lane ? remoteSessionStore.getSessionLiveActivity(lane) : null);- const waiting = pending.length > 0 || live?.phase === 'needs-interaction';+ const live = useSyncExternalStore(remoteSessionStore.subscribe, () => lane ? remoteSessionStore.getSessionLiveActivity(lane, deviceId) : null);+ const waiting = pending.length > 0 || live?.phase === 'needs-interaction' || executionStatus === 'needs_input';const livePhase = readWorkingPhase(live?.workingPhase);// The organizer's decision runs outside any Session: there is no live phase to show.const copy = useCompanionGenerationCopy({deviceId,botId: identity.botId,- phase: activity === 'reply' ? livePhase ?? 'thinking' : livePhase,+ phase: activity === 'reply' ? livePhase ?? 'processing' : livePhase,active: !waiting && activity !== 'planning' && (activity === 'reply' || livePhase !== null),turnId: lane,});- const label = activity === 'planning'+ const label = stopping || executionStatus === 'stopping' ? t('groupChat.speaking.stopping')+ : executionStatus === 'queued' ? t('devices.companions.queued')+ : activity === 'planning'? t('groupChat.speaking.planning')- : copy ?? (activity === 'step' ? t('groupChat.speaking.step') : t('devices.companions.working.thinking'));+ : copy ?? (activity === 'step' ? t('groupChat.speaking.step') : t('devices.companions.working.processing'));// G4: the same working vocabulary as the 1:1 chat — breathing portrait, three dots, paced copy.return <View style={styles.row} testID="botGroup.speaking" accessibilityLabel={`${identity.name}, ${waiting ? t('groupChat.waitingConfirm', { name: identity.name }) : label}`}><View style={styles.avatar}>@@ -82,7 +86,8 @@ export function BotGroupSpeakerRow({ deviceId, identity, sessionId, activity, on<ThinkingDots /><WorkingStatusText key={`${lane}:${activity}`} text={label} style={styles.statusText} /></View> : null}- {sessionId ? <MainWindowActionButton action={{ label: t('devices.companions.openTask'), onPress: () => router.push({ pathname: '/sessions/[sessionId]', params: { sessionId, deviceId } }) }} /> : null}+ {live?.compactDetail?.trim() && !/^(?:NO_REPLY|SILENT)$/i.test(live.compactDetail.trim()) ? <Text numberOfLines={2} style={styles.statusText}>{live.compactDetail}</Text> : null}+ {sessionId && deviceId ? <MainWindowActionButton action={{ label: t('devices.companions.openTask'), onPress: () => router.push({ pathname: '/sessions/[sessionId]', params: { sessionId, deviceId } }) }} /> : null}{pending.length > 0 && lane ? <InteractionPanel embedded companioncompanionIdentity={{ name: identity.name, avatar: <BotGroupAvatar deviceId={deviceId} identity={identity} size={BOT_GROUP_INLINE_AVATAR_SIZE} online={online} /> }}deviceId={deviceId} sessionId={lane} interactions={pending} onError={onError} />diff --git a/apps/mobile/src/session/BotGroupWorkArea.tsx b/apps/mobile/src/session/BotGroupWorkArea.tsxnew file mode 100644index 0000000000..01c4b5863a--- /dev/null+++ b/apps/mobile/src/session/BotGroupWorkArea.tsx@@ -0,0 +1,80 @@+import { useCallback, useState } from 'react';+import { ScrollView } from 'react-native';+import { useFocusEffect } from 'expo-router';+import { useTranslation } from 'react-i18next';+import type { BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';+import { useAuth } from '@/auth/AuthContext';+import { useDeviceLink } from '@/device-link/DeviceLinkContext';+import { getRemoteResource } from '@/device-link/remoteResources';+import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';+import { BOT_GROUP_CLIENT_PRIMITIVES, botGroupChatDataFromResource, botGroupResourceRef } from './botGroupRemote';+import { BotGroupSpeakerRow } from './BotGroupSpeakerRow';+import type { BotGroupIdentity } from './BotGroupAvatars';++/** Live work is separate from messages. Only an owned companion's computer can+ * resolve its execution to a task; another member's private task is never queried. */+export function BotGroupWorkArea({ group, deviceId, online, identityFor, onError }: {+ group: BotGroupRemoteChatData; deviceId: string; online: boolean;+ identityFor(botId: string, name: string): BotGroupIdentity;+ onError(message: string | null): void;+}) {+ const { accountGeneration } = useAuth();+ const { i18n } = useTranslation();+ const { invoke, openLink, connectionEpoch, presenceVersion, getPresenceAvailability, subscribe, unsubscribe, onRemoteResourceChanged } = useDeviceLink();+ const candidates = group.round.speakers.flatMap(speaker => {+ const member = group.members.find(member => member.botId === speaker.botId);+ return !speaker.sessionId && speaker.executionId && member?.isOwned && member.homeDeviceId+ ? [{ executionId: speaker.executionId, deviceId: member.homeDeviceId }] : [];+ });+ const scope = JSON.stringify([accountGeneration, group.id, deviceId, candidates]);+ const [resolved, setResolved] = useState<{ scope: string; targets: Map<string, { deviceId: string; sessionId: string; botId: string }> }>();+ useFocusEffect(useCallback(() => {+ if (!online || !candidates.length) return;+ let cancelled = false;+ let reading = false;+ let again = false;+ const hosts = [...new Set(candidates.map(candidate => candidate.deviceId))];+ const read = async () => {+ if (cancelled) return;+ if (reading) { again = true; return; }+ reading = true;+ const targets = new Map<string, { deviceId: string; sessionId: string; botId: string }>();+ await Promise.all(hosts.map(async host => {+ if (getPresenceAvailability(host) === false) return;+ try {+ await openLink(host);+ const resource = await getRemoteResource(invoke, { deviceId: host, deviceName: '' }, botGroupResourceRef(group.id), i18n.language, BOT_GROUP_CLIENT_PRIMITIVES);+ const remote = botGroupChatDataFromResource(resource);+ if (remote?.id !== group.id) return;+ for (const candidate of candidates.filter(candidate => candidate.deviceId === host)) {+ const speaker = remote.round.speakers.find(speaker => speaker.executionId === candidate.executionId);+ if (speaker?.sessionId) targets.set(candidate.executionId, { deviceId: host, sessionId: speaker.sessionId, botId: speaker.botId });+ }+ } catch { /* Generic server status remains available while the computer cannot be reached. */ }+ }));+ if (!cancelled) setResolved({ scope, targets });+ reading = false;+ if (again) { again = false; void read(); }+ };+ const off = onRemoteResourceChanged((host, payload) => {+ if (hosts.includes(host) && payload.collectionId === 'bot-groups'+ && (!payload.resourceRefs?.length || payload.resourceRefs.some(ref => ref.id === group.id))) void read();+ });+ const topics = hosts.map(host => startFocusedTopicSubscription({ deviceId: host, owner: `group-work:${group.id}`, topic: 'sessions', subscribe, unsubscribe }));+ void read();+ return () => { cancelled = true; off(); topics.forEach(offTopic => offTopic()); };+ }, [scope, online, connectionEpoch, presenceVersion, invoke, openLink, subscribe, unsubscribe, onRemoteResourceChanged, getPresenceAvailability, i18n.language]));+ if (group.round.status !== 'running' || !group.round.speakers.length) return null;+ return <ScrollView testID="botGroup.work" style={{ maxHeight: 220 }} contentContainerStyle={{ paddingHorizontal: 16, paddingVertical: 8, gap: 12 }} keyboardShouldPersistTaps="handled">+ {group.round.speakers.map(speaker => {+ const member = group.members.find(member => member.botId === speaker.botId);+ if (!member) return null;+ const target = speaker.executionId && resolved?.scope === scope ? resolved.targets.get(speaker.executionId) : undefined;+ const host = target?.deviceId ?? deviceId;+ return <BotGroupSpeakerRow key={speaker.executionId ?? `${speaker.botId}:${speaker.activity}`}+ deviceId={host} online={online && !!host && getPresenceAvailability(host) !== false}+ identity={{ ...identityFor(member.botId, member.name), ...(target ? { botId: target.botId } : {}) }} sessionId={speaker.sessionId ?? target?.sessionId ?? null}+ activity={speaker.activity} executionStatus={speaker.executionStatus} stopping={speaker.stopping} onError={onError} />;+ })}+ </ScrollView>;+}diff --git a/apps/mobile/src/session/botGroupRemote.ts b/apps/mobile/src/session/botGroupRemote.tsindex 2a58aa54bf..4359d329e5 100644--- a/apps/mobile/src/session/botGroupRemote.ts+++ b/apps/mobile/src/session/botGroupRemote.ts@@ -316,6 +316,11 @@ function parseRound(value: unknown): BotGroupRoundView {botId,sessionId: optionalId(speaker.sessionId),activity: enumOf(speaker.activity, SPEAKER_ACTIVITIES) ?? 'reply',+ ...(id(speaker.executionId) ? { executionId: id(speaker.executionId)! } : {}),+ ...(typeof speaker.startedAt === 'number' && Number.isFinite(speaker.startedAt) ? { startedAt: speaker.startedAt } : {}),+ ...(speaker.stopping === true ? { stopping: true } : {}),+ ...(['queued', 'running', 'needs_input', 'stopping'].includes(String(speaker.executionStatus))+ ? { executionStatus: speaker.executionStatus as BotGroupSpeaker['executionStatus'] } : {}),}];}): [];diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 976195c733..9da087aae0 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -259,9 +259,10 @@ Chat Server 声明 `capabilities.groupSingleSpeaker: 1` 时,服务器群按下悬停时出现在气泡外侧,键盘聚焦与触屏时常显;@ 点名在所有消息里用主题链接色(`--msg-link`,不加底色;它不是链接,不受 DESIGN.md「聊天正文不使用 `--msg-link`」约束,2026-10-20 裁决),指针停在点名上约 0.25 秒弹出该成员的信息卡(头像、名字、谁的伙伴或群内角色、暂停/不可用状态),指针可移入卡片;`@所有人` 不弹卡;表情回应贴在气泡外上角(别人的在右上、自己的在左上),≤3 人时显示头像;话题入口是气泡下方与气泡左缘对齐的一行(回复者头像、N 条回复、最后回复时间);轮次结束、分工结束与系统提示是居中的一行小字。多人群里别人带来的伙伴显示「伙伴名 (主人昵称)」,人类成员名字旁带「某某的主人」。-- 进行中:正在发言的伙伴在时间线末尾一行「X 正在想…」,本机能读到流式正文时下面跟最后两行;分工某一步在做,- 或某位伙伴说了超过三秒时,输入框上方出现固定的、按内容宽的进行中胶囊(不随时间线滚走;「看过程」直接打开该专线的普通任务页,不展开独立过程面板;外层形状见 [DESIGN.md §5 的 Desktop group progress capsule 登记](../design-rules/DESIGN.md#step-1--registered-shapes)):「第 k/n 步 · 谁 做什么 · 已做多久 ·- 当前动作」,带「看过程」(本机能读到这条专线时)与「停止」;分工进行中它替代时间线末尾的发言行,等确认的卡仍在时间线里。+- 进行中:前三秒显示简短状态,之后进度固定在输入框上方的动态区,不作为聊天正文发布。每条并发执行各自显示当前阶段、公开动作、耗时与任务入口;本机公开进度在工具执行期间保留最后两行,不显示私密思考或前一轮内容。缺少活动数据时写「正在处理」,不猜成「正在思考」。等待、排队与停止中分别显示,结束后动态区撤下,聊天结果保留。+ 胶囊沿用 [DESIGN.md §5 的 Desktop group progress capsule 登记](../design-rules/DESIGN.md#step-1--registered-shapes);动作与公开进度放在胶囊下方,不挤占按钮。分工保留「第 k/n 步 · 谁 做什么」,本机确认卡仍可就地作答。+ 「看过程」打开这一次执行对应的原普通任务页;同账号远端伙伴通过已有授权的群资源按执行 ID 解析任务和所属电脑,不能回退到伙伴的私聊任务,也不读取别人的伙伴电脑。远端不可读时保留真实通用状态与原有停止权限,不显示错误任务入口。+ 手机同样将工作状态放在输入框上方,提供「打开任务」,确认与任务正文沿用普通任务界面。直连 Chat Server 的手机读取执行状态,停止自己的请求、安排及自己伙伴的工作;执行电脑终止后提交已有 cancel 回执,失败重试回执而不重跑模型,避免长期留在「正在停止」。- 输入框支持 @ 伙伴,候选第一项为「所有人」;支持附件(见 3.1)。服务器群的话题回复用同一个输入框的话题模式,@ 候选也是同一套(`useBotGroupMentionPicker`):候选、筛选、键盘与鼠标选择、Esc 收起和同名伙伴按选中身份区分都与主群一致;候选与点名解析都不含当前用户自己(与手机一致)。草稿随群持久(切走再回来文字还在,群被删除时丢弃)。diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.tsindex 578abbe786..451c026ac3 100644--- a/packages/maker-shared/src/botGroupChat.ts+++ b/packages/maker-shared/src/botGroupChat.ts@@ -430,6 +430,11 @@ export type BotGroupSpeakerActivity = 'reply' | 'planning' | 'step';export interface BotGroupSpeaker {botId: string;+ /** Server execution identity: match the same work on its owning computer, never a bot's main chat. */+ executionId?: string;+ startedAt?: number;+ stopping?: boolean;+ executionStatus?: 'queued' | 'running' | 'needs_input' | 'stopping';/** Hidden group lane or 分工 Session of the speaking Bot, for pending permission/question UI. */sessionId: string | null;activity: BotGroupSpeakerActivity;