Files
RedditBot/apps/dashboard/src/features/conversations/conversation-triage.ts
T
Jamie BruntonandClaude Opus 5 725b5fc4e6 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>
2026-08-10 10:06:03 +01:00

205 lines
7.5 KiB
TypeScript

import type { ActiveChat } from '../../../../../packages/api-contracts/src/index.js';
/**
* Inbox buckets. These are the operator's actual work queues, derived from
* application read state rather than Matrix's unread count.
*
* `all` deliberately excludes resolved and snoozed conversations — the default
* view is "what is still on my plate", and the two terminal buckets have their
* own pills so nothing becomes unreachable.
*/
export type ConversationFilter =
| 'all'
| 'needs-reply'
| 'unread'
| 'awaiting-reply'
| 'received-images'
| 'snoozed'
| 'done';
export type ConversationSort = 'recent' | 'oldest-unanswered';
export interface ConversationFilters {
search: string;
filter: ConversationFilter;
showSellers: boolean;
sort: ConversationSort;
/** Reddit account id to narrow to, or `all`. */
account: string;
}
export const DEFAULT_CONVERSATION_FILTERS: ConversationFilters = {
search: '',
filter: 'all',
showSellers: false,
sort: 'recent',
account: 'all',
};
export const CONVERSATION_FILTERS: ReadonlyArray<{ value: ConversationFilter; label: string }> = [
{ value: 'all', label: 'All' },
{ value: 'needs-reply', label: 'Needs reply' },
{ value: 'unread', label: 'Unread' },
{ value: 'awaiting-reply', label: 'Waiting on them' },
{ value: 'received-images', label: 'Images' },
{ value: 'snoozed', label: 'Snoozed' },
{ value: 'done', label: 'Done' },
];
export const CONVERSATION_SORTS: ReadonlyArray<{ value: ConversationSort; label: string }> = [
{ value: 'recent', label: 'Newest activity' },
{ value: 'oldest-unanswered', label: 'Oldest unanswered' },
];
export function isConversationFilter(value: string | null): value is ConversationFilter {
return CONVERSATION_FILTERS.some((option) => option.value === value);
}
export function isConversationSort(value: string | null): value is ConversationSort {
return CONVERSATION_SORTS.some((option) => option.value === value);
}
export function triageStatus(conversation: ActiveChat): 'open' | 'snoozed' | 'done' {
return conversation.triageStatus ?? 'open';
}
/**
* True when the newest message is inbound and newer than the read watermark.
*
* Falls back to Matrix's `unread` only when the server has not supplied read
* state at all, so an older backend keeps behaving as before rather than
* showing an inbox with nothing unread.
*/
export function isUnread(conversation: ActiveChat): boolean {
if (conversation.hasUnreadInbound !== undefined) return conversation.hasUnreadInbound;
return conversation.unread;
}
export function needsReply(conversation: ActiveChat): boolean {
if (conversation.needsReply !== undefined) return conversation.needsReply;
return !conversation.isFromUs && triageStatus(conversation) === 'open';
}
/** We have replied and are waiting on them. */
export function isWaitingOnThem(conversation: ActiveChat): boolean {
return conversation.isFromUs && triageStatus(conversation) === 'open';
}
export function matchesFilter(conversation: ActiveChat, filter: ConversationFilter): boolean {
const status = triageStatus(conversation);
switch (filter) {
case 'needs-reply':
return needsReply(conversation);
case 'unread':
return status === 'open' && isUnread(conversation);
case 'awaiting-reply':
return isWaitingOnThem(conversation);
case 'received-images':
return status === 'open' && conversation.hasReceivedImages === true;
case 'snoozed':
return status === 'snoozed';
case 'done':
return status === 'done';
default:
return status === 'open';
}
}
export function matchesSearch(conversation: ActiveChat, search: string): boolean {
const normalized = search.trim().toLowerCase();
if (normalized.length === 0) return true;
if (conversation.username.toLowerCase().includes(normalized)) return true;
if (conversation.lastMessageSnippet.toLowerCase().includes(normalized)) return true;
// Message text is only present for conversations whose history has been
// loaded, so this is a bonus rather than a guarantee.
return (conversation.messages ?? []).some((message) => message.text.toLowerCase().includes(normalized));
}
function matchesAccount(conversation: ActiveChat, account: string): boolean {
return account === 'all' || conversation.owner?.accountId === account;
}
export interface ConversationListPartition {
/** Conversations passing every active filter, in the requested order. */
visible: ActiveChat[];
/** How many were removed purely by the seller toggle, so the UI can say so. */
hiddenSellerCount: number;
}
/**
* `oldest-unanswered` puts the longest-waiting conversation that needs a reply
* first — the order you actually want when draining a queue — and keeps
* everything else in newest-first order behind it.
*/
function compareConversations(sort: ConversationSort) {
return (left: ActiveChat, right: ActiveChat): number => {
if (sort === 'oldest-unanswered') {
const leftNeeds = needsReply(left);
const rightNeeds = needsReply(right);
if (leftNeeds !== rightNeeds) return leftNeeds ? -1 : 1;
if (leftNeeds && rightNeeds) return left.lastMessageTime - right.lastMessageTime;
}
return right.lastMessageTime - left.lastMessageTime;
};
}
export function partitionConversations(
conversations: readonly ActiveChat[],
filters: ConversationFilters,
): ConversationListPartition {
let hiddenSellerCount = 0;
const visible = conversations.filter((conversation) => {
if (!matchesSearch(conversation, filters.search)) return false;
if (!matchesFilter(conversation, filters.filter)) return false;
if (!matchesAccount(conversation, filters.account)) return false;
if (!filters.showSellers && conversation.sellerDetected === true) {
hiddenSellerCount += 1;
return false;
}
return true;
});
return { visible: visible.sort(compareConversations(filters.sort)), hiddenSellerCount };
}
/**
* Per-bucket counts for the filter pills. Counts respect search, account and
* the seller toggle so a pill never promises rows the list will not show.
*/
export function filterCounts(
conversations: readonly ActiveChat[],
filters: ConversationFilters,
): Record<ConversationFilter, number> {
const candidates = conversations.filter((conversation) =>
matchesSearch(conversation, filters.search)
&& matchesAccount(conversation, filters.account)
&& (filters.showSellers || conversation.sellerDetected !== true));
const counts = {} as Record<ConversationFilter, number>;
for (const { value } of CONVERSATION_FILTERS) {
counts[value] = candidates.filter((conversation) => matchesFilter(conversation, value)).length;
}
return counts;
}
export interface ConversationAccountOption {
accountId: string;
redditUsername: string;
}
/** Distinct owning accounts present in the list, for the account switcher. */
export function accountOptions(conversations: readonly ActiveChat[]): ConversationAccountOption[] {
const seen = new Map<string, string>();
for (const conversation of conversations) {
if (conversation.owner) seen.set(conversation.owner.accountId, conversation.owner.redditUsername);
}
return [...seen]
.map(([accountId, redditUsername]) => ({ accountId, redditUsername }))
.sort((left, right) => left.redditUsername.localeCompare(right.redditUsername));
}
export const SNOOZE_OPTIONS: ReadonlyArray<{ label: string; ms: number }> = [
{ label: '1 hour', ms: 60 * 60_000 },
{ label: 'Tomorrow', ms: 24 * 60 * 60_000 },
{ label: '3 days', ms: 3 * 24 * 60 * 60_000 },
{ label: '1 week', ms: 7 * 24 * 60 * 60_000 },
];