Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): 伙伴群聊第三阶段——手机端群聊与分工 (#5162)
Chris Zhang7c59d6f8e472
diff --git a/AGENTS.md b/AGENTS.mdindex 8929a82435..782a9bc3d6 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -56,8 +56,8 @@`docs/product-rules/shared-task-mode.md`;复用 device-link,同账号远控行为不变。- 修改伙伴(Bot)的身份、Session 生命周期、模型 fallback、工作目录、Skill / MCP 装配、委派协作或伙伴设置前,必须先读 `docs/product-rules/cindy-bots-runtime.md`。-- 新增或修改伙伴群聊的数据、发言编排、群专线 Session、分工(负责人、安排、分工 Session、群工作目录)- 或群聊界面前,必须先读 `docs/product-rules/bot-group-chat.md`。+- 新增或修改伙伴群聊的数据、发言编排、群专线 Session、分工(负责人、安排、分工 Session、群工作目录)、+ 群聊界面或手机端群聊(`bot-groups` 远程资源、群推送深链)前,必须先读 `docs/product-rules/bot-group-chat.md`。- 新增或修改 `/review`、Reviewer 任务、成果快照、Finding 协议、复核入口、结果呈现或复核生命周期前,必须先读 `docs/product-rules/review-product-direction.md`。- 新增或修改按区域(`cn` / `global`)分支的逻辑、构建身份与命名、端点选择、区域相关diff --git a/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.ts b/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.tsindex 721caa276c..7430d0df4c 100644--- a/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.ts@@ -1,7 +1,7 @@import { createHash } from 'node:crypto';import { describe, expect, it } from 'vitest';import { NOTIFY_TITLE_MAX_LENGTH, NOTIFY_BODY_MAX_LENGTH, NOTIFY_DEEP_LINK_MAX_LENGTH } from '@cindy/device-link';-import { MobileNotifyDeduper, buildSessionNotifyPayload } from '../mobileNotify';+import { MobileNotifyDeduper, buildBotGroupNotifyPayload, buildSessionNotifyPayload } from '../mobileNotify';describe('buildSessionNotifyPayload', () => {const base = {@@ -146,3 +146,24 @@ it('sends plain text to APNs, not Markdown or image paths', () => {expect(buildSessionNotifyPayload({ ...payload, detail: '**Report** [ready](https://example.com) `a_b`' }).body).toBe('Report ready a_b');expect(buildSessionNotifyPayload({ ...payload, detail: '' }).body).toBe('New reply');});++describe('buildBotGroupNotifyPayload', () => {+ it('opens the group on the phone and folds per (device, group)', () => {+ const payload = buildBotGroupNotifyPayload({+ groupId: 'g 1',+ title: '官网介绍页',+ body: '咪咪做完了「策划」,等你继续',+ selfDeviceId: 'desk-1',+ });+ expect(payload).toMatchObject({+ category: 'session-needs-reply',+ title: '官网介绍页',+ body: '咪咪做完了「策划」,等你继续',+ deepLink: '/companions/groups/g%201?deviceId=desk-1',+ });+ expect(payload.collapseId).toBe(createHash('sha256').update('desk-1:bot-group:g 1').digest('hex').slice(0, 32));+ expect(buildBotGroupNotifyPayload({ groupId: 'g', title: ' ', body: 'x', selfDeviceId: 'd' }).title).toBe('g');+ expect(buildBotGroupNotifyPayload({ groupId: 'g', title: 'x'.repeat(500), body: 'y', selfDeviceId: 'd' }).title)+ .toHaveLength(NOTIFY_TITLE_MAX_LENGTH);+ });+});diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex ecad69e063..dc7ab6f129 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -138,6 +138,7 @@ import { startSharedTaskRuntime, stopSharedTaskRuntime } from './sharedTaskRuntiimport { sharedTaskApi } from './sharedTaskApi.js';import {MobileNotifyDeduper,+ buildBotGroupNotifyPayload,buildSessionNotifyPayload,type MobileSessionEventKind,} from './mobileNotify';@@ -1959,6 +1960,32 @@ export function sendMobileSessionNotify(payload: {return sent;}+/** Phone push for a 分工 step that stopped for the user (bot-group-chat.md §8.3). */+export function sendMobileBotGroupNotify(payload: {+ groupId: string;+ title: string;+ body: string;+ /** Unique per settled step, so a redo of the same step notifies again. */+ eventId: string;+ generation?: number;+}): boolean {+ if (!client) return false;+ if (payload.generation !== undefined && payload.generation !== mobileNotifyGeneration) return false;+ const selfDeviceId = client.getSelfDeviceId();+ if (!selfDeviceId) return false;+ const key = `bot-group:${payload.groupId}`;+ const now = Date.now();+ if (!mobileNotifyDeduper.shouldSend(key, 'needs-reply', now, payload.eventId)) return false;+ const sent = client.sendNotify(buildBotGroupNotifyPayload({+ groupId: payload.groupId,+ title: payload.title,+ body: payload.body,+ selfDeviceId,+ }));+ if (sent) mobileNotifyDeduper.recordSent(key, 'needs-reply', now, payload.eventId);+ return sent;+}+export function broadcast(channel: string, payload: unknown): void {const ownerStamp = getActiveDataOwnerPushStamp();for (const win of BrowserWindow.getAllWindows()) {diff --git a/apps/desktop/src/main/device-link/mobileNotify.ts b/apps/desktop/src/main/device-link/mobileNotify.tsindex b5bf76fe54..1ff8584996 100644--- a/apps/desktop/src/main/device-link/mobileNotify.ts+++ b/apps/desktop/src/main/device-link/mobileNotify.ts@@ -66,6 +66,31 @@ export function buildSessionNotifyPayload(opts: {};}+/**+ * A 分工 step waiting for the phone's owner (bot-group-chat.md §8.3). There is no category for+ * groups in the notify protocol, so it rides `session-needs-reply`; the deep link opens the+ * group on the phone. Phones without the group screen ignore the unknown link and just open.+ */+export function buildBotGroupNotifyPayload(opts: {+ groupId: string;+ title: string;+ body: string;+ selfDeviceId: string;+}): NotifyPayload {+ const title = (opts.title.trim() || opts.groupId.slice(0, 8)).slice(0, NOTIFY_TITLE_MAX_LENGTH);+ return {+ category: 'session-needs-reply',+ title,+ body: notificationPreview(opts.body, NOTIFY_BODY_MAX_LENGTH),+ deepLink: `/companions/groups/${encodeURIComponent(opts.groupId)}?deviceId=${encodeURIComponent(opts.selfDeviceId)}`+ .slice(0, NOTIFY_DEEP_LINK_MAX_LENGTH),+ collapseId: createHash('sha256')+ .update(`${opts.selfDeviceId}:bot-group:${opts.groupId}`)+ .digest('hex')+ .slice(0, 32),+ };+}+function sessionDeepLink(sessionId: string, deviceId: string, teammateBotId?: string): string {const base = `/sessions/${encodeURIComponent(sessionId)}?deviceId=${encodeURIComponent(deviceId)}`;if (!teammateBotId) return base;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.tsindex 2f906c52ba..ebc13dbdcc 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts@@ -753,6 +753,36 @@ describe('botGroupChatService 分工', () => {expect(lanePrompt.prompt).toContain('not in your own workspace');});+ it('reports every settled step so phones can be told', async () => {+ const onStepSettled = vi.fn();+ let fail = true;+ const harness = createHarness((botId) => (botId === 'xiaoman' && fail ? null : '好了'), {+ decidePlan: async () => ({ needsPlan: true, steps: [{ botId: 'mimi', task: '策划' }, { botId: 'xiaoman', task: '设计' }] }),+ workDir: fakeWorkDir(),+ onStepSettled,+ });+ const groupId = await createGroup(harness);+ const plan = await proposePlan(harness, groupId);+ await harness.service.startPlan({ groupId, planId: plan.id });+ await waitForIdle(harness, groupId);+ await harness.service.continuePlan({ groupId, planId: plan.id });+ await vi.waitFor(() => expect(harness.dispatches.at(-1)!.botId).toBe('xiaoman'));+ const call = harness.dispatches.at(-1)!;+ await harness.service.settleLaneTurn({ sessionId: call.sessionId, activeInputClientId: call.clientId, outcome: 'error', resultText: '' });+ await waitForIdle(harness, groupId);+ fail = false;+ await harness.service.retryPlan({ groupId, planId: plan.id });+ await waitForIdle(harness, groupId);+ expect(onStepSettled.mock.calls.map(([event]) => [event.botName, event.task, event.outcome, event.planDone])).toEqual([+ ['咪咪', '策划', 'done', false],+ ['小满', '设计', 'failed', false],+ ['小满', '设计', 'done', true],+ ]);+ expect(onStepSettled.mock.calls[0]![0]).toMatchObject({ groupId, groupName: '周末出游', planId: plan.id, position: 0 });+ // The whole group, so the push can apply the phone's member-visibility rule.+ expect([...onStepSettled.mock.calls[0]![0].memberBotIds].sort()).toEqual(['abu', 'mimi', 'xiaoman']);+ });+it('a plain message after a step asks the same Bot to redo it, and later steps read the new hand-off', async () => {const replies: Record<string, string[]> = { mimi: ['第一版', '第二版'], xiaoman: ['设计好了'] };const harness = createHarness((botId) => replies[botId]!.shift() ?? 'x', { decidePlan: async () => THREE_STEPS, workDir: fakeWorkDir() });diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.tsnew file mode 100644index 0000000000..9d2fef41d6--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts@@ -0,0 +1,246 @@+import Database from 'better-sqlite3';+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({ sqlite: null as import('better-sqlite3').Database | null, ownerCurrent: (): boolean => true }));++vi.mock('../../localDb/client/current.js', async () => {+ const { drizzle } = await import('drizzle-orm/better-sqlite3');+ return { getDbClient: () => ({ drizzle: drizzle(h.sqlite!) }) };+});+vi.mock('../../device-link/broadcast-tap.js', () => ({+ captureDataOwnerBroadcastScope: () => ({ owner: 'a' }),+ isDataOwnerBroadcastScopeCurrent: () => h.ownerCurrent(),+}));++import { remoteResourceRegistry } from '../../device-link/remoteResourceRegistry.js';+import {+ botGroupMembersVisibleRemotely,+ botGroupRemoteChatData,+ botGroupRemoteItem,+ botGroupRemotePreview,+ registerBotGroupRemoteResourceProvider,+} from '../botGroupRemoteResourceProvider.js';+import type { BotGroupChatService } from '../botGroupChatService.js';+import {+ BOT_GROUP_CHAT_PRIMITIVE,+ BOT_GROUP_REMOTE_COLLECTION_ID,+ BOT_GROUP_REMOTE_RESOURCE_KIND,+ type BotGroupDetail,+ type BotGroupSummary,+} from '../../../shared/botGroupChat.js';++const context = { controllerDeviceId: 'phone-1' };+const client = (primitives: string[] = []) => ({ protocolVersion: 1, primitives, locale: 'zh-CN' });+const ref = (id: string) => ({ collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, kind: BOT_GROUP_REMOTE_RESOURCE_KIND, id });++function summary(overrides: Partial<BotGroupSummary> = {}): BotGroupSummary {+ return {+ id: 'g1',+ name: '官网介绍页',+ replyMode: 'all',+ speakingMode: 'auto',+ members: [+ { botId: 'mimi', name: '咪咪', avatar: '🐱', avatarColor: 'red', status: 'active' },+ { botId: 'abu', name: '阿布', avatar: '🦉', avatarColor: 'blue', status: 'active' },+ ],+ organizerBotId: 'mimi',+ projectDir: '/Users/me/site',+ lastMessage: { authorKind: 'bot', authorName: '阿布', preview: '写好了', createdAt: 50 },+ speakingBotIds: [],+ planningBotId: null,+ openPlan: null,+ createdAt: 1,+ updatedAt: 40,+ ...overrides,+ };+}++function detail(overrides: Partial<BotGroupDetail> = {}): BotGroupDetail {+ return {+ ...summary(),+ messages: [+ {+ id: 'm1', sequence: 1, kind: 'message', authorKind: 'user', authorBotId: null, authorName: '',+ content: '做个页面', mentions: { all: false, botIds: [] }, noticeCode: null, planId: null, files: [], createdAt: 10,+ },+ {+ id: 'm2', sequence: 2, kind: 'message', authorKind: 'bot', authorBotId: 'abu', authorName: '阿布',+ content: '写好了', mentions: { all: false, botIds: [] }, noticeCode: null, planId: 'p1', files: ['index.html'], createdAt: 50,+ },+ ],+ hasMoreBefore: false,+ round: { status: 'idle', speakers: [], canContinue: false },+ plans: [{+ id: 'p1', status: 'done', organizerBotId: 'mimi', organizerName: '咪咪',+ steps: [{ position: 0, botId: 'abu', botName: '阿布', task: '写代码', status: 'done' }],+ currentStep: 0, workDir: '/Users/me/site/.cindy-worktrees/brave', branch: 'cindy/brave', createdAt: 1, updatedAt: 2,+ }],+ ...overrides,+ };+}++const service = {+ listGroups: vi.fn(),+ getGroup: vi.fn(),+ createGroup: vi.fn(),+ updateGroup: vi.fn(),+ setMembers: vi.fn(),+ deleteGroup: vi.fn(),+ sendMessage: vi.fn(),+ continueRound: vi.fn(),+ stopRound: vi.fn(),+ startPlan: vi.fn(),+ dismissPlan: vi.fn(),+ continuePlan: vi.fn(),+ retryPlan: vi.fn(),+ editPlanStep: vi.fn(),+};++describe('bot group remote resources', () => {+ beforeAll(() => {+ registerBotGroupRemoteResourceProvider(() => service as unknown as BotGroupChatService);+ });++ beforeEach(() => {+ h.sqlite = new Database(':memory:');+ h.sqlite.exec(`+ CREATE TABLE bot_profiles (id TEXT PRIMARY KEY, hidden_at INTEGER, status TEXT NOT NULL);+ INSERT INTO bot_profiles VALUES ('mimi', NULL, 'active'), ('abu', NULL, 'active'), ('ghost', 5, 'active');+ `);+ h.ownerCurrent = () => true;+ for (const fn of Object.values(service)) fn.mockReset();+ service.getGroup.mockResolvedValue({ ok: true, group: detail() });+ for (const name of ['updateGroup', 'setMembers', 'deleteGroup', 'continueRound', 'stopRound', 'startPlan', 'dismissPlan', 'continuePlan', 'retryPlan', 'editPlanStep'] as const) {+ service[name].mockResolvedValue({ ok: true });+ }+ service.sendMessage.mockResolvedValue({ ok: true, messageId: 'm3' });+ });++ afterEach(() => h.sqlite?.close());++ it('lists only groups whose members are all visible to phones, with member links', async () => {+ const hidden = summary({+ id: 'g2',+ members: [...summary().members, { botId: 'ghost', name: '隐藏', avatar: '', avatarColor: '', status: 'active' }],+ });+ service.listGroups.mockResolvedValue({ ok: true, groups: [summary(), hidden] });+ const listed = await remoteResourceRegistry.list(context, { client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID });+ expect(listed.items.map((item) => item.ref.id)).toEqual(['g1']);+ expect(listed.items[0]!.links.map((link) => link.target)).toEqual([+ { kind: 'resource', ref: { collectionId: 'teammates', kind: 'bot', id: 'mimi' } },+ { kind: 'resource', ref: { collectionId: 'teammates', kind: 'bot', id: 'abu' } },+ ]);+ expect(JSON.stringify(listed)).not.toContain('/Users/me/site');+ });++ it('previews the same plan states as the desktop sidebar', () => {+ const running = summary({+ openPlan: { id: 'p1', status: 'running', currentStep: 1, stepCount: 3, currentBotName: '阿布', currentStepStatus: 'running' },+ });+ expect(botGroupRemotePreview(running)).toMatchObject({ translations: { 'zh-CN': '分工 2/3 · 阿布正在做' } });+ expect(botGroupRemoteItem(summary({ speakingBotIds: ['abu'] })).display.generation).toEqual({ phase: 'processing', startedAt: null });+ expect(botGroupRemotePreview(summary({ planningBotId: 'mimi' }))).toMatchObject({ translations: { 'zh-CN': '咪咪正在安排…' } });+ const waiting = summary({+ openPlan: { id: 'p1', status: 'waiting', currentStep: 0, stepCount: 3, currentBotName: '咪咪', currentStepStatus: 'failed' },+ });+ expect(botGroupRemotePreview(waiting)).toMatchObject({ translations: { 'zh-CN': '咪咪没做完' } });+ expect(botGroupRemotePreview(summary())).toMatchObject({ translations: { 'zh-CN': '阿布:写好了' } });+ });++ it('sends the chat only to controllers that understand it, without host paths', async () => {+ const rich = await remoteResourceRegistry.get(context, { client: client([BOT_GROUP_CHAT_PRIMITIVE]), ref: ref('g1') });+ expect(rich.blocks?.[0]).toMatchObject({ primitive: BOT_GROUP_CHAT_PRIMITIVE });+ const data = rich.blocks![0]!.data as ReturnType<typeof botGroupRemoteChatData>;+ expect(data.projectDir).toBeNull();+ expect(data.projectDirName).toBe('site');+ expect(data.plans[0]!.workDir).toBeNull();+ expect(data.plans[0]!.branch).toBe('cindy/brave');+ expect(JSON.stringify(rich)).not.toContain('/Users/me');+ const plain = await remoteResourceRegistry.get(context, { client: client(), ref: ref('g1') });+ expect(plain.blocks?.[0]).toMatchObject({ primitive: 'markdown' });+ expect(plain.blocks?.[0]?.data).toBeUndefined();+ expect(plain.blocks?.[0]?.fallbackMarkdown).toContain('**阿布**: 写好了');+ });++ it('forwards actions to the group service and reports its error code when refused', async () => {+ const send = await remoteResourceRegistry.invoke(context, {+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'send', resourceRef: ref('g1'),+ input: { text: '安排一下', mentions: { all: false, botIds: [] }, clientId: 'c1', division: true },+ });+ expect(service.sendMessage).toHaveBeenCalledWith({+ groupId: 'g1', text: '安排一下', mentions: { all: false, botIds: [] }, clientId: 'c1', division: true,+ });+ expect(send.effects).toEqual([{ kind: 'refresh-resource', ref: ref('g1') }]);++ await remoteResourceRegistry.invoke(context, {+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'plan-continue', resourceRef: ref('g1'),+ input: { planId: 'p1' },+ });+ expect(service.continuePlan).toHaveBeenCalledWith({ groupId: 'g1', planId: 'p1' });++ service.startPlan.mockResolvedValue({ ok: false, errorCode: 'PLAN_CLOSED', message: '已经开始了' });+ await expect(remoteResourceRegistry.invoke(context, {+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'plan-start', resourceRef: ref('g1'),+ input: { planId: 'p1' },+ })).rejects.toMatchObject({ code: 'INVALID_PARAMS', message: 'PLAN_CLOSED' });+ });++ it('never lets a phone set a folder or reach a hidden teammate', async () => {+ await remoteResourceRegistry.invoke(context, {+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'update', resourceRef: ref('g1'),+ input: { name: '新名字', projectDir: '/etc', organizerBotId: 'abu' },+ });+ expect(service.updateGroup).toHaveBeenCalledWith({ groupId: 'g1', name: '新名字', organizerBotId: 'abu' });+ await expect(remoteResourceRegistry.invoke(context, {+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'set-members', resourceRef: ref('g1'),+ input: { botIds: ['mimi', 'ghost'] },+ })).rejects.toMatchObject({ message: 'MEMBER_UNAVAILABLE' });+ expect(service.setMembers).not.toHaveBeenCalled();+ await expect(remoteResourceRegistry.invoke(context, {+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'create',+ input: { name: '新群', botIds: ['mimi', 'ghost'] },+ })).rejects.toMatchObject({ message: 'MEMBER_UNAVAILABLE' });+ service.getGroup.mockResolvedValue({+ ok: true,+ group: detail({ members: [...summary().members, { botId: 'ghost', name: '隐藏', avatar: '', avatarColor: '', status: 'active' }] }),+ });+ await expect(remoteResourceRegistry.invoke(context, {+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'stop', resourceRef: ref('g1'),+ })).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(service.stopRound).not.toHaveBeenCalled();+ });++ it('writes nothing once the computer has switched accounts during the checks', async () => {+ // The first owner check runs after the visibility reads; by then the account has changed.+ h.ownerCurrent = () => false;+ await expect(remoteResourceRegistry.invoke(context, {+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'create',+ input: { name: '新群', botIds: ['mimi', 'abu'] },+ })).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(service.createGroup).not.toHaveBeenCalled();+ await expect(remoteResourceRegistry.invoke(context, {+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'set-members', resourceRef: ref('g1'),+ input: { botIds: ['mimi', 'abu'] },+ })).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(service.setMembers).not.toHaveBeenCalled();+ });++ it('applies the same member rule to anything else a phone hears about a group', async () => {+ await expect(botGroupMembersVisibleRemotely(['mimi', 'abu'])).resolves.toBe(true);+ await expect(botGroupMembersVisibleRemotely(['mimi', 'ghost'])).resolves.toBe(false);+ await expect(botGroupMembersVisibleRemotely(['mimi', 'gone'])).resolves.toBe(false);+ });++ it('creates a group and navigates the phone to it', async () => {+ service.createGroup.mockResolvedValue({ ok: true, groupId: 'g9' });+ const created = await remoteResourceRegistry.invoke(context, {+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'create',+ input: { name: '新群', botIds: ['mimi', 'abu'] },+ });+ expect(service.createGroup).toHaveBeenCalledWith({ name: '新群', botIds: ['mimi', 'abu'] });+ expect(created.effects).toEqual([+ { kind: 'refresh-collection', collectionId: BOT_GROUP_REMOTE_COLLECTION_ID },+ { kind: 'navigate', target: { kind: 'resource', ref: ref('g9') } },+ ]);+ });+});diff --git a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts b/apps/desktop/src/main/maker-ipc/botGroupChatService.tsindex 934e080f24..5537bec7a5 100644--- a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts+++ b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts@@ -127,6 +127,11 @@ export interface BotGroupChatServiceDeps {workDir?: Pick<BotGroupWorkDir, 'prepare' | 'snapshot' | 'changedFiles' | 'trashGroupFolder'>;/** Existing local directory usable as a 项目文件夹 (same rules as new-task projects). */validateProjectDir?: (dir: string) => Promise<{ ok: true; dir: string } | { ok: false; message: string }>;+ /**+ * A 分工 step stopped for the user: finished (继续, or the whole plan is done) or not+ * finished (重试). Phones are notified from here (bot-group-chat.md §8.3).+ */+ onStepSettled?: (event: BotGroupStepSettledEvent, ownerScope?: DataOwnerBroadcastScope) => void;captureOwnerScope?: () => DataOwnerBroadcastScope;isOwnerScopeCurrent?: (scope: DataOwnerBroadcastScope) => boolean;onChanged?: (payload: BotGroupChangedPayload, ownerScope?: DataOwnerBroadcastScope) => void;@@ -137,6 +142,20 @@ export interface BotGroupChatServiceDeps {log?: { warn: (message: string, meta?: Record<string, unknown>) => void };}+export interface BotGroupStepSettledEvent {+ groupId: string;+ groupName: string;+ /** Every member of the group, so a controller push can apply the same visibility rule as its list. */+ memberBotIds: string[];+ planId: string;+ position: number;+ botName: string;+ task: string;+ outcome: 'done' | 'failed';+ /** The last step finished: the whole plan is done. */+ planDone: boolean;+}+interface MemberRow {botId: string;position: number;@@ -1244,7 +1263,22 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {endMessage: done && isLast ? messageRow({ groupId, kind: 'plan-end', authorKind: 'system', planId }) : null,now: now(),});- if (result.settled) emit(groupId, 'messages', scope);+ if (!result.settled) return;+ emit(groupId, 'messages', scope);+ const group = await readGroup(groupId);+ if (group && scopeIsCurrent(scope)) {+ deps.onStepSettled?.({+ groupId,+ groupName: group.name,+ memberBotIds: members.map((member) => member.botId),+ planId,+ position,+ botName: authorName,+ task: step.task,+ outcome: outcome.kind,+ planDone: done && isLast,+ }, scope);+ }};try {diff --git a/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceInvalidation.ts b/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceInvalidation.tsnew file mode 100644index 0000000000..2d27cabe51--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceInvalidation.ts@@ -0,0 +1,27 @@+import { REMOTE_RESOURCE_CHANGED_CHANNEL, type RemoteResourceChangedPayload } from '@cindy/device-link';++import { getSafeDataOwnerPushStamp, tapWindowBroadcast } from '../device-link/broadcast-tap.js';+import { createLogger } from '../logger.js';+import {+ BOT_GROUP_REMOTE_COLLECTION_ID,+ BOT_GROUP_REMOTE_RESOURCE_KIND,+} from '../../shared/botGroupChat.js';++const log = createLogger('maker-ipc:bot-group-remote-resource');++/**+ * Tell controllers that a group projection must be re-read. Every group change touches the+ * collection row (preview, running state), so the payload names the collection and the group.+ * Only the device-link tap needs it: local windows already listen to `maker:bot-group:changed`.+ */+export function broadcastBotGroupRemoteResourceChanged(groupId: string): void {+ const payload: RemoteResourceChangedPayload = {+ collectionId: BOT_GROUP_REMOTE_COLLECTION_ID,+ resourceRefs: [{ collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, kind: BOT_GROUP_REMOTE_RESOURCE_KIND, id: groupId }],+ };+ try {+ tapWindowBroadcast(REMOTE_RESOURCE_CHANGED_CHANNEL, payload, getSafeDataOwnerPushStamp());+ } catch (error) {+ log.warn('remote group invalidation broadcast failed', { error: error instanceof Error ? error.message : String(error) });+ }+}diff --git a/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts b/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.tsnew file mode 100644index 0000000000..4475f5074d--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts@@ -0,0 +1,392 @@+/**+ * Bot group chat for controllers (phones) through the Remote Resource protocol+ * (docs/product-rules/bot-group-chat.md §8, docs/dev-rules/remote-and-mobile-adaptation.md).+ *+ * The host keeps every rule: this module only projects groups and forwards actions to+ * the same group service the local window uses. Host paths never leave the computer, and a+ * group is shown only while every member is a remotely visible teammate.+ */++import path from 'node:path';++import { inArray } from 'drizzle-orm';+import type {+ RemoteActionInvokeResponse,+ RemoteCollectionItem,+ RemoteLocalizedText,+ RemoteResource,+ RemoteResourceRef,+} from '@cindy/device-link';++import {+ captureDataOwnerBroadcastScope,+ isDataOwnerBroadcastScopeCurrent,+} from '../device-link/broadcast-tap.js';+import {+ RemoteResourceRegistryError,+ remoteResourceRegistry,+} from '../device-link/remoteResourceRegistry.js';+import { getDbClient } from '../localDb/client/current.js';+import {+ BOT_REMOTE_RESOURCE_KIND,+ TEAMMATES_REMOTE_COLLECTION_ID,+} from '../localDb/ipc/botRemoteResourceProjection.js';+import { isBotVisibleRemotely } from '../localDb/ipc/botRemoteVisibility.js';+import { botProfiles } from '../localDb/schema.js';+import {+ BOT_GROUP_CHAT_PRIMITIVE,+ BOT_GROUP_MEMBER_LINK_REL,+ BOT_GROUP_REMOTE_COLLECTION_ID,+ BOT_GROUP_REMOTE_RESOURCE_KIND,+ type BotGroupDetail,+ type BotGroupFailure,+ type BotGroupRemoteActionId,+ type BotGroupRemoteChatData,+ type BotGroupSummary,+} from '../../shared/botGroupChat.js';+import type { BotGroupChatService } from './botGroupChatService.js';++const FALLBACK_MESSAGES = 20;+const FALLBACK_MESSAGE_CHARS = 280;++type Locale = 'en' | 'zh-CN' | 'zh-TW' | 'ja' | 'ko';+type Copy = Record<Locale, string>;++const COPY = {+ title: { en: 'Group chats', 'zh-CN': '群聊', 'zh-TW': '群聊', ja: 'グループチャット', ko: '그룹 채팅' },+ planning: {+ en: '{name} is splitting the work…',+ 'zh-CN': '{name}正在安排…',+ 'zh-TW': '{name}正在安排…',+ ja: '{name} が役割分担を考えています…',+ ko: '{name} 님이 역할을 나누는 중…',+ },+ proposed: {+ en: '{name}: plan ready, waiting for you',+ 'zh-CN': '{name}:安排好了,等你开始',+ 'zh-TW': '{name}:安排好了,等你開始',+ ja: '{name}:分担が決まりました。開始を待っています',+ ko: '{name}: 분담을 정했어요. 시작을 기다려요',+ },+ running: {+ en: 'Step {step}/{total} · {name} is working',+ 'zh-CN': '分工 {step}/{total} · {name}正在做',+ 'zh-TW': '分工 {step}/{total} · {name}正在做',+ ja: '分担 {step}/{total} · {name} が作業中',+ ko: '분담 {step}/{total} · {name} 작업 중',+ },+ stepDone: {+ en: '{name} is done — continue when ready',+ 'zh-CN': '{name}做完了,等你继续',+ 'zh-TW': '{name}做完了,等你繼續',+ ja: '{name} が完了しました。続行を待っています',+ ko: '{name} 님이 끝냈어요. 계속을 기다려요',+ },+ stepFailed: {+ en: "{name} didn't finish",+ 'zh-CN': '{name}没做完',+ 'zh-TW': '{name}沒做完',+ ja: '{name} は完了できませんでした',+ ko: '{name} 님이 끝내지 못했어요',+ },+ lastMessage: {+ en: '{name}: {text}',+ 'zh-CN': '{name}:{text}',+ 'zh-TW': '{name}:{text}',+ ja: '{name}:{text}',+ ko: '{name}: {text}',+ },+} satisfies Record<string, Copy>;++function fill(template: string, vars: Record<string, string | number>): string {+ return template.replace(/\{(\w+)\}/g, (match, key: string) => (key in vars ? String(vars[key]) : match));+}++function localized(copy: Copy, vars: Record<string, string | number> = {}): RemoteLocalizedText {+ const { en, ...rest } = copy;+ return {+ fallback: fill(en, vars),+ translations: Object.fromEntries(Object.entries(rest).map(([locale, text]) => [locale, fill(text, vars)])),+ };+}++function groupRef(groupId: string): RemoteResourceRef {+ return { collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, kind: BOT_GROUP_REMOTE_RESOURCE_KIND, id: groupId };+}++/** Sidebar line for a group, the same states the desktop sidebar shows. */+export function botGroupRemotePreview(group: BotGroupSummary): RemoteLocalizedText | string | undefined {+ const name = (botId: string | null) => group.members.find((member) => member.botId === botId)?.name ?? '';+ if (group.planningBotId) return localized(COPY.planning, { name: name(group.planningBotId) });+ const plan = group.openPlan;+ if (plan?.status === 'proposed') return localized(COPY.proposed, { name: name(group.organizerBotId) });+ if (plan?.status === 'running' && plan.currentStep !== null) {+ return localized(COPY.running, { step: plan.currentStep + 1, total: plan.stepCount, name: plan.currentBotName ?? '' });+ }+ if (plan?.status === 'waiting' && plan.currentBotName) {+ return localized(plan.currentStepStatus === 'failed' ? COPY.stepFailed : COPY.stepDone, { name: plan.currentBotName });+ }+ const last = group.lastMessage;+ if (!last) return undefined;+ return last.authorKind === 'bot' && last.authorName+ ? localized(COPY.lastMessage, { name: last.authorName, text: last.preview })+ : last.preview;+}++export function botGroupRemoteItem(group: BotGroupSummary): RemoteCollectionItem {+ const busy = group.speakingBotIds.length > 0 || group.planningBotId !== null;+ const preview = botGroupRemotePreview(group);+ return {+ ref: groupRef(group.id),+ display: {+ title: group.name,+ subtitle: group.members.map((member) => member.name).join('、'),+ ...(preview ? { preview } : {}),+ timestamp: group.lastMessage?.createdAt ?? group.updatedAt,+ ...(busy ? { generation: { phase: 'processing', startedAt: null } } : {}),+ },+ links: group.members.map((member) => ({+ rel: BOT_GROUP_MEMBER_LINK_REL,+ target: {+ kind: 'resource' as const,+ ref: { collectionId: TEAMMATES_REMOTE_COLLECTION_ID, kind: BOT_REMOTE_RESOURCE_KIND, id: member.botId },+ },+ label: member.name,+ })),+ revision: JSON.stringify([+ group.updatedAt,+ group.name,+ group.members.map((member) => [member.botId, member.name, member.status]),+ group.organizerBotId,+ group.lastMessage?.createdAt ?? null,+ group.openPlan,+ group.speakingBotIds,+ group.planningBotId,+ ]),+ };+}++/** Host paths stay on the computer; the phone gets the folder name only. */+export function botGroupRemoteChatData(detail: BotGroupDetail): BotGroupRemoteChatData {+ return {+ ...detail,+ projectDir: null,+ projectDirName: detail.projectDir ? path.basename(detail.projectDir) : null,+ plans: detail.plans.map((plan) => ({ ...plan, workDir: null })),+ };+}++function fallbackMarkdown(detail: BotGroupDetail): string {+ const lines = detail.messages+ .filter((message) => message.kind === 'message' && message.content.trim())+ .slice(-FALLBACK_MESSAGES)+ .map((message) => {+ const text = message.content.replace(/\s+/g, ' ').trim();+ const clipped = Array.from(text).length > FALLBACK_MESSAGE_CHARS+ ? `${Array.from(text).slice(0, FALLBACK_MESSAGE_CHARS - 1).join('')}…`+ : text;+ return message.authorKind === 'user' ? `> ${clipped}` : `**${message.authorName}**: ${clipped}`;+ });+ return lines.length > 0 ? lines.join('\n\n') : detail.name;+}++function recordOf(value: unknown): Record<string, unknown> {+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};+}++/** A refused action reports the group's own error code so controllers can word it. */+function refuse(result: BotGroupFailure): never {+ throw new RemoteResourceRegistryError(result.errorCode === 'NOT_FOUND' ? 'NOT_FOUND' : 'INVALID_PARAMS', result.errorCode);+}++async function remoteVisibility(botIds: readonly string[]): Promise<Map<string, boolean>> {+ if (botIds.length === 0) return new Map();+ const rows = await getDbClient()+ .drizzle.select({ id: botProfiles.id, hiddenAt: botProfiles.hiddenAt, status: botProfiles.status })+ .from(botProfiles)+ .where(inArray(botProfiles.id, [...new Set(botIds)]));+ return new Map(rows.map((row) => [row.id, isBotVisibleRemotely(row)]));+}++/** A group reaches a phone only while every member is a remotely visible teammate. */+async function visibleGroups<T extends Pick<BotGroupSummary, 'members'>>(groups: readonly T[]): Promise<T[]> {+ const visibility = await remoteVisibility(groups.flatMap((group) => group.members.map((member) => member.botId)));+ return groups.filter((group) => group.members.every((member) => visibility.get(member.botId) === true));+}++/** The same rule for anything else that reaches a phone about a group, such as a step push. */+export async function botGroupMembersVisibleRemotely(memberBotIds: readonly string[]): Promise<boolean> {+ const visibility = await remoteVisibility(memberBotIds);+ return memberBotIds.every((botId) => visibility.get(botId) === true);+}++async function assertBotsVisible(botIds: readonly string[]): Promise<void> {+ const visibility = await remoteVisibility(botIds);+ if (botIds.some((botId) => visibility.get(botId) !== true)) {+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'MEMBER_UNAVAILABLE');+ }+}++let registered = false;++export function registerBotGroupRemoteResourceProvider(service: () => BotGroupChatService | null): void {+ if (registered) return;+ registered = true;++ const requireService = (): BotGroupChatService => {+ const current = service();+ if (!current) throw new RemoteResourceRegistryError('NOT_FOUND', 'HOST_NOT_READY');+ return current;+ };++ /** The group, if a phone may see it right now. */+ const readVisibleGroup = async (groupId: string): Promise<BotGroupDetail> => {+ const result = await requireService().getGroup(groupId);+ if (!result.ok) refuse(result);+ const [visible] = await visibleGroups([result.group]);+ if (!visible) throw new RemoteResourceRegistryError('NOT_FOUND', 'NOT_FOUND');+ return visible;+ };++ remoteResourceRegistry.register({+ collection: {+ id: BOT_GROUP_REMOTE_COLLECTION_ID,+ resourceKind: BOT_GROUP_REMOTE_RESOURCE_KIND,+ title: localized(COPY.title),+ icon: { name: 'users', fallbackText: '••' },+ actions: [{ id: 'create' satisfies BotGroupRemoteActionId, label: localized(COPY.title) }],+ },++ async list(_context, request) {+ const scope = captureDataOwnerBroadcastScope();+ const result = await requireService().listGroups();+ if (!result.ok) refuse(result);+ const groups = await visibleGroups(result.groups);+ if (!isDataOwnerBroadcastScopeCurrent(scope)) throw new RemoteResourceRegistryError('NOT_FOUND', 'Account changed');+ const query = request.query?.trim().toLocaleLowerCase() ?? '';+ const matched = query+ ? groups.filter((group) =>+ [group.name, ...group.members.map((member) => member.name)].some((value) => value.toLocaleLowerCase().includes(query)))+ : groups;+ const items = matched.slice(0, request.limit ?? 200).map(botGroupRemoteItem);+ return {+ collectionId: BOT_GROUP_REMOTE_COLLECTION_ID,+ revision: items.map((item) => item.revision).join('|'),+ items,+ };+ },++ async get(_context, request) {+ const scope = captureDataOwnerBroadcastScope();+ const detail = await readVisibleGroup(request.ref.id);+ if (!isDataOwnerBroadcastScopeCurrent(scope)) throw new RemoteResourceRegistryError('NOT_FOUND', 'Account changed');+ const resource: RemoteResource = {+ ...botGroupRemoteItem(detail),+ blocks: [+ request.client.primitives.includes(BOT_GROUP_CHAT_PRIMITIVE)+ ? {+ id: 'chat',+ primitive: BOT_GROUP_CHAT_PRIMITIVE,+ fallbackMarkdown: fallbackMarkdown(detail),+ data: botGroupRemoteChatData(detail),+ }+ // Older controllers can still read the conversation.+ : { id: 'chat', primitive: 'markdown', fallbackMarkdown: fallbackMarkdown(detail) },+ ],+ };+ return resource;+ },++ async invoke(_context, request): Promise<RemoteActionInvokeResponse> {+ // Checks read the current account's data; a switch before the write must not let them+ // authorize a change to the next account.+ const scope = captureDataOwnerBroadcastScope();+ const ownerService = (): BotGroupChatService => {+ if (!isDataOwnerBroadcastScopeCurrent(scope)) throw new RemoteResourceRegistryError('NOT_FOUND', 'Account changed');+ return requireService();+ };+ const actionId = request.actionId as BotGroupRemoteActionId;+ const input = recordOf(request.input);+ const botIdsInput = (): string[] =>+ Array.isArray(input.botIds) ? input.botIds.filter((id): id is string => typeof id === 'string') : [];++ if (actionId === 'create') {+ const botIds = botIdsInput();+ await assertBotsVisible(botIds);+ const created = await ownerService().createGroup({ name: input.name, botIds });+ if (!created.ok) refuse(created);+ return {+ effects: [+ { kind: 'refresh-collection', collectionId: BOT_GROUP_REMOTE_COLLECTION_ID },+ { kind: 'navigate', target: { kind: 'resource', ref: groupRef(created.groupId) } },+ ],+ };+ }++ const groupId = request.resourceRef?.collectionId === BOT_GROUP_REMOTE_COLLECTION_ID+ ? request.resourceRef.id+ : null;+ if (!groupId) throw new RemoteResourceRegistryError('INVALID_PARAMS', 'INVALID_PARAMS');+ // Every action re-checks that the phone may still see this group, and any teammate it names.+ await readVisibleGroup(groupId);+ if (actionId === 'update' && typeof input.organizerBotId === 'string') await assertBotsVisible([input.organizerBotId]);+ if (actionId === 'set-members') await assertBotsVisible(botIdsInput());+ if (actionId === 'plan-edit' && typeof input.botId === 'string') await assertBotsVisible([input.botId]);+ const current = ownerService();+ const planInput = { groupId, planId: input.planId };+ let result: { ok: true } | BotGroupFailure;+ switch (actionId) {+ case 'send':+ result = await current.sendMessage({+ groupId,+ text: input.text,+ mentions: input.mentions,+ clientId: input.clientId,+ division: input.division === true,+ });+ break;+ case 'continue':+ result = await current.continueRound(groupId);+ break;+ case 'stop':+ result = await current.stopRound(groupId);+ break;+ case 'update': {+ // A phone cannot point the group at a folder on this computer.+ const patch: Record<string, unknown> = { groupId };+ for (const key of ['name', 'replyMode', 'speakingMode', 'organizerBotId'] as const) {+ if (input[key] !== undefined) patch[key] = input[key];+ }+ result = await current.updateGroup(patch);+ break;+ }+ case 'set-members':+ result = await current.setMembers({ groupId, botIds: botIdsInput() });+ break;+ case 'delete':+ result = await current.deleteGroup(groupId);+ if (!result.ok) refuse(result);+ return { effects: [{ kind: 'refresh-collection', collectionId: BOT_GROUP_REMOTE_COLLECTION_ID }] };+ case 'plan-start':+ result = await current.startPlan(planInput);+ break;+ case 'plan-dismiss':+ result = await current.dismissPlan(planInput);+ break;+ case 'plan-continue':+ result = await current.continuePlan(planInput);+ break;+ case 'plan-retry':+ result = await current.retryPlan(planInput);+ break;+ case 'plan-edit':+ result = await current.editPlanStep({ ...planInput, position: input.position, action: input.action, botId: input.botId });+ break;+ default:+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'INVALID_PARAMS');+ }+ if (!result.ok) refuse(result);+ return { effects: [{ kind: 'refresh-resource', ref: groupRef(groupId) }] };+ },+ });+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 40747c0a56..ce0d4af730 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -114,7 +114,7 @@ import { isRetainableProjectSession } from '../../shared/sessionSource.js';import { initializePluginOauthCards } from '../plugin-oauth/cards.js';import { currentOauthIdentityScope, loadOauthSigningKey } from '../plugin-oauth/desktopIdentity.js';import { readDeviceLinkSettings } from '../device-link/settings-store.js';-import { getDeviceLinkStatus } from '../device-link/index.js';+import { getDeviceLinkStatus, getMobileNotifyGeneration, sendMobileBotGroupNotify } from '../device-link/index.js';import type { AgentMeta, Session as RendererSession } from '../../renderer/lib/ccAgent.types';import {deriveAutoTitleSeed,@@ -459,6 +459,9 @@ import {} from './botDirectMessageService.js';import { createBotGroupChatService, type BotGroupChatService } from './botGroupChatService.js';import { createBotGroupPlanDecider } from './botGroupPlanDecider.js';+import { botGroupMembersVisibleRemotely, registerBotGroupRemoteResourceProvider } from './botGroupRemoteResourceProvider.js';+import { broadcastBotGroupRemoteResourceChanged } from './botGroupRemoteResourceInvalidation.js';+import { getBotGroupStepNotificationBody } from '../sessionNotificationCopy.js';import { createBotGroupWorkDir } from './botGroupWorkDir.js';import { requestUtilityText } from '../utility-model/oneShotCandidates.js';import { validateExistingLocalProjectDirectory } from '../mcp-integrations/createProject.js';@@ -9975,9 +9978,31 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const ownerScope = scope as ReturnType<typeof captureDataOwnerBroadcastScope> | undefined;if (ownerScope && !isDataOwnerBroadcastScopeCurrent(ownerScope)) return;broadcastToAllWindows(MAKER_PUSH.BOT_GROUP_CHANGED, payload, ownerScope);+ // Phones read groups as remote resources; any change re-reads the row and the chat.+ broadcastBotGroupRemoteResourceChanged(payload.groupId);+ },+ onStepSettled: (event, scope) => {+ const ownerScope = scope as ReturnType<typeof captureDataOwnerBroadcastScope> | undefined;+ if (ownerScope && !isDataOwnerBroadcastScopeCurrent(ownerScope)) return;+ const generation = getMobileNotifyGeneration();+ // Same boundary as the phone's group list: a group with a hidden member never reaches it.+ void botGroupMembersVisibleRemotely(event.memberBotIds).then((visible) => {+ if (!visible || (ownerScope && !isDataOwnerBroadcastScopeCurrent(ownerScope))) return;+ sendMobileBotGroupNotify({+ groupId: event.groupId,+ title: event.groupName,+ body: getBotGroupStepNotificationBody(event),+ eventId: `${event.planId}:${event.position}:${event.outcome}:${Date.now()}`,+ generation,+ });+ }).catch((error: unknown) => {+ log.warn('bot group step push skipped', { error: error instanceof Error ? error.message : String(error) });+ });},log,});+ // Phones reach groups through the Remote Resource protocol (bot-group-chat.md §8).+ registerBotGroupRemoteResourceProvider(() => botGroupChatServiceHolder);botDelegationServiceHolder?.dispose();botDelegationServiceHolder = createBotDelegationService({readSessionExecution: id => {diff --git a/apps/desktop/src/main/sessionNotificationCopy.ts b/apps/desktop/src/main/sessionNotificationCopy.tsindex 0c2a704d90..9af56db8ca 100644--- a/apps/desktop/src/main/sessionNotificationCopy.ts+++ b/apps/desktop/src/main/sessionNotificationCopy.ts@@ -38,3 +38,21 @@ export function getSessionExternalNotificationText(title: string, kind: SessionEexport function getTeammateNotificationFallback(): string {return t('settings.notifications.sessionEvent.newReply');}++/** Phone push body for a 分工 step that stopped for the user (bot-group-chat.md §8.3). */+export function getBotGroupStepNotificationBody(event: {+ botName: string;+ task: string;+ outcome: 'done' | 'failed';+ planDone: boolean;+}): string {+ const key = event.outcome === 'failed'+ ? 'settings.notifications.botGroupPlan.stepFailed'+ : event.planDone+ ? 'settings.notifications.botGroupPlan.planDone'+ : 'settings.notifications.botGroupPlan.stepDone';+ // Function replacements: names and tasks are data, never replacement tokens.+ return t(key)+ .replaceAll('{{name}}', () => event.botName)+ .replaceAll('{{task}}', () => event.task);+}diff --git a/apps/desktop/src/renderer/features/bots/botGroupMentions.ts b/apps/desktop/src/renderer/features/bots/botGroupMentions.tsindex 1365c65440..30e06c34d9 100644--- a/apps/desktop/src/renderer/features/bots/botGroupMentions.ts+++ b/apps/desktop/src/renderer/features/bots/botGroupMentions.ts@@ -1,206 +1,5 @@/**- * 群聊输入框里的 @ 点名:纯文本解析,不依赖 React 与 IPC。- *- * 输入框是普通 textarea,点名以 `@名字 ` 的形式留在正文里。发送时以正文为准重新解析- * (手打的 `@小满` 与从候选里选的效果一致),只有「重名」这种正文分辨不了的情况,才用- * 选择候选时记下的 botId 消歧。宿主按解析结果决定谁回答- * (docs/product-rules/bot-group-chat.md §4.1)。+ * 群聊输入框里的 @ 点名:纯文本解析。Desktop 与手机同一套规则(名字不要求后跟空格、+ * 最长优先、重名才用选中时记下的 botId 消歧),正本在 `@cindy/maker-shared/botGroupMentions`。*/-import type { BotGroupMention } from '../../../shared/botGroupChat';--export interface BotGroupMentionMember {- botId: string;- name: string;-}--/** A mention picked from the candidate list; `label` is the text after `@`. */-export interface BotGroupTrackedMention {- botId: string;- label: string;-}--export interface BotGroupMentionQuery {- /** Index of the `@`. */- start: number;- /** Text typed after `@`, up to the caret. */- query: string;-}--/** 候选词最长这么多字;再长就当成普通正文,不再弹候选。 */-const MAX_MENTION_QUERY_CHARS = 32;--/** `@` 紧跟在这些字符后面时是邮箱或标识符的一部分,不是点名。 */-const WORD_BEFORE_AT = /[A-Za-z0-9._%+-]/;-const LATIN_WORD_CHAR = /[A-Za-z0-9_]/;--function isMentionStart(text: string, at: number): boolean {- return at === 0 || !WORD_BEFORE_AT.test(text[at - 1] ?? '');-}--/**- * 中文名后面常常直接接正文(「@小满帮我查一下」),所以名字不要求后面跟空格;- * 只有以拉丁字母或数字结尾的名字才要求词边界,免得 `@Anna` 被当成 `@Ann`。- */-function endsAtBoundary(label: string, next: string | undefined): boolean {- if (next === undefined) return true;- const last = label[label.length - 1] ?? '';- return !(LATIN_WORD_CHAR.test(last) && LATIN_WORD_CHAR.test(next));-}--interface LabelEntry {- label: string;- all: boolean;- botIds: string[];-}--function buildLabelEntries(- members: readonly BotGroupMentionMember[],- allLabels: readonly string[],- tracked: readonly BotGroupTrackedMention[],-): LabelEntry[] {- const byLabel = new Map<string, LabelEntry>();- for (const raw of allLabels) {- const label = raw.trim();- if (label) byLabel.set(label, { label, all: true, botIds: [] });- }- const memberIds = new Set(members.map((member) => member.botId));- const trackedByLabel = new Map<string, string[]>();- for (const mention of tracked) {- const label = mention.label.trim();- if (!label || !memberIds.has(mention.botId)) continue;- const ids = trackedByLabel.get(label) ?? [];- if (!ids.includes(mention.botId)) ids.push(mention.botId);- trackedByLabel.set(label, ids);- }- for (const member of members) {- const label = member.name.trim();- if (!label || byLabel.get(label)?.all) continue;- const entry = byLabel.get(label) ?? { label, all: false, botIds: [] };- if (!entry.botIds.includes(member.botId)) entry.botIds.push(member.botId);- byLabel.set(label, entry);- }- // 重名时正文分辨不出是哪一位,才用选择候选时记下的 botId 收窄。- for (const [label, ids] of trackedByLabel) {- const entry = byLabel.get(label);- if (entry && !entry.all) entry.botIds = ids;- }- // 最长优先:`@小满满` 不能先被 `@小满` 截走。- return [...byLabel.values()].sort((a, b) => b.label.length - a.label.length);-}--interface MentionToken {- start: number;- end: number;- entry: LabelEntry;-}--function scanMentionTokens(text: string, entries: readonly LabelEntry[]): MentionToken[] {- const tokens: MentionToken[] = [];- let index = text.indexOf('@');- while (index >= 0) {- let next = index + 1;- if (isMentionStart(text, index)) {- const entry = entries.find(- (candidate) =>- text.startsWith(candidate.label, index + 1) &&- endsAtBoundary(candidate.label, text[index + 1 + candidate.label.length]),- );- if (entry) {- const end = index + 1 + entry.label.length;- tokens.push({ start: index, end, entry });- next = end;- }- }- index = text.indexOf('@', next);- }- return tokens;-}--/**- * Resolve who a group message addresses. Mentions are re-derived from the text- * at send time; a tracked pick only disambiguates members that share a name.- */-export function resolveBotGroupMentions(- text: string,- input: {- members: readonly BotGroupMentionMember[];- allLabels: readonly string[];- tracked?: readonly BotGroupTrackedMention[];- },-): BotGroupMention {- const entries = buildLabelEntries(input.members, input.allLabels, input.tracked ?? []);- const memberIds = new Set(input.members.map((member) => member.botId));- const botIds: string[] = [];- let all = false;- for (const token of scanMentionTokens(text, entries)) {- if (token.entry.all) all = true;- for (const botId of token.entry.botIds) {- if (memberIds.has(botId) && !botIds.includes(botId)) botIds.push(botId);- }- }- // 按正文里点名的先后输出:宿主直接按这个顺序轮流发言(bot-group-chat.md §4.1)。- return { all, botIds };-}--/** The `@query` being typed right before the caret, if any. */-export function findBotGroupMentionQuery(text: string, caret: number): BotGroupMentionQuery | null {- const before = text.slice(0, Math.max(0, Math.min(caret, text.length)));- const at = before.lastIndexOf('@');- if (at < 0 || !isMentionStart(before, at)) return null;- const query = before.slice(at + 1);- if (query.length > MAX_MENTION_QUERY_CHARS || /\s/.test(query)) return null;- return { start: at, query };-}--/** Case-insensitive match; names starting with the query come first. */-export function filterBotGroupMentionCandidates<T extends { name: string }>(- query: string,- candidates: readonly T[],-): T[] {- const needle = query.trim().toLocaleLowerCase();- if (!needle) return [...candidates];- const prefix: T[] = [];- const inner: T[] = [];- for (const candidate of candidates) {- const name = candidate.name.toLocaleLowerCase();- if (name.startsWith(needle)) prefix.push(candidate);- else if (name.includes(needle)) inner.push(candidate);- }- return [...prefix, ...inner];-}--/** Replace `@query` (from `start` to `end`) with `@label ` and return the new caret. */-export function insertBotGroupMention(- text: string,- range: { start: number; end: number },- label: string,-): { text: string; caret: number } {- const after = text.slice(range.end);- const inserted = after.startsWith(' ') ? `@${label}` : `@${label} `;- const caret = range.start + inserted.length + (after.startsWith(' ') ? 1 : 0);- return { text: text.slice(0, range.start) + inserted + after, caret };-}--export interface BotGroupTextSegment {- text: string;- mention: boolean;-}--/** Split message text so `@name` tokens can be shown as mention chips. */-export function splitBotGroupMentionSegments(- text: string,- labels: readonly string[],-): BotGroupTextSegment[] {- const entries = [...new Set(labels.map((label) => label.trim()).filter(Boolean))]- .sort((a, b) => b.length - a.length)- .map((label) => ({ label, all: false, botIds: [] }));- const segments: BotGroupTextSegment[] = [];- let cursor = 0;- for (const token of scanMentionTokens(text, entries)) {- if (token.start > cursor) segments.push({ text: text.slice(cursor, token.start), mention: false });- segments.push({ text: text.slice(token.start, token.end), mention: true });- cursor = token.end;- }- if (cursor < text.length) segments.push({ text: text.slice(cursor), mention: false });- return segments;-}+export * from '@cindy/maker-shared/botGroupMentions';diff --git a/apps/desktop/src/renderer/features/bots/botGroupPresentation.ts b/apps/desktop/src/renderer/features/bots/botGroupPresentation.tsindex f47f68e6e4..ad8915dba4 100644--- a/apps/desktop/src/renderer/features/bots/botGroupPresentation.ts+++ b/apps/desktop/src/renderer/features/bots/botGroupPresentation.ts@@ -1,251 +1,52 @@/*** 群聊界面的纯展示逻辑:排序、成员名单、错误文案 key、轮次标记与分工(安排、下一步、* 交接文件)的判定。与组件分开,便于不挂 DOM 做单测。+ *+ * 判定本身与手机共用,正本在 `@cindy/maker-shared/botGroupPresentation`;这里只补+ * Desktop 自己的路由参数与 `bots.groupChat.*` 文案 key。*/import {BOT_GROUP_MAX_MEMBERS,BOT_GROUP_MIN_MEMBERS,- isBotGroupPlanOpen,- type BotGroupDetail,type BotGroupErrorCode,- type BotGroupMemberView,- type BotGroupMessageView,type BotGroupNoticeCode,- type BotGroupPlanStepView,- type BotGroupPlanView,- type BotGroupSummary,} from '../../../shared/botGroupChat';+import { botGroupErrorVariant, botGroupNoticeVariant } from '@cindy/maker-shared/botGroupPresentation';++export {+ botGroupComposerPlanState,+ botGroupMemberNames,+ botGroupPathBasename,+ botGroupPlanFilePath,+ botGroupPlanFollowUp,+ botGroupPreviewLine,+ botGroupSidebarPlanPreview,+ continuableRoundEndId,+ currentBotGroupPlanStep,+ isActiveBotGroupMember,+ isBotGroupDivisionBlocked,+ isRunningBotGroupSidebarPreview,+ mergeBotGroupMessages,+ mergeBotGroupPlans,+ openBotGroupPlan,+ sortBotGroups,+ type BotGroupComposerPlanState,+ type BotGroupPlanFollowUp,+ type BotGroupSidebarPlanPreview,+} from '@cindy/maker-shared/botGroupPresentation';export { BOT_GROUP_MAX_MEMBERS, BOT_GROUP_MIN_MEMBERS };/** Route query that opens the group settings drawer over the chat. */export const BOT_GROUP_SETTINGS_PARAM = 'groupSettings';-/** Only active members can be mentioned, speak, or keep a group sendable. */-export function isActiveBotGroupMember(member: Pick<BotGroupMemberView, 'status'>): boolean {- return member.status === 'active';-}--/** Latest activity first, like every other chat list. */-export function sortBotGroups(groups: readonly BotGroupSummary[]): BotGroupSummary[] {- const activityAt = (group: BotGroupSummary) =>- Math.max(group.lastMessage?.createdAt ?? 0, group.updatedAt, group.createdAt);- return [...groups].sort(- (left, right) => activityAt(right) - activityAt(left) || left.id.localeCompare(right.id),- );-}--export function botGroupMemberNames(- members: readonly Pick<BotGroupMemberView, 'name'>[],- separator: string,-): string {- return members- .map((member) => member.name.trim())- .filter(Boolean)- .join(separator);-}--/** Collapse whitespace so a multi-line message fits a one-line preview. */-export function botGroupPreviewLine(text: string): string {- return text.replace(/\s+/g, ' ').trim();-}--/**- * The only round-end that may offer 「继续讨论」: the newest one, and only while- * main says the round can be continued.- */-export function continuableRoundEndId(- messages: readonly Pick<BotGroupMessageView, 'id' | 'kind'>[],- round: { status: 'idle' | 'running'; canContinue: boolean },-): string | null {- if (round.status !== 'idle' || !round.canContinue) return null;- for (let index = messages.length - 1; index >= 0; index -= 1) {- const message = messages[index];- if (message?.kind === 'round-end') return message.id;- }- return null;-}--/** Merge an older page under the latest page, keyed by sequence. */-export function mergeBotGroupMessages(- older: readonly BotGroupMessageView[],- latest: readonly BotGroupMessageView[],-): BotGroupMessageView[] {- const bySequence = new Map<number, BotGroupMessageView>();- for (const message of older) bySequence.set(message.sequence, message);- for (const message of latest) bySequence.set(message.sequence, message);- return [...bySequence.values()].sort((a, b) => a.sequence - b.sequence);-}--const ERROR_KEYS: Partial<Record<BotGroupErrorCode, string>> = {- MEMBER_LIMIT: 'bots.groupChat.errors.memberLimit',- MEMBER_UNAVAILABLE: 'bots.groupChat.errors.memberUnavailable',- NOT_FOUND: 'bots.groupChat.errors.notFound',- HOST_NOT_READY: 'bots.groupChat.errors.hostNotReady',- PLAN_OPEN: 'bots.groupChat.errors.planOpen',- PLAN_CLOSED: 'bots.groupChat.errors.planClosed',-};-/** Specific error copy when main names a cause the user can act on. */export function botGroupErrorKey(errorCode: BotGroupErrorCode | null | undefined, fallback: string): string {- return (errorCode && ERROR_KEYS[errorCode]) || fallback;-}--// ---- 分工 (docs/product-rules/bot-group-chat.md §7) ----------------------------/** Merge plan snapshots from an older page under the latest read; the latest wins. */-export function mergeBotGroupPlans(- older: readonly BotGroupPlanView[],- latest: readonly BotGroupPlanView[],-): BotGroupPlanView[] {- const byId = new Map<string, BotGroupPlanView>();- for (const plan of older) byId.set(plan.id, plan);- for (const plan of latest) byId.set(plan.id, plan);- return [...byId.values()];+ const variant = botGroupErrorVariant(errorCode);+ return variant ? `bots.groupChat.errors.${variant}` : fallback;}-/** The group's open plan with its steps, when main sent it along with the detail. */-export function openBotGroupPlan(- group: Pick<BotGroupDetail, 'openPlan' | 'plans'>,-): BotGroupPlanView | null {- const openId = group.openPlan?.id;- if (!openId) return null;- const plan = group.plans.find((candidate) => candidate.id === openId);- return plan && isBotGroupPlanOpen(plan.status) ? plan : null;-}--/** The step main reports as current (running, being redone, or last finished / failed). */-export function currentBotGroupPlanStep(plan: BotGroupPlanView): BotGroupPlanStepView | null {- if (plan.currentStep === null) return null;- return plan.steps.find((step) => step.position === plan.currentStep) ?? null;-}--export type BotGroupPlanFollowUp =- | { kind: 'continue'; next: BotGroupPlanStepView }- | { kind: 'retry'; failed: BotGroupPlanStepView };--/**- * What the timeline offers under a plan that stopped after a step: 「下一步 · 继续」- * when the step finished and another one waits, 「没做完 · 重试」 when it failed.- */-export function botGroupPlanFollowUp(plan: BotGroupPlanView | null): BotGroupPlanFollowUp | null {- if (!plan || plan.status !== 'waiting') return null;- const current = currentBotGroupPlanStep(plan);- if (!current) return null;- if (current.status === 'failed') return { kind: 'retry', failed: current };- if (current.status !== 'done') return null;- const index = plan.steps.indexOf(current);- const next = plan.steps.slice(index + 1).find((step) => step.status === 'pending');- return next ? { kind: 'continue', next } : null;-}--/** Composer copy that follows the open plan (placeholder and the 「安排分工」 gate). */-export type BotGroupComposerPlanState =- | { kind: 'proposed' }- | { kind: 'running'; botName: string }- | { kind: 'waiting'; botName: string; stepDone: boolean };--export function botGroupComposerPlanState(plan: BotGroupPlanView | null): BotGroupComposerPlanState | null {- if (!plan) return null;- if (plan.status === 'proposed') return { kind: 'proposed' };- const current = currentBotGroupPlanStep(plan);- const botName = current?.botName.trim() ?? '';- if (plan.status === 'running') return { kind: 'running', botName };- if (plan.status === 'waiting') return { kind: 'waiting', botName, stepDone: current?.status === 'done' };- return null;-}--/** A plan that is running or waiting blocks a new 「安排分工」 (main answers PLAN_OPEN). */-export function isBotGroupDivisionBlocked(state: BotGroupComposerPlanState | null): boolean {- return state?.kind === 'running' || state?.kind === 'waiting';-}--const NOTICE_KEYS: Record<BotGroupNoticeCode, string> = {- 'member-failed': 'bots.groupChat.notice.memberFailed',- 'member-timeout': 'bots.groupChat.notice.memberTimeout',- 'member-unavailable': 'bots.groupChat.notice.memberUnavailable',- 'plan-failed': 'bots.groupChat.notice.planFailed',- 'plan-stopped': 'bots.groupChat.notice.planStopped',- 'workdir-unavailable': 'bots.groupChat.notice.workdirUnavailable',-};--/** Member notices inside a plan are about a step, not a chat reply. */-const STEP_NOTICE_KEYS: Partial<Record<BotGroupNoticeCode, string>> = {- 'member-failed': 'bots.groupChat.notice.stepFailed',- 'member-timeout': 'bots.groupChat.notice.stepTimeout',- 'member-unavailable': 'bots.groupChat.notice.stepUnavailable',-};-export function botGroupNoticeKey(code: BotGroupNoticeCode | null, planScoped: boolean): string | null {- if (!code) return null;- return (planScoped ? STEP_NOTICE_KEYS[code] : undefined) ?? NOTICE_KEYS[code] ?? null;-}--/**- * Absolute path of a hand-off file, or null when the entry could leave the plan's- * work directory. Main lists files relative to `workDir` with POSIX separators;- * the join follows the work directory's own separator so Windows paths stay native.- */-export function botGroupPlanFilePath(workDir: string | null, file: string): string | null {- if (!workDir || !file) return null;- if (file.startsWith('/') || file.includes('\\') || /^[A-Za-z]:/.test(file)) return null;- const segments = file.split('/');- if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) return null;- const windows = /^[A-Za-z]:[\\/]/.test(workDir) || workDir.startsWith('\\\\');- const separator = windows ? '\\' : '/';- const base = workDir.replace(/[\\/]+$/, '');- return `${base}${separator}${segments.join(separator)}`;-}--export type BotGroupSidebarPlanPreview =- /** Running treatment: the organizer is working out a plan. */- | { kind: 'planning'; botName: string }- /** Running treatment: a step is in progress. `step` is 1-based. */- | { kind: 'running'; botName: string; step: number | null; total: number }- | { kind: 'proposed'; organizerName: string }- | { kind: 'step-done'; botName: string }- | { kind: 'step-failed'; botName: string }- /** Waiting, but main did not name the step (older host or a removed step). */- | { kind: 'waiting' };--/** Running previews take the speaking row's place (orange sparkles). */-export function isRunningBotGroupSidebarPreview(- preview: BotGroupSidebarPlanPreview | null,-): preview is Extract<BotGroupSidebarPlanPreview, { kind: 'planning' | 'running' }> {- return preview?.kind === 'planning' || preview?.kind === 'running';-}--/**- * Sidebar line for the group's plan: the organizer working out a plan, a step in- * progress, a plan waiting for 开始, or a step waiting for 继续 / 重试. Null falls back- * to the speaking row or the latest message.- */-export function botGroupSidebarPlanPreview(group: BotGroupSummary): BotGroupSidebarPlanPreview | null {- const memberName = (botId: string | null) =>- group.members.find((member) => member.botId === botId)?.name.trim() ?? '';- if (group.planningBotId) return { kind: 'planning', botName: memberName(group.planningBotId) };- const plan = group.openPlan;- if (!plan) return null;- const botName = plan.currentBotName?.trim() ?? '';- if (plan.status === 'running') {- return {- kind: 'running',- botName,- step: plan.currentStep === null ? null : plan.currentStep + 1,- total: plan.stepCount,- };- }- if (plan.status === 'proposed') return { kind: 'proposed', organizerName: memberName(group.organizerBotId) };- if (plan.status === 'waiting') {- if (botName && plan.currentStepStatus === 'done') return { kind: 'step-done', botName };- if (botName && plan.currentStepStatus === 'failed') return { kind: 'step-failed', botName };- return { kind: 'waiting' };- }- return null;-}--/** Last path segment for compact labels (project folder, file chips). */-export function botGroupPathBasename(path: string): string {- const parts = path.split(/[\\/]+/).filter(Boolean);- return parts[parts.length - 1] ?? path;+ const variant = botGroupNoticeVariant(code, planScoped);+ return variant ? `bots.groupChat.notice.${variant}` : null;}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 722702466f..d24c3f3058 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -867,6 +867,11 @@"feishuHint": "Sends a private message via the linked Feishu or Lark bot; only when the window is unfocused.","feishuDisabledHint": "First set up the bot in \"Feishu / Lark Bot\" and DM it once to complete binding.","feishuAria": "Toggle session-done FeiShu notifications",+ "botGroupPlan": {+ "stepDone": "{{name}} finished “{{task}}” — continue when ready",+ "stepFailed": "{{name}} didn't finish “{{task}}” — you can retry",+ "planDone": "The work split is done; the last step was {{name}}’s “{{task}}”"+ },"sessionEvent": {"untitled": "Untitled session","done": "Completed ✓",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 1d31c99843..c76eacd766 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -867,6 +867,11 @@"feishuHint": "連携済みの Feishu または Lark ボットからプライベートメッセージを送信します。ウィンドウが非アクティブの場合のみ送信。","feishuDisabledHint": "先に「Feishu / Lark ボット」で設定し、ボットに 1 度メッセージを送ってバインドを完了してください。","feishuAria": "セッション完了時の Feishu 通知を切り替え",+ "botGroupPlan": {+ "stepDone": "{{name}} が「{{task}}」を終えました。続行を待っています",+ "stepFailed": "{{name}} は「{{task}}」を終えられませんでした。再試行できます",+ "planDone": "役割分担がすべて完了しました(最後は {{name}} の「{{task}}」)"+ },"sessionEvent": {"untitled": "無題のセッション","done": "完了しました ✓",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 5c68e2340d..acf113d14e 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -867,6 +867,11 @@"feishuHint": "연동된 Feishu 또는 Lark 봇을 통해 개인 메시지를 보냅니다. 창이 비활성 상태일 때만 전송됩니다.","feishuDisabledHint": "먼저 \"Feishu / Lark 봇\"에서 봇을 설정하고 한 번 메시지를 보내 바인딩을 완료하세요.","feishuAria": "세션 완료 Feishu 알림 전환",+ "botGroupPlan": {+ "stepDone": "{{name}} 님이 「{{task}}」를 끝냈어요. 계속을 기다려요",+ "stepFailed": "{{name}} 님이 「{{task}}」를 끝내지 못했어요. 다시 시도할 수 있어요",+ "planDone": "역할 분담이 모두 끝났어요. 마지막은 {{name}} 님의 「{{task}}」"+ },"sessionEvent": {"untitled": "제목 없는 세션","done": "완료됨 ✓",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex d98ec5e1d9..36a7de60d5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -867,6 +867,11 @@"feishuHint": "通过已绑定的飞书或 Lark 机器人,向你私聊发送一条消息;仅在窗口失焦时发送。","feishuDisabledHint": "需要先在「飞书 / Lark 机器人」中配置 bot 并向它发送一条消息以完成绑定。","feishuAria": "切换任务完成的飞书通知",+ "botGroupPlan": {+ "stepDone": "{{name}}做完了「{{task}}」,等你继续",+ "stepFailed": "{{name}}没做完「{{task}}」,可以重试",+ "planDone": "分工全部做完了,最后一步是{{name}}的「{{task}}」"+ },"sessionEvent": {"untitled": "未命名任务","done": "已完成 ✓",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 556209062e..c7c3b084db 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -867,6 +867,11 @@"feishuHint": "透過已繫結的飛書或 Lark 機器人,向你私聊傳送一條訊息;僅在視窗失焦時傳送。","feishuDisabledHint": "需要先在「飛書 / Lark 機器人」中配置 bot 並向它傳送一條訊息以完成繫結。","feishuAria": "切換任務完成的飛書通知",+ "botGroupPlan": {+ "stepDone": "{{name}}做完了「{{task}}」,等你繼續",+ "stepFailed": "{{name}}沒做完「{{task}}」,可以重試",+ "planDone": "分工全部做完了,最後一步是{{name}}的「{{task}}」"+ },"sessionEvent": {"untitled": "未命名任務","done": "已完成 ✓",diff --git a/apps/mobile/app/companions/groups/[groupId].tsx b/apps/mobile/app/companions/groups/[groupId].tsxnew file mode 100644index 0000000000..a38e5884dd--- /dev/null+++ b/apps/mobile/app/companions/groups/[groupId].tsx@@ -0,0 +1,21 @@+import { useLocalSearchParams } from 'expo-router';+import { useAuth } from '@/auth/AuthContext';+import { BotGroupChatScreen } from '@/session/BotGroupChatScreen';++function firstParam(value: string | string[] | undefined): string {+ return Array.isArray(value) ? value[0] ?? '' : value ?? '';+}++/**+ * A group chat on one computer (docs/product-rules/bot-group-chat.md §8). Opened from the+ * teammates page or a 分工 notification (`/companions/groups/<groupId>?deviceId=<id>`),+ * which carries no computer name; the screen then shows the id until the group loads.+ */+export default function BotGroupChatRoute() {+ const params = useLocalSearchParams<{ groupId?: string | string[]; deviceId?: string | string[]; deviceName?: string | string[] }>();+ const { accountGeneration } = useAuth();+ const groupId = firstParam(params.groupId);+ const deviceId = firstParam(params.deviceId);+ return <BotGroupChatScreen key={`${accountGeneration}:${deviceId}:${groupId}`} groupId={groupId} deviceId={deviceId}+ deviceName={firstParam(params.deviceName)} />;+}diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsxnew file mode 100644index 0000000000..8bbd036b4c--- /dev/null+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx@@ -0,0 +1,457 @@+// @vitest-environment jsdom+import { act, createElement as el, useEffect, useRef } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';++const h = vi.hoisted(() => ({+ chat: null as any,+ alert: vi.fn(),+ confirm: vi.fn(),+ leave: vi.fn(),+ row: null as any,+ inputs: {} as Record<string, any>,+ teammates: { rows: [] as any[], loading: false, failed: false },+ uuid: 0,+}));++vi.mock('react-native', () => {+ const box = (tag: string) => ({ children, testID, accessibilityLabel }: any) =>+ el(tag, { 'data-testid': testID, 'aria-label': accessibilityLabel }, children);+ return {+ View: box('div'), ScrollView: box('div'), KeyboardAvoidingView: box('div'),+ Pressable: ({ children, onPress, disabled, testID, accessibilityLabel }: any) => el('button',+ { 'data-testid': testID, 'aria-label': accessibilityLabel, disabled, onClick: onPress },+ typeof children === 'function' ? children({ pressed: false }) : children),+ ActivityIndicator: () => el('i', { 'data-testid': 'spinner' }),+ StyleSheet: { create: (value: unknown) => value, hairlineWidth: 1 },+ Platform: { OS: 'ios', select: (value: any) => value.ios },+ Alert: { alert: h.alert },+ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },+ };+});+vi.mock('expo-router', () => ({+ Stack: { Screen: () => null },+ useRouter: () => ({ back: vi.fn(), replace: vi.fn() }),+ useFocusEffect: (effect: () => void) => useEffect(effect, [effect]),+}));+vi.mock('react-native-safe-area-context', () => ({ SafeAreaView: ({ children }: any) => el('main', null, children) }));+vi.mock('react-i18next', async (importOriginal) => ({+ ...await importOriginal<typeof import('react-i18next')>(),+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) => options+ ? `${key}(${Object.entries(options).map(([name, value]) => `${name}=${String(value)}`).join(',')})`+ : key,+ i18n: { language: 'zh-CN' },+ }),+}));+vi.mock('expo-crypto', () => ({ randomUUID: () => `uuid-${++h.uuid}` }));+vi.mock('lucide-react-native', () => Object.fromEntries(+ ['ChevronLeft', 'Settings2', 'Plus', 'Square', 'Users', 'X', 'Check', 'CircleAlert', 'CircleCheck', 'CircleDashed', 'FileText', 'Sparkles', 'Folder']+ .map((name) => [name, () => null]),+));+vi.mock('@/theme', () => ({+ useThemedStyles: () => ({}), useTheme: () => ({ colors: {} }), fontWeight: {}, iconStroke: {}, monoFont: 'mono',+}));+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'owner' }, accountGeneration: 1 }) }));+vi.mock('@/utils/backGuard', () => ({ goBackGuarded: h.leave }));+vi.mock('@/device-link/remoteResourceAvailability', () => ({ readRemoteCollectionCache: () => [] }));+vi.mock('@/platform/chrome', () => ({ showConfirm: h.confirm }));+vi.mock('@/platform/chrome/NativePullDownMenu', () => ({+ usesNativePullDownMenu: () => true,+ NativePullDownMenu: ({ actions, onAction, children, testID, disabled }: any) => {+ const flat = (list: any[]): any[] => list.flatMap((action) => action.subactions ? flat(action.subactions) : [action]);+ return el('div', { 'data-testid': testID }, children, disabled ? null : flat(actions).map((action) => el('button', {+ key: action.id, 'data-testid': `${testID}.action.${action.id}`, 'data-state': action.state, disabled: action.disabled,+ onClick: () => onAction(action.id),+ }, action.title)));+ },+}));+vi.mock('@/components/AppText', () => ({+ Text: ({ children, testID }: any) => el('span', { 'data-testid': testID }, children),+ TextInput: ({ testID, ...props }: any) => { h.inputs[testID] = props; return el('input', { 'data-testid': testID, value: props.value ?? '', readOnly: true }); },+}));+vi.mock('@/components/PaperPlaneIcon', () => ({ PaperPlaneIcon: () => null }));+vi.mock('@/components/MobilePrimitives', () => ({+ MainWindowActionButton: ({ action }: any) => el('button', {+ 'data-testid': action.testID, 'aria-label': action.accessibilityLabel, 'aria-busy': action.busy ? 'true' : undefined,+ disabled: action.disabled || action.busy || !action.onPress, onClick: action.onPress,+ }, action.label),+ MainWindowOptionButton: ({ label, onPress, selected, disabled, testID }: any) => el('button',+ { 'data-testid': testID, 'aria-pressed': selected, disabled, onClick: onPress }, label),+ MainWindowRowButton: ({ children, onPress, testID }: any) => el('button', { 'data-testid': testID, onClick: onPress }, children),+ MainWindowEmptyState: ({ title, copy, children, testID }: any) => el('section', { 'data-testid': testID }, title, copy, children),+}));+vi.mock('@/session/HomeHeaderGlassButton', () => ({+ HomeHeaderGlassButton: ({ onPress, testID, disabled, children }: any) => el('button', { 'data-testid': testID, disabled, onClick: onPress }, children),+}));+vi.mock('@/session/CompanionSheet', () => ({+ CompanionSheet: ({ visible, children, onClosed, testID }: any) => {+ const was = useRef(visible);+ useEffect(() => { if (was.current && !visible) onClosed?.(); was.current = visible; }, [visible]);+ return visible ? el('div', { 'data-testid': testID }, children) : null;+ },+}));+vi.mock('@/session/BotGroupAvatars', () => ({+ BOT_GROUP_MESSAGE_AVATAR_SIZE: 28, BOT_GROUP_STEP_AVATAR_SIZE: 24, BOT_GROUP_INLINE_AVATAR_SIZE: 20, BOT_GROUP_ROW_AVATAR_SIZE: 32,+ BotGroupAvatar: () => null, BotGroupAvatarStack: () => null,+ useBotGroupIdentities: () => (botId: string, fallbackName = '', member?: { name: string }) => ({ botId, name: fallbackName || member?.name || botId }),+}));+vi.mock('@/session/BotGroupSpeakerRow', () => ({+ BotGroupSpeakerRow: ({ identity, activity, sessionId }: any) => el('div', { 'data-testid': `speaker.${identity.botId}.${activity}`, 'data-session': sessionId }, identity.name),+}));+vi.mock('@/session/MobileComposerInputRow', () => ({+ MobileComposerInputRow: (props: any) => { h.row = props; return el('div', { 'data-testid': 'composer-row' }, props.leading, el('span', { 'data-testid': 'placeholder' }, props.placeholder), props.trailing); },+}));+vi.mock('@/session/useHostTeammates', () => ({ useHostTeammates: () => h.teammates }));+vi.mock('@/session/useBotGroupChat', () => ({ useBotGroupChat: () => h.chat }));++import { BotGroupChatScreen } from '@/session/BotGroupChatScreen';++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });++const message = (id: string, sequence: number, overrides: Partial<BotGroupRemoteChatData['messages'][number]>) => ({+ id, sequence, kind: 'message' as const, authorKind: 'bot' as const, authorBotId: null, authorName: '', content: '',+ mentions: { all: false, botIds: [] }, noticeCode: null, planId: null, files: [], createdAt: sequence * 1000, ...overrides,+});++function group(overrides: Partial<BotGroupRemoteChatData> = {}): BotGroupRemoteChatData {+ return {+ id: 'g1', name: '官网介绍页', replyMode: 'all', speakingMode: 'auto',+ members: [+ { botId: 'mimi', name: '咪咪', avatar: '🐱', avatarColor: 'red', status: 'active' },+ { botId: 'abu', name: '阿布', avatar: '🦉', avatarColor: 'blue', status: 'active' },+ { botId: 'xiaoman', name: '小满', avatar: '', avatarColor: '', status: 'active' },+ ],+ organizerBotId: 'mimi', projectDir: null, projectDirName: 'site', lastMessage: null, speakingBotIds: [], planningBotId: null,+ openPlan: { id: 'p1', status: 'proposed', currentStep: null, stepCount: 2, currentBotName: null, currentStepStatus: null },+ createdAt: 1, updatedAt: 2, hasMoreBefore: true,+ round: { status: 'idle', speakers: [], canContinue: true },+ messages: [+ message('m1', 1, { authorKind: 'user', content: '@咪咪 帮我做官网', mentions: { all: false, botIds: ['mimi'] } }),+ message('m2', 2, { authorBotId: 'mimi', authorName: '咪咪', content: '**好的**,我看看' }),+ message('m3', 3, { kind: 'round-end', authorKind: 'system' }),+ message('m4', 4, { kind: 'notice', authorKind: 'system', authorBotId: 'abu', authorName: '阿布', noticeCode: 'member-failed' }),+ message('m5', 5, { kind: 'round-end', authorKind: 'system' }),+ message('m6', 6, { kind: 'plan', authorBotId: 'mimi', authorName: '咪咪', planId: 'p1' }),+ message('m7', 7, { authorBotId: 'abu', authorName: '阿布', content: '写好了', planId: 'p0', files: ['docs/页面想法.md'] }),+ message('m8', 8, { kind: 'notice', authorKind: 'system', authorName: '阿布', noticeCode: 'member-timeout', planId: 'p0' }),+ message('m9', 9, { kind: 'plan-end', authorKind: 'system', planId: 'p0' }),+ ],+ plans: [+ { id: 'p1', status: 'proposed', organizerBotId: 'mimi', organizerName: '咪咪', currentStep: null, workDir: null, branch: null, createdAt: 1, updatedAt: 1,+ steps: [+ { position: 0, botId: 'mimi', botName: '咪咪', task: '想清楚这页讲什么', status: 'pending' },+ { position: 1, botId: 'abu', botName: '阿布', task: '写代码', status: 'pending' },+ ] },+ { id: 'p0', status: 'done', organizerBotId: 'mimi', organizerName: '咪咪', currentStep: 2, workDir: null, branch: null, createdAt: 1, updatedAt: 1,+ steps: [0, 1, 2].map((position) => ({ position, botId: 'abu', botName: '阿布', task: `步骤${position}`, status: 'done' as const })) },+ ],+ ...overrides,+ };+}++let root: Root;+let node: HTMLDivElement;+const byId = (id: string) => node.querySelector(`[data-testid="${id}"]`) as HTMLButtonElement | null;+const all = (id: string) => [...node.querySelectorAll(`[data-testid="${id}"]`)];+async function click(id: string) {+ const target = byId(id);+ if (!target) throw new Error(`missing ${id}`);+ await act(async () => { target.click(); });+}+async function render(data: BotGroupRemoteChatData | null = group(), kind: 'ready' | 'loading' | 'missing' | 'error' = 'ready') {+ h.chat = {+ ...h.chat,+ state: kind === 'ready' ? { kind, group: data } : kind === 'error' ? { kind, message: 'x' } : { kind },+ };+ await act(async () => root.render(el(BotGroupChatScreen, { deviceId: 'mac', deviceName: 'Mac', groupId: 'g1' })));+}++beforeEach(() => {+ vi.clearAllMocks();+ h.uuid = 0; h.inputs = {}; h.teammates = { rows: [], loading: false, failed: false };+ h.chat = { reload: vi.fn(), act: vi.fn(async () => ({ effects: [] })), online: true };+ h.confirm.mockResolvedValue(true);+ node = document.createElement('div');+ root = createRoot(node);+});+afterEach(async () => { await act(async () => root.unmount()); });++describe('group timeline', () => {+ it('renders messages, notices, round ends and plan ends like the desktop timeline', async () => {+ await render();+ expect(byId('botGroup.message.user')?.textContent).toBe('@咪咪 帮我做官网');+ expect(all('botGroup.message.bot')[0]?.textContent).toContain('好的,我看看');+ expect(all('botGroup.message.bot')[0]?.textContent).not.toContain('**');+ const notices = all('botGroup.notice').map((entry) => entry.textContent);+ // A plain member failure speaks about a reply; inside a plan it speaks about a step.+ expect(notices).toEqual(['groupChat.notice.memberFailed(name=阿布)', 'groupChat.notice.stepTimeout(name=阿布)']);+ // Only the newest round end offers 继续讨论.+ expect(all('botGroup.roundEnd')).toHaveLength(2);+ expect(all('botGroup.continue')).toHaveLength(1);+ expect(byId('botGroup.planEnd')?.textContent).toBe('groupChat.timeline.planDone(count=3)');+ expect(byId('botGroup.file')?.textContent).toBe('页面想法.md');+ expect(byId('botGroup.olderOnComputer')).not.toBeNull();+ expect(byId('botGroup.organizerTag')?.textContent).toBe('groupChat.organizer');+ expect(node.textContent).toContain('咪咪groupChat.memberSeparator阿布groupChat.memberSeparator小满');+ });++ it('continues the round and explains files that stay on the computer', async () => {+ await render();+ await click('botGroup.continue');+ expect(h.chat.act).toHaveBeenCalledWith('continue');+ await click('botGroup.file');+ expect(h.alert).toHaveBeenCalledWith('docs/页面想法.md', 'groupChat.files.onComputer');+ });++ it('starts, dismisses and edits a proposed plan through the group actions', async () => {+ await render();+ expect(byId('botGroup.plan.proposed')).not.toBeNull();+ await click('botGroup.plan.start');+ expect(h.chat.act).toHaveBeenLastCalledWith('plan-start', { planId: 'p1' });+ await click('botGroup.plan.dismiss');+ expect(h.chat.act).toHaveBeenLastCalledWith('plan-dismiss', { planId: 'p1' });+ // The current Bot is checked; choosing it again changes nothing.+ expect(byId('botGroup.plan.stepMenu.1.action.member:abu')?.getAttribute('data-state')).toBe('on');+ await click('botGroup.plan.stepMenu.1.action.member:abu');+ expect(h.chat.act).toHaveBeenCalledTimes(2);+ await click('botGroup.plan.stepMenu.1.action.member:xiaoman');+ expect(h.chat.act).toHaveBeenLastCalledWith('plan-edit', { planId: 'p1', position: 1, action: 'reassign', botId: 'xiaoman' });+ await click('botGroup.plan.stepMenu.0.action.remove');+ expect(h.chat.act).toHaveBeenLastCalledWith('plan-edit', { planId: 'p1', position: 0, action: 'remove' });+ });++ it('keeps at least one step and names the host’s reason when an action is refused', async () => {+ const data = group();+ data.plans[0]!.steps = [data.plans[0]!.steps[0]!];+ h.chat.act.mockRejectedValueOnce(Object.assign(new Error('PLAN_CLOSED'), { code: 'INVALID_PARAMS' }));+ await render(data);+ expect(byId('botGroup.plan.stepMenu.0.action.remove')?.disabled).toBe(true);+ await click('botGroup.plan.start');+ expect(h.alert).toHaveBeenCalledWith('groupChat.errors.planClosed');+ });++ it('offers 继续 / 结束分工 after a finished step and reassigns only what is not done', async () => {+ const data = group({ openPlan: { id: 'p1', status: 'waiting', currentStep: 0, stepCount: 2, currentBotName: '咪咪', currentStepStatus: 'done' } });+ data.plans[0] = { ...data.plans[0]!, status: 'waiting', currentStep: 0,+ steps: [{ ...data.plans[0]!.steps[0]!, status: 'done' }, data.plans[0]!.steps[1]!] };+ await render(data);+ expect(byId('botGroup.plan.start')).toBeNull();+ expect(byId('botGroup.plan.stepMenu.0')).toBeNull();+ expect(byId('botGroup.plan.stepMenu.1.action.remove')).toBeNull();+ await click('botGroup.plan.stepMenu.1.action.member:xiaoman');+ expect(h.chat.act).toHaveBeenLastCalledWith('plan-edit', { planId: 'p1', position: 1, action: 'reassign', botId: 'xiaoman' });+ expect(byId('botGroup.followUpRow.continue')?.textContent).toContain('阿布');+ await click('botGroup.followUp.continue');+ expect(h.chat.act).toHaveBeenLastCalledWith('plan-continue', { planId: 'p1' });+ await click('botGroup.followUp.end');+ expect(h.chat.act).toHaveBeenLastCalledWith('plan-dismiss', { planId: 'p1' });+ expect(byId('placeholder')?.textContent).toBe('groupChat.composer.placeholderPlanWaiting(name=咪咪)');+ });++ it('offers 重试 when a step did not finish', async () => {+ const data = group({ openPlan: { id: 'p1', status: 'waiting', currentStep: 1, stepCount: 2, currentBotName: '阿布', currentStepStatus: 'failed' } });+ data.plans[0] = { ...data.plans[0]!, status: 'waiting', currentStep: 1,+ steps: [{ ...data.plans[0]!.steps[0]!, status: 'done' }, { ...data.plans[0]!.steps[1]!, status: 'failed' }] };+ await render(data);+ expect(byId('botGroup.followUp.retry')?.textContent).toContain('groupChat.timeline.retryStep');+ expect(node.textContent).toContain('groupChat.timeline.stepFailed(name=阿布)');+ await click('botGroup.followUp.retry');+ expect(h.chat.act).toHaveBeenLastCalledWith('plan-retry', { planId: 'p1' });+ });++ it('shows superseded and stopped plans read-only', async () => {+ const data = group({ openPlan: null });+ data.plans[0] = { ...data.plans[0]!, status: 'superseded' };+ await render(data);+ expect(byId('botGroup.plan.start')).toBeNull();+ expect(byId('botGroup.plan.stepMenu.0')).toBeNull();+ expect(byId('botGroup.plan.finalNote')?.textContent).toBe('groupChat.plan.superseded');+ });++ it('shows one row per speaker with its lane session', async () => {+ await render(group({ round: { status: 'running', canContinue: false, speakers: [+ { botId: 'abu', sessionId: 's-abu', activity: 'reply' },+ { botId: 'mimi', sessionId: null, activity: 'planning' },+ { botId: 'ghost', sessionId: 's-x', activity: 'reply' },+ ] } }));+ expect(byId('speaker.abu.reply')?.getAttribute('data-session')).toBe('s-abu');+ expect(byId('speaker.mimi.planning')).not.toBeNull();+ expect(byId('speaker.ghost.reply')).toBeNull();+ expect(all('botGroup.continue')).toHaveLength(0);+ });++ it('shows the unavailable and failed states', async () => {+ await render(null, 'missing');+ expect(byId('botGroup.unavailable')).not.toBeNull();+ await click('botGroup.leave');+ expect(h.leave).toHaveBeenCalled();+ await render(null, 'error');+ await click('botGroup.retry');+ expect(h.chat.reload).toHaveBeenCalled();+ });+});++describe('group composer', () => {+ async function type(text: string) {+ await act(async () => {+ h.row.onFocus();+ h.row.onChangeText(text);+ h.row.onSelectionChange({ nativeEvent: { selection: { start: text.length, end: text.length } } });+ });+ }++ it('offers 所有人 first, inserts a picked teammate and sends the resolved mentions', async () => {+ await render(group({ openPlan: null }));+ await type('请 @');+ const options = [...node.querySelectorAll('[data-testid^="botGroup.mention."]')].map((entry) => entry.getAttribute('data-testid'));+ expect(options).toEqual(['botGroup.mention.all', 'botGroup.mention.mimi', 'botGroup.mention.abu', 'botGroup.mention.xiaoman']);+ await click('botGroup.mention.abu');+ expect(h.row.value).toBe('请 @阿布 ');+ await type('请 @阿布 写代码');+ await click('botGroup.composer.send');+ expect(h.chat.act).toHaveBeenLastCalledWith('send', {+ text: '请 @阿布 写代码', mentions: { all: false, botIds: ['abu'] }, clientId: 'uuid-1',+ });+ expect(h.row.value).toBe('');+ });++ it('sends a 分工 message and keeps the clientId and tag for a retry', async () => {+ await render(group({ openPlan: null }));+ expect(byId('botGroup.divisionTag')).toBeNull();+ await click('botGroup.composer.menu.action.division');+ expect(byId('botGroup.divisionTag')).not.toBeNull();+ expect(byId('placeholder')?.textContent).toBe('groupChat.composer.placeholderDivision');+ await type('做个官网');+ h.chat.act.mockRejectedValueOnce(new Error('[NOT_CONNECTED] offline'));+ await click('botGroup.composer.send');+ expect(h.chat.act).toHaveBeenLastCalledWith('send', expect.objectContaining({ text: '做个官网', clientId: 'uuid-1', division: true }));+ expect(h.alert).toHaveBeenCalledWith('groupChat.composer.sendFailed');+ // The draft and its tag come back; the retry reuses the same idempotency key.+ expect(h.row.value).toBe('做个官网');+ expect(byId('botGroup.divisionTag')).not.toBeNull();+ await click('botGroup.composer.send');+ expect(h.chat.act).toHaveBeenLastCalledWith('send', expect.objectContaining({ clientId: 'uuid-1', division: true }));+ expect(byId('botGroup.divisionTag')).toBeNull();+ // Removing the tag makes it a different message with its own key.+ await click('botGroup.composer.menu.action.division');+ await type('再做一个');+ h.chat.act.mockRejectedValueOnce(new Error('[NOT_CONNECTED] offline'));+ await click('botGroup.composer.send');+ expect(h.chat.act.mock.calls.at(-1)![1]).toMatchObject({ clientId: 'uuid-2', division: true });+ await click('botGroup.divisionTag.remove');+ await click('botGroup.composer.send');+ const last = h.chat.act.mock.calls.at(-1)![1];+ expect(last).toMatchObject({ text: '再做一个', clientId: 'uuid-3' });+ expect(last).not.toHaveProperty('division');+ });++ it('explains why 安排分工 is unavailable while a plan runs, and stops the round when empty', async () => {+ const data = group({+ openPlan: { id: 'p1', status: 'running', currentStep: 0, stepCount: 2, currentBotName: '咪咪', currentStepStatus: 'running' },+ round: { status: 'running', speakers: [{ botId: 'mimi', sessionId: 's1', activity: 'step' }], canContinue: false },+ });+ data.plans[0] = { ...data.plans[0]!, status: 'running', currentStep: 0, steps: [{ ...data.plans[0]!.steps[0]!, status: 'running' }, data.plans[0]!.steps[1]!] };+ await render(data);+ expect(byId('botGroup.composer.menu')).toBeNull();+ await click('botGroup.composer.more');+ expect(h.alert).toHaveBeenCalledWith('groupChat.composer.division', 'groupChat.composer.divisionBusy');+ expect(byId('placeholder')?.textContent).toBe('groupChat.composer.placeholderPlanRunning(name=咪咪)');+ await click('botGroup.composer.stop');+ expect(h.chat.act).toHaveBeenLastCalledWith('stop');+ });+});++describe('group settings', () => {+ async function openSettings(data = group()) {+ await render(data);+ await click('botGroup.settingsButton');+ expect(byId('botGroup.settings')).not.toBeNull();+ }++ it('renames, changes the organizer and edits members on this computer', async () => {+ h.teammates = { rows: [{ key: 'k', host: { deviceId: 'mac', deviceName: 'Mac' }, item: {+ ref: { collectionId: 'teammates', kind: 'bot', id: 'ahua' }, revision: '1', display: { title: '阿花' }, links: [],+ } }, { key: 'k2', host: { deviceId: 'mac', deviceName: 'Mac' }, item: {+ ref: { collectionId: 'teammates', kind: 'bot', id: 'abu' }, revision: '1', display: { title: '阿布' }, links: [],+ } }], loading: false, failed: false };+ await openSettings();+ await act(async () => { h.inputs['botGroup.settings.name'].onChangeText('新名字'); });+ await act(async () => { h.inputs['botGroup.settings.name'].onBlur(); });+ expect(h.chat.act).toHaveBeenLastCalledWith('update', { name: '新名字' });+ expect(byId('botGroup.settings.organizer.mimi')).toBeNull();+ await click('botGroup.settings.organizer.abu');+ expect(h.chat.act).toHaveBeenLastCalledWith('update', { organizerBotId: 'abu' });+ await click('botGroup.settings.remove.xiaoman');+ expect(h.chat.act).toHaveBeenLastCalledWith('set-members', { botIds: ['mimi', 'abu'] });+ await click('botGroup.settings.add');+ // Current members are not offered again.+ expect(byId('botGroup.settings.addable.abu')).toBeNull();+ await click('botGroup.settings.addable.ahua');+ expect(h.chat.act).toHaveBeenLastCalledWith('set-members', { botIds: ['mimi', 'abu', 'xiaoman', 'ahua'] });+ });++ it('switches reply and speaking modes, shows the folder read-only, and reports failures', async () => {+ await openSettings();+ expect(byId('botGroup.settings.projectDir')?.textContent).toContain('site');+ expect(byId('botGroup.settings.projectDir')?.textContent).toContain('groupChat.settings.projectDirOnComputer');+ await click('botGroup.settings.replyMode.all');+ expect(h.chat.act).not.toHaveBeenCalled();+ await click('botGroup.settings.replyMode.mentioned');+ expect(h.chat.act).toHaveBeenLastCalledWith('update', { replyMode: 'mentioned' });+ h.chat.act.mockRejectedValueOnce(new Error('[INVALID_PARAMS] MEMBER_LIMIT'));+ await click('botGroup.settings.speakingMode.sequential');+ expect(h.chat.act).toHaveBeenLastCalledWith('update', { speakingMode: 'sequential' });+ expect(node.textContent).toContain('groupChat.errors.memberLimit');+ });++ it('keeps two members at least', async () => {+ const data = group();+ data.members = data.members.slice(0, 2);+ await openSettings(data);+ expect(byId('botGroup.settings.remove.abu')?.disabled).toBe(true);+ });++ it('deletes after the system confirmation, then leaves once the sheet has closed', async () => {+ h.confirm.mockResolvedValueOnce(false);+ await openSettings();+ await click('botGroup.settings.delete');+ expect(h.chat.act).not.toHaveBeenCalled();+ await click('botGroup.settings.delete');+ expect(h.confirm).toHaveBeenLastCalledWith(expect.objectContaining({ destructive: true, confirmLabel: 'groupChat.settings.delete' }));+ expect(h.chat.act).toHaveBeenLastCalledWith('delete', {});+ expect(byId('botGroup.settings')).toBeNull();+ expect(h.leave).toHaveBeenCalledOnce();+ // The later re-read that finds the group gone does not leave a second time.+ await render(null, 'missing');+ expect(h.leave).toHaveBeenCalledOnce();+ });++ it('still leaves when the group reads as gone before the delete returns', async () => {+ let finish!: () => void;+ h.chat.act.mockImplementationOnce(() => new Promise((resolve) => { finish = () => resolve({ effects: [] }); }));+ await openSettings();+ await click('botGroup.settings.delete');+ // The computer's change announcement re-reads the group first, which unmounts the sheet.+ await render(null, 'missing');+ expect(byId('botGroup.settings')).toBeNull();+ expect(h.leave).not.toHaveBeenCalled();+ await act(async () => { finish(); });+ expect(h.leave).toHaveBeenCalledOnce();+ });+});++describe('offline computer', () => {+ it('says the computer is offline instead of spinning, and disables actions on a loaded group', async () => {+ h.chat = { ...h.chat, online: false };+ await render(null, 'loading');+ expect(byId('botGroup.offline')?.textContent).toContain('devices.resources.hostOffline');+ expect(byId('spinner')).toBeNull();+ await render();+ expect(byId('botGroup.offlineNote')).not.toBeNull();+ expect(byId('botGroup.plan.start')?.disabled).toBe(true);+ expect(byId('botGroup.continue')?.disabled).toBe(true);+ expect(h.row.editable).toBe(false);+ });+});diff --git a/apps/mobile/src/__tests__/BotGroupList.test.tsx b/apps/mobile/src/__tests__/BotGroupList.test.tsxnew file mode 100644index 0000000000..b0d33164e5--- /dev/null+++ b/apps/mobile/src/__tests__/BotGroupList.test.tsx@@ -0,0 +1,209 @@+// @vitest-environment jsdom+import { act, createElement as el, useEffect, useRef } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';++const h = vi.hoisted(() => ({+ invoke: vi.fn(),+ openLink: vi.fn(async () => undefined),+ inputs: {} as Record<string, any>,+ teammates: { rows: [] as any[], loading: false, failed: false },+ alert: vi.fn(),+ nativeMenu: true,+}));++vi.mock('react-native', () => {+ const box = ({ children, testID, accessibilityLabel }: any) => el('div', { 'data-testid': testID, 'aria-label': accessibilityLabel }, children);+ return {+ View: box, ScrollView: box,+ Pressable: ({ children, onPress, disabled, testID, accessibilityLabel }: any) => el('button',+ { 'data-testid': testID, 'aria-label': accessibilityLabel, disabled, onClick: onPress },+ typeof children === 'function' ? children({ pressed: false }) : children),+ ActivityIndicator: () => null,+ StyleSheet: { create: (value: unknown) => value, hairlineWidth: 1 },+ Alert: { alert: h.alert },+ };+});+vi.mock('react-i18next', async (importOriginal) => ({+ ...await importOriginal<typeof import('react-i18next')>(),+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) => options+ ? `${key}(${Object.entries(options).map(([name, value]) => `${name}=${String(value)}`).join(',')})` : key,+ i18n: { language: 'zh-CN' },+ }),+}));+vi.mock('lucide-react-native', () => ({ Plus: () => null, Sparkles: ({ testID }: any) => el('i', { 'data-testid': testID }), Check: () => null, Users: () => null }));+vi.mock('@/theme', () => ({ useThemedStyles: () => ({}), useTheme: () => ({ colors: {} }), fontWeight: {}, iconStroke: {} }));+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'owner' }, accountGeneration: 1 }) }));+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke: h.invoke, openLink: h.openLink }) }));+vi.mock('@/utils/useMinuteNow', () => ({ useMinuteNow: () => 0 }));+vi.mock('@/session/sessionList', () => ({ formatRemoteSessionSidebarTime: () => '9:41' }));+vi.mock('@/components/AppText', () => ({+ Text: ({ children, testID }: any) => el('span', { 'data-testid': testID }, children),+ TextInput: ({ testID, ...props }: any) => { h.inputs[testID] = props; return el('input', { 'data-testid': testID, value: props.value ?? '', readOnly: true }); },+}));+vi.mock('@/components/MobilePrimitives', () => ({+ MainWindowActionButton: ({ action }: any) => el('button', { 'data-testid': action.testID, disabled: action.disabled || action.busy, onClick: action.onPress }, action.label),+ MainWindowRowButton: ({ children, onPress, testID }: any) => el('button', { 'data-testid': testID, onClick: onPress }, children),+}));+vi.mock('@/platform/chrome/NativePullDownMenu', () => ({+ usesNativePullDownMenu: () => h.nativeMenu,+ NativePullDownMenu: ({ actions, onAction, children, testID }: any) => {+ const flat = (list: any[]): any[] => list.flatMap((action) => action.subactions ? flat(action.subactions) : [action]);+ return el('div', { 'data-testid': testID }, children, flat(actions).map((action) => el('button', {+ key: action.id, 'data-testid': `${testID}.action.${action.id}`, onClick: () => onAction(action.id),+ }, action.title)));+ },+}));+vi.mock('@/session/CompanionSheet', () => ({+ CompanionSheet: ({ visible, children, onClosed, testID }: any) => {+ const was = useRef(visible);+ useEffect(() => { if (was.current && !visible) onClosed?.(); was.current = visible; }, [visible]);+ return visible ? el('div', { 'data-testid': testID }, children) : null;+ },+}));+vi.mock('@/session/BotGroupAvatars', () => ({+ BOT_GROUP_ROW_AVATAR_SIZE: 32,+ BotGroupAvatar: () => null,+ BotGroupDuoAvatar: ({ members }: any) => el('span', { 'data-testid': 'duo' }, members.map((member: any) => member.name).join('+')),+ useBotGroupIdentities: () => (botId: string, fallbackName = '') => ({ botId, name: fallbackName || botId }),+}));+vi.mock('@/session/useHostTeammates', () => ({ useHostTeammates: () => h.teammates }));++import { BotGroupSection } from '@/session/BotGroupList';++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });++const row = (deviceId: string, id: string, display: Record<string, unknown>): HostedRemoteCollectionItem => ({+ key: `${deviceId}:${id}`, host: { deviceId, deviceName: deviceId === 'mac' ? 'Mac' : 'PC' },+ item: { ref: { collectionId: 'bot-groups', kind: 'bot-group', id }, revision: '1', display: { title: id, ...display }, links: [+ { rel: 'member', target: { kind: 'resource', ref: { collectionId: 'teammates', kind: 'bot', id: 'mimi' } }, label: '咪咪' },+ { rel: 'member', target: { kind: 'resource', ref: { collectionId: 'teammates', kind: 'bot', id: 'abu' } }, label: '阿布' },+ ] },+});+const teammate = (id: string, title: string) => ({ key: `mac:${id}`, host: { deviceId: 'mac', deviceName: 'Mac' },+ item: { ref: { collectionId: 'teammates', kind: 'bot', id }, revision: '1', display: { title }, links: [] } });++let root: Root;+let node: HTMLDivElement;+const byId = (id: string) => node.querySelector(`[data-testid="${id}"]`) as HTMLButtonElement | null;+async function click(id: string) {+ const target = byId(id);+ if (!target) throw new Error(`missing ${id}`);+ await act(async () => { target.click(); });+}+const props = (overrides: Record<string, unknown> = {}) => ({+ items: [row('mac', 'g-old', { timestamp: 1, preview: '**阿布**:写好了' }), row('pc', 'g-new', { timestamp: 5, generation: { phase: 'processing', startedAt: null }, preview: { fallback: 'Mimi is splitting the work…', translations: { 'zh-CN': '咪咪正在安排…' } } })],+ query: '',+ isOnline: () => true,+ createTargets: [{ deviceId: 'mac', deviceName: 'Mac' }],+ onOpen: vi.fn(), onOpenCreated: vi.fn(),+ ...overrides,+});+async function render(value = props()) {+ await act(async () => root.render(el(BotGroupSection, value as any)));+ return value;+}++beforeEach(() => {+ vi.clearAllMocks(); h.inputs = {}; h.nativeMenu = true;+ h.teammates = { rows: [teammate('mimi', '咪咪'), teammate('abu', '阿布'), teammate('xiaoman', '小满')], loading: false, failed: false };+ node = document.createElement('div'); root = createRoot(node);+});+afterEach(async () => { await act(async () => root.unmount()); });++describe('group section', () => {+ it('lists groups newest first with member avatars, localized previews and a running mark', async () => {+ const value = await render();+ const rows = [...node.querySelectorAll('[data-testid^="botGroups.item."]')];+ expect(rows.map((entry) => entry.getAttribute('data-testid'))).toEqual(['botGroups.item.pc.g-new', 'botGroups.item.mac.g-old']);+ expect(rows[0]!.textContent).toContain('咪咪正在安排…');+ expect(rows[1]!.textContent).toContain('阿布:写好了');+ expect(rows[1]!.textContent).not.toContain('**');+ expect(rows[0]!.querySelector('[data-testid="botGroups.running"]')).not.toBeNull();+ expect(rows[1]!.querySelector('[data-testid="botGroups.running"]')).toBeNull();+ expect(byId('duo')?.textContent).toBe('咪咪+阿布');+ await click('botGroups.item.mac.g-old');+ expect(value.onOpen).toHaveBeenCalledWith(value.items[0]);+ });++ it('disables groups whose computer is offline and hides the running mark there', async () => {+ await render(props({ isOnline: (host: { deviceId: string }) => host.deviceId === 'mac' }));+ expect(byId('botGroups.item.pc.g-new')?.disabled).toBe(true);+ expect(byId('botGroups.item.pc.g-new')?.textContent).toContain('devices.resources.hostOffline');+ expect(byId('botGroups.running')).toBeNull();+ });++ it('filters by the teammate search and shows an empty hint', async () => {+ await render(props({ query: '阿布' }));+ expect(node.querySelectorAll('[data-testid^="botGroups.item."]')).toHaveLength(2);+ await render(props({ query: '没有的' }));+ expect(byId('botGroups.section')).toBeNull();+ await render(props({ items: [] }));+ expect(byId('botGroups.empty')?.textContent).toBe('groupChat.list.empty');+ });+});++describe('create a group', () => {+ it('creates on the only computer with 2–6 teammates in list order, then opens it after the sheet closes', async () => {+ const value = await render();+ await click('botGroups.create');+ expect(byId('botGroup.create')).not.toBeNull();+ await click('botGroup.create.submit');+ expect(node.textContent).toContain('groupChat.create.nameRequired');+ expect(node.textContent).toContain('groupChat.create.minMembers(min=2)');+ expect(h.invoke).not.toHaveBeenCalled();+ await act(async () => { h.inputs['botGroup.create.name'].onChangeText(' 官网 '); });+ await click('botGroup.create.member.abu');+ await click('botGroup.create.member.mimi');+ h.invoke.mockResolvedValueOnce({ effects: [+ { kind: 'refresh-collection', collectionId: 'bot-groups' },+ { kind: 'navigate', target: { kind: 'resource', ref: { collectionId: 'bot-groups', kind: 'bot-group', id: 'g9' } } },+ ] });+ await click('botGroup.create.submit');+ const request = h.invoke.mock.calls[0]!;+ expect(request[0]).toBe('mac');+ expect(request[1]).toBe('maker:remote-resources:invoke');+ expect(request[2][0]).toMatchObject({ collectionId: 'bot-groups', actionId: 'create', input: { name: '官网', botIds: ['mimi', 'abu'] } });+ expect(byId('botGroup.create')).toBeNull();+ expect(value.onOpenCreated).toHaveBeenCalledWith({ deviceId: 'mac', deviceName: 'Mac' }, 'g9');+ });++ it('shows the host’s reason when it refuses', async () => {+ await render();+ await click('botGroups.create');+ await act(async () => { h.inputs['botGroup.create.name'].onChangeText('官网'); });+ await click('botGroup.create.member.abu');+ await click('botGroup.create.member.mimi');+ h.invoke.mockRejectedValueOnce(Object.assign(new Error('MEMBER_UNAVAILABLE'), { code: 'INVALID_PARAMS' }));+ await click('botGroup.create.submit');+ expect(byId('botGroup.create.error')?.textContent).toBe('groupChat.errors.memberUnavailable');+ });++ it('asks which computer hosts the group when several support it', async () => {+ const value = await render(props({ createTargets: [{ deviceId: 'mac', deviceName: 'Mac' }, { deviceId: 'pc', deviceName: 'PC' }], preferredDeviceId: 'pc' }));+ const options = [...node.querySelectorAll('[data-testid^="botGroups.createMenu.action."]')].map((entry) => entry.textContent);+ expect(options).toEqual(['PC', 'Mac']);+ await click('botGroups.createMenu.action.pc');+ expect(node.textContent).toContain('groupChat.create.computerNote(deviceName=PC)');+ expect(value.onOpenCreated).not.toHaveBeenCalled();+ });++ it('falls back to a sheet of the same choices where the platform has no anchored menu', async () => {+ h.nativeMenu = false;+ await render(props({ createTargets: [{ deviceId: 'mac', deviceName: 'Mac' }, { deviceId: 'pc', deviceName: 'PC' }] }));+ expect(byId('botGroups.createMenu.sheet')).toBeNull();+ await click('botGroups.create');+ expect(byId('botGroups.createMenu.sheet')).not.toBeNull();+ await click('botGroups.createMenu.option.pc');+ // The create sheet opens only after the chooser has closed.+ expect(byId('botGroups.createMenu.sheet')).toBeNull();+ expect(node.textContent).toContain('groupChat.create.computerNote(deviceName=PC)');+ });++ it('cannot create while no computer that supports groups is online', async () => {+ await render(props({ createTargets: [] }));+ expect(byId('botGroups.create')?.disabled).toBe(true);+ });+});diff --git a/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsx b/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsxnew file mode 100644index 0000000000..ba5a8ca9f4--- /dev/null+++ b/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsx@@ -0,0 +1,101 @@+// @vitest-environment jsdom+import { act, createElement as el, useEffect } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ invoke: vi.fn(),+ subscribe: vi.fn(async () => undefined),+ unsubscribe: vi.fn(async () => undefined),+ setPending: vi.fn(),+ pending: {} as Record<string, unknown[]>,+ live: {} as Record<string, unknown>,+ copy: vi.fn(),+ panel: null as any,+}));++vi.mock('react-native', () => ({+ View: ({ children, testID, accessibilityLabel }: any) => el('div', { 'data-testid': testID, 'aria-label': accessibilityLabel }, children),+ StyleSheet: { create: (value: unknown) => value },+}));+vi.mock('expo-router', () => ({ useFocusEffect: (effect: () => void) => useEffect(effect, [effect]) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, options?: { name?: string }) => options?.name ? `${key}:${options.name}` : key }) }));+vi.mock('lucide-react-native', () => ({ CircleAlert: () => null, Sparkles: () => null }));+vi.mock('@/theme', () => ({ useThemedStyles: () => ({}), useTheme: () => ({ colors: {} }) }));+vi.mock('@/components/AppText', () => ({ Text: ({ children }: any) => el('span', null, children) }));+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke: h.invoke, subscribe: h.subscribe, unsubscribe: h.unsubscribe }) }));+vi.mock('@/session/BotGroupAvatars', () => ({ BOT_GROUP_MESSAGE_AVATAR_SIZE: 28, BOT_GROUP_INLINE_AVATAR_SIZE: 20, BotGroupAvatar: () => null }));+vi.mock('@/session/InteractionPanel', () => ({ InteractionPanel: (props: any) => { h.panel = props; return el('div', { 'data-testid': 'panel' }); } }));+vi.mock('@/session/remoteSessionStore', () => ({+ remoteSessionStore: {+ subscribe: () => () => {},+ getSessionLiveActivity: (sessionId: string) => h.live[sessionId] ?? null,+ setPendingInteractions: h.setPending,+ },+ useSessionPendingInteractions: (sessionId: string) => h.pending[sessionId] ?? [],+}));+vi.mock('@/session/useCompanionGenerationCopy', () => ({+ useCompanionGenerationCopy: (input: { phase: string | null; active: boolean }) => { h.copy(input); return input.active ? `copy:${input.phase}` : null; },+}));+vi.mock('@/session/WorkingStatusText', () => ({ WorkingStatusText: ({ text }: any) => el('span', { 'data-testid': 'status' }, text) }));++import { BotGroupSpeakerRow } from '@/session/BotGroupSpeakerRow';++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+let root: Root;+let node: HTMLDivElement;+const identity = { botId: 'abu', name: '阿布' };+async function render(props: Record<string, unknown>) {+ await act(async () => root.render(el(BotGroupSpeakerRow, { deviceId: 'mac', identity, online: true, onError: vi.fn(), sessionId: 's1', activity: 'reply', ...props } as any)));+}+beforeEach(() => {+ vi.clearAllMocks(); h.pending = {}; h.live = {}; h.panel = null;+ h.invoke.mockResolvedValue([{ request: { requestId: 'r1' } }]);+ node = document.createElement('div'); root = createRoot(node);+});+afterEach(async () => { await act(async () => root.unmount()); });++it('follows the speaking lane while focused and seeds its pending prompts', async () => {+ await render({});+ expect(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' } }]);+ // No live phase yet: a reply reads 「正在思考…」.+ expect(node.textContent).toContain('copy:thinking');+ await act(async () => root.unmount());+ expect(h.unsubscribe).toHaveBeenCalledWith(expect.stringMatching(/^bot-group-speaker:s1:focus:/), 'mac', ['session:s1']);+ root = createRoot(node);+});++it('uses the live phase, and plain copy while planning or before a step reports one', async () => {+ h.live.s1 = { sessionId: 's1', phase: 'running', compactDetail: '', workingPhase: 'reading-file' };+ await render({});+ expect(node.textContent).toContain('copy:reading-file');+ await render({ activity: 'planning', sessionId: null });+ expect(node.textContent).toContain('groupChat.speaking.planning');+ expect(h.copy).toHaveBeenLastCalledWith(expect.objectContaining({ active: false }));+ await render({ activity: 'step', sessionId: 's2' });+ expect(node.textContent).toContain('groupChat.speaking.step');+});++it('shows the teammate’s pending prompt inline instead of the working line', async () => {+ h.pending.s1 = [{ request: { requestId: 'r1', kind: 'permission' } }];+ await render({});+ expect(h.panel).toMatchObject({ companion: true, embedded: true, deviceId: 'mac', sessionId: 's1', interactions: h.pending.s1 });+ expect(h.panel.companionIdentity.name).toBe('阿布');+ expect(node.querySelector('[data-testid="status"]')).toBeNull();+});++it('says it is waiting when the host reports a prompt the phone cannot show yet', async () => {+ h.live.s1 = { sessionId: 's1', phase: 'needs-interaction', compactDetail: '' };+ await render({});+ expect(node.querySelector('[data-testid="botGroup.speaking.waiting"]')?.textContent).toBe('groupChat.waitingConfirm:阿布');+ expect(h.panel).toBeNull();+});++it('does not subscribe without a lane or while the computer is offline', async () => {+ await render({ sessionId: null, activity: 'planning' });+ await render({ online: false, sessionId: 's3' });+ expect(h.subscribe).not.toHaveBeenCalled();+ expect(h.invoke).not.toHaveBeenCalled();+});diff --git a/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx b/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsxindex ebeae12c16..e928b1ae54 100644--- a/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx+++ b/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx@@ -11,7 +11,10 @@ const h = vi.hoisted(() => ({nav: { hydrated: true, lastTeammate: null as LastTeammateIdentity | null, mode: 'teammates' as HomeMode,restoreLastTeammate: true, saveFailed: false, openTeammate: vi.fn(), rememberTeammate: vi.fn(), setMode: vi.fn() },roster: { createTargets: [], authoritative: true, items: [] as HostedRemoteCollectionItem[], loading: false, refreshing: false, error: null as string | null,- isOnline: vi.fn(() => true), refresh: vi.fn() },+ isOnline: vi.fn(() => true), refresh: vi.fn(), groupTargets: [] as { deviceId: string; deviceName: string }[] },+ groups: { items: [] as HostedRemoteCollectionItem[], supported: false, isOnline: () => true, refresh: vi.fn() },+ groupTargetsSeen: [] as unknown[],+ section: {} as any,}));vi.mock('react-native', async () => {const { createElement: el } = await import('react');@@ -33,6 +36,8 @@ vi.mock('@/session/AccountSwitcherSheet', () => ({ AccountSwitcherSheet: (props:vi.mock('@/session/HomeHeaderGlassButton', () => ({ HomeHeaderGlassButton: () => null }));vi.mock('@/session/TeammateList', () => ({ TeammateList: (props: unknown) => { h.list = props; return null; } }));vi.mock('@/session/useTeammateRoster', () => ({ useTeammateRoster: () => ({ ...h.roster }) }));+vi.mock('@/session/useBotGroupRoster', () => ({ useBotGroupRoster: (targets: unknown) => { h.groupTargetsSeen.push(targets); return h.groups; } }));+vi.mock('@/session/BotGroupList', () => ({ BotGroupSection: (props: unknown) => { h.section = props; return null; } }));vi.mock('@/session/useTeammateNavigation', async original => {const actual = await original<typeof import('@/session/useTeammateNavigation')>();return { useTeammateNavigation: () => h.realNavigation ? actual.useTeammateNavigation() : { ...h.nav } };@@ -140,3 +145,34 @@ describe('explicit sidebar entry through the home page', () => {expect(h.push.mock.calls[0][0].params.resourceId).toBe('writer');});});++describe('group chats section', () => {+ const group: HostedRemoteCollectionItem = { key: 'mac:g1', host: { deviceId: 'mac', deviceName: 'Mac' },+ item: { ref: { collectionId: 'bot-groups', kind: 'bot-group', id: 'g1' }, revision: '1', display: { title: '官网' }, links: [] } };+ afterEach(() => { h.roster.groupTargets = []; h.groups = { items: [], supported: false, isOnline: () => true, refresh: vi.fn() }; h.section = {}; });++ it('hides the section when no computer supports group chats (older desktops)', async () => {+ h.nav.lastTeammate = null; await render();+ expect(h.list.renderFooter('')).toBeNull();+ });++ it('lists the discovered computers’ groups and opens a group on its computer', async () => {+ h.nav.lastTeammate = null;+ h.roster.groupTargets = [{ deviceId: 'mac', deviceName: 'Mac' }, { deviceId: 'pc', deviceName: 'PC' }];+ h.groups = { items: [group], supported: true, isOnline: (host: { deviceId: string }) => host.deviceId === 'mac', refresh: vi.fn() } as any;+ await render();+ expect(h.groupTargetsSeen.at(-1)).toBe(h.roster.groupTargets);+ const footer = h.list.renderFooter('官');+ expect(footer).not.toBeNull();+ await act(async () => { root!.render(footer); });+ expect(h.section.items).toEqual([group]);+ expect(h.section.query).toBe('官');+ // Only online computers can host a new group.+ expect(h.section.createTargets).toEqual([{ deviceId: 'mac', deviceName: 'Mac' }]);+ await act(async () => h.section.onOpen(group));+ expect(h.push).toHaveBeenLastCalledWith({ pathname: '/companions/groups/[groupId]', params: { groupId: 'g1', deviceId: 'mac', deviceName: 'Mac' } });+ await act(async () => h.section.onOpenCreated({ deviceId: 'pc', deviceName: 'PC' }, 'g2'));+ expect(h.push).toHaveBeenLastCalledWith({ pathname: '/companions/groups/[groupId]', params: { groupId: 'g2', deviceId: 'pc', deviceName: 'PC' } });+ expect(h.nav.openTeammate).not.toHaveBeenCalled();+ });+});diff --git a/apps/mobile/src/__tests__/botGroupRemote.test.ts b/apps/mobile/src/__tests__/botGroupRemote.test.tsnew file mode 100644index 0000000000..58fc901365--- /dev/null+++ b/apps/mobile/src/__tests__/botGroupRemote.test.ts@@ -0,0 +1,150 @@+import { describe, expect, it } from 'vitest';+import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';+import {+ botGroupChatDataFromResource,+ botGroupErrorCode,+ botGroupMemberAvatar,+ botGroupMemberLinks,+ createdBotGroupId,+ hasBotGroupCollection,+ nextBotGroupSendAttempt,+ orderedBotGroups,+ parseBotGroupChatData,+} from '@/session/botGroupRemote';++function chatData(overrides: Record<string, unknown> = {}) {+ return {+ id: 'g1', name: '官网介绍页', replyMode: 'all', speakingMode: 'auto',+ members: [+ { botId: 'mimi', name: '咪咪', avatar: '🐱', avatarColor: 'red', status: 'active' },+ { botId: 'abu', name: '阿布', avatar: 'cindy://avatar/preset/dash', avatarColor: 'blue', status: 'paused' },+ ],+ organizerBotId: 'mimi', projectDir: '/Users/me/site', projectDirName: 'site',+ lastMessage: { authorKind: 'bot', authorName: '阿布', preview: '写好了', createdAt: 50 },+ speakingBotIds: [], planningBotId: null, openPlan: { id: 'p1', status: 'waiting', currentStep: 0, stepCount: 2, currentBotName: '咪咪', currentStepStatus: 'done' },+ createdAt: 1, updatedAt: 40,+ messages: [+ { id: 'm2', sequence: 2, kind: 'plan', authorKind: 'bot', authorBotId: 'mimi', authorName: '咪咪', content: '', mentions: { all: false, botIds: [] }, noticeCode: null, planId: 'p1', files: [], createdAt: 20 },+ { id: 'm1', sequence: 1, kind: 'message', authorKind: 'user', authorBotId: null, authorName: '', content: '做个页面', mentions: { all: true, botIds: ['mimi', 7] }, noticeCode: null, planId: null, files: [], createdAt: 10 },+ { id: 'm3', sequence: 3, kind: 'future-kind', authorKind: 'bot', authorBotId: 'abu', authorName: '阿布', content: 'x', createdAt: 30 },+ { id: 'm4', sequence: 4, kind: 'notice', authorKind: 'system', authorBotId: 'abu', authorName: '阿布', content: 'fallback', noticeCode: 'something-new', planId: null, files: 'nope', createdAt: 40 },+ 'garbage',+ ],+ hasMoreBefore: true,+ round: { status: 'running', speakers: [{ botId: 'abu', sessionId: 's1', activity: 'step' }, { botId: 5 }], canContinue: false },+ plans: [+ { id: 'p1', status: 'waiting', organizerBotId: 'mimi', organizerName: '咪咪', currentStep: 0, workDir: '/Users/me/site/.cindy-worktrees/x', branch: 'cindy/x', createdAt: 1, updatedAt: 2,+ steps: [+ { position: 0, botId: 'mimi', botName: '咪咪', task: '想清楚', status: 'done' },+ { position: 1, botId: 'abu', botName: '阿布', task: '写代码', status: 'pending' },+ ] },+ { id: 'p0', status: 'done', organizerBotId: 'mimi', organizerName: '咪咪', currentStep: 0, steps: [{ position: 0, botId: 'mimi', task: 'x', status: 'weird' }] },+ ],+ ...overrides,+ };+}++describe('parseBotGroupChatData', () => {+ it('validates the host projection field by field and keeps host paths off the phone', () => {+ const parsed = parseBotGroupChatData(chatData())!;+ expect(parsed.messages.map((message) => message.id)).toEqual(['m1', 'm2', 'm4']);+ expect(parsed.messages[0]!.mentions).toEqual({ all: true, botIds: ['mimi'] });+ // Unknown notice codes keep the message and fall back to its text.+ expect(parsed.messages[2]).toMatchObject({ kind: 'notice', noticeCode: null, content: 'fallback', files: [] });+ expect(parsed.members[1]!.status).toBe('paused');+ expect(parsed.projectDir).toBeNull();+ expect(parsed.projectDirName).toBe('site');+ expect(parsed.plans.map((plan) => plan.id)).toEqual(['p1']);+ expect(parsed.plans[0]!.workDir).toBeNull();+ expect(parsed.round).toEqual({ status: 'running', speakers: [{ botId: 'abu', sessionId: 's1', activity: 'step' }], canContinue: false });+ expect(parsed.openPlan).toMatchObject({ id: 'p1', status: 'waiting', currentStepStatus: 'done' });+ expect(parsed.hasMoreBefore).toBe(true);+ });++ it('rejects data without the essentials', () => {+ expect(parseBotGroupChatData(null)).toBeNull();+ expect(parseBotGroupChatData(chatData({ id: '' }))).toBeNull();+ expect(parseBotGroupChatData(chatData({ members: 'x' }))).toBeNull();+ expect(parseBotGroupChatData(chatData({ messages: undefined }))).toBeNull();+ });++ it('reads only the declared chat block of a resource', () => {+ expect(botGroupChatDataFromResource({ blocks: [{ id: 'chat', primitive: 'markdown', fallbackMarkdown: 'x' }] })).toBeNull();+ expect(botGroupChatDataFromResource({ blocks: [{ id: 'chat', primitive: 'bot-group-chat', fallbackMarkdown: '', data: chatData() }] })?.id).toBe('g1');+ });+});++describe('group rows', () => {+ const row = (deviceId: string, id: string, timestamp: number, title = id): HostedRemoteCollectionItem => ({+ key: `${deviceId}:${id}`, host: { deviceId, deviceName: deviceId },+ item: {+ ref: { collectionId: 'bot-groups', kind: 'bot-group', id }, revision: '1',+ display: { title, subtitle: '咪咪、阿布', timestamp },+ links: [+ { rel: 'member', target: { kind: 'resource', ref: { collectionId: 'teammates', kind: 'bot', id: 'mimi' } }, label: '咪咪' },+ { rel: 'member', target: { kind: 'resource', ref: { collectionId: 'teammates', kind: 'bot', id: 'mimi' } }, label: '咪咪' },+ { rel: 'member', target: { kind: 'resource', ref: { collectionId: 'teammates', kind: 'bot', id: 'abu' } }, label: { fallback: 'Abu', translations: { 'zh-CN': '阿布' } } },+ { rel: 'conversation', target: { kind: 'session', sessionId: 's' } },+ ],+ },+ });++ it('lists members in order from the member links, once each', () => {+ expect(botGroupMemberLinks(row('mac', 'g1', 1).item, 'zh-CN')).toEqual([+ { botId: 'mimi', label: '咪咪' },+ { botId: 'abu', label: '阿布' },+ ]);+ });++ it('orders by latest activity and filters by group or member name', () => {+ const rows = [row('mac', 'old', 1, '周末'), row('mac', 'new', 5, '官网'), row('pc', 'new', 3, '官网')];+ expect(orderedBotGroups(rows, '', 'zh-CN').map((entry) => entry.key)).toEqual(['mac:new', 'pc:new', 'mac:old']);+ expect(orderedBotGroups(rows, '周末', 'zh-CN').map((entry) => entry.key)).toEqual(['mac:old']);+ expect(orderedBotGroups(rows, '阿布', 'zh-CN')).toHaveLength(3);+ expect(orderedBotGroups(rows, 'nobody', 'zh-CN')).toEqual([]);+ });++ it('detects hosts that advertise group chats', () => {+ expect(hasBotGroupCollection({ collections: [{ id: 'bot-groups', resourceKind: 'bot-group' }] })).toBe(true);+ expect(hasBotGroupCollection({ collections: [{ id: 'teammates', resourceKind: 'bot' }] })).toBe(false);+ expect(hasBotGroupCollection(null)).toBe(false);+ });+});++describe('actions', () => {+ it.each([+ [Object.assign(new Error('PLAN_OPEN'), { code: 'INVALID_PARAMS' }), 'PLAN_OPEN'],+ ['[INVALID_PARAMS] MEMBER_LIMIT', 'MEMBER_LIMIT'],+ [new Error('[NOT_FOUND] NOT_FOUND'), 'NOT_FOUND'],+ [new Error('[INVALID_PARAMS] MEMBER_UNAVAILABLE'), 'MEMBER_UNAVAILABLE'],+ [new Error('[NOT_CONNECTED] not online within 1500ms'), null],+ [new Error('XPLAN_OPEN'), null],+ ])('reads the group error code of %s', (error, code) => {+ expect(botGroupErrorCode(error)).toBe(code);+ });++ it('finds the new group in the create receipt', () => {+ expect(createdBotGroupId([+ { kind: 'refresh-collection', collectionId: 'bot-groups' },+ { kind: 'navigate', target: { kind: 'resource', ref: { collectionId: 'bot-groups', kind: 'bot-group', id: 'g9' } } },+ ])).toBe('g9');+ expect(createdBotGroupId([{ kind: 'navigate', target: { kind: 'resource', ref: { collectionId: 'teammates', kind: 'bot', id: 'x' } } }])).toBeNull();+ expect(createdBotGroupId(undefined)).toBeNull();+ });++ it('projects a member avatar like the teammates collection', () => {+ expect(botGroupMemberAvatar({ name: '咪咪', avatar: '🐱', avatarColor: 'red' })).toEqual({ kind: 'emoji', value: '🐱', fallbackText: '咪', color: 'red' });+ expect(botGroupMemberAvatar({ name: 'A', avatar: 'cindy://avatar/preset/cindy', avatarColor: '' }).kind).toBe('asset');+ expect(botGroupMemberAvatar({ name: 'A', avatar: 'cindy-media://avatar/x.png', avatarColor: '' }).kind).toBe('media');+ expect(botGroupMemberAvatar({ name: 'A', avatar: '', avatarColor: '' }).kind).toBe('text');+ });++ it('reuses the clientId only for the same text and the same 分工 tag', () => {+ let serial = 0;+ const next = () => `c${++serial}`;+ const first = nextBotGroupSendAttempt(null, 'hi', false, next);+ expect(nextBotGroupSendAttempt(first, 'hi', false, next)).toBe(first);+ expect(nextBotGroupSendAttempt(first, 'hi', true, next).clientId).toBe('c2');+ expect(nextBotGroupSendAttempt(first, 'hello', false, next).clientId).toBe('c3');+ });+});diff --git a/apps/mobile/src/__tests__/pushRegistrationModel.test.ts b/apps/mobile/src/__tests__/pushRegistrationModel.test.tsindex 765d6784bc..3b6e658154 100644--- a/apps/mobile/src/__tests__/pushRegistrationModel.test.ts+++ b/apps/mobile/src/__tests__/pushRegistrationModel.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {buildPushTokenRegistrationBody,+ notificationRecoveryRoute,parseNotificationDeepLink,parseNotificationResponseDeepLink,resolvePushAppVariant,@@ -53,9 +54,33 @@ describe('parseNotificationDeepLink', () => {['绝对 URL', { deepLink: 'https://evil.example/sessions/x' }],['嵌入 scheme', { deepLink: '/sessions/x://evil' }],['协议相对', { deepLink: '//evil.example/sessions/x' }],+ ['群聊缺 deviceId', { deepLink: '/companions/groups/g-1' }],+ ['群聊 deviceId 为空', { deepLink: '/companions/groups/g-1?deviceId=' }],+ ['群聊多余参数', { deepLink: '/companions/groups/g-1?deviceId=d-1&next=/settings' }],+ ['群聊重复 deviceId', { deepLink: '/companions/groups/g-1?deviceId=d-1&deviceId=d-2' }],+ ['群聊多段路径', { deepLink: '/companions/groups/g-1/x?deviceId=d-1' }],+ ['群聊片段', { deepLink: '/companions/groups/g-1?deviceId=d-1#x' }],+ ['群聊未编码 id', { deepLink: '/companions/groups/g 1?deviceId=d-1' }],+ ['群聊坏编码', { deepLink: '/companions/groups/%E0%A4%A?deviceId=d-1' }],+ ['群聊控制字符', { deepLink: '/companions/groups/g%0A1?deviceId=d-1' }],+ ['群聊嵌入 scheme', { deepLink: '/companions/groups/g-1?deviceId=https://evil' }],+ ['群聊空 id', { deepLink: '/companions/groups/?deviceId=d-1' }],+ ['其它伙伴路径', { deepLink: '/companions/direct/t-1?deviceId=d-1' }],])('拒绝:%s', (_label, input) => {expect(parseNotificationDeepLink(input)).toBeNull();});++ it('接受分工提醒的群聊深链,并按规范编码重建', () => {+ expect(parseNotificationDeepLink({ deepLink: '/companions/groups/g-1?deviceId=d-1' }))+ .toBe('/companions/groups/g-1?deviceId=d-1');+ expect(parseNotificationDeepLink({ deepLink: `/companions/groups/${encodeURIComponent('群 1')}?deviceId=${encodeURIComponent('mac:1')}` }))+ .toBe(`/companions/groups/${encodeURIComponent('群 1')}?deviceId=${encodeURIComponent('mac:1')}`);+ });++ it('群聊深链经通知点击恢复路由后仍带着 deviceId', () => {+ const link = parseNotificationDeepLink({ deepLink: '/companions/groups/g-1?deviceId=d-1' })!;+ expect(notificationRecoveryRoute(link, 'id:n-1')).toBe('/companions/groups/g-1?deviceId=d-1¬ificationResponse=id%3An-1');+ });});describe('parseNotificationResponseDeepLink', () => {diff --git a/apps/mobile/src/__tests__/remoteResources.test.ts b/apps/mobile/src/__tests__/remoteResources.test.tsindex ae440f37a0..f4fe2bb2c1 100644--- a/apps/mobile/src/__tests__/remoteResources.test.ts+++ b/apps/mobile/src/__tests__/remoteResources.test.ts@@ -267,3 +267,25 @@ it('preserves additive public generation state without interpreting unknown futuexpect(normalizeRemoteCollectionItems(input(), 'teammates')[0].display.generation).toBeUndefined();expect(normalizeRemoteCollectionItems(input({ phase: {}, startedAt: Infinity }), 'teammates')[0].display.generation).toBeUndefined();});++describe('bot group chat block', () => {+ const ref = { collectionId: 'bot-groups', kind: 'bot-group', id: 'g1' };+ const response = {+ ref, revision: '1', display: { title: '官网介绍页' }, links: [],+ blocks: [{ id: 'chat', primitive: 'bot-group-chat', fallbackMarkdown: '**阿布**: 写好了', data: { id: 'g1', messages: [{ id: 'm1' }] } }],+ };++ it('keeps the structured group data only for the screen that declared the primitive', async () => {+ const invoke = vi.fn(async () => response) as RemoteInvoke;+ const resource = await getRemoteResource(invoke, targets[0], ref, 'zh-CN', ['bot-group-chat']);+ expect(resource.blocks?.[0]).toEqual(response.blocks[0]);+ const request = (invoke as unknown as { mock: { calls: unknown[][] } }).mock.calls[0]![2] as [{ client: { primitives: string[] } }];+ expect(request[0].client.primitives).toEqual([...MOBILE_REMOTE_RESOURCE_PRIMITIVES, 'bot-group-chat']);+ });++ it('never hands the group data to an ordinary resource view', async () => {+ const invoke = vi.fn(async () => response) as RemoteInvoke;+ const resource = await getRemoteResource(invoke, targets[0], ref);+ expect(resource.blocks?.[0]).toEqual({ id: 'chat', primitive: 'bot-group-chat', fallbackMarkdown: '**阿布**: 写好了' });+ });+});diff --git a/apps/mobile/src/__tests__/useBotGroupChat.test.tsx b/apps/mobile/src/__tests__/useBotGroupChat.test.tsxnew file mode 100644index 0000000000..c46f759ff8--- /dev/null+++ b/apps/mobile/src/__tests__/useBotGroupChat.test.tsx@@ -0,0 +1,116 @@+// @vitest-environment jsdom+import { act, createElement } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ listeners: new Set<(deviceId: string, payload: { collectionId: string; resourceRefs?: { id: string; kind: string; collectionId: string }[] }) => void>(),+ link: {+ status: 'online', connectionEpoch: 1, presenceVersion: 1,+ getPresenceAvailability: vi.fn(() => true as boolean | null),+ invoke: vi.fn(), openLink: vi.fn(async () => undefined),+ subscribe: vi.fn(async () => undefined), unsubscribe: vi.fn(async () => undefined),+ onRemoteResourceChanged: vi.fn(),+ },+}));+vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) } }));+vi.mock('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (effect: () => void) => useEffect(effect, [effect]) }; });+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'zh-CN' } }) }));+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'owner' }, accountGeneration: 1 }) }));+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));+vi.mock('@/device-link/remoteStatus', async () => ({ formatRemoteError: (await import('@cindy/maker-shared/device-link-contract')).formatRemoteError }));++import { useBotGroupChat } from '@/session/useBotGroupChat';++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+const host = { deviceId: 'mac', deviceName: 'Mac' };+const groupData = (name: string) => ({+ id: 'g1', name, members: [{ botId: 'mimi', name: '咪咪', avatar: '', avatarColor: '', status: 'active' }],+ messages: [], plans: [], round: { status: 'idle', speakers: [], canContinue: false },+});+const resource = (name: string) => ({+ ref: { collectionId: 'bot-groups', kind: 'bot-group', id: 'g1' }, revision: name, display: { title: name }, links: [],+ blocks: [{ id: 'chat', primitive: 'bot-group-chat', fallbackMarkdown: '', data: groupData(name) }],+});+let root: Root | undefined;+let result: ReturnType<typeof useBotGroupChat>;+function Probe() { result = useBotGroupChat(host, 'g1'); return null; }+async function render() { root ??= createRoot(document.createElement('div')); await act(async () => root!.render(createElement(Probe))); }+const reads = () => h.link.invoke.mock.calls.filter((call) => call[1] === 'maker:remote-resources:get');+async function push(payload: Parameters<typeof h.listeners extends Set<infer L> ? L : never>[1], deviceId = 'mac') {+ await act(async () => {+ h.listeners.forEach((listener) => listener(deviceId, payload));+ await new Promise((resolve) => setTimeout(resolve, 200));+ });+}++beforeEach(() => {+ vi.clearAllMocks(); h.listeners.clear(); h.link.status = 'online';+ h.link.getPresenceAvailability.mockReturnValue(true);+ h.link.onRemoteResourceChanged.mockImplementation((listener) => { h.listeners.add(listener); return () => h.listeners.delete(listener); });+ h.link.invoke.mockImplementation(async (_deviceId: string, channel: string) => channel === 'maker:remote-resources:get' ? resource('官网') : { effects: [] });+});+afterEach(() => { act(() => root?.unmount()); root = undefined; });++it('reads the group with the chat primitive and follows its change pushes', async () => {+ await render();+ expect(result.state).toMatchObject({ kind: 'ready', group: { id: 'g1', name: '官网' } });+ expect(reads()[0]![2][0]).toMatchObject({ ref: { collectionId: 'bot-groups', kind: 'bot-group', id: 'g1' } });+ expect(reads()[0]![2][0].client.primitives).toContain('bot-group-chat');+ expect(h.link.subscribe).toHaveBeenCalledWith(expect.stringMatching(/^bot-group:g1:focus:/), 'mac', ['sessions']);+ expect(result.online).toBe(true);++ h.link.invoke.mockImplementation(async () => resource('新名字'));+ await push({ collectionId: 'bot-groups', resourceRefs: [{ collectionId: 'bot-groups', kind: 'bot-group', id: 'other' }] });+ await push({ collectionId: 'teammates' });+ await push({ collectionId: 'bot-groups' }, 'pc');+ expect(reads()).toHaveLength(1);+ // A burst of pushes for this group is read once.+ await act(async () => {+ for (let index = 0; index < 3; index += 1) h.listeners.forEach((listener) => listener('mac', { collectionId: 'bot-groups', resourceRefs: [{ collectionId: 'bot-groups', kind: 'bot-group', id: 'g1' }] }));+ await new Promise((resolve) => setTimeout(resolve, 200));+ });+ expect(reads()).toHaveLength(2);+ expect(result.state).toMatchObject({ kind: 'ready', group: { name: '新名字' } });+});++it('keeps the conversation on a failed re-read, and reports a missing group', async () => {+ await render();+ h.link.invoke.mockRejectedValue(new Error('[NOT_CONNECTED] offline'));+ await push({ collectionId: 'bot-groups' });+ expect(result.state.kind).toBe('ready');+ h.link.invoke.mockRejectedValue(Object.assign(new Error('NOT_FOUND'), { code: 'NOT_FOUND' }));+ await push({ collectionId: 'bot-groups' });+ expect(result.state.kind).toBe('missing');+});++it('shows an error when the first read fails or the data is unreadable', async () => {+ h.link.invoke.mockResolvedValue({ ...resource('x'), blocks: [{ id: 'chat', primitive: 'markdown', fallbackMarkdown: 'x' }] });+ await render();+ expect(result.state.kind).toBe('error');+});++it('runs actions on the group and re-reads after success and refusal', async () => {+ await render();+ await act(async () => { await result.act('plan-start', { planId: 'p1' }); });+ const invokeCall = h.link.invoke.mock.calls.find((call) => call[1] === 'maker:remote-resources:invoke')!;+ expect(invokeCall[2][0]).toMatchObject({+ collectionId: 'bot-groups', actionId: 'plan-start', input: { planId: 'p1' },+ resourceRef: { collectionId: 'bot-groups', kind: 'bot-group', id: 'g1' },+ });+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+ expect(reads()).toHaveLength(2);+ h.link.invoke.mockImplementation(async (_deviceId: string, channel: string) => {+ if (channel === 'maker:remote-resources:invoke') throw Object.assign(new Error('PLAN_CLOSED'), { code: 'INVALID_PARAMS' });+ return resource('官网');+ });+ await act(async () => { await expect(result.act('plan-continue', { planId: 'p1' })).rejects.toThrow('PLAN_CLOSED'); });+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+ expect(reads()).toHaveLength(3);+});++it('treats a computer known to be offline as unavailable for actions', async () => {+ h.link.getPresenceAvailability.mockReturnValue(false);+ await render();+ expect(result.online).toBe(false);+});diff --git a/apps/mobile/src/__tests__/useTeammateRoster.test.tsx b/apps/mobile/src/__tests__/useTeammateRoster.test.tsxindex 8863ce1108..fc8464b4f8 100644--- a/apps/mobile/src/__tests__/useTeammateRoster.test.tsx+++ b/apps/mobile/src/__tests__/useTeammateRoster.test.tsx@@ -72,3 +72,21 @@ it('shows cached teammates while host discovery is pending, then removes revokedh.revoked = new Set(['old']); await render();expect(result.items).toEqual([]);});++it('exposes only computers whose manifest advertises group chats, keeping them through a failed read', async () => {+ const manifest = (groups: boolean) => ({ protocolVersion: 1, collections: [+ { id: 'teammates', title: 'Teammates', resourceKind: 'bot', placement: 'home-scope' },+ ...(groups ? [{ id: 'bot-groups', title: 'Group Chats', resourceKind: 'bot-group' }] : []),+ ] });+ h.link.invoke.mockImplementation(async (deviceId) => manifest(deviceId === 'new'));+ await render();+ expect(result.groupTargets).toEqual([{ deviceId: 'new', deviceName: 'new' }]);+ // A transient manifest failure keeps the computer's groups; an older desktop never gains them.+ h.link.invoke.mockImplementation(async (deviceId) => { if (deviceId === 'new') throw new Error('timeout'); return manifest(false); });+ h.link.connectionEpoch++; await render();+ expect(result.groupTargets.map((host) => host.deviceId)).toEqual(['new']);+ // A computer that answers without the collection drops it.+ h.link.invoke.mockImplementation(async () => manifest(false));+ h.link.connectionEpoch++; await render();+ expect(result.groupTargets).toEqual([]);+});diff --git a/apps/mobile/src/components/MobilePrimitives.tsx b/apps/mobile/src/components/MobilePrimitives.tsxindex 655c77f108..e5a6d91058 100644--- a/apps/mobile/src/components/MobilePrimitives.tsx+++ b/apps/mobile/src/components/MobilePrimitives.tsx@@ -587,6 +587,7 @@ export function MainWindowActionButton({action,density = 'default',grow = false,+ hitSlop,style,textStyle,buttonRef,@@ -594,6 +595,8 @@ export function MainWindowActionButton({action: MainWindowAction;density?: MainWindowActionDensity;grow?: boolean;+ /** Compact buttons (38pt) inside content rows extend their touch target to 44pt this way. */+ hitSlop?: PressableProps['hitSlop'];style?: StyleProp<ViewStyle>;textStyle?: StyleProp<TextStyle>;buttonRef?: Ref<View>;@@ -606,6 +609,7 @@ export function MainWindowActionButton({return (<Pressableref={buttonRef}+ hitSlop={hitSlop}accessibilityLabel={action.accessibilityLabel ?? action.label}accessibilityRole="button"accessibilityState={{diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.tsindex d81eb86061..026bd5861b 100644--- a/apps/mobile/src/device-link/remoteResources.ts+++ b/apps/mobile/src/device-link/remoteResources.ts@@ -21,6 +21,7 @@ import {type RemoteActionDescriptor,type RemoteResourceBlock,} from '@cindy/device-link';+import { BOT_GROUP_CHAT_PRIMITIVE } from '@cindy/maker-shared/botGroupChat';import { normalizeRemoteActions, normalizeRemoteBlocks } from './remoteResourceContent';import type { RemoteInvoke } from './mobileMakerTransport';@@ -31,6 +32,18 @@ export const MOBILE_REMOTE_RESOURCE_PRIMITIVES = ['session-controls',] as const;+/**+ * Primitives whose whole block data is kept for a dedicated screen that asked for them+ * (`getRemoteResource(..., supportedPrimitives)`); ordinary resource views never get it.+ * The screen still validates that data before using it.+ */+const RICH_REMOTE_RESOURCE_PRIMITIVES: readonly string[] = [+ 'form',+ 'routine-list',+ 'routine-detail',+ BOT_GROUP_CHAT_PRIMITIVE,+];+/** Routines remain a desktop feature; other portable collections stay available. */export function isMobileRemoteCollectionSupported(collectionId: string): boolean {return collectionId !== 'routines';@@ -356,7 +369,7 @@ export async function getRemoteResource(}const source = recordOf(raw);// Rich forms are consumed only by the dedicated editor, never ordinary resource views.- if (supportedPrimitives.some(primitive => ['form', 'routine-list', 'routine-detail'].includes(primitive))) return {+ if (supportedPrimitives.some(primitive => RICH_REMOTE_RESOURCE_PRIMITIVES.includes(primitive))) return {...normalized, actions: normalizeRemoteActions(source?.actions), blocks: normalizeRemoteBlocks(source?.blocks),};const actions: RemoteActionDescriptor[] = Array.isArray(source?.actions)diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.jsonnew file mode 100644index 0000000000..774d4d041b--- /dev/null+++ b/apps/mobile/src/i18n/locales/en/groupChat.json@@ -0,0 +1,166 @@+{+ "title": "Group Chats",+ "memberSeparator": ", ",+ "memberCount_one": "{{count}} teammate",+ "memberCount_other": "{{count}} teammates",+ "organizer": "Organizer",+ "waitingConfirm": "{{name}} is waiting for your go-ahead",+ "loadFailedTitle": "Couldn’t Load This Group Chat",+ "loadFailedDescription": "Can’t read this group chat from your computer right now. Try again, or go back to Teammates.",+ "unavailableTitle": "This Group Chat Is No Longer Available",+ "unavailableDescription": "It may have been deleted. Go back to Teammates to open another group chat or teammate.",+ "list": {+ "noMessages": "No messages yet",+ "empty": "No group chats yet. Tap + to put a few teammates together.",+ "running": "A teammate is working"+ },+ "create": {+ "title": "New Group Chat",+ "description": "Put a few teammates in one group. Say something and they’ll chime in together.",+ "nameLabel": "Group Name",+ "namePlaceholder": "e.g. Weekend Trip",+ "nameRequired": "Enter a group name",+ "membersLabel": "Choose Teammates",+ "selectedCount_one": "{{count}} selected, up to {{max}}",+ "selectedCount_other": "{{count}} selected, up to {{max}}",+ "minMembers": "Choose at least {{min}} teammates",+ "notEnoughBots": "You need at least {{min}} available teammates to start a group chat. Add a teammate first.",+ "submit": "Create Group Chat",+ "failed": "Couldn’t create the group chat. Try again in a moment.",+ "chooseComputer": "Choose a Computer",+ "computerNote": "This group chat lives on {{deviceName}}, and its teammates work there."+ },+ "memberStatus": {+ "paused": "Paused",+ "unavailable": "Unavailable"+ },+ "mention": {+ "all": "Everyone",+ "allHint": "Everyone replies",+ "label": "Mention a teammate"+ },+ "composer": {+ "label": "Group chat message",+ "placeholder": "Say something to the group. @ a teammate to have only them reply…",+ "noMembers": "No teammates here can reply right now. Add one in group settings.",+ "tooLong": "This message is too long. The limit is {{max}} characters.",+ "sendFailed": "Message not sent. Try again in a moment.",+ "stopFailed": "Couldn’t stop this round. Try again.",+ "stop": "Stop This Round",+ "more": "More Actions",+ "division": "Split the Work",+ "divisionDescription": "The organizer splits the work first, then teammates take it step by step",+ "divisionBusy": "A work split is underway. Finish or stop it before starting another.",+ "divisionTag": "Work split",+ "removeDivision": "Remove Work Split",+ "placeholderDivision": "Describe what to get done. The organizer will split the work first…",+ "placeholderPlanProposed": "To change who does what, just say so…",+ "placeholderPlanWaiting": "Want {{name}} to change something? Just say so…",+ "placeholderPlanRunning": "What you say goes to {{name}}, who’s working on it…",+ "send": "Send"+ },+ "timeline": {+ "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",+ "continue": "Continue Discussion",+ "continueFailed": "Couldn’t continue the discussion. Try again.",+ "nextStep": "Next:",+ "continuePlan": "Start Next Step",+ "continuePlanFailed": "Couldn’t start the next step. Try again.",+ "stepFailed": "{{name}} didn’t finish",+ "retryStep": "Retry Step",+ "retryFailed": "Couldn’t retry this step. Try again.",+ "endPlan": "End Work Split",+ "planDone_one": "{{count}} step is done",+ "planDone_other": "All {{count}} steps are done",+ "planDoneGeneric": "Work split finished",+ "olderOnComputer": "Earlier messages are on your computer"+ },+ "notice": {+ "memberFailed": "{{name}} couldn’t reply this time",+ "memberTimeout": "{{name}} took too long to reply and was skipped this time",+ "memberUnavailable": "{{name}} is unavailable and didn’t speak this time",+ "planFailed": "{{name}} couldn’t work out a split. Try again.",+ "planStopped": "Work split stopped",+ "workdirUnavailable": "{{name}} can’t find the working directory",+ "stepFailed": "{{name}} ran into a problem and didn’t finish this step",+ "stepTimeout": "{{name}} took too long, so this step was stopped",+ "stepUnavailable": "{{name}} is unavailable and can’t do this step"+ },+ "plan": {+ "intro_one": "This takes {{count}} step. Here’s who does it:",+ "intro_other": "This takes {{count}} steps. Here’s who does what:",+ "missing": "This plan is no longer available",+ "start": "Start Plan",+ "dismiss": "Skip Plan",+ "editHint": "To change who does what, just say so",+ "pauseNote": "Work pauses after each step until you click “Start Next Step”.",+ "superseded": "Updated",+ "dismissed": "Skipped",+ "stopped": "Stopped",+ "stepDone": "Done",+ "stepRunning": "In progress",+ "stepFailed": "Not finished",+ "stepPending": "Not started",+ "stepMenuTitle": "Who should do this step",+ "removeStep": "Remove This Step",+ "keepOneStep": "Keep at least one",+ "startFailed": "Couldn’t start the plan. Try again.",+ "dismissFailed": "Couldn’t end this plan. Try again.",+ "editFailed": "Couldn’t change this step. Try again.",+ "editStepHint": "Reassign or remove this step",+ "reassignStepHint": "Reassign this step"+ },+ "speaking": {+ "planning": "Splitting the work…",+ "step": "Working on it…"+ },+ "files": {+ "onComputer": "These files are on your computer. Open them there."+ },+ "settings": {+ "open": "Group Settings",+ "title": "Group Settings",+ "members": "Members",+ "remove": "Remove",+ "removeNamed": "Remove {{name}} from the group",+ "minMembers": "A group chat needs at least {{min}} teammates",+ "maxMembers": "Up to {{max}}",+ "noMoreBots": "No other teammates are available to add",+ "nameSaveFailed": "Couldn’t save the group name. The previous name was kept.",+ "membersSaveFailed": "Couldn’t update members. Try again.",+ "replyMode": "When No One Is @Mentioned",+ "replyModeAll": "Anyone Can Reply",+ "replyModeMentioned": "Only @Mentioned Reply",+ "replyModeNote": "Teammates with nothing to add stay quiet. Each round runs up to 3 passes and 10 messages, then waits for you to click “Continue Discussion”.",+ "replyModeSaveFailed": "Couldn’t save the reply setting. Try again.",+ "delete": "Delete Group Chat",+ "deleteNote": "Only this group chat and its messages are deleted. The teammates, their memory, and their private chats aren’t affected.",+ "deleteConfirmTitle": "Delete “{{name}}”?",+ "deleteFailed": "Couldn’t delete the group chat. Try again in a moment.",+ "speakingMode": "Speaking order",+ "speakingModeAuto": "Automatic",+ "speakingModeSequential": "One at a time",+ "speakingModeAutoNote": "Without @mentions or with @Everyone, teammates think at the same time in the first pass, then reply one after another. Mentioned teammates answer in the order you mentioned them.",+ "speakingModeSequentialNote": "One teammate speaks at a time, and each one sees the replies before it.",+ "speakingModeSaveFailed": "Couldn't save the speaking order. Try again.",+ "setOrganizer": "Make Organizer",+ "setOrganizerNamed": "Make {{name}} the organizer",+ "organizerNote": "The organizer decides who does each step. By default, it’s the first teammate.",+ "organizerSaveFailed": "Couldn’t change the organizer. Try again.",+ "projectDir": "Project Folder",+ "projectDirNone": "None selected",+ "projectDirNote": "Teammates work here when they split the work. You can leave it empty and they’ll use this group chat’s own folder. If you choose a git project, each work split gets a new worktree and branch, so your own code stays untouched.",+ "add": "Add teammate",+ "projectDirOnComputer": "Choose or change it on your computer"+ },+ "errors": {+ "memberLimit": "A group chat needs 2–6 teammates",+ "memberUnavailable": "One of these teammates is unavailable. Choose another and try again.",+ "notFound": "This group chat no longer exists",+ "hostNotReady": "Cindy is still getting ready. Try again in a moment.",+ "planOpen": "A work split is underway. Finish or stop it before starting another.",+ "planClosed": "This plan has already ended or been updated."+ }+}diff --git a/apps/mobile/src/i18n/locales/en/index.ts b/apps/mobile/src/i18n/locales/en/index.tsindex a51e2acd9f..5a06acd366 100644--- a/apps/mobile/src/i18n/locales/en/index.ts+++ b/apps/mobile/src/i18n/locales/en/index.ts@@ -13,6 +13,7 @@ import composer from './composer.json';import deviceLink from './deviceLink.json';import devices from './devices.json';import files from './files.json';+import groupChat from './groupChat.json';import home from './home.json';import interaction from './interaction.json';import message from './message.json';@@ -33,6 +34,7 @@ export default {deviceLink,devices,files,+ groupChat,home,interaction,message,diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.jsonnew file mode 100644index 0000000000..818d891598--- /dev/null+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json@@ -0,0 +1,166 @@+{+ "title": "グループチャット",+ "memberSeparator": "、",+ "memberCount_one": "仲間 {{count}} 人",+ "memberCount_other": "仲間 {{count}} 人",+ "organizer": "まとめ役",+ "waitingConfirm": "{{name}} があなたの確認を待っています",+ "loadFailedTitle": "このグループチャットを読み込めません",+ "loadFailedDescription": "このグループチャットをパソコンから読み込めません。もう一度試すか、仲間の一覧に戻ってください。",+ "unavailableTitle": "このグループチャットは利用できません",+ "unavailableDescription": "削除された可能性があります。仲間のページに戻ると、ほかのグループチャットや仲間を開けます。",+ "list": {+ "noMessages": "メッセージはまだありません",+ "empty": "グループチャットはまだありません。+ をタップして仲間を集めましょう。",+ "running": "仲間が作業中"+ },+ "create": {+ "title": "グループチャットを作成",+ "description": "何人かの仲間を 1 つのグループにまとめます。あなたが話しかけると、仲間たちが一緒に返信します。",+ "nameLabel": "グループ名",+ "namePlaceholder": "例: 週末のお出かけ",+ "nameRequired": "グループ名を入力してください",+ "membersLabel": "仲間を選択",+ "selectedCount_one": "{{count}} 人選択中(最大 {{max}} 人)",+ "selectedCount_other": "{{count}} 人選択中(最大 {{max}} 人)",+ "minMembers": "仲間を {{min}} 人以上選択してください",+ "notEnoughBots": "グループチャットを作成するには、利用できる仲間が {{min}} 人以上必要です。まず仲間を追加してください。",+ "submit": "グループチャットを作成",+ "failed": "グループチャットを作成できませんでした。しばらくしてから再試行してください",+ "chooseComputer": "作成するパソコンを選択",+ "computerNote": "このグループチャットは {{deviceName}} に作成され、仲間はそのパソコンで作業します。"+ },+ "memberStatus": {+ "paused": "一時停止中",+ "unavailable": "利用不可"+ },+ "mention": {+ "all": "全員",+ "allHint": "全員が返信",+ "label": "仲間をメンション"+ },+ "composer": {+ "label": "グループチャットのメッセージ",+ "placeholder": "グループに話しかけましょう。@ で仲間を指名すると、その仲間だけが返信します…",+ "noMembers": "今返信できる仲間がいません。グループの設定で仲間を追加してください",+ "tooLong": "メッセージが長すぎます。上限は {{max}} 文字です",+ "sendFailed": "メッセージを送信できませんでした。しばらくしてから再試行してください",+ "stopFailed": "このラウンドを停止できませんでした。もう一度お試しください",+ "stop": "このラウンドを停止",+ "more": "その他の操作",+ "division": "役割分担する",+ "divisionDescription": "まとめ役が先に役割を分け、仲間が一歩ずつ進めます",+ "divisionBusy": "役割分担の途中です。終わるか停止してから新しく始めてください",+ "divisionTag": "役割分担",+ "removeDivision": "役割分担を外す",+ "placeholderDivision": "やりたいことを書いてください。まとめ役が先に役割を分けます…",+ "placeholderPlanProposed": "担当や手順を変えたいときは、そのまま話しかけてください…",+ "placeholderPlanWaiting": "{{name}} に直してほしいことがあれば、そのまま話しかけてください…",+ "placeholderPlanRunning": "送った内容は作業中の {{name}} に届きます…",+ "send": "送信"+ },+ "timeline": {+ "emptyTitle": "このグループにはまだメッセージがありません",+ "emptyDescription": "話しかけると仲間たちが会話を続けます。@ で仲間を指名すると、その仲間だけが返信します。",+ "roundEnded": "仲間たちの発言が終わりました",+ "continue": "議論を続ける",+ "continueFailed": "議論を続けられませんでした。もう一度お試しください",+ "nextStep": "次のステップ:",+ "continuePlan": "次へ進む",+ "continuePlanFailed": "次のステップに進めませんでした。もう一度お試しください",+ "stepFailed": "{{name}} は完了できませんでした",+ "retryStep": "やり直す",+ "retryFailed": "このステップをやり直せませんでした。もう一度お試しください",+ "endPlan": "役割分担を終える",+ "planDone_one": "{{count}} ステップすべて完了しました",+ "planDone_other": "{{count}} ステップすべて完了しました",+ "planDoneGeneric": "役割分担が完了しました",+ "olderOnComputer": "それより前のメッセージはパソコンで確認できます"+ },+ "notice": {+ "memberFailed": "{{name}} は今回返信できませんでした",+ "memberTimeout": "{{name}} の返信に時間がかかりすぎたため、今回はスキップしました",+ "memberUnavailable": "{{name}} は現在利用できないため、今回は発言しませんでした",+ "planFailed": "{{name}} は役割分担を決められませんでした。もう一度お試しください",+ "planStopped": "役割分担を停止しました",+ "workdirUnavailable": "{{name}} が作業ディレクトリを見つけられません",+ "stepFailed": "{{name}} はエラーのため、このステップを完了できませんでした",+ "stepTimeout": "{{name}} の作業に時間がかかりすぎたため、このステップを止めました",+ "stepUnavailable": "{{name}} は現在利用できないため、このステップを進められません"+ },+ "plan": {+ "intro_one": "この件は {{count}} ステップに分けて、次のように分担します:",+ "intro_other": "この件は {{count}} ステップに分けて、次のように分担します:",+ "missing": "この計画は読み込めなくなりました",+ "start": "開始する",+ "dismiss": "今回はやめる",+ "editHint": "担当や手順を変えたいときは、そのまま話しかけてください",+ "pauseNote": "1 ステップ終わるごとに止まり、「次へ進む」を押すまで待ちます。",+ "superseded": "更新済み",+ "dismissed": "見送りました",+ "stopped": "停止しました",+ "stepDone": "完了",+ "stepRunning": "作業中",+ "stepFailed": "未完了",+ "stepPending": "未着手",+ "stepMenuTitle": "このステップの担当",+ "removeStep": "このステップを削除",+ "keepOneStep": "1 つは残す必要があります",+ "startFailed": "役割分担を開始できませんでした。もう一度お試しください",+ "dismissFailed": "この計画を終了できませんでした。もう一度お試しください",+ "editFailed": "このステップを変更できませんでした。もう一度お試しください",+ "editStepHint": "担当を変えるか、このステップを削除します",+ "reassignStepHint": "このステップの担当を変えます"+ },+ "speaking": {+ "planning": "役割分担を考えています…",+ "step": "作業中…"+ },+ "files": {+ "onComputer": "ファイルはパソコンにあります。パソコンで開いてください"+ },+ "settings": {+ "open": "グループの設定",+ "title": "グループの設定",+ "members": "メンバー",+ "remove": "外す",+ "removeNamed": "{{name}} をグループから外す",+ "minMembers": "グループチャットには仲間が {{min}} 人以上必要です",+ "maxMembers": "最大 {{max}} 人",+ "noMoreBots": "追加できるほかの仲間はいません",+ "nameSaveFailed": "グループ名を保存できなかったため、元の名前に戻しました",+ "membersSaveFailed": "メンバーを更新できませんでした。もう一度お試しください",+ "replyMode": "誰も @ されていないとき",+ "replyModeAll": "誰でも返信できる",+ "replyModeMentioned": "@ された仲間だけ返信",+ "replyModeNote": "付け加えることがない仲間は発言しません。1 ラウンドは最大 3 周・10 件までで、その後は「議論を続ける」を押すまで待ちます。",+ "replyModeSaveFailed": "返信の設定を保存できませんでした。もう一度お試しください",+ "delete": "グループチャットを削除",+ "deleteNote": "削除されるのはこのグループチャットとそのメッセージだけです。仲間本人、その記憶、個別のチャットには影響しません。",+ "deleteConfirmTitle": "「{{name}}」を削除しますか?",+ "deleteFailed": "グループチャットを削除できませんでした。しばらくしてから再試行してください",+ "speakingMode": "発言の順番",+ "speakingModeAuto": "自動",+ "speakingModeSequential": "常に順番に",+ "speakingModeAutoNote": "メンションなし、または @全員 のときは、最初の一巡は全員が同時に考え、その後は順番に話します。メンションした仲間は、メンションした順に答えます。",+ "speakingModeSequentialNote": "一度に一人の仲間だけが話し、後の仲間は前の返信を見てから答えます。",+ "speakingModeSaveFailed": "発言の順番を保存できませんでした。もう一度お試しください。",+ "setOrganizer": "まとめ役にする",+ "setOrganizerNamed": "{{name}} をまとめ役にする",+ "organizerNote": "まとめ役が、どのステップを誰が担当するかを決めます。既定では最初の仲間です。",+ "organizerSaveFailed": "まとめ役を変更できませんでした。もう一度お試しください",+ "projectDir": "プロジェクトフォルダ",+ "projectDirNone": "未選択",+ "projectDirNote": "役割分担で作業するとき、仲間はここで作業します。選ばなくてもかまいません。その場合はこのグループチャット専用のフォルダを使います。git プロジェクトを選ぶと、役割分担のたびに新しい worktree とブランチを作るので、手元のコードには触れません。",+ "add": "仲間を追加",+ "projectDirOnComputer": "パソコンで選択・変更できます"+ },+ "errors": {+ "memberLimit": "グループチャットには仲間が 2〜6 人必要です",+ "memberUnavailable": "利用できない仲間がいます。別の仲間を選んで再試行してください",+ "notFound": "このグループチャットはもう存在しません",+ "hostNotReady": "Cindy の準備がまだ終わっていません。しばらくしてから再試行してください",+ "planOpen": "役割分担の途中です。終わるか停止してから新しく始めてください",+ "planClosed": "この計画はすでに終了したか、更新されています"+ }+}diff --git a/apps/mobile/src/i18n/locales/ja/index.ts b/apps/mobile/src/i18n/locales/ja/index.tsindex a51e2acd9f..5a06acd366 100644--- a/apps/mobile/src/i18n/locales/ja/index.ts+++ b/apps/mobile/src/i18n/locales/ja/index.ts@@ -13,6 +13,7 @@ import composer from './composer.json';import deviceLink from './deviceLink.json';import devices from './devices.json';import files from './files.json';+import groupChat from './groupChat.json';import home from './home.json';import interaction from './interaction.json';import message from './message.json';@@ -33,6 +34,7 @@ export default {deviceLink,devices,files,+ groupChat,home,interaction,message,diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.jsonnew file mode 100644index 0000000000..cf67372d2c--- /dev/null+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json@@ -0,0 +1,166 @@+{+ "title": "그룹 채팅",+ "memberSeparator": ", ",+ "memberCount_one": "동료 {{count}}명",+ "memberCount_other": "동료 {{count}}명",+ "organizer": "담당자",+ "waitingConfirm": "{{name}} 님이 확인을 기다리고 있어요",+ "loadFailedTitle": "이 그룹 채팅을 불러올 수 없습니다",+ "loadFailedDescription": "지금은 컴퓨터에서 이 그룹 채팅을 불러올 수 없습니다. 다시 시도하거나 동료 목록으로 돌아가세요.",+ "unavailableTitle": "이 그룹 채팅을 더 이상 사용할 수 없습니다",+ "unavailableDescription": "삭제되었을 수 있습니다. 동료 페이지로 돌아가 다른 그룹 채팅이나 동료를 열어 보세요.",+ "list": {+ "noMessages": "아직 메시지가 없습니다",+ "empty": "아직 그룹 채팅이 없습니다. +를 눌러 동료 몇 명을 모아 보세요.",+ "running": "동료가 작업 중"+ },+ "create": {+ "title": "새 그룹 채팅",+ "description": "동료 몇 명을 한 그룹에 모아 보세요. 한마디 하면 동료들이 함께 이어서 답합니다.",+ "nameLabel": "그룹 이름",+ "namePlaceholder": "예: 주말 나들이",+ "nameRequired": "그룹 이름을 입력하세요",+ "membersLabel": "동료 선택",+ "selectedCount_one": "{{count}}명 선택됨, 최대 {{max}}명",+ "selectedCount_other": "{{count}}명 선택됨, 최대 {{max}}명",+ "minMembers": "동료를 {{min}}명 이상 선택하세요",+ "notEnoughBots": "그룹 채팅을 만들려면 사용할 수 있는 동료가 {{min}}명 이상 필요합니다. 먼저 동료를 추가하세요.",+ "submit": "그룹 채팅 만들기",+ "failed": "그룹 채팅을 만들지 못했습니다. 잠시 후 다시 시도하세요.",+ "chooseComputer": "만들 컴퓨터 선택",+ "computerNote": "이 그룹 채팅은 {{deviceName}}에 만들어지고, 동료들은 그 컴퓨터에서 작업합니다."+ },+ "memberStatus": {+ "paused": "일시 중지됨",+ "unavailable": "사용 불가"+ },+ "mention": {+ "all": "모두",+ "allHint": "모두 답변",+ "label": "동료 멘션"+ },+ "composer": {+ "label": "그룹 채팅 메시지",+ "placeholder": "그룹에 말을 걸어 보세요. @로 동료를 지정하면 그 동료만 답합니다…",+ "noMembers": "지금 답할 수 있는 동료가 없습니다. 그룹 설정에서 동료를 추가하세요",+ "tooLong": "메시지가 너무 깁니다. 최대 {{max}}자까지 보낼 수 있습니다",+ "sendFailed": "메시지를 보내지 못했습니다. 잠시 후 다시 시도하세요",+ "stopFailed": "이번 라운드를 멈추지 못했습니다. 다시 시도하세요",+ "stop": "이번 라운드 중지",+ "more": "더 보기",+ "division": "역할 분담하기",+ "divisionDescription": "담당자가 먼저 역할을 나누고, 동료들이 한 단계씩 진행합니다",+ "divisionBusy": "역할 분담이 진행 중입니다. 끝내거나 중지한 뒤 새로 시작하세요",+ "divisionTag": "역할 분담",+ "removeDivision": "역할 분담 해제",+ "placeholderDivision": "하고 싶은 일을 적어 주세요. 담당자가 먼저 역할을 나눕니다…",+ "placeholderPlanProposed": "담당이나 단계를 바꾸려면 그냥 말해 주세요…",+ "placeholderPlanWaiting": "{{name}} 님에게 고칠 점이 있으면 그냥 말해 주세요…",+ "placeholderPlanRunning": "보내는 말은 작업 중인 {{name}} 님에게 전달됩니다…",+ "send": "보내기"+ },+ "timeline": {+ "emptyTitle": "이 그룹에는 아직 메시지가 없습니다",+ "emptyDescription": "한마디 하면 동료들이 이어서 대화합니다. @로 동료를 지정하면 그 동료만 답합니다.",+ "roundEnded": "동료들이 말을 마쳤습니다",+ "continue": "토론 계속하기",+ "continueFailed": "토론을 이어 가지 못했습니다. 다시 시도하세요",+ "nextStep": "다음 단계:",+ "continuePlan": "다음 단계 시작",+ "continuePlanFailed": "다음 단계를 시작하지 못했습니다. 다시 시도하세요",+ "stepFailed": "{{name}} 님이 끝내지 못했습니다",+ "retryStep": "다시 시도",+ "retryFailed": "이 단계를 다시 시도하지 못했습니다. 잠시 후 다시 시도하세요",+ "endPlan": "역할 분담 끝내기",+ "planDone_one": "{{count}}단계를 모두 마쳤습니다",+ "planDone_other": "{{count}}단계를 모두 마쳤습니다",+ "planDoneGeneric": "역할 분담을 마쳤습니다",+ "olderOnComputer": "이전 메시지는 컴퓨터에서 확인하세요"+ },+ "notice": {+ "memberFailed": "{{name}} 님이 이번에는 답하지 못했습니다",+ "memberTimeout": "{{name}} 님의 답이 너무 늦어 이번에는 건너뛰었습니다",+ "memberUnavailable": "{{name}} 님을 지금 사용할 수 없어 이번에는 발언하지 않았습니다",+ "planFailed": "{{name}} 님이 역할 분담을 정하지 못했습니다. 다시 시도해 보세요",+ "planStopped": "역할 분담을 중지했습니다",+ "workdirUnavailable": "{{name}} 님이 작업 디렉터리를 찾지 못했습니다",+ "stepFailed": "{{name}} 님이 오류로 이 단계를 끝내지 못했습니다",+ "stepTimeout": "{{name}} 님의 작업이 너무 오래 걸려 이 단계를 멈췄습니다",+ "stepUnavailable": "{{name}} 님을 지금 사용할 수 없어 이 단계를 진행할 수 없습니다"+ },+ "plan": {+ "intro_one": "이 일은 {{count}}단계로 나눠서 이렇게 분담할게요:",+ "intro_other": "이 일은 {{count}}단계로 나눠서 이렇게 분담할게요:",+ "missing": "이 계획을 더 이상 불러올 수 없습니다",+ "start": "시작하기",+ "dismiss": "필요 없어요",+ "editHint": "담당이나 단계를 바꾸려면 그냥 말해 주세요",+ "pauseNote": "한 단계가 끝날 때마다 멈추고, ‘다음 단계 시작’을 누를 때까지 기다립니다.",+ "superseded": "업데이트됨",+ "dismissed": "사용 안 함",+ "stopped": "중지됨",+ "stepDone": "완료",+ "stepRunning": "진행 중",+ "stepFailed": "끝내지 못함",+ "stepPending": "시작 전",+ "stepMenuTitle": "이 단계를 맡을 동료",+ "removeStep": "이 단계 삭제",+ "keepOneStep": "최소 한 단계는 남겨야 합니다",+ "startFailed": "역할 분담을 시작하지 못했습니다. 다시 시도하세요",+ "dismissFailed": "이 계획을 끝내지 못했습니다. 다시 시도하세요",+ "editFailed": "이 단계를 바꾸지 못했습니다. 다시 시도하세요",+ "editStepHint": "담당을 바꾸거나 이 단계를 삭제합니다",+ "reassignStepHint": "이 단계의 담당을 바꿉니다"+ },+ "speaking": {+ "planning": "역할을 나누는 중…",+ "step": "작업 중…"+ },+ "files": {+ "onComputer": "파일은 컴퓨터에 있습니다. 컴퓨터에서 열어 주세요"+ },+ "settings": {+ "open": "그룹 설정",+ "title": "그룹 설정",+ "members": "멤버",+ "remove": "내보내기",+ "removeNamed": "{{name}} 님을 그룹에서 내보내기",+ "minMembers": "그룹 채팅에는 동료가 {{min}}명 이상 있어야 합니다",+ "maxMembers": "최대 {{max}}명",+ "noMoreBots": "추가할 수 있는 다른 동료가 없습니다",+ "nameSaveFailed": "그룹 이름을 저장하지 못해 이전 이름으로 되돌렸습니다",+ "membersSaveFailed": "멤버를 업데이트하지 못했습니다. 다시 시도하세요",+ "replyMode": "아무도 @멘션되지 않았을 때",+ "replyModeAll": "누구나 답할 수 있음",+ "replyModeMentioned": "@된 동료만 답함",+ "replyModeNote": "더 보탤 말이 없는 동료는 말하지 않습니다. 한 라운드는 최대 3바퀴, 메시지 10개까지이며, 그 후에는 ‘토론 계속하기’를 누를 때까지 기다립니다.",+ "replyModeSaveFailed": "답변 방식을 저장하지 못했습니다. 다시 시도하세요",+ "delete": "그룹 채팅 삭제",+ "deleteNote": "이 그룹 채팅과 그 안의 메시지만 삭제됩니다. 동료 자체와 동료의 기억, 개인 대화에는 영향이 없습니다.",+ "deleteConfirmTitle": "‘{{name}}’을(를) 삭제할까요?",+ "deleteFailed": "그룹 채팅을 삭제하지 못했습니다. 잠시 후 다시 시도하세요",+ "speakingMode": "발언 순서",+ "speakingModeAuto": "자동",+ "speakingModeSequential": "항상 차례대로",+ "speakingModeAutoNote": "멘션이 없거나 @모두일 때는 첫 순서에서 모두 동시에 생각하고, 이후에는 차례대로 이어서 말합니다. 멘션한 동료는 멘션한 순서대로 답합니다.",+ "speakingModeSequentialNote": "한 번에 한 동료만 말하며, 뒤에 말하는 동료는 앞의 답을 보고 답합니다.",+ "speakingModeSaveFailed": "발언 순서를 저장하지 못했습니다. 다시 시도해 주세요.",+ "setOrganizer": "담당자로 지정",+ "setOrganizerNamed": "{{name}} 님을 담당자로 지정",+ "organizerNote": "담당자가 각 단계를 누가 맡을지 정합니다. 기본값은 첫 번째 동료입니다.",+ "organizerSaveFailed": "담당자를 바꾸지 못했습니다. 다시 시도하세요",+ "projectDir": "프로젝트 폴더",+ "projectDirNone": "선택 안 함",+ "projectDirNote": "역할 분담으로 일할 때 동료들이 여기서 작업합니다. 선택하지 않아도 되며, 그러면 이 그룹 채팅 전용 폴더를 사용합니다. git 프로젝트를 선택하면 역할 분담마다 새 worktree와 브랜치를 만들어, 지금 작업 중인 코드는 건드리지 않습니다.",+ "add": "동료 추가",+ "projectDirOnComputer": "컴퓨터에서 선택하거나 바꿀 수 있습니다"+ },+ "errors": {+ "memberLimit": "그룹 채팅에는 동료가 2~6명 필요합니다",+ "memberUnavailable": "사용할 수 없는 동료가 있습니다. 다른 동료를 골라 다시 시도하세요",+ "notFound": "이 그룹 채팅은 더 이상 존재하지 않습니다",+ "hostNotReady": "Cindy가 아직 준비 중입니다. 잠시 후 다시 시도하세요",+ "planOpen": "역할 분담이 진행 중입니다. 끝내거나 중지한 뒤 새로 시작하세요",+ "planClosed": "이 계획은 이미 끝났거나 업데이트되었습니다"+ }+}diff --git a/apps/mobile/src/i18n/locales/ko/index.ts b/apps/mobile/src/i18n/locales/ko/index.tsindex a51e2acd9f..5a06acd366 100644--- a/apps/mobile/src/i18n/locales/ko/index.ts+++ b/apps/mobile/src/i18n/locales/ko/index.ts@@ -13,6 +13,7 @@ import composer from './composer.json';import deviceLink from './deviceLink.json';import devices from './devices.json';import files from './files.json';+import groupChat from './groupChat.json';import home from './home.json';import interaction from './interaction.json';import message from './message.json';@@ -33,6 +34,7 @@ export default {deviceLink,devices,files,+ groupChat,home,interaction,message,diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.jsonnew file mode 100644index 0000000000..d1c103a943--- /dev/null+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json@@ -0,0 +1,166 @@+{+ "title": "群聊",+ "memberSeparator": "、",+ "memberCount_one": "{{count}} 位伙伴",+ "memberCount_other": "{{count}} 位伙伴",+ "organizer": "负责人",+ "waitingConfirm": "{{name}}在等你确认",+ "loadFailedTitle": "无法加载这个群聊",+ "loadFailedDescription": "暂时读不到电脑上的这个群聊,可以重试,或返回伙伴页。",+ "unavailableTitle": "这个群聊已不可用",+ "unavailableDescription": "它可能已被删除。返回伙伴页可以打开其他群聊和伙伴。",+ "list": {+ "noMessages": "还没有消息",+ "empty": "还没有群聊。点 + 选几位伙伴建一个。",+ "running": "有伙伴正在忙"+ },+ "create": {+ "title": "新建群聊",+ "description": "选几位伙伴放进一个群。你说一句,它们会一起接话。",+ "nameLabel": "群名称",+ "namePlaceholder": "例如:周末出游",+ "nameRequired": "给群起个名字",+ "membersLabel": "选择伙伴",+ "selectedCount_one": "已选 {{count}} 位,最多 {{max}} 位",+ "selectedCount_other": "已选 {{count}} 位,最多 {{max}} 位",+ "minMembers": "至少选 {{min}} 位伙伴",+ "notEnoughBots": "至少需要 {{min}} 位可用的伙伴才能建群,先去添加伙伴吧。",+ "submit": "创建群聊",+ "failed": "群聊没有建成,请稍后重试",+ "chooseComputer": "在哪台电脑上建群",+ "computerNote": "群聊建在 {{deviceName}} 上,伙伴们在这台电脑上干活。"+ },+ "memberStatus": {+ "paused": "已暂停",+ "unavailable": "不可用"+ },+ "mention": {+ "all": "所有人",+ "allHint": "大家都回答",+ "label": "点名伙伴"+ },+ "composer": {+ "label": "群聊消息",+ "placeholder": "在群里说点什么,@ 某位伙伴就只让它回答…",+ "noMembers": "群里暂时没有能接话的伙伴,去群设置里添加一位吧",+ "tooLong": "消息太长了,最多 {{max}} 个字",+ "sendFailed": "消息没有发出去,请稍后重试",+ "stopFailed": "没能停下这一轮,请再试一次",+ "stop": "停止这一轮",+ "more": "更多操作",+ "division": "安排分工",+ "divisionDescription": "让负责人先分好工,伙伴们一步步做",+ "divisionBusy": "正在分工,做完或停止后才能安排新的",+ "divisionTag": "分工",+ "removeDivision": "去掉分工",+ "placeholderDivision": "说说要做成什么,负责人会先分好工…",+ "placeholderPlanProposed": "想换人或改步骤,直接说…",+ "placeholderPlanWaiting": "想让{{name}}改改,直接说…",+ "placeholderPlanRunning": "说的话会带给正在做的{{name}}…",+ "send": "发送"+ },+ "timeline": {+ "emptyTitle": "群里还没有消息",+ "emptyDescription": "说一句话开始,伙伴们会接着聊。@ 某位伙伴就只让它回答。",+ "roundEnded": "伙伴们说完了",+ "continue": "继续讨论",+ "continueFailed": "没能继续讨论,请再试一次",+ "nextStep": "下一步:",+ "continuePlan": "继续",+ "continuePlanFailed": "没能继续下一步,请再试一次",+ "stepFailed": "{{name}}没做完",+ "retryStep": "重试",+ "retryFailed": "没能重试这一步,请再试一次",+ "endPlan": "结束分工",+ "planDone_one": "{{count}} 步都做完了",+ "planDone_other": "{{count}} 步都做完了",+ "planDoneGeneric": "分工做完了",+ "olderOnComputer": "更早的消息请在电脑上查看"+ },+ "notice": {+ "memberFailed": "{{name}}这次没能回复",+ "memberTimeout": "{{name}}太久没有回复,这次先跳过",+ "memberUnavailable": "{{name}}现在不可用,这次没有发言",+ "planFailed": "{{name}}没排出分工,可以再试一次",+ "planStopped": "分工已停止",+ "workdirUnavailable": "{{name}}找不到工作目录",+ "stepFailed": "{{name}}这一步出错了,没做完",+ "stepTimeout": "{{name}}太久没做完,这一步先停下",+ "stepUnavailable": "{{name}}现在不可用,这一步没法做"+ },+ "plan": {+ "intro_one": "这件事分 {{count}} 步,我这样分工:",+ "intro_other": "这件事分 {{count}} 步,我这样分工:",+ "missing": "这个安排已经读不到了",+ "start": "开始",+ "dismiss": "不用了",+ "editHint": "想换人或改步骤,直接说",+ "pauseNote": "每做完一步会停下来,等你点「继续」。",+ "superseded": "已更新",+ "dismissed": "不用了",+ "stopped": "已停止",+ "stepDone": "做完了",+ "stepRunning": "正在做",+ "stepFailed": "没做完",+ "stepPending": "还没开始",+ "stepMenuTitle": "谁来做这一步",+ "removeStep": "删掉这一步",+ "keepOneStep": "至少留一步",+ "startFailed": "没能开始分工,请再试一次",+ "dismissFailed": "没能结束这个安排,请再试一次",+ "editFailed": "这一步没改成,请再试一次",+ "editStepHint": "换人或删掉这一步",+ "reassignStepHint": "换人做这一步"+ },+ "speaking": {+ "planning": "正在安排…",+ "step": "正在做…"+ },+ "files": {+ "onComputer": "文件在电脑上,回电脑打开"+ },+ "settings": {+ "open": "群设置",+ "title": "群设置",+ "members": "成员",+ "remove": "移出",+ "removeNamed": "把 {{name}} 移出群聊",+ "minMembers": "群里至少要有 {{min}} 位伙伴",+ "maxMembers": "最多 {{max}} 位",+ "noMoreBots": "没有其他可以加入的伙伴了",+ "nameSaveFailed": "群名称没能保存,已恢复原来的名字",+ "membersSaveFailed": "成员没能更新,请再试一次",+ "replyMode": "没有 @ 人的时候",+ "replyModeAll": "大家都可以接话",+ "replyModeMentioned": "只有被 @ 的回答",+ "replyModeNote": "没什么可补充的伙伴不会说话。每轮最多聊 3 圈、10 条,之后等你点「继续讨论」。",+ "replyModeSaveFailed": "回复方式没能保存,请再试一次",+ "delete": "删除群聊",+ "deleteNote": "只删除这个群和群里的消息,伙伴本身、它们的记忆和私聊都不受影响。",+ "deleteConfirmTitle": "删除「{{name}}」?",+ "deleteFailed": "群聊没能删除,请稍后重试",+ "speakingMode": "发言方式",+ "speakingModeAuto": "自动",+ "speakingModeSequential": "始终轮流",+ "speakingModeAutoNote": "没有 @ 人或 @所有人时,第一圈大家同时想,之后轮流接话;@ 了伙伴就按 @ 的先后轮流。",+ "speakingModeSequentialNote": "每次只有一位伙伴发言,后说的能看到前面的回答。",+ "speakingModeSaveFailed": "发言方式没能保存,请再试一次",+ "setOrganizer": "设为负责人",+ "setOrganizerNamed": "把 {{name}} 设为负责人",+ "organizerNote": "负责人帮你安排谁做哪一步,默认是第一位伙伴。",+ "organizerSaveFailed": "负责人没能更换,请再试一次",+ "projectDir": "项目文件夹",+ "projectDirNone": "没选",+ "projectDirNote": "分工做事时,伙伴们在这里干活。不选也行,会用这个群自己的文件夹;选了 git 项目,每次分工会新开一个 worktree 和分支,不动你手上的代码。",+ "add": "添加伙伴",+ "projectDirOnComputer": "在电脑上选择或更换"+ },+ "errors": {+ "memberLimit": "一个群需要 2–6 位伙伴",+ "memberUnavailable": "有伙伴现在不可用,换一位再试",+ "notFound": "这个群聊已不存在",+ "hostNotReady": "Cindy 还在准备中,请稍后重试",+ "planOpen": "正在分工,做完或停止后才能安排新的",+ "planClosed": "这个安排已经结束或更新了"+ }+}diff --git a/apps/mobile/src/i18n/locales/zh-CN/index.ts b/apps/mobile/src/i18n/locales/zh-CN/index.tsindex a51e2acd9f..5a06acd366 100644--- a/apps/mobile/src/i18n/locales/zh-CN/index.ts+++ b/apps/mobile/src/i18n/locales/zh-CN/index.ts@@ -13,6 +13,7 @@ import composer from './composer.json';import deviceLink from './deviceLink.json';import devices from './devices.json';import files from './files.json';+import groupChat from './groupChat.json';import home from './home.json';import interaction from './interaction.json';import message from './message.json';@@ -33,6 +34,7 @@ export default {deviceLink,devices,files,+ groupChat,home,interaction,message,diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.jsonnew file mode 100644index 0000000000..f1499cd81c--- /dev/null+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json@@ -0,0 +1,166 @@+{+ "title": "群聊",+ "memberSeparator": "、",+ "memberCount_one": "{{count}} 位夥伴",+ "memberCount_other": "{{count}} 位夥伴",+ "organizer": "負責人",+ "waitingConfirm": "{{name}}在等你確認",+ "loadFailedTitle": "無法載入這個群聊",+ "loadFailedDescription": "暫時讀不到電腦上的這個群聊,可以重試,或返回夥伴頁。",+ "unavailableTitle": "這個群聊已無法使用",+ "unavailableDescription": "它可能已被刪除。返回夥伴頁可以開啟其他群聊和夥伴。",+ "list": {+ "noMessages": "還沒有訊息",+ "empty": "還沒有群聊。點 + 選幾位夥伴建一個。",+ "running": "有夥伴正在忙"+ },+ "create": {+ "title": "新增群聊",+ "description": "選幾位夥伴放進一個群聊。你說一句,它們會一起接話。",+ "nameLabel": "群聊名稱",+ "namePlaceholder": "例如:週末出遊",+ "nameRequired": "為群聊取個名字",+ "membersLabel": "選擇夥伴",+ "selectedCount_one": "已選 {{count}} 位,最多 {{max}} 位",+ "selectedCount_other": "已選 {{count}} 位,最多 {{max}} 位",+ "minMembers": "至少選 {{min}} 位夥伴",+ "notEnoughBots": "至少需要 {{min}} 位可用的夥伴才能建立群聊,先去新增夥伴吧。",+ "submit": "建立群聊",+ "failed": "群聊沒能建立,請稍後重試",+ "chooseComputer": "在哪台電腦上建群",+ "computerNote": "群聊建在 {{deviceName}} 上,夥伴們在這台電腦上做事。"+ },+ "memberStatus": {+ "paused": "已暫停",+ "unavailable": "無法使用"+ },+ "mention": {+ "all": "所有人",+ "allHint": "大家都回答",+ "label": "點名夥伴"+ },+ "composer": {+ "label": "群聊訊息",+ "placeholder": "在群聊裡說點什麼,@ 某位夥伴就只讓它回答…",+ "noMembers": "群聊裡暫時沒有能接話的夥伴,去群聊設定裡新增一位吧",+ "tooLong": "訊息太長了,最多 {{max}} 個字",+ "sendFailed": "訊息沒有送出,請稍後重試",+ "stopFailed": "沒能停下這一輪,請再試一次",+ "stop": "停止這一輪",+ "more": "更多操作",+ "division": "安排分工",+ "divisionDescription": "讓負責人先分好工,夥伴們一步步做",+ "divisionBusy": "正在分工,做完或停止後才能安排新的",+ "divisionTag": "分工",+ "removeDivision": "移除分工",+ "placeholderDivision": "說說要做成什麼,負責人會先分好工…",+ "placeholderPlanProposed": "想換人或改步驟,直接說…",+ "placeholderPlanWaiting": "想讓{{name}}改改,直接說…",+ "placeholderPlanRunning": "說的話會帶給正在做的{{name}}…",+ "send": "傳送"+ },+ "timeline": {+ "emptyTitle": "群聊裡還沒有訊息",+ "emptyDescription": "說一句話開始,夥伴們會接著聊。@ 某位夥伴就只讓它回答。",+ "roundEnded": "夥伴們說完了",+ "continue": "繼續討論",+ "continueFailed": "沒能繼續討論,請再試一次",+ "nextStep": "下一步:",+ "continuePlan": "繼續",+ "continuePlanFailed": "沒能繼續下一步,請再試一次",+ "stepFailed": "{{name}}沒做完",+ "retryStep": "重試",+ "retryFailed": "沒能重試這一步,請再試一次",+ "endPlan": "結束分工",+ "planDone_one": "{{count}} 步都做完了",+ "planDone_other": "{{count}} 步都做完了",+ "planDoneGeneric": "分工做完了",+ "olderOnComputer": "更早的訊息請在電腦上查看"+ },+ "notice": {+ "memberFailed": "{{name}}這次沒能回覆",+ "memberTimeout": "{{name}}太久沒有回覆,這次先跳過",+ "memberUnavailable": "{{name}}現在無法使用,這次沒有發言",+ "planFailed": "{{name}}沒排出分工,可以再試一次",+ "planStopped": "分工已停止",+ "workdirUnavailable": "{{name}}找不到工作目錄",+ "stepFailed": "{{name}}這一步出錯了,沒做完",+ "stepTimeout": "{{name}}太久沒做完,這一步先停下",+ "stepUnavailable": "{{name}}現在無法使用,這一步沒辦法做"+ },+ "plan": {+ "intro_one": "這件事分 {{count}} 步,我這樣分工:",+ "intro_other": "這件事分 {{count}} 步,我這樣分工:",+ "missing": "這個安排已經讀不到了",+ "start": "開始",+ "dismiss": "不用了",+ "editHint": "想換人或改步驟,直接說",+ "pauseNote": "每做完一步會停下來,等你點「繼續」。",+ "superseded": "已更新",+ "dismissed": "不用了",+ "stopped": "已停止",+ "stepDone": "做完了",+ "stepRunning": "正在做",+ "stepFailed": "沒做完",+ "stepPending": "還沒開始",+ "stepMenuTitle": "誰來做這一步",+ "removeStep": "刪掉這一步",+ "keepOneStep": "至少留一步",+ "startFailed": "沒能開始分工,請再試一次",+ "dismissFailed": "沒能結束這個安排,請再試一次",+ "editFailed": "這一步沒改成,請再試一次",+ "editStepHint": "換人或刪掉這一步",+ "reassignStepHint": "換人做這一步"+ },+ "speaking": {+ "planning": "正在安排…",+ "step": "正在做…"+ },+ "files": {+ "onComputer": "檔案在電腦上,回電腦開啟"+ },+ "settings": {+ "open": "群聊設定",+ "title": "群聊設定",+ "members": "成員",+ "remove": "移出",+ "removeNamed": "把 {{name}} 移出群聊",+ "minMembers": "群聊裡至少要有 {{min}} 位夥伴",+ "maxMembers": "最多 {{max}} 位",+ "noMoreBots": "沒有其他可以加入的夥伴了",+ "nameSaveFailed": "群聊名稱沒能儲存,已恢復原來的名稱",+ "membersSaveFailed": "成員沒能更新,請再試一次",+ "replyMode": "沒有 @ 人的時候",+ "replyModeAll": "大家都可以接話",+ "replyModeMentioned": "只有被 @ 的回答",+ "replyModeNote": "沒什麼可補充的夥伴不會說話。每輪最多聊 3 圈、10 則,之後等你點「繼續討論」。",+ "replyModeSaveFailed": "回覆方式沒能儲存,請再試一次",+ "delete": "刪除群聊",+ "deleteNote": "只刪除這個群聊和其中的訊息,夥伴本身、它們的記憶和私聊都不受影響。",+ "deleteConfirmTitle": "刪除「{{name}}」?",+ "deleteFailed": "群聊沒能刪除,請稍後重試",+ "speakingMode": "發言方式",+ "speakingModeAuto": "自動",+ "speakingModeSequential": "一律輪流",+ "speakingModeAutoNote": "沒有 @ 人或 @所有人時,第一輪大家同時想,之後輪流接話;@ 了夥伴就按 @ 的先後輪流。",+ "speakingModeSequentialNote": "每次只有一位夥伴發言,後說的能看到前面的回答。",+ "speakingModeSaveFailed": "發言方式沒能儲存,請再試一次",+ "setOrganizer": "設為負責人",+ "setOrganizerNamed": "把 {{name}} 設為負責人",+ "organizerNote": "負責人幫你安排誰做哪一步,預設是第一位夥伴。",+ "organizerSaveFailed": "負責人沒能更換,請再試一次",+ "projectDir": "專案資料夾",+ "projectDirNone": "沒選",+ "projectDirNote": "分工做事時,夥伴們在這裡工作。不選也行,會用這個群聊自己的資料夾;選了 git 專案,每次分工會新開一個 worktree 和分支,不動你手上的程式碼。",+ "add": "新增夥伴",+ "projectDirOnComputer": "在電腦上選擇或更換"+ },+ "errors": {+ "memberLimit": "一個群聊需要 2–6 位夥伴",+ "memberUnavailable": "有夥伴現在無法使用,換一位再試",+ "notFound": "這個群聊已不存在",+ "hostNotReady": "Cindy 還在準備中,請稍後重試",+ "planOpen": "正在分工,做完或停止後才能安排新的",+ "planClosed": "這個安排已經結束或更新了"+ }+}diff --git a/apps/mobile/src/i18n/locales/zh-TW/index.ts b/apps/mobile/src/i18n/locales/zh-TW/index.tsindex a51e2acd9f..5a06acd366 100644--- a/apps/mobile/src/i18n/locales/zh-TW/index.ts+++ b/apps/mobile/src/i18n/locales/zh-TW/index.ts@@ -13,6 +13,7 @@ import composer from './composer.json';import deviceLink from './deviceLink.json';import devices from './devices.json';import files from './files.json';+import groupChat from './groupChat.json';import home from './home.json';import interaction from './interaction.json';import message from './message.json';@@ -33,6 +34,7 @@ export default {deviceLink,devices,files,+ groupChat,home,interaction,message,diff --git a/apps/mobile/src/notifications/pushRegistrationModel.ts b/apps/mobile/src/notifications/pushRegistrationModel.tsindex 1da568fcb5..8c1dc9be18 100644--- a/apps/mobile/src/notifications/pushRegistrationModel.ts+++ b/apps/mobile/src/notifications/pushRegistrationModel.ts@@ -47,16 +47,55 @@ export function buildPushTokenRegistrationBody(opts: {};}+const BOT_GROUP_DEEP_LINK = /^\/companions\/groups\/([^/?#]+)\?([^#]*)$/;+const MAX_DEEP_LINK_ID_CHARS = 256;++function hasControlCharacter(value: string): boolean {+ for (let index = 0; index < value.length; index += 1) {+ if (value.charCodeAt(index) < 0x20 || value.charCodeAt(index) === 0x7f) return true;+ }+ return false;+}++function decodedDeepLinkId(value: string): string | null {+ try {+ const decoded = decodeURIComponent(value);+ return decoded && decoded.length <= MAX_DEEP_LINK_ID_CHARS && !hasControlCharacter(decoded) ? decoded : null;+ } catch {+ return null;+ }+}+/**- * 从通知 data 中解析深链。只接受桌面端契约内的应用内路径(/sessions/...),- * 拒绝任意 URL / 其它路径 —— 推送 payload 经第三方通道,按不可信输入对待。+ * 分工一步停下时的群聊提醒(bot-group-chat.md §8.3):`/companions/groups/<groupId>?deviceId=<id>`。+ * 形状逐项校验:群 id 必须是规范编码的单段路径,查询串只能有一个非空的 deviceId,不带片段;+ * 通过后按规范形式重建,绝不原样转发。+ */+function parseBotGroupDeepLink(deepLink: string): string | null {+ const match = BOT_GROUP_DEEP_LINK.exec(deepLink);+ if (!match) return null;+ const [, encodedGroupId, query] = match;+ const groupId = decodedDeepLinkId(encodedGroupId!);+ if (!groupId || encodeURIComponent(groupId) !== encodedGroupId) return null;+ const params = new URLSearchParams(query);+ const keys = [...params.keys()];+ if (keys.length !== 1 || keys[0] !== 'deviceId') return null;+ const deviceId = params.get('deviceId') ?? '';+ if (!deviceId || deviceId.length > MAX_DEEP_LINK_ID_CHARS || hasControlCharacter(deviceId)) return null;+ return `/companions/groups/${encodeURIComponent(groupId)}?deviceId=${encodeURIComponent(deviceId)}`;+}++/**+ * 从通知 data 中解析深链。只接受桌面端契约内的应用内路径(/sessions/... 与群聊+ * /companions/groups/...),拒绝任意 URL / 其它路径 —— 推送 payload 经第三方通道,按不可信输入对待。*/export function parseNotificationDeepLink(data: unknown): string | null {if (!data || typeof data !== 'object') return null;const deepLink = (data as Record<string, unknown>).deepLink;if (typeof deepLink !== 'string') return null;- if (!deepLink.startsWith('/sessions/')) return null;if (deepLink.includes('://') || deepLink.startsWith('//')) return null;+ if (deepLink.startsWith('/companions/groups/')) return parseBotGroupDeepLink(deepLink);+ if (!deepLink.startsWith('/sessions/')) return null;return deepLink;}diff --git a/apps/mobile/src/session/BotGroupAvatars.tsx b/apps/mobile/src/session/BotGroupAvatars.tsxnew file mode 100644index 0000000000..1f0d10dfc5--- /dev/null+++ b/apps/mobile/src/session/BotGroupAvatars.tsx@@ -0,0 +1,116 @@+/**+ * 群的身份标记(对照桌面 BotGroupAvatars.tsx):列表行用两位成员斜向叠放,顶栏用一排+ * 叠放头像。每个头像仍是 RemoteCompanionAvatar;叠放处用与底色同色的 2pt 描边隔开,+ * 不引入阴影或新 token。头像与名字取伙伴列表缓存(只用于显示),缓存里没有时退回群里+ * 带来的名字与头像字段。+ */+import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';+import { StyleSheet, View } from 'react-native';+import { Users } from 'lucide-react-native';+import { useTranslation } from 'react-i18next';+import { resolveRemoteText, type RemoteResourceAvatar } from '@cindy/device-link';+import type { BotGroupMemberView } from '@cindy/maker-shared/botGroupChat';+import { useAuth } from '@/auth/AuthContext';+import { RemoteCompanionAvatar } from '@/components/RemoteCompanionAvatar';+import {+ cachedBotItem,+ readRemoteResourceSnapshot,+ remoteResourceCacheRevision,+ subscribeRemoteResourceCache,+} from '@/device-link/remoteResourceCache';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { iconSize, radius } from '@/theme/tokens';+import { BOT_GROUP_TEAMMATES_COLLECTION_ID, botGroupMemberAvatar } from './botGroupRemote';++export interface BotGroupIdentity {+ botId: string;+ name: string;+ avatar?: RemoteResourceAvatar;+}++/** Timeline and plan rows: Desktop BotAvatar `sm` / `xs` on a phone. */+export const BOT_GROUP_MESSAGE_AVATAR_SIZE = 28;+export const BOT_GROUP_STEP_AVATAR_SIZE = 24;+export const BOT_GROUP_INLINE_AVATAR_SIZE = 20;+export const BOT_GROUP_ROW_AVATAR_SIZE = 32;+const STACK_AVATAR_SIZE = 24;+const DUO_AVATAR_SIZE = 28;+const DUO_BOX_SIZE = 44;+/** Separates overlapped avatars; the same 2pt ring as the teammate connection dot. */+const STACK_RING = 2;++/**+ * Identity lookup for one computer's Bots: the cached teammate row (name, avatar) wins,+ * then the group's own member fields, then the name snapshot a message or step carries.+ */+export function useBotGroupIdentities(deviceId: string) {+ const { user } = useAuth();+ const userId = user?.id ?? '';+ const { i18n } = useTranslation();+ const revision = useSyncExternalStore(subscribeRemoteResourceCache, remoteResourceCacheRevision);+ // Loading the persisted roster does not notify subscribers; re-render once it is in memory.+ const [loaded, setLoaded] = useState(0);+ useEffect(() => {+ if (!userId) return;+ let current = true;+ void readRemoteResourceSnapshot(userId).then(() => { if (current) setLoaded((value) => value + 1); });+ return () => { current = false; };+ }, [userId]);+ return useCallback((botId: string, fallbackName = '', member?: Pick<BotGroupMemberView, 'name' | 'avatar' | 'avatarColor'>): BotGroupIdentity => {+ void revision; void loaded;+ const cached = botId ? cachedBotItem(userId, BOT_GROUP_TEAMMATES_COLLECTION_ID, deviceId, botId) : null;+ const cachedName = cached ? resolveRemoteText(cached.display.title, i18n.language) : '';+ const name = fallbackName.trim() || member?.name.trim() || cachedName || '';+ const avatar = cached?.display.avatar ?? (member ? botGroupMemberAvatar({ ...member, name: member.name || name }) : undefined);+ return { botId, name, ...(avatar ? { avatar } : {}) };+ }, [deviceId, i18n.language, loaded, revision, userId]);+}++export function BotGroupAvatar({ deviceId, identity, size, online }: {+ deviceId: string; identity: BotGroupIdentity; size: number; online: boolean;+}) {+ return <RemoteCompanionAvatar avatar={identity.avatar} deviceId={deviceId} name={identity.name} online={online} size={size} framed />;+}++/** A row of overlapped member avatars (screen header). */+export function BotGroupAvatarStack({ deviceId, members, online, max = 3 }: {+ deviceId: string; members: readonly BotGroupIdentity[]; online: boolean; max?: number;+}) {+ const styles = useThemedStyles(makeStyles);+ return <View style={styles.stack} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">+ {members.slice(0, max).map((member, index) => <View key={member.botId || index} style={[styles.ring, index > 0 && styles.stacked]}>+ <BotGroupAvatar deviceId={deviceId} identity={member} size={STACK_AVATAR_SIZE} online={online} />+ </View>)}+ </View>;+}++/** 44pt list mark: the first two members, offset diagonally (Desktop BotGroupDuoAvatar). */+export function BotGroupDuoAvatar({ deviceId, members, online }: {+ deviceId: string; members: readonly BotGroupIdentity[]; online: boolean;+}) {+ const styles = useThemedStyles(makeStyles);+ const { colors } = useTheme();+ const [first, second] = members;+ if (!first) {+ return <View style={[styles.duo, styles.duoEmpty]} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">+ <Users size={iconSize.md} color={colors.textTertiary} />+ </View>;+ }+ return <View style={styles.duo} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">+ <View style={styles.duoFirst}><BotGroupAvatar deviceId={deviceId} identity={first} size={DUO_AVATAR_SIZE} online={online} /></View>+ {second ? <View style={[styles.ring, styles.duoSecond]}>+ <BotGroupAvatar deviceId={deviceId} identity={second} size={DUO_AVATAR_SIZE} online={online} />+ </View> : null}+ </View>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ stack: { flexDirection: 'row', alignItems: 'center', flexShrink: 0 },+ ring: { borderRadius: radius.pill, borderWidth: STACK_RING, borderColor: colors.surface, overflow: 'hidden' },+ // Overlap by a third of the avatar, the same rhythm as the desktop header lockup.+ stacked: { marginLeft: -(STACK_AVATAR_SIZE / 3) },+ duo: { width: DUO_BOX_SIZE, height: DUO_BOX_SIZE, flexShrink: 0 },+ duoEmpty: { alignItems: 'center', justifyContent: 'center', borderRadius: radius.pill, backgroundColor: colors.surfaceChip },+ duoFirst: { position: 'absolute', left: 0, top: 0 },+ duoSecond: { position: 'absolute', right: -STACK_RING, bottom: -STACK_RING },+});diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsxnew file mode 100644index 0000000000..d41173c0e1--- /dev/null+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx@@ -0,0 +1,436 @@+/**+ * 手机上的群聊页(docs/product-rules/bot-group-chat.md §8,对照桌面 BotGroupChatView.tsx):+ * 顶栏(叠放头像、群名、成员名单、群设置)+ 多作者时间线 + 输入框。+ *+ * 群在电脑上,电脑执行全部规则;这里整页读电脑给的群快照(最新 100 条消息与涉及的安排),+ * 每次电脑推送变化就重读,不在本地拼时间线。分工的安排卡、交接文件、「下一步 · 继续」+ * 「没做完 · 重试」见 BotGroupPlan.tsx;正在发言的伙伴与它待确认的操作见 BotGroupSpeakerRow。+ */+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import {+ ActivityIndicator,+ Alert,+ KeyboardAvoidingView,+ Platform,+ Pressable,+ ScrollView,+ StyleSheet,+ View,+ type NativeScrollEvent,+ type NativeSyntheticEvent,+} from 'react-native';+import { Stack, useRouter } from 'expo-router';+import { ChevronLeft, Settings2 } from 'lucide-react-native';+import { SafeAreaView } from 'react-native-safe-area-context';+import { useTranslation } from 'react-i18next';+import { resolveRemoteText } from '@cindy/device-link';+import {+ BOT_GROUP_REMOTE_COLLECTION_ID,+ type BotGroupMemberView,+ type BotGroupMessageView,+ type BotGroupPlanAction,+ type BotGroupPlanStepView,+ type BotGroupPlanView,+ type BotGroupRemoteChatData,+} from '@cindy/maker-shared/botGroupChat';+import {+ botGroupComposerPlanState,+ botGroupMemberNames,+ botGroupNoticeVariant,+ botGroupPlanFollowUp,+ continuableRoundEndId,+ openBotGroupPlan,+} from '@cindy/maker-shared/botGroupPresentation';+import { collectBotMessageTimeGroups, formatBotMessageGroupTime } from '@cindy/maker-shared/botTimeline';+import { useAuth } from '@/auth/AuthContext';+import { Text } from '@/components/AppText';+import { MainWindowActionButton, MainWindowEmptyState } from '@/components/MobilePrimitives';+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';+import { readRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';+import type { RemoteResourceHostTarget } from '@/device-link/remoteResources';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';+import { goBackGuarded } from '@/utils/backGuard';+import {+ BOT_GROUP_MESSAGE_AVATAR_SIZE,+ BotGroupAvatar,+ BotGroupAvatarStack,+ useBotGroupIdentities,+} from './BotGroupAvatars';+import { BotGroupComposer, type BotGroupSendInput } from './BotGroupComposer';+import { BotGroupMarkdownText, BotGroupUserText } from './BotGroupMessageText';+import {+ BOT_GROUP_COMPACT_HIT_SLOP,+ BotGroupDivider,+ BotGroupHandoffFiles,+ BotGroupOrganizerTag,+ BotGroupPlanCard,+ BotGroupPlanEndDivider,+ BotGroupPlanFollowUpRow,+ type BotGroupFollowUpAction,+ type BotGroupIdentityLookup,+ type BotGroupPlanCardAction,+} from './BotGroupPlan';+import { BotGroupSettingsSheet } from './BotGroupSettingsSheet';+import { BotGroupSpeakerRow } from './BotGroupSpeakerRow';+import { botGroupActionErrorText } from './botGroupCopy';+import { HomeHeaderGlassButton } from './HomeHeaderGlassButton';+import { useBotGroupChat } from './useBotGroupChat';++/** Toast copy when a plan action fails without a more specific cause. */+const PLAN_ACTION_FAILED: Record<BotGroupPlanAction, string> = {+ start: 'groupChat.plan.startFailed',+ dismiss: 'groupChat.plan.dismissFailed',+ continue: 'groupChat.timeline.continuePlanFailed',+ retry: 'groupChat.timeline.retryFailed',+};++type PlanPending = { planId: string; action: BotGroupPlanAction | 'edit' };+/** Follow new messages while the reader is within this distance of the bottom. */+const STICK_TO_BOTTOM_PX = 48;++export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId: string; deviceName: string; groupId: string }) {+ const { t, i18n } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const router = useRouter();+ const { user, accountGeneration } = useAuth();+ const host = useMemo<RemoteResourceHostTarget>(() => ({ deviceId, deviceName: deviceName || deviceId }), [deviceId, deviceName]);+ const chat = useBotGroupChat(host, groupId);+ const identity = useBotGroupIdentities(deviceId);+ const [settings, setSettings] = useState(false);+ const leaveAfterSettings = useRef(false);+ const [continuing, setContinuing] = useState(false);+ const [planPending, setPlanPending] = useState<PlanPending | null>(null);+ const planPendingRef = useRef(false);+ const scrollRef = useRef<ScrollView>(null);+ const stickToBottom = useRef(true);+ const group = chat.state.kind === 'ready' ? chat.state.group : null;+ // The list row seeds the header while the first read is in flight (display only).+ const cachedRow = group ? null : readRemoteCollectionCache(`${user?.id ?? ''}:${accountGeneration}`, BOT_GROUP_REMOTE_COLLECTION_ID)+ .find((row) => row.host.deviceId === deviceId && row.item.ref.id === groupId) ?? null;++ const identityFor = useCallback<BotGroupIdentityLookup>((botId, fallbackName = '') => {+ const member = group?.members.find((candidate) => candidate.botId === botId);+ return identity(botId, fallbackName, member);+ }, [group?.members, identity]);++ const leave = useCallback(() => goBackGuarded(router, '/devices'), [router]);++ // The computer announces a deleted group before the delete returns, so the phone can re-read+ // it as gone first. That unmounts the settings sheet before it reports closing; leave anyway.+ const hasGroup = group !== null;+ const hasGroupRef = useRef(hasGroup);+ useEffect(() => {+ hasGroupRef.current = hasGroup;+ if (!hasGroup && leaveAfterSettings.current) { leaveAfterSettings.current = false; leave(); }+ }, [hasGroup, leave]);+ const onGroupDeleted = useCallback(() => {+ if (hasGroupRef.current) { leaveAfterSettings.current = true; setSettings(false); } else leave();+ }, [leave]);++ const report = useCallback((error: unknown, fallbackKey: string) => {+ Alert.alert(chat.online ? botGroupActionErrorText(t, error, fallbackKey) : t('devices.resources.hostOffline'));+ }, [chat.online, t]);++ const continueRound = async () => {+ if (continuing) return;+ setContinuing(true);+ stickToBottom.current = true;+ try { await chat.act('continue'); } catch (error) { report(error, 'groupChat.timeline.continueFailed'); } finally { setContinuing(false); }+ };++ /** 开始 / 不用了 / 继续 / 重试 / 结束分工; the computer pushes the change and the view re-reads. */+ const runPlanAction = async (action: BotGroupPlanAction, planId: string) => {+ if (planPendingRef.current) return;+ planPendingRef.current = true;+ setPlanPending({ planId, action });+ stickToBottom.current = true;+ try { await chat.act(`plan-${action}`, { planId }); } catch (error) { report(error, PLAN_ACTION_FAILED[action]); } finally {+ planPendingRef.current = false;+ setPlanPending(null);+ }+ };++ const editPlanStep = async (planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) => {+ if (planPendingRef.current) return;+ planPendingRef.current = true;+ setPlanPending({ planId, action: 'edit' });+ try {+ await chat.act('plan-edit', { planId, position: step.position, action, ...(botId ? { botId } : {}) });+ } catch (error) { report(error, 'groupChat.plan.editFailed'); } finally {+ planPendingRef.current = false;+ setPlanPending(null);+ }+ };++ const send = async (input: BotGroupSendInput) => {+ stickToBottom.current = true;+ try {+ await chat.act('send', {+ text: input.text,+ mentions: input.mentions,+ clientId: input.clientId,+ ...(input.division ? { division: true } : {}),+ });+ } catch (error) {+ report(error, 'groupChat.composer.sendFailed');+ throw error;+ }+ };++ const stop = async () => {+ try { await chat.act('stop'); } catch (error) { report(error, 'groupChat.composer.stopFailed'); }+ };++ const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {+ const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;+ stickToBottom.current = contentSize.height - contentOffset.y - layoutMeasurement.height < STICK_TO_BOTTOM_PX;+ };++ const title = group?.name ?? (cachedRow ? resolveRemoteText(cachedRow.item.display.title, i18n.language) : '');+ const memberLine = group+ ? botGroupMemberNames(group.members, t('groupChat.memberSeparator'))+ : cachedRow?.item.display.subtitle ? resolveRemoteText(cachedRow.item.display.subtitle, i18n.language) : '';+ const headerMembers = group ? group.members.map((member) => identityFor(member.botId, member.name)) : [];++ const header = <View style={styles.header} testID="botGroup.header">+ <HomeHeaderGlassButton accessibilityLabel={t('shared.back')} onPress={leave} testID="botGroup.back">+ <ChevronLeft size={iconSize.xl} color={colors.textPrimary} strokeWidth={iconStroke.regular} />+ </HomeHeaderGlassButton>+ <Pressable accessibilityRole="button" accessibilityLabel={[title, memberLine].filter(Boolean).join(', ')}+ accessibilityHint={t('groupChat.settings.open')} disabled={!group} onPress={() => setSettings(true)}+ style={({ pressed }) => [styles.identity, pressed && mobileInteractionStyles.pressed]} testID="botGroup.identity">+ {headerMembers.length ? <BotGroupAvatarStack deviceId={deviceId} members={headerMembers} online={chat.online} /> : null}+ <View style={styles.identityText}>+ <Text numberOfLines={1} style={styles.headerTitle}>{title}</Text>+ {memberLine ? <Text numberOfLines={1} style={styles.headerSubtitle}>{memberLine}</Text> : null}+ </View>+ </Pressable>+ <HomeHeaderGlassButton accessibilityLabel={t('groupChat.settings.open')} disabled={!group} onPress={() => setSettings(true)}+ testID="botGroup.settingsButton">+ <Settings2 size={iconSize.lg} color={colors.textPrimary} strokeWidth={iconStroke.regular} />+ </HomeHeaderGlassButton>+ </View>;++ let body;+ if (chat.state.kind === 'loading' && !chat.online) {+ // Nothing to show until the computer is reachable again; the screen re-reads on reconnect.+ body = <View style={styles.center}>+ <MainWindowEmptyState centered testID="botGroup.offline" title={t('groupChat.loadFailedTitle')} copy={t('devices.resources.hostOffline')}>+ <View style={styles.emptyActions}>+ <MainWindowActionButton action={{ label: t('shared.back'), onPress: leave, testID: 'botGroup.leave' }} />+ </View>+ </MainWindowEmptyState>+ </View>;+ } else if (chat.state.kind === 'loading') {+ body = <View style={styles.center}><ActivityIndicator color={colors.textSecondary} /></View>;+ } else if (chat.state.kind !== 'ready' || !group) {+ const failed = chat.state.kind === 'error';+ body = <View style={styles.center}>+ <MainWindowEmptyState centered testID={failed ? 'botGroup.loadFailed' : 'botGroup.unavailable'}+ title={t(failed ? 'groupChat.loadFailedTitle' : 'groupChat.unavailableTitle')}+ copy={t(failed ? 'groupChat.loadFailedDescription' : 'groupChat.unavailableDescription')}>+ <View style={styles.emptyActions}>+ <MainWindowActionButton action={{ label: t('shared.back'), onPress: leave, testID: 'botGroup.leave' }} />+ {failed ? <MainWindowActionButton action={{ label: t('devices.resources.retry'), tone: 'primary', onPress: chat.reload, testID: 'botGroup.retry' }} /> : null}+ </View>+ </MainWindowEmptyState>+ </View>;+ } else {+ body = <KeyboardAvoidingView style={styles.flex} enabled={Platform.OS === 'ios'} behavior="padding">+ {!chat.online ? <Text accessibilityRole="alert" style={styles.offline} testID="botGroup.offlineNote">{t('devices.resources.hostOffline')}</Text> : null}+ <ScrollView ref={scrollRef} style={styles.flex} contentContainerStyle={styles.timeline} keyboardShouldPersistTaps="handled"+ keyboardDismissMode="interactive" onScroll={onScroll} scrollEventThrottle={64}+ onContentSizeChange={() => { if (stickToBottom.current) scrollRef.current?.scrollToEnd({ animated: false }); }}+ testID="botGroup.timeline">+ <BotGroupTimeline group={group} deviceId={deviceId} online={chat.online} identityFor={identityFor}+ continuing={continuing} planPending={planPending}+ onContinue={() => void continueRound()}+ onPlanAction={(action, planId) => void runPlanAction(action, planId)}+ onEditStep={(planId, step, action, botId) => void editPlanStep(planId, step, action, botId)}+ onInteractionError={(message) => { if (message) Alert.alert(message); }} />+ </ScrollView>+ <BotGroupComposer members={group.members} identityFor={identityFor} deviceId={deviceId} online={chat.online}+ running={group.round.status === 'running'} planState={botGroupComposerPlanState(openBotGroupPlan(group))}+ onSend={send} onStop={stop} />+ </KeyboardAvoidingView>;+ }++ return <SafeAreaView style={styles.screen} edges={['top', 'left', 'right', 'bottom']} testID="botGroup.screen">+ <Stack.Screen options={{ headerShown: false }} />+ {header}+ {body}+ {group ? <BotGroupSettingsSheet visible={settings} group={group} host={host} identityFor={identityFor} online={chat.online}+ act={chat.act} onClose={() => setSettings(false)}+ onClosed={() => { if (leaveAfterSettings.current) { leaveAfterSettings.current = false; leave(); } }}+ onDeleted={onGroupDeleted} /> : null}+ </SafeAreaView>;+}++function planCardPending(action: PlanPending['action'] | null): BotGroupPlanCardAction | null {+ return action === 'start' || action === 'dismiss' || action === 'edit' ? action : null;+}++function followUpPending(action: PlanPending['action'] | null): BotGroupFollowUpAction | null {+ return action === 'continue' || action === 'retry' || action === 'dismiss' ? action : null;+}++export function BotGroupTimeline({+ group, deviceId, online, identityFor, continuing, planPending, onContinue, onPlanAction, onEditStep, onInteractionError,+}: {+ group: BotGroupRemoteChatData;+ deviceId: string;+ online: boolean;+ identityFor: BotGroupIdentityLookup;+ continuing: boolean;+ planPending: PlanPending | null;+ onContinue(): void;+ onPlanAction(action: BotGroupPlanAction, planId: string): void;+ onEditStep(planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string): void;+ onInteractionError(message: string | null): void;+}) {+ const { t, i18n } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ const messages = group.messages;+ const planById = new Map(group.plans.map((plan) => [plan.id, plan]));+ const openPlan = openBotGroupPlan(group);+ const followUp = botGroupPlanFollowUp(openPlan);+ const continueId = continuableRoundEndId(messages, group.round);+ const timeGroups = collectBotMessageTimeGroups(messages.map((message) => ({ clientId: message.id, createdAt: message.createdAt })));+ const allLabel = t('groupChat.mention.all');+ 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 ? <Text style={styles.olderNote} testID="botGroup.olderOnComputer">{t('groupChat.timeline.olderOnComputer')}</Text> : null}+ {messages.length === 0 && !running ? <MainWindowEmptyState centered testID="botGroup.empty"+ title={t('groupChat.timeline.emptyTitle')} copy={t('groupChat.timeline.emptyDescription')} /> : null}+ {messages.map((message) => {+ const groupTime = timeGroups.get(message.id);+ return <View key={message.id} style={styles.item}>+ {groupTime !== undefined ? <Text style={styles.time}>{formatBotMessageGroupTime(groupTime, i18n.language)}</Text> : null}+ <BotGroupTimelineItem message={message} member={message.authorBotId ? memberById.get(message.authorBotId) : undefined}+ members={group.members} deviceId={deviceId} online={online} identityFor={identityFor} mentionLabels={mentionLabels}+ canContinue={message.id === continueId} continuing={continuing} onContinue={onContinue}+ plan={message.planId ? planById.get(message.planId) : undefined}+ planActionable={message.kind === 'plan' && openPlan?.id === message.planId && openPlan.status === 'proposed'}+ planReassignable={message.kind === 'plan' && openPlan?.id === message.planId && openPlan.status === 'waiting'}+ planPending={planCardPending(pendingFor(message.planId))}+ onPlanAction={(action) => { if (message.planId) onPlanAction(action, message.planId); }}+ onEditStep={(step, action, botId) => { if (message.planId) onEditStep(message.planId, step, action, botId); }} />+ </View>;+ })}+ {openPlan && followUp ? <View style={styles.indented}>+ <BotGroupPlanFollowUpRow followUp={followUp} identityFor={identityFor} deviceId={deviceId} online={online}+ pending={followUpPending(pendingFor(openPlan.id))}+ onContinue={() => onPlanAction('continue', openPlan.id)}+ onRetry={() => onPlanAction('retry', openPlan.id)}+ onEnd={() => onPlanAction('dismiss', openPlan.id)} />+ </View> : null}+ {speakers.map((speaker) => {+ const member = memberById.get(speaker.botId)!;+ return <BotGroupSpeakerRow key={`${speaker.botId}:${speaker.activity}`} deviceId={deviceId} online={online}+ identity={identityFor(member.botId, member.name)} sessionId={speaker.sessionId} activity={speaker.activity}+ onError={onInteractionError} />;+ })}+ </>;+}++function BotGroupTimelineItem({+ message, member, members, deviceId, online, identityFor, mentionLabels, canContinue, continuing, onContinue,+ plan, planActionable, planReassignable, planPending, onPlanAction, onEditStep,+}: {+ message: BotGroupMessageView;+ member: BotGroupMemberView | undefined;+ members: readonly BotGroupMemberView[];+ deviceId: string;+ online: boolean;+ identityFor: BotGroupIdentityLookup;+ 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;+ planReassignable: boolean;+ planPending: BotGroupPlanCardAction | null;+ onPlanAction(action: 'start' | 'dismiss'): void;+ onEditStep(step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string): void;+}) {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ if (message.kind === 'round-end') {+ return <BotGroupDivider testID="botGroup.roundEnd">+ <Text style={styles.dividerText}>{t('groupChat.timeline.roundEnded')}</Text>+ {canContinue ? <MainWindowActionButton density="compact" hitSlop={BOT_GROUP_COMPACT_HIT_SLOP}+ action={{ label: t('groupChat.timeline.continue'), busy: continuing, disabled: !online, onPress: onContinue, testID: 'botGroup.continue' }} /> : null}+ </BotGroupDivider>;+ }+ 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 || '';+ const variant = botGroupNoticeVariant(message.noticeCode, message.planId !== null);+ return <Text style={styles.notice} testID="botGroup.notice">{variant ? t(`groupChat.notice.${variant}`, { name }) : message.content}</Text>;+ }+ if (message.authorKind === 'user') {+ return <View style={styles.userRow} testID="botGroup.message.user">+ <View style={styles.userBubble}><BotGroupUserText content={message.content} mentionLabels={mentionLabels} /></View>+ </View>;+ }+ // Name snapshot from when it was said; the avatar follows the live profile.+ const author = identityFor(message.authorBotId ?? '', message.authorName || member?.name || '');+ const isPlanCard = message.kind === 'plan';+ return <View style={styles.botRow} testID={isPlanCard ? 'botGroup.message.plan' : 'botGroup.message.bot'}>+ <BotGroupAvatar deviceId={deviceId} identity={author} size={BOT_GROUP_MESSAGE_AVATAR_SIZE} online={online} />+ <View style={styles.botColumn}>+ <View style={styles.authorRow}>+ <Text numberOfLines={1} style={styles.authorName}>{author.name}</Text>+ {isPlanCard ? <BotGroupOrganizerTag /> : null}+ </View>+ {isPlanCard+ ? <BotGroupPlanCard plan={plan} members={members} identityFor={identityFor} deviceId={deviceId} online={online}+ actionable={planActionable} reassignable={planReassignable} pending={planPending}+ onStart={() => onPlanAction('start')} onDismiss={() => onPlanAction('dismiss')} onEditStep={onEditStep} />+ : <>+ {message.content.trim() ? <BotGroupMarkdownText content={message.content} /> : null}+ <BotGroupHandoffFiles files={message.files} />+ </>}+ </View>+ </View>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ screen: { flex: 1, backgroundColor: colors.surface },+ flex: { flex: 1 },+ header: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, minHeight: 52, paddingHorizontal: spacing.md,+ borderBottomColor: colors.border, borderBottomWidth: StyleSheet.hairlineWidth },+ identity: { flex: 1, minWidth: 0, minHeight: 44, flexDirection: 'row', alignItems: 'center', gap: spacing.sm },+ identityText: { flex: 1, minWidth: 0 },+ headerTitle: { color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.semibold },+ headerSubtitle: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },+ center: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: spacing.xl },+ emptyActions: { flexDirection: 'row', justifyContent: 'center', gap: spacing.sm, marginTop: spacing.lg },+ timeline: { flexGrow: 1, justifyContent: 'flex-end', gap: spacing.lg, paddingHorizontal: spacing.lg, paddingVertical: spacing.md },+ item: { gap: spacing.lg },+ // Aligns the follow-up row with message text, past the 28pt avatar and its gap.+ indented: { paddingLeft: BOT_GROUP_MESSAGE_AVATAR_SIZE + spacing.sm },+ offline: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, textAlign: 'center',+ paddingHorizontal: spacing.lg, paddingTop: spacing.sm },+ olderNote: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, textAlign: 'center' },+ time: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, textAlign: 'center' },+ notice: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, textAlign: 'center' },+ dividerText: { flexShrink: 1, color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, textAlign: 'center' },+ userRow: { flexDirection: 'row', justifyContent: 'flex-end' },+ userBubble: { maxWidth: '82%', backgroundColor: colors.surfaceElevated, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,+ borderRadius: radius.container, paddingHorizontal: spacing.md, paddingVertical: spacing.sm },+ botRow: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm },+ botColumn: { flex: 1, minWidth: 0, gap: spacing.xs },+ authorRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, minHeight: BOT_GROUP_MESSAGE_AVATAR_SIZE },+ authorName: { flexShrink: 1, color: colors.textPrimary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.medium },+});diff --git a/apps/mobile/src/session/BotGroupComposer.tsx b/apps/mobile/src/session/BotGroupComposer.tsxnew file mode 100644index 0000000000..e8b22eb2ff--- /dev/null+++ b/apps/mobile/src/session/BotGroupComposer.tsx@@ -0,0 +1,289 @@+/**+ * 群聊输入框(对照桌面 BotGroupComposer.tsx,docs/product-rules/bot-group-chat.md §4.1 / §7.2)。+ *+ * 纯文本;输入 `@` 在输入框上方弹出点名候选,第一项固定是「所有人」。发送时以正文重新+ * 解析点名(与桌面同一套规则,见 @cindy/maker-shared/botGroupMentions),clientId 作为幂等+ * 键:同一段文字、同一个「分工」标签重发沿用同一个 clientId。一轮进行中输入框为空时,+ * 发送按钮变成停止;有文字时照常发送(插话本身就会作废当前一轮)。+ *+ * 「+」里的「安排分工」给这条消息加上可去掉的「分工」标签(`division: true`);安排进行中+ * 或等继续时不能再安排新的,点「+」只说明原因。占位文字跟随未结束的安排。+ */+import { useMemo, useRef, useState } from 'react';+import { Alert, Pressable, ScrollView, StyleSheet, View, type TextInput as NativeTextInput } from 'react-native';+import { randomUUID } from 'expo-crypto';+import { Plus, Square, Users, X } from 'lucide-react-native';+import { useTranslation } from 'react-i18next';+import { BOT_GROUP_MESSAGE_MAX_CHARS, type BotGroupMemberView, type BotGroupMention } from '@cindy/maker-shared/botGroupChat';+import {+ filterBotGroupMentionCandidates,+ findBotGroupMentionQuery,+ insertBotGroupMention,+ resolveBotGroupMentions,+ type BotGroupTrackedMention,+} from '@cindy/maker-shared/botGroupMentions';+import {+ isActiveBotGroupMember,+ isBotGroupDivisionBlocked,+ type BotGroupComposerPlanState,+} from '@cindy/maker-shared/botGroupPresentation';+import { Text } from '@/components/AppText';+import { PaperPlaneIcon } from '@/components/PaperPlaneIcon';+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';+import { iconStroke, useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, iconSize, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';+import { BOT_GROUP_STEP_AVATAR_SIZE, BotGroupAvatar } from './BotGroupAvatars';+import { BotGroupMenu } from './BotGroupMenu';+import type { BotGroupIdentityLookup } from './BotGroupPlan';+import { MobileComposerInputRow } from './MobileComposerInputRow';+import { nextBotGroupSendAttempt, type BotGroupSendAttempt } from './botGroupRemote';++const CONTROL_SIZE = 34;+const CONTROL_HIT_SLOP = { top: 8, bottom: 8, left: 8, right: 8 } as const;+const TAG_HIT_SLOP = { top: 12, bottom: 12, left: 8, right: 12 } as const;+/** Five candidate rows stay visible above the keyboard; the rest scroll. */+const PICKER_MAX_HEIGHT = 5 * 44;++export interface BotGroupSendInput {+ text: string;+ mentions: BotGroupMention;+ clientId: string;+ division: boolean;+}++type MentionOption =+ | { kind: 'all'; label: string }+ | { kind: 'member'; label: string; member: BotGroupMemberView };++export function BotGroupComposer({+ members, identityFor, deviceId, online, running, planState, onSend, onStop,+}: {+ members: readonly BotGroupMemberView[];+ identityFor: BotGroupIdentityLookup;+ deviceId: string;+ online: boolean;+ running: boolean;+ planState: BotGroupComposerPlanState | null;+ /** Rejects with the host's error; the draft (and its tag) come back. */+ onSend(input: BotGroupSendInput): Promise<void>;+ onStop(): Promise<void>;+}) {+ const { t } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const [text, setText] = useState('');+ const [caret, setCaret] = useState(0);+ const [forcedSelection, setForcedSelection] = useState<{ start: number; end: number } | undefined>(undefined);+ const [focused, setFocused] = useState(false);+ const [tracked, setTracked] = useState<BotGroupTrackedMention[]>([]);+ const [division, setDivision] = useState(false);+ const [sending, setSending] = useState(false);+ const [stopping, setStopping] = useState(false);+ const inputRef = useRef<NativeTextInput>(null);+ const textRef = useRef(text); textRef.current = text;+ const sendingRef = useRef(false);+ const stoppingRef = useRef(false);+ const attemptRef = useRef<BotGroupSendAttempt | null>(null);++ const activeMembers = useMemo(() => members.filter(isActiveBotGroupMember), [members]);+ const allLabel = t('groupChat.mention.all');+ const query = focused ? findBotGroupMentionQuery(text, caret) : null;+ const options = useMemo<MentionOption[]>(() => {+ if (!query || activeMembers.length === 0) return [];+ const everyone: MentionOption[] = filterBotGroupMentionCandidates(query.query, [{ name: allLabel }]).length > 0+ ? [{ kind: 'all', label: allLabel }]+ : [];+ const people = filterBotGroupMentionCandidates(query.query, activeMembers)+ .map((member): MentionOption => ({ kind: 'member', label: member.name, member }));+ return [...everyone, ...people];+ }, [activeMembers, allLabel, query]);+ const pickerOpen = query !== null && options.length > 0;++ const trimmed = text.trim();+ const tooLong = trimmed.length > BOT_GROUP_MESSAGE_MAX_CHARS;+ const hasMembers = activeMembers.length > 0;+ const canSend = online && trimmed.length > 0 && !tooLong && hasMembers;+ const showStop = running && trimmed.length === 0;+ const divisionBlocked = isBotGroupDivisionBlocked(planState);++ const choose = (option: MentionOption) => {+ if (!query) return;+ const next = insertBotGroupMention(text, { start: query.start, end: caret }, option.label);+ setText(next.text);+ setCaret(next.caret);+ setForcedSelection({ start: next.caret, end: next.caret });+ if (option.kind === 'member') {+ setTracked((current) => [+ ...current.filter((mention) => mention.botId !== option.member.botId),+ { botId: option.member.botId, label: option.label },+ ]);+ }+ inputRef.current?.focus();+ };++ const send = async () => {+ if (!canSend || sendingRef.current) return;+ // The tag changes what the host does with the text, so it is part of the idempotency key.+ const attempt = nextBotGroupSendAttempt(attemptRef.current, trimmed, division, randomUUID);+ attemptRef.current = attempt;+ const mentions = resolveBotGroupMentions(trimmed, {+ members: members.map((member) => ({ botId: member.botId, name: member.name })),+ allLabels: [allLabel],+ tracked,+ });+ const draft = text;+ const draftTracked = tracked;+ sendingRef.current = true;+ setSending(true);+ // Clear at once like any chat; a failed send puts the draft back if nothing new was typed.+ setText('');+ setCaret(0);+ setTracked([]);+ setDivision(false);+ try {+ await onSend({ text: attempt.text, mentions, clientId: attempt.clientId, division: attempt.division });+ attemptRef.current = null;+ } catch {+ if (!textRef.current) {+ setText(draft);+ setTracked(draftTracked);+ // The tag comes back only with its own draft, never onto newly typed text.+ if (attempt.division) setDivision(true);+ }+ } finally {+ sendingRef.current = false;+ setSending(false);+ }+ };++ const stop = async () => {+ if (stoppingRef.current) return;+ stoppingRef.current = true;+ setStopping(true);+ try { await onStop(); } catch { /* the screen reports the failure */ } finally {+ stoppingRef.current = false;+ setStopping(false);+ }+ };++ const hint = !hasMembers+ ? t('groupChat.composer.noMembers')+ : tooLong ? t('groupChat.composer.tooLong', { max: BOT_GROUP_MESSAGE_MAX_CHARS }) : null;+ const placeholder = !hasMembers+ ? t('groupChat.composer.noMembers')+ : division+ ? t('groupChat.composer.placeholderDivision')+ : planState?.kind === 'proposed'+ ? t('groupChat.composer.placeholderPlanProposed')+ : planState?.kind === 'running' && planState.botName+ ? t('groupChat.composer.placeholderPlanRunning', { name: planState.botName })+ : planState?.kind === 'waiting' && planState.stepDone && planState.botName+ ? t('groupChat.composer.placeholderPlanWaiting', { name: planState.botName })+ : t('groupChat.composer.placeholder');++ const moreLabel = t('groupChat.composer.more');+ const plusButton = (onPress: (() => void) | undefined) => <Pressable accessibilityRole="button" accessibilityLabel={moreLabel}+ hitSlop={CONTROL_HIT_SLOP} disabled={!online} onPress={onPress}+ style={({ pressed }) => [styles.control, styles.plus, pressed && mobileInteractionStyles.pressed, !online && styles.disabled]}+ testID="botGroup.composer.more">+ <Plus size={iconSize.sm} color={colors.textSecondary} strokeWidth={iconStroke.regular} />+ </Pressable>;+ const leading = divisionBlocked+ // Nothing to pick while a plan runs or waits; say why instead of showing a dead menu.+ ? plusButton(() => Alert.alert(t('groupChat.composer.division'), t('groupChat.composer.divisionBusy')))+ : <BotGroupMenu title={moreLabel} accessibilityLabel={moreLabel} disabled={!online} testID="botGroup.composer.menu"+ sections={[{ id: 'more', options: [{ id: 'division', title: t('groupChat.composer.division'), subtitle: t('groupChat.composer.divisionDescription') }] }]}+ onSelect={(id) => { if (id === 'division') { setDivision(true); inputRef.current?.focus(); } }}>+ {(open) => plusButton(open)}+ </BotGroupMenu>;++ const actionDisabled = showStop ? stopping : !canSend || sending;+ const trailing = <Pressable accessibilityRole="button"+ accessibilityLabel={showStop ? t('groupChat.composer.stop') : t('groupChat.composer.send')}+ accessibilityState={{ disabled: actionDisabled, busy: sending || stopping || undefined }}+ disabled={actionDisabled} hitSlop={CONTROL_HIT_SLOP} onPress={() => void (showStop ? stop() : send())}+ style={({ pressed }) => [styles.control, styles.send, actionDisabled && styles.sendInactive, pressed && mobileInteractionStyles.pressed]}+ testID={showStop ? 'botGroup.composer.stop' : 'botGroup.composer.send'}>+ {showStop+ ? <Square size={iconSize.xs} color={actionDisabled ? colors.textSecondary : colors.ctaText}+ fill={actionDisabled ? colors.textSecondary : colors.ctaText} strokeWidth={iconStroke.thin} />+ : <PaperPlaneIcon color={actionDisabled ? colors.textSecondary : colors.ctaText} size={iconSize.lg} />}+ </Pressable>;++ return <View style={styles.wrap} testID="botGroup.composer">+ {pickerOpen && query ? <View style={styles.picker} accessibilityLabel={t('groupChat.mention.label')} testID="botGroup.mentionPicker">+ <ScrollView keyboardShouldPersistTaps="always" style={styles.pickerScroll}>+ {options.map((option) => <Pressable key={option.kind === 'all' ? 'all' : option.member.botId} accessibilityRole="button"+ accessibilityLabel={option.label} onPress={() => choose(option)}+ style={({ pressed }) => [styles.pickerRow, pressed && mobileInteractionStyles.pressed]}+ testID={`botGroup.mention.${option.kind === 'all' ? 'all' : option.member.botId}`}>+ {option.kind === 'all'+ ? <View style={styles.everyone}><Users size={iconSize.sm} color={colors.textSecondary} /></View>+ : <BotGroupAvatar deviceId={deviceId} identity={identityFor(option.member.botId, option.member.name)} size={BOT_GROUP_STEP_AVATAR_SIZE} online={online} />}+ <Text numberOfLines={1} style={styles.pickerName}>{option.label}</Text>+ {option.kind === 'all' ? <Text numberOfLines={1} style={styles.pickerHint}>{t('groupChat.mention.allHint')}</Text> : null}+ </Pressable>)}+ </ScrollView>+ </View> : null}+ {hint ? <Text accessibilityLiveRegion="polite" style={styles.hint}>{hint}</Text> : null}+ {division ? <View style={styles.tagRow}>+ <View style={styles.tag} testID="botGroup.divisionTag">+ <Users size={iconSize.xs} color={colors.textSecondary} />+ <Text style={styles.tagText}>{t('groupChat.composer.divisionTag')}</Text>+ <Pressable accessibilityRole="button" accessibilityLabel={t('groupChat.composer.removeDivision')} hitSlop={TAG_HIT_SLOP}+ onPress={() => setDivision(false)} testID="botGroup.divisionTag.remove">+ <X size={iconSize.xs} color={colors.textTertiary} />+ </Pressable>+ </View>+ </View> : null}+ <MobileComposerInputRow+ accessibilityLabel={t('groupChat.composer.label')}+ inputRef={inputRef}+ inputTestID="botGroup.composer.input"+ value={text}+ editable={online && hasMembers}+ placeholder={placeholder}+ placeholderTextColor={colors.textPlaceholder}+ cursorColor={colors.inputCaret}+ selectionColor={colors.inputCaret}+ selection={forcedSelection}+ onChangeText={setText}+ onSelectionChange={(event) => {+ setForcedSelection(undefined);+ setCaret(event.nativeEvent.selection.end);+ }}+ onFocus={() => setFocused(true)}+ onBlur={() => setFocused(false)}+ onKeyPress={(event) => {+ // Backspace in an empty input takes the 「分工」 tag off (Desktop behavior).+ if (event.nativeEvent.key === 'Backspace' && division && !textRef.current) setDivision(false);+ }}+ leading={leading}+ trailing={trailing}+ testID="botGroup.composer.row"+ />+ </View>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ wrap: { gap: spacing.sm, paddingHorizontal: spacing.lg, paddingTop: spacing.sm, paddingBottom: spacing.sm },+ control: { width: CONTROL_SIZE, height: CONTROL_SIZE, borderRadius: radius.pill, alignItems: 'center', justifyContent: 'center',+ borderWidth: StyleSheet.hairlineWidth },+ plus: { backgroundColor: colors.sheetActionSurface, borderColor: colors.sheetActionBorder },+ send: { backgroundColor: colors.cta, borderColor: colors.cta },+ sendInactive: { backgroundColor: colors.surfaceChip, borderColor: colors.border },+ disabled: { opacity: 0.46 },+ hint: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, paddingHorizontal: spacing.xs },+ tagRow: { flexDirection: 'row' },+ tag: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs, minHeight: 28, paddingLeft: spacing.sm, paddingRight: spacing.sm,+ borderRadius: radius.pill, backgroundColor: colors.surfaceChip },+ tagText: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },+ picker: { backgroundColor: colors.surfaceElevated, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,+ borderRadius: radius.container, paddingVertical: spacing.xs, overflow: 'hidden' },+ pickerScroll: { maxHeight: PICKER_MAX_HEIGHT },+ pickerRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, minHeight: 44, paddingHorizontal: spacing.md },+ everyone: { width: BOT_GROUP_STEP_AVATAR_SIZE, height: BOT_GROUP_STEP_AVATAR_SIZE, borderRadius: radius.pill,+ alignItems: 'center', justifyContent: 'center', backgroundColor: colors.surfaceChip },+ pickerName: { flex: 1, minWidth: 0, color: colors.textPrimary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.medium },+ pickerHint: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },+});diff --git a/apps/mobile/src/session/BotGroupCreateSheet.tsx b/apps/mobile/src/session/BotGroupCreateSheet.tsxnew file mode 100644index 0000000000..48d9f53f49--- /dev/null+++ b/apps/mobile/src/session/BotGroupCreateSheet.tsx@@ -0,0 +1,197 @@+/**+ * 新建群聊(对照桌面 BotGroupCreateDialog.tsx):填群名称,选 2–6 位伙伴。群建在一台电脑上,+ * 只能选这台电脑上的伙伴;多台电脑时先在「+」的菜单里选电脑。成员顺序即发言顺序,跟随+ * 列表顺序而不是点选先后(与桌面一致)。群名长度与人数由电脑最终校验,这里先挡住明显不+ * 成立的提交。建好后电脑回一个跳转,页面打开新群。+ */+import { useEffect, useRef, useState } from 'react';+import { ActivityIndicator, Alert, Pressable, StyleSheet, View } from 'react-native';+import { Check } from 'lucide-react-native';+import { useTranslation } from 'react-i18next';+import { resolveRemoteText } from '@cindy/device-link';+import {+ BOT_GROUP_MAX_MEMBERS,+ BOT_GROUP_MIN_MEMBERS,+ BOT_GROUP_NAME_MAX_CHARS,+ BOT_GROUP_REMOTE_COLLECTION_ID,+} from '@cindy/maker-shared/botGroupChat';+import { useAuth } from '@/auth/AuthContext';+import { Text, TextInput } from '@/components/AppText';+import { MainWindowActionButton } from '@/components/MobilePrimitives';+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';+import { useDeviceLink } from '@/device-link/DeviceLinkContext';+import { invokeRemoteResourceAction, type RemoteResourceHostTarget } from '@/device-link/remoteResources';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';+import { BOT_GROUP_ROW_AVATAR_SIZE, BotGroupAvatar } from './BotGroupAvatars';+import { botGroupActionErrorText } from './botGroupCopy';+import { createdBotGroupId } from './botGroupRemote';+import { CompanionSheet } from './CompanionSheet';+import { orderedTeammates } from './teammateNavigation';+import { useHostTeammates } from './useHostTeammates';++export function BotGroupCreateSheet(props: {+ visible: boolean;+ host: RemoteResourceHostTarget | null;+ online: boolean;+ onClose(): void;+ onClosed?(): void;+ /** The new group; the caller opens it after the sheet has closed. */+ onCreated(groupId: string): void;+}) {+ const { accountGeneration } = useAuth();+ // A new computer or account starts an empty form.+ return <CreateSheetContent key={`${accountGeneration}:${props.host?.deviceId ?? ''}`} {...props} />;+}++function CreateSheetContent({ visible, host, online, onClose, onClosed, onCreated }: Parameters<typeof BotGroupCreateSheet>[0]) {+ const { t, i18n } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const { invoke, openLink } = useDeviceLink();+ const teammates = useHostTeammates(host, visible);+ const [name, setName] = useState('');+ const [selected, setSelected] = useState<string[]>([]);+ const [nameError, setNameError] = useState(false);+ const [membersError, setMembersError] = useState(false);+ const [submitError, setSubmitError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const busyRef = useRef(false);+ const mounted = useRef(true);+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);+ useEffect(() => {+ if (!visible) return;+ setName(''); setSelected([]); setNameError(false); setMembersError(false); setSubmitError(null);+ }, [visible]);++ const candidates = orderedTeammates(teammates.rows, '', i18n.language);+ // Speaking order follows the list order, not the tap order.+ const ordered = candidates.map((row) => row.item.ref.id).filter((botId) => selected.includes(botId));+ const atLimit = ordered.length >= BOT_GROUP_MAX_MEMBERS;+ const dirty = !!name.trim() || selected.length > 0;++ const toggle = (botId: string) => {+ setSubmitError(null);+ setMembersError(false);+ setSelected((current) => current.includes(botId)+ ? current.filter((id) => id !== botId)+ : current.length >= BOT_GROUP_MAX_MEMBERS ? current : [...current, botId]);+ };++ const close = () => {+ if (busyRef.current) return;+ if (!dirty) { onClose(); return; }+ Alert.alert(t('devices.companions.automation.unsavedTitle'), t('devices.companions.automation.unsavedBody'), [+ { text: t('devices.common.cancel'), style: 'cancel' },+ { text: t('devices.companions.automation.discard'), style: 'destructive', onPress: () => { if (!busyRef.current) onClose(); } },+ ]);+ };++ const submit = async () => {+ if (busyRef.current || !host) return;+ const trimmed = name.trim();+ const nameInvalid = trimmed.length === 0;+ const membersInvalid = ordered.length < BOT_GROUP_MIN_MEMBERS || ordered.length > BOT_GROUP_MAX_MEMBERS;+ setNameError(nameInvalid);+ setMembersError(membersInvalid);+ if (nameInvalid || membersInvalid) return;+ busyRef.current = true;+ setBusy(true);+ setSubmitError(null);+ try {+ await openLink(host.deviceId);+ const response = await invokeRemoteResourceAction(invoke, host, {+ collectionId: BOT_GROUP_REMOTE_COLLECTION_ID,+ actionId: 'create',+ input: { name: trimmed, botIds: ordered },+ }, i18n.language);+ if (!mounted.current) return;+ const groupId = createdBotGroupId(response.effects);+ if (!groupId) throw new Error('Creation receipt missing');+ onCreated(groupId);+ onClose();+ } catch (error) {+ if (mounted.current) setSubmitError(botGroupActionErrorText(t, error, 'groupChat.create.failed'));+ } finally {+ busyRef.current = false;+ if (mounted.current) setBusy(false);+ }+ };++ const notEnough = !teammates.loading && candidates.length < BOT_GROUP_MIN_MEMBERS;+ return <CompanionSheet visible={visible} title={t('groupChat.create.title')} onClose={close} onClosed={onClosed}+ preventDismiss={dirty || busy} testID="botGroup.create">+ <View style={styles.content}>+ <Text style={styles.description}>{t('groupChat.create.description')}</Text>+ {host ? <Text style={styles.note}>{t('groupChat.create.computerNote', { deviceName: host.deviceName })}</Text> : null}+ {!online ? <Text accessibilityRole="alert" style={styles.note}>{t('devices.resources.hostOffline')}</Text> : null}+ <View style={styles.field}>+ <Text style={styles.label}>{t('groupChat.create.nameLabel')}</Text>+ <TextInput accessibilityLabel={t('groupChat.create.nameLabel')} value={name} maxLength={BOT_GROUP_NAME_MAX_CHARS}+ editable={!busy} placeholder={t('groupChat.create.namePlaceholder')} placeholderTextColor={colors.textPlaceholder}+ onChangeText={(value) => { setName(value); if (value.trim()) setNameError(false); setSubmitError(null); }}+ style={styles.input} testID="botGroup.create.name" />+ {nameError ? <Text accessibilityRole="alert" style={styles.error}>{t('groupChat.create.nameRequired')}</Text> : null}+ </View>+ <View style={styles.field}>+ <View style={styles.labelRow}>+ <Text style={[styles.label, styles.flex]}>{t('groupChat.create.membersLabel')}</Text>+ <Text style={styles.count}>{t('groupChat.create.selectedCount', { count: ordered.length, max: BOT_GROUP_MAX_MEMBERS })}</Text>+ </View>+ {candidates.length > 0 ? <View style={styles.group}>+ {candidates.map((row, index) => {+ const title = resolveRemoteText(row.item.display.title, i18n.language);+ const checked = selected.includes(row.item.ref.id);+ const disabled = busy || (!checked && atLimit);+ return <Pressable key={row.key} accessibilityRole="checkbox" accessibilityLabel={title}+ accessibilityState={{ checked, disabled }} disabled={disabled} onPress={() => toggle(row.item.ref.id)}+ style={({ pressed }) => [styles.row, index === candidates.length - 1 && styles.lastRow, pressed && mobileInteractionStyles.pressed, disabled && !checked && styles.inactive]}+ testID={`botGroup.create.member.${row.item.ref.id}`}>+ <BotGroupAvatar deviceId={row.host.deviceId} identity={{ botId: row.item.ref.id, name: title, avatar: row.item.display.avatar }}+ size={BOT_GROUP_ROW_AVATAR_SIZE} online={online} />+ <Text numberOfLines={1} style={[styles.rowTitle, styles.flex]}>{title}</Text>+ <View style={[styles.check, checked && styles.checked]}>+ {checked ? <Check size={iconSize.xs} color={colors.ctaText} strokeWidth={iconStroke.bold} /> : null}+ </View>+ </Pressable>;+ })}+ </View> : null}+ {teammates.loading && candidates.length === 0 ? <ActivityIndicator color={colors.textSecondary} style={styles.spinner} /> : null}+ {notEnough ? <Text style={styles.note}>{t(teammates.failed ? 'devices.resources.loadFailed' : 'groupChat.create.notEnoughBots', { min: BOT_GROUP_MIN_MEMBERS })}</Text> : null}+ {membersError ? <Text accessibilityRole="alert" style={styles.error}>{t('groupChat.create.minMembers', { min: BOT_GROUP_MIN_MEMBERS })}</Text> : null}+ </View>+ {submitError ? <Text accessibilityRole="alert" style={styles.error} testID="botGroup.create.error">{submitError}</Text> : null}+ <View style={styles.actions}>+ <MainWindowActionButton action={{ label: t('devices.common.cancel'), disabled: busy, onPress: close, testID: 'botGroup.create.cancel' }} />+ <MainWindowActionButton action={{ label: t('groupChat.create.submit'), tone: 'primary', busy, disabled: !online || !host,+ onPress: () => void submit(), testID: 'botGroup.create.submit' }} />+ </View>+ </View>+ </CompanionSheet>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ content: { gap: spacing.lg, paddingTop: spacing.sm, paddingBottom: spacing.xl },+ description: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ note: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ error: { color: colors.errorText, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ field: { gap: spacing.sm },+ labelRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },+ label: { color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium },+ count: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontVariant: ['tabular-nums'] },+ flex: { flex: 1 },+ input: { minHeight: 44, borderRadius: radius.pill, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,+ paddingHorizontal: spacing.lg, color: colors.textPrimary, backgroundColor: colors.surfaceElevated, fontSize: typeScale.body },+ group: { backgroundColor: colors.surfaceElevated, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,+ borderRadius: radius.container, overflow: 'hidden' },+ row: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, minHeight: 52, paddingHorizontal: spacing.md,+ borderBottomColor: colors.border, borderBottomWidth: StyleSheet.hairlineWidth },+ lastRow: { borderBottomWidth: 0 },+ rowTitle: { color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium },+ inactive: { opacity: 0.6 },+ check: { width: iconSize.action, height: iconSize.action, borderRadius: radius.pill, borderWidth: 1, borderColor: colors.borderStrong,+ alignItems: 'center', justifyContent: 'center' },+ checked: { backgroundColor: colors.cta, borderColor: colors.cta },+ spinner: { paddingVertical: spacing.md },+ actions: { flexDirection: 'row', justifyContent: 'flex-end', gap: spacing.sm },+});diff --git a/apps/mobile/src/session/BotGroupList.tsx b/apps/mobile/src/session/BotGroupList.tsxnew file mode 100644index 0000000000..83702f8ee3--- /dev/null+++ b/apps/mobile/src/session/BotGroupList.tsx@@ -0,0 +1,153 @@+/**+ * 伙伴页里的「群聊」分组(对照桌面 BotGroupSidebarSection.tsx):小节头带新建按钮,下面是+ * 群行。群行与伙伴行同一套行几何:两位成员斜向叠放的头像,第一行群名与时间,第二行是电脑+ * 给的预览(安排状态或最近一条消息,已按语言给好);有伙伴正在说话、安排或做事时,预览前+ * 加运行中标记。只在至少一台电脑支持群聊时出现(旧版桌面没有这个集合)。+ */+import { useRef, useState } from 'react';+import { Pressable, StyleSheet, View } from 'react-native';+import { Plus, Sparkles } from 'lucide-react-native';+import { useTranslation } from 'react-i18next';+import { resolveRemoteText } from '@cindy/device-link';+import { Text } from '@/components/AppText';+import { useAuth } from '@/auth/AuthContext';+import type { HostedRemoteCollectionItem, RemoteResourceHostTarget } from '@/device-link/remoteResources';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';+import { useMinuteNow } from '@/utils/useMinuteNow';+import { BotGroupDuoAvatar, useBotGroupIdentities } from './BotGroupAvatars';+import { BotGroupCreateSheet } from './BotGroupCreateSheet';+import { BotGroupMenu } from './BotGroupMenu';+import { botGroupMemberLinks, orderedBotGroups } from './botGroupRemote';+import { parseMobileMarkdownInlines } from './messageMarkdown';+import { formatRemoteSessionSidebarTime } from './sessionList';++const CREATE_HIT_SLOP = { top: 8, bottom: 8, left: 8, right: 8 } as const;++export function BotGroupSection({ items, query, isOnline, createTargets, preferredDeviceId, onOpen, onOpenCreated, onInteract }: {+ items: readonly HostedRemoteCollectionItem[];+ query: string;+ isOnline(host: RemoteResourceHostTarget): boolean;+ /** Online computers that support group chats. */+ createTargets: readonly RemoteResourceHostTarget[];+ preferredDeviceId?: string;+ onOpen(row: HostedRemoteCollectionItem): void;+ onOpenCreated(host: RemoteResourceHostTarget, groupId: string): void;+ onInteract?(): void;+}) {+ const { t, i18n } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ const rows = orderedBotGroups(items, query, i18n.language);+ if (query.trim() && rows.length === 0) return null;+ return <View style={styles.section} testID="botGroups.section">+ <View style={styles.header}>+ <Text accessibilityRole="header" style={styles.sectionTitle}>{t('groupChat.title')}</Text>+ <BotGroupCreateButton targets={createTargets} preferredDeviceId={preferredDeviceId} onInteract={onInteract} onCreated={onOpenCreated} />+ </View>+ {rows.length === 0 ? <Text style={styles.empty} testID="botGroups.empty">{t('groupChat.list.empty')}</Text> : null}+ {rows.map((row) => <BotGroupRow key={row.key} row={row} online={isOnline(row.host)} onPress={() => onOpen(row)} />)}+ </View>;+}++function BotGroupRow({ row, online, onPress }: { row: HostedRemoteCollectionItem; online: boolean; onPress(): void }) {+ const { t, i18n } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const now = useMinuteNow();+ const identityFor = useBotGroupIdentities(row.host.deviceId);+ const display = row.item.display;+ const title = resolveRemoteText(display.title, i18n.language);+ const preview = display.preview ? parseMobileMarkdownInlines(resolveRemoteText(display.preview, i18n.language))+ .map((inline) => inline.type === 'image' ? inline.alt : inline.text).join('').replace(/\s+/g, ' ').trim() : '';+ const summary = preview || t('groupChat.list.noMessages');+ const running = online && !!display.generation;+ const members = botGroupMemberLinks(row.item, i18n.language).map((member) => identityFor(member.botId, member.label));+ const time = display.timestamp !== undefined && Number.isFinite(new Date(display.timestamp).getTime())+ ? formatRemoteSessionSidebarTime(new Date(display.timestamp).toISOString(), now) : '';+ const offline = online ? '' : t('devices.resources.hostOffline');+ return <Pressable accessibilityRole="button" accessibilityState={{ disabled: !online }}+ accessibilityLabel={[title, running ? t('groupChat.list.running') : '', summary, time, offline].filter(Boolean).join(', ')}+ disabled={!online} onPress={onPress} style={({ pressed }) => [styles.row, pressed && styles.pressed]}+ testID={`botGroups.item.${row.host.deviceId}.${row.item.ref.id}`}>+ <BotGroupDuoAvatar deviceId={row.host.deviceId} members={members} online={online} />+ <View style={styles.body}>+ <View style={styles.titleRow}>+ <Text numberOfLines={1} style={styles.title}>{title}</Text>+ {time ? <Text numberOfLines={1} style={styles.time}>{time}</Text> : null}+ </View>+ <View style={styles.previewRow}>+ {running ? <Sparkles size={iconSize.xs} color={colors.statusAccent} testID="botGroups.running" /> : null}+ <Text numberOfLines={1} style={styles.preview}>{summary}</Text>+ </View>+ {offline ? <Text numberOfLines={1} style={styles.meta}>{offline}</Text> : null}+ </View>+ </Pressable>;+}++/** 「+」 in the section header; with several computers it first asks which one hosts the group. */+function BotGroupCreateButton({ targets, preferredDeviceId, onInteract, onCreated }: {+ targets: readonly RemoteResourceHostTarget[];+ preferredDeviceId?: string;+ onInteract?(): void;+ onCreated(host: RemoteResourceHostTarget, groupId: string): void;+}) {+ const { t } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const { accountGeneration } = useAuth();+ const [host, setHost] = useState<RemoteResourceHostTarget | null>(null);+ const [visible, setVisible] = useState(false);+ const receipt = useRef<{ host: RemoteResourceHostTarget; groupId: string; account: number } | null>(null);+ const ordered = [...targets].sort((a, b) => Number(b.deviceId === preferredDeviceId) - Number(a.deviceId === preferredDeviceId));+ const open = (deviceId: string) => {+ onInteract?.();+ const target = targets.find((candidate) => candidate.deviceId === deviceId);+ if (!target) return;+ setHost(target);+ setVisible(true);+ };+ const label = t('groupChat.create.title');+ const button = (onPress: (() => void) | undefined) => <Pressable accessibilityRole="button" accessibilityLabel={label}+ disabled={targets.length === 0} hitSlop={CREATE_HIT_SLOP} onPress={onPress}+ style={({ pressed }) => [styles.create, pressed && styles.pressed, targets.length === 0 && styles.disabled]}+ testID="botGroups.create">+ <Plus size={iconSize.md} color={colors.textSecondary} strokeWidth={iconStroke.regular} />+ </Pressable>;+ return <>+ {targets.length > 1+ ? <BotGroupMenu title={t('groupChat.create.chooseComputer')} accessibilityLabel={label} testID="botGroups.createMenu"+ sections={[{ id: 'computers', title: t('groupChat.create.chooseComputer'), options: ordered.map((target) => ({ id: target.deviceId, title: target.deviceName })) }]}+ onSelect={open}>+ {button}+ </BotGroupMenu>+ : button(targets[0] ? () => open(targets[0]!.deviceId) : undefined)}+ <BotGroupCreateSheet visible={visible} host={host} online={!!host && targets.some((target) => target.deviceId === host.deviceId)}+ onClose={() => setVisible(false)}+ onCreated={(groupId) => { if (host) receipt.current = { host, groupId, account: accountGeneration }; }}+ onClosed={() => {+ const created = receipt.current;+ receipt.current = null;+ if (created && created.account === accountGeneration) onCreated(created.host, created.groupId);+ }} />+ </>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ section: { paddingTop: spacing.lg },+ header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: spacing.lg, minHeight: 44 },+ sectionTitle: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.semibold },+ create: { width: 32, height: 32, borderRadius: radius.pill, alignItems: 'center', justifyContent: 'center' },+ disabled: { opacity: 0.46 },+ empty: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, paddingHorizontal: spacing.lg, paddingBottom: spacing.md },+ // Teammate row geometry (TeammateList): the divider sits on the text column's bottom edge.+ row: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, paddingHorizontal: spacing.lg, minHeight: 78 },+ pressed: { opacity: 0.72 },+ body: { flex: 1, minWidth: 0, alignSelf: 'stretch', justifyContent: 'center', gap: spacing.xs,+ borderBottomColor: colors.border, borderBottomWidth: StyleSheet.hairlineWidth, paddingVertical: 18 },+ titleRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },+ title: { flex: 1, color: colors.textPrimary, fontSize: typeScale.subtitle, fontWeight: fontWeight.medium, lineHeight: lineHeight.listTitle },+ previewRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },+ preview: { flex: 1, color: colors.textSecondary, fontSize: typeScale.bodySmall, fontWeight: fontWeight.regular, lineHeight: lineHeight.subtitle },+ time: { color: colors.textTertiary, fontSize: typeScale.footnote, fontWeight: fontWeight.regular, lineHeight: lineHeight.body },+ meta: { color: colors.textTertiary, fontSize: typeScale.footnote, fontWeight: fontWeight.regular, lineHeight: lineHeight.body },+});diff --git a/apps/mobile/src/session/BotGroupMenu.tsx b/apps/mobile/src/session/BotGroupMenu.tsxnew file mode 100644index 0000000000..c9cd65f3b5--- /dev/null+++ b/apps/mobile/src/session/BotGroupMenu.tsx@@ -0,0 +1,101 @@+/**+ * 群聊里贴着控件弹出的小菜单(步骤换人、输入框「+」、选电脑)。iOS 用系统 UIMenu、+ * Android 用 Cindy 自绘的 AnchoredPullDownMenu(都经 NativePullDownMenu);iOS 包里还没有+ * MenuView 时退回同样选项的底部面板,等面板收起后再执行选中的项,避免两层遮罩叠在一起。+ */+import { useRef, useState, type ReactElement } from 'react';+import { StyleSheet, View } from 'react-native';+import { Check } from 'lucide-react-native';+import { Text } from '@/components/AppText';+import { MainWindowRowButton } from '@/components/MobilePrimitives';+import { NativePullDownMenu, usesNativePullDownMenu, type NativePullDownAction } from '@/platform/chrome/NativePullDownMenu';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, iconSize, lineHeight, spacing, typeScale } from '@/theme/tokens';+import { CompanionSheet } from './CompanionSheet';++export interface BotGroupMenuOption {+ id: string;+ title: string;+ subtitle?: string;+ disabled?: boolean;+ destructive?: boolean;+ selected?: boolean;+}++export interface BotGroupMenuSection {+ id: string;+ title?: string;+ options: readonly BotGroupMenuOption[];+}++function toAction(option: BotGroupMenuOption): NativePullDownAction {+ return {+ id: option.id,+ title: option.title,+ ...(option.subtitle ? { subtitle: option.subtitle } : {}),+ ...(option.disabled ? { disabled: true } : {}),+ ...(option.destructive ? { destructive: true } : {}),+ ...(option.selected ? { state: 'on' as const } : {}),+ };+}++export function botGroupMenuActions(sections: readonly BotGroupMenuSection[]): NativePullDownAction[] {+ return sections.flatMap((section): NativePullDownAction[] => section.title+ ? [{ id: `section:${section.id}`, title: section.title, displayInline: true, subactions: section.options.map(toAction) }]+ : section.options.map(toAction));+}++export function BotGroupMenu({ title, sections, onSelect, accessibilityLabel, disabled = false, testID, children }: {+ /** Fallback sheet title. */+ title: string;+ sections: readonly BotGroupMenuSection[];+ onSelect(id: string): void;+ accessibilityLabel?: string;+ disabled?: boolean;+ testID?: string;+ /** The trigger. `open` is set only when the fallback sheet has to be opened by the trigger itself. */+ children(open: (() => void) | undefined): ReactElement;+}) {+ const styles = useThemedStyles(makeStyles);+ const { colors } = useTheme();+ const [sheet, setSheet] = useState(false);+ const chosen = useRef<string | null>(null);+ const known = new Set(sections.flatMap((section) => section.options.filter((option) => !option.disabled).map((option) => option.id)));+ const select = (id: string) => { if (known.has(id)) onSelect(id); };+ if (usesNativePullDownMenu()) {+ return <NativePullDownMenu actions={botGroupMenuActions(sections)} onAction={select} disabled={disabled}+ accessibilityLabel={accessibilityLabel} testID={testID}>+ {children(undefined)}+ </NativePullDownMenu>;+ }+ return <>+ {children(disabled ? undefined : () => setSheet(true))}+ <CompanionSheet visible={sheet} title={title} onClose={() => { chosen.current = null; setSheet(false); }}+ onClosed={() => { const id = chosen.current; chosen.current = null; if (id) select(id); }} testID={testID ? `${testID}.sheet` : undefined}>+ <View style={styles.content}>+ {sections.map((section) => <View key={section.id} style={styles.section}>+ {section.title ? <Text style={styles.sectionTitle}>{section.title}</Text> : null}+ {section.options.map((option) => <MainWindowRowButton key={option.id} accessibilityLabel={option.title}+ accessibilityState={{ checked: option.selected }} disabled={option.disabled} selected={option.selected}+ onPress={() => { chosen.current = option.id; setSheet(false); }} style={styles.row} testID={testID ? `${testID}.option.${option.id}` : undefined}>+ <View style={styles.rowText}>+ <Text numberOfLines={1} style={[styles.title, option.destructive && { color: colors.destructive }]}>{option.title}</Text>+ {option.subtitle ? <Text style={styles.subtitle}>{option.subtitle}</Text> : null}+ </View>+ {option.selected ? <Check size={iconSize.md} color={colors.textSecondary} /> : null}+ </MainWindowRowButton>)}+ </View>)}+ </View>+ </CompanionSheet>+ </>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ content: { gap: spacing.lg, paddingTop: spacing.sm, paddingBottom: spacing.xl },+ section: { gap: spacing.xs },+ sectionTitle: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.semibold },+ row: { minHeight: 48, gap: spacing.md, paddingVertical: spacing.sm },+ rowText: { flex: 1, minWidth: 0, gap: spacing.xs },+ title: { color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium },+ subtitle: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+});diff --git a/apps/mobile/src/session/BotGroupMessageText.tsx b/apps/mobile/src/session/BotGroupMessageText.tsxnew file mode 100644index 0000000000..39f59f94bd--- /dev/null+++ b/apps/mobile/src/session/BotGroupMessageText.tsx@@ -0,0 +1,100 @@+/**+ * 群聊消息正文。伙伴的回复是 Markdown:这里只做轻量排版(段落、标题、引用、列表、代码块、+ * 行内强调 / 代码),与伙伴私聊回看同样是只读文本,不加载任务页的完整消息渲染器;链接只+ * 显示文字,不在群聊里打开。用户自己的消息保留原文,`@名字` 画成点名标记。+ */+import { useMemo, type ReactNode } from 'react';+import { StyleSheet, View } from 'react-native';+import { splitBotGroupMentionSegments } from '@cindy/maker-shared/botGroupMentions';+import { Text } from '@/components/AppText';+import { fontWeight, monoFont, useThemedStyles, type ThemeColors } from '@/theme';+import { lineHeight, radius, spacing, typeScale } from '@/theme/tokens';+import { parseMobileMarkdown, type MobileMarkdownBlock, type MobileMarkdownInline } from './messageMarkdown';++type Styles = ReturnType<typeof makeStyles>;++function renderInlines(inlines: readonly MobileMarkdownInline[], styles: Styles): ReactNode[] {+ return inlines.map((inline, index) => {+ switch (inline.type) {+ case 'strong': return <Text key={index} style={styles.strong}>{inline.text}</Text>;+ case 'emphasis': return <Text key={index} style={styles.emphasis}>{inline.text}</Text>;+ case 'strikethrough': return <Text key={index} style={styles.strike}>{inline.text}</Text>;+ case 'code': return <Text key={index} style={styles.inlineCode}>{inline.text}</Text>;+ case 'link': return <Text key={index} style={styles.link}>{inline.text}</Text>;+ case 'image': return <Text key={index}>{inline.alt ? `[${inline.alt}]` : ''}</Text>;+ default: return <Text key={index}>{inline.text}</Text>;+ }+ });+}++function tableText(block: Extract<MobileMarkdownBlock, { type: 'table' }>): string {+ const cell = (inlines: readonly MobileMarkdownInline[]) => inlines.map((inline) => inline.type === 'image' ? inline.alt : inline.text).join('');+ return [block.header, ...block.rows.map((row) => row.cells)]+ .map((cells) => cells.map(cell).join(' | '))+ .join('\n');+}++function renderBlock(block: MobileMarkdownBlock, styles: Styles): ReactNode {+ switch (block.type) {+ case 'heading':+ return <Text key={block.key} selectable style={[styles.text, styles.heading]}>{renderInlines(block.inlines, styles)}</Text>;+ case 'blockquote':+ return <View key={block.key} style={styles.quote}>+ <Text selectable style={[styles.text, styles.quoteText]}>{renderInlines(block.inlines, styles)}</Text>+ </View>;+ case 'list_item':+ return <View key={block.key} style={styles.listItem}>+ <Text style={styles.text}>{block.checked === undefined ? (block.ordered ? block.marker : '•') : block.checked ? '☑' : '☐'}</Text>+ <Text selectable style={[styles.text, styles.listText]}>{renderInlines(block.inlines, styles)}</Text>+ </View>;+ case 'code':+ case 'mermaid':+ case 'math':+ return <View key={block.key} style={styles.codeBlock}>+ <Text selectable style={styles.codeText}>{block.text}</Text>+ </View>;+ case 'table':+ return <View key={block.key} style={styles.codeBlock}>+ <Text selectable style={styles.codeText}>{tableText(block)}</Text>+ </View>;+ default:+ return <Text key={block.key} selectable style={styles.text}>{renderInlines(block.inlines, styles)}</Text>;+ }+}++export function BotGroupMarkdownText({ content }: { content: string }) {+ const styles = useThemedStyles(makeStyles);+ const blocks = useMemo(() => parseMobileMarkdown(content), [content]);+ return <View style={styles.body}>{blocks.map((block) => renderBlock(block, styles))}</View>;+}++/** The user's own words: plain text with `@name` shown as a mention mark. */+export function BotGroupUserText({ content, mentionLabels }: { content: string; mentionLabels: readonly string[] }) {+ const styles = useThemedStyles(makeStyles);+ const segments = useMemo(() => splitBotGroupMentionSegments(content, mentionLabels), [content, mentionLabels]);+ return <Text selectable style={styles.text}>+ {segments.map((segment, index) => segment.mention+ ? <Text key={index} style={styles.mention}>{segment.text}</Text>+ : <Text key={index}>{segment.text}</Text>)}+ </Text>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ body: { gap: spacing.sm, minWidth: 0 },+ // Conversation message body (mobile guide §3): 17 / 26 regular.+ text: { color: colors.textPrimary, fontSize: typeScale.bodyLarge, lineHeight: lineHeight.bodyLarge },+ heading: { fontWeight: fontWeight.semibold },+ strong: { fontWeight: fontWeight.semibold },+ emphasis: { fontStyle: 'italic' },+ strike: { textDecorationLine: 'line-through' },+ link: { textDecorationLine: 'underline' },+ inlineCode: { fontFamily: monoFont, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodyLarge, backgroundColor: colors.surfaceChip },+ quote: { borderLeftWidth: 2, borderLeftColor: colors.border, paddingLeft: spacing.md },+ quoteText: { color: colors.textSecondary },+ listItem: { flexDirection: 'row', gap: spacing.sm },+ listText: { flex: 1, minWidth: 0 },+ codeBlock: { backgroundColor: colors.chatCodeSurface, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,+ borderRadius: radius.control, paddingHorizontal: spacing.md, paddingVertical: spacing.sm },+ codeText: { color: colors.textPrimary, fontFamily: monoFont, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall },+ mention: { fontWeight: fontWeight.medium, backgroundColor: colors.surfaceChip },+});diff --git a/apps/mobile/src/session/BotGroupPlan.tsx b/apps/mobile/src/session/BotGroupPlan.tsxnew file mode 100644index 0000000000..b8ccc15e94--- /dev/null+++ b/apps/mobile/src/session/BotGroupPlan.tsx@@ -0,0 +1,301 @@+/**+ * 群聊里的分工(docs/product-rules/bot-group-chat.md §7,对照桌面 BotGroupPlan.tsx):+ * 负责人的安排卡、交接消息下的文件、时间线末尾的「下一步 · 继续」「没做完 · 重试」与+ * 「N 步都做完了」。+ *+ * 安排卡一步一行(编号或状态、头像、名字 + 做什么),行间不画分隔线。只有群里未结束的+ * 那张卡能操作:待开始时点某一步换人或删掉,下面是小号「开始」「不用了」;做完一步停下时,+ * 还没做或没做完的步骤仍可换人。按钮是可见 38pt 的紧凑档,hitSlop 补到 44pt 热区。+ *+ * 交接文件在电脑的工作目录里,手机不打开,点一下说明去电脑上看。+ */+import type { ReactNode } from 'react';+import { Alert, Pressable, StyleSheet, View } from 'react-native';+import { CircleAlert, CircleCheck, CircleDashed, FileText, Sparkles } from 'lucide-react-native';+import { useTranslation } from 'react-i18next';+import { botGroupPathBasename, isActiveBotGroupMember, type BotGroupPlanFollowUp } from '@cindy/maker-shared/botGroupPresentation';+import type { BotGroupMemberView, BotGroupPlanStepView, BotGroupPlanView } from '@cindy/maker-shared/botGroupChat';+import { Text } from '@/components/AppText';+import { MainWindowActionButton } from '@/components/MobilePrimitives';+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, iconSize, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';+import {+ BOT_GROUP_INLINE_AVATAR_SIZE,+ BOT_GROUP_STEP_AVATAR_SIZE,+ BotGroupAvatar,+ type BotGroupIdentity,+} from './BotGroupAvatars';+import { BotGroupMenu, type BotGroupMenuSection } from './BotGroupMenu';++/** Compact actions are 38pt tall; this makes their touch target 44pt. */+export const BOT_GROUP_COMPACT_HIT_SLOP = { top: 4, bottom: 4, left: 4, right: 4 } as const;++export type BotGroupPlanCardAction = 'start' | 'dismiss' | 'edit';+export type BotGroupFollowUpAction = 'continue' | 'retry' | 'dismiss';+export type BotGroupIdentityLookup = (botId: string, fallbackName?: string) => BotGroupIdentity;++const REMOVE_STEP_ID = 'remove';++/** Small pill after the organizer's name (plan card and settings member rows). */+export function BotGroupOrganizerTag() {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ return <View style={styles.organizerBadge} testID="botGroup.organizerTag">+ <Text numberOfLines={1} style={styles.organizerBadgeText}>{t('groupChat.organizer')}</Text>+ </View>;+}++function started(plan: BotGroupPlanView): boolean {+ return plan.status !== 'proposed' && plan.status !== 'superseded' && plan.status !== 'dismissed';+}++/** 16pt leading mark: the step number before 开始, its live status afterwards. */+function StepLead({ plan, step, index }: { plan: BotGroupPlanView; step: BotGroupPlanStepView; index: number }) {+ const styles = useThemedStyles(makeStyles);+ const { colors } = useTheme();+ if (!started(plan)) return <Text style={styles.stepNumber}>{index + 1}</Text>;+ if (step.status === 'done') return <CircleCheck size={iconSize.md} color={colors.textSecondary} />;+ // Same running mark as the speaking row (Heart Orange).+ if (step.status === 'running') return <Sparkles size={iconSize.sm} color={colors.statusAccent} />;+ if (step.status === 'failed') return <CircleAlert size={iconSize.md} color={colors.errorText} />;+ return <CircleDashed size={iconSize.md} color={colors.textTertiary} />;+}++const STEP_STATUS_KEYS: Partial<Record<BotGroupPlanStepView['status'], string>> = {+ done: 'groupChat.plan.stepDone',+ running: 'groupChat.plan.stepRunning',+ failed: 'groupChat.plan.stepFailed',+};++function StepRowContent({ plan, step, index, identity, deviceId, online, muted }: {+ plan: BotGroupPlanView; step: BotGroupPlanStepView; index: number; identity: BotGroupIdentity;+ deviceId: string; online: boolean; muted: boolean;+}) {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ const statusKey = started(plan) ? STEP_STATUS_KEYS[step.status] : undefined;+ return <>+ <View style={styles.stepLead}><StepLead plan={plan} step={step} index={index} /></View>+ <View style={muted ? styles.muted : undefined}>+ <BotGroupAvatar deviceId={deviceId} identity={identity} size={BOT_GROUP_STEP_AVATAR_SIZE} online={online} />+ </View>+ <Text numberOfLines={1} style={[styles.stepText, muted && styles.stepTextMuted]}>+ <Text style={[styles.stepName, muted && styles.stepTextMuted]}>{identity.name}</Text>+ {' '}{step.task}+ </Text>+ {statusKey ? <Text numberOfLines={1} style={styles.stepStatus}>{t(statusKey)}</Text> : null}+ </>;+}++function stepAccessibility(t: (key: string, options?: Record<string, unknown>) => string, plan: BotGroupPlanView,+ step: BotGroupPlanStepView, index: number, name: string): string {+ const status = started(plan)+ ? t(STEP_STATUS_KEYS[step.status] ?? 'groupChat.plan.stepPending')+ : `${index + 1}`;+ return [status, name, step.task].filter(Boolean).join(', ');+}++/**+ * Body of the organizer's 安排卡 (the header is the usual Bot header plus the 负责人 tag).+ * `actionable` = the group's open plan, still waiting for 开始; `reassignable` = the open+ * plan stopped after a step (steps not done can change hands before 继续 / 重试).+ */+export function BotGroupPlanCard({+ plan, members, identityFor, deviceId, online, actionable, reassignable, pending, onStart, onDismiss, onEditStep,+}: {+ plan: BotGroupPlanView | undefined;+ members: readonly BotGroupMemberView[];+ identityFor: BotGroupIdentityLookup;+ deviceId: string;+ online: boolean;+ actionable: boolean;+ reassignable: boolean;+ pending: BotGroupPlanCardAction | null;+ onStart(): void;+ onDismiss(): void;+ onEditStep(step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string): void;+}) {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ if (!plan) return <Text style={styles.note}>{t('groupChat.plan.missing')}</Text>;+ const muted = plan.status === 'superseded' || plan.status === 'dismissed';+ const finalNote = plan.status === 'superseded' ? 'groupChat.plan.superseded'+ : plan.status === 'dismissed' ? 'groupChat.plan.dismissed'+ : plan.status === 'stopped' ? 'groupChat.plan.stopped' : null;+ const busy = pending !== null;+ const candidates = members.filter(isActiveBotGroupMember);+ return <View testID="botGroup.plan" style={styles.planColumn}>+ <Text selectable style={styles.planIntro}>{t('groupChat.plan.intro', { count: plan.steps.length })}</Text>+ <View style={styles.card} testID={`botGroup.plan.${plan.status}`}>+ {plan.steps.map((step, index) => {+ const identity = identityFor(step.botId, step.botName);+ const editable = online && (actionable || (reassignable && (step.status === 'pending' || step.status === 'failed')));+ const label = stepAccessibility(t, plan, step, index, identity.name);+ if (!editable) {+ return <View key={step.position} accessible accessibilityLabel={label} style={styles.stepRow} testID="botGroup.plan.step">+ <StepRowContent plan={plan} step={step} index={index} identity={identity} deviceId={deviceId} online={online} muted={muted} />+ </View>;+ }+ const sections: BotGroupMenuSection[] = [{+ id: 'members',+ title: t('groupChat.plan.stepMenuTitle'),+ options: candidates.map((member) => ({+ id: `member:${member.botId}`,+ title: identityFor(member.botId, member.name).name,+ selected: member.botId === step.botId,+ })),+ }];+ if (actionable) {+ sections.push({+ id: 'remove',+ options: [{+ id: REMOVE_STEP_ID,+ title: t('groupChat.plan.removeStep'),+ destructive: true,+ disabled: plan.steps.length <= 1,+ ...(plan.steps.length <= 1 ? { subtitle: t('groupChat.plan.keepOneStep') } : {}),+ }],+ });+ }+ return <BotGroupMenu key={step.position} title={t('groupChat.plan.stepMenuTitle')} sections={sections} disabled={busy}+ accessibilityLabel={label} testID={`botGroup.plan.stepMenu.${step.position}`}+ onSelect={(id) => {+ if (id === REMOVE_STEP_ID) onEditStep(step, 'remove');+ else if (id.startsWith('member:') && id.slice('member:'.length) !== step.botId) onEditStep(step, 'reassign', id.slice('member:'.length));+ }}>+ {(open) => <Pressable accessibilityRole="button" accessibilityLabel={label} disabled={busy}+ accessibilityHint={t(actionable ? 'groupChat.plan.editStepHint' : 'groupChat.plan.reassignStepHint')}+ accessibilityState={{ disabled: busy }} onPress={open}+ style={({ pressed }) => [styles.stepRow, pressed && mobileInteractionStyles.pressed, busy && styles.muted]}+ testID="botGroup.plan.step">+ <StepRowContent plan={plan} step={step} index={index} identity={identity} deviceId={deviceId} online={online} muted={false} />+ </Pressable>}+ </BotGroupMenu>;+ })}+ {actionable ? <View style={styles.actions}>+ <MainWindowActionButton density="compact" hitSlop={BOT_GROUP_COMPACT_HIT_SLOP}+ action={{ label: t('groupChat.plan.start'), tone: 'primary', busy: pending === 'start', disabled: busy || !online, onPress: onStart, testID: 'botGroup.plan.start' }} />+ <MainWindowActionButton density="compact" hitSlop={BOT_GROUP_COMPACT_HIT_SLOP}+ action={{ label: t('groupChat.plan.dismiss'), busy: pending === 'dismiss', disabled: busy || !online, onPress: onDismiss, testID: 'botGroup.plan.dismiss' }} />+ </View> : null}+ </View>+ {actionable ? <Text style={styles.note}>{t('groupChat.plan.pauseNote')}</Text>+ : finalNote ? <Text style={styles.note} testID="botGroup.plan.finalNote">{t(finalNote)}</Text> : null}+ </View>;+}++/** Files a step created or changed, under its hand-off message. They live on the computer. */+export function BotGroupHandoffFiles({ files }: { files: readonly string[] }) {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ const { colors } = useTheme();+ if (files.length === 0) return null;+ return <View style={styles.files} testID="botGroup.files">+ {files.map((file) => {+ const name = botGroupPathBasename(file);+ return <Pressable key={file} accessibilityRole="button" accessibilityLabel={name} accessibilityHint={t('groupChat.files.onComputer')}+ hitSlop={{ top: 6, bottom: 6 }}+ onPress={() => Alert.alert(file, t('groupChat.files.onComputer'))}+ style={({ pressed }) => [styles.fileChip, pressed && mobileInteractionStyles.pressed]} testID="botGroup.file">+ <FileText size={iconSize.sm} color={colors.textSecondary} />+ <Text numberOfLines={1} style={styles.fileName}>{name}</Text>+ </Pressable>;+ })}+ </View>;+}++export function BotGroupDivider({ children, testID }: { children: ReactNode; testID?: string }) {+ const styles = useThemedStyles(makeStyles);+ return <View style={styles.divider} testID={testID}>+ <View style={styles.dividerLine} />+ {children}+ <View style={styles.dividerLine} />+ </View>;+}++/** 「N 步都做完了」 — closes a finished plan in the timeline. */+export function BotGroupPlanEndDivider({ stepCount }: { stepCount: number | null }) {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ return <BotGroupDivider testID="botGroup.planEnd">+ <Text style={styles.dividerText}>+ {stepCount ? t('groupChat.timeline.planDone', { count: stepCount }) : t('groupChat.timeline.planDoneGeneric')}+ </Text>+ </BotGroupDivider>;+}++/** Under an open plan that stopped after a step: continue with the next one, or retry. */+export function BotGroupPlanFollowUpRow({ followUp, identityFor, deviceId, online, pending, onContinue, onRetry, onEnd }: {+ followUp: BotGroupPlanFollowUp;+ identityFor: BotGroupIdentityLookup;+ deviceId: string;+ online: boolean;+ pending: BotGroupFollowUpAction | null;+ onContinue(): void;+ onRetry(): void;+ onEnd(): void;+}) {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ const step = followUp.kind === 'continue' ? followUp.next : followUp.failed;+ const identity = identityFor(step.botId, step.botName);+ const busy = pending !== null;+ const primary = followUp.kind === 'continue' ? 'continue' : 'retry';+ const label = followUp.kind === 'continue'+ ? `${t('groupChat.timeline.nextStep')}${identity.name} ${step.task}`+ : t('groupChat.timeline.stepFailed', { name: identity.name });+ return <View style={styles.followUp} testID={`botGroup.followUpRow.${followUp.kind}`}>+ <View style={styles.followUpText} accessible accessibilityLabel={label}>+ {followUp.kind === 'continue' ? <>+ <Text style={styles.followUpLead}>{t('groupChat.timeline.nextStep')}</Text>+ <BotGroupAvatar deviceId={deviceId} identity={identity} size={BOT_GROUP_INLINE_AVATAR_SIZE} online={online} />+ <Text numberOfLines={1} style={styles.followUpLabel}>+ <Text style={styles.followUpName}>{identity.name}</Text>{' '}{step.task}+ </Text>+ </> : <Text numberOfLines={1} style={styles.followUpLabel}>{label}</Text>}+ </View>+ <MainWindowActionButton density="compact" hitSlop={BOT_GROUP_COMPACT_HIT_SLOP} action={{+ label: t(followUp.kind === 'continue' ? 'groupChat.timeline.continuePlan' : 'groupChat.timeline.retryStep'),+ tone: 'primary', busy: pending === primary, disabled: busy || !online,+ onPress: followUp.kind === 'continue' ? onContinue : onRetry, testID: `botGroup.followUp.${primary}`,+ }} />+ <MainWindowActionButton density="compact" hitSlop={BOT_GROUP_COMPACT_HIT_SLOP} action={{+ label: t('groupChat.timeline.endPlan'), busy: pending === 'dismiss', disabled: busy || !online,+ onPress: onEnd, testID: 'botGroup.followUp.end',+ }} />+ </View>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ organizerBadge: { borderRadius: radius.pill, backgroundColor: colors.surfaceChip, paddingHorizontal: spacing.sm, flexShrink: 0 },+ organizerBadgeText: { color: colors.textSecondary, fontSize: typeScale.micro, lineHeight: lineHeight.micro, fontWeight: fontWeight.semibold },+ planColumn: { gap: spacing.sm, minWidth: 0 },+ planIntro: { color: colors.textPrimary, fontSize: typeScale.bodyLarge, lineHeight: lineHeight.bodyLarge },+ // Floating card: 1px border on the elevated surface (mobile guide §2), no row dividers.+ card: { backgroundColor: colors.surfaceElevated, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,+ borderRadius: radius.container, paddingVertical: spacing.xs, overflow: 'hidden' },+ stepRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, minHeight: 44, paddingHorizontal: spacing.md },+ stepLead: { width: iconSize.md, alignItems: 'center', justifyContent: 'center' },+ stepNumber: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontVariant: ['tabular-nums'] },+ stepText: { flex: 1, minWidth: 0, color: colors.textSecondary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall },+ stepName: { color: colors.textPrimary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.medium },+ stepTextMuted: { color: colors.textTertiary, fontWeight: fontWeight.regular },+ stepStatus: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, flexShrink: 0 },+ muted: { opacity: 0.6 },+ actions: { flexDirection: 'row', gap: spacing.sm, paddingHorizontal: spacing.md, paddingTop: spacing.xs, paddingBottom: spacing.sm },+ note: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ files: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },+ fileChip: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs, minHeight: 32, maxWidth: '100%',+ paddingHorizontal: spacing.md, borderRadius: radius.pill, borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.border, backgroundColor: colors.surfaceElevated },+ fileName: { flexShrink: 1, color: colors.textPrimary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ divider: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, minHeight: 44 },+ dividerLine: { flex: 1, minWidth: spacing.xl, height: StyleSheet.hairlineWidth, backgroundColor: colors.border },+ dividerText: { flexShrink: 1, color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, textAlign: 'center' },+ followUp: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, minHeight: 44 },+ followUpText: { flex: 1, minWidth: 0, flexDirection: 'row', alignItems: 'center', gap: spacing.xs },+ followUpLead: { flexShrink: 0, color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ followUpLabel: { flexShrink: 1, color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ followUpName: { color: colors.textPrimary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },+});diff --git a/apps/mobile/src/session/BotGroupSettingsSheet.tsx b/apps/mobile/src/session/BotGroupSettingsSheet.tsxnew file mode 100644index 0000000000..676ed3dd4a--- /dev/null+++ b/apps/mobile/src/session/BotGroupSettingsSheet.tsx@@ -0,0 +1,286 @@+/**+ * 群设置(对照桌面 BotGroupSettingsDrawer.tsx):群名称、成员(移出 / 添加伙伴 / 设为负责人)、+ * 项目文件夹(只读:手机不能指定电脑上的文件夹,在电脑上选择或更换)、没有 @ 人时的回复方式、+ * 发言方式、删除群聊(系统确认框二次确认)。+ *+ * 每项改动立即交给电脑;群数据以电脑推送后重读的结果为准,失败就地提示并保持原值。+ * 成员数 2–6 由电脑最终校验,这里只把不会成立的操作提前禁用。能加入的只有这台电脑上的伙伴。+ */+import { useEffect, useRef, useState } from 'react';+import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';+import { Folder, Plus } from 'lucide-react-native';+import { useTranslation } from 'react-i18next';+import { resolveRemoteText } from '@cindy/device-link';+import {+ BOT_GROUP_MAX_MEMBERS,+ BOT_GROUP_MIN_MEMBERS,+ BOT_GROUP_NAME_MAX_CHARS,+ type BotGroupRemoteActionId,+ type BotGroupRemoteChatData,+ type BotGroupReplyMode,+ type BotGroupSpeakingMode,+} from '@cindy/maker-shared/botGroupChat';+import { isActiveBotGroupMember } from '@cindy/maker-shared/botGroupPresentation';+import { Text, TextInput } from '@/components/AppText';+import { MainWindowActionButton, MainWindowOptionButton } from '@/components/MobilePrimitives';+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';+import type { RemoteResourceHostTarget } from '@/device-link/remoteResources';+import { showConfirm } from '@/platform/chrome';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, iconSize, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';+import { BOT_GROUP_ROW_AVATAR_SIZE, BotGroupAvatar } from './BotGroupAvatars';+import { BOT_GROUP_COMPACT_HIT_SLOP, BotGroupOrganizerTag, type BotGroupIdentityLookup } from './BotGroupPlan';+import { botGroupActionErrorText } from './botGroupCopy';+import { CompanionSheet } from './CompanionSheet';+import { useHostTeammates } from './useHostTeammates';++type Busy = 'name' | 'members' | 'organizer' | 'replyMode' | 'speakingMode' | 'delete' | null;+type Act = (actionId: BotGroupRemoteActionId, input?: Record<string, unknown>) => Promise<unknown>;++export function BotGroupSettingsSheet({ visible, group, host, identityFor, online, act, onClose, onClosed, onDeleted }: {+ visible: boolean;+ group: BotGroupRemoteChatData;+ host: RemoteResourceHostTarget;+ identityFor: BotGroupIdentityLookup;+ online: boolean;+ act: Act;+ onClose(): void;+ onClosed?(): void;+ /** The group is gone; the screen leaves once the sheet has closed. */+ onDeleted(): void;+}) {+ const { t, i18n } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const [name, setName] = useState(group.name);+ const [busy, setBusy] = useState<Busy>(null);+ const busyRef = useRef<Busy>(null);+ const [errors, setErrors] = useState<Partial<Record<Exclude<Busy, null>, string>>>({});+ const [picking, setPicking] = useState(false);+ const nameFocused = useRef(false);+ const teammates = useHostTeammates(host, visible && picking);++ // Follow renames that land from the computer while the field is not being edited.+ useEffect(() => { if (!nameFocused.current) setName(group.name); }, [group.name]);+ useEffect(() => { if (!visible) { setPicking(false); setErrors({}); } }, [visible]);++ const memberIds = group.members.map((member) => member.botId);+ const canRemove = group.members.length > BOT_GROUP_MIN_MEMBERS;+ const canAdd = group.members.length < BOT_GROUP_MAX_MEMBERS;+ const addable = teammates.rows.filter((row) => !memberIds.includes(row.item.ref.id));+ const locked = busy !== null || !online;++ /** Run one change; the section shows the failure copy, or clears it on success. */+ const run = async (section: Exclude<Busy, null>, actionId: BotGroupRemoteActionId, input: Record<string, unknown>, fallbackKey: string) => {+ if (busyRef.current) return false;+ busyRef.current = section;+ setBusy(section);+ setErrors((current) => ({ ...current, [section]: undefined }));+ try {+ await act(actionId, input);+ return true;+ } catch (error) {+ setErrors((current) => ({ ...current, [section]: botGroupActionErrorText(t, error, fallbackKey) }));+ return false;+ } finally {+ busyRef.current = null;+ setBusy(null);+ }+ };++ const saveName = async () => {+ const trimmed = name.trim();+ if (!trimmed) { setName(group.name); return; }+ if (trimmed === group.name) return;+ const saved = await run('name', 'update', { name: trimmed }, 'groupChat.settings.nameSaveFailed');+ if (!saved) setName(group.name);+ };++ const setMembers = async (botIds: string[]) => {+ const saved = await run('members', 'set-members', { botIds }, 'groupChat.settings.membersSaveFailed');+ if (saved) setPicking(false);+ };++ const remove = async () => {+ if (busyRef.current) return;+ const confirmed = await showConfirm({+ title: t('groupChat.settings.deleteConfirmTitle', { name: group.name }),+ message: t('groupChat.settings.deleteNote'),+ cancelLabel: t('devices.common.cancel'),+ confirmLabel: t('groupChat.settings.delete'),+ destructive: true,+ });+ if (!confirmed) return;+ if (await run('delete', 'delete', {}, 'groupChat.settings.deleteFailed')) onDeleted();+ };++ const error = (section: Exclude<Busy, null>) => errors[section]+ ? <Text accessibilityRole="alert" style={styles.error}>{errors[section]}</Text>+ : null;++ const segmented = <T extends string>(section: 'replyMode' | 'speakingMode', value: T, options: { value: T; label: string }[]) =>+ <View style={styles.segments} accessibilityRole="tablist">+ {options.map((option) => <MainWindowOptionButton key={option.value} accessibilityRole="tab" density="default" variant="segmented"+ label={option.label} selected={option.value === value} disabled={locked}+ onPress={() => { if (option.value !== value) void run(section, 'update', { [section]: option.value }, `groupChat.settings.${section}SaveFailed`); }}+ style={styles.segment} testID={`botGroup.settings.${section}.${option.value}`} />)}+ </View>;++ return <CompanionSheet visible={visible} title={t('groupChat.settings.title')} onClose={onClose} onClosed={onClosed}+ preventDismiss={busy !== null} testID="botGroup.settings">+ <View style={styles.content}>+ <View style={styles.section}>+ <Text style={styles.sectionTitle}>{t('groupChat.create.nameLabel')}</Text>+ <TextInput accessibilityLabel={t('groupChat.create.nameLabel')} value={name} maxLength={BOT_GROUP_NAME_MAX_CHARS}+ editable={!locked || busy === 'name'} returnKeyType="done"+ onChangeText={(value) => { setName(value); setErrors((current) => ({ ...current, name: undefined })); }}+ onFocus={() => { nameFocused.current = true; }}+ onBlur={() => { nameFocused.current = false; void saveName(); }}+ onSubmitEditing={() => void saveName()}+ placeholderTextColor={colors.textPlaceholder} style={styles.input} testID="botGroup.settings.name" />+ {error('name')}+ </View>++ <View style={styles.section}>+ <Text style={styles.sectionTitle}>{t('groupChat.settings.members')}</Text>+ <View style={styles.group}>+ {group.members.map((member) => {+ const identity = identityFor(member.botId, member.name);+ const active = isActiveBotGroupMember(member);+ const organizer = member.botId === group.organizerBotId;+ return <View key={member.botId} style={styles.memberRow} testID={`botGroup.settings.member.${member.botId}`}>+ <View style={!active ? styles.inactive : undefined}>+ <BotGroupAvatar deviceId={host.deviceId} identity={identity} size={BOT_GROUP_ROW_AVATAR_SIZE} online={online} />+ </View>+ <View style={styles.memberName}>+ <Text numberOfLines={1} style={styles.rowTitle}>{identity.name}</Text>+ {organizer ? <BotGroupOrganizerTag /> : null}+ {!active ? <Text numberOfLines={1} style={styles.rowMeta}>+ {t(member.status === 'paused' ? 'groupChat.memberStatus.paused' : 'groupChat.memberStatus.unavailable')}+ </Text> : null}+ </View>+ {!organizer && active ? <MainWindowActionButton density="compact" hitSlop={BOT_GROUP_COMPACT_HIT_SLOP} action={{+ label: t('groupChat.settings.setOrganizer'),+ accessibilityLabel: t('groupChat.settings.setOrganizerNamed', { name: identity.name }),+ busy: busy === 'organizer', disabled: locked,+ onPress: () => void run('organizer', 'update', { organizerBotId: member.botId }, 'groupChat.settings.organizerSaveFailed'),+ testID: `botGroup.settings.organizer.${member.botId}`,+ }} /> : null}+ <MainWindowActionButton density="compact" hitSlop={BOT_GROUP_COMPACT_HIT_SLOP} action={{+ label: t('groupChat.settings.remove'),+ accessibilityLabel: canRemove+ ? t('groupChat.settings.removeNamed', { name: identity.name })+ : t('groupChat.settings.minMembers', { min: BOT_GROUP_MIN_MEMBERS }),+ disabled: locked || !canRemove,+ onPress: () => void setMembers(memberIds.filter((botId) => botId !== member.botId)),+ testID: `botGroup.settings.remove.${member.botId}`,+ }} />+ </View>;+ })}+ <Pressable accessibilityRole="button" accessibilityState={{ expanded: picking, disabled: locked || !canAdd }}+ accessibilityLabel={canAdd ? t('groupChat.settings.add') : t('groupChat.settings.maxMembers', { max: BOT_GROUP_MAX_MEMBERS })}+ disabled={locked || !canAdd} onPress={() => setPicking((value) => !value)}+ style={({ pressed }) => [styles.memberRow, styles.lastRow, pressed && mobileInteractionStyles.pressed, (locked || !canAdd) && styles.inactive]}+ testID="botGroup.settings.add">+ <View style={styles.addMark}><Plus size={iconSize.sm} color={colors.textSecondary} /></View>+ <Text numberOfLines={1} style={[styles.rowTitle, styles.flex]}>{t('groupChat.settings.add')}</Text>+ {!canAdd ? <Text style={styles.rowMeta}>{t('groupChat.settings.maxMembers', { max: BOT_GROUP_MAX_MEMBERS })}</Text> : null}+ </Pressable>+ {picking && canAdd ? <View style={styles.picker} testID="botGroup.settings.addable">+ {teammates.loading && addable.length === 0 ? <ActivityIndicator color={colors.textSecondary} style={styles.spinner} /> : null}+ {!teammates.loading && addable.length === 0+ ? <Text style={styles.note}>{t(teammates.failed ? 'devices.resources.loadFailed' : 'groupChat.settings.noMoreBots')}</Text>+ : null}+ {addable.map((row) => {+ const title = resolveRemoteText(row.item.display.title, i18n.language);+ return <Pressable key={row.key} accessibilityRole="button" accessibilityLabel={title} disabled={locked}+ onPress={() => void setMembers([...memberIds, row.item.ref.id])}+ style={({ pressed }) => [styles.memberRow, pressed && mobileInteractionStyles.pressed]}+ testID={`botGroup.settings.addable.${row.item.ref.id}`}>+ <BotGroupAvatar deviceId={host.deviceId} identity={{ botId: row.item.ref.id, name: title, avatar: row.item.display.avatar }}+ size={BOT_GROUP_ROW_AVATAR_SIZE} online={online} />+ <Text numberOfLines={1} style={[styles.rowTitle, styles.flex]}>{title}</Text>+ <Plus size={iconSize.sm} color={colors.textTertiary} />+ </Pressable>;+ })}+ </View> : null}+ </View>+ <Text style={styles.note}>{t('groupChat.settings.organizerNote')}</Text>+ {error('members')}+ {error('organizer')}+ </View>++ <View style={styles.section}>+ <Text style={styles.sectionTitle}>{t('groupChat.settings.projectDir')}</Text>+ <View style={[styles.group, styles.memberRow]} testID="botGroup.settings.projectDir">+ <Folder size={iconSize.md} color={colors.textSecondary} />+ <Text numberOfLines={1} style={[styles.rowValue, styles.flex]}>{group.projectDirName ?? t('groupChat.settings.projectDirNone')}</Text>+ <Text numberOfLines={1} style={styles.rowMeta}>{t('groupChat.settings.projectDirOnComputer')}</Text>+ </View>+ <Text style={styles.note}>{t('groupChat.settings.projectDirNote')}</Text>+ </View>++ <View style={styles.section}>+ <Text style={styles.sectionTitle}>{t('groupChat.settings.replyMode')}</Text>+ {segmented<BotGroupReplyMode>('replyMode', group.replyMode, [+ { value: 'all', label: t('groupChat.settings.replyModeAll') },+ { value: 'mentioned', label: t('groupChat.settings.replyModeMentioned') },+ ])}+ <Text style={styles.note}>{t('groupChat.settings.replyModeNote')}</Text>+ {error('replyMode')}+ </View>++ <View style={styles.section}>+ <Text style={styles.sectionTitle}>{t('groupChat.settings.speakingMode')}</Text>+ {segmented<BotGroupSpeakingMode>('speakingMode', group.speakingMode, [+ { value: 'auto', label: t('groupChat.settings.speakingModeAuto') },+ { value: 'sequential', label: t('groupChat.settings.speakingModeSequential') },+ ])}+ <Text style={styles.note}>{t(group.speakingMode === 'sequential'+ ? 'groupChat.settings.speakingModeSequentialNote'+ : 'groupChat.settings.speakingModeAutoNote')}</Text>+ {error('speakingMode')}+ </View>++ <View style={styles.section}>+ <Pressable accessibilityRole="button" accessibilityLabel={t('groupChat.settings.delete')} disabled={locked}+ onPress={() => void remove()}+ style={({ pressed }) => [styles.group, styles.memberRow, pressed && mobileInteractionStyles.pressed, locked && styles.inactive]}+ testID="botGroup.settings.delete">+ {busy === 'delete' ? <ActivityIndicator color={colors.destructive} /> : null}+ <Text style={[styles.rowTitle, styles.destructive]}>{t('groupChat.settings.delete')}</Text>+ </Pressable>+ <Text style={styles.note}>{t('groupChat.settings.deleteNote')}</Text>+ {error('delete')}+ </View>+ </View>+ </CompanionSheet>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ content: { gap: spacing.xl, paddingTop: spacing.sm, paddingBottom: spacing.xl },+ section: { gap: spacing.sm },+ sectionTitle: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.semibold },+ input: { minHeight: 44, borderRadius: radius.pill, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,+ paddingHorizontal: spacing.lg, color: colors.textPrimary, backgroundColor: colors.surfaceElevated, fontSize: typeScale.body },+ group: { backgroundColor: colors.surfaceElevated, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,+ borderRadius: radius.container, overflow: 'hidden' },+ memberRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, minHeight: 52, paddingHorizontal: spacing.md,+ paddingVertical: spacing.sm, borderBottomColor: colors.border, borderBottomWidth: StyleSheet.hairlineWidth },+ lastRow: { borderBottomWidth: 0 },+ memberName: { flex: 1, minWidth: 0, flexDirection: 'row', alignItems: 'center', gap: spacing.sm },+ rowTitle: { flexShrink: 1, color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium },+ rowValue: { color: colors.textSecondary, fontSize: typeScale.body, lineHeight: lineHeight.body },+ rowMeta: { flexShrink: 0, color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },+ flex: { flex: 1 },+ inactive: { opacity: 0.6 },+ addMark: { width: BOT_GROUP_ROW_AVATAR_SIZE, height: BOT_GROUP_ROW_AVATAR_SIZE, borderRadius: radius.pill, borderWidth: 1,+ borderStyle: 'dashed', borderColor: colors.borderStrong, alignItems: 'center', justifyContent: 'center' },+ picker: { borderTopColor: colors.border, borderTopWidth: StyleSheet.hairlineWidth },+ spinner: { paddingVertical: spacing.md },+ segments: { flexDirection: 'row', backgroundColor: colors.surfaceChip, borderRadius: radius.pill, padding: spacing.xs },+ segment: { flex: 1, minHeight: 44 },+ note: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ error: { color: colors.errorText, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ destructive: { color: colors.destructive },+});diff --git a/apps/mobile/src/session/BotGroupSpeakerRow.tsx b/apps/mobile/src/session/BotGroupSpeakerRow.tsxnew file mode 100644index 0000000000..5ac81104a2--- /dev/null+++ b/apps/mobile/src/session/BotGroupSpeakerRow.tsx@@ -0,0 +1,97 @@+/**+ * 正在发言 / 安排 / 做事的伙伴一行(对照桌面 BotGroupChatView 的 BotGroupSpeakingRow 与+ * BotGroupPendingInteraction)。+ *+ * 伙伴的群专线或分工 Session 是一条普通 Cindy Session:页面聚焦期间订阅它的+ * `session:<id>` 流并读一次挂起交互的快照,权限请求 / 提问就地用伙伴卡片样式显示在这位+ * 伙伴下面,作答走任务页同一条路径。等你确认时不再显示「正在…」。+ */+import { useCallback, useSyncExternalStore } from 'react';+import { StyleSheet, View } from 'react-native';+import { useFocusEffect } from 'expo-router';+import { CircleAlert, Sparkles } from 'lucide-react-native';+import { useTranslation } from 'react-i18next';+import { readWorkingPhase } from '@cindy/maker-shared';+import type { BotGroupSpeakerActivity } from '@cindy/maker-shared/botGroupChat';+import { Text } from '@/components/AppText';+import { useDeviceLink } from '@/device-link/DeviceLinkContext';+import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, iconSize, lineHeight, spacing, typeScale } from '@/theme/tokens';+import {+ BOT_GROUP_INLINE_AVATAR_SIZE,+ BOT_GROUP_MESSAGE_AVATAR_SIZE,+ BotGroupAvatar,+ type BotGroupIdentity,+} from './BotGroupAvatars';+import { InteractionPanel } from './InteractionPanel';+import { remoteSessionStore, useSessionPendingInteractions } from './remoteSessionStore';+import type { PendingInteraction } from './types';+import { useCompanionGenerationCopy } from './useCompanionGenerationCopy';+import { WorkingStatusText } from './WorkingStatusText';++export function BotGroupSpeakerRow({ deviceId, identity, sessionId, activity, online, onError }: {+ deviceId: string;+ identity: BotGroupIdentity;+ sessionId: string | null;+ activity: BotGroupSpeakerActivity;+ online: boolean;+ onError(message: string | null): void;+}) {+ const { t } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const { invoke, subscribe, unsubscribe } = useDeviceLink();+ const lane = sessionId ?? '';+ useFocusEffect(useCallback(() => {+ if (!lane || !online) return;+ let cancelled = false;+ const offTopic = startFocusedTopicSubscription({ deviceId, owner: `bot-group-speaker:${lane}`, topic: `session:${lane}`, subscribe, unsubscribe });+ // Seed prompts raised before this screen subscribed; later ones arrive as pushes.+ void invoke<PendingInteraction[]>(deviceId, 'maker:get-pending-interactions', [lane]).then((list) => {+ if (!cancelled && Array.isArray(list)) remoteSessionStore.setPendingInteractions(lane, list);+ }).catch(() => undefined);+ return () => { 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 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,+ active: !waiting && activity !== 'planning' && (activity === 'reply' || livePhase !== null),+ turnId: lane,+ });+ const label = activity === 'planning'+ ? t('groupChat.speaking.planning')+ : copy ?? (activity === 'step' ? t('groupChat.speaking.step') : t('devices.companions.working.thinking'));+ return <View style={styles.row} testID="botGroup.speaking" accessibilityLabel={`${identity.name}, ${waiting ? t('groupChat.waitingConfirm', { name: identity.name }) : label}`}>+ <BotGroupAvatar deviceId={deviceId} identity={identity} size={BOT_GROUP_MESSAGE_AVATAR_SIZE} online={online} />+ <View style={styles.column}>+ <Text numberOfLines={1} style={styles.name}>{identity.name}</Text>+ {!waiting ? <View style={styles.status} accessibilityLiveRegion="polite" testID={`botGroup.speaking.${activity}`}>+ <Sparkles size={iconSize.sm} color={colors.statusAccent} />+ <WorkingStatusText key={`${lane}:${activity}`} text={label} style={styles.statusText} />+ </View> : null}+ {pending.length > 0 && lane ? <InteractionPanel embedded companion+ companionIdentity={{ 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} />+ : waiting ? <View style={styles.status} testID="botGroup.speaking.waiting">+ <CircleAlert size={iconSize.sm} color={colors.warningFg} />+ <Text style={styles.waitingText}>{t('groupChat.waitingConfirm', { name: identity.name })}</Text>+ </View> : null}+ </View>+ </View>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ row: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm },+ column: { flex: 1, minWidth: 0, gap: spacing.xs },+ name: { color: colors.textPrimary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.medium },+ status: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },+ statusText: { flexShrink: 1, color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+ waitingText: { flexShrink: 1, color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+});diff --git a/apps/mobile/src/session/TeammateHomeScreen.tsx b/apps/mobile/src/session/TeammateHomeScreen.tsxindex 6280fb144b..15bc6e202f 100644--- a/apps/mobile/src/session/TeammateHomeScreen.tsx+++ b/apps/mobile/src/session/TeammateHomeScreen.tsx@@ -11,11 +11,14 @@ import { useGuardedPush } from '@/utils/useGuardedPush';import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';import { fontWeight, iconSize, iconStroke, lineHeight, spacing, typeScale } from '@/theme/tokens';import { AccountSwitcherSheet } from './AccountSwitcherSheet';+import { BotGroupSection } from './BotGroupList';+import { botGroupRoute } from './botGroupNavigation';import { HomeChromeDrawer } from './HomeChromeDrawer';import { HomeHeaderGlassButton } from './HomeHeaderGlassButton';import { TeammateCreateButton } from './TeammateCreateButton';import { TeammateList } from './TeammateList';import { useTeammateRoster } from './useTeammateRoster';+import { useBotGroupRoster } from './useBotGroupRoster';import { useTeammateNavigation } from './useTeammateNavigation';import { findLastTeammate } from './teammateNavigation';import { remoteSessionStore } from './remoteSessionStore';@@ -31,6 +34,7 @@ export function TeammateHomeScreen({ active = true }: { active?: boolean }) {const push = useGuardedPush();const navigation = useTeammateNavigation();const roster = useTeammateRoster(focused);+ const groups = useBotGroupRoster(roster.groupTargets, focused);const resumed = useRef(false);const wasFocused = useRef(focused);const [drawer, setDrawer] = useState(false);@@ -85,8 +89,14 @@ export function TeammateHomeScreen({ active = true }: { active?: boolean }) {{navigation.saveFailed ? <Text accessibilityRole="alert" style={styles.notice}>{t('devices.companions.preferenceSaveFailed')}</Text> : null}<TeammateList key={searchEpoch} {...roster} current={navigation.lastTeammate} autoFocusSearch={searchEpoch > 0}onInteract={() => { resumed.current = true; }}- onRefresh={() => { resumed.current = true; void roster.refresh(); }}- onSelect={(item) => { resumed.current = true; void navigation.openTeammate(item); }} />+ onRefresh={() => { resumed.current = true; void roster.refresh(); if (groups.supported) void groups.refresh(); }}+ onSelect={(item) => { resumed.current = true; void navigation.openTeammate(item); }}+ renderFooter={(query) => groups.supported || groups.items.length > 0 ? <BotGroupSection items={groups.items} query={query}+ isOnline={groups.isOnline} createTargets={roster.groupTargets.filter(groups.isOnline)}+ preferredDeviceId={navigation.lastTeammate?.deviceId}+ onInteract={() => { resumed.current = true; }}+ onOpen={(row) => { resumed.current = true; Keyboard.dismiss(); push(botGroupRoute(row.host, row.item.ref.id)); }}+ onOpenCreated={(host, groupId) => { resumed.current = true; push(botGroupRoute(host, groupId)); }} /> : null} /><HomeChromeDrawer open={drawer} user={auth.user} loggingOut={loggingOut} mode="teammates"onModeChange={(mode) => afterDrawer(() => { void navigation.setMode(mode); })}onClose={() => { pending.current = null; setDrawer(false); }} onClosed={finishOverlay}diff --git a/apps/mobile/src/session/TeammateList.tsx b/apps/mobile/src/session/TeammateList.tsxindex bbd517e3f1..3d430da9f5 100644--- a/apps/mobile/src/session/TeammateList.tsx+++ b/apps/mobile/src/session/TeammateList.tsx@@ -1,6 +1,6 @@import { readWorkingPhase } from '@cindy/maker-shared';import { TeammateGenerationLabel } from './TeammateGenerationLabel';-import { useMemo, useState } from 'react';+import { useMemo, useState, type ReactElement } from 'react';import { ActivityIndicator, FlatList, Pressable, RefreshControl, StyleSheet, View } from 'react-native';import { useTranslation } from 'react-i18next';import { RefreshCw, TriangleAlert } from 'lucide-react-native';@@ -33,10 +33,12 @@ export interface TeammateListProps {embedded?: boolean;autoFocusSearch?: boolean;onInteract?(): void;+ /** Home only: the 「群聊」 section under the teammates, filtered by the same search text. */+ renderFooter?(query: string): ReactElement | null;}/** Flat identity list shared by home, collection route and the name picker. No host headings or groups. */export function TeammateList({ items, loading, refreshing, error, isOnline, connectionState, onRefresh, onSelect,- current = null, embedded = false, autoFocusSearch = false, onInteract }: TeammateListProps) {+ current = null, embedded = false, autoFocusSearch = false, onInteract, renderFooter }: TeammateListProps) {const { t, i18n } = useTranslation();const { user } = useAuth();const { colors } = useTheme();@@ -109,10 +111,11 @@ export function TeammateList({ items, loading, refreshing, error, isOnline, conn</View></Pressable>;};- if (embedded) return <View testID="teammates.list">{header}{rows.length ? rows.map(renderRow) : empty}</View>;+ const footer = renderFooter?.(query) ?? null;+ if (embedded) return <View testID="teammates.list">{header}{rows.length ? rows.map(renderRow) : empty}{footer}</View>;return <FlatList style={styles.list} contentContainerStyle={styles.content} data={rows} keyExtractor={(row) => row.key}keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag" onScrollBeginDrag={onInteract} testID="teammates.list"- ListHeaderComponent={header} ListEmptyComponent={empty} renderItem={({ item }) => renderRow(item)}+ ListHeaderComponent={header} ListEmptyComponent={empty} ListFooterComponent={footer} renderItem={({ item }) => renderRow(item)}refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={colors.textSecondary} />} />;}const makeStyles = (colors: ThemeColors) => StyleSheet.create({diff --git a/apps/mobile/src/session/botGroupCopy.ts b/apps/mobile/src/session/botGroupCopy.tsnew file mode 100644index 0000000000..ad8c87f161--- /dev/null+++ b/apps/mobile/src/session/botGroupCopy.ts@@ -0,0 +1,13 @@+import { botGroupErrorVariant } from '@cindy/maker-shared/botGroupPresentation';+import { botGroupErrorCode } from './botGroupRemote';++type Translate = (key: string, options?: Record<string, unknown>) => string;++/**+ * User-facing copy for a refused or failed group action: the host's own reason when it names+ * one the user can act on (PLAN_OPEN, MEMBER_LIMIT, …), otherwise the action's fallback line.+ */+export function botGroupActionErrorText(t: Translate, error: unknown, fallbackKey: string): string {+ const variant = botGroupErrorVariant(botGroupErrorCode(error));+ return t(variant ? `groupChat.errors.${variant}` : fallbackKey);+}diff --git a/apps/mobile/src/session/botGroupNavigation.ts b/apps/mobile/src/session/botGroupNavigation.tsnew file mode 100644index 0000000000..e28bd1dbce--- /dev/null+++ b/apps/mobile/src/session/botGroupNavigation.ts@@ -0,0 +1,9 @@+import type { RemoteResourceHostTarget } from '@/device-link/remoteResources';++/** The group screen; a group lives on one computer, so the route always names it. */+export function botGroupRoute(host: RemoteResourceHostTarget, groupId: string) {+ return {+ pathname: '/companions/groups/[groupId]' as const,+ params: { groupId, deviceId: host.deviceId, deviceName: host.deviceName },+ };+}diff --git a/apps/mobile/src/session/botGroupRemote.ts b/apps/mobile/src/session/botGroupRemote.tsnew file mode 100644index 0000000000..dc3fb48f64--- /dev/null+++ b/apps/mobile/src/session/botGroupRemote.ts@@ -0,0 +1,385 @@+/**+ * 伙伴群聊在手机上的数据边界(docs/product-rules/bot-group-chat.md §8)。+ *+ * 群走 Remote Resource 协议:列表是 `bot-groups` 集合,群详情是 `bot-group-chat` 块,+ * 操作是集合动作。电脑是唯一的规则执行方,这里只做三件事:把电脑发来的数据当不可信+ * 输入逐字段校验、把被拒的动作读回群聊错误码、给列表与发送准备纯函数。不碰 React。+ */+import { resolveRemoteText, type RemoteActionEffect, type RemoteCollectionItem, type RemoteResource, type RemoteResourceAvatar, type RemoteResourceRef } from '@cindy/device-link';+import {+ BOT_GROUP_CHAT_PRIMITIVE,+ BOT_GROUP_MEMBER_LINK_REL,+ BOT_GROUP_REMOTE_COLLECTION_ID,+ BOT_GROUP_REMOTE_RESOURCE_KIND,+ type BotGroupErrorCode,+ type BotGroupLastMessage,+ type BotGroupMemberStatus,+ type BotGroupMemberView,+ type BotGroupMention,+ type BotGroupMessageView,+ type BotGroupOpenPlanSummary,+ type BotGroupPlanStepView,+ type BotGroupPlanView,+ type BotGroupRemoteChatData,+ type BotGroupRoundView,+ type BotGroupSpeaker,+} from '@cindy/maker-shared/botGroupChat';+import { formatRemoteError } from '@cindy/maker-shared/device-link-contract';++/** Member links point at the teammates collection; avatars come from its cached rows. */+export const BOT_GROUP_TEAMMATES_COLLECTION_ID = 'teammates';+/** Declared on `get` so the host sends the structured chat block instead of Markdown. */+export const BOT_GROUP_CLIENT_PRIMITIVES: readonly string[] = [BOT_GROUP_CHAT_PRIMITIVE];++export function botGroupResourceRef(groupId: string): RemoteResourceRef {+ return { collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, kind: BOT_GROUP_REMOTE_RESOURCE_KIND, id: groupId };+}++function recordOf(value: unknown): Record<string, unknown> | null {+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;+}++/** Old desktops have no group collection: the phone then hides groups entirely. */+export function hasBotGroupCollection(manifest: unknown): boolean {+ const collections = recordOf(manifest)?.collections;+ return Array.isArray(collections) && collections.some((collection) => {+ const record = recordOf(collection);+ return record?.id === BOT_GROUP_REMOTE_COLLECTION_ID && record.resourceKind === BOT_GROUP_REMOTE_RESOURCE_KIND;+ });+}++export interface BotGroupMemberLink {+ botId: string;+ label: string;+}++/** Members of a list row, in member order, from the row's `member` links. */+export function botGroupMemberLinks(item: Pick<RemoteCollectionItem, 'links'>, locale: string): BotGroupMemberLink[] {+ const seen = new Set<string>();+ return item.links.flatMap((link) => {+ const target = link.target;+ if (link.rel !== BOT_GROUP_MEMBER_LINK_REL || target.kind !== 'resource') return [];+ if (target.ref.collectionId !== BOT_GROUP_TEAMMATES_COLLECTION_ID || target.ref.kind !== 'bot') return [];+ if (seen.has(target.ref.id)) return [];+ seen.add(target.ref.id);+ return [{ botId: target.ref.id, label: link.label ? resolveRemoteText(link.label, locale) : '' }];+ });+}++/** Group rows: newest activity first, one row per host and group, filtered by name or member. */+export function orderedBotGroups<T extends { host: { deviceId: string }; item: RemoteCollectionItem }>(+ rows: readonly T[],+ query: string,+ locale: string,+): T[] {+ const needle = query.normalize('NFKC').trim().toLocaleLowerCase(locale);+ const unique = new Map<string, T>();+ for (const row of rows) {+ if (row.item.ref.collectionId !== BOT_GROUP_REMOTE_COLLECTION_ID || row.item.ref.kind !== BOT_GROUP_REMOTE_RESOURCE_KIND) continue;+ if (needle) {+ const haystack = [+ resolveRemoteText(row.item.display.title, locale),+ row.item.display.subtitle ? resolveRemoteText(row.item.display.subtitle, locale) : '',+ ...botGroupMemberLinks(row.item, locale).map((member) => member.label),+ ].join('\n').normalize('NFKC').toLocaleLowerCase(locale);+ if (!haystack.includes(needle)) continue;+ }+ unique.set(JSON.stringify([row.host.deviceId, row.item.ref.id]), row);+ }+ return [...unique.values()].sort((a, b) => (b.item.display.timestamp ?? 0) - (a.item.display.timestamp ?? 0));+}++// ---- Chat block validation ------------------------------------------------------++const MEMBER_STATUSES = new Set<BotGroupMemberStatus>(['active', 'paused', 'error', 'archived', 'deleting', 'missing']);+const MESSAGE_KINDS = new Set<BotGroupMessageView['kind']>(['message', 'round-end', 'notice', 'plan', 'plan-end']);+const AUTHOR_KINDS = new Set<BotGroupMessageView['authorKind']>(['user', 'bot', 'system']);+const NOTICE_CODES = new Set<string>([+ 'member-failed', 'member-timeout', 'member-unavailable', 'plan-failed', 'plan-stopped', 'workdir-unavailable',+]);+const PLAN_STATUSES = new Set<BotGroupPlanView['status']>([+ 'proposed', 'running', 'waiting', 'done', 'stopped', 'dismissed', 'superseded',+]);+const STEP_STATUSES = new Set<BotGroupPlanStepView['status']>(['pending', 'running', 'done', 'failed']);+const SPEAKER_ACTIVITIES = new Set<BotGroupSpeaker['activity']>(['reply', 'planning', 'step']);+const MAX_ID = 256;+const MAX_NAME = 512;+const MAX_TEXT = 200_000;+const MAX_FILES = 64;++function text(value: unknown, max: number): string | null {+ return typeof value === 'string' && value.length <= max ? value : null;+}+function id(value: unknown): string | null {+ const parsed = text(value, MAX_ID);+ return parsed ? parsed : null;+}+function optionalId(value: unknown): string | null {+ return value === null || value === undefined ? null : id(value);+}+function finite(value: unknown): number | null {+ return typeof value === 'number' && Number.isFinite(value) ? value : null;+}+function stringList(value: unknown, max: number, itemMax: number): string[] {+ return Array.isArray(value)+ ? value.slice(0, max).flatMap((item) => {+ const parsed = text(item, itemMax);+ return parsed ? [parsed] : [];+ })+ : [];+}+function enumOf<T extends string>(value: unknown, allowed: ReadonlySet<T>): T | null {+ return typeof value === 'string' && allowed.has(value as T) ? value as T : null;+}++function parseMember(value: unknown): BotGroupMemberView | null {+ const record = recordOf(value);+ const botId = id(record?.botId);+ const name = text(record?.name, MAX_NAME);+ if (!record || !botId || name === null) return null;+ return {+ botId,+ name,+ avatar: text(record.avatar, 4_096) ?? '',+ avatarColor: text(record.avatarColor, 64) ?? '',+ status: enumOf(record.status, MEMBER_STATUSES) ?? 'missing',+ };+}++function parseMentions(value: unknown): BotGroupMention {+ const record = recordOf(value);+ return { all: record?.all === true, botIds: stringList(record?.botIds, 32, MAX_ID) };+}++function parseMessage(value: unknown): BotGroupMessageView | null {+ const record = recordOf(value);+ const messageId = id(record?.id);+ const sequence = finite(record?.sequence);+ const kind = enumOf(record?.kind, MESSAGE_KINDS);+ const authorKind = enumOf(record?.authorKind, AUTHOR_KINDS);+ const content = text(record?.content, MAX_TEXT);+ const createdAt = finite(record?.createdAt);+ // Unknown future kinds are dropped rather than shown as ordinary chat.+ if (!record || !messageId || sequence === null || !kind || !authorKind || content === null || createdAt === null) return null;+ const noticeCode = typeof record.noticeCode === 'string' && NOTICE_CODES.has(record.noticeCode)+ ? record.noticeCode as BotGroupMessageView['noticeCode']+ : null;+ return {+ id: messageId,+ sequence,+ kind,+ authorKind,+ authorBotId: optionalId(record.authorBotId),+ authorName: text(record.authorName, MAX_NAME) ?? '',+ content,+ mentions: parseMentions(record.mentions),+ noticeCode,+ planId: optionalId(record.planId),+ files: stringList(record.files, MAX_FILES, 1_024),+ createdAt,+ };+}++function parseStep(value: unknown): BotGroupPlanStepView | null {+ const record = recordOf(value);+ const position = finite(record?.position);+ const botId = id(record?.botId);+ const status = enumOf(record?.status, STEP_STATUSES);+ const task = text(record?.task, 4_096);+ if (!record || position === null || !botId || !status || task === null) return null;+ return { position, botId, botName: text(record.botName, MAX_NAME) ?? '', task, status };+}++function parsePlan(value: unknown): BotGroupPlanView | null {+ const record = recordOf(value);+ const planId = id(record?.id);+ const status = enumOf(record?.status, PLAN_STATUSES);+ if (!record || !planId || !status || !Array.isArray(record.steps)) return null;+ const steps = record.steps.slice(0, 32).map(parseStep);+ // A plan with an unreadable step would misstate who does what; show it as unreadable instead.+ if (steps.length === 0 || steps.some((step) => step === null)) return null;+ const currentStep = record.currentStep === null ? null : finite(record.currentStep);+ return {+ id: planId,+ status,+ organizerBotId: id(record.organizerBotId) ?? '',+ organizerName: text(record.organizerName, MAX_NAME) ?? '',+ steps: steps as BotGroupPlanStepView[],+ currentStep,+ // Host paths never leave the computer.+ workDir: null,+ branch: text(record.branch, 1_024),+ createdAt: finite(record.createdAt) ?? 0,+ updatedAt: finite(record.updatedAt) ?? 0,+ };+}++function parseOpenPlan(value: unknown): BotGroupOpenPlanSummary | null {+ const record = recordOf(value);+ const planId = id(record?.id);+ const status = enumOf(record?.status, PLAN_STATUSES);+ if (!record || !planId || !status) return null;+ return {+ id: planId,+ status,+ currentStep: record.currentStep === null ? null : finite(record.currentStep),+ stepCount: finite(record.stepCount) ?? 0,+ currentBotName: text(record.currentBotName, MAX_NAME),+ currentStepStatus: enumOf(record.currentStepStatus, STEP_STATUSES),+ };+}++function parseRound(value: unknown): BotGroupRoundView {+ const record = recordOf(value);+ const speakers = Array.isArray(record?.speakers)+ ? record.speakers.slice(0, 16).flatMap((raw): BotGroupSpeaker[] => {+ const speaker = recordOf(raw);+ const botId = id(speaker?.botId);+ if (!speaker || !botId) return [];+ return [{+ botId,+ sessionId: optionalId(speaker.sessionId),+ activity: enumOf(speaker.activity, SPEAKER_ACTIVITIES) ?? 'reply',+ }];+ })+ : [];+ return {+ status: record?.status === 'running' ? 'running' : 'idle',+ speakers,+ canContinue: record?.canContinue === true,+ };+}++function parseLastMessage(value: unknown): BotGroupLastMessage | null {+ const record = recordOf(value);+ const authorKind = enumOf(record?.authorKind, AUTHOR_KINDS);+ const createdAt = finite(record?.createdAt);+ if (!record || !authorKind || createdAt === null) return null;+ return {+ authorKind,+ authorName: text(record.authorName, MAX_NAME) ?? '',+ preview: text(record.preview, 4_096) ?? '',+ createdAt,+ };+}++/**+ * The host's `bot-group-chat` block data, validated field by field. Returns null when+ * the essentials (id, name, members, messages) are unreadable; malformed messages and+ * plans are dropped one by one so a single bad entry cannot blank the conversation.+ */+export function parseBotGroupChatData(value: unknown): BotGroupRemoteChatData | null {+ const record = recordOf(value);+ const groupId = id(record?.id);+ const name = text(record?.name, MAX_NAME);+ if (!record || !groupId || name === null || !Array.isArray(record.members) || !Array.isArray(record.messages)) return null;+ const members = record.members.slice(0, 16).flatMap((raw) => {+ const member = parseMember(raw);+ return member ? [member] : [];+ });+ const messages = record.messages.slice(0, 500).flatMap((raw) => {+ const message = parseMessage(raw);+ return message ? [message] : [];+ }).sort((a, b) => a.sequence - b.sequence);+ const plans = Array.isArray(record.plans)+ ? record.plans.slice(0, 200).flatMap((raw) => {+ const plan = parsePlan(raw);+ return plan ? [plan] : [];+ })+ : [];+ return {+ id: groupId,+ name,+ replyMode: record.replyMode === 'mentioned' ? 'mentioned' : 'all',+ speakingMode: record.speakingMode === 'sequential' ? 'sequential' : 'auto',+ members,+ organizerBotId: optionalId(record.organizerBotId),+ projectDir: null,+ projectDirName: text(record.projectDirName, 1_024) || null,+ lastMessage: parseLastMessage(record.lastMessage),+ speakingBotIds: stringList(record.speakingBotIds, 16, MAX_ID),+ planningBotId: optionalId(record.planningBotId),+ openPlan: parseOpenPlan(record.openPlan),+ createdAt: finite(record.createdAt) ?? 0,+ updatedAt: finite(record.updatedAt) ?? 0,+ messages,+ hasMoreBefore: record.hasMoreBefore === true,+ round: parseRound(record.round),+ plans,+ };+}++/** The chat block of a group resource read with `BOT_GROUP_CLIENT_PRIMITIVES`. */+export function botGroupChatDataFromResource(resource: Pick<RemoteResource, 'blocks'>): BotGroupRemoteChatData | null {+ const block = resource.blocks?.find((candidate) => candidate.primitive === BOT_GROUP_CHAT_PRIMITIVE);+ return block ? parseBotGroupChatData(block.data) : null;+}++// ---- Actions ---------------------------------------------------------------++/** Specific codes first: the transport code (INVALID_PARAMS / NOT_FOUND) wraps them. */+const ERROR_CODES: readonly BotGroupErrorCode[] = [+ 'MEMBER_LIMIT',+ 'MEMBER_UNAVAILABLE',+ 'PLAN_OPEN',+ 'PLAN_CLOSED',+ 'HOST_NOT_READY',+ 'NOT_FOUND',+ 'INVALID_PARAMS',+];++/** The group error code a refused action carries (as its message), if any. */+export function botGroupErrorCode(error: unknown): BotGroupErrorCode | null {+ const message = formatRemoteError(error);+ return ERROR_CODES.find((code) => new RegExp(`(^|[^A-Z_])${code}([^A-Z_]|$)`).test(message)) ?? null;+}++/** The new group a `create` action navigated to. */+export function createdBotGroupId(effects: readonly RemoteActionEffect[] | undefined): string | null {+ for (const effect of effects ?? []) {+ if (effect.kind !== 'navigate' || effect.target.kind !== 'resource') continue;+ const ref = effect.target.ref;+ if (ref.collectionId === BOT_GROUP_REMOTE_COLLECTION_ID && ref.kind === BOT_GROUP_REMOTE_RESOURCE_KIND && ref.id) return ref.id;+ }+ return null;+}++/**+ * The same projection the teammates collection uses for a Bot avatar, from a member's+ * raw fields. Used only when the teammates cache has no row for that Bot.+ */+export function botGroupMemberAvatar(member: Pick<BotGroupMemberView, 'avatar' | 'avatarColor' | 'name'>): RemoteResourceAvatar {+ const value = member.avatar;+ const kind = value.startsWith('cindy://avatar/')+ ? 'asset'+ : /^[a-z][a-z0-9+.-]*:\/\//i.test(value) || value.startsWith('/')+ ? 'media'+ : value ? 'emoji' : 'text';+ return {+ kind,+ value,+ fallbackText: Array.from(member.name.trim())[0] ?? '',+ ...(member.avatarColor ? { color: member.avatarColor } : {}),+ };+}++export interface BotGroupSendAttempt {+ text: string;+ division: boolean;+ clientId: string;+}++/**+ * A retry of the same text with the same 「分工」 tag reuses its clientId, so the host+ * returns the message it already stored instead of writing it twice.+ */+export function nextBotGroupSendAttempt(+ previous: BotGroupSendAttempt | null,+ text: string,+ division: boolean,+ newClientId: () => string,+): BotGroupSendAttempt {+ return previous && previous.text === text && previous.division === division+ ? previous+ : { text, division, clientId: newClientId() };+}diff --git a/apps/mobile/src/session/useBotGroupChat.ts b/apps/mobile/src/session/useBotGroupChat.tsnew file mode 100644index 0000000000..7c204ad2e9--- /dev/null+++ b/apps/mobile/src/session/useBotGroupChat.ts@@ -0,0 +1,111 @@+import { useCallback, useRef, useState } from 'react';+import { AppState } from 'react-native';+import { useFocusEffect } from 'expo-router';+import { useTranslation } from 'react-i18next';+import type { RemoteActionInvokeResponse } from '@cindy/device-link';+import { BOT_GROUP_REMOTE_COLLECTION_ID, type BotGroupRemoteActionId, type BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';+import { useAuth } from '@/auth/AuthContext';+import { useDeviceLink } from '@/device-link/DeviceLinkContext';+import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';+import { getRemoteResource, invokeRemoteResourceAction, type RemoteResourceHostTarget } from '@/device-link/remoteResources';+import { formatRemoteError } from '@/device-link/remoteStatus';+import { useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';+import { BOT_GROUP_CLIENT_PRIMITIVES, botGroupChatDataFromResource, botGroupErrorCode, botGroupResourceRef } from './botGroupRemote';++export type BotGroupChatState =+ | { kind: 'loading' }+ | { kind: 'ready'; group: BotGroupRemoteChatData }+ | { kind: 'missing' }+ | { kind: 'error'; message: string };++/** Pushes for one change arrive in bursts (messages, round, plan); read once per burst. */+const PUSH_COALESCE_MS = 150;++/**+ * One group as the computer sees it (docs/product-rules/bot-group-chat.md §8). Every change+ * on the computer broadcasts `maker:remote-resources:changed` for the group; the screen+ * re-reads the whole projection on it, never patches the timeline locally. Actions go+ * through the same resource and are followed by a read.+ */+export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string) {+ const { invoke, openLink, status, connectionEpoch, presenceVersion, getPresenceAvailability, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();+ const { accountGeneration } = useAuth();+ const { i18n } = useTranslation();+ const identity = JSON.stringify([accountGeneration, host.deviceId, groupId]);+ const identityRef = useRef(identity); identityRef.current = identity;+ const [state, setState] = useState<{ identity: string; value: BotGroupChatState }>({ identity, value: { kind: 'loading' } });++ const read = useCallback(async (isStale: () => boolean) => {+ const owner = identity;+ const valid = () => !isStale() && identityRef.current === owner;+ if (!host.deviceId || !groupId) {+ setState({ identity: owner, value: { kind: 'missing' } });+ return;+ }+ try {+ await openLink(host.deviceId);+ const resource = await getRemoteResource(invoke, host, botGroupResourceRef(groupId), i18n.language, BOT_GROUP_CLIENT_PRIMITIVES);+ if (!valid()) return;+ const group = botGroupChatDataFromResource(resource);+ if (!group || group.id !== groupId) throw new Error('INVALID_GROUP_DATA');+ setState({ identity: owner, value: { kind: 'ready', group } });+ } catch (error) {+ if (!valid()) return;+ if (botGroupErrorCode(error) === 'NOT_FOUND') {+ setState({ identity: owner, value: { kind: 'missing' } });+ return;+ }+ // Keep a conversation that is already on screen; only a first read fails loudly.+ setState((previous) => previous.identity === owner && previous.value.kind === 'ready'+ ? previous+ : { identity: owner, value: { kind: 'error', message: formatRemoteError(error) } });+ }+ }, [groupId, host, i18n.language, identity, invoke, openLink]);++ const request = useRemoteSyncCoordinator((run) => read(run.isStale), identity);+ const reload = useCallback(() => { void request({ reason: 'changed' }); }, [request]);++ useFocusEffect(useCallback(() => {+ if (!host.deviceId || !groupId || status !== 'online') return;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const schedule = () => {+ if (timer) return;+ timer = setTimeout(() => { timer = undefined; if (AppState.currentState === 'active') reload(); }, PUSH_COALESCE_MS);+ };+ const offPush = onRemoteResourceChanged((source, payload) => {+ if (source !== host.deviceId || payload.collectionId !== BOT_GROUP_REMOTE_COLLECTION_ID) return;+ if (payload.resourceRefs?.length && !payload.resourceRefs.some((ref) => ref.id === groupId)) return;+ schedule();+ });+ // The change push rides the account-level `sessions` topic.+ const offTopic = startFocusedTopicSubscription({ deviceId: host.deviceId, owner: `bot-group:${groupId}`, topic: 'sessions', subscribe, unsubscribe });+ const appState = AppState.addEventListener('change', (value) => { if (value === 'active') reload(); });+ reload();+ return () => { offPush(); offTopic(); appState.remove(); if (timer) clearTimeout(timer); };+ }, [connectionEpoch, groupId, host.deviceId, onRemoteResourceChanged, reload, status, subscribe, unsubscribe]));++ /** Run a group action; rejects with the host's error (see `botGroupErrorCode`). */+ const act = useCallback(async (actionId: BotGroupRemoteActionId, input?: Record<string, unknown>): Promise<RemoteActionInvokeResponse> => {+ try {+ await openLink(host.deviceId);+ return await invokeRemoteResourceAction(invoke, host, {+ collectionId: BOT_GROUP_REMOTE_COLLECTION_ID,+ actionId,+ resourceRef: botGroupResourceRef(groupId),+ ...(input ? { input } : {}),+ }, i18n.language);+ } finally {+ // A refused action usually means the phone's copy is stale (PLAN_CLOSED, PLAN_OPEN): re-read either way.+ // A deleted group is left by the screen instead.+ if (actionId !== 'delete' && identityRef.current === identity) reload();+ }+ }, [groupId, host, i18n.language, identity, invoke, openLink, reload]);++ const value: BotGroupChatState = !host.deviceId || !groupId+ ? { kind: 'missing' }+ : state.identity === identity ? state.value : { kind: 'loading' };+ void presenceVersion;+ // Unknown presence still allows actions; the host answers or the link reports offline.+ const online = status === 'online' && !!host.deviceId && getPresenceAvailability(host.deviceId) !== false;+ return { state: value, reload, act, online };+}diff --git a/apps/mobile/src/session/useBotGroupRoster.ts b/apps/mobile/src/session/useBotGroupRoster.tsnew file mode 100644index 0000000000..778214c996--- /dev/null+++ b/apps/mobile/src/session/useBotGroupRoster.ts@@ -0,0 +1,25 @@+import { BOT_GROUP_REMOTE_COLLECTION_ID, BOT_GROUP_REMOTE_RESOURCE_KIND } from '@cindy/maker-shared/botGroupChat';+import { useRevokedDevices } from '@/device-link/revokedDevicesStore';+import type { RemoteResourceHostTarget } from '@/device-link/remoteResources';+import { useRemoteResourceList } from './useRemoteResourceList';++const NO_TARGETS: RemoteResourceHostTarget[] = [];++/**+ * Group chats of the computers whose manifest advertises them (`useTeammateRoster().groupTargets`).+ * The list re-reads on the host's `maker:remote-resources:changed` push like every resource list.+ */+export function useBotGroupRoster(targets: readonly RemoteResourceHostTarget[], enabled: boolean) {+ const revoked = useRevokedDevices();+ const hosts = targets.length ? targets : NO_TARGETS;+ const list = useRemoteResourceList(BOT_GROUP_REMOTE_COLLECTION_ID, hosts, enabled && hosts.length > 0);+ const items = list.items.filter((row) => row.item.ref.kind === BOT_GROUP_REMOTE_RESOURCE_KIND+ && !revoked.has(row.host.deviceId) && hosts.some((host) => host.deviceId === row.host.deviceId));+ return {+ items,+ /** The section shows only when some computer supports group chats. */+ supported: hosts.length > 0,+ isOnline: (host: RemoteResourceHostTarget) => !revoked.has(host.deviceId) && list.isOnline(host),+ refresh: list.refresh,+ };+}diff --git a/apps/mobile/src/session/useHostTeammates.ts b/apps/mobile/src/session/useHostTeammates.tsnew file mode 100644index 0000000000..6693f3f6c4--- /dev/null+++ b/apps/mobile/src/session/useHostTeammates.ts@@ -0,0 +1,59 @@+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useAuth } from '@/auth/AuthContext';+import { useDeviceLink } from '@/device-link/DeviceLinkContext';+import { readRemoteResourceSnapshot } from '@/device-link/remoteResourceCache';+import {+ listRemoteCollection,+ normalizeRemoteCollectionItems,+ type HostedRemoteCollectionItem,+ type RemoteResourceHostTarget,+} from '@/device-link/remoteResources';+import { BOT_GROUP_TEAMMATES_COLLECTION_ID } from './botGroupRemote';++/**+ * Teammates of one computer for the group pickers (create, add member). A group lives on+ * one computer, so only that computer's Bots can join it. The cached roster shows at once;+ * a live read replaces it while the sheet is open. The host still validates every pick.+ */+export function useHostTeammates(host: RemoteResourceHostTarget | null, enabled: boolean) {+ const { user, accountGeneration } = useAuth();+ const { invoke, openLink } = useDeviceLink();+ const { i18n } = useTranslation();+ const deviceId = host?.deviceId ?? '';+ const deviceName = host?.deviceName ?? '';+ const scope = JSON.stringify([accountGeneration, deviceId]);+ const [state, setState] = useState<{ scope: string; rows: HostedRemoteCollectionItem[]; loading: boolean; failed: boolean }>(+ { scope, rows: [], loading: false, failed: false },+ );+ useEffect(() => {+ if (!enabled || !deviceId) return;+ let cancelled = false;+ const target = { deviceId, deviceName };+ setState((previous) => ({ scope, rows: previous.scope === scope ? previous.rows : [], loading: true, failed: false }));+ void readRemoteResourceSnapshot(user?.id ?? '').then((snapshot) => {+ if (cancelled) return;+ const cached = (snapshot.items[BOT_GROUP_TEAMMATES_COLLECTION_ID] ?? [])+ .filter((row) => row.host.deviceId === deviceId && row.item.ref.kind === 'bot');+ setState((previous) => previous.scope === scope && previous.rows.length === 0 && previous.loading+ ? { ...previous, rows: cached }+ : previous);+ });+ void (async () => {+ try {+ await openLink(deviceId);+ const response = await listRemoteCollection(invoke, target, BOT_GROUP_TEAMMATES_COLLECTION_ID, i18n.language);+ if (cancelled) return;+ const rows = normalizeRemoteCollectionItems(response, BOT_GROUP_TEAMMATES_COLLECTION_ID)+ .filter((item) => item.ref.kind === 'bot')+ .map((item) => ({ host: target, item, key: JSON.stringify([deviceId, item.ref.collectionId, item.ref.kind, item.ref.id]) }));+ setState({ scope, rows, loading: false, failed: false });+ } catch {+ if (!cancelled) setState((previous) => ({ ...previous, scope, loading: false, failed: previous.rows.length === 0 }));+ }+ })();+ return () => { cancelled = true; };+ }, [deviceId, deviceName, enabled, i18n.language, invoke, openLink, scope, user?.id]);+ const own = state.scope === scope;+ return { rows: own ? state.rows : [], loading: own && state.loading, failed: own && state.failed };+}diff --git a/apps/mobile/src/session/useTeammateRoster.ts b/apps/mobile/src/session/useTeammateRoster.tsindex 4c08696dcd..786e51ad49 100644--- a/apps/mobile/src/session/useTeammateRoster.ts+++ b/apps/mobile/src/session/useTeammateRoster.ts@@ -11,6 +11,7 @@ import { cacheRemoteResourceHome, readRemoteResourceSnapshot } from '@/device-liimport { discoverRemoteHomeCollections, remoteResourceDiscoveryTargets,type RemoteHomeCollection, type RemoteResourceHostTarget } from '@/device-link/remoteResources';import { formatRemoteError } from '@/device-link/remoteStatus';+import { hasBotGroupCollection } from './botGroupRemote';import { useRemoteResourceList } from './useRemoteResourceList';import { startBoundedStartupRead } from './mobileHomeStartup';@@ -26,9 +27,12 @@ export function useTeammateRoster(enabled = true) {const binding = `${user?.id ?? ''}:${accountGeneration}`;const ownerRef = useRef(binding); ownerRef.current = binding;const generation = useRef(0);+ // Hosts whose manifest advertises group chats (bot-group-chat.md §8); an older desktop never does.+ const lastGroupTargets = useRef<{ binding: string; targets: RemoteResourceHostTarget[] }>({ binding: '', targets: NO_TARGETS });const [discovery, setDiscovery] = useState<{- binding: string; ready: boolean; loading: boolean; targets: RemoteResourceHostTarget[]; createTargets: RemoteResourceHostTarget[]; error: string | null;- }>({ binding: '', ready: false, loading: true, targets: NO_TARGETS, createTargets: NO_TARGETS, error: null });+ binding: string; ready: boolean; loading: boolean; targets: RemoteResourceHostTarget[]; createTargets: RemoteResourceHostTarget[];+ groupTargets: RemoteResourceHostTarget[]; error: string | null;+ }>({ binding: '', ready: false, loading: true, targets: NO_TARGETS, createTargets: NO_TARGETS, groupTargets: NO_TARGETS, error: null });const discover = useCallback(async () => {const expected = ++generation.current;const current = () => ownerRef.current === binding && generation.current === expected;@@ -38,6 +42,8 @@ export function useTeammateRoster(enabled = true) {let collections: RemoteHomeCollection[] = snapshot.home;let error: string | null = null;const createTargets: RemoteResourceHostTarget[] = [];+ const previousGroupTargets = lastGroupTargets.current.binding === binding ? lastGroupTargets.current.targets : NO_TARGETS;+ let groupTargets = previousGroupTargets;try {if (status !== 'online') throw new Error(t('devices.resources.hostOffline'));const response = await readDeviceList();@@ -50,11 +56,15 @@ export function useTeammateRoster(enabled = true) {collections = collections.map((collection) => ({ ...collection,targets: collection.targets.filter((host) => targets.some((target) => target.deviceId === host.deviceId)),}));+ const answered = new Set<string>();+ const advertisingGroups = new Set<string>();collections = await discoverRemoteHomeCollections(async <T,>(deviceId: string, channel: string, args?: unknown[]) => {await openLink(deviceId);const response = await invoke<T>(deviceId, channel, args);if (channel === REMOTE_RESOURCE_MANIFEST_CHANNEL) {const manifest = response as RemoteResourceManifestResponse | null;+ answered.add(deviceId);+ if (hasBotGroupCollection(manifest)) advertisingGroups.add(deviceId);if (manifest?.collections?.some((collection) => collection.id === TEAMMATE_COLLECTION_ID&& collection.resourceKind === 'bot' && collection.actions?.some((action) => action.id === 'open-create'))) {const host = targets.find((target) => target.deviceId === deviceId);@@ -64,11 +74,16 @@ export function useTeammateRoster(enabled = true) {return response;}, targets, i18n.language, collections);if (!current()) return;+ // A host that did not answer this time keeps its groups until it answers again.+ groupTargets = targets.filter((target) => advertisingGroups.has(target.deviceId)+ || (!answered.has(target.deviceId) && previousGroupTargets.some((host) => host.deviceId === target.deviceId)));void cacheRemoteResourceHome(user?.id ?? '', collections);} catch (cause) { error = formatRemoteError(cause); }if (!current()) return;const targets = collections.find((collection) => collection.id === TEAMMATE_COLLECTION_ID && collection.resourceKind === 'bot')?.targets ?? NO_TARGETS;- setDiscovery({ binding, ready: true, loading: false, createTargets, targets: targets.filter((host) => !revoked.has(host.deviceId)), error });+ groupTargets = groupTargets.filter((host) => !revoked.has(host.deviceId));+ lastGroupTargets.current = { binding, targets: groupTargets };+ setDiscovery({ binding, ready: true, loading: false, createTargets, targets: targets.filter((host) => !revoked.has(host.deviceId)), groupTargets, error });}, [binding, i18n.language, invoke, openLink, readDeviceList, revoked, status, t, user?.id]);useFocusEffect(useCallback(() => {if (!enabled) return;@@ -85,6 +100,9 @@ export function useTeammateRoster(enabled = true) {return { ...list, items,isOnline: (host: RemoteResourceHostTarget) => ready && !revoked.has(host.deviceId) && list.isOnline(host),targets: ready ? discovery.targets : NO_TARGETS,+ /** Computers with group chats; empty until discovery ran, and for older desktops. */+ // Stable reference (revocation is applied at discovery and again to the listed rows).+ groupTargets: ready ? discovery.groupTargets : NO_TARGETS,createTargets: ready && status === 'online' ? discovery.createTargets.filter((host) => !revoked.has(host.deviceId) && list.isOnline(host)) : NO_TARGETS,authoritative: ready && !discovery.loading && !list.loading && !list.syncing && status === 'online' && !discovery.error && (!discovery.targets.length || !list.error),loading: items.length === 0 && (!ready || list.loading),diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex 16f1a27428..bf5a1d89b5 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -9,9 +9,9 @@本区块由 `scripts/design-inventory.mjs` 生成,请勿手改。重新生成:`pnpm design:inventory`;校验:`pnpm check:design-inventory`。-计数快照日期:2026-09-27。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。+计数快照日期:2026-09-28。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。-登记 surface 数:50。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。+登记 surface 数:51。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。| ID | 平台 | 标题 | 生产入口 | 可达组件 | 样式来源 | Token 数 | 裸颜色 | 裸圆角 || --- | --- | --- | --- | --- | --- | ---: | ---: | ---: |@@ -57,10 +57,11 @@| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AccountSwitcherSheet, AdaptiveWindow, AgentErrorDetails, AnchoredPullDownMenu, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, CompanionChoice, CompanionCreateNativeView, CompanionCreateNativeView.ios, CompanionHeader, CompanionImportSheet, CompanionMemoryPage, CompanionMemoryPage.ios, CompanionMessageActions, CompanionMessageCard, CompanionModelChain, CompanionNativeContent.ios, CompanionNavigationDrawer, CompanionPortraitPicker, CompanionProfileArtifacts, CompanionProfileNativeView, CompanionProfileNativeView.ios, CompanionProfileSheet, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, CompanionTaskResultCard, CompanionWorkingStatus, ComposerAttachmentTray, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetCollabView, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, FileTypeIcon, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSurface, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, LoginNativeButton, LoginNativeButton.ios, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModalContentArea, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginInvocationHeader, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, RecentMessageHistories, RemoteAccessGuide, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, RewindPreviewPanel, RunningTokenRatePopover, SentInlineAtomBody, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, SwipeableSessionRow, SwipeableSessionRow.ios, SystemNavigationBack, TaskTags, TaskTagsSheet, TeammateGenerationLabel, TeammateList, TeammatePicker, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, WorkingStatusText, [sessionId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, peerFileTransport, useLocale, useSharedTaskConfirmation | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/FileTypeIcon.tsx, apps/mobile/src/components/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/SystemNavigationBack.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AgentErrorDetails.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/CompanionChoice.tsx, apps/mobile/src/session/CompanionCreateNativeView.ios.tsx, apps/mobile/src/session/CompanionCreateNativeView.tsx, apps/mobile/src/session/CompanionHeader.tsx, apps/mobile/src/session/CompanionImportSheet.tsx, apps/mobile/src/session/CompanionMemoryPage.ios.tsx, apps/mobile/src/session/CompanionMemoryPage.tsx, apps/mobile/src/session/CompanionMessageActions.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/CompanionModelChain.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionNavigationDrawer.tsx, apps/mobile/src/session/CompanionPortraitPicker.tsx, apps/mobile/src/session/CompanionProfileArtifacts.tsx, apps/mobile/src/session/CompanionProfileNativeView.ios.tsx, apps/mobile/src/session/CompanionProfileNativeView.tsx, apps/mobile/src/session/CompanionProfileSheet.tsx, apps/mobile/src/session/CompanionSettingsRow.ios.tsx, apps/mobile/src/session/CompanionSettingsRow.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/CompanionTaskResultCard.tsx, apps/mobile/src/session/CompanionWorkingStatus.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetCollabView.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeListVisuals.tsx, apps/mobile/src/session/HomeModeSwitch.tsx, apps/mobile/src/session/HomeNewTaskButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/PromptRecommendation.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/RunningTokenRatePopover.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionResourceCards.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareImageNativeButton.ios.tsx, apps/mobile/src/session/ShareImageNativeButton.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TaskTagsSheet.tsx, apps/mobile/src/session/TeammateGenerationLabel.tsx, apps/mobile/src/session/TeammateList.tsx, apps/mobile/src/session/TeammatePicker.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/session/useSharedTaskConfirmation.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 7 | 239 | 307 || `mobile.chat.sharing` | mobile | 共享任务邀请与成员 | app/shared-session.tsx | AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, shared-session, useLocale, useSharedTaskConfirmation | apps/mobile/app/_layout.tsx, apps/mobile/app/shared-session.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/useSharedTaskConfirmation.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 206 | 66 || `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 206 | 61 |+| `mobile.companions.groups` | mobile | 伙伴群聊与分工 | app/companions/groups/[groupId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, BotGroupAvatars, BotGroupChatScreen, BotGroupComposer, BotGroupMenu, BotGroupMessageText, BotGroupPlan, BotGroupSettingsSheet, BotGroupSpeakerRow, CenteredScreen, CompanionSheet, CompanionSheet.ios, ComposerFrame, ComposerFrame.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, InteractionPanel, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PaperPlaneIcon, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, WorkingStatusText, [groupId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/groups/[groupId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/BotGroupAvatars.tsx, apps/mobile/src/session/BotGroupChatScreen.tsx, apps/mobile/src/session/BotGroupComposer.tsx, apps/mobile/src/session/BotGroupMenu.tsx, apps/mobile/src/session/BotGroupMessageText.tsx, apps/mobile/src/session/BotGroupPlan.tsx, apps/mobile/src/session/BotGroupSettingsSheet.tsx, apps/mobile/src/session/BotGroupSpeakerRow.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 206 | 114 || `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, ModalContentArea, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RenameDeviceModal, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, manage, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RenameDeviceModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 206 | 61 || `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSurface, IncomingShareBridge, LoginNativeButton, LoginNativeButton.ios, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, MobileVendorIcon, ModalContentArea, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeListVisuals.tsx, apps/mobile/src/session/HomeModeSwitch.tsx, apps/mobile/src/session/HomeNewTaskButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 206 | 117 || `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FileTypeIcon, FileTypeTile, FoldTouchpad, HomeEntryProvider, HtmlBrowserChrome, HtmlBrowserChrome.ios, HtmlFileReader, HtmlWebsiteBrowser, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, ModalContentArea, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, SystemNavigationBack, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/FileTypeIcon.tsx, apps/mobile/src/components/FileTypeTile.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SystemNavigationBack.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HtmlBrowserChrome.ios.tsx, apps/mobile/src/session/HtmlBrowserChrome.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/HtmlWebsiteBrowser.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 238 | 84 |-| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, CompanionChoice, CompanionCreateNativeView, CompanionCreateNativeView.ios, CompanionImportSheet, CompanionMemoryPage, CompanionMemoryPage.ios, CompanionModelChain, CompanionNativeContent.ios, CompanionPortraitPicker, CompanionProfileArtifacts, CompanionProfileNativeView, CompanionProfileNativeView.ios, CompanionProfileSheet, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModePanes, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSurface, IncomingShareBridge, LoginNativeButton, LoginNativeButton.ios, MobileAgentMark, MobileAgentSwitcher, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModalContentArea, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteAccessGuide, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, TeammateCreateButton, TeammateGenerationLabel, TeammateHomeScreen, TeammateList, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, WorkingStatusText, _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/CompanionChoice.tsx, apps/mobile/src/session/CompanionCreateNativeView.ios.tsx, apps/mobile/src/session/CompanionCreateNativeView.tsx, apps/mobile/src/session/CompanionImportSheet.tsx, apps/mobile/src/session/CompanionMemoryPage.ios.tsx, apps/mobile/src/session/CompanionMemoryPage.tsx, apps/mobile/src/session/CompanionModelChain.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPortraitPicker.tsx, apps/mobile/src/session/CompanionProfileArtifacts.tsx, apps/mobile/src/session/CompanionProfileNativeView.ios.tsx, apps/mobile/src/session/CompanionProfileNativeView.tsx, apps/mobile/src/session/CompanionProfileSheet.tsx, apps/mobile/src/session/CompanionSettingsRow.ios.tsx, apps/mobile/src/session/CompanionSettingsRow.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeListVisuals.tsx, apps/mobile/src/session/HomeModePanes.tsx, apps/mobile/src/session/HomeModeSwitch.tsx, apps/mobile/src/session/HomeNewTaskButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TeammateCreateButton.tsx, apps/mobile/src/session/TeammateGenerationLabel.tsx, apps/mobile/src/session/TeammateHomeScreen.tsx, apps/mobile/src/session/TeammateList.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 206 | 141 |+| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, BotGroupAvatars, BotGroupCreateSheet, BotGroupList, BotGroupMenu, CenteredScreen, CompanionChoice, CompanionCreateNativeView, CompanionCreateNativeView.ios, CompanionImportSheet, CompanionMemoryPage, CompanionMemoryPage.ios, CompanionModelChain, CompanionNativeContent.ios, CompanionPortraitPicker, CompanionProfileArtifacts, CompanionProfileNativeView, CompanionProfileNativeView.ios, CompanionProfileSheet, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModePanes, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSurface, IncomingShareBridge, LoginNativeButton, LoginNativeButton.ios, MobileAgentMark, MobileAgentSwitcher, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModalContentArea, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteAccessGuide, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, TeammateCreateButton, TeammateGenerationLabel, TeammateHomeScreen, TeammateList, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, WorkingStatusText, _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/BotGroupAvatars.tsx, apps/mobile/src/session/BotGroupCreateSheet.tsx, apps/mobile/src/session/BotGroupList.tsx, apps/mobile/src/session/BotGroupMenu.tsx, apps/mobile/src/session/CompanionChoice.tsx, apps/mobile/src/session/CompanionCreateNativeView.ios.tsx, apps/mobile/src/session/CompanionCreateNativeView.tsx, apps/mobile/src/session/CompanionImportSheet.tsx, apps/mobile/src/session/CompanionMemoryPage.ios.tsx, apps/mobile/src/session/CompanionMemoryPage.tsx, apps/mobile/src/session/CompanionModelChain.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPortraitPicker.tsx, apps/mobile/src/session/CompanionProfileArtifacts.tsx, apps/mobile/src/session/CompanionProfileNativeView.ios.tsx, apps/mobile/src/session/CompanionProfileNativeView.tsx, apps/mobile/src/session/CompanionProfileSheet.tsx, apps/mobile/src/session/CompanionSettingsRow.ios.tsx, apps/mobile/src/session/CompanionSettingsRow.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeListVisuals.tsx, apps/mobile/src/session/HomeModePanes.tsx, apps/mobile/src/session/HomeModeSwitch.tsx, apps/mobile/src/session/HomeNewTaskButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TeammateCreateButton.tsx, apps/mobile/src/session/TeammateGenerationLabel.tsx, apps/mobile/src/session/TeammateHomeScreen.tsx, apps/mobile/src/session/TeammateList.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 206 | 147 || `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 206 | 55 || `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 206 | 55 || `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, TeammateGenerationLabel, TeammateList, ThemeProvider, WorkingStatusText, [collectionId], [resourceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/TeammateGenerationLabel.tsx, apps/mobile/src/session/TeammateList.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 206 | 68 |@@ -125,6 +126,7 @@| apps/mobile/app/account-deletion.tsx | AccountDeletionScreen | `mobile.account-deletion` || apps/mobile/app/add-account.tsx | AddAccountScreen | `mobile.auth` || apps/mobile/app/companions/direct/[threadId].tsx | CompanionDirectMessages | `mobile.companions.direct` |+| apps/mobile/app/companions/groups/[groupId].tsx | BotGroupChatRoute | `mobile.companions.groups` || apps/mobile/app/devices/[deviceId].tsx | DeviceDetailScreen | `mobile.devices` || apps/mobile/app/devices/desktop/[deviceId].tsx | RemoteDesktopRoute | `mobile.remote-desktop` || apps/mobile/app/devices/index.tsx | HomeScreen | `mobile.home` |@@ -215,6 +217,7 @@ Mobile 已由 DS-7 纳入同一台账(2026-09-10 静态入口发现),保| `mobile.chat.session` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 || `mobile.chat.sharing` | unassigned | legacy | — | DS-7 发现入口,Mobile 独立阶段接管;未迁移 | 保持现状;发现问题记下一动作,本张不修视觉 || `mobile.companions.direct` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 |+| `mobile.companions.groups` | unassigned | legacy | — | DS-7 发现入口,Mobile 独立阶段接管;未迁移 | 保持现状;发现问题记下一动作,本张不修视觉 || `mobile.device-management` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 || `mobile.devices` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 || `mobile.files` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 |diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex dddeb8ae11..bb64bdb355 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -468,6 +468,20 @@ canonical 主任务时,宿主额外追加 `resourceCollectionId=teammates&reso不识别它们的旧控制端仍按普通任务打开。拼接后超过 `NOTIFY_DEEP_LINK_MAX_LENGTH` 时回退为原深链。委派的独立 Session 任务和普通任务不带这组参数。不修改 notify 帧结构、relay 或协议版本。+## 伙伴群聊手机端(Remote Resource 与群推送深链)++群聊以新的 Remote Resource collection `bot-groups`(`resourceKind: bot-group`,无 placement)接入控制端,+列表项的 `links` 以 rel `member` 指向 `teammates` 中的成员。新增可移植原语 `bot-group-chat`:主机只对声明它的+控制端在 `get` 中输出该块,`data` 为 `@cindy/maker-shared/botGroupChat` 的 `BotGroupRemoteChatData`+(主机路径置空,只给文件夹名);未声明的控制端只拿到 `markdown` 块的可读摘要。动作 id 见同文件+`BotGroupRemoteActionId`,被拒时以群聊错误码作为 registry 错误 message。变化沿用+`maker:remote-resources:changed`(collection + 该群 ref)。++分工停下时的手机推送沿用 notify 帧与 `session-needs-reply` 类别,深链为+`/companions/groups/<groupId>?deviceId=<hostDeviceId>`,`collapseId` 为 `(设备, 群)` 摘要。旧手机不识别该深链,+点开只进入 App;旧主机没有该 collection,新手机不显示群聊入口。未新增 channel、allowlist、relay 类型、+notify 类别或协议版本,服务端无需升级;Mobile 无原生 fingerprint 变更。+## 伙伴记忆远程页面与资源内搜索伙伴设置主资源(声明 `form` 的控制端)追加 `memories` list 块,入口指向 `settings:<botId>/memory`;diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex c2474729cc..825130b96d 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -1,7 +1,7 @@# 伙伴群聊-> **状态**:权威产品规则(authoritative)。第一阶段已实现;第二阶段「分工」实现中(第 7 节)。-> **读取时机**:新增或修改伙伴群聊的数据、发言编排、群专线 Session、分工(负责人、安排、分工 Session、群工作目录)、群聊界面或相关 IPC 前。+> **状态**:权威产品规则(authoritative)。第一、二阶段已实现;第三阶段手机端实现中(第 8 节)。+> **读取时机**:新增或修改伙伴群聊的数据、发言编排、群专线 Session、分工(负责人、安排、分工 Session、群工作目录)、群聊界面、手机端群聊或相关 IPC/远程资源前。> 伙伴身份、Profile、主任务与后台任务的通用契约仍以 [`cindy-bots-runtime.md`](cindy-bots-runtime.md) 为准。## 1. 定位与分期@@ -13,7 +13,7 @@| --- | --- | --- || 1 群聊基础 | 本机、同账号伙伴;建群、群里发言、@ 点名、继续讨论、停止、群设置;Desktop | 本文档 || 2 分工 | 负责人伙伴出安排、用户点开始后伙伴一步步做;群工作目录(项目文件夹或群自己的文件夹,git 项目共用一个 worktree 与分支)、每步做完停下等继续 | 第 7 节 |-| 3 手机端 | 手机查看与发言 | 待实现 |+| 3 手机端 | 手机查看与发言、分工操作、分工停下时推送 | 第 8 节 || 远期 | 跨账号的群 | 不在当前范围 |群聊涉及会话生命周期、伙伴运行时与权限,只能由 Core 承载,不做成插件。@@ -34,7 +34,7 @@- 每位成员在每个群里有一条隐藏的**群专线 Session**:`source = 'bot'`,`bot_session_links.role = 'group'`,`route_key = 'group:<groupId>'`。它与伙伴主任务共享同一个 Profile 与 Bot Home,按需在第一次轮到该伙伴发言时创建。-- 群专线 Session 不进入任务列表、伙伴主时间线、历史会话列表、未读和系统通知;它随伙伴 Profile 更新推进+- 群专线 Session 不进入任务列表、伙伴主时间线、历史会话列表、未读和系统通知(分工停下时的手机推送见 8.3);它随伙伴 Profile 更新推进Profile 版本,权限档跟随伙伴主任务。- 伙伴被删除时,其成员关系一并移除;群里已有的消息保留发言时的名字快照。- 删除群会删除群、成员与群消息,并归档各成员在该群的群专线 Session;伙伴本身、记忆与私聊不受影响。@@ -98,7 +98,7 @@## 6. 当前限制-- 仅本机、同账号伙伴;不支持设备互联的远端伙伴,也不支持手机端(第三阶段)。+- 仅同账号伙伴;群和伙伴都在同一台电脑上,不支持跨电脑、跨账号的群。手机端见第 8 节。- 群里发送纯文本,不支持附件。- 进行中的一轮只保存在内存,重启后结束;分工的安排与每步状态持久保存(见 7.6)。@@ -180,3 +180,37 @@- 应用退出或重启时进行中的一步结束,安排停在该步「没做完 · 重试」,不自动续跑。- 删除群聊:删除安排与步骤数据,归档各成员在该群的群专线与分工 Session;worktree 与分支保留。- 移出成员:它未开始的步骤在轮到时提示伙伴不可用并停下,用户可重试(换人后)或停止;伙伴本身不受影响。++## 8. 手机端(第三阶段)++手机是控制端:群、伙伴与分工都在电脑上运行,手机只查看、发言和点按钮,所有规则仍由电脑判断。++### 8.1 接入方式++- 群聊经设备互联的 Remote Resource 协议接入(collection `bot-groups`,资源类型 `bot-group`),不新增专用 IPC+ channel、推送事件或 allowlist 条目;列表、详情与动作复用 `maker:remote-resources:*`,任何变化都用+ `maker:remote-resources:changed` 让手机重读该群和列表。+- 声明 `bot-group-chat` 原语的手机拿到完整的群视图(与电脑同一份契约);旧手机只拿到可读的 Markdown 摘要。+ 电脑上的路径不离开电脑:项目文件夹只给文件夹名,安排的工作目录不下发。+- 手机可以:新建群、发言(@、@所有人、「+」安排分工)、停止、继续讨论、开始/不用了/继续/重试/结束分工、+ 开始前换人或删步骤、停下时给没做完的步骤换人、改群名/回复方式/发言方式/负责人、增删成员、删除群。+ **不能**选择或更换项目文件夹(只能在电脑上选)。+- 只有全部成员都是手机可见的伙伴(未隐藏、未归档)时,群才出现在手机上;所有动作都重新核对。+- 旧电脑没有该 collection 时,手机不显示群聊入口。++### 8.2 界面++- 伙伴页增加「群聊」分组:叠放头像、群名、最近状态(与电脑侧栏相同的分工状态)、运行中标记;可新建群聊。+- 群聊页与电脑一致:多作者时间线、安排卡、交接消息与文件名、「下一步 · 继续」「没做完 · 重试」、+ 「N 步都做完了」、正在发言/安排/做的伙伴、待确认操作内嵌;输入框支持 @ 与「+」安排分工。+- 文件在电脑上:手机只显示文件名,不在手机上打开。+- 视觉遵循 Mobile 设计规范:按钮用手机端现有的紧凑按钮(视觉轻、触控够),Light / Dark 同时实现。++### 8.3 分工停下时推送到手机++- 分工的一步做完(等继续)、没做完(等重试)或全部做完时,电脑向手机发一条推送:标题为群名,正文说明谁做完了+ 哪一步、要做什么。桌面不弹系统通知(桌面侧栏已显示状态)。+- 推送沿用现有 notify 帧(类别 `session-needs-reply`),深链为 `/companions/groups/<groupId>?deviceId=<电脑>`,+ 同一台电脑同一个群的推送在系统层合并。不认识该深链的旧手机点开只进入 App。+- 聊天里的普通接话不推送。+- 只推送手机能看到的群:与群列表同一条规则(全部成员都是手机可见的伙伴),隐藏了成员的群不推送。\ No newline at end of filediff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex fe4d20bec6..410c3f95fc 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -81,6 +81,8 @@"./botCollaboration": "./src/botCollaboration.ts","./botDirectMessage": "./src/botDirectMessage.ts","./botGroupChat": "./src/botGroupChat.ts",+ "./botGroupMentions": "./src/botGroupMentions.ts",+ "./botGroupPresentation": "./src/botGroupPresentation.ts","./botDelegation": "./src/botDelegation.ts","./botTimeline": "./src/botTimeline.ts","./remote-desktop-viewer": "./src/remote-desktop/viewerRuntime.js",diff --git a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts b/packages/maker-shared/src/__tests__/botGroupPresentation.test.tsnew file mode 100644index 0000000000..9b0e0226b8--- /dev/null+++ b/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';+import {+ botGroupComposerPlanState,+ botGroupErrorVariant,+ botGroupNoticeVariant,+ botGroupPlanFollowUp,+ isBotGroupDivisionBlocked,+} from '../botGroupPresentation.js';+import type { BotGroupErrorCode, BotGroupNoticeCode, BotGroupPlanView } from '../botGroupChat.js';++const plan = (overrides: Partial<BotGroupPlanView> = {}): BotGroupPlanView => ({+ id: 'p1', status: 'waiting', organizerBotId: 'a', organizerName: 'A', currentStep: 0, workDir: null, branch: null,+ createdAt: 1, updatedAt: 1,+ steps: [+ { position: 0, botId: 'a', botName: 'A', task: 'one', status: 'done' },+ { position: 1, botId: 'b', botName: 'B', task: 'two', status: 'pending' },+ ],+ ...overrides,+});++describe('bot group copy variants (shared by desktop and phone)', () => {+ it('speaks about a step for member notices inside a plan', () => {+ expect(botGroupNoticeVariant('member-failed', false)).toBe('memberFailed');+ expect(botGroupNoticeVariant('member-failed', true)).toBe('stepFailed');+ expect(botGroupNoticeVariant('plan-stopped', true)).toBe('planStopped');+ expect(botGroupNoticeVariant(null, true)).toBeNull();+ // Untrusted codes from a newer host fall back to the message text.+ expect(botGroupNoticeVariant('toString' as BotGroupNoticeCode, false)).toBeNull();+ });++ it('names only the refusals the user can act on', () => {+ expect(botGroupErrorVariant('PLAN_OPEN')).toBe('planOpen');+ expect(botGroupErrorVariant('INTERNAL')).toBeNull();+ expect(botGroupErrorVariant('constructor' as BotGroupErrorCode)).toBeNull();+ expect(botGroupErrorVariant(undefined)).toBeNull();+ });+});++describe('plan follow-up and composer state', () => {+ it('offers the next step after a finished one and a retry after a failed one', () => {+ expect(botGroupPlanFollowUp(plan())).toEqual({ kind: 'continue', next: plan().steps[1] });+ const failed = plan({ steps: [{ ...plan().steps[0]!, status: 'failed' }, plan().steps[1]!] });+ expect(botGroupPlanFollowUp(failed)).toEqual({ kind: 'retry', failed: failed.steps[0] });+ expect(botGroupPlanFollowUp(plan({ status: 'running' }))).toBeNull();+ });++ it('blocks a new 安排分工 while a plan runs or waits', () => {+ expect(isBotGroupDivisionBlocked(botGroupComposerPlanState(plan()))).toBe(true);+ expect(isBotGroupDivisionBlocked(botGroupComposerPlanState(plan({ status: 'proposed' })))).toBe(false);+ expect(botGroupComposerPlanState(plan())).toEqual({ kind: 'waiting', botName: 'A', stepDone: true });+ });+});diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.tsindex ec19828472..16108a6017 100644--- a/packages/maker-shared/src/botGroupChat.ts+++ b/packages/maker-shared/src/botGroupChat.ts@@ -267,6 +267,49 @@ export function isBotGroupNoReplyPrefix(text: string): boolean {return trimmed.length === 0 || BOT_GROUP_NO_REPLY_SENTINEL.startsWith(trimmed);}+// ---- Controllers (phones) — docs/product-rules/bot-group-chat.md §8 -------------++/**+ * Groups reach controllers through the Remote Resource protocol (collection below), not+ * dedicated channels. The host keeps every rule; controllers only render and invoke actions.+ */+export const BOT_GROUP_REMOTE_COLLECTION_ID = 'bot-groups';+export const BOT_GROUP_REMOTE_RESOURCE_KIND = 'bot-group';+/** Block primitive whose `data` is `BotGroupRemoteChatData`; only sent to controllers declaring it. */+export const BOT_GROUP_CHAT_PRIMITIVE = 'bot-group-chat';+/** Collection item link to each member (`teammates` resource), in member order. */+export const BOT_GROUP_MEMBER_LINK_REL = 'member';++/**+ * Remote actions. `create` is collection-level ({ name, botIds }); the others target a group:+ * `send` ({ text, mentions, clientId, division? }), `continue`, `stop`, `update`+ * ({ name?, replyMode?, speakingMode?, organizerBotId? } — never a host path),+ * `set-members` ({ botIds }), `delete`, `plan-start` / `plan-dismiss` / `plan-continue` /+ * `plan-retry` ({ planId }) and `plan-edit` ({ planId, position, action, botId? }).+ * A refused action fails with the `BotGroupErrorCode` as its message.+ */+export type BotGroupRemoteActionId =+ | 'create'+ | 'send'+ | 'continue'+ | 'stop'+ | 'update'+ | 'set-members'+ | 'delete'+ | 'plan-start'+ | 'plan-dismiss'+ | 'plan-continue'+ | 'plan-retry'+ | 'plan-edit';++/**+ * The group as a controller sees it. Host paths never leave the computer: `projectDir`+ * and every plan `workDir` are null, and `projectDirName` names the folder.+ */+export interface BotGroupRemoteChatData extends BotGroupDetail {+ projectDirName: string | null;+}+export const BOT_GROUP_CLIENT_ID_PREFIX = 'bot-group:';export const BOT_GROUP_CLIENT_ID = {diff --git a/packages/maker-shared/src/botGroupMentions.ts b/packages/maker-shared/src/botGroupMentions.tsnew file mode 100644index 0000000000..f295c84e41--- /dev/null+++ b/packages/maker-shared/src/botGroupMentions.ts@@ -0,0 +1,206 @@+/**+ * 群聊输入框里的 @ 点名:纯文本解析,不依赖 React 与 IPC。+ *+ * 输入框是普通 textarea,点名以 `@名字 ` 的形式留在正文里。发送时以正文为准重新解析+ * (手打的 `@小满` 与从候选里选的效果一致),只有「重名」这种正文分辨不了的情况,才用+ * 选择候选时记下的 botId 消歧。宿主按解析结果决定谁回答+ * (docs/product-rules/bot-group-chat.md §4.1)。+ */+import type { BotGroupMention } from './botGroupChat.js';++export interface BotGroupMentionMember {+ botId: string;+ name: string;+}++/** A mention picked from the candidate list; `label` is the text after `@`. */+export interface BotGroupTrackedMention {+ botId: string;+ label: string;+}++export interface BotGroupMentionQuery {+ /** Index of the `@`. */+ start: number;+ /** Text typed after `@`, up to the caret. */+ query: string;+}++/** 候选词最长这么多字;再长就当成普通正文,不再弹候选。 */+const MAX_MENTION_QUERY_CHARS = 32;++/** `@` 紧跟在这些字符后面时是邮箱或标识符的一部分,不是点名。 */+const WORD_BEFORE_AT = /[A-Za-z0-9._%+-]/;+const LATIN_WORD_CHAR = /[A-Za-z0-9_]/;++function isMentionStart(text: string, at: number): boolean {+ return at === 0 || !WORD_BEFORE_AT.test(text[at - 1] ?? '');+}++/**+ * 中文名后面常常直接接正文(「@小满帮我查一下」),所以名字不要求后面跟空格;+ * 只有以拉丁字母或数字结尾的名字才要求词边界,免得 `@Anna` 被当成 `@Ann`。+ */+function endsAtBoundary(label: string, next: string | undefined): boolean {+ if (next === undefined) return true;+ const last = label[label.length - 1] ?? '';+ return !(LATIN_WORD_CHAR.test(last) && LATIN_WORD_CHAR.test(next));+}++interface LabelEntry {+ label: string;+ all: boolean;+ botIds: string[];+}++function buildLabelEntries(+ members: readonly BotGroupMentionMember[],+ allLabels: readonly string[],+ tracked: readonly BotGroupTrackedMention[],+): LabelEntry[] {+ const byLabel = new Map<string, LabelEntry>();+ for (const raw of allLabels) {+ const label = raw.trim();+ if (label) byLabel.set(label, { label, all: true, botIds: [] });+ }+ const memberIds = new Set(members.map((member) => member.botId));+ const trackedByLabel = new Map<string, string[]>();+ for (const mention of tracked) {+ const label = mention.label.trim();+ if (!label || !memberIds.has(mention.botId)) continue;+ const ids = trackedByLabel.get(label) ?? [];+ if (!ids.includes(mention.botId)) ids.push(mention.botId);+ trackedByLabel.set(label, ids);+ }+ for (const member of members) {+ const label = member.name.trim();+ if (!label || byLabel.get(label)?.all) continue;+ const entry = byLabel.get(label) ?? { label, all: false, botIds: [] };+ if (!entry.botIds.includes(member.botId)) entry.botIds.push(member.botId);+ byLabel.set(label, entry);+ }+ // 重名时正文分辨不出是哪一位,才用选择候选时记下的 botId 收窄。+ for (const [label, ids] of trackedByLabel) {+ const entry = byLabel.get(label);+ if (entry && !entry.all) entry.botIds = ids;+ }+ // 最长优先:`@小满满` 不能先被 `@小满` 截走。+ return [...byLabel.values()].sort((a, b) => b.label.length - a.label.length);+}++interface MentionToken {+ start: number;+ end: number;+ entry: LabelEntry;+}++function scanMentionTokens(text: string, entries: readonly LabelEntry[]): MentionToken[] {+ const tokens: MentionToken[] = [];+ let index = text.indexOf('@');+ while (index >= 0) {+ let next = index + 1;+ if (isMentionStart(text, index)) {+ const entry = entries.find(+ (candidate) =>+ text.startsWith(candidate.label, index + 1) &&+ endsAtBoundary(candidate.label, text[index + 1 + candidate.label.length]),+ );+ if (entry) {+ const end = index + 1 + entry.label.length;+ tokens.push({ start: index, end, entry });+ next = end;+ }+ }+ index = text.indexOf('@', next);+ }+ return tokens;+}++/**+ * Resolve who a group message addresses. Mentions are re-derived from the text+ * at send time; a tracked pick only disambiguates members that share a name.+ */+export function resolveBotGroupMentions(+ text: string,+ input: {+ members: readonly BotGroupMentionMember[];+ allLabels: readonly string[];+ tracked?: readonly BotGroupTrackedMention[];+ },+): BotGroupMention {+ const entries = buildLabelEntries(input.members, input.allLabels, input.tracked ?? []);+ const memberIds = new Set(input.members.map((member) => member.botId));+ const botIds: string[] = [];+ let all = false;+ for (const token of scanMentionTokens(text, entries)) {+ if (token.entry.all) all = true;+ for (const botId of token.entry.botIds) {+ if (memberIds.has(botId) && !botIds.includes(botId)) botIds.push(botId);+ }+ }+ // 按正文里点名的先后输出:宿主直接按这个顺序轮流发言(bot-group-chat.md §4.1)。+ return { all, botIds };+}++/** The `@query` being typed right before the caret, if any. */+export function findBotGroupMentionQuery(text: string, caret: number): BotGroupMentionQuery | null {+ const before = text.slice(0, Math.max(0, Math.min(caret, text.length)));+ const at = before.lastIndexOf('@');+ if (at < 0 || !isMentionStart(before, at)) return null;+ const query = before.slice(at + 1);+ if (query.length > MAX_MENTION_QUERY_CHARS || /\s/.test(query)) return null;+ return { start: at, query };+}++/** Case-insensitive match; names starting with the query come first. */+export function filterBotGroupMentionCandidates<T extends { name: string }>(+ query: string,+ candidates: readonly T[],+): T[] {+ const needle = query.trim().toLocaleLowerCase();+ if (!needle) return [...candidates];+ const prefix: T[] = [];+ const inner: T[] = [];+ for (const candidate of candidates) {+ const name = candidate.name.toLocaleLowerCase();+ if (name.startsWith(needle)) prefix.push(candidate);+ else if (name.includes(needle)) inner.push(candidate);+ }+ return [...prefix, ...inner];+}++/** Replace `@query` (from `start` to `end`) with `@label ` and return the new caret. */+export function insertBotGroupMention(+ text: string,+ range: { start: number; end: number },+ label: string,+): { text: string; caret: number } {+ const after = text.slice(range.end);+ const inserted = after.startsWith(' ') ? `@${label}` : `@${label} `;+ const caret = range.start + inserted.length + (after.startsWith(' ') ? 1 : 0);+ return { text: text.slice(0, range.start) + inserted + after, caret };+}++export interface BotGroupTextSegment {+ text: string;+ mention: boolean;+}++/** Split message text so `@name` tokens can be shown as mention chips. */+export function splitBotGroupMentionSegments(+ text: string,+ labels: readonly string[],+): BotGroupTextSegment[] {+ const entries = [...new Set(labels.map((label) => label.trim()).filter(Boolean))]+ .sort((a, b) => b.length - a.length)+ .map((label) => ({ label, all: false, botIds: [] }));+ const segments: BotGroupTextSegment[] = [];+ let cursor = 0;+ for (const token of scanMentionTokens(text, entries)) {+ if (token.start > cursor) segments.push({ text: text.slice(cursor, token.start), mention: false });+ segments.push({ text: text.slice(token.start, token.end), mention: true });+ cursor = token.end;+ }+ if (cursor < text.length) segments.push({ text: text.slice(cursor), mention: false });+ return segments;+}diff --git a/packages/maker-shared/src/botGroupPresentation.ts b/packages/maker-shared/src/botGroupPresentation.tsnew file mode 100644index 0000000000..e0e6e71f23--- /dev/null+++ b/packages/maker-shared/src/botGroupPresentation.ts@@ -0,0 +1,269 @@+/**+ * 伙伴群聊的纯展示判定,Desktop 与手机共用(docs/product-rules/bot-group-chat.md):+ * 排序、成员名单、轮次标记与分工(安排、下一步、交接文件)的判定,以及提示 / 报错+ * 该用哪一句文案(各端按自己的 i18n 命名空间拼 key)。只依赖群聊契约,不碰 React 与 IPC。+ */+import {+ isBotGroupPlanOpen,+ type BotGroupDetail,+ type BotGroupErrorCode,+ type BotGroupMemberView,+ type BotGroupMessageView,+ type BotGroupNoticeCode,+ type BotGroupPlanStepView,+ type BotGroupPlanView,+ type BotGroupSummary,+} from './botGroupChat.js';++/** Only active members can be mentioned, speak, or keep a group sendable. */+export function isActiveBotGroupMember(member: Pick<BotGroupMemberView, 'status'>): boolean {+ return member.status === 'active';+}++/** Latest activity first, like every other chat list. */+export function sortBotGroups(groups: readonly BotGroupSummary[]): BotGroupSummary[] {+ const activityAt = (group: BotGroupSummary) =>+ Math.max(group.lastMessage?.createdAt ?? 0, group.updatedAt, group.createdAt);+ return [...groups].sort(+ (left, right) => activityAt(right) - activityAt(left) || left.id.localeCompare(right.id),+ );+}++export function botGroupMemberNames(+ members: readonly Pick<BotGroupMemberView, 'name'>[],+ separator: string,+): string {+ return members+ .map((member) => member.name.trim())+ .filter(Boolean)+ .join(separator);+}++/** Collapse whitespace so a multi-line message fits a one-line preview. */+export function botGroupPreviewLine(text: string): string {+ return text.replace(/\s+/g, ' ').trim();+}++/**+ * The only round-end that may offer 「继续讨论」: the newest one, and only while+ * the host says the round can be continued.+ */+export function continuableRoundEndId(+ messages: readonly Pick<BotGroupMessageView, 'id' | 'kind'>[],+ round: { status: 'idle' | 'running'; canContinue: boolean },+): string | null {+ if (round.status !== 'idle' || !round.canContinue) return null;+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];+ if (message?.kind === 'round-end') return message.id;+ }+ return null;+}++/** Merge an older page under the latest page, keyed by sequence. */+export function mergeBotGroupMessages(+ older: readonly BotGroupMessageView[],+ latest: readonly BotGroupMessageView[],+): BotGroupMessageView[] {+ const bySequence = new Map<number, BotGroupMessageView>();+ for (const message of older) bySequence.set(message.sequence, message);+ for (const message of latest) bySequence.set(message.sequence, message);+ return [...bySequence.values()].sort((a, b) => a.sequence - b.sequence);+}++/** Copy variant for a refused group action; null keeps the caller's own fallback. */+export type BotGroupErrorVariant =+ | 'memberLimit'+ | 'memberUnavailable'+ | 'notFound'+ | 'hostNotReady'+ | 'planOpen'+ | 'planClosed';++const ERROR_VARIANTS: ReadonlyMap<string, BotGroupErrorVariant> = new Map<BotGroupErrorCode, BotGroupErrorVariant>([+ ['MEMBER_LIMIT', 'memberLimit'],+ ['MEMBER_UNAVAILABLE', 'memberUnavailable'],+ ['NOT_FOUND', 'notFound'],+ ['HOST_NOT_READY', 'hostNotReady'],+ ['PLAN_OPEN', 'planOpen'],+ ['PLAN_CLOSED', 'planClosed'],+]);++/** Specific error copy when the host names a cause the user can act on. */+export function botGroupErrorVariant(errorCode: BotGroupErrorCode | null | undefined): BotGroupErrorVariant | null {+ return (errorCode && ERROR_VARIANTS.get(errorCode)) || null;+}++// ---- 分工 (docs/product-rules/bot-group-chat.md §7) --------------------------++/** Merge plan snapshots from an older page under the latest read; the latest wins. */+export function mergeBotGroupPlans(+ older: readonly BotGroupPlanView[],+ latest: readonly BotGroupPlanView[],+): BotGroupPlanView[] {+ const byId = new Map<string, BotGroupPlanView>();+ for (const plan of older) byId.set(plan.id, plan);+ for (const plan of latest) byId.set(plan.id, plan);+ return [...byId.values()];+}++/** The group's open plan with its steps, when the host sent it along with the detail. */+export function openBotGroupPlan(+ group: Pick<BotGroupDetail, 'openPlan' | 'plans'>,+): BotGroupPlanView | null {+ const openId = group.openPlan?.id;+ if (!openId) return null;+ const plan = group.plans.find((candidate) => candidate.id === openId);+ return plan && isBotGroupPlanOpen(plan.status) ? plan : null;+}++/** The step the host reports as current (running, being redone, or last finished / failed). */+export function currentBotGroupPlanStep(plan: BotGroupPlanView): BotGroupPlanStepView | null {+ if (plan.currentStep === null) return null;+ return plan.steps.find((step) => step.position === plan.currentStep) ?? null;+}++export type BotGroupPlanFollowUp =+ | { kind: 'continue'; next: BotGroupPlanStepView }+ | { kind: 'retry'; failed: BotGroupPlanStepView };++/**+ * What the timeline offers under a plan that stopped after a step: 「下一步 · 继续」+ * when the step finished and another one waits, 「没做完 · 重试」 when it failed.+ */+export function botGroupPlanFollowUp(plan: BotGroupPlanView | null): BotGroupPlanFollowUp | null {+ if (!plan || plan.status !== 'waiting') return null;+ const current = currentBotGroupPlanStep(plan);+ if (!current) return null;+ if (current.status === 'failed') return { kind: 'retry', failed: current };+ if (current.status !== 'done') return null;+ const index = plan.steps.indexOf(current);+ const next = plan.steps.slice(index + 1).find((step) => step.status === 'pending');+ return next ? { kind: 'continue', next } : null;+}++/** Composer copy that follows the open plan (placeholder and the 「安排分工」 gate). */+export type BotGroupComposerPlanState =+ | { kind: 'proposed' }+ | { kind: 'running'; botName: string }+ | { kind: 'waiting'; botName: string; stepDone: boolean };++export function botGroupComposerPlanState(plan: BotGroupPlanView | null): BotGroupComposerPlanState | null {+ if (!plan) return null;+ if (plan.status === 'proposed') return { kind: 'proposed' };+ const current = currentBotGroupPlanStep(plan);+ const botName = current?.botName.trim() ?? '';+ if (plan.status === 'running') return { kind: 'running', botName };+ if (plan.status === 'waiting') return { kind: 'waiting', botName, stepDone: current?.status === 'done' };+ return null;+}++/** A plan that is running or waiting blocks a new 「安排分工」 (the host answers PLAN_OPEN). */+export function isBotGroupDivisionBlocked(state: BotGroupComposerPlanState | null): boolean {+ return state?.kind === 'running' || state?.kind === 'waiting';+}++/** Copy variant for a timeline notice; plan-scoped member notices speak about a step. */+export type BotGroupNoticeVariant =+ | 'memberFailed'+ | 'memberTimeout'+ | 'memberUnavailable'+ | 'planFailed'+ | 'planStopped'+ | 'workdirUnavailable'+ | 'stepFailed'+ | 'stepTimeout'+ | 'stepUnavailable';++const NOTICE_VARIANTS: ReadonlyMap<string, BotGroupNoticeVariant> = new Map<BotGroupNoticeCode, BotGroupNoticeVariant>([+ ['member-failed', 'memberFailed'],+ ['member-timeout', 'memberTimeout'],+ ['member-unavailable', 'memberUnavailable'],+ ['plan-failed', 'planFailed'],+ ['plan-stopped', 'planStopped'],+ ['workdir-unavailable', 'workdirUnavailable'],+]);++/** Member notices inside a plan are about a step, not a chat reply. */+const STEP_NOTICE_VARIANTS: ReadonlyMap<string, BotGroupNoticeVariant> = new Map<BotGroupNoticeCode, BotGroupNoticeVariant>([+ ['member-failed', 'stepFailed'],+ ['member-timeout', 'stepTimeout'],+ ['member-unavailable', 'stepUnavailable'],+]);++export function botGroupNoticeVariant(+ code: BotGroupNoticeCode | null,+ planScoped: boolean,+): BotGroupNoticeVariant | null {+ if (!code) return null;+ return (planScoped ? STEP_NOTICE_VARIANTS.get(code) : undefined) ?? NOTICE_VARIANTS.get(code) ?? null;+}++/**+ * Absolute path of a hand-off file, or null when the entry could leave the plan's+ * work directory. The host lists files relative to `workDir` with POSIX separators;+ * the join follows the work directory's own separator so Windows paths stay native.+ */+export function botGroupPlanFilePath(workDir: string | null, file: string): string | null {+ if (!workDir || !file) return null;+ if (file.startsWith('/') || file.includes('\\') || /^[A-Za-z]:/.test(file)) return null;+ const segments = file.split('/');+ if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) return null;+ const windows = /^[A-Za-z]:[\\/]/.test(workDir) || workDir.startsWith('\\\\');+ const separator = windows ? '\\' : '/';+ const base = workDir.replace(/[\\/]+$/, '');+ return `${base}${separator}${segments.join(separator)}`;+}++export type BotGroupSidebarPlanPreview =+ /** Running treatment: the organizer is working out a plan. */+ | { kind: 'planning'; botName: string }+ /** Running treatment: a step is in progress. `step` is 1-based. */+ | { kind: 'running'; botName: string; step: number | null; total: number }+ | { kind: 'proposed'; organizerName: string }+ | { kind: 'step-done'; botName: string }+ | { kind: 'step-failed'; botName: string }+ /** Waiting, but the host did not name the step (older host or a removed step). */+ | { kind: 'waiting' };++/** Running previews take the speaking row's place (orange sparkles). */+export function isRunningBotGroupSidebarPreview(+ preview: BotGroupSidebarPlanPreview | null,+): preview is Extract<BotGroupSidebarPlanPreview, { kind: 'planning' | 'running' }> {+ return preview?.kind === 'planning' || preview?.kind === 'running';+}++/**+ * Sidebar line for the group's plan: the organizer working out a plan, a step in+ * progress, a plan waiting for 开始, or a step waiting for 继续 / 重试. Null falls back+ * to the speaking row or the latest message.+ */+export function botGroupSidebarPlanPreview(group: BotGroupSummary): BotGroupSidebarPlanPreview | null {+ const memberName = (botId: string | null) =>+ group.members.find((member) => member.botId === botId)?.name.trim() ?? '';+ if (group.planningBotId) return { kind: 'planning', botName: memberName(group.planningBotId) };+ const plan = group.openPlan;+ if (!plan) return null;+ const botName = plan.currentBotName?.trim() ?? '';+ if (plan.status === 'running') {+ return {+ kind: 'running',+ botName,+ step: plan.currentStep === null ? null : plan.currentStep + 1,+ total: plan.stepCount,+ };+ }+ if (plan.status === 'proposed') return { kind: 'proposed', organizerName: memberName(group.organizerBotId) };+ if (plan.status === 'waiting') {+ if (botName && plan.currentStepStatus === 'done') return { kind: 'step-done', botName };+ if (botName && plan.currentStepStatus === 'failed') return { kind: 'step-failed', botName };+ return { kind: 'waiting' };+ }+ return null;+}++/** Last path segment for compact labels (project folder, file chips). */+export function botGroupPathBasename(path: string): string {+ const parts = path.split(/[\\/]+/).filter(Boolean);+ return parts[parts.length - 1] ?? path;+}diff --git a/scripts/shared/design-inventory.mjs b/scripts/shared/design-inventory.mjsindex 48b6a4c473..ef43508848 100644--- a/scripts/shared/design-inventory.mjs+++ b/scripts/shared/design-inventory.mjs@@ -1403,6 +1403,7 @@ export function mobileCatalogSurfaces() {['remote-desktop', '远程桌面', ['devices/desktop/[deviceId].tsx']],['resources', '远程资源列表与详情', ['resources/[collectionId].tsx', 'resources/[collectionId]/[resourceId].tsx']],['companions.direct', '伙伴私聊回看', ['companions/direct/[threadId].tsx']],+ ['companions.groups', '伙伴群聊与分工', ['companions/groups/[groupId].tsx']],['chat.session', '任务内容与输入', ['sessions/[sessionId].tsx']],['chat.sharing', '共享任务邀请与成员', ['shared-session.tsx']],['chat.new', '新建任务', ['sessions/new.tsx']],