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。

perf(desktop): 归档后精简工具结果数据 (#3474)

DavidShenXD2ad8ade33643
diff --git a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
index e4be811774..8e79ef335b 100644
--- a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
@@ -13,6 +13,7 @@ const h = vi.hoisted(() => ({
tapWindowBroadcast: vi.fn(),
notifyAgentIslandSessionPatch: vi.fn(),
runtimeCleanup: vi.fn(),
+ compactSessionToolResultsBestEffort: vi.fn(async () => undefined),
}));
vi.mock('electron', () => ({
@@ -27,6 +28,9 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({
vi.mock('../agentIslandSessionPatch.js', () => ({
notifyAgentIslandSessionPatch: h.notifyAgentIslandSessionPatch,
}));
+vi.mock('../toolResultCompaction.js', () => ({
+ compactSessionToolResultsBestEffort: h.compactSessionToolResultsBestEffort,
+}));
describe('orcaTeamStore', () => {
let currentClient: DbClient | null = null;
@@ -117,6 +121,15 @@ describe('orcaTeamStore', () => {
expect(h.runtimeCleanup).toHaveBeenCalledTimes(2);
expect(h.runtimeCleanup).toHaveBeenCalledWith('worker-session-1');
expect(h.runtimeCleanup).toHaveBeenCalledWith('worker-session-2');
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledTimes(2);
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledWith({
+ client,
+ sessionId: 'worker-session-1',
+ });
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledWith({
+ client,
+ sessionId: 'worker-session-2',
+ });
});
it('never archives or broadcasts a worker task that is already deleted', async () => {
@@ -141,6 +154,7 @@ describe('orcaTeamStore', () => {
patch: { status: 'archived' },
});
expect(h.runtimeCleanup).not.toHaveBeenCalledWith('worker-session-2');
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledTimes(1);
});
it('reconciles only still-active workers from inactive teams', async () => {
@@ -169,6 +183,10 @@ describe('orcaTeamStore', () => {
]);
expect(h.runtimeCleanup).toHaveBeenCalledTimes(1);
expect(h.runtimeCleanup).toHaveBeenCalledWith('worker-session-1');
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledWith({
+ client,
+ sessionId: 'worker-session-1',
+ });
});
it('cleans archived worker runtime state before releasing route locks and broadcasting', async () => {
@@ -211,14 +229,34 @@ describe('orcaTeamStore', () => {
await archiveSingleWorkerSession('worker-session-1');
expect(h.runtimeCleanup).toHaveBeenCalledWith('worker-session-1');
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledWith({
+ client,
+ sessionId: 'worker-session-1',
+ });
h.runtimeCleanup.mockClear();
+ h.compactSessionToolResultsBestEffort.mockClear();
await client.exec('UPDATE sessions SET status = ? WHERE id = ?', [
'deleted',
'worker-session-2',
]);
await archiveSingleWorkerSession('worker-session-2');
expect(h.runtimeCleanup).not.toHaveBeenCalled();
+ expect(h.compactSessionToolResultsBestEffort).not.toHaveBeenCalled();
+ });
+
+ it('compacts a worker task after removeWorker archives it', async () => {
+ const { removeWorker } = await import('../orcaTeamStore.js');
+ const client = createTestDbClient();
+ setCurrentDbClient(client, 'test-user');
+ await seedOrcaWorkers(client);
+
+ await removeWorker('worker-1');
+
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledWith({
+ client,
+ sessionId: 'worker-session-1',
+ });
});
it('preserves Pi worker identity in Orca projections', async () => {
diff --git a/apps/desktop/src/main/localDb/__tests__/toolResultCompaction.test.ts b/apps/desktop/src/main/localDb/__tests__/toolResultCompaction.test.ts
new file mode 100644
index 0000000000..274bff20eb
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/toolResultCompaction.test.ts
@@ -0,0 +1,82 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { DbClient } from '../client/DbClient.js';
+import { compactSessionToolResultsBestEffort } from '../toolResultCompaction.js';
+
+const h = vi.hoisted(() => ({
+ drainPersistQueue: vi.fn(async (): Promise<void> => undefined),
+}));
+
+vi.mock('../../messagePersistBroadcaster.js', () => ({
+ drainPersistQueue: h.drainPersistQueue,
+}));
+
+function createClient(tx: ReturnType<typeof vi.fn>): DbClient {
+ return { tx } as unknown as DbClient;
+}
+
+describe('tool result compaction trigger', () => {
+ beforeEach(() => {
+ h.drainPersistQueue.mockReset();
+ h.drainPersistQueue.mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('runs one explicit-session compaction without a size threshold', async () => {
+ vi.useFakeTimers();
+ const now = Date.UTC(2026, 7, 26, 8);
+ vi.setSystemTime(now);
+ const tx = vi.fn(async () => ({ compactedRows: 1, originalBytes: 70_000 }));
+
+ await compactSessionToolResultsBestEffort({
+ client: createClient(tx),
+ sessionId: 'session-1',
+ });
+
+ expect(tx).toHaveBeenCalledTimes(1);
+ expect(h.drainPersistQueue).toHaveBeenCalledTimes(1);
+ expect(tx).toHaveBeenCalledWith('toolResults.compactSession', {
+ sessionId: 'session-1',
+ now,
+ });
+ });
+
+ it('waits for already queued message writes before its single attempt', async () => {
+ let releaseDrain!: () => void;
+ h.drainPersistQueue.mockReturnValue(
+ new Promise<void>((resolve) => {
+ releaseDrain = resolve;
+ }),
+ );
+ const tx = vi.fn(async () => ({ compactedRows: 1, originalBytes: 10 }));
+
+ const pending = compactSessionToolResultsBestEffort({
+ client: createClient(tx),
+ sessionId: 'session-1',
+ });
+ await Promise.resolve();
+
+ expect(tx).not.toHaveBeenCalled();
+ releaseDrain();
+ await pending;
+ expect(tx).toHaveBeenCalledTimes(1);
+ });
+
+ it('swallows a failed attempt without scheduling a retry', async () => {
+ const tx = vi.fn(async () => {
+ throw new Error('database closed');
+ });
+
+ await expect(
+ compactSessionToolResultsBestEffort({
+ client: createClient(tx),
+ sessionId: 'session-1',
+ }),
+ ).resolves.toBeUndefined();
+ expect(tx).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index 5948681f34..d9122b7798 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -311,6 +311,8 @@ function dispatchTx(readyDb, payload) {
return sessionsRenameTitles(readyDb, request.args);
case 'sessions.setStatus':
return sessionsSetStatus(readyDb, request.args);
+ case 'toolResults.compactSession':
+ return compactSessionToolResults(readyDb, request.args);
case 'session.agentSwitchFallback':
return sessionAgentSwitchFallback(readyDb, request.args);
case 'context.rebuild':
@@ -809,10 +811,54 @@ function sessionsSetStatus(readyDb, args) {
})();
}
-// 会话分享(.xdtshare)导入落库: 与 worker/opHandlers/tx.ts 的同名 handler 保持一致。
+function compactSessionToolResults(readyDb, args) {
+ const payload = asRecord(args, 'toolResults.compactSession args');
+ const sessionId = expectString(payload.sessionId, 'sessionId');
+ const now = expectNumber(payload.now, 'now');
+
+ const selectSession = readyDb.prepare(
+ "SELECT id FROM sessions WHERE id = ? AND status IN ('archived', 'deleted') LIMIT 1",
+ );
+ // Keep this aggregate + bulk update path in sync with worker/opHandlers/tx.ts.
+ // Only prefix-shaped rows pay for JSON validation.
+ const uncompactedContentPredicate = [
+ 'CASE',
+ "WHEN content NOT GLOB '{\\\"type\\\":\\\"tool_result_compacted\\\",\\\"version\\\":1,*' THEN 1",
+ 'WHEN json_valid(content) = 0 THEN 1',
+ "WHEN json_type(content) = 'object'",
+ "AND json_extract(content, '$.type') = 'tool_result_compacted'",
+ "AND json_extract(content, '$.version') = 1",
+ "AND json_type(content, '$.originalBytes') IN ('integer', 'real')",
+ "AND json_extract(content, '$.originalBytes') >= 0",
+ "AND json_type(content, '$.compactedAt') IN ('integer', 'real')",
+ "AND json_extract(content, '$.compactedAt') >= 0 THEN 0",
+ 'ELSE 1 END',
+ ].join(' ');
+ const summarizeCandidates = readyDb.prepare(
+ "SELECT COALESCE(SUM(octet_length(content)), 0) AS originalBytes FROM messages WHERE session_id = ? AND role = 'tool_result' AND (" + uncompactedContentPredicate + ') = 1',
+ );
+ const compactMessages = readyDb.prepare(
+ "UPDATE messages SET content = json_object('type', 'tool_result_compacted', 'version', 1, 'originalBytes', octet_length(content), 'compactedAt', ?) WHERE session_id = ? AND role = 'tool_result' AND (" + uncompactedContentPredicate + ') = 1',
+ );
+
+ return readyDb.transaction(() => {
+ const session = selectSession.get(sessionId);
+ if (!session) {
+ return { compactedRows: 0, originalBytes: 0 };
+ }
+ const summary = summarizeCandidates.get(session.id);
+ const compactedRows = compactMessages.run(now, session.id).changes;
+ return {
+ compactedRows,
+ originalBytes: compactedRows > 0 ? summary.originalBytes : 0,
+ };
+ })();
+}
+
// 单事务插 session 行 + 全量 messages, 任一行非法整体回滚零写入;
// session 已存在按 ALREADY_EXISTS 抛(并发双导入兜底)。
// 协同包经可选 orca 段在同一事务追加 Worker 会话 + orca_teams/orca_workers 关系图。
+// 会话分享(.xdtshare)导入落库: 与 worker/opHandlers/tx.ts 的同名 handler 保持一致。
function sessionImportShare(readyDb, args) {
const payload = asRecord(args, 'session.importShare args');
const session = asRecord(payload.session, 'session');
@@ -1221,6 +1267,21 @@ function claudeImportMessages(readyDb, args) {
WHERE
messages.role != 'message_tombstone' AND
messages.rewind_at IS NULL AND
+ (
+ messages.role != 'tool_result' OR
+ CASE
+ WHEN messages.content NOT GLOB '{"type":"tool_result_compacted","version":1,*' THEN 1
+ WHEN json_valid(messages.content) = 0 THEN 1
+ WHEN json_type(messages.content) = 'object'
+ AND json_extract(messages.content, '$.type') = 'tool_result_compacted'
+ AND json_extract(messages.content, '$.version') = 1
+ AND json_type(messages.content, '$.originalBytes') IN ('integer', 'real')
+ AND json_extract(messages.content, '$.originalBytes') >= 0
+ AND json_type(messages.content, '$.compactedAt') IN ('integer', 'real')
+ AND json_extract(messages.content, '$.compactedAt') >= 0 THEN 0
+ ELSE 1
+ END = 1
+ ) AND
(
messages.role IS NOT excluded.role OR
messages.content IS NOT excluded.content OR
diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
index 2adc58a255..9c0721448d 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -5,6 +5,7 @@ import path from 'node:path';
import Database from 'better-sqlite3';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { SESSION_SOURCES } from '../../../../shared/sessionSource.js';
import { buildDbWorkerBundle } from '../../__tests__/dbWorkerTestUtils.js';
import type { DbClient } from '../DbClient.js';
import { createDbClient } from '../DbClient.js';
@@ -40,6 +41,10 @@ CREATE TABLE sessions (
user_send_at INTEGER,
agent_kind TEXT NOT NULL DEFAULT 'cc',
orca_role TEXT,
+ source TEXT NOT NULL DEFAULT 'desktop',
+ remote_host_id TEXT,
+ active_turn_started_at INTEGER,
+ last_turn_ended_at INTEGER,
workspace_kind TEXT NOT NULL DEFAULT 'project',
codex_history_has_product_prompt INTEGER,
codex_plan_json TEXT,
@@ -182,6 +187,290 @@ describe('db worker tx handlers', () => {
}
});
+ it.each([
+ { useInlineWorker: false, status: 'archived' as const },
+ { useInlineWorker: true, status: 'archived' as const },
+ { useInlineWorker: false, status: 'deleted' as const },
+ { useInlineWorker: true, status: 'deleted' as const },
+ ])(
+ 'compacts one explicit $status session without scanning history (inline=$useInlineWorker)',
+ async ({ useInlineWorker, status }) => {
+ await withClient(
+ async (client) => {
+ await seedSession(client, 's1');
+ await seedSession(client, 'historical');
+ await client.exec("UPDATE sessions SET status = 'archived' WHERE id = 'historical'");
+ const largeText = 'x'.repeat(70 * 1024);
+ const jsonText = JSON.stringify('y'.repeat(70 * 1024));
+ await client.exec(
+ `INSERT INTO messages
+ (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at)
+ VALUES
+ ('large', 'large', 's1', 'tool_result', ?, 'tool-1', NULL, 1),
+ ('json-text', 'json-text', 's1', 'tool_result', ?, 'tool-2', NULL, 2),
+ ('small', 'small', 's1', 'tool_result', ?, 'tool-3', NULL, 3),
+ ('structured', 'structured', 's1', 'tool_result', ?, 'tool-4', NULL, 4),
+ ('structured-text', 'structured-text', 's1', 'tool_result', ?, 'tool-5', NULL, 5),
+ ('subagent', 'subagent', 's1', 'tool_result', ?, 'tool-6', ?, 6),
+ ('invalid-meta', 'invalid-meta', 's1', 'tool_result', ?, 'tool-7', '{', 7),
+ ('media-text', 'media-text', 's1', 'tool_result', ?, 'tool-8', NULL, 8),
+ ('agent-task-use', 'agent-task-use', 's1', 'tool_use', ?, 'collab-tool', NULL, 9),
+ ('agent-task-result', 'agent-task-result', 's1', 'tool_result', ?, 'collab-tool', NULL, 10),
+ ('historical-large', 'historical-large', 'historical', 'tool_result', ?, 'tool-historical', NULL, 11)`,
+ [
+ largeText,
+ jsonText,
+ JSON.stringify('small'),
+ JSON.stringify({ type: 'image', data: 'x'.repeat(70 * 1024) }),
+ JSON.stringify(JSON.stringify({ xdt_image_urls: ['x'.repeat(70 * 1024)] })),
+ largeText,
+ JSON.stringify({ parentUuid: 'toolu_123' }),
+ largeText,
+ `![image](cindy-media://blobs/${'a'.repeat(64)}.png)\n${'x'.repeat(70 * 1024)}`,
+ JSON.stringify({ toolUseId: 'collab-tool', toolName: 'collab:wait', input: {} }),
+ largeText,
+ largeText,
+ ],
+ );
+ await client.exec('UPDATE sessions SET status = ? WHERE id = ?', [status, 's1']);
+ const [expected] = await client.query<{ compactedRows: number; originalBytes: number }>(
+ `SELECT COUNT(*) AS compactedRows,
+ SUM(length(CAST(content AS BLOB))) AS originalBytes
+ FROM messages
+ WHERE session_id = 's1'
+ AND role = 'tool_result'`,
+ );
+ expect(expected.compactedRows).toBe(9);
+
+ const result = await client.tx('toolResults.compactSession', {
+ sessionId: 's1',
+ now: 500,
+ });
+ expect(result).toEqual(expected);
+
+ const rows = await client.query<{ id: string; content: string }>(
+ `SELECT id, content
+ FROM messages WHERE role = 'tool_result' ORDER BY created_at`,
+ );
+ expect(JSON.parse(rows[0].content)).toEqual({
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: Buffer.byteLength(largeText),
+ compactedAt: 500,
+ });
+ expect(JSON.parse(rows[1].content)).toEqual({
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: Buffer.byteLength(jsonText),
+ compactedAt: 500,
+ });
+ expect(
+ rows.filter((row) => row.id !== 'historical-large' && row.content.includes('tool_result_compacted')),
+ ).toHaveLength(9);
+ expect(rows.find((row) => row.id === 'historical-large')?.content).toBe(largeText);
+ },
+ { useInlineWorker },
+ );
+ },
+ );
+
+ it.each([false, true])(
+ 'compacts every tool result without parsing content or resolving its source (inline=%s)',
+ async (useInlineWorker) => {
+ await withClient(async (client) => {
+ await seedSession(client, 's1');
+ const largeText = 'x'.repeat(20 * 1024);
+ const imageUrl = `cindy-media://blobs/${'a'.repeat(64)}.png`;
+ const mediaContent = JSON.stringify({
+ ok: true,
+ output: largeText,
+ xdt_image_urls: [imageUrl],
+ });
+ const malformedStructured = `{"xdt_image_urls":["${imageUrl}"],"output":"${largeText}`;
+ const mediaLikePlainText = `source mentions xdt_image_urls but is not structured\n${largeText}`;
+ const markerPrefixCollision = JSON.stringify({
+ type: 'tool_result_compacted',
+ version: 1,
+ note: 'ordinary tool output',
+ });
+ const cases = [
+ ['plain', largeText, 'tool-1'],
+ ['missing-id', largeText, null],
+ ['orphan', largeText, 'missing'],
+ ['structured', JSON.stringify({ ok: true, output: largeText }), 'tool-2'],
+ ['media', mediaContent, 'tool-3'],
+ ['malformed', malformedStructured, 'tool-4'],
+ ['media-like-text', mediaLikePlainText, 'tool-5'],
+ ['data-url', `data:image/png;base64,${largeText}`, 'tool-6'],
+ ['utf8-bytes', '测'.repeat(6 * 1024), 'tool-7'],
+ ] as const;
+ for (const [index, [id, content, toolUseId]] of cases.entries()) {
+ await client.exec(
+ `INSERT INTO messages
+ (id, client_id, session_id, role, content, tool_use_id, created_at)
+ VALUES (?, ?, 's1', 'tool_result', ?, ?, ?)`,
+ [id, id, content, toolUseId, index + 1],
+ );
+ }
+ await client.exec(
+ `INSERT INTO messages
+ (id, client_id, session_id, role, content, tool_use_id, created_at)
+ VALUES
+ ('small', 'small', 's1', 'tool_result', 'small', NULL, 99),
+ ('empty', 'empty', 's1', 'tool_result', '', NULL, 100),
+ ('compacted', 'compacted', 's1', 'tool_result', ?, NULL, 101),
+ ('prefix-collision', 'prefix-collision', 's1', 'tool_result', ?, NULL, 102)`,
+ [
+ JSON.stringify({
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: 123,
+ compactedAt: 100,
+ }),
+ markerPrefixCollision,
+ ],
+ );
+
+ await client.exec("UPDATE sessions SET status = 'archived' WHERE id = 's1'");
+ await expect(
+ client.tx('toolResults.compactSession', {
+ sessionId: 's1',
+ now: 500,
+ }),
+ ).resolves.toEqual({
+ compactedRows: cases.length + 3,
+ originalBytes: cases.map(([, content]) => content)
+ .reduce(
+ (sum, content) => sum + Buffer.byteLength(content),
+ Buffer.byteLength('small') + Buffer.byteLength(markerPrefixCollision),
+ ),
+ });
+
+ const rows = await client.query<{ id: string; content: string }>(
+ "SELECT id, content FROM messages WHERE role = 'tool_result' ORDER BY created_at",
+ );
+ for (const [id, originalContent] of cases) {
+ expect(JSON.parse(rows.find((row) => row.id === id)!.content)).toEqual({
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: Buffer.byteLength(originalContent),
+ compactedAt: 500,
+ });
+ }
+ expect(JSON.parse(rows.find((row) => row.id === 'small')!.content)).toEqual({
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: Buffer.byteLength('small'),
+ compactedAt: 500,
+ });
+ expect(JSON.parse(rows.find((row) => row.id === 'empty')!.content)).toEqual({
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: 0,
+ compactedAt: 500,
+ });
+ expect(JSON.parse(rows.find((row) => row.id === 'prefix-collision')!.content)).toEqual({
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: Buffer.byteLength(markerPrefixCollision),
+ compactedAt: 500,
+ });
+ const compactedBeforeRetry = rows.map((row) => row.content);
+ expect(JSON.parse(rows.find((row) => row.id === 'compacted')!.content)).toEqual({
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: 123,
+ compactedAt: 100,
+ });
+
+ await expect(
+ client.tx('toolResults.compactSession', {
+ sessionId: 's1',
+ now: 600,
+ }),
+ ).resolves.toEqual({ compactedRows: 0, originalBytes: 0 });
+ await expect(
+ client.query<{ content: string }>(
+ "SELECT content FROM messages WHERE role = 'tool_result' ORDER BY created_at",
+ ),
+ ).resolves.toEqual(compactedBeforeRetry.map((content) => ({ content })));
+ }, { useInlineWorker });
+ },
+ );
+
+ it.each([false, true])(
+ 'compacts SSH sessions and every local source while skipping restored sessions (inline=%s)',
+ async (useInlineWorker) => {
+ await withClient(async (client) => {
+ const sourceSessionIds = SESSION_SOURCES.map((source) => `source-${source}`);
+ for (const id of ['ssh', 'orca', 'turn', 'restored', ...sourceSessionIds]) {
+ await seedSession(client, id);
+ await client.exec("UPDATE sessions SET status = 'archived' WHERE id = ?", [id]);
+ await client.exec(
+ `INSERT INTO messages
+ (id, client_id, session_id, role, content, tool_use_id, created_at)
+ VALUES (?, ?, ?, 'tool_result', ?, ?, 1)`,
+ [
+ `message-${id}`,
+ `client-${id}`,
+ id,
+ JSON.stringify('x'.repeat(70 * 1024)),
+ `tool-${id}`,
+ ],
+ );
+ }
+ await client.exec("UPDATE sessions SET remote_host_id = 'host-1' WHERE id = 'ssh'");
+ for (const source of SESSION_SOURCES) {
+ await client.exec('UPDATE sessions SET source = ? WHERE id = ?', [
+ source,
+ `source-${source}`,
+ ]);
+ }
+ await client.exec("UPDATE sessions SET orca_role = 'lead' WHERE id = 'orca'");
+ await client.exec(
+ "UPDATE sessions SET active_turn_started_at = 10, last_turn_ended_at = 9 WHERE id = 'turn'",
+ );
+ await client.exec("UPDATE sessions SET status = 'active' WHERE id = 'restored'");
+
+ for (const sessionId of ['restored']) {
+ await expect(
+ client.tx('toolResults.compactSession', {
+ sessionId,
+ now: 2,
+ }),
+ ).resolves.toEqual({ compactedRows: 0, originalBytes: 0 });
+ }
+ for (const sessionId of [...sourceSessionIds, 'ssh', 'orca', 'turn']) {
+ await expect(
+ client.tx('toolResults.compactSession', {
+ sessionId,
+ now: 2,
+ }),
+ ).resolves.toEqual({ compactedRows: 1, originalBytes: 70 * 1024 + 2 });
+ }
+ const rows = await client.query<{ id: string; content: string }>(
+ 'SELECT id, content FROM messages ORDER BY id',
+ );
+ expect(
+ rows.filter((row) => {
+ try {
+ return JSON.parse(row.content)?.type === 'tool_result_compacted';
+ } catch {
+ return false;
+ }
+ }).map((row) => row.id),
+ ).toEqual(
+ [
+ 'message-ssh',
+ 'message-orca',
+ 'message-turn',
+ ...sourceSessionIds.map((id) => `message-${id}`),
+ ].sort(),
+ );
+ }, { useInlineWorker });
+ },
+ );
+
it('codex.importMessages skips likely local duplicates and upserts imported rows', async () => {
await withClient(async (client) => {
await seedSession(client, 's1');
@@ -431,6 +720,81 @@ describe('db worker tx handlers', () => {
});
});
+ it.each([false, true])(
+ 'claude.importMessages does not restore a compacted tool result (inline=%s)',
+ async (useInlineWorker) => {
+ await withClient(async (client) => {
+ await seedSession(client, 's1');
+ const marker = JSON.stringify({
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: 80_000,
+ compactedAt: 500,
+ });
+ await client.exec(
+ `INSERT INTO messages
+ (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at)
+ VALUES
+ (?, ?, ?, 'tool_result', ?, ?, NULL, ?),
+ (?, ?, ?, 'tool_result', ?, ?, NULL, ?)`,
+ [
+ 'existing',
+ 'claude-import:8-0',
+ 's1',
+ marker,
+ 'tool-2',
+ 3100,
+ 'prefix-collision',
+ 'claude-import:9-0',
+ 's1',
+ '{"type":"tool_result_compacted","version":1,',
+ 'tool-3',
+ 3200,
+ ],
+ );
+
+ await expect(
+ client.tx('claude.importMessages', {
+ sessionId: 's1',
+ importClientIdPrefix: 'claude-import:',
+ sdkSessionId: 'sdk-1',
+ rows: [
+ {
+ lineNo: 8,
+ partIndex: 0,
+ role: 'tool_result',
+ content: 'restored full body',
+ toolUseId: 'tool-2',
+ agentMeta: null,
+ createdAt: 3100,
+ },
+ {
+ lineNo: 9,
+ partIndex: 0,
+ role: 'tool_result',
+ content: 'replacement full body',
+ toolUseId: 'tool-3',
+ agentMeta: null,
+ createdAt: 3200,
+ },
+ ],
+ }),
+ ).resolves.toEqual({ changed: 1 });
+ await expect(
+ client.queryOne<{ content: string }>(
+ 'SELECT content FROM messages WHERE client_id = ?',
+ ['claude-import:8-0'],
+ ),
+ ).resolves.toEqual({ content: marker });
+ const collision = await client.queryOne<{ content: string }>(
+ 'SELECT content FROM messages WHERE client_id = ?',
+ ['claude-import:9-0'],
+ );
+ expect(JSON.parse(collision!.content)).toBe('replacement full body');
+ }, { useInlineWorker });
+ },
+ );
+
it('claude.importMessages caps oversized tool_result content at the persistence limit', async () => {
await withClient(async (client) => {
await seedSession(client, 's1');
@@ -2471,15 +2835,18 @@ async function withTwoClients(fn: (clients: [DbClient, DbClient]) => Promise<voi
const clients: DbClient[] = [];
try {
for (let index = 0; index < 2; index += 1) {
- clients.push(
- await createDbClient({
- userId: `test-user-${index}`,
- dbPath,
- drizzleDir,
- betterSqliteModulePath: require.resolve('better-sqlite3'),
- workerScriptPath,
- }),
- );
+ const client = await createDbClient({
+ userId: `test-user-${index}`,
+ dbPath,
+ drizzleDir,
+ betterSqliteModulePath: require.resolve('better-sqlite3'),
+ workerScriptPath,
+ });
+ clients.push(client);
+ // createDbClient starts its Worker lazily. Finish each startup before
+ // opening the next connection so this helper tests transaction
+ // contention rather than concurrent WAL initialization.
+ await client.queryOne('SELECT 1 AS ready');
}
await fn(clients as [DbClient, DbClient]);
} finally {
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index 3fa51c867d..62c7f981b1 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -19,6 +19,7 @@ export type DbTxName =
| 'orca.reconcileInactiveTeamWorkersForLead'
| 'sessions.renameTitles'
| 'sessions.setStatus'
+ | 'toolResults.compactSession'
| 'session.agentSwitchFallback'
| 'context.rebuild'
| 'message.insert'
@@ -399,6 +400,16 @@ export interface SessionsSetStatusResultItem {
status: 'active' | 'archived';
}
+export interface CompactSessionToolResultsArgs {
+ sessionId: string;
+ now: number;
+}
+
+export interface CompactSessionToolResultsResult {
+ compactedRows: number;
+ originalBytes: number;
+}
+
/** session.importShare 的单条 session 行(lead 与协同 Worker 共用形状)。 */
export interface SessionImportShareSessionRow {
id: string;
@@ -812,6 +823,7 @@ export type DbTxArgsByName = {
'orca.reconcileInactiveTeamWorkersForLead': OrcaReconcileInactiveTeamWorkersForLeadArgs;
'sessions.renameTitles': SessionsRenameTitlesArgs;
'sessions.setStatus': SessionsSetStatusArgs;
+ 'toolResults.compactSession': CompactSessionToolResultsArgs;
'session.agentSwitchFallback': SessionAgentSwitchFallbackArgs;
'context.rebuild': ContextRebuildArgs;
'message.insert': MessageInsertArgs;
@@ -862,6 +874,7 @@ export type DbTxResultByName = {
'orca.reconcileInactiveTeamWorkersForLead': string[];
'sessions.renameTitles': SessionsRenameTitleResult[];
'sessions.setStatus': SessionsSetStatusResultItem[];
+ 'toolResults.compactSession': CompactSessionToolResultsResult;
'session.agentSwitchFallback': undefined;
'context.rebuild': undefined;
'message.insert': { changes: number };
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionShareCompaction.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionShareCompaction.test.ts
new file mode 100644
index 0000000000..4a95da600c
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionShareCompaction.test.ts
@@ -0,0 +1,92 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ handlers: new Map<string, (...args: unknown[]) => unknown>(),
+ client: { drizzle: {} },
+ commitShareImport: vi.fn(),
+ cleanupReplacedSessionMediaRefs: vi.fn(async () => undefined),
+ compactSessionToolResultsBestEffort: vi.fn(async () => undefined),
+ broadcastSessionPatched: vi.fn(),
+ recycleSessionWorktreeForStatusChange: vi.fn(async () => undefined),
+ notifyGhostSessionEvent: vi.fn(),
+ assertStillValid: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ BrowserWindow: { getFocusedWindow: () => null, getAllWindows: () => [] },
+ dialog: { showOpenDialog: vi.fn(), showSaveDialog: vi.fn() },
+ ipcMain: {
+ handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => {
+ h.handlers.set(channel, handler);
+ }),
+ },
+}));
+vi.mock('../../../logger.js', () => ({
+ createLogger: () => ({ warn: vi.fn() }),
+}));
+vi.mock('../../../cindy-brain/index.js', () => ({
+ notifyGhostSessionEvent: h.notifyGhostSessionEvent,
+}));
+vi.mock('../../../session-share/sessionShareExport.js', () => ({
+ exportSessionShare: vi.fn(),
+}));
+vi.mock('../../../session-share/sessionShareImport.js', () => ({
+ cancelShareDraft: vi.fn(),
+ cleanupReplacedSessionMediaRefs: h.cleanupReplacedSessionMediaRefs,
+ commitShareImport: h.commitShareImport,
+ inspectShareFile: vi.fn(),
+ unlockShareDraft: vi.fn(),
+}));
+vi.mock('../../client/current.js', () => ({
+ getDbClient: () => h.client,
+ tryGetDbClient: () => h.client,
+}));
+vi.mock('../../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => 'owner-1',
+ isAppSessionBoundaryPending: () => false,
+}));
+vi.mock('../../../cindy-media/refCompensationJournal.js', () => ({
+ captureMediaRefCompensationScope: () => ({ assertStillValid: h.assertStillValid }),
+}));
+vi.mock('../../toolResultCompaction.js', () => ({
+ compactSessionToolResultsBestEffort: h.compactSessionToolResultsBestEffort,
+}));
+vi.mock('../sessions.js', () => ({
+ broadcastSessionPatched: h.broadcastSessionPatched,
+ captureSessionRecycleScope: () => ({ ownerScope: null, mediaDb: h.client.drizzle }),
+ recycleSessionWorktreeForStatusChange: h.recycleSessionWorktreeForStatusChange,
+}));
+
+describe('session share replacement compaction', () => {
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ h.handlers.clear();
+ h.commitShareImport.mockResolvedValue({
+ sessionId: 'replacement',
+ fidelity: 'full',
+ notes: [],
+ orcaWorkers: [],
+ replacedSessions: [{ id: 'replaced-session' }],
+ });
+ const { registerSessionShareIpc } = await import('../session-share.js');
+ registerSessionShareIpc();
+ });
+
+ it('starts one best-effort compaction after the replaced task is deleted', async () => {
+ const handler = h.handlers.get('local-db:session-share:commit');
+ expect(handler).toBeTypeOf('function');
+
+ await handler?.({}, { draftId: 'draft-1', overwrite: true });
+
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledTimes(1);
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledWith({
+ client: h.client,
+ sessionId: 'replaced-session',
+ });
+ expect(h.recycleSessionWorktreeForStatusChange).toHaveBeenCalledWith(
+ 'replaced-session',
+ 'deleted',
+ expect.any(Object),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index ee4a219a8c..75acbb90c0 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -50,6 +50,7 @@ const h = vi.hoisted(() => ({
task(),
) as SessionRouteLockMock,
runtimeCleanup: vi.fn(),
+ compactSessionToolResultsBestEffort: vi.fn(async () => undefined),
userDataDir: null as string | null,
}));
@@ -99,6 +100,9 @@ vi.mock('../../../security/trustedAppRenderer.js', () => ({
}));
vi.mock('../../agentIslandSessionPatch', () => ({ notifyAgentIslandSessionPatch: vi.fn() }));
vi.mock('../../../messagePersistBroadcaster', () => ({ noteSessionClearBoundary: vi.fn() }));
+vi.mock('../../toolResultCompaction.js', () => ({
+ compactSessionToolResultsBestEffort: h.compactSessionToolResultsBestEffort,
+}));
vi.mock('../../../sessionIds', () => ({ resolveBusinessSessionId: (id: string) => id }));
vi.mock('../../../maker-host/claude-transcript-relocation.js', () => ({
relocateClaudeTranscriptsForSessionMove: h.relocate,
@@ -519,6 +523,9 @@ describe('local-db:sessions:update handler wiring', () => {
patch: { status: 'deleted' },
}),
);
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionId: 'cc-local' }),
+ );
});
it('broadcasts local unarchive status patches to every window (#3175)', async () => {
@@ -535,6 +542,7 @@ describe('local-db:sessions:update handler wiring', () => {
sessionId: 'codex-local',
patch: { status: 'active' },
});
+ expect(h.compactSessionToolResultsBestEffort).not.toHaveBeenCalled();
});
// setStatus 的归档形是 { status, pinnedAt: null }:广播沿用置顶合并逻辑,
@@ -552,6 +560,9 @@ describe('local-db:sessions:update handler wiring', () => {
sessionId: 'codex-local',
patch: { status: 'archived', pinnedAt: null, summary: null },
});
+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionId: 'codex-local' }),
+ );
});
it('cleans runtime state before releasing the local terminal status lock', async () => {
diff --git a/apps/desktop/src/main/localDb/ipc/session-share.ts b/apps/desktop/src/main/localDb/ipc/session-share.ts
index 7150cd6383..331eca8dae 100644
--- a/apps/desktop/src/main/localDb/ipc/session-share.ts
+++ b/apps/desktop/src/main/localDb/ipc/session-share.ts
@@ -38,6 +38,7 @@ import {
import { getDbClient, tryGetDbClient } from '../client/current.js';
import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../appSessionState.js';
import { captureMediaRefCompensationScope } from '../../cindy-media/refCompensationJournal.js';
+import { compactSessionToolResultsBestEffort } from '../toolResultCompaction.js';
import {
broadcastSessionPatched,
captureSessionRecycleScope,
@@ -199,6 +200,10 @@ export function registerSessionShareIpc(): void {
for (const replaced of result.replacedSessions) {
if (!isStillCurrent()) break;
broadcastSessionPatched(replaced.id, { status: 'deleted' }, recycleScope.ownerScope);
+ void compactSessionToolResultsBestEffort({
+ client: importDbClient,
+ sessionId: replaced.id,
+ });
await recycleSessionWorktreeForStatusChange(replaced.id, 'deleted', recycleScope);
}
if (isStillCurrent()) {
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index cc3e8d4f8f..24158fe110 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -73,6 +73,7 @@ import { quiesceSessionBeforeWorktreeRecycle } from './sessionRemovalOperations.
import { withSessionRouteLock, withSessionRouteLocks } from '../sessionRouteLock.js';
import { cleanupSessionRuntimeForTerminalStatus } from '../sessionRuntimeCleanup.js';
import { broadcastSubagentRunsInvalidated } from './subagentRuns.js';
+import { compactSessionToolResultsBestEffort } from '../toolResultCompaction.js';
export { setSessionRuntimeCleanup } from '../sessionRuntimeCleanup.js';
@@ -101,6 +102,17 @@ function readCurrentDbClientUserId(): string | null {
}
}
+function compactTerminalSessionToolResults(
+ client: DbClient,
+ sessionId: string,
+ status: unknown,
+): void {
+ if (status !== 'archived' && status !== 'deleted') return;
+ void compactSessionToolResultsBestEffort({
+ client,
+ sessionId,
+ });
+}
type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null;
type SessionRemovalCancelOperations = (sessionId: string) => Promise<void>;
type SessionRemovalCleanup = (sessionId: string) => Promise<void>;
@@ -1412,7 +1424,8 @@ export function registerSessionIpc(
const sid = requireString(id, 'id');
const ownerScope = captureOwnerScope();
const p = requireObject(patch, 'patch');
- const db = getDbClient().drizzle;
+ const dbClient = getDbClient();
+ const db = dbClient.drizzle;
// 工作目录切换必须和发送/懒启动共用同一把路由锁。否则发送可能在
// 读取旧目录后、写入新目录前重建 runtime,随后仍在旧目录执行。
const update = async () => {
@@ -1653,6 +1666,7 @@ export function registerSessionIpc(
scheduleWorktreeRecycleForStatusChange(sid, p.status, { ownerScope, mediaDb: db });
notifyGhostSessionStatusChange(sid, p.status, updated.workingDir);
cleanupSessionTerminalArtifacts(sid, p.status);
+ compactTerminalSessionToolResults(dbClient, sid, p.status);
return updated;
};
return p.workingDir === undefined ? update() : withSessionRouteLock(sid, update);
@@ -1730,7 +1744,8 @@ export async function patchSessionMetaInDb(
throwIpcError('INVALID_PARAMS', 'title must be a string');
}
- const db = getDbClient().drizzle;
+ const dbClient = getDbClient();
+ const db = dbClient.drizzle;
const setObj = sessionPatchToRow(patch, { bumpUpdatedAt: false });
// 控制端远程改名走这条,与本机改名同口径(同样先记号后写库)。
if (patch.title !== undefined) noteUserTitleWritten(sessionId);
@@ -1782,6 +1797,7 @@ export async function patchSessionMetaInDb(
m.maybeGenerateSessionTaskSummary(sessionId, { force: true }),
);
}
+ compactTerminalSessionToolResults(dbClient, sessionId, patch.status);
return updated;
}
@@ -1909,6 +1925,9 @@ export async function setSessionsStatusInDb(
}
return rows;
});
+ for (const item of applied) {
+ compactTerminalSessionToolResults(dbClient, item.sessionId, item.status);
+ }
if (!isOwnerScopeCurrent(ownerScope))
return applied.map((item) => ({
sessionId: item.sessionId,
diff --git a/apps/desktop/src/main/localDb/orcaTeamStore.ts b/apps/desktop/src/main/localDb/orcaTeamStore.ts
index e9395cf6c9..89fdfc879b 100644
--- a/apps/desktop/src/main/localDb/orcaTeamStore.ts
+++ b/apps/desktop/src/main/localDb/orcaTeamStore.ts
@@ -10,6 +10,7 @@ import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';
import { notifyAgentIslandSessionPatch } from './agentIslandSessionPatch.js';
import { withSessionRouteLock, withSessionRouteLocks } from './sessionRouteLock.js';
import { cleanupSessionRuntimeForTerminalStatus } from './sessionRuntimeCleanup.js';
+import { compactSessionToolResultsBestEffort } from './toolResultCompaction.js';
const log = createLogger('orca-team-store');
@@ -248,9 +249,10 @@ export async function markTeamEnded(
* orca_role 字段保留 'worker' 不动 — 历史上下文识别需要它。
*/
export async function archiveWorkersByTeam(teamId: string): Promise<string[]> {
+ const client = getDbClient();
const candidateIds = await listActiveWorkerSessionIdsForTeam(teamId);
const updatedIds = await withSessionRouteLocks(candidateIds, async () => {
- const ids = await getDbClient().tx('orca.archiveWorkersByTeam', {
+ const ids = await client.tx('orca.archiveWorkersByTeam', {
teamId,
sessionIds: candidateIds,
now: Date.now(),
@@ -258,7 +260,10 @@ export async function archiveWorkersByTeam(teamId: string): Promise<string[]> {
for (const id of ids) cleanupSessionRuntimeForTerminalStatus(id, 'archived');
return ids;
});
- for (const id of updatedIds) broadcastSessionPatch(id, { status: 'archived' });
+ for (const id of updatedIds) {
+ broadcastSessionPatch(id, { status: 'archived' });
+ void compactSessionToolResultsBestEffort({ client, sessionId: id });
+ }
return updatedIds;
}
@@ -291,9 +296,10 @@ export async function markWorkersStatusByTeam(
export async function reconcileInactiveTeamWorkersForLead(
leadSessionId: string,
): Promise<string[]> {
+ const client = getDbClient();
const candidateIds = await listActiveWorkerSessionIdsForInactiveTeams(leadSessionId);
const updatedIds = await withSessionRouteLocks(candidateIds, async () => {
- const ids = await getDbClient().tx('orca.reconcileInactiveTeamWorkersForLead', {
+ const ids = await client.tx('orca.reconcileInactiveTeamWorkersForLead', {
leadSessionId,
sessionIds: candidateIds,
now: Date.now(),
@@ -301,7 +307,10 @@ export async function reconcileInactiveTeamWorkersForLead(
for (const id of ids) cleanupSessionRuntimeForTerminalStatus(id, 'archived');
return ids;
});
- for (const id of updatedIds) broadcastSessionPatch(id, { status: 'archived' });
+ for (const id of updatedIds) {
+ broadcastSessionPatch(id, { status: 'archived' });
+ void compactSessionToolResultsBestEffort({ client, sessionId: id });
+ }
return updatedIds;
}
@@ -500,12 +509,14 @@ export async function restoreWorkerDoneIfIdle(workerId: string): Promise<boolean
* 这条路径只服务失败清理,不影响正常协同结束时保留历史 worker link 的语义。
*/
export async function removeWorker(workerId: string): Promise<void> {
- const removedSessionId = await getDbClient().tx('orca.removeWorker', {
+ const client = getDbClient();
+ const removedSessionId = await client.tx('orca.removeWorker', {
workerId,
now: Date.now(),
});
if (removedSessionId) {
broadcastSessionPatch(removedSessionId, { status: 'archived', orcaRole: null });
+ void compactSessionToolResultsBestEffort({ client, sessionId: removedSessionId });
}
}
@@ -524,8 +535,9 @@ export async function setWorkerFocus(teamId: string, workerId: string): Promise<
* 归档单个 worker session, 不牵连同 team 其他 worker。
*/
export async function archiveSingleWorkerSession(sessionId: string): Promise<void> {
+ const client = getDbClient();
const changed = await withSessionRouteLock(sessionId, async () => {
- const result = await getDbClient().drizzle
+ const result = await client.drizzle
.update(sessions)
.set({ status: 'archived', updatedAt: Date.now() })
.where(and(eq(sessions.id, sessionId), ne(sessions.status, 'deleted')))
@@ -534,7 +546,10 @@ export async function archiveSingleWorkerSession(sessionId: string): Promise<voi
cleanupSessionRuntimeForTerminalStatus(sessionId, 'archived');
return true;
});
- if (changed) broadcastSessionPatch(sessionId, { status: 'archived' });
+ if (changed) {
+ broadcastSessionPatch(sessionId, { status: 'archived' });
+ void compactSessionToolResultsBestEffort({ client, sessionId });
+ }
}
async function listActiveWorkerSessionIdsForTeam(teamId: string): Promise<string[]> {
diff --git a/apps/desktop/src/main/localDb/toolResultCompaction.ts b/apps/desktop/src/main/localDb/toolResultCompaction.ts
new file mode 100644
index 0000000000..595b7cf6ad
--- /dev/null
+++ b/apps/desktop/src/main/localDb/toolResultCompaction.ts
@@ -0,0 +1,33 @@
+import { createLogger } from '../logger.js';
+import { drainPersistQueue } from '../messagePersistBroadcaster.js';
+import type { DbClient } from './client/DbClient.js';
+
+const log = createLogger('localDb/toolResultCompaction');
+
+export async function compactSessionToolResultsBestEffort(options: {
+ client: DbClient;
+ sessionId: string;
+}): Promise<void> {
+ try {
+ // Archive/delete must remain responsive, so callers fire-and-forget this
+ // whole helper. Drain only the writes already queued at the status boundary;
+ // the compaction transaction itself stays outside the global persist queue.
+ await drainPersistQueue();
+ const result = await options.client.tx('toolResults.compactSession', {
+ sessionId: options.sessionId,
+ now: Date.now(),
+ });
+ if (result.compactedRows > 0) {
+ log.info('task tool results compacted', {
+ sessionId: options.sessionId,
+ rows: result.compactedRows,
+ originalBytes: result.originalBytes,
+ });
+ }
+ } catch (error) {
+ log.warn('task tool result compaction failed', {
+ sessionId: options.sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 341c02c15b..c83b8c9d41 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -76,6 +76,8 @@ export function tx(db: Database.Database, args: unknown): unknown {
return sessionsRenameTitles(db, txArgs);
case 'sessions.setStatus':
return sessionsSetStatus(db, txArgs);
+ case 'toolResults.compactSession':
+ return compactSessionToolResults(db, txArgs);
case 'session.agentSwitchFallback':
return sessionAgentSwitchFallback(db, txArgs);
case 'context.rebuild':
@@ -779,6 +781,77 @@ function invalidateSessionListProjection(db: Database.Database, sessionId: strin
).run(sessionId);
}
+function compactSessionToolResults(
+ db: Database.Database,
+ args: unknown,
+): {
+ compactedRows: number;
+ originalBytes: number;
+} {
+ const payload = asRecord(args, 'toolResults.compactSession args');
+ const sessionId = expectString(payload.sessionId, 'sessionId');
+ const now = expectNumber(payload.now, 'now');
+
+ const selectSession = db.prepare(`
+ SELECT id
+ FROM sessions
+ WHERE id = ?
+ AND status IN ('archived', 'deleted')
+ LIMIT 1
+ `);
+ // Archived/deleted tool results are intentionally treated uniformly. Ordinary
+ // rows only pay for the fixed-prefix check. JSON validation runs solely for
+ // the tiny set of rows that look like our marker, preventing an unrelated
+ // tool result with the same prefix from being skipped forever.
+ const uncompactedContentPredicate = `
+ CASE
+ WHEN content NOT GLOB '{"type":"tool_result_compacted","version":1,*' THEN 1
+ WHEN json_valid(content) = 0 THEN 1
+ WHEN json_type(content) = 'object'
+ AND json_extract(content, '$.type') = 'tool_result_compacted'
+ AND json_extract(content, '$.version') = 1
+ AND json_type(content, '$.originalBytes') IN ('integer', 'real')
+ AND json_extract(content, '$.originalBytes') >= 0
+ AND json_type(content, '$.compactedAt') IN ('integer', 'real')
+ AND json_extract(content, '$.compactedAt') >= 0 THEN 0
+ ELSE 1
+ END
+ `;
+ const summarizeCandidates = db.prepare(`
+ SELECT COALESCE(SUM(octet_length(content)), 0) AS originalBytes
+ FROM messages
+ WHERE session_id = ?
+ AND role = 'tool_result'
+ AND (${uncompactedContentPredicate}) = 1
+ `);
+ const compactMessages = db.prepare(`
+ UPDATE messages
+ SET content = json_object(
+ 'type', 'tool_result_compacted',
+ 'version', 1,
+ 'originalBytes', octet_length(content),
+ 'compactedAt', ?
+ )
+ WHERE session_id = ?
+ AND role = 'tool_result'
+ AND (${uncompactedContentPredicate}) = 1
+ `);
+
+ return db.transaction(() => {
+ const session = selectSession.get(sessionId) as { id: string } | undefined;
+ if (!session) {
+ return { compactedRows: 0, originalBytes: 0 };
+ }
+
+ const summary = summarizeCandidates.get(session.id) as { originalBytes: number };
+ const compactedRows = compactMessages.run(now, session.id).changes;
+ return {
+ compactedRows,
+ originalBytes: compactedRows > 0 ? summary.originalBytes : 0,
+ };
+ })();
+}
+
function codexImportMessages(db: Database.Database, args: unknown): { changed: number } {
const payload = asRecord(args, 'codex.importMessages args');
const sessionId = expectString(payload.sessionId, 'sessionId');
@@ -863,6 +936,21 @@ function claudeImportMessages(db: Database.Database, args: unknown): { changed:
WHERE
messages.role != 'message_tombstone' AND
messages.rewind_at IS NULL AND
+ (
+ messages.role != 'tool_result' OR
+ CASE
+ WHEN messages.content NOT GLOB '{"type":"tool_result_compacted","version":1,*' THEN 1
+ WHEN json_valid(messages.content) = 0 THEN 1
+ WHEN json_type(messages.content) = 'object'
+ AND json_extract(messages.content, '$.type') = 'tool_result_compacted'
+ AND json_extract(messages.content, '$.version') = 1
+ AND json_type(messages.content, '$.originalBytes') IN ('integer', 'real')
+ AND json_extract(messages.content, '$.originalBytes') >= 0
+ AND json_type(messages.content, '$.compactedAt') IN ('integer', 'real')
+ AND json_extract(messages.content, '$.compactedAt') >= 0 THEN 0
+ ELSE 1
+ END = 1
+ ) AND
(
messages.role IS NOT excluded.role OR
messages.content IS NOT excluded.content OR
diff --git a/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts b/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts
index 90a130fbe7..eb1c0f95c6 100644
--- a/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts
+++ b/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts
@@ -24,13 +24,20 @@ vi.mock('react-i18next', () => ({
// t 返回原 key(带 count 时后缀 :count),断言直接对 key 做,避免复制文案表。
useTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) =>
- options && typeof options.count === 'number' ? `${key}:${String(options.count)}` : key,
+ options && typeof options.count === 'number'
+ ? `${key}:${String(options.count)}`
+ : options && typeof options.size === 'string'
+ ? `${key}:${options.size}`
+ : key,
}),
}));
// Lightbox 家族与文件 chip 菜单只在交互后出现,渲染测试不涉及 — mock 掉,
// 避免拖进重型依赖(DiffView / 文稿浏览器)。
-vi.mock('@/components/chat/TextLightbox', () => ({ TextLightbox: () => null }));
+vi.mock('@/components/chat/TextLightbox', () => ({
+ formatBytes: (bytes: number) => `${bytes / 1024} KB`,
+ TextLightbox: () => null,
+}));
vi.mock('@/components/chat/ImageLightbox', () => ({ ImageLightbox: () => null }));
vi.mock('@/components/chat/ToolPayloadLightbox', () => ({
ToolPayloadLightbox: ({ payload }: { payload: unknown }) => JSON.stringify(payload),
@@ -395,6 +402,24 @@ describe('AgentActionRow — 行主文案', () => {
expect(screen.queryByText(/^# /)).toBeNull();
});
+ it('已精简的工具结果显示释放提示与原始大小', () => {
+ render(
+ createElement(AgentActionRow, {
+ message: mkTool('t1', 'Bash', { command: 'git status' }),
+ toolResult: JSON.stringify({
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: 128 * 1024,
+ compactedAt: 500,
+ }),
+ }),
+ );
+
+ fireEvent.click(screen.getByRole('button'));
+ expect(screen.getByText('chat.toolResultCompacted:128 KB')).toBeTruthy();
+ expect(document.body.textContent).not.toContain('tool_result_compacted');
+ });
+
it('exposes the tool clientId as a viewport child anchor', () => {
const { container } = render(
createElement(AgentActionRow, {
diff --git a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
index 3ddae39711..b450b5caba 100644
--- a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
+++ b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
@@ -79,6 +79,10 @@ import { ImageLightbox } from './ImageLightbox';
import { TextLightbox } from './TextLightbox';
import { ToolPayloadLightbox, type ToolPayloadMode } from './ToolPayloadLightbox';
import { useFileChipContextMenu } from './useFileChipContextMenu';
+import {
+ formatToolResultCompactionBytes,
+ parseToolResultCompactionMarker,
+} from '@cindy/maker-shared/tool-result-compaction';
/**
* 点击走「文件类」交互(diff / 文稿 / 图片 lightbox)的工具:CC 大写 + pi 小写
@@ -682,6 +686,12 @@ export function AgentActionRow({
status = 'done',
}: AgentActionRowProps) {
const { t } = useTranslation();
+ const compactedToolResult = parseToolResultCompactionMarker(toolResult);
+ const displayedToolResult = compactedToolResult
+ ? t('chat.toolResultCompacted', {
+ size: formatToolResultCompactionBytes(compactedToolResult.originalBytes),
+ })
+ : toolResult;
// 会话文件来源:remote 时 Read 图片走远程媒体改写、文件打开走远程分流。
const fileCtx = useChatSessionFile();
const toolName = message.toolName ?? '';
@@ -750,8 +760,8 @@ export function AgentActionRow({
descriptor.command
? descriptor.command
: null;
- const userFacingToolResult = toolResult
- ? (humanizeDocumentToolResult(toolName, toolResult) ?? toolResult)
+ const userFacingToolResult = displayedToolResult
+ ? (humanizeDocumentToolResult(toolName, displayedToolResult) ?? displayedToolResult)
: null;
const stats = useMemo(() => statsForToolCall(toolName, inp), [toolName, inp]);
const isFilePathTool = FILE_PATH_TOOLS.has(toolName);
diff --git a/apps/desktop/src/renderer/components/chat/ToolCallCard.tsx b/apps/desktop/src/renderer/components/chat/ToolCallCard.tsx
index 2a7d72ee2e..467484a021 100644
--- a/apps/desktop/src/renderer/components/chat/ToolCallCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/ToolCallCard.tsx
@@ -10,6 +10,7 @@
import { useRef, useState } from 'react';
import { ChevronRight, FileText } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
import { cn, basename } from '@/lib/utils';
import { shouldOpenTextLightboxForOrigin } from '@/lib/filePreview';
@@ -19,6 +20,10 @@ import { Collapse } from '@/components/ui/collapse';
import { Tip } from '@/components/ui/tooltip';
import { DiffView } from './DiffView';
import { TextLightbox } from './TextLightbox';
+import {
+ formatToolResultCompactionBytes,
+ parseToolResultCompactionMarker,
+} from '@cindy/maker-shared/tool-result-compaction';
// text-lightbox F1: only these 4 tools get the preview entry chip-row.
// Bash/Grep/Glob etc. are explicitly out of scope per the spec's 非目标 list.
@@ -84,7 +89,14 @@ export function getToolSummary(toolName: string, input: unknown): string {
}
export function ToolCallCard({ toolName, toolInput, summary, toolResult }: ToolCallCardProps) {
+ const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
+ const compactedToolResult = parseToolResultCompactionMarker(toolResult);
+ const displayedToolResult = compactedToolResult
+ ? t('chat.toolResultCompacted', {
+ size: formatToolResultCompactionBytes(compactedToolResult.originalBytes),
+ })
+ : toolResult;
// 会话文件来源:remote 时文件 chip 点击走远程分流(取回缓存副本),不直打本机 fs。
const fileCtx = useChatSessionFile();
// text-lightbox F1/F3: open TextLightbox on chip click.
@@ -228,7 +240,7 @@ export function ToolCallCard({ toolName, toolInput, summary, toolResult }: ToolC
)}
{/* Result section */}
- {toolResult && (
+ {displayedToolResult && (
<div>
<div className="mb-1 text-xs font-medium text-[var(--msg-tool-card-chevron)]">
Result
@@ -243,7 +255,7 @@ export function ToolCallCard({ toolName, toolInput, summary, toolResult }: ToolC
'select-text',
)}
>
- {toolResult}
+ {displayedToolResult}
</pre>
</div>
)}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 3700922729..d6b3001884 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7538,6 +7538,7 @@
"promptSend": "Send",
"promptCancel": "Cancel"
},
+ "toolResultCompacted": "Full tool output was released (original size {{size}})",
"agentActionRow": {
"noContent": "Nothing to display",
"fileChange": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c67c875a2d..6ad079d29b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7535,6 +7535,7 @@
"promptSend": "送信",
"promptCancel": "キャンセル"
},
+ "toolResultCompacted": "Full tool output was released (original size {{size}})",
"agentActionRow": {
"noContent": "表示できる内容はありません",
"fileChange": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index bd1c1f9290..bacd7ccf66 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7535,6 +7535,7 @@
"promptSend": "보내기",
"promptCancel": "취소"
},
+ "toolResultCompacted": "Full tool output was released (original size {{size}})",
"agentActionRow": {
"noContent": "표시할 내용이 없음",
"fileChange": {
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 ebde6549d5..b902b485a0 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7527,6 +7527,7 @@
"promptSend": "发送",
"promptCancel": "取消"
},
+ "toolResultCompacted": "Full tool output was released (original size {{size}})",
"agentActionRow": {
"noContent": "无可展示内容",
"fileChange": {
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 5fa93af6cd..2ca655a568 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -7526,6 +7526,7 @@
"promptSend": "傳送",
"promptCancel": "取消"
},
+ "toolResultCompacted": "Full tool output was released (original size {{size}})",
"agentActionRow": {
"noContent": "無可展示內容",
"fileChange": {
diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.ts
index 6c8c0f5c50..9159dddc17 100644
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@ -5,6 +5,7 @@ import {
UI_ACTION_TRIGGER_PREFIX,
} from '@cindy/maker-shared/synthetic-trigger';
import { composerDocumentFromSerializedMessage } from '@/session/composerDocument';
+import { buildMobileMessageCopyText } from '@/session/messageActions';
import { normalizeRemoteMessages } from '@/session/messageNormalize';
import type { RemoteMessage } from '@/session/types';
@@ -476,6 +477,37 @@ describe('normalizeRemoteMessages', () => {
});
});
+ it('renders and copies compacted tool results without exposing the internal marker', () => {
+ const [item] = normalizeRemoteMessages([
+ message({
+ id: 'tool-compacted',
+ role: 'tool_use',
+ content: {
+ toolUseId: 'tu_compacted',
+ toolName: 'Read',
+ input: { file_path: '/repo/a.ts' },
+ },
+ }),
+ message({
+ id: 'result-compacted',
+ role: 'tool_result',
+ toolUseId: 'tu_compacted',
+ content: {
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: 128 * 1024,
+ compactedAt: 500,
+ },
+ }),
+ ]);
+
+ expect(item.secondaryBody).toBe('Full tool output was released (original size 128 KB)');
+ expect(buildMobileMessageCopyText(item)).toContain(
+ 'Full tool output was released (original size 128 KB)',
+ );
+ expect(buildMobileMessageCopyText(item)).not.toContain('tool_result_compacted');
+ });
+
it('marks tools settled by result arrival, including hidden orca empty results', () => {
const items = normalizeRemoteMessages([
message({
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 74c3c6e883..f1de4c0451 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -116,6 +116,7 @@
"controlFork": "Fork session",
"markdownDocAriaLabel": "Message body",
"toolOutputTitle": "{{label}} output",
+ "toolResultCompacted": "Full tool output was released (original size {{size}})",
"mermaidEmpty": "Empty Mermaid diagram.",
"diffEditCount": "{{n}} edits"
},
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 35a142d186..2409d98495 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -116,6 +116,7 @@
"controlFork": "セッションを分岐",
"markdownDocAriaLabel": "メッセージ本文",
"toolOutputTitle": "{{label}} の出力",
+ "toolResultCompacted": "Full tool output was released (original size {{size}})",
"mermaidEmpty": "空の Mermaid 図。",
"diffEditCount": "{{n}} 件の編集"
},
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index d4e9bc8050..be863a205c 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -116,6 +116,7 @@
"controlFork": "세션 분기",
"markdownDocAriaLabel": "메시지 본문",
"toolOutputTitle": "{{label}} 출력",
+ "toolResultCompacted": "Full tool output was released (original size {{size}})",
"mermaidEmpty": "빈 Mermaid 다이어그램.",
"diffEditCount": "{{n}}개 편집"
},
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index df9c759f19..31e2b4f016 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -116,6 +116,7 @@
"controlFork": "分叉任务",
"markdownDocAriaLabel": "消息正文",
"toolOutputTitle": "{{label}} 输出",
+ "toolResultCompacted": "Full tool output was released (original size {{size}})",
"mermaidEmpty": "空 Mermaid 图表。",
"diffEditCount": "{{n}} 处编辑"
},
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index 51c3708961..10dedc99e8 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -116,6 +116,7 @@
"controlFork": "分叉任務",
"markdownDocAriaLabel": "訊息正文",
"toolOutputTitle": "{{label}} 輸出",
+ "toolResultCompacted": "Full tool output was released (original size {{size}})",
"mermaidEmpty": "空 Mermaid 圖表。",
"diffEditCount": "{{n}} 處編輯"
},
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index 81214ec691..48806f689c 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -1,6 +1,7 @@
import type { RemoteMessage, RemoteMessageRole } from '@/session/types';
import type { MobileSystemCardType } from '@/session/systemCard';
import { contentToPreview } from '@/utils/contentPreview';
+import { i18n } from '@/i18n';
import { describeAgentAuthError } from '@/device-link/remoteStatus';
import {
buildMessageToolResultPairing,
@@ -15,6 +16,10 @@ import {
type AgentTaskTerminalStatus,
} from '@cindy/maker-shared/agent-task';
import { isSyntheticTriggerText } from '@cindy/maker-shared/synthetic-trigger';
+import {
+ formatToolResultCompactionBytes,
+ parseToolResultCompactionMarker,
+} from '@cindy/maker-shared/tool-result-compaction';
import {
buildPayloadToolDiff,
extractPayloadToolResultMedia,
@@ -172,7 +177,9 @@ interface ToolUsePayload extends MessageNormalizeToolUse {
export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): NormalizedRemoteMessage[] {
const sorted = sortMessagesByCreatedAt(messages);
- const toolResultPairing = buildMessageToolResultPairing(sorted);
+ const toolResultPairing = buildMessageToolResultPairing(sorted, {
+ contentToPreview: toolResultContentToPreview,
+ });
const result: NormalizedRemoteMessage[] = [];
for (const message of sorted) {
@@ -412,6 +419,14 @@ export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): Nor
return result;
}
+function toolResultContentToPreview(content: unknown): string {
+ const compacted = parseToolResultCompactionMarker(content);
+ if (!compacted) return contentToPreview(content);
+ return i18n.t('message.renderer.toolResultCompacted', {
+ size: formatToolResultCompactionBytes(compacted.originalBytes),
+ });
+}
+
function toolResultContentFor(
message: RemoteMessage,
tool: ToolUsePayload,
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index f1a75b67e4..2d4a6a47e0 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -67,6 +67,7 @@
"./thinking-text": "./src/thinkingText.ts",
"./turn-continuation": "./src/turnContinuation.ts",
"./tool-use-descriptor": "./src/toolUseDescriptor.ts",
+ "./tool-result-compaction": "./src/toolResultCompaction.ts",
"./update-channel": "./src/updateChannel.ts",
"./url-text-boundary": "./src/urlTextBoundary.ts",
"./usage-format": "./src/usageFormat.ts",
diff --git a/packages/maker-shared/src/__tests__/toolResultCompaction.test.ts b/packages/maker-shared/src/__tests__/toolResultCompaction.test.ts
new file mode 100644
index 0000000000..d569d66b91
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/toolResultCompaction.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ formatToolResultCompactionBytes,
+ parseToolResultCompactionMarker,
+} from '../toolResultCompaction.js';
+
+describe('tool result compaction marker', () => {
+ const marker = {
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: 128 * 1024,
+ compactedAt: 500,
+ } as const;
+
+ it('parses persisted strings and mapped message objects', () => {
+ expect(parseToolResultCompactionMarker(JSON.stringify(marker))).toEqual(marker);
+ expect(parseToolResultCompactionMarker(marker)).toEqual(marker);
+ });
+
+ it('rejects malformed or unsupported values', () => {
+ expect(parseToolResultCompactionMarker('{')).toBeNull();
+ expect(parseToolResultCompactionMarker({ ...marker, version: 2 })).toBeNull();
+ expect(parseToolResultCompactionMarker({ ...marker, originalBytes: -1 })).toBeNull();
+ expect(parseToolResultCompactionMarker('ordinary tool output')).toBeNull();
+ });
+
+ it('formats the retained original byte count consistently across clients', () => {
+ expect(formatToolResultCompactionBytes(128 * 1024)).toBe('128 KB');
+ expect(formatToolResultCompactionBytes(3.4 * 1024 * 1024)).toBe('3.4 MB');
+ });
+});
diff --git a/packages/maker-shared/src/index.ts b/packages/maker-shared/src/index.ts
index c511e7d9a3..33c86fa9b2 100644
--- a/packages/maker-shared/src/index.ts
+++ b/packages/maker-shared/src/index.ts
@@ -49,6 +49,7 @@ export * from './subagentObservation.js';
export * from './subagentWorkspace.js';
export * from './systemCard.js';
export * from './toolUseDescriptor.js';
+export * from './toolResultCompaction.js';
export * from './thinkingText.js';
export * from './turnContinuation.js';
export * from './updateChannel.js';
diff --git a/packages/maker-shared/src/toolResultCompaction.ts b/packages/maker-shared/src/toolResultCompaction.ts
new file mode 100644
index 0000000000..8bf6e874e2
--- /dev/null
+++ b/packages/maker-shared/src/toolResultCompaction.ts
@@ -0,0 +1,50 @@
+export interface ToolResultCompactionMarker {
+ type: 'tool_result_compacted';
+ version: 1;
+ originalBytes: number;
+ compactedAt: number;
+}
+
+export function parseToolResultCompactionMarker(
+ content: unknown,
+): ToolResultCompactionMarker | null {
+ let parsed = content;
+ if (typeof parsed === 'string') {
+ if (!parsed.includes('tool_result_compacted')) return null;
+ try {
+ parsed = JSON.parse(parsed) as unknown;
+ } catch {
+ return null;
+ }
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
+ const record = parsed as Record<string, unknown>;
+ if (
+ record.type !== 'tool_result_compacted' ||
+ record.version !== 1 ||
+ typeof record.originalBytes !== 'number' ||
+ !Number.isFinite(record.originalBytes) ||
+ record.originalBytes < 0 ||
+ typeof record.compactedAt !== 'number' ||
+ !Number.isFinite(record.compactedAt) ||
+ record.compactedAt < 0
+ ) {
+ return null;
+ }
+ return {
+ type: 'tool_result_compacted',
+ version: 1,
+ originalBytes: record.originalBytes,
+ compactedAt: record.compactedAt,
+ };
+}
+
+export function formatToolResultCompactionBytes(bytes: number): string {
+ if (!Number.isFinite(bytes) || bytes < 0) return '0 B';
+ if (bytes < 1024) return `${bytes} B`;
+ const kb = bytes / 1024;
+ if (kb < 1024) return `${kb < 10 ? kb.toFixed(1) : Math.round(kb)} KB`;
+ const mb = kb / 1024;
+ if (mb < 1024) return `${mb.toFixed(1)} MB`;
+ return `${(mb / 1024).toFixed(1)} GB`;
+}