diff --git a/src/app/components/upload-card/CompactUploadCardRenderer.tsx b/src/app/components/upload-card/CompactUploadCardRenderer.tsx index d10fbaa6..5fe73a10 100644 --- a/src/app/components/upload-card/CompactUploadCardRenderer.tsx +++ b/src/app/components/upload-card/CompactUploadCardRenderer.tsx @@ -6,6 +6,7 @@ import { useMatrixClient } from '../../hooks/useMatrixClient'; import { TUploadContent } from '../../utils/matrix'; import { bytesToSize, getFileTypeIcon } from '../../utils/common'; import { useMediaConfig } from '../../hooks/useMediaConfig'; +import { UploadFailureNote } from './UploadFailureNote'; import { PhoneHitSpread28 } from '../../styles/PhoneHit.css'; type CompactUploadCardRendererProps = { @@ -93,7 +94,7 @@ export function CompactUploadCardRenderer({ )} {upload.status === UploadStatus.Error && ( - {upload.error.message} + )} {upload.status === UploadStatus.Idle && fileSizeExceeded && ( diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index 4ca1cc87..e1d12843 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -12,6 +12,7 @@ import { } from '../../state/room/roomInputDrafts'; import { useObjectURL } from '../../hooks/useObjectURL'; import { useMediaConfig } from '../../hooks/useMediaConfig'; +import { UploadFailureNote } from './UploadFailureNote'; import { PhoneHitSpread28 } from '../../styles/PhoneHit.css'; type PreviewImageProps = { @@ -192,7 +193,7 @@ export function UploadCardRenderer({ )} {upload.status === UploadStatus.Error && ( - {upload.error.message} + )} {upload.status === UploadStatus.Idle && fileSizeExceeded && ( diff --git a/src/app/components/upload-card/UploadFailureNote.test.tsx b/src/app/components/upload-card/UploadFailureNote.test.tsx new file mode 100644 index 00000000..c2f917ec --- /dev/null +++ b/src/app/components/upload-card/UploadFailureNote.test.tsx @@ -0,0 +1,33 @@ +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { describe, expect, it } from 'vitest'; +import { uploadFailure } from '../../utils/matrix'; +import { UploadFailureNote } from './UploadFailureNote'; + +const text = (html: string) => + html + .replace(/<[^>]*>/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + +describe('the failed upload card', () => { + it('leads with the reason and the next step, and keeps the diagnostics behind Details', async () => { + const error = await uploadFailure(new DOMException('', 'AbortError'), new Blob(['abcd']), { + startedAt: Date.now(), + }); + const html = renderToStaticMarkup(); + const before = html.slice(0, html.indexOf(']*>.*Details.*<\/details>/s); + expect(text(html.slice(html.indexOf(' { + const html = renderToStaticMarkup(); + expect(text(html)).toContain('Upload failed. Send again'); + expect(text(html)).toContain('boom'); + }); +}); diff --git a/src/app/components/upload-card/UploadFailureNote.tsx b/src/app/components/upload-card/UploadFailureNote.tsx new file mode 100644 index 00000000..df4498ba --- /dev/null +++ b/src/app/components/upload-card/UploadFailureNote.tsx @@ -0,0 +1,22 @@ +import React from 'react'; +import { Text } from 'folds'; +import { uploadFailureText } from '../../utils/uploadReason'; + +/** A failed upload as the card shows it: the reason and what to do, the diagnostic text one tap away. */ +export function UploadFailureNote({ error }: { error: Error }) { + return ( + <> + {uploadFailureText(error)} +
+ + + Details + + + + {error.message} + +
+ + ); +} diff --git a/src/app/features/albums/shareSet.test.ts b/src/app/features/albums/shareSet.test.ts index 3fd85700..8fc4a8b8 100644 --- a/src/app/features/albums/shareSet.test.ts +++ b/src/app/features/albums/shareSet.test.ts @@ -215,6 +215,22 @@ describe('refusals', () => { ); }); + it('a failure the client saw, not the server, is named too', async () => { + const dropped: SharePort = { + send: async () => '$e', + contentOf: async () => { + throw Object.assign(new Error('x'), { + errcode: 'AbortError', + info: { aborted: true, progressed: true }, + }); + }, + }; + const res = await sendShareSet(dropped, 't', clips.slice(0, 1)); + expect(resultNote(res)).toBe( + 'Nothing was shared. Not sent: a.ogg (the connection dropped partway through)' + ); + }); + it('an unnamed failure lists the bare name', async () => { const res = await sendShareSet(refuse('M_UNKNOWN'), 't', clips.slice(0, 1)); expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg'); diff --git a/src/app/features/albums/shareSet.ts b/src/app/features/albums/shareSet.ts index 7c30fecc..007d7e91 100644 --- a/src/app/features/albums/shareSet.ts +++ b/src/app/features/albums/shareSet.ts @@ -3,6 +3,8 @@ // are the same thing to every viewer. Ports are injected so the order and the failure rules are // testable without a homeserver. See docs/file-zone.md, "Share a set". +import { uploadReason } from '../../utils/uploadReason'; + export type ShareFile = { name: string; mimeType: string }; /** What sendShareSet needs from the outside world. */ @@ -45,17 +47,8 @@ export const freshest = (album: ExistingAlbum, events: ThreadEvent[]): ExistingA export const CANCELLED = 'stopped'; -const REFUSALS: Record = { - M_TOO_LARGE: 'too large for this server', - M_FORBIDDEN: 'not allowed to upload here', - M_LIMIT_EXCEEDED: 'uploading too fast, try again shortly', -}; - -/** The sentence for a homeserver refusal we know, from the error's Matrix errcode. */ -export const refusalOf = (e: unknown): string | undefined => { - const code = (e as { errcode?: unknown } | null)?.errcode; - return typeof code === 'string' && Object.hasOwn(REFUSALS, code) ? REFUSALS[code] : undefined; -}; +/** The short reason for a failure we can name (the homeserver's refusal or what the client saw), else undefined. */ +export const refusalOf = (e: unknown): string | undefined => uploadReason(e)?.cause; /** The reply relation Matrix clients expect for a thread message: root, with the last event as fallback reply. */ export const threadRelation = (rootId: string, lastId: string) => ({ diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index f0ded881..d4972677 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -18,6 +18,7 @@ import { IImageInfo, IThumbnailContent, IVideoInfo } from '../../types/matrix/co import { AccountDataEvent } from '../../types/matrix/accountData'; import { getStateEvent } from './room'; import { Membership, StateEvent } from '../../types/matrix/room'; +import { NO_INFO, UploadFailureInfo } from './uploadReason'; const DOMAIN_REGEX = /\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b/; @@ -392,8 +393,19 @@ export const uploadFailure = async ( if (trace.previous) parts.push(`retried (attempt 1: ${trace.previous})`); } const error = `Upload failed: ${message ? `${name}: ${message}` : name} (${parts.join(', ')})`; - const err = new MatrixError({ error, errcode: name }); + // A homeserver refusal keeps its own errcode (M_TOO_LARGE ...), which is what names it to the sender. + const errcode = typeof e?.errcode === 'string' && e.errcode.startsWith('M_') ? e.errcode : name; + const err = new MatrixError({ error, errcode }); (err as any).cause = e; + const info: UploadFailureInfo = { + unreadable: readable !== 'file readable', + offline: typeof navigator !== 'undefined' && navigator.onLine === false, + hidden: typeof document !== 'undefined' && document?.visibilityState === 'hidden', + aborted: name === 'AbortError', + progressed: trace?.firstProgressAt !== undefined, + stopped: trace?.signalAborted === true, + }; + (err as any).info = info; return err; }; @@ -435,14 +447,14 @@ export const uploadContent = async ( body = await copyInMemory(file); } catch (readErr: any) { const errcode = readErr?.name || 'Error'; - onError( - new MatrixError({ - error: `Upload failed: file unreadable before upload (${errcode}) (${file.size} bytes, ${ - file.type || 'unknown type' - })`, - errcode, - }) - ); + const unreadable = new MatrixError({ + error: `Upload failed: file unreadable before upload (${errcode}) (${file.size} bytes, ${ + file.type || 'unknown type' + })`, + errcode, + }); + (unreadable as any).info = { ...NO_INFO, unreadable: true }; + onError(unreadable); return; } const probe = startAbortProbe(); diff --git a/src/app/utils/uploadReason.test.ts b/src/app/utils/uploadReason.test.ts new file mode 100644 index 00000000..d9e83d4d --- /dev/null +++ b/src/app/utils/uploadReason.test.ts @@ -0,0 +1,111 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { uploadContent, uploadFailure } from './matrix'; +import { uploadFailureText, uploadReason } from './uploadReason'; + +// What a person reads, from failures built the way the app builds them: through uploadFailure and +// uploadContent, not by hand-made info objects. +const abort = () => new DOMException('', 'AbortError'); +const blob = new Blob(['abcd'], { type: 'image/jpeg' }); +const textOf = async (e: unknown, trace = { startedAt: Date.now() } as any, file: Blob = blob) => + uploadFailureText(await uploadFailure(e, file, trace)); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('what the sender is told when an upload fails', () => { + it('a drop before any byte left says the file never started, and to send again', async () => { + expect(await textOf(abort())).toBe( + 'Upload failed: the connection dropped before the file started. Send again.' + ); + }); + + it('a drop after progress says partway through and points at Wi-Fi', async () => { + const text = await textOf(abort(), { startedAt: 1, firstProgressAt: 5, loaded: 2, total: 4 }); + expect(text).toContain('dropped partway through'); + expect(text).toContain('Wi-Fi'); + }); + + it('a drop with the tab in the background says to keep the tab open', async () => { + vi.stubGlobal('document', { visibilityState: 'hidden' }); + const text = await textOf(abort()); + expect(text).toContain('(this tab was in the background)'); + expect(text).toContain('Keep this tab open'); + }); + + it('offline outranks the drop it caused', async () => { + vi.stubGlobal('navigator', { onLine: false }); + expect(await textOf(abort())).toBe('Upload failed: you are offline. Reconnect and send again.'); + }); + + it('offline is not blamed for a failure that was not a dropped request', async () => { + vi.stubGlobal('navigator', { onLine: false }); + expect(await textOf(new Error('Bad Gateway'))).toContain('Upload failed. Send again;'); + }); + + it('a file the browser can no longer read says to pick it again', async () => { + const gone = new Blob(['x']); + (gone as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); + expect(await textOf(abort(), undefined, gone)).toContain('can no longer read the file'); + }); + + it('a stopped upload says stopped, not that the connection failed', async () => { + const text = await textOf(abort(), { startedAt: 1, signalAborted: true }); + expect(text).toBe('Upload failed: stopped. Send it again when you are ready.'); + }); + + it('a homeserver refusal says what the server said in words, with what to do', () => { + expect(uploadFailureText({ errcode: 'M_TOO_LARGE' })).toBe( + 'Upload failed: too large for this server. Pick a smaller file.' + ); + expect(uploadFailureText({ errcode: 'M_FORBIDDEN' })).toContain('Ask a steward'); + expect(uploadFailureText({ errcode: 'M_LIMIT_EXCEEDED' })).toContain('Wait a moment'); + }); + + it('a failure we cannot name stays generic and sends the sender to the details', async () => { + const text = await textOf(new Error('Timeout')); + expect(text).toBe( + 'Upload failed. Send again; if it keeps failing, show the details below to a steward.' + ); + expect(uploadReason({ errcode: 'constructor' })).toBeUndefined(); + expect(uploadReason(null)).toBeUndefined(); + }); + + it('the long diagnostic text is still on the error for the details', async () => { + const err = await uploadFailure(abort(), blob, { startedAt: Date.now() }); + expect(err.message).toContain('4 bytes'); + expect(err.message).toContain('no progress'); + }); +}); + +describe('through uploadContent, as the composer and the share panel call it', () => { + it('an unreadable picked file is named before any request', async () => { + const bad = new Blob(['x']); + (bad as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); + const mx = { uploadContent: vi.fn() } as any; + const onError = vi.fn(); + await uploadContent(mx, bad, { onSuccess: vi.fn(), onError }); + expect(mx.uploadContent).not.toHaveBeenCalled(); + expect(uploadFailureText(onError.mock.calls[0][0])).toContain('can no longer read the file'); + }); + + it('a request that dies is told as a drop', async () => { + const mx = { uploadContent: () => Promise.reject(abort()) } as any; + const onError = vi.fn(); + await uploadContent(mx, blob, { onSuccess: vi.fn(), onError }); + expect(uploadFailureText(onError.mock.calls[0][0])).toContain('the connection dropped'); + }); + + it('a server that refuses keeps its errcode and is told in words', async () => { + const mx = { + uploadContent: () => + Promise.reject(Object.assign(new Error('x'), { errcode: 'M_TOO_LARGE' })), + } as any; + const onError = vi.fn(); + await uploadContent(mx, blob, { onSuccess: vi.fn(), onError }); + expect(onError.mock.calls[0][0].errcode).toBe('M_TOO_LARGE'); + expect(uploadFailureText(onError.mock.calls[0][0])).toBe( + 'Upload failed: too large for this server. Pick a smaller file.' + ); + }); +}); diff --git a/src/app/utils/uploadReason.ts b/src/app/utils/uploadReason.ts new file mode 100644 index 00000000..badbaf95 --- /dev/null +++ b/src/app/utils/uploadReason.ts @@ -0,0 +1,78 @@ +// What a person is told when an upload fails: a cause they can name and the thing to do next. +// uploadFailure (matrix.ts) attaches the facts the client observed as `info`; the homeserver's +// refusals arrive as Matrix errcodes. The long diagnostic text stays on the error's message. + +/** What the client observed at the moment an upload died. */ +export type UploadFailureInfo = { + /** The browser could not read the picked file back. */ + unreadable: boolean; + /** navigator.onLine was false. */ + offline: boolean; + /** The tab was in the background. */ + hidden: boolean; + /** The request was aborted (the SDK reports a dropped XHR as an AbortError). */ + aborted: boolean; + /** At least one progress event arrived before it died. */ + progressed: boolean; + /** The sender pressed Stop. */ + stopped: boolean; +}; + +export const NO_INFO: UploadFailureInfo = { + unreadable: false, + offline: false, + hidden: false, + aborted: false, + progressed: false, + stopped: false, +}; + +export type UploadReason = { cause: string; action: string }; + +const REFUSALS: Record = { + M_TOO_LARGE: { cause: 'too large for this server', action: 'Pick a smaller file.' }, + M_FORBIDDEN: { + cause: 'not allowed to upload here', + action: 'Ask a steward if you should be able to.', + }, + M_LIMIT_EXCEEDED: { + cause: 'uploading too fast, try again shortly', + action: 'Wait a moment and send again.', + }, +}; + +/** The reason for a failure we can name, or undefined when we cannot: then the text stays generic. */ +export const uploadReason = (e: unknown): UploadReason | undefined => { + const code = (e as { errcode?: unknown } | null)?.errcode; + if (typeof code === 'string' && Object.hasOwn(REFUSALS, code)) return REFUSALS[code]; + const info = (e as { info?: Partial } | null)?.info; + if (!info) return undefined; + if (info.stopped) return { cause: 'stopped', action: 'Send it again when you are ready.' }; + if (info.unreadable) + return { + cause: 'this device can no longer read the file', + action: 'Pick it again; if it came from another app, save a copy first.', + }; + // Offline and hidden-tab are only read as the cause of a dropped request, not of any failure. + if (!info.aborted) return undefined; + if (info.offline) return { cause: 'you are offline', action: 'Reconnect and send again.' }; + if (info.hidden) + return { + cause: 'the connection dropped (this tab was in the background)', + action: 'Keep this tab open while it uploads, and send again.', + }; + return info.progressed + ? { + cause: 'the connection dropped partway through', + action: 'Send again; a large file is safer on Wi-Fi.', + } + : { cause: 'the connection dropped before the file started', action: 'Send again.' }; +}; + +/** The line the upload card shows: the reason when there is one, else a generic line. */ +export const uploadFailureText = (e: unknown): string => { + const reason = uploadReason(e); + return reason + ? `Upload failed: ${reason.cause}. ${reason.action}` + : 'Upload failed. Send again; if it keeps failing, show the details below to a steward.'; +};