feat: application-level read state and inbox triage for conversations
Conversations were hard to manage because "unread" came straight from
Matrix's notification_count, and nothing in the app ever sends a read
receipt — so opening a conversation in the dashboard could never clear it
and the unread set only ever grew. The list also collapsed three
orthogonal facts into one word, labelling "they spoke last and we have
not replied" as "Up to date".
Read state is now ours:
- conversation_read_state table (migration 19) plus
ConversationReadStateRepository, kept separate from conversation_states
so a read write can never be lost to mergeConversationState. The
watermark is monotonic, so a stale poll cannot resurrect an unread
badge.
- hasUnreadInbound and needsReply are derived server-side and returned on
every conversation. Matrix's `unread` stays on the contract but the
dashboard no longer reads it.
- POST /conversations/{id}/read|unread|status and
POST /conversations/bulk-read, with optimistic cache updates.
Inbox rework:
- List rows are a real grid (checkbox, open button, chip strip) instead of
a full-bleed absolute overlay button, which previously forced a
pointer-events escape hatch for anything interactive in a row. Rows use
aria-current rather than aria-pressed. Not a listbox: options must not
contain interactive descendants.
- Counted filter pills replace the select, independent state chips replace
the collapsed status word, plus a sort control (including oldest
unanswered), a per-account filter, age-coloured timestamps, and an
explicit count of rows hidden by the seller filter.
- Keyboard: j/k/arrows, Enter, u, e, / and Escape. Shortcuts yield to any
open dialog so Escape dismisses the modal, not the conversation behind
it. Multi-select with bulk mark-read and mark-done.
- Detail panel: auto-mark-read on open, a "New messages" divider pinned at
mount (deriving it from the live watermark made it vanish a second after
opening), triage actions in the header, the automation banner moved out
of the composer, day dividers with time-only stamps, and a flex column
so history scrolls in its own region instead of painting over the
composer.
- Row order freezes while a conversation is open, with a "N new — refresh"
pill, so a background poll cannot reorder rows mid-triage.
Two database tests rewound user_version by an offset from the latest
version, which silently re-targets a different migration whenever one is
appended. They now pin absolute versions.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c8689af04d
commit
725b5fc4e6
26 files changed
+2625
-203
No files matched your search
@@ -0,0 +1,110 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { runMigrations } from '../src/database/client.js';
|
||||
import { ConversationReadStateRepository } from '../src/database/repositories.js';
|
||||
|
||||
describe('ConversationReadStateRepository', () => {
|
||||
let db: Database.Database;
|
||||
let repo: ConversationReadStateRepository;
|
||||
let other: ConversationReadStateRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:');
|
||||
runMigrations(db);
|
||||
repo = new ConversationReadStateRepository(db, 'account-one');
|
||||
other = new ConversationReadStateRepository(db, 'account-two');
|
||||
});
|
||||
|
||||
afterEach(() => db.close());
|
||||
|
||||
it('returns nothing for a conversation that has never been read', () => {
|
||||
expect(repo.get('room-1')).toBeUndefined();
|
||||
expect(repo.list()).toEqual([]);
|
||||
});
|
||||
|
||||
it('records a read watermark and defaults to an open status', () => {
|
||||
repo.markRead('room-1', 500, 1_000);
|
||||
|
||||
expect(repo.get('room-1')).toEqual({
|
||||
conversationId: 'room-1',
|
||||
lastReadMessageTs: 500,
|
||||
lastReadAt: 1_000,
|
||||
status: 'open',
|
||||
snoozedUntil: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('never moves the watermark backwards, so a stale write cannot resurrect an unread badge', () => {
|
||||
repo.markRead('room-1', 900, 1_000);
|
||||
repo.markRead('room-1', 400, 2_000);
|
||||
|
||||
const record = repo.get('room-1');
|
||||
expect(record?.lastReadMessageTs).toBe(900);
|
||||
// The read *time* still advances even when the watermark does not.
|
||||
expect(record?.lastReadAt).toBe(2_000);
|
||||
});
|
||||
|
||||
it('rewinds the watermark just before the named message when marking unread', () => {
|
||||
repo.markRead('room-1', 900, 1_000);
|
||||
repo.markUnread('room-1', 900, 2_000);
|
||||
|
||||
expect(repo.get('room-1')?.lastReadMessageTs).toBe(899);
|
||||
});
|
||||
|
||||
it('reopens and clears any snooze when marking unread', () => {
|
||||
repo.setStatus('room-1', 'snoozed', 5_000, 1_000);
|
||||
repo.markUnread('room-1', 100, 2_000);
|
||||
|
||||
expect(repo.get('room-1')).toMatchObject({ status: 'open', snoozedUntil: null });
|
||||
});
|
||||
|
||||
it('clamps a negative watermark to zero', () => {
|
||||
repo.markUnread('room-1', 0, 1_000);
|
||||
|
||||
expect(repo.get('room-1')?.lastReadMessageTs).toBe(0);
|
||||
});
|
||||
|
||||
it('stores a snooze deadline and drops it when the status changes', () => {
|
||||
repo.setStatus('room-1', 'snoozed', 5_000, 1_000);
|
||||
expect(repo.get('room-1')).toMatchObject({ status: 'snoozed', snoozedUntil: 5_000 });
|
||||
|
||||
repo.setStatus('room-1', 'done', null, 2_000);
|
||||
expect(repo.get('room-1')).toMatchObject({ status: 'done', snoozedUntil: null });
|
||||
});
|
||||
|
||||
it('ignores a snooze deadline for non-snoozed statuses', () => {
|
||||
repo.setStatus('room-1', 'open', 5_000, 1_000);
|
||||
|
||||
expect(repo.get('room-1')?.snoozedUntil).toBeNull();
|
||||
});
|
||||
|
||||
it('preserves the read watermark when only the status changes', () => {
|
||||
repo.markRead('room-1', 900, 1_000);
|
||||
repo.setStatus('room-1', 'done', null, 2_000);
|
||||
|
||||
expect(repo.get('room-1')).toMatchObject({ lastReadMessageTs: 900, status: 'done' });
|
||||
});
|
||||
|
||||
it('reopens only snoozes whose deadline has passed', () => {
|
||||
repo.setStatus('room-past', 'snoozed', 1_000, 1);
|
||||
repo.setStatus('room-future', 'snoozed', 9_000, 1);
|
||||
|
||||
expect(repo.expireSnoozes(5_000)).toEqual(['room-past']);
|
||||
expect(repo.get('room-past')).toMatchObject({ status: 'open', snoozedUntil: null });
|
||||
expect(repo.get('room-future')).toMatchObject({ status: 'snoozed', snoozedUntil: 9_000 });
|
||||
});
|
||||
|
||||
it('does not reopen an indefinite snooze', () => {
|
||||
repo.setStatus('room-1', 'snoozed', null, 1);
|
||||
|
||||
expect(repo.expireSnoozes(9_999)).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps read state isolated per account', () => {
|
||||
repo.markRead('room-1', 500, 1_000);
|
||||
|
||||
expect(other.get('room-1')).toBeUndefined();
|
||||
expect(other.list()).toEqual([]);
|
||||
expect(repo.list()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { ActiveChat } from '../packages/api-contracts/src/index.js';
|
||||
import {
|
||||
DEFAULT_CONVERSATION_FILTERS,
|
||||
accountOptions,
|
||||
filterCounts,
|
||||
isConversationFilter,
|
||||
isConversationSort,
|
||||
isUnread,
|
||||
isWaitingOnThem,
|
||||
matchesFilter,
|
||||
matchesSearch,
|
||||
needsReply,
|
||||
partitionConversations,
|
||||
triageStatus,
|
||||
type ConversationFilters,
|
||||
} from '../apps/dashboard/src/features/conversations/conversation-triage.js';
|
||||
|
||||
function chat(overrides: Partial<ActiveChat> & { username: string }): ActiveChat {
|
||||
return {
|
||||
roomName: overrides.username,
|
||||
roomId: `room-${overrides.username}`,
|
||||
lastMessageTime: 1_000,
|
||||
lastMessageSnippet: `snippet for ${overrides.username}`,
|
||||
isFromUs: false,
|
||||
unread: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function filters(overrides: Partial<ConversationFilters> = {}): ConversationFilters {
|
||||
return { ...DEFAULT_CONVERSATION_FILTERS, ...overrides };
|
||||
}
|
||||
|
||||
describe('conversation triage', () => {
|
||||
describe('derived state', () => {
|
||||
it('prefers application read state over the Matrix unread flag', () => {
|
||||
expect(isUnread(chat({ username: 'a', unread: true, hasUnreadInbound: false }))).toBe(false);
|
||||
expect(isUnread(chat({ username: 'a', unread: false, hasUnreadInbound: true }))).toBe(true);
|
||||
});
|
||||
|
||||
it('falls back to the Matrix flag when the server sends no read state', () => {
|
||||
expect(isUnread(chat({ username: 'a', unread: true }))).toBe(true);
|
||||
expect(isUnread(chat({ username: 'a', unread: false }))).toBe(false);
|
||||
});
|
||||
|
||||
it('treats an inbound newest message on an open conversation as needing a reply', () => {
|
||||
expect(needsReply(chat({ username: 'a', isFromUs: false }))).toBe(true);
|
||||
expect(needsReply(chat({ username: 'a', isFromUs: true }))).toBe(false);
|
||||
});
|
||||
|
||||
it('stops a resolved or snoozed conversation from needing a reply', () => {
|
||||
expect(needsReply(chat({ username: 'a', triageStatus: 'done' }))).toBe(false);
|
||||
expect(needsReply(chat({ username: 'a', triageStatus: 'snoozed' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('separates waiting-on-them from needing a reply', () => {
|
||||
const waiting = chat({ username: 'a', isFromUs: true });
|
||||
expect(isWaitingOnThem(waiting)).toBe(true);
|
||||
expect(needsReply(waiting)).toBe(false);
|
||||
});
|
||||
|
||||
it('defaults a conversation with no stored state to open', () => {
|
||||
expect(triageStatus(chat({ username: 'a' }))).toBe('open');
|
||||
});
|
||||
});
|
||||
|
||||
describe('filters', () => {
|
||||
const open = chat({ username: 'open', hasUnreadInbound: true });
|
||||
const replied = chat({ username: 'replied', isFromUs: true });
|
||||
const snoozed = chat({ username: 'snoozed', triageStatus: 'snoozed' });
|
||||
const done = chat({ username: 'done', triageStatus: 'done' });
|
||||
const withImage = chat({ username: 'image', hasReceivedImages: true });
|
||||
|
||||
it('excludes snoozed and resolved conversations from the default view', () => {
|
||||
expect(matchesFilter(open, 'all')).toBe(true);
|
||||
expect(matchesFilter(replied, 'all')).toBe(true);
|
||||
expect(matchesFilter(snoozed, 'all')).toBe(false);
|
||||
expect(matchesFilter(done, 'all')).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps snoozed and resolved conversations reachable through their own buckets', () => {
|
||||
expect(matchesFilter(snoozed, 'snoozed')).toBe(true);
|
||||
expect(matchesFilter(done, 'done')).toBe(true);
|
||||
});
|
||||
|
||||
it('scopes unread and image buckets to open conversations', () => {
|
||||
expect(matchesFilter(open, 'unread')).toBe(true);
|
||||
expect(matchesFilter(chat({ username: 'x', hasUnreadInbound: true, triageStatus: 'done' }), 'unread')).toBe(false);
|
||||
expect(matchesFilter(withImage, 'received-images')).toBe(true);
|
||||
expect(matchesFilter(chat({ username: 'y', hasReceivedImages: true, triageStatus: 'done' }), 'received-images')).toBe(false);
|
||||
});
|
||||
|
||||
it('matches search against username, snippet and loaded message text', () => {
|
||||
const conversation = chat({
|
||||
username: 'alice',
|
||||
lastMessageSnippet: 'about the weather',
|
||||
messages: [{ sender: 'alice', text: 'I live in Bristol', timestamp: 1, isSelf: false }],
|
||||
});
|
||||
expect(matchesSearch(conversation, 'ALI')).toBe(true);
|
||||
expect(matchesSearch(conversation, 'weather')).toBe(true);
|
||||
expect(matchesSearch(conversation, 'bristol')).toBe(true);
|
||||
expect(matchesSearch(conversation, 'nothing')).toBe(false);
|
||||
expect(matchesSearch(conversation, ' ')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('partitionConversations', () => {
|
||||
it('sorts newest first by default', () => {
|
||||
const result = partitionConversations([
|
||||
chat({ username: 'old', lastMessageTime: 100 }),
|
||||
chat({ username: 'new', lastMessageTime: 300 }),
|
||||
chat({ username: 'mid', lastMessageTime: 200 }),
|
||||
], filters());
|
||||
|
||||
expect(result.visible.map((item) => item.username)).toEqual(['new', 'mid', 'old']);
|
||||
});
|
||||
|
||||
it('puts the longest-waiting unanswered conversation first when sorting by oldest unanswered', () => {
|
||||
const result = partitionConversations([
|
||||
chat({ username: 'recent-inbound', lastMessageTime: 300 }),
|
||||
chat({ username: 'replied-old', lastMessageTime: 50, isFromUs: true }),
|
||||
chat({ username: 'stale-inbound', lastMessageTime: 100 }),
|
||||
], filters({ sort: 'oldest-unanswered' }));
|
||||
|
||||
// Unanswered first, oldest of those leading; everything else newest-first.
|
||||
expect(result.visible.map((item) => item.username))
|
||||
.toEqual(['stale-inbound', 'recent-inbound', 'replied-old']);
|
||||
});
|
||||
|
||||
it('reports how many rows the seller filter removed', () => {
|
||||
const result = partitionConversations([
|
||||
chat({ username: 'alice' }),
|
||||
chat({ username: 'seller-one', sellerDetected: true }),
|
||||
chat({ username: 'seller-two', sellerDetected: true }),
|
||||
], filters());
|
||||
|
||||
expect(result.visible.map((item) => item.username)).toEqual(['alice']);
|
||||
expect(result.hiddenSellerCount).toBe(2);
|
||||
});
|
||||
|
||||
it('includes sellers without counting them as hidden once revealed', () => {
|
||||
const result = partitionConversations([
|
||||
chat({ username: 'seller', sellerDetected: true }),
|
||||
], filters({ showSellers: true }));
|
||||
|
||||
expect(result.visible).toHaveLength(1);
|
||||
expect(result.hiddenSellerCount).toBe(0);
|
||||
});
|
||||
|
||||
it('narrows to a single owning account', () => {
|
||||
const result = partitionConversations([
|
||||
chat({ username: 'a', owner: { accountId: 'one', redditUsername: 'bot-one' } }),
|
||||
chat({ username: 'b', owner: { accountId: 'two', redditUsername: 'bot-two' } }),
|
||||
], filters({ account: 'two' }));
|
||||
|
||||
expect(result.visible.map((item) => item.username)).toEqual(['b']);
|
||||
});
|
||||
|
||||
it('does not mutate the input array order', () => {
|
||||
const input = [
|
||||
chat({ username: 'old', lastMessageTime: 100 }),
|
||||
chat({ username: 'new', lastMessageTime: 300 }),
|
||||
];
|
||||
partitionConversations(input, filters());
|
||||
|
||||
expect(input.map((item) => item.username)).toEqual(['old', 'new']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterCounts', () => {
|
||||
it('counts each bucket independently', () => {
|
||||
const counts = filterCounts([
|
||||
chat({ username: 'unread-inbound', hasUnreadInbound: true }),
|
||||
chat({ username: 'read-inbound', hasUnreadInbound: false }),
|
||||
chat({ username: 'replied', isFromUs: true }),
|
||||
chat({ username: 'snoozed', triageStatus: 'snoozed' }),
|
||||
chat({ username: 'done', triageStatus: 'done' }),
|
||||
], filters());
|
||||
|
||||
expect(counts.all).toBe(3);
|
||||
expect(counts.unread).toBe(1);
|
||||
expect(counts['needs-reply']).toBe(2);
|
||||
expect(counts['awaiting-reply']).toBe(1);
|
||||
expect(counts.snoozed).toBe(1);
|
||||
expect(counts.done).toBe(1);
|
||||
});
|
||||
|
||||
it('respects the search term so a pill never promises rows the list will not show', () => {
|
||||
const counts = filterCounts([
|
||||
chat({ username: 'alice', hasUnreadInbound: true }),
|
||||
chat({ username: 'bob', hasUnreadInbound: true }),
|
||||
], filters({ search: 'alice' }));
|
||||
|
||||
expect(counts.unread).toBe(1);
|
||||
expect(counts.all).toBe(1);
|
||||
});
|
||||
|
||||
it('excludes hidden sellers from the counts', () => {
|
||||
const counts = filterCounts([
|
||||
chat({ username: 'alice', hasUnreadInbound: true }),
|
||||
chat({ username: 'seller', hasUnreadInbound: true, sellerDetected: true }),
|
||||
], filters());
|
||||
|
||||
expect(counts.unread).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('accountOptions', () => {
|
||||
it('lists distinct owners sorted by username', () => {
|
||||
expect(accountOptions([
|
||||
chat({ username: 'a', owner: { accountId: 'two', redditUsername: 'zoe' } }),
|
||||
chat({ username: 'b', owner: { accountId: 'one', redditUsername: 'adam' } }),
|
||||
chat({ username: 'c', owner: { accountId: 'one', redditUsername: 'adam' } }),
|
||||
chat({ username: 'd' }),
|
||||
])).toEqual([
|
||||
{ accountId: 'one', redditUsername: 'adam' },
|
||||
{ accountId: 'two', redditUsername: 'zoe' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('query-parameter guards', () => {
|
||||
it('accepts only known filter and sort values', () => {
|
||||
expect(isConversationFilter('needs-reply')).toBe(true);
|
||||
expect(isConversationFilter('bogus')).toBe(false);
|
||||
expect(isConversationFilter(null)).toBe(false);
|
||||
expect(isConversationSort('oldest-unanswered')).toBe(true);
|
||||
expect(isConversationSort('bogus')).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,468 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { HttpResponse, http } from 'msw';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { ConversationsPage } from '../../apps/dashboard/src/features/conversations/conversations-page.js';
|
||||
import { resetComposerDrafts } from '../../apps/dashboard/src/features/conversations/composer-drafts.js';
|
||||
|
||||
const NOW = 1_786_000_000_000;
|
||||
|
||||
interface ChatOptions {
|
||||
username: string;
|
||||
roomId?: string;
|
||||
lastMessageTime?: number;
|
||||
isFromUs?: boolean;
|
||||
hasUnreadInbound?: boolean;
|
||||
needsReply?: boolean;
|
||||
triageStatus?: 'open' | 'snoozed' | 'done';
|
||||
lastReadMessageTs?: number;
|
||||
sellerDetected?: boolean;
|
||||
}
|
||||
|
||||
function chatFixture(options: ChatOptions) {
|
||||
const roomId = options.roomId ?? `room-${options.username}`;
|
||||
const isFromUs = options.isFromUs ?? false;
|
||||
const triageStatus = options.triageStatus ?? 'open';
|
||||
return {
|
||||
username: options.username,
|
||||
roomName: options.username,
|
||||
roomId,
|
||||
url: `https://chat.reddit.com/room/${roomId}`,
|
||||
lastMessageTime: options.lastMessageTime ?? NOW,
|
||||
lastMessageSnippet: `Latest from ${options.username}`,
|
||||
isFromUs,
|
||||
unread: false,
|
||||
hasUnreadInbound: options.hasUnreadInbound ?? (!isFromUs && triageStatus === 'open'),
|
||||
needsReply: options.needsReply ?? (!isFromUs && triageStatus === 'open'),
|
||||
triageStatus,
|
||||
snoozedUntil: null,
|
||||
lastReadMessageTs: options.lastReadMessageTs ?? 0,
|
||||
...(options.sellerDetected === undefined ? {} : { sellerDetected: options.sellerDetected }),
|
||||
};
|
||||
}
|
||||
|
||||
function detailFixture(chat: ReturnType<typeof chatFixture>, messages?: unknown[]) {
|
||||
return {
|
||||
...chat,
|
||||
messages: messages ?? [
|
||||
{ eventId: '$one', sender: 'me', text: 'Hello there', timestamp: NOW - 200_000, isSelf: true },
|
||||
{ eventId: '$two', sender: chat.username, text: 'Replying now', timestamp: NOW, isSelf: false },
|
||||
],
|
||||
triggeringPost: null,
|
||||
automation: { turnsUsed: 0, remainingTurns: 3, status: 'active', handoffReason: null },
|
||||
syncInProgress: null,
|
||||
};
|
||||
}
|
||||
|
||||
const alice = chatFixture({ username: 'alice' });
|
||||
|
||||
const server = setupServer(
|
||||
http.get('/api/accounts', () => HttpResponse.json([])),
|
||||
http.get('/api/conversations/:id/shareable-media', () => HttpResponse.json({
|
||||
requestKind: null, assets: [], reason: 'Nothing to share.', warning: null,
|
||||
})),
|
||||
);
|
||||
|
||||
function renderConversations() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ConversationsPage />
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
return queryClient;
|
||||
}
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
server.resetHandlers();
|
||||
resetComposerDrafts();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe('application-level read state', () => {
|
||||
it('advances the read watermark after the conversation has been open a moment', async () => {
|
||||
const readCalls: Array<{ id: string; body: unknown }> = [];
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([alice])),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(alice))),
|
||||
http.post('/api/conversations/:id/read', async ({ params, request }) => {
|
||||
readCalls.push({ id: String(params.id), body: await request.json() });
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /u\/alice/ }));
|
||||
await screen.findByRole('heading', { name: 'u/alice' });
|
||||
|
||||
await waitFor(() => expect(readCalls).toHaveLength(1));
|
||||
expect(readCalls[0]).toEqual({ id: 'room-alice', body: { throughTimestamp: NOW } });
|
||||
});
|
||||
|
||||
it('does not mark a conversation read that is already at the watermark', async () => {
|
||||
const read = chatFixture({ username: 'alice', hasUnreadInbound: false, lastReadMessageTs: NOW });
|
||||
let readCalls = 0;
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([read])),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(read))),
|
||||
http.post('/api/conversations/:id/read', () => {
|
||||
readCalls += 1;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /u\/alice/ }));
|
||||
await screen.findByRole('heading', { name: 'u/alice' });
|
||||
// Give the debounce more than enough time to fire if it were going to.
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
|
||||
expect(readCalls).toBe(0);
|
||||
});
|
||||
|
||||
it('clears the unread chip once the watermark has advanced', async () => {
|
||||
// Stateful so the assertion covers the whole round trip, not just the
|
||||
// optimistic frame that the follow-up refetch would overwrite.
|
||||
let watermark = 0;
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([
|
||||
chatFixture({ username: 'alice', hasUnreadInbound: watermark < NOW, lastReadMessageTs: watermark }),
|
||||
])),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(
|
||||
chatFixture({ username: 'alice', hasUnreadInbound: watermark < NOW, lastReadMessageTs: watermark }),
|
||||
))),
|
||||
http.post('/api/conversations/:id/read', async ({ request }) => {
|
||||
const body = await request.json() as { throughTimestamp?: number };
|
||||
watermark = Math.max(watermark, body.throughTimestamp ?? NOW);
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
const row = await screen.findByRole('button', { name: /u\/alice/ });
|
||||
expect(row.getAttribute('aria-label')).toContain('Unread');
|
||||
|
||||
await user.click(row);
|
||||
// The debounce plus the follow-up refetch takes longer than waitFor's default.
|
||||
await waitFor(() => expect(
|
||||
screen.getByRole('button', { name: /u\/alice/ }).getAttribute('aria-label'),
|
||||
).not.toContain('Unread'), { timeout: 4_000 });
|
||||
});
|
||||
|
||||
it('renders a new-messages divider at the read boundary and none for a first read', async () => {
|
||||
const partiallyRead = chatFixture({ username: 'alice', lastReadMessageTs: NOW - 100_000 });
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([partiallyRead])),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(partiallyRead))),
|
||||
http.post('/api/conversations/:id/read', () => HttpResponse.json({ success: true })),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /u\/alice/ }));
|
||||
expect(await screen.findByText('New messages')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the divider in place after auto-mark-read advances the watermark', async () => {
|
||||
// Regression: the divider used to vanish a second after opening, because it
|
||||
// was derived from the live watermark that auto-mark-read had just moved.
|
||||
let watermark = NOW - 100_000;
|
||||
const current = () => chatFixture({
|
||||
username: 'alice', hasUnreadInbound: watermark < NOW, lastReadMessageTs: watermark,
|
||||
});
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([current()])),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(current()))),
|
||||
http.post('/api/conversations/:id/read', async ({ request }) => {
|
||||
const body = await request.json() as { throughTimestamp?: number };
|
||||
watermark = Math.max(watermark, body.throughTimestamp ?? NOW);
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /u\/alice/ }));
|
||||
expect(await screen.findByText('New messages')).toBeInTheDocument();
|
||||
|
||||
// Wait for the read to land and the panel to re-render from fresh data.
|
||||
await waitFor(() => expect(
|
||||
screen.getByRole('button', { name: /u\/alice/ }).getAttribute('aria-label'),
|
||||
).not.toContain('Unread'), { timeout: 4_000 });
|
||||
expect(screen.getByText('New messages')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('omits the divider when the conversation has never been read', async () => {
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([alice])),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(alice))),
|
||||
http.post('/api/conversations/:id/read', () => HttpResponse.json({ success: true })),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /u\/alice/ }));
|
||||
await screen.findByText('Replying now');
|
||||
expect(screen.queryByText('New messages')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('groups history under day dividers instead of stamping every message with a date', async () => {
|
||||
const twoDaysAgo = NOW - (2 * 86_400_000);
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([alice])),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(alice, [
|
||||
{ eventId: '$old', sender: 'me', text: 'Older message', timestamp: twoDaysAgo, isSelf: true },
|
||||
{ eventId: '$new', sender: 'alice', text: 'Newer message', timestamp: Date.now(), isSelf: false },
|
||||
]))),
|
||||
http.post('/api/conversations/:id/read', () => HttpResponse.json({ success: true })),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /u\/alice/ }));
|
||||
await screen.findByText('Newer message');
|
||||
expect(screen.getByText('Today')).toBeInTheDocument();
|
||||
// Two distinct days produce two dividers.
|
||||
expect(document.querySelectorAll('.conversation-day-divider')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('returns a conversation to the queue from the detail header', async () => {
|
||||
let watermark = NOW;
|
||||
let unreadBody: unknown = null;
|
||||
const current = () => chatFixture({
|
||||
username: 'alice', hasUnreadInbound: watermark < NOW, lastReadMessageTs: watermark,
|
||||
});
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([current()])),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(current()))),
|
||||
http.post('/api/conversations/:id/unread', async ({ request }) => {
|
||||
unreadBody = await request.json();
|
||||
watermark = 0;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
// Re-opening the panel re-reads it; that must not fight the manual unread.
|
||||
http.post('/api/conversations/:id/read', () => HttpResponse.json({ success: true })),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /u\/alice/ }));
|
||||
await user.click(await screen.findByRole('button', { name: 'Mark unread' }));
|
||||
|
||||
await waitFor(() => expect(unreadBody).toEqual({}));
|
||||
await waitFor(() => expect(
|
||||
screen.getByRole('button', { name: /u\/alice/ }).getAttribute('aria-label'),
|
||||
).toContain('Unread'));
|
||||
});
|
||||
|
||||
it('resolves a conversation and closes the detail panel', async () => {
|
||||
let statusBody: unknown = null;
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([alice])),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(alice))),
|
||||
http.post('/api/conversations/:id/read', () => HttpResponse.json({ success: true })),
|
||||
http.post('/api/conversations/:id/status', async ({ request }) => {
|
||||
statusBody = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /u\/alice/ }));
|
||||
await user.click(await screen.findByRole('button', { name: 'Mark done' }));
|
||||
|
||||
await waitFor(() => expect(statusBody).toEqual({ status: 'done' }));
|
||||
expect(await screen.findByText('Select a conversation')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('snoozes for a chosen duration', async () => {
|
||||
let statusBody: { status: string; snoozeUntil: number } | null = null;
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([alice])),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(alice))),
|
||||
http.post('/api/conversations/:id/read', () => HttpResponse.json({ success: true })),
|
||||
http.post('/api/conversations/:id/status', async ({ request }) => {
|
||||
statusBody = await request.json() as { status: string; snoozeUntil: number };
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /u\/alice/ }));
|
||||
await user.click(await screen.findByRole('button', { name: 'Snooze' }));
|
||||
const menu = screen.getByRole('group', { name: 'Snooze options' });
|
||||
await user.click(within(menu).getByRole('button', { name: 'Tomorrow' }));
|
||||
|
||||
await waitFor(() => expect(statusBody?.status).toBe('snoozed'));
|
||||
expect(statusBody?.snoozeUntil).toBeGreaterThan(Date.now());
|
||||
});
|
||||
|
||||
it('marks every selected conversation read in one request', async () => {
|
||||
let bulkBody: { conversationIds: string[] } | null = null;
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([
|
||||
chatFixture({ username: 'alice' }),
|
||||
chatFixture({ username: 'bob', lastMessageTime: NOW - 1_000 }),
|
||||
])),
|
||||
http.post('/api/conversations/bulk-read', async ({ request }) => {
|
||||
bulkBody = await request.json() as { conversationIds: string[] };
|
||||
return HttpResponse.json({ success: true, updated: 2, failed: [] });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await screen.findByRole('button', { name: /u\/alice/ });
|
||||
await user.click(screen.getByRole('checkbox', { name: 'Select all visible conversations' }));
|
||||
expect(screen.getByText('2 selected')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Mark read' }));
|
||||
|
||||
await waitFor(() => expect(bulkBody?.conversationIds).toEqual(['room-alice', 'room-bob']));
|
||||
});
|
||||
|
||||
it('marks a single checked conversation read without touching the others', async () => {
|
||||
let bulkBody: { conversationIds: string[] } | null = null;
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([
|
||||
chatFixture({ username: 'alice' }),
|
||||
chatFixture({ username: 'bob', lastMessageTime: NOW - 1_000 }),
|
||||
])),
|
||||
http.post('/api/conversations/bulk-read', async ({ request }) => {
|
||||
bulkBody = await request.json() as { conversationIds: string[] };
|
||||
return HttpResponse.json({ success: true, updated: 1, failed: [] });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
|
||||
await screen.findByRole('button', { name: /u\/alice/ });
|
||||
await user.click(screen.getByRole('checkbox', { name: 'Select u/bob' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Mark read' }));
|
||||
|
||||
await waitFor(() => expect(bulkBody?.conversationIds).toEqual(['room-bob']));
|
||||
});
|
||||
|
||||
it('drives the list from the keyboard', async () => {
|
||||
let readId: string | null = null;
|
||||
let statusBody: unknown = null;
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([
|
||||
chatFixture({ username: 'alice' }),
|
||||
chatFixture({ username: 'bob', lastMessageTime: NOW - 1_000 }),
|
||||
])),
|
||||
http.post('/api/conversations/:id/read', ({ params }) => {
|
||||
readId = String(params.id);
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
http.post('/api/conversations/:id/status', async ({ request }) => {
|
||||
statusBody = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
await screen.findByRole('button', { name: /u\/alice/ });
|
||||
|
||||
// j moves to the first row, then to the second.
|
||||
await user.keyboard('j');
|
||||
expect(screen.getByRole('button', { name: /u\/alice/ })).toHaveFocus();
|
||||
await user.keyboard('j');
|
||||
expect(screen.getByRole('button', { name: /u\/bob/ })).toHaveFocus();
|
||||
await user.keyboard('k');
|
||||
expect(screen.getByRole('button', { name: /u\/alice/ })).toHaveFocus();
|
||||
|
||||
// u marks the focused row read; e resolves it.
|
||||
await user.keyboard('u');
|
||||
await waitFor(() => expect(readId).toBe('room-alice'));
|
||||
await user.keyboard('e');
|
||||
await waitFor(() => expect(statusBody).toEqual({ status: 'done' }));
|
||||
});
|
||||
|
||||
it('focuses search with / and ignores shortcuts while typing', async () => {
|
||||
server.use(http.get('/api/conversations', () => HttpResponse.json([alice])));
|
||||
const user = userEvent.setup();
|
||||
renderConversations();
|
||||
await screen.findByRole('button', { name: /u\/alice/ });
|
||||
|
||||
await user.keyboard('/');
|
||||
const search = screen.getByRole('searchbox', { name: 'Search conversations' });
|
||||
expect(search).toHaveFocus();
|
||||
|
||||
// 'j' and 'e' are literal characters here, not shortcuts.
|
||||
await user.keyboard('je');
|
||||
expect(search).toHaveValue('je');
|
||||
expect(search).toHaveFocus();
|
||||
});
|
||||
|
||||
it('holds the row order while a conversation is open and offers an explicit refresh', async () => {
|
||||
let listRequests = 0;
|
||||
server.use(
|
||||
http.get('/api/conversations', () => {
|
||||
listRequests += 1;
|
||||
return HttpResponse.json(listRequests === 1
|
||||
? [chatFixture({ username: 'alice' })]
|
||||
: [chatFixture({ username: 'carol', lastMessageTime: NOW + 5_000 }), chatFixture({ username: 'alice' })]);
|
||||
}),
|
||||
http.get('/api/conversations/room-alice', () => HttpResponse.json(detailFixture(alice))),
|
||||
http.post('/api/conversations/:id/read', () => HttpResponse.json({ success: true })),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
const queryClient = renderConversations();
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /u\/alice/ }));
|
||||
await screen.findByRole('heading', { name: 'u/alice' });
|
||||
|
||||
await queryClient.refetchQueries({ queryKey: ['conversations'] });
|
||||
|
||||
// carol arrived but must not push alice down mid-triage.
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /1 new conversation/ })).toBeInTheDocument());
|
||||
expect(screen.queryByRole('button', { name: /u\/carol/ })).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /1 new conversation/ }));
|
||||
expect(await screen.findByRole('button', { name: /u\/carol/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('explains rows hidden by the seller filter instead of silently dropping them', async () => {
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([
|
||||
chatFixture({ username: 'alice' }),
|
||||
chatFixture({ username: 'seller', sellerDetected: true }),
|
||||
])),
|
||||
);
|
||||
renderConversations();
|
||||
|
||||
await screen.findByRole('button', { name: /u\/alice/ });
|
||||
expect(screen.getByText('1 hidden by the seller filter.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('flags an unanswered conversation that has gone stale', async () => {
|
||||
server.use(
|
||||
http.get('/api/conversations', () => HttpResponse.json([
|
||||
chatFixture({ username: 'stale', lastMessageTime: Date.now() - (3 * 86_400_000) }),
|
||||
])),
|
||||
);
|
||||
renderConversations();
|
||||
|
||||
const row = await screen.findByRole('button', { name: /u\/stale/ });
|
||||
expect(row.getAttribute('aria-label')).toContain('Overdue');
|
||||
expect(row.querySelector('time')).toHaveClass('is-critical');
|
||||
});
|
||||
});
|
||||
@@ -70,6 +70,12 @@ const server = setupServer(
|
||||
requestKind: null, assets: [], warning: null,
|
||||
reason: 'No enabled, unused library images are available to share.',
|
||||
})),
|
||||
// Opening a conversation advances the read watermark.
|
||||
http.post('/api/conversations/:id/read', () => HttpResponse.json({ success: true })),
|
||||
http.post('/api/conversations/:id/unread', () => HttpResponse.json({ success: true })),
|
||||
http.post('/api/conversations/:id/status', () => HttpResponse.json({ success: true })),
|
||||
http.post('/api/conversations/bulk-read', () =>
|
||||
HttpResponse.json({ success: true, updated: 1, failed: [] })),
|
||||
);
|
||||
|
||||
function installConversationList() {
|
||||
@@ -139,7 +145,7 @@ describe('ConversationsPage', () => {
|
||||
expect(screen.getByRole('button', { name: /u\/bob/ })).toBeInTheDocument();
|
||||
|
||||
await user.clear(screen.getByRole('searchbox', { name: 'Search conversations' }));
|
||||
await user.selectOptions(screen.getByRole('combobox', { name: 'Filter conversations' }), 'unread');
|
||||
await user.click(screen.getByRole('button', { name: /^Unread/ }));
|
||||
expect(screen.getByRole('button', { name: /u\/alice/ })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /u\/bob/ })).not.toBeInTheDocument();
|
||||
|
||||
@@ -249,7 +255,7 @@ describe('ConversationsPage', () => {
|
||||
const aliceItem = await screen.findByRole('button', { name: /u\/alice/ });
|
||||
expect(screen.getByText('Image received')).toBeInTheDocument();
|
||||
|
||||
await user.selectOptions(screen.getByRole('combobox', { name: 'Filter conversations' }), 'received-images');
|
||||
await user.click(screen.getByRole('button', { name: /^Images/ }));
|
||||
expect(screen.getByRole('button', { name: /u\/alice/ })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /u\/bob/ })).not.toBeInTheDocument();
|
||||
|
||||
@@ -459,13 +465,17 @@ describe('ConversationsPage', () => {
|
||||
expect(screen.queryByRole('button', { name: 'Start conversation' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the unread count and marks unread rows with state and time in the label', async () => {
|
||||
it('counts each triage bucket on its filter pill and marks unread rows in the label', async () => {
|
||||
installConversationList();
|
||||
renderConversations();
|
||||
|
||||
const aliceButton = await screen.findByRole('button', { name: /u\/alice/ });
|
||||
expect(screen.getByText('1 unread')).toBeInTheDocument();
|
||||
expect(aliceButton.getAttribute('aria-label')).toMatch(/^u\/alice, Unread, .+ ago/);
|
||||
// alice is inbound and unread; bob is a conversation we replied to last.
|
||||
expect(screen.getByRole('button', { name: 'Unread, 1' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Needs reply, 1' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Waiting on them, 1' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'All, 2' })).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(aliceButton.getAttribute('aria-label')).toMatch(/^u\/alice, Unread, Needs reply, .+ago/);
|
||||
expect(aliceButton.closest('li')).toHaveClass('is-unread');
|
||||
expect(screen.getByRole('button', { name: /u\/bob/ }).closest('li')).not.toHaveClass('is-unread');
|
||||
});
|
||||
|
||||
@@ -32,14 +32,21 @@ describe('route-friendly filters', () => {
|
||||
it('hydrates and writes conversation search and status filters', async () => {
|
||||
server.use(http.get('/api/conversations', () => HttpResponse.json([])));
|
||||
const user = userEvent.setup();
|
||||
renderRoute('/conversations?q=alice&filter=received-images&showSellers=true', <ConversationRoute />);
|
||||
renderRoute(
|
||||
'/conversations?q=alice&filter=received-images&showSellers=true&sort=oldest-unanswered',
|
||||
<ConversationRoute />,
|
||||
);
|
||||
const search = await screen.findByRole('searchbox', { name: 'Search conversations' });
|
||||
expect(search).toHaveValue('alice');
|
||||
expect(screen.getByRole('combobox', { name: 'Filter conversations' })).toHaveValue('received-images');
|
||||
expect(screen.getByRole('button', { name: /^Images/ })).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByRole('combobox', { name: 'Sort' })).toHaveValue('oldest-unanswered');
|
||||
expect(screen.getByRole('checkbox', { name: 'Show sellers' })).toBeChecked();
|
||||
await user.clear(search);
|
||||
await user.type(search, 'bob');
|
||||
expect(screen.getByLabelText('Current URL')).toHaveTextContent('q=bob');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /^Needs reply/ }));
|
||||
expect(screen.getByLabelText('Current URL')).toHaveTextContent('filter=needs-reply');
|
||||
});
|
||||
|
||||
it('hydrates and writes media filters', async () => {
|
||||
|
||||
@@ -107,12 +107,13 @@ describe('Database Client', () => {
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
|
||||
.all() as { name: string }[];
|
||||
// Existing domain/config tables plus account, conversation, sync and media ownership stores.
|
||||
expect(tables.length).toBe(20);
|
||||
expect(tables.length).toBe(21);
|
||||
expect(tables.map((table) => table.name)).toEqual(expect.arrayContaining([
|
||||
'candidate_queue',
|
||||
'runtime_state',
|
||||
'media_library_assets',
|
||||
'media_library_sends',
|
||||
'conversation_read_state',
|
||||
]));
|
||||
});
|
||||
|
||||
@@ -156,13 +157,15 @@ describe('Database Client', () => {
|
||||
) VALUES (?, 'old-post', 'Sent_Contact', 'subject', 'message', 11)
|
||||
`).run('__legacy_unassigned__');
|
||||
|
||||
const latestVersion = db.pragma('user_version', { simple: true }) as number;
|
||||
db.exec(`
|
||||
DELETE FROM recipient_suppressions;
|
||||
DROP TABLE conversation_automation_claims;
|
||||
DROP TABLE ai_usage;
|
||||
`);
|
||||
db.pragma(`user_version = ${latestVersion - 7}`);
|
||||
// Rewind to just before the suppression backfill migration. This must be an
|
||||
// absolute version, not an offset from the latest — an offset silently
|
||||
// re-targets a different migration every time a new one is appended.
|
||||
db.pragma('user_version = 11');
|
||||
runMigrations(db);
|
||||
|
||||
expect(db.prepare('SELECT recipient, reason FROM recipient_suppressions ORDER BY recipient COLLATE NOCASE').all())
|
||||
@@ -174,7 +177,6 @@ describe('Database Client', () => {
|
||||
|
||||
it('preserves pending reply claims when adding auditable superseded status', () => {
|
||||
runMigrations(db);
|
||||
const latestVersion = db.pragma('user_version', { simple: true }) as number;
|
||||
db.exec(`
|
||||
DROP TABLE conversation_automation_claims;
|
||||
CREATE TABLE conversation_automation_claims (
|
||||
@@ -199,7 +201,8 @@ describe('Database Client', () => {
|
||||
'durable reply', 5, 11, 1
|
||||
);
|
||||
`);
|
||||
db.pragma(`user_version = ${latestVersion - 2}`);
|
||||
// Absolute version: rewind to just before the superseded-status rebuild.
|
||||
db.pragma('user_version = 16');
|
||||
|
||||
runMigrations(db);
|
||||
|
||||
|
||||
@@ -7,6 +7,19 @@ import { buildConversationState, conversationMessageFingerprint } from '../../sr
|
||||
|
||||
const servers: Array<ReturnType<express.Express['listen']>> = [];
|
||||
|
||||
/**
|
||||
* Triage fields the route projects onto every conversation when no operator
|
||||
* read state has been recorded yet: an inbound newest message is unread and
|
||||
* needs a reply, and the conversation is still open.
|
||||
*/
|
||||
const UNREAD_INBOUND_TRIAGE = {
|
||||
hasUnreadInbound: true,
|
||||
needsReply: true,
|
||||
triageStatus: 'open',
|
||||
snoozedUntil: null,
|
||||
lastReadMessageTs: 0,
|
||||
} as const;
|
||||
|
||||
async function request(
|
||||
app: express.Express,
|
||||
path: string,
|
||||
@@ -289,9 +302,11 @@ describe('conversations route', () => {
|
||||
const response = await request(app, '/api/conversations?includeImageMetadata=true');
|
||||
|
||||
expect(legacyResponse.status).toBe(200);
|
||||
expect(await legacyResponse.json()).toEqual([conversation]);
|
||||
expect(await legacyResponse.json()).toEqual([{ ...conversation, ...UNREAD_INBOUND_TRIAGE }]);
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual([{ ...conversation, hasReceivedImages: true }]);
|
||||
expect(await response.json()).toEqual([
|
||||
{ ...conversation, ...UNREAD_INBOUND_TRIAGE, hasReceivedImages: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it('marks conversations with a durable seller detection', async () => {
|
||||
@@ -313,7 +328,9 @@ describe('conversations route', () => {
|
||||
const response = await request(app, '/api/conversations');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual([{ ...conversation, sellerDetected: true }]);
|
||||
expect(await response.json()).toEqual([
|
||||
{ ...conversation, ...UNREAD_INBOUND_TRIAGE, sellerDetected: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it('serves conversation details without starting a delta sync', async () => {
|
||||
@@ -458,4 +475,218 @@ describe('conversations route', () => {
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ success: true });
|
||||
});
|
||||
|
||||
describe('operator read state', () => {
|
||||
const conversation = {
|
||||
username: 'alice', roomName: 'alice', roomId: 'room-alice',
|
||||
lastMessageTime: 500, lastMessageSnippet: 'Hello', isFromUs: false, unread: false,
|
||||
messages: [{ sender: 'alice', text: 'Hello', timestamp: 500, isSelf: false }],
|
||||
};
|
||||
|
||||
function contextWithReadState(readState: Record<string, unknown>) {
|
||||
return {
|
||||
logger: { error: vi.fn(), warn: vi.fn() },
|
||||
repos: { messages: { getByChatRoomId: vi.fn(), getLatestByRecipient: vi.fn() } },
|
||||
services: {
|
||||
chat: {
|
||||
getCachedConversations: vi.fn().mockResolvedValue([conversation]),
|
||||
getSyncStatus: vi.fn(() => ({ syncing: false, progress: null, syncingKind: null })),
|
||||
loadConversationDetails: vi.fn(),
|
||||
saveCacheExternal: vi.fn(),
|
||||
},
|
||||
conversationReadState: readState,
|
||||
},
|
||||
} as unknown as WebContext;
|
||||
}
|
||||
|
||||
function readStateStub(record?: Record<string, unknown>) {
|
||||
return {
|
||||
get: vi.fn(() => record),
|
||||
list: vi.fn(() => (record ? [record] : [])),
|
||||
expireSnoozes: vi.fn(() => []),
|
||||
markRead: vi.fn(),
|
||||
markUnread: vi.fn(),
|
||||
setStatus: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
it('reports an inbound message newer than the watermark as unread and needing a reply', async () => {
|
||||
const readState = readStateStub({
|
||||
conversationId: 'room-alice', lastReadMessageTs: 100, lastReadAt: 100,
|
||||
status: 'open', snoozedUntil: null,
|
||||
});
|
||||
const app = express().use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
const body = await (await request(app, '/api/conversations')).json();
|
||||
|
||||
expect(body[0]).toMatchObject({
|
||||
hasUnreadInbound: true, needsReply: true, triageStatus: 'open', lastReadMessageTs: 100,
|
||||
});
|
||||
expect(readState.expireSnoozes).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears unread once the watermark reaches the newest message', async () => {
|
||||
const readState = readStateStub({
|
||||
conversationId: 'room-alice', lastReadMessageTs: 500, lastReadAt: 600,
|
||||
status: 'open', snoozedUntil: null,
|
||||
});
|
||||
const app = express().use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
const body = await (await request(app, '/api/conversations')).json();
|
||||
|
||||
expect(body[0]).toMatchObject({ hasUnreadInbound: false, needsReply: true });
|
||||
});
|
||||
|
||||
it('stops treating a done conversation as needing a reply', async () => {
|
||||
const readState = readStateStub({
|
||||
conversationId: 'room-alice', lastReadMessageTs: 500, lastReadAt: 600,
|
||||
status: 'done', snoozedUntil: null,
|
||||
});
|
||||
const app = express().use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
const body = await (await request(app, '/api/conversations')).json();
|
||||
|
||||
expect(body[0]).toMatchObject({ needsReply: false, triageStatus: 'done' });
|
||||
});
|
||||
|
||||
it('marks read through the newest message when no timestamp is supplied', async () => {
|
||||
const readState = readStateStub();
|
||||
const app = express()
|
||||
.use(express.json())
|
||||
.use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
const response = await request(app, '/api/conversations/room-alice/read', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(readState.markRead).toHaveBeenCalledWith('room-alice', 500);
|
||||
});
|
||||
|
||||
it('marks read only through an explicitly supplied timestamp', async () => {
|
||||
const readState = readStateStub();
|
||||
const app = express()
|
||||
.use(express.json())
|
||||
.use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
await request(app, '/api/conversations/room-alice/read', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ throughTimestamp: 200 }),
|
||||
});
|
||||
|
||||
expect(readState.markRead).toHaveBeenCalledWith('room-alice', 200);
|
||||
});
|
||||
|
||||
it('marks a conversation unread again', async () => {
|
||||
const readState = readStateStub();
|
||||
const app = express()
|
||||
.use(express.json())
|
||||
.use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
const response = await request(app, '/api/conversations/room-alice/unread', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(readState.markUnread).toHaveBeenCalledWith('room-alice', 500);
|
||||
});
|
||||
|
||||
it('rejects a snooze with no deadline', async () => {
|
||||
const readState = readStateStub();
|
||||
const app = express()
|
||||
.use(express.json())
|
||||
.use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
const response = await request(app, '/api/conversations/room-alice/status', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: 'snoozed' }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(readState.setStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an unrecognised triage status', async () => {
|
||||
const readState = readStateStub();
|
||||
const app = express()
|
||||
.use(express.json())
|
||||
.use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
const response = await request(app, '/api/conversations/room-alice/status', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: 'archived' }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(readState.setStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stores a snooze deadline', async () => {
|
||||
const readState = readStateStub();
|
||||
const app = express()
|
||||
.use(express.json())
|
||||
.use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
const response = await request(app, '/api/conversations/room-alice/status', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: 'snoozed', snoozeUntil: 9_000 }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(readState.setStatus).toHaveBeenCalledWith('room-alice', 'snoozed', 9_000);
|
||||
});
|
||||
|
||||
it('reports unresolvable ids in a bulk mark-read rather than failing the batch', async () => {
|
||||
const readState = readStateStub();
|
||||
const app = express()
|
||||
.use(express.json())
|
||||
.use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
const response = await request(app, '/api/conversations/bulk-read', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ conversationIds: ['room-alice', 'room-missing'] }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ success: true, updated: 1, failed: ['room-missing'] });
|
||||
expect(readState.markRead).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('rejects an empty bulk mark-read', async () => {
|
||||
const app = express()
|
||||
.use(express.json())
|
||||
.use('/api', createConversationsRouter(contextWithReadState(readStateStub())));
|
||||
|
||||
const response = await request(app, '/api/conversations/bulk-read', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ conversationIds: [] }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
});
|
||||
|
||||
it('exposes the read watermark on the conversation detail so the divider can be placed', async () => {
|
||||
const readState = readStateStub({
|
||||
conversationId: 'room-alice', lastReadMessageTs: 100, lastReadAt: 100,
|
||||
status: 'open', snoozedUntil: null,
|
||||
});
|
||||
const app = express().use('/api', createConversationsRouter(contextWithReadState(readState)));
|
||||
|
||||
const body = await (await request(app, '/api/conversations/room-alice')).json();
|
||||
|
||||
expect(body).toMatchObject({
|
||||
lastReadMessageTs: 100, hasUnreadInbound: true, needsReply: true, triageStatus: 'open',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user