mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 00:51:17 -08:00
fix(schedule-send): serialize scheduled message cancellation per room (#1564)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description nothing stopped you double-clicking cancel on a scheduled message, and a failed cancel was silent. cancels go through a per-room queue now, button spinners and disables while in flight, failures show an inline retry. Fixes # #### Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings ### AI disclosure: - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. -->
This commit is contained in:
4 files changed
+363
-7
No files matched your search
@@ -0,0 +1,201 @@
|
||||
/* oxlint-disable typescript/no-explicit-any, typescript/no-extraneous-class, unicorn/consistent-function-scoping, vitest/require-mock-type-parameters */
|
||||
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ScheduledMessagesList } from './ScheduledMessagesList';
|
||||
import type * as MatrixSdkModule from '$types/matrix-sdk';
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
cancelDelayedEvent: vi.fn(),
|
||||
coordinatorRun: vi.fn(),
|
||||
invalidateQueries: vi.fn(),
|
||||
matrix: {
|
||||
getSafeUserId: vi.fn(() => '@me:example.org'),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useMatrixClient', () => ({
|
||||
useMatrixClient: () => testState.matrix,
|
||||
}));
|
||||
|
||||
vi.mock('$utils/delayedEvents', () => ({
|
||||
cancelDelayedEvent: testState.cancelDelayedEvent,
|
||||
getDelayedEvents: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('$state/room/roomScheduleCoordinator', () => ({
|
||||
roomScheduleCoordinator: {
|
||||
run: testState.coordinatorRun,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@tanstack/react-query', () => ({
|
||||
useQuery: () => ({
|
||||
data: {
|
||||
delayed_events: [
|
||||
{
|
||||
delay_id: 'delay-1',
|
||||
room_id: '!room:example.org',
|
||||
type: 'm.room.message',
|
||||
content: { body: 'Scheduled message' },
|
||||
running_since: 1_000,
|
||||
delay: 60_000,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
useQueryClient: () => ({ invalidateQueries: testState.invalidateQueries }),
|
||||
}));
|
||||
|
||||
vi.mock('$state/scheduledMessages', async () => {
|
||||
const { atom } = await import('jotai');
|
||||
const scheduledTimeAtom = atom<Date | null>(null);
|
||||
const editingScheduledDelayIdAtom = atom<string | null>(null);
|
||||
|
||||
return {
|
||||
delayedEventsSupportedAtom: atom(true),
|
||||
roomIdToScheduledTimeAtomFamily: () => scheduledTimeAtom,
|
||||
roomIdToEditingScheduledDelayIdAtomFamily: () => editingScheduledDelayIdAtom,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('$state/hooks/settings', () => ({
|
||||
useSetting: (_atom: unknown, key: string) => [
|
||||
key === 'hour24Clock' ? false : 'YYYY-MM-DD',
|
||||
vi.fn(),
|
||||
],
|
||||
}));
|
||||
|
||||
vi.mock('$state/settings', () => ({ settingsAtom: {} }));
|
||||
|
||||
vi.mock('$types/matrix-sdk', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof MatrixSdkModule>()),
|
||||
MatrixEvent: class MatrixEvent {},
|
||||
}));
|
||||
|
||||
vi.mock('$utils/time', () => ({
|
||||
timeDayMonthYear: () => '2026-07-28',
|
||||
timeHourMinute: () => '00:01',
|
||||
}));
|
||||
|
||||
vi.mock('$components/message-preview', () => ({
|
||||
MessagePreview: ({ actions, event }: any) => (
|
||||
<div>
|
||||
<span>{event.getContent?.().body ?? 'Scheduled message'}</span>
|
||||
{actions}
|
||||
</div>
|
||||
),
|
||||
useRoomMessagePreviewRenderer: () => vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('$components/icons/phosphor', () => ({
|
||||
CaretDown: 'CaretDown',
|
||||
CaretUp: 'CaretUp',
|
||||
Clock: 'Clock',
|
||||
Lock: 'Lock',
|
||||
PencilSimple: 'PencilSimple',
|
||||
X: 'X',
|
||||
chipIcon: () => null,
|
||||
}));
|
||||
|
||||
vi.mock('folds', () => {
|
||||
const Box = ({ children, ...props }: any) => <div {...props}>{children}</div>;
|
||||
const Text = ({ children, ...props }: any) => <span {...props}>{children}</span>;
|
||||
const Button = ({ children, ...props }: any) => <button {...props}>{children}</button>;
|
||||
|
||||
return {
|
||||
Box,
|
||||
Chip: Button,
|
||||
IconButton: Button,
|
||||
Spinner: () => <span role="progressbar">Cancelling</span>,
|
||||
Text,
|
||||
config: {
|
||||
borderWidth: { B300: '1px' },
|
||||
space: { S100: '1px', S200: '2px', S400: '4px' },
|
||||
},
|
||||
toRem: (value: number) => `${value / 16}rem`,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('./SchedulePickerDialog', () => ({
|
||||
SchedulePickerDialog: () => null,
|
||||
}));
|
||||
|
||||
const room = { roomId: '!room:example.org' } as any;
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((promiseResolve, promiseReject) => {
|
||||
resolve = promiseResolve;
|
||||
reject = promiseReject;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function renderExpandedList() {
|
||||
render(<ScheduledMessagesList room={room} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: /1 scheduled message/i }));
|
||||
return screen.getByRole('button', { name: 'Cancel scheduled message' });
|
||||
}
|
||||
|
||||
describe('ScheduledMessagesList cancellation', () => {
|
||||
beforeEach(() => {
|
||||
testState.cancelDelayedEvent.mockReset();
|
||||
testState.coordinatorRun.mockReset();
|
||||
testState.invalidateQueries.mockReset();
|
||||
testState.coordinatorRun.mockImplementation(
|
||||
(_mx: unknown, _roomId: string, operation: () => unknown) => operation()
|
||||
);
|
||||
});
|
||||
|
||||
it('blocks duplicate cancellation clicks and shows pending state', () => {
|
||||
const pending = deferred<void>();
|
||||
testState.cancelDelayedEvent.mockReturnValue(pending.promise);
|
||||
|
||||
const cancel = renderExpandedList();
|
||||
fireEvent.click(cancel);
|
||||
fireEvent.click(cancel);
|
||||
|
||||
expect(testState.coordinatorRun).toHaveBeenCalledWith(
|
||||
testState.matrix,
|
||||
room.roomId,
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(testState.cancelDelayedEvent).toHaveBeenCalledOnce();
|
||||
expect(cancel).toBeDisabled();
|
||||
expect(cancel).toHaveAttribute('aria-busy', 'true');
|
||||
expect(screen.getByRole('progressbar')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows a retryable alert when cancellation fails', async () => {
|
||||
testState.cancelDelayedEvent.mockRejectedValueOnce(new Error('Cancel failed'));
|
||||
const cancel = renderExpandedList();
|
||||
|
||||
fireEvent.click(cancel);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('alert')).toHaveTextContent(
|
||||
'Failed to cancel scheduled message. Try again.'
|
||||
)
|
||||
);
|
||||
expect(cancel).not.toBeDisabled();
|
||||
expect(cancel).not.toHaveAttribute('aria-busy', 'true');
|
||||
});
|
||||
|
||||
it('successfully retries cancellation after a failure', async () => {
|
||||
testState.cancelDelayedEvent
|
||||
.mockRejectedValueOnce(new Error('Cancel failed'))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
const cancel = renderExpandedList();
|
||||
|
||||
fireEvent.click(cancel);
|
||||
await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
|
||||
|
||||
fireEvent.click(cancel);
|
||||
|
||||
await waitFor(() => expect(testState.cancelDelayedEvent).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(testState.invalidateQueries).toHaveBeenCalledOnce());
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Box, Text, Chip, IconButton } from 'folds';
|
||||
import { Box, Text, Chip, IconButton, Spinner } from 'folds';
|
||||
import {
|
||||
CaretDown,
|
||||
CaretUp,
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
import { timeHourMinute, timeDayMonthYear } from '$utils/time';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { roomScheduleCoordinator } from '$state/room/roomScheduleCoordinator';
|
||||
import { MessagePreview, useRoomMessagePreviewRenderer } from '$components/message-preview';
|
||||
import { SchedulePickerDialog } from './SchedulePickerDialog';
|
||||
import * as css from './ScheduledMessagesList.css';
|
||||
@@ -44,6 +45,12 @@ type ScheduledMessageRowProps = {
|
||||
hour24Clock: boolean;
|
||||
onEdit: (delayId: string, body: string, formattedBody?: string, scheduledTs?: number) => void;
|
||||
onCancel: (delayId: string) => void;
|
||||
cancellationState: CancellationState;
|
||||
};
|
||||
|
||||
type CancellationState = {
|
||||
status: 'idle' | 'pending' | 'error';
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function ScheduledMessageRow({
|
||||
@@ -52,6 +59,7 @@ function ScheduledMessageRow({
|
||||
hour24Clock,
|
||||
onEdit,
|
||||
onCancel,
|
||||
cancellationState,
|
||||
}: ScheduledMessageRowProps) {
|
||||
const mx = useMatrixClient();
|
||||
const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString');
|
||||
@@ -63,6 +71,8 @@ function ScheduledMessageRow({
|
||||
!isEncrypted && typeof event.content.formatted_body === 'string'
|
||||
? event.content.formatted_body
|
||||
: undefined;
|
||||
const isCancelling = cancellationState.status === 'pending';
|
||||
const cancelIcon = isCancelling ? <Spinner size="100" /> : chipIcon(X);
|
||||
const matrixEvent = useMemo(
|
||||
() =>
|
||||
new MatrixEvent({
|
||||
@@ -106,9 +116,11 @@ function ScheduledMessageRow({
|
||||
variant="Critical"
|
||||
radii="300"
|
||||
onClick={() => onCancel(event.delay_id)}
|
||||
disabled={isCancelling}
|
||||
aria-busy={isCancelling}
|
||||
aria-label="Cancel scheduled message"
|
||||
>
|
||||
{chipIcon(X)}
|
||||
{cancelIcon}
|
||||
</IconButton>
|
||||
</Box>
|
||||
}
|
||||
@@ -126,12 +138,19 @@ function ScheduledMessageRow({
|
||||
variant="Critical"
|
||||
radii="300"
|
||||
onClick={() => onCancel(event.delay_id)}
|
||||
disabled={isCancelling}
|
||||
aria-busy={isCancelling}
|
||||
aria-label="Cancel scheduled message"
|
||||
>
|
||||
{chipIcon(X)}
|
||||
{cancelIcon}
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
{cancellationState.status === 'error' && (
|
||||
<Text size="T200" priority="300" role="alert" aria-live="polite">
|
||||
{cancellationState.error}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -146,6 +165,10 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages
|
||||
const [editingDelayId, setEditingDelayId] = useAtom(
|
||||
roomIdToEditingScheduledDelayIdAtomFamily(room.roomId)
|
||||
);
|
||||
const [cancellationStates, setCancellationStates] = useState<Record<string, CancellationState>>(
|
||||
{}
|
||||
);
|
||||
const pendingCancellations = useRef(new Set<string>());
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ['delayedEvents', room.roomId],
|
||||
@@ -167,10 +190,35 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages
|
||||
|
||||
const handleCancel = useCallback(
|
||||
async (delayId: string) => {
|
||||
await cancelDelayedEvent(mx, delayId);
|
||||
invalidateEvents();
|
||||
if (pendingCancellations.current.has(delayId)) return;
|
||||
|
||||
pendingCancellations.current.add(delayId);
|
||||
setCancellationStates((states) => ({
|
||||
...states,
|
||||
[delayId]: { status: 'pending' },
|
||||
}));
|
||||
|
||||
try {
|
||||
await roomScheduleCoordinator.run(mx, room.roomId, () => cancelDelayedEvent(mx, delayId));
|
||||
invalidateEvents();
|
||||
setCancellationStates((states) => {
|
||||
const next = { ...states };
|
||||
delete next[delayId];
|
||||
return next;
|
||||
});
|
||||
} catch {
|
||||
setCancellationStates((states) => ({
|
||||
...states,
|
||||
[delayId]: {
|
||||
status: 'error',
|
||||
error: 'Failed to cancel scheduled message. Try again.',
|
||||
},
|
||||
}));
|
||||
} finally {
|
||||
pendingCancellations.current.delete(delayId);
|
||||
}
|
||||
},
|
||||
[mx, invalidateEvents]
|
||||
[mx, room.roomId, invalidateEvents]
|
||||
);
|
||||
|
||||
const handleEdit = useCallback(
|
||||
@@ -218,6 +266,7 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages
|
||||
hour24Clock={hour24Clock}
|
||||
onEdit={handleEdit}
|
||||
onCancel={handleCancel}
|
||||
cancellationState={cancellationStates[event.delay_id] ?? { status: 'idle' }}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { roomScheduleCoordinator } from './roomScheduleCoordinator';
|
||||
|
||||
const account = (userId: string) => ({ getSafeUserId: () => userId });
|
||||
const alice = account('@alice:example.org');
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((resolvePromise) => {
|
||||
resolve = resolvePromise;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
describe('roomScheduleCoordinator', () => {
|
||||
it('runs operations in FIFO order for a room', async () => {
|
||||
const first = deferred();
|
||||
const order: string[] = [];
|
||||
|
||||
const firstOperation = roomScheduleCoordinator.run(alice, '!room:example.org', async () => {
|
||||
order.push('first-start');
|
||||
await first.promise;
|
||||
order.push('first-end');
|
||||
});
|
||||
const secondOperation = roomScheduleCoordinator.run(alice, '!room:example.org', async () => {
|
||||
order.push('second');
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
expect(order).toEqual(['first-start']);
|
||||
|
||||
first.resolve();
|
||||
await Promise.all([firstOperation, secondOperation]);
|
||||
expect(order).toEqual(['first-start', 'first-end', 'second']);
|
||||
});
|
||||
|
||||
it('continues the room queue after an operation fails', async () => {
|
||||
const second = vi.fn<() => Promise<string>>(async () => 'completed');
|
||||
|
||||
await expect(
|
||||
roomScheduleCoordinator.run(alice, '!room:example.org', async () => {
|
||||
throw new Error('cancel failed');
|
||||
})
|
||||
).rejects.toThrow('cancel failed');
|
||||
await expect(roomScheduleCoordinator.run(alice, '!room:example.org', second)).resolves.toBe(
|
||||
'completed'
|
||||
);
|
||||
|
||||
expect(second).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('does not serialize operations for different rooms', async () => {
|
||||
const first = deferred();
|
||||
const second = vi.fn<() => Promise<string>>(async () => 'completed');
|
||||
|
||||
const firstOperation = roomScheduleCoordinator.run(
|
||||
alice,
|
||||
'!first:example.org',
|
||||
() => first.promise
|
||||
);
|
||||
const secondOperation = roomScheduleCoordinator.run(alice, '!second:example.org', second);
|
||||
|
||||
await expect(secondOperation).resolves.toBe('completed');
|
||||
expect(second).toHaveBeenCalledOnce();
|
||||
|
||||
first.resolve();
|
||||
await firstOperation;
|
||||
});
|
||||
|
||||
it('does not serialize the same room ID across accounts', async () => {
|
||||
const first = deferred();
|
||||
const second = vi.fn<() => Promise<string>>(async () => 'completed');
|
||||
|
||||
const firstOperation = roomScheduleCoordinator.run(
|
||||
alice,
|
||||
'!room:example.org',
|
||||
() => first.promise
|
||||
);
|
||||
const secondOperation = roomScheduleCoordinator.run(
|
||||
account('@bob:example.org'),
|
||||
'!room:example.org',
|
||||
second
|
||||
);
|
||||
|
||||
await expect(secondOperation).resolves.toBe('completed');
|
||||
expect(second).toHaveBeenCalledOnce();
|
||||
|
||||
first.resolve();
|
||||
await firstOperation;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { createKeyedQueue } from '$utils/keyedQueue';
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
|
||||
const runQueued = createKeyedQueue();
|
||||
|
||||
/** Serializes delayed-event mutations per account and room. */
|
||||
export const roomScheduleCoordinator = {
|
||||
run<T>(
|
||||
mx: Pick<MatrixClient, 'getSafeUserId'>,
|
||||
roomId: string,
|
||||
operation: () => T | PromiseLike<T>
|
||||
): Promise<T> {
|
||||
return runQueued(`${mx.getSafeUserId()}\0${roomId}`, operation);
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user