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): 移除截屏自动进入分享界面

Dash5c82e495bb94
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index f58f890c58..408103992c 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -73,10 +73,7 @@ import {
getRecordingPermissionsAsync,
requestRecordingPermissionsAsync,
} from 'expo-audio';
-import {
- addScreenshotListener,
- renderConversationShareHtmlToPng,
-} from 'xdt-screenshot-monitor';
+import { renderConversationShareHtmlToPng } from 'xdt-screenshot-monitor';
import { Stack, useFocusEffect, useLocalSearchParams, useNavigation, useRouter } from 'expo-router';
import { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode, type RefObject, type SetStateAction } from 'react';
import {
@@ -169,7 +166,6 @@ import {
MessageRenderer,
type MobileMessageActionBusyKind,
type MobileMessageDraft,
- type ShareableMessageViewport,
} from '@/session/MessageRenderer';
import {
bundledAssetToDataUri,
@@ -771,7 +767,6 @@ const REOPEN_MESSAGE_WINDOW_LIMITS = [20, 10, 5, 1] as const;
// session-tail-banner「重试」短窗口隐藏的超时兜底(接管信号全部丢失时恢复错误入口);
// 覆盖 settling 窗口上限(10s)之后仍无任何在途证据的场景。
const TAIL_RETRY_HIDE_TIMEOUT_MS = 15_000;
-const SCREENSHOT_SHARE_ACTIVATION_DEBOUNCE_MS = 1_200;
const nativeConversationShareAvailable = Platform.OS === 'ios';
// 原生 WKWebView 只能稳定读取 data URI;SVG 兜底直接使用同一组 bundle asset。
@@ -818,27 +813,6 @@ function choiceLabel(options: readonly { id: string; label: string }[], value: s
return options.find((option) => option.id === value)?.label ?? value;
}
-function measureViewInWindow(view: View | null): Promise<{
- height: number;
- width: number;
- x: number;
- y: number;
-} | null> {
- return new Promise((resolve) => {
- if (!view) {
- resolve(null);
- return;
- }
- view.measureInWindow((x, y, width, height) => {
- if (![x, y, width, height].every(Number.isFinite)) {
- resolve(null);
- return;
- }
- resolve({ height, width, x, y });
- });
- });
-}
-
/** 会话已读回执的驻留门槛:聚焦本会话且消息已渲染后停满这段时间才算「真实看到」。 */
const SESSION_READ_ACK_DWELL_MS = 200;
@@ -1213,19 +1187,12 @@ function SessionScreenContent() {
const conversationShareSvgRef = useRef<ConversationShareSvgHandle | null>(null);
const topOverlayRef = useRef<View>(null);
const bottomOverlayRef = useRef<View>(null);
- const visibleShareableMessageIdsReaderRef = useRef<(
- (viewport: ShareableMessageViewport) => Promise<readonly string[]>
- ) | null>(null);
- const screenshotBlockedByOverlayRef = useRef(false);
- const [messageBlockingOverlay, setMessageBlockingOverlay] = useState(false);
const shareSelectionActiveRef = useRef(shareSelectionActive);
shareSelectionActiveRef.current = shareSelectionActive;
const shareSelectionRevisionRef = useRef(shareSelectionRevision);
shareSelectionRevisionRef.current = shareSelectionRevision;
- const lastScreenshotActivationAtRef = useRef(0);
const shareOperationSeqRef = useRef(0);
const [conversationShareBusy, setConversationShareBusy] = useState(false);
- const [shareSelectionTriggeredByScreenshot, setShareSelectionTriggeredByScreenshot] = useState(false);
const [shareCharacterSrc, setShareCharacterSrc] = useState<string | null>(null);
const [shareLogoSrc, setShareLogoSrc] = useState<string | null>(null);
const shareLogoModeRef = useRef<string | null>(null);
@@ -1239,75 +1206,15 @@ function SessionScreenContent() {
appendQuote(sessionId, { text: truncateQuoteText(quote.text) });
requestAnimationFrame(() => composerInputRef.current?.focus());
}, [sessionId]);
- const handleVisibleShareableMessageIdsReaderChange = useCallback((
- reader: ((viewport: ShareableMessageViewport) => Promise<readonly string[]>) | null,
- ) => {
- visibleShareableMessageIdsReaderRef.current = reader;
- }, []);
- const handleMessageBlockingOverlayChange = useCallback((blocked: boolean) => {
- setMessageBlockingOverlay(blocked);
- }, []);
useEffect(() => {
shareOperationSeqRef.current += 1;
- lastScreenshotActivationAtRef.current = 0;
setConversationShareBusy(false);
- setShareSelectionTriggeredByScreenshot(false);
shareSelectionStore.exitIfNotSession(sessionId);
return () => {
shareOperationSeqRef.current += 1;
if (shareSelectionStore.getActiveSessionId() === sessionId) shareSelectionStore.exit();
};
}, [sessionId]);
- useFocusEffect(
- useCallback(() => {
- if (Platform.OS !== 'ios' || !sessionId) return undefined;
- let cancelled = false;
- const subscription = addScreenshotListener(() => {
- if (
- AppState.currentState !== 'active'
- || shareSelectionActiveRef.current
- || screenshotBlockedByOverlayRef.current
- ) return;
- const now = Date.now();
- if (now - lastScreenshotActivationAtRef.current < SCREENSHOT_SHARE_ACTIVATION_DEBOUNCE_MS) return;
- lastScreenshotActivationAtRef.current = now;
- void (async () => {
- const [topOverlayFrame, bottomOverlayFrame] = await Promise.all([
- measureViewInWindow(topOverlayRef.current),
- measureViewInWindow(bottomOverlayRef.current),
- ]);
- if (
- cancelled
- || AppState.currentState !== 'active'
- || shareSelectionActiveRef.current
- || screenshotBlockedByOverlayRef.current
- ) return;
- const reader = visibleShareableMessageIdsReaderRef.current;
- if (!topOverlayFrame || !bottomOverlayFrame || !reader) return;
- const measuredClientIds = await reader({
- visibleBottom: bottomOverlayFrame.y,
- visibleTop: topOverlayFrame.y + topOverlayFrame.height,
- });
- if (
- cancelled
- || AppState.currentState !== 'active'
- || shareSelectionActiveRef.current
- || screenshotBlockedByOverlayRef.current
- ) return;
- const visibleClientIds = [...new Set(measuredClientIds)];
- if (visibleClientIds.length === 0) return;
- Keyboard.dismiss();
- setShareSelectionTriggeredByScreenshot(true);
- shareSelectionStore.enter(sessionId);
- shareSelectionStore.setSelection(visibleClientIds);
- })();
- });
- return () => {
- cancelled = true;
- subscription?.remove();
- };
- }, [sessionId]),
- );
useEffect(() => {
if (!nativeConversationShareAvailable || !shareSelectionActive) return undefined;
let cancelled = false;
@@ -6249,14 +6156,12 @@ function SessionScreenContent() {
});
const enterShareSelection = useCallback((clientId: string) => {
Keyboard.dismiss();
- setShareSelectionTriggeredByScreenshot(false);
shareSelectionStore.enter(sessionId, clientId);
}, [sessionId]);
const cancelShareSelection = useCallback(() => {
shareOperationSeqRef.current += 1;
shareImages.cancel();
setConversationShareBusy(false);
- setShareSelectionTriggeredByScreenshot(false);
shareSelectionStore.exit();
}, [shareImages.cancel]);
const exportConversationSharePng = useCallback(async () => {
@@ -6326,7 +6231,6 @@ function SessionScreenContent() {
// 也必须交给下一次有界清理,不能在 finally 中提前删除。
shareCompleted = true;
if (!isShareOperationActive()) return;
- setShareSelectionTriggeredByScreenshot(false);
shareSelectionStore.exit();
} catch (error) {
if (!isShareOperationActive()) return;
@@ -8939,18 +8843,6 @@ function SessionScreenContent() {
}, []);
const dismissTransientNotice = useCallback(() => setTransientNotice(null), []);
const [chipShareBusy, setChipShareBusy] = useState(false);
- screenshotBlockedByOverlayRef.current = Boolean(
- settingsOpen
- || searchOpen
- || contextSheetOpen
- || chipMenuTarget !== null
- || (modelSheetOpen && canUseComposer)
- || (permissionSheetOpen && canUseComposer)
- || composerPreviewAttachmentId !== null
- || pendingImagePreview.active
- || sessionListDrawerOverlayMounted
- || messageBlockingOverlay
- );
// 聊天正文文件 chip 上下文(消息树内 inline chip 经 context 消费,不走多层 prop):
// stat 走被控端 fs:stat-path(失败由 verdict 层归为 unknown 乐观点亮)。
@@ -10261,11 +10153,9 @@ function SessionScreenContent() {
// 设备来源标签只标别的设备发来的消息:本机发出的不标。
viewerDeviceId={auth.deviceId}
onOpenSourceDevice={openSourceDevice}
- onBlockingOverlayChange={handleMessageBlockingOverlayChange}
onOpenSessionLink={openSessionLink}
onPreviewRewind={isSharedTaskPeer(deviceId) ? undefined : previewRewindAtMessage}
onEnterShareSelection={enterShareSelection}
- onVisibleShareableMessageIdsReaderChange={handleVisibleShareableMessageIdsReaderChange}
shareSelectionActive={shareSelectionActive}
shareSelectionBusy={conversationShareBusy}
// chat-text-quote:选中消息文字 → 引用进本会话草稿(截断后写
@@ -10756,7 +10646,6 @@ function SessionScreenContent() {
<ShareSelectionBar
busy={conversationShareBusy}
count={shareSelectionCount}
- screenshotTriggered={shareSelectionTriggeredByScreenshot}
onCancel={cancelShareSelection}
onShare={() => void shareSelectedConversation()}
/>
diff --git a/apps/mobile/src/__tests__/sessionScreenshotShare.test.ts b/apps/mobile/src/__tests__/sessionScreenshotShare.test.ts
index f0088b577d..6d6212dec6 100644
--- a/apps/mobile/src/__tests__/sessionScreenshotShare.test.ts
+++ b/apps/mobile/src/__tests__/sessionScreenshotShare.test.ts
@@ -1,73 +1,10 @@
-// guard: engineering-conventions.md 3.2 race contract: overlay ownership and selection revisions fence the screenshot listener and asynchronous exporter across renderer/page boundaries.
+// guard: engineering-conventions.md 3.2 race contract: selection revisions fence
+// the asynchronous exporter across renderer/page boundaries.
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
-describe("mobile screenshot-triggered share guards", () => {
- it("blocks screenshot activation while any session overlay is visible", () => {
- const source = readFileSync(
- resolve(process.cwd(), "app/sessions/[sessionId].tsx"),
- "utf8",
- );
-
- expect(source).toContain(
- "const screenshotBlockedByOverlayRef = useRef(false);",
- );
- expect(source).toContain("settingsOpen");
- expect(source).toContain("searchOpen");
- expect(source).toContain("contextSheetOpen");
- expect(source).toContain("chipMenuTarget !== null");
- expect(source).toContain("modelSheetOpen && canUseComposer");
- expect(source).toContain("permissionSheetOpen && canUseComposer");
- expect(source).toContain("composerPreviewAttachmentId !== null");
- expect(source).toContain("sessionListDrawerOverlayMounted");
- expect(source).toContain(
- "onBlockingOverlayChange={handleMessageBlockingOverlayChange}",
- );
-
- const listenerStart = source.indexOf(
- "const subscription = addScreenshotListener",
- );
- const listenerEnd = source.indexOf("return () => {", listenerStart);
- const listenerSource = source.slice(listenerStart, listenerEnd);
- expect(listenerSource).toContain("screenshotBlockedByOverlayRef.current");
- expect(
- listenerSource.match(/screenshotBlockedByOverlayRef\.current/g)?.length,
- ).toBeGreaterThanOrEqual(3);
- });
-
- it("reports message payload viewers and action sheets as blocking overlays", () => {
- const source = readFileSync(
- resolve(process.cwd(), "src/session/MessageRenderer.tsx"),
- "utf8",
- );
-
- expect(source).toContain(
- "onBlockingOverlayChange?: (blocked: boolean) => void;",
- );
- expect(source).toContain("const openMessageActionSheetsRef = useRef(new Set<string>());");
- expect(source).toContain("onMessageActionSheetOpenChange: handleMessageActionSheetOpenChange,");
- expect(source).toContain("actions.onMessageActionSheetOpenChange?.(clientId, true);");
- expect(source).toContain("actions.onMessageActionSheetOpenChange?.(clientId, false);");
- expect(source).toContain(
- "payload !== null || openMessageActionSheetsRef.current.size > 0",
- );
- });
-
- it("recomputes the screenshot guard from message overlay state", () => {
- const source = readFileSync(
- resolve(process.cwd(), "app/sessions/[sessionId].tsx"),
- "utf8",
- );
-
- expect(source).toContain(
- "const [messageBlockingOverlay, setMessageBlockingOverlay] = useState(false);",
- );
- expect(source).toContain("setMessageBlockingOverlay(blocked);");
- expect(source).toContain("|| messageBlockingOverlay");
- expect(source).not.toContain("messageBlockingOverlayRef");
- });
-
+describe("mobile conversation share guards", () => {
it("invalidates an export when the share selection revision changes", () => {
const source = readFileSync(
resolve(process.cwd(), "app/sessions/[sessionId].tsx"),
@@ -89,5 +26,4 @@ describe("mobile screenshot-triggered share guards", () => {
expect(source).not.toContain("conversationShareHtmlRef");
expect(source).not.toContain("operationShareHtml");
});
-
});
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index b4118ef1b3..b2ae344e90 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -437,7 +437,6 @@ const MarkdownRemoteMediaContext = createContext<ResolveRemoteMediaFn | undefine
/** 分享模式吸顶 check 与行内 check 共用 44px 触达高度。 */
const SHARE_STICKY_CHECK_HEIGHT = 44;
const STICKY_SHARE_CHECK_THROTTLE_MS = 150;
-const SCREENSHOT_SHARE_VISIBLE_PERCENT_THRESHOLD = 10;
// LegendList 变高 item 的初始估高(仅影响首帧布局定位,LegendList 挂载后按实测尺寸修正)。
/** Bound the hidden initial correction so live measurement churn cannot blank the list for seconds. */
const MOBILE_INITIAL_REVEAL_MAX_MS = 300;
@@ -644,11 +643,6 @@ export interface MobileMessageDraft {
export type MobileMessageActionBusyKind = 'fork' | 'rewind' | 'delete';
-export interface ShareableMessageViewport {
- visibleBottom: number;
- visibleTop: number;
-}
-
/** Desktop BotAvatar `sm` beside teammate replies; exported so the host renders a matching portrait. */
export const COMPANION_AVATAR_SIZE = 28;
const COMPANION_AVATAR_GAP = 10;
@@ -698,8 +692,6 @@ interface MessageActions {
*/
onOpenPayloadFromItem?: (payload: MessagePayload, sourceGroupKey: string) => void;
onLoadToolInput?: (ref: MobileToolInputProjection) => Promise<MobileToolInputDetail>;
- onBlockingOverlayChange?: (blocked: boolean) => void;
- onMessageActionSheetOpenChange?: (clientId: string, open: boolean) => void;
/** 正文里会话深链 chip(xdt-maker://session/…)点击回调,app 内跳转。 */
onOpenSessionLink?: (url: string) => void;
onPreviewRewind?: (clientId: string, draft: MobileMessageDraft) => void;
@@ -753,11 +745,9 @@ export function MessageRenderer({
onOpenOriginSession,
viewerDeviceId,
onOpenSourceDevice,
- onBlockingOverlayChange,
onOpenSessionLink,
onPreviewRewind,
onEnterShareSelection,
- onVisibleShareableMessageIdsReaderChange,
shareSelectionActive,
shareSelectionBusy,
onQuoteSelection,
@@ -838,9 +828,6 @@ export function MessageRenderer({
/** 全屏图片查看器的圈点标注配置(画笔 → 发送到对话;由会话屏接线附件管线)。 */
imageAnnotation?: ImageLightboxAnnotationConfig;
onEnterShareSelection?: (clientId: string) => void;
- onVisibleShareableMessageIdsReaderChange?: (
- reader: ((viewport: ShareableMessageViewport) => Promise<readonly string[]>) | null,
- ) => void;
shareSelectionActive?: boolean;
shareSelectionBusy?: boolean;
/** DEV-only:把内部列表控制器暴露给性能 harness 驱动自动滚动(临时,profiling/回归测量用)。 */
@@ -1108,27 +1095,9 @@ export function MessageRenderer({
setPayloadSourceGroupKey(sourceGroupKey);
setPayload(next);
}, []);
- const payloadRef = useRef(payload);
- payloadRef.current = payload;
- const openMessageActionSheetsRef = useRef(new Set<string>());
- const handleMessageActionSheetOpenChange = useCallback((clientId: string, open: boolean) => {
- if (open) openMessageActionSheetsRef.current.add(clientId);
- else openMessageActionSheetsRef.current.delete(clientId);
- if (!historyActiveRef.current) return;
- onBlockingOverlayChange?.(
- payloadRef.current !== null || openMessageActionSheetsRef.current.size > 0,
- );
- }, [onBlockingOverlayChange]);
useEffect(() => {
- if (!historyActive) {
- setPayload(null);
- return;
- }
- onBlockingOverlayChange?.(
- payload !== null || openMessageActionSheetsRef.current.size > 0,
- );
- return () => onBlockingOverlayChange?.(false);
- }, [historyActive, onBlockingOverlayChange, payload]);
+ if (!historyActive) setPayload(null);
+ }, [historyActive, payload]);
// 关闭回调必须引用稳定:内联闭包每次渲染换新,会经 ImageLightbox 透传成
// LightboxPage 手势 useMemo 的依赖,流式回复期间每 token 重建手势图,
// 可能打断进行中的捏合/拖动手势(rule 7)。
@@ -1799,7 +1768,6 @@ export function MessageRenderer({
onOpenPayload: openPayload,
onOpenPayloadFromItem: openPayloadFromItem,
onLoadToolInput,
- onMessageActionSheetOpenChange: handleMessageActionSheetOpenChange,
onResolveRemoteMedia,
// 待发送气泡(pending_send 项)的展开态与队列操作:漏了这一项 actions.pendingSend 就是
// undefined,渲染分支直接 null —— 气泡整个不画,乐观显示消失。
@@ -1846,7 +1814,6 @@ export function MessageRenderer({
onPreviewRewind,
onEnterShareSelection,
handleShareableMessageViewChange,
- handleMessageActionSheetOpenChange,
onResolveRemoteMedia,
openPayload,
openPayloadFromItem,
@@ -1943,45 +1910,6 @@ export function MessageRenderer({
useEffect(() => () => {
if (stickyCheckTimerRef.current) clearTimeout(stickyCheckTimerRef.current);
}, []);
- const readActuallyVisibleShareableMessageIds = useCallback(async (
- viewport: ShareableMessageViewport,
- ): Promise<readonly string[]> => {
- const list = listRef.current;
- if (!list) return [];
- const listFrame = await measureInWindow(list.getNativeScrollRef());
- if (!listFrame || listFrame.height <= 0) return [];
- const visibleTop = Math.max(listFrame.y, viewport.visibleTop);
- const visibleBottom = Math.min(
- listFrame.y + listFrame.height,
- viewport.visibleBottom,
- );
- if (visibleBottom <= visibleTop) return [];
- const measuredItems = await Promise.all(
- Array.from(shareableMessageViewsRef.current.entries()).map(async ([clientId, view]) => {
- const frame = await measureInWindow(view);
- if (!frame || frame.height <= 0) return null;
- const visibleHeight = Math.max(
- 0,
- Math.min(frame.y + frame.height, visibleBottom) - Math.max(frame.y, visibleTop),
- );
- if (
- visibleHeight / frame.height
- < SCREENSHOT_SHARE_VISIBLE_PERCENT_THRESHOLD / 100
- ) return null;
- return { clientId, y: frame.y };
- }),
- );
- return measuredItems
- .filter((item): item is { clientId: string; y: number } => item !== null)
- .sort((left, right) => left.y - right.y)
- .map((item) => item.clientId);
- }, []);
- useEffect(() => {
- if (!historyActive) return;
- onVisibleShareableMessageIdsReaderChange?.(readActuallyVisibleShareableMessageIds);
- return () => onVisibleShareableMessageIdsReaderChange?.(null);
- }, [historyActive, onVisibleShareableMessageIdsReaderChange, readActuallyVisibleShareableMessageIds]);
-
// 贴底跟随由 handleContentSize 的手动补滚承担(nearBottomRef 是跟随意图的唯一真相);
// 跳底先命令式 scrollToEnd,随后复用同一轮有界落底校验。
const scrollToBottom = useCallback(() => {
@@ -3499,11 +3427,6 @@ function MessageBubble({
const isUser = presentation.isUserAligned && !item.message.hookSource;
const isStreamingAssistant = item.message.kind === 'assistant' && item.message.isStreaming === true;
const clientId = messageClientId(item);
- useEffect(() => {
- if (!historyActive || !actionSheetOpen) return undefined;
- actions.onMessageActionSheetOpenChange?.(clientId, true);
- return () => actions.onMessageActionSheetOpenChange?.(clientId, false);
- }, [historyActive, actionSheetOpen, actions.onMessageActionSheetOpenChange, clientId]);
const shareableMessage = isShareableMessage(item.message);
const handleShareableMessageViewChange = useCallback((view: View | null) => {
actions.onShareableMessageViewChange?.(clientId, view);
diff --git a/apps/mobile/src/session/ShareSelectionBar.tsx b/apps/mobile/src/session/ShareSelectionBar.tsx
index 63bf971842..a02bca7ee6 100644
--- a/apps/mobile/src/session/ShareSelectionBar.tsx
+++ b/apps/mobile/src/session/ShareSelectionBar.tsx
@@ -20,13 +20,11 @@ import {
export function ShareSelectionBar({
busy,
count,
- screenshotTriggered = false,
onCancel,
onShare,
}: {
busy?: boolean;
count: number;
- screenshotTriggered?: boolean;
onCancel(): void;
onShare(): void;
}) {
@@ -54,9 +52,7 @@ export function ShareSelectionBar({
</HomeHeaderGlassButton>
);
const countLabel = (
- <View
- style={[styles.count, screenshotTriggered && styles.screenshotSafeCount]}
- >
+ <View style={styles.count}>
<Text ellipsizeMode="tail" numberOfLines={1} style={styles.titleText}>
{t("session.shareImage.title")}
</Text>
@@ -156,9 +152,6 @@ const makeStyles = (colors: ThemeColors) =>
lineHeight: lineHeight.caption,
marginTop: spacing.xs,
},
- screenshotSafeCount: {
- paddingLeft: spacing.xl,
- },
shareButton: {
alignItems: "center",
backgroundColor: colors.cta,