result-persistence-format.test.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { describe, expect, it } from "vitest";
  2. import { truncateMiddleForModel } from "../src/tool/result-persistence-format.js";
  3. const HEAD_CHARS = 5_000;
  4. const TAIL_CHARS = 5_000;
  5. const marker = (count: string) => `\n\n... [${count} characters truncated] ...\n\n`;
  6. const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
  7. describe("truncateMiddleForModel", () => {
  8. it("keeps text within the limit plus slack unchanged", () => {
  9. const text = "x".repeat(10_000 + 1_024);
  10. expect(truncateMiddleForModel(text)).toBe(text);
  11. });
  12. it("adds the recorded counts of nested truncation markers to the new count", () => {
  13. const head = "h".repeat(HEAD_CHARS);
  14. const tail = "t".repeat(TAIL_CHARS);
  15. const first = marker("300");
  16. const second = marker("4500");
  17. const text = `${head}${"m".repeat(1_000)}${first}${"m".repeat(500)}${second}${"m".repeat(500)}${tail}`;
  18. // 被截掉的中段里已有两条截断说明:数字按它们记录的原字符数累计,反映原文长度。
  19. const removed = text.length - HEAD_CHARS - TAIL_CHARS;
  20. const expected = removed - first.length - second.length + 300 + 4_500;
  21. expect(truncateMiddleForModel(text)).toBe(
  22. `${head}\n\n... [${expected} characters truncated] ...\n\n${tail}`,
  23. );
  24. });
  25. it("does not trust markers whose count is too long or shorter than the marker itself", () => {
  26. const head = "h".repeat(HEAD_CHARS);
  27. const tail = "t".repeat(TAIL_CHARS);
  28. // 16 位数字超出可信范围;5 小于说明本身的长度,都按普通文本计数。
  29. const text = `${head}${"m".repeat(1_000)}${marker("1234567890123456")}${marker("5")}${"m".repeat(1_000)}${tail}`;
  30. const removed = text.length - HEAD_CHARS - TAIL_CHARS;
  31. expect(truncateMiddleForModel(text)).toBe(
  32. `${head}\n\n... [${removed} characters truncated] ...\n\n${tail}`,
  33. );
  34. });
  35. it("drops half surrogate pairs at both cut points", () => {
  36. // 头部切点落在 😀 中间,尾部切点落在 🎉 中间:两个半字符都丢弃,不产生孤立代理。
  37. const head = `${"h".repeat(HEAD_CHARS - 1)}😀`;
  38. const tail = `🎉${"t".repeat(TAIL_CHARS - 1)}`;
  39. const text = `${head}${"m".repeat(2_000)}${tail}`;
  40. const result = truncateMiddleForModel(text);
  41. expect(LONE_SURROGATE.test(result)).toBe(false);
  42. expect(result.startsWith(`${"h".repeat(HEAD_CHARS - 1)}\n\n... [`)).toBe(true);
  43. expect(result.endsWith(`] ...\n\n${"t".repeat(TAIL_CHARS - 1)}`)).toBe(true);
  44. const removed = text.length - (HEAD_CHARS - 1) - (TAIL_CHARS - 1);
  45. expect(result).toContain(`[${removed} characters truncated]`);
  46. });
  47. });