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。

fix(mobile): restore full-screen companion navigation on Android

zqchrisc3abdc9febd9
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 4b80dbf6a1..2eac4aa333 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -13,6 +13,7 @@ import { getActiveMobileSessionRealm } from '@/config/env';
import { FailedScheduleNotice } from '@/session/FailedScheduleNotice';
import { shouldShowFailedScheduleNotice, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';
import { CompanionHeader } from '@/session/CompanionHeader';
+import { CompanionNavigationDrawer } from '@/session/CompanionNavigationDrawer';
import { collectCompanionPluginInvocations } from '@/session/pluginInvocations';
import { CompanionWorkingStatus, useCompanionWorkingLabel } from '@/session/CompanionWorkingStatus';
import { useRemoteResourceSession } from '@/session/useRemoteResourceSession';
@@ -2242,6 +2243,12 @@ export default function SessionScreen() {
&& contentRecoveryKey !== null && contentSyncedKey === contentRecoveryKey
&& !outboxRecoverySyncHeld && !loading);
const companionChat = companionResource?.ref.kind === 'bot';
+ const companionNavigationScope = JSON.stringify([auth.accountGeneration, deviceId, sessionId, companionResource?.ref.id, shareSelectionActive]);
+ const [companionNavigation, setCompanionNavigation] = useState({ scope: companionNavigationScope, open: false });
+ // Reused routes must not carry an open drawer (or a queued action) into another companion.
+ if (companionNavigation.scope !== companionNavigationScope) {
+ setCompanionNavigation({ scope: companionNavigationScope, open: false });
+ }
const lastAckKeyRef = useRef<string | null>(null);
const sessionResourceCards = useSessionResourceCards(
deviceId, deviceName, sessionId, currentSession?.source, remoteSessionRunning,
@@ -8960,7 +8967,8 @@ export default function SessionScreen() {
<SystemNavigationBack label={t('shared.back')} onPress={goBackToHome} />
<CompanionHeader key={`${auth.accountGeneration}:${deviceId}:${companionResource.ref.id}`}
resource={companionResource} deviceId={deviceId} deviceName={deviceName} online={!remoteUnavailableReason}
- onSearch={() => setSearchOpen(true)} />
+ onSearch={() => setSearchOpen(true)}
+ onOpenNavigation={() => setCompanionNavigation({ scope: companionNavigationScope, open: true })} />
</> : <SessionHeaderBar
horizontalSystemHeader={horizontalSystemHeader}
currentSession={currentSession}
@@ -9808,6 +9816,12 @@ export default function SessionScreen() {
open={(paneLayout.persistent && !sessionListDrawerOverlayMounted) || sessionListDrawerOpen}
width={paneLayout.persistent && !sessionListDrawerOverlayMounted ? paneLayout.sidebarWidth : sessionListDrawerWidthRef.current}
/>
+ {companionChat && companionResource && !shareSelectionActive ? (
+ <CompanionNavigationDrawer key={companionNavigationScope}
+ open={companionNavigation.scope === companionNavigationScope && companionNavigation.open}
+ onClose={() => setCompanionNavigation({ scope: companionNavigationScope, open: false })}
+ onSearch={() => setSearchOpen(true)} />
+ ) : null}
</MessageHistoryOverlay>
</View>
);
diff --git a/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsx b/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsx
new file mode 100644
index 0000000000..44379d9c92
--- /dev/null
+++ b/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsx
@@ -0,0 +1,107 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { RemoteResource } from '@cindy/device-link';
+
+const h = vi.hoisted(() => ({
+ drawer: {} as any, accounts: {} as any, profile: {} as any,
+ dismiss: vi.fn(), push: vi.fn(), chooseMode: vi.fn(),
+ auth: { accountGeneration: 1, user: null, logout: vi.fn(), beginAddAccount: vi.fn() },
+}));
+vi.mock('react-native', () => ({
+ Keyboard: { dismiss: h.dismiss }, Alert: { alert: vi.fn() },
+ View: ({ children, testID }: any) => createElement('div', { 'data-testid': testID }, children),
+ Pressable: ({ children, onPress, testID }: any) => createElement('button', { onClick: onPress, 'data-testid': testID }, children),
+ StyleSheet: { create: (s: unknown) => s },
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: 'en' } }) }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));
+vi.mock('@/components/AppText', () => ({ Text: 'span' }));
+vi.mock('@/components/RemoteCompanionAvatar', () => ({ RemoteCompanionAvatar: () => null }));
+vi.mock('@/theme', async () => {
+ const tokens = await import('@/theme/tokens');
+ return { ...tokens, useTheme: () => ({ colors: tokens.lightColors }), useThemedStyles: (fn: any) => fn(tokens.lightColors) };
+});
+vi.mock('lucide-react-native', () => ({ ChevronDown: () => null, PanelLeft: () => null, Settings2: () => null }));
+vi.mock('@/session/HomeHeaderGlassButton', () => ({ HomeHeaderGlassButton: ({ onPress, testID, children }: any) =>
+ createElement('button', { onClick: onPress, 'data-testid': testID }, children) }));
+vi.mock('@/session/TeammatePicker', () => ({ TeammatePicker: () => null }));
+vi.mock('@/session/CompanionProfileSheet', () => ({ CompanionCreateSheet: () => null,
+ CompanionProfileSheet: (props: unknown) => { h.profile = props; return null; } }));
+vi.mock('@/session/CompanionAutomationSheet', () => ({ CompanionAutomationSheet: () => null }));
+vi.mock('@/session/useTeammateNavigation', () => ({ useTeammateNavigation: () => ({ chooseMode: h.chooseMode }) }));
+vi.mock('@/utils/useGuardedPush', () => ({ useGuardedPush: () => h.push }));
+vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: String }));
+vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: {
+ subscribe: () => () => {}, getSessions: () => [], isSessionRunning: () => false,
+} }));
+vi.mock('@/session/AccountSwitcherSheet', () => ({ AccountSwitcherSheet: (props: unknown) => { h.accounts = props; return null; } }));
+vi.mock('@/session/HomeChromeDrawer', () => ({ HomeChromeDrawer: (props: any) => {
+ h.drawer = props;
+ return createElement('div', { 'data-drawer': true, 'data-open': props.open });
+} }));
+import { CompanionHeader } from '@/session/CompanionHeader';
+import { CompanionNavigationDrawer } from '@/session/CompanionNavigationDrawer';
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root; let host: HTMLDivElement;
+beforeEach(() => {
+ vi.clearAllMocks(); h.auth.accountGeneration = 1;
+ h.drawer = {}; h.accounts = {}; h.profile = {};
+ host = document.createElement('div'); root = createRoot(host);
+});
+afterEach(() => act(() => root.unmount()));
+
+it('opens navigation through the page owner without mounting an overlay inside the clipped header', async () => {
+ const onOpenNavigation = vi.fn(), onSearch = vi.fn();
+ const resource = { ref: { kind: 'bot', collectionId: 'bots', id: 'bot' }, display: { title: 'Cindy' } } as RemoteResource;
+ await act(async () => root.render(<CompanionHeader resource={resource} deviceId="pc" deviceName="PC" online
+ onOpenNavigation={onOpenNavigation} onSearch={onSearch} />));
+ await act(async () => host.querySelector<HTMLButtonElement>('[data-testid="companion.navigation"]')!.click());
+ expect(h.dismiss).toHaveBeenCalledOnce();
+ expect(onOpenNavigation).toHaveBeenCalledOnce();
+ expect(host.querySelector('[data-drawer]')).toBeNull();
+ // Profile/search remain the existing sheet flow, independent of drawer ownership.
+ await act(async () => host.querySelector<HTMLButtonElement>('[data-testid="companion.settings"]')!.click());
+ expect(h.profile.visible).toBe(true);
+ await act(async () => h.profile.onOpenSearch());
+ expect(onSearch).not.toHaveBeenCalled();
+ await act(async () => h.profile.onClosed());
+ expect(onSearch).toHaveBeenCalledOnce();
+});
+
+it.each([
+ ['onOpenSettings', '/settings'], ['onOpenDevices', '/devices/manage'],
+])('preserves %s navigation after the full-screen drawer finishes closing', async (action, route) => {
+ const onClose = vi.fn();
+ await act(async () => root.render(<CompanionNavigationDrawer open onClose={onClose} onSearch={() => {}} />));
+ await act(async () => h.drawer[action]());
+ expect(onClose).toHaveBeenCalledOnce(); expect(h.push).not.toHaveBeenCalled();
+ await act(async () => h.drawer.onClosed());
+ expect(h.push).toHaveBeenCalledExactlyOnceWith(route);
+ await act(async () => h.drawer.onClosed());
+ expect(h.push).toHaveBeenCalledTimes(1);
+});
+
+it('preserves search, mode switching, account switching and logout actions', async () => {
+ const onSearch = vi.fn();
+ await act(async () => root.render(<CompanionNavigationDrawer open onClose={() => {}} onSearch={onSearch} />));
+ await act(async () => h.drawer.onOpenSearch()); expect(onSearch).not.toHaveBeenCalled();
+ await act(async () => h.drawer.onClosed()); expect(onSearch).toHaveBeenCalledOnce();
+ await act(async () => h.drawer.onModeChange('tasks')); expect(h.chooseMode).not.toHaveBeenCalled();
+ await act(async () => h.drawer.onClosed()); expect(h.chooseMode).toHaveBeenCalledWith('tasks');
+ await act(async () => { h.drawer.onOpenAccounts(); h.drawer.onClosed(); }); expect(h.accounts.visible).toBe(true);
+ h.auth.logout.mockResolvedValue(undefined);
+ await act(async () => h.drawer.onLogout()); expect(h.auth.logout).toHaveBeenCalledOnce();
+});
+
+it.each(['account', 'companion'])('drops a queued navigation action when the %s scope changes', async (change) => {
+ const render = (scope: string) => act(async () => root.render(<CompanionNavigationDrawer key={scope} open onClose={() => {}} onSearch={() => {}} />));
+ await render('old');
+ await act(async () => h.drawer.onOpenSettings());
+ const staleFinish = h.drawer.onClosed;
+ if (change === 'account') h.auth.accountGeneration++;
+ await render('new');
+ await act(async () => staleFinish());
+ expect(h.push).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/session/CompanionHeader.tsx b/apps/mobile/src/session/CompanionHeader.tsx
index 7955bb9be5..3a402647fe 100644
--- a/apps/mobile/src/session/CompanionHeader.tsx
+++ b/apps/mobile/src/session/CompanionHeader.tsx
@@ -8,7 +8,6 @@ import { Text } from '@/components/AppText';
import { RemoteCompanionAvatar } from '@/components/RemoteCompanionAvatar';
import { fontWeight, iconSize, iconStroke, spacing, typeScale, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { HomeHeaderGlassButton } from './HomeHeaderGlassButton';
-import { CompanionNavigationDrawer } from './CompanionNavigationDrawer';
import { TeammatePicker } from './TeammatePicker';
import { CompanionCreateSheet, CompanionProfileSheet } from './CompanionProfileSheet';
import { CompanionAutomationSheet } from './CompanionAutomationSheet';
@@ -17,17 +16,16 @@ import { useTeammateNavigation } from './useTeammateNavigation';
const AVATAR_SIZE = 32;
export function CompanionHeader(props: {
- resource: RemoteResource; deviceId: string; deviceName: string; online: boolean; onSearch(): void;
+ resource: RemoteResource; deviceId: string; deviceName: string; online: boolean; onSearch(): void; onOpenNavigation(): void;
}) {
const { accountGeneration } = useAuth();
return <CompanionHeaderContent key={accountGeneration} {...props} />;
}
-function CompanionHeaderContent({ resource, deviceId, deviceName, online, onSearch }: Parameters<typeof CompanionHeader>[0]) {
+function CompanionHeaderContent({ resource, deviceId, deviceName, online, onSearch, onOpenNavigation }: Parameters<typeof CompanionHeader>[0]) {
const { t, i18n } = useTranslation();
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
const navigation = useTeammateNavigation();
- const [drawer, setDrawer] = useState(false);
const [picker, setPicker] = useState(false);
const [profile, setProfile] = useState(false);
const [automation, setAutomation] = useState(false);
@@ -38,7 +36,7 @@ function CompanionHeaderContent({ resource, deviceId, deviceName, online, onSear
const afterProfile = (action: () => void) => { pending.current = action; setProfile(false); };
return <>
<View style={styles.header} testID="companion.header">
- <HomeHeaderGlassButton testID="companion.navigation" accessibilityLabel={t('devices.companions.openNavigation')} onPress={() => { Keyboard.dismiss(); setDrawer(true); }}>
+ <HomeHeaderGlassButton testID="companion.navigation" accessibilityLabel={t('devices.companions.openNavigation')} onPress={() => { Keyboard.dismiss(); onOpenNavigation(); }}>
<PanelLeft size={iconSize.lg} strokeWidth={iconStroke.regular} color={colors.textPrimary} />
</HomeHeaderGlassButton>
<Pressable style={styles.identity} accessibilityRole="button" accessibilityLabel={name} accessibilityHint={t('devices.companions.title')} onPress={() => setPicker(true)} testID="companion.picker">
@@ -50,7 +48,6 @@ function CompanionHeaderContent({ resource, deviceId, deviceName, online, onSear
<Settings2 size={iconSize.lg} strokeWidth={iconStroke.regular} color={colors.textPrimary} />
</HomeHeaderGlassButton>
</View>
- <CompanionNavigationDrawer open={drawer} onClose={() => setDrawer(false)} onSearch={onSearch} />
<TeammatePicker visible={picker} onClose={() => setPicker(false)} onSelect={item => void navigation.openTeammate(item)}
onCreate={() => { created.current = null; setCreating(true); }}
current={{ deviceId, collectionId: resource.ref.collectionId, resourceKind: 'bot', resourceId: resource.ref.id }} />
diff --git a/docs/assets/mobile-companion-focus/android-drawer-dark.png b/docs/assets/mobile-companion-focus/android-drawer-dark.png
new file mode 100644
index 0000000000..591c11037d
Binary files /dev/null and b/docs/assets/mobile-companion-focus/android-drawer-dark.png differ
diff --git a/docs/assets/mobile-companion-focus/android-drawer-light.png b/docs/assets/mobile-companion-focus/android-drawer-light.png
new file mode 100644
index 0000000000..4617000320
Binary files /dev/null and b/docs/assets/mobile-companion-focus/android-drawer-light.png differ