Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(mobile): avoid Android home and SVG bitmap crashes (#5165)

bobo7591d0dc7126
diff --git a/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsx b/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsx
index d63576940c..7f683ec71c 100644
--- a/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsx
+++ b/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsx
@@ -18,6 +18,7 @@ import { lightColors, darkColors } from "@/theme/tokens";
const native = vi.hoisted(() => ({
os: "ios",
+ density: 1,
nextId: 0,
svgLoads: new Map<number, () => void>(),
imageLoads: new Map<string, () => void>(),
@@ -56,6 +57,7 @@ vi.mock("react-native", async () => {
);
return {
Image,
+ PixelRatio: { get: () => native.density },
Platform: {
get OS() {
return native.os;
@@ -91,9 +93,9 @@ vi.mock("react-native-svg", async () => {
createElement("span", null, children);
return {
default: forwardRef(
- ({ children }: { children?: import("react").ReactNode }, ref) => {
+ ({ children, height, width }: { children?: import("react").ReactNode; height: number; width: number }, ref) => {
useImperativeHandle(ref, () => ({ toDataURL: native.capture }), []);
- return createElement("section", { "data-svg": "true" }, children);
+ return createElement("section", { "data-svg": "true", "data-height": height, "data-width": width }, children);
},
),
ClipPath: element,
@@ -174,6 +176,7 @@ beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
native.os = "ios";
+ native.density = 1;
native.svgLoads.clear();
native.imageLoads.clear();
native.imageErrors.clear();
@@ -195,14 +198,18 @@ afterEach(async () => {
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
-function render(width = 390, dark = false) {
+function render(
+ width = 390,
+ dark = false,
+ messages: readonly ConversationShareMessage[] = [message],
+) {
const colors = dark ? darkColors : lightColors;
root.render(
<StrictMode>
<ConversationShareSvg
ref={ref}
- messages={[message]}
- allShareableIds={["m"]}
+ messages={messages}
+ allShareableIds={messages.map((entry) => entry.clientId)}
colors={{
...colors,
dark,
@@ -242,6 +249,23 @@ async function start() {
}
describe("SVG export lifecycle", () => {
+ it("keeps a tall Android conversation below the physical bitmap limit", async () => {
+ native.os = "android";
+ native.density = 3;
+ const messages = Array.from({ length: 100 }, (_, index) => ({
+ clientId: `long-${index}`,
+ kind: "assistant" as const,
+ body: "A message in a long conversation",
+ }));
+ await act(async () => render(390, false, messages));
+ const svg = host.querySelector<HTMLElement>('[data-svg="true"]')!;
+ const width = Number(svg.dataset.width);
+ const height = Number(svg.dataset.height);
+ expect(height).toBeGreaterThan(2_500);
+ expect(height).toBeGreaterThan(width * 8);
+ expect(width * height * native.density ** 2).toBeLessThanOrEqual(12_000_000);
+ });
+
it.each([false, true])(
"waits for each cold iOS occurrence, then captures once after native layout (dark=%s)",
async (dark) => {
diff --git a/apps/mobile/src/__tests__/conversationShareSvg.test.ts b/apps/mobile/src/__tests__/conversationShareSvg.test.ts
index 4c3b39557d..07b754e034 100644
--- a/apps/mobile/src/__tests__/conversationShareSvg.test.ts
+++ b/apps/mobile/src/__tests__/conversationShareSvg.test.ts
@@ -497,4 +497,12 @@ describe("ConversationShareSvg", () => {
conversationShareSvgRenderSize({ height: 40_000, width: 390 }),
).toEqual({ height: 1, scale: 1, sourceTooLarge: true, width: 1 });
});
+
+ it("limits Android SVG bitmaps by physical pixels on high density screens", () => {
+ const layout = { height: 6_000, width: 390 };
+ const renderSize = conversationShareSvgRenderSize(layout, 3);
+ expect(renderSize.sourceTooLarge).toBe(false);
+ expect(renderSize.width * renderSize.height * 3 ** 2).toBeLessThanOrEqual(12_000_000);
+ expect(renderSize.width).toBeLessThan(conversationShareSvgRenderSize(layout).width);
+ });
});
diff --git a/apps/mobile/src/__tests__/optionalHeaderHeight.test.tsx b/apps/mobile/src/__tests__/optionalHeaderHeight.test.tsx
new file mode 100644
index 0000000000..947d36149f
--- /dev/null
+++ b/apps/mobile/src/__tests__/optionalHeaderHeight.test.tsx
@@ -0,0 +1,33 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot } from 'react-dom/client';
+import { expect, it, vi } from 'vitest';
+
+vi.mock('expo-router/react-navigation', async () => {
+ const { createContext } = await import('react');
+ return { HeaderHeightContext: createContext<number | undefined>(undefined) };
+});
+
+import { HeaderHeightContext } from 'expo-router/react-navigation';
+import { useOptionalHeaderHeight } from '@/session/useOptionalHeaderHeight';
+
+it('allows the embedded home to render without a navigation header and reads the native height when present', async () => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ const root = createRoot(document.createElement('div'));
+ let height = -1;
+ function Probe() {
+ height = useOptionalHeaderHeight();
+ return null;
+ }
+ try {
+ await act(async () => root.render(createElement(Probe)));
+ expect(height).toBe(0);
+
+ await act(async () =>
+ root.render(createElement(HeaderHeightContext.Provider, { value: 82 }, createElement(Probe))),
+ );
+ expect(height).toBe(82);
+ } finally {
+ await act(async () => root.unmount());
+ }
+});
diff --git a/apps/mobile/src/session/ConversationShareSvg.tsx b/apps/mobile/src/session/ConversationShareSvg.tsx
index f83d2982c3..788b2d655a 100644
--- a/apps/mobile/src/session/ConversationShareSvg.tsx
+++ b/apps/mobile/src/session/ConversationShareSvg.tsx
@@ -6,7 +6,7 @@ import {
useRef,
useState,
} from "react";
-import { Image as NativeImage, Platform, StyleSheet, View } from "react-native";
+import { Image as NativeImage, PixelRatio, Platform, StyleSheet, View } from "react-native";
import Svg, {
ClipPath,
Defs,
@@ -122,7 +122,11 @@ export const ConversationShareSvg = forwardRef<
});
}, [imageKeysByUri, layout.images]);
const renderSize = useMemo(
- () => conversationShareSvgRenderSize(layout),
+ () =>
+ conversationShareSvgRenderSize(
+ layout,
+ Platform.OS === "android" ? PixelRatio.get() : 1,
+ ),
[layout],
);
const logoAsset = colors.dark ? shareLogoDarkAsset : shareLogoLightAsset;
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index 37455317c7..854201af80 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -6,7 +6,7 @@ import { HomeNewTaskButton } from './HomeNewTaskButton';
import { useRetainedHomeState, getHomeViewSession } from './homeViewSession';
import { rememberRecentTask } from './recentTasks';
import { homeListStyles, SessionStatusMark } from '@/session/HomeListVisuals';
-import { useHeaderHeight } from "expo-router/react-navigation";
+import { useOptionalHeaderHeight } from '@/session/useOptionalHeaderHeight';
import { SessionHeaderNativeBlur } from "@/session/SessionHeaderNativeControls";
import { RemoteTaskSuggestions } from '@/session/RemoteTaskSuggestions';
import { isTaskSuggestionsSyncPending, useRemoteTaskSuggestionsPresentation } from '@/session/useRemoteTaskSuggestionsPresentation';
@@ -2570,7 +2570,7 @@ function HomeScreenContent({ active = true, onModeChange, width, onDismiss, newS
const nativeHomeHeader = !embedded && usesNativeStackHeader();
const homeGeometry = useAdaptiveWindow();
const keepMenuTopLeft = nativeHomeHeader && homeGeometry.barEdge !== 'none';
- const nativeHeaderHeight = useHeaderHeight();
+ const nativeHeaderHeight = useOptionalHeaderHeight();
const chromeHeight = nativeHomeHeader
? nativeHeaderHeight + (headerHeight ?? 0)
: (headerHeight ?? edgePadding.paddingTop + HOME_HEADER_MIN_HEIGHT);
diff --git a/apps/mobile/src/session/conversationShareSvgLayout.ts b/apps/mobile/src/session/conversationShareSvgLayout.ts
index f6e0c996aa..cb77c72cee 100644
--- a/apps/mobile/src/session/conversationShareSvgLayout.ts
+++ b/apps/mobile/src/session/conversationShareSvgLayout.ts
@@ -67,6 +67,7 @@ export interface ConversationShareSvgLayout {
export function conversationShareSvgRenderSize(
layout: Pick<ConversationShareSvgLayout, "height" | "width">,
+ pixelRatio = 1,
): { height: number; scale: number; sourceTooLarge: boolean; width: number } {
const sourceTooLarge = layout.width * layout.height > MAX_OUTPUT_PIXELS;
if (sourceTooLarge) {
@@ -74,13 +75,17 @@ export function conversationShareSvgRenderSize(
}
const scale = Math.min(
DEFAULT_EXPORT_SCALE,
- Math.sqrt(MAX_OUTPUT_PIXELS / Math.max(1, layout.width * layout.height)),
+ // SvgView allocates its bitmap in physical pixels, not React Native points.
+ Math.sqrt(
+ MAX_OUTPUT_PIXELS /
+ Math.max(1, layout.width * layout.height * Math.max(1, pixelRatio) ** 2),
+ ),
);
return {
- height: Math.max(1, Math.ceil(layout.height * scale)),
+ height: Math.max(1, Math.floor(layout.height * scale)),
scale,
sourceTooLarge,
- width: Math.max(1, Math.ceil(layout.width * scale)),
+ width: Math.max(1, Math.floor(layout.width * scale)),
};
}
diff --git a/apps/mobile/src/session/useOptionalHeaderHeight.ts b/apps/mobile/src/session/useOptionalHeaderHeight.ts
new file mode 100644
index 0000000000..5b7a195893
--- /dev/null
+++ b/apps/mobile/src/session/useOptionalHeaderHeight.ts
@@ -0,0 +1,8 @@
+import { HeaderHeightContext } from 'expo-router/react-navigation';
+import { useContext } from 'react';
+
+// The home surface also renders inside the session drawer, where no screen
+// header context exists. Only the native-header layout consumes this height.
+export function useOptionalHeaderHeight(): number {
+ return useContext(HeaderHeightContext) ?? 0;
+}