Upload failure text carries what the client can observe
Some checks failed
Build pull request / Build pull request (pull_request) Failing after 3m5s

Adds connectivity (onLine, effectiveType, rtt, downlink, saveData), tab visibility, ms since
last user activity, time to first progress and bytes loaded, and ms to failure. Nothing patches
XMLHttpRequest; the progress handler and window input events are the only sources.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Void 2026-11-08 17:32:32 +00:00
commit 95f0dce05f
2 changed files with 119 additions and 10 deletions

View file

@ -145,12 +145,48 @@ export type ContentUploadOptions = {
onError: (error: MatrixError) => void;
};
let lastUserActivity = Date.now();
export const noteUserActivity = () => {
lastUserActivity = Date.now();
};
if (typeof window !== 'undefined') {
['pointerdown', 'keydown', 'touchstart'].forEach((type) =>
window.addEventListener(type, noteUserActivity, { capture: true, passive: true })
);
}
/** What the progress handler saw of one upload, for the failure text. */
export type UploadTrace = {
startedAt: number;
firstProgressAt?: number;
loaded?: number;
total?: number;
};
const describeNetwork = (): string => {
const online =
typeof navigator !== 'undefined' && navigator.onLine === false ? 'offline' : 'online';
const c = typeof navigator !== 'undefined' ? (navigator as any).connection : undefined;
const net = c
? `${c.effectiveType ?? '?'} rtt ${c.rtt ?? '?'}ms down ${c.downlink ?? '?'}Mbps saveData ${
c.saveData ? 'on' : 'off'
}`
: 'n/a';
const tab = typeof document !== 'undefined' ? document.visibilityState : 'n/a';
return `${online}, net ${net}, tab ${tab}`;
};
/**
* Describe why an upload died. The SDK reports an XHR with status 0 as an
* AbortError DOMException with an empty message, so name, size, type and
* whether the browser can still read the file all go into the message.
* Describe why an upload died. The SDK reports an XHR with status 0 as an AbortError
* DOMException with an empty message, so the text carries what the client can observe: file
* size, type and readability, connectivity, tab visibility, idle time, progress, time to fail.
*/
export const uploadFailure = async (e: any, file: TUploadContent): Promise<MatrixError> => {
export const uploadFailure = async (
e: any,
file: TUploadContent,
trace?: UploadTrace
): Promise<MatrixError> => {
const now = Date.now();
const name = typeof e?.name === 'string' && e.name ? e.name : 'Error';
const message = typeof e?.message === 'string' ? e.message : '';
let readable: string;
@ -160,8 +196,19 @@ export const uploadFailure = async (e: any, file: TUploadContent): Promise<Matri
} catch (readErr: any) {
readable = `file unreadable (${readErr?.name ?? 'unknown'})`;
}
const detail = `${file.size} bytes, ${file.type || 'unknown type'}, ${readable}`;
const error = `Upload failed: ${message ? `${name}: ${message}` : name} (${detail})`;
const parts = [`${file.size} bytes`, file.type || 'unknown type', readable, describeNetwork()];
parts.push(`idle ${now - lastUserActivity}ms`);
if (trace) {
parts.push(
trace.firstProgressAt === undefined
? 'no progress'
: `first progress ${trace.firstProgressAt - trace.startedAt}ms ${trace.loaded ?? 0}/${
trace.total ?? '?'
}B`
);
parts.push(`failed after ${now - trace.startedAt}ms`);
}
const error = `Upload failed: ${message ? `${name}: ${message}` : name} (${parts.join(', ')})`;
const err = new MatrixError({ error, errcode: name });
(err as any).cause = e;
return err;
@ -174,11 +221,17 @@ export const uploadContent = async (
) => {
const { name, fileType, hideFilename, onProgress, onPromise, onSuccess, onError } = options;
const trace: UploadTrace = { startedAt: Date.now() };
const uploadPromise = mx.uploadContent(file, {
name,
type: fileType,
includeFilename: !hideFilename,
progressHandler: onProgress,
progressHandler: (progress) => {
if (trace.firstProgressAt === undefined) trace.firstProgressAt = Date.now();
trace.loaded = progress.loaded;
trace.total = progress.total;
onProgress?.(progress);
},
});
onPromise?.(uploadPromise);
try {
@ -187,7 +240,7 @@ export const uploadContent = async (
if (mxc) onSuccess(mxc);
else onError(new MatrixError(data));
} catch (e: any) {
onError(await uploadFailure(e, file));
onError(await uploadFailure(e, file, trace));
}
};

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { uploadFailure } from './matrix';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { noteUserActivity, uploadFailure } from './matrix';
const abort = () => new DOMException('', 'AbortError');
@ -42,3 +42,59 @@ describe('uploadFailure', () => {
expect(err.errcode).toBe('Error');
});
});
describe('uploadFailure client trace', () => {
const blob = new Blob(['abcd'], { type: 'image/jpeg' });
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('reports connectivity, visibility and idle time at the moment of failure', async () => {
vi.useFakeTimers();
vi.setSystemTime(10_000);
vi.stubGlobal('navigator', {
onLine: false,
connection: { effectiveType: '3g', rtt: 300, downlink: 1.5, saveData: true },
});
vi.stubGlobal('document', { visibilityState: 'hidden' });
noteUserActivity();
vi.setSystemTime(13_000);
const err = await uploadFailure(abort(), blob, { startedAt: 12_000 });
expect(err.message).toContain('offline');
expect(err.message).toContain('3g rtt 300ms down 1.5Mbps saveData on');
expect(err.message).toContain('tab hidden');
expect(err.message).toContain('idle 3000ms');
expect(err.message).toContain('failed after 1000ms');
});
it('says so when no progress event ever arrived', async () => {
vi.useFakeTimers();
vi.setSystemTime(5_000);
const err = await uploadFailure(abort(), blob, { startedAt: 4_000 });
expect(err.message).toContain('no progress');
});
it('reports time to first progress and bytes loaded when some arrived', async () => {
vi.useFakeTimers();
vi.setSystemTime(9_000);
const err = await uploadFailure(abort(), blob, {
startedAt: 5_000,
firstProgressAt: 5_120,
loaded: 65536,
total: 700000,
});
expect(err.message).toContain('first progress 120ms');
expect(err.message).toContain('65536/700000B');
expect(err.message).toContain('failed after 4000ms');
});
it('copes with a browser that has no connection info or document', async () => {
vi.stubGlobal('navigator', { onLine: true });
vi.stubGlobal('document', undefined);
const err = await uploadFailure(abort(), blob, { startedAt: Date.now() });
expect(err.message).toContain('online');
expect(err.message).toContain('net n/a');
});
});