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:
Jamie BruntonandClaude Opus 5 committed 2026-08-10 10:06:03 +01:00
1 parent c8689af04d
commit 725b5fc4e6
26 files changed
+2625 -203

No files matched your search

@@ -11,9 +11,16 @@ import {
StartConversationResponseSchema,
SuccessResponseSchema,
SuggestedReplyResponseSchema,
BulkMarkConversationsReadRequestSchema,
BulkMarkConversationsReadResponseSchema,
MarkConversationReadRequestSchema,
MarkConversationUnreadRequestSchema,
SetConversationStatusRequestSchema,
type ActiveChat,
type BulkMarkConversationsReadResponse,
type ConversationDetailResponse,
type ConversationMediaShareOptions,
type ConversationTriageStatus,
type ProcessedPost,
type SuccessResponse,
} from '../../../../../packages/api-contracts/src/index.js';
@@ -42,6 +49,18 @@ export interface ConversationApi {
sendReply(id: string, message: string): Promise<SuccessResponse>;
shareMedia(id: string, assetId: string): Promise<SuccessResponse>;
startConversation(accountId: string, username: string, message: string): Promise<ActiveChat>;
markRead(id: string, throughTimestamp?: number): Promise<SuccessResponse>;
markUnread(id: string, beforeTimestamp?: number): Promise<SuccessResponse>;
setStatus(id: string, status: ConversationTriageStatus, snoozeUntil?: number | null): Promise<SuccessResponse>;
bulkMarkRead(ids: string[]): Promise<BulkMarkConversationsReadResponse>;
}
function jsonPost(body: unknown): RequestInit {
return {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
};
}
export function createConversationApi(fetchImplementation?: typeof fetch): ConversationApi {
@@ -121,6 +140,40 @@ export function createConversationApi(fetchImplementation?: typeof fetch): Conve
);
return response.chat;
},
async markRead(id, throughTimestamp) {
const body = MarkConversationReadRequestSchema.parse(
throughTimestamp === undefined ? {} : { throughTimestamp },
);
return parseResponse(
await request(`${conversationPath(id)}/read`, jsonPost(body)),
SuccessResponseSchema,
);
},
async markUnread(id, beforeTimestamp) {
const body = MarkConversationUnreadRequestSchema.parse(
beforeTimestamp === undefined ? {} : { beforeTimestamp },
);
return parseResponse(
await request(`${conversationPath(id)}/unread`, jsonPost(body)),
SuccessResponseSchema,
);
},
async setStatus(id, status, snoozeUntil) {
const body = SetConversationStatusRequestSchema.parse(
snoozeUntil === undefined ? { status } : { status, snoozeUntil },
);
return parseResponse(
await request(`${conversationPath(id)}/status`, jsonPost(body)),
SuccessResponseSchema,
);
},
async bulkMarkRead(ids) {
const body = BulkMarkConversationsReadRequestSchema.parse({ conversationIds: ids });
return parseResponse(
await request('/api/conversations/bulk-read', jsonPost(body)),
BulkMarkConversationsReadResponseSchema,
);
},
};
}
@@ -1,11 +1,18 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { ConversationDetailResponse, MediaLibraryAsset } from '../../../../../packages/api-contracts/src/index.js';
import type {
ChatMessage,
ConversationDetailResponse,
MediaLibraryAsset,
} from '../../../../../packages/api-contracts/src/index.js';
import { RedditUsernameLink, redditUsernameLabel } from '../../components/reddit-username-link.js';
import { OriginPostCard } from '../../components/origin-post.js';
import {
useConversationDetailQuery,
useConversationMediaShareOptionsQuery,
useMarkConversationReadMutation,
useMarkConversationUnreadMutation,
useSendReplyMutation,
useSetConversationStatusMutation,
useShareConversationMediaMutation,
useSuggestMediaAskMutation,
useSuggestReplyMutation,
@@ -13,14 +20,19 @@ import {
import { SendConfirmationDialog } from './send-confirmation-dialog.js';
import { MediaShareConfirmationDialog } from './media-share-confirmation-dialog.js';
import { AccountOwnerBadge } from '../../components/account-owner-badge.js';
import { formatExactTime } from './relative-time.js';
import { formatDayLabel, formatExactTime, formatTimeOfDay, isSameDay } from './relative-time.js';
import { getStoredComposerDraft, storeComposerDraft } from './composer-drafts.js';
import { SNOOZE_OPTIONS, isUnread, triageStatus } from './conversation-triage.js';
/** Reddit chat rejects messages longer than roughly this many characters. */
export const REDDIT_CHAT_MAX_MESSAGE_LENGTH = 10_000;
const CHARACTER_WARNING_MARGIN = 500;
const SUCCESS_NOTICE_DISMISS_MS = 5_000;
const AT_BOTTOM_THRESHOLD_PX = 48;
/** Keeps a little context above the "New messages" rule when jumping to it. */
const UNREAD_DIVIDER_HEADROOM_PX = 12;
/** Grace period before an open conversation is considered read. */
export const AUTO_MARK_READ_DELAY_MS = 1_000;
interface ConversationDetailProps {
conversationId: string;
@@ -40,12 +52,35 @@ function useAutoDismiss(isVisible: boolean, dismiss: () => void) {
}, [isVisible, dismiss]);
}
function MessageHistory({ conversation }: { conversation: ConversationDetailResponse }) {
/**
* Index of the first inbound message the operator has not read.
*
* Returns -1 unless the boundary falls *inside* the loaded history — a
* conversation being opened for the first time has no meaningful boundary, and
* a "New messages" rule above the very first message is noise rather than
* information.
*/
export function firstUnreadIndex(messages: ChatMessage[], lastReadMessageTs: number | undefined): number {
if (!lastReadMessageTs) return -1;
const index = messages.findIndex((message) => !message.isSelf && message.timestamp > lastReadMessageTs);
return index > 0 ? index : -1;
}
function MessageHistory({ conversation, now }: { conversation: ConversationDetailResponse; now: number }) {
const [revealedMedia, setRevealedMedia] = useState<Set<string>>(() => new Set());
const listRef = useRef<HTMLOListElement>(null);
const dividerRef = useRef<HTMLLIElement>(null);
const isAtBottomRef = useRef(true);
const [isAtBottom, setIsAtBottom] = useState(true);
const messageCount = conversation.messages?.length ?? 0;
const messages = conversation.messages ?? [];
const messageCount = messages.length;
// Pinned at mount: opening the conversation advances the read watermark a
// second later, and the marker must not disappear from under the operator
// while they are still reading. It resets when they switch conversations,
// because the panel is keyed on the conversation id.
const [readBoundary] = useState(() => conversation.lastReadMessageTs ?? 0);
const unreadIndex = firstUnreadIndex(messages, readBoundary);
const hasScrolledToBoundaryRef = useRef(false);
const scrollToBottom = useCallback(() => {
const list = listRef.current;
@@ -55,11 +90,24 @@ function MessageHistory({ conversation }: { conversation: ConversationDetailResp
setIsAtBottom(true);
}, []);
// Stick to the latest message on mount and when new messages arrive,
// unless the operator has scrolled up to read history.
// Land on the first unread message rather than the bottom, so the operator
// starts reading where they left off. Only done once per mount — after that,
// stick to the latest message unless they have scrolled up to read history.
useEffect(() => {
const list = listRef.current;
const divider = dividerRef.current;
if (unreadIndex >= 0 && !hasScrolledToBoundaryRef.current && list && divider) {
hasScrolledToBoundaryRef.current = true;
// Scroll the history pane only. `scrollIntoView` would also scroll every
// ancestor scroller, yanking the whole page out of position.
const offset = divider.getBoundingClientRect().top - list.getBoundingClientRect().top;
list.scrollTop = Math.max(0, list.scrollTop + offset - UNREAD_DIVIDER_HEADROOM_PX);
isAtBottomRef.current = false;
setIsAtBottom(false);
return;
}
if (isAtBottomRef.current) scrollToBottom();
}, [messageCount, scrollToBottom]);
}, [messageCount, scrollToBottom, unreadIndex]);
function handleScroll() {
const list = listRef.current;
@@ -69,58 +117,76 @@ function MessageHistory({ conversation }: { conversation: ConversationDetailResp
setIsAtBottom(atBottom);
}
if (!conversation.messages || conversation.messages.length === 0) {
if (messageCount === 0) {
return <div className="conversation-empty-detail">No messages have been loaded for this conversation.</div>;
}
return (
<div className="conversation-messages-shell">
<ol aria-label="Message history" className="conversation-messages" onScroll={handleScroll} ref={listRef}>
{conversation.messages.map((message) => (
<li className={message.isSelf ? 'is-self' : 'is-recipient'} key={message.eventId ?? `${message.timestamp}-${message.sender}-${message.text}`}>
<div>
<strong>{message.isSelf
? `You${conversation.owner ? ` (u/${conversation.owner.redditUsername})` : ''}`
: <RedditUsernameLink username={conversation.username} />}</strong>
{message.isAi ? <span aria-label="Sent by AI" className="conversation-ai-badge">AI</span> : null}
<time dateTime={new Date(message.timestamp).toISOString()}>{formatExactTime(message.timestamp)}</time>
</div>
<p>{message.text}</p>
{message.media?.length ? (
<div className="conversation-message-images">
{message.media.map((media) => {
const mediaKey = `${message.timestamp}-${media.localPath}`;
const sender = message.isSelf ? 'sent by you' : `received from ${redditUsernameLabel(conversation.username)}`;
const isRevealed = revealedMedia.has(mediaKey);
{messages.map((message, index) => {
const previous = index > 0 ? messages[index - 1] : null;
const startsNewDay = previous === null || !isSameDay(previous.timestamp, message.timestamp);
const key = message.eventId ?? `${message.timestamp}-${message.sender}-${message.text}`;
return (
<div className="conversation-message-image" key={mediaKey}>
<img
alt={`Image ${sender}`}
className={isRevealed ? undefined : 'is-blurred'}
loading="lazy"
src={mediaPath(media.localPath)}
/>
<button
aria-pressed={isRevealed}
className="conversation-image-reveal"
onClick={() => setRevealedMedia((current) => {
const next = new Set(current);
if (next.has(mediaKey)) next.delete(mediaKey);
else next.add(mediaKey);
return next;
})}
type="button"
>
{isRevealed ? 'Blur conversation image' : 'Reveal conversation image'}
</button>
</div>
);
})}
return [
startsNewDay ? (
<li aria-hidden="true" className="conversation-day-divider" key={`day-${key}`}>
<span>{formatDayLabel(message.timestamp, now)}</span>
</li>
) : null,
index === unreadIndex ? (
<li className="conversation-unread-divider" key={`unread-${key}`} ref={dividerRef}>
<span>New messages</span>
</li>
) : null,
<li className={message.isSelf ? 'is-self' : 'is-recipient'} key={key}>
<div>
<strong>{message.isSelf
? `You${conversation.owner ? ` (u/${conversation.owner.redditUsername})` : ''}`
: <RedditUsernameLink username={conversation.username} />}</strong>
{message.isAi ? <span aria-label="Sent by AI" className="conversation-ai-badge">AI</span> : null}
<time dateTime={new Date(message.timestamp).toISOString()} title={formatExactTime(message.timestamp)}>
{formatTimeOfDay(message.timestamp)}
</time>
</div>
) : null}
</li>
))}
<p>{message.text}</p>
{message.media?.length ? (
<div className="conversation-message-images">
{message.media.map((media) => {
const mediaKey = `${message.timestamp}-${media.localPath}`;
const sender = message.isSelf ? 'sent by you' : `received from ${redditUsernameLabel(conversation.username)}`;
const isRevealed = revealedMedia.has(mediaKey);
return (
<div className="conversation-message-image" key={mediaKey}>
<img
alt={`Image ${sender}`}
className={isRevealed ? undefined : 'is-blurred'}
loading="lazy"
src={mediaPath(media.localPath)}
/>
<button
aria-pressed={isRevealed}
className="conversation-image-reveal"
onClick={() => setRevealedMedia((current) => {
const next = new Set(current);
if (next.has(mediaKey)) next.delete(mediaKey);
else next.add(mediaKey);
return next;
})}
type="button"
>
{isRevealed ? 'Blur conversation image' : 'Reveal conversation image'}
</button>
</div>
);
})}
</div>
) : null}
</li>,
];
})}
</ol>
{!isAtBottom ? (
<button className="conversation-jump-latest" onClick={scrollToBottom} type="button">
@@ -225,13 +291,6 @@ function ConversationComposer({ conversation, conversationId }: { conversation:
{mediaAskMutation.isPending ? 'Generating media ask…' : 'Suggest media ask'}
</button>
</div>
<div
className={`conversation-automation-status is-${conversation.automation.status}`}
role="status"
>
<strong>{conversation.automation.remainingTurns} automated {conversation.automation.remainingTurns === 1 ? 'turn' : 'turns'} remaining</strong>
<span>{automationStatusMessage(conversation)}</span>
</div>
<label className="sr-only" htmlFor="conversation-reply">Reply to {redditUsernameLabel(conversation.username)}</label>
<textarea
id="conversation-reply"
@@ -375,8 +434,120 @@ function automationStatusMessage(conversation: ConversationDetailResponse): stri
}
}
/**
* Triage controls for the open conversation. These live in the header rather
* than the composer because they act on the conversation, not on the draft.
*/
function ConversationTriageActions({ conversation, conversationId, onResolved }: {
conversation: ConversationDetailResponse;
conversationId: string;
onResolved(): void;
}) {
const [isSnoozeOpen, setIsSnoozeOpen] = useState(false);
const markRead = useMarkConversationReadMutation();
const markUnread = useMarkConversationUnreadMutation();
const setStatus = useSetConversationStatusMutation();
const status = triageStatus(conversation);
const unread = isUnread(conversation);
return (
<div className="conversation-triage-actions">
<button
disabled={markRead.isPending || markUnread.isPending}
onClick={() => (unread
? markRead.mutate({ id: conversationId })
: markUnread.mutate({ id: conversationId }))}
type="button"
>
{unread ? 'Mark read' : 'Mark unread'}
</button>
<div className="conversation-snooze">
<button
aria-expanded={isSnoozeOpen}
onClick={() => setIsSnoozeOpen((current) => !current)}
type="button"
>
{status === 'snoozed' ? 'Snoozed' : 'Snooze'}
</button>
{isSnoozeOpen ? (
<div aria-label="Snooze options" className="conversation-snooze-menu" role="group">
{SNOOZE_OPTIONS.map((option) => (
<button
key={option.label}
onClick={() => {
setStatus.mutate({ id: conversationId, status: 'snoozed', snoozeUntil: Date.now() + option.ms });
setIsSnoozeOpen(false);
onResolved();
}}
type="button"
>
{option.label}
</button>
))}
{status === 'snoozed' ? (
<button
onClick={() => {
setStatus.mutate({ id: conversationId, status: 'open' });
setIsSnoozeOpen(false);
}}
type="button"
>
Unsnooze
</button>
) : null}
</div>
) : null}
</div>
{status === 'done' ? (
<button onClick={() => setStatus.mutate({ id: conversationId, status: 'open' })} type="button">
Reopen
</button>
) : (
<button
onClick={() => {
setStatus.mutate({ id: conversationId, status: 'done' });
onResolved();
}}
type="button"
>
Mark done
</button>
)}
</div>
);
}
/**
* Advances the read watermark once the operator has actually had the
* conversation open for a moment. Debounced so switching quickly through rows
* does not mark everything read, and keyed on the newest message so a reply
* arriving while the panel is open is also picked up.
*/
function useAutoMarkRead(conversationId: string, conversation: ConversationDetailResponse | undefined) {
const markRead = useMarkConversationReadMutation();
const markedRef = useRef<string | null>(null);
const newestTimestamp = conversation?.messages?.length
? conversation.messages[conversation.messages.length - 1].timestamp
: conversation?.lastMessageTime ?? 0;
const lastReadMessageTs = conversation?.lastReadMessageTs ?? 0;
const mutate = markRead.mutate;
useEffect(() => {
if (!conversation || newestTimestamp <= lastReadMessageTs) return;
const key = `${conversationId}:${newestTimestamp}`;
if (markedRef.current === key) return;
const timer = window.setTimeout(() => {
markedRef.current = key;
mutate({ id: conversationId, throughTimestamp: newestTimestamp });
}, AUTO_MARK_READ_DELAY_MS);
return () => window.clearTimeout(timer);
}, [conversation, conversationId, newestTimestamp, lastReadMessageTs, mutate]);
}
export function ConversationDetail({ conversationId, onClose }: ConversationDetailProps) {
const detailQuery = useConversationDetailQuery(conversationId);
const [now] = useState(() => Date.now());
useAutoMarkRead(conversationId, detailQuery.data);
if (detailQuery.isPending) {
return <div aria-label="Loading conversation" className="conversation-detail-state" role="status">Loading conversation…</div>;
@@ -392,18 +563,37 @@ export function ConversationDetail({ conversationId, onClose }: ConversationDeta
}
const conversation = detailQuery.data;
const status = triageStatus(conversation);
return (
<article className="conversation-detail">
<header>
<div>
<div className="conversation-detail-identity">
<span className="conversation-eyebrow">Conversation</span>
<h2><RedditUsernameLink username={conversation.username} /></h2>
<AccountOwnerBadge owner={conversation.owner} />
{conversation.sellerDetected ? <span className="conversation-seller-marker">Seller</span> : null}
{conversation.unread ? <span className="conversation-badge">Unread</span> : null}
<span className="conversation-detail-badges">
<AccountOwnerBadge owner={conversation.owner} />
{conversation.sellerDetected ? <span className="conversation-seller-marker">Seller</span> : null}
{isUnread(conversation) ? <span className="conversation-badge">Unread</span> : null}
{status === 'snoozed' ? <span className="conversation-badge is-snoozed">Snoozed</span> : null}
{status === 'done' ? <span className="conversation-badge is-done">Done</span> : null}
</span>
</div>
<div className="conversation-detail-controls">
<ConversationTriageActions
conversation={conversation}
conversationId={conversationId}
onResolved={onClose}
/>
<button aria-label="Close conversation" onClick={onClose} type="button">Close</button>
</div>
<button aria-label="Close conversation" onClick={onClose} type="button">Close</button>
</header>
<div
className={`conversation-automation-status is-${conversation.automation.status}`}
role="status"
>
<strong>{conversation.automation.remainingTurns} automated {conversation.automation.remainingTurns === 1 ? 'turn' : 'turns'} remaining</strong>
<span>{automationStatusMessage(conversation)}</span>
</div>
{conversation.syncInProgress ? (
<div className="conversation-sync-notice" role="status">
A {conversation.syncInProgress.kind ?? 'chat'} sync is in progress. Messages may be stale.
@@ -420,7 +610,7 @@ export function ConversationDetail({ conversationId, onClose }: ConversationDeta
}} />
</div>
) : null}
<MessageHistory conversation={conversation} />
<MessageHistory conversation={conversation} now={now} />
<ConversationComposer conversation={conversation} conversationId={conversationId} />
</article>
);
@@ -1,5 +1,7 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query';
import type { ActiveChat, ConversationTriageStatus } from '../../../../../packages/api-contracts/src/index.js';
import { conversationApi } from './conversation-api.js';
import { ownedConversationId } from './conversation-identity.js';
export const conversationQueryKeys = {
all: ['conversations'] as const,
@@ -78,6 +80,108 @@ export function useShareConversationMediaMutation(id: string) {
});
}
/**
* Applies a triage patch to the cached list and detail entries for one
* conversation. Read-state writes are optimistic because the list only polls
* every 30s — waiting for a refetch would make marking read feel broken.
*/
function patchCachedConversation(
queryClient: QueryClient,
id: string,
patch: Partial<ActiveChat>,
): void {
queryClient.setQueryData<ActiveChat[]>(conversationQueryKeys.all, (current) =>
current?.map((conversation) => (ownedConversationId(conversation) === id
? { ...conversation, ...patch }
: conversation)));
queryClient.setQueryData<ActiveChat>(
conversationQueryKeys.detail(id),
(current) => (current ? { ...current, ...patch } : current),
);
}
function cachedConversation(queryClient: QueryClient, id: string): ActiveChat | undefined {
return queryClient.getQueryData<ActiveChat[]>(conversationQueryKeys.all)
?.find((conversation) => ownedConversationId(conversation) === id);
}
export function useMarkConversationReadMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, throughTimestamp }: { id: string; throughTimestamp?: number }) =>
conversationApi.markRead(id, throughTimestamp),
onMutate({ id, throughTimestamp }) {
const watermark = throughTimestamp ?? cachedConversation(queryClient, id)?.lastMessageTime ?? 0;
patchCachedConversation(queryClient, id, { hasUnreadInbound: false, lastReadMessageTs: watermark });
},
async onSettled() {
await queryClient.invalidateQueries({ queryKey: conversationQueryKeys.all });
},
});
}
export function useMarkConversationUnreadMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, beforeTimestamp }: { id: string; beforeTimestamp?: number }) =>
conversationApi.markUnread(id, beforeTimestamp),
onMutate({ id, beforeTimestamp }) {
const boundary = beforeTimestamp ?? cachedConversation(queryClient, id)?.lastMessageTime ?? 0;
patchCachedConversation(queryClient, id, {
hasUnreadInbound: true,
triageStatus: 'open',
snoozedUntil: null,
lastReadMessageTs: Math.max(0, boundary - 1),
});
},
async onSettled() {
await queryClient.invalidateQueries({ queryKey: conversationQueryKeys.all });
},
});
}
export function useSetConversationStatusMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, status, snoozeUntil }: {
id: string;
status: ConversationTriageStatus;
snoozeUntil?: number | null;
}) => conversationApi.setStatus(id, status, snoozeUntil),
onMutate({ id, status, snoozeUntil }) {
const conversation = cachedConversation(queryClient, id);
patchCachedConversation(queryClient, id, {
triageStatus: status,
snoozedUntil: status === 'snoozed' ? snoozeUntil ?? null : null,
// Resolving a conversation implies you have read it.
...(status === 'done'
? { hasUnreadInbound: false, lastReadMessageTs: conversation?.lastMessageTime ?? 0 }
: {}),
needsReply: status === 'open' && conversation?.isFromUs === false,
});
},
async onSettled() {
await queryClient.invalidateQueries({ queryKey: conversationQueryKeys.all });
},
});
}
export function useBulkMarkConversationsReadMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (ids: string[]) => conversationApi.bulkMarkRead(ids),
onMutate(ids) {
for (const id of ids) {
const watermark = cachedConversation(queryClient, id)?.lastMessageTime ?? 0;
patchCachedConversation(queryClient, id, { hasUnreadInbound: false, lastReadMessageTs: watermark });
}
},
async onSettled() {
await queryClient.invalidateQueries({ queryKey: conversationQueryKeys.all });
},
});
}
export function useStartConversationMutation() {
const queryClient = useQueryClient();
return useMutation({
@@ -1,20 +1,24 @@
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { ConversationsPage, type ConversationFilters } from './conversations-page.js';
import { ConversationsPage } from './conversations-page.js';
import {
DEFAULT_CONVERSATION_FILTERS,
isConversationFilter,
isConversationSort,
type ConversationFilters,
} from './conversation-triage.js';
export function ConversationRoute() {
const navigate = useNavigate();
const { conversationId } = useParams<{ conversationId: string }>();
const [searchParams, setSearchParams] = useSearchParams();
const filterValue = searchParams.get('filter');
const sortValue = searchParams.get('sort');
const filters: ConversationFilters = {
search: searchParams.get('q') ?? '',
showSellers: searchParams.get('showSellers') === 'true',
filter:
filterValue === 'unread'
|| filterValue === 'awaiting-reply'
|| filterValue === 'received-images'
? filterValue
: 'all',
filter: isConversationFilter(filterValue) ? filterValue : DEFAULT_CONVERSATION_FILTERS.filter,
sort: isConversationSort(sortValue) ? sortValue : DEFAULT_CONVERSATION_FILTERS.sort,
account: searchParams.get('account') ?? DEFAULT_CONVERSATION_FILTERS.account,
};
function selectConversation(nextConversationId: string | null) {
@@ -31,6 +35,8 @@ export function ConversationRoute() {
if (next.search) params.set('q', next.search); else params.delete('q');
if (next.filter !== 'all') params.set('filter', next.filter); else params.delete('filter');
if (next.showSellers) params.set('showSellers', 'true'); else params.delete('showSellers');
if (next.sort !== DEFAULT_CONVERSATION_FILTERS.sort) params.set('sort', next.sort); else params.delete('sort');
if (next.account !== 'all') params.set('account', next.account); else params.delete('account');
setSearchParams(params, { replace: true });
}
@@ -0,0 +1,204 @@
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 },
];
@@ -1,25 +1,39 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { ActiveChat } from '../../../../../packages/api-contracts/src/index.js';
import { RedditUsernameLink, redditUsernameLabel } from '../../components/reddit-username-link.js';
import { ConversationDetail } from './conversation-detail.js';
import { useConversationsQuery } from './conversation-queries.js';
import {
useBulkMarkConversationsReadMutation,
useConversationsQuery,
useMarkConversationReadMutation,
useMarkConversationUnreadMutation,
useSetConversationStatusMutation,
} from './conversation-queries.js';
import { StartConversationForm } from './start-conversation-form.js';
import { ProcessedUserLookup } from './processed-user-lookup.js';
import { AccountOwnerBadge } from '../../components/account-owner-badge.js';
import './conversations.css';
import { ownedConversationId } from './conversation-identity.js';
import { formatExactTime, formatShortRelativeTime } from './relative-time.js';
import { conversationAge, formatExactTime, formatShortRelativeTime } from './relative-time.js';
import {
CONVERSATION_FILTERS,
CONVERSATION_SORTS,
DEFAULT_CONVERSATION_FILTERS,
accountOptions,
filterCounts,
isUnread,
needsReply,
partitionConversations,
triageStatus,
type ConversationFilter,
type ConversationFilters,
type ConversationSort,
} from './conversation-triage.js';
export type ConversationFilter = 'all' | 'unread' | 'awaiting-reply' | 'received-images';
export type { ConversationFilter, ConversationFilters, ConversationSort } from './conversation-triage.js';
const SMALL_VIEWPORT_QUERY = '(max-width: 51.9999rem)';
export interface ConversationFilters {
search: string;
filter: ConversationFilter;
showSellers: boolean;
}
export interface ConversationsPageProps {
selectedConversationId?: string | null;
onSelectedConversationChange?(conversationId: string | null): void;
@@ -27,59 +41,118 @@ export interface ConversationsPageProps {
onFiltersChange?(filters: ConversationFilters): void;
}
function matchesFilter(conversation: ActiveChat, filter: ConversationFilter): boolean {
if (filter === 'unread') return conversation.unread;
if (filter === 'awaiting-reply') return conversation.isFromUs;
if (filter === 'received-images') return conversation.hasReceivedImages === true;
return true;
}
function ConversationListItem({ conversation, isSelected, now, onSelect }: {
interface ConversationRowProps {
conversation: ActiveChat;
isSelected: boolean;
isChecked: boolean;
/** Only worth the row space when more than one account is in play. */
showOwner: boolean;
now: number;
onSelect(): void;
}) {
const state = conversation.unread ? 'Unread' : conversation.isFromUs ? 'Awaiting reply' : 'Up to date';
onToggleChecked(): void;
registerRef(element: HTMLButtonElement | null): void;
}
/** Independent state chips. A conversation can be several of these at once. */
function conversationChips(conversation: ActiveChat, now: number): string[] {
const chips: string[] = [];
if (isUnread(conversation)) chips.push('Unread');
if (needsReply(conversation)) chips.push('Needs reply');
else if (conversation.isFromUs && triageStatus(conversation) === 'open') chips.push('Waiting on them');
const status = triageStatus(conversation);
if (status === 'snoozed') chips.push('Snoozed');
if (status === 'done') chips.push('Done');
if (needsReply(conversation) && conversationAge(conversation.lastMessageTime, now) !== 'fresh') {
chips.push('Overdue');
}
return chips;
}
function ConversationRow({
conversation, isSelected, isChecked, showOwner, now, onSelect, onToggleChecked, registerRef,
}: ConversationRowProps) {
const relativeTime = formatShortRelativeTime(conversation.lastMessageTime, now);
const unread = isUnread(conversation);
const overdue = needsReply(conversation) ? conversationAge(conversation.lastMessageTime, now) : 'fresh';
const chips = conversationChips(conversation, now);
const itemClasses = ['conversation-list-item'];
if (isSelected) itemClasses.push('is-selected');
if (conversation.unread) itemClasses.push('is-unread');
if (unread) itemClasses.push('is-unread');
if (isChecked) itemClasses.push('is-checked');
const descriptors = [
redditUsernameLabel(conversation.username),
...chips,
relativeTime,
...(conversation.sellerDetected ? ['Seller'] : []),
...(conversation.hasReceivedImages ? ['Image received'] : []),
];
return (
<li className={itemClasses.join(' ')}>
<label className="conversation-list-check">
<input
aria-label={`Select ${redditUsernameLabel(conversation.username)}`}
checked={isChecked}
onChange={onToggleChecked}
type="checkbox"
/>
</label>
<button
aria-label={`${redditUsernameLabel(conversation.username)}, ${state}, ${relativeTime}${conversation.sellerDetected ? ', Seller' : ''}${conversation.hasReceivedImages ? ', Image received' : ''}`}
aria-pressed={isSelected}
className="conversation-list-target"
aria-current={isSelected || undefined}
aria-label={descriptors.join(', ')}
className="conversation-list-open"
onClick={onSelect}
ref={registerRef}
type="button"
/>
<span className="conversation-list-heading">
<strong><RedditUsernameLink username={conversation.username} /></strong>
<span className="conversation-list-meta">
<small>{state}</small>
<time dateTime={new Date(conversation.lastMessageTime).toISOString()} title={formatExactTime(conversation.lastMessageTime)}>
>
<span className="conversation-list-heading">
<strong>{redditUsernameLabel(conversation.username)}</strong>
<time
className={overdue === 'fresh' ? undefined : `is-${overdue}`}
dateTime={new Date(conversation.lastMessageTime).toISOString()}
title={formatExactTime(conversation.lastMessageTime)}
>
{relativeTime}
</time>
</span>
<span className="conversation-list-snippet">
{conversation.lastMessageSnippet || 'No message preview'}
</span>
</button>
<span className="conversation-list-chips">
{chips.map((chip) => (
<span className={`conversation-chip is-${chip.toLowerCase().replaceAll(' ', '-')}`} key={chip}>
{chip}
</span>
))}
{showOwner ? <AccountOwnerBadge owner={conversation.owner} /> : null}
{conversation.sellerDetected ? <span className="conversation-seller-marker">Seller</span> : null}
{conversation.hasReceivedImages ? <span className="conversation-image-marker">Image received</span> : null}
<span className="conversation-list-profile"><RedditUsernameLink username={conversation.username} /></span>
</span>
<AccountOwnerBadge owner={conversation.owner} />
{conversation.sellerDetected ? <span className="conversation-seller-marker">Seller</span> : null}
{conversation.hasReceivedImages ? <span className="conversation-image-marker">Image received</span> : null}
<span>{conversation.lastMessageSnippet || 'No message preview'}</span>
</li>
);
}
export function ConversationsPage({ selectedConversationId, onSelectedConversationChange, filters, onFiltersChange }: ConversationsPageProps) {
export function ConversationsPage({
selectedConversationId, onSelectedConversationChange, filters, onFiltersChange,
}: ConversationsPageProps) {
const conversationsQuery = useConversationsQuery();
const [internalSelectedId, setInternalSelectedId] = useState<string | null>(null);
const [localFilters, setLocalFilters] = useState<ConversationFilters>({ search: '', filter: 'all', showSellers: false });
const [localFilters, setLocalFilters] = useState<ConversationFilters>(DEFAULT_CONVERSATION_FILTERS);
const [isStartingConversation, setIsStartingConversation] = useState(false);
const [now, setNow] = useState(() => Date.now());
const [checkedIds, setCheckedIds] = useState<Set<string>>(() => new Set());
const detailPanelRef = useRef<HTMLElement>(null);
const searchRef = useRef<HTMLInputElement>(null);
const rowRefs = useRef(new Map<string, HTMLButtonElement>());
const activeConversationId = selectedConversationId !== undefined ? selectedConversationId : internalSelectedId;
const activeFilters = filters ?? localFilters;
const markRead = useMarkConversationReadMutation();
const markUnread = useMarkConversationUnreadMutation();
const setStatus = useSetConversationStatusMutation();
const bulkMarkRead = useBulkMarkConversationsReadMutation();
useEffect(() => {
const interval = window.setInterval(() => setNow(Date.now()), 60_000);
@@ -95,28 +168,54 @@ export function ConversationsPage({ selectedConversationId, onSelectedConversati
detailPanelRef.current?.scrollIntoView?.({ behavior: 'smooth', block: 'start' });
}, [activeConversationId]);
function updateFilters(next: ConversationFilters) {
const updateFilters = useCallback((next: ConversationFilters) => {
if (filters === undefined) setLocalFilters(next);
onFiltersChange?.(next);
}
}, [filters, onFiltersChange]);
const allConversations = conversationsQuery.data ?? [];
const { visible: liveConversations, hiddenSellerCount } = useMemo(
() => partitionConversations(allConversations, activeFilters),
[allConversations, activeFilters],
);
const counts = useMemo(() => filterCounts(allConversations, activeFilters), [allConversations, activeFilters]);
const accounts = useMemo(() => accountOptions(allConversations), [allConversations]);
// While a conversation is open the row order is frozen. A background poll
// re-sorting the list would move rows out from under the operator mid-triage;
// anything new is surfaced as an explicit refresh instead.
const [frozenOrder, setFrozenOrder] = useState<string[] | null>(null);
const liveIds = useMemo(
() => liveConversations.map((conversation) => ownedConversationId(conversation)),
[liveConversations],
);
useEffect(() => {
if (!activeConversationId) {
setFrozenOrder(null);
return;
}
// Capture the order as it was when the conversation was opened. `liveIds` is
// intentionally read once here rather than tracked, so later polls do not
// re-freeze against a reordered list.
setFrozenOrder((current) => current ?? liveIds);
}, [activeConversationId, liveIds]);
const visibleConversations = useMemo(() => {
const normalizedSearch = activeFilters.search.trim().toLowerCase();
return (conversationsQuery.data ?? [])
.filter((conversation) => {
const matchesSearch = normalizedSearch.length === 0
|| conversation.username.toLowerCase().includes(normalizedSearch)
|| conversation.lastMessageSnippet.toLowerCase().includes(normalizedSearch);
return matchesSearch
&& matchesFilter(conversation, activeFilters.filter)
&& (activeFilters.showSellers || conversation.sellerDetected !== true);
})
.sort((left, right) => right.lastMessageTime - left.lastMessageTime);
}, [activeFilters, conversationsQuery.data]);
if (!frozenOrder) return liveConversations;
const rank = new Map(frozenOrder.map((id, index) => [id, index]));
return liveConversations
.filter((conversation) => rank.has(ownedConversationId(conversation)))
.sort((left, right) =>
(rank.get(ownedConversationId(left)) ?? 0) - (rank.get(ownedConversationId(right)) ?? 0));
}, [liveConversations, frozenOrder]);
const unreadCount = useMemo(
() => (conversationsQuery.data ?? []).filter((conversation) => conversation.unread).length,
[conversationsQuery.data],
const pendingCount = liveConversations.length - visibleConversations.length;
const visibleIds = useMemo(
() => visibleConversations.map((conversation) => ownedConversationId(conversation)),
[visibleConversations],
);
function selectConversation(id: string | null) {
@@ -124,6 +223,121 @@ export function ConversationsPage({ selectedConversationId, onSelectedConversati
onSelectedConversationChange?.(id);
}
function releaseFrozenOrder() {
setFrozenOrder(activeConversationId ? liveIds : null);
}
function toggleChecked(id: string) {
setCheckedIds((current) => {
const next = new Set(current);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
const checkedVisibleIds = visibleIds.filter((id) => checkedIds.has(id));
const allVisibleChecked = visibleIds.length > 0 && checkedVisibleIds.length === visibleIds.length;
function toggleAllVisible() {
setCheckedIds(allVisibleChecked ? new Set() : new Set(visibleIds));
}
function moveFocus(offset: number) {
if (visibleIds.length === 0) return;
const focused = document.activeElement;
let index = visibleIds.findIndex((id) => rowRefs.current.get(id) === focused);
if (index < 0) index = visibleIds.findIndex((id) => id === activeConversationId);
if (index < 0) {
// Entering the list for the first time: land on the near end rather than
// stepping past it.
rowRefs.current.get(visibleIds[offset > 0 ? 0 : visibleIds.length - 1])?.focus();
return;
}
const nextIndex = Math.min(visibleIds.length - 1, Math.max(0, index + offset));
rowRefs.current.get(visibleIds[nextIndex])?.focus();
}
function focusedConversationId(): string | null {
const focused = document.activeElement;
const focusedId = visibleIds.find((id) => rowRefs.current.get(id) === focused);
return focusedId ?? activeConversationId ?? null;
}
function isTypingTarget(target: EventTarget | null): boolean {
if (!(target instanceof HTMLElement)) return false;
return target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName);
}
/**
* Inbox keyboard shortcuts. Suppressed whenever focus is inside a text field
* so typing a reply or a search term never triggers an action.
*/
function handleShortcut(event: KeyboardEvent) {
if (event.metaKey || event.ctrlKey || event.altKey) return;
// A modal owns the keyboard while it is open — including Escape, which must
// dismiss the dialog rather than the conversation behind it.
if (event.defaultPrevented || document.querySelector('dialog[open]')) return;
const typing = isTypingTarget(event.target);
if (event.key === '/' && !typing) {
event.preventDefault();
searchRef.current?.focus();
return;
}
if (event.key === 'Escape') {
if (typing) (event.target as HTMLElement).blur();
else if (activeConversationId) selectConversation(null);
return;
}
if (typing) return;
switch (event.key) {
case 'j':
case 'ArrowDown':
event.preventDefault();
moveFocus(1);
break;
case 'k':
case 'ArrowUp':
event.preventDefault();
moveFocus(-1);
break;
case 'u': {
const id = focusedConversationId();
const conversation = allConversations.find((item) => ownedConversationId(item) === id);
if (!id || !conversation) return;
event.preventDefault();
if (isUnread(conversation)) markRead.mutate({ id });
else markUnread.mutate({ id });
break;
}
case 'e': {
const id = focusedConversationId();
if (!id) return;
event.preventDefault();
setStatus.mutate({ id, status: 'done' });
if (id === activeConversationId) selectConversation(null);
break;
}
default:
break;
}
}
// The handler closes over per-render state, so it is kept in a ref and the
// listener is registered once rather than re-bound on every render.
const shortcutRef = useRef(handleShortcut);
shortcutRef.current = handleShortcut;
useEffect(() => {
const listener = (event: KeyboardEvent) => shortcutRef.current(event);
window.addEventListener('keydown', listener);
return () => window.removeEventListener('keydown', listener);
}, []);
const lastSyncedLabel = conversationsQuery.dataUpdatedAt
? formatShortRelativeTime(conversationsQuery.dataUpdatedAt, now)
: null;
return (
<div className="conversations-page">
<header className="conversations-header">
@@ -142,7 +356,9 @@ export function ConversationsPage({ selectedConversationId, onSelectedConversati
>
{conversationsQuery.isFetching ? 'Refreshing…' : 'Refresh'}
</button>
<span className="conversation-refresh-note">Auto-refreshes every 30s</span>
<span className="conversation-refresh-note">
{lastSyncedLabel ? `Updated ${lastSyncedLabel} · auto every 30s` : 'Auto-refreshes every 30s'}
</span>
</div>
<button className="conversation-primary" onClick={() => setIsStartingConversation((current) => !current)} type="button">
{isStartingConversation ? 'Close new conversation' : 'New conversation'}
@@ -165,30 +381,107 @@ export function ConversationsPage({ selectedConversationId, onSelectedConversati
<input
id="conversation-search"
onChange={(event) => updateFilters({ ...activeFilters, search: event.target.value })}
placeholder="Search conversations"
placeholder="Search conversations (/)"
ref={searchRef}
type="search"
value={activeFilters.search}
/>
<label className="sr-only" htmlFor="conversation-filter">Filter conversations</label>
<select
id="conversation-filter"
onChange={(event) => updateFilters({ ...activeFilters, filter: event.target.value as ConversationFilter })}
value={activeFilters.filter}
>
<option value="all">All</option>
<option value="unread">Unread</option>
<option value="awaiting-reply">Awaiting reply</option>
<option value="received-images">Received images</option>
</select>
<span className="conversation-unread-count">{unreadCount} unread</span>
<label className="conversation-seller-toggle">
<input
checked={activeFilters.showSellers}
onChange={(event) => updateFilters({ ...activeFilters, showSellers: event.target.checked })}
type="checkbox"
/>
Show sellers
</label>
<div aria-label="Filter conversations" className="conversation-filter-pills" role="group">
{CONVERSATION_FILTERS.map((option) => (
<button
aria-label={`${option.label}, ${counts[option.value]}`}
aria-pressed={activeFilters.filter === option.value}
className="conversation-filter-pill"
key={option.value}
onClick={() => updateFilters({ ...activeFilters, filter: option.value })}
type="button"
>
{option.label}
<span className="conversation-filter-count">{counts[option.value]}</span>
</button>
))}
</div>
<div className="conversation-toolbar-row">
<label className="conversation-sort">
<span>Sort</span>
<select
onChange={(event) => updateFilters({
...activeFilters,
sort: event.target.value as ConversationSort,
})}
value={activeFilters.sort}
>
{CONVERSATION_SORTS.map((option) => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</label>
{accounts.length > 1 ? (
<label className="conversation-account-filter">
<span>Account</span>
<select
onChange={(event) => updateFilters({ ...activeFilters, account: event.target.value })}
value={activeFilters.account}
>
<option value="all">All accounts</option>
{accounts.map((account) => (
<option key={account.accountId} value={account.accountId}>
u/{account.redditUsername}
</option>
))}
</select>
</label>
) : null}
<label className="conversation-seller-toggle">
<input
checked={activeFilters.showSellers}
onChange={(event) => updateFilters({ ...activeFilters, showSellers: event.target.checked })}
type="checkbox"
/>
Show sellers
</label>
</div>
{visibleConversations.length > 0 ? (
<div className="conversation-bulk-bar">
<label className="conversation-bulk-select-all">
<input
aria-label="Select all visible conversations"
checked={allVisibleChecked}
onChange={toggleAllVisible}
type="checkbox"
/>
{checkedVisibleIds.length > 0 ? `${checkedVisibleIds.length} selected` : 'Select all'}
</label>
{checkedVisibleIds.length > 0 ? (
<>
<button
disabled={bulkMarkRead.isPending}
onClick={() => bulkMarkRead.mutate(checkedVisibleIds, {
onSuccess: () => setCheckedIds(new Set()),
})}
type="button"
>
{bulkMarkRead.isPending ? 'Marking read…' : 'Mark read'}
</button>
<button
disabled={setStatus.isPending}
onClick={() => {
for (const id of checkedVisibleIds) setStatus.mutate({ id, status: 'done' });
setCheckedIds(new Set());
}}
type="button"
>
Mark done
</button>
</>
) : null}
</div>
) : null}
{pendingCount > 0 ? (
<button className="conversation-pending-refresh" onClick={releaseFrozenOrder} type="button">
{pendingCount} new {pendingCount === 1 ? 'conversation' : 'conversations'} — refresh list
</button>
) : null}
</div>
{conversationsQuery.isPending ? (
<div aria-label="Loading conversations" className="conversation-list-state" role="status">Loading conversations…</div>
@@ -201,19 +494,45 @@ export function ConversationsPage({ selectedConversationId, onSelectedConversati
) : conversationsQuery.data.length === 0 ? (
<div className="conversation-list-state"><strong>No conversations yet.</strong><span>Start one when you are ready.</span></div>
) : visibleConversations.length === 0 ? (
<div className="conversation-list-state"><strong>No matching conversations.</strong><span>Try a different search or filter.</span></div>
<div className="conversation-list-state">
<strong>No matching conversations.</strong>
<span>Try a different search or filter.</span>
{hiddenSellerCount > 0 ? (
<span>{hiddenSellerCount} hidden by the seller filter.</span>
) : null}
</div>
) : (
<ul className="conversation-list">
{visibleConversations.map((conversation) => (
<ConversationListItem
conversation={conversation}
isSelected={ownedConversationId(conversation) === activeConversationId}
key={ownedConversationId(conversation)}
now={now}
onSelect={() => selectConversation(ownedConversationId(conversation))}
/>
))}
</ul>
<>
<ul className="conversation-list">
{visibleConversations.map((conversation) => {
const id = ownedConversationId(conversation);
return (
<ConversationRow
conversation={conversation}
isChecked={checkedIds.has(id)}
isSelected={id === activeConversationId}
key={id}
now={now}
onSelect={() => selectConversation(id)}
onToggleChecked={() => toggleChecked(id)}
showOwner={accounts.length > 1}
registerRef={(element) => {
if (element) rowRefs.current.set(id, element);
else rowRefs.current.delete(id);
}}
/>
);
})}
</ul>
<p className="conversation-list-footer">
{hiddenSellerCount > 0
? `${hiddenSellerCount} hidden by the seller filter.`
: null}
<span className="conversation-shortcut-hint">
j/k move · Enter opens · u toggles unread · e marks done · / searches
</span>
</p>
</>
)}
</section>
@@ -40,39 +40,88 @@
.conversation-field input:focus, .conversation-field textarea:focus, .conversation-toolbar input:focus, .conversation-toolbar select:focus, .conversation-composer textarea:focus { outline: 2px solid var(--accent); outline-offset: 2px; }
.conversation-workspace { display: grid; gap: .75rem; }
.conversation-master, .conversation-detail-panel { min-width: 0; background: var(--surface); border: 1px solid var(--border); border-radius: .9rem; overflow: hidden; }
.conversation-toolbar { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: .5rem; padding: .75rem; border-bottom: 1px solid var(--border); }
.conversation-unread-count { grid-column: 1 / -1; color: var(--accent); font-size: .75rem; font-weight: 800; }
.conversation-seller-toggle { grid-column: 1 / -1; display: inline-flex; align-items: center; gap: .45rem; color: var(--muted); font-size: .78rem; font-weight: 700; }
.conversation-toolbar { display: grid; gap: .55rem; padding: .75rem; border-bottom: 1px solid var(--border); }
.conversation-toolbar-row { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; }
.conversation-seller-toggle { display: inline-flex; align-items: center; gap: .45rem; color: var(--muted); font-size: .78rem; font-weight: 700; white-space: nowrap; }
.conversation-seller-toggle input { width: auto; accent-color: var(--accent); }
.conversation-sort, .conversation-account-filter { display: inline-flex; align-items: center; gap: .4rem; color: var(--muted); font-size: .78rem; font-weight: 700; }
.conversation-sort select, .conversation-account-filter select { padding: .35rem .45rem; color: #e9f1ec; background: #0b1410; border: 1px solid var(--border); border-radius: .45rem; font-size: .78rem; }
/* Filter pills replace a select so every bucket's count is visible at a glance. */
.conversation-filter-pills { display: flex; flex-wrap: wrap; gap: .35rem; }
.conversation-filter-pill { display: inline-flex; align-items: center; gap: .4rem; min-height: 2rem !important; padding: .3rem .6rem !important; border-radius: 999px !important; font-size: .78rem; font-weight: 700; }
.conversation-filter-pill[aria-pressed='true'] { color: #06140b !important; background: var(--accent) !important; border-color: transparent !important; }
.conversation-filter-count { padding: .05rem .35rem; border-radius: 999px; background: rgba(255, 255, 255, .12); font-size: .7rem; font-weight: 800; font-variant-numeric: tabular-nums; }
.conversation-filter-pill[aria-pressed='true'] .conversation-filter-count { background: rgba(0, 0, 0, .22); }
.conversation-bulk-bar { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; }
.conversation-bulk-select-all { display: inline-flex; align-items: center; gap: .45rem; color: var(--muted); font-size: .78rem; font-weight: 700; white-space: nowrap; }
.conversation-bulk-select-all input { accent-color: var(--accent); }
.conversation-bulk-bar button { min-height: 2rem !important; padding: .3rem .6rem !important; font-size: .78rem; }
.conversation-pending-refresh { justify-self: start; min-height: 2rem !important; padding: .3rem .65rem !important; color: var(--warning-text) !important; background: var(--warning-bg) !important; border-color: var(--warning-border) !important; font-size: .78rem; font-weight: 700; }
.conversation-list { display: grid; gap: .35rem; max-height: 46rem; padding: .5rem; margin: 0; overflow: auto; list-style: none; }
.conversation-list-item { position: relative; display: grid; gap: .4rem; width: 100%; padding: .8rem; text-align: left; background: transparent; border: 1px solid transparent; border-radius: .6rem; }
/*
* The row is a grid of real siblings: a selection checkbox, a primary open
* button, and a chip strip. The previous full-bleed absolute overlay button made
* every per-row control need a pointer-events escape hatch.
*/
.conversation-list-item { position: relative; display: grid; grid-template-columns: auto minmax(0, 1fr); gap: .15rem .5rem; width: 100%; padding: .6rem .7rem; background: transparent; border: 1px solid transparent; border-radius: .6rem; }
.conversation-list-item:hover { background: var(--surface-raised); }
.conversation-list-item.is-selected { background: var(--accent-dark); border-color: #28593d; }
.conversation-list-item.is-unread { padding-left: 1.4rem; }
.conversation-list-item.is-unread::before { content: ''; position: absolute; top: 1.2rem; left: .55rem; width: .45rem; height: .45rem; background: var(--accent); border-radius: 50%; }
.conversation-list-item.is-checked { border-color: var(--accent); }
.conversation-list-item.is-unread .conversation-list-heading strong { font-weight: 900; }
.conversation-list-target { position: absolute; inset: 0; z-index: 0; min-height: 0 !important; padding: 0 !important; background: transparent !important; border: 0 !important; }
.conversation-list-target:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.conversation-list-item > span { position: relative; z-index: 1; pointer-events: none; }
.conversation-list-item .reddit-username-link { pointer-events: auto; }
.conversation-list-item > span:last-child { overflow: hidden; color: var(--muted); font-size: .82rem; text-overflow: ellipsis; white-space: nowrap; }
.conversation-list-item.is-unread .conversation-list-heading strong::before { content: ''; display: inline-block; width: .45rem; height: .45rem; margin-right: .45rem; vertical-align: middle; background: var(--accent); border-radius: 50%; }
.conversation-list-check { display: flex; align-items: start; padding-top: .3rem; }
.conversation-list-check input { accent-color: var(--accent); }
.conversation-list-open { display: grid; gap: .25rem; width: 100%; min-height: 0 !important; padding: 0 !important; text-align: left; background: transparent !important; border: 0 !important; }
.conversation-list-open:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.conversation-list-snippet { overflow: hidden; color: var(--muted); font-size: .82rem; text-overflow: ellipsis; white-space: nowrap; }
.conversation-list-heading { display: flex; align-items: center; justify-content: space-between; gap: .5rem; }
.conversation-list-heading small { color: var(--accent); }
.conversation-list-meta { display: flex; align-items: center; gap: .45rem; }
.conversation-list-meta time { color: var(--muted); font-size: .7rem; white-space: nowrap; }
.conversation-list-heading time { color: var(--muted); font-size: .7rem; white-space: nowrap; }
.conversation-list-heading time.is-stale { color: var(--warning-text); font-weight: 700; }
.conversation-list-heading time.is-critical { color: var(--danger-text); font-weight: 800; }
.conversation-list-chips { grid-column: 2; display: flex; flex-wrap: wrap; align-items: center; gap: .3rem; }
.conversation-list-profile { font-size: .7rem; }
.conversation-chip { padding: .1rem .4rem; border: 1px solid var(--border); border-radius: 999px; background: var(--surface-raised); color: var(--muted); font-size: .68rem; font-weight: 750; }
.conversation-chip.is-unread { color: var(--accent); border-color: #28593d; background: var(--accent-dark); }
.conversation-chip.is-needs-reply { color: #cfe8ff; border-color: #315d85; background: #18324d; }
.conversation-chip.is-overdue { color: var(--warning-text); border-color: var(--warning-border); background: var(--warning-bg); }
.conversation-chip.is-snoozed, .conversation-chip.is-done { opacity: .85; }
.conversation-list-footer { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .5rem; padding: .5rem .75rem .75rem; margin: 0; color: var(--muted); font-size: .72rem; }
.conversation-shortcut-hint { margin-left: auto; opacity: .8; }
.conversation-image-marker { justify-self: start; padding: .18rem .45rem; color: #d8e8ff !important; background: #18324d; border: 1px solid #315d85; border-radius: 999px; font-size: .68rem !important; font-weight: 750; }
.conversation-seller-marker { display: inline-flex; justify-self: start; padding: .18rem .45rem; margin-right: .35rem; color: #ffd6d0 !important; background: #4b1e1a; border: 1px solid #874139; border-radius: 999px; font-size: .68rem !important; font-weight: 800; }
.conversation-list-state, .conversation-detail-state { display: grid; place-items: center; align-content: center; gap: .5rem; min-height: 16rem; padding: 1.5rem; color: var(--muted); text-align: center; }
.conversation-list-state strong, .conversation-detail-state strong { color: #e9f1ec; }
.conversation-detail { min-height: 32rem; }
.conversation-detail > header { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; padding: 1rem; border-bottom: 1px solid var(--border); }
/* Column layout: history takes the slack, the composer stays reachable. */
.conversation-detail { display: flex; flex-direction: column; min-height: 32rem; max-height: min(48rem, calc(100vh - 6rem)); }
.conversation-detail > header { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: .75rem; padding: 1rem; border-bottom: 1px solid var(--border); }
.conversation-detail h2 { display: inline; margin-right: .6rem; }
.conversation-detail-identity { min-width: 0; }
.conversation-detail-badges { display: inline-flex; flex-wrap: wrap; align-items: center; gap: .35rem; }
.conversation-detail-controls { display: flex; flex-wrap: wrap; align-items: center; gap: .4rem; }
.conversation-triage-actions { display: flex; flex-wrap: wrap; align-items: center; gap: .4rem; }
.conversation-triage-actions button, .conversation-detail-controls > button { min-height: 2.1rem !important; padding: .35rem .6rem !important; font-size: .8rem; }
.conversation-snooze { position: relative; }
.conversation-snooze-menu { position: absolute; right: 0; z-index: 3; display: grid; gap: .2rem; min-width: 9rem; padding: .35rem; margin-top: .25rem; background: var(--surface-raised); border: 1px solid var(--border); border-radius: .55rem; box-shadow: 0 .5rem 1.5rem rgba(0, 0, 0, .45); }
.conversation-snooze-menu button { width: 100%; text-align: left; }
.conversation-badge { display: inline-flex; padding: .2rem .45rem; color: #aaf0c4; background: #163a26; border-radius: 999px; font-size: .7rem; font-weight: 800; }
.conversation-badge.is-snoozed { color: var(--warning-text); background: var(--warning-bg); }
.conversation-badge.is-done { color: var(--muted); background: var(--surface-raised); }
.conversation-sync-notice { padding: .75rem 1rem; color: #ffe1a0; background: #2a2111; border-bottom: 1px solid #59451e; }
.triggering-post { margin: 1rem; padding: .75rem; background: var(--surface-raised); border: 1px solid var(--border); border-radius: .65rem; }
.conversation-messages-shell { position: relative; }
.conversation-messages-shell { position: relative; display: flex; flex: 1 1 auto; min-height: 0; overflow: hidden; }
.conversation-jump-latest { position: absolute; right: 1rem; bottom: .75rem; z-index: 2; padding: .35rem .7rem !important; min-height: 2rem !important; color: #06140b !important; background: var(--accent) !important; border-color: transparent !important; border-radius: 999px !important; font-size: .78rem; font-weight: 800; box-shadow: 0 .4rem 1.2rem rgba(0, 0, 0, .35); }
.conversation-messages { display: grid; gap: .75rem; max-height: 30rem; padding: 1rem; margin: 0; overflow: auto; list-style: none; }
.conversation-messages { display: grid; flex: 1 1 auto; align-content: start; gap: .75rem; min-height: 0; padding: 1rem; margin: 0; overflow-y: auto; list-style: none; }
/* Day dividers let the reader see silences; the unread rule marks where to resume. */
.conversation-day-divider, .conversation-unread-divider { display: flex; align-items: center; gap: .6rem; justify-self: stretch; max-width: none !important; padding: 0 !important; background: none !important; }
.conversation-day-divider::before, .conversation-day-divider::after, .conversation-unread-divider::before, .conversation-unread-divider::after { content: ''; flex: 1; height: 1px; background: var(--border); }
.conversation-day-divider span { color: var(--muted); font-size: .7rem; font-weight: 750; text-transform: uppercase; letter-spacing: .06em; }
.conversation-unread-divider::before, .conversation-unread-divider::after { background: var(--accent); opacity: .6; }
.conversation-unread-divider span { padding: .1rem .5rem; border-radius: 999px; background: var(--accent); color: #06140b; font-size: .68rem; font-weight: 800; text-transform: uppercase; letter-spacing: .06em; }
.conversation-messages li { max-width: 85%; padding: .7rem .8rem; border-radius: .8rem; }
.conversation-messages li.is-self { justify-self: end; background: var(--accent-dark); }
.conversation-messages li.is-recipient { justify-self: start; background: var(--surface-raised); }
@@ -86,7 +135,7 @@
.conversation-image-reveal { position: absolute; bottom: .5rem; left: .5rem; min-height: 2rem !important; padding: .35rem .6rem !important; color: white !important; background: rgba(0, 0, 0, .76) !important; border-color: rgba(255, 255, 255, .45) !important; font-size: .75rem; font-weight: 800; }
.conversation-image-reveal:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.conversation-empty-detail { padding: 2rem; color: var(--muted); text-align: center; }
.conversation-composer { display: grid; gap: .65rem; padding: 1rem; border-top: 1px solid var(--border); }
.conversation-composer { flex: 0 0 auto; display: grid; gap: .65rem; padding: 1rem; overflow-y: auto; border-top: 1px solid var(--border); }
.conversation-section-heading, .conversation-actions { display: flex; align-items: center; justify-content: space-between; gap: .75rem; }
.conversation-section-heading h3 { margin: 0; }
.conversation-actions > span { color: var(--muted); font-size: .75rem; }
@@ -124,7 +173,7 @@ dialog.conversation-media-confirmation { width: min(34rem, calc(100% - 2rem)); }
@media (min-width: 52rem) {
.conversations-page { padding: 3rem 2rem 5rem; }
.start-conversation-form { grid-template-columns: minmax(12rem, .5fr) minmax(18rem, 1fr) auto; align-items: end; }
.conversation-workspace { grid-template-columns: minmax(17rem, .75fr) minmax(28rem, 1.5fr); }
.conversation-workspace { grid-template-columns: minmax(21rem, .85fr) minmax(28rem, 1.5fr); }
}
.conversation-automation-status {
display: flex;
@@ -18,3 +18,40 @@ export function formatShortRelativeTime(timestamp: number, now: number): string
export function formatExactTime(timestamp: number): string {
return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(timestamp);
}
/** Time of day only. Paired with a day divider so history is not full of dates. */
export function formatTimeOfDay(timestamp: number): string {
return new Intl.DateTimeFormat(undefined, { timeStyle: 'short' }).format(timestamp);
}
export function isSameDay(left: number, right: number): boolean {
const a = new Date(left);
const b = new Date(right);
return a.getFullYear() === b.getFullYear()
&& a.getMonth() === b.getMonth()
&& a.getDate() === b.getDate();
}
/** "Today" / "Yesterday" / an explicit date, for message-history day dividers. */
export function formatDayLabel(timestamp: number, now: number): string {
if (isSameDay(timestamp, now)) return 'Today';
if (isSameDay(timestamp, now - DAY_MS)) return 'Yesterday';
return new Intl.DateTimeFormat(undefined, { dateStyle: 'full' }).format(timestamp);
}
export const STALE_REPLY_THRESHOLD_MS = 12 * HOUR_MS;
export const CRITICAL_REPLY_THRESHOLD_MS = 48 * HOUR_MS;
export type ConversationAge = 'fresh' | 'stale' | 'critical';
/**
* How overdue an unanswered conversation is. Only meaningful for conversations
* waiting on us — "3d ago" on a conversation we already replied to is fine, but
* on one awaiting a reply it is the thing the operator most needs to notice.
*/
export function conversationAge(timestamp: number, now: number): ConversationAge {
const elapsed = Math.max(0, now - timestamp);
if (elapsed >= CRITICAL_REPLY_THRESHOLD_MS) return 'critical';
if (elapsed >= STALE_REPLY_THRESHOLD_MS) return 'stale';
return 'fresh';
}