From 92f1b9dbea271ce2c88902737bad25dcf4041d03 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 08:31:17 -0700 Subject: [PATCH 1/5] fix(native-chat): reserve pending chips before checking dropped files A local file drop checked each file before adding it, with nothing in the composer meanwhile: Send during the check went without the file, which then landed in the next draft; unmounting mid-check lost it; and files queued behind an input-method composition were lost on unmount. Drops now reserve a pending chip per file before the check, so Send waits as it already does for server-upload drops. The prepared attachment travels through the existing composition queue as one operation, settles into its draft scope after unmount, releases its chips when refused or disabled, and reads the scope's current image capability when it applies. --- ...-external-attachments-destination.test.tsx | 136 +++++++++- .../native-chat-floating-file-drop.test.tsx | 10 +- .../native-chat-pending-attachment-cache.ts | 5 +- .../native-chat-resolved-path-ownership.ts | 6 + .../native-chat-session-attachment-drop.ts | 16 +- .../use-native-chat-composer-attachments.ts | 57 ++-- ...-native-chat-external-attachments.test.tsx | 54 ++-- .../use-native-chat-external-attachments.ts | 83 ++++-- ...e-native-chat-resolved-path-attachments.ts | 253 +++++++++++------- 9 files changed, 448 insertions(+), 172 deletions(-) diff --git a/src/renderer/src/components/native-chat/native-chat-external-attachments-destination.test.tsx b/src/renderer/src/components/native-chat/native-chat-external-attachments-destination.test.tsx index 7537a5d7c121..b30174c2bdea 100644 --- a/src/renderer/src/components/native-chat/native-chat-external-attachments-destination.test.tsx +++ b/src/renderer/src/components/native-chat/native-chat-external-attachments-destination.test.tsx @@ -4,6 +4,9 @@ import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as AttachmentUploadModule from './native-chat-attachment-upload' import type { NativeChatAttachmentOwner } from './native-chat-attachment-upload' +import { nativeChatPendingAttachmentSnapshot } from './native-chat-pending-attachment-cache' +import { nativeChatImagesHoldSend } from './native-chat-image-reattach' +import { readNativeChatDraftCache } from './native-chat-draft-cache' import { useNativeChatExternalAttachments } from './use-native-chat-external-attachments' import { clearNativeChatAttachmentCacheForTests, @@ -44,15 +47,24 @@ let root: Root let container: HTMLDivElement let composing = true -function Probe({ worktreeId }: { worktreeId?: string }): React.JSX.Element { +function Probe({ + worktreeId, + acceptsImages = true, + disabled = false +}: { + worktreeId?: string + acceptsImages?: boolean + disabled?: boolean +}): React.JSX.Element { const [draft, setDraft] = useState('') const [caret, setCaret] = useState(0) const [notice, setNotice] = useState(null) const textareaRef = useRef(null) const attachments = useNativeChatComposerAttachments({ attachmentScopeKey: 'drop-test', + acceptsImages, caret, - disabled: false, + disabled, isComposing: () => composing, resolveTarget: () => ({ ptyId: 'pty-1', settings: { activeRuntimeEnvironmentId: null } }), textareaRef, @@ -63,7 +75,7 @@ function Probe({ worktreeId }: { worktreeId?: string }): React.JSX.Element { const external = useNativeChatExternalAttachments({ terminalTabId: 'tab-1', structuredWorktreeId: worktreeId, - disabled: false, + disabled, attachResolvedPaths: attachments.attachResolvedPaths, pendingChips: attachments.pendingChips, setNotice @@ -85,8 +97,10 @@ function latest(): Api { return api } -async function render(worktreeId?: string): Promise { - await act(async () => root.render()) +async function render(worktreeId?: string, acceptsImages = true, disabled = false): Promise { + await act(async () => + root.render() + ) } beforeEach(() => { @@ -115,6 +129,7 @@ describe('OS attachment destination through input-method composition', () => { async (change) => { await render(change === 'terminal-workspace' ? undefined : 'workspace-1') await act(async () => latest().attachExternalPaths(['/local/file.txt', '/local/image.png'])) + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toHaveLength(2) expect(container.querySelector('[data-draft]')?.textContent).toBe('') if (change === 'workspace') { await render('workspace-2') @@ -129,6 +144,7 @@ describe('OS attachment destination through input-method composition', () => { act(() => latest().flushPendingAttachments()) expect(container.querySelector('[data-draft]')?.textContent).toBe('') expect(latest().imageAttachments).toEqual([]) + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toEqual([]) expect(container.querySelector('[data-notice]')?.textContent).toBe( 'This workspace changed hosts while attaching — drop the files again.' ) @@ -138,11 +154,42 @@ describe('OS attachment destination through input-method composition', () => { it('attaches an unchanged queued OS destination normally', async () => { await render('workspace-1') await act(async () => latest().attachExternalPaths(['/local/file.txt'])) + expect(readNativeChatDraftCache('drop-test')).toBe('') + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toHaveLength(1) composing = false act(() => latest().flushPendingAttachments()) expect(container.querySelector('[data-draft]')?.textContent).toBe('@/local/file.txt ') + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toEqual([]) }) + it.each([true, false])( + 'uses current image support when queued with acceptsImages=%s', + async (acceptsImages) => { + const path = '/local/image.png' + await render('workspace-1', acceptsImages) + await act(async () => latest().attachExternalPaths([path])) + expect(mocks.stat).toHaveBeenCalledOnce() + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toHaveLength(1) + expect(latest().imageAttachments.every(({ pending }) => pending)).toBe(true) + expect(container.querySelector('[data-draft]')?.textContent).toBe('') + + const currentAcceptsImages = !acceptsImages + await render('workspace-1', currentAcceptsImages) + composing = false + act(() => latest().flushPendingAttachments()) + act(() => latest().flushPendingAttachments()) + + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toEqual([]) + expect(latest().imageAttachments.map(({ path }) => path)).toEqual( + currentAcceptsImages ? [path] : [] + ) + expect(nativeChatImagesHoldSend(latest().imageAttachments)).toBe(false) + expect(container.querySelector('[data-draft]')?.textContent).toBe( + currentAcceptsImages ? '' : `@${path} ` + ) + } + ) + it.each([true, false])( 'keeps the workspace-file exemption off OS drops (queued=$queued)', async (queued) => { @@ -164,4 +211,83 @@ describe('OS attachment destination through input-method composition', () => { ) } ) + + it('reserves before stat and settles the captured scope across removal, failure and remount', async () => { + let finish = (): void => {} + mocks.stat + .mockReturnValueOnce( + new Promise((resolve) => { + finish = resolve + }) + ) + .mockRejectedValueOnce(new Error('unreadable')) + await render('workspace-1') + act(() => latest().attachExternalPaths(['/a.png', '/bad.png', '/removed.png', '/notes.txt'])) + expect(nativeChatImagesHoldSend(latest().imageAttachments)).toBe(true) + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toHaveLength(4) + const removed = latest().imageAttachments.find( + ({ pendingName }) => pendingName === 'removed.png' + ) + if (!removed) { + throw new Error('Missing reserved chip') + } + act(() => latest().removeImageAttachment(removed.id)) + act(() => root.unmount()) + await act(async () => finish()) + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toEqual([]) + root = createRoot(container) + await render('workspace-1') + expect(latest().imageAttachments).toMatchObject([{ path: '/a.png' }]) + expect(latest().imageAttachments).toHaveLength(1) + expect(nativeChatImagesHoldSend(latest().imageAttachments)).toBe(false) + expect(readNativeChatDraftCache('drop-test')).toBe('@/notes.txt') + }) + + it('settles prepared pending work quietly when composition loses its composer', async () => { + await render('workspace-1') + await act(async () => latest().attachExternalPaths(['/a.png', '/notes.txt', '/removed.png'])) + const removed = latest().imageAttachments.find( + ({ pendingName }) => pendingName === 'removed.png' + ) + if (!removed) { + throw new Error('Missing reserved chip') + } + act(() => latest().removeImageAttachment(removed.id)) + const other = document.createElement('input') + document.body.append(other) + other.focus() + act(() => root.unmount()) + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toEqual([]) + expect(readNativeChatDraftCache('drop-test')).toBe('@/notes.txt') + root = createRoot(container) + await render('workspace-1') + expect(latest().imageAttachments).toMatchObject([{ path: '/a.png' }]) + expect(latest().imageAttachments).toHaveLength(1) + await new Promise((resolve) => requestAnimationFrame(resolve)) + expect(document.activeElement).toBe(other) + other.remove() + }) + + it('releases refused and disabled work, including stat spanning disable and re-enable', async () => { + await render('workspace-1') + act(() => + latest().attachResolvedPaths(Array.from({ length: 256 }, (_, i) => `/queued/${i}.txt`)) + ) + await act(async () => latest().attachExternalPaths(['/refused.png'])) + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toEqual([]) + let finish = (): void => {} + mocks.stat.mockReturnValueOnce( + new Promise((resolve) => { + finish = resolve + }) + ) + act(() => latest().attachExternalPaths(['/late.png'])) + await render('workspace-1', true, true) + await render('workspace-1') + await act(async () => finish()) + act(() => latest().flushPendingAttachments()) + expect(nativeChatPendingAttachmentSnapshot('drop-test')).toEqual([]) + expect(latest().imageAttachments).toEqual([]) + expect(container.querySelector('[data-draft]')?.textContent).toBe('') + }) }) diff --git a/src/renderer/src/components/native-chat/native-chat-floating-file-drop.test.tsx b/src/renderer/src/components/native-chat/native-chat-floating-file-drop.test.tsx index 6914b12cb0db..342af5780221 100644 --- a/src/renderer/src/components/native-chat/native-chat-floating-file-drop.test.tsx +++ b/src/renderer/src/components/native-chat/native-chat-floating-file-drop.test.tsx @@ -3,6 +3,7 @@ import { act, cleanup, fireEvent, render } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import type { TerminalTab } from '../../../../shared/terminal-tab-types' +import { createUuidV4 } from '../../../../shared/uuid-v4' import { NativeChatPaneFileDropSurface } from './NativeChatPaneFileDropSurface' import { useNativeChatFileDrops } from './use-native-chat-file-drops' @@ -39,10 +40,10 @@ function Composer({ attach, notice }: { attach: () => void; notice: () => void } disabled: false, attachResolvedPaths: attach, pendingChips: { - begin: () => null, - resolve: () => {}, + begin: createUuidV4, + resolve: () => false, drop: () => false, - attachReferences: () => {} + attachReferences: () => false }, setNotice: notice }) @@ -117,7 +118,8 @@ describe('floating chat attachments with a different remote runtime focused', () access: { kind: 'user-file' } }) expect(attach).toHaveBeenCalledExactlyOnceWith([path], undefined, { - destinationIsCurrent: expect.any(Function) + destinationIsCurrent: expect.any(Function), + operation: { apply: expect.any(Function), cancel: expect.any(Function) } }) expect(attach.mock.calls[0][2].destinationIsCurrent()).toBe(true) expect(upload).not.toHaveBeenCalled() diff --git a/src/renderer/src/components/native-chat/native-chat-pending-attachment-cache.ts b/src/renderer/src/components/native-chat/native-chat-pending-attachment-cache.ts index a2c771a6568d..ef3ad5caf8cc 100644 --- a/src/renderer/src/components/native-chat/native-chat-pending-attachment-cache.ts +++ b/src/renderer/src/components/native-chat/native-chat-pending-attachment-cache.ts @@ -116,19 +116,20 @@ export function settleNativeChatPendingAttachmentReferences( scopeKey: string, references: { id: string; path: string }[], insertAtCaret?: (paths: string[]) => void -): void { +): boolean { const owner = pendingOwners.get(scopeKey) const paths = references.flatMap(({ id, path }) => takeNativeChatPendingAttachment(scopeKey, id) ? [path] : [] ) if (paths.length === 0) { - return + return false } if (insertAtCaret) { insertAtCaret(paths) } else { appendNativeChatDraftCache(scopeKey, paths.map(formatNativeChatFileReference).join(' '), owner) } + return true } export function clearNativeChatPendingAttachments(scopeKey: string): void { diff --git a/src/renderer/src/components/native-chat/native-chat-resolved-path-ownership.ts b/src/renderer/src/components/native-chat/native-chat-resolved-path-ownership.ts index 9e6321b1d6b9..c42b925f105a 100644 --- a/src/renderer/src/components/native-chat/native-chat-resolved-path-ownership.ts +++ b/src/renderer/src/components/native-chat/native-chat-resolved-path-ownership.ts @@ -1,7 +1,13 @@ import { translate } from '@/i18n/i18n' import type { NativeChatAttachmentOwner } from './native-chat-attachment-upload' +export type NativeChatResolvedPathOperation = { + apply: (insertReferences: ((paths: string[]) => void) | null) => boolean + cancel: () => void +} + export type NativeChatResolvedPathOptions = { + operation?: NativeChatResolvedPathOperation /** Revalidates the destination without granting workspace-file provenance. */ destinationIsCurrent?: () => boolean /** Revalidates internal path ownership when an IME-delayed attachment is applied. */ diff --git a/src/renderer/src/components/native-chat/native-chat-session-attachment-drop.ts b/src/renderer/src/components/native-chat/native-chat-session-attachment-drop.ts index e51be382d945..42949251479b 100644 --- a/src/renderer/src/components/native-chat/native-chat-session-attachment-drop.ts +++ b/src/renderer/src/components/native-chat/native-chat-session-attachment-drop.ts @@ -10,15 +10,27 @@ import { type NativeChatRuntimeSessionAttachmentOwner } from './native-chat-attachment-upload' +export type NativeChatPendingAttachmentOptions = { + insertReferences?: ((paths: string[]) => void) | null +} + /** The composer's pending-chip controls, as an upload drives them. */ export type NativeChatPendingAttachmentChips = { begin: (previewUrl?: string, pendingName?: string) => string | null - resolve: (id: string, path: string, connectionId?: string | null) => void + resolve: ( + id: string, + path: string, + connectionId?: string | null, + options?: NativeChatPendingAttachmentOptions + ) => boolean /** Removes the chip; false when the user already removed it, so its file must not attach. */ drop: (id: string) => boolean /** Adds stored files as `@path` references to the scope's draft, which keeps them through an * input-method composition or a remount. */ - attachReferences: (references: { id: string; path: string }[]) => void + attachReferences: ( + references: { id: string; path: string }[], + options?: NativeChatPendingAttachmentOptions + ) => boolean } /** diff --git a/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts b/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts index 2eb20ac79545..1522f2f8c22a 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts @@ -1,5 +1,12 @@ import type { NativeChatComposerInput } from './native-chat-composer-input' -import { useCallback, useEffect, useMemo, useSyncExternalStore, type RefObject } from 'react' +import { + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useSyncExternalStore, + type RefObject +} from 'react' import { nativeChatComposerTargetIsRemote, nativeChatLocalAttachmentUnsupportedNotice, @@ -15,7 +22,10 @@ import { import { useRestoredNativeChatComposerDraftImageCheck } from './native-chat-composer-draft-image-check' import type { NativeChatResolvedPathOptions } from './native-chat-resolved-path-ownership' import { useNativeChatResolvedPathAttachments } from './use-native-chat-resolved-path-attachments' -import type { NativeChatPendingAttachmentChips } from './native-chat-session-attachment-drop' +import type { + NativeChatPendingAttachmentChips, + NativeChatPendingAttachmentOptions +} from './native-chat-session-attachment-drop' import { addNativeChatPendingAttachment, clearNativeChatPendingAttachments, @@ -67,7 +77,7 @@ export function useNativeChatComposerAttachments({ flushPendingAttachments: () => void removeImageAttachment: (id: string) => void beginPendingImageAttachment: (previewUrl?: string, pendingName?: string) => string | null - resolvePendingImageAttachment: (id: string, path: string, connectionId?: string | null) => void + resolvePendingImageAttachment: NativeChatPendingAttachmentChips['resolve'] revealPendingImageAttachment: (id: string, previewUrl?: string) => void dropPendingImageAttachment: (id: string) => boolean pendingChips: NativeChatPendingAttachmentChips @@ -105,15 +115,24 @@ export function useNativeChatComposerAttachments({ [pending, previews, restoring, settled] ) const mountedRef = useMemo( - () => ({ scopeKey: attachmentScopeKey, current: true }), + () => ({ scopeKey: attachmentScopeKey, current: true, acceptsImages: true }), [attachmentScopeKey] ) + // Captured callbacks retain this scope's last committed capability after unmount. + useLayoutEffect(() => { + mountedRef.acceptsImages = acceptsImages + }, [acceptsImages, mountedRef]) useEffect(() => { mountedRef.current = true return () => { mountedRef.current = false } }, [mountedRef]) + useLayoutEffect(() => { + if (disabled) { + clearNativeChatPendingAttachments(attachmentScopeKey) + } + }, [attachmentScopeKey, disabled]) const nextAttachmentId = useCallback(() => createUuidV4(), []) @@ -157,6 +176,7 @@ export function useNativeChatComposerAttachments({ caret, disabled, isComposing, + mountedRef, noteAttachmentTargetBlocked, setCaret, setDraft, @@ -196,27 +216,32 @@ export function useNativeChatComposerAttachments({ ) const attachPendingReferences = useCallback( - (references: { id: string; path: string }[]) => { - settleNativeChatPendingAttachmentReferences( + (references: { id: string; path: string }[], options?: NativeChatPendingAttachmentOptions) => { + return settleNativeChatPendingAttachmentReferences( attachmentScopeKey, references, - mountedRef.current && !disabledRef.current && !isComposing() - ? (paths) => attachResolvedPaths(paths, null) - : undefined + options?.insertReferences !== undefined + ? (options.insertReferences ?? undefined) + : mountedRef.current && !disabledRef.current && !isComposing() + ? (paths) => attachResolvedPaths(paths, null) + : undefined ) }, [attachResolvedPaths, attachmentScopeKey, disabledRef, isComposing, mountedRef] ) const resolvePendingImageAttachment = useCallback( - (id: string, path: string, connectionId?: string | null) => { - if (acceptsImages) { - settleNativeChatPendingAttachment(attachmentScopeKey, id, path, connectionId) - } else { - attachPendingReferences([{ id, path }]) - } + ( + id: string, + path: string, + connectionId?: string | null, + options?: NativeChatPendingAttachmentOptions + ) => { + return mountedRef.acceptsImages + ? settleNativeChatPendingAttachment(attachmentScopeKey, id, path, connectionId) + : attachPendingReferences([{ id, path }], options) }, - [acceptsImages, attachPendingReferences, attachmentScopeKey] + [attachPendingReferences, attachmentScopeKey, mountedRef] ) const revealPendingImageAttachment = useCallback( diff --git a/src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx index e2e7a41c105e..8ee0bba3d62a 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx @@ -48,11 +48,12 @@ function deferred(): { promise: Promise; resolve: (value: T) => void } { } function noPendingChips(): NativeChatPendingAttachmentChips { + let id = 0 return { - begin: vi.fn(() => null), - resolve: vi.fn(), + begin: vi.fn(() => String(++id)), + resolve: vi.fn(() => true), drop: vi.fn(() => true), - attachReferences: vi.fn() + attachReferences: vi.fn(() => true) } } @@ -171,7 +172,8 @@ describe('useNativeChatExternalAttachments', () => { access: { kind: 'user-file' } }) expect(attachResolvedPaths).toHaveBeenCalledWith(['/local/a.txt'], undefined, { - destinationIsCurrent: expect.any(Function) + destinationIsCurrent: expect.any(Function), + operation: expect.any(Object) }) }) @@ -215,7 +217,7 @@ describe('useNativeChatExternalAttachments', () => { expect(attachResolvedPaths).toHaveBeenCalledExactlyOnceWith( ['/external/a.png', '/external/c.png'], undefined, - { destinationIsCurrent: expect.any(Function) } + { destinationIsCurrent: expect.any(Function), operation: expect.any(Object) } ) expect(mocks.stat).toHaveBeenCalledTimes(3) }) @@ -365,9 +367,9 @@ describe('useNativeChatExternalAttachments', () => { begun.push(name ?? '') return `chip-${begun.length}` }), - resolve: vi.fn(), + resolve: vi.fn(() => true), drop: vi.fn((id: string) => !removed.has(id)), - attachReferences: vi.fn() + attachReferences: vi.fn(() => true) } } @@ -425,12 +427,14 @@ describe('useNativeChatExternalAttachments', () => { expect(chips.resolve).toHaveBeenCalledExactlyOnceWith( 'chip-1', '/srv/agent-session-attachments/u1/shot.png', - null + null, + undefined ) expect(chips.drop).not.toHaveBeenCalled() - expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith([ - { id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' } - ]) + expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith( + [{ id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' }], + undefined + ) // The client never reads its own disk for these paths: the server stores the bytes. expect(mocks.stat).not.toHaveBeenCalled() }) @@ -492,9 +496,10 @@ describe('useNativeChatExternalAttachments', () => { uploaded([['/Users/me/notes.md', '/srv/agent-session-attachments/u1/notes.md']]) ) ) - expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith([ - { id: 'chip-1', path: '/srv/agent-session-attachments/u1/notes.md' } - ]) + expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith( + [{ id: 'chip-1', path: '/srv/agent-session-attachments/u1/notes.md' }], + undefined + ) }) it('keeps each file operation ID through reference settlement, including removed chips', async () => { @@ -520,10 +525,13 @@ describe('useNativeChatExternalAttachments', () => { ) ) - expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith([ - { id: 'chip-1', path: '/srv/agent-session-attachments/u1/report.pdf' }, - { id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' } - ]) + expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith( + [ + { id: 'chip-1', path: '/srv/agent-session-attachments/u1/report.pdf' }, + { id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' } + ], + undefined + ) }) it('names, in one notice, each file that did not attach', async () => { @@ -549,9 +557,10 @@ describe('useNativeChatExternalAttachments', () => { ) expect(chips.drop).toHaveBeenCalledWith('chip-1') - expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith([ - { id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' } - ]) + expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith( + [{ id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' }], + undefined + ) // The cause, the size limit here, rides in the same notice. expect(notices).toEqual([ "Couldn't attach huge.mov. 'huge.mov' is 60 MB, over the 50 MB chat attachment limit." @@ -618,7 +627,8 @@ describe('useNativeChatExternalAttachments', () => { expect(mocks.resolveNativeChatAttachmentOwnerForWorktree).toHaveBeenCalled() expect(mocks.prepareNativeChatSessionAttachmentUpload).not.toHaveBeenCalled() expect(attachResolvedPaths).toHaveBeenCalledWith(['/local/a.txt'], undefined, { - destinationIsCurrent: expect.any(Function) + destinationIsCurrent: expect.any(Function), + operation: expect.any(Object) }) }) }) diff --git a/src/renderer/src/components/native-chat/use-native-chat-external-attachments.ts b/src/renderer/src/components/native-chat/use-native-chat-external-attachments.ts index 8920f76585d8..e1fc8de86327 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-external-attachments.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-external-attachments.ts @@ -1,5 +1,6 @@ import { useCallback, useLayoutEffect, useRef } from 'react' import { useAppStore } from '@/store' +import { basename } from '@/lib/path' import { NATIVE_FILE_DROP_MAX_PATHS } from '../../../../shared/native-file-drop' import { nativeChatAttachmentOwnerUnchanged, @@ -24,6 +25,7 @@ import { import { userNamedFileAccess } from '@/lib/local-file-access' import { useMountedRef } from '@/hooks/useMountedRef' import { findTerminalTabWorktreeId } from './native-chat-file-link' +import { isNativeChatImageAttachmentPath } from './native-chat-image-paste' export type UseNativeChatExternalAttachmentsArgs = { terminalTabId: string @@ -130,8 +132,6 @@ export function useNativeChatExternalAttachments({ ) const capturedWorktreeId = currentWorktreeId() const ownerStillCurrent = (): boolean => - // Server uploads settle into the captured scope even while its composer is unmounted. - (owner.kind === 'runtime-session' || mountedRef.current) && destinationIsCurrent() && isSameComposerWorkspace(capturedWorkspace, workspaceRef.current) && capturedWorktreeId === currentWorktreeId() && @@ -172,34 +172,75 @@ export function useNativeChatExternalAttachments({ }) return } - const readablePaths: string[] = [] - for (const targetPath of paths) { - if (disabledRef.current || !mountedRef.current) { + const chips = pendingChipsRef.current + const pending: { path: string; chipId: string }[] = [] + try { + for (const path of paths) { + const chipId = chips.begin(undefined, basename(path)) + if (chipId) { + pending.push({ path, chipId }) + } + } + if (pending.length === 0) { + return + } + const readable: typeof pending = [] + for (const entry of pending) { + if (disabledRef.current) { + return + } + if (!ownerStillCurrent()) { + setNotice(nativeChatAttachmentOwnerChangedNotice()) + return + } + try { + await window.api.fs.stat({ filePath: entry.path, access: userNamedFileAccess() }) + readable.push(entry) + } catch { + // Skip unreadable paths, matching workspace composer drops. + chips.drop(entry.chipId) + } + } + if (disabledRef.current) { return } if (!ownerStillCurrent()) { setNotice(nativeChatAttachmentOwnerChangedNotice()) return } - try { - await window.api.fs.stat({ filePath: targetPath, access: userNamedFileAccess() }) - readablePaths.push(targetPath) - } catch { - // Skip unreadable paths, matching workspace composer drops. + if (readable.length === 0) { + setNotice(nativeChatAttachmentUnreadableNotice()) + return } - } - if (disabledRef.current || !mountedRef.current) { - return - } - if (!ownerStillCurrent()) { - setNotice(nativeChatAttachmentOwnerChangedNotice()) - return - } - if (readablePaths.length === 0) { + const prepared = pending.splice(0) + attachResolvedPaths( + readable.map(({ path }) => path), + undefined, + { + destinationIsCurrent: ownerStillCurrent, + operation: { + apply: (insertReferences) => { + const completion = { insertReferences } + let attached = false + for (const { path, chipId } of readable) { + attached = + (isNativeChatImageAttachmentPath(path) + ? chips.resolve(chipId, path, undefined, completion) + : chips.attachReferences([{ id: chipId, path }], completion)) || attached + } + return attached + }, + cancel: () => prepared.forEach(({ chipId }) => chips.drop(chipId)) + } + } + ) + } catch { setNotice(nativeChatAttachmentUnreadableNotice()) - return + } finally { + for (const { chipId } of pending) { + chips.drop(chipId) + } } - attachResolvedPaths(readablePaths, undefined, { destinationIsCurrent: ownerStillCurrent }) } }, [attachResolvedPaths, mountedRef, resolveAttachmentOwner, setNotice] diff --git a/src/renderer/src/components/native-chat/use-native-chat-resolved-path-attachments.ts b/src/renderer/src/components/native-chat/use-native-chat-resolved-path-attachments.ts index e159c8660425..dd3b3512cf05 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-resolved-path-attachments.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-resolved-path-attachments.ts @@ -1,4 +1,4 @@ -import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react' +import { useCallback, useEffect, useLayoutEffect, useRef, type RefObject } from 'react' import { translate } from '@/i18n/i18n' import { NATIVE_FILE_DROP_MAX_PATHS } from '../../../../shared/native-file-drop' import { formatNativeChatFileReference } from './native-chat-composer-target' @@ -7,13 +7,19 @@ import { isNativeChatImageAttachmentPath } from './native-chat-image-paste' import { nativeChatAttachmentOwnerChangedNotice } from './native-chat-attachment-upload' import { nativeChatWorkspaceAttachmentMismatchNotice, + type NativeChatResolvedPathOperation, type NativeChatResolvedPathOptions } from './native-chat-resolved-path-ownership' type ResolvedAttachmentPath = { path: string connectionId?: string | null -} & NativeChatResolvedPathOptions +} & Omit + +type ResolvedAttachmentBatch = { + paths: ResolvedAttachmentPath[] + operation?: NativeChatResolvedPathOperation +} type Args = { /** False when the agent takes no image input: an image is then referenced by path like any file. */ @@ -23,6 +29,7 @@ type Args = { caret: number disabled: boolean isComposing: () => boolean + mountedRef: RefObject noteAttachmentTargetBlocked: () => void setCaret: (caret: number) => void setDraft: (updater: (previous: string) => string) => void @@ -37,6 +44,7 @@ export function useNativeChatResolvedPathAttachments({ caret, disabled, isComposing, + mountedRef, noteAttachmentTargetBlocked, setCaret, setDraft, @@ -51,14 +59,16 @@ export function useNativeChatResolvedPathAttachments({ disabledRef: RefObject flushPendingAttachments: () => void } { - const pendingResolvedBatchesRef = useRef([]) + const pendingResolvedBatchesRef = useRef([]) const pendingPathLimitRejectedRef = useRef(false) const disabledRef = useRef(disabled) useLayoutEffect(() => { disabledRef.current = disabled if (disabled) { + const batches = pendingResolvedBatchesRef.current pendingResolvedBatchesRef.current = [] + batches.forEach(({ operation }) => operation?.cancel()) pendingPathLimitRejectedRef.current = false } }, [disabled]) @@ -87,13 +97,17 @@ export function useNativeChatResolvedPathAttachments({ ) const resolvedBatchIsCurrent = useCallback( - (resolvedPaths: ResolvedAttachmentPath[]): boolean => { + (resolvedPaths: ResolvedAttachmentPath[], quiet = false): boolean => { if (resolvedPaths.some(({ destinationIsCurrent }) => destinationIsCurrent?.() === false)) { - setNotice(nativeChatAttachmentOwnerChangedNotice()) + if (!quiet) { + setNotice(nativeChatAttachmentOwnerChangedNotice()) + } return false } if (resolvedPaths.some(({ targetOwnerIsCurrent }) => targetOwnerIsCurrent?.() === false)) { - setNotice(nativeChatWorkspaceAttachmentMismatchNotice()) + if (!quiet) { + setNotice(nativeChatWorkspaceAttachmentMismatchNotice()) + } return false } return true @@ -102,44 +116,64 @@ export function useNativeChatResolvedPathAttachments({ ) const applyResolvedPaths = useCallback( - (resolvedPaths: ResolvedAttachmentPath[], focus: boolean, preserveNotice = false) => { - if (resolvedPaths.length === 0 || !resolvedBatchIsCurrent(resolvedPaths)) { - return - } - // Ownership is per path, so the verdict is too: a queued batch can mix a - // workspace drop the target owns with a client-local paste it does not, - // and one verdict for the batch would refuse the drop the user can make. - const ownedBlocked = - resolvedPaths.some(({ targetOwnerIsCurrent }) => targetOwnerIsCurrent) && - attachmentTargetBlocked(true) - const clientLocalBlocked = - resolvedPaths.some(({ targetOwnerIsCurrent }) => !targetOwnerIsCurrent) && - attachmentTargetBlocked(false) - // Filter rather than partition: the two halves are interleaved, and these - // references are inserted in the order the user attached them. - const attachable = resolvedPaths.filter(({ targetOwnerIsCurrent }) => - targetOwnerIsCurrent ? !ownedBlocked : !clientLocalBlocked - ) - if (attachable.length === 0) { - noteAttachmentTargetBlocked() - return - } - const attachesAsImage = (path: string): boolean => - acceptsImages && isNativeChatImageAttachmentPath(path) - const imagePaths = attachable.filter(({ path }) => attachesAsImage(path)) - const filePaths = attachable - .filter(({ path }) => !attachesAsImage(path)) - .map(({ path }) => path) - // Images ride along on submit so chips and the TUI input cannot diverge. - appendImageAttachments(imagePaths.map(({ path, connectionId }) => ({ path, connectionId }))) - insertFileReferences(filePaths) - if (ownedBlocked || clientLocalBlocked) { - noteAttachmentTargetBlocked() - } else if (!preserveNotice) { - setNotice(null) - } - if (focus) { - requestAnimationFrame(() => textareaRef.current?.focus()) + ( + batches: ResolvedAttachmentBatch[], + focus: boolean, + preserveNotice = false, + intoScope = false + ) => { + try { + const current = batches.filter(({ paths }) => { + if (resolvedBatchIsCurrent(paths, intoScope)) { + return true + } + preserveNotice = true + return false + }) + const paths = current.flatMap((batch) => batch.paths) + const ownedBlocked = + paths.some(({ targetOwnerIsCurrent }) => targetOwnerIsCurrent) && + attachmentTargetBlocked(true) + const clientLocalBlocked = + paths.some(({ targetOwnerIsCurrent }) => !targetOwnerIsCurrent) && + attachmentTargetBlocked(false) + const filePaths: string[] = [] + let attached = false + for (const batch of current) { + const attachable = batch.paths.filter(({ targetOwnerIsCurrent }) => + targetOwnerIsCurrent ? !ownedBlocked : !clientLocalBlocked + ) + if (attachable.length === 0) { + continue + } + if (batch.operation) { + attached = + batch.operation.apply(intoScope ? null : (paths) => filePaths.push(...paths)) || + attached + } else { + const images = attachable.filter( + ({ path }) => acceptsImages && isNativeChatImageAttachmentPath(path) + ) + appendImageAttachments(images.map(({ path, connectionId }) => ({ path, connectionId }))) + filePaths.push( + ...attachable.filter((path) => !images.includes(path)).map(({ path }) => path) + ) + attached = true + } + } + insertFileReferences(filePaths) + if (!intoScope) { + if (ownedBlocked || clientLocalBlocked) { + noteAttachmentTargetBlocked() + } else if (attached && !preserveNotice) { + setNotice(null) + } + if (attached && focus) { + requestAnimationFrame(() => textareaRef.current?.focus()) + } + } + } finally { + batches.forEach(({ operation }) => operation?.cancel()) } }, [ @@ -153,6 +187,27 @@ export function useNativeChatResolvedPathAttachments({ textareaRef ] ) + const applyRef = useRef(applyResolvedPaths) + useLayoutEffect(() => { + applyRef.current = applyResolvedPaths + }, [applyResolvedPaths]) + useEffect( + () => () => { + const batches = pendingResolvedBatchesRef.current + pendingResolvedBatchesRef.current = [] + if (disabledRef.current) { + batches.forEach(({ operation }) => operation?.cancel()) + } else { + applyRef.current( + batches.filter(({ operation }) => operation), + false, + true, + true + ) + } + }, + [mountedRef] + ) const attachResolvedPaths = useCallback( ( @@ -160,82 +215,80 @@ export function useNativeChatResolvedPathAttachments({ connectionId?: string | null, options: NativeChatResolvedPathOptions = {} ) => { - if (paths.length === 0 || disabledRef.current) { - return - } - if (options.destinationIsCurrent?.() === false) { - setNotice(nativeChatAttachmentOwnerChangedNotice()) - return - } - const targetOwnerIsCurrent = options.targetOwnerIsCurrent?.() - if (targetOwnerIsCurrent === false) { - setNotice(nativeChatWorkspaceAttachmentMismatchNotice()) - return - } - if (attachmentTargetBlocked(targetOwnerIsCurrent === true)) { - noteAttachmentTargetBlocked() - return - } - if (isComposing()) { - const pendingCount = pendingResolvedBatchesRef.current.reduce( - (count, batch) => count + batch.length, - 0 - ) - if (paths.length > NATIVE_FILE_DROP_MAX_PATHS - pendingCount) { - // Reject the whole completion so ordered path batches are never partially applied. - pendingPathLimitRejectedRef.current = true - setNotice( - translate( - 'components.native-chat.composer.pendingAttachmentLimit', - 'Too many attachments are waiting. Finish composing before attaching more.' - ) + const { operation: suppliedOperation, ...pathOptions } = options + let operation = suppliedOperation + try { + if (paths.length === 0 || disabledRef.current) { + return + } + if ( + !resolvedBatchIsCurrent( + paths.map((path) => ({ path, ...pathOptions })), + !mountedRef.current ) + ) { return } - pendingResolvedBatchesRef.current.push( - paths.map((path) => ({ - path, - connectionId, - ...options - })) - ) - return + if (attachmentTargetBlocked(options.targetOwnerIsCurrent?.() === true)) { + if (mountedRef.current) { + noteAttachmentTargetBlocked() + } + return + } + if (isComposing() && (mountedRef.current || !operation)) { + const pendingCount = pendingResolvedBatchesRef.current.reduce( + (count, batch) => count + batch.paths.length, + 0 + ) + if (paths.length > NATIVE_FILE_DROP_MAX_PATHS - pendingCount) { + pendingPathLimitRejectedRef.current = true + setNotice( + translate( + 'components.native-chat.composer.pendingAttachmentLimit', + 'Too many attachments are waiting. Finish composing before attaching more.' + ) + ) + return + } + pendingResolvedBatchesRef.current.push({ + paths: paths.map((path) => ({ path, connectionId, ...pathOptions })), + operation + }) + operation = undefined + return + } + const batch = { + paths: paths.map((path) => ({ path, connectionId, ...pathOptions })), + operation + } + operation = undefined + applyResolvedPaths([batch], true, false, !mountedRef.current) + } finally { + operation?.cancel() } - applyResolvedPaths( - paths.map((path) => ({ - path, - connectionId, - ...options - })), - true - ) }, [ applyResolvedPaths, attachmentTargetBlocked, isComposing, + mountedRef, noteAttachmentTargetBlocked, + resolvedBatchIsCurrent, setNotice ] ) const flushPendingAttachments = useCallback(() => { const batches = pendingResolvedBatchesRef.current - let preserveNotice = pendingPathLimitRejectedRef.current + const preserveNotice = pendingPathLimitRejectedRef.current pendingResolvedBatchesRef.current = [] pendingPathLimitRejectedRef.current = false - if (batches.length === 0 || disabledRef.current) { + if (disabledRef.current) { + batches.forEach(({ operation }) => operation?.cancel()) return } - const paths = batches.flatMap((batch) => { - if (resolvedBatchIsCurrent(batch)) { - return batch - } - preserveNotice = true - return [] - }) - applyResolvedPaths(paths, false, preserveNotice) - }, [applyResolvedPaths, resolvedBatchIsCurrent]) + applyResolvedPaths(batches, false, preserveNotice) + }, [applyResolvedPaths]) return { attachResolvedPaths, disabledRef, flushPendingAttachments } } From 0cc796df1be2d45ae8e07f8e28c97bdba97df8b8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 08:46:30 -0700 Subject: [PATCH 2/5] test(native-chat): server-upload chip calls carry no options without paste --- ...-native-chat-external-attachments.test.tsx | 35 ++++++++----------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx index 8ee0bba3d62a..2a1b7f2463ff 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx @@ -427,14 +427,12 @@ describe('useNativeChatExternalAttachments', () => { expect(chips.resolve).toHaveBeenCalledExactlyOnceWith( 'chip-1', '/srv/agent-session-attachments/u1/shot.png', - null, - undefined + null ) expect(chips.drop).not.toHaveBeenCalled() - expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith( - [{ id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' }], - undefined - ) + expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith([ + { id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' } + ]) // The client never reads its own disk for these paths: the server stores the bytes. expect(mocks.stat).not.toHaveBeenCalled() }) @@ -496,10 +494,9 @@ describe('useNativeChatExternalAttachments', () => { uploaded([['/Users/me/notes.md', '/srv/agent-session-attachments/u1/notes.md']]) ) ) - expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith( - [{ id: 'chip-1', path: '/srv/agent-session-attachments/u1/notes.md' }], - undefined - ) + expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith([ + { id: 'chip-1', path: '/srv/agent-session-attachments/u1/notes.md' } + ]) }) it('keeps each file operation ID through reference settlement, including removed chips', async () => { @@ -525,13 +522,10 @@ describe('useNativeChatExternalAttachments', () => { ) ) - expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith( - [ - { id: 'chip-1', path: '/srv/agent-session-attachments/u1/report.pdf' }, - { id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' } - ], - undefined - ) + expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith([ + { id: 'chip-1', path: '/srv/agent-session-attachments/u1/report.pdf' }, + { id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' } + ]) }) it('names, in one notice, each file that did not attach', async () => { @@ -557,10 +551,9 @@ describe('useNativeChatExternalAttachments', () => { ) expect(chips.drop).toHaveBeenCalledWith('chip-1') - expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith( - [{ id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' }], - undefined - ) + expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith([ + { id: 'chip-2', path: '/srv/agent-session-attachments/u2/notes.md' } + ]) // The cause, the size limit here, rides in the same notice. expect(notices).toEqual([ "Couldn't attach huge.mov. 'huge.mov' is 60 MB, over the 50 MB chat attachment limit." From 76511230d909b7dcaea8589b544983038e1d20ad Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:04:15 -0700 Subject: [PATCH 3/5] refactor(native-chat): move the composer's image chip list into its own hook Main's server-owned paste pushed the attachments hook past the file length limit. --- .../use-native-chat-composer-attachments.ts | 51 ++----------------- .../use-native-chat-composer-image-chips.ts | 49 ++++++++++++++++++ 2 files changed, 54 insertions(+), 46 deletions(-) create mode 100644 src/renderer/src/components/native-chat/use-native-chat-composer-image-chips.ts diff --git a/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts b/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts index 5a3e4aada458..c49b2f097a1b 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts @@ -1,12 +1,5 @@ import type { NativeChatComposerInput } from './native-chat-composer-input' -import { - useCallback, - useEffect, - useLayoutEffect, - useMemo, - useSyncExternalStore, - type RefObject -} from 'react' +import { useCallback, useEffect, useLayoutEffect, useMemo, type RefObject } from 'react' import { nativeChatComposerTargetIsRemote, nativeChatLocalAttachmentUnsupportedNotice, @@ -14,12 +7,9 @@ import { } from './native-chat-composer-target' import type { NativeChatComposerImageAttachment } from './NativeChatComposerField' import { - isKeptLocalPaste, readNativeChatComposerDraft, - subscribeToNativeChatComposerDraft, updateNativeChatComposerDraft } from './native-chat-composer-draft-store' -import { useRestoredNativeChatComposerDraftImageCheck } from './native-chat-composer-draft-image-check' import type { NativeChatResolvedPathOptions } from './native-chat-resolved-path-ownership' import { useNativeChatResolvedPathAttachments } from './use-native-chat-resolved-path-attachments' import type { @@ -32,11 +22,10 @@ import { settleNativeChatPendingAttachment, settleNativeChatPendingAttachmentReferences, nativeChatPendingAttachmentSnapshot, - takeNativeChatPendingAttachment, - useNativeChatPendingAttachments + takeNativeChatPendingAttachment } from './native-chat-pending-attachment-cache' import { appendNativeChatAttachmentCache } from './native-chat-draft-cache' -import { useNativeChatComposerAttachmentPreviews } from './use-native-chat-composer-attachment-previews' +import { useNativeChatComposerImageChips } from './use-native-chat-composer-image-chips' import { createUuidV4 } from '../../../../shared/uuid-v4' export type UseNativeChatComposerAttachmentsArgs = { @@ -87,38 +76,8 @@ export function useNativeChatComposerAttachments({ dropPendingImageAttachment: (id: string) => boolean pendingChips: NativeChatPendingAttachmentChips } { - const subscribe = useCallback( - (listener: () => void) => subscribeToNativeChatComposerDraft(attachmentScopeKey, listener), - [attachmentScopeKey] - ) - const settled = useSyncExternalStore( - subscribe, - () => readNativeChatComposerDraft(attachmentScopeKey).images - ) - // Why: a restored paste shows only once main confirms it is still kept, so until the restore - // check is done it waits like a chip still saving, instead of flashing before a placeholder. - const restoring = useRestoredNativeChatComposerDraftImageCheck(attachmentScopeKey, subscribe) - // Chips still on their way live outside the composer, so one a prompt card unmounted comes back - // still pending and settles into the draft whichever composer is showing. - const pending = useNativeChatPendingAttachments(attachmentScopeKey) - const { previews, setPreview, releasePreview, releaseAllPreviews } = - useNativeChatComposerAttachmentPreviews(settled, pending) - const imageAttachments = useMemo( - () => [ - ...settled.map((image) => { - const previewUrl = previews.get(image.id) - if (restoring && isKeptLocalPaste(image)) { - return { ...image, pending: true } - } - return previewUrl ? { ...image, previewUrl } : image - }), - ...pending.map((chip) => { - const previewUrl = previews.get(chip.id) - return previewUrl ? { ...chip, previewUrl } : chip - }) - ], - [pending, previews, restoring, settled] - ) + const { imageAttachments, setPreview, releasePreview, releaseAllPreviews } = + useNativeChatComposerImageChips(attachmentScopeKey) const mountedRef = useMemo( () => ({ scopeKey: attachmentScopeKey, current: true, acceptsImages: true }), [attachmentScopeKey] diff --git a/src/renderer/src/components/native-chat/use-native-chat-composer-image-chips.ts b/src/renderer/src/components/native-chat/use-native-chat-composer-image-chips.ts new file mode 100644 index 000000000000..4822b65a136f --- /dev/null +++ b/src/renderer/src/components/native-chat/use-native-chat-composer-image-chips.ts @@ -0,0 +1,49 @@ +import { useCallback, useMemo, useSyncExternalStore } from 'react' +import type { NativeChatComposerImageAttachment } from './NativeChatComposerField' +import { + isKeptLocalPaste, + readNativeChatComposerDraft, + subscribeToNativeChatComposerDraft +} from './native-chat-composer-draft-store' +import { useRestoredNativeChatComposerDraftImageCheck } from './native-chat-composer-draft-image-check' +import { useNativeChatPendingAttachments } from './native-chat-pending-attachment-cache' +import { useNativeChatComposerAttachmentPreviews } from './use-native-chat-composer-attachment-previews' + +/** The composer's image chips: the draft's settled images, then those still on their way. */ +export function useNativeChatComposerImageChips(attachmentScopeKey: string): { + imageAttachments: NativeChatComposerImageAttachment[] +} & Omit, 'previews'> { + const subscribe = useCallback( + (listener: () => void) => subscribeToNativeChatComposerDraft(attachmentScopeKey, listener), + [attachmentScopeKey] + ) + const settled = useSyncExternalStore( + subscribe, + () => readNativeChatComposerDraft(attachmentScopeKey).images + ) + // Why: a restored paste shows only once main confirms it is still kept, so until the restore + // check is done it waits like a chip still saving, instead of flashing before a placeholder. + const restoring = useRestoredNativeChatComposerDraftImageCheck(attachmentScopeKey, subscribe) + // Chips still on their way live outside the composer, so one a prompt card unmounted comes back + // still pending and settles into the draft whichever composer is showing. + const pending = useNativeChatPendingAttachments(attachmentScopeKey) + const { previews, setPreview, releasePreview, releaseAllPreviews } = + useNativeChatComposerAttachmentPreviews(settled, pending) + const imageAttachments = useMemo( + () => [ + ...settled.map((image) => { + const previewUrl = previews.get(image.id) + if (restoring && isKeptLocalPaste(image)) { + return { ...image, pending: true } + } + return previewUrl ? { ...image, previewUrl } : image + }), + ...pending.map((chip) => { + const previewUrl = previews.get(chip.id) + return previewUrl ? { ...chip, previewUrl } : chip + }) + ], + [pending, previews, restoring, settled] + ) + return { imageAttachments, setPreview, releasePreview, releaseAllPreviews } +} From 847bd36edddb1f12efd296f672e2bd856015aeef Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 16 Oct 2026 18:58:13 -0700 Subject: [PATCH 4/5] fix(native-chat): a pending attachment chip shows a spinner and its name, not a stacked icon A local drop now waits as a pending chip, which drew the kind icon, the file name and a centered spinner on top of each other. Without a thumbnail the chip shows the spinner above the name; with one, the dimmed picture keeps a spinner strip along its bottom. --- .../NativeChatImageAttachmentPreview.tsx | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/renderer/src/components/native-chat/NativeChatImageAttachmentPreview.tsx b/src/renderer/src/components/native-chat/NativeChatImageAttachmentPreview.tsx index e011cfebef3f..e6d780bf4868 100644 --- a/src/renderer/src/components/native-chat/NativeChatImageAttachmentPreview.tsx +++ b/src/renderer/src/components/native-chat/NativeChatImageAttachmentPreview.tsx @@ -207,20 +207,23 @@ function NativeChatImageThumbnail({ alt={label} className={`size-full object-cover${isPending ? ' opacity-50' : ''}`} /> - ) : attachment.pendingName ? ( - - - - {attachment.pendingName} - + ) : isPending ? ( + // Why: a chip still on its way shows only that it is loading and what it is. + + + {attachment.pendingName ? ( + + {attachment.pendingName} + + ) : null} ) : ( )} - {isPending ? ( - - + {isPending && thumbnailSrc ? ( + + ) : null} onRemove(attachment.id)} /> From 03472b3536da5c61ab36be4b4267a56d5f6cb9ec Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:08:58 -0700 Subject: [PATCH 5/5] test(native-chat): a pending chip shows its name and spinner, no kind icon --- .../NativeChatImageAttachmentPreview.test.tsx | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/src/renderer/src/components/native-chat/NativeChatImageAttachmentPreview.test.tsx b/src/renderer/src/components/native-chat/NativeChatImageAttachmentPreview.test.tsx index e49929fe06c1..eea5ca02025d 100644 --- a/src/renderer/src/components/native-chat/NativeChatImageAttachmentPreview.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatImageAttachmentPreview.test.tsx @@ -117,22 +117,13 @@ describe('NativeChatImageAttachmentPreview', () => { ) }) - it('shows a dropped file by name and kind while it uploads', () => { + it('shows a dropped file by name beside its spinner, with no kind icon, while it waits', () => { mocks.useLocalImageSrc.mockReturnValue(undefined) renderPreview({ id: 'a1', path: '', pending: true, pendingName: 'report.pdf' }) expect(screen.getByRole('button', { name: 'Uploading report.pdf…' })).toBeTruthy() expect(screen.getByText('report.pdf')).toBeTruthy() - expect(document.querySelector('.lucide-file-text')).toBeTruthy() - expect(document.querySelector('.lucide-image')).toBeFalsy() - }) - - it('shows a dropped image as an image while it uploads', () => { - mocks.useLocalImageSrc.mockReturnValue(undefined) - renderPreview({ id: 'a1', path: '', pending: true, pendingName: 'shot.png' }) - - expect(screen.getByText('shot.png')).toBeTruthy() - expect(document.querySelector('.lucide-image')).toBeTruthy() + expect(document.querySelector('.lucide-file-text, .lucide-image')).toBeFalsy() }) it('offers the full-size file, not the clipboard thumbnail, to the chat copy menu', () => {