Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): track image additions independently of upload completion
Dasheafdcc3af4b9
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex a590e5c76a..51f44870e7 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -906,6 +906,7 @@ export default function NewRemoteSessionScreen() {const {pendingUploads,pastePlaceholderCount,+ imageSelectionRevision,beginPastePlaceholders,failPastePlaceholders,addImages: addLocalImageAttachments,@@ -2101,7 +2102,7 @@ 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 { active: composerImageHoldActive, collapse: collapseComposerImages } = useComposerImageExpansion(composerImageCount, composerIncomingImageCount);+ const { active: composerImageHoldActive, collapse: collapseComposerImages } = useComposerImageExpansion(composerImageCount, imageSelectionRevision);const composerCardActive = firstMessageInputFocused || composerPillOpen.opening|| composerImageHoldActive|| modelSheetOpendiff --git a/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsx b/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsxindex 5ecfa7d1af..a0dcc283d6 100644--- a/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsx+++ b/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsx@@ -143,14 +143,16 @@ describe("composer attachment tray overlay foreground", () => {uploaded,uploading,placeholders,+ revision,}: {uploaded: number;uploading: number;placeholders: number;+ revision: number;}) {const expansion = useComposerImageExpansion(uploaded + uploading + placeholders,- uploading + placeholders,+ revision,);return (<button onClick={expansion.collapse}>@@ -158,13 +160,19 @@ describe("composer attachment tray overlay foreground", () => {</button>);}- const render = (uploaded: number, uploading: number, placeholders = 0) =>+ const render = (+ uploaded: number,+ uploading: number,+ placeholders = 0,+ revision = 1,+ ) =>act(() =>root.render(<Composeruploaded={uploaded}uploading={uploading}placeholders={placeholders}+ revision={revision}/>,),);@@ -177,10 +185,10 @@ describe("composer attachment tray overlay foreground", () => {expect(host.textContent).toBe("collapsed");render(1, 0);expect(host.textContent).toBe("collapsed");- render(1, 0, 1); // paste another image+ render(1, 0, 1, 2); // paste another imageexpect(host.textContent).toBe("expanded");act(() => host.querySelector("button")!.click());- render(1, 1); // placeholder becomes a pending upload, no new slot+ render(1, 1, 0, 2); // placeholder becomes a pending upload, no new selectionexpect(host.textContent).toBe("collapsed");render(0, 0);render(1, 0); // restored image draftdiff --git a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsxindex d9efc4493f..dcd8f56cff 100644--- a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx+++ b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx@@ -3,6 +3,7 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { MobileLocalAttachmentUploadCandidate } from '@/session/mobileLocalAttachmentUpload';+import { useComposerImageExpansion } from '@/session/useComposerImageExpansion';import {useMobileLocalAttachments,type UseMobileLocalAttachmentsOptions,@@ -75,8 +76,14 @@ function mount(scopeKey: string) {onPicked: vi.fn(),};const results: UseMobileLocalAttachmentsResult[] = [];+ let expansion!: ReturnType<typeof useComposerImageExpansion>;function Harness({ scope }: { scope: string }) {- results.push(useMobileLocalAttachments({ ...options, attachmentScopeKey: scope }));+ const local = useMobileLocalAttachments({ ...options, attachmentScopeKey: scope });+ results.push(local);+ expansion = useComposerImageExpansion(+ local.pendingUploads.filter((item) => item.kind === 'image').length + local.pastePlaceholderCount,+ local.imageSelectionRevision,+ );return null;}act(() => root.render(<Harness scope={scopeKey} />));@@ -84,6 +91,7 @@ function mount(scopeKey: string) {options,first: results[0],latest: () => results.at(-1)!,+ expansion: () => expansion,rerender: (scope: string) => act(() => root.render(<Harness scope={scope} />)),};}@@ -99,6 +107,57 @@ const imageCandidate = (name: string, onAbandoned: () => void): MobileLocalAttacconst flush = () => new Promise((resolve) => { setTimeout(resolve, 0); });describe('useMobileLocalAttachments abandonment on scope change', () => {+ // PR #6291: unit integration through the real selection/upload and expansion+ // hooks. Count-only tests miss a completion and addition in the same render.+ it('reopens for a new selection during completion but not for paste materialization or retry', async () => {+ const harness = mount('session-a');+ act(() => harness.latest().enqueueUploads([imageCandidate('first.png', vi.fn())], { token: 'token' }));+ await act(async () => { await flush(); });+ expect(harness.expansion().active).toBe(true);+ act(() => harness.expansion().collapse());+ await act(async () => {+ runtime.uploads[0].resolve();+ await harness.latest().waitForPendingUploads();+ harness.latest().enqueueUploads([imageCandidate('next.png', vi.fn())], { token: 'token' });+ await flush();+ });+ expect(harness.latest().pendingUploads).toHaveLength(1);+ expect(harness.expansion().active).toBe(true);+ act(() => harness.expansion().collapse());+ act(() => harness.latest().beginPastePlaceholders(1));+ expect(harness.expansion().active).toBe(true);+ act(() => harness.expansion().collapse());+ // Keep this upload at the token boundary, without native file conversion.+ harness.options.getAccessToken = () => new Promise(() => {});+ harness.rerender('session-a');+ await act(async () => { await harness.latest().addPastedImages(['file:///cache/paste.png']); });+ expect(harness.latest().pastePlaceholderCount).toBe(0);+ expect(harness.expansion().active).toBe(false);+ act(() => harness.latest().beginPastePlaceholders(1));+ expect(harness.expansion().active).toBe(true);+ act(() => harness.expansion().collapse());+ act(() => {+ harness.latest().failPastePlaceholders();+ harness.latest().beginPastePlaceholders(1);+ });+ expect(harness.expansion().active).toBe(true);+ act(() => harness.latest().failPastePlaceholders());+ act(() => harness.expansion().collapse());+ // Direct paste (without a loading event) is a new selection as well.+ await act(async () => { await harness.latest().addPastedImages(['file:///cache/direct.png']); });+ expect(harness.expansion().active).toBe(true);+ act(() => harness.latest().discardAllPendingUploads());+ await act(async () => {+ harness.latest().enqueueUploads([imageCandidate('failed.png', vi.fn())], { token: Promise.resolve(null) });+ await harness.latest().waitForPendingUploads();+ });+ expect(harness.latest().pendingUploads[0].failed).toBe(true);+ act(() => harness.expansion().collapse());+ act(() => harness.latest().retryPendingUpload(harness.latest().pendingUploads[0].localId));+ expect(harness.latest().pendingUploads[0].failed).toBeFalsy();+ expect(harness.expansion().active).toBe(false);+ });+// 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 () => {diff --git a/apps/mobile/src/session/useComposerImageExpansion.ts b/apps/mobile/src/session/useComposerImageExpansion.tsindex fd4baad7ec..112566671f 100644--- a/apps/mobile/src/session/useComposerImageExpansion.ts+++ b/apps/mobile/src/session/useComposerImageExpansion.ts@@ -3,21 +3,21 @@ 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,+ imageSelectionRevision: number,) {- const previousIncomingCount = useRef(0);+ const previousSelectionRevision = useRef(imageSelectionRevision);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.+ // Selection and completion can cancel each other out in the pending count.+ // The upload hook reports actual additions, including native paste starts.if (- incomingImageCount > previousIncomingCount.current ||+ imageSelectionRevision !== previousSelectionRevision.current ||imageCount === 0) {setCollapsed(false);}- previousIncomingCount.current = incomingImageCount;- }, [imageCount, incomingImageCount]);+ previousSelectionRevision.current = imageSelectionRevision;+ }, [imageCount, imageSelectionRevision]);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 c1d02fd348..5b241e794f 100644--- a/apps/mobile/src/session/useMobileLocalAttachments.ts+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts@@ -106,6 +106,8 @@ export interface UseMobileLocalAttachmentsResult {* 托盘先画 N 张无图转圈占位卡;onPasteImages 兑现或失败 / 超时后归零。*/pastePlaceholderCount: number;+ /** Changes only for newly selected image batches, not upload progress or paste materialization. */+ imageSelectionRevision: number;/** 原生 images-loading 事件:立刻竖起 count 张粘贴占位卡。 */beginPastePlaceholders: (count: number) => void;/** 原生 images-load-failed 事件:撤掉占位卡并提示。 */@@ -184,6 +186,7 @@ export function useMobileLocalAttachments(// 仍在原生处理中的占位继续转圈(review P2)。超时定时器兜底事件丢失,超时属// 异常兜底,一次清全部不做批次精度。const [pastePlaceholderCount, setPastePlaceholderCount] = useState(0);+ const [imageSelectionRevision, setImageSelectionRevision] = useState(0);const pastePlaceholderBatchesRef = useRef<number[]>([]);const pastePlaceholderTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);// 占位窗口的发送等待者:waitForPendingUploads 必须把占位当在途工作等待——@@ -251,6 +254,7 @@ export function useMobileLocalAttachments(const beginPastePlaceholders = (count: number) => {if (count <= 0 || !isAttachmentScopeActive()) return;pastePlaceholderBatchesRef.current.push(count);+ setImageSelectionRevision((revision) => revision + 1);syncPastePlaceholders();};@@ -386,6 +390,7 @@ export function useMobileLocalAttachments(const enqueueUploads = (candidates: readonly MobileLocalAttachmentUploadCandidate[],opts: { token: string | Promise<string | null> },+ replacesPastePlaceholder = false,) => {if (!isAttachmentScopeActive()) {// 作用域已失效,任务不会入队:视同放弃,让自行生成输入文件的调用方回收。@@ -403,6 +408,9 @@ export function useMobileLocalAttachments(})),opts,);+ if (!replacesPastePlaceholder && candidates.some((candidate) => candidate.kind === 'image')) {+ setImageSelectionRevision((revision) => revision + 1);+ }};useEffect(() => () => {@@ -568,6 +576,7 @@ export function useMobileLocalAttachments(// 本批 uris 就是最早一批占位卡的兑现:先按 FIFO 出列本批再做限额检查//(否则这批会被自己的占位双扣槽位)。出列与下方 enqueue 的 pending 上屏在// 同一同步段,React 批处理保证占位卡 → pending 卡之间没有空帧。+ const replacesPastePlaceholder = getPastePlaceholderTotal() > 0;shiftPastePlaceholderBatch();const begun = beginPick();if (!begun) {@@ -598,7 +607,7 @@ export function useMobileLocalAttachments(},cleanupLocalUris: ownsLocalFile ? cleanupPastedImageLocalUris : undefined,};- }), { token: optionsRef.current.getAccessToken() });+ }), { token: optionsRef.current.getAccessToken() }, replacesPastePlaceholder);} catch (err) {if (isAttachmentScopeActive()) optionsRef.current.onError(formatRemoteError(err));} finally {@@ -629,6 +638,7 @@ export function useMobileLocalAttachments(},pendingUploads,pastePlaceholderCount,+ imageSelectionRevision,beginPastePlaceholders,failPastePlaceholders,addImages,