promptHistory.test.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. appendPromptHistoryEntry,
  4. MAX_PROMPT_HISTORY,
  5. navigatePromptHistory,
  6. } from "../src/lib/promptHistory.js";
  7. describe("appendPromptHistoryEntry", () => {
  8. it("会忽略空白内容", () => {
  9. expect(appendPromptHistoryEntry(["first"], " ")).toEqual(["first"]);
  10. });
  11. it("只过滤 trim 后与上一条相同的连续重复", () => {
  12. expect(appendPromptHistoryEntry(["first"], " first ")).toEqual(["first"]);
  13. expect(appendPromptHistoryEntry(["first", "second"], " first ")).toEqual([
  14. "first",
  15. "second",
  16. "first",
  17. ]);
  18. });
  19. it("保留内部空白、换行和大小写不同的历史", () => {
  20. expect(appendPromptHistoryEntry(["A B"], " A B ")).toEqual(["A B", "A B"]);
  21. expect(appendPromptHistoryEntry(["line\nvalue"], "line value")).toEqual([
  22. "line\nvalue",
  23. "line value",
  24. ]);
  25. expect(appendPromptHistoryEntry(["Prompt"], "prompt")).toEqual(["Prompt", "prompt"]);
  26. });
  27. it("会在尾部追加并裁剪到最近 30 条", () => {
  28. const history = Array.from(
  29. { length: MAX_PROMPT_HISTORY },
  30. (_, index) => `message-${index + 1}`,
  31. );
  32. const next = appendPromptHistoryEntry(history, "message-31");
  33. expect(next).toHaveLength(MAX_PROMPT_HISTORY);
  34. expect(next[0]).toBe("message-2");
  35. expect(next.at(-1)).toBe("message-31");
  36. });
  37. });
  38. describe("navigatePromptHistory", () => {
  39. const history = ["first", "second", "third"];
  40. it("向上导航时会先命中最新一条", () => {
  41. expect(navigatePromptHistory(history, null, "up")).toEqual({
  42. nextIndex: 2,
  43. nextValue: "third",
  44. shouldHandle: true,
  45. });
  46. });
  47. it("向上导航到顶部后会停在最旧一条", () => {
  48. expect(navigatePromptHistory(history, 0, "up")).toEqual({
  49. nextIndex: 0,
  50. nextValue: "first",
  51. shouldHandle: true,
  52. });
  53. });
  54. it("向下导航时会逐步回到较新的记录,再回到空输入", () => {
  55. expect(navigatePromptHistory(history, 0, "down")).toEqual({
  56. nextIndex: 1,
  57. nextValue: "second",
  58. shouldHandle: true,
  59. });
  60. expect(navigatePromptHistory(history, 2, "down")).toEqual({
  61. nextIndex: null,
  62. nextValue: "",
  63. shouldHandle: true,
  64. });
  65. });
  66. it("空输入时向下也能先带出最新一条记录", () => {
  67. expect(navigatePromptHistory(history, null, "down")).toEqual({
  68. nextIndex: 2,
  69. nextValue: "third",
  70. shouldHandle: true,
  71. });
  72. });
  73. });