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): 贴回引用不再回退卡片文字,话题回退读取改为后台

Dash6ee4930e5e33
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 6d406130b1..e16d3396a9 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -1310,14 +1310,43 @@ describe('Chat Server result delivery and refresh', () => {
if (!result.ok) throw new Error('Expected group');
return result.group.messages.find(m => m.id === share.id)!.threadShare!;
};
+ expect(await shareView()).toMatchObject({ status: 'loading', content: '' });
+ await vi.advanceTimersByTimeAsync(0);
expect(await shareView()).toMatchObject({ status: 'available', content: 'before you left' });
await vi.advanceTimersByTimeAsync(2000);
// Removed from the room; on rejoin the history window no longer covers that reply.
fixture.sockets.at(-1)!.emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'FORBIDDEN' } }));
visible = false;
+ expect(await shareView()).not.toMatchObject({ content: 'before you left' });
+ await vi.advanceTimersByTimeAsync(0);
expect(await shareView()).toMatchObject({ status: 'unavailable', content: '' });
});
+ it.each([
+ ['a server error', { status: 503, body: { error: { code: 'UNAVAILABLE' } } }, 'loading'],
+ ['a timeout-like failure', null, 'loading'],
+ ['forbidden', { status: 403, body: { error: { code: 'FORBIDDEN' } } }, 'unavailable'],
+ ] as const)('never shows the card text when reading the reply hits %s', async (_label, reply, status) => {
+ const outside = '70000000-0000-4000-8000-00000000000b';
+ const share = msg('90000000-0000-4000-8000-00000000000b', 9, aliceId, { content: shareCard(outside) });
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [share], cursor: '9' } };
+ if (route.startsWith(`/conversations/${roomId}/messages?limit=`)) return { body: [share] };
+ if (route.endsWith(`/messages/${outside}`)) { if (!reply) throw new Error('socket hang up'); return reply; }
+ return threadResponse(route, method, body);
+ });
+ const read = async () => {
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error('Expected group');
+ return result.group.messages.find(m => m.id === share.id)!.threadShare!;
+ };
+ await read();
+ await vi.advanceTimersByTimeAsync(0);
+ const view = await read();
+ expect(view).toMatchObject({ status, content: '', authorName: '' });
+ expect(JSON.stringify(view)).not.toContain('forged words');
+ });
+
it('does not let 「继续讨论」 restart a re-posted reply', async () => {
const ask = msg('90000000-0000-4000-8000-0000000000aa', 1, selfId);
fixture.handle.mockImplementation((route, method, body) => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts
index 4dd2b1e465..b88c862f26 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts
@@ -12,54 +12,89 @@ function message(overrides: Partial<ThreadMessage> & { id: string }): ThreadMess
}
const reply = (id: string, rootId: string, extra: Partial<ThreadMessage> = {}) => message({ id, threadRootId: rootId, ...extra });
const fullWindow = (messages: ThreadMessage[]) => [...messages, ...Array.from({ length: 100 - messages.length }, (_, i) => message({ id: `filler-${i}` }))];
+const deferred = <T,>() => { let resolve!: (value: T) => void; const promise = new Promise<T>(r => { resolve = r; }); return { promise, resolve }; };
+const makeIo = () => ({ threadPage: vi.fn(), message: vi.fn(), filled: vi.fn() });
describe('thread previews', () => {
- const io = { threadPage: vi.fn(), message: vi.fn() };
+ let io: ReturnType<typeof makeIo>;
let projection: ReturnType<typeof createThreadProjection<ThreadMessage>>;
- beforeEach(() => { io.threadPage.mockReset(); io.message.mockReset(); projection = createThreadProjection(io); });
+ beforeEach(() => { io = makeIo(); projection = createThreadProjection(io); });
afterEach(() => vi.useRealTimers());
- it('uses the snapshot window for active threads without any extra request', async () => {
+ it('uses the snapshot window for active threads without any extra request', () => {
const root = message({ id: rootA, replyCount: 3 });
// Newest first, like the server snapshot; a deleted reply never previews.
const window = fullWindow([reply('r3', rootA), reply('gone', rootA, { deleted: true }), reply('r2', rootA), reply('r1', rootA)]);
- const previews = await projection.previews(room, [root], window);
- expect(previews.get(rootA)!.map(m => m.id)).toEqual(['r2', 'r3']);
+ expect(projection.previews(room, [root], window).get(rootA)!.map(m => m.id)).toEqual(['r2', 'r3']);
expect(io.threadPage).not.toHaveBeenCalled();
});
- it('treats a short snapshot as the whole history', async () => {
+ it('treats a short snapshot as the whole history', () => {
const root = message({ id: rootA, replyCount: 1 });
- const previews = await projection.previews(room, [root], [reply('only', rootA)]);
- expect(previews.get(rootA)!.map(m => m.id)).toEqual(['only']);
+ expect(projection.previews(room, [root], [reply('only', rootA)]).get(rootA)!.map(m => m.id)).toEqual(['only']);
expect(io.threadPage).not.toHaveBeenCalled();
});
- it('reads one bounded page only for quiet threads and caches it until the count changes', async () => {
+ it('answers at once and fills quiet threads in the background, then asks for one refresh', async () => {
const root = message({ id: rootB, replyCount: 2 });
- io.threadPage.mockResolvedValue([reply('b2', rootB), reply('b1', rootB)]);
- const window = fullWindow([]);
- expect((await projection.previews(room, [root], window)).get(rootB)!.map(m => m.id)).toEqual(['b1', 'b2']);
- expect(io.threadPage).toHaveBeenCalledWith(room, rootB, 6);
- await projection.previews(room, [root], window);
+ const page = deferred<ThreadMessage[]>();
+ io.threadPage.mockReturnValue(page.promise);
+ // The room is not held back by the thread read.
+ expect(projection.previews(room, [root], fullWindow([])).has(rootB)).toBe(false);
+ expect(io.threadPage).toHaveBeenCalledWith(room, rootB, 6, undefined);
+ // A refresh while the read is in flight does not start a second one.
+ projection.previews(room, [root], fullWindow([]));
+ expect(io.threadPage).toHaveBeenCalledTimes(1);
+ page.resolve([reply('b2', rootB), reply('b1', rootB)]);
+ await projection.settled();
+ expect(io.filled).toHaveBeenCalledExactlyOnceWith(room);
+ expect(projection.previews(room, [root], fullWindow([])).get(rootB)!.map(m => m.id)).toEqual(['b1', 'b2']);
expect(io.threadPage).toHaveBeenCalledTimes(1);
// A new reply changes the count, so the cached page is no longer trusted.
- await projection.previews(room, [{ ...root, replyCount: 3 }], window);
+ projection.previews(room, [{ ...root, replyCount: 3 }], fullWindow([]));
expect(io.threadPage).toHaveBeenCalledTimes(2);
});
+ it('reads further back when deleted replies fill the newest page', async () => {
+ const root = message({ id: rootB, replyCount: 2 });
+ const tombstones = Array.from({ length: 5 }, (_, i) => reply(`gone-${i}`, rootB, { deleted: true }));
+ const older = reply('old-1', rootB);
+ io.threadPage
+ .mockResolvedValueOnce([...tombstones, reply('newest', rootB)])
+ .mockResolvedValueOnce([older, reply('old-2', rootB)]);
+ projection.previews(room, [root], fullWindow([]));
+ await projection.settled();
+ const before = [...tombstones, reply('x', rootB)].reduce((min, m) => Math.min(min, Number(m.seq)), Infinity);
+ expect(io.threadPage).toHaveBeenNthCalledWith(2, room, rootB, 6, expect.any(String));
+ expect(Number(io.threadPage.mock.calls[1]![3])).toBeLessThanOrEqual(before);
+ expect(projection.previews(room, [root], fullWindow([])).get(rootB)!.map(m => m.id)).toEqual(['old-1', 'newest']);
+ });
+
+ it('stops reading back once history ends or after a bounded number of pages', async () => {
+ const root = message({ id: rootB, replyCount: 2 });
+ io.threadPage.mockImplementation(async () => Array.from({ length: 6 }, (_, i) => reply(`gone-${i}`, rootB, { deleted: true })));
+ projection.previews(room, [root], fullWindow([]));
+ await projection.settled();
+ expect(io.threadPage).toHaveBeenCalledTimes(4);
+ io.threadPage.mockClear().mockResolvedValue([reply('only', rootB)]);
+ projection.previews(room, [{ ...root, replyCount: 5 }], fullWindow([]));
+ await projection.settled();
+ expect(io.threadPage).toHaveBeenCalledTimes(1);
+ });
+
it('drops a cached page when one of its replies is edited or deleted, and resets after reconnect', async () => {
const root = message({ id: rootB, replyCount: 1 });
io.threadPage.mockResolvedValue([reply('b1', rootB)]);
- await projection.previews(room, [root], fullWindow([]));
+ const read = async () => { projection.previews(room, [root], fullWindow([])); await projection.settled(); };
+ await read();
projection.invalidate(room, 'unrelated');
- await projection.previews(room, [root], fullWindow([]));
+ await read();
expect(io.threadPage).toHaveBeenCalledTimes(1);
projection.invalidate(room, 'b1');
- await projection.previews(room, [root], fullWindow([]));
+ await read();
expect(io.threadPage).toHaveBeenCalledTimes(2);
projection.reset();
- await projection.previews(room, [root], fullWindow([]));
+ await read();
expect(io.threadPage).toHaveBeenCalledTimes(3);
});
@@ -73,106 +108,122 @@ describe('thread previews', () => {
return [reply(`latest-${rootId}`, rootId)];
});
const roots = Array.from({ length: 20 }, (_, i) => message({ id: `30000000-0000-4000-8000-0000000000${String(i).padStart(2, '0')}`, replyCount: 1 }));
- const previews = await projection.previews(room, roots, fullWindow([]));
+ projection.previews(room, roots, fullWindow([]));
+ await projection.settled();
expect(peak).toBeLessThanOrEqual(6);
- expect(previews.size).toBe(18);
+ expect(projection.previews(room, roots, fullWindow([])).size).toBe(18);
io.threadPage.mockClear();
- await projection.previews(room, roots, fullWindow([]));
+ projection.previews(room, roots, fullWindow([]));
expect(io.threadPage).not.toHaveBeenCalled();
vi.setSystemTime(Date.now() + 31_000);
- await projection.previews(room, roots, fullWindow([]));
+ projection.previews(room, roots, fullWindow([]));
+ await projection.settled();
expect(io.threadPage).toHaveBeenCalledTimes(2);
});
- it('ignores replies themselves and roots without replies', async () => {
- const previews = await projection.previews(room, [message({ id: rootA, replyCount: 0 }), reply('nested', rootA, { replyCount: 4 })], fullWindow([]));
+ it('ignores replies themselves and roots without replies', () => {
+ const previews = projection.previews(room, [message({ id: rootA, replyCount: 0 }), reply('nested', rootA, { replyCount: 4 })], fullWindow([]));
expect(previews.size).toBe(0);
expect(io.threadPage).not.toHaveBeenCalled();
});
});
describe('share sources', () => {
- const io = { threadPage: vi.fn(), message: vi.fn() };
+ let io: ReturnType<typeof makeIo>;
let projection: ReturnType<typeof createThreadProjection<ThreadMessage>>;
- beforeEach(() => { io.threadPage.mockReset(); io.message.mockReset(); projection = createThreadProjection(io); });
+ beforeEach(() => { io = makeIo(); projection = createThreadProjection(io); });
const share = (id: string, messageId: string) => message({ id, content: [buildBotGroupThreadShareCard({ messageId, threadRootId: rootA, authorName: 'Miao', text: 'hi' })] });
const sourceId = '40000000-0000-4000-8000-000000000001';
- it('prefers fresh snapshot copies and reads each missing reply once', async () => {
+ it('prefers fresh snapshot copies and reads each missing reply once, in the background', async () => {
const fresh = reply(sourceId, rootA);
- expect((await projection.shareSources(room, [share('s1', sourceId)], [fresh])).get(sourceId)).toBe(fresh);
+ expect(projection.shareSources(room, [share('s1', sourceId)], [fresh]).get(sourceId)).toBe(fresh);
expect(io.message).not.toHaveBeenCalled();
const other = '40000000-0000-4000-8000-000000000002';
io.message.mockResolvedValue(reply(other, rootA));
- await projection.shareSources(room, [share('s2', other), share('s3', other)], []);
- await projection.shareSources(room, [share('s2', other)], []);
+ // Still being read: absent, so the caller shows a loading state rather than the card text.
+ expect(projection.shareSources(room, [share('s2', other), share('s3', other)], []).has(other)).toBe(false);
+ projection.shareSources(room, [share('s2', other)], []);
+ await projection.settled();
expect(io.message).toHaveBeenCalledTimes(1);
+ expect(io.filled).toHaveBeenCalledWith(room);
+ expect(projection.shareSources(room, [share('s2', other)], []).get(other)?.id).toBe(other);
});
- it('remembers a missing reply as unavailable and forgets edited ones', async () => {
+ it('remembers a reply the reader may not see and forgets edited ones', async () => {
io.message.mockResolvedValue(null);
- expect((await projection.shareSources(room, [share('s1', sourceId)], [])).get(sourceId)).toBeNull();
+ projection.shareSources(room, [share('s1', sourceId)], []);
+ await projection.settled();
+ expect(projection.shareSources(room, [share('s1', sourceId)], []).get(sourceId)).toBeNull();
io.message.mockResolvedValue(reply(sourceId, rootA, { revision: 2 }));
projection.invalidate(room, sourceId);
- expect((await projection.shareSources(room, [share('s1', sourceId)], [])).get(sourceId)?.revision).toBe(2);
+ projection.shareSources(room, [share('s1', sourceId)], []);
+ await projection.settled();
+ expect(projection.shareSources(room, [share('s1', sourceId)], []).get(sourceId)?.revision).toBe(2);
});
- it('leaves a share unresolved while the server cannot be reached', async () => {
+ it('keeps a share unresolved, without asking for a refresh, while the server cannot be reached', async () => {
io.message.mockRejectedValue(new Error('offline'));
- expect((await projection.shareSources(room, [share('s1', sourceId)], [])).has(sourceId)).toBe(false);
+ projection.shareSources(room, [share('s1', sourceId)], []);
+ await projection.settled();
+ expect(projection.shareSources(room, [share('s1', sourceId)], []).has(sourceId)).toBe(false);
+ expect(io.filled).not.toHaveBeenCalled();
});
- it('does not treat a card posted inside a thread as a share', async () => {
+ it('does not treat a card posted inside a thread as a share', () => {
const nested = { ...share('s1', sourceId), threadRootId: rootA };
- expect((await projection.shareSources(room, [nested], [])).size).toBe(0);
- });
-});
-
-describe('reply summaries', () => {
- it('summarizes text separately from files and refuses system or deleted replies', () => {
- const files = reply('f', rootA, { content: [{ type: 'text', text: ' 第一行\n第二行 ' }, { type: 'media', mediaId: 'm1', caption: 'shot.PNG' }, { type: 'media', mediaId: 'm2', caption: 'notes.pdf' }] });
- expect(threadPreviewText(files)).toBe('第一行 第二行');
- expect(threadPreviewAttachments(files)).toEqual([{ name: 'shot.PNG', category: 'image' }, { name: 'notes.pdf', category: 'file' }]);
- expect(threadPreviewText(reply('long', rootA, { content: [{ type: 'text', text: 'x'.repeat(400) }] }))).toHaveLength(280);
- expect(isShareableThreadReply(files)).toBe(true);
- expect(isShareableThreadReply(message({ id: 'root' }))).toBe(false);
- expect(isShareableThreadReply(reply('d', rootA, { deleted: true }))).toBe(false);
- expect(isShareableThreadReply(reply('s', rootA, { origin: 'system' }))).toBe(false);
- expect(isShareableThreadReply(reply('n', rootA, { content: [{ type: 'card', namespace: 'cindy.group-notice', fallback: 'x' }] }))).toBe(false);
+ expect(projection.shareSources(room, [nested], []).size).toBe(0);
});
});
describe('late reads after a reset or invalidation', () => {
- const deferred = <T,>() => { let resolve!: (value: T) => void; const promise = new Promise<T>(r => { resolve = r; }); return { promise, resolve }; };
const sourceId = '40000000-0000-4000-8000-000000000001';
const share = message({ id: 's1', content: [buildBotGroupThreadShareCard({ messageId: sourceId, threadRootId: rootA, authorName: 'Miao', text: 'hi' })] });
it.each(['reset', 'invalidate'] as const)('does not let a thread page started before %s refill the cache', async (clear) => {
- const io = { threadPage: vi.fn(), message: vi.fn() };
+ const io = makeIo();
const projection = createThreadProjection(io);
const root = message({ id: rootB, replyCount: 1 });
const stale = deferred<ThreadMessage[]>();
io.threadPage.mockReturnValueOnce(stale.promise).mockResolvedValue([reply('b1', rootB, { revision: 2 })]);
- const inFlight = projection.previews(room, [root], fullWindow([]));
+ projection.previews(room, [root], fullWindow([]));
if (clear === 'reset') projection.reset(); else projection.invalidate(room, 'b1');
stale.resolve([reply('b1', rootB)]);
- await inFlight;
- const next = await projection.previews(room, [root], fullWindow([]));
+ await projection.settled();
+ // The stale copy is dropped, but the reader is still told to look again.
+ expect(io.filled).toHaveBeenCalledWith(room);
+ projection.previews(room, [root], fullWindow([]));
+ await projection.settled();
expect(io.threadPage).toHaveBeenCalledTimes(2);
- expect(next.get(rootB)![0]!.revision).toBe(2);
+ expect(projection.previews(room, [root], fullWindow([])).get(rootB)![0]!.revision).toBe(2);
});
it.each(['reset', 'invalidate'] as const)('does not let a share source read started before %s refill the cache', async (clear) => {
- const io = { threadPage: vi.fn(), message: vi.fn() };
+ const io = makeIo();
const projection = createThreadProjection(io);
const stale = deferred<ThreadMessage | null>();
io.message.mockReturnValueOnce(stale.promise).mockResolvedValue(reply(sourceId, rootA, { revision: 2 }));
- const inFlight = projection.shareSources(room, [share], []);
+ projection.shareSources(room, [share], []);
if (clear === 'reset') projection.reset(); else projection.invalidate(room, sourceId);
stale.resolve(reply(sourceId, rootA));
- await inFlight;
- const next = await projection.shareSources(room, [share], []);
+ await projection.settled();
+ projection.shareSources(room, [share], []);
+ await projection.settled();
expect(io.message).toHaveBeenCalledTimes(2);
- expect(next.get(sourceId)?.revision).toBe(2);
+ expect(projection.shareSources(room, [share], []).get(sourceId)?.revision).toBe(2);
+ });
+});
+
+describe('reply summaries', () => {
+ it('summarizes text separately from files and refuses system or deleted replies', () => {
+ const files = reply('f', rootA, { content: [{ type: 'text', text: ' 第一行\n第二行 ' }, { type: 'media', mediaId: 'm1', caption: 'shot.PNG' }, { type: 'media', mediaId: 'm2', caption: 'notes.pdf' }] });
+ expect(threadPreviewText(files)).toBe('第一行 第二行');
+ expect(threadPreviewAttachments(files)).toEqual([{ name: 'shot.PNG', category: 'image' }, { name: 'notes.pdf', category: 'file' }]);
+ expect(threadPreviewText(reply('long', rootA, { content: [{ type: 'text', text: 'x'.repeat(400) }] }))).toHaveLength(280);
+ expect(isShareableThreadReply(files)).toBe(true);
+ expect(isShareableThreadReply(message({ id: 'root' }))).toBe(false);
+ expect(isShareableThreadReply(reply('d', rootA, { deleted: true }))).toBe(false);
+ expect(isShareableThreadReply(reply('s', rootA, { origin: 'system' }))).toBe(false);
+ expect(isShareableThreadReply(reply('n', rootA, { content: [{ type: 'card', namespace: 'cindy.group-notice', fallback: 'x' }] }))).toBe(false);
});
});
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 5b707fa40c..cb908266d1 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -281,11 +281,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
}
const media = createChatMedia(api, current, deps.log, { allowLoopback: !app.isPackaged && process.env.XDT_ISOLATED === '1' && config.baseUrl === 'http://127.0.0.1:3018' });
const threads = createThreadProjection<Message>({
- threadPage: (roomId, rootId, limit) => api<Message[]>(`/conversations/${roomId}/messages?threadRootId=${rootId}&limit=${limit}`),
+ threadPage: (roomId, rootId, limit, before) => api<Message[]>(`/conversations/${roomId}/messages?threadRootId=${rootId}&limit=${limit}${before ? `&before=${before}` : ''}`),
+ // Not found and forbidden both mean this reader may not see the reply now.
message: (roomId, messageId) => api<Message>(`/conversations/${roomId}/messages/${messageId}`).catch(error => {
- if (error instanceof ChatResponseError && error.status === 404) return null;
+ if (error instanceof ChatResponseError && (error.status === 404 || error.status === 403)) return null;
throw error;
}),
+ filled: roomId => changed(roomId),
});
let upgrade: Promise<Map<string, string>> | undefined;
let upgradeRetryAt = 0;
@@ -560,14 +562,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
}
/**
* Attach thread previews (roots) and resolved shares (main-chat references) to the views
- * of `page`. `snapshot` is the newest window across all threads. A share whose reply
- * cannot be read right now keeps its plain fallback text and is resolved on a later read.
+ * of `page`. `snapshot` is the newest window across all threads. A share whose reply is
+ * still being read is marked `loading`: the card's own fallback text is never shown here.
*/
async function decorateThreads(roomId: string, views: BotGroupMessageView[], page: Message[], snapshot: Message[], members: Member[], withPreviews: boolean) {
- const [previews, sources] = await Promise.all([
- withPreviews ? threads.previews(roomId, page, snapshot) : new Map<string, Message[]>(),
- threads.shareSources(roomId, page, [...snapshot, ...page]),
- ]);
+ const previews = withPreviews ? threads.previews(roomId, page, snapshot) : new Map<string, Message[]>();
+ const sources = threads.shareSources(roomId, page, [...snapshot, ...page]);
const shareable = [...sources.values()].filter((m): m is Message => !!m && isShareableThreadReply(m));
const sourceViews = new Map((await messageViews(roomId, shareable, members)).map(view => [view.id, view]));
const byId = new Map(page.map(m => [m.id, m]));
@@ -582,14 +582,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
});
if (replies?.length) view.threadPreview = { replies };
const card = readBotGroupThreadShareCard(message);
- if (!card || !sources.has(card.messageId)) continue;
+ if (!card) continue;
const source = sources.get(card.messageId);
const resolved = source && source.threadRootId === card.threadRootId ? sourceViews.get(source.id) : undefined;
view.threadShare = source && resolved ? {
...card, status: 'available', authorKind: resolved.authorKind, authorBotId: resolved.authorBotId, authorName: resolved.authorName,
sharedByAuthor: source.authorId === message.authorId, content: resolved.content, attachments: resolved.attachments,
createdAt: resolved.createdAt, edited: (source.revision ?? 1) > 1,
- } : { ...card, status: 'unavailable', authorKind: 'user', authorBotId: null, authorName: '', sharedByAuthor: false,
+ } : { ...card, status: sources.has(card.messageId) ? 'unavailable' : 'loading', authorKind: 'user', authorBotId: null, authorName: '', sharedByAuthor: false,
content: '', attachments: [], createdAt: null, edited: false };
}
}
diff --git a/apps/desktop/src/main/maker-ipc/chatServerThreads.ts b/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
index 7536cf4db1..d737df8c7a 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
@@ -23,6 +23,8 @@ const READ_CONCURRENCY = 6;
const RETRY_MS = 30_000;
/** Deleted replies still occupy a page, so read a little more than the preview needs. */
const FALLBACK_PAGE = BOT_GROUP_THREAD_PREVIEW_REPLIES + 4;
+/** A thread whose newest replies are mostly deleted reads back at most this far. */
+const FALLBACK_PAGES = 4;
const SNAPSHOT_WINDOW = 100;
async function eachLimited<T>(items: readonly T[], run: (item: T) => Promise<void>) {
@@ -32,26 +34,55 @@ async function eachLimited<T>(items: readonly T[], run: (item: T) => Promise<voi
}));
}
+/**
+ * Cache lookups never wait for the network: a missing entry is filled in the background
+ * and `filled(roomId)` asks for one more read once anything new is cached, so a room with
+ * many quiet threads still opens at once and shows the counts first.
+ */
export function createThreadProjection<M extends ThreadMessage>(io: {
- /** Newest-first page of one thread. */
- threadPage(roomId: string, rootId: string, limit: number): Promise<M[]>;
- /** One message as this reader may see it; `null` when the server says it does not exist. */
+ /** Newest-first page of one thread, optionally before a sequence. */
+ threadPage(roomId: string, rootId: string, limit: number, before?: string): Promise<M[]>;
+ /** One message as this reader may see it; `null` when the server says it is not visible. */
message(roomId: string, messageId: string): Promise<M | null>;
+ filled(roomId: string): void;
}) {
const previews = new Map<string, { replyCount: number; replies: M[] }>();
const sources = new Map<string, M | null>();
const retryAt = new Map<string, number>();
+ const inFlight = new Set<string>();
+ const settling = new Set<Promise<void>>();
// A read that was in flight across reset()/invalidate() may carry the old copy.
let generation = 0;
const key = (roomId: string, id: string) => `${roomId}:${id}`;
- const waiting = (cacheKey: string) => (retryAt.get(cacheKey) ?? 0) > Date.now();
+ const waiting = (cacheKey: string) => inFlight.has(cacheKey) || (retryAt.get(cacheKey) ?? 0) > Date.now();
+
+ function fill<T>(roomId: string, items: Array<{ cacheKey: string; item: T }>, read: (item: T) => Promise<(() => void) | null>) {
+ if (!items.length) return;
+ for (const { cacheKey } of items) inFlight.add(cacheKey);
+ const started = generation;
+ const task = (async () => {
+ let wrote = false;
+ await eachLimited(items, async ({ cacheKey, item }) => {
+ try {
+ const store = await read(item);
+ retryAt.delete(cacheKey);
+ // A copy that outlived a reset is dropped, but the reader still needs a fresh read.
+ if (store) { if (generation === started) store(); wrote = true; }
+ } catch { retryAt.set(cacheKey, Date.now() + RETRY_MS); }
+ finally { inFlight.delete(cacheKey); }
+ });
+ if (wrote) io.filled(roomId);
+ })();
+ settling.add(task);
+ void task.finally(() => settling.delete(task));
+ }
return {
/**
- * Newest replies of every root in `page`, chronological. `snapshot` is the server's
- * newest-first window across the main chat and all threads.
+ * Newest replies of every root in `page` that are known now, chronological. `snapshot`
+ * is the server's newest-first window across the main chat and all threads.
*/
- async previews(roomId: string, page: readonly M[], snapshot: readonly M[]): Promise<Map<string, M[]>> {
+ previews(roomId: string, page: readonly M[], snapshot: readonly M[]): Map<string, M[]> {
const complete = snapshot.length < SNAPSHOT_WINDOW;
const inWindow = new Map<string, M[]>();
for (const message of snapshot) {
@@ -60,56 +91,53 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
list.push(message); inWindow.set(message.threadRootId, list);
}
const result = new Map<string, M[]>();
- const missing: M[] = [];
+ const missing: Array<{ cacheKey: string; item: M }> = [];
for (const root of page) {
const count = root.replyCount ?? 0;
if (root.threadRootId || count <= 0) continue;
const found = inWindow.get(root.id) ?? [];
- const cached = previews.get(key(roomId, root.id));
+ const cacheKey = key(roomId, root.id);
+ const cached = previews.get(cacheKey);
// The window is a suffix of the room's sequence, so what it holds is the newest.
if (complete || found.length >= Math.min(count, BOT_GROUP_THREAD_PREVIEW_REPLIES)) result.set(root.id, found);
else if (cached?.replyCount === count) result.set(root.id, cached.replies);
- else if (!waiting(key(roomId, root.id))) missing.push(root);
+ else if (!waiting(cacheKey)) missing.push({ cacheKey, item: root });
}
- await eachLimited(missing, async root => {
- const cacheKey = key(roomId, root.id);
- const started = generation;
- try {
- const replies = (await io.threadPage(roomId, root.id, FALLBACK_PAGE)).filter(message => !message.deleted);
- if (generation === started) previews.set(cacheKey, { replyCount: root.replyCount ?? 0, replies });
- retryAt.delete(cacheKey);
- result.set(root.id, replies);
- } catch { retryAt.set(cacheKey, Date.now() + RETRY_MS); }
+ fill(roomId, missing, async root => {
+ const wanted = Math.min(root.replyCount ?? 0, BOT_GROUP_THREAD_PREVIEW_REPLIES);
+ const replies: M[] = [];
+ let before: string | undefined;
+ for (let pages = 0; pages < FALLBACK_PAGES && replies.length < wanted; pages += 1) {
+ const batch = await io.threadPage(roomId, root.id, FALLBACK_PAGE, before);
+ replies.push(...batch.filter(message => !message.deleted));
+ if (batch.length < FALLBACK_PAGE) break;
+ before = batch.reduce((min, message) => BigInt(message.seq) < BigInt(min) ? message.seq : min, batch[0]!.seq);
+ }
+ return () => previews.set(key(roomId, root.id), { replyCount: root.replyCount ?? 0, replies });
});
for (const [rootId, replies] of result)
result.set(rootId, replies.slice(0, BOT_GROUP_THREAD_PREVIEW_REPLIES).reverse());
return result;
},
/**
- * The replies named by share cards in `page`: a message, `null` when it no longer
- * exists for this reader, or absent while the server cannot be reached.
+ * The replies named by share cards in `page`: a message, `null` when this reader may
+ * not see it, or absent while it is still being read.
*/
- async shareSources(roomId: string, page: readonly M[], known: readonly M[]): Promise<Map<string, M | null>> {
+ shareSources(roomId: string, page: readonly M[], known: readonly M[]): Map<string, M | null> {
const fresh = new Map(known.map(message => [message.id, message]));
const result = new Map<string, M | null>();
- const missing = new Set<string>();
+ const missing = new Map<string, { cacheKey: string; item: string }>();
for (const message of page) {
const card = readBotGroupThreadShareCard(message);
if (!card || result.has(card.messageId)) continue;
const cacheKey = key(roomId, card.messageId);
if (fresh.has(card.messageId)) result.set(card.messageId, fresh.get(card.messageId)!);
else if (sources.has(cacheKey)) result.set(card.messageId, sources.get(cacheKey)!);
- else if (!waiting(cacheKey)) missing.add(card.messageId);
+ else if (!waiting(cacheKey)) missing.set(card.messageId, { cacheKey, item: card.messageId });
}
- await eachLimited([...missing], async messageId => {
- const cacheKey = key(roomId, messageId);
- const started = generation;
- try {
- const value = await io.message(roomId, messageId);
- if (generation === started) sources.set(cacheKey, value);
- retryAt.delete(cacheKey);
- result.set(messageId, value);
- } catch { retryAt.set(cacheKey, Date.now() + RETRY_MS); }
+ fill(roomId, [...missing.values()], async messageId => {
+ const value = await io.message(roomId, messageId);
+ return () => sources.set(key(roomId, messageId), value);
});
return result;
},
@@ -122,6 +150,8 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
},
/** Pushes may have been missed while disconnected. */
reset() { generation += 1; previews.clear(); sources.clear(); retryAt.clear(); },
+ /** Tests: wait for background fills started so far. */
+ async settled() { while (settling.size) await Promise.all([...settling]); },
};
}
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index c42a6bbd0a..2e733d3359 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -694,7 +694,8 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
align={message.authorKind === 'user' && message.isSelf !== false ? 'right' : 'left'}
onReply={group.serverBacked ? () => openThread(message.id) : undefined}
replyCountShown={group.serverBacked && (message.replyCount ?? 0) > 0}
- copyText={message.threadShare?.status === 'available' ? message.threadShare.content : undefined}
+ // A share copies the server's reply, never the card's fallback text.
+ copyText={message.threadShare ? message.threadShare.status === 'available' ? message.threadShare.content : '' : undefined}
onChanged={() => loadRef.current()} /> : undefined}
onOpenThread={group.serverBacked ? (rootId, focusMessageId) => openThread(rootId, focusMessageId) : undefined}
member={message.authorBotId ? memberById.get(message.authorBotId) : undefined}
@@ -783,7 +784,8 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
) : null}
</main>
{group.serverBacked && threadRootId && <ChatThreadPanel key={`${group.id}:${threadRootId}`} group={group} rootId={threadRootId}
- focus={threadFocus} sharedReplies={sharedReplies} onRevealShare={revealMainMessage} onClose={closeThread} />}
+ focus={threadFocus} sharedReplies={sharedReplies} onRevealShare={revealMainMessage} onClose={closeThread}
+ renderAttachments={attachments => <BotGroupUserAttachments attachments={attachments} align="start" />} />}
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupThreadViews.tsx b/apps/desktop/src/renderer/features/bots/BotGroupThreadViews.tsx
index 12ccf71d9e..d10c311dff 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupThreadViews.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupThreadViews.tsx
@@ -103,7 +103,9 @@ export function botGroupThreadShareLabel(share: BotGroupThreadShareView, t: (key
/** The referenced reply as the server has it now: edits show, deletions say so. */
export function BotGroupThreadShareQuote({ share, members, attachments, onOpenThread }: {
- share: BotGroupThreadShareView; members: readonly BotGroupMemberView[]; attachments: ReactNode; onOpenThread: () => void;
+ share: BotGroupThreadShareView; members: readonly BotGroupMemberView[]; attachments: ReactNode;
+ /** Omitted inside the thread panel, where the quote is already the thread's root. */
+ onOpenThread?: () => void;
}) {
const { t } = useTranslation();
const createdAt = share.createdAt ? new Date(share.createdAt).toISOString() : undefined;
@@ -131,13 +133,15 @@ export function BotGroupThreadShareQuote({ share, members, attachments, onOpenTh
{attachments}
</>
) : (
- <p className="text-13 text-[var(--text-tertiary)]">{t(key('sourceUnavailable'))}</p>
+ <p role={share.status === 'loading' ? 'status' : undefined} className="text-13 text-[var(--text-tertiary)]">
+ {t(key(share.status === 'loading' ? 'loadingSource' : 'sourceUnavailable'))}
+ </p>
)}
- <button type="button" onClick={onOpenThread}
+ {onOpenThread ? <button type="button" onClick={onOpenThread}
className={cn('-ml-1.5 inline-flex min-h-6 w-fit select-none items-center gap-1 rounded-full px-1.5 text-12 text-[var(--text-secondary)] transition-colors duration-[var(--motion-fast)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]', FOCUS)}>
<CornerDownRight size={12} aria-hidden />
{t(key('viewThread'))}
- </button>
+ </button> : null}
</figure>
);
}
diff --git a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
index f230b1d44b..8f713f4611 100644
--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from 'react';
import { Check, CornerDownRight, MessageSquareShare, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
@@ -19,7 +19,7 @@ import { refreshBotGroups } from './botGroupStore';
import { mergeBotGroupMessages, projectBotGroupExecutionFailures } from './botGroupPresentation';
import { BotAvatar } from './BotAvatar';
import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';
-import { botGroupThreadShareLabel, findThreadMessageElement, flashThreadTarget } from './BotGroupThreadViews';
+import { BotGroupThreadShareQuote, botGroupThreadShareLabel, findThreadMessageElement, flashThreadTarget } from './BotGroupThreadViews';
import { ChatMessageActions, chatErrorKey } from './ChatServerControls';
const key = (name: string) => `bots.groupChat.server.${name}`;
const api = () => window.electronAPI.maker.chatServer;
@@ -29,6 +29,12 @@ const FOCUS_PAGE_LIMIT = 5;
/** Shares of this thread's replies that the main chat has loaded. */
export type BotGroupSharedReplies = ReadonlyMap<string, { messageId: string; bySelf: boolean }>;
+/**
+ * Replies that reached a thread while their main-chat copy did not, per group and thread.
+ * Kept outside the panel so switching threads and coming back still offers the retry.
+ */
+const unpostedReplies = new Map<string, ReadonlySet<string>>();
+
export function animateThreadPanelWidth(panel: HTMLElement, from: string, to: string): Animation | null {
const style = getComputedStyle(panel);
const token = style.getPropertyValue('--motion-base').trim();
@@ -39,15 +45,17 @@ export function animateThreadPanelWidth(panel: HTMLElement, from: string, to: st
});
}
-function ThreadMessage({ group, message, shareScope, sharing, shared, posting, onPost, onReveal, onChanged }: {
+function ThreadMessage({ group, message, shareScope, sharing, shared, posting, onPost, onReveal, onChanged, renderAttachments }: {
group: BotGroupDetail; message: BotGroupMessageView; shareScope: string; sharing: boolean;
+ renderAttachments?: (attachments: BotGroupMessageView['attachments']) => ReactNode;
/** Replies only: already in the main chat (by anyone), and whether the reader shared it. */
shared?: { bySelf: boolean } | null; posting?: boolean; onPost?: () => void; onReveal?: () => void; onChanged: () => void;
}) {
const { t } = useTranslation();
const member = group.members.find(m => m.botId === message.authorBotId);
if (message.kind === 'notice' && isBotGroupRuntimeFailureCode(message.runtimeFailureCode)) return <BotGroupRuntimeFailureNotice name={message.authorName || member?.name || ''} code={message.runtimeFailureCode} />;
- const share = message.threadShare?.status === 'available' ? message.threadShare : undefined;
+ // A share as a thread root shows the same quote as the main chat, in every state.
+ const share = message.threadShare;
const postAction = onPost && !message.deleted && message.kind === 'message' ? shared?.bySelf && onReveal
? { key: 'reveal-in-main', label: t(key('thread.viewInMain')), icon: <CornerDownRight size={14} strokeWidth={2} className="shrink-0" />, onSelect: onReveal }
: { key: 'post-to-main', label: t(key('thread.postToMain')), disabled: posting, icon: <MessageSquareShare size={14} strokeWidth={2} className="shrink-0" />, onSelect: onPost }
@@ -58,22 +66,24 @@ function ThreadMessage({ group, message, shareScope, sharing, shared, posting, o
<BotAvatar bot={{ name: message.authorName, avatar: member?.avatar ?? null, avatarUrl: member?.avatarUrl, avatarColor: member?.avatarColor ?? null }} size="sm" />
<div className="min-w-0 flex-1 space-y-1">
<p className="text-13 font-medium leading-7 text-[var(--text-primary)]">{message.authorName}</p>
- {share && <p className="flex select-none items-center gap-1 text-12 text-[var(--text-tertiary)]">
- <CornerDownRight size={12} aria-hidden />{botGroupThreadShareLabel(share, t)} · {share.authorName}</p>}
- <div className="break-words text-14 leading-relaxed text-[var(--text-primary)]">
- <MarkdownRenderer workingDir="" content={share?.content ?? message.content} allowPrivilegedLinks={false} />
- </div>
+ {share ? <>
+ <p className="flex select-none items-center gap-1 text-12 text-[var(--text-tertiary)]">
+ <CornerDownRight size={12} aria-hidden />{botGroupThreadShareLabel(share, t)}</p>
+ <BotGroupThreadShareQuote share={share} members={group.members} attachments={renderAttachments?.(share.attachments)} />
+ </> : <div className="break-words text-14 leading-relaxed text-[var(--text-primary)]">
+ <MarkdownRenderer workingDir="" content={message.content} allowPrivilegedLinks={false} />
+ </div>}
{shared && <button type="button" onClick={onReveal} disabled={!onReveal}
className="-ml-1.5 inline-flex min-h-6 select-none items-center gap-1 rounded-full px-1.5 text-12 text-[var(--text-tertiary)] outline-none transition-colors duration-[var(--motion-fast)] enabled:hover:bg-[var(--surface-hover)] enabled:hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]">
<CornerDownRight size={12} aria-hidden />{t(key(shared.bySelf ? 'thread.postedBySelf' : 'thread.postedToMain'))}
</button>}
<ChatMessageActions groupId={group.id} shareScope={shareScope} message={message} align="left" onChanged={onChanged}
- copyText={share?.content} menuActions={postAction ? [postAction] : undefined} />
+ copyText={share ? share.status === 'available' ? share.content : '' : undefined} menuActions={postAction ? [postAction] : undefined} />
</div>
</article>;
}
-export function ChatThreadPanel({ group, rootId, focus, sharedReplies, onRevealShare, onClose }: {
+export function ChatThreadPanel({ group, rootId, focus, sharedReplies, onRevealShare, onClose, renderAttachments }: {
group: BotGroupDetail; rootId: string;
/** A reply to bring into view; a new nonce repeats the jump. */
focus?: { messageId: string; nonce: number } | null;
@@ -81,6 +91,8 @@ export function ChatThreadPanel({ group, rootId, focus, sharedReplies, onRevealS
/** Scroll the main chat to a share; false when it is not loaded there. */
onRevealShare?: (messageId: string) => boolean;
onClose: () => void;
+ /** The main chat's attachment view, reused for a shared reply at the thread root. */
+ renderAttachments?: (attachments: BotGroupMessageView['attachments']) => ReactNode;
}) {
const { t } = useTranslation();
const titleId = useId();
@@ -105,12 +117,17 @@ export function ChatThreadPanel({ group, rootId, focus, sharedReplies, onRevealS
const [error, setError] = useState('');
// Off by default: a reply stays in the thread unless the user asks for both.
const [alsoSend, setAlsoSend] = useState(false);
- /** A reply that reached the thread while its main-chat copy did not. */
- const [unposted, setUnposted] = useState<string | null>(null);
+ const unpostedKey = `${group.id}:${rootId}`;
+ const [unposted, setUnpostedState] = useState<ReadonlySet<string>>(() => unpostedReplies.get(unpostedKey) ?? new Set());
+ const setUnposted = (update: (previous: ReadonlySet<string>) => ReadonlySet<string>) => setUnpostedState(previous => {
+ const next = update(previous);
+ if (next.size) unpostedReplies.set(unpostedKey, next); else unpostedReplies.delete(unpostedKey);
+ return next;
+ });
const [posting, setPosting] = useState<ReadonlySet<string>>(new Set());
const postingRef = useRef(new Set<string>());
- /** Shares confirmed in this panel, until the main chat's reload lists them. */
- const [posted, setPosted] = useState<ReadonlySet<string>>(new Set());
+ /** Shares confirmed in this panel (reply → main-chat message, null when unknown). */
+ const [posted, setPosted] = useState<ReadonlyMap<string, string | null>>(new Map());
const request = useRef(0);
const attempt = useRef<{ text: string; id: string; mentions: BotGroupMention } | null>(null);
const sending = useRef(false);
@@ -156,15 +173,15 @@ export function ChatThreadPanel({ group, rootId, focus, sharedReplies, onRevealS
const owner = getDataOwnerGeneration();
const failed = (code?: string) => {
if (!isDataOwnerGenerationCurrent(owner)) return;
- if (fromComposer) setUnposted(messageId);
+ if (fromComposer) setUnposted(previous => new Set(previous).add(messageId));
else toast.error(t(code ? chatErrorKey(code) : key('requestFailed')));
};
try {
const result = await api().shareToMain({ groupId: group.id, messageId });
if (!isDataOwnerGenerationCurrent(owner)) return false;
if (!result.ok) { failed(result.errorCode); return false; }
- setPosted(previous => new Set(previous).add(messageId));
- setUnposted(current => current === messageId ? null : current);
+ setPosted(previous => new Map(previous).set(messageId, result.messageId));
+ setUnposted(previous => { const next = new Set(previous); next.delete(messageId); return next; });
if (result.alreadyShared && !fromComposer) toast.info(t(key('thread.alreadyPosted')));
refreshBotGroups();
return true;
@@ -172,7 +189,7 @@ export function ChatThreadPanel({ group, rootId, focus, sharedReplies, onRevealS
finally { postingRef.current.delete(messageId); setPosting(new Set(postingRef.current)); }
}
async function retryUnposted() {
- if (unposted) await postToMain(unposted, true);
+ for (const messageId of unposted) await postToMain(messageId, true);
}
async function send() {
if (group.archived || sending.current || !text.trim()) return;
@@ -198,7 +215,11 @@ export function ChatThreadPanel({ group, rootId, focus, sharedReplies, onRevealS
const sharedState = (messageId: string) => {
const known = sharedReplies?.get(messageId);
if (known) return { bySelf: known.bySelf, shareId: known.messageId };
- return posted.has(messageId) ? { bySelf: true, shareId: null } : null;
+ return posted.has(messageId) ? { bySelf: true, shareId: posted.get(messageId) ?? null } : null;
+ };
+ /** The share may sit on an older page the main chat has not loaded. */
+ const revealShare = (shareId: string) => {
+ if (!onRevealShare?.(shareId)) toast.info(t(key('thread.shareNotLoaded')));
};
return <aside ref={panelRef} aria-labelledby={titleId}
className="flex h-full min-w-0 w-1/2 max-w-[min(50%,28rem)] shrink-0 flex-col overflow-hidden border-l border-[var(--border-default)] bg-[var(--surface)]">
@@ -211,7 +232,8 @@ export function ChatThreadPanel({ group, rootId, focus, sharedReplies, onRevealS
</Tip>
</header>
<div ref={contentRef} className="min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4">
- {projectBotGroupExecutionFailures(root ? [root] : [], executionFailures).map(message => <ThreadMessage key={message.id} shareScope={shareScope} sharing={sharing} group={group} message={message} onChanged={() => void loadRef.current()} />)}
+ {projectBotGroupExecutionFailures(root ? [root] : [], executionFailures).map(message => <ThreadMessage key={message.id} shareScope={shareScope} sharing={sharing} group={group} message={message}
+ renderAttachments={renderAttachments} onChanged={() => void loadRef.current()} />)}
<div className="border-t border-[var(--border-default)] pt-3 text-12 text-[var(--text-tertiary)]">{t(key('replies'))}</div>
{hasMore && <Button variant="secondary" size="sm" onClick={() => void loadRef.current(replies[0]?.sequence)}>{t('bots.groupChat.timeline.loadEarlier')}</Button>}
{projectBotGroupExecutionFailures(replies, executionFailures).map(message => {
@@ -219,7 +241,7 @@ export function ChatThreadPanel({ group, rootId, focus, sharedReplies, onRevealS
return <ThreadMessage key={message.id} shareScope={shareScope} sharing={sharing} group={group} message={message}
shared={shared} posting={posting.has(message.id)}
onPost={group.archived ? undefined : () => void postToMain(message.id, false)}
- onReveal={shared?.shareId && onRevealShare ? () => { onRevealShare(shared.shareId!); } : undefined}
+ onReveal={shared?.shareId ? () => revealShare(shared.shareId!) : undefined}
onChanged={() => void loadRef.current()} />;
})}
</div>
@@ -227,9 +249,9 @@ export function ChatThreadPanel({ group, rootId, focus, sharedReplies, onRevealS
getContentWidth={() => contentRef.current?.querySelector('article')?.getBoundingClientRect().width ?? 400} /> : <div className="space-y-3 border-t border-[var(--border-default)] p-4">
{error && <p role="alert" className="text-13 text-[var(--error-fg)]">{error}</p>}
{/* Kept apart from read errors: a thread refresh must not hide the retry. */}
- {unposted && <div role="alert" className="flex flex-wrap items-center gap-x-2 gap-y-1 text-13 text-[var(--error-fg)]">
- <span className="min-w-0">{t(key('thread.alsoSendFailed'))}</span>
- <Button variant="secondary" size="sm" compact loading={posting.has(unposted)} onClick={() => void retryUnposted()}>
+ {unposted.size > 0 && <div role="alert" className="flex flex-wrap items-center gap-x-2 gap-y-1 text-13 text-[var(--error-fg)]">
+ <span className="min-w-0">{t(key('thread.alsoSendFailed'), { count: unposted.size })}</span>
+ <Button variant="secondary" size="sm" compact loading={[...unposted].some(id => posting.has(id))} onClick={() => void retryUnposted()}>
{t(key('thread.retryPost'))}</Button>
</div>}
<Textarea aria-label={t(key('replyPlaceholder'))} placeholder={t(key('replyPlaceholder'))} value={text} onChange={value => {
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
index 727f372df1..637e3a882b 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -1840,3 +1840,86 @@ describe('thread previews and posting to the main chat', () => {
expect(mocks.reply).not.toHaveBeenCalled();
});
});
+
+describe('thread share follow-ups', () => {
+ const t = (name: string) => `bots.groupChat.server.thread.${name}`;
+ const share = (overrides: Partial<NonNullable<BotGroupMessageView['threadShare']>> = {}): NonNullable<BotGroupMessageView['threadShare']> => ({
+ messageId: 'reply-x', threadRootId: 'u1', status: 'available', authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满',
+ sharedByAuthor: false, content: '服务器上的原文', attachments: [], createdAt: 1_700_000_000_000, edited: false, ...overrides });
+ beforeEach(() => { vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }); });
+
+ it('shows a loading placeholder, never the card text, while the reply is read', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [
+ msg({ id: 's1', authorKind: 'user', isSelf: false, authorName: 'Alice', content: '↪ 冒充: 卡片文字', threadShare: share({ status: 'loading', authorName: '', content: '' }) }),
+ ] }) });
+ renderView();
+ expect(await screen.findByText(t('loadingSource'))).toBeTruthy();
+ expect(screen.queryByText('↪ 冒充: 卡片文字')).toBeNull();
+ });
+
+ it.each(['unavailable', 'available'] as const)('keeps a %s share as a quote when it is the thread root', async status => {
+ const root = msg({ id: 's1', authorKind: 'user', isSelf: false, authorName: 'Alice', content: '↪ 冒充: 卡片文字', replyCount: 1,
+ threadShare: share(status === 'available'
+ ? { attachments: [{ id: 'f1', name: '路线.pdf', category: 'file', mimeType: 'application/pdf', size: 1, url: null, path: '/tmp/路线.pdf' }] }
+ : { status: 'unavailable', authorName: '', content: '' }) });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [root] }) });
+ mocks.thread.mockResolvedValue({ ok: true, root, replies: [], hasMore: false });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.replyCount' }));
+ const panel = await screen.findByRole('complementary');
+ await waitFor(() => expect(within(panel).getAllByRole('figure').length).toBe(1));
+ expect(within(panel).queryByText('↪ 冒充: 卡片文字')).toBeNull();
+ if (status === 'available') {
+ expect(within(panel).getByText('服务器上的原文')).toBeTruthy();
+ expect(within(panel).getByText('路线.pdf')).toBeTruthy();
+ } else expect(within(panel).getByText(t('sourceUnavailable'))).toBeTruthy();
+ });
+
+ it('keeps the share it got back and says when that share is on an older page', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: '去哪玩' })] }) });
+ mocks.thread.mockResolvedValue({ ok: true, root: msg({ id: 'u1', content: '去哪玩' }), hasMore: false,
+ replies: [msg({ id: 'alice-reply', authorKind: 'user', isSelf: false, authorName: 'Alice', content: 'Alice says hi' })] });
+ mocks.shareToMain.mockResolvedValue({ ok: true, messageId: 'old-share', alreadyShared: false });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.reply' }));
+ const reply = (await within(await screen.findByRole('complementary')).findByText('Alice says hi')).closest('article')!;
+ fireEvent.pointerDown(within(reply).getByRole('button', { name: 'chat.messageActionBar.moreActions' }), { button: 0, ctrlKey: false });
+ await user.click(await screen.findByRole('menuitem', { name: t('postToMain') }));
+ const badge = await within(reply).findByRole('button', { name: t('postedBySelf') });
+ expect((badge as HTMLButtonElement).disabled).toBe(false);
+ await user.click(badge);
+ expect(mocks.toastInfo).toHaveBeenCalledWith(t('shareNotLoaded'));
+ fireEvent.pointerDown(within(reply).getByRole('button', { name: 'chat.messageActionBar.moreActions' }), { button: 0, ctrlKey: false });
+ expect(await screen.findByRole('menuitem', { name: t('viewInMain') })).toBeTruthy();
+ });
+
+ it('keeps every failed main-chat copy retryable, across switching threads', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: 'A' }), msg({ id: 'u2', sequence: 2, content: 'B' })] }) });
+ mocks.reply.mockResolvedValueOnce({ ok: true, messageId: 'first' }).mockResolvedValueOnce({ ok: true, messageId: 'second' });
+ mocks.shareToMain.mockResolvedValue({ ok: false, errorCode: 'SERVICE_ERROR' });
+ const user = userEvent.setup();
+ renderView();
+ const [first, second] = await screen.findAllByRole('button', { name: 'bots.groupChat.server.reply' });
+ await user.click(first!);
+ let panel = await screen.findByRole('complementary');
+ for (const text of ['one', 'two']) {
+ await user.click(within(panel).getByRole('checkbox', { name: t('alsoSend') }));
+ await user.type(within(panel).getByRole('textbox'), `${text}{Enter}`);
+ await waitFor(() => expect(mocks.shareToMain).toHaveBeenCalledWith({ groupId: 'g1', messageId: text === 'one' ? 'first' : 'second' }));
+ }
+ await within(panel).findByRole('button', { name: t('retryPost') });
+ await user.click(second!);
+ await screen.findByText('Reply to u2');
+ expect(within(screen.getByRole('complementary')).queryByRole('button', { name: t('retryPost') })).toBeNull();
+ await user.click(first!);
+ panel = await screen.findByRole('complementary');
+ const retry = await within(panel).findByRole('button', { name: t('retryPost') });
+ mocks.shareToMain.mockClear().mockResolvedValue({ ok: true, messageId: 'share', alreadyShared: false });
+ await user.click(retry);
+ await waitFor(() => expect(within(panel).queryByRole('button', { name: t('retryPost') })).toBeNull());
+ expect(mocks.shareToMain.mock.calls.map(([input]) => input.messageId)).toEqual(['first', 'second']);
+ expect(mocks.reply).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 8509bb3f22..626dcd0036 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9151,7 +9151,10 @@
"postedBySelf": "You posted this to the main chat",
"postedToMain": "Posted to the main chat",
"alsoSend": "Also send to main chat",
- "alsoSendFailed": "Your reply is in the thread, but it couldn't be sent to the main chat.",
+ "alsoSendFailed_one": "Your reply is in the thread, but it couldn't be sent to the main chat.",
+ "alsoSendFailed_other": "{{count}} replies are in the thread, but they couldn't be sent to the main chat.",
+ "loadingSource": "Loading the original reply…",
+ "shareNotLoaded": "This share is further back in the main chat. Load earlier messages to see it.",
"retryPost": "Send to main chat again",
"alreadyPosted": "You've already posted this reply to the main chat.",
"shareUnavailable": "This reply was deleted or isn't available, so it can't be posted to the main chat."
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 18980cdafa..c2550c4a1a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9114,7 +9114,10 @@
"postedBySelf": "あなたがメインチャットに投稿済み",
"postedToMain": "メインチャットに投稿済み",
"alsoSend": "メインチャットにも送信",
- "alsoSendFailed": "返信はスレッドに送信されましたが、メインチャットには送信できませんでした。",
+ "alsoSendFailed_one": "返信はスレッドに送信されましたが、メインチャットには送信できませんでした。",
+ "alsoSendFailed_other": "{{count}} 件の返信はスレッドに送信されましたが、メインチャットには送信できませんでした。",
+ "loadingSource": "元の返信を読み込んでいます…",
+ "shareNotLoaded": "この共有はメインチャットの以前のメッセージにあります。さらに読み込むと表示されます。",
"retryPost": "メインチャットに再送信",
"alreadyPosted": "この返信はすでにメインチャットに投稿しています。",
"shareUnavailable": "この返信は削除されたか表示できないため、メインチャットに投稿できません。"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1a89373f0a..a6f8f7a495 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9114,7 +9114,10 @@
"postedBySelf": "내가 메인 채팅에 올림",
"postedToMain": "메인 채팅에 올라감",
"alsoSend": "메인 채팅에도 보내기",
- "alsoSendFailed": "답글은 스레드에 보냈지만 메인 채팅에는 보내지 못했습니다.",
+ "alsoSendFailed_one": "답글은 스레드에 보냈지만 메인 채팅에는 보내지 못했습니다.",
+ "alsoSendFailed_other": "답글 {{count}}개를 스레드에 보냈지만 메인 채팅에는 보내지 못했습니다.",
+ "loadingSource": "원래 답글을 불러오는 중…",
+ "shareNotLoaded": "이 공유는 메인 채팅의 이전 메시지에 있습니다. 이전 메시지를 불러오면 볼 수 있습니다.",
"retryPost": "메인 채팅에 다시 보내기",
"alreadyPosted": "이 답글은 이미 메인 채팅에 올렸습니다.",
"shareUnavailable": "이 답글은 삭제되었거나 볼 수 없어 메인 채팅에 올릴 수 없습니다."
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 8915d89ecb..e9138d8c76 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9114,7 +9114,10 @@
"postedBySelf": "你已贴到群聊",
"postedToMain": "已贴到群聊",
"alsoSend": "同时发到群聊",
- "alsoSendFailed": "回复已发到话题,但没能同时发到群聊。",
+ "alsoSendFailed_one": "回复已发到话题,但没能同时发到群聊。",
+ "alsoSendFailed_other": "有 {{count}} 条回复已发到话题,但没能同时发到群聊。",
+ "loadingSource": "正在读取原回复…",
+ "shareNotLoaded": "这条贴回在更早的群聊记录里,往上加载后可以看到。",
"retryPost": "重新发到群聊",
"alreadyPosted": "你已经把这条回复贴到群聊了",
"shareUnavailable": "这条回复已删除或无法查看,不能贴到群聊。"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 928616b17f..a22484b353 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9114,7 +9114,10 @@
"postedBySelf": "你已貼到群聊",
"postedToMain": "已貼到群聊",
"alsoSend": "同時發到群聊",
- "alsoSendFailed": "回覆已發到話題,但沒能同時發到群聊。",
+ "alsoSendFailed_one": "回覆已發到話題,但沒能同時發到群聊。",
+ "alsoSendFailed_other": "有 {{count}} 則回覆已發到話題,但沒能同時發到群聊。",
+ "loadingSource": "正在讀取原回覆…",
+ "shareNotLoaded": "這則貼回在更早的群聊記錄裡,往上載入後可以看到。",
"retryPost": "重新發到群聊",
"alreadyPosted": "你已經把這則回覆貼到群聊了",
"shareUnavailable": "這則回覆已刪除或無法查看,不能貼到群聊。"
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 11798ee935..22e37b12bf 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -461,20 +461,27 @@ Desktop 主聊天直接展示话题里的最新回复,并能把话题回复贴
- **最近回复预览**:有回复的根消息下方显示最新 2 条回复(作者、单行摘要),以及回复数和最后回复时间。整张卡片是打开话题的按钮,键盘可达;
工具栏回复按钮不再重复显示数字。长文字截成单行;只有附件的回复显示「图片/文件 · 文件名」;已删除的回复不进入预览,与回复数口径一致。
预览先用房间快照里已有的最新 100 条消息(含所有话题回复),活跃话题不额外请求;只有最新回复早于这个窗口的话题,才按根消息读一页不超过 6 条,
- 并缓存到回复数变化或其中某条被编辑、删除为止。读取失败只让该话题暂时只显示数量,30 秒后再试,不阻断群页面。
+ 遇到已删除回复占位时向前再读,最多 4 页。这些读取在后台进行,不拖住群页面:先显示数量,读完后刷新一次。
+ 结果缓存到回复数变化,或其中某条被编辑、删除为止;读取失败就先只显示数量,30 秒后再试。
- **同时发到主聊天**:话题输入框有「同时发到群聊」,默认不选、每次发送后恢复默认、切换话题不继承。先发话题回复,成功后再贴回主聊天;
- 贴回失败时回复保留在话题里,显示「重新发到群聊」,重试只重做贴回这一步,不重发回复。回复失败时重试沿用原 `clientId`,回复送达前不会贴回。
+ 贴回失败时回复保留在话题里,显示「重新发到群聊」,重试只重做贴回这一步,不重发回复。多条失败一起列出,
+ 按群和话题保存在本次运行中,切换话题再回来仍可重试。回复失败时重试沿用原 `clientId`,回复送达前不会贴回。
- **贴回已有回复**:话题里每条回复(包括别人和伙伴的)在「更多」菜单里有「贴回群聊」。已贴过的回复显示「已贴到群聊」,点了回到主聊天里那条;
- 自己贴过的,菜单变为「在群聊中查看」。
+ 自己贴过的,菜单变为「在群聊中查看」。贴回接口返回的消息 ID 会保留下来;那条贴回在主群更早的记录里、还没加载时,会提示往上加载。
+ 主群未加载到的历史贴回,需要服务端提供按回复查询的索引才能显示状态;在此之前,重复贴回仍由服务端幂等去重。
- **持久化引用**:贴回是由分享者在主聊天发的一条新消息,内容只有一个 `cindy.thread-share` 卡片(revision 1),`data` 仅含 `messageId` 与
`threadRootId`。客户端渲染时按 ID 读取服务器上这条回复的当前版本,原作者、正文和附件都来自服务器,卡片里的文字只是旧客户端的回退显示,
- 不能借卡片冒充原作者。目标已删除、读者无权查看、或 ID 与所属话题不一致时,显示「原回复已删除,或你无权查看」。原回复留在话题里不移动;
+ 不能借卡片冒充原作者。来源在后台读取,读取中显示「正在读取原回复…」。目标已删除、读者无权查看(服务器返回 404/403)、
+ 或 ID 与所属话题不一致时,显示「原回复已删除,或你无权查看」。新版客户端在任何状态下都不显示卡片的回退文字,复制也不会带出这段文字;
+ 贴回消息自己成为话题根时,话题面板里用同一个引用块展示,附件也一起显示。原回复留在话题里不移动;
原回复被编辑后显示新内容并标「已编辑」。界面区分分享者与原作者:分享者是消息作者,引用块内是原作者;自己发回自己的回复显示「回复了话题,也发到了群聊」。
引用块里的「查看话题」打开原话题并定位、高亮那条回复(必要时向前读最多 5 页)。
- **去重**:每个人对每条回复只有一个固定的 `operationId`(`thread-share:<回复 ID>`),重试和重复点击都由服务端操作幂等返回同一条消息;
原回复改过后再贴,服务端返回 `OPERATION_CONFLICT`,显示为「已经贴过」,不再发第二条。不同的人分别贴同一条回复是各自的分享。
- **不重复唤起伙伴**:贴回消息的 `mentions` 只含分享者本人。服务端定向消息从不放宽到其他人,所以不会启动伙伴回合,引用里的 @ 也不会再点名任何人;
新回复本身的 @ 按原规则只在话题里生效一次。「继续讨论」不会把贴回消息当作新请求。伙伴读到群历史时,贴回消息带 `sharedReplyId`,并被说明为引用、不是新请求。
+- **更早页面**:「查看更早的消息」加载的页面不随推送刷新,这与这些页面上普通消息的编辑、删除、表情和回复数一致,是现有限制;
+ 重新打开群聊时会按服务器当前状态重新读取。要让旧页面跟着实时刷新,需要另做一套旧页面同步,不在本功能范围内。
- **兼容与边界**:只新增可选字段 `threadPreview`、`threadShare` 与 Desktop 专用 IPC `maker:chat-server:shareToMain`,不进入设备互联白名单。
旧客户端与手机直连页把贴回消息显示为卡片的回退文字「↪ 原作者: 摘要」;手机直连页暂无话题功能。
- **服务端缺口**:Chat Server 目前没有“不启动执行”的发帖字段,`deferExecution` 只是推迟 2 分钟。本功能依赖“定向消息不放宽”的现有不变量;
diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.ts
index acb79d114e..9c435b5ef6 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -235,8 +235,11 @@ export interface BotGroupThreadShareView {
messageId: string;
/** The thread the reply stays in; sharing never moves it. */
threadRootId: string;
- /** `unavailable`: deleted, outside this reader's history, or not a reply in `threadRootId`. */
- status: 'available' | 'unavailable';
+ /**
+ * `loading`: the reply is still being read. `unavailable`: deleted, outside this reader's
+ * history, or not a reply in `threadRootId`. Neither shows the card's fallback text.
+ */
+ status: 'available' | 'loading' | 'unavailable';
authorKind: BotGroupAuthorKind;
authorBotId: string | null;
authorName: string;