Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,20 +207,23 @@ function NativeChatImageThumbnail({
alt={label}
className={`size-full object-cover${isPending ? ' opacity-50' : ''}`}
/>
) : attachment.pendingName ? (
<span className="flex max-w-full flex-col items-center gap-0.5 px-1">
<KindIcon className="size-5 shrink-0 text-muted-foreground" />
<span className="max-w-full truncate text-xs text-muted-foreground">
{attachment.pendingName}
</span>
) : isPending ? (
// Why: a chip still on its way shows only that it is loading and what it is.
<span className="flex max-w-full flex-col items-center gap-1 px-1">
<LoadingSpinner className="size-4 shrink-0 text-muted-foreground" />
{attachment.pendingName ? (
<span className="max-w-full truncate text-xs text-muted-foreground">
{attachment.pendingName}
</span>
) : null}
</span>
) : (
<KindIcon className="size-5 text-muted-foreground" />
)}
</button>
{isPending ? (
<span className="pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-chat-canvas/50">
<LoadingSpinner className="size-4 text-muted-foreground" />
{isPending && thumbnailSrc ? (
<span className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center rounded-b-md bg-chat-canvas/90 py-0.5">
<LoadingSpinner className="size-3 text-muted-foreground" />
</span>
) : null}
<RemoveAttachmentButton onRemove={() => onRemove(attachment.id)} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<string | null>(null)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const attachments = useNativeChatComposerAttachments({
attachmentScopeKey: 'drop-test',
acceptsImages,
caret,
disabled: false,
disabled,
isComposing: () => composing,
resolveTarget: () => ({ ptyId: 'pty-1', settings: { activeRuntimeEnvironmentId: null } }),
textareaRef,
Expand All @@ -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
Expand All @@ -85,8 +97,10 @@ function latest(): Api {
return api
}

async function render(worktreeId?: string): Promise<void> {
await act(async () => root.render(<Probe worktreeId={worktreeId} />))
async function render(worktreeId?: string, acceptsImages = true, disabled = false): Promise<void> {
await act(async () =>
root.render(<Probe worktreeId={worktreeId} acceptsImages={acceptsImages} disabled={disabled} />)
)
}

beforeEach(() => {
Expand Down Expand Up @@ -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')
Expand All @@ -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.'
)
Expand All @@ -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) => {
Expand All @@ -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<void>((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<void>((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('')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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
})
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

/**
Expand Down
Loading
Loading