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): 超出单次上限的旧页贴回不再保留旧正文,同群多条失败读取都能重试

Dashb549c13ec3fd
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 2c8521e5a0..d2f635c892 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -1404,6 +1404,26 @@ describe('Chat Server result delivery and refresh', () => {
expect(await read()).toMatchObject({ status: 'unavailable', content: '' });
});
+ it('raises the share version on edits and lost access so unchecked older shares are not trusted', async () => {
+ const version = async () => {
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error('Expected group');
+ return result.group.threadShareVersion!;
+ };
+ const start = await version();
+ await vi.advanceTimersByTimeAsync(2000);
+ const socket = fixture.sockets.at(-1)!;
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '10', changes: [{ type: 'message.deleted', entityId: botReply }] }));
+ const afterDelete = await version();
+ expect(afterDelete).toBeGreaterThan(start);
+ socket.emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'FORBIDDEN' } }));
+ expect(await version()).toBeGreaterThan(afterDelete);
+ // Share views carry the version they were checked at.
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error('Expected group');
+ expect(result.group.messages.find(m => m.id === shares[0]!.id)!.threadShare!.version).toBe(result.group.threadShareVersion);
+ });
+
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 78fe84efc9..85f6039096 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts
@@ -283,3 +283,79 @@ describe('recovering from a failed read in a quiet room', () => {
expect(io.filled).not.toHaveBeenCalled();
});
});
+
+describe('one wake-up per room with several failed reads', () => {
+ beforeEach(() => vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }));
+ afterEach(() => vi.useRealTimers());
+ const idA = '40000000-0000-4000-8000-00000000000a';
+ const idB = '40000000-0000-4000-8000-00000000000b';
+ const card = (id: string, messageId: string) => message({ id, content: [buildBotGroupThreadShareCard({ messageId, threadRootId: rootA, authorName: 'Miao', text: 'hi' })] });
+ const shares = [card('sa', idA), card('sb', idB)];
+
+ it('keeps waking up for a later deadline after an earlier one has recovered', async () => {
+ const io = makeIo();
+ const projection = createThreadProjection(io);
+ const failOnce = new Set([idA, idB]);
+ io.message.mockImplementation(async (_room: string, id: string) => {
+ if (failOnce.delete(id)) throw new Error('offline');
+ return reply(id, rootA);
+ });
+ io.filled.mockImplementation(() => { projection.shareSources(room, shares, []); });
+ projection.shareSources(room, [shares[0]!], []); // A fails at t0 → due t30
+ await projection.settled();
+ await vi.advanceTimersByTimeAsync(5_000);
+ projection.shareSources(room, [shares[1]!], []); // B fails at t5 → due t35
+ await projection.settled();
+ await vi.advanceTimersByTimeAsync(25_000); // t30: A retried and recovered; B not yet due
+ await projection.settled();
+ expect(projection.shareSources(room, shares, []).get(idA)?.id).toBe(idA);
+ expect(projection.shareSources(room, shares, []).has(idB)).toBe(false);
+ await vi.advanceTimersByTimeAsync(5_000); // t35: nothing else happens in the room
+ await projection.settled();
+ expect(projection.shareSources(room, shares, []).get(idB)?.id).toBe(idB);
+ // Both recovered: no further wake-ups.
+ io.filled.mockClear();
+ await vi.advanceTimersByTimeAsync(60 * 60_000);
+ expect(io.filled).not.toHaveBeenCalled();
+ });
+
+ it('keeps each read to its own five automatic retries when failures are staggered', async () => {
+ const io = makeIo();
+ const projection = createThreadProjection(io);
+ let bFailed = false;
+ io.message.mockImplementation(async (_room: string, id: string) => {
+ if (id === idA) throw new Error('offline');
+ if (!bFailed) { bFailed = true; throw new Error('offline'); }
+ return reply(id, rootA);
+ });
+ io.filled.mockImplementation(() => { projection.shareSources(room, shares, []); });
+ projection.shareSources(room, [shares[0]!], []);
+ await projection.settled();
+ await vi.advanceTimersByTimeAsync(5_000);
+ projection.shareSources(room, [shares[1]!], []);
+ await projection.settled();
+ for (let step = 0; step < 200; step += 1) { await vi.advanceTimersByTimeAsync(30_000); await projection.settled(); }
+ const reads = (id: string) => io.message.mock.calls.filter(([, value]) => value === id).length;
+ expect(reads(idA)).toBe(6);
+ expect(reads(idB)).toBe(2);
+ expect(projection.shareSources(room, shares, []).get(idB)?.id).toBe(idB);
+ // A gave up and B recovered: the room has nothing left to wake up for.
+ io.filled.mockClear();
+ await vi.advanceTimersByTimeAsync(24 * 60 * 60_000);
+ expect(io.filled).not.toHaveBeenCalled();
+ });
+
+ it.each(['dispose', 'reset'] as const)('cancels every pending wake-up of the room on %s', async (stop) => {
+ const io = makeIo();
+ const projection = createThreadProjection(io);
+ io.message.mockRejectedValue(new Error('offline'));
+ projection.shareSources(room, [shares[0]!], []);
+ await projection.settled();
+ await vi.advanceTimersByTimeAsync(5_000);
+ projection.shareSources(room, [shares[1]!], []);
+ await projection.settled();
+ projection[stop]();
+ await vi.advanceTimersByTimeAsync(60 * 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 33572e20e8..4d484fe74f 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -568,6 +568,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
*/
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 }> = []) {
+ // Taken before reading, so a change while this read is in progress marks it stale.
+ const version = threads.version();
const previews = withPreviews ? threads.previews(roomId, page, snapshot) : new Map<string, Message[]>();
const sources = threads.sources(roomId, [...page.flatMap(m => readBotGroupThreadShareCard(m)?.messageId ?? []),
...shownShares.map(share => share.messageId)], [...snapshot, ...page]);
@@ -579,9 +581,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
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,
+ createdAt: resolved.createdAt, edited: (source.revision ?? 1) > 1, version,
} : { ...card, status: sources.has(card.messageId) ? 'unavailable' : 'loading', authorKind: 'user', authorBotId: null, authorName: '', sharedByAuthor: false,
- content: '', attachments: [], createdAt: null, edited: false };
+ content: '', attachments: [], createdAt: null, edited: false, version };
};
const byId = new Map(page.map(m => [m.id, m]));
for (const view of views) {
@@ -598,8 +600,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
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))]));
+ return { version, updates: 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);
@@ -621,7 +623,8 @@ 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);
- const threadShareUpdates = summaryOnly ? undefined : await decorateThreads(roomId, messages, page, s.messages, s.members, true, o.shownShares);
+ const shares = summaryOnly ? undefined : await decorateThreads(roomId, messages, page, s.messages, s.members, true, o.shownShares);
+ const threadShareUpdates = shares?.updates;
messages.sort((a, b) => a.sequence - b.sequence);
const last = s.messages[0];
const lastView = last ? messageView(last, s.members) : null;
@@ -642,7 +645,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
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, ...(threadShareUpdates && Object.keys(threadShareUpdates).length ? { threadShareUpdates } : {}), hasMoreBefore: page.length === (o.limit ?? 100), plans,
+ messages, executionFailures, ...(threadShareUpdates && Object.keys(threadShareUpdates).length ? { threadShareUpdates } : {}),
+ ...(shares ? { threadShareVersion: shares.version } : {}), 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 {
diff --git a/apps/desktop/src/main/maker-ipc/chatServerThreads.ts b/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
index fc1c6d22f7..ff8b90dce9 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
@@ -53,8 +53,28 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
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.
+ // One wake-up per room, aimed at the earliest pending retry; after firing it re-arms for
+ // the next one, so a quiet room still recovers every read that failed.
+ const pendingRetries = new Map<string, Map<string, number>>();
const retryTimers = new Map<string, { at: number; timer: ReturnType<typeof setTimeout> }>();
+ function armRetry(roomId: string) {
+ const pending = pendingRetries.get(roomId);
+ const armed = retryTimers.get(roomId);
+ const at = pending?.size ? Math.min(...pending.values()) : undefined;
+ if (armed && armed.at === at) return;
+ if (armed) { clearTimeout(armed.timer); retryTimers.delete(roomId); }
+ if (at === undefined) return;
+ const timer = setTimeout(() => {
+ retryTimers.delete(roomId);
+ let due = false;
+ for (const [cacheKey, deadline] of pending!) if (deadline <= Date.now()) { pending!.delete(cacheKey); due = true; }
+ if (!pending!.size) pendingRetries.delete(roomId);
+ if (due) io.filled(roomId);
+ armRetry(roomId);
+ }, Math.max(0, at - Date.now()));
+ timer.unref?.();
+ retryTimers.set(roomId, { at, timer });
+ }
function scheduleRetry(roomId: string, cacheKey: string) {
const attempt = (failures.get(cacheKey) ?? 0) + 1;
failures.set(cacheKey, attempt);
@@ -62,17 +82,19 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
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 });
+ const pending = pendingRetries.get(roomId) ?? new Map<string, number>();
+ pending.set(cacheKey, at); pendingRetries.set(roomId, pending);
+ armRetry(roomId);
+ }
+ function settledRetry(roomId: string, cacheKey: string) {
+ failures.delete(cacheKey);
+ if (pendingRetries.get(roomId)?.delete(cacheKey)) armRetry(roomId);
}
function cancelRetries() {
for (const { timer } of retryTimers.values()) clearTimeout(timer);
- retryTimers.clear(); failures.clear();
+ retryTimers.clear(); pendingRetries.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}`;
@@ -87,7 +109,7 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
await eachLimited(items, async ({ cacheKey, item }) => {
try {
const store = await read(item);
- retryAt.delete(cacheKey); failures.delete(cacheKey);
+ retryAt.delete(cacheKey); settledRetry(roomId, 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 { if (generation === started) scheduleRetry(roomId, cacheKey); }
@@ -177,6 +199,8 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
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(); },
+ /** Raised by every invalidation and reset; views checked at an older one may be stale. */
+ version() { return generation; },
/** 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 4573ee92b6..1e0edbc86b 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -176,6 +176,8 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
useEffect(() => {
let cancelled = false;
let requestVersion = 0;
+ // Follow-up reads for older shares one refresh could not check; bounded per chain.
+ let shareFollowUps = 0;
const load = async (additionalSources: string[] = []) => {
const version = ++requestVersion;
const owner = getDataOwnerGeneration();
@@ -192,7 +194,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
const sourceMessageIds = [...new Set([...(shown
? mergeBotGroupMessages(displayed.older, displayed.group.messages).map(message => message.id) : []), ...additionalSources])];
// Older pages are not re-read, so their shares ask for the reply's current state.
- const shownShares = shown ? botGroupShownShares(displayed.older) : [];
+ const shownShares = shown ? botGroupShownShares(displayed.older, displayed.group.threadShareVersion) : [];
const result = sourceMessageIds.length || shownShares.length
? await api.getBotGroup(groupId, { sourceMessageIds, ...(shownShares.length ? { shownShares } : {}) })
: await api.getBotGroup(groupId);
@@ -201,7 +203,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
readOwner.current = owner;
setState((previous) =>
previous.kind === 'ready'
- ? { ...previous, group: result.group, older: applyBotGroupThreadShareUpdates(previous.older, result.group.threadShareUpdates) }
+ ? { ...previous, group: result.group, older: applyBotGroupThreadShareUpdates(previous.older, result.group) }
: {
kind: 'ready',
group: result.group,
@@ -210,6 +212,14 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
olderHasMore: result.group.hasMoreBefore,
},
);
+ const older = shown ? applyBotGroupThreadShareUpdates(displayed.older, result.group) : [];
+ const unchecked = staleBotGroupShares(older, result.group.threadShareVersion).length;
+ const total = older.filter(message => message.threadShare).length;
+ if (!unchecked) shareFollowUps = 0;
+ else if (shareFollowUps < Math.ceil(total / BOT_GROUP_SHOWN_SHARES_MAX) + 1) {
+ shareFollowUps += 1;
+ setTimeout(() => { if (!cancelled) void load(); }, 0);
+ }
} else if (result.errorCode === 'NOT_FOUND') {
setState({ kind: 'missing' });
} else {
@@ -795,22 +805,40 @@ 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);
+/** Older shares checked before the latest edit, deletion or reset: they may be out of date. */
+function staleBotGroupShares(older: readonly BotGroupMessageView[], version: number | undefined) {
+ return older.filter(message => message.threadShare && version !== undefined && (message.threadShare.version ?? 0) < version);
}
-function applyBotGroupThreadShareUpdates(older: BotGroupMessageView[], updates: BotGroupDetail['threadShareUpdates']) {
- if (!updates) return older;
+/**
+ * Which older shares one refresh re-checks: stale or still-loading ones first, then the
+ * newest, up to the per-read cap. The rest are checked by later refreshes.
+ */
+function botGroupShownShares(older: readonly BotGroupMessageView[], version: number | undefined) {
+ const withShares = older.filter(message => message.threadShare).reverse();
+ const first = new Set(withShares.filter(message => message.threadShare!.status === 'loading'
+ || (version !== undefined && (message.threadShare!.version ?? 0) < version)));
+ return [...first, ...withShares.filter(message => !first.has(message))].slice(0, BOT_GROUP_SHOWN_SHARES_MAX).map(message => ({
+ id: message.id, messageId: message.threadShare!.messageId, threadRootId: message.threadShare!.threadRootId,
+ ...(message.authorBotId ? { sharerId: message.authorBotId } : {}) }));
+}
+
+/**
+ * Apply the refreshed older shares. One this refresh could not check that is older than the
+ * latest version stops quoting its old text until a later refresh confirms it.
+ */
+function applyBotGroupThreadShareUpdates(older: BotGroupMessageView[], group: Pick<BotGroupDetail, 'threadShareUpdates' | 'threadShareVersion'>) {
+ const { threadShareUpdates: updates, threadShareVersion: version } = group;
+ if (!updates && version === undefined) return older;
let changed = false;
const next = older.map(message => {
- const update = updates[message.id];
- if (!update || !message.threadShare) return message;
+ const share = message.threadShare;
+ if (!share) return message;
+ const update = updates?.[message.id];
+ if (update) { changed = true; return { ...message, threadShare: update }; }
+ if (version === undefined || (share.version ?? 0) >= version || share.status !== 'available') return message;
changed = true;
- return { ...message, threadShare: update };
+ return { ...message, threadShare: { ...share, status: 'loading' as const, authorName: '', authorBotId: null, content: '', attachments: [], edited: false } };
});
return changed ? next : older;
}
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 382e7cf69d..375867ed16 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -1949,3 +1949,48 @@ describe('shares on older pages', () => {
shownShares: [{ id: 'old-share', messageId: 'old-reply', threadRootId: 'old-root', sharerId: 'alice-actor' }] }));
});
});
+
+describe('more older shares than one refresh re-reads', () => {
+ const t = (name: string) => `bots.groupChat.server.thread.${name}`;
+ beforeEach(() => { vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }); });
+
+ it('never keeps showing a share the refresh could not check, and gets to it within a few refreshes', async () => {
+ type Share = NonNullable<BotGroupMessageView['threadShare']>;
+ const shareOf = (i: number, extra: Partial<Share> = {}): Share => ({ messageId: `reply-${i}`, threadRootId: 'root', status: 'available', authorKind: 'bot',
+ authorBotId: 'xiaoman', authorName: '小满', sharedByAuthor: false, content: `原文 ${i}`, attachments: [], createdAt: 1, edited: false, version: 1, ...extra });
+ const older = Array.from({ length: 201 }, (_, i) => msg({ id: `share-${i}`, sequence: i + 1, authorKind: 'user', isSelf: false, authorBotId: 'alice',
+ authorName: 'Alice', content: `↪ 卡片 ${i}`, threadShare: shareOf(i) }));
+ const latest = detail({ serverBacked: true, hasMoreBefore: true, threadShareVersion: 1, messages: [msg({ id: 'new', sequence: 500, content: '最新' })] });
+ let version = 1;
+ const refreshes: Array<string[]> = [];
+ let release!: () => void;
+ const followUp = new Promise<void>(resolve => { release = resolve; });
+ mocks.getBotGroup.mockImplementation(async (_groupId: string, options?: { beforeSequence?: number; shownShares?: Array<{ id: string; messageId: string }> }) => {
+ if (options?.beforeSequence) return { ok: true, group: { ...latest, hasMoreBefore: false, messages: older } };
+ refreshes.push((options?.shownShares ?? []).map(share => share.id));
+ // Hold the read that finally checks the oldest share, to see what shows meanwhile.
+ if (version > 1 && options?.shownShares?.some(share => share.id === 'share-0')) await followUp;
+ // The oldest share's reply has been deleted on the server since it was shown.
+ const threadShareUpdates = Object.fromEntries((options?.shownShares ?? []).map(share => [share.id, share.messageId === 'reply-0'
+ ? shareOf(0, { status: 'unavailable', authorName: '', content: '', version }) : shareOf(Number(share.messageId.slice(6)), { version })]));
+ return { ok: true, group: { ...latest, threadShareVersion: version, threadShareUpdates } };
+ });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ expect(await screen.findByText('原文 0')).toBeTruthy();
+ version = 2;
+ act(() => { for (const push of mocks.pushes) push({ groupId: 'g1', change: 'messages' }); });
+ // Not checked by the first refresh: its old text goes away before anything confirms it.
+ await waitFor(() => expect(refreshes.some(ids => ids.includes('share-0'))).toBe(true));
+ expect(screen.queryByText('原文 0')).toBeNull();
+ expect(screen.getAllByText(t('loadingSource')).length).toBe(1);
+ act(() => release());
+ await waitFor(() => expect(screen.queryByText(t('loadingSource'))).toBeNull());
+ expect(screen.getAllByText(t('sourceUnavailable')).length).toBe(1);
+ // Bounded: the push plus at most a couple of follow-ups, each within the per-read cap.
+ expect(refreshes.length).toBeLessThanOrEqual(3);
+ expect(refreshes.every(ids => ids.length <= 200)).toBe(true);
+ expect(screen.queryByText('↪ 卡片 0')).toBeNull();
+ });
+});
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 41b911a341..eb2de6e0ee 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -463,7 +463,8 @@ Desktop 主聊天直接展示话题里的最新回复,并能把话题回复贴
预览先用房间快照里已有的最新 100 条消息(含所有话题回复),活跃话题不额外请求;只有最新回复早于这个窗口的话题,才按根消息读一页不超过 6 条,
遇到已删除回复占位时向前再读,最多 4 页。这些读取在后台进行,不拖住群页面:先显示数量,读完后刷新一次。
结果缓存到回复数变化,或其中某条被编辑、删除为止。读取失败时先只显示数量,然后按 30 秒、1、2、4、8 分钟自动重试,
- 最多 5 次,之后等下一条推送或重新打开群聊;切换账号或退出时取消。
+ 最多 5 次,之后等下一条推送或重新打开群聊;同一群里多条读取失败各自按自己的到期时间重试,共用一个定时器、到点后接着排下一个;
+ 切换账号或退出时取消。
- **同时发到主聊天**:话题输入框有「同时发到群聊」,默认不选、每次发送后恢复默认、切换话题不继承。先发话题回复,成功后再贴回主聊天;
贴回失败时回复保留在话题里,显示「重新发到群聊」,重试只重做贴回这一步,不重发回复。多条失败一起列出,
按群和话题保存在本次运行中,切换话题再回来仍可重试。回复失败时重试沿用原 `clientId`,回复送达前不会贴回。
@@ -483,6 +484,8 @@ Desktop 主聊天直接展示话题里的最新回复,并能把话题回复贴
新回复本身的 @ 按原规则只在话题里生效一次。「继续讨论」不会把贴回消息当作新请求。伙伴读到群历史时,贴回消息带 `sharedReplyId`,并被说明为引用、不是新请求。
- **更早页面上的贴回**:「查看更早的消息」加载出的贴回卡片会跟着原回复变化。每次刷新时,客户端把已显示的旧卡片(最多 200 张)
交给主进程,按同一套缓存、失效和权限判定重新解析;原回复被编辑后显示新内容,删除或失去查看权限后显示无法查看,不需要点击或重新打开群聊。
+ 超过 200 张时,过期或仍在读取的卡片优先,其余取最新的;这次没核对、而在最近一次编辑/删除/重置之前核对过的卡片,
+ 先改为「正在读取原回复…」,不再显示旧正文,随后有界地追加刷新(最多「卡片数 ÷ 200 + 1」次)把它们核对完。
旧页面上普通消息的编辑、删除、表情和回复数仍不随推送刷新,这是现有限制,不在本功能范围内。
- **侧栏**:群的最新一条是贴回时,侧栏只显示「谁贴回了一条话题回复」,不引用卡片里的文字,也不为此读取原回复。
- **兼容与边界**:只新增可选字段 `threadPreview`、`threadShare` 与 Desktop 专用 IPC `maker:chat-server:shareToMain`,不进入设备互联白名单。
diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.ts
index a5d1966d4b..b45af719d7 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -249,6 +249,8 @@ export interface BotGroupThreadShareView {
attachments: BotGroupAttachment[];
createdAt: number | null;
edited: boolean;
+ /** Cache version this view was checked at; compare with `BotGroupDetail.threadShareVersion`. */
+ version?: number;
}
export type BotGroupAttachmentCategory = 'image' | 'pdf' | 'text' | 'office' | 'file';
@@ -406,6 +408,8 @@ export interface BotGroupDetail extends BotGroupSummary {
executionFailures?: BotGroupExecutionFailureView[];
/** Current state of shares the reader listed in `shownShares`, keyed by the share's message ID. */
threadShareUpdates?: Record<string, BotGroupThreadShareView>;
+ /** Raised by every edit, deletion or reset; an older share view may no longer be true. */
+ threadShareVersion?: number;
hasMoreBefore: boolean;
round: BotGroupRoundView;
/** Plans referenced by the loaded messages, plus the open plan. */