Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): 任务首页加入可收起的伙伴段
Chris1585102c215d
diff --git a/apps/mobile/src/__tests__/useTeammateNavigation.test.tsx b/apps/mobile/src/__tests__/useTeammateNavigation.test.tsxindex e96ea7bfa4..723ba2d39f 100644--- a/apps/mobile/src/__tests__/useTeammateNavigation.test.tsx+++ b/apps/mobile/src/__tests__/useTeammateNavigation.test.tsx@@ -57,6 +57,17 @@ describe('header/home shared navigation', () => {});expect(h.set).toHaveBeenCalledTimes(1);});+ it('opening from the task home keeps the task mode, and the section layout survives later selections', async () => {+ await render(); await act(async () => result.setTeammatesCollapsed(true));+ await act(async () => result.openTeammate(teammate, { keepMode: true }));+ expect(h.push).toHaveBeenCalledTimes(1);+ expect(result.mode).toBe('tasks'); // Back from the chat must land on the tasks, not the teammate home.+ expect(await readHomeNavigationPreferences(result.owner)).toEqual({ teammatesCollapsed: true, lastTeammate: teammateIdentity(teammate) });+ await act(async () => result.openTeammate(teammate));+ expect(await readHomeNavigationPreferences(result.owner)).toEqual({+ mode: 'teammates', teammatesCollapsed: true, lastTeammate: teammateIdentity(teammate),+ });+ });it('opens a creation receipt through the canonical resolver with one atomic preference update', async () => {await render(); await act(async () => result.openCreatedTeammate(teammate.host, teammate.item.ref));expect(h.push).toHaveBeenCalledExactlyOnceWith({ pathname: '/resources/[collectionId]/[resourceId]', params: {diff --git a/apps/mobile/src/debug/teammateVisualFixture.ts b/apps/mobile/src/debug/teammateVisualFixture.tsnew file mode 100644index 0000000000..cb891b32ba--- /dev/null+++ b/apps/mobile/src/debug/teammateVisualFixture.ts@@ -0,0 +1,59 @@+import {+ REMOTE_RESOURCE_LIST_CHANNEL,+ REMOTE_RESOURCE_MANIFEST_CHANNEL,+ REMOTE_RESOURCE_PROTOCOL_VERSION,+ type RemoteCollectionItem,+ type RemoteCollectionListResponse,+ type RemoteResourceManifestResponse,+} from '@cindy/device-link';++/**+ * `--mock` teammates (docs/dev-rules/ui-mock-data.md): the roster the teammate home and the task+ * home's teammate section read. Invented names and previews only; the three presets ship with the app.+ */+const TEAMMATES = 'teammates';+const MINUTE = 60_000;+const teammates: ReadonlyArray<{ id: string; name: string; preview: string; minutesAgo: number; avatar: RemoteCollectionItem['display']['avatar']; working?: boolean }> = [+ { id: 'visual-bot-cindy', name: 'Cindy', preview: '登录页窄窗口的错位已经修好,截图放在任务里了。', minutesAgo: 2,+ avatar: { kind: 'asset', value: 'cindy://avatar/preset/cindy', fallbackText: 'C' }, working: true },+ { id: 'visual-bot-dash', name: 'Dash', preview: 'Weekly numbers are in: sign-ups up 12%, churn flat.', minutesAgo: 25,+ avatar: { kind: 'asset', value: 'cindy://avatar/preset/dash', fallbackText: 'D' } },+ { id: 'visual-bot-lizi', name: 'LiZi', preview: '这个 PR 我看完了,留了两条建议。', minutesAgo: 90,+ avatar: { kind: 'asset', value: 'cindy://avatar/preset/lizi', fallbackText: 'L' } },+ { id: 'visual-bot-xiaoman', name: '小满', preview: '明天上午十点的会已经帮你约好。', minutesAgo: 60 * 20,+ avatar: { kind: 'emoji', value: '🌾', fallbackText: '小' } },+ { id: 'visual-bot-research', name: 'Research Assistant', preview: 'Three sources disagree on the release date; details inside.', minutesAgo: 60 * 30,+ avatar: { kind: 'text', value: 'R', fallbackText: 'R' } },+ { id: 'visual-bot-tuantuan', name: '团团', preview: '开始对话', minutesAgo: 60 * 72,+ avatar: { kind: 'emoji', value: '🐼', fallbackText: '团' } },+];++// Fixed per process: a moving clock would make every row look unread again on each read.+const FIXTURE_NOW = Date.now();++export function teammateVisualFixture(channel: string, args: unknown[], now = FIXTURE_NOW): unknown {+ if (channel === REMOTE_RESOURCE_MANIFEST_CHANNEL) return {+ protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION,+ collections: [{ id: TEAMMATES, resourceKind: 'bot', title: 'Teammates', placement: 'home-scope',+ actions: [{ id: 'open-create', label: 'New teammate' }] }],+ } satisfies RemoteResourceManifestResponse;+ const request = args[0] as { collectionId?: string } | undefined;+ if (channel !== REMOTE_RESOURCE_LIST_CHANNEL || request?.collectionId !== TEAMMATES) return undefined;+ return {+ collectionId: TEAMMATES,+ revision: 'visual-teammates-1',+ items: teammates.map((bot) => ({+ ref: { collectionId: TEAMMATES, kind: 'bot', id: bot.id },+ display: {+ title: bot.name,+ preview: bot.preview,+ timestamp: now - bot.minutesAgo * MINUTE,+ lastReplyAt: now - bot.minutesAgo * MINUTE,+ avatar: bot.avatar,+ ...(bot.working ? { generation: { phase: 'replying', startedAt: now - MINUTE } } : {}),+ },+ links: [],+ revision: 'visual-1',+ })),+ } satisfies RemoteCollectionListResponse;+}diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.tsindex 253bc486aa..16a6b31c9e 100644--- a/apps/mobile/src/debug/visualMock.ts+++ b/apps/mobile/src/debug/visualMock.ts@@ -21,6 +21,7 @@ import type {} from '@/device-link/mobileMakerTransport';import { remoteSessionStore } from '@/session/remoteSessionStore';import { pluginVisualFixture } from '@/debug/pluginVisualFixture';+import { teammateVisualFixture } from '@/debug/teammateVisualFixture';import { markdownPreviewFixture } from '@/debug/markdownPreviewFixture';import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';@@ -219,6 +220,8 @@ async function visualMockInvoke<T = unknown>(const realData = await loadVisualRealDataSnapshot();const pluginResult = realData ? undefined : pluginVisualFixture(channel, args);if (pluginResult !== undefined) return pluginResult as T;+ const teammateResult = realData ? undefined : teammateVisualFixture(channel, args);+ if (teammateResult !== undefined) return teammateResult as T;if (channel === 'local-db:task-tags:execute') {const request = args[0] as TaskTagRequest;if (request.action !== 'list' && request.action !== 'get') {diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.jsonindex 42d7c819d8..71fa7de39b 100644--- a/apps/mobile/src/i18n/locales/en/devices.json+++ b/apps/mobile/src/i18n/locales/en/devices.json@@ -588,6 +588,11 @@"viewAllRuns": "View all {{count}} runs"},"companions": {+ "section": {+ "showAll": "Show all",+ "showAllA11y": "Show all {{count}}",+ "showLess": "Show less"+ },"noCreateHosts": "No compatible computer is available. Open Cindy on a computer and sign in with the same account to create a teammate.","taskAttentionCount": "Tasks needing attention: {{count}}","unreadChatCount": "Unread chats: {{count}}",diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.jsonindex 01f3c6dcf4..9bbd1d0fcc 100644--- a/apps/mobile/src/i18n/locales/ja/devices.json+++ b/apps/mobile/src/i18n/locales/ja/devices.json@@ -588,6 +588,11 @@"viewAllRuns": "すべての実行 {{count}} 回を表示"},"companions": {+ "section": {+ "showAll": "すべて表示",+ "showAllA11y": "すべて表示({{count}})",+ "showLess": "閉じる"+ },"noCreateHosts": "対応するコンピュータを利用できません。パソコンで Cindy を開き、同じアカウントでログインするとチームメイトを新規作成できます。","taskAttentionCount": "確認が必要なタスク:{{count}}","unreadChatCount": "未読のチャット:{{count}}",diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.jsonindex 5fbadf8ba3..6c45a98d6e 100644--- a/apps/mobile/src/i18n/locales/ko/devices.json+++ b/apps/mobile/src/i18n/locales/ko/devices.json@@ -588,6 +588,11 @@"viewAllRuns": "실행 {{count}}회 모두 보기"},"companions": {+ "section": {+ "showAll": "모두 보기",+ "showAllA11y": "모두 보기 ({{count}})",+ "showLess": "접기"+ },"noCreateHosts": "사용 가능한 호환 컴퓨터가 없습니다. 컴퓨터에서 Cindy를 열고 같은 계정으로 로그인하면 팀원을 새로 만들 수 있습니다.","taskAttentionCount": "확인이 필요한 작업: {{count}}","unreadChatCount": "읽지 않은 채팅: {{count}}",diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.jsonindex be020401ef..f2b4e48342 100644--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json@@ -588,6 +588,11 @@"viewAllRuns": "查看全部 {{count}} 次运行"},"companions": {+ "section": {+ "showAll": "显示全部",+ "showAllA11y": "显示全部 {{count}} 位",+ "showLess": "收起"+ },"noCreateHosts": "当前没有可用的兼容电脑。在电脑上打开 Cindy 并登录同一账号后即可新建伙伴。","taskAttentionCount": "{{count}} 个任务待关注","unreadChatCount": "{{count}} 段对话未读",diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.jsonindex 5cf08b0a60..eccd65cd3c 100644--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json@@ -588,6 +588,11 @@"viewAllRuns": "檢視全部 {{count}} 次執行"},"companions": {+ "section": {+ "showAll": "顯示全部",+ "showAllA11y": "顯示全部 {{count}} 位",+ "showLess": "收起"+ },"noCreateHosts": "目前沒有可用的相容電腦。在電腦上開啟 Cindy 並登入同一帳號後即可新建夥伴。","taskAttentionCount": "{{count}} 個任務待關注","unreadChatCount": "{{count}} 段對話未讀",diff --git a/apps/mobile/src/session/BotGroupAvatars.tsx b/apps/mobile/src/session/BotGroupAvatars.tsxindex f684de5600..7b24a45e6b 100644--- a/apps/mobile/src/session/BotGroupAvatars.tsx+++ b/apps/mobile/src/session/BotGroupAvatars.tsx@@ -1,6 +1,6 @@/*** 群的身份标记(对照桌面 BotGroupAvatars.tsx):双人斜向叠放,三人以上圆形聚拢,最多前五位。- * 列表行 44 框、聊天顶栏 32 框;第一位始终在最前层。每个头像仍是 RemoteCompanionAvatar;叠放处用与+ * 列表行 44 框、任务首页头像条 56 框、聊天顶栏 32 框;第一位始终在最前层。每个头像仍是 RemoteCompanionAvatar;叠放处用与* 底色同色的 2pt 描边隔开,不引入阴影或新 token。头像与名字取伙伴列表缓存(只用于显示),* 缓存里没有时退回群里带来的名字与头像字段。*/@@ -35,8 +35,8 @@ 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;-/** List rows (44 box, two 30 avatars) and chat headers (32 box, two 22 avatars). */-const DUO_SIZES = { row: { box: 44, avatar: 30 }, header: { box: 32, avatar: 22 } } as const;+/** List rows (44 box, two 30 avatars), the task home's avatar strip (56, two 38) and chat headers (32, two 22). */+const DUO_SIZES = { row: { box: 44, avatar: 30 }, strip: { box: 56, avatar: 38 }, header: { box: 32, avatar: 22 } } as const;/** Separates overlapped avatars; the same 2pt ring as the teammate connection dot. */const STACK_RING = 2;diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsxindex 2dc5eb6e4d..4b046b40ae 100644--- a/apps/mobile/src/session/HomeSurface.tsx+++ b/apps/mobile/src/session/HomeSurface.tsx@@ -71,6 +71,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context';import { useTranslation } from 'react-i18next';import type { TFunction } from 'i18next';import { useAuth } from '@/auth/AuthContext';+import { HomeTeammatesSection } from './HomeTeammatesSection';import { createDisclosureListCell, DisclosureGroupView, DisclosureItem, ListDisclosureScope, useDisclosurePrepare, useListDisclosureTransition } from './listDisclosureTransition';import { useGuardedPush } from '@/utils/useGuardedPush';import { useHomeMenuFadeTiming } from '@/session/homeMenuFadeTiming';@@ -2959,7 +2960,13 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSysrestoreListPosition();}}sections={sections}- ListHeaderComponent={sharedRows.length > 0 ? <DisclosureItem clip style={styles.projectGroup} testID="home.sharedGroup">+ ListHeaderComponent={<>+ {embedded ? null : <HomeTeammatesSection active={active}+ visible={!searchQuery.trim() && indexedSearch.activeFilterCount === 0 && statusFilter !== 'archived' && !showRemoteGuide}+ // Shared group and project blocks draw their own full-width top line.+ showFooter={sharedRows.length === 0 && !isBlockHomeRow(sections[0]?.data[0])}+ runDisclosure={runDisclosure} prepareDisclosure={prepareListDisclosure} />}+ {sharedRows.length > 0 ? <DisclosureItem clip style={styles.projectGroup} testID="home.sharedGroup"><PressableaccessibilityRole="button"accessibilityLabel={t('sharedTask.title')}@@ -3021,6 +3028,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys</View></Pressable>; })}</DisclosureItem>}</DisclosureItem> : null}+ </>}style={styles.homeList}keyExtractor={(item) => item.key}// A grouped row contains its preview children. Twelve such rows candiff --git a/apps/mobile/src/session/HomeTeammatesSection.tsx b/apps/mobile/src/session/HomeTeammatesSection.tsxnew file mode 100644index 0000000000..84dd6246a8--- /dev/null+++ b/apps/mobile/src/session/HomeTeammatesSection.tsx@@ -0,0 +1,251 @@+/**+ * 任务首页顶部的「伙伴」段(对照桌面 TeammatesSection.tsx 与 2026-10-24 手机「A+B 合一」定稿):+ * 展开 = 伙伴行(与伙伴页同一个 CompanionListRow,默认 3 位,多了「显示全部」);+ * 收起 = 段头 + 56pt 头像条(名字 12/18,可横滑,最后一格新建)。收起状态按账号记住。+ * 伙伴与群聊按最近活动混排;不跟随顶栏的电脑范围筛选(与桌面一致)。点开伙伴不切换首页模式,+ * 返回仍回到任务。只在首页(有共享伙伴名册)出现;没有伙伴也没有能新建的电脑时整段不显示。+ */+import { useCallback, useEffect, useMemo, useState, useSyncExternalStore, type ReactElement } from 'react';+import { Keyboard, Pressable, ScrollView, StyleSheet, View } from 'react-native';+import { useIsFocused } from 'expo-router';+import { useTranslation } from 'react-i18next';+import { ChevronDown, ChevronRight, ChevronUp, Plus, UsersRound } from 'lucide-react-native';+import { resolveRemoteText } from '@cindy/device-link';+import { useAuth } from '@/auth/AuthContext';+import { Text } from '@/components/AppText';+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';+import { RemoteCompanionAvatar } from '@/components/RemoteCompanionAvatar';+import { CLOUD_ROW_REVISION, cloudActorForRow, cloudCompanionRows } from '@/chat/cloudCompanion';+import { useCloudCompanionHome } from '@/chat/useCloudCompanion';+import { isRemoteResourceUnread, remoteResourceCacheRevision, subscribeRemoteResourceCache } from '@/device-link/remoteResourceCache';+import type { HostedRemoteCollectionItem, RemoteResourceHostTarget } from '@/device-link/remoteResources';+import { useGuardedPush } from '@/utils/useGuardedPush';+import { useStableValue } from '@/utils/useStableValue';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';+import { BotGroupDuoAvatar, useBotGroupIdentities } from './BotGroupAvatars';+import { OFFLINE_AVATAR_OPACITY } from './BotGroupList';+import { botGroupMemberLinks } from './botGroupRemote';+import { botGroupRoute } from './botGroupNavigation';+import { COMPANION_ROW_AVATAR_SIZE, COMPANION_ROW_DOT_SIZE } from './CompanionListRow';+import { CompanionPresenceRing } from './CompanionPresenceRing';+import { homeListStyles } from './HomeListVisuals';+import { useHomeRoster } from './HomeUnreadContext';+import { DisclosureItem } from './listDisclosureTransition';+import { TeammateCreateButton } from './TeammateCreateButton';+import { useTeammateEntries, useTeammateRowRenderer, type TeammateListEntry } from './TeammateList';+import { cloudCompanionRoute } from './teammateNavigation';+import { useTeammateNavigation } from './useTeammateNavigation';++/** Desktop previews five in a 260px sidebar; three keeps the first screen of tasks on a phone. */+export const HOME_TEAMMATE_PREVIEW_LIMIT = 3;+/** Strip avatar: the row's 44 grows to the teammate-home empty presets' 56 when the section folds. */+const STRIP_AVATAR_SIZE = 56;+/** One strip cell: the avatar plus 4pt on each side, so a 12/18 name fits under it. */+const STRIP_CELL_WIDTH = STRIP_AVATAR_SIZE + spacing.sm;+const SHOW_ALL_ROW_HEIGHT = 48;+const ADD_ROW_HEIGHT = 64;++export function HomeTeammatesSection({ active, visible, showFooter, runDisclosure, prepareDisclosure }: {+ /** The tasks pane is the visible home pane. */+ active: boolean;+ /** Hidden while searching or browsing archived tasks; the hooks stay mounted. */+ visible: boolean;+ /** Full-width hairline under the section, unless the next block draws its own top line. */+ showFooter: boolean;+ runDisclosure(apply: () => void): void;+ prepareDisclosure(): void;+}) {+ const shared = useHomeRoster();+ if (!shared) return null;+ return <SectionContent shared={shared} active={active} visible={visible} showFooter={showFooter}+ runDisclosure={runDisclosure} prepareDisclosure={prepareDisclosure} />;+}++function SectionContent({ shared, active, visible, showFooter, runDisclosure, prepareDisclosure }: {+ shared: NonNullable<ReturnType<typeof useHomeRoster>>;+ active: boolean; visible: boolean; showFooter: boolean;+ runDisclosure(apply: () => void): void; prepareDisclosure(): void;+}) {+ const { t, i18n } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const list = useThemedStyles(homeListStyles);+ const push = useGuardedPush();+ const navigation = useTeammateNavigation();+ const focused = useIsFocused() && active;+ const { roster, groups } = shared;+ const cloud = useCloudCompanionHome(focused && visible);+ // Same row identity as the teammate home (cloud-companions.md): one row per companion.+ const items = useMemo(() => cloud.supported ? cloudCompanionRows(roster.items, cloud.actors, cloud.deviceNames) : roster.items,+ [cloud.actors, cloud.deviceNames, cloud.supported, roster.items]);+ const listedCompanions = roster.items.map(row => `${row.key}\t${row.item.revision}`).sort().join('\n');+ const refreshCloud = cloud.refresh;+ useEffect(() => { if (cloud.supported) void refreshCloud(); }, [cloud.supported, listedCompanions, refreshCloud]);+ const cloudActor = (row: HostedRemoteCollectionItem) => cloud.supported && row.item.revision === CLOUD_ROW_REVISION ? cloudActorForRow(cloud.actors, row) : null;+ const quietPresence = (row: HostedRemoteCollectionItem) => cloud.supported && !!cloudActorForRow(cloud.actors, row);+ const showGroups = groups.supported || groups.items.length > 0;+ const entries = useTeammateEntries(items, showGroups ? groups.items : undefined);+ const openTeammate = (row: HostedRemoteCollectionItem) => {+ const actor = cloudActor(row);+ if (actor) { Keyboard.dismiss(); push(cloudCompanionRoute(row, actor.id, i18n.language)); }+ else void navigation.openTeammate(row, { keepMode: true });+ };+ const openGroup = (row: HostedRemoteCollectionItem) => { Keyboard.dismiss(); push(botGroupRoute(row.host, row.item.ref.id)); };+ const renderRow = useTeammateRowRenderer({+ items, isOnline: roster.isOnline, connectionState: roster.connectionState, quietPresence, onSelect: openTeammate,+ groups: showGroups ? { items: groups.items, isOnline: groups.isOnline, onSelect: openGroup } : undefined,+ });+ // The store answer is the account's choice; the local copy flips inside the disclosure window+ // and never carries over to another account.+ const [local, setLocal] = useState<{ owner: string; collapsed: boolean } | null>(null);+ const owner = navigation.owner;+ const collapsed = local?.owner === owner ? local.collapsed : navigation.teammatesCollapsed;+ const [showAll, setShowAll] = useState(false);+ const setTeammatesCollapsed = navigation.setTeammatesCollapsed;+ const toggleCollapsed = useCallback(() => {+ const next = !collapsed;+ runDisclosure(() => { setLocal({ owner, collapsed: next }); if (next) setShowAll(false); });+ void setTeammatesCollapsed(next);+ }, [collapsed, owner, runDisclosure, setTeammatesCollapsed]);+ const createTargets = useStableValue(roster.createTargets, sameHosts);+ const groupCreateTargets = useStableValue(roster.groupTargets.filter(groups.isOnline), sameHosts);+ const canCreate = createTargets.length > 0 || groupCreateTargets.length > 0;+ // A first read with nothing cached stays out of the way instead of flashing an empty section.+ if (!visible || (!entries.length && (!canCreate || roster.loading))) return null;+ const title = t('devices.companions.title');+ const create = (trigger: (press: () => void, label: string) => ReactElement) => canCreate+ ? <TeammateCreateButton targets={createTargets} groupTargets={groupCreateTargets} preferredDeviceId={navigation.lastTeammate?.deviceId}+ onCreated={(host, ref) => { void navigation.openCreatedTeammate(host, ref, { keepMode: true }); }}+ onGroupCreated={(host, groupId) => push(botGroupRoute(host, groupId))} trigger={trigger} />+ : null;+ const preview = entries.slice(0, HOME_TEAMMATE_PREVIEW_LIMIT);+ const extra = entries.slice(HOME_TEAMMATE_PREVIEW_LIMIT);+ const hasMore = extra.length > 0;+ return <DisclosureItem clip testID="home.teammates">+ <View style={styles.header}>+ <Pressable accessibilityRole="button" accessibilityState={{ expanded: !collapsed }}+ accessibilityLabel={t(collapsed ? 'devices.list.a11y.expand' : 'devices.list.a11y.collapse', { title })}+ onPress={toggleCollapsed} onPressIn={prepareDisclosure}+ style={({ pressed }) => [list.projectRow, styles.headerToggle, pressed && mobileInteractionStyles.pressed]} testID="home.teammatesHeader">+ {collapsed+ ? <ChevronRight color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />+ : <ChevronDown color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />}+ <UsersRound color={colors.textSecondary} size={iconSize.action} strokeWidth={iconStroke.thin} />+ <Text style={[list.projectTitle, styles.headerTitle]} numberOfLines={1}>{title}</Text>+ {collapsed || !entries.length ? null : <Text style={[list.projectCount, styles.count]} numberOfLines={1}>{entries.length}</Text>}+ </Pressable>+ {/* Folded, the strip's last cell is the create entry; the header keeps only one. */}+ {collapsed || !entries.length ? null : create((press, label) => <Pressable accessibilityRole="button" accessibilityLabel={label}+ onPress={press} hitSlop={spacing.xs} style={({ pressed }) => [styles.headerAdd, pressed && mobileInteractionStyles.pressed]} testID="home.teammatesCreate">+ <Plus color={colors.textSecondary} size={iconSize.action} strokeWidth={iconStroke.regular} />+ </Pressable>)}+ </View>+ {!entries.length ? <DisclosureItem exit>{create((press, label) => <Pressable accessibilityRole="button" accessibilityLabel={label} onPress={press}+ style={({ pressed }) => [styles.addRow, pressed && mobileInteractionStyles.pressed]} testID="home.teammatesAdd">+ <View style={[styles.addCircle, styles.addCircleRow]}><Plus color={colors.textSecondary} size={iconSize.action} strokeWidth={iconStroke.regular} /></View>+ <Text style={styles.addText} numberOfLines={1}>{t('devices.companions.createTeammate')}</Text>+ </Pressable>)}</DisclosureItem>+ : collapsed ? <DisclosureItem exit>+ <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.strip} testID="home.teammatesStrip">+ {entries.map(entry => <StripCell key={`${entry.kind}:${entry.row.key}`} entry={entry}+ online={entry.kind === 'group' ? groups.isOnline(entry.row.host) : roster.isOnline(entry.row.host)}+ connected={entry.kind === 'bot' ? (roster.connectionState ? roster.connectionState(entry.row.host) : roster.isOnline(entry.row.host)) : null}+ quiet={entry.kind === 'bot' && quietPresence(entry.row)}+ onPress={() => entry.kind === 'group' ? openGroup(entry.row) : openTeammate(entry.row)} />)}+ {create((press, label) => <Pressable accessibilityRole="button" accessibilityLabel={label} onPress={press}+ style={({ pressed }) => [styles.cell, pressed && mobileInteractionStyles.pressed]} testID="home.teammatesStripCreate">+ <View style={[styles.addCircle, styles.addCircleStrip]}><Plus color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} /></View>+ <View style={styles.cellNameSpace} />+ </Pressable>)}+ </ScrollView>+ </DisclosureItem>+ : <DisclosureItem exit>+ {preview.map((entry, index) => renderRow(entry, !hasMore && index === preview.length - 1))}+ {hasMore && showAll ? <DisclosureItem exit>{extra.map(entry => renderRow(entry, false))}</DisclosureItem> : null}+ {hasMore ? <Pressable accessibilityRole="button" accessibilityState={{ expanded: showAll }}+ accessibilityLabel={showAll ? t('devices.companions.section.showLess') : t('devices.companions.section.showAllA11y', { count: entries.length })}+ onPress={() => runDisclosure(() => setShowAll(value => !value))} onPressIn={prepareDisclosure}+ style={({ pressed }) => [styles.moreRow, pressed && mobileInteractionStyles.pressed]} testID="home.teammatesShowAll">+ <Text style={styles.moreText} numberOfLines={1}>{t(showAll ? 'devices.companions.section.showLess' : 'devices.companions.section.showAll')}</Text>+ {showAll ? null : <Text style={styles.moreCount} numberOfLines={1}>{entries.length}</Text>}+ {showAll+ ? <ChevronUp color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.medium} />+ : <ChevronDown color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.medium} />}+ </Pressable> : null}+ </DisclosureItem>}+ {showFooter ? <View style={styles.footer} /> : null}+ </DisclosureItem>;+}++function StripCell({ entry, online, connected, quiet, onPress }: {+ entry: TeammateListEntry; online: boolean; connected: boolean | null; quiet: boolean; onPress(): void;+}) {+ const { t, i18n } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ const { user } = useAuth();+ const identityFor = useBotGroupIdentities(entry.row.host.deviceId);+ useSyncExternalStore(subscribeRemoteResourceCache, remoteResourceCacheRevision);+ const { row } = entry;+ const display = row.item.display;+ const title = resolveRemoteText(display.title, i18n.language);+ const unread = isRemoteResourceUnread(user?.id ?? '', row.host.deviceId, row.item.ref.id, display.lastReplyAt,+ entry.kind === 'group' ? row.lastReplySequence : undefined);+ const working = online && !!display.generation;+ const group = entry.kind === 'group';+ const dimmed = group ? !online : connected === false && !quiet;+ const offline = dimmed ? t('devices.resources.hostOffline') : '';+ return <Pressable accessibilityRole="button" disabled={group && !online} accessibilityState={{ disabled: group && !online }}+ accessibilityLabel={[title, offline, working ? t('groupChat.list.running') : '', unread ? t('devices.companions.unread') : ''].filter(Boolean).join(', ')}+ onPress={onPress} style={({ pressed }) => [styles.cell, pressed && mobileInteractionStyles.pressed]}+ testID={`home.teammatesStrip.${group ? 'group' : 'bot'}.${row.host.deviceId}.${row.item.ref.id}`}>+ <View style={styles.cellAvatar}>+ <View style={dimmed ? { opacity: OFFLINE_AVATAR_OPACITY } : undefined}>+ {group+ ? <BotGroupDuoAvatar deviceId={row.host.deviceId} variant="strip" online={online} working={working}+ members={botGroupMemberLinks(row.item, i18n.language).map(member =>+ identityFor(member.botId, member.label, row.groupMembers?.find(identity => identity.botId === member.botId)))} />+ : <RemoteCompanionAvatar avatar={display.avatar} deviceId={row.host.deviceId} name={title} online={connected === true} size={STRIP_AVATAR_SIZE} framed />}+ </View>+ {group ? null : <CompanionPresenceRing active={working} />}+ {unread ? <View style={styles.unreadRing} testID="home.teammatesStrip.unread"><View style={styles.unreadDot} /></View> : null}+ </View>+ <Text style={[styles.cellName, unread && styles.cellNameUnread]} numberOfLines={1}>{title}</Text>+ </Pressable>;+}++function sameHosts(a: readonly RemoteResourceHostTarget[], b: readonly RemoteResourceHostTarget[]): boolean {+ return a.length === b.length && a.every((host, index) =>+ host.deviceId === b[index].deviceId && host.deviceName === b[index].deviceName);+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ header: { flexDirection: 'row', alignItems: 'center', backgroundColor: colors.surface },+ headerToggle: { flex: 1 },+ headerTitle: { flex: 0, flexShrink: 1 },+ count: { flex: 1 },+ // 44 target whose glyph sits on the row's 16pt right edge (36 + hitSlop 4 each side).+ headerAdd: { width: 36, height: 36, marginRight: spacing.sm, alignItems: 'center', justifyContent: 'center', borderRadius: radius.pill },+ strip: { flexDirection: 'row', gap: spacing.sm, paddingHorizontal: spacing.lg, paddingBottom: spacing.md },+ cell: { width: STRIP_CELL_WIDTH, alignItems: 'center', gap: spacing.xs, paddingVertical: spacing.xs, borderRadius: radius.container },+ cellAvatar: { width: STRIP_AVATAR_SIZE, height: STRIP_AVATAR_SIZE },+ cellName: { width: STRIP_CELL_WIDTH, color: colors.textSecondary, fontSize: typeScale.caption, lineHeight: lineHeight.caption,+ fontWeight: fontWeight.regular, textAlign: 'center' },+ cellNameUnread: { color: colors.textPrimary, fontWeight: fontWeight.medium },+ cellNameSpace: { height: lineHeight.caption },+ // The row's 10pt unread dot in a 2pt page-colored ring (CompanionPresenceDot geometry).+ unreadRing: { position: 'absolute', right: 0, bottom: 0, padding: 2, borderRadius: radius.pill, backgroundColor: colors.surface },+ unreadDot: { width: COMPANION_ROW_DOT_SIZE, height: COMPANION_ROW_DOT_SIZE, borderRadius: radius.pill, backgroundColor: colors.botUnread },+ addCircle: { borderRadius: radius.pill, borderWidth: 1, borderStyle: 'dashed', borderColor: colors.borderStrong, alignItems: 'center', justifyContent: 'center' },+ addCircleStrip: { width: STRIP_AVATAR_SIZE, height: STRIP_AVATAR_SIZE },+ addCircleRow: { width: COMPANION_ROW_AVATAR_SIZE, height: COMPANION_ROW_AVATAR_SIZE },+ addRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, height: ADD_ROW_HEIGHT, paddingLeft: spacing.lg, paddingRight: spacing.lg },+ addText: { flexShrink: 1, color: colors.textSecondary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.regular },+ // Text column of the rows above (16 inset + 44 avatar + 12 gap).+ moreRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs, height: SHOW_ALL_ROW_HEIGHT,+ paddingLeft: spacing.lg + COMPANION_ROW_AVATAR_SIZE + spacing.md, paddingRight: spacing.lg },+ moreText: { flexShrink: 1, color: colors.textSecondary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.regular },+ moreCount: { color: colors.textTertiary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.regular,+ fontVariant: ['tabular-nums'] },+ footer: { backgroundColor: colors.border, height: StyleSheet.hairlineWidth },+});diff --git a/apps/mobile/src/session/TeammateCreateButton.tsx b/apps/mobile/src/session/TeammateCreateButton.tsxindex 0e3e4c719f..26db789727 100644--- a/apps/mobile/src/session/TeammateCreateButton.tsx+++ b/apps/mobile/src/session/TeammateCreateButton.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from 'react';+import { useEffect, useRef, useState, type ReactElement } from 'react';import { Alert } from 'react-native';import { Stack } from 'expo-router';import { nativeToolbarMenuItems } from '@/platform/chrome/nativeToolbarMenuItems';@@ -25,8 +25,10 @@ type Choice = { kind: CreateKind; host: RemoteResourceHostTarget };* 伙伴页顶栏的「+」。支持群聊时是一个菜单:新建伙伴 / 新建群聊(多台电脑时再选电脑);* 旧版电脑不支持群聊时保持原来的直接新建伙伴。表单关闭后才回报创建结果,避免两个 Modal 叠加。*/-export function TeammateCreateButton({ targets, groupTargets = [], preferredDeviceId, onCreated, onGroupCreated, appearance = 'glass' }: {+export function TeammateCreateButton({ targets, groupTargets = [], preferredDeviceId, onCreated, onGroupCreated, appearance = 'glass', trigger }: {targets: readonly RemoteResourceHostTarget[];+ /** Replaces the glass button (the task home's teammate section); menus and sheets stay the same. */+ trigger?(press: () => void, label: string): ReactElement;/** `cta`: the empty list's primary button; it only creates a teammate. */appearance?: 'glass' | 'cta' | 'toolbar';/** Online computers that support group chats; empty keeps the single-purpose button. */@@ -37,10 +39,10 @@ export function TeammateCreateButton({ targets, groupTargets = [], preferredDevi}) {const { accountGeneration } = useAuth();// Account changes discard both native menu selections and dismissal receipts.- return <CreateButton key={accountGeneration} {...{ targets, groupTargets, preferredDeviceId, onCreated, onGroupCreated, appearance }} account={accountGeneration} />;+ return <CreateButton key={accountGeneration} {...{ targets, groupTargets, preferredDeviceId, onCreated, onGroupCreated, appearance, trigger }} account={accountGeneration} />;}-function CreateButton({ targets, groupTargets = [], preferredDeviceId, onCreated, onGroupCreated, appearance, account }: Parameters<typeof TeammateCreateButton>[0] & { account: number }) {+function CreateButton({ targets, groupTargets = [], preferredDeviceId, onCreated, onGroupCreated, appearance, trigger: customTrigger, account }: Parameters<typeof TeammateCreateButton>[0] & { account: number }) {const { t } = useTranslation();const { colors } = useTheme();const { accountGeneration } = useAuth();@@ -88,7 +90,7 @@ function CreateButton({ targets, groupTargets = [], preferredDeviceId, onCreatedelse if (!needsMenu) start('bot', targets[0]!.deviceId);else if (cta || !usesNativePullDownMenu()) setChoosing(true);};- const button = cta+ const button = customTrigger && !cta ? customTrigger(press, label) : cta? <MainWindowActionButton action={{ label: botLabel, tone: 'primary', onPress: press, testID: 'teammates.emptyCreate' }} />: <HomeHeaderGlassButton accessibilityLabel={label} testID="teammates.create" onPress={press}><Plus color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />diff --git a/apps/mobile/src/session/TeammateList.tsx b/apps/mobile/src/session/TeammateList.tsxindex 8757bcb7fb..9f2e51078f 100644--- a/apps/mobile/src/session/TeammateList.tsx+++ b/apps/mobile/src/session/TeammateList.tsx@@ -73,8 +73,6 @@ export interface TeammateListProps {scrollInsetProps?: Pick<ScrollViewProps, 'automaticallyAdjustsScrollIndicatorInsets' | 'contentInsetAdjustmentBehavior'>;}-type ListEntry = { kind: 'bot' | 'group'; row: HostedRemoteCollectionItem };-function conversationSessionId(row: HostedRemoteCollectionItem): string | null {const target = row.item.links.find(({ rel, target: link }) => rel === 'conversation' && link.kind === 'session')?.target;return target?.kind === 'session' ? target.sessionId : null;@@ -90,26 +88,27 @@ function useAwaitingSessions(items: readonly HostedRemoteCollectionItem[]): Readreturn useMemo(() => new Set(key ? key.split('\u0000') : []), [key]);}-/** Identity list shared by home (with group chats) and the collection route. No host headings. */-export function TeammateList({ items, loading, refreshing, error, isOnline, connectionState, quietPresence, onRefresh, onSelect,- embedded = false, autoFocusSearch = false, onInteract, groups, emptyAction, scrollInsetProps, topInset, notice }: TeammateListProps) {- const { t, i18n } = useTranslation();- const { user } = useAuth();- const { colors } = useTheme();- const styles = useThemedStyles(makeStyles);- const now = useMinuteNow();- const listRef = useRef<FlatList<ListEntry>>(null);- // The notice sits in the list header; a kept-alive list may be scrolled past it when it appears.- const showsNotice = !!notice;- useEffect(() => { if (showsNotice) listRef.current?.scrollToOffset({ offset: 0, animated: true }); }, [showsNotice]);- const [query, setQuery] = useState('');- const awaiting = useAwaitingSessions(items);- const entries = useMemo<ListEntry[]>(() => {+export type TeammateListEntry = { kind: 'bot' | 'group'; row: HostedRemoteCollectionItem };++/** Teammates and (home only) group chats, mixed by latest activity and filtered by the same search. */+export function useTeammateEntries(items: readonly HostedRemoteCollectionItem[], groups: readonly HostedRemoteCollectionItem[] | undefined, query = '') {+ const { i18n } = useTranslation();+ return useMemo<TeammateListEntry[]>(() => {const bots = orderedTeammates(items, query, i18n.language).map((row) => ({ kind: 'bot' as const, row }));if (!groups) return bots;- const chats = orderedBotGroups(groups.items, query, i18n.language).map((row) => ({ kind: 'group' as const, row }));+ const chats = orderedBotGroups(groups, query, i18n.language).map((row) => ({ kind: 'group' as const, row }));return [...bots, ...chats].sort((a, b) => (b.row.item.display.timestamp ?? 0) - (a.row.item.display.timestamp ?? 0));}, [groups, items, query, i18n.language]);+}++type TeammateRowOptions = Pick<TeammateListProps, 'items' | 'isOnline' | 'connectionState' | 'quietPresence' | 'onSelect' | 'groups'>;++/** The teammate / group row, shared by the roster and the task home's teammate section. */+export function useTeammateRowRenderer({ items, isOnline, connectionState, quietPresence, onSelect, groups }: TeammateRowOptions) {+ const { t, i18n } = useTranslation();+ const { user } = useAuth();+ const now = useMinuteNow();+ const awaiting = useAwaitingSessions(items);const duplicateNames = useMemo(() => {const names = new Map<string, number>();for (const row of items) {@@ -118,50 +117,6 @@ export function TeammateList({ items, loading, refreshing, error, isOnline, conn}return names;}, [items, i18n.language]);- const searchLabel = t(groups ? 'devices.companions.searchWithGroups' : 'devices.companions.search');- const errorKey = error === 'CHAT_ENDPOINT_UNAVAILABLE' ? 'groupChat.server.endpointUnavailable'- : error === 'CHAT_LIST_FAILED' ? 'groupChat.server.loadFailed'- : items.length + (groups?.items.length ?? 0) ? 'devices.companions.stale' : 'devices.resources.loadFailed';- const header = <View style={styles.controls}>- <View style={styles.search}>- <Search size={iconSize.md} color={colors.textPlaceholder} strokeWidth={iconStroke.regular} />- <TextInput accessibilityLabel={searchLabel} autoFocus={autoFocusSearch}- autoCorrect={false} onChangeText={(value) => { onInteract?.(); setQuery(value); }} onFocus={onInteract} placeholder={searchLabel}- placeholderTextColor={colors.textPlaceholder} selectionColor={colors.inputCaret}- style={styles.searchInput} value={query} testID="teammates.search" />- {/* Mirrors HomeSearchBar: the trailing X clears typed text. */}- {query.trim() ? <Pressable accessibilityRole="button" hitSlop={spacing.xs}- accessibilityLabel={t('devices.detail.search.clearA11y')}- onPress={() => setQuery('')}- style={({ pressed }) => [styles.searchButton, pressed && mobileInteractionStyles.pressed]} testID="teammates.searchClose">- <X color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />- </Pressable> : null}- </View>- {error ? <View style={styles.noticeRow}>- <Text accessibilityRole="alert" style={[styles.notice, styles.noticeText]} testID="teammates.error">{t(errorKey)}</Text>- <Pressable accessibilityRole="button" accessibilityLabel={t('devices.resources.retry')} disabled={refreshing}- onPress={onRefresh} style={styles.retry} testID="teammates.refresh">- {refreshing ? <ActivityIndicator color={colors.textSecondary} /> : <RefreshCw size={iconSize.sm} color={colors.textSecondary} />}- </Pressable>- </View> : null}- </View>;- const searching = !!query.trim();- const empty = loading- ? (embedded- ? <RemoteListSyncingPlaceholder testID="teammates.loading" />- : <TeammateListSkeleton />)- : searching || error || !emptyAction- ? <MainWindowEmptyState centered style={styles.empty} testID="teammates.empty"- title={searching ? t('devices.companions.noResults') : t('devices.companions.emptyTitle')}- copy={searching || error ? '' : t('devices.companions.emptyCopy')} />- : <View style={styles.emptyHome} testID="teammates.empty">- <View style={styles.presetStack} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">- {EMPTY_PRESETS.map((source, index) => <Image key={index} source={source} style={[styles.preset, index > 0 && styles.presetOverlap]} />)}- </View>- <Text accessibilityRole="header" style={styles.emptyTitle}>{t('devices.companions.emptyTitle')}</Text>- <Text style={styles.emptyCopy}>{t('devices.companions.emptyCopyCreate')}</Text>- <View style={styles.emptyAction}>{emptyAction}</View>- </View>;const renderBot = (row: HostedRemoteCollectionItem, last: boolean) => {const display = row.item.display;const title = resolveRemoteText(display.title, i18n.language);@@ -211,12 +166,71 @@ export function TeammateList({ items, loading, refreshing, error, isOnline, connlast={last}onPress={() => onSelect(row)} />;};- const renderEntry = (entry: ListEntry, index: number) => {- const last = index === entries.length - 1;+ return (entry: TeammateListEntry, last: boolean) => {if (entry.kind === 'bot' || !groups) return renderBot(entry.row, last);return <BotGroupListRow key={`group:${entry.row.key}`} row={entry.row} online={groups.isOnline(entry.row.host)} last={last}onPress={() => groups.onSelect(entry.row)} />;};+}++/** Identity list shared by home (with group chats) and the collection route. No host headings. */+export function TeammateList({ items, loading, refreshing, error, isOnline, connectionState, quietPresence, onRefresh, onSelect,+ embedded = false, autoFocusSearch = false, onInteract, groups, emptyAction, scrollInsetProps, topInset, notice }: TeammateListProps) {+ const { t } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const listRef = useRef<FlatList<TeammateListEntry>>(null);+ // The notice sits in the list header; a kept-alive list may be scrolled past it when it appears.+ const showsNotice = !!notice;+ useEffect(() => { if (showsNotice) listRef.current?.scrollToOffset({ offset: 0, animated: true }); }, [showsNotice]);+ const [query, setQuery] = useState('');+ const entries = useTeammateEntries(items, groups?.items, query);+ const renderRow = useTeammateRowRenderer({ items, isOnline, connectionState, quietPresence, onSelect, groups });+ const renderEntry = (entry: TeammateListEntry, index: number) => renderRow(entry, index === entries.length - 1);+ const searchLabel = t(groups ? 'devices.companions.searchWithGroups' : 'devices.companions.search');+ const errorKey = error === 'CHAT_ENDPOINT_UNAVAILABLE' ? 'groupChat.server.endpointUnavailable'+ : error === 'CHAT_LIST_FAILED' ? 'groupChat.server.loadFailed'+ : items.length + (groups?.items.length ?? 0) ? 'devices.companions.stale' : 'devices.resources.loadFailed';+ const header = <View style={styles.controls}>+ <View style={styles.search}>+ <Search size={iconSize.md} color={colors.textPlaceholder} strokeWidth={iconStroke.regular} />+ <TextInput accessibilityLabel={searchLabel} autoFocus={autoFocusSearch}+ autoCorrect={false} onChangeText={(value) => { onInteract?.(); setQuery(value); }} onFocus={onInteract} placeholder={searchLabel}+ placeholderTextColor={colors.textPlaceholder} selectionColor={colors.inputCaret}+ style={styles.searchInput} value={query} testID="teammates.search" />+ {/* Mirrors HomeSearchBar: the trailing X clears typed text. */}+ {query.trim() ? <Pressable accessibilityRole="button" hitSlop={spacing.xs}+ accessibilityLabel={t('devices.detail.search.clearA11y')}+ onPress={() => setQuery('')}+ style={({ pressed }) => [styles.searchButton, pressed && mobileInteractionStyles.pressed]} testID="teammates.searchClose">+ <X color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />+ </Pressable> : null}+ </View>+ {error ? <View style={styles.noticeRow}>+ <Text accessibilityRole="alert" style={[styles.notice, styles.noticeText]} testID="teammates.error">{t(errorKey)}</Text>+ <Pressable accessibilityRole="button" accessibilityLabel={t('devices.resources.retry')} disabled={refreshing}+ onPress={onRefresh} style={styles.retry} testID="teammates.refresh">+ {refreshing ? <ActivityIndicator color={colors.textSecondary} /> : <RefreshCw size={iconSize.sm} color={colors.textSecondary} />}+ </Pressable>+ </View> : null}+ </View>;+ const searching = !!query.trim();+ const empty = loading+ ? (embedded+ ? <RemoteListSyncingPlaceholder testID="teammates.loading" />+ : <TeammateListSkeleton />)+ : searching || error || !emptyAction+ ? <MainWindowEmptyState centered style={styles.empty} testID="teammates.empty"+ title={searching ? t('devices.companions.noResults') : t('devices.companions.emptyTitle')}+ copy={searching || error ? '' : t('devices.companions.emptyCopy')} />+ : <View style={styles.emptyHome} testID="teammates.empty">+ <View style={styles.presetStack} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">+ {EMPTY_PRESETS.map((source, index) => <Image key={index} source={source} style={[styles.preset, index > 0 && styles.presetOverlap]} />)}+ </View>+ <Text accessibilityRole="header" style={styles.emptyTitle}>{t('devices.companions.emptyTitle')}</Text>+ <Text style={styles.emptyCopy}>{t('devices.companions.emptyCopyCreate')}</Text>+ <View style={styles.emptyAction}>{emptyAction}</View>+ </View>;if (embedded) return <View testID="teammates.list">{notice}{header}{entries.length ? entries.map(renderEntry) : empty}</View>;return <FlatList ref={listRef} {...scrollInsetProps} style={styles.list} contentContainerStyle={[styles.content, topInset !== undefined && { paddingTop: topInset }]}contentInsetAdjustmentBehavior={topInset !== undefined ? 'never' : scrollInsetProps?.contentInsetAdjustmentBehavior}diff --git a/apps/mobile/src/session/homeViewPreferenceStore.ts b/apps/mobile/src/session/homeViewPreferenceStore.tsindex b5d618eab9..21adc14a2d 100644--- a/apps/mobile/src/session/homeViewPreferenceStore.ts+++ b/apps/mobile/src/session/homeViewPreferenceStore.ts@@ -247,6 +247,8 @@ export interface LastTeammateIdentity {export interface HomeNavigationPreferences {mode?: HomeMode;lastTeammate?: LastTeammateIdentity;+ /** The task home's teammate section: rows (false/absent) or the avatar strip (true). */+ teammatesCollapsed?: boolean;}const NAVIGATION_PREFIX = 'cindy.mobile.home.navigation.v1.';@@ -259,6 +261,7 @@ export function normalizeHomeNavigationPreferences(value: unknown): HomeNavigatitypeof last[field] === 'string' && last[field].trim().length > 0 && last[field].length <= 256);return {...(record.mode === 'tasks' || record.mode === 'teammates' ? { mode: record.mode } : {}),+ ...(typeof record.teammatesCollapsed === 'boolean' ? { teammatesCollapsed: record.teammatesCollapsed } : {}),...(validLast ? { lastTeammate: {deviceId: last!.deviceId as string,collectionId: last!.collectionId as string,@@ -278,7 +281,7 @@ export async function readHomeNavigationPreferences(owner: string): Promise<Homeexport function saveHomeNavigationPreferences(owner: string,- patch: { mode?: HomeMode; lastTeammate?: LastTeammateIdentity | null },+ patch: { mode?: HomeMode; lastTeammate?: LastTeammateIdentity | null; teammatesCollapsed?: boolean },): Promise<void> {if (!owner) return Promise.resolve();// Share the existing serialized writer; each operation captures its own owner.diff --git a/apps/mobile/src/session/useHomeMode.ts b/apps/mobile/src/session/useHomeMode.tsindex 58738ad148..105cb8df97 100644--- a/apps/mobile/src/session/useHomeMode.ts+++ b/apps/mobile/src/session/useHomeMode.ts@@ -14,9 +14,10 @@ interface Snapshot {hydrated: boolean;mode: HomeMode;lastTeammate: LastTeammateIdentity | null;+ teammatesCollapsed: boolean;saveFailed: boolean;}-const initial: Snapshot = { hydrated: false, mode: 'tasks', lastTeammate: null, saveFailed: false };+const initial: Snapshot = { hydrated: false, mode: 'tasks', lastTeammate: null, teammatesCollapsed: false, saveFailed: false };interface Entry { snapshot: Snapshot; revision: number; loading?: Promise<void> }const entries = new Map<string, Entry>();const listeners = new Set<() => void>();@@ -37,12 +38,15 @@ function hydrate(owner: string, entry: Entry): Promise<void> {const read = startBoundedStartupRead<HomeNavigationPreferences>(readHomeNavigationPreferences(owner), {});entry.loading = read.initial.then(({ value: stored, timedOut }) => {publish(entry, entry.revision === revision- ? { hydrated: true, mode: stored.mode ?? 'tasks', lastTeammate: stored.lastTeammate ?? null }+ ? { hydrated: true, mode: stored.mode ?? 'tasks', lastTeammate: stored.lastTeammate ?? null,+ teammatesCollapsed: stored.teammatesCollapsed ?? false }: { hydrated: true });if (timedOut) void read.completion.then((result) => {// Never switch away from the task list the user has begun using after a timeout.// The stored mode remains intact on disk; only recover the identity for the next explicit switch.- if (result.ok && entry.revision === revision) publish(entry, { lastTeammate: result.value.lastTeammate ?? null });+ if (result.ok && entry.revision === revision) publish(entry, {+ lastTeammate: result.value.lastTeammate ?? null, teammatesCollapsed: result.value.teammatesCollapsed ?? false,+ });});});return entry.loading;@@ -55,7 +59,7 @@ export function useHomeMode() {const entry = entryFor(owner);const snapshot = useSyncExternalStore(subscribe, () => entry.snapshot, () => initial);useEffect(() => { if (owner) void hydrate(owner, entry); }, [entry, owner]);- const update = useCallback((patch: { mode?: HomeMode; lastTeammate?: LastTeammateIdentity | null }) => {+ const update = useCallback((patch: { mode?: HomeMode; lastTeammate?: LastTeammateIdentity | null; teammatesCollapsed?: boolean }) => {if (!owner) return Promise.resolve();// Hydrate first so changing mode cannot erase an unread last-teammate choice.return hydrate(owner, entry).then(() => {@@ -71,6 +75,8 @@ export function useHomeMode() {}, [entry, owner]);const setMode = useCallback((mode: HomeMode) => update({ mode }), [update]);// The remembered teammate only preselects its computer when creating another; launch never reopens it.- const selectTeammate = useCallback((identity: LastTeammateIdentity) => update({ mode: 'teammates', lastTeammate: identity }), [update]);- return { ...snapshot, owner, setMode, selectTeammate };+ const selectTeammate = useCallback((identity: LastTeammateIdentity, options?: { keepMode?: boolean }) =>+ update(options?.keepMode ? { lastTeammate: identity } : { mode: 'teammates', lastTeammate: identity }), [update]);+ const setTeammatesCollapsed = useCallback((teammatesCollapsed: boolean) => update({ teammatesCollapsed }), [update]);+ return { ...snapshot, owner, setMode, selectTeammate, setTeammatesCollapsed };}diff --git a/apps/mobile/src/session/useTeammateNavigation.ts b/apps/mobile/src/session/useTeammateNavigation.tsindex 98a08cf244..a40c57758a 100644--- a/apps/mobile/src/session/useTeammateNavigation.ts+++ b/apps/mobile/src/session/useTeammateNavigation.ts@@ -49,15 +49,18 @@ export function useTeammateNavigation() {}} finally { if (pendingAccount.current === accountGeneration) pendingAccount.current = null; }}, [accountGeneration, navigation, preferences.setMode, router]);- /** `replace` swaps the current screen (the cloud view handing over to the new main computer). */- const openTeammate = useCallback(async (hosted: HostedRemoteCollectionItem, options?: { replace?: boolean }) => {+ /**+ * `replace` swaps the current screen (the cloud view handing over to the new main computer).+ * `keepMode`: opened from the task home's teammate section, so back returns to the tasks.+ */+ const openTeammate = useCallback(async (hosted: HostedRemoteCollectionItem, options?: { replace?: boolean; keepMode?: boolean }) => {const identity = teammateIdentity(hosted);if (!identity || pendingAccount.current === accountGeneration) return;// Fence rapid taps before the async preference write, not only at router.push.pendingAccount.current = accountGeneration;Keyboard.dismiss();try {- await preferences.selectTeammate(identity);+ await preferences.selectTeammate(identity, { keepMode: options?.keepMode });if (mounted.current && current.current === accountGeneration) {const owner = `${user?.id ?? ''}:${accountGeneration}`;const cached = readRemoteCollectionCache(owner, identity.collectionId);@@ -76,13 +79,14 @@ export function useTeammateNavigation() {}} finally { if (pendingAccount.current === accountGeneration) pendingAccount.current = null; }}, [accountGeneration, i18n.language, preferences.selectTeammate, push, router, user?.id]);- const openCreatedTeammate = useCallback(async (host: RemoteResourceHostTarget, ref: RemoteResourceRef) => {+ const openCreatedTeammate = useCallback(async (host: RemoteResourceHostTarget, ref: RemoteResourceRef, options?: { keepMode?: boolean }) => {if (!mounted.current || current.current !== accountGeneration || !host.deviceId || !ref.id || !ref.collectionId|| ref.kind !== 'bot' || pendingAccount.current === accountGeneration) return;pendingAccount.current = accountGeneration;Keyboard.dismiss();try {- await preferences.selectTeammate({ deviceId: host.deviceId, collectionId: ref.collectionId, resourceKind: 'bot', resourceId: ref.id });+ await preferences.selectTeammate({ deviceId: host.deviceId, collectionId: ref.collectionId, resourceKind: 'bot', resourceId: ref.id },+ { keepMode: options?.keepMode });if (mounted.current && current.current === accountGeneration) push({pathname: '/resources/[collectionId]/[resourceId]',params: { deviceId: host.deviceId, deviceName: host.deviceName, collectionId: ref.collectionId, resourceKind: ref.kind, resourceId: ref.id },diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 34c59dc1d4..0d0d4b014f 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -1147,6 +1147,7 @@ Codex 切模型重建时,线程索引里的路径不等于文件已经落盘## 导航未读与系统角标- 桌面伙伴与任务共用一个侧栏(2026-10-13 定稿):「伙伴」是侧栏第一层的一段,固定在置顶上方,与置顶、全部任务并存;点伙伴只切换主区域,不再整栏切换,也不再有顶部导航的「伙伴 / 返回任务」入口。段名在「展开(行列表)」与「收起成单行头像」之间切换,默认展开,按账号记住;收起时只占一行,放不下的收进末尾「+N」(点开即展开),正在看的聊天始终留在行内,群聊沿用[群聊界面规则](bot-group-chat.md#5-界面)的成员组合头像与单聊区分(`features/bots/TeammatesSection.tsx`、`teammatesSectionPrefs.ts`)。原伙伴列表的新建伙伴 / 群聊、加入群聊、群聊与私聊混排、多设备 Cindy、置顶 / 隐藏 / 复制 / 删除、已隐藏、需要处理的伙伴都留在段内;伙伴不默认置顶。伙伴段没有独立搜索框:侧栏总搜索同时匹配伙伴(名字、简介、技能,含已隐藏、不含已停止)、远程伙伴(含电脑名)与群聊(群名、成员名),命中排在会话结果之前(`TeammateSearchResults`)。侧栏收窄(rail)时由一个带未读数的伙伴图标直达 `/bots`(上次看的伙伴,没有则 Cindy)。+- 手机任务首页同样以「伙伴」段开头(2026-10-24 定稿「A+B 合一」):段头与置顶段头同款,固定在共享任务、置顶与项目组之上;**展开**为伙伴页同款伙伴行(伙伴与群聊按最近活动混排,默认 3 行,多出的收进「显示全部 N / 收起」),段头右侧「+」新建伙伴或群聊;**收起**为一排 56pt 头像(12/18 名字、未读角点、在回话环,可横滑,最后一格新建)。手机用横滑代替桌面的「+N」。收起状态按账号与首页导航偏好一起记住(`teammatesCollapsed`)。段落不跟随顶栏电脑范围筛选(与桌面一致);搜索、筛选、归档视图与远程引导时隐藏;没有伙伴时只显示一行「添加伙伴」,既无伙伴也无可新建的电脑或仍在首次加载时整段不显示。从段内打开伙伴不切换首页模式,返回仍回到任务;原「任务/伙伴」切换与伙伴页保留不变。实现见 Mobile `HomeTeammatesSection.tsx`,行与排序复用 `TeammateList.tsx` 的 `useTeammateEntries` / `useTeammateRowRenderer`。- 系统通知(完成 / 出错 / 待回复)只由任务侧栏一处发出,`/bots` 路由同样由它观察;正在看的伙伴会话按「注视中」处理,不记未读、不发通知(`useViewedBotSessionId`)。群专线仍不通知。- 伙伴未读按**有未读的对话数**聚合可见、未归档的伙伴私聊与群聊;私聊行仍显示原有的回复条数,群聊行标记该群未读。生成状态、工具过程、内部私信回执和静默巡检不新增未读。收起成头像时以头像角点提示未读,rail 伙伴图标显示聚合数。- 桌面 Dock 的完整投影为本机待关注任务数 + 本机未读伙伴对话数。远程伙伴可以出现在伙伴段,但不扩大本机 Dock 范围;目录加载前的通知事件兜底仍由既有 appBadgeService 管理,目录覆盖的伙伴底层 Session ID 用于去重。