Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(console): read only what is seen, retry failed reads, and keep who a mention names

raullopez-sandbox1808f29f5152
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/chat-people.test.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-people.test.ts
new file mode 100644
index 000000000..d5ab0b0bf
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-people.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it, vi } from 'vitest';
+import { knownPeople } from './chat-people';
+
+vi.mock('@renderer/lib/ipc', () => ({ events: { on: vi.fn() }, rpc: {} }));
+vi.mock('./stores/chats', () => ({ chatsStore: {} }));
+
+describe('knownPeople', () => {
+ it('keeps the viewer among the members and adds the rest of the roster to the known', () => {
+ const { members, known } = knownPeople(
+ [
+ { userId: 'me', name: 'Alice' },
+ { userId: 'u2', name: 'Bob' },
+ ],
+ [
+ { userId: 'u2', name: 'Bob', email: '[email protected]' },
+ { userId: 'u9', name: 'Carol', email: null },
+ ]
+ );
+ expect(members.map((p) => p.userId)).toEqual(['me', 'u2']);
+ expect(members[1]!.email).toBe('[email protected]');
+ expect(known.map((p) => p.userId)).toEqual(['me', 'u2', 'u9']);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/chat-people.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-people.ts
index 16ef22c70..edd370a40 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/chat-people.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-people.ts
@@ -20,23 +20,40 @@ export function workspaceRosterQuery(serverId: string, tenantId: string | null)
};
}
-/** The other people in a chat, with their email from the roster when it has one. */
+type ChatPerson = { userId: string; name: string; email: string | null };
+
+/**
+ * The people of a chat. `members` is everyone in it, the viewer included, with
+ * their email from the roster when it has one; `known` adds the rest of the
+ * roster, so a message keeps naming someone who has since left.
+ */
export function useChatPeople(
serverId: string,
chat: ChatSummary | undefined
-): { userId: string; name: string; email: string | null }[] {
+): { members: ChatPerson[]; known: ChatPerson[] } {
const members = useQuery({
queryKey: chat ? chatMembersQueryKey(serverId, chat) : ['chat-members', serverId, null],
queryFn: () => rpc.chats.members(serverId, (chat as ChatSummary).roomId),
enabled: chat !== undefined,
});
const roster = useQuery(workspaceRosterQuery(serverId, chatsStore.tenantId));
- const emails = new Map((roster.data ?? []).map((person) => [person.userId, person.email]));
- return (members.data ?? [])
- .filter((member) => member.userId !== chatsStore.userId)
- .map((member) => ({
- userId: member.userId,
- name: member.name,
- email: emails.get(member.userId) ?? null,
- }));
+ return knownPeople(members.data ?? [], roster.data ?? []);
+}
+
+/** The chat's members with their emails, then everyone else the roster knows. */
+export function knownPeople(
+ members: { userId: string; name: string }[],
+ roster: { userId: string; name: string; email: string | null }[]
+): { members: ChatPerson[]; known: ChatPerson[] } {
+ const emails = new Map(roster.map((person) => [person.userId, person.email]));
+ const inChat = members.map((member) => ({
+ userId: member.userId,
+ name: member.name,
+ email: emails.get(member.userId) ?? null,
+ }));
+ const ids = new Set(inChat.map((member) => member.userId));
+ return {
+ members: inChat,
+ known: [...inChat, ...roster.filter((person) => !ids.has(person.userId))],
+ };
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx
index 47b0fb5c9..fec33f407 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx
@@ -13,15 +13,17 @@ import { type ChatAgent, type ChatMessage, chatAgentLabel } from '@shared/core/c
import { snippetOf } from '../chat-threads';
import {
agentTargets,
+ composeMentions,
filterMentionAgents,
filterMentionPeople,
mentionAgentIds,
type MentionPerson,
mentionQuery,
mentionSegments,
- mentionTokens,
+ type MentionToken,
mentionUserIds,
personTargets,
+ shiftMentions,
tokenToRemove,
} from '../mentions';
import { isInterruptAck } from '../stop-rows';
@@ -54,7 +56,7 @@ type Suggestion =
| { kind: 'person'; id: string; person: MentionPerson & { email: string | null } };
/** Drafts by chat, so a draft outlives navigating away. */
-const drafts = new Map<string, string>();
+const drafts = new Map<string, { text: string; mentions: MentionToken[] }>();
/** Chats just created here, whose composer takes focus when it first shows. */
const focusOnOpen = new Set<string>();
@@ -176,10 +178,20 @@ export const ChatComposer = observer(function ChatComposer({
disabled: string | null;
}) {
const draftKey = `${serverId}\u0000${timeline.roomId}`;
- const [draft, setDraft] = useState(() => drafts.get(draftKey) ?? '');
+ const [draft, setDraft] = useState(() => drafts.get(draftKey)?.text ?? '');
+ /** The mentions picked from the list, each with who it names, kept with the draft. */
+ const [picked, setPicked] = useState<MentionToken[]>(() => drafts.get(draftKey)?.mentions ?? []);
useEffect(() => {
- drafts.set(draftKey, draft);
- }, [draftKey, draft]);
+ drafts.set(draftKey, { text: draft, mentions: picked });
+ }, [draftKey, draft, picked]);
+ /** A pick the next edit inserts, placed once that edit has moved the others. */
+ const pendingPick = useRef<MentionToken | null>(null);
+ const edit = (next: string) => {
+ const pick = pendingPick.current;
+ pendingPick.current = null;
+ setPicked((current) => [...shiftMentions(draft, next, current), ...(pick ? [pick] : [])]);
+ setDraft(next);
+ };
const [files, setFiles] = useState<{ id: string; file: File }[]>([]);
const [confirmReset, setConfirmReset] = useState(false);
const [contextOpen, setContextOpen] = useState(false);
@@ -190,14 +202,9 @@ export const ChatComposer = observer(function ChatComposer({
const [mentionIndex, setMentionIndex] = useState(0);
/** Where the `@` of a suggestion list Esc closed sits, so it stays closed for that `@`. */
const [dismissedAt, setDismissedAt] = useState<number | null>(null);
- /** People picked from the list; one sharing an agent's name is read as the person. */
- const [pickedPeople, setPickedPeople] = useState<ReadonlySet<string>>(new Set());
- const targets = [
- ...personTargets(people.filter((person) => pickedPeople.has(person.userId))),
- ...agentTargets(agents),
- ...personTargets(people.filter((person) => !pickedPeople.has(person.userId))),
- ];
- const tokens = mentionTokens(draft, targets);
+ // Text typed rather than picked reads as an agent first where a person shares its name.
+ const targets = [...agentTargets(agents), ...personTargets(people)];
+ const tokens = composeMentions(draft, picked, targets);
const mentionable = agents.length > 0 || people.length > 0;
const query = mentionable ? mentionQuery(draft, caret) : null;
const suggestions: Suggestion[] = query
@@ -251,18 +258,21 @@ export const ChatComposer = observer(function ChatComposer({
input.current?.focus();
};
- const pick = (picked: Suggestion) => {
+ const pick = (choice: Suggestion) => {
const textarea = input.current;
if (!textarea || !query) return;
- const name = picked.kind === 'agent' ? picked.agent.name : picked.person.name;
- if (picked.kind === 'person')
- setPickedPeople((current) => new Set(current).add(picked.person.userId));
+ const name = choice.kind === 'agent' ? choice.agent.name : choice.person.name;
+ pendingPick.current = {
+ kind: choice.kind,
+ id: choice.kind === 'agent' ? choice.agent.id : choice.person.userId,
+ start: query.start,
+ end: query.start + 1 + name.length,
+ };
textarea.focus();
textarea.setSelectionRange(query.start, caret);
// insertText keeps the native undo stack; a controlled-value write would wipe it.
if (!document.execCommand('insertText', false, `@${name} `)) {
- const next = `${draft.slice(0, query.start)}@${name} ${draft.slice(caret)}`;
- setDraft(next);
+ edit(`${draft.slice(0, query.start)}@${name} ${draft.slice(caret)}`);
setCaret(query.start + name.length + 2);
}
setMentionIndex(0);
@@ -310,17 +320,18 @@ export const ChatComposer = observer(function ChatComposer({
timeline.messages.filter((message) => message.sender.kind === 'human').length +
timeline.pending.length
);
+ const sent = composeMentions(body, shiftMentions(draft, body, picked), targets);
timeline.send({
body,
threadRootId: replyTo?.messageId ?? null,
- mentionAgentIds: mentionAgentIds(mentionTokens(body, targets)),
- mentionUserIds: mentionUserIds(mentionTokens(body, targets)),
+ mentionAgentIds: mentionAgentIds(sent),
+ mentionUserIds: mentionUserIds(sent),
files: files.map(({ file }) => chatFile(file)),
});
void chatTitler.sent(serverId, timeline.roomId, body);
setDraft('');
+ setPicked([]);
setFiles([]);
- setPickedPeople(new Set());
onClearReply();
};
@@ -496,7 +507,7 @@ export const ChatComposer = observer(function ChatComposer({
}
onKeyDown={onKeyDown}
onChange={(event) => {
- setDraft(event.target.value);
+ edit(event.target.value);
setCaret(event.target.selectionStart);
setMentionIndex(0);
if (!mentionQuery(event.target.value, event.target.selectionStart))
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx
index 30f2008db..a91a1b88f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx
@@ -5,6 +5,7 @@ import { Button } from '@renderer/lib/ui/button';
import { SERVER_TOO_OLD_FOR_ACTIVITY } from '@shared/core/chats/activity';
import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';
import { useChatPeople } from '../chat-people';
+import { readThroughSeq } from '../read-progress';
import { agentActivities } from '../stores/activities';
import type { AgentActivity } from '../stores/chat-activity-store';
import type { ChatTimeline } from '../stores/chat-timeline-store';
@@ -85,7 +86,7 @@ export const ChatPanel = observer(function ChatPanel({
if (!timeline.loaded && !lost && !timeline.notMember) void timeline.load();
}, [timeline, lost, timeline.notMember]);
const panel = useRef<HTMLDivElement>(null);
- useReadWhileShown(roomId, timeline, panel, lost || timeline.notMember);
+ const shown = useShown(panel, lost || timeline.notMember);
// Reasoning lives only on a local or SSH host and is read while a turn runs,
// and whenever the joined turns change.
@@ -162,7 +163,7 @@ export const ChatPanel = observer(function ChatPanel({
serverId={serverId}
timeline={timeline}
agents={chat?.agents ?? []}
- people={people}
+ people={people.known}
activities={activities}
onReply={setReplyTo}
/>
@@ -180,13 +181,15 @@ export const ChatPanel = observer(function ChatPanel({
/>
<MessageScrollerButton className="absolute bottom-3 left-1/2 -translate-x-1/2" />
<FollowOwnSends timeline={timeline} />
+ <ReadWhileFollowing roomId={roomId} timeline={timeline} shown={shown} />
</MessageScroller>
<ActivityUnavailable serverId={serverId} activities={activities} />
<ChatComposer
serverId={serverId}
timeline={timeline}
agents={chat?.agents ?? []}
- people={people}
+ // Everyone but the viewer can be mentioned from here.
+ people={people.members.filter((person) => person.userId !== chatsStore.userId)}
groupName={chat && chat.channelType !== 'direct' ? chat.name : null}
activity={activities[0] ?? null}
replyTo={replyTo}
@@ -201,19 +204,9 @@ export const ChatPanel = observer(function ChatPanel({
);
});
-/**
- * While the conversation is on screen in a focused window it is the chat being
- * read: its new messages do not count as unread, and it is marked read through
- * the last message shown. A hidden tab or a background window reads nothing.
- */
-function useReadWhileShown(
- roomId: string,
- timeline: ChatTimeline,
- panel: React.RefObject<HTMLDivElement | null>,
- hidden: boolean
-): void {
+/** Whether the conversation is on screen in a focused window; a hidden tab or a background window is not. */
+function useShown(panel: React.RefObject<HTMLDivElement | null>, hidden: boolean): boolean {
const [shown, setShown] = useState(false);
- const lastSeq = timeline.loaded ? (timeline.messages.at(-1)?.seq ?? null) : null;
useEffect(() => {
const update = () =>
setShown(
@@ -232,17 +225,43 @@ function useReadWhileShown(
window.removeEventListener('blur', update);
};
}, [panel, hidden]);
+ return shown;
+}
+
+/**
+ * While the conversation is on screen and followed at the bottom, it is the
+ * chat being read: its new messages do not count as unread, and it is marked
+ * read through the last one. Scrolled up, arrivals count until the reader
+ * comes back down.
+ */
+const ReadWhileFollowing = observer(function ReadWhileFollowing({
+ roomId,
+ timeline,
+ shown,
+}: {
+ roomId: string;
+ timeline: ChatTimeline;
+ shown: boolean;
+}) {
+ const { isAtBottom } = useMessageScroller();
+ const reading = shown && isAtBottom;
+ const seq = readThroughSeq({
+ shown,
+ atBottom: isAtBottom,
+ lastSeq: timeline.loaded ? (timeline.messages.at(-1)?.seq ?? null) : null,
+ });
useEffect(() => {
- if (!shown) return;
+ if (!reading) return;
chatsStore.setViewing(roomId);
return () => {
if (chatsStore.viewing === roomId) chatsStore.setViewing(null);
};
- }, [shown, roomId]);
+ }, [reading, roomId]);
useEffect(() => {
- if (shown && lastSeq !== null) chatsStore.read(roomId, lastSeq);
- }, [shown, roomId, lastSeq]);
-}
+ if (seq !== null) chatsStore.read(roomId, seq);
+ }, [roomId, seq]);
+ return null;
+});
/**
* Sending from here jumps to the end and resumes following, wherever the
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/mentions.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/mentions.ts
index 695f3fae6..bb6ef5798 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/mentions.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/mentions.ts
@@ -130,3 +130,57 @@ export function mentionSegments(
/** A mention's badge; a ring rather than padding, so it never moves the text it sits behind. */
export const MENTION_BADGE =
'rounded-sm bg-background-tertiary-1 ring-2 ring-background-tertiary-1';
+
+/**
+ * Picked mentions carried across an edit from `before` to `after`: those wholly
+ * before or after the changed run keep their place (shifted), and one the edit
+ * touches is dropped.
+ */
+export function shiftMentions(
+ before: string,
+ after: string,
+ mentions: MentionToken[]
+): MentionToken[] {
+ let start = 0;
+ while (start < before.length && start < after.length && before[start] === after[start]) start++;
+ let tail = 0;
+ while (
+ tail < before.length - start &&
+ tail < after.length - start &&
+ before[before.length - 1 - tail] === after[after.length - 1 - tail]
+ )
+ tail++;
+ const endBefore = before.length - tail;
+ const delta = after.length - before.length;
+ return mentions.flatMap((mention) => {
+ if (mention.end <= start) return [mention];
+ if (mention.start >= endBefore)
+ return [{ ...mention, start: mention.start + delta, end: mention.end + delta }];
+ return [];
+ });
+}
+
+/**
+ * The mentions in `text`: the picked ones, each still reading as `@` one of
+ * its target's names, and around them whatever the targets' names match on
+ * their own.
+ */
+export function composeMentions(
+ text: string,
+ picked: MentionToken[],
+ targets: MentionTarget[]
+): MentionToken[] {
+ const kept = picked.filter((mention) => {
+ const target = targets.find((each) => each.kind === mention.kind && each.id === mention.id);
+ const said = text.slice(mention.start + 1, mention.end).toLowerCase();
+ return (
+ text[mention.start] === '@' &&
+ target !== undefined &&
+ target.names.some((name) => name.toLowerCase() === said)
+ );
+ });
+ const found = mentionTokens(text, targets).filter(
+ (token) => !kept.some((mention) => token.start < mention.end && mention.start < token.end)
+ );
+ return [...kept, ...found].sort((a, b) => a.start - b.start);
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/read-progress.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/read-progress.ts
new file mode 100644
index 000000000..d4f7f011a
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/read-progress.ts
@@ -0,0 +1,12 @@
+/**
+ * How far a chat on screen has been read: through the last message, but only
+ * while the reader is at the bottom where it shows; scrolled up, new messages
+ * wait as unread.
+ */
+export function readThroughSeq(state: {
+ shown: boolean;
+ atBottom: boolean;
+ lastSeq: number | null;
+}): number | null {
+ return state.shown && state.atBottom ? state.lastSeq : null;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts
index 89638632c..0506e91e6 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts
@@ -68,8 +68,10 @@ export class ChatsStore {
listError: string | null = null;
/** The room whose chat is on screen and being read: its messages do not count as unread. */
viewing: string | null = null;
- /** The furthest message marked read here, by room; a read never moves back. */
+ /** The furthest message the server has taken as read, by room; a read never moves back. */
private readonly readThrough = new Map<string, number>();
+ /** A read position on its way to the server, by room; dropped if it fails, so the next read retries. */
+ private readonly readPending = new Map<string, number>();
private readonly readTimers = new Map<string, ReturnType<typeof setTimeout>>();
readonly timelines: ChatTimelines;
@@ -78,10 +80,11 @@ export class ChatsStore {
events: ChatsEvents
) {
this.timelines = new ChatTimelines(api.timeline);
- makeAutoObservable<ChatsStore, 'api' | 'readThrough' | 'readTimers'>(this, {
+ makeAutoObservable<ChatsStore, 'api' | 'readThrough' | 'readPending' | 'readTimers'>(this, {
api: false,
timelines: false,
readThrough: false,
+ readPending: false,
readTimers: false,
});
events.onSummary(({ serverId, chat }) => {
@@ -285,14 +288,23 @@ export class ChatsStore {
if (!serverId) return;
const chat = this.chats.get(roomId);
if (chat && chat.unreadCount !== 0) this.chats.set(roomId, { ...chat, unreadCount: 0 });
- if ((this.readThrough.get(roomId) ?? 0) >= seq) return;
- this.readThrough.set(roomId, seq);
+ const furthest = Math.max(this.readThrough.get(roomId) ?? 0, this.readPending.get(roomId) ?? 0);
+ if (furthest >= seq) return;
+ this.readPending.set(roomId, seq);
clearTimeout(this.readTimers.get(roomId));
this.readTimers.set(
roomId,
setTimeout(() => {
this.readTimers.delete(roomId);
- void this.api.markRead(serverId, roomId, seq);
+ this.api.markRead(serverId, roomId, seq).then(
+ () => {
+ this.readThrough.set(roomId, Math.max(this.readThrough.get(roomId) ?? 0, seq));
+ if (this.readPending.get(roomId) === seq) this.readPending.delete(roomId);
+ },
+ () => {
+ if (this.readPending.get(roomId) === seq) this.readPending.delete(roomId);
+ }
+ );
}, READ_DEBOUNCE_MS)
);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts
index f9d365d9f..229050529 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts
@@ -35,13 +35,14 @@ export const chatsStore = new ChatsStore(
rpc.chats.removeMember({ serverId, roomId, userId }),
markRead: (serverId, roomId, seq) =>
rpc.chats.markRead({ serverId, roomId, seq }).catch((error: unknown) => {
- // The count stays at 0 here; the server's comes back with the next summary.
+ // The store tries again on the next read; the server's count returns with the next summary.
log.warn('Could not save how far a chat has been read', {
serverId,
roomId,
seq,
error: String(error),
});
+ throw error;
}),
},
chatsEventsFrom(events)
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-mentions.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-mentions.test.ts
index 40528abaa..102df2856 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-mentions.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-mentions.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
import {
agentTargets,
+ composeMentions,
+ shiftMentions,
filterMentionAgents,
filterMentionPeople,
mentionUserIds,
@@ -127,3 +129,41 @@ describe('people mentions', () => {
expect(filterMentionPeople(people, '').map((p) => p.userId)).toEqual(['u1', 'u2']);
});
});
+
+describe('picked mentions', () => {
+ const sharer = [{ id: 'a9', name: 'Bob Member', alias: null }];
+ const bob = [{ userId: 'u1', name: 'Bob Member' }];
+ const targets = [...agentTargets(sharer), ...personTargets(bob)];
+
+ it('keeps who a picked mention names across a saved and restored draft', () => {
+ const text = 'hi @Bob Member';
+ const saved = { text, mentions: [{ kind: 'person' as const, id: 'u1', start: 3, end: 14 }] };
+ const restored = composeMentions(saved.text, saved.mentions, targets);
+ expect(restored).toEqual([{ kind: 'person', id: 'u1', start: 3, end: 14 }]);
+ // Unpicked, the same text reads as the agent.
+ expect(composeMentions(text, [], targets)[0]!.kind).toBe('agent');
+ });
+
+ it('addresses the agent and the person of one name, one each', () => {
+ const text = '@Bob Member and @Bob Member';
+ const tokens = composeMentions(
+ text,
+ [
+ { kind: 'agent', id: 'a9', start: 0, end: 11 },
+ { kind: 'person', id: 'u1', start: 16, end: 27 },
+ ],
+ targets
+ );
+ expect(mentionAgentIds(tokens)).toEqual(['a9']);
+ expect(mentionUserIds(tokens)).toEqual(['u1']);
+ });
+
+ it('moves picked mentions with an edit before them and drops one an edit lands in', () => {
+ const mention = { kind: 'person' as const, id: 'u1', start: 3, end: 14 };
+ expect(shiftMentions('hi @Bob Member', 'oh hi @Bob Member', [mention])).toEqual([
+ { ...mention, start: 6, end: 17 },
+ ]);
+ expect(shiftMentions('hi @Bob Member', 'hi @Bob XMember', [mention])).toEqual([]);
+ expect(composeMentions('hi @Bob', [mention], targets)).toEqual([]);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-view.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-view.test.ts
index bcd145a0a..575cf86fa 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-view.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-view.test.ts
@@ -128,3 +128,25 @@ describe('ChatTimelineView mentions', () => {
expect(render([], ['a3'])).toContain('data-mention="agent"');
});
});
+
+describe('ChatTimelineView mentions of people no longer in the chat', () => {
+ it('still badges a person the message names, from the wider list of known people', () => {
+ const timeline = new ChatTimeline('room-1', api);
+ timeline.apply({
+ ...message(1, 'me', 'Alice'),
+ body: 'thanks @Carol Gone',
+ namedUserIds: ['u9'],
+ });
+ const html = renderToStaticMarkup(
+ createElement(ChatTimelineView, {
+ serverId: 's',
+ timeline,
+ agents: [],
+ people: [{ userId: 'u9', name: 'Carol Gone' }],
+ activities: [],
+ onReply: () => {},
+ })
+ );
+ expect(html).toContain('data-mention="person"');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts
index b43c499c6..3d5cb8f06 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
+import { readThroughSeq } from '@renderer/features/chats/read-progress';
import type { TimelineApi } from '@renderer/features/chats/stores/chat-timeline-store';
import {
ChatsStore,
@@ -390,3 +391,48 @@ describe('ChatsStore leave', () => {
expect(store.removed.has('g')).toBe(false);
});
});
+
+describe('ChatsStore read progress', () => {
+ const from = (roomId: string, seq: number) => ({
+ ...message(roomId, seq),
+ sender: { ...message(roomId, seq).sender, userId: 'bob' },
+ });
+
+ it('counts arrivals while scrolled up, and reads them once back at the bottom', async () => {
+ vi.useFakeTimers();
+ try {
+ const { store, emit, markRead } = await viewer();
+ store.setViewing(null);
+ emit(from('g', 2));
+ expect(store.unread('g')).toBe(1);
+ const seq = readThroughSeq({ shown: true, atBottom: false, lastSeq: 2 });
+ expect(seq).toBeNull();
+ store.setViewing('g');
+ store.read('g', readThroughSeq({ shown: true, atBottom: true, lastSeq: 2 })!);
+ expect(store.unread('g')).toBe(0);
+ vi.advanceTimersByTime(READ_DEBOUNCE_MS);
+ expect(markRead).toHaveBeenCalledWith('s1', 'g', 2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('tries a failed read again the next time the same messages are shown', async () => {
+ vi.useFakeTimers();
+ try {
+ const { store, markRead } = await viewer();
+ markRead.mockRejectedValueOnce(new Error('offline'));
+ store.read('g', 5);
+ await vi.advanceTimersByTimeAsync(READ_DEBOUNCE_MS);
+ expect(markRead).toHaveBeenCalledTimes(1);
+ store.read('g', 5);
+ await vi.advanceTimersByTimeAsync(READ_DEBOUNCE_MS);
+ expect(markRead).toHaveBeenCalledTimes(2);
+ store.read('g', 5);
+ await vi.advanceTimersByTimeAsync(READ_DEBOUNCE_MS);
+ expect(markRead).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});