fix: Preserve Legacy Unread Reminder Placement

This commit is contained in:
Lia 2026-10-03 15:36:11 +00:00 • committed by Danny Avila
parent e19d2dbea1
commit d621cd8b69
12 changed files with 162 additions and 13 deletions

View file

@ -207,6 +207,7 @@ describe('groupConversationsByStatus finished chats', () => {
({
...convo(conversationId, daysAgo),
lastResponseAt: new Date(Date.now() - daysAgo * 86_400_000).toISOString(),
isMarkedUnread: false,
...read,
}) as TConversation;
@ -259,6 +260,30 @@ describe('groupConversationsByStatus finished chats', () => {
expect(partitionGroups(dated, new Set(), newestFirst)).toBe(dated);
});
it.each([undefined, false])(
'keeps unknown legacy intent in date groups (synthetic flag: %s)',
(synthetic) => {
const legacy = replied('legacy', 1, {
isMarkedUnread: undefined,
lastResponseIsManual: synthetic,
lastResponseMessageId: 'existing-reply',
lastSeenAt: undefined,
});
const restored = JSON.parse(JSON.stringify(legacy)) as TConversation;
const dated = groupConversations([restored], newestFirst);
expect(partitionGroups(dated, new Set(), newestFirst)).toBe(dated);
},
);
it('shows a new confirmed reply after an unknown legacy reminder', () => {
const legacy = replied('legacy', 1, { isMarkedUnread: undefined });
const confirmed = replied('confirmed', 0);
const dated = groupConversations([confirmed, legacy], newestFirst);
const groups = partitionGroups(dated, new Set(), newestFirst);
expect(groups[0]).toEqual([FINISHED_CHATS_GROUP, [confirmed]]);
expect(groups.slice(1)).toEqual(groupConversations([legacy], newestFirst));
});
it.each([
{ field: 'updatedAt' as const, direction: 'asc' as const },
{ field: 'title' as const, direction: 'asc' as const },

View file

@ -19,11 +19,10 @@ function showsStatusGroups(options: ConversationGroupOptions): boolean {
return !options.includePinned && options.field === 'updatedAt' && options.direction === 'desc';
}
/** A reply that landed while the user was elsewhere. "Mark as unread" sets the same
* stamp as a reminder, not as a finished run, so that chat keeps its date. */
/** Missing intent is legacy/unknown, not evidence of a newly finished reply. */
function isFinishedUnseen(conversation: TConversation): boolean {
return (
conversation.isMarkedUnread !== true &&
conversation.isMarkedUnread === false &&
conversation.lastResponseIsManual !== true &&
isConversationUnseen(conversation)
);

View file

@ -98,12 +98,25 @@ describe('useMarkConversationUnreadMutation', () => {
lastResponseMessageId: 'new-reply',
});
});
expect(cached()?.isMarkedUnread).toBeUndefined();
expect(cached()?.isMarkedUnread).toBe(false);
expect(groupConversationsByStatus([['Today', [cached()!]]], new Set(), options)[0][0]).toBe(
FINISHED_CHATS_GROUP,
);
});
it("keeps an older backend's successful unread response in the date group", async () => {
mockMarkUnread.mockResolvedValue({ modified: true, lastResponseAt: RESPONDED_AT });
const { result, cached } = setup(RESPONDED_AT, SEEN_AT);
await act(async () => {
await result.current.mutateAsync({ conversationId: CONVO_ID });
});
expect(cached()?.isMarkedUnread).toBe(true);
const dates = [['Today', [cached()!]]] as [string, NonNullable<ReturnType<typeof cached>>[]][];
expect(
groupConversationsByStatus(dates, new Set(), { field: 'updatedAt', direction: 'desc' }),
).toBe(dates);
});
it('restores manual unread intent when the write fails', async () => {
mockMarkUnread.mockRejectedValue(new Error('Unavailable'));
const { result, cached } = setup(RESPONDED_AT, SEEN_AT);

View file

@ -1201,6 +1201,43 @@ describe('Conversation Utilities', () => {
expect(data!.pages[0].conversations[0].lastResponseMessageId).toBe('reply-a');
});
it('does not invent reply eligibility for an unclassified backend snapshot', () => {
updateConvoInAllQueries(queryClient, 'a', (c) => ({
...c,
lastResponseAt: '2026-08-16T10:00:00.000Z',
isMarkedUnread: true,
}));
updateConvoInAllQueries(
queryClient,
'a',
() =>
({
conversationId: 'a',
lastResponseAt: '2026-08-16T11:00:00.000Z',
}) as TConversation,
);
expect(findConvoInAllQueries(queryClient, 'a')?.isMarkedUnread).toBeUndefined();
});
it('marks only an advancing live reply as confirmed, preserving reminders on duplicate delivery', () => {
const original = '2026-08-16T10:00:00.000Z';
updateConvoInAllQueries(queryClient, 'a', (c) => ({
...c,
lastResponseAt: original,
isMarkedUnread: true,
}));
applyServerReplyStamp(queryClient, 'a', {
lastResponseAt: original,
lastResponseMessageId: 'existing',
});
expect(findConvoInAllQueries(queryClient, 'a')?.isMarkedUnread).toBe(true);
applyServerReplyStamp(queryClient, 'a', {
lastResponseAt: '2026-08-16T11:00:00.000Z',
lastResponseMessageId: 'new',
});
expect(findConvoInAllQueries(queryClient, 'a')?.isMarkedUnread).toBe(false);
});
it('updateConvoInAllQueries lets an explicit lastSeenAt win over the cached one', () => {
updateConvoInAllQueries(queryClient, 'a', (c) => ({
...c,

View file

@ -1240,7 +1240,7 @@ export function applyServerReplyStamp(
lastResponseAt,
lastResponseMessageId: lastResponseMessageId ?? convo.lastResponseMessageId,
lastResponseIsManual: undefined,
isMarkedUnread: advances ? undefined : convo.isMarkedUnread,
isMarkedUnread: advances ? false : convo.isMarkedUnread,
lastSeenAt: advances ? undefined : convo.lastSeenAt,
updatedAt: updatedAt ?? convo.updatedAt,
}),

View file

@ -122,7 +122,11 @@ test.describe('bookmark counts', () => {
await db.collection('conversations').updateOne(
{ conversationId: unreadId },
{
$set: { lastResponseAt: previous, lastSeenAt: new Date(previous.getTime() - 1000) },
$set: {
lastResponseAt: previous,
lastSeenAt: new Date(previous.getTime() - 1000),
isMarkedUnread: false,
},
},
);
});

View file

@ -235,6 +235,46 @@ test.describe('unseen replies', () => {
}
});
test('a pre-upgrade manual reminder keeps its date group after reload @scenario:legacy-manual-unread-keeps-date', async ({
page,
}) => {
const id = conversationId();
const title = `Legacy reminder ${id.slice(0, 8)}`;
try {
await seedConversation(id, title, { lastResponseAt: new Date(Date.now() - 2000) });
await seedReplyMessage(id, title);
await page.goto(NEW_CHAT_PATH);
await openSidebar(page);
const row = page.getByTestId('convo-item').filter({ hasText: title });
for (let pass = 0; pass < 2; pass++) {
if (pass > 0) {
await page.reload();
await openSidebar(page);
}
await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toBeVisible();
await expect
.poll(async () =>
row.evaluate((node) => {
let previous = node.closest('[role="row"]')?.previousElementSibling;
while (previous) {
const heading = previous.querySelector('h2');
if (heading) return heading.textContent;
previous = previous.previousElementSibling;
}
return null;
}),
)
.toBe('Today');
}
const stored = await readConversation(id);
expect(stored?.isMarkedUnread).toBeUndefined();
expect(stored?.lastResponseIsManual).toBeUndefined();
expect(stored?.lastSeenAt).toBeUndefined();
} finally {
await cleanup(id);
}
});
test('marking a read conversation unread restores its dot and title count @scenario:mark-as-unread-restores-dot', async ({
page,
}) => {

View file

@ -1255,7 +1255,7 @@ export const tConversationSchema = z.object({
lastResponseMessageId: z.string().optional(),
/** True only while `lastResponseAt` is the synthetic marker from "mark unread". */
lastResponseIsManual: z.boolean().optional(),
/** Manual reminder, cleared by reading or a new persisted reply. */
/** True: manual reminder; false: real reply; absent: legacy/unknown intent. */
isMarkedUnread: z.boolean().optional(),
/** Set when the user has the newest message on screen; compared against `lastResponseAt`. */
lastSeenAt: z.string().optional(),

View file

@ -513,6 +513,7 @@ export type TMarkConversationUnreadResponse = {
lastResponseMessageId?: string;
/** True only when the settled stamp is the synthetic mark-unread marker. */
lastResponseIsManual?: boolean;
/** True: manual reminder; false: real reply; absent: legacy/unknown intent. */
isMarkedUnread?: boolean;
};

View file

@ -3319,10 +3319,36 @@ describe('Conversation Operations', () => {
const replied = await Conversation.findOne({
conversationId: mockConversationData.conversationId,
}).lean<IConversation>();
expect(replied?.isMarkedUnread).toBeUndefined();
expect(replied?.isMarkedUnread).toBe(false);
expect(replied?.lastResponseMessageId).toBe('new-reply');
});
it('leaves legacy intent unknown through listing and metadata saves, until a real reply', async () => {
await Conversation.create({
conversationId: mockConversationData.conversationId,
user: 'user123',
endpoint: EModelEndpoint.openAI,
lastResponseAt: new Date('2026-08-16T10:00:00.000Z'),
lastResponseMessageId: 'legacy-reply',
});
await saveConvo(mockCtx, {
conversationId: mockConversationData.conversationId,
title: 'Reminder',
});
const { conversations } = await getConvosByCursor('user123');
expect(conversations[0].isMarkedUnread).toBeUndefined();
expect(conversations[0].lastResponseMessageId).toBe('legacy-reply');
expect(conversations[0].lastSeenAt).toBeUndefined();
await methods.stampConvoLastResponse(
'user123',
mockConversationData.conversationId,
'confirmed-reply',
);
const reloaded = await getConvo('user123', mockConversationData.conversationId);
expect(reloaded?.isMarkedUnread).toBe(false);
expect(reloaded?.lastResponseMessageId).toBe('confirmed-reply');
});
it('is cleared only by an acknowledgement of the current reply', async () => {
const responseAt = new Date('2026-08-16T10:00:00.000Z');
await Conversation.create({

View file

@ -653,8 +653,12 @@ export function createConversationMethods(
const stamped = await Conversation.findOneAndUpdate(
casFilter,
{
$set: { lastResponseAt: stamp, lastResponseMessageId: responseMessageId },
$unset: { lastSeenAt: '', lastResponseIsManual: '', isMarkedUnread: '' },
$set: {
lastResponseAt: stamp,
lastResponseMessageId: responseMessageId,
isMarkedUnread: false,
},
$unset: { lastSeenAt: '', lastResponseIsManual: '' },
$max: { updatedAt: stamp },
},
{ new: true, projection, timestamps: false },
@ -2569,9 +2573,9 @@ export function createConversationMethods(
* DocumentDB targets rule out. */
if (setFields.lastResponseAt instanceof Date) {
const { lastResponseAt, ...withoutReplyStamp } = setFields;
operation.$set = withoutReplyStamp;
operation.$set = { ...withoutReplyStamp, isMarkedUnread: false };
operation.$max = { lastResponseAt };
operation.$unset = { lastResponseIsManual: '', isMarkedUnread: '' };
operation.$unset = { lastResponseIsManual: '' };
}
if (Object.keys(unsetFields).length > 0) {
operation.$unset = {

View file

@ -346,7 +346,7 @@ export interface IConversation extends Document {
lastResponseMessageId?: string;
/** True only while `lastResponseAt` is the synthetic marker from "mark unread". */
lastResponseIsManual?: boolean;
/** Manual reminder, cleared by reading or a new persisted reply. */
/** True: manual reminder; false: real reply; absent: legacy/unknown intent. */
isMarkedUnread?: boolean;
/** Set when the user has the newest message on screen; compared against `lastResponseAt`. */
lastSeenAt?: Date;