diff --git a/.agents/skills/verify-deepseekbot/features/README.md b/.agents/skills/verify-deepseekbot/features/README.md index 520dab909b..bfc76e1cfa 100644 --- a/.agents/skills/verify-deepseekbot/features/README.md +++ b/.agents/skills/verify-deepseekbot/features/README.md @@ -27,6 +27,7 @@ One file per user-facing feature. Each file has four sections: `Sub-features`, ` | PersonaBot creation and restart persistence | for Bot-created Bots | `scripts/e2e-personabot-create.mjs` (CI) | [personabot-create.md](personabot-create.md) | | Stop a working Bot (Web Client) | yes | `scripts/e2e-web-stop.mjs` | [bot-stop.md](bot-stop.md) | | Phone pairing and paired devices | no | `scripts/e2e-mobile-pairing-web.mjs`, `scripts/e2e-device-pairing.mjs`, `scripts/e2e-mobile-sim.mjs`, `scripts/e2e-mobile-pair-android.mjs` | [phone-pairing.md](phone-pairing.md) | +| Phone Chats drawer views and Android Host accent | no | none (shared-device native path) | [phone-drawer-views.md](phone-drawer-views.md) | | Native mobile chat backgrounds | no (except live-reply regression) | none (shared-device native path) | [phone-chat-backgrounds.md](phone-chat-backgrounds.md) | | Android sheets, shell and chat presentation | no | `scripts/e2e-mobile-android-interactions.mjs` | [phone-android-interactions.md](phone-android-interactions.md) | | Phone notifications and paired computers (iOS Simulator) | for the approval step | `scripts/e2e-mobile-sim.mjs` (Mac) | [phone-notifications.md](phone-notifications.md) | diff --git a/.agents/skills/verify-deepseekbot/features/phone-drawer-views.md b/.agents/skills/verify-deepseekbot/features/phone-drawer-views.md new file mode 100644 index 0000000000..9bc8a73585 --- /dev/null +++ b/.agents/skills/verify-deepseekbot/features/phone-drawer-views.md @@ -0,0 +1,35 @@ +# Phone Chats drawer views + +## Sub-features + +- `all`: the first drawer row selects All without switching the current paired Host. Chats renders one list containing the current Host and available cloud workspaces. +- `host`: choosing a Host closes the drawer and queues its switch through the existing Host Session. Each switch waits for the prior save/adopt to settle before checking the current Host. Only the latest successful choice selects its conversation filter, so the final Host owner, persisted Host and selected Host view agree. A failed switch does not block the next choice. All updates the filter immediately without cancelling an already requested Host switch. +- `header`: All shows a chat icon and its title; a Host shows its device-local name, icon and colour. The title button announces the full selected view name (including cloud disambiguation) in the current locale. Title icons and the All row icon follow their label roles and live system text size. Removing a selected Host falls back to All. +- `accent`: Android's root accent follows the current Host colour in each scheme only while that Host's filter is selected. All, cloud, a different Host filter and a Host without a colour keep the default theme. iOS keeps its existing accent. +- `gestures`: Chats has no source tabs or sideways pager. The existing iOS left-edge drawer gesture remains available. +- `pairing`: cancelling first-run pairing leaves the empty home; drawer account rows open `/pair/account` with the selected account id. Cloud entries follow the existing feature flag. + +## How to get to it (user POV) + +Open Chats in the paired app, tap the title to open the left drawer, then choose All or a Host. Long-press a Host or open its menu to change its device-local icon and colour. On iOS, swipe in from the left edge to open the drawer. + +## Driving it with verify-app + +Use the designated [shared device QA runner](../../../../docs/agents/device-qa.md), with the Windows [Android lane](../../../../docs/agents/android-device-qa.md) and the Mac/iOS lane. Record the exact PR head, batch head, native build provenance and assigned Host. This journey needs two paired QA Hosts for switching, but no model, push, camera or real tailnet. Any optional model run uses `deepseek-v4-pro`. + +1. Capture the base and candidate with the same data, locale and viewport. On each platform, run default/intermediate/maximum system text sizes in light and dark. +2. Tap `chats-view-button`, then `drawer-all`. Check All is selected, one list is visible, and its rows belong to the current Host or enabled cloud workspaces. Check no environment tabs or pager remain. With TalkBack/VoiceOver, focus the title and confirm it announces the complete selected All/Host/cloud name. On Android, press All both while selected and unselected; its foreground ripple must be visible and clipped to the row. +3. Tap `drawer-host-` for another paired Host. Check its selected row, title, icon and conversations agree. Open a conversation and read its owning Host's canonical record. Switch back to All and verify it retains that current Host. Choose All while a Host switch is pending; the completed switch must not overwrite All. On device, rapidly choose B then A from current A; after settling, current Host, persisted Host and filter must all end on A. With a third disposable Host C, rapidly choose B then C and verify all three facts end on C. Restart and confirm the persisted owner agrees. The automated Host Session test controls SecureStore completion order for deterministic delayed-write coverage; rapid native taps alone do not prove that timing case. +4. Search in the selected list, clear search, scroll a long list and return to the drawer. Confirm labels wrap and all actions remain reachable at maximum text size. Confirm the new title glyphs and drawer All icon grow with their labels without clipping or double scaling. +5. Customize the current Host to orange, then teal, then default. With the current Host selected, Android's app accent changes in both schemes. Switching to All or a cloud view restores the default accent; switching back restores the Host tint. iOS's accent stays unchanged. The header icon reflects the Host colour on both platforms. +6. On iOS, swipe within the existing `EDGE_WIDTH` at the left edge to open the drawer, then close it by swipe and backdrop. A horizontal swipe away from the edge must not page the list. Android Back dismisses the drawer. +7. Remove only a disposable selected QA Host. Check the view returns to All. In an isolated unpaired app state, cancel pairing and check the empty home remains. An unpaired account row opens the selected account pairing page directly. + +Keep matched before/after screenshots, accessibility snapshots and console/runtime errors for each changed state. Web previews and source tests do not qualify native gestures, Android colour rendering or large-text usability. + +## Gotchas + +- All covers the current Host plus cloud workspaces, not every paired Host. The drawer's existing bounded status glances are not concurrent conversation feeds. +- Host looks remain device-local. There is no cross-device pairing or appearance sync. +- Preserve the cloud feature flag and the existing cloud-enabled empty-home route separately from first-run pairing. +- Never reset a Human's pairings or take another runner's device, Metro or Host. Unavailable native lanes remain explicitly untested. diff --git a/apps/mobile/DESIGN.md b/apps/mobile/DESIGN.md index d309637d47..9b7d161b69 100644 --- a/apps/mobile/DESIGN.md +++ b/apps/mobile/DESIGN.md @@ -53,11 +53,11 @@ References: [Apple toolbars](https://developer.apple.com/design/human-interface- ## Chats source navigation (#2194) -Chats uses the same canvas and left-aligned title treatment as Activity. The title/chevron opens the workspace drawer; Settings remains on the right. Directly below, a reusable native pager presents a horizontally scrolling **All → Computer → Organization** strip. Selecting a tab or swiping the list changes only the device-local browsing scope. Stable directory order, including empty member Organizations and channel-only guest Organizations, is independent of message arrival. Labels use local Computer names; keys retain full source/account identity. Each tab stays on one line with a bounded width and tail-ellipsized label; the source icon leads the label and never shrinks. The Computer tab's icon is that Computer's chosen icon; when the Computer has a chosen colour, the icon (while selected) and the tab underline use it, and other tabs keep the theme accent underline. Service URLs do not add a second line. Full source/account identity remains in accessibility labels and the source drawer. +Chats uses the same canvas and left-aligned title treatment as Activity. The title/chevron opens the workspace drawer; Settings remains on the right. One conversation list follows the existing device-local conversation filter, with no environment tabs or horizontal pager. The drawer's **All** row keeps the current paired Host and includes its conversations plus available cloud workspaces. Host choices queue their existing Host Session switches: each waits for the prior save/adopt to settle before checking the current Host, then selects that Host's filter only if no newer All or Host selection superseded it. The final Host owner, persisted Host and selected Host view therefore agree, including a return to the original Host while another save is pending. A failed switch does not block the next choice; All changes the filter immediately without cancelling an already requested Host switch. All never opens simultaneous conversation feeds for every paired Host. The header shows All with the Chats icon in the accent colour, or the selected Host's local name and Host glyph in its contrast-adjusted colour. Android's root accent follows the current Host's local colour for the active scheme only when that Host's filter is selected. All, cloud views, a different Host filter and a Host without a colour keep the default accent; iOS retains its system accent and existing left-edge drawer gesture. The title button announces the full selected view name, including existing cloud disambiguation. Its icons scale with the title text role; the drawer All icon scales with its body label. The All row clips Android foreground ripple over both selected and unselected backgrounds. Cloud entries still obey the cloud feature flag. This first slice retains one active Computer plus authorized Organizations. It does not implement simultaneous multiple-Computer connections. Search and creation remain in their existing list-header placement until #2195/#2196. Activity inherits scope and keeps action/replies/unread paging; unsupported Cloud scope has an explicit notice and no borrowed Computer badge. All discloses that Cloud activity is not yet included. Source-owned history, credentials, drafts, permissions and send paths stay unchanged. -The older Host-band description below records prior presentation behavior. The Chats Header and environment selector above supersede that entry layout; Computer customization (name, icon, colour) remains available in the drawer. +The older Host-band and environment-strip descriptions below record prior presentation behavior. The Chats Header and drawer selection above supersede those entry layouts; Host customization (name, icon, colour) remains available in the drawer. ## Structure @@ -154,7 +154,7 @@ The shell is set by [ADR-0211](../../docs/adr/0211-the-mobile-app-has-two-tabs-w - On the Activity and Chats root lists, deliberate downward content scrolling hides the global bottom navigation; upward travel or reaching the top restores it. Clamp elastic overscroll so bounce does not toggle chrome. Activity also collapses its title/filter/search row, leaving the three tabs pinned below the safe area; no gradient covers rows beneath the tabs. Searching and filtering keep controls visible. Page changes restore chrome without discarding each page's scroll position. Scroll intent and transforms run on the UI thread; only native visibility/accessibility boundaries cross to React. List geometry stays fixed during the animation. - A 48pt avatar: the Bot's avatar as a rounded square (`radius.md`), or a rounded square with `#` for a Channel. A paused Bot's avatar is dimmed. -- First line: title, then its source mark, IM channel badges and time. The source mark is the Computer's chosen icon (in its chosen colour, `subtle` without one) for a Computer chat and the cloud glyph for a Cloud chat, at `meta` size, so chats from different places stay apart in **All**. It shows on every tab so rows keep one layout while the pager swipes. The time follows IM lists: the clock time today, then Yesterday, the weekday within the last week, month/day this year, and the full date before that. +- First line: title, then its source mark, IM channel badges and time. The source mark is the Computer's chosen icon (in its chosen colour, `subtle` without one) for a Computer chat and the cloud glyph for a Cloud chat, at `meta` size, so chats from different places stay apart in **All**. It shows in every filtered view so rows keep one layout when the selection changes. The time follows IM lists: the clock time today, then Yesterday, the weekday within the last week, month/day this year, and the full date before that. - Second line: the latest message as a one-line preview, in `fg` while the conversation has unread messages, then one status glyph at the trailing edge, the same set as the desktop sidebar: a spinning arc while the Bot thinks or works (still under Reduce Motion), a `warning` ring when it waits for the Human, a `danger` mark when blocked, a filled check when it finished and the Human has not read it, a `muted` check when it finished within the last day, and a `muted` moon when paused. Idle rows and Channels show none. - One count chip on the avatar's top-right corner, cut out of the row with a `canvas` edge: **Needs you** (how many requests wait for the Human) takes priority over **Unread** (how many messages arrived since the Human last read the conversation, from the Host's `channelUnreadCounts`). A muted conversation's unread count uses the neutral tone. - A collapsed Channel section shows one count chip for everything inside it: Needs you first, otherwise the unread sum, leaving muted conversations out. An expanded section that holds Bots waiting for the Human says how many, in `warning`. diff --git a/apps/mobile/app/(tabs)/(home)/index.tsx b/apps/mobile/app/(tabs)/(home)/index.tsx index 3444591e2c..4875c37598 100644 --- a/apps/mobile/app/(tabs)/(home)/index.tsx +++ b/apps/mobile/app/(tabs)/(home)/index.tsx @@ -30,7 +30,6 @@ import { CloudConversationRow } from '../../../src/ui/chat/cloud-conversation-ro import { useConversationFilter } from '../../../src/host/native-conversation-filter'; import { ConnectionBanner } from '../../../src/ui/connection-banner'; import { space } from '../../../src/ui/design/tokens'; -import { EnvironmentPager } from '../../../src/ui/shell/environment-pager'; import { conversationEnvironments, computerEnvironmentKey, @@ -46,7 +45,7 @@ import { HostDrawerEdge } from '../../../src/ui/shell/host-drawer'; import { ConversationPeek, conversationPeek } from '../../../src/ui/shell/conversation-peek'; import { useFloatingTabInset } from '../../../src/ui/shell/floating-tab-inset'; import { conversationHref, openConversation } from '../../../src/ui/shell/open-conversation'; -import { useChromeScroll, useScrollChrome } from '../../../src/ui/shell/scroll-chrome'; +import { useChromeScroll } from '../../../src/ui/shell/scroll-chrome'; import { t } from '../../../src/ui/strings'; import { LoadingIndicator } from '../../../src/ui/primitives/loading-indicator'; import { PullToRefresh } from '../../../src/ui/primitives/pull-to-refresh'; @@ -113,7 +112,6 @@ const HomeContent = memo(function HomeContent({ const [searching, setSearching] = useState(false); const [searchFocused, setSearchFocused] = useState(false); const onScroll = useChromeScroll(true, searchFocused || query !== ''); - const chrome = useScrollChrome(); const bottom = useFloatingTabInset(); const look = useHostLook(saved?.hostId); const cloud = useCloudSnapshot(); @@ -157,7 +155,8 @@ const HomeContent = memo(function HomeContent({ ), [saved, look, cloud.rows, directory.workspaces], ); - const effectiveFilter = filters.some((f) => f.key === filter) ? filter : 'all'; + const environment = filters.find((item) => item.key === filter) ?? filters[0]!; + const effectiveFilter = environment.key; const quiet = useQuietChannels(saved?.hostId); useFocusEffect( useCallback(() => { @@ -319,9 +318,10 @@ const HomeContent = memo(function HomeContent({ }; return ( <> - + } > - { - chrome.hidden.value = false; - setFilter(key); - }} - renderPage={(environment, active) => ( - void refresh()} - > - {(pull) => ( - - {...pull} - renderScrollComponent={renderKeyboardFormScroll} - onScroll={active ? onScroll : undefined} - scrollEventThrottle={1} - contentContainerStyle={{ paddingBottom: bottom + space.x6 }} - keyboardShouldPersistTaps="handled" - keyboardDismissMode="on-drag" - data={rows.filter( - (row) => environment.key === 'all' || row.environment === environment.key, - )} - keyExtractor={(r) => r.key} - ListHeaderComponent={ - <> - {saved && - (environment.key === 'all' || - environment.key === computerEnvironmentKey(saved.hostId)) && ( - client?.retryNow()} - onPairAgain={() => router.push('/pair')} - /> - )} - {(directory.errors.length > 0 || cloud.error || error) && ( - - {t.cloudListUnavailable} - {error ? ` (${error})` : ''} - - )} - - } - ListEmptyComponent={ - directory.busy || - (saved && - (environment.key === 'all' || - environment.key === computerEnvironmentKey(saved.hostId)) && - !snapshot.roster && - snapshot.connection.status === 'connecting') ? ( - - - - ) : ( - - {query ? t.searchNoMatch(query.trim()) : t.cloudChannels.empty} - - ) - } - renderItem={({ item }) => - item.type === 'computer' ? ( - conversationPeek ? ( - - - - ) : ( - - openConversation(router, item.conversation, saved?.hostId) - } - actions={conversationActions(item.conversation, { - pinned: item.pinned, - hostMuted: - snapshot.roster?.arrangement?.muted?.includes( - conversationChannelId(item.conversation) ?? '', - ) === true, - })} - onAction={(key) => { - if (client === undefined) return; - runConversationAction(client, inbox, item.conversation, key).catch( - () => - showAppDialog(t.rowActions.failed, undefined, [{ text: t.done }]), - ); - }} - /> - ) - ) : ( - void openCloud(item.conversation)} - /> - ) - } - /> + void refresh()}> + {(pull) => ( + + {...pull} + renderScrollComponent={renderKeyboardFormScroll} + onScroll={onScroll} + scrollEventThrottle={1} + contentContainerStyle={{ paddingBottom: bottom + space.x6 }} + keyboardShouldPersistTaps="handled" + keyboardDismissMode="on-drag" + data={rows.filter( + (row) => environment.key === 'all' || row.environment === environment.key, )} - + keyExtractor={(r) => r.key} + ListHeaderComponent={ + <> + {saved && + (environment.key === 'all' || + environment.key === computerEnvironmentKey(saved.hostId)) && ( + client?.retryNow()} + onPairAgain={() => router.push('/pair')} + /> + )} + {(directory.errors.length > 0 || cloud.error || error) && ( + + {t.cloudListUnavailable} + {error ? ` (${error})` : ''} + + )} + + } + ListEmptyComponent={ + directory.busy || + (saved && + (environment.key === 'all' || + environment.key === computerEnvironmentKey(saved.hostId)) && + !snapshot.roster && + snapshot.connection.status === 'connecting') ? ( + + + + ) : ( + + {query ? t.searchNoMatch(query.trim()) : t.cloudChannels.empty} + + ) + } + renderItem={({ item }) => + item.type === 'computer' ? ( + conversationPeek ? ( + + + + ) : ( + openConversation(router, item.conversation, saved?.hostId)} + actions={conversationActions(item.conversation, { + pinned: item.pinned, + hostMuted: + snapshot.roster?.arrangement?.muted?.includes( + conversationChannelId(item.conversation) ?? '', + ) === true, + })} + onAction={(key) => { + if (client === undefined) return; + runConversationAction(client, inbox, item.conversation, key).catch(() => + showAppDialog(t.rowActions.failed, undefined, [{ text: t.done }]), + ); + }} + /> + ) + ) : ( + void openCloud(item.conversation)} + /> + ) + } + /> )} - /> + diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index 7b853b3108..297ff7f611 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -10,6 +10,7 @@ import { StatisticsNotice } from '../src/ui/shell/statistics-notice'; import { KeyboardRoot } from '../src/ui/primitives/keyboard-frame'; import { AppDialogHost } from '../src/ui/primitives/app-dialog-host'; import { sheetScreenOptions } from '../src/ui/primitives/sheet-screen'; +import { HostAccentProvider } from '../src/ui/shell/host-accent-provider'; import { useDesignTheme } from '../src/ui/design/theme'; import { t } from '../src/ui/strings'; import { useTheme } from '../src/ui/theme'; @@ -17,6 +18,14 @@ import { useTheme } from '../src/ui/theme'; export const unstable_settings = { initialRouteName: '(tabs)' }; export default function RootLayout() { + return ( + + + + ); +} + +function RootNavigator() { const theme = useTheme(); const design = useDesignTheme(); const routing = usePushRouting(); diff --git a/apps/mobile/src/ui/shell/environment-pager.tsx b/apps/mobile/src/ui/shell/environment-pager.tsx deleted file mode 100644 index d1a22e3ece..0000000000 --- a/apps/mobile/src/ui/shell/environment-pager.tsx +++ /dev/null @@ -1,117 +0,0 @@ -import { useMemo, type ReactNode } from 'react'; -import { useWindowDimensions, View } from 'react-native'; -import { TabBar, TabView } from 'react-native-tab-view'; -import { useReducedMotion } from 'react-native-reanimated'; -import type { ConversationEnvironment } from '../../host/conversation-environments'; -import { useDesignTheme } from '../design/theme'; -import { edge, environmentTab, space } from '../design/tokens'; -import { Text } from '../primitives/text'; -import { hostColorInk } from '../design/host-look'; -import { HostGlyph } from './host-tile'; -import { CloudIcon, ComputerIcon } from './icons'; - -export function EnvironmentPager({ - routes, - selected, - onSelect, - renderPage, -}: { - routes: ConversationEnvironment[]; - selected: string; - onSelect(key: string): void; - renderPage(route: ConversationEnvironment, active: boolean): ReactNode; -}) { - const theme = useDesignTheme(); - const { width } = useWindowDimensions(); - const reducedMotion = useReducedMotion(); - const maxTabWidth = width * environmentTab.widthRatio; - const index = Math.max( - 0, - routes.findIndex((route) => route.key === selected), - ); - const options = useMemo( - () => - Object.fromEntries( - routes.map((route) => [ - route.key, - { - accessibilityLabel: route.accessibilityLabel ?? route.title, - label: ({ focused }: { focused: boolean }) => { - const tint = !focused - ? theme.color.muted - : route.hostColor === undefined - ? theme.color.fg - : hostColorInk(theme.scheme, theme.color, route.hostColor); - const size = theme.type.meta.line * theme.fontScale; - const leading = - route.hostIcon !== undefined ? ( - - ) : route.kind === 'cloud' ? ( - - ) : route.kind === 'computer' ? ( - - ) : null; - return ( - - {leading === null ? null : {leading}} - - {route.title} - - - ); - }, - }, - ]), - ), - [routes, theme, maxTabWidth], - ); - return ( - { - const route = routes[next]; - if (route) onSelect(route.key); - }} - animationEnabled={!reducedMotion} - lazy - renderTabBar={(props) => ( - - )} - renderScene={({ route }) => renderPage(route, route.key === routes[index]?.key)} - /> - ); -} diff --git a/apps/mobile/src/ui/shell/home-header.tsx b/apps/mobile/src/ui/shell/home-header.tsx index a369e413c8..a84d0bcbea 100644 --- a/apps/mobile/src/ui/shell/home-header.tsx +++ b/apps/mobile/src/ui/shell/home-header.tsx @@ -3,19 +3,24 @@ import { StatusBar } from 'expo-status-bar'; import type { ReactNode } from 'react'; import { Pressable, View, type ViewInstance } from 'react-native'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import type { ConversationEnvironment } from '../../host/conversation-environments'; +import { hostColorInk } from '../design/host-look'; import { useDesignTheme } from '../design/theme'; import { space } from '../design/tokens'; import { Text } from '../primitives/text'; import { useMounted } from '../mounted'; import { t } from '../strings'; -import { ChevronDownIcon } from './icons'; +import { ChatsIcon, ChevronDownIcon, CloudIcon } from './icons'; +import { HostGlyph } from './host-tile'; import { focusOn, hostDrawer, openHostDrawer, useHostDrawerOpen } from './host-drawer'; export function HomeHeader({ + environment, actions, search, children, }: { + environment: ConversationEnvironment; actions?: ReactNode; search?: ReactNode; children: ReactNode; @@ -45,9 +50,10 @@ export function HomeHeader({ <> ({ flex: 1, @@ -59,8 +65,25 @@ export function HomeHeader({ opacity: pressed ? 0.7 : 1, })} > + {environment.kind === 'computer' && environment.hostIcon ? ( + + ) : environment.kind === 'cloud' ? ( + + ) : ( + + )} - {t.chats} + {environment.title} diff --git a/apps/mobile/src/ui/shell/host-accent-provider.tsx b/apps/mobile/src/ui/shell/host-accent-provider.tsx new file mode 100644 index 0000000000..6abad6cec1 --- /dev/null +++ b/apps/mobile/src/ui/shell/host-accent-provider.tsx @@ -0,0 +1,24 @@ +import type { ReactNode } from 'react'; +import { Platform } from 'react-native'; + +import { computerEnvironmentKey } from '../../host/conversation-environments'; +import { useConversationFilter } from '../../host/native-conversation-filter'; +import { useHostSession } from '../../host/host-session'; +import { useHostLook } from '../../host/native-host-look'; +import { HOST_COLORS } from '../design/host-look'; +import { AccentProvider, useDesignTheme } from '../design/theme'; + +export function HostAccentProvider({ children }: { children: ReactNode }) { + const { saved } = useHostSession(); + const [filter] = useConversationFilter(); + const look = useHostLook(saved?.hostId); + const { scheme } = useDesignTheme(); + const accent = + Platform.OS === 'android' && + saved != null && + filter === computerEnvironmentKey(saved.hostId) && + look.color !== undefined + ? HOST_COLORS[look.color][scheme] + : undefined; + return {children}; +} diff --git a/apps/mobile/src/ui/shell/host-drawer-model.ts b/apps/mobile/src/ui/shell/host-drawer-model.ts index 75f9102d7c..f5778588ad 100644 --- a/apps/mobile/src/ui/shell/host-drawer-model.ts +++ b/apps/mobile/src/ui/shell/host-drawer-model.ts @@ -82,6 +82,7 @@ export interface HostDrawerState { export interface HostDrawerPort { switchTo(hostId: string): Promise; + showView(hostId: string | undefined): void; pair(): void; notifications(): void; } @@ -94,6 +95,7 @@ export interface HostDrawer { close(): void; hidden(): void; select(hostId: string): Promise; + selectAll(): void; pairNew(): void; openNotifications(): void; setReturnFocus(focus: (() => void) | undefined): void; @@ -103,6 +105,8 @@ export function createHostDrawer(port: HostDrawerPort): HostDrawer { const listeners = new Set<() => void>(); let state: HostDrawerState = { open: false, shown: false }; let returnFocus: (() => void) | undefined; + let selection = 0; + let switching: Promise | undefined; const publish = (next: HostDrawerState): void => { if (next.open === state.open && next.shown === state.shown) return; @@ -127,8 +131,24 @@ export function createHostDrawer(port: HostDrawerPort): HostDrawer { if (!state.open) publish({ open: false, shown: false }); }, async select(hostId) { + const selected = ++selection; close(); - return port.switchTo(hostId); + const switchHost = () => port.switchTo(hostId); + const pending = + switching === undefined ? switchHost() : switching.then(switchHost, switchHost); + switching = pending; + try { + const switched = await pending; + if (switched && selected === selection) port.showView(hostId); + return switched; + } finally { + if (switching === pending) switching = undefined; + } + }, + selectAll() { + selection++; + close(); + port.showView(undefined); }, pairNew() { close(); diff --git a/apps/mobile/src/ui/shell/host-drawer.tsx b/apps/mobile/src/ui/shell/host-drawer.tsx index 994a740de1..62c70f82fd 100644 --- a/apps/mobile/src/ui/shell/host-drawer.tsx +++ b/apps/mobile/src/ui/shell/host-drawer.tsx @@ -32,6 +32,8 @@ import { type CloudWorkspace, type WorkspaceDirectoryEntry, } from '../../cloud/workspace-directory'; +import { computerEnvironmentKey } from '../../host/conversation-environments'; +import { conversationFilter, useConversationFilter } from '../../host/native-conversation-filter'; import { createHostClient } from '../../host/client'; import type { ConnectHost } from '../../host/connect-account'; import { connectAccount } from '../../host/native-connect-account'; @@ -63,14 +65,14 @@ import { unpairedAccountHosts, type HostDrawerRow, } from './host-drawer-model'; -import { ActivityIcon, CloudIcon, ComputerIcon, PlusIcon } from './icons'; +import { ActivityIcon, ChatsIcon, CloudIcon, ComputerIcon, PlusIcon } from './icons'; import { noticeHostKept } from '../unpair-notice'; export const hostDrawer = createHostDrawer({ - switchTo: async (hostId) => { - const switched = await hostSession.switchTo(hostId); - if (switched) router.replace('/'); - return switched; + switchTo: (hostId) => hostSession.switchTo(hostId), + showView: (hostId) => { + conversationFilter.set(hostId === undefined ? 'all' : computerEnvironmentKey(hostId)); + router.replace('/'); }, pair: () => router.push('/pair'), notifications: () => router.push('/notifications'), @@ -278,7 +280,15 @@ function DrawerTile({ look, name, current }: { look: HostLook; name: string; cur ); } -function HostRow({ row, address }: { row: HostDrawerRow; address: string }) { +function HostRow({ + row, + address, + selected, +}: { + row: HostDrawerRow; + address: string; + selected: boolean; +}) { const theme = useDesignTheme(); const glass = useLiquidGlass(); const android = !glass && Platform.OS === 'android'; @@ -298,23 +308,24 @@ function HostRow({ row, address }: { row: HostDrawerRow; address: string }) { closeThen(() => void hostDrawer.select(row.hostId))} onLongPress={() => openHostMenu(row, name)} accessibilityRole="button" accessibilityLabel={[ name, - row.current ? t.showing : undefined, + selected ? t.showing : undefined, status, pending > 0 ? t.hostPending(pending) : undefined, unread > 0 ? t.hostUnread(unread) : undefined, ] .filter((part) => part !== undefined) .join(', ')} - accessibilityState={{ selected: row.current }} + accessibilityState={{ selected }} style={({ pressed }) => ({ flex: 1, minHeight: theme.touch + space.x3, @@ -337,7 +348,7 @@ function HostRow({ row, address }: { row: HostDrawerRow; address: string }) { : theme.layer.sheet.fill, })} > - + {name} @@ -509,6 +520,7 @@ export function WorkspaceButton() { } type WorkspaceDrawerItem = + | { kind: 'all'; key: string } | { kind: 'host'; key: string; row: HostDrawerRow } | { kind: 'account-title'; key: string } | { kind: 'account'; key: string; host: ConnectHost } @@ -580,6 +592,7 @@ export function HostDrawer() { const reduced = useReducedMotion(); const state = useSyncExternalStore(hostDrawer.subscribe, hostDrawer.getSnapshot); const { saved, hosts, client, inbox } = useHostSession(); + const [filter] = useConversationFilter(); const connection = useHostSnapshot(client).connection; const list = useInbox(inbox); const glanceMap = useSyncExternalStore(glances.subscribe, glances.getSnapshot); @@ -670,6 +683,7 @@ export function HostDrawer() { const drawerRows: WorkspaceDrawerItem[] = tab === 'computers' ? [ + { kind: 'all', key: 'all' }, ...rows.map((row): WorkspaceDrawerItem => ({ kind: 'host', key: 'host:' + row.hostId, @@ -802,10 +816,40 @@ export function HostDrawer() { keyExtractor={(row) => row.key} contentContainerStyle={{ paddingBottom: space.x4 }} renderItem={({ item }) => { + if (item.kind === 'all') + return ( + closeThen(() => hostDrawer.selectAll())} + android_ripple={{ color: pressTint(theme.color.fg), foreground: true }} + style={({ pressed }) => ({ + flexDirection: 'row', + alignItems: 'center', + gap: space.x4, + minHeight: theme.touch + space.x3, + padding: space.x4, + ...rowStyle(theme, glass, pressed, !cloudRoute && filter === 'all'), + overflow: 'hidden', + })} + > + + + {t.allEnvironments} + + + ); if (item.kind === 'host') return ( host.hostId === item.row.hostId)?.routes[0], )} @@ -832,7 +876,10 @@ export function HostDrawer() { host={item.host} onPress={() => closeThen(() => - router.push({ pathname: '/pair', params: { account: item.host.id } }), + router.push({ + pathname: '/pair/account', + params: { account: item.host.id }, + }), ) } /> diff --git a/apps/mobile/test/home-search.test.tsx b/apps/mobile/test/home-search.test.tsx index 96733ca9ec..b2d2ba81ae 100644 --- a/apps/mobile/test/home-search.test.tsx +++ b/apps/mobile/test/home-search.test.tsx @@ -7,11 +7,22 @@ import type { CloudRow } from '../src/cloud/client'; import type { CloudConversation, ConversationWorkspace } from '../src/cloud/conversations'; import { publicInstance, MOBILE_REDIRECT_URI } from '../src/cloud/instance-contract'; import { cloudViewScope } from '../src/cloud/workspace-directory'; +import { computerEnvironmentKey, cloudEnvironmentKey } from '../src/host/conversation-environments'; +import { HOST_COLORS, type HostColorId } from '../src/ui/design/host-look'; +import { Platform } from 'react-native'; +import { HostAccentProvider } from '../src/ui/shell/host-accent-provider'; +import { HomeHeader } from '../src/ui/shell/home-header'; +import { DesignThemeProvider, resolveTheme, useDesignTheme } from '../src/ui/design/theme'; import type { RosterView } from '../src/host/client'; const { push, cloudState, directoryState, hostState } = vi.hoisted(() => ({ push: vi.fn(), - hostState: { connecting: false }, + hostState: { + connecting: false, + removed: false, + color: undefined as HostColorId | undefined, + fontScale: 1, + }, cloudState: { error: undefined as string | undefined, ready: true, @@ -53,8 +64,19 @@ const roster: RosterView = { }; vi.mock('../src/host/native-conversation-filter', async () => { - const { useState } = await import('react'); - return { useConversationFilter: () => useState('all') }; + const { useSyncExternalStore } = await import('react'); + const { createConversationFilter } = await import('../src/host/conversation-filter'); + const conversationFilter = createConversationFilter({ + read: async () => undefined, + write: () => {}, + }); + return { + conversationFilter, + useConversationFilter: () => [ + useSyncExternalStore(conversationFilter.subscribe, conversationFilter.getSnapshot), + conversationFilter.set, + ], + }; }); vi.mock('../src/cloud/native', () => ({ useCloudSnapshot: () => cloudState, @@ -66,10 +88,24 @@ vi.mock('../src/cloud/native-conversations', () => ({ })); vi.mock('react-native-keyboard-controller', async () => import('./keyboard-controller-shim')); vi.mock('react-native-tab-view', () => import('./tab-view-shim')); -vi.mock('react-native', () => import('./react-native-shim')); +vi.mock('react-native', async () => { + const native = await import('./react-native-shim'); + return { + ...native, + useWindowDimensions: () => ({ + ...native.useWindowDimensions(), + fontScale: hostState.fontScale, + }), + }; +}); vi.mock('react-native-reanimated', () => import('./reanimated-shim')); vi.mock('react-native-worklets', () => ({ scheduleOnRN: (callback: () => void) => callback() })); -vi.mock('react-native-svg', () => ({ default: () => null, Path: () => null })); +vi.mock('react-native-svg', () => ({ + default: ({ width, height }: { width: number; height: number }) => ( + + ), + Path: () => null, +})); vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }), })); @@ -87,7 +123,7 @@ vi.mock('expo-router', () => { }); vi.mock('../src/host/host-session', () => ({ useHostSession: () => ({ - saved: { hostId: 'h1', hostName: 'studio' }, + saved: hostState.removed ? null : { hostId: 'h1', hostName: 'studio' }, client: undefined, inbox: undefined, }), @@ -103,34 +139,27 @@ vi.mock('../src/host/native-section-collapse', () => ({ sectionCollapse: { toggle: () => {} }, useCollapsedSections: () => new Set(), })); -vi.mock('expo-symbols', () => ({ SymbolView: () => null })); +vi.mock('expo-symbols', () => ({ + SymbolView: ({ size }: { size: number }) => , +})); vi.mock('../src/host/native-host-look', () => ({ - useHostLook: () => ({ icon: { kind: 'symbol', id: 'desktop' } }), + useHostLook: () => ({ icon: { kind: 'symbol', id: 'desktop' }, color: hostState.color }), })); vi.mock('../src/ui/chat/section-header', () => ({ SectionHeader: () => null })); -vi.mock('../src/ui/shell/home-header', () => ({ - HomeHeader: ({ - actions, - search, - children, - }: { - actions?: ReactNode; - search?: ReactNode; - children: ReactNode; - }) => ( - <> - {search ?? actions} - {children} - - ), -})); vi.mock('../src/ui/shell/host-drawer', () => ({ HostDrawerEdge: ({ children }: { children: ReactNode }) => children, + hostDrawer: { setReturnFocus: () => {} }, + focusOn: () => {}, + openHostDrawer: () => {}, + useHostDrawerOpen: () => false, })); vi.mock('../src/ui/shell/human-avatar', () => ({ HumanAvatarButton: () => null })); vi.mock('../src/ui/connection-banner', () => ({ ConnectionBanner: () => null })); vi.mock('../src/ui/bot-avatar', () => ({ BotAvatar: () => null })); +vi.mock('expo-status-bar', () => ({ StatusBar: () => null })); + +import { conversationFilter } from '../src/host/native-conversation-filter'; import HomeScreen from '../app/(tabs)/(home)/index'; import { t } from '../src/ui/strings'; @@ -152,6 +181,10 @@ afterEach(() => { push.mockReset(); vi.unstubAllGlobals(); hostState.connecting = false; + hostState.removed = false; + hostState.color = undefined; + hostState.fontScale = 1; + conversationFilter.set('all'); cloudState.rows = []; cloudState.ready = true; cloudState.error = undefined; @@ -182,6 +215,7 @@ async function type(view: HTMLElement, text: string): Promise { const rows = (view: HTMLElement) => [...view.querySelectorAll('button')] + .filter((node) => node.dataset.testid !== 'chats-view-button') .filter((node) => !node.closest('[hidden]') && !node.dataset.testid?.startsWith('pager-')) .filter( (node) => @@ -192,6 +226,7 @@ const rows = (view: HTMLElement) => t.closeSearch, t.openSearch, t.settings, + t.workspaces, ].includes(node.getAttribute('aria-label') ?? ''), ) .map((node) => node.getAttribute('aria-label')); @@ -260,17 +295,12 @@ describe('Search in the Chats header', () => { organizationId: 'same-name-empty', }); const view = await home(); - const duplicate = view.querySelector( - '[role="tab"][aria-label="Cloud team, https://uat.example.test, same-name-empty"]', - )!; - expect(duplicate).not.toBeNull(); - await act(async () => duplicate.click()); + expect(view.querySelector('[role="tab"]')).toBeNull(); + expect(view.querySelector('[data-testid="pager-next"]')).toBeNull(); + await act(async () => conversationFilter.set(cloudEnvironmentKey(scope, 'same-name-empty'))); expect(rows(view).join(' ')).not.toContain('Cloud general'); - await act(async () => - view - .querySelector(`[role="tab"][aria-label="${t.allEnvironments}"]`)! - .click(), - ); + expect(view.querySelector('[data-testid="chats-view-button"]')?.textContent).toBe('Cloud team'); + await act(async () => conversationFilter.set('all')); expect(view.textContent).toContain('Cloud general'); expect(view.textContent).toContain('Ada'); await act(async () => @@ -290,28 +320,28 @@ describe('Search in the Chats header', () => { accountScope: scope, }, }); - await act(async () => - view.querySelector('[data-testid="pager-next"]')!.click(), - ); + await act(async () => conversationFilter.set(computerEnvironmentKey('h1'))); + expect(view.querySelector('[data-testid="chats-view-button"]')?.textContent).toBe('studio'); expect(rows(view).join(' ')).not.toContain('Cloud general'); expect(view.textContent).toContain('Ada'); - await act(async () => - view.querySelector('[data-testid="pager-next"]')!.click(), - ); - expect( - view - .querySelector('[role="tab"][aria-label="Cloud team, https://uat.example.test, org_a"]') - ?.getAttribute('aria-selected'), - ).toBe('true'); + await act(async () => conversationFilter.set(cloudEnvironmentKey(scope, 'org_a'))); expect(rows(view).join(' ')).not.toContain('Ada, Done'); expect(rows(view).join(' ')).toContain('Cloud general'); hostState.connecting = true; - await act(async () => - view.querySelector('button[aria-label="Empty workspace"]')!.click(), - ); + await act(async () => conversationFilter.set(cloudEnvironmentKey(scope, 'empty'))); expect(view.textContent).toContain(t.cloudChannels.empty); }); + it('falls back to All when its selected Host is no longer available', async () => { + const view = await home(); + await act(async () => conversationFilter.set(computerEnvironmentKey('removed-host'))); + expect(conversationFilter.getSnapshot()).toBe('all'); + expect(view.querySelector('[data-testid="chats-view-button"]')?.textContent).toBe( + t.allEnvironments, + ); + expect(rows(view)).toHaveLength(3); + }); + it('filters the list in place and opens the chat the Human taps', async () => { const view = await home(); expect(rows(view)).toHaveLength(3); @@ -384,3 +414,116 @@ describe('Search in the Chats header', () => { expect(view.querySelector(`button[aria-label="${t.settings}"]`)).not.toBeNull(); }); }); + +describe('Selected view header accessibility', () => { + it.each(['all', 'computer', 'cloud'] as const)( + 'announces the full %s view and scales its icon with live system text size', + async (kind) => { + const title = kind === 'all' ? t.allEnvironments : 'Studio team with a long complete name'; + const accessibilityLabel = + kind === 'cloud' ? `${title}, cloud.example.test, team-one` : undefined; + host = document.createElement('div'); + root = createRoot(host); + for (const fontScale of [1, 1.4, 2]) { + hostState.fontScale = fontScale; + await act(async () => + root!.render( + + + {null} + + , + ), + ); + const button = host.querySelector('[data-testid="chats-view-button"]')!; + expect(button.getAttribute('aria-label')).toBe( + `${t.workspaces}, ${accessibilityLabel ?? title}`, + ); + const size = resolveTheme('light', {}, 'ios').type.title.line * fontScale; + if (kind === 'computer') { + expect(button.querySelector('[data-symbol-size]')?.getAttribute('data-symbol-size')).toBe( + String(size), + ); + } else { + expect(button.querySelector('svg')?.getAttribute('width')).toBe(String(size)); + expect(button.querySelector('svg')?.getAttribute('height')).toBe(String(size)); + } + } + }, + ); +}); + +describe('Selected current Host accent', () => { + it.each(['light', 'dark'] as const)( + 'limits Android tint to the current Host filter and follows %s theme changes', + async (scheme) => { + const Probe = () => {useDesignTheme().color.accent}; + host = document.createElement('div'); + root = createRoot(host); + const render = (appearance = scheme) => + root!.render( + + + + + , + ); + const before = Platform.OS; + try { + Platform.OS = 'android'; + hostState.color = 'orange'; + await act(async () => render()); + expect(host.textContent).toBe(resolveTheme(scheme, {}, 'android').color.accent); + await act(async () => conversationFilter.set(computerEnvironmentKey('h1'))); + expect(host.textContent).toBe( + resolveTheme(scheme, { accent: HOST_COLORS.orange[scheme] }, 'android').color.accent, + ); + const otherScheme = scheme === 'light' ? 'dark' : 'light'; + await act(async () => render(otherScheme)); + expect(host.textContent).toBe( + resolveTheme(otherScheme, { accent: HOST_COLORS.orange[otherScheme] }, 'android').color + .accent, + ); + await act(async () => render()); + await act(async () => conversationFilter.set('all')); + expect(host.textContent).toBe(resolveTheme(scheme, {}, 'android').color.accent); + await act(async () => conversationFilter.set(computerEnvironmentKey('other-host'))); + expect(host.textContent).toBe(resolveTheme(scheme, {}, 'android').color.accent); + await act(async () => conversationFilter.set(cloudEnvironmentKey('cloud', 'team'))); + expect(host.textContent).toBe(resolveTheme(scheme, {}, 'android').color.accent); + await act(async () => conversationFilter.set(computerEnvironmentKey('h1'))); + hostState.color = 'teal'; + await act(async () => render()); + expect(host.textContent).toBe( + resolveTheme(scheme, { accent: HOST_COLORS.teal[scheme] }, 'android').color.accent, + ); + Platform.OS = 'ios'; + await act(async () => render()); + expect(host.textContent).toBe(resolveTheme(scheme, {}, 'ios').color.accent); + await act(async () => conversationFilter.set('all')); + expect(host.textContent).toBe(resolveTheme(scheme, {}, 'ios').color.accent); + Platform.OS = 'android'; + await act(async () => conversationFilter.set(computerEnvironmentKey('h1'))); + hostState.color = undefined; + await act(async () => render()); + expect(host.textContent).toBe(resolveTheme(scheme, {}, 'android').color.accent); + hostState.color = 'orange'; + hostState.removed = true; + await act(async () => render()); + expect(host.textContent).toBe(resolveTheme(scheme, {}, 'android').color.accent); + } finally { + Platform.OS = before; + } + }, + ); +}); diff --git a/apps/mobile/test/host-drawer.test.ts b/apps/mobile/test/host-drawer.test.ts index ccab9da5f2..72e3eaf85c 100644 --- a/apps/mobile/test/host-drawer.test.ts +++ b/apps/mobile/test/host-drawer.test.ts @@ -47,9 +47,18 @@ function answering( } as unknown as HostClient; } +function deferredSwitch() { + let resolve: (value: boolean) => void = () => {}; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + describe('Host drawer', () => { it('opens from the chip and closes from the backdrop, returning focus to the chip', () => { const drawer = createHostDrawer({ + showView: vi.fn(), switchTo: vi.fn(async () => true), pair: vi.fn(), notifications: vi.fn(), @@ -71,6 +80,7 @@ describe('Host drawer', () => { it('shows the drawer while an edge swipe drags it in, and hides it again when the swipe is let go early', () => { const drawer = createHostDrawer({ + showView: vi.fn(), switchTo: vi.fn(async () => true), pair: vi.fn(), notifications: vi.fn(), @@ -89,6 +99,7 @@ describe('Host drawer', () => { it('keeps the drawer shown when it reopens before the closing slide ends', () => { const drawer = createHostDrawer({ + showView: vi.fn(), switchTo: vi.fn(async () => true), pair: vi.fn(), notifications: vi.fn(), @@ -102,7 +113,12 @@ describe('Host drawer', () => { it('switches to the chosen Host and closes', async () => { const switchTo = vi.fn(async () => true); - const drawer = createHostDrawer({ switchTo, pair: vi.fn(), notifications: vi.fn() }); + const drawer = createHostDrawer({ + showView: vi.fn(), + switchTo, + pair: vi.fn(), + notifications: vi.fn(), + }); drawer.open(); await expect(drawer.select('laptop')).resolves.toBe(true); @@ -110,9 +126,102 @@ describe('Host drawer', () => { expect(drawer.getSnapshot().open).toBe(false); }); + it('selects All without changing the current Host', () => { + const showView = vi.fn(); + const switchTo = vi.fn(async () => true); + const drawer = createHostDrawer({ showView, switchTo, pair: vi.fn(), notifications: vi.fn() }); + drawer.open(); + drawer.selectAll(); + expect(showView).toHaveBeenCalledWith(undefined); + expect(switchTo).not.toHaveBeenCalled(); + expect(drawer.getSnapshot().open).toBe(false); + }); + + it('changes the conversation view only after a successful Host switch', async () => { + const showView = vi.fn(); + let resolveSwitch: (value: boolean) => void = () => {}; + const switchTo = vi.fn( + () => + new Promise((resolve) => { + resolveSwitch = resolve; + }), + ); + const drawer = createHostDrawer({ showView, switchTo, pair: vi.fn(), notifications: vi.fn() }); + const selecting = drawer.select('laptop'); + expect(showView).not.toHaveBeenCalled(); + resolveSwitch(true); + await selecting; + expect(showView).toHaveBeenLastCalledWith('laptop'); + showView.mockClear(); + const removed = drawer.select('removed'); + resolveSwitch(false); + await expect(removed).resolves.toBe(false); + expect(showView).not.toHaveBeenCalled(); + }); + + it('keeps a newer All choice when an earlier Host switch finishes', async () => { + const pending = deferredSwitch(); + const showView = vi.fn(); + const drawer = createHostDrawer({ + showView, + switchTo: () => pending.promise, + pair: vi.fn(), + notifications: vi.fn(), + }); + const selecting = drawer.select('laptop'); + drawer.selectAll(); + pending.resolve(true); + await expect(selecting).resolves.toBe(true); + expect(showView.mock.calls).toEqual([[undefined]]); + }); + + it.each([true, false])( + 'commits only the latest Host choice when the older switch completes first: %s', + async (olderFirst) => { + const older = deferredSwitch(); + const newer = deferredSwitch(); + const showView = vi.fn(); + const drawer = createHostDrawer({ + showView, + switchTo: (hostId) => (hostId === 'laptop' ? older.promise : newer.promise), + pair: vi.fn(), + notifications: vi.fn(), + }); + const laptop = drawer.select('laptop'); + const tower = drawer.select('tower'); + if (olderFirst) { + older.resolve(true); + await laptop; + expect(showView).not.toHaveBeenCalled(); + newer.resolve(true); + } else { + newer.resolve(true); + older.resolve(true); + } + await Promise.all([laptop, tower]); + expect(showView.mock.calls).toEqual([['tower']]); + }, + ); + + it('continues with the next Host choice after a switch rejects', async () => { + const error = new Error('storage failed'); + const switchTo = vi + .fn<(hostId: string) => Promise>() + .mockRejectedValueOnce(error) + .mockResolvedValueOnce(true); + const showView = vi.fn(); + const drawer = createHostDrawer({ switchTo, showView, pair: vi.fn(), notifications: vi.fn() }); + const failed = drawer.select('laptop'); + const next = drawer.select('tower'); + await expect(failed).rejects.toBe(error); + await expect(next).resolves.toBe(true); + expect(showView.mock.calls).toEqual([['tower']]); + }); + it('opens the pairing flow from "Pair a new computer" and closes', () => { const pair = vi.fn(); const drawer = createHostDrawer({ + showView: vi.fn(), switchTo: vi.fn(async () => true), pair, notifications: vi.fn(), @@ -127,6 +236,7 @@ describe('Host drawer', () => { it('opens notification settings from the footer and closes', () => { const notifications = vi.fn(); const drawer = createHostDrawer({ + showView: vi.fn(), switchTo: vi.fn(async () => true), pair: vi.fn(), notifications, diff --git a/apps/mobile/test/host-session-unpair.test.ts b/apps/mobile/test/host-session-unpair.test.ts index 1965aa39a6..b769073cbf 100644 --- a/apps/mobile/test/host-session-unpair.test.ts +++ b/apps/mobile/test/host-session-unpair.test.ts @@ -1,14 +1,22 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { computerEnvironmentKey } from '../src/host/conversation-environments'; +import { parseSavedHosts } from '../src/host/hosts'; +import { createHostDrawer } from '../src/ui/shell/host-drawer-model'; const secure = new Map(); const quickActions = vi.hoisted(() => ({ items: [] as Array<{ id: string }> })); const clearedCaches = vi.hoisted(() => [] as string[]); const forgotten = vi.hoisted(() => [] as string[]); +let beforeSave: ((key: string, value: string) => Promise) | undefined; +let savedFilter = 'all'; vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 0, getItemAsync: async (key: string) => secure.get(key) ?? null, - setItemAsync: async (key: string, value: string) => void secure.set(key, value), + setItemAsync: async (key: string, value: string) => { + await beforeSave?.(key, value); + secure.set(key, value); + }, deleteItemAsync: async (key: string) => void secure.delete(key), })); vi.mock('expo-quick-actions', () => ({ @@ -28,6 +36,8 @@ vi.mock('react-native', () => ({ vi.mock('../src/host/native-source-drafts', () => ({ sourceDrafts: { ready: Promise.resolve(), removeWhere: () => undefined }, })); +vi.mock('../src/host/conversation', () => ({ createConversation: vi.fn() })); +vi.mock('../src/host/conversation-playback', () => ({ createConversationPlayback: vi.fn() })); vi.mock('../src/host/native-cache', () => ({ clearHostConversationCache: (hostId: string) => void clearedCaches.push(hostId), nativeConversationCache: {}, @@ -37,7 +47,9 @@ vi.mock('../src/host/native-conversation-filter', async () => { return { conversationFilter: createConversationFilter({ read: async () => undefined, - write: () => undefined, + write: (value: string) => { + savedFilter = value; + }, }), }; }); @@ -97,18 +109,15 @@ const chat = (id: string, hostId: string) => ({ href: `/dm/${id}?hostId=${encodeURIComponent(hostId)}`, }); -async function session(current: string) { - secure.set( - 'deepseekbot.hosts.v3', - JSON.stringify({ hosts: [host('old'), host('new')], current }), - ); +async function session(current: string, ids = ['old', 'new']) { + secure.set('deepseekbot.hosts.v3', JSON.stringify({ hosts: ids.map(host), current })); secure.set( 'deepseekbot.recent-chats.v1', JSON.stringify([chat('writer', 'old'), chat('coder', 'new')]), ); const { hostSession } = await import('../src/host/host-session'); const { conversationFilter } = await import('../src/host/native-conversation-filter'); - await vi.waitFor(() => expect(hostSession.getState().hosts).toHaveLength(2)); + await vi.waitFor(() => expect(hostSession.getState().hosts).toHaveLength(ids.length)); conversationFilter.set(JSON.stringify(['computer', 'old'])); return { hostSession, conversationFilter }; } @@ -120,15 +129,17 @@ const savedIds = () => } ).hosts.map((entry) => entry.hostId); -describe('unpairing a Computer', () => { - beforeEach(() => { - secure.clear(); - quickActions.items = []; - clearedCaches.length = 0; - forgotten.length = 0; - vi.resetModules(); - }); +beforeEach(() => { + secure.clear(); + quickActions.items = []; + clearedCaches.length = 0; + forgotten.length = 0; + beforeSave = undefined; + savedFilter = 'all'; + vi.resetModules(); +}); +describe('unpairing a Computer', () => { it('drops an older Computer from the list, storage and everything it left on the phone', async () => { const { hostSession, conversationFilter } = await session('new'); const result = await hostSession.unpair('old'); @@ -170,3 +181,84 @@ describe('unpairing a Computer', () => { expect(conversationFilter.getSnapshot()).toBe(JSON.stringify(['computer', 'old'])); }); }); + +function deferredSave() { + let resolve = () => {}; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +async function switchingSession() { + const { hostSession, conversationFilter } = await session('a', ['a', 'b', 'c']); + conversationFilter.set(computerEnvironmentKey('a')); + const writes: string[] = []; + const gates = { b: deferredSave(), c: deferredSave() }; + beforeSave = async (key, value) => { + if (key !== 'deepseekbot.hosts.v3') return; + const current = parseSavedHosts(value).current!; + writes.push(current); + if (current === 'b' || current === 'c') await gates[current].promise; + }; + const drawer = createHostDrawer({ + switchTo: hostSession.switchTo, + showView: (hostId) => + conversationFilter.set(hostId === undefined ? 'all' : computerEnvironmentKey(hostId)), + pair: () => {}, + notifications: () => {}, + }); + const expectSelection = async (owner: string, filter = computerEnvironmentKey(owner)) => { + const { loadSavedHosts } = await import('../src/host/saved-host'); + expect(hostSession.getState().saved?.hostId).toBe(owner); + expect((await loadSavedHosts()).current).toBe(owner); + expect(conversationFilter.getSnapshot()).toBe(filter); + expect(savedFilter).toBe(filter); + }; + return { drawer, writes, gates, expectSelection }; +} + +describe('drawer selection through the real Host Session', () => { + it('returns to A after a pending B save instead of accepting the old current A early', async () => { + const { drawer, writes, gates, expectSelection } = await switchingSession(); + const b = drawer.select('b'); + await vi.waitFor(() => expect(writes).toEqual(['b'])); + const a = drawer.select('a'); + gates.b.resolve(); + await Promise.all([b, a]); + await expectSelection('a'); + expect(writes).toEqual(['b', 'a']); + }); + + it.each([true, false])( + 'keeps C as owner and filter when C storage is released first: %s', + async (newerFirst) => { + const { drawer, writes, gates, expectSelection } = await switchingSession(); + const b = drawer.select('b'); + await vi.waitFor(() => expect(writes).toEqual(['b'])); + const c = drawer.select('c'); + if (newerFirst) { + gates.c.resolve(); + await Promise.resolve(); + gates.b.resolve(); + } else { + gates.b.resolve(); + await b; + gates.c.resolve(); + } + await Promise.all([b, c]); + await expectSelection('c'); + expect(writes).toEqual(['b', 'c']); + }, + ); + + it('keeps All after the pending Host is saved and adopted', async () => { + const { drawer, writes, gates, expectSelection } = await switchingSession(); + const b = drawer.select('b'); + await vi.waitFor(() => expect(writes).toEqual(['b'])); + drawer.selectAll(); + gates.b.resolve(); + await b; + await expectSelection('b', 'all'); + }); +}); diff --git a/changes/2518-mobile-drawer-views.md b/changes/2518-mobile-drawer-views.md new file mode 100644 index 0000000000..6e0e31dd16 --- /dev/null +++ b/changes/2518-mobile-drawer-views.md @@ -0,0 +1,11 @@ +--- +section: Changed +--- + +## en + +- Phone Chats now uses one list selected from All or a Host in the left drawer, with the selected view's full accessible name and icons that follow system text size. The All row shows clipped Android press feedback. Android's accent follows the current Host colour only when that Host's view is selected; All keeps the default accent and queued Host switches keep the final owner and saved Host aligned with the latest Host selection, while All stays selected after a pending switch; iOS keeps its accent and edge swipe ([#2518](https://github.com/BotHarness/DeepSeekBot/issues/2518)). + +## zh + +- 手机聊天页改为在左侧抽屉选择全部或一个 Host,单列表随选择筛选,标题读屏播报完整视图名称,新增图标跟随系统字号,全部行显示裁剪后的 Android 按压反馈。Android 仅在选中当前 Host 视图时使用其颜色,全部视图保留默认强调色;Host 切换按顺序保存并生效,确保最终 Host、持久化记录与最新 Host 选择一致;等待切换时选择全部,也不会被旧视图覆盖。iOS 保留原有强调色和边缘滑动([#2518](https://github.com/BotHarness/DeepSeekBot/issues/2518))。 diff --git a/scripts/verification-inventory.json b/scripts/verification-inventory.json index 2cfc1f9166..c51d36c943 100644 --- a/scripts/verification-inventory.json +++ b/scripts/verification-inventory.json @@ -3,6 +3,14 @@ "auditedBase": "1d1f8ac0cfeb26a8f3bf3a04550e6b92cee52bd9", "boundary": "All scripts/e2e-*.mjs files and all current feature-map documents, augmented by implemented Client/CLI/mobile source entry points. Behavior rows group related acceptance paths; they are not an exhaustive product behavior denominator. Planned unmerged #1954 work and packaged/restart identity promises are excluded.", "behaviors": [ + { + "id": "phone.drawer-views", + "label": "Choose All or one Host from the phone drawer with Android Host accent", + "source": "apps/mobile/src/ui/shell/host-drawer.tsx", + "guide": ".agents/skills/verify-deepseekbot/features/phone-drawer-views.md", + "task": 2518, + "gap": "Native iOS and Android light/dark/large-text qualification requires the shared device queues. All covers the current Host and cloud workspaces only." + }, { "id": "browser.remote-hosts", "label": "Pair Remote Hosts, retain browser pairings across the Host Feed rename and open their conversations",