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(maker-shared): roll the byte formatter over at the unit boundary

Eapp1ed57c4de8f972
diff --git a/packages/maker-shared/src/__tests__/toolResultCompaction.test.ts b/packages/maker-shared/src/__tests__/toolResultCompaction.test.ts
index d569d66b91..7670c9bd09 100644
--- a/packages/maker-shared/src/__tests__/toolResultCompaction.test.ts
+++ b/packages/maker-shared/src/__tests__/toolResultCompaction.test.ts
@@ -29,4 +29,17 @@ describe('tool result compaction marker', () => {
expect(formatToolResultCompactionBytes(128 * 1024)).toBe('128 KB');
expect(formatToolResultCompactionBytes(3.4 * 1024 * 1024)).toBe('3.4 MB');
});
+
+ it('字节数取整后跨过档位时升档,不留 "1024 KB" / "1024.0 MB"', () => {
+ expect(formatToolResultCompactionBytes(1023.6)).toBe('1.0 KB');
+ expect(formatToolResultCompactionBytes(1024 * 1024 - 1)).toBe('1.0 MB');
+ expect(formatToolResultCompactionBytes(1023)).toBe('1023 B');
+ expect(formatToolResultCompactionBytes(1024 * 1023)).toBe('1023 KB');
+ // 各档原有精度不变:MB/GB 始终一位小数,只有取整后真的达到 1024 才升档。
+ expect(formatToolResultCompactionBytes(12.4 * 1024 * 1024)).toBe('12.4 MB');
+ expect(formatToolResultCompactionBytes(10.5 * 1024 * 1024)).toBe('10.5 MB');
+ expect(formatToolResultCompactionBytes(50.49 * 1024 * 1024)).toBe('50.5 MB');
+ expect(formatToolResultCompactionBytes(1024 * 1024 * 1023.6)).toBe('1023.6 MB');
+ });
});
+
diff --git a/packages/maker-shared/src/toolResultCompaction.ts b/packages/maker-shared/src/toolResultCompaction.ts
index 8bf6e874e2..7c8f8cd924 100644
--- a/packages/maker-shared/src/toolResultCompaction.ts
+++ b/packages/maker-shared/src/toolResultCompaction.ts
@@ -39,12 +39,34 @@ export function parseToolResultCompactionMarker(
};
}
+const COMPACTED_BYTE_UNITS = ['B', 'KB', 'MB', 'GB'] as const;
+
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`;
+ // 先取整字节数,再交替换档位:1048575 B 属于 MB 档,不该停在 KB 档被四舍五入成
+ // "1024 KB" —— 那一档的合法最大值是 1023,超过就该升到下一档。
+ let value = Math.round(bytes);
+ let unit = 0;
+ while (value >= 1024 && unit < COMPACTED_BYTE_UNITS.length - 1) {
+ value /= 1024;
+ unit += 1;
+ }
+ for (;;) {
+ // 展示值也可能因为取整跨过 1024(1023.6 KB → "1024"),此时同样要升档。
+ // 各档原有精度保持不变:KB 小于 10 保留一位小数、其余取整;MB 与 GB 始终一位小数。
+ const text =
+ unit === 0
+ ? `${value}`
+ : unit === 1
+ ? value < 10
+ ? value.toFixed(1)
+ : `${Math.round(value)}`
+ : value.toFixed(1);
+ if (Number(text) < 1024 || unit === COMPACTED_BYTE_UNITS.length - 1) {
+ return `${text} ${COMPACTED_BYTE_UNITS[unit]}`;
+ }
+ value = Number(text) / 1024;
+ unit += 1;
+ }
}
+