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。

perf(mobile): 选择性使用安卓原生容器

DavidShen9d750ca42913
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 821a9d94b2..665d848ed5 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -485,7 +485,7 @@ export default function NewRemoteSessionScreen() {
const composerDock = useComposerDock();
const visualInitialDraft = MOBILE_VISUAL_MOCK_ENABLED ? readRouteString(params.visualDraft) : null;
const router = useRouter();
- const nativeSelectionSheet = Platform.OS === 'ios';
+ const nativeSelectionSheet = Platform.OS === 'ios' || Platform.OS === 'android';
const auth = useAuth();
const outboxOwner = useSyncExternalStore(subscribeMobileAuthOwner, getMobileAuthOwner, getMobileAuthOwner);
const {
@@ -6489,6 +6489,7 @@ export default function NewRemoteSessionScreen() {
/> : null}
<SheetModal
backdropTestID="newSession.worktreeBranchSheet.backdrop"
+ nativePresentation
onBackdropPress={() => setWorktreeBranchSheetOpen(false)}
onRequestClose={() => setWorktreeBranchSheetOpen(false)}
visible={worktreeBranchSheetVisible}
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsx
index 2a69701328..66e0ce8ab7 100644
--- a/apps/mobile/app/settings.tsx
+++ b/apps/mobile/app/settings.tsx
@@ -1167,6 +1167,7 @@ export default function SettingsScreen() {
</ScrollView>
<SheetModal
backdropTestID="settings.appearancePicker.backdrop"
+ nativePresentation
onBackdropPress={() => setAppearancePickerOpen(false)}
onRequestClose={() => setAppearancePickerOpen(false)}
visible={appearancePickerOpen}
@@ -1190,6 +1191,7 @@ export default function SettingsScreen() {
</SheetModal>
<SheetModal
backdropTestID="settings.languagePicker.backdrop"
+ nativePresentation
onBackdropPress={() => setLanguagePickerOpen(false)}
onRequestClose={() => setLanguagePickerOpen(false)}
visible={languagePickerOpen}
diff --git a/apps/mobile/docs/mobile-design-guide.md b/apps/mobile/docs/mobile-design-guide.md
index 49ae26a98f..7a19075261 100644
--- a/apps/mobile/docs/mobile-design-guide.md
+++ b/apps/mobile/docs/mobile-design-guide.md
@@ -228,7 +228,24 @@ iOS 新增与改造界面遵循 [iOS 原生界面规范](../../../docs/design-ru
- 系统管理的圆角、字体、材质与反馈保留系统默认,不强制套自绘圆角档位或零阴影约束;自绘内容继续遵守本文 token 规则。
- 模型/权限、Context、账号切换等存量自绘面板列为渐进迁移项,不因本规范批量重写。Android 与必要兼容回退继续复用现有基础组件,不降低业务能力。
- 首页筛选继续使用原生 UIMenu;左侧抽屉和文件浏览顶部的存量实现不代表已经迁移,需分别审查。
-- **Android 交互跟随 iOS**(2026-09-27 产品裁决):入口位置、顺序、分组、显示哪些信息、打开 / 关闭方式与输入校验以 iOS 为准;外观保持 Android 平台实现,不照搬玻璃。贴着控件弹出的菜单(iOS UIMenu)在 Android 用同一个 `NativePullDownMenu`,渲染为 Cindy 自绘的 `AnchoredPullDownMenu`:surfaceElevated 实底 + 1px 边框、零阴影,行首固定列打勾,内联分组带标题与分隔线,子菜单逐层进入,`keepPresented` 的项点完不收起,居中的触发器居中展开。不用系统 PopupMenu(画不出分组标题、给每个可勾选项画空复选框、不跟随主题)。触发器整块是一个读屏按钮;触发控件禁用时传 `disabled`,不挂菜单。
+- Android 首页任务行「选项」采用现有 Expo UI 的 Compose `ModalBottomSheet`
+ (`SessionActionSheetFrame.android.tsx`):原生容器负责拖动、遮罩、系统返回与关闭动画,
+ 任务标题、Lucide 图标和标签操作继续复用 RN 内容及双模式 token。关闭动画完成且容器卸载后,
+ 才通过 `onClosed` 打开重命名或删除确认;不得用固定延时推测原生动画结束。
+ 窄屏、横屏和标签展开时内容可滚动,系统容器保留平台几何,自绘内容仍遵守本文排版规则。
+ 账号切换、权限、标签、消息操作、分支和浏览器菜单等单层面板通过 `SheetModal.nativePresentation`
+ 复用 Material 容器。折叠屏分区、浮动布局、二级返回与未保存表单继续保留兼容外壳,
+ 不把不同关闭回调合并。设置、模型、权限和 Context 的普通行保留 RN 实现,
+ 复用既有主题、排版、禁用态、独立配置按钮与业务回调,不为静态表单逐行嵌套 Compose Host。
+ Android 模型目录通过 `FlatList` 按可见范围分批挂载 RN 行,分组标题与模型共用列表;
+ 使用 `SheetSurface.renderScrollContent` 替换内容滚动层,不能嵌套同向 `ScrollView`。
+ 搜索或来源变化须滚回首条结果,配置入口与模型选择仍是独立点击目标。
+ 新建任务的设备、工作区和远程目录选择复用 RN `NewTaskSelectionRow`;设备使用原生底部弹层,
+ 目录仍在同一兼容弹层内逐级返回,盘符通过原生菜单切换,继续调用被控端目录接口。
+ 开关和普通文本输入原本已是原生控件;富文本编辑器不属于此次迁移。
+- **Android 交互跟随 iOS**(2026-09-27 产品裁决):入口位置、顺序、分组、显示哪些信息与输入校验以 iOS 为准;外观保持 Android 平台实现,不照搬玻璃。贴着控件弹出的菜单统一走 `NativePullDownMenu`,Android 通过 `AnchoredPullDownMenu.android` 使用现有 Expo UI 的 Material `DropdownMenu`,保留分组标题、勾选、禁用、危险操作、子菜单返回行及 `keepPresented`。弹出定位、滚动、焦点及动画交给系统;外部点击和系统返回收起原生菜单。触发器整块是一个读屏按钮,触发控件禁用时不挂菜单。自绘实现保留用于兼容,不使用能力不足的基础 PopupMenu 替代。
+ 原生菜单首次使用时创建 Compose 容器,随后随触发器复用;收起只修改 `expanded`,保留系统关闭动画,避免每次点击重建整棵原生树。锚点的 RN 外层使用 `pointerEvents="none"`,防止关闭后的容器挡住触发器;弹出窗口独立接收菜单点击。验收必须覆盖关闭后再次打开、外部点击和菜单项选择,不能只验证首次呈现。
+ 可勾选菜单项在原生弹出窗口中使用 `RNHostView` 承载一个 RN `menuitem`,通过 `accessibilityState.checked` 表达选中、未选中和半选,禁用态与整行点击共用同一节点;勾号只是装饰,不能代替无障碍语义。现有 Compose modifier 未提供完整三态设置,不增加第二个可点击复选框。回归见 `androidMaterialMenu.test.tsx`,模拟器须核验真实节点。
首页「所有任务」下拉只负责范围筛选:点设备名直接切换到该设备的任务,不得为补充管理动作改成设备子菜单或增加一次确认。设备详情、重命名与删除集中在左侧抽屉的「设备管理」页;列表不画进入箭头或重命名图标。所有设备无论在线、离线或未开启远程控制,都能点进资料详情,再重命名或删除;右滑显示重命名、左滑显示删除,删除需系统确认。iOS 使用系统原生列表与滑动操作。删除使用服务端接口,在线设备当前需先离线才能删除,不以本地隐藏代替删除。iOS 原生菜单与自绘回退、Android 遵守同一交互边界。
diff --git a/apps/mobile/docs/simulator-debugging.md b/apps/mobile/docs/simulator-debugging.md
index 7cb4ac3948..f4f875eb9a 100644
--- a/apps/mobile/docs/simulator-debugging.md
+++ b/apps/mobile/docs/simulator-debugging.md
@@ -416,6 +416,31 @@ Keyboard covers the composer
behavior, safe-area insets, and composer bottom spacing together. Do not validate
keyboard layout with only the hardware keyboard.
+## Android Rendering Performance
+
+- Record the running AVD's actual RAM, GPU backend, CPU count, resolution,
+ installed build, source label, and uptime. `config.ini` can differ from the
+ running emulator's command-line overrides (`hardware-qemu.ini`).
+- First repeat a fixed scroll in Android Settings as an environment control.
+ If it also stalls, save `dumpsys gfxinfo`, memory/swap counters and a Perfetto
+ trace before investigating the app. Cold boot the same AVD without loading or
+ saving a snapshot, preserve user data, and repeat the control with the same
+ hardware settings. Do not attribute this recovery to an application patch.
+- For the app, verify the updated bundle was actually loaded after restarting
+ Metro through `mobile:sim:start`. A development client can continue running
+ cached code after Metro exits. Focus/page assertions must pass before each
+ scripted interaction; an aborted sequence is not a performance sample.
+- Warm each version, repeat the same interaction at least three times, and keep
+ builds, animation settings and simulator configuration identical. Do not run
+ builds, type checks or tests concurrently with sampling. Record frame count,
+ missed-deadline count and frame-time percentiles together: adding a native
+ exit animation changes the denominator of the jank percentage.
+- Use Perfetto to separate React/Fabric mount work, Compose recomposition,
+ RenderThread and graphics-buffer waits. `gfxinfo` for a removed popup can omit
+ that window's frames; retain snapshots while the popup is open as well as the
+ process totals. Debug/emulator results identify regressions, but do not prove
+ release-build performance on physical devices.
+
## Before Asking For Manual Retest
Run this checklist:
diff --git a/apps/mobile/src/__tests__/androidMaterialMenu.test.tsx b/apps/mobile/src/__tests__/androidMaterialMenu.test.tsx
new file mode 100644
index 0000000000..753badf12b
--- /dev/null
+++ b/apps/mobile/src/__tests__/androidMaterialMenu.test.tsx
@@ -0,0 +1,272 @@
+// @vitest-environment jsdom
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+const native = vi.hoisted(() => ({ dismiss: () => {}, mode: "light" }));
+vi.mock("react-native", () => ({
+ View: ({ children, pointerEvents }: any) => (
+ <div data-pointer-events={pointerEvents}>{children}</div>
+ ),
+ Pressable: ({
+ children,
+ onPress,
+ onLongPress,
+ accessibilityState,
+ accessibilityLabel,
+ accessibilityRole,
+ disabled,
+ testID,
+ }: any) => (
+ <button
+ aria-label={accessibilityLabel}
+ aria-expanded={accessibilityState?.expanded}
+ aria-checked={accessibilityState?.checked}
+ aria-disabled={accessibilityState?.disabled}
+ role={accessibilityRole}
+ disabled={disabled}
+ data-testid={testID}
+ onClick={onPress ?? onLongPress}
+ >
+ {children}
+ </button>
+ ),
+ StyleSheet: { absoluteFill: {} },
+}));
+vi.mock("@expo/ui/jetpack-compose", () => {
+ const Slot = ({ children }: any) => <>{children}</>;
+ const DropdownMenu = Object.assign(
+ ({ children, onDismissRequest, expanded }: any) => {
+ native.dismiss = onDismissRequest;
+ return expanded ? <section>{children}</section> : null;
+ },
+ { Trigger: Slot, Items: Slot },
+ );
+ const DropdownMenuItem = Object.assign(
+ ({ children, enabled, onClick, elementColors }: any) => (
+ <button
+ disabled={enabled === false}
+ onClick={onClick}
+ data-color={elementColors?.textColor}
+ >
+ {children}
+ </button>
+ ),
+ { Text: Slot, TrailingIcon: Slot },
+ );
+ return {
+ Box: () => null,
+ Column: Slot,
+ DropdownMenu,
+ DropdownMenuItem,
+ HorizontalDivider: () => <hr />,
+ Host: ({ children, colorScheme }: any) => (
+ <div data-theme={colorScheme}>{children}</div>
+ ),
+ RNHostView: Slot,
+ Text: Slot,
+ };
+});
+vi.mock("@expo/ui/jetpack-compose/modifiers", () => ({
+ fillMaxSize: () => ({}),
+ padding: () => ({}),
+ width: () => ({}),
+ testID: () => ({}),
+}));
+vi.mock("@/components/AppText", () => ({
+ Text: ({ children }: any) => <span>{children}</span>,
+}));
+vi.mock("@/theme", () => ({
+ fontWeight: {},
+ lineHeight: {},
+ spacing: {},
+ typeScale: {},
+ useTheme: () => ({
+ mode: native.mode,
+ colors: {
+ textPrimary: "ink",
+ textSecondary: "muted",
+ destructive: "danger",
+ },
+ }),
+}));
+import { AnchoredPullDownMenu } from "@/platform/chrome/AnchoredPullDownMenu.android";
+
+let root: Root;
+let container: HTMLDivElement;
+beforeEach(() => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ container = document.createElement("div");
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+});
+const click = (label: string) =>
+ act(() => {
+ const button = Array.from(container.querySelectorAll("button")).find(
+ (b) => b.textContent === label,
+ );
+ expect(button).toBeDefined();
+ button!.click();
+ });
+it("keeps groups, check states, disabled choices and repeated selections in the native popup", () => {
+ const choose = vi.fn();
+ act(() =>
+ root.render(
+ <AnchoredPullDownMenu
+ onAction={choose}
+ actions={[
+ {
+ id: "group",
+ title: "Order",
+ displayInline: true,
+ subactions: [
+ { id: "time", title: "Time", state: "on", keepPresented: true },
+ ],
+ },
+ { id: "locked", title: "Locked", disabled: true },
+ { id: "delete", title: "Delete", destructive: true },
+ ]}
+ >
+ <span>Open</span>
+ </AnchoredPullDownMenu>,
+ ),
+ );
+ click("Open");
+ expect(container.textContent).toContain("Order");
+ click("Time✓");
+ click("Time✓");
+ click("Locked");
+ expect(choose.mock.calls).toEqual([["time"], ["time"]]);
+ expect(container.querySelector('[data-color="danger"]')?.textContent).toBe(
+ "Delete",
+ );
+ click("Delete");
+ expect(container.querySelector("section")).toBeNull();
+ expect(
+ container
+ .querySelector("[data-theme]")
+ ?.parentElement?.getAttribute("data-pointer-events"),
+ ).toBe("none");
+ expect(choose).toHaveBeenLastCalledWith("delete");
+});
+it("exposes on/off/mixed on one named action and updates state without losing disabled or keepPresented", () => {
+ const choose = vi.fn();
+ const render = (state: "on" | "off" | "mixed", disabled = false) =>
+ act(() =>
+ root.render(
+ <AnchoredPullDownMenu
+ onAction={choose}
+ actions={[
+ {
+ id: "choice",
+ title: "Choice",
+ subtitle: "Details",
+ state,
+ disabled,
+ keepPresented: true,
+ },
+ { id: "close", title: "Close" },
+ ]}
+ >
+ <span>Open</span>
+ </AnchoredPullDownMenu>,
+ ),
+ );
+ render("on");
+ click("Open");
+ const row = () =>
+ container.querySelector<HTMLButtonElement>(
+ '[data-testid="pullDownMenu.item.choice"]',
+ )!;
+ for (const [state, expected] of [
+ ["on", "true"],
+ ["off", "false"],
+ ["mixed", "mixed"],
+ ] as const) {
+ render(state);
+ expect(row().getAttribute("aria-checked")).toBe(expected);
+ expect(row().getAttribute("aria-label")).toBe("Choice, Details");
+ expect(row().getAttribute("role")).toBe("menuitem");
+ expect(row().querySelector("button")).toBeNull();
+ act(() => row().click());
+ expect(container.querySelector("section")).not.toBeNull();
+ }
+ expect(choose.mock.calls).toEqual([["choice"], ["choice"], ["choice"]]);
+ render("mixed", true);
+ expect(row().disabled).toBe(true);
+ expect(row().getAttribute("aria-disabled")).toBe("true");
+ act(() => row().click());
+ expect(choose).toHaveBeenCalledTimes(3);
+ click("Close");
+ expect(container.querySelector("section")).toBeNull();
+});
+
+it("creates the host on demand and reuses it across dismiss/reopen without blocking the trigger", () => {
+ act(() =>
+ root.render(
+ <AnchoredPullDownMenu
+ actions={[{ id: "one", title: "One" }]}
+ onAction={vi.fn()}
+ >
+ <span>Open</span>
+ </AnchoredPullDownMenu>,
+ ),
+ );
+ expect(container.querySelector("[data-theme]")).toBeNull();
+ click("Open");
+ const host = container.querySelector("[data-theme]");
+ act(() => native.dismiss());
+ expect(container.querySelector("section")).toBeNull();
+ expect(container.querySelector("[data-theme]")).toBe(host);
+ expect(host?.parentElement?.getAttribute("data-pointer-events")).toBe("none");
+ click("Open");
+ expect(container.querySelector("[data-theme]")).toBe(host);
+ expect(host?.parentElement?.getAttribute("data-pointer-events")).toBe("none");
+ expect(container.textContent).toContain("One");
+});
+it("navigates a submenu, returns through its back row, dismisses and resets the path on reopen", () => {
+ act(() =>
+ root.render(
+ <AnchoredPullDownMenu
+ onAction={vi.fn()}
+ actions={[
+ {
+ id: "more",
+ title: "More",
+ subactions: [{ id: "nested", title: "Nested" }],
+ },
+ ]}
+ >
+ <span>Open</span>
+ </AnchoredPullDownMenu>,
+ ),
+ );
+ click("Open");
+ click("More›");
+ expect(container.textContent).toContain("Nested");
+ click("‹ More");
+ expect(container.textContent).not.toContain("Nested");
+ click("More›");
+ act(() => native.dismiss());
+ click("Open");
+ expect(container.textContent).not.toContain("Nested");
+});
+it.each(["light", "dark"])(
+ "uses the %s app appearance for the popup",
+ (mode) => {
+ native.mode = mode;
+ act(() =>
+ root.render(
+ <AnchoredPullDownMenu actions={[]} onAction={vi.fn()}>
+ <span>Open</span>
+ </AnchoredPullDownMenu>,
+ ),
+ );
+ click("Open");
+ expect(
+ container.querySelector("[data-theme]")?.getAttribute("data-theme"),
+ ).toBe(mode);
+ },
+);
diff --git a/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx b/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx
index 8712e5bf47..efad0adbf7 100644
--- a/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx
+++ b/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx
@@ -101,6 +101,22 @@ vi.mock("react-native", async () => {
);
},
ScrollView: passthrough,
+ FlatList: ({
+ data,
+ renderItem,
+ ListHeaderComponent,
+ ListEmptyComponent,
+ }: AnyProps) =>
+ el(
+ "div",
+ null,
+ ListHeaderComponent,
+ data.length
+ ? data.map((item: any, index: number) =>
+ el("div", { key: item.key }, renderItem({ item, index })),
+ )
+ : ListEmptyComponent,
+ ),
StyleSheet: { create: <T,>(styles: T) => styles, hairlineWidth: 1 },
Easing: { bezier: () => (t: number) => t },
View,
@@ -231,7 +247,14 @@ vi.mock("@/session/SheetModal", async () => {
vi.mock("@/session/SheetSurface", async () => {
const { createElement: el } = await import("react");
return {
- SheetSurface: ({ children, title, pinnedTop, onBack, testID }: AnyProps) =>
+ SheetSurface: ({
+ children,
+ title,
+ pinnedTop,
+ onBack,
+ testID,
+ renderScrollContent,
+ }: AnyProps) =>
el(
"section",
{ "data-testid": testID, "data-title": title },
@@ -239,7 +262,7 @@ vi.mock("@/session/SheetSurface", async () => {
? el("button", { "data-testid": `${testID}.back`, onClick: onBack })
: null,
pinnedTop,
- children,
+ renderScrollContent ? renderScrollContent({}) : children,
),
};
});
@@ -650,7 +673,14 @@ describe("Android legacy model list groups by source like iOS", () => {
try {
render(
createElement(MobileModelPickerList, {
- providerRows: [{ provider: provider("sub", "ChatGPT", { access: { kind: "subscription" } }), model: model("a") }],
+ providerRows: [
+ {
+ provider: provider("sub", "ChatGPT", {
+ access: { kind: "subscription" },
+ }),
+ model: model("a"),
+ },
+ ],
flatOptions: [],
activeModelId: "b",
activeSourceId: "sub",
@@ -665,7 +695,9 @@ describe("Android legacy model list groups by source like iOS", () => {
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);
+ 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;
@@ -717,9 +749,17 @@ describe("Android legacy model list groups by source like iOS", () => {
testID: "flat",
} as never),
);
- act(() => native.layouts.get("flat.selectedRow")!({ nativeEvent: { layout: { y: 60 } } }));
+ 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 } } }));
+ act(() =>
+ native.layouts.get("flat.group.__flat__")!({
+ nativeEvent: { layout: { y: 120 } },
+ }),
+ );
expect(onSelectedRowLayout).toHaveBeenLastCalledWith(180);
});
});
diff --git a/apps/mobile/src/__tests__/androidSessionInteractionParity.test.tsx b/apps/mobile/src/__tests__/androidSessionInteractionParity.test.tsx
index 5a50aa6117..0cd03f54e4 100644
--- a/apps/mobile/src/__tests__/androidSessionInteractionParity.test.tsx
+++ b/apps/mobile/src/__tests__/androidSessionInteractionParity.test.tsx
@@ -9,6 +9,7 @@ const sheet = vi.hoisted(() => ({ onClosed: undefined as (() => void) | undefine
vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => false, getCachedReduceMotionEnabled: () => false }));
vi.mock('react-native', () => ({
+ Platform: { OS: 'android' },
ActivityIndicator: () => null,
Pressable: ({ children, onPress, testID }: { children?: ReactNode; onPress?: () => void; testID?: string }) =>
createElement('button', { 'data-testid': testID, onClick: onPress }, children as ReactNode),
diff --git a/apps/mobile/src/__tests__/blurBackdropScrim.test.ts b/apps/mobile/src/__tests__/blurBackdropScrim.test.ts
index b6a496986a..1d98c54266 100644
--- a/apps/mobile/src/__tests__/blurBackdropScrim.test.ts
+++ b/apps/mobile/src/__tests__/blurBackdropScrim.test.ts
@@ -23,11 +23,15 @@ describe('BlurBackdrop scrim 双模式恒深 (用户定稿 2026-07-21)', () => {
expect(src).toContain("isScrim ? 'dark' : mode === 'dark' ? 'dark' : 'light'");
});
- it('scrim 消费点用裸 BlurBackdrop(走恒深默认):SheetModal / SessionActionSheet 背板', () => {
+ it('兼容弹层保留恒深 BlurBackdrop,Android 原生弹层消费同一遮罩 token', () => {
const sheetModal = readTextLf(resolve(process.cwd(), 'src/session/SheetModal.tsx'), 'utf8');
- const actionSheet = readTextLf(resolve(process.cwd(), 'src/session/SessionActionSheet.tsx'), 'utf8');
+ const actionSheet = readTextLf(resolve(process.cwd(), 'src/session/SessionActionSheetFrame.tsx'), 'utf8');
+ const nativeSheet = readTextLf(resolve(process.cwd(), 'src/session/SessionActionSheetFrame.android.tsx'), 'utf8');
expect(sheetModal).toContain('<BlurBackdrop />');
expect(actionSheet).toContain('<BlurBackdrop />');
+ expect(nativeSheet).toContain('scrimColor={colors.overlay}');
+ expect(nativeSheet).toContain('containerColor={colors.surfaceElevated}');
+ expect(nativeSheet).toContain('colorScheme={mode}');
});
it('surface 消费点保留显式浅色 overlayColor(面板表面不染深)', () => {
diff --git a/apps/mobile/src/__tests__/iosChromeActionMenu.test.ts b/apps/mobile/src/__tests__/iosChromeActionMenu.test.ts
index 43349f3a1c..8b02433fbf 100644
--- a/apps/mobile/src/__tests__/iosChromeActionMenu.test.ts
+++ b/apps/mobile/src/__tests__/iosChromeActionMenu.test.ts
@@ -158,7 +158,15 @@ describe("iOS chrome presenters stay on the system menu path", () => {
"utf8",
);
- expect(sessionSheet).toContain('testID="home.sessionActions"');
+ expect(sessionSheet).toContain("<SessionActionSheetFrame");
+ for (const file of [
+ "SessionActionSheetFrame.tsx",
+ "SessionActionSheetFrame.android.tsx",
+ ]) {
+ expect(
+ readTextLf(resolve(process.cwd(), "src/session", file), "utf8"),
+ ).toContain('testID="home.sessionActions"');
+ }
expect(messageSheet).toContain("<SheetModal");
expect(chipSheet).toContain('testID="session.chipMenu"');
expect(settings).toContain('backTestID="settings.backButton"');
diff --git a/apps/mobile/src/__tests__/newTaskSelectionAndroid.test.tsx b/apps/mobile/src/__tests__/newTaskSelectionAndroid.test.tsx
new file mode 100644
index 0000000000..9d49099a3f
--- /dev/null
+++ b/apps/mobile/src/__tests__/newTaskSelectionAndroid.test.tsx
@@ -0,0 +1,171 @@
+// @vitest-environment jsdom
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { beforeEach, afterEach, expect, it, vi } from "vitest";
+
+const modal = vi.hoisted(() => ({ props: null as any }));
+vi.mock("react-native", () => ({
+ View: ({ children }: any) => <div>{children}</div>,
+ ActivityIndicator: () => <span>loading</span>,
+ useWindowDimensions: () => ({ width: 400, height: 800 }),
+}));
+vi.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 20, bottom: 20 }),
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (s: string) => s }),
+}));
+vi.mock("@/components/AppText", () => ({
+ Text: ({ children }: any) => <span>{children}</span>,
+}));
+vi.mock("@/theme", () => ({
+ iconSize: {},
+ lineHeight: {},
+ spacing: {},
+ typeScale: {},
+ useTheme: () => ({ colors: {} }),
+}));
+vi.mock("lucide-react-native", () => ({
+ ArrowUp: () => null,
+ ChevronRight: () => null,
+ Folder: () => null,
+ FolderPlus: () => null,
+ Laptop: () => null,
+ MessageCircle: () => null,
+}));
+vi.mock("@/session/NewTaskSelectionRow", () => ({
+ NewTaskSelectionRow: ({ title, testID, selected, disabled, onPress }: any) => (
+ <button
+ data-testid={testID}
+ aria-pressed={selected}
+ disabled={disabled}
+ onClick={onPress}
+ >
+ {title}
+ </button>
+ ),
+}));
+vi.mock("@/platform/chrome", () => ({
+ NativePullDownMenu: ({ children }: any) => children,
+ NativeSwitch: () => null,
+}));
+vi.mock("@/session/SheetModal", () => ({
+ SheetModal: (p: any) => {
+ modal.props = p;
+ return p.children;
+ },
+}));
+vi.mock("@/session/SheetSurface", () => ({
+ SheetSurface: ({ children, footer }: any) => (
+ <>
+ {children}
+ {footer}
+ </>
+ ),
+}));
+vi.mock("@/session/ContextSheet", () => ({
+ ContextSheetFooterButton: ({ label, testID, disabled, onPress }: any) => (
+ <button data-testid={testID} disabled={disabled} onClick={onPress}>
+ {label}
+ </button>
+ ),
+}));
+vi.mock("@/session/newSessionMessages", () => ({
+ newSessionText: (s: string) => s,
+}));
+import { NewTaskSelectionSheet } from "@/session/NewTaskSelectionSheet.android";
+import type { NewTaskSelectionSheetProps } from "@/session/NewTaskSelectionSheet";
+
+let root: Root;
+let container: HTMLDivElement;
+let props: NewTaskSelectionSheetProps;
+beforeEach(() => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ container = document.createElement("div");
+ root = createRoot(container);
+ props = {
+ page: "device",
+ busy: false,
+ devices: [{ deviceId: "pc", name: "PC" }],
+ selectedDeviceId: "pc",
+ workspaces: [{ title: "Project", workingDir: "D:/project" }],
+ workspaceKind: "project",
+ workingDir: "D:/project",
+ path: "D:/project",
+ parent: "D:/",
+ drives: [],
+ entries: [{ name: "src", path: "D:/project/src" }],
+ loading: false,
+ error: null,
+ showHidden: false,
+ onClose: vi.fn(),
+ onBack: vi.fn(),
+ onDevice: vi.fn(),
+ onDialogue: vi.fn(),
+ onProject: vi.fn(),
+ onBrowse: vi.fn(),
+ onEnter: vi.fn(),
+ onChoose: vi.fn(),
+ onShowHidden: vi.fn(),
+ };
+});
+afterEach(() => act(() => root.unmount()));
+function render(p: Partial<NewTaskSelectionSheetProps> = {}) {
+ props = { ...props, ...p };
+ act(() => root.render(<NewTaskSelectionSheet {...props} />));
+}
+function click(id: string) {
+ act(() =>
+ (
+ container.querySelector(
+ `[data-testid="newSession.${id}"]`,
+ ) as HTMLButtonElement
+ ).click(),
+ );
+}
+it("selects a device and retains the native presentation until its closing animation finishes", () => {
+ render();
+ click("deviceOption");
+ expect(props.onDevice).toHaveBeenCalledWith("pc");
+ expect(modal.props.nativePresentation).toBe(true);
+ render({ page: null });
+ expect(modal.props.visible).toBe(false);
+ expect(modal.props.nativePresentation).toBe(true);
+});
+it("keeps directory Back separate from backdrop dismissal and uses remote paths", () => {
+ render({ page: "directory" });
+ expect(modal.props.nativePresentation).toBe(false);
+ act(() => modal.props.onRequestClose());
+ expect(props.onBack).toHaveBeenCalledOnce();
+ expect(props.onClose).not.toHaveBeenCalled();
+ act(() => modal.props.onBackdropPress());
+ expect(props.onClose).toHaveBeenCalledOnce();
+ click("remoteBrowseParentButton");
+ click("remoteBrowseEnterEntry");
+ expect(props.onEnter).toHaveBeenNthCalledWith(1, "D:/");
+ expect(props.onEnter).toHaveBeenNthCalledWith(2, "D:/project/src");
+ click("remoteBrowseSelectCurrent");
+ expect(props.onChoose).toHaveBeenCalledWith("D:/project");
+});
+it.each([
+ { loading: true },
+ { busy: true },
+ { error: "offline" },
+ { path: "" },
+])("does not choose an unavailable directory (%j)", (state) => {
+ render({ page: "directory", ...state });
+ click("remoteBrowseSelectCurrent");
+ expect(props.onChoose).not.toHaveBeenCalled();
+});
+it("keeps workspace choices and blocks them while busy", () => {
+ render({ page: "workspace" });
+ click("workspaceDialogueOption");
+ click("workspaceProjectOption");
+ click("workspaceBrowseOption");
+ expect(props.onDialogue).toHaveBeenCalledOnce();
+ expect(props.onProject).toHaveBeenCalledWith("D:/project");
+ expect(props.onBrowse).toHaveBeenCalledOnce();
+ render({ busy: true });
+ click("workspaceBrowseOption");
+ expect(props.onBrowse).toHaveBeenCalledOnce();
+});
diff --git a/apps/mobile/src/__tests__/sessionActionSheetAndroid.test.tsx b/apps/mobile/src/__tests__/sessionActionSheetAndroid.test.tsx
new file mode 100644
index 0000000000..0537999b10
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionActionSheetAndroid.test.tsx
@@ -0,0 +1,198 @@
+// @vitest-environment jsdom
+import React, { act, useState } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const native = vi.hoisted(() => ({
+ props: null as any,
+ hide: vi.fn<() => Promise<void>>(),
+ expand: vi.fn<() => Promise<void>>(),
+ mode: "light",
+}));
+vi.mock("@expo/ui/jetpack-compose", () => ({
+ Host: ({ children, colorScheme }: any) => (
+ <div data-scheme={colorScheme}>{children}</div>
+ ),
+ RNHostView: ({ children }: any) => children,
+ ModalBottomSheet: ({ ref, ...props }: any) => {
+ native.props = props;
+ React.useImperativeHandle(
+ ref,
+ () => ({ hide: native.hide, expand: native.expand }),
+ [],
+ );
+ return <div data-testid="native-sheet">{props.children}</div>;
+ },
+}));
+vi.mock("react-native", () => ({
+ ScrollView: ({ children }: any) => <div>{children}</div>,
+ StyleSheet: { create: (s: any) => s },
+ useWindowDimensions: () => ({ width: 400, height: 800 }),
+}));
+vi.mock("@/platform/gestureHandler", () => ({
+ GestureHandlerRootView: ({ children }: any) => children,
+}));
+vi.mock("@/platform/AdaptiveWindowContext", () => ({
+ PaneViewportProvider: ({ children }: any) => children,
+}));
+vi.mock("@/theme", () => ({
+ useTheme: () => ({
+ mode: native.mode,
+ colors: {
+ surfaceElevated: "surface",
+ textPrimary: "text",
+ overlay: "scrim",
+ },
+ }),
+}));
+
+import { SessionActionSheetFrame } from "@/session/SessionActionSheetFrame.android";
+import { NativeBottomSheet } from "@/session/NativeBottomSheet.android";
+
+let root: Root;
+let container: HTMLDivElement;
+let frames: Map<number, FrameRequestCallback>;
+function flushFrames() {
+ act(() => {
+ const pending = [...frames.values()];
+ frames.clear();
+ pending.forEach((callback) => callback(0));
+ });
+}
+beforeEach(() => {
+ frames = new Map();
+ let nextFrame = 0;
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
+ frames.set(++nextFrame, callback);
+ return nextFrame;
+ });
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ native.hide.mockReset();
+ native.expand.mockReset().mockResolvedValue();
+ native.mode = "light";
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+describe.each([SessionActionSheetFrame, NativeBottomSheet])(
+ "Android native sheet lifecycle (%s)",
+ (Frame) => {
+ it("waits for native hide and unmount before opening the next dialog, exactly once", async () => {
+ let finish!: () => void;
+ native.hide.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const closed = vi.fn(() =>
+ expect(
+ container.querySelector('[data-testid="native-sheet"]'),
+ ).toBeNull(),
+ );
+ const render = (visible: boolean) =>
+ act(() =>
+ root.render(
+ <Frame visible={visible} onClose={vi.fn()} onClosed={closed}>
+ actions
+ </Frame>,
+ ),
+ );
+ render(false);
+ expect(closed).not.toHaveBeenCalled();
+ render(true);
+ render(false);
+ expect(native.hide).toHaveBeenCalledOnce();
+ expect(container.textContent).toContain("actions");
+ expect(closed).not.toHaveBeenCalled();
+ await act(async () => {
+ finish();
+ });
+ expect(closed).not.toHaveBeenCalled();
+ flushFrames();
+ expect(closed).toHaveBeenCalledOnce();
+ render(false);
+ expect(closed).toHaveBeenCalledOnce();
+ });
+
+ it("handles native swipe, scrim and Back dismissal without an extra hide animation", () => {
+ const closed = vi.fn();
+ function Presenter() {
+ const [visible, setVisible] = useState(true);
+ return (
+ <Frame
+ visible={visible}
+ onClose={() => setVisible(false)}
+ onClosed={closed}
+ >
+ actions
+ </Frame>
+ );
+ }
+ act(() => root.render(<Presenter />));
+ act(() => native.props.onDismissRequest());
+ expect(container.textContent).toBe("");
+ flushFrames();
+ expect(closed).toHaveBeenCalledOnce();
+ expect(native.hide).not.toHaveBeenCalled();
+ });
+
+ it("does not let an old hide completion dismiss a newly reopened sheet", async () => {
+ let finish!: () => void;
+ native.hide.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const closed = vi.fn();
+ const render = (visible: boolean) =>
+ act(() =>
+ root.render(
+ <Frame visible={visible} onClose={vi.fn()} onClosed={closed}>
+ actions
+ </Frame>,
+ ),
+ );
+ render(true);
+ render(false);
+ render(true);
+ await act(async () => {
+ finish();
+ });
+ expect(container.textContent).toContain("actions");
+ expect(native.expand).toHaveBeenCalledOnce();
+ expect(closed).not.toHaveBeenCalled();
+ });
+
+ it.each(["light", "dark"])(
+ "passes the %s theme and semantic surface/scrim to Compose",
+ (mode) => {
+ native.mode = mode;
+ act(() =>
+ root.render(
+ <Frame visible onClose={vi.fn()}>
+ actions
+ </Frame>,
+ ),
+ );
+ expect(
+ container.querySelector("[data-scheme]")?.getAttribute("data-scheme"),
+ ).toBe(mode);
+ expect(native.props).toMatchObject({
+ containerColor: "surface",
+ contentColor: "text",
+ scrimColor: "scrim",
+ skipPartiallyExpanded: true,
+ });
+ },
+ );
+ },
+);
diff --git a/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx b/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx
index 8998a6d300..af4facdc2a 100644
--- a/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx
+++ b/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx
@@ -1,48 +1,164 @@
// @vitest-environment jsdom
-import { act, createElement } from 'react';
-import { createRoot } from 'react-dom/client';
-import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { UnifiedModelPickerView } from '@/session/UnifiedModelPickerView';
-vi.mock('react-native', async () => {
- const { createElement: el } = await import('react');
- const View = ({ children }: any) => el('div', null, children);
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { UnifiedModelPickerView } from "@/session/UnifiedModelPickerView";
+const virtualList = vi.hoisted(() => ({ scrollToOffset: vi.fn() }));
+vi.mock("react-native", async () => {
+ const { createElement: el, useImperativeHandle } = await import("react");
+ const View = ({ children }: any) => el("div", null, children);
return {
- View, ScrollView: View,
- Pressable: ({ children, onPress, disabled }: any) => el('button', { onClick: onPress, disabled }, children),
+ Platform: { OS: "android" },
+ View,
+ ScrollView: View,
+ FlatList: ({
+ ref,
+ data,
+ renderItem,
+ ListHeaderComponent,
+ ListEmptyComponent,
+ }: any) => {
+ useImperativeHandle(
+ ref,
+ () => ({ scrollToOffset: virtualList.scrollToOffset }),
+ [],
+ );
+ return el(
+ "div",
+ null,
+ ListHeaderComponent,
+ data.length
+ ? data.map((item: any, index: number) =>
+ el("div", { key: item.key }, renderItem({ item, index })),
+ )
+ : ListEmptyComponent,
+ );
+ },
+ Pressable: ({ children, onPress, disabled }: any) =>
+ el("button", { onClick: onPress, disabled }, children),
StyleSheet: { create: (styles: any) => styles, hairlineWidth: 1 },
useWindowDimensions: () => ({ height: 800 }),
};
});
-vi.mock('@/components/AppText', async () => {
- const { createElement: el } = await import('react');
- return { Text: ({ children }: any) => el('span', null, children), TextInput: () => null };
+vi.mock("@/components/AppText", async () => {
+ const { createElement: el } = await import("react");
+ return {
+ Text: ({ children }: any) => el("span", null, children),
+ TextInput: () => null,
+ };
});
-vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 40, bottom: 20 }) }));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
-vi.mock('lucide-react-native', () => Object.fromEntries(['Brain', 'Star', 'SlidersHorizontal', 'Check', 'Zap', 'LayoutGrid', 'Search', 'X', 'ChevronDown', 'ChevronRight', 'ChevronsUpDown'].map(key => [key, () => null])));
-vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: ({ children }: any) => children, NativeSwitch: () => null, usesNativePullDownMenu: () => true }));
-vi.mock('@/components/MobileAgentMark', () => ({ MobileAgentMark: () => null }));
-vi.mock('@/session/MobileProviderMark', () => ({ MobileModelIconMark: () => null, MobileProviderMark: () => null }));
-vi.mock('@/session/SheetModal', () => ({ SheetModal: ({ children }: any) => children }));
-vi.mock('@/session/SheetSurface', () => ({ SheetSurface: ({ children }: any) => children }));
-vi.mock('@/session/sessionAgentSwitch', () => ({ mobileAgentLabel: (agent: string) => agent }));
-vi.mock('@/theme', async () => ({ ...(await import('@/theme/tokens')), useTheme: () => ({ colors: {} }), useThemedStyles: (factory: any) => factory({}) }));
+vi.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 40, bottom: 20 }),
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock("lucide-react-native", () =>
+ Object.fromEntries(
+ [
+ "Brain",
+ "Star",
+ "SlidersHorizontal",
+ "Check",
+ "Zap",
+ "LayoutGrid",
+ "Search",
+ "X",
+ "ChevronDown",
+ "ChevronRight",
+ "ChevronsUpDown",
+ ].map((key) => [key, () => null]),
+ ),
+);
+vi.mock("@/platform/chrome", () => ({
+ NativePullDownMenu: ({ children }: any) => children,
+ NativeSwitch: () => null,
+ usesNativePullDownMenu: () => true,
+}));
+vi.mock("@/components/MobileAgentMark", () => ({
+ MobileAgentMark: () => null,
+}));
+vi.mock("@/session/MobileProviderMark", () => ({
+ MobileModelIconMark: () => null,
+ MobileProviderMark: () => null,
+}));
+vi.mock("@/session/SheetModal", () => ({
+ SheetModal: ({ children }: any) => children,
+}));
+vi.mock("@/session/SheetSurface", () => ({
+ SheetSurface: ({ children, renderScrollContent }: any) =>
+ renderScrollContent ? renderScrollContent({}) : children,
+}));
+vi.mock("@/session/sessionAgentSwitch", () => ({
+ mobileAgentLabel: (agent: string) => agent,
+}));
+vi.mock("@/theme", async () => ({
+ ...(await import("@/theme/tokens")),
+ useTheme: () => ({ colors: {} }),
+ useThemedStyles: (factory: any) => factory({}),
+}));
let root: ReturnType<typeof createRoot>;
let host: HTMLDivElement;
beforeEach(() => {
+ virtualList.scrollToOffset.mockClear();
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
- host = document.createElement('div');
+ host = document.createElement("div");
root = createRoot(host);
});
afterEach(() => act(() => root.unmount()));
-it.each([null, '2d · 70%'])('keeps both account identities visible with quota %s', async quotaLabel => {
- const rows = ['[email protected]', '[email protected]'].map(subtitle => ({
- key: subtitle, subtitle, quotaLabel, entry: { displayName: 'Same Model' },
- config: { agent: 'codex' }, providerMark: {},
- }));
- await act(async () => root.render(createElement(UnifiedModelPickerView, {
- visible: true, groups: [{ key: 'favorites', title: 'Favorites', rows }], filters: [],
- } as any)));
- for (const row of rows) expect(host.textContent).toContain(row.subtitle);
- if (quotaLabel) expect(host.textContent).toContain(quotaLabel);
-});
+it.each([null, "2d · 70%"])(
+ "keeps both account identities visible with quota %s",
+ async (quotaLabel) => {
+ const rows = ["[email protected]", "[email protected]"].map(
+ (subtitle) => ({
+ key: subtitle,
+ subtitle,
+ quotaLabel,
+ entry: { displayName: "Same Model" },
+ config: { agent: "codex" },
+ providerMark: {},
+ }),
+ );
+ await act(async () =>
+ root.render(
+ createElement(UnifiedModelPickerView, {
+ visible: true,
+ groups: [{ key: "favorites", title: "Favorites", rows }],
+ filters: [],
+ } as any),
+ ),
+ );
+ for (const row of rows) expect(host.textContent).toContain(row.subtitle);
+ if (quotaLabel) expect(host.textContent).toContain(quotaLabel);
+ },
+);
+it.each(["query", "filter"])(
+ "returns to the first result when %s changes after scrolling",
+ async (field) => {
+ const props = {
+ visible: true,
+ groups: [],
+ filters: [],
+ query: "",
+ filter: "all",
+ emptyHint: "No results",
+ };
+ await act(async () =>
+ root.render(createElement(UnifiedModelPickerView, props as any)),
+ );
+ virtualList.scrollToOffset.mockClear();
+ await act(async () =>
+ root.render(
+ createElement(UnifiedModelPickerView, {
+ ...props,
+ [field]: "changed",
+ } as any),
+ ),
+ );
+ expect(virtualList.scrollToOffset).toHaveBeenCalledWith({
+ offset: 0,
+ animated: false,
+ });
+ expect(host.textContent).toContain("No results");
+ },
+);
diff --git a/apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx b/apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx
new file mode 100644
index 0000000000..86c699e912
--- /dev/null
+++ b/apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx
@@ -0,0 +1,314 @@
+import {
+ Box,
+ Column,
+ DropdownMenu,
+ DropdownMenuItem,
+ HorizontalDivider,
+ Host,
+ RNHostView,
+ Text,
+} from "@expo/ui/jetpack-compose";
+import {
+ fillMaxSize,
+ padding,
+ width,
+ testID as nativeTestID,
+} from "@expo/ui/jetpack-compose/modifiers";
+import { Fragment, isValidElement, useState, type ComponentProps } from "react";
+import {
+ Pressable,
+ StyleSheet,
+ View,
+ type AccessibilityProps,
+} from "react-native";
+import type { AnchoredPullDownMenu as CompatibleMenu } from "./AnchoredPullDownMenu";
+import {
+ buildPullDownMenuSections,
+ resolvePullDownSubmenu,
+} from "./pullDownMenuModel";
+import { fontWeight, lineHeight, spacing, typeScale, useTheme } from "@/theme";
+import { Text as AppText } from "@/components/AppText";
+import type { NativePullDownAction } from "./NativePullDownMenu";
+
+/** Compose's exported modifiers lack a tri-state semantic setter. Keep one RN
+ * accessible row inside the native popup, rather than exposing a decorative
+ * checkmark (or adding a second clickable checkbox beside the menu action). */
+function CheckedMenuItem({
+ action,
+ onPress,
+ testID,
+}: {
+ action: NativePullDownAction;
+ onPress(): void;
+ testID: string;
+}) {
+ const { colors } = useTheme();
+ const color = action.disabled
+ ? colors.textTertiary
+ : action.destructive
+ ? colors.destructive
+ : colors.textPrimary;
+ return (
+ <RNHostView matchContents>
+ <Pressable
+ accessible
+ accessibilityRole="menuitem"
+ accessibilityLabel={[action.title, action.subtitle]
+ .filter(Boolean)
+ .join(", ")}
+ accessibilityState={{
+ checked: action.state === "mixed" ? "mixed" : action.state === "on",
+ disabled: !!action.disabled,
+ }}
+ disabled={!!action.disabled}
+ onPress={onPress}
+ testID={testID}
+ style={({ pressed }) => ({
+ width: 280,
+ minHeight: 48,
+ justifyContent: "center",
+ paddingHorizontal: spacing.lg,
+ paddingVertical: spacing.sm,
+ backgroundColor: pressed ? colors.surfaceChip : "transparent",
+ })}
+ >
+ <View
+ importantForAccessibility="no-hide-descendants"
+ style={{
+ flexDirection: "row",
+ alignItems: "center",
+ gap: spacing.md,
+ }}
+ >
+ <View style={{ flex: 1 }}>
+ <AppText
+ style={{
+ color,
+ fontSize: typeScale.body,
+ lineHeight: lineHeight.body,
+ fontWeight: action.disabled
+ ? fontWeight.regular
+ : fontWeight.medium,
+ }}
+ >
+ {action.title}
+ </AppText>
+ {action.subtitle ? (
+ <AppText
+ style={{
+ color: action.disabled
+ ? colors.textTertiary
+ : colors.textSecondary,
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ }}
+ >
+ {action.subtitle}
+ </AppText>
+ ) : null}
+ </View>
+ {action.subactions?.length || action.state !== "off" ? (
+ <AppText
+ style={{
+ color,
+ fontSize: typeScale.body,
+ lineHeight: lineHeight.body,
+ }}
+ >
+ {action.subactions?.length
+ ? "›"
+ : action.state === "mixed"
+ ? "−"
+ : "✓"}
+ </AppText>
+ ) : null}
+ </View>
+ </Pressable>
+ </RNHostView>
+ );
+}
+
+/** Material owns popup placement, scrolling, focus and enter/exit animations. */
+export function AnchoredPullDownMenu({
+ actions,
+ children,
+ longPress,
+ onAction,
+ style,
+ testID,
+ accessibilityLabel,
+}: ComponentProps<typeof CompatibleMenu>) {
+ const { colors, mode } = useTheme();
+ const [open, setOpen] = useState(false);
+ // Lazily create the Compose tree, then reuse it for this trigger's lifetime.
+ // Removing it on every close adds Fabric mount work to the next input frame
+ // and cuts off Material's exit animation. The popup itself still closes.
+ const [mounted, setMounted] = useState(false);
+ const [path, setPath] = useState<string[]>([]);
+ const child = isValidElement(children)
+ ? (children.props as AccessibilityProps)
+ : {};
+ const submenu = resolvePullDownSubmenu(actions, path);
+ const sections = buildPullDownMenuSections(submenu?.subactions ?? actions);
+ const show = () => {
+ setMounted(true);
+ setPath([]);
+ setOpen(true);
+ };
+ const back = () => setPath((current) => current.slice(0, -1));
+ const choose = (action: NativePullDownAction) => {
+ if (action.disabled) return;
+ if (action.subactions?.length && !action.displayInline) {
+ setPath((current) => [...current, action.id]);
+ return;
+ }
+ if (!action.keepPresented) setOpen(false);
+ onAction(action.id);
+ };
+ return (
+ <View style={style}>
+ <Pressable
+ accessibilityLabel={accessibilityLabel ?? child.accessibilityLabel}
+ accessibilityHint={child.accessibilityHint}
+ accessibilityValue={child.accessibilityValue}
+ accessibilityRole="button"
+ accessibilityState={{ ...child.accessibilityState, expanded: open }}
+ onPress={longPress ? undefined : show}
+ onLongPress={longPress ? show : undefined}
+ testID={testID}
+ >
+ <View
+ pointerEvents="none"
+ importantForAccessibility="no-hide-descendants"
+ >
+ {children}
+ </View>
+ </Pressable>
+ {mounted ? (
+ // The anchor has no input of its own. RN must exclude the Host from
+ // hit testing; Compose's popup receives input in its separate window.
+ <View pointerEvents="none" style={StyleSheet.absoluteFill}>
+ <Host
+ colorScheme={mode}
+ seedColor={colors.textPrimary}
+ style={StyleSheet.absoluteFill}
+ >
+ <DropdownMenu
+ expanded={open}
+ modifiers={[
+ nativeTestID(testID ? `${testID}.menu` : "pullDownMenu"),
+ ]}
+ color={colors.surfaceElevated}
+ onDismissRequest={() => setOpen(false)}
+ >
+ <DropdownMenu.Trigger>
+ <Box modifiers={[fillMaxSize()]} />
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Items>
+ {submenu ? (
+ <DropdownMenuItem onClick={back}>
+ <DropdownMenuItem.Text>
+ <Text
+ color={colors.textPrimary}
+ style={{
+ fontSize: typeScale.body,
+ lineHeight: lineHeight.body,
+ }}
+ >
+ ‹ {submenu.title}
+ </Text>
+ </DropdownMenuItem.Text>
+ </DropdownMenuItem>
+ ) : null}
+ {sections.map((section, index) => (
+ <Fragment key={section.key}>
+ {index > 0 || submenu ? (
+ <HorizontalDivider color={colors.border} />
+ ) : null}
+ {section.title ? (
+ <Text
+ color={colors.textSecondary}
+ modifiers={[
+ padding(
+ spacing.md,
+ spacing.sm,
+ spacing.md,
+ spacing.xs,
+ ),
+ ]}
+ style={{
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ }}
+ >
+ {section.title}
+ </Text>
+ ) : null}
+ {section.rows.map((action) =>
+ action.state ? (
+ <CheckedMenuItem
+ key={action.id}
+ action={action}
+ onPress={() => choose(action)}
+ testID={`${testID ? `${testID}.menu` : "pullDownMenu"}.item.${action.id}`}
+ />
+ ) : (
+ <DropdownMenuItem
+ key={action.id}
+ enabled={!action.disabled}
+ modifiers={[
+ width(280),
+ nativeTestID(
+ `${testID ? `${testID}.menu` : "pullDownMenu"}.item.${action.id}`,
+ ),
+ ]}
+ elementColors={{
+ textColor: action.destructive
+ ? colors.destructive
+ : colors.textPrimary,
+ disabledTextColor: colors.textTertiary,
+ }}
+ onClick={() => choose(action)}
+ >
+ <DropdownMenuItem.Text>
+ <Column>
+ <Text
+ style={{
+ fontSize: typeScale.body,
+ lineHeight: lineHeight.body,
+ fontWeight: fontWeight.regular,
+ }}
+ >
+ {action.title}
+ </Text>
+ {action.subtitle ? (
+ <Text
+ color={colors.textSecondary}
+ style={{
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ }}
+ >
+ {action.subtitle}
+ </Text>
+ ) : null}
+ </Column>
+ </DropdownMenuItem.Text>
+ {action.subactions?.length ? (
+ <DropdownMenuItem.TrailingIcon>
+ <Text>›</Text>
+ </DropdownMenuItem.TrailingIcon>
+ ) : null}
+ </DropdownMenuItem>
+ ),
+ )}
+ </Fragment>
+ ))}
+ </DropdownMenu.Items>
+ </DropdownMenu>
+ </Host>
+ </View>
+ ) : null}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/platform/chrome/NativePullDownMenu.tsx b/apps/mobile/src/platform/chrome/NativePullDownMenu.tsx
index 89f001392e..7cc784bc27 100644
--- a/apps/mobile/src/platform/chrome/NativePullDownMenu.tsx
+++ b/apps/mobile/src/platform/chrome/NativePullDownMenu.tsx
@@ -28,7 +28,7 @@ let nativePullDownAvailable: boolean | null = null;
/**
* 是否用「贴着触发控件弹出」的菜单:iOS 在包里编进 MenuView 时用系统 UIMenu(没冷更前
- * 自动退回调用方的自绘面板);Android 始终用 Cindy 自绘的 AnchoredPullDownMenu。
+ * 自动退回调用方的自绘面板);Android 用 Compose DropdownMenu 的平台实现。
*/
export function usesNativePullDownMenu(): boolean {
if (Platform.OS === "android") return true;
@@ -101,8 +101,8 @@ function childDisabled(children: ReactNode): boolean {
}
/**
- * 收起时完全是调用方原来的按钮/标题;iOS 点开是系统 UIMenu 下拉,Android 是 Cindy 自绘
- * 的同交互菜单(AnchoredPullDownMenu)。iOS 尚未编进 MenuView 的包只渲染 children,
+ * 收起时完全是调用方原来的按钮/标题;iOS 点开是系统 UIMenu 下拉,Android 是 Material
+ * 下拉菜单(AnchoredPullDownMenu.android)。iOS 尚未编进 MenuView 的包只渲染 children,
* 由调用方继续走自绘面板。
*/
export function NativePullDownMenu({
diff --git a/apps/mobile/src/session/AccountSwitcherSheet.tsx b/apps/mobile/src/session/AccountSwitcherSheet.tsx
index f20e257b22..396f36c41b 100644
--- a/apps/mobile/src/session/AccountSwitcherSheet.tsx
+++ b/apps/mobile/src/session/AccountSwitcherSheet.tsx
@@ -185,7 +185,7 @@ function AccountSwitcherContainer({ visible, onClosed, children, ...surface }: S
visible={visible} onClose={surface.onClose} onClosed={onClosed}
title={surface.title} footer={surface.footer} testID={surface.testID}
>{children}</ComposerSheet>;
- return <SheetModal visible={visible} onRequestClose={surface.onClose}
+ return <SheetModal nativePresentation visible={visible} onRequestClose={surface.onClose}
onBackdropPress={surface.onClose} onClosed={onClosed} backdropTestID="accountSwitcher.backdrop">
<SheetSurface {...surface}>{children}</SheetSurface>
</SheetModal>;
diff --git a/apps/mobile/src/session/HtmlBrowserChrome.tsx b/apps/mobile/src/session/HtmlBrowserChrome.tsx
index d8013e0e97..f802ebe3cb 100644
--- a/apps/mobile/src/session/HtmlBrowserChrome.tsx
+++ b/apps/mobile/src/session/HtmlBrowserChrome.tsx
@@ -191,6 +191,7 @@ export function HtmlBrowserChrome(p: HtmlBrowserChromeProps) {
)}
</View>
<SheetModal
+ nativePresentation
visible={menuOpen}
onBackdropPress={close}
onRequestClose={close}
diff --git a/apps/mobile/src/session/MessageActionSheet.tsx b/apps/mobile/src/session/MessageActionSheet.tsx
index d930133ce0..c901bd6453 100644
--- a/apps/mobile/src/session/MessageActionSheet.tsx
+++ b/apps/mobile/src/session/MessageActionSheet.tsx
@@ -64,6 +64,7 @@ export function MessageActionSheet({
return (
<SheetModal
+ nativePresentation
backdropTestID="message.actions.backdrop"
onBackdropPress={closeWithoutAction}
onClosed={handleClosed}
diff --git a/apps/mobile/src/session/NativeBottomSheet.android.tsx b/apps/mobile/src/session/NativeBottomSheet.android.tsx
new file mode 100644
index 0000000000..c76d0c8dfe
--- /dev/null
+++ b/apps/mobile/src/session/NativeBottomSheet.android.tsx
@@ -0,0 +1,96 @@
+import {
+ Host,
+ ModalBottomSheet,
+ RNHostView,
+ type ModalBottomSheetRef,
+} from "@expo/ui/jetpack-compose";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useWindowDimensions } from "react-native";
+import { GestureHandlerRootView } from "@/platform/gestureHandler";
+import { PaneViewportProvider } from "@/platform/AdaptiveWindowContext";
+import { useTheme } from "@/theme";
+import { NativeSheetContext } from "./NativeSheetContext";
+import type { NativeBottomSheetProps } from "./NativeBottomSheet";
+
+/** Used for single-level sheets; nested Back/draft-veto sheets keep their existing modal contract. */
+export function NativeBottomSheet({
+ visible,
+ onClose,
+ onClosed,
+ children,
+}: NativeBottomSheetProps) {
+ const { colors, mode } = useTheme();
+ const window = useWindowDimensions();
+ const width = Math.min(window.width, 640);
+ const height = window.height * 0.85;
+ const sheet = useRef<ModalBottomSheetRef>(null);
+ const [mounted, setMounted] = useState(visible);
+ const visibleRef = useRef(visible);
+ visibleRef.current = visible;
+ const onClosedRef = useRef(onClosed);
+ onClosedRef.current = onClosed;
+ const wasMounted = useRef(mounted);
+ useEffect(() => {
+ if (visible) {
+ setMounted(true);
+ return;
+ }
+ let cancelled = false;
+ const closing = sheet.current;
+ void closing?.hide().then(() => {
+ if (!cancelled) setMounted(false);
+ else if (visibleRef.current && sheet.current === closing)
+ void closing.expand();
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [visible]);
+ useEffect(() => {
+ const closed = wasMounted.current && !mounted;
+ wasMounted.current = mounted;
+ if (closed && !visible) {
+ const frame = requestAnimationFrame(() => onClosedRef.current?.());
+ return () => cancelAnimationFrame(frame);
+ }
+ }, [mounted, visible]);
+ const context = useMemo(
+ () => ({
+ height,
+ expand: () => {
+ void sheet.current?.expand();
+ },
+ }),
+ [height],
+ );
+ if (!mounted) return null;
+ return (
+ <Host
+ colorScheme={mode}
+ seedColor={colors.textPrimary}
+ style={{ position: "absolute", width }}
+ >
+ <ModalBottomSheet
+ ref={sheet}
+ skipPartiallyExpanded
+ containerColor={colors.surfaceElevated}
+ contentColor={colors.textPrimary}
+ scrimColor={colors.overlay}
+ onDismissRequest={() => {
+ setMounted(false);
+ onClose();
+ }}
+ >
+ <RNHostView matchContents>
+ <GestureHandlerRootView style={{ maxHeight: height }}>
+ <PaneViewportProvider value={{ width, height }}>
+ <NativeSheetContext.Provider value={context}>
+ {children}
+ </NativeSheetContext.Provider>
+ </PaneViewportProvider>
+ </GestureHandlerRootView>
+ </RNHostView>
+ </ModalBottomSheet>
+ </Host>
+ );
+}
diff --git a/apps/mobile/src/session/NativeBottomSheet.tsx b/apps/mobile/src/session/NativeBottomSheet.tsx
new file mode 100644
index 0000000000..ff2b954988
--- /dev/null
+++ b/apps/mobile/src/session/NativeBottomSheet.tsx
@@ -0,0 +1,10 @@
+import type { ReactNode } from "react";
+export interface NativeBottomSheetProps {
+ visible: boolean;
+ onClose(): void;
+ onClosed?: () => void;
+ children: ReactNode;
+}
+export function NativeBottomSheet(_props: NativeBottomSheetProps) {
+ return null;
+}
diff --git a/apps/mobile/src/session/NativePermissionSheet.tsx b/apps/mobile/src/session/NativePermissionSheet.tsx
index 6c289b8672..8c9b16e183 100644
--- a/apps/mobile/src/session/NativePermissionSheet.tsx
+++ b/apps/mobile/src/session/NativePermissionSheet.tsx
@@ -50,6 +50,7 @@ export function NativePermissionSheet(props: NativePermissionSheetProps) {
}, [props.visible]);
return (
<SheetModal
+ nativePresentation
backdropTestID={props.testID ? `${props.testID}.backdrop` : undefined}
onBackdropPress={props.onClose}
onClosed={() => {
diff --git a/apps/mobile/src/session/NativeSheetContext.ts b/apps/mobile/src/session/NativeSheetContext.ts
new file mode 100644
index 0000000000..457dc3fe6b
--- /dev/null
+++ b/apps/mobile/src/session/NativeSheetContext.ts
@@ -0,0 +1,7 @@
+import { createContext } from "react";
+
+/** Present only inside a Material sheet; its dialog owns gestures and detents. */
+export const NativeSheetContext = createContext<{
+ expand(): void;
+ height: number;
+} | null>(null);
diff --git a/apps/mobile/src/session/NewTaskSelectionRow.tsx b/apps/mobile/src/session/NewTaskSelectionRow.tsx
new file mode 100644
index 0000000000..e6569cc757
--- /dev/null
+++ b/apps/mobile/src/session/NewTaskSelectionRow.tsx
@@ -0,0 +1,102 @@
+import type { ReactNode } from "react";
+import { Pressable, View } from "react-native";
+import { Check } from "lucide-react-native";
+import { Text } from "@/components/AppText";
+import {
+ iconSize,
+ iconStroke,
+ lineHeight,
+ spacing,
+ typeScale,
+ useTheme,
+} from "@/theme";
+
+/** RN content shared by the Android device, workspace and directory pickers. */
+export function NewTaskSelectionRow({
+ title,
+ subtitle,
+ value,
+ leading,
+ trailing,
+ selected,
+ disabled,
+ onPress,
+ testID,
+}: {
+ title: string;
+ subtitle?: string;
+ value?: string;
+ leading?: ReactNode;
+ trailing?: ReactNode;
+ selected?: boolean;
+ disabled?: boolean;
+ onPress(): void;
+ testID?: string;
+}) {
+ const { colors } = useTheme();
+ return (
+ <Pressable
+ accessible
+ accessibilityRole="button"
+ accessibilityLabel={[title, subtitle, value].filter(Boolean).join(", ")}
+ accessibilityState={{ selected: !!selected, disabled: !!disabled }}
+ disabled={disabled}
+ onPress={onPress}
+ testID={testID}
+ style={({ pressed }) => ({
+ flexDirection: "row",
+ alignItems: "center",
+ padding: spacing.md,
+ minHeight: 56,
+ gap: spacing.sm,
+ opacity: disabled ? 0.5 : pressed ? 0.6 : 1,
+ })}
+ >
+ {leading}
+ <View style={{ flex: 1, minWidth: 0 }}>
+ <Text
+ numberOfLines={2}
+ style={{
+ color: colors.textPrimary,
+ fontSize: typeScale.body,
+ lineHeight: lineHeight.body,
+ }}
+ >
+ {title}
+ </Text>
+ {subtitle ? (
+ <Text
+ style={{
+ color: colors.textSecondary,
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ }}
+ >
+ {subtitle}
+ </Text>
+ ) : null}
+ </View>
+ {value ? (
+ <Text
+ numberOfLines={1}
+ style={{
+ maxWidth: "45%",
+ color: colors.textSecondary,
+ fontSize: typeScale.bodySmall,
+ lineHeight: lineHeight.bodySmall,
+ }}
+ >
+ {value}
+ </Text>
+ ) : null}
+ {selected ? (
+ <Check
+ color={colors.textPrimary}
+ size={iconSize.lg}
+ strokeWidth={iconStroke.medium}
+ />
+ ) : null}
+ {trailing}
+ </Pressable>
+ );
+}
diff --git a/apps/mobile/src/session/NewTaskSelectionSheet.android.tsx b/apps/mobile/src/session/NewTaskSelectionSheet.android.tsx
new file mode 100644
index 0000000000..572551208b
--- /dev/null
+++ b/apps/mobile/src/session/NewTaskSelectionSheet.android.tsx
@@ -0,0 +1,241 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { ActivityIndicator, View, useWindowDimensions } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { useTranslation } from "react-i18next";
+import {
+ ArrowUp,
+ ChevronRight,
+ Folder,
+ FolderPlus,
+ Laptop,
+ MessageCircle,
+} from "lucide-react-native";
+import { Text } from "@/components/AppText";
+import { NewTaskSelectionRow } from "@/session/NewTaskSelectionRow";
+import { NativePullDownMenu, NativeSwitch } from "@/platform/chrome";
+import { iconSize, lineHeight, spacing, typeScale, useTheme } from "@/theme";
+import { SheetModal } from "./SheetModal";
+import { SheetSurface } from "./SheetSurface";
+import { ContextSheetFooterButton } from "./ContextSheet";
+import {
+ computeContextSheetSnapHeights,
+ type ContextSheetSnap,
+} from "./contextSheetModel";
+import { newSessionText } from "./newSessionMessages";
+import type { NewTaskSelectionSheetProps } from "./NewTaskSelectionSheet";
+
+/** Same remote callbacks as iOS; the UI never reads the phone's local filesystem. */
+export function NewTaskSelectionSheet(p: NewTaskSelectionSheetProps) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const { height } = useWindowDimensions();
+ const insets = useSafeAreaInsets();
+ const browsing = p.page === "directory";
+ const nativePresentation = useRef(false);
+ // Keep the presentation kind through the closing animation, when page becomes null.
+ if (p.page !== null) nativePresentation.current = p.page === "device";
+ const unavailable = p.busy || p.loading;
+ const [snap, setSnap] = useState<ContextSheetSnap>("half");
+ useEffect(() => setSnap(browsing ? "full" : "half"), [p.page, browsing]);
+ const heights = useMemo(
+ () =>
+ computeContextSheetSnapHeights({
+ screenHeight: height,
+ safeAreaTopInset: insets.top,
+ }),
+ [height, insets.top],
+ );
+ const icon = (Icon: typeof Folder) => (
+ <Icon size={iconSize.lg} color={colors.textSecondary} />
+ );
+ const title = t(
+ p.page === "device"
+ ? "session.new.selectControlledDevice"
+ : browsing
+ ? "session.new.chooseOtherFolder"
+ : "session.new.selectWorkspace",
+ );
+ return (
+ <SheetModal
+ visible={p.page !== null}
+ nativePresentation={nativePresentation.current}
+ onBackdropPress={p.onClose}
+ onRequestClose={browsing ? p.onBack : p.onClose}
+ >
+ <SheetSurface
+ title={title}
+ onClose={p.onClose}
+ onBack={browsing ? p.onBack : undefined}
+ heights={heights}
+ snap={snap}
+ onSnapChange={setSnap}
+ bottomInset={insets.bottom}
+ testID="newSession.selectionSheet"
+ footer={
+ browsing ? (
+ <ContextSheetFooterButton
+ label={t("session.new.useCurrent")}
+ disabled={unavailable || !p.path || !!p.error}
+ onPress={() => {
+ if (p.path && !unavailable && !p.error) p.onChoose(p.path);
+ }}
+ testID="newSession.remoteBrowseSelectCurrent"
+ />
+ ) : undefined
+ }
+ >
+ {p.page === "device" ? (
+ p.devices.map((device) => (
+ <NewTaskSelectionRow
+ key={device.deviceId}
+ title={device.name || device.deviceId}
+ leading={icon(Laptop)}
+ selected={device.deviceId === p.selectedDeviceId}
+ disabled={p.busy}
+ onPress={() => p.onDevice(device.deviceId)}
+ testID="newSession.deviceOption"
+ />
+ ))
+ ) : p.page === "workspace" ? (
+ <>
+ <NewTaskSelectionRow
+ title={t("session.new.workspaceDialogue")}
+ leading={icon(MessageCircle)}
+ selected={p.workspaceKind === "dialogue"}
+ disabled={p.busy}
+ onPress={p.onDialogue}
+ testID="newSession.workspaceDialogueOption"
+ />
+ {p.workspaces.map((workspace) => (
+ <NewTaskSelectionRow
+ key={workspace.workingDir}
+ title={workspace.title}
+ subtitle={workspace.workingDir}
+ leading={icon(Folder)}
+ selected={
+ p.workspaceKind === "project" &&
+ p.workingDir.trim() === workspace.workingDir
+ }
+ disabled={p.busy}
+ onPress={() => p.onProject(workspace.workingDir)}
+ testID="newSession.workspaceProjectOption"
+ />
+ ))}
+ <NewTaskSelectionRow
+ title={t("session.new.chooseOtherFolder")}
+ leading={icon(FolderPlus)}
+ trailing={icon(ChevronRight)}
+ disabled={p.busy}
+ onPress={p.onBrowse}
+ testID="newSession.workspaceBrowseOption"
+ />
+ </>
+ ) : browsing ? (
+ <>
+ <Text
+ testID="newSession.remoteBrowseCurrentPath"
+ style={{
+ color: colors.textSecondary,
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ paddingVertical: spacing.sm,
+ }}
+ >
+ {p.path || t("session.new.readingRemoteDir")}
+ </Text>
+ <NewTaskSelectionRow
+ title={t("session.new.parentDir")}
+ leading={icon(ArrowUp)}
+ disabled={!p.parent || unavailable}
+ onPress={() => {
+ if (p.parent) p.onEnter(p.parent);
+ }}
+ testID="newSession.remoteBrowseParentButton"
+ />
+ {p.drives.length ? (
+ <NativePullDownMenu
+ disabled={unavailable}
+ actions={p.drives.map((drive) => ({
+ id: drive.path,
+ title: drive.name,
+ state: drive.current ? "on" : "off",
+ }))}
+ onAction={(path) => {
+ if (!unavailable) p.onEnter(path);
+ }}
+ testID="newSession.remoteBrowseDrivePicker"
+ >
+ <NewTaskSelectionRow
+ title={t("session.new.drive")}
+ value={p.drives.find((drive) => drive.current)?.name}
+ onPress={() => {}}
+ />
+ </NativePullDownMenu>
+ ) : null}
+ <View
+ style={{
+ flexDirection: "row",
+ alignItems: "center",
+ justifyContent: "space-between",
+ padding: spacing.md,
+ }}
+ >
+ <Text
+ style={{
+ color: colors.textPrimary,
+ fontSize: typeScale.body,
+ lineHeight: lineHeight.body,
+ }}
+ >
+ {newSessionText("showHiddenDirectories")}
+ </Text>
+ <NativeSwitch
+ accessibilityLabel={newSessionText("showHiddenDirectories")}
+ disabled={p.busy}
+ value={p.showHidden}
+ onValueChange={p.onShowHidden}
+ testID="newSession.remoteBrowseShowHidden"
+ />
+ </View>
+ {p.loading ? (
+ <ActivityIndicator color={colors.textSecondary} />
+ ) : null}
+ {p.error ? (
+ <Text
+ style={{
+ color: colors.errorText,
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ }}
+ >
+ {p.error}
+ </Text>
+ ) : null}
+ {!p.loading && !p.error && !p.entries.length ? (
+ <Text
+ style={{
+ color: colors.textSecondary,
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ }}
+ >
+ {newSessionText("emptyDirectory")}
+ </Text>
+ ) : null}
+ {p.entries.map((entry) => (
+ <NewTaskSelectionRow
+ key={entry.path}
+ title={entry.name}
+ leading={icon(Folder)}
+ trailing={icon(ChevronRight)}
+ disabled={unavailable}
+ onPress={() => p.onEnter(entry.path)}
+ testID="newSession.remoteBrowseEnterEntry"
+ />
+ ))}
+ </>
+ ) : null}
+ </SheetSurface>
+ </SheetModal>
+ );
+}
diff --git a/apps/mobile/src/session/NewTaskSelectionSheet.tsx b/apps/mobile/src/session/NewTaskSelectionSheet.tsx
index e453170234..5f29aaddc4 100644
--- a/apps/mobile/src/session/NewTaskSelectionSheet.tsx
+++ b/apps/mobile/src/session/NewTaskSelectionSheet.tsx
@@ -25,7 +25,7 @@ export interface NewTaskSelectionSheetProps {
onShowHidden(value: boolean): void;
}
-// Android retains its existing selection and directory controls.
+// Native platforms resolve their platform-specific sheet; web retains inline controls.
export function NewTaskSelectionSheet(_props: NewTaskSelectionSheetProps) {
return null;
}
diff --git a/apps/mobile/src/session/PiSessionTreeSheet.tsx b/apps/mobile/src/session/PiSessionTreeSheet.tsx
index 19977738bd..d79deea6d4 100644
--- a/apps/mobile/src/session/PiSessionTreeSheet.tsx
+++ b/apps/mobile/src/session/PiSessionTreeSheet.tsx
@@ -143,7 +143,7 @@ export function PiSessionTreeSheet({
};
return (
- <SheetModal visible={visible} onBackdropPress={onClose} onRequestClose={onClose}>
+ <SheetModal nativePresentation visible={visible} onBackdropPress={onClose} onRequestClose={onClose}>
<SheetSurface
bottomInset={insets.bottom}
heights={heights}
diff --git a/apps/mobile/src/session/SessionActionSheet.tsx b/apps/mobile/src/session/SessionActionSheet.tsx
index 4e920b1173..3c9b75807b 100644
--- a/apps/mobile/src/session/SessionActionSheet.tsx
+++ b/apps/mobile/src/session/SessionActionSheet.tsx
@@ -1,28 +1,9 @@
-import { TaskMenuHeading, TaskTagsPanel } from './TaskTags';
-import { GestureHandlerRootView } from '@/platform/gestureHandler';
-import type { RemoteSession } from './types';
-/**
- * SessionActionSheet —— 首页会话行左滑「选项」触发的底部操作菜单
- * (重命名 / 置顶切换 / 归档 / 删除 + 独立「取消」)。
- *
- * iOS 走 Expo UI BottomSheet,不挂本组件。本文件只服务 Android。
- *
- * 刻意不用 SheetSurface:它是内容型 snap 面板(half/full 档位 + 把手拖拽),
- * 五行固定菜单套进去要伪造档位状态。这里沿用 DeviceMenuModal 的轻量模式:
- * 单 Modal + 自绘动画(overlay 淡入、卡片 translateY 滑入),关闭动画播完才真正
- * 卸载,并经 onClosed 通知父级 —— 兄弟 Modal(重命名弹窗)必须等本 Modal 卸载后
- * 再挂,否则 Android 叠 Dialog / 旧 iOS 路径 present-during-dismiss 会把新弹窗吞掉。
- * 视觉(圆角卡片分组 / 行高 / 危险色)对齐会话详情页 SessionMenuSheet 的 actionGroup。
- */
-import { useEffect, useRef, useState } from "react";
-import {
- Animated,
- Easing,
- Modal,
- Pressable,
- StyleSheet,
- View,
-} from "react-native";
+import { TaskMenuHeading, TaskTagsPanel } from "./TaskTags";
+import { SessionActionSheetFrame } from "./SessionActionSheetFrame";
+import type { RemoteSession } from "./types";
+/** Task actions share content; Android presents them in a Compose bottom sheet. */
+import { useEffect, useState } from "react";
+import { Platform, Pressable, StyleSheet, View } from "react-native";
import {
Archive,
ArchiveRestore,
@@ -32,7 +13,6 @@ import {
Trash2,
type LucideIcon,
} from "lucide-react-native";
-import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useTranslation } from "react-i18next";
import { Text } from "@/components/AppText";
import { BlurBackdrop } from "@/session/BlurBackdrop";
@@ -50,16 +30,10 @@ import {
import {
fontWeight,
lineHeight,
- motionDuration,
- motionEasing,
radius,
spacing,
typeScale,
} from "@/theme/tokens";
-import { useReduceMotionEnabled } from "@/hooks/useReduceMotion";
-
-/** 卡片滑入距离(略大于卡片实高即可,滑入曲线吃掉误差)。 */
-const CARD_SLIDE_DISTANCE = 360;
const ACTION_ICONS: Record<SessionSwipeAction, LucideIcon> = {
archive: Archive,
@@ -96,199 +70,148 @@ export function SessionActionSheet({
}, [visible]);
const { colors } = useTheme();
const { t } = useTranslation();
- const insets = useSafeAreaInsets();
- const [mounted, setMounted] = useState(visible);
- const progress = useRef(new Animated.Value(visible ? 1 : 0)).current;
- // 只有明确 === false 才播动画;null(尚未查到)/ true 一律直接显示 / 隐藏。
- const animate = useReduceMotionEnabled() === false;
-
- useEffect(() => {
- if (visible) {
- setMounted(true);
- if (!animate) {
- progress.setValue(1);
- return;
- }
- Animated.timing(progress, {
- duration: motionDuration.enter,
- easing: Easing.bezier(...motionEasing.out),
- toValue: 1,
- useNativeDriver: true,
- }).start();
- } else {
- if (!animate) {
- progress.setValue(0);
- setMounted(false);
- return;
- }
- Animated.timing(progress, {
- duration: motionDuration.exit,
- easing: Easing.bezier(...motionEasing.in),
- toValue: 0,
- useNativeDriver: true,
- }).start(({ finished }) => {
- if (finished) setMounted(false);
- });
- }
- }, [animate, visible, progress]);
-
- // onClosed 等 Modal 真正从树上卸载后再触发(同 DeviceMenuModal:动画回调里同步挂
- // 第二个 Modal 会和本 Modal 的卸载挤进同一个 commit,iOS 可能吞掉新弹窗)。
- const onClosedRef = useRef(onClosed);
- onClosedRef.current = onClosed;
- const wasMountedRef = useRef(mounted);
- useEffect(() => {
- const wasMounted = wasMountedRef.current;
- wasMountedRef.current = mounted;
- if (wasMounted && !mounted) onClosedRef.current?.();
- }, [mounted]);
-
- const translateY = progress.interpolate({
- inputRange: [0, 1],
- outputRange: [CARD_SLIDE_DISTANCE, 0],
- });
+ const nativeSheet = Platform.OS === "android";
const menu = buildSessionActionMenu(pinnedAt, status);
return (
- <Modal
- supportedOrientations={["portrait", "portrait-upside-down", "landscape-left", "landscape-right"]}
- animationType="none"
- onRequestClose={onClose}
- transparent
- visible={mounted}
+ <SessionActionSheetFrame
+ visible={visible}
+ onClose={onClose}
+ onClosed={onClosed}
>
- <GestureHandlerRootView style={styles.overlay}>
- <Animated.View style={[StyleSheet.absoluteFill, { opacity: progress }]}>
- <BlurBackdrop />
- <Pressable
- accessibilityLabel={t("session.row.closeActionMenu")}
- onPress={onClose}
- style={styles.backdrop}
- testID="home.sessionActions.backdrop"
+ <View style={[styles.actionCard, nativeSheet && styles.nativeCard]}>
+ {!nativeSheet && (
+ <BlurBackdrop
+ intensity={32}
+ overlayColor={colors.sheetActionSurface}
+ />
+ )}
+ {session && <TaskMenuHeading session={session} />}
+ {!tagsExpanded &&
+ menu
+ .filter(
+ (item) =>
+ !item.destructive &&
+ item.action !== "archive" &&
+ item.action !== "restore",
+ )
+ .map((item) => {
+ const IconComponent = ACTION_ICONS[item.action];
+ const color = item.destructive
+ ? colors.destructive
+ : colors.textPrimary;
+ return (
+ <Pressable
+ accessibilityLabel={item.label}
+ accessibilityRole="button"
+ key={item.action}
+ onPress={() => onAction(item.action)}
+ style={({ pressed }) => [
+ styles.actionRow,
+ pressed && styles.pressed,
+ ]}
+ testID={`home.sessionActions.${item.action}`}
+ >
+ <IconComponent
+ color={color}
+ size={iconSize.lg}
+ strokeWidth={iconStroke.regular}
+ />
+ <Text
+ numberOfLines={1}
+ style={[
+ styles.actionLabel,
+ item.destructive && styles.actionLabelDanger,
+ ]}
+ >
+ {item.label}
+ </Text>
+ </Pressable>
+ );
+ })}
+ {visible && session && (
+ <TaskTagsPanel
+ key={`${session.canonicalDeviceId ?? session.deviceLinkDeviceId}:${session.id}`}
+ session={session}
+ expanded={tagsExpanded}
+ onExpandedChange={setTagsExpanded}
/>
- </Animated.View>
- <Animated.View
- style={[
- styles.cardArea,
- {
- paddingBottom: Math.max(insets.bottom, spacing.md),
- transform: [{ translateY }],
- },
- ]}
- testID="home.sessionActions"
- >
- <View style={styles.actionCard}>
- <BlurBackdrop intensity={32} overlayColor={colors.sheetActionSurface} />
- {session && <TaskMenuHeading session={session} />}
- {!tagsExpanded &&
- menu
- .filter(
- (item) =>
- !item.destructive && item.action !== 'archive' && item.action !== 'restore',
- )
- .map((item) => {
- const IconComponent = ACTION_ICONS[item.action];
- const color = item.destructive ? colors.destructive : colors.textPrimary;
- return (
- <Pressable
- accessibilityLabel={item.label}
- accessibilityRole="button"
- key={item.action}
- onPress={() => onAction(item.action)}
- style={({ pressed }) => [styles.actionRow, pressed && styles.pressed]}
- testID={`home.sessionActions.${item.action}`}
- >
- <IconComponent
- color={color}
- size={iconSize.lg}
- strokeWidth={iconStroke.regular}
- />
- <Text
- numberOfLines={1}
- style={[styles.actionLabel, item.destructive && styles.actionLabelDanger]}
- >
- {item.label}
- </Text>
- </Pressable>
- );
- })}
- {visible && session && (
- <TaskTagsPanel
- key={`${session.canonicalDeviceId ?? session.deviceLinkDeviceId}:${session.id}`}
- session={session}
- expanded={tagsExpanded}
- onExpandedChange={setTagsExpanded}
- />
- )}
- {!tagsExpanded &&
- menu
- .filter(
- (item) =>
- item.destructive || item.action === 'archive' || item.action === 'restore',
- )
- .map((item) => {
- const IconComponent = ACTION_ICONS[item.action];
- const color = item.destructive ? colors.destructive : colors.textPrimary;
- return (
- <Pressable
- accessibilityLabel={item.label}
- accessibilityRole="button"
- key={item.action}
- onPress={() => onAction(item.action)}
- style={({ pressed }) => [styles.actionRow, pressed && styles.pressed]}
- testID={`home.sessionActions.${item.action}`}
- >
- <IconComponent
- color={color}
- size={iconSize.lg}
- strokeWidth={iconStroke.regular}
- />
- <Text
- numberOfLines={1}
- style={[styles.actionLabel, item.destructive && styles.actionLabelDanger]}
- >
- {item.label}
- </Text>
- </Pressable>
- );
- })}
- </View>
- <Pressable
- accessibilityLabel={t("session.common.cancel")}
- accessibilityRole="button"
- onPress={onClose}
- style={({ pressed }) => [
- styles.cancelCard,
- pressed && styles.pressed,
- ]}
- testID="home.sessionActions.cancel"
- >
- <BlurBackdrop
- intensity={32}
- overlayColor={colors.sheetActionSurface}
- />
- <Text style={styles.cancelText}>{t("session.common.cancel")}</Text>
- </Pressable>
- </Animated.View>
- </GestureHandlerRootView>
- </Modal>
+ )}
+ {!tagsExpanded &&
+ menu
+ .filter(
+ (item) =>
+ item.destructive ||
+ item.action === "archive" ||
+ item.action === "restore",
+ )
+ .map((item) => {
+ const IconComponent = ACTION_ICONS[item.action];
+ const color = item.destructive
+ ? colors.destructive
+ : colors.textPrimary;
+ return (
+ <Pressable
+ accessibilityLabel={item.label}
+ accessibilityRole="button"
+ key={item.action}
+ onPress={() => onAction(item.action)}
+ style={({ pressed }) => [
+ styles.actionRow,
+ pressed && styles.pressed,
+ ]}
+ testID={`home.sessionActions.${item.action}`}
+ >
+ <IconComponent
+ color={color}
+ size={iconSize.lg}
+ strokeWidth={iconStroke.regular}
+ />
+ <Text
+ numberOfLines={1}
+ style={[
+ styles.actionLabel,
+ item.destructive && styles.actionLabelDanger,
+ ]}
+ >
+ {item.label}
+ </Text>
+ </Pressable>
+ );
+ })}
+ </View>
+ <Pressable
+ accessibilityLabel={t("session.common.cancel")}
+ accessibilityRole="button"
+ onPress={onClose}
+ style={({ pressed }) => [
+ styles.cancelCard,
+ nativeSheet && styles.nativeCancel,
+ pressed && styles.pressed,
+ ]}
+ testID="home.sessionActions.cancel"
+ >
+ {!nativeSheet && (
+ <BlurBackdrop
+ intensity={32}
+ overlayColor={colors.sheetActionSurface}
+ />
+ )}
+ <Text style={styles.cancelText}>{t("session.common.cancel")}</Text>
+ </Pressable>
+ </SessionActionSheetFrame>
);
}
const makeStyles = (colors: ThemeColors) =>
StyleSheet.create({
- overlay: {
- flex: 1,
- justifyContent: "flex-end",
- },
- backdrop: {
- // 背板玻璃色由 BlurBackdrop 承担(absoluteFill 在本 Pressable 之下);Pressable 透明,
- // 仅占触摸区接收点按关闭。
- flex: 1,
+ nativeCard: {
+ borderWidth: 0,
},
- cardArea: {
- gap: spacing.sm,
- paddingHorizontal: spacing.md,
+ nativeCancel: {
+ backgroundColor: colors.surfaceChip,
+ borderWidth: 0,
+ borderRadius: radius.pill,
},
actionCard: {
backgroundColor: "transparent",
diff --git a/apps/mobile/src/session/SessionActionSheetFrame.android.tsx b/apps/mobile/src/session/SessionActionSheetFrame.android.tsx
new file mode 100644
index 0000000000..f85efc335d
--- /dev/null
+++ b/apps/mobile/src/session/SessionActionSheetFrame.android.tsx
@@ -0,0 +1,105 @@
+import {
+ Host,
+ ModalBottomSheet,
+ RNHostView,
+ type ModalBottomSheetRef,
+} from "@expo/ui/jetpack-compose";
+import { useEffect, useRef, useState } from "react";
+import { ScrollView, StyleSheet, useWindowDimensions } from "react-native";
+import { GestureHandlerRootView } from "@/platform/gestureHandler";
+import { useTheme } from "@/theme";
+import { spacing } from "@/theme/tokens";
+import type { SessionActionSheetFrameProps } from "./SessionActionSheetFrame";
+
+/** Native dialog owns dragging, the scrim, Back and its dismiss animation. */
+export function SessionActionSheetFrame({
+ visible,
+ onClose,
+ onClosed,
+ children,
+}: SessionActionSheetFrameProps) {
+ const { colors, mode } = useTheme();
+ const { height, width } = useWindowDimensions();
+ const sheet = useRef<ModalBottomSheetRef>(null);
+ const [mounted, setMounted] = useState(visible);
+ const visibleRef = useRef(visible);
+ visibleRef.current = visible;
+ const onClosedRef = useRef(onClosed);
+ onClosedRef.current = onClosed;
+ const wasMounted = useRef(mounted);
+
+ useEffect(() => {
+ if (visible) {
+ setMounted(true);
+ return;
+ }
+ let cancelled = false;
+ // hide resolves after the native animation; never use a guessed timer.
+ const closingSheet = sheet.current;
+ void closingSheet?.hide().then(() => {
+ if (!cancelled) setMounted(false);
+ else if (visibleRef.current && sheet.current === closingSheet) {
+ // A new open can overtake hide(); restore the existing native dialog.
+ void closingSheet.expand();
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [visible]);
+
+ useEffect(() => {
+ const closed = wasMounted.current && !mounted;
+ wasMounted.current = mounted;
+ // Let the native unmount commit reach the UI thread before presenting a
+ // sibling dialog; presenting in this effect can leave RN Modal invisible.
+ if (closed && !visible) {
+ const frame = requestAnimationFrame(() => onClosedRef.current?.());
+ return () => cancelAnimationFrame(frame);
+ }
+ }, [mounted, visible]);
+
+ if (!mounted) return null;
+ return (
+ <Host
+ colorScheme={mode}
+ seedColor={colors.textPrimary}
+ // Material's modal sheet caps its width at 640dp on wide windows. Match
+ // the RN layout root to it so embedded actions cannot extend off-sheet.
+ style={[styles.host, { width: Math.min(width, 640) }]}
+ >
+ <ModalBottomSheet
+ ref={sheet}
+ skipPartiallyExpanded
+ containerColor={colors.surfaceElevated}
+ contentColor={colors.textPrimary}
+ scrimColor={colors.overlay}
+ onDismissRequest={() => {
+ setMounted(false);
+ onClose();
+ }}
+ >
+ <RNHostView matchContents>
+ <GestureHandlerRootView style={{ maxHeight: height * 0.8 }}>
+ <ScrollView
+ keyboardShouldPersistTaps="handled"
+ contentContainerStyle={styles.content}
+ testID="home.sessionActions"
+ >
+ {children}
+ </ScrollView>
+ </GestureHandlerRootView>
+ </RNHostView>
+ </ModalBottomSheet>
+ </Host>
+ );
+}
+
+const styles = StyleSheet.create({
+ host: { position: "absolute" },
+ content: {
+ paddingHorizontal: spacing.md,
+ paddingBottom: spacing.md,
+ gap: spacing.sm,
+ },
+});
diff --git a/apps/mobile/src/session/SessionActionSheetFrame.tsx b/apps/mobile/src/session/SessionActionSheetFrame.tsx
new file mode 100644
index 0000000000..f06c687854
--- /dev/null
+++ b/apps/mobile/src/session/SessionActionSheetFrame.tsx
@@ -0,0 +1,108 @@
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import { Animated, Easing, Modal, Pressable, StyleSheet } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { useTranslation } from "react-i18next";
+import { GestureHandlerRootView } from "@/platform/gestureHandler";
+import { BlurBackdrop } from "@/session/BlurBackdrop";
+import { spacing } from "@/theme/tokens";
+
+export interface SessionActionSheetFrameProps {
+ visible: boolean;
+ onClose(): void;
+ onClosed?(): void;
+ children: ReactNode;
+}
+
+/** Compatibility presentation; Android resolves the Compose implementation. */
+export function SessionActionSheetFrame({
+ visible,
+ onClose,
+ onClosed,
+ children,
+}: SessionActionSheetFrameProps) {
+ const { t } = useTranslation();
+ const insets = useSafeAreaInsets();
+ const [mounted, setMounted] = useState(visible);
+ const progress = useRef(new Animated.Value(visible ? 1 : 0)).current;
+
+ useEffect(() => {
+ if (visible) {
+ setMounted(true);
+ Animated.timing(progress, {
+ duration: 220,
+ easing: Easing.out(Easing.cubic),
+ toValue: 1,
+ useNativeDriver: true,
+ }).start();
+ } else {
+ Animated.timing(progress, {
+ duration: 160,
+ easing: Easing.in(Easing.quad),
+ toValue: 0,
+ useNativeDriver: true,
+ }).start(({ finished }) => {
+ if (finished) setMounted(false);
+ });
+ }
+ }, [visible, progress]);
+
+ // onClosed 等 Modal 真正从树上卸载后再触发(同 DeviceMenuModal:动画回调里同步挂
+ // 第二个 Modal 会和本 Modal 的卸载挤进同一个 commit,iOS 可能吞掉新弹窗)。
+ const onClosedRef = useRef(onClosed);
+ onClosedRef.current = onClosed;
+ const wasMountedRef = useRef(mounted);
+ useEffect(() => {
+ const wasMounted = wasMountedRef.current;
+ wasMountedRef.current = mounted;
+ if (wasMounted && !mounted) onClosedRef.current?.();
+ }, [mounted]);
+
+ const translateY = progress.interpolate({
+ inputRange: [0, 1],
+ outputRange: [CARD_SLIDE_DISTANCE, 0],
+ });
+ return (
+ <Modal
+ supportedOrientations={[
+ "portrait",
+ "portrait-upside-down",
+ "landscape-left",
+ "landscape-right",
+ ]}
+ animationType="none"
+ onRequestClose={onClose}
+ transparent
+ visible={mounted}
+ >
+ <GestureHandlerRootView style={styles.overlay}>
+ <Animated.View style={[StyleSheet.absoluteFill, { opacity: progress }]}>
+ <BlurBackdrop />
+ <Pressable
+ accessibilityLabel={t("session.row.closeActionMenu")}
+ onPress={onClose}
+ style={styles.backdrop}
+ testID="home.sessionActions.backdrop"
+ />
+ </Animated.View>
+ <Animated.View
+ style={[
+ styles.cardArea,
+ {
+ paddingBottom: Math.max(insets.bottom, spacing.md),
+ transform: [{ translateY }],
+ },
+ ]}
+ testID="home.sessionActions"
+ >
+ {children}
+ </Animated.View>
+ </GestureHandlerRootView>
+ </Modal>
+ );
+}
+const CARD_SLIDE_DISTANCE = 360;
+const styles = StyleSheet.create({
+ overlay: { flex: 1, justifyContent: "flex-end" },
+ backdrop: { flex: 1 },
+ cardArea: { gap: spacing.sm, paddingHorizontal: spacing.md },
+});
diff --git a/apps/mobile/src/session/SheetModal.tsx b/apps/mobile/src/session/SheetModal.tsx
index 06a9d10321..1c6fe9e39d 100644
--- a/apps/mobile/src/session/SheetModal.tsx
+++ b/apps/mobile/src/session/SheetModal.tsx
@@ -1,5 +1,6 @@
import { useAdaptiveWindow, PaneViewportProvider, FloatingSheetContext } from '@/platform/AdaptiveWindowContext';
import { modalLayout } from '@/platform/modalLayout';
+import { NativeBottomSheet } from './NativeBottomSheet';
/**
* SheetModal —— 底部 sheet 共用的 Modal 外壳(背板淡入淡出 + 面板自底部滑入滑出)。
*
@@ -36,6 +37,8 @@ import { useThemedStyles, type ThemeColors } from '@/theme';
import { motionDuration } from '@/theme/tokens';
export interface SheetModalProps {
+ /** Single-level, unconditional dismissal only. Nested Back / unsaved draft veto keeps the compatibility shell. */
+ nativePresentation?: boolean;
visible: boolean;
/** Android 返回键 / iOS 关闭手势(调用方可做两段式:二级先回一级)。 */
onRequestClose: () => void;
@@ -51,7 +54,17 @@ export interface SheetModalProps {
children: ReactNode;
}
-export function SheetModal({
+export function SheetModal(props: SheetModalProps) {
+ const geometry = useAdaptiveWindow();
+ const { floating } = modalLayout(geometry, 0);
+ // Floating/hinged layouts retain pane placement rather than a full-window dialog.
+ if (Platform.OS === 'android' && props.nativePresentation && !floating && geometry.regions.length === 0) {
+ return <NativeBottomSheet visible={props.visible} onClose={props.onBackdropPress} onClosed={props.onClosed}>{props.children}</NativeBottomSheet>;
+ }
+ return <CompatibleSheetModal {...props} />;
+}
+
+function CompatibleSheetModal({
visible,
onRequestClose,
onBackdropPress,
@@ -128,6 +141,7 @@ export function SheetModal({
</Animated.View>
);
+
return (
<Modal
supportedOrientations={["portrait", "portrait-upside-down", "landscape-left", "landscape-right"]}
diff --git a/apps/mobile/src/session/SheetSurface.tsx b/apps/mobile/src/session/SheetSurface.tsx
index 9d4252ed68..d83be10f4c 100644
--- a/apps/mobile/src/session/SheetSurface.tsx
+++ b/apps/mobile/src/session/SheetSurface.tsx
@@ -1,4 +1,5 @@
-import { useContext, useMemo } from 'react';
+import { useContext, useEffect, useMemo } from 'react';
+import { NativeSheetContext } from './NativeSheetContext';
import { FloatingSheetContext, usePaneViewport } from '@/platform/AdaptiveWindowContext';
/**
* SheetSurface —— 可拖动底部浮窗的「面板表面」(从 ContextSheet 抽出,非 Modal)。
@@ -17,7 +18,7 @@ import { FloatingSheetContext, usePaneViewport } from '@/platform/AdaptiveWindow
import type { ReactNode, RefObject } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronLeft } from 'lucide-react-native';
-import { Pressable, ScrollView, View, type StyleProp, type ViewStyle } from 'react-native';
+import { Pressable, ScrollView, View, type ScrollViewProps, type StyleProp, type ViewStyle } from 'react-native';
import Animated from 'react-native-reanimated';
import { GestureDetector } from '@/platform/gestureHandler';
import { Text } from '@/components/AppText';
@@ -40,6 +41,8 @@ export interface SheetSurfaceProps {
/** header 下、滚动区上的固定插槽(如搜索框);不传不占位。 */
pinnedTop?: ReactNode;
children: ReactNode;
+ /** Replace the ScrollView for virtualized content; never nest a vertical list inside it. */
+ renderScrollContent?: (props: Pick<ScrollViewProps, 'style' | 'contentContainerStyle' | 'keyboardShouldPersistTaps' | 'testID'>) => ReactNode;
/** 固定在面板底部(滚动区之外)的操作区。 */
footer?: ReactNode;
/** 暴露内容 ScrollView(打开时滚动到选中行用);不传则内部自管。 */
@@ -65,6 +68,7 @@ export function SheetSurface({
headerTrailing,
pinnedTop,
children,
+ renderScrollContent,
footer,
scrollRef,
heights,
@@ -79,6 +83,8 @@ export function SheetSurface({
const { t } = useTranslation();
const viewport = usePaneViewport();
const floating = useContext(FloatingSheetContext);
+ const nativeSheet = useContext(NativeSheetContext);
+ useEffect(() => { if (snap === 'full') nativeSheet?.expand(); }, [snap, nativeSheet]);
const boundedHeights = useMemo(() => ({ half: Math.min(heights.half, viewport.height), full: Math.min(heights.full, viewport.height) }), [heights, viewport.height]);
const drag = useContextSheetDrag({
heights: boundedHeights,
@@ -92,20 +98,20 @@ export function SheetSurface({
style={[
styles.sheet,
variant === 'tasksheet' && styles.sheetTasksheet,
- { paddingBottom: floating ? spacing.md : bottomInset },
+ { paddingBottom: nativeSheet || floating ? spacing.md : bottomInset },
floating && { borderRadius: radius.container },
- drag.animatedStyle,
+ nativeSheet ? { height: Math.min(boundedHeights[snap], nativeSheet.height) } : drag.animatedStyle,
{ maxHeight: "100%" },
]}
testID={testID}
>
- <BlurBackdrop
+ {!nativeSheet && <BlurBackdrop
intensity={32}
overlayColor={variant === 'tasksheet' ? colors.sheetSurface : colors.surfaceGlassPanel}
- />
- <GestureDetector gesture={drag.gesture}>
- <View collapsable={false} style={styles.dragZone} {...drag.panHandlers}>
- <SheetGrabber variant={variant} />
+ />}
+ <GestureDetector gesture={drag.gesture.enabled(!nativeSheet)}>
+ <View collapsable={false} style={styles.dragZone} {...(nativeSheet ? {} : drag.panHandlers)}>
+ {!nativeSheet && <SheetGrabber variant={variant} />}
<View style={styles.header}>
{onBack ? (
<Pressable
@@ -129,7 +135,12 @@ export function SheetSurface({
</View>
</GestureDetector>
{pinnedTop ? <View style={styles.pinnedTop}>{pinnedTop}</View> : null}
- <ScrollView
+ {renderScrollContent ? renderScrollContent({
+ contentContainerStyle: styles.contentScrollContent,
+ keyboardShouldPersistTaps: 'handled',
+ style: styles.contentScroll,
+ testID: testID ? `${testID}.scroll` : undefined,
+ }) : <ScrollView
contentContainerStyle={styles.contentScrollContent}
keyboardShouldPersistTaps="handled"
ref={scrollRef}
@@ -137,7 +148,7 @@ export function SheetSurface({
testID={testID ? `${testID}.scroll` : undefined}
>
{children}
- </ScrollView>
+ </ScrollView>}
{footer ? (
<View style={styles.footer} testID={testID ? `${testID}.footer` : undefined}>
{footer}
diff --git a/apps/mobile/src/session/TaskTagsSheet.tsx b/apps/mobile/src/session/TaskTagsSheet.tsx
index ef63bc46f7..d0985be210 100644
--- a/apps/mobile/src/session/TaskTagsSheet.tsx
+++ b/apps/mobile/src/session/TaskTagsSheet.tsx
@@ -73,6 +73,7 @@ export function TaskTagsSheet({
}
return (
<SheetModal
+ nativePresentation
visible={visible}
onRequestClose={onClose}
onBackdropPress={onClose}
diff --git a/apps/mobile/src/session/UnifiedModelPickerView.tsx b/apps/mobile/src/session/UnifiedModelPickerView.tsx
index 558c145d12..41ddd22a3b 100644
--- a/apps/mobile/src/session/UnifiedModelPickerView.tsx
+++ b/apps/mobile/src/session/UnifiedModelPickerView.tsx
@@ -23,6 +23,8 @@ import {
} from "lucide-react-native";
import {
Pressable,
+ FlatList,
+ Platform,
StyleSheet,
View,
useWindowDimensions,
@@ -214,6 +216,23 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
const [page, setPage] = useState<Page>(null);
const [effortExpanded, setEffortExpanded] = useState(false);
const searchRef = useRef<RNTextInput>(null);
+ const modelListRef = useRef<FlatList>(null);
+ const modelItems = useMemo(
+ () =>
+ p.groups.flatMap((group) => [
+ { kind: "header" as const, key: `header:${group.key}`, group },
+ ...group.rows.map((row, index) => ({
+ kind: "model" as const,
+ key: `${group.key}:${row.key}`,
+ row,
+ separator: index > 0,
+ })),
+ ]),
+ [p.groups],
+ );
+ useEffect(() => {
+ modelListRef.current?.scrollToOffset({ offset: 0, animated: false });
+ }, [p.query, p.filter]);
// 与 iOS 同口径:重新打开或切换设置对象都回到主页。
useEffect(() => {
setPage(null);
@@ -642,24 +661,25 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
);
};
- 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}
- </>
- );
+ const listPage =
+ Platform.OS === "android" ? null : (
+ <>
+ {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
@@ -686,6 +706,51 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
snap={snap}
testID={p.testID}
title={title}
+ renderScrollContent={
+ Platform.OS === "android" && !page && !options
+ ? (scrollProps) => (
+ <FlatList
+ {...scrollProps}
+ ref={modelListRef}
+ data={modelItems}
+ keyExtractor={(item) => item.key}
+ initialNumToRender={8}
+ maxToRenderPerBatch={4}
+ windowSize={3}
+ removeClippedSubviews={false}
+ ListHeaderComponent={
+ p.error ? <Text style={styles.error}>{p.error}</Text> : null
+ }
+ ListEmptyComponent={
+ <Text style={styles.empty} testID={`${p.testID}.empty`}>
+ {p.loading
+ ? t("models.picker.loadingDefault")
+ : p.emptyHint}
+ </Text>
+ }
+ renderItem={({ item }) =>
+ item.kind === "header" ? (
+ <View
+ style={styles.group}
+ testID={`${p.testID}.group.${item.group.key}`}
+ >
+ <Text style={styles.groupLabel}>
+ {item.group.title}
+ </Text>
+ </View>
+ ) : (
+ <View>
+ {item.separator ? (
+ <View style={styles.separator} />
+ ) : null}
+ {modelRow(item.row)}
+ </View>
+ )
+ }
+ />
+ )
+ : undefined
+ }
>
{p.error ? <Text style={styles.error}>{p.error}</Text> : null}
{page === "sources"
diff --git a/apps/mobile/src/session/useSessionListActions.ts b/apps/mobile/src/session/useSessionListActions.ts
index bfbb362962..6529584143 100644
--- a/apps/mobile/src/session/useSessionListActions.ts
+++ b/apps/mobile/src/session/useSessionListActions.ts
@@ -146,7 +146,7 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()
setActionSheetSession(null);
if (!session) return;
if (action === 'rename' || action === 'delete') {
- // Android 自绘 Modal、iOS Expo BottomSheet、系统 Alert 都不能在 Sheet
+ // Android Compose BottomSheet、iOS Expo BottomSheet、系统 Alert 都不能在 Sheet
// dismiss 过程中再 present,否则会被吞掉或压在后面。
pendingSheetActionRef.current = () => applySessionSheetAction(session, action);
return;