diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 2a45143b023..93300d62740 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -3240,7 +3240,10 @@ describe('AgentPanelRoot attach flow', () => { integration_target: 'assets', feature_flag: 'agent_panel', feature_flag_state: 'enabled', - project_context: 'agent_composer' + project_context: 'agent_composer', + upload_failure_cause: 'http_500', + file_type: 'image/png', + file_size_bytes: 1 } }) const serializedReport = JSON.stringify(vi.mocked(reportError).mock.calls) diff --git a/src/workbench/extensions/agent/composables/agent/useAttachment.test.ts b/src/workbench/extensions/agent/composables/agent/useAttachment.test.ts index b30f7e2cf5b..443484507de 100644 --- a/src/workbench/extensions/agent/composables/agent/useAttachment.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAttachment.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it, vi } from 'vitest' import { reportError } from '@/platform/telemetry/reportError' +import { + AgentApiError, + AgentResponseUnreadableError +} from '../../services/agent/agentRestClient' import type { ComposerAttachment } from './useComposer' import { MAX_ATTACHMENT_BYTES, useAttachment } from './useAttachment' @@ -268,7 +272,7 @@ describe('useAttachment', () => { const registry = chipRegistry() const { addFiles } = useAttachment({ upload, onError, ...registry }) - await addFiles([fileOfSize(privateFilename, 1024)]) + await addFiles([fileOfSize(privateFilename, 1024, 'image/png')]) expect(registry.chips).toEqual([]) expect(onError).toHaveBeenCalledOnce() @@ -282,7 +286,10 @@ describe('useAttachment', () => { integration_target: 'assets', feature_flag: 'agent_panel', feature_flag_state: 'enabled', - project_context: 'agent_composer' + project_context: 'agent_composer', + upload_failure_cause: 'unknown', + file_type: 'image/png', + file_size_bytes: 1024 } }) const reportedError = vi.mocked(reportError).mock.calls[0][0] as Error @@ -296,6 +303,140 @@ describe('useAttachment', () => { ) }) + it.for([ + { + label: 'an API error', + cause: new AgentApiError('nope', 503, undefined), + expectedCause: 'http_503' + }, + { + label: 'an unreadable response', + cause: new AgentResponseUnreadableError(new Error('bad json')), + expectedCause: 'unreadable_response' + }, + { + label: 'an upload error with a timeout-like message', + cause: new Error('Timed out after an upstream timeout'), + expectedCause: 'unknown' + } + ])( + 'tags the upload failure cause for $label', + async ({ cause, expectedCause }) => { + const upload = vi.fn().mockRejectedValue(cause) + const registry = chipRegistry() + const { addFiles } = useAttachment({ upload, ...registry }) + + await addFiles([fileOfSize('shot.png', 2048, 'image/png')]) + + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + tags: expect.objectContaining({ + upload_failure_cause: expectedCause, + file_type: 'image/png', + file_size_bytes: 2048 + }) + }) + ) + } + ) + + it.for([ + { label: 'empty', fileType: '' }, + { label: 'overlong', fileType: `application/${'x'.repeat(128)}` } + ])( + 'reports a $label browser-provided MIME type as unknown', + async ({ fileType }) => { + const upload = vi.fn().mockRejectedValue(new Error('upload failed')) + const registry = chipRegistry() + const { addFiles } = useAttachment({ upload, ...registry }) + + await addFiles([fileOfSize('unknown.bin', 128, fileType)]) + + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + tags: expect.objectContaining({ + file_type: 'unknown', + file_size_bytes: 128 + }) + }) + ) + } + ) + + it('does not report a path from a constructed MIME parameter', async () => { + const privatePath = '/Users/alice/Secret/private.txt' + const upload = vi.fn().mockRejectedValue(new Error('upload failed')) + const registry = chipRegistry() + const { addFiles } = useAttachment({ upload, ...registry }) + + await addFiles([ + fileOfSize('unknown.bin', 128, `text/plain; name="${privatePath}"`) + ]) + + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + tags: expect.objectContaining({ file_type: 'unknown' }) + }) + ) + expect(JSON.stringify(vi.mocked(reportError).mock.calls)).not.toContain( + privatePath + ) + }) + + it('tags an aborted-by-timeout upload with the timeout failure cause', async () => { + vi.useFakeTimers() + try { + const upload = vi.fn(() => new Promise<{ ref: string }>(() => {})) + const registry = chipRegistry() + const { addFiles } = useAttachment({ + upload, + uploadTimeoutMs: 1000, + ...registry + }) + + const pending = addFiles([fileOfSize('stuck.png', 512, 'image/png')]) + await vi.advanceTimersByTimeAsync(1000) + await pending + + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + tags: expect.objectContaining({ + upload_failure_cause: 'timeout', + file_type: 'image/png', + file_size_bytes: 512 + }) + }) + ) + } finally { + vi.useRealTimers() + } + }) + + it('tags a non-cancelled AbortError upload with the aborted failure cause', async () => { + const upload = vi + .fn() + .mockRejectedValue(new DOMException('request aborted', 'AbortError')) + const registry = chipRegistry() + const { addFiles } = useAttachment({ upload, ...registry }) + + await addFiles([fileOfSize('shot.png', 512, 'image/png')]) + + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + tags: expect.objectContaining({ + upload_failure_cause: 'aborted', + file_type: 'image/png', + file_size_bytes: 512 + }) + }) + ) + }) + it('keeps earlier settled chips and continues the batch when one upload fails', async () => { const upload = vi .fn() @@ -534,7 +675,10 @@ describe('useAttachment', () => { tags: expect.objectContaining({ feature_area: 'agent', integration_target: 'assets', - outcome: 'failed' + outcome: 'failed', + upload_failure_cause: 'timeout', + file_type: 'unknown', + file_size_bytes: -1 }) }) } finally { diff --git a/src/workbench/extensions/agent/composables/agent/useAttachment.ts b/src/workbench/extensions/agent/composables/agent/useAttachment.ts index b94388a9aa2..5de2bd51b12 100644 --- a/src/workbench/extensions/agent/composables/agent/useAttachment.ts +++ b/src/workbench/extensions/agent/composables/agent/useAttachment.ts @@ -2,6 +2,10 @@ import { i18n } from '@/i18n' import { reportError } from '@/platform/telemetry/reportError' import { hasImageType } from '@/utils/eventUtils' import { formatSize } from '@/utils/formatUtil' +import { + AgentApiError, + AgentResponseUnreadableError +} from '../../services/agent/agentRestClient' import type { ComposerAttachment } from './useComposer' export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024 @@ -9,6 +13,16 @@ const UPLOAD_HANDSHAKE_TIMEOUT_MS = 30 * 1000 const UPLOAD_FLOOR_BYTES_PER_SECOND = 64 * 1024 const DEFERRED_FETCH_TIMEOUT_MS = 60 * 1000 const MAX_CONCURRENT_UPLOADS = 3 +const MAX_TELEMETRY_FILE_TYPE_LENGTH = 128 +const MIME_TYPE_PATTERN = + /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+\/[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ + +class DeadlineExceededError extends Error { + constructor(timeoutMs: number) { + super(`Timed out after ${timeoutMs}ms`) + this.name = 'DeadlineExceededError' + } +} interface UploadResult { ref: string @@ -35,6 +49,11 @@ function uploadDeadlineMs(file: File): number { ) } +function telemetryFileType(type: string | undefined): string { + if (!type || type.length > MAX_TELEMETRY_FILE_TYPE_LENGTH) return 'unknown' + return MIME_TYPE_PATTERN.test(type) ? type : 'unknown' +} + async function withDeadline( work: Promise, timeoutMs: number, @@ -44,7 +63,7 @@ async function withDeadline( const expiry = new Promise((_resolve, reject) => { timer = setTimeout(() => { onExpire?.() - reject(new Error(`Timed out after ${timeoutMs}ms`)) + reject(new DeadlineExceededError(timeoutMs)) }, timeoutMs) }) try { @@ -89,7 +108,27 @@ export function useAttachment(options: UseAttachmentOptions) { return true } - function failAttachment(id: string, name: string, errorType: string) { + // The file's declared size/type and the failure's shape (status code, + // timeout, abort) are safe, bounded context. The caught error's own + // message/stack are not reported: they can carry a local file path (e.g. a + // dropped file's full source path), which is why this always reports a + // fresh synthetic Error rather than the original cause. + function uploadFailureCause(cause: unknown): string { + if (cause instanceof AgentApiError) return `http_${cause.status}` + if (cause instanceof AgentResponseUnreadableError) + return 'unreadable_response' + if (cause instanceof DeadlineExceededError) return 'timeout' + if (cause instanceof DOMException && cause.name === 'AbortError') + return 'aborted' + return 'unknown' + } + + function failAttachment( + id: string, + file: { name: string; size?: number; type?: string }, + errorType: string, + cause: unknown + ) { return (): undefined => { reportError(new Error('Agent attachment upload failed'), { errorType, @@ -101,10 +140,15 @@ export function useAttachment(options: UseAttachmentOptions) { integration_target: 'assets', feature_flag: 'agent_panel', feature_flag_state: 'enabled', - project_context: 'agent_composer' + project_context: 'agent_composer', + upload_failure_cause: uploadFailureCause(cause), + file_type: telemetryFileType(file.type), + file_size_bytes: file.size ?? -1 } }) - options.onError?.(i18n.global.t('agent.attachmentUploadFailed', { name })) + options.onError?.( + i18n.global.t('agent.attachmentUploadFailed', { name: file.name }) + ) options.remove(id) return undefined } @@ -133,9 +177,9 @@ export function useAttachment(options: UseAttachmentOptions) { uploading: false }) return true - } catch { + } catch (cause) { if (!cancelled.has(id)) - failAttachment(id, file.name, 'agent_attachment_upload_failed')() + failAttachment(id, file, 'agent_attachment_upload_failed', cause)() return false } finally { settle(id) @@ -175,9 +219,9 @@ export function useAttachment(options: UseAttachmentOptions) { if (!(await uploadStagedFile(id, file))) return 'failed' options.onUploaded?.() return 'uploaded' - } catch { + } catch (cause) { if (cancelled.has(id)) return 'cancelled' - failAttachment(id, name, 'agent_attachment_fetch_failed')() + failAttachment(id, { name }, 'agent_attachment_fetch_failed', cause)() return 'failed' } finally { settle(id)