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(desktop): prevent duplicate streaming message identities

DavidShen0215c2d52591
diff --git a/apps/desktop/src/main/cindy-media/__tests__/blobStore.test.ts b/apps/desktop/src/main/cindy-media/__tests__/blobStore.test.ts
index 4712c96aa4..5b2107fd6d 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/blobStore.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/blobStore.test.ts
@@ -12,6 +12,9 @@ import fs from 'node:fs';
import fsp from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
+import { fileSymlinkFixture } from './fileSymlinkFixture';
+
+const directoryLinkType = process.platform === 'win32' ? 'junction' : 'dir';
let tmpUserData = '';
let scratchRoot = '';
@@ -50,17 +53,13 @@ function scratchDir(label: string): string {
return fs.mkdtempSync(path.join(scratchRoot, `${label}-`));
}
-function seedDest(dest: string, contents: Buffer | 'dir' | { symlink: string }) {
+function seedDest(dest: string, contents: Buffer | 'dir') {
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.rmSync(dest, { recursive: true, force: true });
if (contents === 'dir') {
fs.mkdirSync(dest);
return;
}
- if (typeof contents === 'object' && 'symlink' in contents) {
- fs.symlinkSync(contents.symlink, dest);
- return;
- }
fs.writeFileSync(dest, contents);
}
@@ -154,11 +153,16 @@ describe('writeBlob(已存在副本核验与自愈)', () => {
const outsideDir = scratchDir(`outside-${mode}`);
const outside = path.join(outsideDir, 'payload.bin');
fs.writeFileSync(outside, sample.buffer);
- seedDest(sample.dest, { symlink: outside });
- const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });
- await expect(mode === 'rename' ? withUnsupportedLink(run) : run()).rejects.toThrow(/symlink/);
- expect(fs.lstatSync(sample.dest).isSymbolicLink()).toBe(true);
- expect(fs.readFileSync(outside)).toEqual(sample.buffer);
+ fs.mkdirSync(sample.shard, { recursive: true });
+ const link = fileSymlinkFixture(outside, sample.dest);
+ try {
+ const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });
+ await expect(mode === 'rename' ? withUnsupportedLink(run) : run()).rejects.toThrow(/symlink/);
+ link.expectIntact();
+ expect(fs.readFileSync(outside)).toEqual(sample.buffer);
+ } finally {
+ link.restore();
+ }
});
it.each(['link', 'rename'] as const)('%s 分支:目录不当成去重成功', async (mode) => {
@@ -176,19 +180,22 @@ describe('writeBlob(已存在副本核验与自愈)', () => {
const outside = path.join(outsideDir, 'not-the-blob.bin');
fs.writeFileSync(outside, Buffer.from('not-the-blob'));
const originalOpen = fsp.open.bind(fsp);
+ let link: ReturnType<typeof fileSymlinkFixture> | undefined;
const spy = vi.spyOn(fsp, 'open').mockImplementation(async (target, flags, perm) => {
- if (path.resolve(String(target)) === path.resolve(sample.dest)) {
+ if (!link && path.resolve(String(target)) === path.resolve(sample.dest)) {
fs.rmSync(sample.dest, { force: true });
- fs.symlinkSync(outside, sample.dest);
+ link = fileSymlinkFixture(outside, sample.dest);
}
return originalOpen(target, flags, perm);
});
try {
const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });
await expect(mode === 'rename' ? withUnsupportedLink(run) : run()).rejects.toThrow();
- expect(fs.lstatSync(sample.dest).isSymbolicLink()).toBe(true);
+ expect(link).toBeDefined();
+ link!.expectIntact();
expect(fs.readFileSync(outside).toString()).toBe('not-the-blob');
} finally {
+ link?.restore();
spy.mockRestore();
}
});
@@ -198,7 +205,7 @@ describe('writeBlob(已存在副本核验与自愈)', () => {
const outsideDir = scratchDir('bucket-outside');
fs.mkdirSync(sample.shard, { recursive: true });
fs.rmSync(sample.shard, { recursive: true, force: true });
- fs.symlinkSync(outsideDir, sample.shard);
+ fs.symlinkSync(outsideDir, sample.shard, directoryLinkType);
await expect(
blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' }),
).rejects.toThrow(/symlink|out of bounds/);
@@ -211,12 +218,15 @@ describe('writeBlob(已存在副本核验与自愈)', () => {
const target = path.join(tmpUserData, 'cindy-media', ...(kind === 'blobs' ? ['blobs'] : []));
const outside = scratchDir(`anc-${kind}`);
fs.rmSync(target, { recursive: true, force: true });
- fs.symlinkSync(outside, target);
- await expect(blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' })).rejects.toThrow(/symlink|out of bounds/);
- expect(fs.lstatSync(target).isSymbolicLink()).toBe(true);
- expect(fs.readdirSync(outside)).toEqual([]);
- fs.rmSync(target, { recursive: true, force: true });
- fs.mkdirSync(path.join(tmpUserData, 'cindy-media', 'blobs'), { recursive: true });
+ try {
+ fs.symlinkSync(outside, target, directoryLinkType);
+ await expect(blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' })).rejects.toThrow(/symlink|out of bounds/);
+ expect(fs.lstatSync(target).isSymbolicLink()).toBe(true);
+ expect(fs.readdirSync(outside)).toEqual([]);
+ } finally {
+ fs.rmSync(target, { recursive: true, force: true });
+ fs.mkdirSync(path.join(tmpUserData, 'cindy-media', 'blobs'), { recursive: true });
+ }
});
it('hash 后 size 变化视为替换,不得去重成功', async () => {
diff --git a/apps/desktop/src/main/cindy-media/__tests__/fileSymlinkFixture.ts b/apps/desktop/src/main/cindy-media/__tests__/fileSymlinkFixture.ts
new file mode 100644
index 0000000000..1f9287ccd6
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/__tests__/fileSymlinkFixture.ts
@@ -0,0 +1,50 @@
+import fs from 'node:fs';
+import fsp from 'node:fs/promises';
+import path from 'node:path';
+import { expect, vi } from 'vitest';
+
+/**
+ * Prefer a real file symlink. Unprivileged Windows cannot create one, so keep a
+ * real external-file alias (hard link) and simulate only its lstat type bits.
+ * Reads/writes and inode replacement remain real; no production operation is
+ * mocked to reject. Directory attacks use real junctions instead of this helper.
+ */
+export function fileSymlinkFixture(target: string, linkPath: string) {
+ let native = true;
+ try {
+ fs.symlinkSync(target, linkPath, 'file');
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (process.platform !== 'win32' || (code !== 'EPERM' && code !== 'EACCES')) throw error;
+ native = false;
+ fs.linkSync(target, linkPath);
+ }
+
+ const identity = fs.lstatSync(linkPath);
+ const originalLstat = fsp.lstat.bind(fsp);
+ const spy = native ? undefined : vi.spyOn(fsp, 'lstat').mockImplementation(async (candidate, opts) => {
+ const stat = await originalLstat(candidate, opts);
+ // Stop reporting a link if the code replaced the fixture. Otherwise a
+ // constant mocked stat could hide the very unsafe mutation we are testing.
+ if (
+ path.resolve(String(candidate)) === path.resolve(linkPath) &&
+ stat.dev === identity.dev && stat.ino === identity.ino
+ ) {
+ return Object.assign(Object.create(Object.getPrototypeOf(stat)), stat, {
+ isSymbolicLink: () => true,
+ isFile: () => false,
+ });
+ }
+ return stat;
+ });
+
+ return {
+ restore: () => spy?.mockRestore(),
+ expectIntact: () => {
+ const current = fs.lstatSync(linkPath);
+ expect(current.isSymbolicLink()).toBe(native);
+ expect(current.dev).toBe(identity.dev);
+ expect(current.ino).toBe(identity.ino);
+ },
+ };
+}
diff --git a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
index bc2d8eae4d..f0a076c5f1 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
@@ -15,6 +15,7 @@ import path from 'node:path';
import { createHash } from 'node:crypto';
import type { LedgerDb } from '../ledger';
import type { MediaRefCompensationScope } from '../refCompensationJournal';
+import { fileSymlinkFixture } from './fileSymlinkFixture';
let tmpUserData = '';
const OWNER_ID = 'owner-a';
@@ -244,10 +245,11 @@ describe('ingestMedia(全局去重)', () => {
const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-media-ingest-outside-'));
const outside = path.join(outsideDir, 'leave-me-alone.bin');
fs.writeFileSync(outside, Buffer.from('leave-me-alone'));
+ let link: ReturnType<typeof fileSymlinkFixture> | undefined;
try {
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.rmSync(dest, { recursive: true, force: true });
- fs.symlinkSync(outside, dest);
+ link = fileSymlinkFixture(outside, dest);
await expect(
ingest.ingestMedia(
{
@@ -258,11 +260,12 @@ describe('ingestMedia(全局去重)', () => {
db,
),
).rejects.toThrow(/symlink/);
- expect(fs.lstatSync(dest).isSymbolicLink()).toBe(true);
+ link.expectIntact();
expect(fs.readFileSync(outside).toString()).toBe('leave-me-alone');
expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(0);
expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
} finally {
+ link?.restore();
fs.rmSync(dest, { force: true });
fs.rmSync(outsideDir, { recursive: true, force: true });
}
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
index 273a5d97e3..15cafc78e3 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
@@ -1625,6 +1625,99 @@ describe('makerChatStore text delta batching', () => {
]);
});
+ it('does not append a second bubble when a DB snapshot arrives before the first batched delta', () => {
+ emitTextDelta('draft');
+ onDbMessageCreated?.({
+ sessionId: SESSION_ID,
+ message: {
+ clientId: 'assistant-1', role: 'assistant', content: 'complete answer',
+ createdAt: '2026-06-15T00:00:05.000Z',
+ },
+ });
+ vi.advanceTimersByTime(32);
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([
+ expect.objectContaining({ clientId: 'assistant-1', content: 'complete answer', isStreaming: false }),
+ ]);
+ });
+
+ it('calibrates an earlier finalized item in place without sealing a newer stream', () => {
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: { type: 'text', source: 'pi', data: { text: 'draft', isFinal: true, isFullText: true } },
+ persistId: 'assistant-1',
+ });
+ emitTextDelta('new answer', SESSION_ID, 'assistant-2');
+ vi.advanceTimersByTime(32);
+ const previousMeta = makerChatStore.getSnapshot(SESSION_ID).lastAgentMeta;
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'text', source: 'pi',
+ data: { text: 'corrected', isFinal: true, isFullText: true },
+ agentMeta: { model: 'earlier-model' },
+ },
+ persistId: 'assistant-1',
+ });
+ emitTextDelta(' tail', SESSION_ID, 'assistant-2');
+ vi.advanceTimersByTime(32);
+ const snapshot = makerChatStore.getSnapshot(SESSION_ID);
+ expect(snapshot.streamingClientId).toBe('assistant-2');
+ expect(snapshot.lastAgentMeta).toBe(previousMeta);
+ expect(snapshot.messages).toEqual([
+ expect.objectContaining({ clientId: 'assistant-1', content: 'corrected', isStreaming: false, model: 'earlier-model' }),
+ expect.objectContaining({ clientId: 'assistant-2', content: 'new answer tail', isStreaming: true }),
+ ]);
+ });
+
+ it('ignores late deltas and partial final blocks for an already finalized item', () => {
+ onDbMessageCreated?.({
+ sessionId: SESSION_ID,
+ message: { clientId: 'assistant-1', role: 'assistant', content: 'full answer', createdAt: new Date().toISOString() },
+ });
+ emitTextDelta('stale', SESSION_ID, 'assistant-1');
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: { type: 'text', source: 'claude-code', data: { text: 'answer', isFinal: true } },
+ persistId: 'assistant-1',
+ });
+ vi.advanceTimersByTime(32);
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([
+ expect.objectContaining({ clientId: 'assistant-1', content: 'full answer', isStreaming: false }),
+ ]);
+ });
+
+ it('does not reset or duplicate thinking on a repeated start, including after its DB echo', () => {
+ const start = {
+ sessionId: SESSION_ID,
+ event: { type: 'thinking', source: 'pi', data: { stage: 'start', blockId: 'thinking-replayed', startedAt: Date.now() } },
+ };
+ onEvent?.(start);
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: { type: 'thinking', source: 'pi', data: { stage: 'delta', blockId: 'thinking-replayed', text: 'reasoning' } },
+ });
+ onEvent?.(start);
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([
+ expect.objectContaining({ clientId: 'thinking-replayed', content: 'reasoning', isStreaming: true }),
+ ]);
+ onDbMessageCreated?.({
+ sessionId: SESSION_ID,
+ message: {
+ clientId: 'thinking-replayed', role: 'thinking',
+ content: { kind: 'thinking', text: 'finished reasoning', durationMs: 5000, isRedacted: false },
+ createdAt: new Date().toISOString(),
+ },
+ });
+ onEvent?.(start);
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: { type: 'thinking', source: 'pi', data: { stage: 'delta', blockId: 'thinking-replayed', text: 'late delta' } },
+ });
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([
+ expect.objectContaining({ clientId: 'thinking-replayed', content: 'finished reasoning', isStreaming: false }),
+ ]);
+ });
+
it('calibrates an in-flight bubble to a shorter authoritative final text', () => {
emitTextDelta('Hello worxderful');
@@ -6946,6 +7039,21 @@ describe('makerChatStore text delta batching', () => {
]);
});
+ it('deduplicates history batches and previously duplicated runtime rows by message identity', () => {
+ const old: ChatMessage = {
+ clientId: 'assistant-1', role: 'assistant', content: 'old', isStreaming: false,
+ createdAt: '2026-06-15T00:00:03.000Z',
+ };
+ const latest = { ...old, content: 'latest' };
+ const persisted = { ...latest, id: 'db-1', rowid: 1 };
+ const other = { ...old, clientId: 'assistant-2', content: 'other' };
+ expect(makerChatStore.__mergeMessagesForTest([old, persisted, other], [])).toEqual([persisted, other]);
+ expect(makerChatStore.__mergeMessagesForTest([persisted, persisted, other], [old, latest])).toEqual([persisted, other]);
+ expect(makerChatStore.__mergeMessagesForTest([old], [latest, latest], { addOnly: true })).toEqual([latest]);
+ const stable = [persisted, other];
+ expect(makerChatStore.__mergeMessagesForTest([persisted], stable)).toBe(stable);
+ });
+
it('does not stop remote reconciliation on row-trimmed overlaps', () => {
const row = serverMessage({
id: 'row-1',
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index c54af28b82..fe5f4b95e4 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -5029,6 +5029,38 @@ export function handleStreamEvent(
isFullText?: boolean;
};
+ // A DB/history snapshot can beat the first batched delta, or an old item's
+ // final event can arrive after a newer item starts. Identity, not tail
+ // position/content equality, decides whether this is a new bubble.
+ if (event.persistId && event.persistId !== state.streamingClientId) {
+ const existing = state.messages.find(
+ (message) => message.clientId === event.persistId && message.role === 'assistant',
+ );
+ if (existing) {
+ // Persisted/finalized text already includes these late deltas. Only an
+ // explicitly authoritative full-text event may calibrate it again.
+ if (!isFinal) return state;
+ const updated = {
+ ...existing,
+ ...(isFullText === true && text ? { content: text } : {}),
+ ...assistantMetaFields,
+ };
+ // A late item may update its own chip, not the newer stream's metadata.
+ const lastAgentMeta = state.streamingClientId
+ ? state.lastAgentMeta
+ : incomingMeta ?? state.lastAgentMeta;
+ const unchanged = shallowEqualChatMessage(existing, updated);
+ if (unchanged && lastAgentMeta === state.lastAgentMeta) return state;
+ return {
+ ...state,
+ lastAgentMeta,
+ messages: unchanged
+ ? state.messages
+ : replaceMessage(state.messages, (message) => message === existing, () => updated),
+ };
+ }
+ }
+
// Main assigns a fresh persistId when the provider starts a distinct assistant item.
// Seal the preceding bubble before applying the new item's deltas/full-text calibration.
const itemBoundary = Boolean(
@@ -5166,6 +5198,9 @@ export function handleStreamEvent(
| { stage: 'redacted'; blockId: string };
if (data.stage === 'start') {
+ // Replayed starts and DB-before-live delivery must not add a second row
+ // or reset content that this identity has already accumulated.
+ if (state.messages.some((message) => message.clientId === data.blockId)) return state;
// Thinking starts at the head of an API call, possibly before any
// assistant text. Don't finalize streamingText here — text deltas
// may resume on the *same* assistant message after the thinking
@@ -5192,7 +5227,7 @@ export function handleStreamEvent(
...state,
messages: replaceMessage(
state.messages,
- (m) => m.clientId === data.blockId && m.role === 'thinking',
+ (m) => m.clientId === data.blockId && m.role === 'thinking' && m.isStreaming === true,
(m) => ({ ...m, content: m.content + data.text }),
),
};
@@ -11409,8 +11444,8 @@ function loadOlderMessages(
return (async () => {
try {
const collected: Message[] = [];
- // 跨页按 clientId 去重:mergeMessages 只对"新批 vs 已有"去重,不去重批内
- // 重复;游标异常(如远端排序不稳)返回重叠页时,不去重会把同一行灌多份。
+ // 跨页提前按 clientId 去重,避免重叠页虚增回填预算和游标进度;
+ // mergeMessages 仍在发布窗口时兜底消息身份唯一性。
const collectedClientIds = new Set<string>();
let pageOpts = firstPageOpts;
// 初值 true:首页就 fetch 失败时不能把 hasMoreMessages 误收成 false(要留给用户重试)。
@@ -15761,16 +15796,25 @@ function mergeMessages(
rowsOrder: RemoteRowsOrder = 'oldest-first',
): ChatMessage[] {
const serverOrder = new Map(serverMsgs.map((message, index) => [message.clientId, index]));
+ const serverByClientId = new Map(serverMsgs.map((message) => [message.clientId, message]));
if (existing.length === 0) {
return collapseConsecutiveAutoResumeRows(
- sortMessagesChronologically(serverMsgs, serverOrder, rowsOrder),
+ sortMessagesChronologically([...serverByClientId.values()], serverOrder, rowsOrder),
);
}
- const serverByClientId = new Map(serverMsgs.map((message) => [message.clientId, message]));
- const seen = new Set<string>();
- let changed = false;
- const hydratedExisting = existing.map((message) => {
- seen.add(message.clientId);
+ // Repair already-duplicated in-memory rows as well as duplicates within a
+ // fetched batch. Keep the first slot and merge later metadata/content before
+ // applying the authoritative snapshot (or the addOnly live-state guard).
+ const existingByClientId = new Map<string, ChatMessage>();
+ for (const message of existing) {
+ const previous = existingByClientId.get(message.clientId);
+ existingByClientId.set(
+ message.clientId,
+ previous ? hydratePersistedMessage(previous, message, options) : message,
+ );
+ }
+ let changed = existingByClientId.size !== existing.length;
+ const hydratedExisting = Array.from(existingByClientId.values(), (message) => {
const persisted = serverByClientId.get(message.clientId);
if (!persisted) return message;
if (options.addOnly === true && options.addOnlyExcept?.has(message.clientId) !== true) {
@@ -15780,7 +15824,7 @@ function mergeMessages(
if (hydrated !== message) changed = true;
return hydrated;
});
- const filtered = serverMsgs.filter((m) => !seen.has(m.clientId));
+ const filtered = [...serverByClientId.values()].filter((m) => !existingByClientId.has(m.clientId));
if (filtered.length > 0) changed = true;
const sorted = sortMessagesChronologically(
[...hydratedExisting, ...filtered],
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
index b19f80f9c8..589dd2de13 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
@@ -1547,6 +1547,34 @@ describe('pi translator', () => {
expect(ctx.turnCacheWrite).toBe(0);
});
+ it('keeps thinking identities distinct across runtime restarts and stable within each block', () => {
+ const blockIds: string[] = [];
+ for (let runtime = 0; runtime < 2; runtime++) {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+ for (let turn = 0; turn < 2; turn++) {
+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
+ translatePiEvent(ev({ type: 'message_start' }), queue, ctx);
+ const offset = events.length;
+ for (const type of ['thinking_start', 'thinking_delta', 'thinking_end']) {
+ translatePiEvent(ev({
+ type: 'message_update',
+ assistantMessageEvent: { type, contentIndex: 0, delta: 'reasoning', content: 'reasoning' },
+ }), queue, ctx);
+ }
+ const thinking = events.slice(offset).filter((event) => event.type === 'thinking');
+ const data = thinking.map((event) => event.data as { stage: string; blockId: string });
+ expect(data.map((item) => item.stage)).toEqual(['start', 'delta', 'final']);
+ expect(new Set(data.map((item) => item.blockId)).size).toBe(1);
+ blockIds.push(data[0]!.blockId);
+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
+ }
+ disposePiTranslateContext(ctx);
+ }
+ expect(new Set(blockIds).size).toBe(4);
+ expect(blockIds).not.toContain('pi-think-1');
+ });
+
it('preserves pi redacted thinking as a structured redacted event', () => {
const ctx = createPiTranslateContext(noopLogger);
const { queue, events } = makeQueue();
@@ -1602,7 +1630,7 @@ describe('pi translator', () => {
expect(events.filter((e) => e.type === 'thinking')).toEqual([{
type: 'thinking',
- data: { stage: 'redacted', blockId: 'pi-think-1' },
+ data: { stage: 'redacted', blockId: `${ctx.thinkingIdPrefix}-1` },
source: 'pi',
}]);
disposePiTranslateContext(ctx);
@@ -1643,11 +1671,11 @@ describe('pi translator', () => {
expect(events).toEqual([
expect.objectContaining({
type: 'thinking',
- data: expect.objectContaining({ stage: 'start', blockId: 'pi-think-1' }),
+ data: expect.objectContaining({ stage: 'start', blockId: `${ctx.thinkingIdPrefix}-1` }),
}),
{
type: 'thinking',
- data: { stage: 'redacted', blockId: 'pi-think-1' },
+ data: { stage: 'redacted', blockId: `${ctx.thinkingIdPrefix}-1` },
source: 'pi',
},
]);
@@ -1712,12 +1740,12 @@ describe('pi translator', () => {
expect(events.filter((event) => event.type === 'thinking')).toEqual([
{
type: 'thinking',
- data: { stage: 'redacted', blockId: 'pi-think-1' },
+ data: { stage: 'redacted', blockId: `${ctx.thinkingIdPrefix}-1` },
source: 'pi',
},
{
type: 'thinking',
- data: { stage: 'redacted', blockId: 'pi-think-2' },
+ data: { stage: 'redacted', blockId: `${ctx.thinkingIdPrefix}-2` },
source: 'pi',
},
]);
@@ -1756,7 +1784,7 @@ describe('pi translator', () => {
type: 'thinking',
data: expect.objectContaining({
stage: 'final',
- blockId: 'pi-think-1',
+ blockId: `${ctx.thinkingIdPrefix}-1`,
text: 'visible reasoning',
}),
source: 'pi',
diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.ts
index a6967cfc2c..8745276cf2 100644
--- a/packages/maker-core/src/agents/pi/translator.ts
+++ b/packages/maker-core/src/agents/pi/translator.ts
@@ -15,6 +15,7 @@
* message_end 时把该消息全部 text block 拼接发一次 isFinal:true 校准。
*/
+import { randomUUID } from 'node:crypto';
import type { Logger } from '../../interfaces/logger.js';
import { PI_SUBAGENT_TOOL_NAME, subagentSpawnResultIndicatesRunning } from '@cindy/maker-shared/agent-task';
import {
@@ -121,6 +122,8 @@ export interface PiTranslateContext {
/** 当前 turn 内尚未被终态消费的 Host 主动停止请求。 */
hostAbortRequestGeneration: number | null;
hostAbortRequestTokens: Set<symbol>;
+ /** Runtime-local namespace: persisted thinking IDs must not collide after context recreation. */
+ thinkingIdPrefix: string;
/** thinking 块序号(blockId 生成)。 */
thinkingSeq: number;
/** contentIndex → 当前消息内的 thinking block 状态。 */
@@ -209,6 +212,7 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {
pendingHostTurnStartToken: null,
hostAbortRequestGeneration: null,
hostAbortRequestTokens: new Set(),
+ thinkingIdPrefix: `pi-think-${randomUUID()}`,
thinkingSeq: 0,
thinkingBlocks: new Map(),
streamStopTokenByIndex: new Map(),
@@ -1253,7 +1257,7 @@ function ensureThinkingBlock(
const existing = ctx.thinkingBlocks.get(contentIndex);
if (existing) return existing;
const block = {
- blockId: `pi-think-${++ctx.thinkingSeq}`,
+ blockId: `${ctx.thinkingIdPrefix}-${++ctx.thinkingSeq}`,
startedAt: Date.now(),
redacted,
};