Upload failure text carries who called abort and what the owning component did
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled

For each upload attempt, XMLHttpRequest.prototype.abort and AbortController.prototype.abort are
wrapped (reference-counted across overlapping attempts, restored in finally) and every call is
recorded with a six-frame file:line:col stack; "abort calls: none" says the page called neither.
The upload hook also counts renders after attach (and those within 300ms) and any unmount.
The in-memory copy and the once-only retry are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Void 2026-11-08 18:45:29 +00:00
commit 3e57865eca
3 changed files with 356 additions and 45 deletions

View file

@ -1,9 +1,14 @@
import { atom, useAtom } from 'jotai';
import { atomFamily } from 'jotai/utils';
import { MatrixClient, UploadResponse, UploadProgress, MatrixError } from 'matrix-js-sdk';
import { useCallback } from 'react';
import { useCallback, useEffect, useRef } from 'react';
import { useThrottle } from '../hooks/useThrottle';
import { uploadContent, TUploadContent } from '../utils/matrix';
import {
ComponentLifecycle,
describeComponentLifecycle,
uploadContent,
TUploadContent,
} from '../utils/matrix';
export enum UploadStatus {
Idle = 'idle',
@ -105,22 +110,34 @@ export const useBindUploadAtom = (
const [upload, setUpload] = useAtom(uploadAtom);
const { file } = upload;
// For the failure text: renders and unmount of the component that owns this upload.
const life = useRef<ComponentLifecycle>({ attachedAt: 0, rendersAtAttach: 0, renders: [] });
if (life.current.renders.length < 50) life.current.renders.push(Date.now());
useEffect(() => {
const tracked = life.current;
tracked.unmountedAt = undefined;
return () => {
tracked.unmountedAt = Date.now();
};
}, []);
const handleProgress = useThrottle(
useCallback((progress: UploadProgress) => setUpload({ progress }), [setUpload]),
{ immediate: true, wait: 200 }
);
const startUpload = useCallback(
() =>
uploadContent(mx, file, {
hideFilename,
onPromise: (promise: Promise<UploadResponse>) => setUpload({ promise }),
onProgress: handleProgress,
onSuccess: (mxc) => setUpload({ mxc }),
onError: (error) => setUpload({ error }),
}),
[mx, file, hideFilename, setUpload, handleProgress]
);
const startUpload = useCallback(() => {
life.current.attachedAt = Date.now();
life.current.rendersAtAttach = life.current.renders.length;
return uploadContent(mx, file, {
hideFilename,
describeLifecycle: () => describeComponentLifecycle(life.current),
onPromise: (promise: Promise<UploadResponse>) => setUpload({ promise }),
onProgress: handleProgress,
onSuccess: (mxc) => setUpload({ mxc }),
onError: (error) => setUpload({ error }),
});
}, [mx, file, hideFilename, setUpload, handleProgress]);
const cancelUpload = useCallback(async () => {
if (upload.status === UploadStatus.Loading) {

View file

@ -143,6 +143,8 @@ export type ContentUploadOptions = {
onProgress?: (progress: UploadProgress) => void;
onSuccess: (mxc: string) => void;
onError: (error: MatrixError) => void;
/** Read at failure time: what the owning component did since the upload attached. */
describeLifecycle?: () => string;
};
let lastUserActivity = Date.now();
@ -155,6 +157,8 @@ if (typeof window !== 'undefined') {
);
}
export type AbortCall = { api: string; frames: string };
/** What the progress handler saw of one upload, for the failure text. */
export type UploadTrace = {
startedAt: number;
@ -163,6 +167,98 @@ export type UploadTrace = {
total?: number;
/** Summary of an earlier attempt of the same upload, when this one is a retry. */
previous?: string;
/** abort() calls the page made while this attempt ran; absent when not probed. */
aborts?: AbortCall[];
/** What the owning component did since the upload attached. */
lifecycle?: string;
};
const MAX_FRAMES = 6;
const MAX_ABORT_CALLS = 4;
/**
* An Error stack as `file:line:col < file:line:col`, at most six frames. The error line and the
* probe's own frame are dropped; origins and function names are not kept.
*/
export const formatAbortStack = (stack: string): string => {
const frames = stack
.split('\n')
.map((l) => l.trim())
.filter((l) => l.startsWith('at ') || l.includes('@'))
.map((l) => {
const m = /([^/\s()@]+):(\d+):(\d+)\)?$/.exec(l);
return m ? `${m[1]}:${m[2]}:${m[3]}` : undefined;
})
.filter((f): f is string => f !== undefined)
.slice(1, 1 + MAX_FRAMES);
return frames.length > 0 ? frames.join(' < ') : 'no stack';
};
export type ComponentLifecycle = {
attachedAt: number;
rendersAtAttach: number;
renders: number[];
unmountedAt?: number;
};
/** What the component that owns an upload did after the upload attached to it. */
export const describeComponentLifecycle = (life: ComponentLifecycle): string => {
const since = life.renders.slice(life.rendersAtAttach);
const quick = since.filter((t) => t - life.attachedAt <= 300).length;
const unmount =
life.unmountedAt === undefined
? 'not unmounted'
: `unmounted +${life.unmountedAt - life.attachedAt}ms`;
return `component: ${since.length} renders since attach (${quick} within 300ms), ${unmount}`;
};
const collectors = new Set<AbortCall[]>();
let restoreProbe: (() => void) | undefined;
/* eslint-disable no-param-reassign */
const patchAbort = (proto: { abort: (...a: any[]) => any }, api: string) => {
const original = proto.abort;
const wrapper = function abortProbe(this: unknown, ...args: any[]) {
const frames = formatAbortStack(new Error().stack ?? '');
collectors.forEach((calls) => {
if (calls.length < MAX_ABORT_CALLS) calls.push({ api, frames });
});
return original.apply(this, args);
};
proto.abort = wrapper;
return () => {
if (proto.abort === wrapper) proto.abort = original;
};
};
/* eslint-enable no-param-reassign */
/**
* Records every XMLHttpRequest.abort and AbortController.abort the page makes until stopped. The
* prototypes are wrapped while at least one probe runs and restored when the last one stops.
*/
export const startAbortProbe = () => {
const calls: AbortCall[] = [];
if (collectors.size === 0) {
const restores: (() => void)[] = [];
if (typeof XMLHttpRequest !== 'undefined') {
restores.push(patchAbort(XMLHttpRequest.prototype, 'XHR.abort'));
}
if (typeof AbortController !== 'undefined') {
restores.push(patchAbort(AbortController.prototype, 'AbortController.abort'));
}
restoreProbe = () => restores.forEach((r) => r());
}
collectors.add(calls);
return {
calls,
stop: () => {
collectors.delete(calls);
if (collectors.size === 0) {
restoreProbe?.();
restoreProbe = undefined;
}
},
};
};
const describeNetwork = (): string => {
@ -209,6 +305,14 @@ export const uploadFailure = async (
}B`
);
parts.push(`failed after ${now - trace.startedAt}ms`);
if (trace.aborts) {
parts.push(
trace.aborts.length === 0
? 'abort calls: none'
: `abort calls: ${trace.aborts.map((a) => `${a.api} ${a.frames}`).join('; ')}`
);
}
if (trace.lifecycle) parts.push(trace.lifecycle);
if (trace.previous) parts.push(`retried (attempt 1: ${trace.previous})`);
}
const error = `Upload failed: ${message ? `${name}: ${message}` : name} (${parts.join(', ')})`;
@ -227,46 +331,65 @@ export const uploadContent = async (
file: TUploadContent,
options: ContentUploadOptions
) => {
const { name, fileType, hideFilename, onProgress, onPromise, onSuccess, onError } = options;
const {
name,
fileType,
hideFilename,
onProgress,
onPromise,
onSuccess,
onError,
describeLifecycle,
} = options;
let previous: string | undefined;
for (let attempt = 1; ; attempt += 1) {
const trace: UploadTrace = { startedAt: Date.now(), previous };
const probe = startAbortProbe();
const trace: UploadTrace = { startedAt: Date.now(), previous, aborts: probe.calls };
const abortController = new AbortController();
const uploadPromise = mx.uploadContent(file, {
name,
type: fileType,
includeFilename: !hideFilename,
abortController,
progressHandler: (progress) => {
if (trace.firstProgressAt === undefined) trace.firstProgressAt = Date.now();
trace.loaded = progress.loaded;
trace.total = progress.total;
onProgress?.(progress);
},
});
onPromise?.(uploadPromise);
try {
// eslint-disable-next-line no-await-in-loop
const data = await uploadPromise;
const mxc = data.content_uri;
if (mxc) onSuccess(mxc);
else onError(new MatrixError(data));
return;
} catch (e: any) {
const elapsed = Date.now() - trace.startedAt;
const retry =
attempt === 1 &&
e?.name === 'AbortError' &&
!abortController.signal.aborted &&
trace.firstProgressAt === undefined &&
elapsed < RETRY_WINDOW_MS;
if (!retry) {
const uploadPromise = mx.uploadContent(file, {
name,
type: fileType,
includeFilename: !hideFilename,
abortController,
progressHandler: (progress) => {
if (trace.firstProgressAt === undefined) trace.firstProgressAt = Date.now();
trace.loaded = progress.loaded;
trace.total = progress.total;
onProgress?.(progress);
},
});
onPromise?.(uploadPromise);
try {
// eslint-disable-next-line no-await-in-loop
onError(await uploadFailure(e, file, trace));
const data = await uploadPromise;
const mxc = data.content_uri;
if (mxc) onSuccess(mxc);
else onError(new MatrixError(data));
return;
} catch (e: any) {
const elapsed = Date.now() - trace.startedAt;
const retry =
attempt === 1 &&
e?.name === 'AbortError' &&
!abortController.signal.aborted &&
trace.firstProgressAt === undefined &&
elapsed < RETRY_WINDOW_MS;
if (!retry) {
trace.lifecycle = describeLifecycle?.();
// eslint-disable-next-line no-await-in-loop
onError(await uploadFailure(e, file, trace));
return;
}
previous = `AbortError after ${elapsed}ms, no progress, ${
trace.aborts?.length
? `abort calls: ${trace.aborts.map((a) => `${a.api} ${a.frames}`).join('; ')}`
: 'abort calls: none'
}`;
}
previous = `AbortError after ${elapsed}ms, no progress`;
} finally {
probe.stop();
}
}
};

View file

@ -0,0 +1,171 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
describeComponentLifecycle,
formatAbortStack,
startAbortProbe,
uploadContent,
uploadFailure,
} from './matrix';
const chromeStack = [
'Error',
' at wrapper (https://chat.example/assets/index-abc.js:1:100)',
' at https://chat.example/assets/index-abc.js:1:200',
' at Object.cb (https://chat.example/assets/vendor-def.js:7:8)',
' at https://chat.example/assets/a.js:2:3',
' at https://chat.example/assets/b.js:4:5',
' at https://chat.example/assets/c.js:6:7',
' at https://chat.example/assets/d.js:8:9',
' at https://chat.example/assets/e.js:10:11',
].join('\n');
describe('formatAbortStack', () => {
it('keeps at most six frames as file:line:col, skipping the probe wrapper and the error line', () => {
const out = formatAbortStack(chromeStack);
const frames = out.split(' < ');
expect(frames).toHaveLength(6);
expect(frames[0]).toBe('index-abc.js:1:200');
expect(out).not.toContain('https://');
expect(out).not.toContain('wrapper');
});
it('copes with an empty stack', () => {
expect(formatAbortStack('')).toBe('no stack');
});
});
describe('abort probe', () => {
const original = AbortController.prototype.abort;
afterEach(() => {
vi.unstubAllGlobals();
AbortController.prototype.abort = original;
});
it('records an AbortController.abort made while it runs, still aborts, and restores afterwards', () => {
const probe = startAbortProbe();
expect(AbortController.prototype.abort).not.toBe(original);
const c = new AbortController();
c.abort();
expect(c.signal.aborted).toBe(true);
probe.stop();
expect(AbortController.prototype.abort).toBe(original);
expect(probe.calls).toHaveLength(1);
expect(probe.calls[0].api).toBe('AbortController.abort');
});
it('records XMLHttpRequest.prototype.abort and restores it', () => {
const xhrAbort = vi.fn();
class FakeXhr {
// eslint-disable-next-line class-methods-use-this
abort() {
xhrAbort();
}
}
vi.stubGlobal('XMLHttpRequest', FakeXhr);
const probe = startAbortProbe();
new FakeXhr().abort();
probe.stop();
expect(xhrAbort).toHaveBeenCalledTimes(1);
expect(probe.calls.map((c) => c.api)).toContain('XHR.abort');
expect(FakeXhr.prototype.abort.toString()).not.toContain('collectors');
const after = new FakeXhr();
after.abort();
expect(xhrAbort).toHaveBeenCalledTimes(2);
});
it('records nothing after stop', () => {
const probe = startAbortProbe();
probe.stop();
new AbortController().abort();
expect(probe.calls).toHaveLength(0);
});
it('keeps the wrapper until the last overlapping probe stops, then restores the original', () => {
const a = startAbortProbe();
const b = startAbortProbe();
a.stop();
new AbortController().abort();
expect(b.calls).toHaveLength(1);
expect(a.calls).toHaveLength(0);
b.stop();
expect(AbortController.prototype.abort).toBe(original);
});
it('restores the original when the upload attempt throws', async () => {
const mx = { uploadContent: () => Promise.reject(new Error('boom')) } as any;
await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError: vi.fn() });
expect(AbortController.prototype.abort).toBe(original);
});
it('restores the original when uploadContent itself throws synchronously', async () => {
const mx = {
uploadContent: () => {
throw new Error('sync');
},
} as any;
await expect(
uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError: vi.fn() })
).rejects.toThrow('sync');
expect(AbortController.prototype.abort).toBe(original);
});
});
describe('failure text', () => {
const abort = () => new DOMException('', 'AbortError');
it('lists abort calls seen during the attempt', async () => {
const mx = {
uploadContent: () => {
new AbortController().abort();
return Promise.reject(abort());
},
} as any;
const onError = vi.fn();
await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError });
// retried once: the final message carries the second attempt and attempt 1's summary
const msg = onError.mock.calls[0][0].message;
expect(msg).toContain('abort calls: AbortController.abort');
expect(msg).toContain('retried (attempt 1: AbortError');
});
it('says none when nothing in the page called abort', async () => {
const err = await uploadFailure(abort(), new Blob(['x']), {
startedAt: Date.now(),
aborts: [],
});
expect(err.message).toContain('abort calls: none');
});
it('reports the component lifecycle when given', async () => {
const mx = { uploadContent: () => Promise.reject(new Error('Timeout')) } as any;
const onError = vi.fn();
await uploadContent(mx, new Blob(['x']), {
onSuccess: vi.fn(),
onError,
describeLifecycle: () => 'component remounted 0x, renders 3 (2 within 300ms)',
});
expect(onError.mock.calls[0][0].message).toContain('renders 3 (2 within 300ms)');
});
});
describe('describeComponentLifecycle', () => {
it('counts renders after attach and those within 300ms, and reports an unmount', () => {
const text = describeComponentLifecycle({
attachedAt: 1000,
rendersAtAttach: 1,
renders: [990, 1100, 1250, 1400],
unmountedAt: 1500,
});
expect(text).toBe('component: 3 renders since attach (2 within 300ms), unmounted +500ms');
});
it('says not unmounted when it was not', () => {
const text = describeComponentLifecycle({
attachedAt: 1000,
rendersAtAttach: 1,
renders: [990],
});
expect(text).toBe('component: 0 renders since attach (0 within 300ms), not unmounted');
});
});