Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): hand off pending image previews after upload
Dash9860c9e0126b
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex c89cc3f98f..2579de90fc 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -1414,6 +1414,7 @@ function SessionScreenContent() {waitForPendingUploads,beginOutboxAttachmentHandoff,getUploadedSource,+ getUploadedAttachmentId,releaseUploadedSources,waitForPastePlaceholdersSettled,hasPastePlaceholders,@@ -7418,6 +7419,7 @@ function SessionScreenContent() {const renderComposerAttachmentTray = () => (<ComposerAttachmentTrayattachments={attachments}+ getUploadedAttachmentId={getUploadedAttachmentId}onPreview={setComposerPreviewAttachmentId}onRemove={removeRemoteFileAttachment}onRemovePending={removePendingUpload}diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 0b568a6172..a590e5c76a 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -18,6 +18,7 @@ import { resolveWorkspacePickerFrame, type WorkspacePickerFrame } from '@/sessioimport { simpleScreenSafeAreaEdges } from '@/platform/chrome/SimpleStackHeader';import { readComposerEntry, useComposerDock } from '@/session/composerMorph';import { useComposerPillOpen } from '@/session/useComposerPillOpen';+import { useComposerImageExpansion } from '@/session/useComposerImageExpansion';import { DockKeyboardBottomSpacer } from '@/session/ComposerDockKeyboardFollow';import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';import { composerGeometry } from '@/session/composerGeometry';@@ -917,6 +918,7 @@ export default function NewRemoteSessionScreen() {waitForPendingUploads,getPendingUploadCount,getUploadedSource,+ getUploadedAttachmentId,releaseUploadedSources,} = useMobileLocalAttachments({getAccessToken: () => auth.getAccessToken(),@@ -2099,18 +2101,9 @@ export default function NewRemoteSessionScreen() {});const composerIncomingImageCount = pendingUploads.filter((item) => item.kind === 'image').length + pastePlaceholderCount;const composerImageCount = attachments.filter((item) => item.category === 'image').length + composerIncomingImageCount;- const previousComposerIncomingImageCount = useRef(0);- const [composerImagesCollapsed, setComposerImagesCollapsed] = useState(false);- useEffect(() => {- // Only incoming images reopen a manually collapsed tray. Completed uploads- // can briefly appear in both lists and must not count as another addition.- if (composerIncomingImageCount > previousComposerIncomingImageCount.current || composerImageCount === 0) {- setComposerImagesCollapsed(false);- }- previousComposerIncomingImageCount.current = composerIncomingImageCount;- }, [composerImageCount, composerIncomingImageCount]);+ const { active: composerImageHoldActive, collapse: collapseComposerImages } = useComposerImageExpansion(composerImageCount, composerIncomingImageCount);const composerCardActive = firstMessageInputFocused || composerPillOpen.opening- || (composerImageCount > 0 && !composerImagesCollapsed)+ || composerImageHoldActive|| modelSheetOpen|| permissionSheetOpen|| voiceStartPending@@ -2120,10 +2113,10 @@ export default function NewRemoteSessionScreen() {// 下拉收起 = 退出聚焦激活态(模型浮窗已是独立 Modal,拖拽手势够不到它,无需在此关闭)。// 语音结束 hold 态未聚焦,blur 是 no-op,需显式解除 hold 才能收回简洁态。const handleComposerSnapToAuto = useCallback(() => {- setComposerImagesCollapsed(true);+ collapseComposerImages();setComposerVoiceHoldArmed(false);firstMessageInputRef.current?.blur();- }, []);+ }, [collapseComposerImages]);const composerResize = useComposerResize({autoMaxContentHeight: MOBILE_COMPOSER_INPUT_MAX_HEIGHT,// 简洁态一律收到单行(下拉收起和点别处收键盘的结果一致);@@ -4629,6 +4622,7 @@ export default function NewRemoteSessionScreen() {const renderComposerAttachmentTray = () => (<ComposerAttachmentTrayattachments={attachments}+ getUploadedAttachmentId={getUploadedAttachmentId}onPreview={setComposerPreviewAttachmentId}onRemove={removeAttachment}onRemovePending={removePendingUpload}diff --git a/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsx b/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsxindex f78b52b4a8..5ecfa7d1af 100644--- a/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsx+++ b/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsx@@ -7,10 +7,14 @@ import {ComposerAttachmentTray,} from "@/session/ComposerAttachmentTray";import { i18n } from "@/i18n";+import { useComposerImageExpansion } from "@/session/useComposerImageExpansion";import type { RemoteSerializedAttachment } from "@/session/types";import type { PendingLocalAttachmentUpload } from "@/session/mobileLocalAttachmentUpload";-const theme = vi.hoisted(() => ({ mode: "light" }));+const theme = vi.hoisted(() => ({+ mode: "light",+ files: null as Set<string> | null,+}));vi.mock("react-native", async () => {const { createElement } = await import("react");const flatten = (style: unknown): Record<string, unknown> =>@@ -69,7 +73,9 @@ vi.mock("@/session/ImageLightbox", () => ({onClose(): void;}) => (<button data-testid="lightbox" onClick={onClose}>- {images[0].url}+ {theme.files && !theme.files.has(images[0].url)+ ? "missing"+ : images[0].url}</button>),}));@@ -96,6 +102,7 @@ vi.mock("@/theme", async () => {let root: Root;let host: HTMLDivElement;beforeEach(async () => {+ theme.files = null;Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });await i18n.changeLanguage("zh-CN");host = document.createElement("div");@@ -129,15 +136,70 @@ const colorOf = (selector: string) =>host.querySelector(selector)?.getAttribute("data-color");describe("composer attachment tray overlay foreground", () => {+ // PR #6291: production expansion hook, with a button representing the card's+ // collapse gesture. Existing tray tests do not exercise new-task expansion.+ it("opens for new images but respects collapse through paste and upload completion", () => {+ function Composer({+ uploaded,+ uploading,+ placeholders,+ }: {+ uploaded: number;+ uploading: number;+ placeholders: number;+ }) {+ const expansion = useComposerImageExpansion(+ uploaded + uploading + placeholders,+ uploading + placeholders,+ );+ return (+ <button onClick={expansion.collapse}>+ {expansion.active ? "expanded" : "collapsed"}+ </button>+ );+ }+ const render = (uploaded: number, uploading: number, placeholders = 0) =>+ act(() =>+ root.render(+ <Composer+ uploaded={uploaded}+ uploading={uploading}+ placeholders={placeholders}+ />,+ ),+ );+ render(0, 0);+ expect(host.textContent).toBe("collapsed");+ render(0, 1);+ expect(host.textContent).toBe("expanded");+ act(() => host.querySelector("button")!.click());+ render(1, 1); // delivered/pending overlap+ expect(host.textContent).toBe("collapsed");+ render(1, 0);+ expect(host.textContent).toBe("collapsed");+ render(1, 0, 1); // paste another image+ expect(host.textContent).toBe("expanded");+ act(() => host.querySelector("button")!.click());+ render(1, 1); // placeholder becomes a pending upload, no new slot+ expect(host.textContent).toBe("collapsed");+ render(0, 0);+ render(1, 0); // restored image draft+ expect(host.textContent).toBe("expanded");+ });+// 用户反馈:在途图片只能看缩略图。既有颜色测试不覆盖点击;unit 层用一张// 上传中图片验证真实托盘打开本地预览,并在上传完成后仍保持查看器。- it("previews an uploading image and keeps it open after upload completes", () => {- const render = (uploading: boolean) =>+ it("switches an open preview to the durable URI when the temporary file is deleted", () => {+ theme.files = new Set(["file:///uploading.jpg"]);+ const render = (uploading: boolean, delivered = false) =>act(() =>root.render(<ComposerAttachmentTray- attachments={uploading ? [] : [attachment("done")]}- previews={{ done: "file:///uploading.jpg" }}+ attachments={delivered ? [attachment("done")] : []}+ previews={{ done: "file:///durable.jpg" }}+ getUploadedAttachmentId={(id) =>+ delivered && id === "uploading" ? "done" : undefined+ }onRemove={() => {}}onPreview={() => {}}pendingUploads={uploading ? [pending("uploading")] : []}@@ -154,9 +216,16 @@ describe("composer attachment tray overlay foreground", () => {expect(host.querySelector('[data-testid="lightbox"]')?.textContent).toBe("file:///uploading.jpg",);- render(false);+ theme.files.delete("file:///uploading.jpg");+ theme.files.add("file:///durable.jpg");+ // onUploaded publishes the delivered attachment before the controller removes pending.+ render(true, true);expect(host.querySelector('[data-testid="lightbox"]')?.textContent).toBe(- "file:///uploading.jpg",+ "file:///durable.jpg",+ );+ render(false, true);+ expect(host.querySelector('[data-testid="lightbox"]')?.textContent).toBe(+ "file:///durable.jpg",);act(() =>hostdiff --git a/apps/mobile/src/__tests__/composerVoiceStartupFeedback.test.ts b/apps/mobile/src/__tests__/composerVoiceStartupFeedback.test.tsindex d146f5ee7c..8052fcb050 100644--- a/apps/mobile/src/__tests__/composerVoiceStartupFeedback.test.ts+++ b/apps/mobile/src/__tests__/composerVoiceStartupFeedback.test.ts@@ -45,6 +45,7 @@ function readCallbacks(page: string) {const canUseComposer = true;const composerFocused = false, firstMessageInputFocused = false;const modelSheetOpen = false, permissionSheetOpen = false, composerVoiceHoldActive = false;+ const composerImageHoldActive = false;// 收起胶囊点开的过渡期(useComposerPillOpen)不在本用例范围:语音按下前后都未点胶囊。const composerPillOpen = { opening: false };return ${cardActive};diff --git a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsxindex 56faea3a6c..d9efc4493f 100644--- a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx+++ b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx@@ -13,6 +13,7 @@ const runtime = vi.hoisted(() => ({uploads: [] as Array<{ name: string; resolve: () => void }>,discarded: [] as unknown[],pickPhotos: vi.fn(),+ durablePreviewUri: null as string | null,}));vi.mock('react-native', () => ({ Platform: { OS: 'ios' } }));@@ -31,7 +32,7 @@ vi.mock('@/session/durableOutboxFiles', () => ({retainComposerAttachmentFile: async (_owner: string, id: string) => `file:///stage/${id}`,}));vi.mock('@/session/sentAttachmentThumbStore', () => ({- getSentAttachmentThumbUri: () => null,+ getSentAttachmentThumbUri: () => runtime.durablePreviewUri,registerSentAttachmentThumb: async () => undefined,}));vi.mock('@/session/mobileAttachmentUpload', () => ({@@ -59,6 +60,7 @@ beforeEach(() => {runtime.uploads = [];runtime.discarded = [];runtime.pickPhotos.mockReset();+ runtime.durablePreviewUri = null;root = createRoot(document.createElement('div'));});afterEach(() => act(() => root.unmount()));@@ -97,6 +99,38 @@ const imageCandidate = (name: string, onAbandoned: () => void): MobileLocalAttacconst flush = () => new Promise((resolve) => { setTimeout(resolve, 0); });describe('useMobileLocalAttachments abandonment on scope change', () => {+ // PR #6291: the real upload hook must publish the local-id handoff before+ // reclaiming a pasted source. Tray-only tests cannot prove this ordering.+ it('keeps upload identity resolvable after source cleanup and releases it with the attachment', async () => {+ const harness = mount('session-a');+ runtime.durablePreviewUri = 'file:///durable/pasted.png';+ let localId = '';+ let attachmentAtCleanup: string | undefined;+ let deliveriesAtCleanup = 0;+ const cleanup = vi.fn(async () => {+ attachmentAtCleanup = harness.latest().getUploadedAttachmentId(localId);+ deliveriesAtCleanup = vi.mocked(harness.options.onUploaded).mock.calls.length;+ });+ act(() => harness.first.enqueueUploads([{+ ...imageCandidate('pasted.png', vi.fn()), cleanupLocalUris: cleanup,+ }], { token: 'token' }));+ await act(async () => { await flush(); });+ localId = harness.latest().pendingUploads[0].localId;+ expect(harness.latest().getUploadedAttachmentId(localId)).toBeUndefined();+ await act(async () => { runtime.uploads[0].resolve(); await harness.latest().waitForPendingUploads(); });+ expect(cleanup).toHaveBeenCalledOnce();+ expect(attachmentAtCleanup).toBe('att-pasted.png');+ expect(deliveriesAtCleanup).toBe(1);+ expect(harness.options.onUploaded).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'att-pasted.png' }),+ expect.objectContaining({ uri: 'file:///durable/pasted.png' }), localId,+ );+ expect(harness.latest().pendingUploads).toEqual([]);+ expect(harness.latest().getUploadedAttachmentId(localId)).toBe('att-pasted.png');+ act(() => harness.latest().releaseUploadedSources(['att-pasted.png']));+ expect(harness.latest().getUploadedAttachmentId(localId)).toBeUndefined();+ });+it('puts selected photos in the tray and closes the context panel before their originals load', async () => {const harness = mount('session-a');runtime.pickPhotos.mockResolvedValue([{diff --git a/apps/mobile/src/session/BotGroupComposer.tsx b/apps/mobile/src/session/BotGroupComposer.tsxindex f9d606923a..27971f55c0 100644--- a/apps/mobile/src/session/BotGroupComposer.tsx+++ b/apps/mobile/src/session/BotGroupComposer.tsx@@ -351,6 +351,7 @@ export function BotGroupComposer({onPasteImagesLoadFailed={() => { if (pasteAllowedRef.current) tray.failPastePlaceholders(); }}cardActive={cardActive}accessoryAbove={hasAttachments ? <ComposerAttachmentTray attachments={tray.attachments} previews={tray.previews}+ getUploadedAttachmentId={tray.getUploadedAttachmentId}pendingUploads={tray.pendingUploads} pastePlaceholderCount={tray.pastePlaceholderCount}onPreview={setPreviewId} onRemove={tray.removeAttachment} onRemovePending={tray.removePendingUpload}onRetryPending={tray.retryPendingUpload} removeDisabled={sending} testIDPrefix="botGroup" /> : null}diff --git a/apps/mobile/src/session/ComposerAttachmentTray.tsx b/apps/mobile/src/session/ComposerAttachmentTray.tsxindex 84e5dd55f7..f180432f68 100644--- a/apps/mobile/src/session/ComposerAttachmentTray.tsx+++ b/apps/mobile/src/session/ComposerAttachmentTray.tsx@@ -12,7 +12,7 @@ import { FileTypeIcon } from '@/components/FileTypeIcon';*/import { Pen, RefreshCw, X } from 'lucide-react-native';import { Image } from 'expo-image';-import { useState } from 'react';+import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';import { Text } from '@/components/AppText';@@ -36,6 +36,7 @@ export interface ComposerAttachmentTrayProps {onPreview: (attachmentId: string) => void;/** 乐观上传中的本机附件(图片=缩略卡,文件=chip,均带转圈;失败态带重试)。 */pendingUploads?: readonly PendingLocalAttachmentUpload[];+ getUploadedAttachmentId?: (localId: string) => string | undefined;/** X 一个上传中的附件(取消上传)。 */onRemovePending?: (localId: string) => void;/** 重试一个失败态的上传卡。 */@@ -57,6 +58,7 @@ export function ComposerAttachmentTray({onRemove,onPreview,pendingUploads = [],+ getUploadedAttachmentId,onRemovePending,onRetryPending,pastePlaceholderCount = 0,@@ -67,15 +69,19 @@ export function ComposerAttachmentTray({const { t } = useTranslation();const styles = useThemedStyles(makeTrayStyles);const { colors } = useTheme();- // Keep the opened local image stable when the upload becomes a formal attachment.- const [pendingPreview, setPendingPreview] = useState<MobileMessageGalleryImage[] | null>(null);- const previewPending = (pending: PendingLocalAttachmentUpload) => {- if (!pending.previewUri) return;- const payload = buildMediaPayload({ kind: 'image', previewable: true, title: pending.name, url: pending.previewUri }, pending.name);- if (payload.kind === 'media') {- setPendingPreview([{ key: pending.localId, payload, title: pending.name, url: pending.previewUri }]);- }- };+ const [pendingPreviewId, setPendingPreviewId] = useState<string | null>(null);+ const deliveredId = pendingPreviewId ? getUploadedAttachmentId?.(pendingPreviewId) : undefined;+ const delivered = attachments.find((item) => item.id === deliveredId);+ const pending = pendingUploads.find((item) => item.localId === pendingPreviewId);+ // Prefer the delivered URI even during the brief overlap of both lists: the+ // uploader may already have deleted the temporary source at this point.+ const previewUri = delivered ? previews[delivered.id] : pending?.previewUri;+ const previewName = delivered?.name ?? pending?.name;+ const pendingPreview = useMemo<MobileMessageGalleryImage[]>(() => {+ if (!previewUri || !previewName || !pendingPreviewId) return [];+ const payload = buildMediaPayload({ kind: 'image', previewable: true, title: previewName, url: previewUri }, previewName);+ return payload.kind === 'media' ? [{ key: pendingPreviewId, payload, title: previewName, url: previewUri }] : [];+ }, [previewUri, previewName, pendingPreviewId]);if (attachments.length === 0 && pendingUploads.length === 0 && pastePlaceholderCount === 0) return null;return (<View style={styles.tray} testID={`${testIDPrefix}.attachmentTray`}>@@ -161,7 +167,7 @@ export function ComposerAttachmentTray({accessibilityLabel={t('composer.attachments.viewImage', { name: pending.name })}accessibilityRole="button"disabled={!pending.previewUri}- onPress={() => previewPending(pending)}+ onPress={() => setPendingPreviewId(pending.localId)}style={({ pressed }) => [styles.thumbBusyOverlay, pressed && styles.pressed]}testID={`${testIDPrefix}.attachmentPendingPreviewButton`}>@@ -230,8 +236,8 @@ export function ComposerAttachmentTray({</View></View>))}- {pendingPreview ? (- <ImageLightbox images={pendingPreview} initialUrl={pendingPreview[0].url} onClose={() => setPendingPreview(null)} />+ {pendingPreview.length > 0 ? (+ <ImageLightbox key={previewUri} images={pendingPreview} initialUrl={pendingPreview[0].url} onClose={() => setPendingPreviewId(null)} />) : null}</View>);diff --git a/apps/mobile/src/session/useBotGroupComposerAttachments.ts b/apps/mobile/src/session/useBotGroupComposerAttachments.tsindex 3777fedb8c..ad2278110c 100644--- a/apps/mobile/src/session/useBotGroupComposerAttachments.ts+++ b/apps/mobile/src/session/useBotGroupComposerAttachments.ts@@ -188,6 +188,7 @@ export function useBotGroupComposerAttachments({ deviceId, onPicked }: {removePendingUpload: local.removePendingUpload,retryPendingUpload: local.retryPendingUpload,waitForPendingUploads: local.waitForPendingUploads,+ getUploadedAttachmentId: local.getUploadedAttachmentId,clearSent,holdForSend,armMediaTap,diff --git a/apps/mobile/src/session/useComposerImageExpansion.ts b/apps/mobile/src/session/useComposerImageExpansion.tsnew file mode 100644index 0000000000..fd4baad7ec--- /dev/null+++ b/apps/mobile/src/session/useComposerImageExpansion.ts@@ -0,0 +1,23 @@+import { useCallback, useEffect, useRef, useState } from "react";++/** Newly added images open the card; completing uploads respect an explicit collapse. */+export function useComposerImageExpansion(+ imageCount: number,+ incomingImageCount: number,+) {+ const previousIncomingCount = useRef(0);+ const [collapsed, setCollapsed] = useState(false);+ useEffect(() => {+ // Uploaded and pending lists can briefly overlap; only new incoming slots+ // count as an addition. A paste placeholder becoming an upload keeps its slot.+ if (+ incomingImageCount > previousIncomingCount.current ||+ imageCount === 0+ ) {+ setCollapsed(false);+ }+ previousIncomingCount.current = incomingImageCount;+ }, [imageCount, incomingImageCount]);+ const collapse = useCallback(() => setCollapsed(true), []);+ return { active: imageCount > 0 && !collapsed, collapse };+}diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.tsindex df586b40f0..c1d02fd348 100644--- a/apps/mobile/src/session/useMobileLocalAttachments.ts+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts@@ -96,6 +96,8 @@ async function deleteLocalUris(uris: readonly string[]): Promise<void> {export interface UseMobileLocalAttachmentsResult {beginOutboxAttachmentHandoff: () => Promise<ReturnType<MobileLocalAttachmentUploadController['beginHandoff']>>;getUploadedSource: (id: string) => MobileLocalAttachmentUploadCandidate | undefined;+ /** Resolve a tray upload to its delivered attachment without retaining temporary URIs. */+ getUploadedAttachmentId: (localId: string) => string | undefined;releaseUploadedSources: (ids: readonly string[]) => void;/** 上传中的附件(托盘渲染 pending 卡)。 */pendingUploads: readonly PendingLocalAttachmentUpload[];@@ -266,7 +268,7 @@ export function useMobileLocalAttachments(optionsRef.current.onError(t('composer.upload.clipboardReadFailed'));};- const uploadedSourcesRef = useRef(new Map<string, MobileLocalAttachmentUploadCandidate>());+ const uploadedSourcesRef = useRef(new Map<string, MobileLocalAttachmentUploadCandidate & { localId: string }>());const stagingUrisRef = useRef(new Set<string>());const stagingOwnerRef = useRef(`${Date.now()}-${Math.random().toString(36).slice(2)}`);const controller = useMemo(() => createMobileLocalAttachmentUploadController({@@ -331,7 +333,7 @@ export function useMobileLocalAttachments(return;}uploadedSourcesRef.current.set(attachment.id, {- ...candidate, uri: stageUri, name: attachment.name, mimeType: attachment.mimeType,+ ...candidate, localId, uri: stageUri, name: attachment.name, mimeType: attachment.mimeType,size: attachment.size, resolve: undefined, skipPreprocess: true, cleanupLocalUris: undefined,onAbandoned: undefined, onConsumed: undefined,});@@ -615,6 +617,7 @@ export function useMobileLocalAttachments(}},getUploadedSource: (id) => uploadedSourcesRef.current.get(id),+ getUploadedAttachmentId: (localId) => [...uploadedSourcesRef.current].find(([, source]) => source.localId === localId)?.[0],releaseUploadedSources: (ids) => {for (const id of ids) {const source = uploadedSourcesRef.current.get(id);