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): 旧页贴回随原回复更新,侧栏不引用卡片,失败读取自动退避重试

Dash12247318d282
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 e16d3396a9..2c8521e5a0 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -1347,6 +1347,63 @@ describe('Chat Server result delivery and refresh', () => {
expect(JSON.stringify(view)).not.toContain('forged words');
});
+ it('names the sharer in the sidebar and never quotes or resolves the card', async () => {
+ const forged = msg('90000000-0000-4000-8000-00000000000c', 20, aliceId, { content: shareCard(botReply) });
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route === '/conversations?limit=100') return { body: [room(roomId)] };
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [forged, ...replies, root], cursor: '20' } };
+ return threadResponse(route, method, body);
+ });
+ const result = await service.listGroups();
+ if (!result.ok) throw new Error('Expected groups');
+ expect(result.groups[0]!.lastMessage).toMatchObject({ preview: '', threadShare: true, authorName: 'Alice' });
+ expect(JSON.stringify(result.groups)).not.toContain('forged words');
+ // The sidebar costs no per-group share or thread reads.
+ await vi.advanceTimersByTimeAsync(0);
+ expect(fixture.handle.mock.calls.filter(([route]) => route.includes('threadRootId=') || /\/messages\/[0-9a-f-]{36}$/.test(route))).toHaveLength(0);
+ });
+
+ it('updates shares shown on older pages after an edit, a deletion or lost access, without a reload', async () => {
+ const outside = '70000000-0000-4000-8000-00000000000d';
+ const ref = { id: '90000000-0000-4000-8000-00000000000d', messageId: outside, threadRootId: rootId, sharerId: aliceId };
+ let source: Record<string, unknown> | null = msg(outside, 1, aliceId, { threadRootId: rootId, content: [{ type: 'text', text: 'v1' }] });
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [root], cursor: '9' } };
+ if (route.startsWith(`/conversations/${roomId}/messages?limit=`)) return { body: [root] };
+ if (route.endsWith(`/messages/${outside}`)) return source ? { body: source } : { status: 404, body: { error: { code: 'MESSAGE_NOT_FOUND' } } };
+ return threadResponse(route, method, body);
+ });
+ const read = async () => {
+ const result = await service.getGroup(roomId, { shownShares: [ref] });
+ if (!result.ok) throw new Error('Expected group');
+ return result.group.threadShareUpdates![ref.id]!;
+ };
+ const settle = async () => { await read(); await vi.advanceTimersByTimeAsync(0); return read(); };
+ expect(await read()).toMatchObject({ status: 'loading', content: '' });
+ vi.mocked(deps.onChanged!).mockClear();
+ await vi.advanceTimersByTimeAsync(0);
+ // The background read asks the open page to refresh: no click or reopen needed.
+ expect(deps.onChanged).toHaveBeenCalledWith({ groupId: roomId, change: 'messages' }, undefined);
+ expect(await read()).toMatchObject({ status: 'available', content: 'v1', sharedByAuthor: true, edited: false });
+ await vi.advanceTimersByTimeAsync(2000);
+ const socket = fixture.sockets.at(-1)!;
+ source = { ...source, revision: 2, content: [{ type: 'text', text: 'v2' }] };
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '10', changes: [{ type: 'message.updated', entityId: outside }] }));
+ expect(await settle()).toMatchObject({ status: 'available', content: 'v2', edited: true });
+ source = { ...source, deleted: true, content: [] };
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '11', changes: [{ type: 'message.deleted', entityId: outside }] }));
+ expect(await settle()).toMatchObject({ status: 'unavailable', content: '' });
+ // Back to visible, then the reader loses access: the old text must not come back.
+ source = msg(outside, 1, aliceId, { threadRootId: rootId, content: [{ type: 'text', text: 'v3' }] });
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '12', changes: [{ type: 'message.updated', entityId: outside }] }));
+ expect(await settle()).toMatchObject({ status: 'available', content: 'v3' });
+ socket.emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'FORBIDDEN' } }));
+ source = null;
+ expect(await read()).not.toMatchObject({ content: 'v3' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(await read()).toMatchObject({ status: 'unavailable', content: '' });
+ });
+
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 b88c862f26..78fe84efc9 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts
@@ -227,3 +227,59 @@ describe('reply summaries', () => {
expect(isShareableThreadReply(reply('n', rootA, { content: [{ type: 'card', namespace: 'cindy.group-notice', fallback: 'x' }] }))).toBe(false);
});
});
+
+describe('recovering from a failed read in a quiet room', () => {
+ const sourceId = '40000000-0000-4000-8000-000000000001';
+ const share = message({ id: 's1', content: [buildBotGroupThreadShareCard({ messageId: sourceId, threadRootId: rootA, authorName: 'Miao', text: 'hi' })] });
+ beforeEach(() => vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }));
+ afterEach(() => vi.useRealTimers());
+
+ it('asks for one more read after the backoff even when nothing else happens', async () => {
+ const io = makeIo();
+ const projection = createThreadProjection(io);
+ io.message.mockRejectedValueOnce(new Error('offline')).mockResolvedValue(reply(sourceId, rootA));
+ // The adapter answers `filled` by reading again, like a push would.
+ io.filled.mockImplementation(() => { projection.shareSources(room, [share], []); });
+ projection.shareSources(room, [share], []);
+ await projection.settled();
+ expect(io.filled).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(29_000);
+ expect(io.message).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1_000);
+ await projection.settled();
+ expect(io.message).toHaveBeenCalledTimes(2);
+ expect(projection.shareSources(room, [share], []).get(sourceId)?.id).toBe(sourceId);
+ });
+
+ it('backs off and stops retrying by itself after a bounded number of attempts', async () => {
+ const io = makeIo();
+ const projection = createThreadProjection(io);
+ io.threadPage.mockRejectedValue(new Error('offline'));
+ const root = message({ id: rootB, replyCount: 1 });
+ io.filled.mockImplementation(() => { projection.previews(room, [root], fullWindow([])); });
+ projection.previews(room, [root], fullWindow([]));
+ await projection.settled();
+ const gaps: number[] = [];
+ let last = Date.now();
+ for (let step = 0; step < 40; step += 1) {
+ const before = io.threadPage.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(30_000);
+ await projection.settled();
+ if (io.threadPage.mock.calls.length > before) { gaps.push(Date.now() - last); last = Date.now(); }
+ }
+ // 5 automatic retries with doubling gaps, then it waits for a push or a reopen.
+ expect(io.threadPage).toHaveBeenCalledTimes(6);
+ expect(gaps).toEqual([30_000, 60_000, 120_000, 240_000, 480_000]);
+ });
+
+ it.each(['dispose', 'reset'] as const)('cancels a pending retry on %s', async (stop) => {
+ const io = makeIo();
+ const projection = createThreadProjection(io);
+ io.message.mockRejectedValue(new Error('offline'));
+ projection.shareSources(room, [share], []);
+ await projection.settled();
+ projection[stop]();
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(io.filled).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index cb908266d1..33572e20e8 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -30,7 +30,8 @@ import {
isBotGroupRuntimeFailureCode, type BotGroupRuntimeFailureCode,
readImportedBotGroupRuntimeFailureCode,
readBotGroupExecutionFailure, type BotGroupExecutionFailureView,
- buildBotGroupThreadShareCard, botGroupThreadShareOperationId, readBotGroupThreadShareCard,
+ buildBotGroupThreadShareCard, botGroupThreadShareOperationId, readBotGroupThreadShareCard, BOT_GROUP_SHOWN_SHARES_MAX,
+ type BotGroupThreadShareView,
type BotGroupDetail, type BotGroupPlanView, type BotGroupFailure, type BotGroupMessageView, type BotGroupAttachment, type ChatServerApi,
} from '../../shared/botGroupChat.js';
import type { BotGroupChatService, BotGroupChatServiceDeps, BotGroupLaneTerminal } from './botGroupChatService.js';
@@ -565,11 +566,23 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
* 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) {
+ async function decorateThreads(roomId: string, views: BotGroupMessageView[], page: Message[], snapshot: Message[], members: Member[], withPreviews: boolean,
+ shownShares: Array<{ id: string; messageId: string; threadRootId: string; sharerId?: string }> = []) {
const previews = withPreviews ? threads.previews(roomId, page, snapshot) : new Map<string, Message[]>();
- const sources = threads.shareSources(roomId, page, [...snapshot, ...page]);
+ const sources = threads.sources(roomId, [...page.flatMap(m => readBotGroupThreadShareCard(m)?.messageId ?? []),
+ ...shownShares.map(share => share.messageId)], [...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 shareView = (card: { messageId: string; threadRootId: string }, sharerId?: string): BotGroupThreadShareView => {
+ const source = sources.get(card.messageId);
+ const resolved = source && source.threadRootId === card.threadRootId ? sourceViews.get(source.id) : undefined;
+ return source && resolved ? {
+ ...card, status: 'available', authorKind: resolved.authorKind, authorBotId: resolved.authorBotId, authorName: resolved.authorName,
+ sharedByAuthor: source.authorId === sharerId, content: resolved.content, attachments: resolved.attachments,
+ createdAt: resolved.createdAt, edited: (source.revision ?? 1) > 1,
+ } : { ...card, status: sources.has(card.messageId) ? 'unavailable' : 'loading', authorKind: 'user', authorBotId: null, authorName: '', sharedByAuthor: false,
+ content: '', attachments: [], createdAt: null, edited: false };
+ };
const byId = new Map(page.map(m => [m.id, m]));
for (const view of views) {
const message = byId.get(view.id);
@@ -582,21 +595,17 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
});
if (replies?.length) view.threadPreview = { replies };
const card = readBotGroupThreadShareCard(message);
- 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: sources.has(card.messageId) ? 'unavailable' : 'loading', authorKind: 'user', authorBotId: null, authorName: '', sharedByAuthor: false,
- content: '', attachments: [], createdAt: null, edited: false };
+ if (card) view.threadShare = shareView(card, message.authorId);
}
+ // Shares on pages loaded earlier. The sharer ID only picks the label; content is the server's.
+ return Object.fromEntries(shownShares.filter(share => !byId.has(share.id)).map(({ id: shareId, sharerId, ...card }) =>
+ [shareId, shareView(card, sharerId && (actors.find(actor => actor.externalId === sharerId)?.id ?? sharerId))]));
}
async function detail(roomId: string, options?: unknown, summaryOnly = false): Promise<BotGroupDetail> {
const s = await snapshot(roomId);
const o = z.object({ beforeSequence: z.number().int().positive().optional(), limit: z.number().int().min(1).max(100).optional(),
- sourceMessageIds: z.array(id).optional() }).parse(options ?? {});
+ sourceMessageIds: z.array(id).optional(),
+ shownShares: z.array(z.object({ id, messageId: id, threadRootId: id, sharerId: z.string().min(1).max(200).optional() })).max(BOT_GROUP_SHOWN_SHARES_MAX).optional() }).parse(options ?? {});
const query = new URLSearchParams({ limit: String(o.limit ?? 100) });
if (o.beforeSequence) query.set('before', String(o.beforeSequence));
const page = summaryOnly ? s.messages : await api<Message[]>(`/conversations/${roomId}/messages?${query}`);
@@ -612,12 +621,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
}));
// Sidebar refresh must not download every attachment in every group's history.
const messages = summaryOnly ? [] : await messageViews(roomId, page, s.members);
- if (!summaryOnly) {
- await decorateThreads(roomId, messages, page, s.messages, s.members, true);
- messages.sort((a, b) => a.sequence - b.sequence);
- }
+ const threadShareUpdates = summaryOnly ? undefined : await decorateThreads(roomId, messages, page, s.messages, s.members, true, o.shownShares);
+ messages.sort((a, b) => a.sequence - b.sequence);
const last = s.messages[0];
const lastView = last ? messageView(last, s.members) : null;
+ // The sidebar never resolves shares: it names the sharer and never quotes the card's text.
+ const lastIsShare = !!last && !!readBotGroupThreadShareCard(last);
return { serverBacked: true, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), id: s.room.id, name: s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,
members: s.members.filter(m => m.state === 'joined').map(m => {
const p = localBot(m.id);
@@ -628,12 +637,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
name: memberName(m), avatar: p?.avatar ?? (m.avatar?.startsWith('https://') ? '' : m.avatar) ?? '', avatarColor: p?.avatarColor ?? 'violet', status: p?.status ?? 'active' };
}), organizerBotId: s.room.organizer_id ? localBot(s.room.organizer_id)?.id ?? s.room.organizer_id : s.members.find(m => m.kind === 'bot' && m.state === 'joined')?.id ?? null, projectDir: workspace?.projectDir ?? null, lastMessage: lastView ? {
isSelf: lastView.isSelf, authorKind: lastView.authorKind, authorName: lastView.authorName, noticeCode: lastView.noticeCode,
- preview: lastView.content.slice(0, 80), createdAt: lastView.createdAt,
+ preview: lastIsShare ? '' : lastView.content.slice(0, 80), createdAt: lastView.createdAt, ...(lastIsShare ? { threadShare: true } : {}),
} : null, speakingBotIds: speakers.map(s => s.botId), planningBotId: planning.get(roomId)?.botId ?? null, openPlan: open ? { id: open.id, status: open.status, currentStep: open.currentStep, stepCount: open.steps.length, currentBotName: open.steps[open.currentStep ?? 0]?.botName ?? null, currentStepStatus: open.steps[open.currentStep ?? 0]?.status ?? null } : null,
lastReplyAt: s.messages.reduce((latest, m) => !m.deleted && m.origin !== 'system' && m.authorId !== selfId
? Math.max(latest, Date.parse(m.createdAt)) : latest, 0),
createdAt: Date.parse(s.room.created_at), updatedAt: Date.parse(s.room.updated_at ?? s.room.created_at),
- messages, executionFailures, hasMoreBefore: page.length === (o.limit ?? 100), plans,
+ messages, executionFailures, ...(threadShareUpdates && Object.keys(threadShareUpdates).length ? { threadShareUpdates } : {}), hasMoreBefore: page.length === (o.limit ?? 100), plans,
round: { status: executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers, canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id && ordinaryExecution(e)) || s.messages.some(discussionSource)) && !executions.some(e => ['queued','running','stopping'].includes(e.status)) } };
}
function planView(plan: ServerPlan, members: Member[], workspace: ReturnType<ReturnType<typeof chatServerWorkspaces>['read']>): BotGroupPlanView {
@@ -1407,7 +1416,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
continuePlan: input => safe(() => actPlan(input, 'continue')), retryPlan: input => safe(() => actPlan(input, 'retry')),
editPlanStep: input => safe(() => actPlan(input, 'reassign')),
dispose: () => {
- disposed = true; clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); socket?.close();
+ disposed = true; threads.dispose(); clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); socket?.close();
for (const run of running.values()) {
run.releaseToolAuthority?.();
if (run.sessionId) void deps.abortLane(run.sessionId).catch(() => undefined);
diff --git a/apps/desktop/src/main/maker-ipc/chatServerThreads.ts b/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
index d737df8c7a..fc1c6d22f7 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
@@ -19,8 +19,9 @@ export interface ThreadMessage {
/** Concurrent reads per refresh; the rest wait for a slot rather than fan out. */
const READ_CONCURRENCY = 6;
-/** A failed read is retried on a later refresh, not on every push. */
+/** A failed read backs off from this delay, doubling, and retries on its own a few times. */
const RETRY_MS = 30_000;
+const RETRY_ATTEMPTS = 5;
/** 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. */
@@ -51,6 +52,27 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
const retryAt = new Map<string, number>();
const inFlight = new Set<string>();
const settling = new Set<Promise<void>>();
+ const failures = new Map<string, number>();
+ // One pending wake-up per room: a quiet room still recovers from a transient failure.
+ const retryTimers = new Map<string, { at: number; timer: ReturnType<typeof setTimeout> }>();
+ function scheduleRetry(roomId: string, cacheKey: string) {
+ const attempt = (failures.get(cacheKey) ?? 0) + 1;
+ failures.set(cacheKey, attempt);
+ const at = Date.now() + RETRY_MS * 2 ** Math.min(attempt - 1, RETRY_ATTEMPTS - 1);
+ retryAt.set(cacheKey, at);
+ // After the last automatic attempt only a later read (a push or reopening) retries.
+ if (attempt > RETRY_ATTEMPTS) return;
+ const pending = retryTimers.get(roomId);
+ if (pending && pending.at <= at) return;
+ if (pending) clearTimeout(pending.timer);
+ const timer = setTimeout(() => { retryTimers.delete(roomId); io.filled(roomId); }, at - Date.now());
+ timer.unref?.();
+ retryTimers.set(roomId, { at, timer });
+ }
+ function cancelRetries() {
+ for (const { timer } of retryTimers.values()) clearTimeout(timer);
+ retryTimers.clear(); failures.clear();
+ }
// 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}`;
@@ -65,10 +87,10 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
await eachLimited(items, async ({ cacheKey, item }) => {
try {
const store = await read(item);
- retryAt.delete(cacheKey);
+ retryAt.delete(cacheKey); failures.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); }
+ } catch { if (generation === started) scheduleRetry(roomId, cacheKey); }
finally { inFlight.delete(cacheKey); }
});
if (wrote) io.filled(roomId);
@@ -124,16 +146,19 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
* not see it, or absent while it is still being read.
*/
shareSources(roomId: string, page: readonly M[], known: readonly M[]): Map<string, M | null> {
+ return this.sources(roomId, page.flatMap(message => readBotGroupThreadShareCard(message)?.messageId ?? []), known);
+ },
+ /** The same lookup by reply ID, for shares the reader already has on screen. */
+ sources(roomId: string, messageIds: readonly string[], 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 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.set(card.messageId, { cacheKey, item: card.messageId });
+ for (const messageId of messageIds) {
+ if (result.has(messageId)) continue;
+ const cacheKey = key(roomId, messageId);
+ if (fresh.has(messageId)) result.set(messageId, fresh.get(messageId)!);
+ else if (sources.has(cacheKey)) result.set(messageId, sources.get(cacheKey)!);
+ else if (!waiting(cacheKey)) missing.set(messageId, { cacheKey, item: messageId });
}
fill(roomId, [...missing.values()], async messageId => {
const value = await io.message(roomId, messageId);
@@ -149,7 +174,9 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
if (cacheKey.startsWith(`${roomId}:`) && entry.replies.some(reply => reply.id === messageId)) previews.delete(cacheKey);
},
/** Pushes may have been missed while disconnected. */
- reset() { generation += 1; previews.clear(); sources.clear(); retryAt.clear(); },
+ reset() { generation += 1; previews.clear(); sources.clear(); retryAt.clear(); cancelRetries(); },
+ /** The adapter is gone (account switch or quit): no wake-up may outlive it. */
+ dispose() { generation += 1; cancelRetries(); },
/** 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 2e733d3359..4573ee92b6 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -69,7 +69,7 @@ import { animateThreadPanelWidth, ChatThreadPanel } from './ChatThreadPanel';
import { BotGroupThreadPreview, BotGroupThreadShareQuote, botGroupThreadShareLabel, findThreadMessageElement, flashThreadTarget } from './BotGroupThreadViews';
import { BotGroupPendingInteraction } from './BotGroupPendingInteraction';
import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';
-import { isBotGroupRuntimeFailureCode } from '../../../shared/botGroupChat';
+import { BOT_GROUP_SHOWN_SHARES_MAX, isBotGroupRuntimeFailureCode } from '../../../shared/botGroupChat';
import {
BotGroupHandoffFiles,
BotGroupOrganizerTag,
@@ -188,15 +188,20 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
}
try {
const displayed = stateRef.current;
- const sourceMessageIds = [...new Set([...(displayed.kind === 'ready' && displayed.group.id === groupId
+ const shown = displayed.kind === 'ready' && displayed.group.id === groupId;
+ const sourceMessageIds = [...new Set([...(shown
? mergeBotGroupMessages(displayed.older, displayed.group.messages).map(message => message.id) : []), ...additionalSources])];
- const result = sourceMessageIds.length ? await api.getBotGroup(groupId, { sourceMessageIds }) : await api.getBotGroup(groupId);
+ // Older pages are not re-read, so their shares ask for the reply's current state.
+ const shownShares = shown ? botGroupShownShares(displayed.older) : [];
+ const result = sourceMessageIds.length || shownShares.length
+ ? await api.getBotGroup(groupId, { sourceMessageIds, ...(shownShares.length ? { shownShares } : {}) })
+ : await api.getBotGroup(groupId);
if (!isCurrent()) return;
if (result.ok) {
readOwner.current = owner;
setState((previous) =>
previous.kind === 'ready'
- ? { ...previous, group: result.group }
+ ? { ...previous, group: result.group, older: applyBotGroupThreadShareUpdates(previous.older, result.group.threadShareUpdates) }
: {
kind: 'ready',
group: result.group,
@@ -790,6 +795,26 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
);
}
+/** Shares on older pages, newest kept when there are more than one refresh re-reads. */
+function botGroupShownShares(older: readonly BotGroupMessageView[]) {
+ return older.flatMap(message => message.threadShare
+ ? [{ id: message.id, messageId: message.threadShare.messageId, threadRootId: message.threadShare.threadRootId,
+ ...(message.authorBotId ? { sharerId: message.authorBotId } : {}) }] : [])
+ .slice(-BOT_GROUP_SHOWN_SHARES_MAX);
+}
+
+function applyBotGroupThreadShareUpdates(older: BotGroupMessageView[], updates: BotGroupDetail['threadShareUpdates']) {
+ if (!updates) return older;
+ let changed = false;
+ const next = older.map(message => {
+ const update = updates[message.id];
+ if (!update || !message.threadShare) return message;
+ changed = true;
+ return { ...message, threadShare: update };
+ });
+ return changed ? next : older;
+}
+
function planCardPending(action: PlanPending['action'] | null): BotGroupPlanCardAction | null {
return action === 'start' || action === 'dismiss' || action === 'edit' ? action : null;
}
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
index b9e27e5a58..8025653bea 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
@@ -79,6 +79,12 @@ export function BotGroupSidebarRow({
const key = botGroupNoticeKey(last.noticeCode ?? null, false);
return key ? t(key, { name: last.authorName }) : botGroupPreviewLine(last.preview);
}
+ // A share names who posted it; the card's own text is never quoted here.
+ if (last.threadShare) {
+ return last.authorKind === 'user' && last.isSelf !== false
+ ? t('bots.groupChat.sidebar.sharedReplyYou')
+ : t('bots.groupChat.sidebar.sharedReply', { name: last.authorName.trim() });
+ }
const text = botGroupPreviewLine(last.preview);
if (last.authorKind === 'user' && last.isSelf !== false) return t('bots.groupChat.sidebar.previewYou', { text });
if (last.authorName.trim()) {
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 637e3a882b..382e7cf69d 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -1923,3 +1923,29 @@ describe('thread share follow-ups', () => {
expect(mocks.reply).toHaveBeenCalledTimes(2);
});
});
+
+describe('shares on older pages', () => {
+ const t = (name: string) => `bots.groupChat.server.thread.${name}`;
+ beforeEach(() => { vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }); });
+
+ it('follows the reply after an edit or deletion without a click or reopen', async () => {
+ const oldShare = msg({ id: 'old-share', sequence: 1, authorKind: 'user', isSelf: false, authorBotId: 'alice-actor', authorName: 'Alice', content: '↪ 冒充: 卡片文字',
+ threadShare: { messageId: 'old-reply', threadRootId: 'old-root', status: 'available', authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满',
+ sharedByAuthor: false, content: '加载时的原文', attachments: [], createdAt: 1, edited: false } });
+ const latest = detail({ serverBacked: true, hasMoreBefore: true, messages: [msg({ id: 'new', sequence: 50, content: '最新' })] });
+ mocks.getBotGroup
+ .mockResolvedValueOnce({ ok: true, group: latest })
+ .mockResolvedValueOnce({ ok: true, group: { ...latest, hasMoreBefore: false, messages: [oldShare] } })
+ .mockResolvedValue({ ok: true, group: { ...latest, threadShareUpdates: { 'old-share': { ...oldShare.threadShare!, status: 'unavailable', authorName: '', content: '' } } } });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ expect(await screen.findByText('加载时的原文')).toBeTruthy();
+ act(() => { for (const push of mocks.pushes) push({ groupId: 'g1', change: 'messages' }); });
+ expect(await screen.findByText(t('sourceUnavailable'))).toBeTruthy();
+ expect(screen.queryByText('加载时的原文')).toBeNull();
+ expect(screen.queryByText('↪ 冒充: 卡片文字')).toBeNull();
+ expect(mocks.getBotGroup).toHaveBeenLastCalledWith('g1', expect.objectContaining({
+ shownShares: [{ id: 'old-share', messageId: 'old-reply', threadRootId: 'old-root', sharerId: 'alice-actor' }] }));
+ });
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
index 5ac012815b..50d7c5eea2 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
@@ -349,3 +349,12 @@ it('localizes the join preview without presenting its subject as a chat author',
expect(screen.getByText('bots.groupChat.notice.memberJoined:{"name":"Taylor"}')).toBeTruthy();
expect(screen.queryByText(/Fallback text/)).toBeNull();
});
+
+it.each([[false, 'bots.groupChat.sidebar.sharedReply:{"name":"Alice"}'], [true, 'bots.groupChat.sidebar.sharedReplyYou']] as const)(
+ 'names who shared a thread reply without quoting any card text (self: %s)', async (isSelf, label) => {
+ mocks.groups = [group({ lastMessage: { authorKind: 'user', isSelf, authorName: 'Alice', threadShare: true,
+ preview: '↪ 冒充: 卡片文字', createdAt: 30 } })];
+ await renderSidebar();
+ expect(screen.getByText(label)).toBeTruthy();
+ expect(screen.queryByText(/冒充|卡片文字/)).toBeNull();
+ });
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 626dcd0036..fec524c6bc 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8944,6 +8944,8 @@
"empty": "No messages yet",
"preview": "{{name}}: {{text}}",
"previewYou": "You: {{text}}",
+ "sharedReplyYou": "You shared a thread reply",
+ "sharedReply": "{{name}} shared a thread reply",
"waiting": "Waiting for your go-ahead",
"planProposed": "{{name}}: plan ready, waiting for you to start",
"planProposedAnonymous": "Plan ready, waiting for you to start",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c2550c4a1a..a9210ef893 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8907,6 +8907,8 @@
"empty": "メッセージはまだありません",
"preview": "{{name}}: {{text}}",
"previewYou": "あなた: {{text}}",
+ "sharedReplyYou": "スレッドの返信を共有しました",
+ "sharedReply": "{{name}} がスレッドの返信を共有しました",
"waiting": "確認待ち",
"planProposed": "{{name}}: 計画ができました。開始を待っています",
"planProposedAnonymous": "計画ができました。開始を待っています",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index a6f8f7a495..6db645f0b5 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8907,6 +8907,8 @@
"empty": "아직 메시지가 없습니다",
"preview": "{{name}}: {{text}}",
"previewYou": "나: {{text}}",
+ "sharedReplyYou": "스레드 답글을 공유했습니다",
+ "sharedReply": "{{name}} 님이 스레드 답글을 공유했습니다",
"waiting": "확인 대기 중",
"planProposed": "{{name}}: 계획이 준비됐어요. 시작을 기다리는 중",
"planProposedAnonymous": "계획이 준비됐어요. 시작을 기다리는 중",
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 e9138d8c76..017222abb0 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8907,6 +8907,8 @@
"empty": "还没有消息",
"preview": "{{name}}:{{text}}",
"previewYou": "你:{{text}}",
+ "sharedReplyYou": "你贴回了一条话题回复",
+ "sharedReply": "{{name}} 贴回了一条话题回复",
"waiting": "在等你确认",
"planProposed": "{{name}}:安排好了,等你开始",
"planProposedAnonymous": "安排好了,等你开始",
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 a22484b353..1b9f1eac55 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8907,6 +8907,8 @@
"empty": "還沒有訊息",
"preview": "{{name}}:{{text}}",
"previewYou": "你:{{text}}",
+ "sharedReplyYou": "你貼回了一則話題回覆",
+ "sharedReply": "{{name}} 貼回了一則話題回覆",
"waiting": "在等你確認",
"planProposed": "{{name}}:安排好了,等你開始",
"planProposedAnonymous": "安排好了,等你開始",
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 22e37b12bf..41b911a341 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -462,7 +462,8 @@ Desktop 主聊天直接展示话题里的最新回复,并能把话题回复贴
工具栏回复按钮不再重复显示数字。长文字截成单行;只有附件的回复显示「图片/文件 · 文件名」;已删除的回复不进入预览,与回复数口径一致。
预览先用房间快照里已有的最新 100 条消息(含所有话题回复),活跃话题不额外请求;只有最新回复早于这个窗口的话题,才按根消息读一页不超过 6 条,
遇到已删除回复占位时向前再读,最多 4 页。这些读取在后台进行,不拖住群页面:先显示数量,读完后刷新一次。
- 结果缓存到回复数变化,或其中某条被编辑、删除为止;读取失败就先只显示数量,30 秒后再试。
+ 结果缓存到回复数变化,或其中某条被编辑、删除为止。读取失败时先只显示数量,然后按 30 秒、1、2、4、8 分钟自动重试,
+ 最多 5 次,之后等下一条推送或重新打开群聊;切换账号或退出时取消。
- **同时发到主聊天**:话题输入框有「同时发到群聊」,默认不选、每次发送后恢复默认、切换话题不继承。先发话题回复,成功后再贴回主聊天;
贴回失败时回复保留在话题里,显示「重新发到群聊」,重试只重做贴回这一步,不重发回复。多条失败一起列出,
按群和话题保存在本次运行中,切换话题再回来仍可重试。回复失败时重试沿用原 `clientId`,回复送达前不会贴回。
@@ -480,8 +481,10 @@ Desktop 主聊天直接展示话题里的最新回复,并能把话题回复贴
原回复改过后再贴,服务端返回 `OPERATION_CONFLICT`,显示为「已经贴过」,不再发第二条。不同的人分别贴同一条回复是各自的分享。
- **不重复唤起伙伴**:贴回消息的 `mentions` 只含分享者本人。服务端定向消息从不放宽到其他人,所以不会启动伙伴回合,引用里的 @ 也不会再点名任何人;
新回复本身的 @ 按原规则只在话题里生效一次。「继续讨论」不会把贴回消息当作新请求。伙伴读到群历史时,贴回消息带 `sharedReplyId`,并被说明为引用、不是新请求。
-- **更早页面**:「查看更早的消息」加载的页面不随推送刷新,这与这些页面上普通消息的编辑、删除、表情和回复数一致,是现有限制;
- 重新打开群聊时会按服务器当前状态重新读取。要让旧页面跟着实时刷新,需要另做一套旧页面同步,不在本功能范围内。
+- **更早页面上的贴回**:「查看更早的消息」加载出的贴回卡片会跟着原回复变化。每次刷新时,客户端把已显示的旧卡片(最多 200 张)
+ 交给主进程,按同一套缓存、失效和权限判定重新解析;原回复被编辑后显示新内容,删除或失去查看权限后显示无法查看,不需要点击或重新打开群聊。
+ 旧页面上普通消息的编辑、删除、表情和回复数仍不随推送刷新,这是现有限制,不在本功能范围内。
+- **侧栏**:群的最新一条是贴回时,侧栏只显示「谁贴回了一条话题回复」,不引用卡片里的文字,也不为此读取原回复。
- **兼容与边界**:只新增可选字段 `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 9c435b5ef6..a5d1966d4b 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -347,6 +347,8 @@ export interface BotGroupLastMessage {
noticeCode?: BotGroupNoticeCode | null;
preview: string;
createdAt: number;
+ /** The latest message re-posts a thread reply; `preview` is then empty, never the card's text. */
+ threadShare?: boolean;
}
/** `reply`: answering in the chat; `planning`: the organizer is working out a plan; `step`: doing a plan step. */
@@ -402,6 +404,8 @@ export interface BotGroupDetail extends BotGroupSummary {
messages: BotGroupMessageView[];
/** Authorized current failures, independent of message pagination. Local/older hosts omit this. */
executionFailures?: BotGroupExecutionFailureView[];
+ /** Current state of shares the reader listed in `shownShares`, keyed by the share's message ID. */
+ threadShareUpdates?: Record<string, BotGroupThreadShareView>;
hasMoreBefore: boolean;
round: BotGroupRoundView;
/** Plans referenced by the loaded messages, plus the open plan. */
@@ -503,8 +507,13 @@ export interface BotGroupGetOptions {
limit?: number;
/** Reconcile execution state for real messages already displayed on older pages. */
sourceMessageIds?: string[];
+ /** Shares already shown from older pages, so edits and deletions reach them without a reload. */
+ shownShares?: Array<{ id: string; messageId: string; threadRootId: string; sharerId?: string }>;
}
+/** Older-page shares re-resolved per refresh; later ones wait for a reload. */
+export const BOT_GROUP_SHOWN_SHARES_MAX = 200;
+
export type BotGroupChange = 'created' | 'updated' | 'deleted' | 'messages' | 'round' | 'plan';
export interface BotGroupChangedPayload {