session.test.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { describe, expect, test } from "bun:test"
  2. import type { SessionMessageInfo } from "@opencode-ai/client"
  3. import { lastAssistantWithUsage } from "../../src/util/session"
  4. const assistant = (id: string, input: number): SessionMessageInfo => ({
  5. id,
  6. type: "assistant",
  7. agent: "build",
  8. model: { id: "model", providerID: "provider" },
  9. content: [],
  10. tokens: { input, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  11. time: { created: 0 },
  12. })
  13. describe("util.session", () => {
  14. test("tracks usage across undo and redo boundaries", () => {
  15. const messages = [assistant("msg_z", 10), assistant("msg_a", 30)]
  16. expect(lastAssistantWithUsage(messages)?.tokens.input).toBe(30)
  17. expect(lastAssistantWithUsage(messages, "msg_a")?.tokens.input).toBe(10)
  18. expect(lastAssistantWithUsage(messages, "msg_missing")).toBeUndefined()
  19. expect(lastAssistantWithUsage(messages)?.tokens.input).toBe(30)
  20. })
  21. test("resets usage at completed compaction until the next assistant reports it", () => {
  22. const compaction: SessionMessageInfo = {
  23. id: "msg_compaction",
  24. type: "compaction",
  25. status: "completed",
  26. reason: "manual",
  27. summary: "Current state",
  28. recent: "",
  29. time: { created: 0 },
  30. }
  31. const messages = [assistant("msg_before", 30), compaction]
  32. expect(lastAssistantWithUsage(messages)).toBeUndefined()
  33. messages.push(assistant("msg_after", 5))
  34. expect(lastAssistantWithUsage(messages)?.tokens.input).toBe(5)
  35. })
  36. })