Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bots): keep unseen Thread replies unread and old-page badges current

zqchrisa29c0c3fa9ed
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
index 96df0d3a43..f15b82d5e5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -2432,9 +2432,9 @@ describe('Chat Server result delivery and refresh', () => {
const read = await service.getGroup(roomId);
if (!read.ok) throw new Error('Expected group');
// Only Alice's reply after seq 2 counts; the deleted one never does.
- expect(read.group.messages.find(m => m.id === rootId)!.threadUnread).toEqual({ count: 1, mentioned: true });
+ expect(read.group.messages.find(m => m.id === rootId)!.threadUnread).toEqual({ count: 1, mentioned: true, latest: Number(mentioning.seq) });
expect(read.group.threads).toEqual([expect.objectContaining({ rootId, rootText: '周末去哪? @Bot', rootAuthorName: 'Alice',
- unread: { count: 1, mentioned: true }, lastReply: expect.objectContaining({ authorName: 'Alice', text: `text of ${aliceReply}` }) })]);
+ unread: { count: 1, mentioned: true, latest: Number(mentioning.seq) }, lastReply: expect.objectContaining({ authorName: 'Alice', text: `text of ${aliceReply}` }) })]);
// An older server keeps no read state: nothing is shown as unread rather than everything.
withReads(undefined);
const older = await service.getGroup(roomId);
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index a20c791613..72c8a16c30 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -1020,12 +1020,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const read = reads.get(rootId) ?? 0n;
let count = 0;
let mentioned = false;
+ let latest = 0;
for (const m of messages) {
if (m.threadRootId !== rootId || m.deleted || m.origin === 'system' || m.authorId === selfId || BigInt(m.seq) <= read) continue;
count += 1;
+ latest = Math.max(latest, Number(m.seq));
if (m.mentions?.includes(selfId)) mentioned = true;
}
- return { count, mentioned };
+ return count ? { count, mentioned, latest } : { count, mentioned };
}
/** The group's Threads with replies in the newest window, unread ones first, newest reply next. */
function threadSummaries(roomId: string, s: Snapshot, page: Message[], reads: Map<string, bigint>): BotGroupThreadSummary[] {
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupThreadHint.tsx b/apps/desktop/src/renderer/features/bots/BotGroupThreadHint.tsx
index ee9c74d1a4..69be5ddcb5 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupThreadHint.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupThreadHint.tsx
@@ -21,7 +21,11 @@ export function botGroupHintThreads(threads: readonly BotGroupThreadSummary[], o
return threads.filter(thread => thread.rootId !== openRootId && thread.unread.count > 0 && thread.unread.mentioned);
}
-const signature = (threads: readonly BotGroupThreadSummary[]) => threads.map(thread => `${thread.rootId}:${thread.unread.count}`).join('|');
+/** What the reader had already been told about when they dismissed the hint: each Thread's newest unread reply. */
+const seen = (threads: readonly BotGroupThreadSummary[]) => new Map(threads.map(thread => [thread.rootId, thread.unread.latest ?? 0]));
+/** Only a reply newer than what was dismissed brings the hint back; a deleted or aged-out one does not. */
+const hasNews = (threads: readonly BotGroupThreadSummary[], dismissed: ReadonlyMap<string, number>) =>
+ threads.some(thread => (thread.unread.latest ?? 0) > (dismissed.get(thread.rootId) ?? -1));
function UnreadDot() {
return <span aria-hidden className="size-1.5 shrink-0 rounded-full bg-[var(--bot-unread-bg)]" />;
@@ -38,16 +42,16 @@ function ThreadRow({ thread, members, onOpen }: {
className={cn('flex w-full min-w-0 items-start gap-2.5 rounded-lg px-2 py-2 text-left hover:bg-[var(--surface-hover)]', FOCUS)}>
<BotAvatar size="sm" bot={{ name: thread.rootAuthorName || '?', avatar: member?.avatar ?? null, avatarUrl: member?.avatarUrl, avatarColor: member?.avatarColor ?? null }} />
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
- <span title={thread.rootText || undefined} className={cn('truncate text-13 leading-[18px]', unread ? 'text-[var(--text-primary)]' : 'text-[var(--text-secondary)]')}>
+ <span title={thread.rootText || undefined} className={cn('truncate text-13', unread ? 'text-[var(--text-primary)]' : 'text-[var(--text-secondary)]')}>
{thread.rootText || t(key('emptyReply'))}
</span>
{thread.lastReply ? (
- <span title={thread.lastReply.text || undefined} className="truncate text-12 leading-[17px] text-[var(--text-secondary)]">
+ <span title={thread.lastReply.text || undefined} className="truncate text-12 text-[var(--text-secondary)]">
<span className="font-medium text-[var(--text-primary)]">{thread.lastReply.authorName}</span>: {thread.lastReply.text || t(key('emptyReply'))}
</span>
) : null}
</span>
- <span className="flex shrink-0 flex-col items-end gap-0.5 text-11 leading-[17px] text-[var(--text-tertiary)]">
+ <span className="flex shrink-0 flex-col items-end gap-0.5 text-11 text-[var(--text-tertiary)]">
{unread ? (
<span className="flex items-center gap-1 font-medium text-[var(--text-primary)]"><UnreadDot />{t(key('newReplies'), { count: thread.unread.count })}</span>
) : <span>{t('bots.groupChat.server.replyCount', { count: thread.replyCount })}</span>}
@@ -66,10 +70,9 @@ export function BotGroupThreadHint({ threads, members, openRootId, onOpen }: {
}) {
const { t } = useTranslation();
const [listOpen, setListOpen] = useState(false);
- const [dismissed, setDismissed] = useState('');
+ const [dismissed, setDismissed] = useState<ReadonlyMap<string, number>>(new Map());
const hinted = botGroupHintThreads(threads, openRootId);
- const current = signature(hinted);
- if (!hinted.length || (dismissed === current && !listOpen)) return null;
+ if (!hinted.length || (!hasNews(hinted, dismissed) && !listOpen)) return null;
const mentioned = hinted.some(thread => thread.unread.mentioned);
const label = hinted.length === 1 ? t(key('hintOne')) : t(key('hintMany'), { count: hinted.length });
const others = threads.filter(thread => !hinted.includes(thread));
@@ -87,7 +90,7 @@ export function BotGroupThreadHint({ threads, members, openRootId, onOpen }: {
{mentioned ? <span className="shrink-0 font-medium"><span aria-hidden className="mr-1.5 font-normal text-[var(--text-tertiary)]">·</span>{t(key('hintMentioned'))}</span> : null}
</button>
<Tip text={t(key('hintDismiss'))}>
- <button type="button" aria-label={t(key('hintDismiss'))} onClick={() => { setDismissed(current); setListOpen(false); }}
+ <button type="button" aria-label={t(key('hintDismiss'))} onClick={() => { setDismissed(new Map([...dismissed, ...seen(hinted)])); setListOpen(false); }}
className={cn('mr-1 flex size-6 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]', FOCUS)}>
<X size={12} aria-hidden />
</button>
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts b/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts
index 67023787c3..af7e4a387e 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts
+++ b/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts
@@ -21,6 +21,7 @@ import type {
BotGroupPlanStepView,
BotGroupPlanView,
BotGroupQuoteView,
+ BotGroupThreadSummary,
} from '../../../shared/botGroupChat';
import type { BotGroupOutboxEntry } from './botGroupOutbox';
import { mergeBotGroupMessages, mergeBotGroupPlans } from './botGroupPresentation';
@@ -53,6 +54,23 @@ function signature(value: object): string {
* `next` with every entry whose content equals the previous entry of the same id replaced by
* that previous object; the previous array itself when nothing changed at all.
*/
+/**
+ * Pages opened through 「查看更早」 are not re-read, so their Thread roots take the unread state
+ * from the latest Thread list; otherwise a Thread read here or on another computer keeps its badge.
+ */
+function withThreadUnread(older: BotGroupMessageView[], threads: readonly BotGroupThreadSummary[] | undefined): BotGroupMessageView[] {
+ if (!threads?.length || !older.length) return older;
+ const unread = new Map(threads.map(thread => [thread.rootId, thread.unread]));
+ let changed = false;
+ const next = older.map((message) => {
+ const latest = unread.get(message.id);
+ if (!latest || signature(latest) === signature(message.threadUnread ?? {})) return message;
+ changed = true;
+ return { ...message, threadUnread: latest };
+ });
+ return changed ? next : older;
+}
+
export function stabilizeById<T extends { id: string }>(
previous: readonly T[],
next: readonly T[],
@@ -105,9 +123,9 @@ export function mergeBotGroupLatestPage(
const pushedOut = next.hasMoreBefore
? previous.group.messages.filter((message) => message.sequence < floor)
: [];
- const older = pushedOut.length > 0
+ const older = withThreadUnread(pushedOut.length > 0
? stabilizeById(previous.older, mergeBotGroupMessages(previous.older, pushedOut))
- : previous.older;
+ : previous.older, next.threads);
// The first rows moving down take over what the old latest page said about earlier history.
const olderHasMore = pushedOut.length > 0 && previous.older.length === 0 ? previous.group.hasMoreBefore : previous.olderHasMore;
const messages = stabilizeById(previous.group.messages, page, previous.older);
diff --git a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
index be46c34dfb..ac7aabb9f8 100644
--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
@@ -152,8 +152,10 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,
const anchorId = before ? shown[0]?.id : undefined;
const anchored = (replies: BotGroupMessageView[]) => !anchorId || replies.some(reply => reply.id === anchorId);
try {
- // Reading the latest page while the panel is open is what marks the Thread read.
- const result = await api().thread({ groupId: group.id, rootId, before, sourceMessageIds: shown.map(message => message.id), markRead: !before });
+ // Reading the latest page marks the Thread read only while the reader is at the newest reply:
+ // a reply that arrives while they read further up stays unread until they scroll down to it.
+ const markRead = !before && stickToBottomRef.current;
+ const result = await api().thread({ groupId: group.id, rootId, before, sourceMessageIds: shown.map(message => message.id), markRead });
if (!current()) return;
if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }
if (readBeforeRef.current === null && result.readBefore !== undefined) {
@@ -384,7 +386,7 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,
const replyCount = Math.max(root?.replyCount ?? 0, realReplies.filter(reply => reply.kind === 'message').length);
// The first reply from someone else after where the reader had read; only worth a divider
// when older replies sit above it.
- const firstNewIndex = readBefore === null ? -1 : replyRows.findIndex(message => message.sequence > readBefore && !message.isSelf);
+ const firstNewIndex = readBefore === null ? -1 : replyRows.findIndex(message => message.sequence > readBefore && !message.isSelf && !message.deleted && message.authorKind !== 'system');
const firstNewId = firstNewIndex > 0 ? replyRows[firstNewIndex]!.id : null;
return <aside ref={panelRef} aria-labelledby={titleId}
@@ -400,7 +402,10 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,
<div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto px-5 pb-4 pt-3"
onScroll={(event) => {
const element = event.currentTarget;
+ const wasAtBottom = stickToBottomRef.current;
stickToBottomRef.current = element.scrollHeight - element.scrollTop - element.clientHeight < STICK_TO_BOTTOM_PX;
+ // Back at the newest reply: what arrived meanwhile has now been seen.
+ if (!wasAtBottom && stickToBottomRef.current) refreshRef.current();
}}>
<div ref={contentRef} className="flex min-w-0 flex-col">
{rootRows.map(message => <Fragment key={message.id}>{renderRow(message, false)}</Fragment>)}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.ts
index f1b8b5e027..37e4d55d0d 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.ts
@@ -71,6 +71,18 @@ describe('push refresh merge', () => {
expect(merged.older).toBe(first.older);
});
+ // bot-group-chat.md §10「话题未读与提示」: older pages are not re-read, yet a Thread read meanwhile must lose its badge.
+ it('gives Thread roots on pages opened with 「查看更早」 the unread state of the latest Thread list', () => {
+ const root = msg({ id: 'm2', sequence: 2, replyCount: 2, threadUnread: { count: 2, mentioned: true, latest: 21 } });
+ const first: BotGroupLoadedTimeline = { group: detail(page(10, 12), true), older: [msg({ id: 'm1', sequence: 1 }), root], olderPlans: [], olderHasMore: true };
+ const thread = { rootId: 'm2', rootAuthorName: '咪咪', rootAuthorBotId: 'mimi', rootText: '', replyCount: 2, lastReply: null };
+ const read = mergeBotGroupLatestPage(first, { ...detail(page(10, 12), true), threads: [{ ...thread, unread: { count: 0, mentioned: false } }] });
+ expect(read.older[1]!.threadUnread).toEqual({ count: 0, mentioned: false });
+ expect(read.older[0]).toBe(first.older[0]);
+ // The same list again changes nothing.
+ expect(mergeBotGroupLatestPage(read, { ...detail(page(10, 12), true), threads: [{ ...thread, unread: { count: 0, mentioned: false } }] })).toBe(read);
+ });
+
it('retains loaded history when exactly one full latest page arrives with no missing sequence', () => {
const first: BotGroupLoadedTimeline = { group: detail(page(101, 200), true), older: page(1, 100), olderPlans: [], olderHasMore: false };
const merged = mergeBotGroupLatestPage(first, detail(page(201, 300), true));
diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.ts
index 8744795196..aed63a2a65 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -182,7 +182,12 @@ export interface BotGroupMessageView {
}
/** Unread replies of one Thread; `mentioned` when one of them names this reader. */
-export interface BotGroupThreadUnread { count: number; mentioned: boolean }
+export interface BotGroupThreadUnread {
+ count: number;
+ mentioned: boolean;
+ /** Sequence of the newest unread reply; tells a new reply apart from the same ones counted again. */
+ latest?: number;
+}
/**
* One Thread of the group for the in-chat 话题 list (bot-group-chat.md §10「话题未读与提示」).