Consumer tests: startClient wiring, Resend/Discard handlers, the 30 s slow-send threshold
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Void 2026-11-13 04:04:45 +00:00
commit da9ef70c03
3 changed files with 214 additions and 0 deletions

View file

@ -0,0 +1,94 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { enqueueOutbox, failOutbox, loadOutbox } from '../../state/room/composerStore';
import { RoomOutbox } from './RoomOutbox';
// The component's hooks are held still (state is its initial value, effects do not run) so the element tree
// it returns can be read and its click handlers called without a DOM.
vi.mock('react', async (importOriginal) => {
const actual = await importOriginal<typeof import('react')>();
const useState = (init: unknown) => [
typeof init === 'function' ? (init as () => unknown)() : init,
() => undefined,
];
return {
...actual,
default: { ...actual, useState, useEffect: () => undefined },
useState,
useEffect: () => undefined,
};
});
type El = { props?: { children?: unknown; onClick?: () => void } };
const flatten = (node: unknown): El[] => {
if (Array.isArray(node)) return node.flatMap(flatten);
if (node && typeof node === 'object') {
const el = node as El;
return [el, ...flatten(el.props?.children)];
}
return [];
};
const textOf = (node: unknown): string => {
if (typeof node === 'string' || typeof node === 'number') return String(node);
if (Array.isArray(node)) return node.map(textOf).join('');
if (node && typeof node === 'object') return textOf((node as El).props?.children);
return '';
};
/** The onClick of the chip whose label is `label`. */
const clickOf = (tree: unknown, label: string) => {
const chip = flatten(tree).find((e) => e.props?.onClick && textOf(e) === label);
if (!chip?.props?.onClick) throw new Error(`no ${label} chip`);
return chip.props.onClick;
};
describe('RoomOutbox actions', () => {
beforeEach(() => {
const m = new Map<string, string>();
vi.stubGlobal('localStorage', {
getItem: (k: string) => m.get(k) ?? null,
setItem: (k: string, v: string) => {
m.set(k, v);
},
removeItem: (k: string) => {
m.delete(k);
},
});
enqueueOutbox('@a:x', { txnId: 'keep', roomId: '!r:x', content: { body: 'stay' } });
enqueueOutbox('@a:x', { txnId: 'bad', roomId: '!r:x', content: { body: 'did not go' } });
failOutbox('@a:x', 'bad', 'ECONNRESET');
});
afterEach(() => {
vi.unstubAllGlobals();
});
const mount = () => {
const mx = {
getUserId: () => '@a:x',
makeTxnId: () => 'txn-new',
getRoom: () => undefined,
sendEvent: vi.fn().mockResolvedValue({ event_id: '$e' }),
};
const tree = (RoomOutbox as unknown as (p: unknown) => unknown)({ mx, roomId: '!r:x' });
return { mx, tree };
};
it('Discard removes that message from the outbox and no other', () => {
const { mx, tree } = mount();
// both entries are shown; the failed one is the one with Discard
clickOf(tree, 'Discard')();
expect(loadOutbox('@a:x').map((e) => e.txnId)).toEqual(['keep']);
expect(mx.sendEvent).not.toHaveBeenCalled();
});
it('Resend sends that message again and does not discard it first', async () => {
const { mx, tree } = mount();
clickOf(tree, 'Resend')();
await Promise.resolve();
expect(mx.sendEvent).toHaveBeenCalledTimes(1);
expect(mx.sendEvent).toHaveBeenCalledWith(
'!r:x',
'm.room.message',
{ body: 'did not go' },
'bad'
);
});
});

View file

@ -17,6 +17,11 @@ describe('outboxView', () => {
});
});
it('offers Resend to a pending send at 30 s and not a millisecond before', () => {
const at = (ms: number) => outboxView({ status: 'pending', ts: 100 }, 100 + ms, 0).canResend;
expect([at(29_999), at(30_000)]).toEqual([false, true]);
});
it('an entry older than this page load reads as interrupted', () => {
expect(outboxView({ status: 'pending', ts: 5 }, 6, 10).label).toMatch(/Interrupted/);
});

View file

@ -0,0 +1,115 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { enqueueOutbox } from '../app/state/room/composerStore';
import { PAGE_START } from '../app/state/room/outboxSend';
import { startClient } from './initMatrix';
import { startResumeSync } from './resumeSync';
import { startWatchdog } from './watchdog';
vi.mock('./resumeSync', () => ({ startResumeSync: vi.fn() }));
vi.mock('./watchdog', async (importOriginal) => ({
...(await importOriginal<typeof import('./watchdog')>()),
startWatchdog: vi.fn(() => () => undefined),
}));
const memoryStore = (m = new Map<string, string>()) => ({
getItem: (k: string) => m.get(k) ?? null,
setItem: (k: string, v: string) => {
m.set(k, v);
},
removeItem: (k: string) => {
m.delete(k);
},
});
// startClient is the one place the dead-connection pieces are wired to the page: what the watchdog reads,
// when it may fire, what it does, and what runs after the reload. These tests call it and exercise that wiring.
describe('startClient wiring', () => {
let handlers: Array<(state: string) => void>;
let mx: Record<string, unknown> & {
sendEvent: ReturnType<typeof vi.fn>;
off: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
vi.clearAllMocks();
handlers = [];
vi.stubGlobal('localStorage', memoryStore());
mx = {
startClient: vi.fn().mockResolvedValue(undefined),
getUserId: () => '@a:x',
makeTxnId: () => 'txn-new',
getRoom: () => undefined,
sendEvent: vi.fn().mockResolvedValue({ event_id: '$e' }),
on: (_ev: string, h: (state: string) => void) => {
handlers.push(h);
},
off: vi.fn(),
};
});
afterEach(() => {
vi.unstubAllGlobals();
});
const watchdogOptions = () =>
(startWatchdog as unknown as ReturnType<typeof vi.fn>).mock.calls[0][0] as Parameters<
typeof startWatchdog
>[0];
it('starts sync, the resume nudge and the watchdog once per client', async () => {
await startClient(mx as never);
await startClient(mx as never);
expect(mx.startClient).toHaveBeenCalledTimes(2);
expect(startResumeSync).toHaveBeenCalledTimes(1);
expect(startResumeSync).toHaveBeenCalledWith(mx);
expect(startWatchdog).toHaveBeenCalledTimes(1);
});
it("feeds the watchdog this page's pending sends for this user", async () => {
await startClient(mx as never);
const { pendingAges } = watchdogOptions();
expect(pendingAges()).toEqual([]);
enqueueOutbox('@a:x', { txnId: 't', roomId: '!r:x', content: {} }, Date.now() - 7000);
enqueueOutbox('@b:x', { txnId: 'u', roomId: '!r:x', content: {} }, Date.now() - 1000);
const ages = pendingAges();
expect(ages).toHaveLength(1);
expect(ages[0]).toBeGreaterThanOrEqual(7000);
});
it('reads visibility and connectivity from the page', async () => {
const doc = { visibilityState: 'visible' };
const nav = { onLine: true };
vi.stubGlobal('document', doc);
vi.stubGlobal('navigator', nav);
await startClient(mx as never);
const { isVisible, isOnline } = watchdogOptions();
expect([isVisible(), isOnline()]).toEqual([true, true]);
doc.visibilityState = 'hidden';
nav.onLine = false;
expect([isVisible(), isOnline()]).toEqual([false, false]);
});
it('recovers by a guarded reload, at most once a minute', async () => {
const reload = vi.fn();
vi.stubGlobal('window', { location: { reload } });
vi.stubGlobal('sessionStorage', memoryStore());
await startClient(mx as never);
const { recover } = watchdogOptions();
recover();
recover();
expect(reload).toHaveBeenCalledTimes(1);
});
it('resends what a reload interrupted once sync is up, and only once', async () => {
enqueueOutbox(
'@a:x',
{ txnId: 'old', roomId: '!r:x', content: { body: 'x' } },
PAGE_START - 5000
);
await startClient(mx as never);
expect(handlers).toHaveLength(1);
handlers[0]('CONNECTING');
expect(mx.sendEvent).not.toHaveBeenCalled();
handlers[0]('SYNCING');
expect(mx.off).toHaveBeenCalledWith('sync', handlers[0]);
expect(mx.sendEvent).toHaveBeenCalledWith('!r:x', 'm.room.message', { body: 'x' }, 'old');
});
});