session-trim.test.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { describe, expect, test } from "bun:test"
  2. import type { PermissionRequest, Session } from "@opencode-ai/sdk/v2/client"
  3. import { trimSessions } from "./session-trim"
  4. const session = (input: { id: string; parentID?: string; created: number; updated?: number; archived?: number }) =>
  5. ({
  6. id: input.id,
  7. parentID: input.parentID,
  8. time: {
  9. created: input.created,
  10. updated: input.updated,
  11. archived: input.archived,
  12. },
  13. }) as Session
  14. describe("trimSessions", () => {
  15. test("keeps base roots and recent roots beyond the limit", () => {
  16. const now = 1_000_000
  17. const list = [
  18. session({ id: "a", created: now - 100_000 }),
  19. session({ id: "b", created: now - 90_000 }),
  20. session({ id: "c", created: now - 80_000 }),
  21. session({ id: "d", created: now - 70_000, updated: now - 1_000 }),
  22. session({ id: "e", created: now - 60_000, archived: now - 10 }),
  23. ]
  24. const result = trimSessions(list, { limit: 2, permission: {}, now })
  25. expect(result.map((x) => x.id)).toEqual(["a", "b", "c", "d"])
  26. })
  27. test("keeps children when root is kept, permission exists, or child is recent", () => {
  28. const now = 1_000_000
  29. const list = [
  30. session({ id: "root-1", created: now - 1000 }),
  31. session({ id: "root-2", created: now - 2000 }),
  32. session({ id: "z-root", created: now - 30_000_000 }),
  33. session({ id: "child-kept-by-root", parentID: "root-1", created: now - 20_000_000 }),
  34. session({ id: "child-kept-by-permission", parentID: "z-root", created: now - 20_000_000 }),
  35. session({ id: "child-kept-by-recency", parentID: "z-root", created: now - 500 }),
  36. session({ id: "child-trimmed", parentID: "z-root", created: now - 20_000_000 }),
  37. ]
  38. const result = trimSessions(list, {
  39. limit: 2,
  40. permission: {
  41. "child-kept-by-permission": [{ id: "perm-1" } as PermissionRequest],
  42. },
  43. now,
  44. })
  45. expect(result.map((x) => x.id)).toEqual([
  46. "child-kept-by-permission",
  47. "child-kept-by-recency",
  48. "child-kept-by-root",
  49. "root-1",
  50. "root-2",
  51. ])
  52. })
  53. })