Skip to content

armgit / cindy

Public Imported from GitHub
0

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

merge: 合入最新 main(000337155f)到移动端导航试用分支

kirozenge6b1c6636398
diff --cc apps/mobile/app/companions/direct/[threadId].tsx
index 265762cecb,f46d104420..38f4c0e53d
--- a/apps/mobile/app/companions/direct/[threadId].tsx
+++ b/apps/mobile/app/companions/direct/[threadId].tsx
@@@ -68,11 -53,10 +68,11 @@@ export default function CompanionDirect
const viewer = thread ? participant(botId, thread.botAId === botId ? thread.botAName : thread.botBName) : null;
const peer = thread ? participant(peerId, thread.botAId === peerId ? thread.botAName : thread.botBName) : null;
const messages = Array.isArray(thread?.messages) ? thread.messages : [];
- return <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.screen}>
- <SimpleStackHeader title={viewer && peer ? `${viewer.name} ⇄ ${peer.name}` : t('devices.companions.messages')}
+ return <SafeAreaView edges={simpleScrollScreenSafeAreaEdges()} style={styles.screen}>
+ <SimpleStackHeader scrollEdge title={viewer && peer ? `${viewer.name} ⇄ ${peer.name}` : t('devices.companions.messages')}
- subtitle={t('devices.companions.readOnly')} onBack={() => goBackGuarded(router)} />
+ onBack={() => goBackGuarded(router)} />
- <ScrollView contentContainerStyle={styles.content} testID="companion.directThread">
+ <ScrollView {...simpleScrollInsetProps} contentContainerStyle={styles.content} testID="companion.directThread"
+ refreshControl={<RefreshControl refreshing={pulling} onRefresh={pullRefresh} tintColor={colors.textSecondary} />}>
{!online ? <Text style={styles.note}>{t('devices.resources.hostOffline')}</Text> : null}
{messages.map((message) => {
const ownSide = message.senderBotId === botId;
diff --cc apps/mobile/app/sessions/[sessionId].tsx
index 47a2a6e45d,9eb9cb1b29..57a0bcf300
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@@ -93,6 -94,6 +94,7 @@@ import { Text, TextInput } from '@/comp
import Reanimated, { useAnimatedStyle } from 'react-native-reanimated';
import { GestureDetector } from '@/platform/gestureHandler';
import { MobileAgentMark } from '@/components/MobileAgentMark';
++import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
import { SessionHeaderNativeBack, SessionHeaderNativeActions, SessionHeaderNativeTitle, SessionHeaderNativeBlur } from '@/session/SessionHeaderNativeControls';
import { TaskTagDots } from '@/session/TaskTags';
import type { TextInput as NativeTextInput } from 'react-native';
@@@ -5569,29 -5577,24 +5605,35 @@@ export default function SessionScreen(
setError(t('session.outbox.creationRecoveryRequired'));
return;
}
- setQueueSelectedClientId(null);
- const owner = getMobileAuthOwner();
- const remove = async () => {
- if (isDurableOutboxUnsent(record)) {
- await mobileDurableOutbox.update(record, { state: 'host-owned', cleanupOutcome: 'cancelled', cancelRequested: true, error: undefined });
- } else await mobileDurableOutbox.update(record, { cancelRequested: true, state: 'confirming' });
+ // 删除发送失败的消息不可撤销:先确认(破坏性按钮),确认后才真正移除。
+ const confirmRemove = () => {
+ setQueueSelectedClientId(null);
+ const owner = getMobileAuthOwner();
+ const remove = async () => {
+ if (isDurableOutboxUnsent(record)) {
+ await mobileDurableOutbox.update(record, { state: 'host-owned', cleanupOutcome: 'cancelled', cancelRequested: true, error: undefined });
+ } else await mobileDurableOutbox.update(record, { cancelRequested: true, state: 'confirming' });
+ };
+ void remove().catch((err) => {
+ if (isMobileAuthOwnerCurrent(owner) && outboxSessionAliveRef.current === sessionId) setError(formatRemoteError(err));
+ });
};
- void remove().catch((err) => {
- if (isMobileAuthOwnerCurrent(owner) && outboxSessionAliveRef.current === sessionId) setError(formatRemoteError(err));
- });
+ Alert.alert(
+ t('session.outbox.deleteConfirmTitle'),
+ t('session.outbox.deleteConfirmBody'),
+ [
+ { text: t('session.common.cancel'), style: 'cancel' },
+ { text: t('session.common.delete'), style: 'destructive', onPress: confirmRemove },
+ ],
+ );
};
- const outboxDisplayItems = useMemo(() => outboxItems.map(outboxDisplayItem), [outboxItems]);
+ const outboxDisplayItems = useMemo(() => outboxItems.map((item) => {
+ const record = findDurableOutboxRecord(item.clientId);
+ return {
+ ...outboxDisplayItem(item),
+ canCancel: !(record?.creation && !record.prepared && !record.template),
+ };
+ }), [outboxItems, deviceId, sessionId]);
// Legacy creation tasks have no app-owned first record. Never downgrade durable follow-ups
// into the old ephemeral draft recovery; new creation tasks use the branch above.
@@@ -9397,17 -9488,25 +9549,29 @@@
</View>
{!isSharedTaskAccessRevoked && nativeComposerFrameAvailable && sessionOperationLayout.composerSlot === 'editable' && !shareSelectionActive ? (
- <SessionHeaderNativeBlur
- edge="bottom"
- height={bottomOverlayHeight + spacing.xxl}
- inset={nativeShellLayout.keyboardBottomInset}
- />
+ <DockKeyboardLift active={dockKeyboardFollow} restingBottom={composerDock.restingBottom} keyboardGap={composerDock.keyboardGap}
+ pointerEvents="none" style={StyleSheet.absoluteFill}>
+ <SessionHeaderNativeBlur
+ edge="bottom"
+ height={bottomOverlayHeight + spacing.xxl}
+ inset={dockKeyboardFollow ? 0 : nativeShellLayout.keyboardBottomInset}
+ />
+ </DockKeyboardLift>
) : null}
+ {Platform.OS === 'android' ? (
+ // 量出键盘避让容器的实际可用高度,供挂到根浮层的输入区对齐(见 SessionChromeLayer)。
+ <View onLayout={handleKeyboardAreaLayout} pointerEvents="none" style={StyleSheet.absoluteFill} />
+ ) : null}
+ <SessionChromeLayer
+ enabled={androidFrostedComposer}
+ height={keyboardAreaHeight ?? windowDimensions.height}
+ hiddenFromAccessibility={sessionListDrawerOverlayMounted}
+ left={paneLayout.detail.x}
+ viewport={detailViewport}
+ width={paneLayout.detail.width}
+ >
- {!isSharedTaskAccessRevoked && <View
+ {!isSharedTaskAccessRevoked && <DockKeyboardLift
+ active={dockKeyboardFollow} restingBottom={composerDock.restingBottom} keyboardGap={composerDock.keyboardGap}
pointerEvents="box-none"
testID="session.bottomViewport"
style={[
@@@ -9740,8 -9856,8 +9934,9 @@@
) : null}
</View>
</View>
- </View>}
+ </DockKeyboardLift>}
+ </SessionChromeLayer>
+ <DockKeyboardViewportSpacer active={dockKeyboardFollow} />
</ComposerKeyboardAvoidingView>
</PaneViewportProvider>
@@@ -11104,6 -11253,17 +11344,17 @@@ function SessionSearchSheet(
testID="session.searchInput"
value={query}
/>
+ {query ? (
+ <Pressable
+ accessibilityLabel={t('devices.detail.search.clearA11y')}
+ accessibilityRole="button"
+ onPress={() => onChangeQuery('')}
- style={({ pressed }) => [styles.searchClearButton, pressed && styles.searchClearButtonPressed]}
++ style={({ pressed }) => [styles.searchClearButton, pressed && mobileInteractionStyles.pressed]}
+ testID="session.searchClearButton"
+ >
+ <X color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ </Pressable>
+ ) : null}
</View>
<View style={styles.searchToolbar}>
<Text style={styles.searchCounter} testID="session.searchCounter">
@@@ -11829,24 -11985,32 +12077,31 @@@ const makeStyles = (colors: ThemeColors
paddingHorizontal: spacing.lg,
paddingVertical: spacing.md,
},
- searchInputRow: {
+ searchInputPill: {
alignItems: 'center',
- backgroundColor: colors.surface,
+ backgroundColor: colors.surfaceElevated,
borderColor: colors.border,
- borderRadius: radius.container,
+ borderRadius: radius.pill,
borderWidth: StyleSheet.hairlineWidth,
flexDirection: 'row',
+ gap: spacing.sm,
minHeight: 44,
- paddingHorizontal: spacing.lg,
- paddingLeft: spacing.md,
++ paddingLeft: spacing.lg,
++ paddingRight: spacing.xs,
},
searchInput: {
color: colors.textPrimary,
flex: 1,
- fontSize: typeScale.body,
- minHeight: 42,
- paddingVertical: spacing.xs,
+ fontSize: typeScale.bodySmall,
+ minWidth: 0,
+ paddingVertical: spacing.sm,
},
+ searchClearButton: {
+ alignItems: 'center',
+ height: 44,
+ justifyContent: 'center',
+ width: 44,
+ },
- searchClearButtonPressed: {
- opacity: 0.72,
- },
searchToolbar: {
alignItems: 'center',
flexDirection: 'row',
diff --cc apps/mobile/app/settings.tsx
index 588182fc9d,a60f9f2ac9..f1d56d3f32
--- a/apps/mobile/app/settings.tsx
+++ b/apps/mobile/app/settings.tsx
@@@ -82,11 -84,21 +82,12 @@@ import
import {
hydrateMobileVoiceDictionary,
readCachedMobileVoiceDictionarySnapshot,
- refreshMobileVoiceDictionary,
subscribeMobileVoiceDictionaryCache,
} from '@/session/mobileVoiceDictionaryCache';
-import {
- buildMobileVoiceDictionaryEntryViews,
- collectMobileVoiceDictionaryHosts,
- patchMobileVoiceDictionaryHosts,
- type MobileVoiceDictionaryEntryView,
- type MobileVoiceDictionaryHost,
-} from '@/session/mobileVoiceDictionaryView';
-import { DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL } from '@cindy/maker-shared/device-link-contract';
-import type { MobileVoiceDictionarySnapshotResult } from '@cindy/maker-shared/device-link-contract';
+import { buildMobileVoiceDictionaryEntryViews } from '@/session/mobileVoiceDictionaryView';
import { buildMobileUpdateInfoRows, currentMobileOtaVersion } from '@/settings/updateInfo';
import { shouldCheckBundleUpdate } from '@/update/bundleUpdate';
+ import { isGooglePlayInstallation } from '@/update/androidInstallSource';
import {
manualUpdateCheckMessage,
runManualUpdateCheck,
@@@ -723,27 -963,49 +727,29 @@@ export default function SettingsScreen(
[desktopDevices, dictionaryRevision],
);
- const dictionaryStatus = desktopDevices.length === 0
- ? 'no-desktops'
- : desktopDevices.some((host) => host.online)
- ? 'ready'
- : 'all-offline';
-
- const avatarLabel = (overview.header.name.trim()[0] ?? '?').toUpperCase();
const updateBusy = updatePhase === 'checking' || updatePhase === 'downloading';
- const updateButtonLabel = updatePhase === 'checking' ? t('settings.version.checking')
- : updatePhase === 'downloading' ? t('settings.version.updating')
- : t(
- IS_TESTFLIGHT_BUILD || playManagedUpdates
- ? 'settings.version.testFlightCheckAction'
- : 'settings.version.checkAction',
- );
-
- if (dictionaryScreenOpen) {
- return (
- <VoiceDictionaryScreen
- entries={dictionaryEntries}
- onBack={() => setDictionaryScreenOpen(false)}
- onRefresh={refreshVoiceDictionary}
- refreshing={dictionaryRefreshing}
- status={dictionaryStatus}
- />
- );
- }
-
- if (selfDeviceNameEditing) {
- return (
- <RenameSelfDeviceScreen
- draft={selfDeviceNameDraft}
- message={selfDeviceNameMessage}
- onChangeDraft={updateSelfDeviceNameDraft}
- onDone={closeSelfDeviceNameEditor}
- onResetDefault={resetSelfDeviceName}
- />
- );
- }
+ const updateActionLabel = t(
- IS_TESTFLIGHT_BUILD
++ IS_TESTFLIGHT_BUILD || playManagedUpdates
+ ? 'settings.version.testFlightCheckAction'
+ : 'settings.version.checkAction',
+ );
+ // 面向用户的更新方式说明;OTA 版本号、运行来源等技术细节在「调试 / 开发者」里。
+ const updateMethodHint = REVIEW_MODE
+ ? null
+ : IS_TESTFLIGHT_BUILD
+ ? (updatesEnabled ? null : t('settings.version.testFlightContentUpdateUnavailable'))
- : updatesEnabled
- ? t('settings.version.updateMethodInApp')
- : bundleCheckEnabled
- ? t('settings.version.updateMethodPackage')
- : t('settings.version.updateMethodUnavailable');
++ : playManagedUpdates
++ ? (updatesEnabled ? null : t('settings.version.googlePlayContentUpdateUnavailable'))
++ : updatesEnabled
++ ? t('settings.version.updateMethodInApp')
++ : bundleCheckEnabled
++ ? t('settings.version.updateMethodPackage')
++ : t('settings.version.updateMethodUnavailable');
return (
- <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.safeArea} testID="settings.screen">
+ <SafeAreaView edges={simpleScrollScreenSafeAreaEdges()} style={styles.safeArea} testID="settings.screen">
<SimpleStackHeader
+ scrollEdge
backTestID="settings.backButton"
onBack={() => goBackGuarded(router)}
title={t('settings.title')}
@@@ -790,14 -1060,26 +796,19 @@@
{t('settings.version.testFlightUpdateManaged')}
</Text>
) : null}
+ {playManagedUpdates ? (
- <Text style={styles.rowDetail} numberOfLines={2} testID="settings.googlePlayUpdateHint">
++ <Text style={styles.versionDetail} testID="settings.googlePlayUpdateHint">
+ {t('settings.version.googlePlayUpdateManaged')}
+ </Text>
+ ) : null}
{updateMessage ? (
- <Text style={styles.rowDetail} numberOfLines={2} testID="settings.updateMessage">{updateMessage}</Text>
- ) : !REVIEW_MODE && !updatesEnabled ? (
- <Text style={styles.rowDetail} numberOfLines={2}>
- {t(
- IS_TESTFLIGHT_BUILD
- ? 'settings.version.testFlightContentUpdateUnavailable'
- : playManagedUpdates
- ? 'settings.version.googlePlayContentUpdateUnavailable'
- : 'settings.version.devNoOta',
- )}
- </Text>
+ <Text style={styles.versionDetail} testID="settings.updateMessage">{updateMessage}</Text>
+ ) : updateMethodHint ? (
+ <Text style={styles.versionDetail} testID="settings.updateMethod">{updateMethodHint}</Text>
) : null}
</View>
- {/* 审核模式(清单 review 命中当前二进制版本):隐藏检查更新入口,版本号照常展示 */}
+ {/* 审核模式(清单 review 命中当前二进制版本):隐藏检查更新入口,版本号照常展示。
+ 次级按钮(描边 + 正文色),避免灰底读成禁用;加载时只转圈。 */}
{!REVIEW_MODE ? (
<MainWindowActionButton
action={{
@@@ -845,16 -1141,28 +856,26 @@@
footer={t('settings.voiceDictionary.hint')}
title={t('settings.voiceDictionary.sectionTitle')}
>
- {[
- <ActionInfoRow
- accessibilityLabel={t('settings.voiceDictionary.openAccessibility')}
- key="voice-dictionary"
- label={t('settings.voiceDictionary.label')}
- onPress={openVoiceDictionary}
- testID="settings.voiceDictionary.row"
- value={t('settings.voiceDictionary.entryCount', { count: dictionaryEntries.length })}
- />,
- ]}
+ <ActionInfoRow
+ accessibilityLabel={t('settings.voiceDictionary.openAccessibility')}
+ key="voice-dictionary"
+ label={t('settings.voiceDictionary.label')}
+ onPress={openVoiceDictionary}
+ testID="settings.voiceDictionary.row"
+ value={t('settings.voiceDictionary.entryCount', { count: dictionaryEntries.length })}
+ />
</SettingsGroup>
+ <SettingsGroup title={t('sharedTask.title')}>
+ <ActionInfoRow
+ accessibilityLabel={t('sharedTask.manageSharing')}
+ label={t('sharedTask.manageSharing')}
+ value=""
+ onPress={() => router.push({ pathname: '/shared-session', params: { mode: 'manage' } })}
+ testID="settings.sharedTasks.row"
+ />
+ </SettingsGroup>
+
{/* 显示模式:默认跟随系统,手动选择浅色 / 深色即持久化 override(恢复跟随系统 = 清除 override) */}
<SettingsGroup title={t('settings.appearance.title')}>
<NativePullDownMenu
diff --cc apps/mobile/app/shared-session.tsx
index 9947cea04e,0a068080a1..deddbaf81b
--- a/apps/mobile/app/shared-session.tsx
+++ b/apps/mobile/app/shared-session.tsx
@@@ -14,7 -16,7 +16,7 @@@ import { sharedTaskErrorKey } from '@/d
import { isSharedTaskGone } from '@/device-link/sharedTaskAccessWatch';
import { markDeviceAccessRevoked } from '@/device-link/accessRevoked';
import { Text, TextInput } from '@/components/AppText';
- import { MainWindowEmptyState, MainWindowRowButton } from '@/components/MobilePrimitives';
-import { MainWindowActionButton, MainWindowRowButton } from '@/components/MobilePrimitives';
++import { MainWindowActionButton, MainWindowEmptyState, MainWindowRowButton } from '@/components/MobilePrimitives';
import { SharedTaskAction, SharedTaskScreen } from '@/session/SharedTaskScreen';
import { useSharedTaskConfirmation } from '@/session/useSharedTaskConfirmation';
import { SharedTaskEndedState } from '@/session/SharedTaskEndedState';
@@@ -251,12 -363,13 +363,12 @@@ export default function SharedSessionSc
<MainWindowRowButton accessibilityLabel={t(hostContext ? 'sharedTask.tabCurrent' : 'sharedTask.join')} selected={tab === 'current'} style={[styles.tab, tab === 'current' && styles.tabSelected]} onPress={() => { setNotice(''); setTab('current'); }}><Text style={styles.small}>{t(hostContext ? 'sharedTask.tabCurrent' : 'sharedTask.join')}</Text></MainWindowRowButton>
<MainWindowRowButton accessibilityLabel={t('sharedTask.tabOwned')} selected={tab === 'owned'} style={[styles.tab, tab === 'owned' && styles.tabSelected]} onPress={() => { setNotice(''); setTab('owned'); }}><Text style={styles.small}>{t('sharedTask.tabOwned')}</Text><View style={styles.badge}><Text style={styles.metadata}>{owned.length}</Text></View></MainWindowRowButton>
</View>}
- {!!notice && <Text accessibilityRole="alert" style={styles.noticeText}>{notice}</Text>}
- {!!loadError && <Text accessibilityRole="alert" style={styles.noticeText}>{loadError}</Text>}
- {!guestId && tab === 'owned' ? owned.length === 0 ? <MainWindowEmptyState centered style={styles.ownedEmpty}
+ {!!notice && !manualOpen && <Text accessibilityRole="alert" style={styles.noticeText}>{notice}</Text>}
+ {!!loadError && <View><Text accessibilityRole="alert" style={styles.noticeText}>{loadError}</Text><SharedTaskAction action={{ label: t('sharedTask.retryAction'), disabled: busy, onPress: () => void run(async current => { await load(current); if (current()) setLoadError(''); }, false) }} /></View>}
- {management && !guestId ? managementView : !guestId && tab === 'owned' ? owned.length === 0 ? <View style={styles.empty}>
- <View style={styles.largeIcon}><Check size={iconSize.md} color={colors.textPrimary} /></View>
- <Text style={styles.emptyTitle}>{t('sharedTask.ownedEmptyTitle')}</Text><Text style={styles.emptyCopy}>{t('sharedTask.ownedEmptyHint')}</Text>
++ {management && !guestId ? managementView : !guestId && tab === 'owned' ? owned.length === 0 ? <MainWindowEmptyState centered style={styles.ownedEmpty}
+ testID="sharedTask.ownedEmpty" title={t('sharedTask.ownedEmptyTitle')} copy={t('sharedTask.ownedEmptyHint')}>
{hostContext && <SharedTaskAction action={{ label: t('sharedTask.shareCurrent'), onPress: () => setTab('current') }} />}
- </View> : <>
+ </MainWindowEmptyState> : <>
<Text style={styles.intro}>{t('sharedTask.ownedIntro', { count: owned.length })}</Text>
{owned.map((item) => <View key={item.sharedTaskId} style={styles.taskRow}><Users size={iconSize.md} color={colors.textTertiary} /><View style={styles.grow}><Text style={styles.taskTitle}>{item.title}</Text><Text style={styles.metadata}>{deviceName(item.hostDeviceId)}{guestCounts[item.sharedTaskId] !== undefined ? ' · ' + t('sharedTask.guestCount', { count: guestCounts[item.sharedTaskId] }) : ''}</Text></View>
{item.sessionId === sessionId && item.hostDeviceId === deviceId ? <SharedTaskAction compact action={{ label: t('sharedTask.manage'), onPress: () => setTab('current') }} /> : <SharedTaskAction compact action={{ label: t('sharedTask.enterTask'), disabled: busy, onPress: () => void run(current => openTask(item.sharedTaskId, current), false) }} />}
@@@ -309,9 -421,33 +420,33 @@@
</SharedTaskScreen>;
}
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ managementEmpty: { alignItems: 'center', paddingVertical: spacing.xxl * 2, paddingHorizontal: spacing.md },
+ managementEmptyIcon: { width: 48, height: 48, alignItems: 'center', justifyContent: 'center', borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, borderRadius: radius.pill, marginBottom: spacing.lg + spacing.xs },
+ managementHeading: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'flex-start', gap: spacing.sm + spacing.xs, marginTop: spacing.sm, marginBottom: spacing.lg + spacing.xs },
+ managementHeadingCopy: { flex: 1, minWidth: 160 },
+ managementTitle: { color: colors.textPrimary, fontSize: typeScale.headline, lineHeight: lineHeight.headline, fontWeight: fontWeight.semibold },
+ managementDescription: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginTop: spacing.sm },
+ managementButton: { minHeight: 44, paddingHorizontal: spacing.md, backgroundColor: colors.surface, flexShrink: 0 },
+ managementButtonText: { fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular },
+ managementTabs: { flexDirection: 'row', gap: spacing.lg + spacing.md, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: colors.border, marginBottom: spacing.xl },
+ managementTab: { minHeight: 44, justifyContent: 'center', paddingBottom: spacing.md },
+ managementTabLabel: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
+ managementTabText: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
+ managementTabTextSelected: { color: colors.textPrimary },
+ managementTabIndicator: { position: 'absolute', bottom: -StyleSheet.hairlineWidth, left: 0, right: 0, height: 2, backgroundColor: colors.textPrimary },
+ managementList: { borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, borderRadius: radius.container, overflow: 'hidden' },
+ managementRow: { flexDirection: 'row', alignItems: 'flex-start', paddingVertical: spacing.lg, paddingHorizontal: spacing.md, gap: spacing.md },
+ managementRowDivider: { borderTopWidth: StyleSheet.hairlineWidth, borderColor: colors.border },
+ managementTaskTitleTarget: { minHeight: 44, justifyContent: 'center' },
+ managementMetadata: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, marginTop: spacing.xs },
+ managementRowActions: { gap: spacing.xs, alignItems: 'flex-end' },
+ managementListNote: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginTop: spacing.lg },
+ managementDangerZone: { borderTopWidth: StyleSheet.hairlineWidth, borderColor: colors.border, marginTop: spacing.xxl, paddingTop: spacing.xl },
+ managementDangerDescription: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginTop: spacing.xs },
+ managementDangerButton: { minHeight: 44, marginTop: spacing.lg, backgroundColor: colors.surface },
- intro: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginBottom: spacing.lg },
+ intro: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginBottom: spacing.lg },
small: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },
- smallMuted: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
+ smallMuted: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
taskTitle: { color: colors.textPrimary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },
metadata: { color: colors.textTertiary, fontSize: typeScale.micro, lineHeight: lineHeight.micro },
caption: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginBottom: spacing.sm },
diff --cc apps/mobile/src/__tests__/CompanionProfileSheet.android.test.tsx
index 0000000000,8354c7b2e6..a32cb5a84f
mode 000000,100644..100644
--- a/apps/mobile/src/__tests__/CompanionProfileSheet.android.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionProfileSheet.android.test.tsx
@@@ -1,0 -1,229 +1,230 @@@
+ // @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(() => ({
+ sheet: null as any, choices: [] as any[], portrait: null as any, read: vi.fn(), openLink: vi.fn(), invoke: vi.fn(), alert: vi.fn(),
+ close: vi.fn(), closed: vi.fn(), search: vi.fn(), created: vi.fn(),
+ }));
+ vi.mock('react-native', () => ({
+ Platform: { OS: 'android' }, StyleSheet: { create: (v: unknown) => v, hairlineWidth: 1 }, Alert: { alert: h.alert }, Image: () => null,
+ View: ({ children, testID }: any) => <div data-testid={testID}>{children}</div>, ScrollView: 'div',
+ Pressable: ({ children, onPress, disabled, testID }: any) => <button data-testid={testID} disabled={disabled} onClick={onPress}>{children}</button>,
+ Switch: ({ accessibilityLabel, value, onValueChange, disabled }: any) => <input type="checkbox" aria-label={accessibilityLabel} checked={value} disabled={disabled} onChange={e => onValueChange(e.currentTarget.checked)} />,
+ ActivityIndicator: ({ accessibilityLabel }: any) => <span role="progressbar" aria-label={accessibilityLabel} />,
+ }));
+ vi.mock('expo-router', () => ({ useRouter: () => ({ push: vi.fn() }) }));
+ vi.mock('expo-crypto', () => ({ randomUUID: () => 'test-id' }));
++vi.mock('@/platform/chrome', () => ({ NativeSwitch: () => null }));
+ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));
+ vi.mock('lucide-react-native', () => Object.fromEntries(['Brain', 'Camera', 'FileText', 'Hand', 'History', 'Info', 'Link2', 'Settings2', 'Sparkles']
+ .map(name => [name, Object.assign(() => null, { displayName: name })])));
+ vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: 1 }) }));
+ vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke: h.invoke, openLink: h.openLink }) }));
+ vi.mock('@/device-link/remoteResources', () => ({ invokeRemoteResourceAction: (...args: unknown[]) => h.invoke(...args) }));
+ vi.mock('@/components/AppText', () => ({
+ Text: ({ children }: any) => <span>{children}</span>,
+ TextInput: (p: any) => <input aria-label={p.accessibilityLabel} value={p.value} maxLength={p.maxLength} disabled={p.editable === false} onInput={e => p.onChangeText(e.currentTarget.value)} onChange={() => {}} />,
+ }));
+ vi.mock('@/components/MobilePrimitives', () => ({ MainWindowActionButton: ({ action }: any) => <button disabled={!!action.disabled || !!action.busy} data-tone={action.tone} onClick={action.onPress}>{action.label}</button> }));
+ vi.mock('@/components/RemoteCompanionAvatar', () => ({ RemoteCompanionAvatar: (p: any) => <span data-testid="avatar" data-size={p.size} /> }));
+ vi.mock('@/session/CompanionSettingsRow', () => ({ CompanionSettingsRow: ({ label, icon, onPress, disabled, busy, destructive, testID }: any) =>
+ <button data-testid={testID} data-icon={icon?.type?.displayName ?? ''} data-destructive={destructive ? 'true' : 'false'} disabled={disabled || busy} onClick={onPress}>{label}</button> }));
+ vi.mock('@/session/CompanionChoice', () => ({ CompanionChoice: (p: any) => { h.choices.push(p); return <span data-choice={p.label} />; } }));
+ vi.mock('@/session/CompanionSheet', () => ({ CompanionSheet: (p: any) => { h.sheet = p; return p.visible ? <div data-testid="sheet">{p.children}</div> : null; } }));
+ vi.mock('@/session/CompanionProfileArtifacts', () => ({ CompanionProfileArtifacts: () => null }));
+ vi.mock('@/session/CompanionPortraitPicker', async original => ({ ...await original<object>(), CompanionPortraitPicker: (p: any) => { h.portrait = p; return <span data-testid="portraits" />; } }));
+ vi.mock('@/session/CompanionMemoryPage', () => ({ CompanionMemoryPage: () => <div data-testid="memoryPage" /> }));
+ vi.mock('@/session/useCompanionMemory', () => ({ useCompanionMemory: () => ({ busy: false, dirty: false, flush: async () => true, back: async () => false }) }));
+ vi.mock('@/session/CompanionProfileNativeView', () => ({ CompanionProfileNativeView: () => { throw new Error('iOS view on Android'); } }));
+ vi.mock('@/session/CompanionCreateNativeView', () => ({ CompanionCreateNativeView: () => { throw new Error('iOS view on Android'); } }));
+ vi.mock('@/session/CompanionModelChain', () => ({ readCompanionModelChain: (v: string) => JSON.parse(v || '[]'), CompanionModelChain: () => null, CompanionModelPicker: () => null }));
+ vi.mock('@/theme', async () => ({ ...await import('@/theme/tokens'), useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}) }));
+ vi.mock('@/session/companionProfileData', async original => ({ ...await original<object>(), loadCompanionProfile: (...args: unknown[]) => h.read(...args) }));
+ import { CompanionCreateSheet, CompanionProfileSheet } from '@/session/CompanionProfileSheet';
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+
+ const ref = { collectionId: 'teammates', kind: 'bot', id: 'bot' };
+ const resource = { ref, display: { title: 'Cindy', subtitle: 'Teammate on Mac' }, links: [], revision: 'v1' };
+ const form = (id: string, fields: object[], values: Record<string, unknown> = {}, extra: object = {}) => ({ id, values, action: { id: `${id}-grant`, label: 'Save', fields }, ...extra });
+ const managed = (id: string, label: string, extra: object = {}) => ({ id, values: {}, action: { id: `${id}-grant`, label, confirmation: { title: `${label}?`, body: `${label} body` }, ...extra } });
+ const home = () => ({ resource, panels: [
+ form('profile', [{ id: 'name', label: 'Name', kind: 'text' }], { name: 'Cindy' }),
+ { id: 'avatar', values: {}, entries: [{ id: 'avatar', title: 'Avatar', resourceId: 'settings:bot/avatar' }] },
+ { ...form('skills', [{ id: 'skillNote', label: 'Skill note', kind: 'text' }]), text: '' },
+ { id: 'connections', values: {}, entries: [{ id: 'refs', title: 'Referenced', resourceId: 'settings:bot/connections' }] },
+ // Host order is authoritative: delete before restart here.
+ managed('delete', 'Delete teammate'), managed('restart', 'Restart'),
+ ] });
+ let root: Root; let container: HTMLDivElement;
+ const buttons = () => [...container.querySelectorAll('button')];
+ const byTest = (id: string) => container.querySelector<HTMLButtonElement>(`[data-testid="${id}"]`);
+ const byText = (text: string) => buttons().find(node => node.textContent === text);
+ const settle = () => act(async () => { for (let i = 0; i < 4; i++) await new Promise(resolve => setTimeout(resolve, 0)); });
+ async function press(node: HTMLElement | null | undefined) { if (!node) throw new Error('Missing control'); await act(async () => { node.click(); }); await settle(); }
+ async function type(label: string, value: string) {
+ const field = container.querySelector<HTMLInputElement>(`input[aria-label="${label}"]`); if (!field) throw new Error(`Missing ${label}`);
+ await act(async () => { field.value = value; field.dispatchEvent(new Event('input', { bubbles: true })); });
+ }
+ async function render() {
+ await act(async () => root.render(createElement(CompanionProfileSheet, { visible: true, resource: resource as any, collectionId: 'teammates', deviceId: 'host', deviceName: 'Mac', online: true,
+ onClose: h.close, onClosed: h.closed, onOpenSearch: h.search })));
+ await settle();
+ }
+ beforeEach(() => {
+ vi.clearAllMocks(); h.choices = []; h.sheet = null;
+ h.read.mockImplementation(async () => home()); h.openLink.mockResolvedValue(undefined); h.invoke.mockResolvedValue({ effects: [] });
+ container = document.createElement('div'); document.body.append(container); root = createRoot(container);
+ });
+ afterEach(() => { act(() => root.unmount()); container.remove(); });
+
+ it('lays out the iOS identity, entry groups, icons and host-ordered management actions', async () => {
+ await render();
+ const avatar = container.querySelector('[data-testid="avatar"]')!;
+ expect(avatar.getAttribute('data-size')).toBe('48');
+ // Identity only: no navigation target and no subtitle line.
+ expect(avatar.closest('button')).toBeNull();
+ expect(container.textContent).toContain('Cindy'); expect(container.textContent).not.toContain('Teammate on Mac');
+ const rows = buttons().map(node => node.dataset.testid ?? '').filter(id => /^companionProfile\.[a-z]+$/.test(id));
+ expect(rows).toEqual(['profile', 'memory', 'models', 'skills', 'artifacts', 'search', 'permissions'].map(id => `companionProfile.${id}`));
+ const icons = Object.fromEntries(rows.map(id => [id.split('.')[1], byTest(id)!.dataset.icon]));
+ // 图标与桌面 BotsHomeView 同一动作同一 lucide 图标(mobile-design-guide §6)。
+ expect(icons).toMatchObject({ profile: 'Info', memory: 'Brain', models: 'Sparkles', skills: 'Settings2', artifacts: 'FileText', search: 'History', permissions: 'Hand' });
+ expect(new Set(Object.values(icons)).size).toBe(rows.length);
+ const actions = buttons().filter(node => node.dataset.testid?.startsWith('companionProfile.action.'));
+ expect(actions.map(node => [node.dataset.testid, node.dataset.destructive])).toEqual([['companionProfile.action.delete', 'true'], ['companionProfile.action.restart', 'false']]);
+ });
+
+ it('keeps automation absent and hands search to the owner like iOS, without closing first', async () => {
+ await render();
+ expect(byTest('companionProfile.automation')).toBeNull();
+ await press(byTest('companionProfile.search'));
+ expect(h.search).toHaveBeenCalledOnce(); expect(h.close).not.toHaveBeenCalled();
+ });
+
+ it('renders confirmation fields for any confirmed action, not only delete', async () => {
+ h.read.mockImplementation(async () => ({ ...home(), panels: [...home().panels.filter(item => item.id !== 'restart'),
+ managed('restart', 'Restart', { fields: [{ id: 'reason', label: 'Reason', kind: 'text' }] })] }));
+ await render(); await press(byTest('companionProfile.action.restart'));
+ expect(h.sheet.title).toBe('Restart?'); expect(h.sheet.preventDismiss).toBe(true); expect(h.sheet.onBack).toBeTypeOf('function');
+ expect(container.textContent).toContain('Restart body');
+ await type('Reason', 'Stuck on a tool'); await press(byText('Restart'));
+ expect(h.invoke.mock.calls[0][2]).toMatchObject({ actionId: 'restart-grant', input: { reason: 'Stuck on a tool' } });
+ });
+
+ it('keeps Settings to Permissions and opens selects through the system menu without a search box', async () => {
+ const models = form('models', [{ id: 'route0', label: 'Route', kind: 'select', options: [{ value: '', label: 'None' }, { value: 'a', label: 'Model A' }] }], { route0: 'a' });
+ h.read.mockImplementation(async (_invoke: unknown, _device: string, target: { id: string }) => target.id === 'settings:bot/avatar'
+ ? { resource: { ...resource, ref: { ...ref, id: 'settings:bot/models' }, display: { title: 'Models' } }, panels: [models] } : home());
+ await render(); await press(byTest('companionProfile.profile')); await press(byTest('companionProfile.avatar'));
+ expect(h.sheet.title).toBe('Models');
+ const choice = h.choices.at(-1);
+ expect(choice).toMatchObject({ label: 'Route', value: 'a', disabled: false, options: [{ value: '', label: 'None', disabled: false }, { value: 'a', label: 'Model A', disabled: false }] });
+ expect(container.querySelector('input[aria-label*="searchOptions"]')).toBeNull();
+ await act(async () => choice.onChange(''));
+ expect(h.sheet.preventDismiss).toBe(true);
+ await act(async () => h.sheet.onBack()); await settle();
+ // Back saves the draft first, exactly like the iOS page Back, then lands on Settings.
+ expect(h.invoke.mock.calls[0][2]).toMatchObject({ actionId: 'models-grant', input: { route0: '' } });
+ const rows = buttons().map(node => node.dataset.testid).filter(Boolean);
+ expect(rows).toEqual(['companionProfile.permissions']); expect(byTest('companionProfile.permissions')!.dataset.icon).toBe('Hand');
+ });
+
+ it('follows the iOS skills page: entry rows or the empty note, never an inline form', async () => {
+ await render(); await press(byTest('companionProfile.skills'));
+ expect(container.textContent).toContain('devices.companionProfile.skillsEmpty');
+ expect(container.querySelector('input[aria-label="Skill note"]')).toBeNull();
+ expect(byTest('companionProfile.connections')!.dataset.icon).toBe('Link2');
+ });
+
+ it('edits a skill with the host body limit and removes it through a destructive row', async () => {
+ const skill = form('skill', [{ id: 'body', label: 'Content', kind: 'multiline' }], { body: 'Original' });
+ const remove = { id: 'remove', values: {}, action: { id: 'skill-remove', label: 'Remove skill', tone: 'destructive', confirmation: { title: 'Remove?' } } };
+ h.read.mockImplementation(async (_invoke: unknown, _device: string, target: { id: string }) => target.id.startsWith('settings:bot/connections')
+ ? { resource: { ...resource, ref: { ...ref, id: 'settings:bot/skills/learned' }, display: { title: 'Learned' } }, panels: [skill, remove] } : home());
+ await render(); await press(byTest('companionProfile.skills')); await press(byTest('companionProfile.connections'));
+ expect(container.querySelector<HTMLInputElement>('input[aria-label="Content"]')!.maxLength).toBe(55000);
+ const row = byTest('companionProfile.action.remove')!;
+ expect(row.dataset.destructive).toBe('true');
+ await press(row); expect(h.sheet.title).toBe('Remove?');
+ });
+
+ it('shows a spinner, not loading text, while an editor loads', async () => {
+ let finish!: (value: unknown) => void;
+ h.read.mockImplementation((_invoke: unknown, _device: string, target: { id: string }) => target.id === 'settings:bot/avatar' ? new Promise(done => { finish = done; }) : Promise.resolve(home()));
+ await render(); await press(byTest('companionProfile.profile')); await press(byTest('companionProfile.avatar'));
+ expect(container.querySelector('[role="progressbar"]')!.getAttribute('aria-label')).toBe('devices.resources.loading');
+ expect(container.textContent).not.toContain('devices.resources.loading');
+ await act(async () => finish(home()));
+ });
+
+ async function renderCreate(visible = true, online = true) {
+ await act(async () => root.render(createElement(CompanionCreateSheet, { visible, deviceId: 'host', deviceName: 'Mac', collectionId: 'teammates', online, onClose: h.close, onCreated: h.created })));
+ await settle();
+ }
+ const createPanel = (disabled = false) => ({ resource: { ...resource, ref: { ...ref, id: 'create' } }, panels: [{ id: 'create', values: {}, action: { id: 'create-grant', label: 'Create', disabled,
+ fields: [{ id: 'name', label: 'Name', kind: 'text' }, { id: 'avatarImageBase64', label: 'Avatar', kind: 'text' }] } }] });
+
+ it('opens the import source picker after the existing creation sheet closes', async () => {
+ const data = createPanel();
+ h.read.mockResolvedValue({ ...data, resource: { ...data.resource, actions: [{ id: 'open-agent-import', label: 'Import' }] } });
+ h.invoke.mockResolvedValue({ blocks: [{ primitive: 'companion-import', data: { sources: [{ id: 'source', name: 'Ada', kind: 'hermes' }] } }] });
+ await renderCreate();
+ await press(byText('devices.companionImport.entry'));
+ expect(h.sheet.visible).toBe(false);
+ expect(h.invoke).not.toHaveBeenCalled();
+ await act(async () => h.sheet.onClosed()); await settle();
+ expect(h.sheet.visible).toBe(true);
+ expect(byText('Ada · Hermes')).toBeDefined();
+ expect(h.close).not.toHaveBeenCalled();
+ expect(h.created).not.toHaveBeenCalled();
+ });
+
+ it('reopens normal creation and starts a fresh import after closing, while preserving an open import on reconnect', async () => {
+ const data = createPanel();
+ h.read.mockResolvedValue({ ...data, resource: { ...data.resource, actions: [{ id: 'open-agent-import', label: 'Import' }] } });
+ const sources = { blocks: [{ primitive: 'companion-import', data: { sources: [{ id: 'source', name: 'Ada', kind: 'hermes' }] } }] };
+ h.invoke.mockResolvedValue(sources);
+ await renderCreate(); await press(byText('devices.companionImport.entry'));
+ await act(async () => h.sheet.onClosed()); await settle();
+ h.invoke.mockResolvedValueOnce({ blocks: [{ primitive: 'companion-import', data: { preview: { id: 'preview', source: { id: 'source', kind: 'hermes', name: 'Ada' }, name: 'Old import draft', entries: [] } } }] });
+ await press(byText('Ada · Hermes'));
+ const name = () => container.querySelector<HTMLInputElement>('input[aria-label="devices.companionProfile.name"]');
+ expect(name()?.value).toBe('Old import draft');
+ await renderCreate(true, false); await renderCreate(true, true);
+ expect(name()?.value).toBe('Old import draft');
+ await act(async () => h.sheet.onClose()); expect(h.close).toHaveBeenCalledOnce();
+ await renderCreate(false); await renderCreate(true);
+ expect(byText('devices.companionImport.entry')).toBeDefined();
+ expect(container.querySelector<HTMLInputElement>('input[aria-label="Name"]')?.value).toBe('');
+ expect(name()).toBeNull();
+ await press(byText('devices.companionImport.entry'));
+ await act(async () => h.sheet.onClosed()); await settle();
+ expect(byText('Ada · Hermes')).toBeDefined();
+ expect(name()).toBeNull();
+ expect(byText('devices.companionImport.submit')).toBeUndefined();
+ });
+
+ it('gates Create like iOS and offers an explicit Cancel that guards the draft', async () => {
+ h.read.mockResolvedValue(createPanel());
+ await renderCreate();
+ const create = () => byText('devices.companionProfile.create')!;
+ expect(create().disabled).toBe(true);
+ await type('Name', 'Nova'); expect(create().disabled).toBe(false);
+ await act(async () => h.portrait.onChange('')); expect(create().disabled).toBe(true);
+ await act(async () => h.portrait.onChange('portrait')); expect(create().disabled).toBe(false);
+ expect(h.sheet.preventDismiss).toBe(true);
+ await press(byText('devices.common.cancel'));
+ expect(h.close).not.toHaveBeenCalled(); expect(h.alert).toHaveBeenCalledOnce();
+ await act(async () => h.alert.mock.calls[0][2][1].onPress()); expect(h.close).toHaveBeenCalledOnce();
+ });
+
+ it('keeps Create disabled for a disabled host action and cancels a clean form directly', async () => {
+ h.read.mockResolvedValue(createPanel(true));
+ await renderCreate(); await type('Name', 'Nova');
+ expect(byText('devices.companionProfile.create')!.disabled).toBe(true);
+ await type('Name', '');
+ await press(byText('devices.common.cancel'));
+ expect(h.alert).not.toHaveBeenCalled(); expect(h.close).toHaveBeenCalledOnce();
+ });
diff --cc apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx
index 002af96614,54eff01275..0bbfaac67c
--- a/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx
@@@ -14,8 -14,9 +14,9 @@@ vi.mock('@/device-link/remoteResources'
vi.mock('@/components/AppText', () => ({ Text: 'span', TextInput: 'input' }));
vi.mock('@/components/MobilePrimitives', () => ({ MainWindowActionButton: () => null }));
vi.mock('@/components/RemoteCompanionAvatar', () => ({ RemoteCompanionAvatar: () => null }));
-vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: () => null, usesNativePullDownMenu: () => true }));
+vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: () => null, NativeSwitch: () => null, usesNativePullDownMenu: () => true }));
vi.mock('@/session/CompanionSettingsRow', () => ({ CompanionSettingsRow: () => null }));
+ vi.mock('@/session/CompanionChoice', () => ({ CompanionChoice: () => null }));
vi.mock('@/session/CompanionSheet', () => ({ CompanionSheet: () => null }));
vi.mock('@/session/CompanionProfileArtifacts', () => ({ CompanionProfileArtifacts: () => null }));
vi.mock('@/theme', async () => ({ ...await import('@/theme/tokens'), useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}) }));
diff --cc apps/mobile/src/__tests__/androidModelPickerParity.test.tsx
index 0000000000,b0e77a6183..8712e5bf47
mode 000000,100644..100644
--- a/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx
+++ b/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx
@@@ -1,0 -1,1011 +1,1013 @@@
+ // @vitest-environment jsdom
+ /**
+ * Android 模型 / 权限 / 目标面板与 iOS 的交互对齐(外观仍是 SheetModal + RN 自绘行)。
+ * react-native 用 DOM 桩替身渲染,按 testID / aria 属性断言信息结构与交互时机。
+ */
+ import { act, createElement, type ReactNode } from "react";
+ import { createRoot, type Root } from "react-dom/client";
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+ const native = vi.hoisted(() => ({
+ budgetDisabled: false,
+ menu: true,
+ menus: new Map<
+ string,
+ {
+ actions: Array<{ id: string; title: string; state?: string }>;
+ onAction(id: string): void;
+ }
+ >(),
+ onClosed: undefined as (() => void) | undefined,
+ layouts: new Map<
+ string,
+ (event: { nativeEvent: { layout: { y: number } } }) => void
+ >(),
+ }));
+
+ type AnyProps = Record<string, any>;
+ const flatStyle = (style: unknown): AnyProps => {
+ const value = typeof style === "function" ? style({ pressed: false }) : style;
+ if (Array.isArray(value)) return Object.assign({}, ...value.map(flatStyle));
+ return value && typeof value === "object" ? (value as AnyProps) : {};
+ };
++vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => false, getCachedReduceMotionEnabled: () => false }));
+ vi.mock("react-native", async () => {
+ const { createElement: el } = await import("react");
+ const passthrough = ({ children }: AnyProps) => el("div", null, children);
+ const View = ({
+ children,
+ testID,
+ accessibilityRole,
+ accessibilityValue,
+ accessibilityLabel,
+ onLayout,
+ }: AnyProps) => {
+ if (testID && onLayout) native.layouts.set(testID, onLayout);
+ return el(
+ "div",
+ {
+ "data-testid": testID,
+ role: accessibilityRole,
+ "aria-label": accessibilityLabel,
+ "aria-valuenow": accessibilityValue?.now,
+ },
+ children,
+ );
+ };
+ class Value {
+ setValue() {}
+ interpolate() {
+ return this;
+ }
+ }
+ return {
+ ActivityIndicator: () => null,
+ Animated: {
+ Value,
+ View: passthrough,
+ timing: () => ({ start: (cb?: () => void) => cb?.() }),
+ },
+ Platform: {
+ OS: "android",
+ select: (v: AnyProps) => v.android ?? v.default,
+ },
+ Pressable: ({
+ children,
+ onPress,
+ testID,
+ disabled,
+ accessibilityLabel,
+ accessibilityState,
+ onLayout,
+ }: AnyProps) => {
+ if (onLayout) native.layouts.set(`${testID}:selectedRow`, onLayout);
+ return el(
+ "button",
+ {
+ "data-testid": testID,
+ "aria-label": accessibilityLabel,
+ "aria-selected":
+ accessibilityState?.selected === undefined
+ ? undefined
+ : String(accessibilityState.selected),
+ "aria-expanded":
+ accessibilityState?.expanded === undefined
+ ? undefined
+ : String(accessibilityState.expanded),
+ disabled,
+ onClick: onPress,
+ },
+ children,
+ );
+ },
+ ScrollView: passthrough,
+ StyleSheet: { create: <T,>(styles: T) => styles, hairlineWidth: 1 },
++ Easing: { bezier: () => (t: number) => t },
+ View,
+ useWindowDimensions: () => ({ height: 800, width: 400 }),
+ };
+ });
+ vi.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),
+ }));
+ vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: AnyProps) =>
+ values?.mode ? `${key}:${values.mode}` : key,
+ }),
+ }));
+ vi.mock("lucide-react-native", async () => {
+ const { createElement: el } = await import("react");
+ const icon =
+ (name: string) =>
+ ({ color, fill }: AnyProps) =>
+ el("i", { "data-icon": name, "data-color": color, "data-fill": fill });
+ return Object.fromEntries(
+ [
+ "Brain",
+ "Check",
+ "ChevronDown",
+ "ChevronRight",
+ "ChevronsUpDown",
+ "LayoutGrid",
+ "Search",
+ "SlidersHorizontal",
+ "Star",
+ "X",
+ "Zap",
+ "Hand",
+ "Sparkles",
+ "TriangleAlert",
+ ].map((name) => [name, icon(name)]),
+ );
+ });
+ vi.mock("@/components/AppText", async () => {
+ const { createElement: el } = await import("react");
+ return {
+ Text: ({ children, numberOfLines, style, testID }: AnyProps) =>
+ el(
+ "span",
+ {
+ "data-testid": testID,
+ "data-color": flatStyle(style).color,
+ "data-lines": numberOfLines,
+ },
+ children,
+ ),
+ TextInput: ({
+ value,
+ onChangeText,
+ onFocus,
+ testID,
+ accessibilityLabel,
+ }: AnyProps) =>
+ el("input", {
+ "aria-label": accessibilityLabel,
+ "data-testid": testID,
+ onChange: (event: { target: { value: string } }) =>
+ onChangeText?.(event.target.value),
+ onFocus,
+ value: value ?? "",
+ }),
+ };
+ });
+ vi.mock("@/theme", async () => {
+ const tokens = await import("@/theme/tokens");
+ const colors = new Proxy({}, { get: (_target, key) => `c.${String(key)}` });
+ return {
+ ...tokens,
+ useTheme: () => ({ colors, mode: "light" }),
+ useThemedStyles: (factory: (c: unknown) => unknown) => factory(colors),
+ };
+ });
+ vi.mock("@/platform/chrome", async () => {
+ const { createElement: el } = await import("react");
+ return {
+ usesNativePullDownMenu: () => native.menu,
+ NativePullDownMenu: ({ actions, onAction, children, testID }: AnyProps) => {
+ if (native.menu) native.menus.set(testID, { actions, onAction });
+ return el("div", null, children);
+ },
+ NativeSwitch: ({ value, onValueChange, testID, disabled }: AnyProps) =>
+ el("button", {
+ "data-testid": testID,
+ "aria-checked": String(value),
+ disabled,
+ onClick: () => onValueChange(!value),
+ }),
+ };
+ });
+ vi.mock("@/components/MobileAgentMark", async () => {
+ const { createElement: el } = await import("react");
+ return {
+ MobileAgentMark: ({ agentKind }: AnyProps) =>
+ el("i", { "data-agent": agentKind }),
+ };
+ });
+ vi.mock("@/session/MobileProviderMark", async () => {
+ const { createElement: el } = await import("react");
+ return {
+ MobileProviderMark: ({ providerId }: AnyProps) =>
+ el("i", { "data-provider-mark": providerId }),
+ MobileModelIconMark: ({ providerId }: AnyProps) =>
+ el("i", { "data-model-mark": providerId }),
+ };
+ });
+ vi.mock("@/session/sessionAgentSwitch", () => ({
+ mobileAgentLabel: (agent: string) => `agent:${agent}`,
+ }));
+ vi.mock("@/session/contextSheetModel", () => ({
+ computeContextSheetSnapHeights: () => ({ half: 400, full: 700 }),
+ }));
+ vi.mock("@/session/SheetModal", async () => {
+ const { createElement: el } = await import("react");
+ return {
+ SheetModal: ({ children, onClosed, visible }: AnyProps) => {
+ native.onClosed = onClosed;
+ return visible ? el("div", null, children) : null;
+ },
+ };
+ });
+ vi.mock("@/session/SheetSurface", async () => {
+ const { createElement: el } = await import("react");
+ return {
+ SheetSurface: ({ children, title, pinnedTop, onBack, testID }: AnyProps) =>
+ el(
+ "section",
+ { "data-testid": testID, "data-title": title },
+ onBack
+ ? el("button", { "data-testid": `${testID}.back`, onClick: onBack })
+ : null,
+ pinnedTop,
+ children,
+ ),
+ };
+ });
+ vi.mock("@/session/draftModelMemory", () => ({
+ useDraftModelMemoryVersion: () => 0,
+ }));
+ vi.mock("@/session/sessionModelMirror", () => ({
+ useSessionModelMirrorVersion: () => 0,
+ }));
+ vi.mock("@/session/permissionPresentation", async () => {
+ const { createElement: el } = await import("react");
+ const Icon = ({ color }: AnyProps) =>
+ el("i", { "data-icon": "permission", "data-color": color });
+ return {
+ permissionPresentation: (id: string, label?: string) => ({
+ Icon,
+ label: label ?? id,
+ accent:
+ id === "auto"
+ ? "auto"
+ : id === "bypassPermissions"
+ ? "bypass"
+ : "neutral",
+ }),
+ permissionAccentColor: (accent: string, colors: AnyProps) =>
+ accent === "auto"
+ ? colors.permAutoAccent
+ : accent === "bypass"
+ ? colors.statusAccent
+ : colors.textSecondary,
+ };
+ });
+ vi.mock("@/session/goalStatusLabel", () => ({
+ GOAL_STATUS_LABEL: {},
+ goalReasonText: (reason?: string) => reason || null,
+ goalStatusLabel: (status: string) => `status:${status}`,
+ }));
+ vi.mock("@/session/modelPickerRows", () => ({
+ budgetDisabledHint: () => "needs key",
+ budgetRowDisabled: () => native.budgetDisabled,
+ effortLabelFor: (_model: unknown, effort: string) => `effort:${effort}`,
+ modelRowAccessibilityLabel: ({ baseLabel }: AnyProps) => baseLabel,
+ rowEffortOf: ({ selected, liveEffort, model }: AnyProps) =>
+ selected ? liveEffort : model.defaultEffort,
+ rowFastEditable: () => true,
+ rowFastOn: ({ selected, liveFastMode }: AnyProps) => selected && liveFastMode,
+ }));
+
+ vi.mock("@/i18n", () => ({
+ i18n: { t: (key: string) => key, language: "en", resolvedLanguage: "en" },
+ }));
+ vi.mock("@/session/UnifiedModelPickerSheet", () => ({
+ UnifiedModelPickerSheet: () => null,
+ }));
+ vi.mock("@/session/ComposerSheet", () => ({ ComposerSheet: () => null }));
+ vi.mock("@/session/ModelPickerNativeHeader", () => ({
+ ModelPickerNativeHeader: () => null,
+ }));
+ vi.mock("@/session/MobileAgentSwitcher", () => ({
+ MobileAgentSwitcher: () => null,
+ }));
+
+ import { UnifiedModelPickerView } from "@/session/UnifiedModelPickerView";
+ import { ModelPickerSheet } from "@/session/ModelPickerSheet";
+ import { MobileModelPickerList } from "@/session/MobileModelPickerList";
+ import { MobilePermissionPickerList } from "@/session/MobilePermissionPickerList";
+ import { NativePermissionSheet } from "@/session/NativePermissionSheet";
+ import { ContextSheetGoalView } from "@/session/ContextSheetGoalView";
+
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ let root: Root;
+ let host: HTMLDivElement;
+ beforeEach(() => {
+ native.menu = true;
+ native.menus.clear();
+ native.onClosed = undefined;
+ native.layouts.clear();
+ host = document.createElement("div");
+ document.body.appendChild(host);
+ root = createRoot(host);
+ });
+ afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+ });
+ const byId = (id: string) =>
+ host.querySelector(`[data-testid="${id}"]`) as HTMLElement | null;
+ const click = (id: string) =>
+ act(() => (byId(id) as HTMLButtonElement).click());
+ const render = (node: ReactNode) => act(() => root.render(node as never));
+
+ function unifiedRow(overrides: AnyProps = {}) {
+ return {
+ key: "p1::m1",
+ entry: {
+ displayName: "Model One",
+ providerId: "p1",
+ modelId: "m1",
+ capabilities: {
+ codex: {
+ wireModelId: "m1-codex",
+ efforts: ["low", "high"],
+ defaultEffort: "high",
+ },
+ pi: { wireModelId: "m1-pi", efforts: [], defaultEffort: null },
+ },
+ },
+ config: {
+ providerId: "p1",
+ modelId: "m1",
+ agent: "codex",
+ effort: "low",
+ fast: false,
+ },
+ selected: true,
+ disabled: false,
+ subtitle: "[email protected] · Low",
+ costMarks: "$$",
+ effortLabel: "Low",
+ quotaLabel: "2d · 70%",
+ providerMark: { providerId: "p1", name: "Provider One" },
+ ...overrides,
+ };
+ }
+
+ function unifiedProps(overrides: AnyProps = {}): AnyProps {
+ return {
+ visible: true,
+ onClose: vi.fn(),
+ title: "models.picker.title",
+ testID: "modelSheet",
+ query: "",
+ onQuery: vi.fn(),
+ filter: "all",
+ onFilter: vi.fn(),
+ filters: [
+ { id: "all", label: "All models" },
+ { id: "favorites", label: "Favorites" },
+ {
+ id: "p1",
+ label: "Provider One",
+ providerMark: { providerId: "p1", name: "Provider One" },
+ quota: { remaining: 40, label: "Week · 40% left" },
+ },
+ ],
+ groups: [
+ {
+ key: "favorites",
+ title: "Favorites",
+ rows: [
+ unifiedRow({
+ key: "fav-1",
+ selected: false,
+ favorite: { uid: "fav-1" },
+ }),
+ ],
+ },
+ {
+ key: "p1",
+ title: "Provider One · [email protected]",
+ rows: [unifiedRow()],
+ },
+ ],
+ busy: false,
+ error: null,
+ loading: false,
+ emptyHint: "empty",
+ onSelect: vi.fn(),
+ onOptions: vi.fn(),
+ ...overrides,
+ };
+ }
+
+ describe("Android unified model picker follows the iOS structure", () => {
+ it("pins a labelled search field with a clear action and preserves the query value", () => {
+ const props = unifiedProps({ query: "gpt" });
+ render(createElement(UnifiedModelPickerView, props as never));
+ const input = byId("modelSheet.search") as HTMLInputElement;
+ expect(input.getAttribute("aria-label")).toBe(
+ "models.picker.searchAccessibility",
+ );
+ expect(input.value).toBe("gpt");
+ const clear = byId("modelSheet.search.clear")!;
+ expect(clear.getAttribute("aria-label")).toBe(
+ "devices.detail.search.clearA11y",
+ );
+ click("modelSheet.search.clear");
+ expect(props.onQuery).toHaveBeenCalledWith("");
+ });
+
+ it("replaces chip filters with a Source entry that opens a secondary page with quota bars", () => {
+ const props = unifiedProps();
+ render(createElement(UnifiedModelPickerView, props as never));
+ expect(byId("modelSheet.source.p1")).toBeNull();
+ click("modelSheet.filter");
+ expect(byId("modelSheet")!.getAttribute("data-title")).toBe(
+ "models.unified.source",
+ );
+ // 搜索框只在列表页出现;来源页有返回。
+ expect(byId("modelSheet.search")).toBeNull();
+ const quota = byId("modelSheet.source.p1.quota")!;
+ expect(quota.getAttribute("role")).toBe("progressbar");
+ expect(quota.getAttribute("aria-valuenow")).toBe("40");
+ expect(byId("modelSheet.source.all")!.getAttribute("aria-selected")).toBe(
+ "true",
+ );
+ click("modelSheet.source.p1");
+ expect(props.onFilter).toHaveBeenCalledWith("p1");
+ expect(byId("modelSheet")!.getAttribute("data-title")).toBe(
+ "models.picker.title",
+ );
+ expect(byId("modelSheet.search")).not.toBeNull();
+ });
+
+ it("renders titled groups in the given order with selection state and separate settings targets", () => {
+ const props = unifiedProps();
+ render(createElement(UnifiedModelPickerView, props as never));
+ const groups = [
+ ...host.querySelectorAll('[data-testid^="modelSheet.group."]'),
+ ].map((node) => node.getAttribute("data-testid"));
+ expect(groups).toEqual([
+ "modelSheet.group.favorites",
+ "modelSheet.group.p1",
+ ]);
+ expect(host.textContent).toContain("Provider One · [email protected]");
+ expect(byId("modelSheet.model.p1::m1")!.getAttribute("aria-selected")).toBe(
+ "true",
+ );
+ expect(byId("modelSheet.model.fav-1")!.getAttribute("aria-selected")).toBe(
+ "false",
+ );
+ click("modelSheet.model.p1::m1");
+ expect(props.onSelect).toHaveBeenCalledTimes(1);
+ click("modelSheet.model.p1::m1.optionsButton");
+ expect(props.onOptions).toHaveBeenCalledTimes(1);
+ });
+
+ function optionsProps(overrides: AnyProps = {}) {
+ const row = unifiedRow();
+ return unifiedProps({
+ onBack: vi.fn(),
+ title: "Model One",
+ options: {
+ row,
+ agents: ["codex", "pi", "claude-code"],
+ fastCapable: true,
+ onChange: vi.fn(),
+ favoritesDisabled: false,
+ onFavorite: vi.fn(),
+ onReset: vi.fn(),
+ context: "Provider One · 200K context",
+ price: "Per 1M tokens\nInput $1 · Output $2",
+ ...overrides,
+ },
+ });
+ }
+
+ it("opens Harness as a secondary page and returns to settings after choosing", () => {
+ const props = optionsProps();
+ render(createElement(UnifiedModelPickerView, props as never));
+ expect(byId("modelSheet.harness")!.textContent).toContain("agent:codex");
+ click("modelSheet.harness");
+ expect(byId("modelSheet")!.getAttribute("data-title")).toBe(
+ "models.unified.harness",
+ );
+ expect(
+ byId("modelSheet.harness.codex")!.getAttribute("aria-selected"),
+ ).toBe("true");
+ // 缺能力的 Harness 不写配置(不再使用非空断言)。
+ click("modelSheet.harness.claude-code");
+ expect(props.options.onChange).not.toHaveBeenCalled();
+ click("modelSheet.harness.pi");
+ expect(props.options.onChange).toHaveBeenCalledWith({
+ providerId: "p1",
+ modelId: "m1-pi",
+ agent: "pi",
+ effort: "",
+ fast: false,
+ });
+ expect(byId("modelSheet")!.getAttribute("data-title")).toBe("Model One");
+ expect(byId("modelSheet.harness")).not.toBeNull();
+ });
+
+ it("uses a pull-down menu for effort, a switch for Fast and standalone favorite / reset rows", () => {
+ const props = optionsProps();
+ render(createElement(UnifiedModelPickerView, props as never));
+ const menu = native.menus.get("modelSheet.effortMenu")!;
+ expect(menu.actions.map((action) => [action.id, action.state])).toEqual([
+ ["low", "on"],
+ ["high", "off"],
+ ]);
+ act(() => menu.onAction("high"));
+ expect(props.options.onChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ effort: "high" }),
+ );
+ act(() => menu.onAction("unknown"));
+ expect(props.options.onChange).toHaveBeenCalledTimes(1);
+ expect(byId("modelSheet.fast")!.getAttribute("aria-checked")).toBe("false");
+ click("modelSheet.fast");
+ expect(props.options.onChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ fast: true }),
+ );
+ click("modelSheet.favorite");
+ expect(props.options.onFavorite).toHaveBeenCalledTimes(1);
+ click("modelSheet.reset");
+ expect(props.options.onReset).toHaveBeenCalledTimes(1);
+ expect(byId("modelSheet.price")!.textContent).toContain("Input $1");
+ });
+
+ it("falls back to inline effort rows when the build has no native menu", () => {
+ native.menu = false;
+ const props = optionsProps();
+ render(createElement(UnifiedModelPickerView, props as never));
+ expect(byId("modelSheet.effort.high")).toBeNull();
+ click("modelSheet.effort");
+ expect(byId("modelSheet.effort.low")!.getAttribute("aria-selected")).toBe(
+ "true",
+ );
+ click("modelSheet.effort.high");
+ expect(props.options.onChange).toHaveBeenCalledWith(
+ expect.objectContaining({ effort: "high" }),
+ );
+ expect(byId("modelSheet.effort.high")).toBeNull();
+ });
+
+ it("hides the reset row for favorites", () => {
+ const props = optionsProps({
+ row: unifiedRow({ favorite: { uid: "fav-1" } }),
+ });
+ render(createElement(UnifiedModelPickerView, props as never));
+ expect(byId("modelSheet.favorite")!.textContent).toContain(
+ "models.unified.removeFavorite",
+ );
+ expect(byId("modelSheet.reset")).toBeNull();
+ });
+ });
+
+ describe("Android legacy model list groups by source like iOS", () => {
+ const provider = (id: string, name: string, extra: AnyProps = {}) => ({
+ id,
+ name,
+ ...extra,
+ });
+ const model = (id: string) => ({
+ id,
+ displayName: `Model ${id}`,
+ efforts: ["low"],
+ defaultEffort: "low",
+ supportsFastMode: true,
+ });
+
+ it("titles groups as source · account and shows subscription · effort · Fast with a check mark", () => {
+ const subscription = provider("sub", "ChatGPT", {
+ access: { kind: "subscription" },
+ openAiAccount: { identity: "[email protected]" },
+ });
+ const api = provider("api", "API [email protected]", {
+ openAiAccount: { identity: "[email protected]" },
+ });
+ render(
+ createElement(MobileModelPickerList, {
+ providerRows: [
+ { provider: subscription, model: model("a") },
+ { provider: subscription, model: model("b") },
+ { provider: api, model: model("c") },
+ ],
+ flatOptions: [],
+ activeModelId: "a",
+ activeSourceId: "sub",
+ agentKind: "codex",
+ capabilities: { hasFastMode: true },
+ selectedEffort: "high",
+ selectedFastMode: true,
+ onSelectProviderRow: vi.fn(),
+ onSelectFlatModel: vi.fn(),
+ onOpenOptions: vi.fn(),
+ testID: "list",
+ } as never),
+ );
+ const groups = [...host.querySelectorAll('[data-testid^="list.group."]')];
+ expect(groups.map((node) => node.getAttribute("data-testid"))).toEqual([
+ "list.group.sub",
+ "list.group.api",
+ ]);
+ expect(groups[0].textContent).toContain("ChatGPT · [email protected]");
+ // 账号已写进来源名时不重复。
+ expect(groups[1].textContent).toContain("API [email protected]");
+ expect(groups[1].textContent).not.toContain(
+ );
+ const rows = [...host.querySelectorAll('button[data-testid="list"]')];
+ expect(rows.map((row) => row.getAttribute("aria-selected"))).toEqual([
+ "true",
+ "false",
+ "false",
+ ]);
+ expect(rows[0].textContent).toContain(
+ "models.picker.subscriptionBadge · effort:high · models.options.fastMode",
+ );
+ expect(rows[0].querySelector('[data-icon="Check"]')).not.toBeNull();
+ expect(rows[1].querySelector('[data-icon="Check"]')).toBeNull();
+ // 来源品牌 mark 保留。
+ expect(rows[0].querySelector('[data-model-mark="sub"]')).not.toBeNull();
+ });
+
+ it("keeps the missing-key hint on its own unrestricted line instead of truncating it", () => {
+ native.budgetDisabled = true;
+ try {
+ render(
+ createElement(MobileModelPickerList, {
+ providerRows: [{ provider: provider("sub", "ChatGPT", { access: { kind: "subscription" } }), model: model("a") }],
+ flatOptions: [],
+ activeModelId: "b",
+ activeSourceId: "sub",
+ agentKind: "codex",
+ capabilities: { hasFastMode: true },
+ onSelectProviderRow: vi.fn(),
+ onSelectFlatModel: vi.fn(),
+ testID: "list",
+ } as never),
+ );
+ const hint = host.querySelector('[data-testid="list.disabledHint"]')!;
+ expect(hint.textContent).toBe("needs key");
+ expect(hint.getAttribute("data-lines")).toBeNull();
+ const row = host.querySelector('button[data-testid="list"]')!;
+ const meta = [...row.querySelectorAll('span[data-lines="1"]')].map((node) => node.textContent);
+ expect(meta.some((text) => text?.includes("needs key"))).toBe(false);
+ } finally {
+ native.budgetDisabled = false;
+ }
+ });
+
+ it("reports the selected row offset in scroll-content coordinates after grouping", () => {
+ const onSelectedRowLayout = vi.fn();
+ const rowsFor = (id: string) => ({
+ provider: provider(id, id),
+ model: model(`${id}-m`),
+ });
+ render(
+ createElement(MobileModelPickerList, {
+ providerRows: [rowsFor("first"), rowsFor("second")],
+ flatOptions: [],
+ activeModelId: "second-m",
+ activeSourceId: "second",
+ onSelectProviderRow: vi.fn(),
+ onSelectFlatModel: vi.fn(),
+ onSelectedRowLayout,
+ testID: "list",
+ } as never),
+ );
+ const layout = (key: string, y: number) =>
+ act(() => native.layouts.get(key)!({ nativeEvent: { layout: { y } } }));
+ // 选中行的布局回调挂在分组的直接子节点上(不是内层按钮),y 相对分组。
+ expect(native.layouts.has("list:selectedRow")).toBe(false);
+ layout("list.selectedRow", 40);
+ expect(onSelectedRowLayout).not.toHaveBeenCalled();
+ layout("list.group.second", 200);
+ expect(onSelectedRowLayout).toHaveBeenLastCalledWith(240);
+ });
+
+ it("adds the flat fallback container offset as well", () => {
+ const onSelectedRowLayout = vi.fn();
+ render(
+ createElement(MobileModelPickerList, {
+ providerRows: [],
+ flatOptions: [
+ { id: "a", label: "A", efforts: [] },
+ { id: "b", label: "B", efforts: [] },
+ ],
+ activeModelId: "b",
+ activeSourceId: null,
+ onSelectProviderRow: vi.fn(),
+ onSelectFlatModel: vi.fn(),
+ onSelectedRowLayout,
+ testID: "flat",
+ } as never),
+ );
+ act(() => native.layouts.get("flat.selectedRow")!({ nativeEvent: { layout: { y: 60 } } }));
+ expect(onSelectedRowLayout).not.toHaveBeenCalled();
+ act(() => native.layouts.get("flat.group.__flat__")!({ nativeEvent: { layout: { y: 120 } } }));
+ expect(onSelectedRowLayout).toHaveBeenLastCalledWith(180);
+ });
+ });
+
+ describe("Android permission picker selection matches iOS", () => {
+ const options = [
+ { id: "ask", label: "Ask" },
+ { id: "auto", label: "Auto" },
+ { id: "bypassPermissions", label: "Full access" },
+ ];
+
+ it("tints only the selected icon; text and check stay neutral", () => {
+ render(
+ createElement(MobilePermissionPickerList, {
+ options,
+ activeMode: "auto",
+ onSelect: vi.fn(),
+ testID: "perm",
+ } as never),
+ );
+ const rows = [...host.querySelectorAll('button[data-testid="perm"]')];
+ expect(rows.map((row) => row.getAttribute("aria-selected"))).toEqual([
+ "false",
+ "true",
+ "false",
+ ]);
+ const icon = (row: Element) =>
+ row.querySelector('[data-icon="permission"]')!.getAttribute("data-color");
+ expect(icon(rows[1])).toBe("c.permAutoAccent");
+ expect(icon(rows[2])).toBe("c.textSecondary");
+ expect(rows[1].querySelector("span")!.getAttribute("data-color")).toBe(
+ "c.textPrimary",
+ );
+ expect(
+ rows[1].querySelector('[data-icon="Check"]')!.getAttribute("data-color"),
+ ).toBe("c.textPrimary");
+ });
+
+ it("closes the Android sheet first and applies the mode only after the close finishes", () => {
+ const order: string[] = [];
+ const onClose = vi.fn(() => order.push("close"));
+ const onSelect = vi.fn((mode: string) => order.push(`select:${mode}`));
+ render(
+ createElement(NativePermissionSheet, {
+ visible: true,
+ onClose,
+ onSelect,
+ options,
+ activeMode: "ask",
+ testID: "session.permissionSheet",
+ } as never),
+ );
+ const rows = host.querySelectorAll(
+ 'button[data-testid="session.permissionSheet.option"]',
+ );
+ act(() => (rows[2] as HTMLButtonElement).click());
+ expect(order).toEqual(["close"]);
+ act(() => native.onClosed?.());
+ expect(order).toEqual(["close", "select:bypassPermissions"]);
+ // 背板关闭等后续 onClosed 不会重放上一次选择。
+ act(() => native.onClosed?.());
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("Android goal form follows the iOS form", () => {
+ const base = {
+ busy: false,
+ error: null,
+ onSetGoal: vi.fn(),
+ onPauseGoal: vi.fn(),
+ onResumeGoal: vi.fn(),
+ onClearGoal: vi.fn(),
+ };
+
+ it("keeps limits collapsed until Advanced opens, then edits them through pull-down menus", () => {
+ const onSetGoal = vi.fn();
+ render(
+ createElement(ContextSheetGoalView, {
+ ...base,
+ goal: null,
+ onSetGoal,
+ initialObjective: "目标",
+ } as never),
+ );
+ expect(byId("contextSheet.goalMaxTurnsOptions")).toBeNull();
+ expect(
+ byId("contextSheet.goalAdvancedToggle")!.getAttribute("aria-expanded"),
+ ).toBe("false");
+ click("contextSheet.goalAdvancedToggle");
+ expect(
+ byId("contextSheet.goalAdvancedToggle")!.getAttribute("aria-expanded"),
+ ).toBe("true");
+ const turns = native.menus.get("contextSheet.goalMaxTurnsOptions.menu")!;
+ expect(turns.actions.map((action) => action.id)).toEqual([
+ "10",
+ "20",
+ "50",
+ "100",
+ "unlimited",
+ ]);
+ expect(turns.actions.find((action) => action.state === "on")!.id).toBe(
+ "unlimited",
+ );
+ act(() => turns.onAction("20"));
+ const budget = native.menus.get("contextSheet.goalBudgetOptions.menu")!;
+ expect(budget.actions.map((action) => action.title)).toEqual([
+ "500K",
+ "1M",
+ "2M",
+ "5M",
+ "interaction.contextSheet.unlimited",
+ ]);
+ click("contextSheet.goalStartButton");
+ expect(onSetGoal).toHaveBeenCalledWith({
+ objective: "目标",
+ limits: { maxTurns: 20, budgetTokens: null, noProgressLimit: 3 },
+ });
+ });
+
+ it("falls back to inline limit choices without a native menu", () => {
+ native.menu = false;
+ const onSetGoal = vi.fn();
+ render(
+ createElement(ContextSheetGoalView, {
+ ...base,
+ goal: null,
+ onSetGoal,
+ initial: {
+ objective: "恢复",
+ limits: { maxTurns: 17, budgetTokens: null, noProgressLimit: 3 },
+ },
+ } as never),
+ );
+ click("contextSheet.goalAdvancedToggle");
+ click("contextSheet.goalNoProgressOptions.trigger");
+ expect(
+ byId("contextSheet.goalNoProgressOptions.option.3")!.getAttribute(
+ "aria-selected",
+ ),
+ ).toBe("true");
+ click("contextSheet.goalNoProgressOptions.option.unlimited");
+ expect(byId("contextSheet.goalNoProgressOptions.option.3")).toBeNull();
+ click("contextSheet.goalMaxTurnsOptions.trigger");
+ // 历史自定义值前置保留。
+ expect(
+ byId("contextSheet.goalMaxTurnsOptions.option.17")!.getAttribute(
+ "aria-selected",
+ ),
+ ).toBe("true");
+ click("contextSheet.goalStartButton");
+ expect(onSetGoal).toHaveBeenCalledWith({
+ objective: "恢复",
+ limits: { maxTurns: 17, budgetTokens: null, noProgressLimit: null },
+ });
+ });
+
+ it("shows the disabled hint like iOS when creation is unavailable", async () => {
+ const { ContextSheetGoalCreateForm } =
+ await import("@/session/ContextSheetGoalView");
+ render(
+ createElement(ContextSheetGoalCreateForm, {
+ busy: false,
+ error: null,
+ onSetGoal: vi.fn(),
+ disabled: true,
+ disabledHint: "not ready",
+ } as never),
+ );
+ expect(byId("contextSheet.goalDisabledHint")!.textContent).toBe(
+ "not ready",
+ );
+ });
+
+ it.each([
+ [
+ "active",
+ ["contextSheet.goalPauseButton", "contextSheet.goalClearButton"],
+ ],
+ [
+ "paused",
+ ["contextSheet.goalResumeButton", "contextSheet.goalClearButton"],
+ ],
+ ["completed", ["contextSheet.goalClearButton"]],
+ ])("orders the %s status view like iOS", (status, actions) => {
+ render(
+ createElement(ContextSheetGoalView, {
+ ...base,
+ goal: {
+ status,
+ objective: "写完文档",
+ turnsUsed: 3,
+ tokensUsed: 1_000_000,
+ maxTurns: 10,
+ budgetTokens: null,
+ lastReason: "waiting",
+ },
+ } as never),
+ );
+ const text = host.textContent ?? "";
+ const order = [
+ `status:${status}`,
+ "写完文档",
+ "interaction.contextSheet.goalMeta",
+ "waiting",
+ ].map((part) => text.indexOf(part));
+ expect(order.every((index) => index >= 0)).toBe(true);
+ expect([...order].sort((a, b) => a - b)).toEqual(order);
+ const buttons = [
+ ...host.querySelectorAll('button[data-testid^="contextSheet.goal"]'),
+ ].map((node) => node.getAttribute("data-testid"));
+ expect(buttons).toEqual(actions);
+ });
+ });
+
+ describe("Android legacy model sheet exposes permissions as a standalone row like iOS", () => {
+ function sheetProps(overrides: AnyProps = {}) {
+ return {
+ visible: true,
+ onClose: vi.fn(),
+ providers: [],
+ flatOptions: [],
+ providersReady: true,
+ agentKind: "codex",
+ capabilities: null,
+ activeModelId: "",
+ selectedProviderId: null,
+ selectedEffort: "",
+ selectedFastMode: false,
+ onSelectProviderRow: vi.fn(),
+ onSelectFlatModel: vi.fn(),
+ permissionOptions: [
+ { id: "ask", label: "Ask" },
+ { id: "auto", label: "Auto" },
+ ],
+ activePermissionMode: "auto",
+ onSelectPermissionMode: vi.fn(),
+ keyboardAvoidingBehavior: undefined,
+ testID: "modelSheet",
+ ...overrides,
+ };
+ }
+
+ it("shows a Permissions row with the current mode and opens the permission page", () => {
+ const props = sheetProps();
+ render(createElement(ModelPickerSheet, props as never));
+ const row = byId("modelSheet.permissionTrigger")!;
+ expect(row.textContent).toContain("models.picker.permissionTitle");
+ expect(row.textContent).toContain("Auto");
+ expect(row.getAttribute("aria-label")).toBe(
+ "models.picker.permissionModeAccessibility:Auto",
+ );
+ click("modelSheet.permissionTrigger");
+ const options = host.querySelectorAll(
+ 'button[data-testid="modelSheet.permissionOption"]',
+ );
+ expect(options).toHaveLength(2);
+ act(() => (options[0] as HTMLButtonElement).click());
+ expect(props.onSelectPermissionMode).toHaveBeenCalledWith("ask");
+ expect(
+ host.querySelector('button[data-testid="modelSheet.permissionOption"]'),
+ ).toBeNull();
+ });
+
+ it("omits the row when the host provides its own permission control", () => {
+ render(
+ createElement(
+ ModelPickerSheet,
+ sheetProps({ hidePermissionTrigger: true }) as never,
+ ),
+ );
+ expect(byId("modelSheet.permissionTrigger")).toBeNull();
+ });
+
+ it("adds a clear action to the search field", () => {
+ render(createElement(ModelPickerSheet, sheetProps() as never));
+ expect(byId("modelSheet.search.clear")).toBeNull();
+ act(() => {
+ const input = byId("modelSheet.search") as HTMLInputElement;
+ const setter = Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ "value",
+ )!.set!;
+ setter.call(input, "gpt");
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ expect((byId("modelSheet.search") as HTMLInputElement).value).toBe("gpt");
+ click("modelSheet.search.clear");
+ expect((byId("modelSheet.search") as HTMLInputElement).value).toBe("");
+ });
+ });
diff --cc apps/mobile/src/__tests__/androidSessionInteractionParity.test.tsx
index 0000000000,936dc843d6..5a50aa6117
mode 000000,100644..100644
--- a/apps/mobile/src/__tests__/androidSessionInteractionParity.test.tsx
+++ b/apps/mobile/src/__tests__/androidSessionInteractionParity.test.tsx
@@@ -1,0 -1,126 +1,128 @@@
+ // @vitest-environment jsdom
+ import { readFileSync } from 'node:fs';
+ import { resolve } from 'node:path';
+ import { act, createElement, type ReactNode } from 'react';
+ import { createRoot, type Root } from 'react-dom/client';
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+ const sheet = vi.hoisted(() => ({ onClosed: undefined as (() => void) | undefined }));
+
++vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => false, getCachedReduceMotionEnabled: () => false }));
+ vi.mock('react-native', () => ({
+ ActivityIndicator: () => null,
+ Pressable: ({ children, onPress, testID }: { children?: ReactNode; onPress?: () => void; testID?: string }) =>
+ createElement('button', { 'data-testid': testID, onClick: onPress }, children as ReactNode),
+ StyleSheet: { create: <T,>(styles: T) => styles, hairlineWidth: 1 },
+ View: ({ children }: { children?: ReactNode }) => createElement('div', null, children),
+ useWindowDimensions: () => ({ height: 800, width: 400 }),
+ }));
+ vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }) }));
+ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+ vi.mock('lucide-react-native', () => ({ ChevronRight: () => null }));
+ vi.mock('@/components/AppText', () => ({
+ Text: ({ children }: { children?: ReactNode }) => createElement('span', null, children),
+ }));
+ vi.mock('@/theme', () => ({
+ fontWeight: {}, iconSize: {}, iconStroke: {}, lineHeight: {}, radius: {}, spacing: {}, typeScale: {},
+ useTheme: () => ({ colors: {} }),
+ useThemedStyles: () => new Proxy({}, { get: () => ({}) }),
+ }));
+ vi.mock('@/session/contextSheetModel', () => ({ computeContextSheetSnapHeights: () => ({}) }));
++vi.mock('@/components/MobilePrimitives', () => ({ MainWindowActionButton: () => null }));
+ vi.mock('@/session/SheetModal', () => ({
+ SheetModal: ({ children, onClosed, visible }: { children?: ReactNode; onClosed?: () => void; visible: boolean }) => {
+ sheet.onClosed = onClosed;
+ return visible ? createElement('div', null, children) : null;
+ },
+ }));
+ vi.mock('@/session/SheetSurface', () => ({
+ SheetSurface: ({ children }: { children?: ReactNode }) => createElement('div', null, children),
+ }));
+
+ import { ContextSheet, ContextSheetRow } from '@/session/ContextSheet';
+
+ const readTextLf = (path: string) => String(readFileSync(resolve(process.cwd(), path), 'utf8')).replace(/\r\n/g, '\n');
+
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ let root: Root;
+ let container: HTMLDivElement;
+ beforeEach(() => {
+ sheet.onClosed = undefined;
+ container = document.createElement('div');
+ root = createRoot(container);
+ });
+ afterEach(() => act(() => root.unmount()));
+
+ describe('Android context sheet follows the iOS dismiss-then-present order', () => {
+ function render(onClose: () => void, onPress: () => void, dismissBeforePress: boolean) {
+ act(() => root.render(createElement(ContextSheet, {
+ visible: true,
+ onClose,
+ title: 'Context',
+ keyboardAvoidingBehavior: undefined,
+ children: createElement(ContextSheetRow, {
+ dismissBeforePress,
+ icon: null,
+ label: 'Photos',
+ onPress,
+ testID: 'row',
+ }),
+ })));
+ }
+
+ it('closes the sheet first and runs the picker only after the close finishes', () => {
+ const order: string[] = [];
+ render(() => order.push('close'), () => order.push('picker'), true);
+ act(() => (container.querySelector('[data-testid="row"]') as HTMLButtonElement).click());
+ expect(order).toEqual(['close']);
+ act(() => sheet.onClosed?.());
+ expect(order).toEqual(['close', 'picker']);
+ // A later close without a pending row action does not replay the picker.
+ act(() => sheet.onClosed?.());
+ expect(order).toEqual(['close', 'picker']);
+ });
+
+ it('drops a pending picker when the sheet reopens before the close finishes', () => {
+ const order: string[] = [];
+ render(() => order.push('close'), () => order.push('picker'), true);
+ act(() => (container.querySelector('[data-testid="row"]') as HTMLButtonElement).click());
+ // Reopened mid-dismiss: the close never completed, then the user closes normally.
+ act(() => root.render(createElement(ContextSheet, {
+ visible: false, onClose: () => undefined, title: 'Context', keyboardAvoidingBehavior: undefined, children: null,
+ })));
+ render(() => order.push('close'), () => order.push('picker'), true);
+ act(() => sheet.onClosed?.());
+ expect(order).toEqual(['close']);
+ });
+
+ it('keeps ordinary rows immediate', () => {
+ const order: string[] = [];
+ render(() => order.push('close'), () => order.push('open'), false);
+ act(() => (container.querySelector('[data-testid="row"]') as HTMLButtonElement).click());
+ expect(order).toEqual(['open']);
+ });
+ });
+
+ describe('Android session chrome matches the iOS entry points', () => {
+ const source = readTextLf('app/sessions/[sessionId].tsx');
+
+ it('shows remote desktop, files and details; search lives in the details sheet', () => {
+ expect(source).toContain(".filter((action) => action.id === 'files');");
+ const header = source.slice(source.indexOf('<View style={styles.sessionHeaderActions}>'));
+ const more = header.slice(header.indexOf('icon={Ellipsis}') - 200, header.indexOf('testID="session.controlsToggle"'));
+ expect(more).not.toContain('messageOnly');
+ expect(more).toContain("accessibilityLabel={t('session.menu.details')}");
+ const menu = readTextLf('src/session/SessionMenuSheet.tsx');
+ expect(menu).toContain('testID="session.detailsSearch"');
+ });
+
+ it('uses the same compact search tool as iOS', () => {
+ const start = source.indexOf('function SessionSearchSheet(');
+ const search = source.slice(start, source.indexOf('function SessionSyncPlaceholder(', start));
+ expect(search).toContain("? hasHits ? `${activeIndex + 1} / ${hitCount}` : '0 / 0'");
+ expect(search).toContain('autoFocus={visible}');
+ expect(search).toContain('testID="session.searchClearButton"');
+ expect(search).not.toContain('session.searchPreview');
+ expect(search).not.toContain('MOBILE_VISUAL_MOCK_ENABLED');
+ });
+ });
diff --cc apps/mobile/src/__tests__/deviceManagementAndroid.test.tsx
index 0000000000,f2b150bb22..b8f1198f87
mode 000000,100644..100644
--- a/apps/mobile/src/__tests__/deviceManagementAndroid.test.tsx
+++ b/apps/mobile/src/__tests__/deviceManagementAndroid.test.tsx
@@@ -1,0 -1,156 +1,173 @@@
+ import { createElement, type ReactNode } from "react";
+ import { renderToStaticMarkup } from "react-dom/server";
+ import type { DeviceView } from "@cindy/device-link";
+ import { beforeEach, describe, expect, it, vi } from "vitest";
+ import { lightColors } from "@/theme/tokens";
+
+ type Captured = Record<string, unknown>;
+ const captured = vi.hoisted(() => ({
+ icons: [] as { name: string; props: Captured }[],
+ listItems: [] as Captured[],
+ pressables: [] as Captured[],
+ texts: [] as { children: unknown; style: Captured }[],
+ }));
+
+ function flatten(style: unknown): Captured {
+ if (Array.isArray(style)) return Object.assign({}, ...style.map(flatten));
+ return style && typeof style === "object" ? (style as Captured) : {};
+ }
+
+ vi.mock("react-native", () => ({
+ Platform: { OS: "android" },
+ Pressable: (props: Captured & { children?: ReactNode }) => {
+ captured.pressables.push(props);
+ return createElement("div", null, props.children);
+ },
++ RefreshControl: () => null,
+ ScrollView: ({ children }: { children?: ReactNode }) => createElement("div", null, children),
+ StyleSheet: { create: <T,>(styles: T) => styles, hairlineWidth: 1 },
+ View: ({ children }: { children?: ReactNode }) => createElement("div", null, children),
+ }));
+ vi.mock("@/components/AppText", () => ({
+ Text: ({ children, style }: { children?: ReactNode; style?: unknown }) => {
+ captured.texts.push({ children, style: flatten(style) });
+ return createElement("span", null, children);
+ },
+ }));
+ vi.mock("lucide-react-native", () => {
+ const icon = (name: string) => (props: Captured) => {
+ captured.icons.push({ name, props });
+ return null;
+ };
+ return { Monitor: icon("Monitor"), Pencil: icon("Pencil"), Trash2: icon("Trash2") };
+ });
+ vi.mock("@/platform/gestureHandler", () => ({
+ ClassicSwipeable: ({
+ children,
+ renderLeftActions,
+ renderRightActions,
+ }: {
+ children?: ReactNode;
+ renderLeftActions(): ReactNode;
+ renderRightActions(): ReactNode;
+ }) => createElement("div", null, renderLeftActions(), children, renderRightActions()),
+ }));
+ vi.mock("@expo/ui", () => ({
+ ListItem: (props: Captured) => {
+ captured.listItems.push(props);
+ return null;
+ },
+ Text: ({ children }: { children?: ReactNode }) => createElement("span", null, children),
+ }));
+ vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+ vi.mock("@/theme", async () => {
+ const tokens = await import("@/theme/tokens");
- return { ...tokens, useTheme: () => ({ colors: tokens.lightColors, mode: "light" }) };
++ return {
++ ...tokens,
++ useTheme: () => ({ colors: tokens.lightColors, mode: "light" }),
++ useThemedStyles: <T,>(make: (colors: typeof tokens.lightColors) => T) => make(tokens.lightColors),
++ };
+ });
++vi.mock("@/components/MobilePrimitives", () => ({ StatusDot: () => null }));
++vi.mock("@/session/SettingsGroupRows", () => ({
++ SettingsGroup: ({ children }: { children?: ReactNode }) => createElement("div", null, children),
++ useSettingsRowStyles: () => ({}),
++}));
+
+ import { DeviceInformationFields } from "@/device-link/DeviceInformationFields";
+ import { DeviceManagementList } from "@/device-link/DeviceManagementList";
+
+ function device(id: string, online: boolean): DeviceView {
- return { deviceId: id, name: `Mac ${id}`, online } as DeviceView;
++ return { deviceId: id, name: `Mac ${id}`, online, lastSeenAt: null } as DeviceView;
++}
++
++function row(target: DeviceView, statusLabel: string, statusDetail: string) {
++ return { device: target, statusDetail, statusLabel, canOpen: target.online, state: target.online ? "ready" as const : "offline" as const };
+ }
+
+ describe("Android device management follows iOS interactions", () => {
+ beforeEach(() => {
+ captured.icons = [];
+ captured.listItems = [];
+ captured.pressables = [];
+ captured.texts = [];
+ });
+
+ it("uses icon-only swipe actions that keep screen-reader labels", () => {
+ const onRename = vi.fn();
+ const onDelete = vi.fn();
+ const target = device("a", true);
+ renderToStaticMarkup(
+ createElement(DeviceManagementList, {
+ busy: false,
+ onDelete,
+ onOpen: vi.fn(),
+ onRename,
- rows: [{ device: target, statusDetail: "just now", statusLabel: "Online" }],
++ onRefresh: vi.fn(async () => undefined),
++ rows: [row(target, "Online", "just now")],
+ }),
+ );
+ const rename = captured.pressables.find((p) => p.testID === "deviceManagement.rename.a");
+ const remove = captured.pressables.find((p) => p.testID === "deviceManagement.delete.a");
+ expect(rename).toMatchObject({ accessibilityLabel: "devices.list.menu.renameDevice", accessibilityRole: "button" });
+ expect(remove).toMatchObject({ accessibilityLabel: "devices.common.delete", accessibilityRole: "button" });
+ const pencil = captured.icons.find((icon) => icon.name === "Pencil");
+ const trash = captured.icons.find((icon) => icon.name === "Trash2");
+ expect(pencil?.props.color).toBe(lightColors.textPrimary);
+ expect(trash?.props.color).toBe(lightColors.destructive);
+ // 滑动按钮里不再渲染文字标签。
+ const labels = captured.texts.map((text) => text.children);
+ expect(labels).not.toContain("devices.common.delete");
+ expect(labels).not.toContain("devices.list.menu.renameDevice");
+ (rename?.onPress as () => void)();
+ (remove?.onPress as () => void)();
+ expect(onRename).toHaveBeenCalledWith(target);
+ expect(onDelete).toHaveBeenCalledWith(target);
+ });
+
- it("shows only the status when online and status · detail when offline", () => {
++ // 分组列表:离线分组标题已说明「离线」,行内只留时间;在线行显示「状态 · 说明」。名称始终用主字色。
++ it("keeps status · detail for online rows and only the time inside the offline group", () => {
+ renderToStaticMarkup(
+ createElement(DeviceManagementList, {
+ busy: false,
+ onDelete: vi.fn(),
+ onOpen: vi.fn(),
+ onRename: vi.fn(),
++ onRefresh: vi.fn(async () => undefined),
+ rows: [
- { device: device("on", true), statusDetail: "just now", statusLabel: "Online" },
- { device: device("off", false), statusDetail: "2h ago", statusLabel: "Offline" },
++ row(device("on", true), "Online", "just now"),
++ row(device("off", false), "Offline", "2h ago"),
+ ],
+ }),
+ );
+ const contents = captured.texts.map((text) => text.children);
- expect(contents).toContain("Online");
- expect(contents).not.toContain("Online · just now");
- expect(contents).toContain("Offline · 2h ago");
++ expect(contents).toContain("Online · just now");
++ expect(contents).toContain("2h ago");
++ expect(contents).not.toContain("Offline · 2h ago");
+ const offlineName = captured.texts.find((text) => text.children === "Mac off");
+ const onlineName = captured.texts.find((text) => text.children === "Mac on");
- expect(offlineName?.style.color).toBe(lightColors.textSecondary);
++ expect(offlineName?.style.color).toBe(lightColors.textPrimary);
+ expect(onlineName?.style.color).toBe(lightColors.textPrimary);
+ });
+
+ it("puts field labels on the left and values on the right", () => {
+ renderToStaticMarkup(
+ createElement(DeviceInformationFields, {
+ fields: [
+ ["name", "My Mac"],
+ ["status", "Online"],
+ ],
+ }),
+ );
+ expect(captured.listItems).toHaveLength(2);
+ const [name] = captured.listItems;
+ expect(name.children).toBe("devices.management.fields.name");
+ expect(name.supportingText).toBeUndefined();
+ const trailing = name.trailing as { props: { children: string; textStyle: Captured } };
+ expect(trailing.props.children).toBe("My Mac");
+ expect(trailing.props.textStyle).toMatchObject({
+ color: lightColors.textSecondary,
+ textAlign: "right",
+ });
+ });
+ });
diff --cc apps/mobile/src/__tests__/homeChromeDrawer.test.tsx
index 6ec9922deb,da4eae1508..9fec1b7986
--- a/apps/mobile/src/__tests__/homeChromeDrawer.test.tsx
+++ b/apps/mobile/src/__tests__/homeChromeDrawer.test.tsx
@@@ -37,123 -64,175 +64,178 @@@ vi.mock('react-native-reanimated', asyn
const { View } = await import('react-native');
return {
default: { View },
- useSharedValue: (value: number | boolean) => {
- const ref = useRef<{ value: number | boolean } | null>(null);
- if (!ref.current) { ref.current = { value }; driver.values.push(ref.current); }
- return ref.current;
- },
+ useSharedValue: (value: number) => useRef({ value }).current,
useAnimatedStyle: () => ({}),
Easing: { bezier: () => undefined },
- cancelAnimation: vi.fn(),
runOnJS: (fn: unknown) => fn,
- runOnUI: (fn: unknown) => fn,
- withTiming: (to: number, _config: unknown, complete?: (finished: boolean) => void) => {
- driver.animations.push({ to, complete });
- return to;
++ runOnUI: (fn: (...args: never[]) => void) => fn,
++ cancelAnimation: () => {},
+ // 退场完成回调由测试手动投递,用来模拟退出动画结束。
+ withTiming: (value: number, _config?: unknown, done?: (finished: boolean) => void) => {
+ if (done) h.timing.push(done);
+ return value;
},
};
});
- vi.mock('@/platform/gestureHandler', async () => {
- const { View } = await import('react-native');
+
+ vi.mock('react-native-screens', async () => {
+ const { createElement } = await import('react');
return {
- GestureHandlerRootView: View,
- GestureDetector: ({ children }: { children: ReactNode }) => children,
- Gesture: { Pan: () => {
- const chain: Record<string, (...args: any[]) => unknown> = {};
- for (const name of ['enabled', 'activeOffsetX', 'failOffsetX', 'failOffsetY']) chain[name] = () => chain;
- for (const name of ['onStart', 'onUpdate', 'onEnd', 'onFinalize']) {
- chain[name] = callback => { driver.gestures[name] = callback; return chain; };
- }
- return chain;
- } },
+ FullWindowOverlay: ({ children }: { children?: ReactNode }) =>
+ createElement('div', { 'data-testid': 'rn.fullWindowOverlay' }, children),
};
});
- vi.mock('react-native-screens', () => ({ FullWindowOverlay: ({ children }: { children: ReactNode }) => children }));
- vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ left: 0, top: 0, bottom: 0 }) }));
- vi.mock('lucide-react-native', () => Object.fromEntries(
- ['Building2', 'LogOut', 'Monitor', 'Search', 'Settings', 'UsersRound'].map(name => [name, () => null]),
- ));
+
+ vi.mock('react-native-safe-area-context', () => ({
+ useSafeAreaInsets: () => ({ left: 0, top: 0, bottom: 0 }),
+ }));
+
+ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+ vi.mock('lucide-react-native', () => ({
+ LogOut: () => null, Monitor: () => null, Search: () => null, Settings: () => null, UsersRound: () => null,
+ }));
+
vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).View }));
+
vi.mock('@/theme', () => ({ useThemedStyles: () => ({}), useTheme: () => ({ colors: {} }) }));
- vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => driver.reduceMotion }));
+
+ vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => h.reduceMotion }));
+
+ vi.mock('@/platform/gestureHandler', () => {
+ const chain = {
+ enabled: () => chain, activeOffsetX: () => chain, failOffsetX: () => chain,
- failOffsetY: () => chain, onUpdate: () => chain, onEnd: () => chain,
++ failOffsetY: () => chain, onStart: () => chain, onUpdate: () => chain, onEnd: () => chain, onFinalize: () => chain,
+ };
+ return {
+ Gesture: { Pan: () => chain },
+ GestureDetector: ({ children }: { children?: ReactNode }) => children,
+ GestureHandlerRootView: ({ children }: { children?: ReactNode }) => children,
+ };
+ });
+
vi.mock('@/session/HomeModeSwitch', () => ({ HomeModeSwitch: () => null }));
- describe('home navigation drawer', () => {
+ vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));
++vi.mock('expo-router', () => ({ useRouter: () => ({ replace: vi.fn() }) }));
+ vi.mock('@/utils/useGuardedPush', () => ({ useGuardedPush: () => vi.fn() }));
+ vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: String }));
+ vi.mock('@/session/AccountSwitcherSheet', () => ({ AccountSwitcherSheet: () => null }));
+ vi.mock('@/session/remoteSessionStore', () => ({
+ remoteSessionStore: { subscribe: () => () => {}, getSessions: () => [], isSessionRunning: () => false },
+ }));
+ vi.mock('@/session/useTeammateNavigation', () => ({ useTeammateNavigation: () => ({ chooseMode: vi.fn() }) }));
+
+ const drawerProps = (over: Partial<Parameters<typeof HomeChromeDrawer>[0]> = {}) => ({
+ onClose: vi.fn(),
+ onClosed: vi.fn(),
+ onOpenSearch: vi.fn(),
+ onOpenAccounts: vi.fn(),
+ onOpenDevices: vi.fn(),
+ onOpenSettings: vi.fn(),
+ onLogout: vi.fn(),
+ open: true,
+ user: null,
+ ...over,
+ });
+
+ const finishTiming = async () => {
+ const pending = h.timing.splice(0);
+ await act(async () => pending.forEach((done) => done(true)));
+ };
+
+ describe('Android home drawer window and close lifecycle', () => {
let root: Root;
let container: HTMLDivElement;
- const props = {
- open: true, onClose: vi.fn(), onClosed: vi.fn(), onOpenSearch: vi.fn(),
- onOpenAccounts: vi.fn(), onOpenDevices: vi.fn(), onOpenSettings: vi.fn(), onLogout: vi.fn(),
- user: { name: 'Kiro', email: '[email protected]', membershipKind: 'org' as const,
- orgName: 'Example Company', orgLogoUrl: 'https://example.com/org.png', avatar: 'https://example.com/person.png' },
- };
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ h.modal = null;
+ h.timing.splice(0);
+ h.reduceMotion = false;
+ h.platform.OS = 'android';
vi.clearAllMocks();
- driver.reduceMotion = false; driver.layout = undefined;
- driver.values = []; driver.animations = []; driver.gestures = {};
- container = document.createElement('div'); document.body.appendChild(container);
+ container = document.createElement('div');
+ document.body.appendChild(container);
root = createRoot(container);
});
- afterEach(async () => { await act(async () => root.unmount()); container.remove(); });
- const layout = async () => { await act(async () => driver.layout?.()); };
- const gesture = (name: string, translationX = 0, velocityX = 0, success = true) =>
- driver.gestures[name]({ translationX, velocityX }, success);
+ afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ });
- it('keeps the user first with a default letter avatar and only a small organization image', async () => {
- await act(async () => root.render(<HomeChromeDrawer {...props} />));
- const account = container.querySelector('[data-testid="home.chromeDrawer.account"]')!;
- expect(account.textContent).toBe('[email protected] Company');
- expect([...account.querySelectorAll('img')].map(image => image.src)).toEqual([props.user.orgLogoUrl]);
- await act(async () => root.render(<HomeChromeDrawer {...props} user={{ ...props.user, membershipKind: 'personal' }} />));
- expect(account.textContent).not.toContain('Example Company');
- expect(account.querySelector('img')).toBeNull();
+ it('mounts the drawer in its own transparent window instead of an in-route overlay', async () => {
+ await act(async () => root.render(<HomeChromeDrawer {...drawerProps()} />));
+ // Android 走独立 Dialog 窗口:整窗透明、状态栏/导航栏可穿透,抽屉自己播动画。
+ expect(h.modal).toMatchObject({
+ animationType: 'none',
+ navigationBarTranslucent: true,
+ statusBarTranslucent: true,
+ transparent: true,
+ visible: true,
+ });
+ expect(typeof h.modal!.onRequestClose).toBe('function');
+ expect(container.querySelector('[data-testid="rn.modal"]')).not.toBeNull();
+ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).not.toBeNull();
});
- it('waits for native layout before entrance and ignores stale close completion after reopening', async () => {
- await act(async () => root.render(<HomeChromeDrawer {...props} />));
- expect(driver.animations).toHaveLength(0);
- expect(driver.values[0].value).toBe(0);
- await layout();
- expect(driver.animations.at(-1)?.to).toBe(1);
- await act(async () => root.render(<HomeChromeDrawer {...props} open={false} />));
- const closing = driver.animations.at(-1)!;
- expect(closing.to).toBe(0);
- expect(props.onClosed).not.toHaveBeenCalled();
- await act(async () => root.render(<HomeChromeDrawer {...props} />));
- await act(async () => closing.complete?.(true));
+ it('keeps iOS on the FullWindowOverlay window with no Modal', async () => {
+ h.platform.OS = 'ios';
+ await act(async () => root.render(<HomeChromeDrawer {...drawerProps()} />));
+ expect(h.modal).toBeNull();
+ expect(container.querySelector('[data-testid="rn.fullWindowOverlay"]')).not.toBeNull();
expect(container.querySelector('[data-testid="home.chromeDrawer"]')).not.toBeNull();
- expect(props.onClosed).not.toHaveBeenCalled();
- await act(async () => root.render(<HomeChromeDrawer {...props} open={false} />));
- await act(async () => driver.animations.at(-1)?.complete?.(true));
- expect(container.querySelector('[data-testid="home.chromeDrawer"]')).toBeNull();
- expect(props.onClosed).toHaveBeenCalledOnce();
});
- it('tracks interrupted entrance from its current position and recovers cancelled drags', async () => {
+ it('turns Android back into close while open, but forwards it to the app during the exit animation', async () => {
+ const props = drawerProps();
await act(async () => root.render(<HomeChromeDrawer {...props} />));
- await layout();
- driver.values[0].value = 0.75;
- gesture('onStart'); gesture('onUpdate', -32);
- expect(driver.values[0].value).toBeCloseTo(0.65);
- gesture('onFinalize', 0, 0, false);
- expect(driver.values[0].value).toBe(1);
- const count = driver.animations.length;
- gesture('onFinalize', 0, 0, false);
- expect(driver.animations).toHaveLength(count);
- gesture('onStart'); gesture('onUpdate', -160); gesture('onEnd', -160);
+ await act(async () => h.modal!.onRequestClose());
+ expect(props.onClose).toHaveBeenCalledOnce();
+ expect(h.emit).not.toHaveBeenCalled();
+ // 关闭后退场动画期间:back 属于底层页面,不得再调 onClose(会清掉调用方
+ // 记下的待执行动作),而是把事件补发回 app 的返回键链。
+ await act(async () => root.render(<HomeChromeDrawer {...props} open={false} />));
+ await act(async () => h.modal!.onRequestClose());
expect(props.onClose).toHaveBeenCalledOnce();
+ expect(h.emit).toHaveBeenCalledExactlyOnceWith('hardwareBackPress');
+ expect(props.onClosed).not.toHaveBeenCalled();
});
- it.each([true, null])('does not animate opening, snap-back or closing when reduce motion is %s', async reduceMotion => {
- driver.reduceMotion = reduceMotion;
+ it('keeps the drawer mounted until the exit animation ends, then reports onClosed after unmount', async () => {
+ const props = drawerProps();
await act(async () => root.render(<HomeChromeDrawer {...props} />));
- await layout();
- gesture('onStart'); gesture('onUpdate', -16); gesture('onEnd', -16);
- expect(driver.values[0].value).toBe(1);
await act(async () => root.render(<HomeChromeDrawer {...props} open={false} />));
- expect(driver.animations).toHaveLength(0);
+ // 退场中:窗口还在播离场动画,不能提前卸载,也不提前回调 onClosed。
+ expect(h.modal).not.toBeNull();
+ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).not.toBeNull();
+ expect(props.onClosed).not.toHaveBeenCalled();
+ await finishTiming();
+ expect(container.querySelector('[data-testid="rn.modal"]')).toBeNull();
+ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).toBeNull();
+ // onClosed 只在窗口真正卸载后触发一次:调用方的延后动作以此为信号执行。
expect(props.onClosed).toHaveBeenCalledOnce();
+ });
+
+ it('opens search through the deferred action and survives a back press during the exit animation', async () => {
+ const onSearch = vi.fn();
+ const onClose = vi.fn();
+ const host = (open: boolean) => (
+ <CompanionNavigationDrawer open={open} onClose={onClose} onSearch={onSearch} />
+ );
+ await act(async () => root.render(host(true)));
+ await act(async () => {
+ (container.querySelector('[data-testid="home.chromeDrawer.search"]') as HTMLElement).click();
+ });
+ // 动作延后到抽屉完全关闭后执行,关闭请求先回到调用方。
+ expect(onSearch).not.toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalledOnce();
+ await act(async () => root.render(host(false)));
+ // 退场期间的返回键不得清掉待执行动作。
+ await act(async () => h.modal!.onRequestClose());
+ expect(h.emit).toHaveBeenCalledExactlyOnceWith('hardwareBackPress');
+ expect(onSearch).not.toHaveBeenCalled();
+ await finishTiming();
+ expect(onSearch).toHaveBeenCalledOnce();
expect(container.querySelector('[data-testid="home.chromeDrawer"]')).toBeNull();
});
});
diff --cc apps/mobile/src/__tests__/homeChromeDrawerAccount.test.tsx
index 0000000000,0000000000..6ec9922deb
new file mode 100644
--- /dev/null
+++ b/apps/mobile/src/__tests__/homeChromeDrawerAccount.test.tsx
@@@ -1,0 -1,0 +1,159 @@@
++// @vitest-environment jsdom
++import { act, type ReactNode } from 'react';
++import { createRoot, type Root } from 'react-dom/client';
++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
++import { HomeChromeDrawer } from '@/session/HomeChromeDrawer';
++
++type GestureEvent = { translationX: number; velocityX: number };
++const driver = vi.hoisted(() => ({
++ reduceMotion: false as boolean | null,
++ layout: undefined as (() => void) | undefined,
++ gestures: {} as Record<string, (event: GestureEvent, success: boolean) => void>,
++ values: [] as Array<{ value: number | boolean }>,
++ animations: [] as Array<{ to: number; complete?: (finished: boolean) => void }>,
++}));
++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
++vi.mock('react-native', async () => {
++ const { createElement } = await import('react');
++ const View = ({ children, testID, onLayout, onPress }: {
++ children?: ReactNode; testID?: string; onLayout?: () => void; onPress?: () => void;
++ }) => {
++ if (testID === 'home.chromeMenu.panel') driver.layout = onLayout;
++ return createElement('div', { 'data-testid': testID, onClick: onPress }, children);
++ };
++ return {
++ View, Pressable: View,
++ Image: ({ source }: { source: { uri: string } }) => createElement('img', { src: source.uri }),
++ AccessibilityInfo: { setAccessibilityFocus: vi.fn() },
++ BackHandler: { addEventListener: () => ({ remove() {} }) },
++ findNodeHandle: () => null,
++ Platform: { OS: 'ios' },
++ StyleSheet: { create: (value: unknown) => value, absoluteFill: {}, hairlineWidth: 1 },
++ useWindowDimensions: () => ({ width: 390, height: 844 }),
++ };
++});
++vi.mock('react-native-reanimated', async () => {
++ const { useRef } = await import('react');
++ const { View } = await import('react-native');
++ return {
++ default: { View },
++ useSharedValue: (value: number | boolean) => {
++ const ref = useRef<{ value: number | boolean } | null>(null);
++ if (!ref.current) { ref.current = { value }; driver.values.push(ref.current); }
++ return ref.current;
++ },
++ useAnimatedStyle: () => ({}),
++ Easing: { bezier: () => undefined },
++ cancelAnimation: vi.fn(),
++ runOnJS: (fn: unknown) => fn,
++ runOnUI: (fn: unknown) => fn,
++ withTiming: (to: number, _config: unknown, complete?: (finished: boolean) => void) => {
++ driver.animations.push({ to, complete });
++ return to;
++ },
++ };
++});
++vi.mock('@/platform/gestureHandler', async () => {
++ const { View } = await import('react-native');
++ return {
++ GestureHandlerRootView: View,
++ GestureDetector: ({ children }: { children: ReactNode }) => children,
++ Gesture: { Pan: () => {
++ const chain: Record<string, (...args: any[]) => unknown> = {};
++ for (const name of ['enabled', 'activeOffsetX', 'failOffsetX', 'failOffsetY']) chain[name] = () => chain;
++ for (const name of ['onStart', 'onUpdate', 'onEnd', 'onFinalize']) {
++ chain[name] = callback => { driver.gestures[name] = callback; return chain; };
++ }
++ return chain;
++ } },
++ };
++});
++vi.mock('react-native-screens', () => ({ FullWindowOverlay: ({ children }: { children: ReactNode }) => children }));
++vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ left: 0, top: 0, bottom: 0 }) }));
++vi.mock('lucide-react-native', () => Object.fromEntries(
++ ['Building2', 'LogOut', 'Monitor', 'Search', 'Settings', 'UsersRound'].map(name => [name, () => null]),
++));
++vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).View }));
++vi.mock('@/theme', () => ({ useThemedStyles: () => ({}), useTheme: () => ({ colors: {} }) }));
++vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => driver.reduceMotion }));
++vi.mock('@/session/HomeModeSwitch', () => ({ HomeModeSwitch: () => null }));
++
++describe('home navigation drawer', () => {
++ let root: Root;
++ let container: HTMLDivElement;
++ const props = {
++ open: true, onClose: vi.fn(), onClosed: vi.fn(), onOpenSearch: vi.fn(),
++ onOpenAccounts: vi.fn(), onOpenDevices: vi.fn(), onOpenSettings: vi.fn(), onLogout: vi.fn(),
++ user: { name: 'Kiro', email: '[email protected]', membershipKind: 'org' as const,
++ orgName: 'Example Company', orgLogoUrl: 'https://example.com/org.png', avatar: 'https://example.com/person.png' },
++ };
++ beforeEach(() => {
++ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
++ vi.clearAllMocks();
++ driver.reduceMotion = false; driver.layout = undefined;
++ driver.values = []; driver.animations = []; driver.gestures = {};
++ container = document.createElement('div'); document.body.appendChild(container);
++ root = createRoot(container);
++ });
++ afterEach(async () => { await act(async () => root.unmount()); container.remove(); });
++ const layout = async () => { await act(async () => driver.layout?.()); };
++ const gesture = (name: string, translationX = 0, velocityX = 0, success = true) =>
++ driver.gestures[name]({ translationX, velocityX }, success);
++
++ it('keeps the user first with a default letter avatar and only a small organization image', async () => {
++ await act(async () => root.render(<HomeChromeDrawer {...props} />));
++ const account = container.querySelector('[data-testid="home.chromeDrawer.account"]')!;
++ expect(account.textContent).toBe('[email protected] Company');
++ expect([...account.querySelectorAll('img')].map(image => image.src)).toEqual([props.user.orgLogoUrl]);
++ await act(async () => root.render(<HomeChromeDrawer {...props} user={{ ...props.user, membershipKind: 'personal' }} />));
++ expect(account.textContent).not.toContain('Example Company');
++ expect(account.querySelector('img')).toBeNull();
++ });
++
++ it('waits for native layout before entrance and ignores stale close completion after reopening', async () => {
++ await act(async () => root.render(<HomeChromeDrawer {...props} />));
++ expect(driver.animations).toHaveLength(0);
++ expect(driver.values[0].value).toBe(0);
++ await layout();
++ expect(driver.animations.at(-1)?.to).toBe(1);
++ await act(async () => root.render(<HomeChromeDrawer {...props} open={false} />));
++ const closing = driver.animations.at(-1)!;
++ expect(closing.to).toBe(0);
++ expect(props.onClosed).not.toHaveBeenCalled();
++ await act(async () => root.render(<HomeChromeDrawer {...props} />));
++ await act(async () => closing.complete?.(true));
++ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).not.toBeNull();
++ expect(props.onClosed).not.toHaveBeenCalled();
++ await act(async () => root.render(<HomeChromeDrawer {...props} open={false} />));
++ await act(async () => driver.animations.at(-1)?.complete?.(true));
++ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).toBeNull();
++ expect(props.onClosed).toHaveBeenCalledOnce();
++ });
++
++ it('tracks interrupted entrance from its current position and recovers cancelled drags', async () => {
++ await act(async () => root.render(<HomeChromeDrawer {...props} />));
++ await layout();
++ driver.values[0].value = 0.75;
++ gesture('onStart'); gesture('onUpdate', -32);
++ expect(driver.values[0].value).toBeCloseTo(0.65);
++ gesture('onFinalize', 0, 0, false);
++ expect(driver.values[0].value).toBe(1);
++ const count = driver.animations.length;
++ gesture('onFinalize', 0, 0, false);
++ expect(driver.animations).toHaveLength(count);
++ gesture('onStart'); gesture('onUpdate', -160); gesture('onEnd', -160);
++ expect(props.onClose).toHaveBeenCalledOnce();
++ });
++
++ it.each([true, null])('does not animate opening, snap-back or closing when reduce motion is %s', async reduceMotion => {
++ driver.reduceMotion = reduceMotion;
++ await act(async () => root.render(<HomeChromeDrawer {...props} />));
++ await layout();
++ gesture('onStart'); gesture('onUpdate', -16); gesture('onEnd', -16);
++ expect(driver.values[0].value).toBe(1);
++ await act(async () => root.render(<HomeChromeDrawer {...props} open={false} />));
++ expect(driver.animations).toHaveLength(0);
++ expect(props.onClosed).toHaveBeenCalledOnce();
++ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).toBeNull();
++ });
++});
diff --cc apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx
index 23b9698eae,99298af40f..8c8bc610f4
--- a/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx
+++ b/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx
@@@ -33,6 -40,12 +40,12 @@@ vi.mock('lucide-react-native', () => (
vi.mock('react-native-svg', () => ({ default: () => null, Circle: () => null }));
vi.mock('react-native-uitextview', () => ({ UITextView: () => null }));
vi.mock('expo-image', () => ({ Image: () => null }));
-vi.mock('expo-router', () => ({ useRouter: () => ({ push: vi.fn() }), useFocusEffect: vi.fn() }));
++vi.mock('expo-router', () => ({ useRouter: () => ({ push: vi.fn() }), useFocusEffect: vi.fn(), useNavigation: () => ({ isFocused: () => true, addListener: () => () => {} }) }));
+ vi.mock('@/device-link/DeviceLinkContext', () => ({
+ useDeviceLink: () => ({ status: 'offline', connectionEpoch: 0, getPresenceAvailability: () => false,
+ invoke: vi.fn(), openLink: vi.fn() }),
+ subscribeRemoteBotChanges: () => () => {},
+ }));
vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }) }));
vi.mock('@/theme', async () => {
const tokens = await import('@/theme/tokens');
diff --cc apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index 8cf9de7696,8c23e75980..a80ec7bae2
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@@ -177,11 -178,10 +178,11 @@@ describe('mobile session composer deskt
expect(composerInputSource).toContain('trailing={composerCardActive ? null : controls.trailing}');
expect(trailingActionsSource).toContain('<PaperPlaneIcon');
expect(trailingActionsSource).toContain('color={composerSendDisabled ? colors.textSecondary : colors.ctaText}');
- expect(source).toContain('const composerCardActive = (canUseComposer && composerFocused)');
+ // 收起胶囊点开到真正聚焦之间的过渡期(composerPillOpen.opening)同样算激活态,仍受 canUseComposer 门控。
+ expect(source).toContain('const composerCardActive = (canUseComposer && (composerFocused || composerPillOpen.opening))');
expect(source).toContain('|| permissionSheetOpen');
// 2026-07-29 用户裁决:权限入口是 composer 左侧图标钮 + 独立浮窗
- // (MobilePermissionPickerList 由本 screen 直挂 SheetSurface);
+ // (两端都经 NativePermissionSheet:点选先关浮窗,关闭完成后再生效);
// 浮窗打开时仍属于 composer 激活态,不能因输入框失焦把底排收起。
// 2026-08:模型药丸改到左侧组(权限/计划右侧),避免发送/停止出现时横向跳动。
// ModelPickerSheet 的 header 权限入口隐藏(hidePermissionTrigger),不再双入口。
diff --cc apps/mobile/src/components/MobilePrimitives.tsx
index d5b5c1b51f,e5a6d91058..1aa328d31d
--- a/apps/mobile/src/components/MobilePrimitives.tsx
+++ b/apps/mobile/src/components/MobilePrimitives.tsx
@@@ -640,7 -618,6 +643,7 @@@ export function MainWindowActionButton(
selected: action.active || undefined,
}}
disabled={disabled}
- hitSlop={compact ? touchTargetSlop(ACTION_BUTTON_COMPACT_HEIGHT) : undefined}
++ hitSlop={hitSlop ?? (compact ? touchTargetSlop(ACTION_BUTTON_COMPACT_HEIGHT) : undefined)}
onPress={disabled ? undefined : action.onPress}
style={({ pressed }) => [
styles.mainActionButton,
diff --cc apps/mobile/src/device-link/DeviceManagementList.tsx
index 135a195c5e,802425f7fa..11ec6747b0
--- a/apps/mobile/src/device-link/DeviceManagementList.tsx
+++ b/apps/mobile/src/device-link/DeviceManagementList.tsx
@@@ -1,9 -1,8 +1,9 @@@
-import { useRef } from 'react';
-import { Pressable, ScrollView, StyleSheet, View } from 'react-native';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { Pressable, RefreshControl, ScrollView, StyleSheet, View } from 'react-native';
import { useTranslation } from 'react-i18next';
- import { Monitor } from 'lucide-react-native';
+ import { Monitor, Pencil, Trash2 } from 'lucide-react-native';
import { Text } from '@/components/AppText';
+import { StatusDot } from '@/components/MobilePrimitives';
import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
import {
ClassicSwipeable,
@@@ -106,24 -44,36 +106,36 @@@ function DeviceRow(
}) {
const ref = useRef<ClassicSwipeableMethods | null>(null);
const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
const { t } = useTranslation();
- const action = (remove: boolean) => (
- <Pressable
- accessibilityRole="button"
- disabled={busy}
- onPress={() => {
- ref.current?.close();
- (remove ? onDelete : onRename)(row.device);
- }}
- style={({ pressed }) => [styles.action, pressed && mobileInteractionStyles.pressed]}
- testID={`deviceManagement.${remove ? 'delete' : 'rename'}.${row.device.deviceId}`}
- >
- <Text style={[styles.actionLabel, remove && styles.actionLabelDestructive]}>
- {t(remove ? 'devices.common.delete' : 'devices.list.menu.renameDevice')}
- </Text>
- </Pressable>
- );
+ // 与 iOS 滑动操作一致:只放图标(重命名=铅笔、删除=红色垃圾桶),文字留给读屏。
+ const action = (remove: boolean) => {
+ const Icon = remove ? Trash2 : Pencil;
+ return (
+ <Pressable
+ accessibilityLabel={t(remove ? 'devices.common.delete' : 'devices.list.menu.renameDevice')}
+ accessibilityRole="button"
+ accessibilityState={{ disabled: busy }}
+ disabled={busy}
+ onPress={() => {
+ ref.current?.close();
+ (remove ? onDelete : onRename)(row.device);
+ }}
+ style={({ pressed }) => [
+ styles.action,
- { backgroundColor: colors.surfaceElevated },
- pressed && styles.pressed,
- busy && styles.disabled,
++ pressed && mobileInteractionStyles.pressed,
++ busy && styles.actionDisabled,
+ ]}
+ testID={`deviceManagement.${remove ? 'delete' : 'rename'}.${row.device.deviceId}`}
+ >
+ <Icon
+ color={remove ? colors.destructive : colors.textPrimary}
+ size={iconSize.xl}
+ strokeWidth={iconStroke.regular}
+ />
+ </Pressable>
+ );
+ };
return (
<ClassicSwipeable
ref={ref}
@@@ -159,32 -131,32 +171,31 @@@
</ClassicSwipeable>
);
}
-/** 与 iOS 一致:在线只写「在线」,离线写「状态 · 详情」。 */
-function deviceManagementStatusLine(
- row: Pick<DeviceManagementListProps['rows'][number], 'device' | 'statusLabel' | 'statusDetail'>,
-): string {
- return row.device.online ? row.statusLabel : `${row.statusLabel} · ${row.statusDetail}`;
-}
-const styles = StyleSheet.create({
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ scroll: { flex: 1 },
+ content: { gap: spacing.xl, paddingBottom: spacing.xxl, paddingHorizontal: spacing.lg, paddingTop: spacing.lg },
row: {
- flexDirection: 'row',
alignItems: 'center',
- minHeight: 60,
- padding: spacing.lg,
+ backgroundColor: colors.surfaceElevated,
+ flexDirection: 'row',
gap: spacing.md,
- borderBottomWidth: StyleSheet.hairlineWidth,
+ minHeight: 60,
+ paddingHorizontal: spacing.lg,
+ paddingVertical: spacing.md,
},
- labels: { flex: 1, gap: spacing.xs },
- status: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
- statusDot: { width: 6, height: 6, borderRadius: radius.pill, flexShrink: 0 },
+ labels: { flex: 1, gap: spacing.xs, minWidth: 0 },
+ name: { color: colors.textPrimary, fontSize: typeScale.body, fontWeight: fontWeight.medium, lineHeight: lineHeight.body },
+ status: { alignItems: 'center', flexDirection: 'row', gap: spacing.sm },
+ statusText: { color: colors.textTertiary, flexShrink: 1, fontSize: typeScale.caption, fontWeight: fontWeight.regular, lineHeight: lineHeight.caption },
+ toggleLabel: { color: colors.textPrimary, fontSize: typeScale.body, fontWeight: fontWeight.medium, lineHeight: lineHeight.body },
action: {
- minWidth: 72,
- minHeight: 44,
alignItems: 'center',
+ backgroundColor: colors.surfaceChip,
justifyContent: 'center',
+ minHeight: 44,
- minWidth: 88,
++ minWidth: 72,
padding: spacing.lg,
},
- actionLabel: { color: colors.textPrimary, fontSize: typeScale.body, fontWeight: fontWeight.medium, lineHeight: lineHeight.body },
- actionLabelDestructive: { color: colors.destructive },
- pressed: mobileInteractionStyles.pressed,
- disabled: { opacity: 0.45 },
++ actionDisabled: { opacity: 0.45 },
});
diff --cc apps/mobile/src/i18n/locales/en/composer.json
index ae52fe8ced,6be9009605..bb225fecad
--- a/apps/mobile/src/i18n/locales/en/composer.json
+++ b/apps/mobile/src/i18n/locales/en/composer.json
@@@ -17,8 -17,9 +17,9 @@@
"uploadFailed": "{{name}} · Upload failed",
"collapsedBadge": "{{count}} attachments, tap to expand",
"imageNotAnnotatable": "This image can't be annotated or forwarded.",
- "downloadOriginalFailed": "Could not download the original image (HTTP {{status}}).",
+ "downloadOriginalFailed": "Couldn't download the original image. Try again later (HTTP {{status}}).",
"annotationSaveFailed": "Could not save annotation",
+ "replacementPending": "Your last change to this image hasn't finished uploading. Wait for it to finish, or retry or remove it above the input, then edit again.",
"tryAgain": "Try again.",
"sendToChat": "Send to Chat",
"save": "Save",
diff --cc apps/mobile/src/i18n/locales/en/devices.json
index 6037612cf7,c0913d12bf..2d0951ec4c
--- a/apps/mobile/src/i18n/locales/en/devices.json
+++ b/apps/mobile/src/i18n/locales/en/devices.json
@@@ -532,287 -527,9 +530,10 @@@
},
"viewAllRuns": "View all {{count}} runs"
},
- "automations": {
- "heading": {
- "delete": "Delete Automation",
- "pause": "Pause Automation",
- "deleteRun": "Delete Run"
- },
- "runNow": "Run now",
- "error": {
- "projectMissingConfig": "This project automation is missing its project settings. Delete it on your computer.",
- "deletePartial": "Automation deleted, but {{count}} generated sessions couldn't be updated. Check them on the desktop."
- },
- "subtitle": "{{active}} running · {{total}} tasks",
- "metric": {
- "running": "Running",
- "unreadResults": "Unread Results",
- "executing": "In Progress"
- },
- "summary": {
- "paused": "{{count}} tasks paused. Select a task to run, pause, edit, or open its latest session.",
- "default": "Select a task to run, pause, edit, or open its latest session."
- },
- "empty": {
- "copy": "Create your first automation right from your phone, or create one on the desktop and sync it here.",
- "title": "No automations on this device"
- },
- "createAutomation": "New Automation",
- "recentRuns": "Recent Runs",
- "runs": {
- "emptyCopy": "After you tap {{runNow}}, new runs show up here.",
- "emptyTitle": "No runs yet"
- },
- "form": {
- "title": {
- "create": "New Automation",
- "edit": "Edit Automation"
- },
- "sessionMode": {
- "bound": "Once bound to an existing session, the directory, worktree, Agent, and Fast mode follow that session.",
- "persistent": "The first trigger creates a persistent session; later triggers continue in the same one.",
- "fresh": "Each trigger creates a new session."
- },
- "field": {
- "name": "Name",
- "prompt": "Prompt",
- "trigger": "Trigger",
- "runSession": "Run Session",
- "boundSession": "Bound Session",
- "intervalMinutes": "Interval (minutes)",
- "workspace": "Workspace",
- "projectDir": "Project Directory",
- "model": "Model",
- "effort": "Reasoning Effort",
- "timezone": "Time Zone"
- },
- "namePlaceholder": "e.g. Daily project check",
- "scriptHint": "This is a script-only task; its script config can only be edited on the desktop. Here you can change the name, trigger, notifications, and other fields.",
- "promptPlaceholder": "Describe clearly what {{appName}} should do on each run",
- "trigger": {
- "recurring": "Recurring",
- "manual": "Manual"
- },
- "session": {
- "fresh": "New Session",
- "persistent": "Persistent",
- "bound": "Bound"
- },
- "boundSessionA11y": "Bind session {{name}}",
- "intervalPlaceholder": "Leave empty to use cron",
- "intervalHint": "For minute intervals, use 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, or 30 minutes. For whole-hour intervals, enter a multiple of 60 from 60 to 1380 minutes (1–23 hours).",
- "intervalPreservedHint": "This task's exact interval is {{duration}} and will be preserved until you edit or clear it.",
- "workspace": {
- "project": "Project",
- "dialogue": "Chat"
- },
- "useWorktree": "Use worktree",
- "modelPlaceholderBound": "Follow session",
- "modelPlaceholderPiDefault": "Leave blank for default model",
- "boundSessionIdPlaceholder": "Session ID",
- "effortDefault": "Default",
- "fastMode": "Fast Mode",
- "notifyDesktop": "Desktop Notifications",
- "notifyFeishu": "Feishu Notifications",
- "savingA11y": "Saving automation",
- "saveA11y": "Save automation",
- "cancelA11y": "Cancel editing automation"
- },
- "delete": {
- "counting": "Counting the sessions this automation generated…",
- "confirmDeleteBoth": "Delete Task and Sessions",
- "confirmArchive": "Delete Task and Archive Sessions",
- "confirmTaskOnly": "Delete Task Only",
- "title": "Delete {{name}}",
- "copy": "Deleting an automation task doesn't interrupt runs already in progress. Generated sessions are handled by the option below, matching the desktop.",
- "optionsA11y": "Choose how to handle generated sessions",
- "keepDesc": "Delete only this automation task; past sessions stay in their original list.",
- "keepLabel": "Keep Generated Sessions",
- "archiveDesc": "After deleting the task, move its generated sessions to the archive, still searchable later.",
- "archiveLabel": "Archive Generated Sessions",
- "deleteDesc": "After deleting the task, also mark its generated sessions as deleted. This can't be undone from your phone.",
- "deleteLabel": "Delete Generated Sessions",
- "cancelA11y": "Cancel deleting automation",
- "confirmA11y": "Confirm deleting automation"
- },
- "pause": {
- "title": "Pause {{name}}",
- "detailFallback": "Pausing stops this automation from triggering.",
- "previewFallback": "No runs in progress",
- "confirmA11y": "Confirm pausing automation",
- "confirm": "Confirm Pause",
- "cancelA11y": "Cancel pausing automation"
- },
- "runDelete": {
- "title": "Delete this run record",
- "copy": "This deletes only this automation run record. It won't delete the sessions it opened, and it won't affect future automatic triggers.",
- "confirmA11y": "Confirm deleting run record",
- "confirm": "Delete Record",
- "cancelA11y": "Cancel deleting run record"
- },
- "template": {
- "label": "Template",
- "loadingA11y": "Loading templates",
- "refreshA11y": "Refresh automation templates",
- "loading": "Loading",
- "refresh": "Refresh",
- "cardA11y": "Automation template {{name}}",
- "manualConfig": "Manual config",
- "builtin": {
- "nightly-test-heal": {
- "name": "Nightly test self-healing",
- "description": "Run tests every night and attempt minimal fixes for failures in an isolated worktree",
- "prompt": "Run the project's test suite. If there are failures, attempt a minimal fix in an isolated worktree.\nConstraints:\n- Determine the standard test command from the repo docs or package scripts before running the full suite\n- Only fix issues backed by clear failing evidence; prefer the smallest possible change and avoid drive-by refactoring\n- Re-run the affected tests after fixing to confirm they pass, and review the full diff\n- Deliver fixes through the repo's workflow (e.g. create a branch and open a PR); never commit directly to the main branch\n- For failures that cannot be fixed safely, report the cause, suspicious files, and suggested next steps"
- },
- "pr-gatekeeper": {
- "name": "PR gatekeeper",
- "description": "Pre-review new changes on open PRs each weekday and report risks by severity",
- "prompt": "Review the repository's open PRs and pre-screen their new changes.\nConstraints:\n- Go through open PRs with new commits in the past 24 hours (on Monday, look back over the whole weekend), citing PR numbers, file paths, and concrete diffs\n- Focus on correctness, security, data-loss, and compatibility issues, graded by severity\n- Only report issues backed by evidence and describe the failure scenario; do not nitpick on style preferences\n- Unless explicitly authorized, only output review conclusions; do not comment on PRs or change code"
- },
- "domain-radar": {
- "name": "Domain radar",
- "description": "Periodically collect the latest updates in a topic you follow and deliver an opinionated digest",
- "prompt": "Collect the latest developments about \"{{topic}}\" from the past 24 hours (on Monday, look back over the whole weekend) and produce an opinionated digest.\nConstraints:\n- Use web search, cross-check multiple sources before trusting a claim, and cite the source link for every item\n- Prefer substantive developments (releases, research, policy, notable discussions); filter out marketing fluff and reposts\n- For each item, add a one-line judgement on why it matters instead of dumping links\n- When information is scarce or sources are questionable, say so honestly; never fabricate",
- "params": {
- "topic": {
- "label": "Topic to follow",
- "placeholder": "e.g. AI agents, EV market, frontend frameworks"
- }
- }
- },
- "competitor-watch": {
- "name": "Competitor watch",
- "description": "Weekly roundup of competitors' product and market moves, with impact analysis",
- "prompt": "Track the past week's activity of these competitors: {{competitors}}.\nConstraints:\n- Use web search to cover product updates, releases, pricing changes, market moves, and user sentiment, citing sources\n- Distinguish official information from third-party accounts; clearly mark unverified rumors\n- For each significant update, analyze what it means for us and suggest a response\n- If nothing substantive happened, say so honestly instead of padding the report",
- "params": {
- "competitors": {
- "label": "Competitors",
- "placeholder": "e.g. Notion, Linear, Figma"
- }
- }
- },
- "weekly-work-draft": {
- "name": "Weekly report drafter",
- "description": "Compile this week's work from documents in the working directory into a report draft",
- "prompt": "Based on this week's changes to documents, notes, and deliverables in the working directory, compile a weekly report draft.\nConstraints:\n- Only use content with actual modification traces in the working directory as evidence, citing the files\n- Organize as \"Done this week / In progress / Next week / Needs coordination\", concise enough to submit directly\n- Separate substantive progress from routine chores and highlight valuable output\n- Leave placeholders with notes where the material is insufficient so the user can fill them in"
- },
- "knowledge-freshness": {
- "name": "Knowledge base freshness check",
- "description": "Monthly health check of working-directory docs for outdated or conflicting content",
- "prompt": "Health-check the documents in the working directory and find content that needs updating.\nConstraints:\n- Look for outdated information (stale dates, dead links, deprecated processes or tools), contradictions, and duplication\n- Cite the file path and location for every issue and explain the reasoning\n- Categorize as \"update / merge / delete\" suggestions and produce a revision checklist\n- Only output the report; do not modify the documents"
- }
- }
- },
- "scheduleRowA11y": "Automation task {{title}}",
- "detail": {
- "promptScriptFallback": "Script-only task; config can only be edited on the desktop",
- "promptEmpty": "No task prompt saved",
- "deleteA11y": "Delete automation",
- "runNowA11y": "Run automation now",
- "resumeA11y": "Resume automation",
- "pauseA11y": "Pause automation",
- "resume": "Resume",
- "pause": "Pause",
- "editA11y": "Edit automation",
- "edit": "Edit"
- },
- "run": {
- "openSessionA11y": "Open automation session",
- "session": "Session",
- "restartA11y": "Re-run automation",
- "restart": "Re-run",
- "markReadA11y": "Mark run record as read",
- "markRead": "Read",
- "deleteA11y": "Delete run record"
- },
- "presentation": {
- "validation": {
- "templateParameter": "Enter the template parameter: {{label}}",
- "name": "Enter a task name",
- "prompt": "Enter a task prompt",
- "timezone": "Enter a time zone",
- "boundSession": "Choose a task to bind",
- "cron": "Enter a cron expression",
- "workingDir": "Enter a project directory",
- "effort": "Reasoning effort must be one of: {{values}}",
- "intervalPositiveInteger": "The interval in minutes must be a positive integer",
- "preRunHookTimeout": "Check timeout must be a positive whole number of milliseconds",
- "intervalUnsupported": "Minute intervals must divide an hour: use 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, or 30 minutes, or whole-hour intervals from 1–23 hours"
- },
- "schedule": {
- "paused": "Paused",
- "manual": "Manual trigger",
- "once": "One-time task",
- "waitingFirstRun": "Waiting for the first run",
- "every": "Every {{duration}}",
- "recurring": "Recurring task",
- "dialogueWorkspace": "Chat workspace",
- "noDirectory": "No directory set",
- "lastRun": "Last run {{relative}}",
- "imminent": "Running soon",
- "nextRun": "In {{duration}}",
- "status": {
- "active": "Running",
- "paused": "Paused",
- "expired": "Completed"
- },
- "session": {
- "persistent": "Persistent task",
- "bound": "Bound task",
- "fresh": "New task",
- "persistentWithId": "Persistent task {{id}}",
- "persistentDetail": "Reuse the same task after the first trigger",
- "boundWithId": "Bound to {{id}}"
- }
- },
- "run": {
- "session": "Task {{id}}",
- "delete": "Delete",
- "markRead": "Read",
- "canRestart": "Can run again",
- "noSession": "No task created",
- "open": "Open",
- "restart": "Re-run",
- "durationUnknown": "Duration unknown",
- "runningFor": "Running for {{duration}}",
- "duration": "Duration {{duration}}",
- "unknownTime": "Unknown time",
- "status": {
- "running": "Running",
- "success": "Completed",
- "failed": "Failed",
- "aborted": "Aborted",
- "interrupted": "Interrupted",
- "skipped": "Skipped"
- }
- },
- "pause": {
- "title": "Pause {{name}}",
- "detail": "This automation currently has {{count}} runs in progress. Pausing stops future triggers immediately and stops these active runs.",
- "preview": "Runs in progress: {{count}}"
- },
- "delete": {
- "noSessions": "No tasks generated by this automation were found",
- "sessions": "Found {{count}} tasks generated by this automation",
- "withInflight": "{{sessions}}, with {{count}} runs still in progress"
- },
- "duration": {
- "seconds": "{{count}} sec",
- "minutesSeconds": "{{minutes}} min {{seconds}} sec",
- "minutes": "{{count}} min",
- "hours": "{{count}} hr",
- "days": "{{count}} days"
- },
- "relative": {
- "justNow": "just now",
- "minutesAgo": "{{count}} min ago",
- "hoursAgo": "{{count}} hr ago",
- "daysAgo": "{{count}} days ago"
- }
- }
- },
"companions": {
+ "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}}",
"messageSent": "Message sent to background task",
"sentTo": "Sent a message to {{name}}",
"receivedFrom": "Message from {{name}}",
diff --cc apps/mobile/src/i18n/locales/en/sharedTask.json
index a7a7320eb2,9d75023da0..0da29eb32a
--- a/apps/mobile/src/i18n/locales/en/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/en/sharedTask.json
@@@ -42,7 -39,7 +39,7 @@@
"joined": "Joined Shared Task",
"joinedBody": "You can view earlier messages, tool results and attachments, and message the same Agent.",
"enterTask": "Enter Task",
- "inviteBoxTitle": "Send the invitation to people you want to work with",
- "inviteBoxTitle": "Send the invitation link to your teammates",
++ "inviteBoxTitle": "Send the invitation link to people you want to work with",
"roleGuest": "Guest",
"removeShort": "Remove",
"removeNamedTitle": "Remove {{name}}?",
diff --cc apps/mobile/src/i18n/locales/ja/devices.json
index f64b3f02f2,3fcb25b2c3..6ba0ccfb58
--- a/apps/mobile/src/i18n/locales/ja/devices.json
+++ b/apps/mobile/src/i18n/locales/ja/devices.json
@@@ -532,287 -527,9 +530,10 @@@
},
"viewAllRuns": "すべての実行 {{count}} 回を表示"
},
- "automations": {
- "heading": {
- "delete": "自動化を削除",
- "pause": "自動化を一時停止",
- "deleteRun": "実行記録を削除"
- },
- "runNow": "今すぐ実行",
- "error": {
- "projectMissingConfig": "このプロジェクト自動化にはプロジェクト設定がありません。パソコンで削除してください。",
- "deletePartial": "自動化を削除しましたが、{{count}} 件の生成されたセッションの状態を更新できませんでした。デスクトップでこれらのセッションを確認してください。"
- },
- "subtitle": "実行中 {{active}} 件 · タスク {{total}} 件",
- "metric": {
- "running": "実行中",
- "unreadResults": "未読の結果",
- "executing": "処理中"
- },
- "summary": {
- "paused": "{{count}} 件のタスクが一時停止中です。タスクを選ぶと実行・一時停止・編集や最近のセッションを開けます。",
- "default": "タスクを選ぶと実行・一時停止・編集や最近のセッションを開けます。"
- },
- "empty": {
- "copy": "最初の自動化タスクをスマホから直接作成するか、デスクトップで作成してここに同期できます。",
- "title": "このデバイスには自動化がありません"
- },
- "createAutomation": "自動化を新規作成",
- "recentRuns": "最近の実行",
- "runs": {
- "emptyCopy": "「{{runNow}}」をタップすると、新しい実行がここに表示されます。",
- "emptyTitle": "まだ実行記録がありません"
- },
- "form": {
- "title": {
- "create": "自動化を新規作成",
- "edit": "自動化を編集"
- },
- "sessionMode": {
- "bound": "既存のセッションにひも付けると、ディレクトリ、worktree、Agent、Fast モードがそのセッションに従います。",
- "persistent": "最初のトリガーで継続セッションを作成し、以降のトリガーは同じセッションに続けます。",
- "fresh": "トリガーごとに新しいセッションを作成します。"
- },
- "field": {
- "name": "名前",
- "prompt": "プロンプト",
- "trigger": "トリガー方式",
- "runSession": "実行セッション",
- "boundSession": "ひも付けセッション",
- "intervalMinutes": "間隔(分)",
- "workspace": "ワークスペース",
- "projectDir": "プロジェクトディレクトリ",
- "model": "モデル",
- "effort": "推論強度",
- "timezone": "タイムゾーン"
- },
- "namePlaceholder": "例:毎日のプロジェクト点検",
- "scriptHint": "これはスクリプトのみのタスクです。スクリプト設定はデスクトップでのみ編集できます。ここでは名前、トリガー方式、通知などのその他の項目を変更できます。",
- "promptPlaceholder": "毎回の自動実行で {{appName}} に何をさせたいかを明確に書いてください",
- "trigger": {
- "recurring": "定期",
- "manual": "手動"
- },
- "session": {
- "fresh": "新しいセッション",
- "persistent": "継続",
- "bound": "ひも付け"
- },
- "boundSessionA11y": "セッション {{name}} をひも付け",
- "intervalPlaceholder": "空欄の場合は cron を使用",
- "intervalHint": "分間隔は 1、2、3、4、5、6、10、12、15、20、30 分から選択してください。整数時間の間隔は、60~1380 分(1~23 時間)の範囲で 60 の倍数を入力してください。",
- "intervalPreservedHint": "このタスクの正確な間隔は {{duration}} です。編集または消去するまで保持されます。",
- "workspace": {
- "project": "プロジェクト",
- "dialogue": "会話"
- },
- "useWorktree": "worktree を使用",
- "modelPlaceholderBound": "セッションに従う",
- "modelPlaceholderPiDefault": "空欄でデフォルトモデル",
- "boundSessionIdPlaceholder": "セッション ID",
- "effortDefault": "デフォルト",
- "fastMode": "Fast モード",
- "notifyDesktop": "デスクトップ通知",
- "notifyFeishu": "Feishu 通知",
- "savingA11y": "自動化を保存中",
- "saveA11y": "自動化を保存",
- "cancelA11y": "自動化の編集をキャンセル"
- },
- "delete": {
- "counting": "この自動化が生成したセッションを集計中…",
- "confirmDeleteBoth": "タスクとセッションを削除",
- "confirmArchive": "タスクを削除してセッションをアーカイブ",
- "confirmTaskOnly": "タスクのみ削除",
- "title": "{{name}} を削除",
- "copy": "自動化タスクを削除しても、すでに開始された実行は中断されません。生成されたセッションは下のオプションに従って処理され、デスクトップと同じ挙動になります。",
- "optionsA11y": "生成されたセッションの処理方法を選択",
- "keepDesc": "この自動化タスクだけを削除し、過去のセッションは元のリストに残します。",
- "keepLabel": "生成されたセッションを残す",
- "archiveDesc": "タスクを削除した後、生成されたセッションをアーカイブに移動します。後で検索できます。",
- "archiveLabel": "生成されたセッションをアーカイブ",
- "deleteDesc": "タスクを削除した後、生成されたセッションも削除済みとして扱います。この操作はスマホからは元に戻せません。",
- "deleteLabel": "生成されたセッションを削除",
- "cancelA11y": "自動化の削除をキャンセル",
- "confirmA11y": "自動化の削除を確定"
- },
- "pause": {
- "title": "{{name}} を一時停止",
- "detailFallback": "一時停止すると、この自動化のトリガーが止まります。",
- "previewFallback": "実行中の run はありません",
- "confirmA11y": "自動化の一時停止を確定",
- "confirm": "一時停止を確定",
- "cancelA11y": "自動化の一時停止をキャンセル"
- },
- "runDelete": {
- "title": "この実行記録を削除",
- "copy": "この自動化の実行記録のみを削除します。開いたセッションは削除されず、以降の自動トリガーにも影響しません。",
- "confirmA11y": "実行記録の削除を確定",
- "confirm": "記録を削除",
- "cancelA11y": "実行記録の削除をキャンセル"
- },
- "template": {
- "label": "テンプレート",
- "loadingA11y": "テンプレートを読み込み中",
- "refreshA11y": "自動化テンプレートを更新",
- "loading": "読み込み中",
- "refresh": "更新",
- "cardA11y": "自動化テンプレート {{name}}",
- "manualConfig": "手動設定",
- "builtin": {
- "nightly-test-heal": {
- "name": "夜間セルフヒーリングテスト",
- "description": "毎晩テストを実行し、失敗項目を分離ワークツリーで最小修正",
- "prompt": "プロジェクトのテストスイートを実行し、失敗があれば隔離された worktree で最小限の修正を試みてください。\n制約:\n- リポジトリのドキュメントまたは package スクリプトから標準のテストコマンドを特定してから、テストスイート全体を実行する\n- 明確な失敗の証拠がある問題だけを修正し、影響範囲が最小の変更を優先して、ついでのリファクタリングは避ける\n- 修正後は関連テストを再実行して成功を確認し、diff 全体をレビューする\n- リポジトリのワークフローに従って修正を提出する(例:ブランチを作成して PR を開く)。main ブランチを直接変更しない\n- 安全に修正できない失敗については、原因、疑わしいファイル、推奨する調査手順を報告する"
- },
- "pr-gatekeeper": {
- "name": "PR ゲートキーパー",
- "description": "平日にオープン PR の新規変更を事前レビューし、重大度別にリスクを報告",
- "prompt": "リポジトリで現在オープンな PR を確認し、新しい変更を事前レビューしてください。\n制約:\n- 過去 24 時間以内に新しいコミットがあるオープン PR を 1 件ずつ確認する(月曜日は週末全体を対象)。PR 番号、ファイルパス、具体的な diff を引用する\n- 正確性、セキュリティ、データ損失、互換性の問題に重点を置き、深刻度別に分類する\n- 証拠で裏付けられる問題だけを報告し、失敗シナリオを説明する。スタイル上の好みだけで指摘しない\n- ユーザーが明示的に許可しない限り、レビュー結果のみを出力し、PR へのコメントやコード変更は行わない"
- },
- "domain-radar": {
- "name": "分野レーダー",
- "description": "注目分野の最新動向を定期収集し、見解付きサマリーを出力",
- "prompt": "テーマ「{{topic}}」について過去 24 時間の最新動向(月曜日は週末全体)を収集し、見解を含むダイジェストを作成してください。\n制約:\n- Web 検索を使い、複数の情報源で照合してから採用し、各項目に出典リンクを付ける\n- リリース、研究、政策、重要な議論など実質的な進展を優先し、宣伝記事や転載を除外する\n- リンクを並べるだけでなく、各動向に「なぜ注目すべきか」を 1 文で示す\n- 情報が少ない場合や情報源に疑義がある場合は率直に明記し、推測で補わない",
- "params": {
- "topic": {
- "label": "注目テーマ",
- "placeholder": "例:AI エージェント、新エネルギー、フロントエンド"
- }
- }
- },
- "competitor-watch": {
- "name": "競合ウォッチ",
- "description": "競合の製品・市場動向を週次でまとめ、自社への影響を分析",
- "prompt": "次の競合の過去 1 週間の動向を追跡してください:{{competitors}}。\n制約:\n- Web 検索で製品更新、リリース、価格変更、市場動向、ユーザー評価を調べ、出典を示す\n- 公式情報と第三者による情報を区別し、未確認の噂は明示する\n- 重要な動向ごとに、それが自社に何を意味するかを分析し、対応案を示す\n- 実質的な動きがない場合は、水増しせず率直にその旨を伝える",
- "params": {
- "competitors": {
- "label": "競合リスト",
- "placeholder": "例:Notion、Linear、Figma"
- }
- }
- },
- "weekly-work-draft": {
- "name": "週報ドラフトアシスタント",
- "description": "作業ディレクトリのドキュメントから今週の作業を整理し、週報ドラフトを生成",
- "prompt": "作業ディレクトリ内で今週変更されたドキュメント、メモ、成果物を基に、週報の下書きを作成してください。\n制約:\n- 作業ディレクトリ内に実際の変更履歴がある内容だけを根拠とし、対応するファイルを示す\n- 「今週完了 / 進行中 / 来週の予定 / 調整が必要」の構成で、そのまま提出できる簡潔な文章にする\n- 実質的な進捗と定常作業を区別し、価値のある成果を強調する\n- 判断材料が足りない箇所には説明付きのプレースホルダーを残し、ユーザーが追記できるようにする"
- },
- "knowledge-freshness": {
- "name": "ナレッジベース鮮度チェック",
- "description": "毎月ドキュメントを点検し、古い内容や矛盾を洗い出す",
- "prompt": "作業ディレクトリ内のドキュメントを点検し、更新が必要な内容を見つけてください。\n制約:\n- 古い情報(過去の日付、無効なリンク、廃止された手順やツール)、矛盾、重複を確認する\n- 各問題についてファイルパスと具体的な場所を示し、判断理由を説明する\n- 「更新を推奨 / 統合を推奨 / 削除を推奨」に分類し、修正チェックリストを作成する\n- 点検レポートだけを出力し、ドキュメント自体は変更しない"
- }
- }
- },
- "scheduleRowA11y": "自動化タスク {{title}}",
- "detail": {
- "promptScriptFallback": "スクリプトのみのタスク。設定はデスクトップでのみ編集できます",
- "promptEmpty": "タスクのプロンプトが保存されていません",
- "deleteA11y": "自動化を削除",
- "runNowA11y": "自動化を今すぐ実行",
- "resumeA11y": "自動化を再開",
- "pauseA11y": "自動化を一時停止",
- "resume": "再開",
- "pause": "一時停止",
- "editA11y": "自動化を編集",
- "edit": "編集"
- },
- "run": {
- "openSessionA11y": "自動化セッションを開く",
- "session": "セッション",
- "restartA11y": "自動化を再実行",
- "restart": "再実行",
- "markReadA11y": "実行記録を既読にする",
- "markRead": "既読",
- "deleteA11y": "実行記録を削除"
- },
- "presentation": {
- "validation": {
- "templateParameter": "テンプレートパラメーターを入力してください:{{label}}",
- "name": "タスク名を入力してください",
- "prompt": "タスクのプロンプトを入力してください",
- "timezone": "タイムゾーンを入力してください",
- "boundSession": "ひも付けるタスクを選択してください",
- "cron": "cron 式を入力してください",
- "workingDir": "プロジェクトディレクトリを入力してください",
- "effort": "推論強度は次のいずれかを指定してください:{{values}}",
- "intervalPositiveInteger": "間隔(分)は正の整数で入力してください",
- "preRunHookTimeout": "確認のタイムアウトは正の整数のミリ秒で入力してください",
- "intervalUnsupported": "分間隔は 1 時間を割り切れる値(1、2、3、4、5、6、10、12、15、20、30 分)、または 1~23 時間の正時で指定してください"
- },
- "schedule": {
- "paused": "一時停止中",
- "manual": "手動トリガー",
- "once": "単発タスク",
- "waitingFirstRun": "初回実行待ち",
- "every": "{{duration}}ごと",
- "recurring": "定期タスク",
- "dialogueWorkspace": "会話ワークスペース",
- "noDirectory": "ディレクトリ未設定",
- "lastRun": "前回 {{relative}}",
- "imminent": "まもなく実行",
- "nextRun": "{{duration}}後",
- "status": {
- "active": "実行中",
- "paused": "一時停止中",
- "expired": "完了"
- },
- "session": {
- "persistent": "継続タスク",
- "bound": "ひも付けタスク",
- "fresh": "新規タスク",
- "persistentWithId": "継続タスク {{id}}",
- "persistentDetail": "初回トリガー後も同じタスクを再利用します",
- "boundWithId": "{{id}} にひも付け"
- }
- },
- "run": {
- "session": "タスク {{id}}",
- "delete": "削除",
- "markRead": "既読",
- "canRestart": "再実行できます",
- "noSession": "タスク未作成",
- "open": "開く",
- "restart": "再実行",
- "durationUnknown": "所要時間不明",
- "runningFor": "実行時間 {{duration}}",
- "duration": "所要時間 {{duration}}",
- "unknownTime": "時刻不明",
- "status": {
- "running": "実行中",
- "success": "完了",
- "failed": "失敗",
- "aborted": "中止済み",
- "interrupted": "中断",
- "skipped": "スキップ"
- }
- },
- "pause": {
- "title": "{{name}} を一時停止",
- "detail": "この自動化では現在 {{count}} 件の実行が進行中です。一時停止すると今後のトリガーを直ちに止め、進行中の実行も停止します。",
- "preview": "実行中:{{count}} 件"
- },
- "delete": {
- "noSessions": "この自動化が生成したタスクは見つかりませんでした",
- "sessions": "この自動化が生成したタスクが {{count}} 件見つかりました",
- "withInflight": "{{sessions}}。さらに {{count}} 件の実行が進行中です"
- },
- "duration": {
- "seconds": "{{count}} 秒",
- "minutesSeconds": "{{minutes}} 分 {{seconds}} 秒",
- "minutes": "{{count}} 分",
- "hours": "{{count}} 時間",
- "days": "{{count}} 日"
- },
- "relative": {
- "justNow": "たった今",
- "minutesAgo": "{{count}} 分前",
- "hoursAgo": "{{count}} 時間前",
- "daysAgo": "{{count}} 日前"
- }
- }
- },
"companions": {
+ "noCreateHosts": "対応するコンピュータを利用できません。パソコンで Cindy を開き、同じアカウントでログインするとチームメイトを新規作成できます。",
+ "taskAttentionCount": "確認が必要なタスク:{{count}}",
+ "unreadChatCount": "未読のチャット:{{count}}",
"messageSent": "バックグラウンドタスクにメッセージを送信しました",
"sentTo": "{{name}} にメッセージを送信",
"receivedFrom": "{{name}} からのメッセージ",
diff --cc apps/mobile/src/i18n/locales/ja/sharedTask.json
index febf865222,21b3644145..0953a00821
--- a/apps/mobile/src/i18n/locales/ja/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/ja/sharedTask.json
@@@ -42,7 -39,7 +39,7 @@@
"joined": "共有タスクに参加しました",
"joinedBody": "参加前のメッセージ、ツールの結果、添付ファイルを確認し、同じ Agent にメッセージを送信できます。",
"enterTask": "タスクを開く",
- "inviteBoxTitle": "一緒に作業する人に招待を送信",
- "inviteBoxTitle": "招待リンクを仲間に送信",
++ "inviteBoxTitle": "一緒に作業する人に招待リンクを送信",
"roleGuest": "ゲスト",
"removeShort": "削除",
"removeNamedTitle": "{{name}}を削除しますか?",
diff --cc apps/mobile/src/i18n/locales/ko/devices.json
index a630b2a33e,f2609b90a6..be1f60bc9a
--- a/apps/mobile/src/i18n/locales/ko/devices.json
+++ b/apps/mobile/src/i18n/locales/ko/devices.json
@@@ -532,287 -527,9 +530,10 @@@
},
"viewAllRuns": "실행 {{count}}회 모두 보기"
},
- "automations": {
- "heading": {
- "delete": "자동화 삭제",
- "pause": "자동화 일시 중지",
- "deleteRun": "실행 기록 삭제"
- },
- "runNow": "지금 실행",
- "error": {
- "projectMissingConfig": "이 프로젝트 자동화에 프로젝트 설정이 없습니다. 컴퓨터에서 삭제하세요.",
- "deletePartial": "자동화를 삭제했지만 생성된 세션 {{count}}개의 상태를 업데이트하지 못했습니다. 데스크톱에서 이 세션들을 확인하세요."
- },
- "subtitle": "실행 중 {{active}}개 · 작업 {{total}}개",
- "metric": {
- "running": "실행 중",
- "unreadResults": "읽지 않은 결과",
- "executing": "처리 중"
- },
- "summary": {
- "paused": "작업 {{count}}개가 일시 중지되었습니다. 작업을 선택하면 실행·일시 중지·편집하거나 최근 세션을 열 수 있습니다.",
- "default": "작업을 선택하면 실행·일시 중지·편집하거나 최근 세션을 열 수 있습니다."
- },
- "empty": {
- "copy": "휴대폰에서 첫 자동화 작업을 바로 만들거나, 데스크톱에서 만든 후 여기로 동기화할 수 있습니다.",
- "title": "이 기기에는 자동화가 없습니다"
- },
- "createAutomation": "자동화 새로 만들기",
- "recentRuns": "최근 실행",
- "runs": {
- "emptyCopy": "‘{{runNow}}’을 누르면 새 실행이 여기에 표시됩니다.",
- "emptyTitle": "아직 실행 기록이 없습니다"
- },
- "form": {
- "title": {
- "create": "자동화 새로 만들기",
- "edit": "자동화 편집"
- },
- "sessionMode": {
- "bound": "기존 세션에 연결하면 디렉터리, worktree, Agent, Fast 모드가 해당 세션을 따릅니다.",
- "persistent": "첫 트리거에서 지속 세션을 만들고, 이후 트리거는 같은 세션에서 이어집니다.",
- "fresh": "트리거할 때마다 새 세션을 만듭니다."
- },
- "field": {
- "name": "이름",
- "prompt": "프롬프트",
- "trigger": "트리거 방식",
- "runSession": "실행 세션",
- "boundSession": "연결 세션",
- "intervalMinutes": "간격(분)",
- "workspace": "작업 공간",
- "projectDir": "프로젝트 디렉터리",
- "model": "모델",
- "effort": "추론 강도",
- "timezone": "시간대"
- },
- "namePlaceholder": "예: 매일 프로젝트 점검",
- "scriptHint": "이것은 스크립트 전용 작업입니다. 스크립트 설정은 데스크톱에서만 편집할 수 있습니다. 여기서는 이름, 트리거 방식, 알림 등 다른 항목을 변경할 수 있습니다.",
- "promptPlaceholder": "매번 자동 실행할 때 {{appName}}이(가) 무엇을 하기를 원하는지 명확하게 작성하세요",
- "trigger": {
- "recurring": "주기",
- "manual": "수동"
- },
- "session": {
- "fresh": "새 세션",
- "persistent": "지속",
- "bound": "연결"
- },
- "boundSessionA11y": "세션 {{name}} 연결",
- "intervalPlaceholder": "비워 두면 cron 사용",
- "intervalHint": "분 간격은 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30분을 사용하세요. 정수 시간 간격은 60~1380분(1~23시간) 범위에서 60의 배수로 입력하세요.",
- "intervalPreservedHint": "이 작업의 정확한 간격은 {{duration}}이며, 수정하거나 지우기 전까지 유지됩니다.",
- "workspace": {
- "project": "프로젝트",
- "dialogue": "대화"
- },
- "useWorktree": "worktree 사용",
- "modelPlaceholderBound": "세션 따르기",
- "modelPlaceholderPiDefault": "비워두면 기본 모델",
- "boundSessionIdPlaceholder": "세션 ID",
- "effortDefault": "기본값",
- "fastMode": "Fast 모드",
- "notifyDesktop": "데스크톱 알림",
- "notifyFeishu": "Feishu 알림",
- "savingA11y": "자동화 저장 중",
- "saveA11y": "자동화 저장",
- "cancelA11y": "자동화 편집 취소"
- },
- "delete": {
- "counting": "이 자동화가 생성한 세션을 집계하는 중…",
- "confirmDeleteBoth": "작업과 세션 삭제",
- "confirmArchive": "작업 삭제 후 세션 보관",
- "confirmTaskOnly": "작업만 삭제",
- "title": "{{name}} 삭제",
- "copy": "자동화 작업을 삭제해도 이미 시작된 실행은 중단되지 않습니다. 생성된 세션은 아래 옵션에 따라 처리되며 데스크톱과 동일하게 동작합니다.",
- "optionsA11y": "생성된 세션 처리 방식 선택",
- "keepDesc": "이 자동화 작업만 삭제하고, 이전 세션은 원래 목록에 그대로 둡니다.",
- "keepLabel": "생성된 세션 유지",
- "archiveDesc": "작업을 삭제한 후 생성된 세션을 보관함으로 옮깁니다. 이후에도 검색할 수 있습니다.",
- "archiveLabel": "생성된 세션 보관",
- "deleteDesc": "작업을 삭제한 후 생성된 세션도 삭제됨으로 표시합니다. 이 작업은 휴대폰에서 되돌릴 수 없습니다.",
- "deleteLabel": "생성된 세션 삭제",
- "cancelA11y": "자동화 삭제 취소",
- "confirmA11y": "자동화 삭제 확인"
- },
- "pause": {
- "title": "{{name}} 일시 중지",
- "detailFallback": "일시 중지하면 이 자동화의 트리거가 멈춥니다.",
- "previewFallback": "실행 중인 run이 없습니다",
- "confirmA11y": "자동화 일시 중지 확인",
- "confirm": "일시 중지 확인",
- "cancelA11y": "자동화 일시 중지 취소"
- },
- "runDelete": {
- "title": "이 실행 기록 삭제",
- "copy": "이 자동화 실행 기록만 삭제합니다. 열었던 세션은 삭제되지 않으며 이후 자동 트리거에도 영향을 주지 않습니다.",
- "confirmA11y": "실행 기록 삭제 확인",
- "confirm": "기록 삭제",
- "cancelA11y": "실행 기록 삭제 취소"
- },
- "template": {
- "label": "템플릿",
- "loadingA11y": "템플릿 불러오는 중",
- "refreshA11y": "자동화 템플릿 새로 고침",
- "loading": "불러오는 중",
- "refresh": "새로 고침",
- "cardA11y": "자동화 템플릿 {{name}}",
- "manualConfig": "수동 설정",
- "builtin": {
- "nightly-test-heal": {
- "name": "야간 자가 복구 테스트",
- "description": "매일 밤 테스트를 실행하고 실패 항목을 격리 워크트리에서 최소 수정",
- "prompt": "프로젝트의 테스트 스위트를 실행하고, 실패 항목이 있으면 격리된 worktree에서 최소한의 수정을 시도하세요.\n제약 사항:\n- 전체 테스트를 실행하기 전에 저장소 문서나 package 스크립트에서 표준 테스트 명령을 확인합니다\n- 명확한 실패 증거가 있는 문제만 수정하고, 영향 범위가 가장 작은 변경을 우선하며 관련 없는 리팩터링은 피합니다\n- 수정 후 관련 테스트를 다시 실행해 통과 여부를 확인하고 전체 diff를 검토합니다\n- 저장소의 작업 흐름에 따라 수정 사항을 전달합니다(예: 브랜치를 만들고 PR 열기). main 브랜치를 직접 변경하지 않습니다\n- 안전하게 수정할 수 없는 실패 항목은 원인, 의심되는 파일, 권장 조사 단계를 보고합니다"
- },
- "pr-gatekeeper": {
- "name": "PR 게이트키퍼",
- "description": "평일마다 오픈 PR의 새 변경을 사전 리뷰하고 심각도별로 위험 보고",
- "prompt": "저장소에서 현재 열려 있는 PR을 확인하고 새 변경 사항을 사전 검토하세요.\n제약 사항:\n- 지난 24시간 동안 새 커밋이 추가된 열린 PR을 하나씩 확인합니다(월요일에는 주말 전체를 확인). PR 번호, 파일 경로, 구체적인 diff를 인용합니다\n- 정확성, 보안, 데이터 손실, 호환성 문제를 중점적으로 찾고 심각도별로 분류합니다\n- 증거로 뒷받침되는 문제만 보고하고 실패 시나리오를 설명합니다. 스타일 취향만으로 지적하지 않습니다\n- 사용자가 명시적으로 허용하지 않는 한 검토 결과만 출력하고 PR에 댓글을 달거나 코드를 변경하지 않습니다"
- },
- "domain-radar": {
- "name": "관심 분야 레이더",
- "description": "관심 분야의 최신 동향을 정기 수집해 관점 있는 요약 제공",
- "prompt": "주제 \"{{topic}}\"에 관한 지난 24시간의 최신 동향을 수집하고(월요일에는 주말 전체를 확인) 관점이 담긴 요약을 작성하세요.\n제약 사항:\n- Web 검색을 사용하고 여러 출처를 교차 확인한 뒤 정보를 채택하며, 각 항목에 출처 링크를 표시합니다\n- 출시, 연구, 정책, 주요 논의처럼 실질적인 진전을 우선하고 홍보성 글과 중복 게시물은 제외합니다\n- 링크만 나열하지 말고 각 동향이 왜 중요한지 한 문장으로 판단을 덧붙입니다\n- 정보가 부족하거나 출처가 의심스러우면 솔직히 밝히고 지어내지 않습니다",
- "params": {
- "topic": {
- "label": "관심 주제",
- "placeholder": "예: AI 에이전트, 신에너지, 프런트엔드"
- }
- }
- },
- "competitor-watch": {
- "name": "경쟁사 동향 추적",
- "description": "경쟁사의 제품·시장 동향을 매주 정리하고 영향 분석",
- "prompt": "다음 경쟁사의 지난 일주일간 동향을 추적하세요: {{competitors}}.\n제약 사항:\n- Web 검색으로 제품 업데이트, 출시, 가격 변경, 시장 움직임, 사용자 반응을 조사하고 출처를 표시합니다\n- 공식 정보와 제3자 전언을 구분하고 확인되지 않은 소문은 명확히 표시합니다\n- 중요한 동향마다 우리에게 어떤 의미가 있는지 분석하고 대응 방안을 제안합니다\n- 실질적인 동향이 없다면 내용을 부풀리지 말고 솔직히 밝힙니다",
- "params": {
- "competitors": {
- "label": "경쟁사 목록",
- "placeholder": "예: Notion, Linear, Figma"
- }
- }
- },
- "weekly-work-draft": {
- "name": "주간 보고서 초안 도우미",
- "description": "작업 디렉터리의 문서와 산출물로 주간 보고서 초안 생성",
- "prompt": "작업 디렉터리에서 이번 주에 변경된 문서, 메모, 결과물을 바탕으로 주간 보고서 초안을 작성하세요.\n제약 사항:\n- 작업 디렉터리에 실제 변경 흔적이 있는 내용만 근거로 사용하고 해당 파일을 표시합니다\n- \"이번 주 완료 / 진행 중 / 다음 주 계획 / 협의 필요\" 구조로, 바로 제출할 수 있을 만큼 간결하게 작성합니다\n- 실질적인 진전과 반복 업무를 구분하고 가치 있는 결과물을 강조합니다\n- 판단할 자료가 부족한 부분에는 설명과 함께 자리 표시자를 남겨 사용자가 보완할 수 있게 합니다"
- },
- "knowledge-freshness": {
- "name": "지식 베이스 신선도 점검",
- "description": "매월 문서를 점검해 오래된 내용과 모순 찾기",
- "prompt": "작업 디렉터리의 문서를 점검하고 업데이트가 필요한 내용을 찾으세요.\n제약 사항:\n- 오래된 정보(지난 날짜, 끊어진 링크, 폐기된 절차나 도구), 모순, 중복 내용을 확인합니다\n- 각 문제의 파일 경로와 구체적인 위치를 표시하고 판단 근거를 설명합니다\n- \"업데이트 권장 / 병합 권장 / 삭제 권장\"으로 분류하고 수정 체크리스트를 작성합니다\n- 점검 보고서만 출력하고 문서 자체는 수정하지 않습니다"
- }
- }
- },
- "scheduleRowA11y": "자동화 작업 {{title}}",
- "detail": {
- "promptScriptFallback": "스크립트 전용 작업. 설정은 데스크톱에서만 편집할 수 있습니다",
- "promptEmpty": "저장된 작업 프롬프트가 없습니다",
- "deleteA11y": "자동화 삭제",
- "runNowA11y": "자동화 지금 실행",
- "resumeA11y": "자동화 재개",
- "pauseA11y": "자동화 일시 중지",
- "resume": "재개",
- "pause": "일시 중지",
- "editA11y": "자동화 편집",
- "edit": "편집"
- },
- "run": {
- "openSessionA11y": "자동화 세션 열기",
- "session": "세션",
- "restartA11y": "자동화 다시 실행",
- "restart": "다시 실행",
- "markReadA11y": "실행 기록 읽음으로 표시",
- "markRead": "읽음",
- "deleteA11y": "실행 기록 삭제"
- },
- "presentation": {
- "validation": {
- "templateParameter": "템플릿 매개변수를 입력하세요: {{label}}",
- "name": "작업 이름을 입력하세요",
- "prompt": "작업 프롬프트를 입력하세요",
- "timezone": "시간대를 입력하세요",
- "boundSession": "연결할 작업을 선택하세요",
- "cron": "cron 표현식을 입력하세요",
- "workingDir": "프로젝트 디렉터리를 입력하세요",
- "effort": "추론 강도는 다음 중 하나여야 합니다: {{values}}",
- "intervalPositiveInteger": "분 간격은 양의 정수여야 합니다",
- "preRunHookTimeout": "검사 제한 시간은 양의 정수(밀리초)여야 합니다",
- "intervalUnsupported": "분 간격은 1시간을 나눌 수 있는 값(1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30분) 또는 1~23시간의 정시 간격만 지원합니다"
- },
- "schedule": {
- "paused": "일시 중지됨",
- "manual": "수동 트리거",
- "once": "일회성 작업",
- "waitingFirstRun": "첫 실행 대기 중",
- "every": "{{duration}}마다",
- "recurring": "주기 작업",
- "dialogueWorkspace": "대화 작업 공간",
- "noDirectory": "디렉터리 미설정",
- "lastRun": "지난 실행 {{relative}}",
- "imminent": "곧 실행",
- "nextRun": "{{duration}} 후",
- "status": {
- "active": "실행 중",
- "paused": "일시 중지됨",
- "expired": "완료됨"
- },
- "session": {
- "persistent": "지속 작업",
- "bound": "연결된 작업",
- "fresh": "새 작업",
- "persistentWithId": "지속 작업 {{id}}",
- "persistentDetail": "첫 트리거 후 같은 작업을 계속 재사용합니다",
- "boundWithId": "{{id}}에 연결"
- }
- },
- "run": {
- "session": "작업 {{id}}",
- "delete": "삭제",
- "markRead": "읽음",
- "canRestart": "다시 실행 가능",
- "noSession": "생성된 작업 없음",
- "open": "열기",
- "restart": "다시 실행",
- "durationUnknown": "소요 시간 알 수 없음",
- "runningFor": "{{duration}} 동안 실행 중",
- "duration": "소요 시간 {{duration}}",
- "unknownTime": "시간 알 수 없음",
- "status": {
- "running": "실행 중",
- "success": "완료",
- "failed": "실패",
- "aborted": "중단됨",
- "interrupted": "중단됨",
- "skipped": "건너뜀"
- }
- },
- "pause": {
- "title": "{{name}} 일시 중지",
- "detail": "현재 이 자동화에서 {{count}}개의 실행이 진행 중입니다. 일시 중지하면 이후 트리거를 즉시 막고 진행 중인 실행도 중지합니다.",
- "preview": "진행 중인 실행: {{count}}개"
- },
- "delete": {
- "noSessions": "이 자동화가 생성한 작업을 찾지 못했습니다",
- "sessions": "이 자동화가 생성한 작업 {{count}}개를 찾았습니다",
- "withInflight": "{{sessions}}. 실행 {{count}}개가 아직 진행 중입니다"
- },
- "duration": {
- "seconds": "{{count}}초",
- "minutesSeconds": "{{minutes}}분 {{seconds}}초",
- "minutes": "{{count}}분",
- "hours": "{{count}}시간",
- "days": "{{count}}일"
- },
- "relative": {
- "justNow": "방금",
- "minutesAgo": "{{count}}분 전",
- "hoursAgo": "{{count}}시간 전",
- "daysAgo": "{{count}}일 전"
- }
- }
- },
"companions": {
+ "noCreateHosts": "사용 가능한 호환 컴퓨터가 없습니다. 컴퓨터에서 Cindy를 열고 같은 계정으로 로그인하면 팀원을 새로 만들 수 있습니다.",
+ "taskAttentionCount": "확인이 필요한 작업: {{count}}",
+ "unreadChatCount": "읽지 않은 채팅: {{count}}",
"messageSent": "백그라운드 작업에 메시지를 보냈습니다",
"sentTo": "{{name}}에게 메시지를 보냄",
"receivedFrom": "{{name}}의 메시지",
diff --cc apps/mobile/src/i18n/locales/ko/sharedTask.json
index f4216b59fa,4018310246..6e0dbfd531
--- a/apps/mobile/src/i18n/locales/ko/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/ko/sharedTask.json
@@@ -42,7 -39,7 +39,7 @@@
"joined": "공유 작업에 참여했습니다",
"joinedBody": "참여 전의 메시지, 도구 결과, 첨부 파일을 확인하고 같은 Agent에게 메시지를 보낼 수 있습니다.",
"enterTask": "작업 열기",
- "inviteBoxTitle": "함께 작업할 사람에게 초대 보내기",
- "inviteBoxTitle": "동료에게 초대 링크 보내기",
++ "inviteBoxTitle": "함께 작업할 사람에게 초대 링크 보내기",
"roleGuest": "게스트",
"removeShort": "제거",
"removeNamedTitle": "{{name}} 님을 제거할까요?",
diff --cc apps/mobile/src/i18n/locales/zh-CN/composer.json
index f473050f15,1ac0170e10..67c69362ed
--- a/apps/mobile/src/i18n/locales/zh-CN/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/composer.json
@@@ -17,8 -17,9 +17,9 @@@
"uploadFailed": "{{name}} · 上传失败",
"collapsedBadge": "{{count}} 个附件,点击展开",
"imageNotAnnotatable": "这张图片暂不支持标注或转发。",
- "downloadOriginalFailed": "下载原图失败(HTTP {{status}})。",
+ "downloadOriginalFailed": "原图下载失败,请稍后重试(HTTP {{status}})。",
"annotationSaveFailed": "标注保存失败",
+ "replacementPending": "这张图片的上一次修改还未上传完成,请等待完成,或在输入框上方重试或移除后再编辑。",
"tryAgain": "请重试。",
"sendToChat": "发送到对话",
"save": "保存",
diff --cc apps/mobile/src/i18n/locales/zh-CN/devices.json
index 2be6c2bd0c,cf9654c6d2..fd7425dc10
--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json
@@@ -532,287 -527,9 +530,10 @@@
},
"viewAllRuns": "查看全部 {{count}} 次运行"
},
- "automations": {
- "heading": {
- "delete": "删除自动化",
- "pause": "暂停自动化",
- "deleteRun": "删除运行记录"
- },
- "runNow": "立即运行",
- "error": {
- "projectMissingConfig": "这个项目自动化缺少项目配置,请在电脑端删除",
- "deletePartial": "自动化已删除,但 {{count}} 个生成任务未能更新状态。请在电脑端检查这些任务。"
- },
- "subtitle": "{{active}} 个运行中 · {{total}} 个自动化",
- "metric": {
- "running": "运行中",
- "unreadResults": "未读结果",
- "executing": "执行中"
- },
- "summary": {
- "paused": "{{count}} 个自动化已暂停。选择后可以运行、暂停、编辑或打开最近任务。",
- "default": "选择自动化后可以运行、暂停、编辑或打开最近任务。"
- },
- "empty": {
- "copy": "可以直接从手机创建第一条自动化,或在电脑端创建后同步到这里。",
- "title": "这台设备暂无自动化"
- },
- "createAutomation": "新建自动化",
- "recentRuns": "最近执行",
- "runs": {
- "emptyCopy": "点击“{{runNow}}”后,新的执行会显示在这里。",
- "emptyTitle": "还没有执行记录"
- },
- "form": {
- "title": {
- "create": "新建自动化",
- "edit": "编辑自动化"
- },
- "sessionMode": {
- "bound": "绑定已有任务后,目录、worktree、Agent 和 Fast 模式跟随该任务。",
- "persistent": "首次触发会创建持续任务,后续触发继续接在同一任务里。",
- "fresh": "每次触发都会创建新的任务。"
- },
- "field": {
- "name": "名称",
- "prompt": "提示词",
- "trigger": "触发方式",
- "runSession": "运行任务",
- "boundSession": "绑定任务",
- "intervalMinutes": "间隔分钟",
- "workspace": "工作区",
- "projectDir": "项目目录",
- "model": "模型",
- "effort": "推理强度",
- "timezone": "时区"
- },
- "namePlaceholder": "例如:每日项目巡检",
- "scriptHint": "这是一个仅运行脚本的自动化,脚本配置只能在电脑端编辑;此处可以改动名称、触发方式、通知等其它字段。",
- "promptPlaceholder": "写清楚每次自动执行要让 {{appName}} 做什么",
- "trigger": {
- "recurring": "周期",
- "manual": "手动"
- },
- "session": {
- "fresh": "新任务",
- "persistent": "持续",
- "bound": "绑定"
- },
- "boundSessionA11y": "绑定任务 {{name}}",
- "intervalPlaceholder": "留空则使用 cron",
- "intervalHint": "分钟间隔请选择 1、2、3、4、5、6、10、12、15、20 或 30 分钟;整小时间隔请输入 60 的倍数,范围为 60–1380 分钟(1–23 小时)。",
- "intervalPreservedHint": "当前任务的精确间隔为每 {{duration}};未编辑或清空前会保留。",
- "workspace": {
- "project": "项目",
- "dialogue": "对话"
- },
- "useWorktree": "使用 worktree",
- "modelPlaceholderBound": "跟随任务",
- "modelPlaceholderPiDefault": "留空使用默认模型",
- "boundSessionIdPlaceholder": "任务 ID",
- "effortDefault": "默认",
- "fastMode": "Fast 模式",
- "notifyDesktop": "桌面通知",
- "notifyFeishu": "飞书通知",
- "savingA11y": "正在保存自动化",
- "saveA11y": "保存自动化",
- "cancelA11y": "取消编辑自动化"
- },
- "delete": {
- "counting": "正在统计由这条自动化生成的任务…",
- "confirmDeleteBoth": "删除自动化和任务",
- "confirmArchive": "删除自动化并归档任务",
- "confirmTaskOnly": "只删除自动化",
- "title": "删除 {{name}}",
- "copy": "删除自动化不会中断已经开始的执行。生成过的任务按下面的选项处理,和电脑端保持一致。",
- "optionsA11y": "选择生成任务处理方式",
- "keepDesc": "只删除这条自动化,历史任务继续保留在原列表里。",
- "keepLabel": "保留生成任务",
- "archiveDesc": "删除自动化后,把由它生成的任务移到归档,后续仍可搜索。",
- "archiveLabel": "归档生成任务",
- "deleteDesc": "删除自动化后,把由它生成的任务也标记为删除。这个操作不可从手机端撤销。",
- "deleteLabel": "删除生成任务",
- "cancelA11y": "取消删除自动化",
- "confirmA11y": "确认删除自动化"
- },
- "pause": {
- "title": "暂停 {{name}}",
- "detailFallback": "暂停会阻止这条自动化继续触发。",
- "previewFallback": "没有正在执行的 run",
- "confirmA11y": "确认暂停自动化",
- "confirm": "确认暂停",
- "cancelA11y": "取消暂停自动化"
- },
- "runDelete": {
- "title": "删除这条执行记录",
- "copy": "只会删除这条自动化执行记录,不会删除它打开过的任务,也不会影响后续自动触发。",
- "confirmA11y": "确认删除执行记录",
- "confirm": "删除记录",
- "cancelA11y": "取消删除执行记录"
- },
- "template": {
- "label": "模板",
- "loadingA11y": "模板加载中",
- "refreshA11y": "刷新自动化模板",
- "loading": "加载中",
- "refresh": "刷新",
- "cardA11y": "自动化模板 {{name}}",
- "manualConfig": "手动配置",
- "builtin": {
- "nightly-test-heal": {
- "name": "夜间自愈测试",
- "description": "每晚跑测试,失败项在隔离 worktree 尝试最小修复",
- "prompt": "运行项目的测试套件,如果有失败项,在隔离 worktree 尝试给出最小修复。\n约束:\n- 先按仓库文档或 package 脚本确定标准测试命令,再完整运行\n- 只修复有明确失败证据的问题,采用影响面最小的改法,避免顺手重构\n- 修复后重跑相关测试确认通过,并复核完整 diff\n- 按仓库工作流交付修复(如创建分支并开 PR),不要直接改动主分支\n- 无法安全修复的失败项,输出失败原因、疑点文件和建议的排查步骤"
- },
- "pr-gatekeeper": {
- "name": "PR 守门人",
- "description": "工作日预审开放 PR 的新增改动,按严重程度报告风险",
- "prompt": "检查仓库当前开放的 PR,对新增改动做一轮预审。\n约束:\n- 逐个查看过去 24 小时内有新提交的开放 PR(周一回看整个周末),引用 PR 编号、文件路径和具体 diff\n- 重点找正确性、安全、数据丢失和兼容性问题,按严重程度分级\n- 只报告有证据支撑的问题,说明失败场景,不要凭风格偏好挑刺\n- 除非用户明确授权,只输出审查结论,不要直接在 PR 上留言或改动代码"
- },
- "domain-radar": {
- "name": "领域雷达",
- "description": "定期搜集你关注领域的最新动态,输出有观点的摘要",
- "prompt": "围绕主题「{{topic}}」搜集过去 24 小时的最新动态(周一回看整个周末),输出一份有观点的摘要。\n约束:\n- 用 Web 搜索获取信息,交叉核对多个来源后再采信,标注每条信息的来源链接\n- 优先收录有实质内容的进展(发布、研究、政策、重要讨论),过滤营销软文和重复转载\n- 对每条动态给出一句\"为什么值得关注\"的判断,而不是罗列链接\n- 信息不足或来源存疑时如实说明,不要臆造",
- "params": {
- "topic": {
- "label": "关注主题",
- "placeholder": "如:AI Agent、新能源、前端框架"
- }
- }
- },
- "competitor-watch": {
- "name": "竞品动态追踪",
- "description": "每周汇总竞品的产品与市场动态,分析对我们的影响",
- "prompt": "追踪以下竞品最近一周的动态:{{competitors}}。\n约束:\n- 用 Web 搜索覆盖产品更新、版本发布、定价变化、市场动作和用户口碑,标注来源\n- 区分官方信息和第三方转述,未经证实的传闻要明确标注\n- 对每条重要动态给出\"对我们意味着什么\"的分析和建议\n- 没有实质动态时如实说明,不要凑数",
- "params": {
- "competitors": {
- "label": "竞品名单",
- "placeholder": "如:Notion、Linear、Figma"
- }
- }
- },
- "weekly-work-draft": {
- "name": "周报草稿助手",
- "description": "从工作目录的文档和产出物整理本周工作,生成周报草稿",
- "prompt": "根据工作目录中本周的文档、笔记和产出物变化,整理一份周报草稿。\n约束:\n- 只使用工作目录内有实际修改痕迹的内容作为证据,注明对应文件\n- 按\"本周完成 / 进行中 / 下周计划 / 需要协调\"组织,语言简洁可直接提交\n- 区分实质进展和例行事务,突出有价值的产出\n- 材料不足以判断的部分留出占位并说明,方便用户补充"
- },
- "knowledge-freshness": {
- "name": "知识库保鲜",
- "description": "每月体检工作目录文档,找出过期与矛盾内容",
- "prompt": "体检工作目录中的文档,找出需要更新的内容。\n约束:\n- 检查过期信息(旧日期、失效链接、已废弃的流程或工具)、前后矛盾和重复内容\n- 每个问题都注明文件路径和具体位置,说明判断依据\n- 按\"建议更新 / 建议合并 / 建议删除\"分类,给出修订建议清单\n- 只输出体检报告,不要直接修改文档"
- }
- }
- },
- "scheduleRowA11y": "自动化 {{title}}",
- "detail": {
- "promptScriptFallback": "仅运行脚本的自动化,配置只能在电脑端编辑",
- "promptEmpty": "没有保存自动化提示词",
- "deleteA11y": "删除自动化",
- "runNowA11y": "立即执行自动化",
- "resumeA11y": "恢复自动化",
- "pauseA11y": "暂停自动化",
- "resume": "恢复",
- "pause": "暂停",
- "editA11y": "编辑自动化",
- "edit": "编辑"
- },
- "run": {
- "openSessionA11y": "打开自动化生成的任务",
- "session": "任务",
- "restartA11y": "重新执行自动化",
- "restart": "重跑",
- "markReadA11y": "标记执行记录已读",
- "markRead": "已读",
- "deleteA11y": "删除执行记录"
- },
- "presentation": {
- "validation": {
- "templateParameter": "请输入模板参数:{{label}}",
- "name": "请输入任务名称",
- "prompt": "请输入任务提示词",
- "timezone": "请输入时区",
- "boundSession": "请选择要绑定的任务",
- "cron": "请输入 cron 表达式",
- "workingDir": "请输入项目目录",
- "effort": "推理强度只能是 {{values}}",
- "intervalPositiveInteger": "间隔分钟必须是正整数",
- "preRunHookTimeout": "检查超时必须是正整数毫秒",
- "intervalUnsupported": "分钟间隔必须能整除 60:请选择 1、2、3、4、5、6、10、12、15、20 或 30 分钟,或 1–23 小时的整点间隔"
- },
- "schedule": {
- "paused": "已暂停",
- "manual": "手动触发",
- "once": "单次任务",
- "waitingFirstRun": "等待首次执行",
- "every": "每 {{duration}}",
- "recurring": "周期任务",
- "dialogueWorkspace": "对话工作区",
- "noDirectory": "未设置目录",
- "lastRun": "上次 {{relative}}",
- "imminent": "即将执行",
- "nextRun": "{{duration}}后",
- "status": {
- "active": "运行中",
- "paused": "已暂停",
- "expired": "已完成"
- },
- "session": {
- "persistent": "持续任务",
- "bound": "绑定任务",
- "fresh": "新任务",
- "persistentWithId": "持续任务 {{id}}",
- "persistentDetail": "首次触发后持续复用同一任务",
- "boundWithId": "绑定到 {{id}}"
- }
- },
- "run": {
- "session": "任务 {{id}}",
- "delete": "删除",
- "markRead": "已读",
- "canRestart": "可重新执行",
- "noSession": "未创建任务",
- "open": "打开",
- "restart": "重跑",
- "durationUnknown": "耗时未知",
- "runningFor": "已运行 {{duration}}",
- "duration": "耗时 {{duration}}",
- "unknownTime": "未知时间",
- "status": {
- "running": "运行中",
- "success": "已完成",
- "failed": "失败",
- "aborted": "已中止",
- "interrupted": "被中断",
- "skipped": "已跳过"
- }
- },
- "pause": {
- "title": "暂停 {{name}}",
- "detail": "这条自动化当前有 {{count}} 次执行正在进行。暂停会立即阻止后续触发,并停止这些正在进行的执行。",
- "preview": "正在执行:{{count}} 次"
- },
- "delete": {
- "noSessions": "没有找到由它生成的任务",
- "sessions": "找到 {{count}} 个由它生成的任务",
- "withInflight": "{{sessions}},还有 {{count}} 次执行正在进行"
- },
- "duration": {
- "seconds": "{{count}} 秒",
- "minutesSeconds": "{{minutes}} 分 {{seconds}} 秒",
- "minutes": "{{count}} 分钟",
- "hours": "{{count}} 小时",
- "days": "{{count}} 天"
- },
- "relative": {
- "justNow": "刚刚",
- "minutesAgo": "{{count}} 分钟前",
- "hoursAgo": "{{count}} 小时前",
- "daysAgo": "{{count}} 天前"
- }
- }
- },
"companions": {
+ "noCreateHosts": "当前没有可用的兼容电脑。在电脑上打开 Cindy 并登录同一账号后即可新建伙伴。",
+ "taskAttentionCount": "{{count}} 个任务待关注",
+ "unreadChatCount": "{{count}} 段对话未读",
"messageSent": "已向后台任务发送消息",
"sentTo": "已发消息给 {{name}}",
"receivedFrom": "消息来自 {{name}}",
diff --cc apps/mobile/src/i18n/locales/zh-CN/interaction.json
index adea39f5ec,cbca389c00..1c5ac22eca
--- a/apps/mobile/src/i18n/locales/zh-CN/interaction.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/interaction.json
@@@ -200,10 -194,11 +200,11 @@@
"enablePhotoPermission": "开启照片权限",
"enable": "去开启",
"icloudTimeout": "照片还在从 iCloud 下载,等待超时了。请检查网络,稍后重试。",
- "photoNotReadable": "这张照片暂时无法读取(可能还没从 iCloud 下载完成),请稍后重试。"
+ "photoNotReadable": "这张照片暂时无法读取(可能还没从 iCloud 下载完成),请稍后重试。"
},
"pluginSetup": {
- "completeOnDesktop": "请在远程电脑完成设置,本卡片会自动更新状态。",
+ "remoteDesktop": "打开桌面",
+ "completeOnDesktop": "可通过远程桌面操作电脑完成设置。登录、授权和凭据保存均在该电脑进行,本卡片会自动更新状态。",
"chooseOne": "选择一种配置方式",
"progress": "{{satisfied}}/{{total}} 已完成",
"desktopActionHint": "在电脑端{{action}}",
diff --cc apps/mobile/src/i18n/locales/zh-CN/message.json
index 85a94f3fbb,982c71d307..e9876d4a7a
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@@ -161,10 -159,16 +161,16 @@@
"loadFailed": "图片加载失败",
"retryLoadImage": "重试加载图片",
"retry": "重试",
- "closeImage": "关闭图片"
+ "closeImage": "关闭图片",
+ "discardAnnotationTitle": "放弃标注?",
+ "discardAnnotationBody": "未保存的笔迹将会丢失。",
+ "continueAnnotating": "继续标注",
+ "discardAnnotation": "放弃标注",
+ "annotateUnavailableTitle": "暂时无法标注",
+ "annotateImageUnavailable": "标注图片(暂不可用)"
},
"queue": {
- "continueSystemInstruction": "继续未完成的任务(系统指令)",
+ "continueSystemInstruction": "继续未完成的任务(系统指令)",
"systemInstruction": "系统指令",
"retrySend": "重试发送",
"clearError": "清除错误",
@@@ -261,9 -265,9 +267,9 @@@
"steering": "插话发送中",
"orcaTitle": "协同队列 {{index}}",
"title": "队列 {{index}}",
- "orcaReadOnly": "协同消息由电脑端编排,手机上只能查看。",
+ "orcaEditDisabled": "协同消息不支持编辑或插话发送。",
"busy": "队列操作同步中,完成后再继续操作。",
- "steeringDisabled": "插话正在发送到当前 turn,等待桌面端回流后再操作。",
+ "steeringDisabled": "插话正在发送到当前这一轮,等电脑端回应后再操作。",
"editLocked": "这条队列消息正在编辑中,完成后再操作。",
"interactionLocked": "队列正在被其它操作锁定,完成后再操作。",
"syntheticHint": "这是系统自动生成的指令,可以取消,但不能编辑或插话发送。",
diff --cc apps/mobile/src/i18n/locales/zh-CN/session.json
index 43328eb661,5678dd69ec..56a8bfccd1
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@@ -530,21 -521,98 +523,98 @@@
"AUTO_REVIEW_UNAVAILABLE": "自动审批暂时无法给出判断,需要审批的操作已改为由你确认。想少被打断,可以把任务切到「完全访问」,但风险更高。",
"AUTO_REVIEW_UNAVAILABLE_WECHAT": "自动审批暂时无法给出判断,需要审批的操作已改为由你确认。个人微信不能使用「完全访问」,请直接确认这次操作。",
"AUTO_REVIEW_CONFIRM_UNDELIVERED": "自动审批没完成,确认也没有送到或没有被点。这次拒绝不是你点的。",
- "REMOTE_COMPAT_MODE_UNSUPPORTED": "远端任务不能使用本机兼容通道。请改用 Cindy AI,或在本机任务里继续。",
- "REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE": "Cindy AI 凭据尚未就绪(登录后由服务端自动下发)。请稍候重试;若持续出现,请到 设置 → 模型供应商 检查 Cindy AI 连接状态。",
- "REMOTE_LOCAL_ONLY_PROVIDER": "该模型供应商是本机专属服务(如 Ollama),SSH 远端任务无法访问本机地址。请改用 Cindy AI 网关,或选择远端主机可达的模型供应商。",
+ "REMOTE_COMPAT_MODE_UNSUPPORTED": "远程任务不能使用本机兼容通道。请改用 Cindy AI,或在本机任务里继续。",
+ "REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE": "Cindy AI 凭据尚未就绪(登录后由服务端自动下发)。请稍候重试;若持续出现,请到「设置 → 模型供应商」检查 Cindy AI 连接状态。",
+ "REMOTE_LOCAL_ONLY_PROVIDER": "该模型供应商是本机专属服务(如 Ollama),SSH 远程任务无法访问本机地址。请改用 Cindy AI 网关,或选择远程主机可达的模型供应商。",
"DEVICE_LINK_CONTROL_DISABLED": "已关闭对该设备的控制,消息未发送。",
"DEVICE_LINK_MEDIA_TRANSFER_FAILED": "附件传输失败,消息未发送。请重试。",
- "MCP_APPROVAL_AUTO_BLOCKED": "这次工具调用被自动审核拦截,未收到你手动拒绝的记录。",
+ "MCP_APPROVAL_AUTO_BLOCKED": "这次工具调用被自动审批拦截,未收到你手动拒绝的记录。",
"MCP_APPROVAL_CONFIRMATION_TIMEOUT": "权限确认超时,未收到有效的确认结果。仅凭超时无法判断你是否点过按钮。",
"MCP_APPROVAL_CONFIRMATION_UNAVAILABLE": "这次权限确认未完成,未收到你手动拒绝的记录。",
- "REMOTE_HOST_PROXY_FORWARD_UNAVAILABLE": "这个模型需要电脑端转发请求,当前远端连接还不能转发。请改用 Cindy AI,或在本机任务里使用这个模型。",
+ "REMOTE_HOST_PROXY_FORWARD_UNAVAILABLE": "这个模型需要电脑端转发请求,当前远程连接还不能转发。请改用 Cindy AI,或在本机任务里使用这个模型。",
"REMOTE_MODEL_SWITCH_ROUTE_CHANGE": "换成这个模型需要另一条连接。请新建任务后再使用。",
- "REMOTE_NATIVE_OAUTH_UNAVAILABLE": "远端任务还不能使用订阅登录。请改用 Cindy AI,或选择已配置密钥的模型供应商。",
- "REMOTE_PI_CONTEXT_PROFILE_UNAVAILABLE": "远端 Pi 任务不能使用这个上下文配置。请改用 Cindy AI,或选择远端可以访问的模型。",
- "REMOTE_PROVIDER_UNSUPPORTED": "远端任务还不能使用这个模型供应商。请换一个供应商,或在本机任务里使用它。",
+ "REMOTE_NATIVE_OAUTH_UNAVAILABLE": "远程任务还不能使用订阅登录。请改用 Cindy AI,或选择已配置密钥的模型供应商。",
+ "REMOTE_PI_CONTEXT_PROFILE_UNAVAILABLE": "远程 Pi 任务不能使用这个上下文配置。请改用 Cindy AI,或选择远程电脑可以访问的模型。",
+ "REMOTE_PROVIDER_UNSUPPORTED": "远程任务还不能使用这个模型供应商。请换一个供应商,或在本机任务里使用它。",
"REMOTE_PROVIDER_UPDATING": "这个模型供应商的凭据正在更新。请稍后再试。",
- "REMOTE_WORKDIR_UNAVAILABLE": "远端工作目录现在不可用。请确认那台电脑上的目录还在,然后重试。",
+ "REMOTE_WORKDIR_UNAVAILABLE": "远程工作目录现在不可用。请确认那台电脑上的目录还在,然后重试。",
"REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "电脑端暂时无法确认这条消息是否已经发出。请稍后再试,不要重复发送同一条。"
+ },
+ "collab": {
+ "modeLabel": "协同模式",
+ "enabled": "已开启",
+ "title": "协同",
+ "enableTitle": "开启协同",
+ "enableSubmit": "开启协同",
+ "createWorkerTitle": "创建新 Worker",
+ "createWorkerSubmit": "创建 Worker",
+ "roleLabel": "角色名",
+ "roleHint": "只是一个名字,方便多个协作者时分辨角色,不改变能力",
+ "customRole": "自定义",
+ "customRolePlaceholder": "自定义角色名",
+ "customRolePredefinedError": "自定义角色名不能使用预设角色名",
+ "agentLabel": "Agent",
+ "modelLabel": "模型",
+ "modelDefault": "默认",
+ "modelDefaultHint": "跟随电脑端的 Worker 默认模型",
+ "permissionLabel": "权限模式",
+ "permissionAuto": "自动审批",
+ "permissionFull": "完全访问",
+ "permissionAutoHint": "允许在工作区内读写,并自动审批提权请求;高风险操作可能被拒绝或要求确认。",
+ "permissionFullHint": "允许修改任意文件并运行联网命令,无需再次确认。风险最高,只适合可信任务。",
+ "initialTaskLabel": "初始任务(可选)",
+ "initialTaskPlaceholder": "给这个 Worker 的可选第一条任务",
+ "workerCountSummary_one": "{{count}} 个 Worker · {{running}} 运行中",
+ "workerCountSummary_other": "{{count}} 个 Worker · {{running}} 运行中",
+ "loading": "正在读取 Worker…",
+ "noWorkers": "还没有 Worker",
+ "focused": "焦点",
+ "manageGroup": "管理",
+ "hardLimitHint": "已达硬上限 {{limit}} 个 · 归档现有 Worker 后可继续创建",
+ "softLimitHint": "已超过软上限 {{limit}} 个 · Worker 过多会增加内存占用",
+ "limitSummary": "Worker 软上限 {{soft}} 个,硬上限 {{hard}} 个。协同设置请在电脑端修改。",
+ "stop": "结束协同",
+ "stopConfirmTitle": "结束协同?",
+ "stopConfirmDesc": "所有 Worker 都会被归档,正在执行的工作会立即停止,本次执行结果会丢失。确认要结束吗?",
+ "cancel": "取消",
+ "archive": "归档",
+ "archiveConfirm": "归档 Worker",
+ "archiveConfirmTitle": "归档 Worker {{name}}?",
+ "archiveConfirmDesc": "这会停止这个 Worker 的运行;历史记录会以归档状态保留。归档后无法恢复,需要重新创建 Worker 派任务。",
+ "loadingHint": "正在确认协同设置…",
+ "disabledHint": "协同模式已关闭,请在电脑端设置中重新启用",
+ "unavailableHint": "暂时无法确认协同设置,请稍后重试",
+ "barLead_one": "协同 · {{count}} 个 Worker · {{running}} 运行中",
+ "barLead_other": "协同 · {{count}} 个 Worker · {{running}} 运行中",
+ "barWorker": "协同 Worker · 返回 Lead",
+ "draftChip": "协同",
+ "draftSummary": "首个 Worker:{{role}} · {{agent}}",
+ "draftSubmit": "确定",
+ "draftRemove": "不开启协同",
+ "startFailedContinue": "开启协同失败,已改为单任务继续。{{reason}}",
+ "status": {
+ "idle": "空闲",
+ "running": "运行中",
+ "done": "已完成",
+ "error": "出错"
+ },
+ "errors": {
+ "unsupported": "电脑端版本过旧,暂不支持协同",
+ "loadFailed": "Worker 状态读取失败。",
+ "startFailed": "开启协同失败。",
+ "createFailed": "创建 Worker 失败。",
+ "archiveFailed": "归档 Worker 失败。",
+ "stopFailed": "结束协同失败。",
+ "WORKER_LIMIT_HARD_EXCEEDED": "已达 Worker 硬上限,请先归档现有 Worker。",
+ "NO_PROVIDER_FOR_AGENT": "电脑端没有为该 Agent 连接可用的模型供应商。请在电脑端完成连接后重试。",
+ "PROVIDER_ROUTE_UNAVAILABLE": "电脑端上的所选模型与供应商精确路由当前不可用,请改选可用的模型后重试。",
+ "BUDGET_MODEL_REQUIRES_API_MODE": "电脑端尚未配置此 Codex 模型所需的 API key。请在电脑端配置后重试。",
+ "INVALID_PARAMS": "电脑端不支持所选模型或协同配置。请改选该电脑支持的模型后重试。",
+ "PRECONDITION_FAILED": "协同模式已关闭,或当前任务暂不支持协同。",
+ "WORKER_CREATION_IN_PROGRESS": "另一个同名 Worker 正在创建,请稍后重试。",
+ "WORKER_NOT_FOUND": "这个 Worker 已不存在,列表已刷新。",
+ "ORCA_CREATE_UNCONFIRMED": "创建 Worker 超时,暂时无法确认是否成功。请先查看 Worker 列表,确认没有新建的 Worker 后再重试。",
+ "ORCA_ACTION_UNCONFIRMED": "操作超时,暂时无法确认结果。已刷新列表,请以当前显示的状态为准。"
+ }
}
}
diff --cc apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
index 86dbf83fde,af1c9dce09..5d78451dfa
--- a/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
@@@ -42,7 -39,7 +39,7 @@@
"joined": "已加入共享任务",
"joinedBody": "你可以查看加入前的消息、工具结果和附件,也可以向同一个 Agent 发消息。",
"enterTask": "进入任务",
- "inviteBoxTitle": "把邀请发给要一起协作的人",
- "inviteBoxTitle": "将邀请链接发给你的伙伴",
++ "inviteBoxTitle": "把邀请链接发给要一起协作的人",
"roleGuest": "访客",
"removeShort": "移除",
"removeNamedTitle": "移除{{name}}?",
diff --cc apps/mobile/src/i18n/locales/zh-TW/composer.json
index 35bd44024f,c38e54a50d..df1d771d10
--- a/apps/mobile/src/i18n/locales/zh-TW/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/composer.json
@@@ -17,8 -17,9 +17,9 @@@
"uploadFailed": "{{name}} · 上傳失敗",
"collapsedBadge": "{{count}} 個附件,點選展開",
"imageNotAnnotatable": "這張圖片暫不支援標註或轉發。",
- "downloadOriginalFailed": "下載原圖失敗(HTTP {{status}})。",
+ "downloadOriginalFailed": "原圖下載失敗,請稍後重試(HTTP {{status}})。",
"annotationSaveFailed": "標註儲存失敗",
+ "replacementPending": "這張圖片的上一次修改尚未上傳完成,請等待完成,或在輸入框上方重試或移除後再編輯。",
"tryAgain": "請重試。",
"sendToChat": "傳送到對話",
"save": "儲存",
diff --cc apps/mobile/src/i18n/locales/zh-TW/devices.json
index 2199cb9d1b,d499de1f23..a43944647d
--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json
@@@ -532,287 -527,9 +530,10 @@@
},
"viewAllRuns": "檢視全部 {{count}} 次執行"
},
- "automations": {
- "heading": {
- "delete": "刪除自動化",
- "pause": "暫停自動化",
- "deleteRun": "刪除執行記錄"
- },
- "runNow": "立即執行",
- "error": {
- "projectMissingConfig": "這個專案自動化缺少專案設定,請在電腦端刪除",
- "deletePartial": "自動化已刪除,但 {{count}} 個生成任務未能更新狀態。請在電腦端檢查這些任務。"
- },
- "subtitle": "{{active}} 個執行中 · {{total}} 個自動化",
- "metric": {
- "running": "執行中",
- "unreadResults": "未讀結果",
- "executing": "執行中"
- },
- "summary": {
- "paused": "{{count}} 個自動化已暫停。選擇後可以執行、暫停、編輯或開啟最近任務。",
- "default": "選擇自動化後可以執行、暫停、編輯或開啟最近任務。"
- },
- "empty": {
- "copy": "可以直接從手機建立第一條自動化,或在電腦端建立後同步到這裡。",
- "title": "這臺裝置暫無自動化"
- },
- "createAutomation": "新建自動化",
- "recentRuns": "最近執行",
- "runs": {
- "emptyCopy": "點選「{{runNow}}」後,新的執行會顯示在這裡。",
- "emptyTitle": "還沒有執行記錄"
- },
- "form": {
- "title": {
- "create": "新建自動化",
- "edit": "編輯自動化"
- },
- "sessionMode": {
- "bound": "繫結已有任務後,目錄、worktree、Agent 和 Fast 模式跟隨該任務。",
- "persistent": "首次觸發會建立持續任務,後續觸發繼續接在同一任務裡。",
- "fresh": "每次觸發都會建立新的任務。"
- },
- "field": {
- "name": "名稱",
- "prompt": "提示詞",
- "trigger": "觸發方式",
- "runSession": "執行任務",
- "boundSession": "繫結任務",
- "intervalMinutes": "間隔分鐘",
- "workspace": "工作區",
- "projectDir": "專案目錄",
- "model": "模型",
- "effort": "推理強度",
- "timezone": "時區"
- },
- "namePlaceholder": "例如:每日專案巡檢",
- "scriptHint": "這是一個僅執行指令碼的自動化,指令碼配置只能在電腦端編輯;此處可以改動名稱、觸發方式、通知等其它欄位。",
- "promptPlaceholder": "寫清楚每次自動執行要讓 {{appName}} 做什麼",
- "trigger": {
- "recurring": "週期",
- "manual": "手動"
- },
- "session": {
- "fresh": "新任務",
- "persistent": "持續",
- "bound": "繫結"
- },
- "boundSessionA11y": "繫結任務 {{name}}",
- "intervalPlaceholder": "留空則使用 cron",
- "intervalHint": "分鐘間隔請選擇 1、2、3、4、5、6、10、12、15、20 或 30 分鐘;整小時間隔請輸入 60 的倍數,範圍為 60–1380 分鐘(1–23 小時)。",
- "intervalPreservedHint": "目前任務的精確間隔為每 {{duration}};未編輯或清空前會保留。",
- "workspace": {
- "project": "專案",
- "dialogue": "對話"
- },
- "useWorktree": "使用 worktree",
- "modelPlaceholderBound": "跟隨任務",
- "modelPlaceholderPiDefault": "留空使用預設模型",
- "boundSessionIdPlaceholder": "任務 ID",
- "effortDefault": "預設",
- "fastMode": "Fast 模式",
- "notifyDesktop": "桌面通知",
- "notifyFeishu": "飛書通知",
- "savingA11y": "正在儲存自動化",
- "saveA11y": "儲存自動化",
- "cancelA11y": "取消編輯自動化"
- },
- "delete": {
- "counting": "正在統計由這條自動化生成的任務…",
- "confirmDeleteBoth": "刪除自動化和任務",
- "confirmArchive": "刪除自動化並歸檔任務",
- "confirmTaskOnly": "只刪除自動化",
- "title": "刪除 {{name}}",
- "copy": "刪除自動化不會中斷已經開始的執行。生成過的任務按下面的選項處理,和電腦端保持一致。",
- "optionsA11y": "選擇生成任務處理方式",
- "keepDesc": "只刪除這條自動化,歷史任務繼續保留在原列表裡。",
- "keepLabel": "保留生成任務",
- "archiveDesc": "刪除自動化後,把由它生成的任務移到歸檔,後續仍可搜尋。",
- "archiveLabel": "歸檔生成任務",
- "deleteDesc": "刪除自動化後,把由它生成的任務也標記為刪除。這個操作不可從手機端撤銷。",
- "deleteLabel": "刪除生成任務",
- "cancelA11y": "取消刪除自動化",
- "confirmA11y": "確認刪除自動化"
- },
- "pause": {
- "title": "暫停 {{name}}",
- "detailFallback": "暫停會阻止這條自動化繼續觸發。",
- "previewFallback": "沒有正在執行的 run",
- "confirmA11y": "確認暫停自動化",
- "confirm": "確認暫停",
- "cancelA11y": "取消暫停自動化"
- },
- "runDelete": {
- "title": "刪除這條執行記錄",
- "copy": "只會刪除這條自動化執行記錄,不會刪除它開啟過的任務,也不會影響後續自動觸發。",
- "confirmA11y": "確認刪除執行記錄",
- "confirm": "刪除記錄",
- "cancelA11y": "取消刪除執行記錄"
- },
- "template": {
- "label": "模板",
- "loadingA11y": "模板載入中",
- "refreshA11y": "重新整理自動化模板",
- "loading": "載入中",
- "refresh": "重新整理",
- "cardA11y": "自動化模板 {{name}}",
- "manualConfig": "手動配置",
- "builtin": {
- "nightly-test-heal": {
- "name": "夜間自愈測試",
- "description": "每晚跑測試,失敗項在隔離 worktree 嘗試最小修復",
- "prompt": "執行專案的測試套件,如果有失敗項,在隔離 worktree 嘗試給出最小修復。\n約束:\n- 先按倉庫文件或 package 指令碼確定標準測試命令,再完整執行\n- 只修復有明確失敗證據的問題,採用影響面最小的改法,避免順手重構\n- 修復後重跑相關測試確認通過,並複核完整 diff\n- 按倉庫工作流交付修復(如建立分支並開 PR),不要直接改動主分支\n- 無法安全修復的失敗項,輸出失敗原因、疑點檔案和建議的排查步驟"
- },
- "pr-gatekeeper": {
- "name": "PR 守門人",
- "description": "工作日預審開放 PR 的新增改動,按嚴重程度報告風險",
- "prompt": "檢查倉庫當前開放的 PR,對新增改動做一輪預審。\n約束:\n- 逐個檢視過去 24 小時內有新提交的開放 PR(週一回看整個週末),引用 PR 編號、檔案路徑和具體 diff\n- 重點找正確性、安全、資料丟失和相容性問題,按嚴重程度分級\n- 只報告有證據支撐的問題,說明失敗場景,不要憑風格偏好挑刺\n- 除非使用者明確授權,只輸出審查結論,不要直接在 PR 上留言或改動程式碼"
- },
- "domain-radar": {
- "name": "領域雷達",
- "description": "定期蒐集你關注領域的最新動態,輸出有觀點的摘要",
- "prompt": "圍繞主題「{{topic}}」蒐集過去 24 小時的最新動態(週一回看整個週末),輸出一份有觀點的摘要。\n約束:\n- 用 Web 搜尋獲取資訊,交叉核對多個來源後再採信,標註每條資訊的來源連結\n- 優先收錄有實質內容的進展(釋出、研究、政策、重要討論),過濾營銷軟文和重複轉載\n- 對每條動態給出一句\"為什麼值得關注\"的判斷,而不是羅列連結\n- 資訊不足或來源存疑時如實說明,不要臆造",
- "params": {
- "topic": {
- "label": "關注主題",
- "placeholder": "如:AI Agent、新能源、前端框架"
- }
- }
- },
- "competitor-watch": {
- "name": "競品動態追蹤",
- "description": "每週彙總競品的產品與市場動態,分析對我們的影響",
- "prompt": "追蹤以下競品最近一週的動態:{{competitors}}。\n約束:\n- 用 Web 搜尋覆蓋產品更新、版本釋出、定價變化、市場動作和使用者口碑,標註來源\n- 區分官方資訊和第三方轉述,未經證實的傳聞要明確標註\n- 對每條重要動態給出\"對我們意味著什麼\"的分析和建議\n- 沒有實質動態時如實說明,不要湊數",
- "params": {
- "competitors": {
- "label": "競品名單",
- "placeholder": "如:Notion、Linear、Figma"
- }
- }
- },
- "weekly-work-draft": {
- "name": "週報草稿助手",
- "description": "從工作目錄的文件和產出物整理本週工作,生成週報草稿",
- "prompt": "根據工作目錄中本週的文件、筆記和產出物變化,整理一份週報草稿。\n約束:\n- 只使用工作目錄內有實際修改痕跡的內容作為證據,註明對應檔案\n- 按\"本週完成 / 進行中 / 下週計劃 / 需要協調\"組織,語言簡潔可直接提交\n- 區分實質進展和例行事務,突出有價值的產出\n- 材料不足以判斷的部分留出佔位並說明,方便使用者補充"
- },
- "knowledge-freshness": {
- "name": "知識庫保鮮",
- "description": "每月體檢工作目錄文件,找出過期與矛盾內容",
- "prompt": "體檢工作目錄中的文件,找出需要更新的內容。\n約束:\n- 檢查過期資訊(舊日期、失效連結、已廢棄的流程或工具)、前後矛盾和重複內容\n- 每個問題都註明檔案路徑和具體位置,說明判斷依據\n- 按\"建議更新 / 建議合併 / 建議刪除\"分類,給出修訂建議清單\n- 只輸出體檢報告,不要直接修改文件"
- }
- }
- },
- "scheduleRowA11y": "自動化 {{title}}",
- "detail": {
- "promptScriptFallback": "僅執行指令碼的自動化,配置只能在電腦端編輯",
- "promptEmpty": "沒有儲存自動化提示詞",
- "deleteA11y": "刪除自動化",
- "runNowA11y": "立即執行自動化",
- "resumeA11y": "恢復自動化",
- "pauseA11y": "暫停自動化",
- "resume": "恢復",
- "pause": "暫停",
- "editA11y": "編輯自動化",
- "edit": "編輯"
- },
- "run": {
- "openSessionA11y": "開啟自動化生成的任務",
- "session": "任務",
- "restartA11y": "重新執行自動化",
- "restart": "重跑",
- "markReadA11y": "標記執行記錄已讀",
- "markRead": "已讀",
- "deleteA11y": "刪除執行記錄"
- },
- "presentation": {
- "validation": {
- "templateParameter": "請輸入模板參數:{{label}}",
- "name": "請輸入任務名稱",
- "prompt": "請輸入任務提示詞",
- "timezone": "請輸入時區",
- "boundSession": "請選擇要繫結的任務",
- "cron": "請輸入 cron 運算式",
- "workingDir": "請輸入專案目錄",
- "effort": "推理強度只能是 {{values}}",
- "intervalPositiveInteger": "間隔分鐘必須是正整數",
- "preRunHookTimeout": "檢查逾時必須是正整數毫秒",
- "intervalUnsupported": "分鐘間隔必須可整除 60:請選擇 1、2、3、4、5、6、10、12、15、20 或 30 分鐘,或 1–23 小時的整點間隔"
- },
- "schedule": {
- "paused": "已暫停",
- "manual": "手動觸發",
- "once": "單次任務",
- "waitingFirstRun": "等待首次執行",
- "every": "每 {{duration}}",
- "recurring": "週期任務",
- "dialogueWorkspace": "對話工作區",
- "noDirectory": "未設定目錄",
- "lastRun": "上次 {{relative}}",
- "imminent": "即將執行",
- "nextRun": "{{duration}}後",
- "status": {
- "active": "執行中",
- "paused": "已暫停",
- "expired": "已完成"
- },
- "session": {
- "persistent": "持續任務",
- "bound": "繫結任務",
- "fresh": "新任務",
- "persistentWithId": "持續任務 {{id}}",
- "persistentDetail": "首次觸發後持續複用同一任務",
- "boundWithId": "繫結到 {{id}}"
- }
- },
- "run": {
- "session": "任務 {{id}}",
- "delete": "刪除",
- "markRead": "已讀",
- "canRestart": "可重新執行",
- "noSession": "未建立任務",
- "open": "開啟",
- "restart": "重跑",
- "durationUnknown": "耗時未知",
- "runningFor": "已執行 {{duration}}",
- "duration": "耗時 {{duration}}",
- "unknownTime": "未知時間",
- "status": {
- "running": "執行中",
- "success": "已完成",
- "failed": "失敗",
- "aborted": "已中止",
- "interrupted": "被中斷",
- "skipped": "已略過"
- }
- },
- "pause": {
- "title": "暫停 {{name}}",
- "detail": "這條自動化目前有 {{count}} 次執行正在進行。暫停會立即阻止後續觸發,並停止這些正在進行的執行。",
- "preview": "正在執行:{{count}} 次"
- },
- "delete": {
- "noSessions": "沒有找到由它生成的任務",
- "sessions": "找到 {{count}} 個由它生成的任務",
- "withInflight": "{{sessions}},還有 {{count}} 次執行正在進行"
- },
- "duration": {
- "seconds": "{{count}} 秒",
- "minutesSeconds": "{{minutes}} 分 {{seconds}} 秒",
- "minutes": "{{count}} 分鐘",
- "hours": "{{count}} 小時",
- "days": "{{count}} 天"
- },
- "relative": {
- "justNow": "剛剛",
- "minutesAgo": "{{count}} 分鐘前",
- "hoursAgo": "{{count}} 小時前",
- "daysAgo": "{{count}} 天前"
- }
- }
- },
"companions": {
+ "noCreateHosts": "目前沒有可用的相容電腦。在電腦上開啟 Cindy 並登入同一帳號後即可新建夥伴。",
+ "taskAttentionCount": "{{count}} 個任務待關注",
+ "unreadChatCount": "{{count}} 段對話未讀",
"messageSent": "已向背景任務傳送訊息",
"sentTo": "已傳訊息給 {{name}}",
"receivedFrom": "訊息來自 {{name}}",
diff --cc apps/mobile/src/i18n/locales/zh-TW/interaction.json
index 995d5ae06c,6511c01ebd..7d893ee766
--- a/apps/mobile/src/i18n/locales/zh-TW/interaction.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/interaction.json
@@@ -200,10 -194,11 +200,11 @@@
"enablePhotoPermission": "開啟照片權限",
"enable": "去開啟",
"icloudTimeout": "照片還在從 iCloud 下載,等待超時了。請檢查網路,稍後重試。",
- "photoNotReadable": "這張照片暫時無法讀取(可能還沒從 iCloud 下載完成),請稍後重試。"
+ "photoNotReadable": "這張照片暫時無法讀取(可能還沒從 iCloud 下載完成),請稍後重試。"
},
"pluginSetup": {
- "completeOnDesktop": "請在遠端電腦完成設定,本卡片會自動更新狀態。",
+ "remoteDesktop": "開啟桌面",
+ "completeOnDesktop": "可透過遠端桌面操作電腦完成設定。登入、授權和憑據儲存均在該電腦進行,本卡片會自動更新狀態。",
"chooseOne": "選擇一種配置方式",
"progress": "{{satisfied}}/{{total}} 已完成",
"desktopActionHint": "在電腦端{{action}}",
diff --cc apps/mobile/src/i18n/locales/zh-TW/message.json
index a529488435,6fa917f7a1..9aaa9f48ef
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@@ -161,10 -159,16 +161,16 @@@
"loadFailed": "圖片載入失敗",
"retryLoadImage": "重試載入圖片",
"retry": "重試",
- "closeImage": "關閉圖片"
+ "closeImage": "關閉圖片",
+ "discardAnnotationTitle": "放棄標註?",
+ "discardAnnotationBody": "未儲存的筆跡將會遺失。",
+ "continueAnnotating": "繼續標註",
+ "discardAnnotation": "放棄標註",
+ "annotateUnavailableTitle": "暫時無法標註",
+ "annotateImageUnavailable": "標註圖片(暫不可用)"
},
"queue": {
- "continueSystemInstruction": "繼續未完成的任務(系統指令)",
+ "continueSystemInstruction": "繼續未完成的任務(系統指令)",
"systemInstruction": "系統指令",
"retrySend": "重試傳送",
"clearError": "清除錯誤",
@@@ -261,9 -265,9 +267,9 @@@
"steering": "插話傳送中",
"orcaTitle": "協同佇列 {{index}}",
"title": "佇列 {{index}}",
- "orcaReadOnly": "協同訊息由電腦端編排,手機上只能檢視。",
+ "orcaEditDisabled": "協同訊息不支援編輯或插話傳送。",
"busy": "佇列操作同步中,完成後再繼續操作。",
- "steeringDisabled": "插話正在傳送到目前 turn,等待桌面端回流後再操作。",
+ "steeringDisabled": "插話正在傳送到目前這一輪,等電腦端回應後再操作。",
"editLocked": "這條佇列訊息正在編輯中,完成後再操作。",
"interactionLocked": "佇列正在被其它操作鎖定,完成後再操作。",
"syntheticHint": "這是系統自動生成的指令,可以取消,但不能編輯或插話傳送。",
diff --cc apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
index 29f4f1ab70,57ae607e49..b9cc31dc47
--- a/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
@@@ -42,7 -39,7 +39,7 @@@
"joined": "已加入共享任務",
"joinedBody": "你可以查看加入前的訊息、工具結果和附件,也可以向同一個 Agent 傳送訊息。",
"enterTask": "進入任務",
- "inviteBoxTitle": "把邀請傳給要一起協作的人",
- "inviteBoxTitle": "將邀請連結傳給你的夥伴",
++ "inviteBoxTitle": "把邀請連結傳給要一起協作的人",
"roleGuest": "訪客",
"removeShort": "移除",
"removeNamedTitle": "移除{{name}}?",
diff --cc apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
index 32ec7613a9,0562660839..83a04ca85f
--- a/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
+++ b/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
@@@ -1,9 -1,11 +1,10 @@@
import type { ComponentProps, ReactNode } from "react";
import { Stack } from "expo-router";
import { HomeHeaderGlassButton } from "@/session/HomeHeaderGlassButton";
-import { BlurBackdrop } from "@/session/BlurBackdrop";
import { QuietSyncIndicator } from '@/components/QuietSyncIndicator';
import { ChevronDown, Menu } from "lucide-react-native";
- import { Pressable, StyleSheet, View, useWindowDimensions } from "react-native";
+ import { Pressable, StyleSheet, View } from "react-native";
+ import { useSafeAreaFrame, useSafeAreaInsets } from "react-native-safe-area-context";
import { Text } from "@/components/AppText";
import {
NativePullDownMenu,
@@@ -20,8 -22,7 +21,7 @@@ import
useThemedStyles,
type ThemeColors,
} from "@/theme";
- import { lineHeight, spacing } from "@/theme/tokens";
- import { navigationTitleMaxWidth } from "@/platform/chrome/navigationTitleWidth";
-import { lineHeight, navigationChrome, radius, spacing } from "@/theme/tokens";
++import { lineHeight, navigationChrome, spacing } from "@/theme/tokens";
/**
* 首页 iOS 顶栏走系统 UINavigationBar。
@@@ -86,8 -95,8 +94,8 @@@ export function HomeNativeStackHeader(
style={({ pressed }) => [styles.titleHit, pressed && styles.pressed]}
testID="devices.title"
>
- <BlurBackdrop intensity={20} overlayColor={colors.surfaceTranslucent} />
+ {/* The title sits directly on the bar: no capsule material behind it. */}
- <View style={[styles.titleCluster, { maxWidth: titleMaxWidth }]}>
+ <View style={styles.titleCluster}>
<Text numberOfLines={1} style={styles.title}>
{title}
</Text>
diff --cc apps/mobile/src/session/CompanionHeader.tsx
index e1bbfae94b,9670a5564a..36a4deaafc
--- a/apps/mobile/src/session/CompanionHeader.tsx
+++ b/apps/mobile/src/session/CompanionHeader.tsx
@@@ -8,11 -8,8 +8,10 @@@ import { Text } from '@/components/AppT
import { RemoteCompanionAvatar } from '@/components/RemoteCompanionAvatar';
import { fontWeight, iconSize, iconStroke, lineHeight, spacing, typeScale, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { HomeHeaderGlassButton } from './HomeHeaderGlassButton';
+import { CompanionBackButton } from './CompanionBackButton';
+import { useSystemNavigationBack } from '@/platform/chrome/SystemNavigationBack';
import { TeammatePicker } from './TeammatePicker';
import { CompanionCreateSheet, CompanionProfileSheet } from './CompanionProfileSheet';
- import { CompanionAutomationSheet } from './CompanionAutomationSheet';
import { useTeammateNavigation } from './useTeammateNavigation';
const AVATAR_SIZE = 32;
@@@ -30,12 -25,8 +29,11 @@@ function CompanionHeaderContent({ resou
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
const navigation = useTeammateNavigation();
+ // Duo's vertical system bar already carries a back item: keep the sidebar
+ // button there instead of showing two backs.
+ const systemBack = useSystemNavigationBack();
const [picker, setPicker] = useState(false);
const [profile, setProfile] = useState(false);
- const [automation, setAutomation] = useState(false);
const [creating, setCreating] = useState(false);
const created = useRef<RemoteResourceRef | null>(null);
const pending = useRef<(() => void) | null>(null);
diff --cc apps/mobile/src/session/CompanionMessageActions.tsx
index 8448e707ce,50bc8760fd..dfdfa38630
--- a/apps/mobile/src/session/CompanionMessageActions.tsx
+++ b/apps/mobile/src/session/CompanionMessageActions.tsx
@@@ -25,14 -24,12 +28,12 @@@ export function CompanionMessageActions
{!user && onCopy ? <Pressable style={hit} disabled={disabled || copying} accessibilityRole="button" accessibilityLabel={t(copied ? 'message.renderer.copyStateCopied' : 'message.renderer.copyStateCopy')} onPress={onCopy} testID="message.copyButton">
{copied ? <Check size={iconSize.sm} color={colors.textSecondary} /> : <Copy size={iconSize.sm} color={colors.textSecondary} />}
</Pressable> : null}
- <NativePullDownMenu actions={actions} onAction={onAction}>
- <Pressable style={hit} disabled={disabled} accessibilityRole="button" accessibilityLabel={t('message.renderer.moreActions')} testID="companion.messageMore" onPress={() => { if (!usesNativePullDownMenu()) setOpen(true); }}>
- <Ellipsis size={iconSize.sm} color={colors.textSecondary} />
- </Pressable>
- </NativePullDownMenu>
+ {/* The system menu (UIMenu / Android PopupMenu) opens over the trigger regardless of its
+ own disabled state, so a disabled More button is rendered without one. */}
+ {disabled ? more : <NativePullDownMenu actions={actions} onAction={onAction}>{more}</NativePullDownMenu>}
<CompanionSheet visible={open} title="" onClose={() => { pending.current = null; setOpen(false); }} onClosed={() => { const id = pending.current; pending.current = null; if (id) onAction(id); }}>
{actions.map(action => <Pressable key={action.id} disabled={action.disabled} accessibilityRole="button" style={{ minHeight: 44, justifyContent: 'center', paddingHorizontal: spacing.md }} onPress={() => { pending.current = action.id; setOpen(false); }}>
- <Text style={{ color: action.destructive ? colors.destructive : action.disabled ? colors.textSecondary : colors.textPrimary }}>{action.title}</Text>
+ <Text style={{ ...menuItemText, color: action.destructive ? colors.destructive : action.disabled ? colors.textSecondary : colors.textPrimary }}>{action.title}</Text>
</Pressable>)}
</CompanionSheet>
</View>;
diff --cc apps/mobile/src/session/CompanionProfileSheet.tsx
index ffb17166a9,d40fa841df..0982d37346
--- a/apps/mobile/src/session/CompanionProfileSheet.tsx
+++ b/apps/mobile/src/session/CompanionProfileSheet.tsx
@@@ -1,21 -2,21 +2,22 @@@ import { CompanionImportSheet } from '.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'expo-router';
import { randomUUID } from 'expo-crypto';
- import { Alert, Image, Platform, Pressable, ScrollView, StyleSheet, View } from 'react-native';
-import { ActivityIndicator, Alert, Image, Platform, Pressable, StyleSheet, Switch, View } from 'react-native';
++import { ActivityIndicator, Alert, Image, Platform, Pressable, StyleSheet, View } from 'react-native';
import { useTranslation } from 'react-i18next';
- import { Brain, Check, ChevronRight, Clock3, FileText, MessageCircle, Search, Settings2, Sparkles, UserRound } from 'lucide-react-native';
+ import { Brain, Camera, FileText, Hand, History, Info, Link2, Settings2, Sparkles } from 'lucide-react-native';
import { resolveRemoteText, type RemoteResource, type RemoteResourceRef, type RemoteText } from '@cindy/device-link';
import { useAuth } from '@/auth/AuthContext';
import { Text, TextInput } from '@/components/AppText';
import { MainWindowActionButton } from '@/components/MobilePrimitives';
- import { NativePullDownMenu, NativeSwitch, usesNativePullDownMenu } from '@/platform/chrome';
++import { NativeSwitch } from '@/platform/chrome';
import { RemoteCompanionAvatar } from '@/components/RemoteCompanionAvatar';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
import { invokeRemoteResourceAction } from '@/device-link/remoteResources';
import { readRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';
import { CompanionSettingsRow as ContextSheetRow } from './CompanionSettingsRow';
+ import { CompanionChoice } from './CompanionChoice';
import { CompanionSheet } from './CompanionSheet';
-import { fontWeight, iconSize, lineHeight, radius, spacing, typeScale, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
+import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { CompanionModelChain, CompanionModelPicker, readCompanionModelChain } from './CompanionModelChain';
import { CompanionCreateNativeView } from './CompanionCreateNativeView';
import { CompanionPortraitPicker, randomCompanionPortrait } from './CompanionPortraitPicker';
@@@ -495,9 -547,14 +548,14 @@@ function CompanionProfileForm({ panel,
}
} else { next[`effort${slot}`] = ''; next[`fast${slot}`] = false; }
}
- if (field.kind === 'select') { setOpenSelect(null); setSelectQuery(''); }
onChange(next);
};
+ if (field.kind === 'toggle') return <View key={field.id} style={styles.inline}>
+ <Text style={[styles.heading, styles.flex]}>{label}</Text>
- <Switch accessibilityLabel={label} value={values[field.id] === true} onValueChange={change} disabled={fieldDisabled} trackColor={{ false: colors.border, true: colors.cta }} />
++ <NativeSwitch accessibilityLabel={label} value={values[field.id] === true} onValueChange={change} disabled={fieldDisabled} seedColor={colors.inputCaret} />
+ </View>;
+ if (field.kind === 'select') return <CompanionChoice key={field.id} label={label} value={typeof values[field.id] === 'string' ? values[field.id] as string : ''} disabled={fieldDisabled}
+ options={options.map(option => ({ value: option.value, label: resolveRemoteText(option.label, i18n.language), disabled: optionDisabled(option) }))} onChange={change} />;
return <View key={field.id} style={styles.field}>
<Text style={styles.heading}>{label}</Text>
{field.id === 'avatarImageBase64' ? <CompanionPortraitPicker value={String(values[field.id] ?? '')} onChange={change} disabled={disabled} /> : field.id === 'portrait' && panel.portraits ? <View style={styles.choices}>{panel.portraits.map(portrait => <Pressable key={portrait.value} accessibilityRole="button" accessibilityLabel={`${label} ${Number(portrait.value) + 1}`} accessibilityState={{ selected: values[field.id] === portrait.value, disabled }} disabled={disabled} onPress={() => change(portrait.value)} style={[styles.portrait, values[field.id] === portrait.value && { borderColor: colors.textPrimary }]}><Image source={{ uri: portrait.uri }} style={styles.portraitImage} /></Pressable>)}</View>
diff --cc apps/mobile/src/session/CompanionTaskResultCard.tsx
index 7c2f1a45af,fdd4bbcd76..d7c4550518
--- a/apps/mobile/src/session/CompanionTaskResultCard.tsx
+++ b/apps/mobile/src/session/CompanionTaskResultCard.tsx
@@@ -3,9 -3,11 +3,11 @@@ import { Pressable, View, StyleSheet }
import { useTranslation } from 'react-i18next';
import { FileText } from 'lucide-react-native';
import type { BotCollaborationMeta } from '@cindy/maker-shared/botCollaboration';
+ import type { BotDelegationListResult } from '@cindy/maker-shared/botDelegation';
+ import { useRemoteCompanionQuery } from './useRemoteCompanionQuery';
import { Text } from '@/components/AppText';
import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
+import { useGuardedPush } from '@/utils/useGuardedPush';
import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { fontWeight, iconSize, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
import { ChatFilePathContext, type ChatFilePathContextValue, type ChatFilePathTarget } from '@/session/chatFilePathContext';
@@@ -95,13 -97,15 +97,15 @@@ function useResultFileContext(deviceId
onLongPressPath: (target: ChatFilePathTarget) => parent.onLongPressPath?.({ ...target, scope: { sessionId: childSessionId, workdir } }),
} : {}),
};
- }, [childSessionId, deviceId, invoke, openLink, parent, router, workdir]);
+ }, [childSessionId, deviceId, invoke, openLink, parent, push, workdir]);
}
- /** A frozen execution receipt (Desktop BotSessionTaskResultCard); expanding never restarts or fetches the task. */
- export function CompanionTaskResultCard({ meta, deviceId, renderMarkdown }: {
+ /** Frozen result data; legacy receipts may read the existing task title only. */
+ export function CompanionTaskResultCard({ meta, deviceId, parentSessionId, renderMarkdown, attached = false }: {
meta: BotCollaborationMeta;
+ attached?: boolean;
deviceId: string;
+ parentSessionId?: string;
/** The conversation's own Markdown renderer, so links, code and file chips read like a reply. */
renderMarkdown?: (text: string) => ReactNode;
}) {
diff --cc apps/mobile/src/session/ContextSheet.tsx
index 8606ee1846,8441f348b4..bcf8bd41b1
--- a/apps/mobile/src/session/ContextSheet.tsx
+++ b/apps/mobile/src/session/ContextSheet.tsx
@@@ -18,9 -18,7 +18,9 @@@ import
View,
useWindowDimensions,
} from 'react-native';
- import { Text } from '@/components/AppText';
+ import { Text, TextInput } from '@/components/AppText';
+import { MainWindowActionButton } from '@/components/MobilePrimitives';
+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { computeContextSheetSnapHeights, type ContextSheetSnap } from '@/session/contextSheetModel';
import { SheetModal } from '@/session/SheetModal';
@@@ -73,34 -79,46 +80,46 @@@ export function ContextSheet(
}), [insets.top, windowHeight]);
return (
- <SheetModal
- backdropTestID={testID ? `${testID}.backdrop` : undefined}
- keyboardAvoiding
- keyboardAvoidingBehavior={keyboardAvoidingBehavior}
- onBackdropPress={onClose}
- // Android 返回键 / iOS 关闭手势:两段式(对齐 ModelPickerSheet / SessionMenuSheet 的
- // handleRequestClose 语义)。子视图状态由页面持有,onBack 即「回一级」——目标模式表单 /
- // 截图列表(传了 onBack)按返回先回根视图不丢草稿,根视图(无 onBack)才整关。
- onRequestClose={onBack ?? onClose}
- visible={visible}
+ <DismissAction.Provider
+ value={(action) => {
+ pendingAfterClose.current = action;
+ onClose();
+ }}
>
- <SheetSurface
- backAccessibilityLabel={t('interaction.contextSheet.backAccessibility')}
- bottomInset={insets.bottom}
- footer={footer}
- heights={heights}
- onBack={onBack}
- onClose={onClose}
- onSnapChange={setSnap}
- snap={snap}
- testID={testID}
- title={title}
+ <SheetModal
+ backdropTestID={testID ? `${testID}.backdrop` : undefined}
+ keyboardAvoiding
+ keyboardAvoidingBehavior={keyboardAvoidingBehavior}
+ onBackdropPress={onClose}
+ onClosed={() => {
+ const action = pendingAfterClose.current;
+ pendingAfterClose.current = null;
+ action?.();
+ }}
+ // Android 返回键 / iOS 关闭手势:两段式(对齐 ModelPickerSheet / SessionMenuSheet 的
+ // handleRequestClose 语义)。子视图状态由页面持有,onBack 即「回一级」——目标模式表单 /
+ // 截图列表(传了 onBack)按返回先回根视图不丢草稿,根视图(无 onBack)才整关。
+ onRequestClose={onBack ?? onClose}
+ visible={visible}
>
- {media}
- {children}
- {error ? <Text style={styles.errorText}>{error}</Text> : null}
- </SheetSurface>
- </SheetModal>
+ <SheetSurface
+ backAccessibilityLabel={t('interaction.contextSheet.backAccessibility')}
+ bottomInset={insets.bottom}
+ footer={footer}
+ heights={heights}
+ onBack={onBack}
+ onClose={onClose}
+ onSnapChange={setSnap}
+ snap={snap}
+ testID={testID}
+ title={title}
+ >
+ {media}
+ {children}
- {error ? <Text style={{ color: colors.errorText }}>{error}</Text> : null}
++ {error ? <Text style={styles.errorText}>{error}</Text> : null}
+ </SheetSurface>
+ </SheetModal>
+ </DismissAction.Provider>
);
}
diff --cc apps/mobile/src/session/ContextSheetGoalView.tsx
index 8b04b79f03,243f249d41..5d359ffafc
--- a/apps/mobile/src/session/ContextSheetGoalView.tsx
+++ b/apps/mobile/src/session/ContextSheetGoalView.tsx
@@@ -17,8 -20,7 +20,8 @@@ import
View,
} from 'react-native';
import { Text, TextInput } from '@/components/AppText';
- import { MainWindowActionButton, MainWindowOptionButton } from '@/components/MobilePrimitives';
+ import { NativePullDownMenu, usesNativePullDownMenu } from '@/platform/chrome';
+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
import type {
MobileGoalLimitsInput,
MobileGoalStatus,
@@@ -447,37 -513,31 +514,29 @@@ function makeGoalStyles(colors: ThemeCo
paddingTop: spacing.md,
},
ctaButton: {
- marginTop: spacing.xl,
- },
- pressed: mobileInteractionStyles.pressed,
- statusHeader: {
alignItems: 'center' as const,
- flexDirection: 'row' as const,
- gap: spacing.md,
- paddingTop: spacing.lg,
- },
- statusChip: {
- backgroundColor: colors.surfaceChip,
- borderRadius: radius.pill,
- paddingHorizontal: spacing.md,
- paddingVertical: 4,
- },
- statusChipActive: {
backgroundColor: colors.cta,
+ borderRadius: radius.pill,
+ height: 50,
+ justifyContent: 'center' as const,
+ marginTop: spacing.xl,
},
- statusChipText: {
- color: colors.textPrimary,
- fontSize: typeScale.caption,
- lineHeight: lineHeight.caption,
- fontWeight: fontWeight.medium,
+ ctaButtonDisabled: {
+ opacity: 0.4,
},
- statusChipTextActive: {
+ ctaLabel: {
color: colors.ctaText,
+ fontSize: typeScale.body,
+ lineHeight: lineHeight.body,
+ fontWeight: fontWeight.medium,
},
- pressed: {
- opacity: 0.7,
- },
++ pressed: mobileInteractionStyles.pressed,
statusMeta: {
- color: colors.textTertiary,
- fontSize: typeScale.caption,
+ color: colors.textSecondary,
+ fontSize: typeScale.footnote,
lineHeight: lineHeight.caption,
+ fontWeight: fontWeight.regular,
+ paddingTop: spacing.xs,
},
objectiveText: {
color: colors.textPrimary,
diff --cc apps/mobile/src/session/HomeChromeDrawer.tsx
index 609169ab7d,4aab1e8a9a..63f134bbe4
--- a/apps/mobile/src/session/HomeChromeDrawer.tsx
+++ b/apps/mobile/src/session/HomeChromeDrawer.tsx
@@@ -2,20 -2,22 +2,23 @@@
* HomeChromeDrawer —— 首页左上角系统菜单。
*
* 从左边滑出,不是下拉卡:承载搜索、设备管理、设置和账号入口。
- * 不用 RN Modal,避免和首页其它 Modal 抢 present/dismiss。
- * iOS 系统导航栏在 RN 内容之上,树内 overlay 盖不住顶栏,所以走
- * react-native-screens FullWindowOverlay(独立 UIWindow)。
- * 新窗口里要自带 GestureHandlerRootView,左滑关闭才有效。
- * Android 无系统顶栏,继续树内 overlay。动画遵循 reduce-motion。
+ * 抽屉必须盖住整个窗口,所以不能是树内 overlay,两端都放进独立窗口:
+ * - iOS 系统导航栏在 RN 内容之上,走 react-native-screens FullWindowOverlay
+ * (独立 UIWindow),不用 RN Modal,避免和首页其它 Modal 抢 present/dismiss。
+ * - Android 宽屏常驻布局(折叠屏展开等)把首页列表挂在路由树之上的根层
+ * (ResidentHomeList),连接提示也在根层,树内 zIndex 越不过这些兄弟层;
+ * 走透明 RN Modal(独立 Dialog 窗口),返回键由 onRequestClose 接管。
+ * 新窗口里要自带 GestureHandlerRootView,左滑关闭才有效。动画遵循 reduce-motion。
*/
-import { LogOut, Monitor, Search, Settings, UsersRound } from 'lucide-react-native';
+import { Building2, LogOut, Monitor, Search, Settings, UsersRound } from 'lucide-react-native';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
AccessibilityInfo,
+ ActivityIndicator,
- BackHandler,
+ DeviceEventEmitter,
findNodeHandle,
Image,
+ Modal,
Platform,
Pressable,
StyleSheet,
@@@ -72,10 -69,8 +75,9 @@@ export function HomeChromeDrawer(
onOpenSearch,
onOpenAccounts,
onOpenDevices,
- onOpenSharedSession,
onOpenSettings,
onLogout,
+ hasRunningTasks = false,
loggingOut = false,
mode = 'tasks',
onModeChange,
@@@ -89,12 -84,8 +91,11 @@@
onOpenSearch(): void;
onOpenAccounts(): void;
onOpenDevices(): void;
- onOpenSharedSession?(): void;
onOpenSettings(): void;
+ /** 确认后才调用:抽屉内部先弹 confirmLogout,调用方不要再重复确认。 */
onLogout(): void;
+ /** 退出确认文案用:有运行中任务时额外说明任务会继续在电脑上运行。 */
+ hasRunningTasks?: boolean;
loggingOut?: boolean;
mode?: HomeMode;
onModeChange?(mode: HomeMode): void;
@@@ -155,48 -144,69 +156,50 @@@
}, [open]);
useEffect(() => {
- const animate = reduceMotion === false;
- if (open) {
+ if (open && !mounted) {
setMounted(true);
- const effective = Math.max(
- 0,
- Math.min(1, progress.value + dragX.value / panelWidth),
- );
- progress.value = effective;
- dragX.value = 0;
- progress.value = animate
- ? withTiming(1, {
- duration: motionDuration.enter,
- easing: Easing.bezier(...motionEasing.out),
- })
- : 1;
- return;
- }
- if (!mountedRef.current) return;
- const effective = Math.max(
- 0,
- Math.min(1, progress.value + dragX.value / panelWidth),
- );
- progress.value = effective;
- dragX.value = 0;
- if (!animate || closeInstant) {
- progress.value = 0;
- finishClose();
return;
}
- progress.value = withTiming(
- 0,
- {
- duration: motionDuration.exit,
- easing: Easing.bezier(...motionEasing.in),
- },
- (finished) => {
- "worklet";
- if (finished) runOnJS(finishClose)();
- },
- );
- }, [
- closeInstant,
- dragX,
- finishClose,
- open,
- panelWidth,
- progress,
- reduceMotion,
- ]);
+ if (!mounted) return;
+ // Wait for FullWindowOverlay to lay out before starting the first frame.
+ if (open && !panelReady) return;
+ runOnUI((opening: boolean, animate: boolean, instant: boolean) => {
+ "worklet";
+ targetOpen.value = opening;
+ cancelAnimation(progress);
+ if (!animate || (!opening && instant)) {
+ progress.value = opening ? 1 : 0;
+ if (!opening) runOnJS(finishClose)();
+ return;
+ }
+ progress.value = withTiming(
+ opening ? 1 : 0,
+ {
+ duration: opening ? motionDuration.enter : motionDuration.exit,
+ easing: opening
+ ? Easing.bezier(...motionEasing.out)
+ : Easing.bezier(...motionEasing.in),
+ },
+ (finished) => {
+ if (finished && !opening) runOnJS(finishClose)();
+ },
+ );
+ })(open, reduceMotion === false, closeInstant);
+ }, [closeInstant, finishClose, mounted, open, panelReady, progress, reduceMotion, targetOpen]);
- useEffect(() => {
- if (!open) return;
- const subscription = BackHandler.addEventListener(
- "hardwareBackPress",
- () => {
- onClose();
- return true;
- },
- );
- return () => subscription.remove();
- }, [onClose, open]);
+ // Android 返回键落在抽屉的 Dialog 窗口上:
+ // - 打开态:转成关闭。
+ // - 退场动画期间(open 已 false、Dialog 还没卸载)这颗键属于底层页面:不能调
+ // onClose——调用方记下的待执行动作会被它清掉;RN Modal 会吞掉原生 back,
+ // 这里把 hardwareBackPress 补发回 app 的返回键监听链,等价于抽屉已卸载时
+ // 的按下(无人消费时走系统默认返回)。
+ const requestClose = useCallback(() => {
+ if (openRef.current) {
+ onClose();
+ return;
+ }
+ DeviceEventEmitter.emit("hardwareBackPress");
+ }, [onClose]);
const closeFromGesture = useCallback(() => onClose(), [onClose]);
const panGesture = useMemo(
@@@ -296,133 -299,105 +299,123 @@@
panelStyle,
]}
testID="home.chromeMenu.panel"
+ onLayout={() => setPanelReady(true)}
>
- <View style={styles.accountRow} testID="home.chromeDrawer.account">
- <View style={styles.avatar}>
- {accountImage ? (
- <Image source={{ uri: accountImage }} style={styles.avatarImage} />
- ) : (
- <Text style={styles.avatarText}>{avatarLabel}</Text>
- )}
+ <View style={[styles.panelContent, {
+ paddingBottom: insets.bottom,
+ paddingLeft: insets.left,
+ paddingTop: insets.top + spacing.xl,
+ }]}>
+ <View style={styles.accountRow} testID="home.chromeDrawer.account">
+ {/* Default letter avatar; the organisation logo is only the small icon below. */}
+ <MobileUserAvatar name={accountName} />
+ <View style={styles.accountTexts}>
+ <Text numberOfLines={1} style={styles.accountName}>{accountName}</Text>
+ {accountEmail && accountEmail !== accountName ? (
+ <Text numberOfLines={1} style={styles.accountEmail}>{accountEmail}</Text>
+ ) : null}
+ {orgName ? (
+ <View style={styles.organizationRow}>
+ {user?.orgLogoUrl ? (
+ <Image source={{ uri: user.orgLogoUrl }} style={styles.organizationLogo} />
+ ) : (
+ <Building2 color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ )}
+ <Text numberOfLines={1} style={styles.organizationName}>{orgName}</Text>
+ </View>
+ ) : null}
+ </View>
</View>
- <View style={styles.accountTexts}>
- <Text numberOfLines={1} style={styles.accountName}>{accountTitle}</Text>
- {accountSubtitle ? (
- <Text numberOfLines={1} style={styles.accountEmail}>{accountSubtitle}</Text>
- ) : null}
- </View>
- </View>
- <View style={styles.divider} />
- {onModeChange ? <HomeModeSwitch mode={mode} onModeChange={onModeChange} /> : null}
+ <View style={styles.divider} />
+ {onModeChange ? <HomeModeSwitch mode={mode} onModeChange={onModeChange} /> : null}
- <Pressable
- accessibilityLabel={t("devices.list.a11y.openSearch")}
- accessibilityRole="button"
- onPress={onOpenSearch}
- style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
- testID="home.chromeDrawer.search"
- >
- <Search
- color={colors.textSecondary}
- size={iconSize.md}
- strokeWidth={iconStroke.regular}
- />
- <Text numberOfLines={1} style={styles.menuLabel}>
- {t("devices.list.menu.search")}
- </Text>
- </Pressable>
+ <Pressable
+ accessibilityLabel={t("devices.list.a11y.openSearch")}
+ accessibilityRole="button"
+ onPress={onOpenSearch}
+ style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
+ testID="home.chromeDrawer.search"
+ >
+ <Search
+ color={colors.textSecondary}
+ size={iconSize.md}
+ strokeWidth={iconStroke.regular}
+ />
+ <Text numberOfLines={1} style={styles.menuLabel}>
+ {t("devices.list.menu.search")}
+ </Text>
+ </Pressable>
- <Pressable
- accessibilityLabel={t('devices.management.title')}
- accessibilityRole="button"
- onPress={onOpenDevices}
- style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
- testID="home.chromeDrawer.devices"
- >
- <Monitor color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- <Text numberOfLines={1} style={styles.menuLabel}>{t('devices.management.title')}</Text>
- </Pressable>
+ <Pressable
+ accessibilityLabel={t('devices.management.title')}
+ accessibilityRole="button"
+ onPress={onOpenDevices}
+ style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
+ testID="home.chromeDrawer.devices"
+ >
+ <Monitor color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ <Text numberOfLines={1} style={styles.menuLabel}>{t('devices.management.title')}</Text>
+ </Pressable>
- {onOpenSharedSession && <Pressable
- accessibilityLabel={t('sharedTask.join')}
- accessibilityRole="button"
- onPress={onOpenSharedSession}
- style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
- >
- <UsersRound color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- <Text numberOfLines={1} style={styles.menuLabel}>{t('sharedTask.join')}</Text>
- </Pressable>}
-
- <Pressable
- accessibilityLabel={t("devices.list.a11y.openSettings")}
- accessibilityRole="button"
- onPress={openSettingsImmediately}
- ref={settingsButtonRef}
- style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
- testID="devices.settingsButton"
- >
- <Settings
- color={colors.textSecondary}
- size={iconSize.md}
- strokeWidth={iconStroke.regular}
- />
- <Text numberOfLines={1} style={styles.menuLabel}>
- {t("devices.list.menu.settings")}
- </Text>
- </Pressable>
+ <Pressable
+ accessibilityLabel={t("devices.list.a11y.openSettings")}
+ accessibilityRole="button"
+ onPress={openSettingsImmediately}
+ ref={settingsButtonRef}
+ style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
+ testID="devices.settingsButton"
+ >
+ <Settings
+ color={colors.textSecondary}
+ size={iconSize.md}
+ strokeWidth={iconStroke.regular}
+ />
+ <Text numberOfLines={1} style={styles.menuLabel}>
+ {t("devices.list.menu.settings")}
+ </Text>
+ </Pressable>
- <Pressable
- accessibilityLabel={t('devices.list.accounts.title')}
- accessibilityRole="button"
- onPress={onOpenAccounts}
- style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
- testID="home.chromeDrawer.accounts"
- >
- <UsersRound color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- <Text numberOfLines={1} style={styles.menuLabel}>{t('devices.list.accounts.title')}</Text>
- </Pressable>
+ <Pressable
+ accessibilityLabel={t('devices.list.accounts.title')}
+ accessibilityRole="button"
+ onPress={onOpenAccounts}
+ style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
+ testID="home.chromeDrawer.accounts"
+ >
+ <UsersRound color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ <Text numberOfLines={1} style={styles.menuLabel}>{t('devices.list.accounts.title')}</Text>
+ </Pressable>
- <View style={styles.menuDivider} />
+ <View style={styles.menuDivider} />
- <Pressable
- accessibilityLabel={loggingOut
- ? t('settings.account.loggingOutAccessibility')
- : t('settings.account.logout')}
- accessibilityRole="button"
- accessibilityState={{ busy: loggingOut || undefined, disabled: loggingOut || undefined }}
- disabled={loggingOut}
- onPress={onLogout}
- style={({ pressed }) => [
- styles.menuRow,
- pressed && styles.pressed,
- loggingOut && styles.disabled,
- ]}
- testID="home.chromeDrawer.logout"
- >
- <LogOut color={colors.destructive} size={iconSize.md} strokeWidth={iconStroke.regular} />
- <Text numberOfLines={1} style={[styles.menuLabel, styles.dangerMenuLabel]}>
- {loggingOut ? t('settings.account.loggingOut') : t('settings.account.logout')}
- </Text>
- </Pressable>
+ <Pressable
+ accessibilityLabel={loggingOut
+ ? t('settings.account.loggingOutAccessibility')
+ : t('settings.account.logout')}
+ accessibilityRole="button"
+ accessibilityState={{ busy: loggingOut || undefined, disabled: loggingOut || undefined }}
+ disabled={loggingOut}
+ onPress={requestLogout}
+ style={({ pressed }) => [
+ styles.menuRow,
+ pressed && styles.pressed,
+ ]}
+ testID="home.chromeDrawer.logout"
+ >
+ {/* 退出中只显示转圈(标签保留给读屏),不换成「正在退出」文字。 */}
+ {loggingOut ? (
+ <ActivityIndicator color={colors.destructive} size="small" />
+ ) : (
+ <>
+ <LogOut color={colors.destructive} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ <Text numberOfLines={1} style={[styles.menuLabel, styles.dangerMenuLabel]}>
+ {t('settings.account.logout')}
+ </Text>
+ </>
+ )}
+ </Pressable>
+ </View>
</Animated.View>
</GestureDetector>
</View>
diff --cc apps/mobile/src/session/HomeSurface.tsx
index 042010a565,76fdd3f233..3bc823e166
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@@ -5,11 -6,9 +6,11 @@@ import { ResidentHomeList, useResidentH
import { HomeNewTaskButton } from './HomeNewTaskButton';
import { useRetainedHomeState, getHomeViewSession } from './homeViewSession';
import { rememberRecentTask } from './recentTasks';
-import { homeListStyles, SessionStatusMark } from '@/session/HomeListVisuals';
+import { homeListStyles, SESSION_ROW_LONG_PRESS_MS, SessionStatusMark } from '@/session/HomeListVisuals';
- import { useHeaderHeight } from "expo-router/react-navigation";
+ import { useOptionalHeaderHeight } from '@/session/useOptionalHeaderHeight';
import { SessionHeaderNativeBlur } from "@/session/SessionHeaderNativeControls";
+import { rememberComposerEntry } from './composerMorph';
+import type { ComposerMorphOrigin } from './composerGeometry';
import { RemoteTaskSuggestions } from '@/session/RemoteTaskSuggestions';
import { isTaskSuggestionsSyncPending, useRemoteTaskSuggestionsPresentation } from '@/session/useRemoteTaskSuggestionsPresentation';
import { countHomeSuggestionSessions, remoteTaskSuggestionsMode, type RemoteTaskSuggestionId } from '@/session/remoteTaskSuggestionsModel';
@@@ -3056,14 -3037,6 +3063,8 @@@ function HomeScreenContent({ active = t
setChromeMenuCloseInstant(true);
setChromeMenuOpen(false);
}}
- onOpenSharedSession={() => {
- pendingMenuActionRef.current = null;
- guardedPush('/shared-session');
- setChromeMenuCloseInstant(true);
- setChromeMenuOpen(false);
- }}
+ // 抽屉内部先确认(confirmLogout)再调 onLogout,这里不重复确认。
+ hasRunningTasks={runningSessionIds.size > 0}
onLogout={() => void logout()}
open={chromeMenuOpen}
user={user}
@@@ -4685,19 -4655,10 +4685,10 @@@ const makeStyles = (colors: ThemeColors
connectionIconButton: {
alignItems: 'center',
borderRadius: radius.pill,
- height: 28,
+ height: CONNECTION_ICON_BUTTON_SIZE,
justifyContent: 'center',
- width: 28,
+ width: CONNECTION_ICON_BUTTON_SIZE,
},
- deviceConnectionFailedRing: {
- borderColor: colors.errorBorder,
- // 16×16 圆环:语义是正圆,用 pill(RN 钳制到半高)而非碰巧同值的 control 档。
- borderRadius: radius.pill,
- borderWidth: 1.5,
- height: 16,
- position: 'absolute',
- width: 16,
- },
deviceMenuBackdrop: {
backgroundColor: colors.overlay,
flex: 1,
diff --cc apps/mobile/src/session/MobileModelPickerList.tsx
index 67f36f5cfe,9121adcbf7..a749ab7664
--- a/apps/mobile/src/session/MobileModelPickerList.tsx
+++ b/apps/mobile/src/session/MobileModelPickerList.tsx
@@@ -18,8 -16,7 +16,8 @@@ import { useRef } from 'react'
import { Pressable, StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
import { useTranslation } from 'react-i18next';
import { Text } from '@/components/AppText';
+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
- import { Check, SlidersHorizontal, Zap } from 'lucide-react-native';
+ import { Check, SlidersHorizontal } from 'lucide-react-native';
import type { MobileAgentCapabilities, MobileModelOption } from '@/session/agentCapabilities';
import type { DeviceApiKeyStatus } from '@/device-link/deviceModelMetaCache';
@@@ -100,6 -113,9 +114,7 @@@ const makeStyles = (c: ThemeColors) =
optionRowDisabled: {
opacity: 0.45,
},
- pressed: {
- opacity: 0.65,
- },
++ pressed: mobileInteractionStyles.pressed,
optionMain: {
flex: 1,
minWidth: 0,
diff --cc apps/mobile/src/session/MobilePermissionPickerList.tsx
index ad190918b7,c812d7ea37..e6a3271c23
--- a/apps/mobile/src/session/MobilePermissionPickerList.tsx
+++ b/apps/mobile/src/session/MobilePermissionPickerList.tsx
@@@ -1,14 -1,14 +1,15 @@@
/**
- * MobilePermissionPickerList —— 权限模式下拉的行列表(新建会话页 + 会话内 composer 共用)。
+ * MobilePermissionPickerList —— 权限模式选择的行列表(新建会话页 + 会话内 composer 共用;
+ * iOS 见 MobilePermissionPickerList.ios.tsx)。
*
- * 每行 = 权限图标(`permissionPresentation`,与桌面 PermissionSelector 对齐)+ 文案 + 选中 Check;
- * auto / bypass 着色(`permissionAccentColor`),其余中性。不含容器/ScrollView —— 由调用方套
- * (新建页 in-flow panel,会话内 composer 浮层)。
+ * 每行 = 权限图标(`permissionPresentation`,与桌面 PermissionSelector 对齐)+ 文案 + 选中勾号。
+ * 选中态与 iOS 同口径:只有选中行的图标按档位着色(`permissionAccentColor`,auto / bypass
+ * 有语义色,其余中性),文字与勾号不着色,也不铺整行底色。不含容器/ScrollView —— 由调用方套。
*/
- import { Pressable, StyleSheet, type StyleProp, type ViewStyle } from 'react-native';
+ import { Pressable, StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
import { useTranslation } from 'react-i18next';
import { Text } from '@/components/AppText';
+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
import { Check } from 'lucide-react-native';
import type { MobileChoiceOption } from '@/session/agentCapabilities';
@@@ -65,39 -65,38 +66,38 @@@ export function MobilePermissionPickerL
const visibleOptions = permissionOptionsForDisplay(options, activeMode);
return (
<>
- {visibleOptions.map((option) => {
+ {visibleOptions.map((option, index) => {
const presentation = permissionPresentation(option.id, option.label);
const selected = option.id === activeMode;
- const accent = permissionAccentColor(presentation.accent, colors);
- const tinted = selected && presentation.accent !== 'neutral';
return (
- <Pressable
- accessibilityLabel={t('interaction.permission.pickerSelect', { mode: presentation.label })}
- accessibilityRole="button"
- accessibilityState={{ selected, disabled }}
- disabled={disabled}
- key={option.id}
- onPress={() => onSelect(option.id)}
- style={({ pressed }) => [
- styles.optionRow,
- rowStyle,
- selected && styles.optionRowSelected,
- pressed && mobileInteractionStyles.pressed,
- ]}
- testID={testID}
- >
- <presentation.Icon
- color={tinted ? accent : selected ? colors.textPrimary : colors.textSecondary}
- size={iconSize.action}
- strokeWidth={iconStroke.regular}
- />
- <Text numberOfLines={1} style={[styles.optionText, tinted && { color: accent }]}>
- {presentation.label}
- </Text>
- {selected ? (
- <Check color={tinted ? accent : colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.medium} />
- ) : null}
- </Pressable>
+ <View key={option.id}>
+ {index > 0 ? <View style={styles.separator} /> : null}
+ <Pressable
+ accessibilityLabel={t('interaction.permission.pickerSelect', { mode: presentation.label })}
+ accessibilityRole="button"
+ accessibilityState={{ selected, disabled }}
+ disabled={disabled}
+ onPress={() => onSelect(option.id)}
+ style={({ pressed }) => [
+ styles.optionRow,
+ rowStyle,
- pressed && { opacity: 0.65 },
++ pressed && mobileInteractionStyles.pressed,
+ ]}
+ testID={testID}
+ >
+ <presentation.Icon
+ color={selected ? permissionAccentColor(presentation.accent, colors) : colors.textSecondary}
+ size={iconSize.action}
+ strokeWidth={iconStroke.regular}
+ />
+ <Text numberOfLines={1} style={styles.optionText}>
+ {presentation.label}
+ </Text>
+ {selected ? (
+ <Check color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.medium} />
+ ) : null}
+ </Pressable>
+ </View>
);
})}
</>
diff --cc apps/mobile/src/session/ModelOptionsSheetView.tsx
index 8efeab2a3b,568f85c28a..3130e788ca
--- a/apps/mobile/src/session/ModelOptionsSheetView.tsx
+++ b/apps/mobile/src/session/ModelOptionsSheetView.tsx
@@@ -292,8 -282,7 +283,7 @@@ export function ModelOptionsSheetView(
onPress={() => setEffort(effortId)}
style={({ pressed }) => [
styles.effortOptionRow,
- effortSelected && styles.effortOptionRowSelected,
- pressed && { opacity: 0.65 },
+ pressed && mobileInteractionStyles.pressed,
]}
testID={`${testID}.effortOption`}
>
diff --cc apps/mobile/src/session/ModelPickerSheet.tsx
index e5a777a9e5,acbb7b0e13..0054b5aead
--- a/apps/mobile/src/session/ModelPickerSheet.tsx
+++ b/apps/mobile/src/session/ModelPickerSheet.tsx
@@@ -7,10 -7,9 +7,10 @@@
import { UnifiedModelPickerSheet, type UnifiedMobilePickerOptions } from './UnifiedModelPickerSheet';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
- import { ChevronDown, Search } from 'lucide-react-native';
+ import { ChevronRight, Search, X } from 'lucide-react-native';
import {
Animated,
+ Easing,
Platform,
Pressable,
ScrollView,
diff --cc apps/mobile/src/session/SessionMenuSheet.tsx
index 599f620d7e,1b1b6bb158..07c6186b89
--- a/apps/mobile/src/session/SessionMenuSheet.tsx
+++ b/apps/mobile/src/session/SessionMenuSheet.tsx
@@@ -608,13 -605,13 +624,13 @@@ export function SessionMenuSheet(
</View>
)}
- {!messageOnly ? <SessionUsageSummary providerName={providerName} session={session} usage={menuUsage} contextUsage={contextUsage} onPress={openInfo} translucent={Platform.OS === 'ios'} /> : null}
+ {!messageOnly ? <SessionUsageSummary modelLabel={modelLabel} providerName={providerName} session={session} usage={menuUsage} contextUsage={contextUsage} onPress={openInfo} translucent={Platform.OS === 'ios'} /> : null}
- {!messageOnly && isSharedTaskPeer(session.deviceLinkDeviceId) && onLeaveSharing ? (
+ {workerMode ? (
+ <WorkerMenuActions onClose={onClose} worker={worker} />
+ ) : null}
+
+ {workerMode ? null : !messageOnly && isSharedTaskPeer(session.deviceLinkDeviceId) && onLeaveSharing ? (
Platform.OS === 'ios' ? <SessionDetailsNativeActions actions={[{
label: t('sharedTask.leave'), danger: true, disabled: leavingSharing,
onPress: onLeaveSharing, testID: 'session.leaveSharingButton',
diff --cc apps/mobile/src/session/SharedTaskScreen.tsx
index cff0897cc6,a61d9d3bed..80666ce3b5
--- a/apps/mobile/src/session/SharedTaskScreen.tsx
+++ b/apps/mobile/src/session/SharedTaskScreen.tsx
@@@ -1,20 -1,29 +1,29 @@@
import { type ReactNode, type Ref } from 'react';
- import { KeyboardAvoidingView, Platform, ScrollView, StyleSheet, type View } from 'react-native';
+ import { KeyboardAvoidingView, Platform, ScrollView, StyleSheet, View } from 'react-native';
+ import { useTranslation } from 'react-i18next';
import { SafeAreaView } from 'react-native-safe-area-context';
- import { MainWindowActionButton, type MainWindowAction } from '@/components/MobilePrimitives';
+ import { MainWindowActionButton, ScreenBackButton, type MainWindowAction } from '@/components/MobilePrimitives';
+ import { Text } from '@/components/AppText';
-import { SimpleStackHeader, simpleScreenSafeAreaEdges } from '@/platform/chrome/SimpleStackHeader';
+import { SimpleStackHeader, simpleScrollInsetProps, simpleScrollScreenSafeAreaEdges } from '@/platform/chrome/SimpleStackHeader';
import { useThemedStyles, type ThemeColors } from '@/theme';
- import { fontWeight, lineHeight, spacing, typeScale } from '@/theme/tokens';
+ import { fontWeight, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
/** Full-screen management; confirmations stay compact, with native material on iOS. */
- export function SharedTaskScreen({ title, onClose, children }: {
- title: string; onClose(): void; children: ReactNode;
+ export function SharedTaskScreen({ title, onClose, children, management = false }: {
+ title: string; onClose(): void; children: ReactNode; management?: boolean;
}) {
+ const { t } = useTranslation();
const styles = useThemedStyles(makeStyles);
- return <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.root}>
- {(!management || Platform.OS === 'ios') && <SimpleStackHeader title={management ? t('settings.title') : title} onBack={onClose} />}
+ return <SafeAreaView edges={simpleScrollScreenSafeAreaEdges()} style={styles.root}>
- <SimpleStackHeader scrollEdge title={title} onBack={onClose} />
++ {(!management || Platform.OS === 'ios') && <SimpleStackHeader scrollEdge title={management ? t('settings.title') : title} onBack={onClose} />}
<KeyboardAvoidingView style={styles.body} enabled={Platform.OS === 'ios'} behavior="padding">
- <ScrollView {...simpleScrollInsetProps} contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag">{children}</ScrollView>
- <ScrollView contentContainerStyle={[styles.content, management && styles.managementContent]} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag">
++ <ScrollView {...simpleScrollInsetProps} contentContainerStyle={[styles.content, management && styles.managementContent]} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag">
+ {management && Platform.OS !== 'ios' && <View style={styles.managementNavigation}>
+ <ScreenBackButton onPress={onClose} style={styles.managementBack} testID="sharedTask.backToSettings" />
+ <Text style={styles.navigationLabel}>{t('settings.title')}</Text>
+ </View>}
+ {children}
+ </ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>;
}
diff --cc apps/mobile/src/session/TeammateHomeScreen.tsx
index 10b9be7a8c,35702e521d..9c55464648
--- a/apps/mobile/src/session/TeammateHomeScreen.tsx
+++ b/apps/mobile/src/session/TeammateHomeScreen.tsx
@@@ -29,9 -33,12 +33,13 @@@ export function TeammateHomeScreen({ ac
const routeFocused = useIsFocused();
const focused = routeFocused && active;
const push = useGuardedPush();
+ const router = useRouter();
const navigation = useTeammateNavigation();
- const roster = useTeammateRoster(focused);
+ const sharedRoster = useHomeRoster();
+ const ownRoster = useTeammateRoster(focused && !sharedRoster);
+ const ownGroups = useBotGroupRoster(ownRoster.groupTargets, focused && !sharedRoster);
+ const roster = sharedRoster?.roster ?? ownRoster;
+ const groups = sharedRoster?.groups ?? ownGroups;
const resumed = useRef(false);
const wasFocused = useRef(focused);
const [drawer, setDrawer] = useState(false);
@@@ -87,9 -93,15 +95,15 @@@
{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"
+ <HomeChromeDrawer open={drawer} user={auth.user} loggingOut={loggingOut} hasRunningTasks={hasRunningTasks} mode="teammates"
onModeChange={(mode) => afterDrawer(() => { void navigation.setMode(mode); })}
onClose={() => { pending.current = null; setDrawer(false); }} onClosed={finishOverlay}
onOpenSearch={() => afterDrawer(() => setSearchEpoch((epoch) => epoch + 1))}
diff --cc apps/mobile/src/session/TeammateList.tsx
index cc2ea7ba2a,3d430da9f5..78624e251e
--- a/apps/mobile/src/session/TeammateList.tsx
+++ b/apps/mobile/src/session/TeammateList.tsx
@@@ -1,13 -1,12 +1,13 @@@
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 { ActivityIndicator, FlatList, Pressable, RefreshControl, StyleSheet, View, type ScrollViewProps } from 'react-native';
import { useTranslation } from 'react-i18next';
-import { RefreshCw, TriangleAlert } from 'lucide-react-native';
+import { RefreshCw, Search, TriangleAlert, X } from 'lucide-react-native';
import { resolveRemoteText } from '@cindy/device-link';
import { Text, TextInput } from '@/components/AppText';
-import { MainWindowEmptyState } from '@/components/MobilePrimitives';
+import { MainWindowEmptyState, RemoteListSyncingPlaceholder, StatusDot } from '@/components/MobilePrimitives';
+import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
import { RemoteCompanionAvatar } from '@/components/RemoteCompanionAvatar';
import { useAuth } from '@/auth/AuthContext';
import { isRemoteResourceUnread } from '@/device-link/remoteResourceCache';
@@@ -32,14 -31,14 +32,16 @@@ export interface TeammateListProps
current?: LastTeammateIdentity | null;
/** SheetSurface already owns the scroll view. */
embedded?: boolean;
+ /** 独立整页、铺到透明系统顶栏下时,由列表自己让出上下安全区。 */
+ scrollInsetProps?: Pick<ScrollViewProps, 'automaticallyAdjustsScrollIndicatorInsets' | 'contentInsetAdjustmentBehavior'>;
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, scrollInsetProps }: TeammateListProps) {
- current = null, embedded = false, autoFocusSearch = false, onInteract, renderFooter }: TeammateListProps) {
++ current = null, embedded = false, autoFocusSearch = false, onInteract, renderFooter, scrollInsetProps }: TeammateListProps) {
const { t, i18n } = useTranslation();
const { user } = useAuth();
const { colors } = useTheme();
@@@ -124,10 -111,11 +126,11 @@@
</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}
+ return <FlatList {...scrollInsetProps} 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 --cc apps/mobile/src/session/UnifiedModelPickerView.tsx
index 06a2ec9693,8d84d5afc9..558c145d12
--- a/apps/mobile/src/session/UnifiedModelPickerView.tsx
+++ b/apps/mobile/src/session/UnifiedModelPickerView.tsx
@@@ -23,327 -57,838 +57,837 @@@ import
type ContextSheetSnap,
} from "./contextSheetModel";
import { mobileAgentLabel } from "./sessionAgentSwitch";
- import type { UnifiedMobilePickerViewProps } from "./UnifiedModelPickerSheet";
- // 文字角色按 mobile-design-guide §3 整行取值(字号 / 行高 / 字重);字色随主题在渲染处注入。
- const textRole = {
- /** 行标题、选项、按钮:16/22 500(textPrimary)。 */
- optionLabel: { fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium },
- /** 行标题(模型名):16/22 500(textPrimary)。 */
- rowTitle: { flexShrink: 1, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium },
- /** 次级正文(模型副标题):15/20 400(textSecondary)。 */
- rowSubtitle: { fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.regular },
- /** 短元数据(价格档、推理档、额度):12/18 400(textTertiary)。 */
- meta: { fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular },
- /** 分组小标签:13/18 600(textTertiary)。 */
- groupLabel: { fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.semibold, paddingTop: spacing.md },
- /** 说明 / 提示 / 报错(成句的话):13/18 400(textSecondary / errorText)。 */
- note: { fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular },
- /** 搜索框:bodySmall 字号;单行输入框不设行高。 */
- searchInput: { fontSize: typeScale.bodySmall, minHeight: 44 },
- } as const;
+ import type {
+ UnifiedMobilePickerViewProps,
+ UnifiedMobileRow,
+ } from "./UnifiedModelPickerSheet";
++import { mobileInteractionStyles } from "@/components/mobileInteractionStyles";
- export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
+ type Page = "sources" | "harness" | null;
+
+ /** 分组:可选小标题 + 行间 hairline(与 ContextSheetGroup 的安卓分组行同一套节奏)。 */
+ function Group({
+ title,
+ children,
+ testID,
+ }: {
+ title?: string;
+ children: ReactNode;
+ testID?: string;
+ }) {
+ const styles = useThemedStyles(makeStyles);
+ const rows = flatten(children);
+ return (
+ <View style={styles.group} testID={testID}>
+ {title ? <Text style={styles.groupLabel}>{title}</Text> : null}
+ {rows.map((row, index) => (
+ <View key={index}>
+ {index > 0 ? <View style={styles.separator} /> : null}
+ {row}
+ </View>
+ ))}
+ </View>
+ );
+ }
+
+ function flatten(children: ReactNode): ReactNode[] {
+ if (
+ children === null ||
+ children === undefined ||
+ typeof children === "boolean"
+ )
+ return [];
+ if (Array.isArray(children)) return children.flatMap(flatten);
+ return [children];
+ }
+
+ /** 设置页 / 来源页的单行:leading + 标题(+副标题)+ 右侧取值 / 勾号 / chevron。 */
+ function Row({
+ title,
+ subtitle,
+ value,
+ leading,
+ trailing,
+ selected,
+ disabled,
+ onPress,
+ accessibilityLabel,
+ testID,
+ }: {
+ title: string;
+ subtitle?: string | null;
+ value?: string | null;
+ leading?: ReactNode;
+ trailing?: ReactNode;
+ selected?: boolean;
+ disabled?: boolean;
+ onPress(): void;
+ accessibilityLabel?: string;
+ testID?: string;
+ }) {
+ const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
- const { t } = useTranslation();
- const insets = useSafeAreaInsets();
- const { height } = useWindowDimensions();
- const [snap, setSnap] = useState<ContextSheetSnap>("half");
- const button = (
- label: string,
- onPress: () => void,
- selected = false,
- icon?: ReactNode,
- disabled = false,
- ) => (
+ return (
<Pressable
- key={label}
+ accessibilityLabel={
+ accessibilityLabel ??
+ [title, subtitle, value].filter(Boolean).join(", ")
+ }
accessibilityRole="button"
- accessibilityLabel={label}
- disabled={p.busy || disabled}
- accessibilityState={{ disabled: p.busy || disabled, selected }}
+ accessibilityState={{ selected: !!selected, disabled: !!disabled }}
+ disabled={disabled}
onPress={onPress}
style={({ pressed }) => [
- {
- opacity: disabled ? 0.4 : 1,
- flexDirection: "row",
- alignItems: "center",
- gap: spacing.sm,
- minHeight: 44,
- padding: spacing.md,
- backgroundColor: selected ? colors.surfaceChip : undefined,
- borderRadius: radius.pill,
- },
- pressed && mobileInteractionStyles.pressed,
+ styles.row,
+ disabled && styles.rowDisabled,
+ pressed && styles.pressed,
]}
+ testID={testID}
>
- {icon}
- <Text style={[textRole.optionLabel, { color: colors.textPrimary }]}>{label}</Text>
+ {leading ? <View style={styles.leading}>{leading}</View> : null}
+ <View style={styles.rowMain}>
+ <Text numberOfLines={1} style={styles.rowTitle}>
+ {title}
+ </Text>
+ {subtitle ? (
+ <Text numberOfLines={1} style={styles.rowSubtitle}>
+ {subtitle}
+ </Text>
+ ) : null}
+ </View>
+ {value ? (
+ <Text numberOfLines={1} style={styles.rowValue}>
+ {value}
+ </Text>
+ ) : null}
+ {trailing}
+ {selected ? (
+ <Check
+ color={colors.textPrimary}
+ size={iconSize.lg}
+ strokeWidth={iconStroke.medium}
+ />
+ ) : null}
</Pressable>
);
- const o = p.options;
+ }
+
+ function QuotaBar({
+ remaining,
+ label,
+ testID,
+ }: {
+ remaining: number;
+ label: string;
+ testID?: string;
+ }) {
+ const styles = useThemedStyles(makeStyles);
+ const now = Math.max(0, Math.min(100, remaining));
+ return (
+ <View
+ accessibilityLabel={label}
+ accessibilityRole="progressbar"
+ accessibilityValue={{ min: 0, max: 100, now }}
+ style={styles.quotaTrack}
+ testID={testID}
+ >
+ <View style={[styles.quotaFill, { width: `${now}%` }]} />
+ </View>
+ );
+ }
+
+ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
+ const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const insets = useSafeAreaInsets();
+ const { height } = useWindowDimensions();
+ const heights = useMemo(
+ () =>
+ computeContextSheetSnapHeights({
+ screenHeight: height,
+ safeAreaTopInset: insets.top,
+ }),
+ [height, insets.top],
+ );
+ const [snap, setSnap] = useState<ContextSheetSnap>("half");
+ const [page, setPage] = useState<Page>(null);
+ const [effortExpanded, setEffortExpanded] = useState(false);
+ const searchRef = useRef<RNTextInput>(null);
+ // 与 iOS 同口径:重新打开或切换设置对象都回到主页。
+ useEffect(() => {
+ setPage(null);
+ setEffortExpanded(false);
+ }, [p.visible, p.options?.row.key]);
+ useEffect(() => {
+ if (p.visible) setSnap("half");
+ }, [p.visible]);
+
+ const icon = (Icon: typeof Star, filled = false) => (
+ <Icon
+ color={colors.textSecondary}
+ fill={filled ? colors.textSecondary : "none"}
+ size={iconSize.action}
+ strokeWidth={iconStroke.regular}
+ />
+ );
+ const level = (id: string) =>
+ t(`models.options.effortLevels.${id}`, { defaultValue: id });
+ const options = p.options;
+ const config = options?.row.config;
+ const back = page ? () => setPage(null) : p.onBack;
+ const currentFilter = p.filters.find((item) => item.id === p.filter);
+ const title =
+ page === "sources"
+ ? t("models.unified.source")
+ : page === "harness"
+ ? t("models.unified.harness")
+ : p.title;
+
+ const filterMark = (filter = currentFilter, selected = false) =>
+ !filter || filter.id === "all" ? (
+ icon(LayoutGrid)
+ ) : filter.id === "favorites" ? (
+ icon(Star, selected || p.filter === "favorites")
+ ) : filter.providerMark ? (
+ <MobileProviderMark {...filter.providerMark} />
+ ) : (
+ icon(LayoutGrid)
+ );
+
+ const searchHeader =
+ !options && !page ? (
+ <View style={styles.searchRow}>
+ <View style={styles.searchField}>
+ <Search
+ color={colors.textSecondary}
+ size={iconSize.md}
+ strokeWidth={iconStroke.regular}
+ />
+ <TextInput
+ accessibilityLabel={t("models.picker.searchAccessibility")}
+ autoCapitalize="none"
+ autoCorrect={false}
+ onChangeText={p.onQuery}
+ // Android adjustResize:聚焦搜索时吸到 full,边输边看列表(与旧版模型浮窗同口径)。
+ onFocus={() => setSnap("full")}
+ placeholder={t("models.picker.searchPlaceholder")}
+ placeholderTextColor={colors.textPlaceholder}
+ ref={searchRef}
+ style={styles.searchInput}
+ testID={`${p.testID}.search`}
+ value={p.query}
+ />
+ {p.query ? (
+ <Pressable
+ accessibilityLabel={t("devices.detail.search.clearA11y")}
+ accessibilityRole="button"
+ hitSlop={4}
+ onPress={() => p.onQuery("")}
+ style={({ pressed }) => [
+ styles.iconButton,
+ pressed && styles.pressed,
+ ]}
+ testID={`${p.testID}.search.clear`}
+ >
+ <X
+ color={colors.textTertiary}
+ size={iconSize.md}
+ strokeWidth={iconStroke.regular}
+ />
+ </Pressable>
+ ) : null}
+ </View>
+ <Pressable
+ accessibilityLabel={t("models.unified.source")}
+ accessibilityRole="button"
+ accessibilityValue={{ text: currentFilter?.label ?? "" }}
+ onPress={() => setPage("sources")}
+ style={({ pressed }) => [
+ styles.sourceButton,
+ pressed && styles.pressed,
+ ]}
+ testID={`${p.testID}.filter`}
+ >
+ <View style={styles.markBox}>{filterMark()}</View>
+ <Text numberOfLines={1} style={styles.sourceLabel}>
+ {currentFilter?.label ?? ""}
+ </Text>
+ <ChevronRight
+ color={colors.textTertiary}
+ size={iconSize.sm}
+ strokeWidth={iconStroke.regular}
+ />
+ </Pressable>
+ </View>
+ ) : undefined;
+
+ const sourcesPage = (
+ <Group testID={`${p.testID}.sources`}>
+ {p.filters.map((item) => (
+ <Row
+ key={item.id}
+ leading={
+ <View style={styles.sourceLeading}>
+ {filterMark(
+ item,
+ item.id === "favorites" && p.filter === "favorites",
+ )}
+ {item.quota ? (
+ <QuotaBar
+ label={item.quota.label}
+ remaining={item.quota.remaining}
+ testID={`${p.testID}.source.${item.id}.quota`}
+ />
+ ) : null}
+ </View>
+ }
+ onPress={() => {
+ p.onFilter(item.id);
+ setPage(null);
+ }}
+ selected={p.filter === item.id}
+ subtitle={item.quota?.label}
+ testID={`${p.testID}.source.${item.id}`}
+ title={item.label}
+ />
+ ))}
+ </Group>
+ );
+
+ const harnessPage =
+ options && config ? (
+ <Group testID={`${p.testID}.harnessPage`}>
+ {options.agents.map((agent) => (
+ <Row
+ disabled={p.busy}
+ key={agent}
+ leading={
+ <MobileAgentMark
+ agentKind={agent}
+ color={colors.textSecondary}
+ size={iconSize.action}
+ />
+ }
+ onPress={() => {
+ const cap = options.row.entry.capabilities[agent];
+ if (!cap) return;
+ options.onChange({
+ ...config,
+ agent,
+ modelId: cap.wireModelId,
+ effort: cap.defaultEffort ?? cap.efforts[0] ?? "",
+ fast: false,
+ });
+ setPage(null);
+ }}
+ selected={config.agent === agent}
+ testID={`${p.testID}.harness.${agent}`}
+ title={mobileAgentLabel(agent)}
+ />
+ ))}
+ </Group>
+ ) : null;
+
+ const efforts =
+ options && config
+ ? (options.row.entry.capabilities[config.agent]?.efforts ?? [])
+ : [];
+ const nativeMenu = usesNativePullDownMenu();
+ const effortRow =
+ options && config && efforts.length ? (
+ <View>
+ <NativePullDownMenu
+ disabled={p.busy}
+ actions={efforts.map((effort) => ({
+ id: effort,
+ title: level(effort),
+ state: effort === config.effort ? "on" : "off",
+ disabled: p.busy,
+ }))}
+ onAction={(id) => {
+ const effort = efforts.find((item) => item === id);
+ if (p.busy || !effort) return;
+ options.onChange({ ...config, effort });
+ }}
+ testID={`${p.testID}.effortMenu`}
+ >
+ <Row
+ accessibilityLabel={`${t("models.options.reasoningEffort")}, ${level(config.effort)}`}
+ disabled={p.busy}
+ onPress={() => {
+ if (!nativeMenu) setEffortExpanded((open) => !open);
+ }}
+ leading={icon(Brain)}
+ testID={`${p.testID}.effort`}
+ title={t("models.options.reasoningEffort")}
+ trailing={
+ <ChevronsUpDown
+ color={colors.textTertiary}
+ size={iconSize.sm}
+ strokeWidth={iconStroke.regular}
+ />
+ }
+ value={config.effort ? level(config.effort) : null}
+ />
+ </NativePullDownMenu>
+ {!nativeMenu && effortExpanded
+ ? efforts.map((effort) => (
+ <Row
+ disabled={p.busy}
+ key={effort}
+ onPress={() => {
+ options.onChange({ ...config, effort });
+ setEffortExpanded(false);
+ }}
+ selected={effort === config.effort}
+ testID={`${p.testID}.effort.${effort}`}
+ title={level(effort)}
+ />
+ ))
+ : null}
+ </View>
+ ) : null;
+
+ const settingsPage =
+ options && config ? (
+ <>
+ {options.context ? (
+ <Text style={styles.footnote} testID={`${p.testID}.context`}>
+ {options.context}
+ </Text>
+ ) : null}
+ <Group>
+ <Row
+ disabled={p.busy}
+ leading={
+ <MobileAgentMark
+ agentKind={config.agent}
+ color={colors.textSecondary}
+ size={iconSize.action}
+ />
+ }
+ onPress={() => setPage("harness")}
+ testID={`${p.testID}.harness`}
+ title={t("models.unified.harness")}
+ trailing={
+ <ChevronRight
+ color={colors.textTertiary}
+ size={iconSize.md}
+ strokeWidth={iconStroke.regular}
+ />
+ }
+ value={mobileAgentLabel(config.agent)}
+ />
+ {effortRow}
+ {options.fastCapable ? (
+ <View style={styles.row}>
+ <View style={styles.leading}>{icon(Zap, true)}</View>
+ <Text numberOfLines={1} style={[styles.rowTitle, styles.rowMain]}>
+ {t("models.options.fastMode")}
+ </Text>
+ <NativeSwitch
+ accessibilityLabel={t("models.options.fastMode")}
+ disabled={p.busy}
+ onValueChange={(fast) => options.onChange({ ...config, fast })}
+ seedColor={colors.cta}
+ testID={`${p.testID}.fast`}
+ value={config.fast}
+ />
+ </View>
+ ) : null}
+ </Group>
+ {options.price ? (
+ <Text
+ style={[styles.footnote, styles.price]}
+ testID={`${p.testID}.price`}
+ >
+ {options.price}
+ </Text>
+ ) : null}
+ <Group>
+ <Row
+ disabled={p.busy || options.favoritesDisabled}
+ leading={icon(Star, !!options.row.favorite)}
+ onPress={options.onFavorite}
+ testID={`${p.testID}.favorite`}
+ title={t(
+ options.row.favorite
+ ? "models.unified.removeFavorite"
+ : "models.unified.addFavorite",
+ )}
+ />
+ {!options.row.favorite ? (
+ <Row
+ disabled={p.busy}
+ onPress={options.onReset}
+ testID={`${p.testID}.reset`}
+ title={t("models.unified.restoreRecommended")}
+ />
+ ) : null}
+ </Group>
+ </>
+ ) : null;
+
+ const modelRow = (row: UnifiedMobileRow) => {
+ const agentLabel = mobileAgentLabel(row.config.agent);
+ const disabled = p.busy || row.disabled;
+ return (
+ <View key={row.key} style={styles.modelRow}>
+ <Pressable
+ accessibilityLabel={[
+ row.entry.displayName,
+ agentLabel,
+ row.subtitle,
+ row.config.fast ? t("models.options.fastMode") : null,
+ row.quotaLabel,
+ ]
+ .filter(Boolean)
+ .join(", ")}
+ accessibilityRole="button"
+ accessibilityState={{ selected: row.selected, disabled }}
+ disabled={disabled}
+ onPress={() => p.onSelect(row)}
+ style={({ pressed }) => [
+ styles.modelMain,
+ row.disabled && styles.rowDisabled,
+ pressed && styles.pressed,
+ ]}
+ testID={`${p.testID}.model.${row.key}`}
+ >
+ <View style={styles.leading}>
+ <MobileModelIconMark
+ icon={row.entry.icon}
+ {...row.providerMark}
+ color={colors.textSecondary}
+ />
+ </View>
+ <View style={styles.rowMain}>
+ <View style={styles.titleLine}>
+ <Text
+ numberOfLines={1}
+ style={[styles.rowTitle, styles.titleText]}
+ >
+ {row.entry.displayName}
+ </Text>
+ {row.costMarks ? (
+ <Text style={styles.meta}>{row.costMarks}</Text>
+ ) : null}
+ <MobileAgentMark
+ agentKind={row.config.agent}
+ color={colors.textSecondary}
+ />
+ {row.effortLabel ? (
+ <Text numberOfLines={1} style={styles.meta}>
+ {row.effortLabel}
+ </Text>
+ ) : null}
+ {row.config.fast ? (
+ <Zap
+ color={colors.textSecondary}
+ fill={colors.textSecondary}
+ size={iconSize.sm}
+ strokeWidth={iconStroke.regular}
+ />
+ ) : null}
+ </View>
+ {row.subtitle ? (
+ <Text numberOfLines={1} style={styles.rowSubtitle}>
+ {row.subtitle}
+ </Text>
+ ) : null}
+ {row.quotaLabel ? (
+ <Text numberOfLines={1} style={styles.quotaText}>
+ {row.quotaLabel}
+ </Text>
+ ) : null}
+ </View>
+ {row.favorite ? (
+ <Star
+ color={colors.textSecondary}
+ fill={colors.textSecondary}
+ size={iconSize.md}
+ strokeWidth={iconStroke.regular}
+ />
+ ) : null}
+ {row.selected ? (
+ <Check
+ color={colors.textPrimary}
+ size={iconSize.lg}
+ strokeWidth={iconStroke.medium}
+ />
+ ) : null}
+ </Pressable>
+ <Pressable
+ accessibilityLabel={t("models.picker.configureAccessibility", {
+ model: row.entry.displayName,
+ })}
+ accessibilityRole="button"
+ accessibilityState={{ disabled }}
+ disabled={disabled}
+ onPress={() => p.onOptions(row)}
+ style={({ pressed }) => [
+ styles.optionsButton,
+ pressed && styles.pressed,
+ ]}
+ testID={`${p.testID}.model.${row.key}.optionsButton`}
+ >
+ <SlidersHorizontal
+ color={colors.textSecondary}
+ size={iconSize.action}
+ strokeWidth={iconStroke.regular}
+ />
+ </Pressable>
+ </View>
+ );
+ };
+
+ const listPage = (
+ <>
+ {p.groups.map((group) => (
+ <Group
+ key={group.key}
+ testID={`${p.testID}.group.${group.key}`}
+ title={group.title}
+ >
+ {group.rows.map(modelRow)}
+ </Group>
+ ))}
+ {!p.groups.length ? (
+ <Text style={styles.empty} testID={`${p.testID}.empty`}>
+ {p.loading ? t("models.picker.loadingDefault") : p.emptyHint}
+ </Text>
+ ) : null}
+ </>
+ );
+
return (
<SheetModal
- visible={p.visible}
- onClosed={p.onClosed}
- onBackdropPress={p.onClose}
- onRequestClose={p.onBack ?? p.onClose}
keyboardAvoiding
+ onBackdropPress={p.onClose}
+ onClosed={p.onClosed}
+ onRequestClose={back ?? p.onClose}
+ visible={p.visible}
>
<SheetSurface
- title={p.title}
- onBack={p.onBack}
+ backAccessibilityLabel={
+ page ? undefined : t("models.picker.backToModels")
+ }
+ bottomInset={insets.bottom}
+ heights={heights}
+ onBack={back}
onClose={p.onClose}
- heights={computeContextSheetSnapHeights({
- screenHeight: height,
- safeAreaTopInset: insets.top,
- })}
+ onSnapChange={(next) => {
+ // 拖回 half 视为想收起键盘(与旧版模型浮窗同口径)。
+ if (next === "half") searchRef.current?.blur();
+ setSnap(next);
+ }}
+ pinnedTop={searchHeader}
snap={snap}
- onSnapChange={setSnap}
- bottomInset={insets.bottom}
testID={p.testID}
+ title={title}
>
- {p.error ? (
- <Text style={[textRole.note, { color: colors.errorText }]}>{p.error}</Text>
- ) : null}
- {o ? (
- <>
- <Text style={[textRole.note, { color: colors.textSecondary }]}>{o.context}</Text>
- <Text style={[textRole.groupLabel, { color: colors.textTertiary }]}>{t("models.unified.harness")}</Text>
- {o.agents.map((agent) =>
- button(
- mobileAgentLabel(agent),
- () => {
- const cap = o.row.entry.capabilities[agent]!;
- o.onChange({
- ...o.row.config,
- agent,
- modelId: cap.wireModelId,
- effort: cap.defaultEffort ?? cap.efforts[0] ?? "",
- fast: false,
- });
- },
- agent === o.row.config.agent,
- <MobileAgentMark
- agentKind={agent}
- color={colors.textSecondary}
- />,
- ),
- )}
- <Text style={[textRole.groupLabel, { color: colors.textTertiary }]}>{t("models.options.reasoningEffort")}</Text>
- {o.row.entry.capabilities[o.row.config.agent]?.efforts.map(
- (effort) =>
- button(
- t(`models.options.effortLevels.${effort}`),
- () => o.onChange({ ...o.row.config, effort }),
- effort === o.row.config.effort,
- ),
- )}
- {o.fastCapable
- ? button(
- t("models.options.fastMode"),
- () =>
- o.onChange({ ...o.row.config, fast: !o.row.config.fast }),
- o.row.config.fast,
- <Zap
- size={iconSize.action}
- color={colors.textSecondary}
- fill={colors.textSecondary}
- />,
- )
- : null}
- {o.price ? <Text style={[textRole.note, { color: colors.textSecondary }]}>{o.price}</Text> : null}
- {button(
- t(
- o.row.favorite
- ? "models.unified.removeFavorite"
- : "models.unified.addFavorite",
- ),
- o.onFavorite,
- false,
- <Star
- size={iconSize.action}
- color={colors.textSecondary}
- fill={o.row.favorite ? colors.textSecondary : "none"}
- />,
- o.favoritesDisabled,
- )}
- {!o.row.favorite
- ? button(t("models.unified.restoreRecommended"), o.onReset)
- : null}
- </>
- ) : (
- <>
- <TextInput
- value={p.query}
- onChangeText={p.onQuery}
- placeholder={t("models.picker.searchPlaceholder")}
- placeholderTextColor={colors.textPlaceholder}
- style={[textRole.searchInput, { color: colors.textPrimary }]}
- />
- <ScrollView horizontal>
- {p.filters.map((item) =>
- button(
- item.quota
- ? `${item.label} · ${item.quota.label}`
- : item.label,
- () => p.onFilter(item.id),
- p.filter === item.id,
- item.providerMark ? (
- <View
- accessibilityLabel={item.quota?.label}
- style={{ alignItems: "center", gap: spacing.xs }}
- >
- <MobileProviderMark {...item.providerMark} />
- {item.quota ? (
- <View
- accessibilityRole="progressbar"
- accessibilityValue={{
- min: 0,
- max: 100,
- now: item.quota.remaining,
- }}
- style={{
- width: 24,
- height: 3,
- borderRadius: radius.pill,
- backgroundColor: colors.surfaceChip,
- overflow: "hidden",
- }}
- >
- <View
- style={{
- width: `${item.quota.remaining}%`,
- height: "100%",
- backgroundColor: colors.textSecondary,
- }}
- />
- </View>
- ) : null}
- </View>
- ) : item.id === "favorites" ? (
- <Star size={iconSize.action} color={colors.textSecondary} />
- ) : (
- <LayoutGrid
- size={iconSize.action}
- color={colors.textSecondary}
- />
- ),
- ),
- )}
- </ScrollView>
- {p.groups.map((group) => (
- <View key={group.key}>
- <Text style={[textRole.groupLabel, { color: colors.textTertiary }]}>{group.title}</Text>
- {group.rows.map((row) => (
- <View
- key={row.key}
- style={{ flexDirection: "row", alignItems: "center" }}
- >
- <Pressable
- disabled={p.busy || row.disabled}
- accessibilityRole="button"
- accessibilityState={{ disabled: p.busy || row.disabled, selected: row.selected }}
- onPress={() => p.onSelect(row)}
- style={({ pressed }) => [
- {
- flex: 1,
- minHeight: 52,
- padding: spacing.md,
- flexDirection: "row",
- alignItems: "center",
- gap: spacing.sm,
- },
- pressed && mobileInteractionStyles.pressed,
- ]}
- >
- <MobileModelIconMark
- icon={row.entry.icon}
- {...row.providerMark}
- />
- <View style={{ flex: 1 }}>
- <View
- style={{
- flexDirection: "row",
- alignItems: "center",
- gap: spacing.xs,
- }}
- >
- <Text numberOfLines={1} style={[textRole.rowTitle, { color: colors.textPrimary }]}>
- {row.entry.displayName}
- </Text>
- {row.costMarks ? (
- <Text style={[textRole.meta, { color: colors.textTertiary }]}>{row.costMarks}</Text>
- ) : null}
- <MobileAgentMark
- agentKind={row.config.agent}
- color={colors.textSecondary}
- />
- <Text style={[textRole.meta, { color: colors.textTertiary }]}>{row.effortLabel}</Text>
- {row.config.fast ? (
- <Zap
- size={iconSize.sm}
- color={colors.textSecondary}
- />
- ) : null}
- </View>
- {row.subtitle ? (
- <Text numberOfLines={1} style={[textRole.rowSubtitle, { color: colors.textSecondary }]}>
- {row.subtitle}
- </Text>
- ) : null}
- {row.quotaLabel ? (
- <Text style={[textRole.meta, { color: colors.textTertiary }]}>{row.quotaLabel}</Text>
- ) : null}
- </View>
- {row.favorite ? (
- <Star
- size={iconSize.action}
- color={colors.textSecondary}
- fill={colors.textSecondary}
- />
- ) : null}
- {row.selected ? (
- <Check
- size={iconSize.action}
- color={colors.textSecondary}
- />
- ) : null}
- </Pressable>
- <Pressable
- accessibilityRole="button"
- accessibilityLabel={t(
- "models.picker.configureAccessibility",
- { model: row.entry.displayName },
- )}
- disabled={p.busy || row.disabled}
- onPress={() => p.onOptions(row)}
- style={({ pressed }) => [
- {
- width: 44,
- height: 44,
- alignItems: "center",
- justifyContent: "center",
- },
- pressed && mobileInteractionStyles.pressed,
- ]}
- >
- <SlidersHorizontal
- size={iconSize.action}
- color={colors.textSecondary}
- />
- </Pressable>
- </View>
- ))}
- </View>
- ))}
- {!p.groups.length ? (
- <Text style={[textRole.note, { color: colors.textSecondary }]}>
- {p.loading ? t("models.picker.loadingDefault") : p.emptyHint}
- </Text>
- ) : null}
- </>
- )}
+ {p.error ? <Text style={styles.error}>{p.error}</Text> : null}
+ {page === "sources"
+ ? sourcesPage
+ : page === "harness" && options
+ ? harnessPage
+ : options
+ ? settingsPage
+ : listPage}
</SheetSurface>
</SheetModal>
);
}
+
+ function makeStyles(colors: ThemeColors) {
+ return StyleSheet.create({
+ searchRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: spacing.sm,
+ paddingBottom: spacing.sm,
+ },
+ searchField: {
+ alignItems: "center",
+ backgroundColor: colors.surfaceElevated,
+ borderColor: colors.border,
+ borderRadius: radius.pill,
+ borderWidth: StyleSheet.hairlineWidth,
+ flex: 1,
+ flexDirection: "row",
+ gap: spacing.sm,
+ minHeight: 44,
+ minWidth: 0,
+ paddingLeft: spacing.md,
+ paddingRight: spacing.xs,
+ },
+ searchInput: {
+ color: colors.textPrimary,
+ flex: 1,
+ fontSize: typeScale.bodySmall,
+ minWidth: 0,
+ paddingVertical: spacing.sm,
+ },
+ iconButton: {
+ alignItems: "center",
+ height: 36,
+ justifyContent: "center",
+ width: 36,
+ },
+ sourceButton: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: spacing.xs,
+ maxWidth: 140,
+ minHeight: 44,
+ },
+ sourceLabel: {
+ color: colors.textSecondary,
+ flexShrink: 1,
+ fontSize: typeScale.bodySmall,
+ fontWeight: fontWeight.medium,
+ lineHeight: lineHeight.bodySmall,
+ },
+ markBox: {
+ alignItems: "center",
+ height: 24,
+ justifyContent: "center",
+ width: 24,
+ },
+ group: {
+ paddingTop: spacing.lg,
+ },
+ groupLabel: {
+ color: colors.textTertiary,
+ fontSize: typeScale.footnote,
+ fontWeight: fontWeight.semibold,
+ lineHeight: lineHeight.caption,
+ paddingBottom: spacing.xs,
+ },
+ separator: {
+ backgroundColor: colors.border,
+ height: StyleSheet.hairlineWidth,
+ },
+ row: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: spacing.md,
+ minHeight: 48,
+ paddingVertical: spacing.xs,
+ },
+ rowDisabled: {
+ opacity: 0.4,
+ },
- pressed: {
- opacity: 0.6,
- },
++ pressed: mobileInteractionStyles.pressed,
+ leading: {
+ alignItems: "center",
+ justifyContent: "center",
+ minHeight: 28,
+ width: 28,
+ },
+ rowMain: {
+ flex: 1,
+ minWidth: 0,
+ },
+ rowTitle: {
+ color: colors.textPrimary,
+ fontSize: typeScale.body,
+ fontWeight: fontWeight.medium,
+ lineHeight: lineHeight.body,
+ },
+ rowSubtitle: {
+ color: colors.textSecondary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.caption,
+ },
+ rowValue: {
+ color: colors.textSecondary,
+ flexShrink: 1,
+ fontSize: typeScale.body,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.body,
+ maxWidth: "50%",
+ },
+ sourceLeading: {
+ alignItems: "center",
+ gap: spacing.xs,
+ },
+ quotaTrack: {
+ backgroundColor: colors.surfaceChip,
+ borderRadius: radius.pill,
+ height: 3,
+ overflow: "hidden",
+ width: 24,
+ },
+ quotaFill: {
+ backgroundColor: colors.textSecondary,
+ height: "100%",
+ },
+ modelRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ },
+ modelMain: {
+ alignItems: "center",
+ flex: 1,
+ flexDirection: "row",
+ gap: spacing.md,
+ minHeight: 56,
+ minWidth: 0,
+ paddingVertical: spacing.sm,
+ },
+ titleLine: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: spacing.xs,
+ minWidth: 0,
+ },
+ titleText: {
+ flexShrink: 1,
+ },
+ meta: {
+ color: colors.textSecondary,
+ flexShrink: 0,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.caption,
+ },
+ quotaText: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.caption,
+ },
+ optionsButton: {
+ alignItems: "center",
+ height: 44,
+ justifyContent: "center",
+ width: 44,
+ },
+ footnote: {
+ color: colors.textSecondary,
+ fontSize: typeScale.footnote,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.caption,
+ paddingTop: spacing.md,
+ },
+ price: {
+ paddingTop: spacing.lg,
+ },
+ empty: {
+ color: colors.textSecondary,
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ paddingVertical: spacing.lg,
+ textAlign: "center",
+ },
+ error: {
+ color: colors.errorText,
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ paddingTop: spacing.md,
+ },
+ });
+ }
diff --cc apps/mobile/src/update/playUpdateEntries.test.ts
index 0000000000,6859236879..5d3645da00
mode 000000,100644..100644
--- a/apps/mobile/src/update/playUpdateEntries.test.ts
+++ b/apps/mobile/src/update/playUpdateEntries.test.ts
@@@ -1,0 -1,118 +1,118 @@@
+ import { readFileSync } from 'node:fs';
+ import { resolve } from 'node:path';
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+ const mocks = vi.hoisted(() => ({
+ playInstall: vi.fn(() => true),
+ fetchLatest: vi.fn(async () => null),
+ checkOta: vi.fn(async () => ({ isAvailable: false })),
+ fetchOta: vi.fn(async () => ({ isNew: false })),
+ appStateListener: null as ((state: string) => void) | null,
+ cleanup: null as (() => void) | null,
+ }));
+
+ // Exercise the update hooks' real effects and callbacks without rendering the full app.
+ vi.mock('react', () => ({
+ useCallback: (callback: unknown) => callback,
+ useRef: (value: unknown) => ({ current: value }),
+ useState: (value: unknown) => [value, vi.fn()],
+ useEffect: (effect: () => void | (() => void)) => {
+ const cleanup = effect();
+ mocks.cleanup = typeof cleanup === 'function' ? cleanup : null;
+ },
+ }));
+ vi.mock('react-native', () => ({
+ Platform: { OS: 'android' },
+ Alert: { alert: vi.fn() },
+ Linking: { openURL: vi.fn() },
+ AppState: {
+ addEventListener: vi.fn((_event: string, listener: (state: string) => void) => {
+ mocks.appStateListener = listener;
+ return { remove: vi.fn() };
+ }),
+ },
+ }));
+ vi.mock('expo-updates', () => ({
+ isEnabled: true,
+ runtimeVersion: 'runtime-1',
+ checkForUpdateAsync: mocks.checkOta,
+ fetchUpdateAsync: mocks.fetchOta,
+ }));
+ vi.mock('@/config/env', () => ({
+ APP_BINARY_VERSION: '1.0.0',
+ IS_OTA_SELFHOST: true,
+ IS_TESTFLIGHT_BUILD: false,
+ REVIEW_MODE: false,
+ }));
+ vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
+ vi.mock('./androidInstallSource', () => ({ isGooglePlayInstallation: mocks.playInstall }));
+ vi.mock('./androidInstaller', () => ({ androidInstaller: { start: vi.fn() } }));
+ vi.mock('./fetchLatestRelease', () => ({ fetchLatestRelease: mocks.fetchLatest }));
+ vi.mock('./forcedUpdateStore', () => ({ enterForcedUpdate: vi.fn() }));
+ vi.mock('./canaryChannelStore', () => ({ resolveUpdateChannelForDevice: () => 'release' }));
+ vi.mock('./otaRequestCoordinator', () => ({
+ runSelfHostedOtaRequest: (_channel: string, operation: (client: {
+ checkForUpdateAsync: typeof mocks.checkOta;
+ fetchUpdateAsync: typeof mocks.fetchOta;
+ }) => Promise<unknown>) => operation({
+ checkForUpdateAsync: mocks.checkOta,
+ fetchUpdateAsync: mocks.fetchOta,
+ }),
+ }));
+
+ import { useBundleUpdatePrompt } from './useBundleUpdatePrompt';
+ import { useResumeUpdateCheck } from './useResumeUpdateCheck';
+ import { runManualUpdateCheck } from './manualUpdateCheck';
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.playInstall.mockReturnValue(true);
+ mocks.appStateListener = null;
+ mocks.cleanup = null;
+ });
+
+ afterEach(() => {
+ mocks.cleanup?.();
+ vi.restoreAllMocks();
+ });
+
+ describe('Google Play update entry points', () => {
+ it('startup hook skips the website release check', async () => {
+ const { checkNow } = useBundleUpdatePrompt({ auto: true, channel: 'release' });
+ await expect(checkNow()).resolves.toBe('skipped');
+ expect(mocks.fetchLatest).not.toHaveBeenCalled();
+ // The root layout still mounts its independent startup content OTA gate.
+ const layout = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');
+ expect(layout).toContain('const otaReady = useStartupOtaGate(channel);');
+ });
+
+ it('resume checks content OTA but never asks for the website APK', async () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValueOnce(0).mockReturnValue(300_001);
+ useResumeUpdateCheck('release');
+ expect(mocks.appStateListener).not.toBeNull();
+ mocks.appStateListener!('background');
+ mocks.appStateListener!('active');
+ await vi.waitFor(() => expect(mocks.checkOta).toHaveBeenCalledOnce());
+ expect(mocks.fetchLatest).not.toHaveBeenCalled();
+ now.mockRestore();
+ });
+
+ it('settings passes no website check and can still check content OTA', async () => {
+ const settings = readFileSync(resolve(process.cwd(), 'app/settings.tsx'), 'utf8');
+ expect(settings).toContain('isGooglePlayInstallation: playManagedUpdates,');
+ expect(settings).toContain('checkBundleUpdate: bundleCheckEnabled ? checkBundleUpdate : undefined,');
+ expect(settings).toContain('const updateCheckEnabled = bundleCheckEnabled || updatesEnabled;');
- expect(settings).toContain("? 'settings.version.googlePlayContentUpdateUnavailable'");
++ expect(settings).toContain("t('settings.version.googlePlayContentUpdateUnavailable')");
+ await expect(runManualUpdateCheck({
+ checkBundleUpdate: undefined,
+ otaEnabled: true,
+ checkOtaUpdate: mocks.checkOta,
+ fetchOtaUpdate: mocks.fetchOta,
+ reload: vi.fn(async () => undefined),
+ isEmergencyLaunch: () => false,
+ onPhase: vi.fn(),
+ })).resolves.toEqual({ kind: 'up-to-date' });
+ expect(mocks.checkOta).toHaveBeenCalledOnce();
+ expect(mocks.fetchLatest).not.toHaveBeenCalled();
+ });
+ });
diff --cc docs/design-rules/design-decision-log.md
index 78b8b95999,1c0a421fc1..e58e4a3c34
--- a/docs/design-rules/design-decision-log.md
+++ b/docs/design-rules/design-decision-log.md
@@@ -12,7 -12,7 +12,8 @@@
## 2026-09
+ - **09-28 任务标签改为紧跟标题常显**——用户要求任务标签不再作为「任务信息」里可选的显示项,而是跟在任务标题后面必然显示。桌面侧栏移除「任务信息 → 标签」复选项;文字版、列表版色球由行尾信息槽移到标题之后,置顶卡片版由底部信息行移到标题首行之后。聊天标题栏与手机端原本已在标题后常显,不变。同日用户指出悬停任务时色球「变大、描边消失」:根因是悬停把外圈改为半透明的 `sidebar-item-hover`,透出色球本色;改为悬停不换外圈色,选中与当前任务仍跟随不透明行底。被取代:09 月「标签」与时间并列、默认勾选并留在行尾信息槽的处理。现行行为见 `docs/product-rules/task-tags.md`;本条为方向裁决,不代表实机视觉验收。
+- **09-27 移动端主菜单账号层级与抽屉层次**——用户要求姓名放大、默认头像取代公司大 Logo、公司 Logo 缩为小图标、不展示 ID;左侧菜单滑出更流畅,右侧有圆角和适当阴影。账号头以用户姓名为主,邮箱与组织信息为辅;仅首页主菜单抽屉(含伙伴入口)登记柔和投影例外,取代该处零阴影要求,不扩展到页面卡片与任务列表侧栏。落点:`DESIGN.md §6`、`mobile-design-guide.md §1`、`HomeChromeDrawer.tsx` 与 `homeDrawerShadow` 色板 token。方向授权不代表实机视觉验收。
- **09-27 字重 / 字号 / 行高规则复核补丁**——整体复核后补齐遗漏并澄清三条口径:chip 底上的徽标与字母标记可用 600(按图形元素处理,不受「浅色字不配粗字重」限制);文字需与相邻图标、按钮或行内正文对齐时,行高跟随被对齐对象(对齐例外);只有单行输入框不设行高,多行编辑区可配标准行高。同时补齐:iOS 对话输入框占位字改用 `textPlaceholder`;队友主页顶栏标题与「所有任务」一致(20 · 600);远程任务建议空状态标题、浏览器菜单标题、伙伴邀请等待页标题改为 600;伙伴变体里的二级色类别标签改为 500;计划正文由 12 改为 13;11 处独立段落的非标准行高回到标准配对。本条为规则裁决,不代表实机视觉验收。