Skip to content

Commit 1fbe383

Browse files
committed
fix(chats): drop stale search hits and cross-chat responses (TM-214)
Search shows hits only from chats still readable in the current list and ignores superseded requests. Sends, edits and deletes stay in the chat they started in. Thread replies no longer bump unread, matching the server count.
1 parent e595957 commit 1fbe383

5 files changed

Lines changed: 211 additions & 23 deletions

File tree

‎src/components/chats/ChatSearch.vue‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,14 @@
1313
<p v-if="searching" class="px-3 py-2 text-sm text-ink-subtle">
1414
{{ $t('common.states.loading') }}
1515
</p>
16-
<p v-else-if="!hits.length" class="px-3 py-2 text-sm text-ink-subtle">
16+
<p
17+
v-else-if="!visibleHits.length"
18+
class="px-3 py-2 text-sm text-ink-subtle"
19+
>
1720
{{ $t('chats.search.empty') }}
1821
</p>
1922
<button
20-
v-for="hit in hits"
23+
v-for="hit in visibleHits"
2124
:key="hit.message_id"
2225
type="button"
2326
class="block w-full px-3 py-2 text-left hover:bg-surface-hover"
@@ -36,7 +39,8 @@
3639
import { searchChats } from '@/actions/tmgr/chats';
3740
import type { ChatMessageHit } from '@/actions/tmgr/chats';
3841
import { Input } from '@/components/ui/input';
39-
import { defineComponent, onBeforeUnmount, ref } from 'vue';
42+
import { readableHits, useChats } from '@/composable/useChats';
43+
import { computed, defineComponent, onBeforeUnmount, ref, watch } from 'vue';
4044
4145
export default defineComponent({
4246
name: 'ChatSearch',
@@ -49,21 +53,35 @@
4953
const query = ref('');
5054
const hits = ref<ChatMessageHit[]>([]);
5155
const searching = ref(false);
56+
const { chats } = useChats();
57+
const visibleHits = computed(() => readableHits(hits.value, chats.value));
5258
let timer: ReturnType<typeof setTimeout> | null = null;
59+
let request = 0;
5360
5461
const run = async () => {
5562
const q = query.value.trim();
5663
if (!q) return;
64+
const current = ++request;
5765
try {
5866
const found = await searchChats(props.workspaceId, q);
59-
if (q === query.value.trim()) hits.value = found;
67+
if (current === request) hits.value = found;
6068
} catch {
61-
hits.value = [];
69+
if (current === request) hits.value = [];
6270
} finally {
63-
searching.value = false;
71+
if (current === request) searching.value = false;
6472
}
6573
};
6674
75+
watch(
76+
() => props.workspaceId,
77+
() => {
78+
request++;
79+
query.value = '';
80+
hits.value = [];
81+
searching.value = false;
82+
},
83+
);
84+
6785
const schedule = () => {
6886
if (timer) clearTimeout(timer);
6987
searching.value = true;
@@ -80,7 +98,7 @@
8098
if (timer) clearTimeout(timer);
8199
});
82100
83-
return { query, hits, searching, schedule, open };
101+
return { query, visibleHits, searching, schedule, open };
84102
},
85103
});
86104
</script>

‎src/components/chats/ThreadPanel.vue‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,11 @@
7474
const { send } = useChats();
7575
const submitReply = (
7676
payload: Pick<SendMessagePayload, 'body' | 'mentions' | 'files'>,
77-
) => send({ ...payload, parent_message_id: props.root.id });
77+
) =>
78+
send(props.root.chat_id, {
79+
...payload,
80+
parent_message_id: props.root.id,
81+
});
7882
return { submitReply };
7983
},
8084
});
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
jest.mock('@/actions/tmgr/chats', () => ({
2+
getChat: jest.fn(),
3+
getMessages: jest.fn(),
4+
getMessage: jest.fn(),
5+
getReplies: jest.fn(),
6+
sendMessage: jest.fn(),
7+
editMessage: jest.fn(),
8+
deleteMessage: jest.fn(),
9+
listChats: jest.fn(),
10+
markRead: jest.fn(),
11+
}));
12+
jest.mock('@/composable/usePusher', () => ({ usePusher: jest.fn() }));
13+
14+
import type { Chat, ChatMessage, ChatMessageHit } from '@/actions/tmgr/chats';
15+
import * as api from '@/actions/tmgr/chats';
16+
import { applyChatEvent, readableHits, useChats } from '@/composable/useChats';
17+
18+
const mocked = api as jest.Mocked<typeof api>;
19+
20+
const msg = (id: number, chatId: number, over: Partial<ChatMessage> = {}) =>
21+
({
22+
id,
23+
chat_id: chatId,
24+
author: { kind: 'user', id: 2, name: 'A' },
25+
body: `m${id}`,
26+
mentions: [],
27+
parent_message_id: null,
28+
reply_count: 0,
29+
last_reply_at: null,
30+
reactions: [],
31+
files: [],
32+
edited_at: null,
33+
deleted: false,
34+
created_at: '2026-01-01T00:00:00Z',
35+
...over,
36+
}) as ChatMessage;
37+
38+
const chat = (id: number, over: Partial<Chat> = {}) =>
39+
({
40+
id,
41+
workspace_id: 1,
42+
kind: 'channel',
43+
visibility: 'members',
44+
title: `c${id}`,
45+
topic: null,
46+
joined: true,
47+
can_read: true,
48+
can_write: true,
49+
can_moderate: false,
50+
can_delete: false,
51+
archived_at: null,
52+
last_message_at: null,
53+
last_message: null,
54+
unread: 0,
55+
member_count: 2,
56+
members: null,
57+
created_at: null,
58+
notify_level: null,
59+
muted_until: null,
60+
...over,
61+
}) as Chat;
62+
63+
const hit = (messageId: number, chatId: number) =>
64+
({
65+
message_id: messageId,
66+
chat_id: chatId,
67+
chat_title: `c${chatId}`,
68+
chat_kind: 'channel',
69+
parent_message_id: null,
70+
author: { kind: 'user', id: 2, name: 'A' },
71+
snippet: 'secret plan',
72+
created_at: '2026-01-01T00:00:00Z',
73+
}) as ChatMessageHit;
74+
75+
const deferred = <T>() => {
76+
let resolve!: (v: T) => void;
77+
const promise = new Promise<T>((r) => (resolve = r));
78+
return { promise, resolve };
79+
};
80+
81+
describe('readableHits', () => {
82+
it('keeps hits only from chats the user can still read', () => {
83+
const hits = [hit(1, 1), hit(2, 2), hit(3, 3)];
84+
const chats = [chat(1), chat(2, { can_read: false, joined: false })];
85+
expect(readableHits(hits, chats).map((h) => h.message_id)).toEqual([1]);
86+
});
87+
88+
it('drops a hit once its chat leaves the list', () => {
89+
const hits = [hit(1, 1)];
90+
expect(readableHits(hits, [chat(1)])).toHaveLength(1);
91+
expect(readableHits(hits, [])).toHaveLength(0);
92+
});
93+
});
94+
95+
describe('chat switches', () => {
96+
const chats = useChats();
97+
98+
beforeEach(() => {
99+
jest.resetAllMocks();
100+
chats.chats.value = [chat(1), chat(2)];
101+
mocked.getMessages.mockImplementation(async (id: number) => [
102+
msg(id * 100, id),
103+
]);
104+
});
105+
106+
it('sends to the chat the composer belongs to and keeps it out of the open one', async () => {
107+
await chats.openChat(1);
108+
const pending = deferred<ChatMessage>();
109+
mocked.sendMessage.mockReturnValue(pending.promise);
110+
const sending = chats.send(1, { body: 'draft for A' });
111+
await chats.openChat(2);
112+
pending.resolve(msg(150, 1));
113+
await sending;
114+
expect(mocked.sendMessage).toHaveBeenCalledWith(1, { body: 'draft for A' });
115+
expect(chats.messages.value.map((m) => m.id)).toEqual([200]);
116+
});
117+
118+
it('ignores an edit response from a chat that is no longer open', async () => {
119+
await chats.openChat(1);
120+
const pending = deferred<ChatMessage>();
121+
mocked.editMessage.mockReturnValue(pending.promise);
122+
const saving = chats.saveEdit(msg(100, 1), 'edited', []);
123+
await chats.openChat(2);
124+
pending.resolve(msg(100, 1, { body: 'edited' }));
125+
await saving;
126+
expect(chats.messages.value.map((m) => m.chat_id)).toEqual([2]);
127+
});
128+
129+
it('ignores a delete response from a chat that is no longer open', async () => {
130+
await chats.openChat(1);
131+
const pending = deferred<void>();
132+
mocked.deleteMessage.mockReturnValue(pending.promise);
133+
const removing = chats.removeMessage(msg(100, 1));
134+
await chats.openChat(2);
135+
chats.messages.value = [msg(100, 2)];
136+
pending.resolve();
137+
await removing;
138+
expect(chats.messages.value[0].deleted).toBe(false);
139+
});
140+
});
141+
142+
describe('unread from thread replies', () => {
143+
it('does not count a reply, matching the server count of top-level messages', () => {
144+
const result = applyChatEvent(
145+
[
146+
chat(1, {
147+
last_message: { id: 5, author_id: 2, preview: 'x', deleted: false },
148+
}),
149+
],
150+
'chat.message.created',
151+
{ chat_id: 1, message_id: 9, parent_message_id: 5, author_id: 3 },
152+
{ openChatId: null, selfId: 2 },
153+
);
154+
expect(result.chats[0].unread).toBe(0);
155+
expect(result.chats[0].last_message?.id).toBe(5);
156+
});
157+
});

‎src/composable/useChats.ts‎

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
type Chat,
1212
type ChatMention,
1313
type ChatMessage,
14+
type ChatMessageHit,
1415
type SendMessagePayload,
1516
} from '@/actions/tmgr/chats';
1617
import { usePusher } from '@/composable/usePusher';
@@ -74,6 +75,14 @@ export const chatTitle = (chat: Chat, selfId: number | null): string => {
7475
return names.join(', ') || chat.title || '';
7576
};
7677

78+
export const readableHits = (
79+
hits: ChatMessageHit[],
80+
chats: Chat[],
81+
): ChatMessageHit[] => {
82+
const readable = new Set(chats.filter((c) => c.can_read).map((c) => c.id));
83+
return hits.filter((h) => readable.has(h.chat_id));
84+
};
85+
7786
export const isMuted = (chat: Chat, now = Date.now()): boolean =>
7887
chat.notify_level === 'none' ||
7988
(!!chat.muted_until && Date.parse(chat.muted_until) > now);
@@ -111,21 +120,20 @@ export const applyChatEvent = (
111120
payload.message_id <= current.last_message.id
112121
)
113122
return { chats, reload: false };
123+
if (payload.parent_message_id) return { chats, reload: false };
114124
const foreign = payload.author_id !== ctx.selfId;
115125
const unreadCounts = foreign && payload.chat_id !== ctx.openChatId;
116126
return {
117127
chats: patch((c) => ({
118128
...c,
119129
unread: unreadCounts ? (c.unread ?? 0) + 1 : c.unread,
120130
last_message_at: new Date().toISOString(),
121-
last_message: payload.parent_message_id
122-
? c.last_message
123-
: {
124-
id: payload.message_id ?? 0,
125-
author_id: payload.author_id ?? null,
126-
preview: payload.preview ?? null,
127-
deleted: false,
128-
},
131+
last_message: {
132+
id: payload.message_id ?? 0,
133+
author_id: payload.author_id ?? null,
134+
preview: payload.preview ?? null,
135+
deleted: false,
136+
},
129137
})),
130138
reload: false,
131139
};
@@ -278,9 +286,7 @@ const closeThread = () => {
278286
replies.value = [];
279287
};
280288

281-
const send = async (payload: SendMessagePayload) => {
282-
const chatId = openChatId.value;
283-
if (chatId === null) return;
289+
const send = async (chatId: number, payload: SendMessagePayload) => {
284290
const message = await sendMessage(chatId, payload);
285291
if (openChatId.value !== chatId) return;
286292
if (payload.parent_message_id) {
@@ -302,6 +308,7 @@ const applyMessage = (message: ChatMessage) => {
302308

303309
const removeMessage = async (message: ChatMessage) => {
304310
await deleteMessage(message.chat_id, message.id);
311+
if (openChatId.value !== message.chat_id) return;
305312
if (message.parent_message_id === null) {
306313
messages.value = markMessageDeleted(messages.value, message.id);
307314
if (threadRoot.value?.id === message.id) closeThread();
@@ -316,9 +323,11 @@ const saveEdit = async (
316323
body: string,
317324
mentions: ChatMention[],
318325
) => {
319-
applyMessage(
320-
await editMessage(message.chat_id, message.id, { body, mentions }),
321-
);
326+
const fresh = await editMessage(message.chat_id, message.id, {
327+
body,
328+
mentions,
329+
});
330+
if (openChatId.value === message.chat_id) applyMessage(fresh);
322331
};
323332

324333
const flushMarkRead = async () => {

‎src/pages/Chats/ChatView.vue‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@
259259
260260
const submit = (
261261
payload: Pick<SendMessagePayload, 'body' | 'mentions' | 'files'>,
262-
) => send(payload);
262+
) => send(chatId.value, payload);
263263
264264
const join = async () => upsertChat(await joinChat(chatId.value));
265265

0 commit comments

Comments
 (0)