sync-optimistic.test.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { describe, expect, test } from "bun:test"
  2. import type { Message, Part } from "@opencode-ai/sdk/v2/client"
  3. import { applyOptimisticAdd, applyOptimisticRemove } from "./sync"
  4. const userMessage = (id: string, sessionID: string): Message => ({
  5. id,
  6. sessionID,
  7. role: "user",
  8. time: { created: 1 },
  9. agent: "assistant",
  10. model: { providerID: "openai", modelID: "gpt" },
  11. })
  12. const textPart = (id: string, sessionID: string, messageID: string): Part => ({
  13. id,
  14. sessionID,
  15. messageID,
  16. type: "text",
  17. text: id,
  18. })
  19. describe("sync optimistic reducers", () => {
  20. test("applyOptimisticAdd inserts message in sorted order and stores parts", () => {
  21. const sessionID = "ses_1"
  22. const draft = {
  23. message: { [sessionID]: [userMessage("msg_2", sessionID)] },
  24. part: {} as Record<string, Part[] | undefined>,
  25. }
  26. applyOptimisticAdd(draft, {
  27. sessionID,
  28. message: userMessage("msg_1", sessionID),
  29. parts: [textPart("prt_2", sessionID, "msg_1"), textPart("prt_1", sessionID, "msg_1")],
  30. })
  31. expect(draft.message[sessionID]?.map((x) => x.id)).toEqual(["msg_1", "msg_2"])
  32. expect(draft.part.msg_1?.map((x) => x.id)).toEqual(["prt_1", "prt_2"])
  33. })
  34. test("applyOptimisticRemove removes message and part entries", () => {
  35. const sessionID = "ses_1"
  36. const draft = {
  37. message: { [sessionID]: [userMessage("msg_1", sessionID), userMessage("msg_2", sessionID)] },
  38. part: {
  39. msg_1: [textPart("prt_1", sessionID, "msg_1")],
  40. msg_2: [textPart("prt_2", sessionID, "msg_2")],
  41. } as Record<string, Part[] | undefined>,
  42. }
  43. applyOptimisticRemove(draft, { sessionID, messageID: "msg_1" })
  44. expect(draft.message[sessionID]?.map((x) => x.id)).toEqual(["msg_2"])
  45. expect(draft.part.msg_1).toBeUndefined()
  46. expect(draft.part.msg_2).toHaveLength(1)
  47. })
  48. })