editor-context.test.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { mkdir, writeFile } from "node:fs/promises"
  2. import os from "node:os"
  3. import path from "node:path"
  4. import { afterEach, expect, spyOn, test } from "bun:test"
  5. import { createRoot } from "solid-js"
  6. import { EditorContextProvider, useEditorContext, type EditorIntegration } from "@kirincode-ai/tui/context/editor"
  7. import { tmpdir } from "../../fixture/fixture"
  8. import { FakeWebSocket } from "../../lib/websocket"
  9. import { TestTuiContexts } from "../../fixture/tui-environment"
  10. import { discoverEditorConnection } from "@kirincode-ai/tui/editor"
  11. const originalClaudePort = process.env.CLAUDE_CODE_SSE_PORT
  12. const originalOpencodePort = process.env.KIRINCODE_EDITOR_SSE_PORT
  13. afterEach(() => {
  14. process.env.CLAUDE_CODE_SSE_PORT = originalClaudePort
  15. process.env.KIRINCODE_EDITOR_SSE_PORT = originalOpencodePort
  16. })
  17. function nextTick() {
  18. return new Promise<void>((resolve) => queueMicrotask(resolve))
  19. }
  20. function mountEditorContext(WebSocketImpl?: typeof WebSocket) {
  21. let editor!: ReturnType<typeof useEditorContext>
  22. let dispose!: () => void
  23. createRoot((nextDispose) => {
  24. dispose = nextDispose
  25. const Consumer = () => {
  26. editor = useEditorContext()
  27. return null
  28. }
  29. const value = process.env.CLAUDE_CODE_SSE_PORT || process.env.KIRINCODE_EDITOR_SSE_PORT
  30. return (
  31. <TestTuiContexts cwd={process.cwd()} paths={{ home: os.homedir() }}>
  32. <EditorContextProvider integration={editorService} WebSocketImpl={WebSocketImpl}>
  33. <Consumer />
  34. </EditorContextProvider>
  35. </TestTuiContexts>
  36. )
  37. })
  38. return {
  39. editor,
  40. dispose,
  41. }
  42. }
  43. const editorService: EditorIntegration = {
  44. connection: discoverEditorConnection,
  45. }
  46. function createWebSocketImpl(...sockets: FakeWebSocket[]) {
  47. let index = 0
  48. return class {
  49. constructor(url: string, options?: { headers?: Record<string, string> }) {
  50. const socket = sockets[index]
  51. index += 1
  52. expect(socket).toBeDefined()
  53. expect(url).toBe(socket!.url)
  54. expect(options).toEqual(socket!.options)
  55. return socket as unknown as object
  56. }
  57. } as unknown as typeof WebSocket
  58. }
  59. function sendSelection(socket: FakeWebSocket, filePath: string, text = "foo") {
  60. socket.message(
  61. JSON.stringify({
  62. jsonrpc: "2.0",
  63. method: "selection_changed",
  64. params: {
  65. text,
  66. filePath,
  67. selection: {
  68. start: { line: 1, character: 1 },
  69. end: { line: 1, character: 4 },
  70. },
  71. },
  72. }),
  73. )
  74. }
  75. function expectedSelection(filePath: string, text = "foo") {
  76. return {
  77. filePath,
  78. source: "websocket" as const,
  79. ranges: [
  80. {
  81. text,
  82. selection: {
  83. start: { line: 1, character: 1 },
  84. end: { line: 1, character: 4 },
  85. },
  86. },
  87. ],
  88. }
  89. }
  90. test("useEditorContext reconnect switches editor server by session directory", async () => {
  91. await using tmp = await tmpdir()
  92. const startupDirectory = path.join(tmp.path, "startup")
  93. const sessionDirectory = path.join(tmp.path, "session")
  94. const ideDirectory = path.join(tmp.path, ".claude", "ide")
  95. await mkdir(startupDirectory, { recursive: true })
  96. await mkdir(sessionDirectory, { recursive: true })
  97. await mkdir(ideDirectory, { recursive: true })
  98. await writeFile(
  99. path.join(ideDirectory, "3001.lock"),
  100. JSON.stringify({
  101. transport: "ws",
  102. workspaceFolders: [startupDirectory],
  103. }),
  104. )
  105. await writeFile(
  106. path.join(ideDirectory, "3002.lock"),
  107. JSON.stringify({
  108. transport: "ws",
  109. workspaceFolders: [sessionDirectory],
  110. }),
  111. )
  112. process.env.CLAUDE_CODE_SSE_PORT = undefined
  113. process.env.KIRINCODE_EDITOR_SSE_PORT = undefined
  114. spyOn(process, "cwd").mockImplementation(() => startupDirectory)
  115. spyOn(os, "homedir").mockImplementation(() => tmp.path)
  116. const firstSocket = new FakeWebSocket("ws://127.0.0.1:3001")
  117. const secondSocket = new FakeWebSocket("ws://127.0.0.1:3002")
  118. const mounted = mountEditorContext(createWebSocketImpl(firstSocket, secondSocket))
  119. await nextTick()
  120. expect(firstSocket.closed).toBeFalse()
  121. sendSelection(firstSocket, path.join(startupDirectory, "file.ts"))
  122. expect(mounted.editor.selection()).toEqual(expectedSelection(path.join(startupDirectory, "file.ts")))
  123. expect(mounted.editor.labelState()).toBe("pending")
  124. mounted.editor.reconnect(sessionDirectory)
  125. await nextTick()
  126. expect(firstSocket.closed).toBeTrue()
  127. expect(secondSocket.closed).toBeFalse()
  128. expect(mounted.editor.selection()).toBeUndefined()
  129. expect(mounted.editor.labelState()).toBe("none")
  130. mounted.dispose()
  131. })
  132. test("useEditorContext favors configured port over lock files", async () => {
  133. await using tmp = await tmpdir()
  134. const startupDirectory = path.join(tmp.path, "startup")
  135. const ideDirectory = path.join(tmp.path, ".claude", "ide")
  136. await mkdir(startupDirectory, { recursive: true })
  137. await mkdir(ideDirectory, { recursive: true })
  138. await writeFile(
  139. path.join(ideDirectory, "3001.lock"),
  140. JSON.stringify({
  141. transport: "ws",
  142. workspaceFolders: [startupDirectory],
  143. }),
  144. )
  145. process.env.CLAUDE_CODE_SSE_PORT = "4010"
  146. process.env.KIRINCODE_EDITOR_SSE_PORT = undefined
  147. spyOn(process, "cwd").mockImplementation(() => startupDirectory)
  148. spyOn(os, "homedir").mockImplementation(() => tmp.path)
  149. const socket = new FakeWebSocket("ws://127.0.0.1:4010")
  150. const mounted = mountEditorContext(createWebSocketImpl(socket))
  151. await nextTick()
  152. expect(socket.closed).toBeFalse()
  153. mounted.dispose()
  154. })
  155. test("useEditorContext clears selection when reconnecting", async () => {
  156. await using tmp = await tmpdir()
  157. const startupDirectory = path.join(tmp.path, "startup")
  158. const ideDirectory = path.join(tmp.path, ".claude", "ide")
  159. await mkdir(startupDirectory, { recursive: true })
  160. await mkdir(ideDirectory, { recursive: true })
  161. await writeFile(
  162. path.join(ideDirectory, "3001.lock"),
  163. JSON.stringify({
  164. transport: "ws",
  165. workspaceFolders: [startupDirectory],
  166. }),
  167. )
  168. process.env.CLAUDE_CODE_SSE_PORT = undefined
  169. process.env.KIRINCODE_EDITOR_SSE_PORT = undefined
  170. spyOn(process, "cwd").mockImplementation(() => startupDirectory)
  171. spyOn(os, "homedir").mockImplementation(() => tmp.path)
  172. const socket = new FakeWebSocket("ws://127.0.0.1:3001")
  173. const mounted = mountEditorContext(createWebSocketImpl(socket))
  174. await nextTick()
  175. expect(socket.closed).toBeFalse()
  176. expect(mounted.editor.selection()).toBeUndefined()
  177. expect(mounted.editor.connected()).toBeFalse()
  178. socket.open()
  179. socket.message(
  180. JSON.stringify({
  181. jsonrpc: "2.0",
  182. id: 1,
  183. result: {
  184. protocolVersion: "2025-11-25",
  185. serverInfo: { name: "test", version: "0.0.0" },
  186. },
  187. }),
  188. )
  189. sendSelection(socket, path.join(startupDirectory, "file.ts"))
  190. expect(mounted.editor.connected()).toBeTrue()
  191. expect(mounted.editor.server()).toEqual({
  192. protocolVersion: "2025-11-25",
  193. serverInfo: { name: "test", version: "0.0.0" },
  194. })
  195. expect(mounted.editor.selection()).toEqual(expectedSelection(path.join(startupDirectory, "file.ts")))
  196. expect(mounted.editor.labelState()).toBe("pending")
  197. mounted.editor.markSelectionSent()
  198. expect(mounted.editor.labelState()).toBe("sent")
  199. mounted.editor.reconnect(startupDirectory)
  200. expect(socket.closed).toBeFalse()
  201. expect(mounted.editor.connected()).toBeTrue()
  202. expect(mounted.editor.selection()).toBeUndefined()
  203. expect(mounted.editor.labelState()).toBe("none")
  204. mounted.dispose()
  205. })
  206. test("useEditorContext preserves selection for the next reconnect when requested", async () => {
  207. await using tmp = await tmpdir()
  208. const startupDirectory = path.join(tmp.path, "startup")
  209. const ideDirectory = path.join(tmp.path, ".claude", "ide")
  210. await mkdir(startupDirectory, { recursive: true })
  211. await mkdir(ideDirectory, { recursive: true })
  212. await writeFile(
  213. path.join(ideDirectory, "3001.lock"),
  214. JSON.stringify({
  215. transport: "ws",
  216. workspaceFolders: [startupDirectory],
  217. }),
  218. )
  219. process.env.CLAUDE_CODE_SSE_PORT = undefined
  220. process.env.KIRINCODE_EDITOR_SSE_PORT = undefined
  221. spyOn(process, "cwd").mockImplementation(() => startupDirectory)
  222. spyOn(os, "homedir").mockImplementation(() => tmp.path)
  223. const socket = new FakeWebSocket("ws://127.0.0.1:3001")
  224. const mounted = mountEditorContext(createWebSocketImpl(socket))
  225. await nextTick()
  226. sendSelection(socket, path.join(startupDirectory, "file.ts"))
  227. expect(mounted.editor.selection()).toEqual(expectedSelection(path.join(startupDirectory, "file.ts")))
  228. mounted.editor.markSelectionSent()
  229. mounted.editor.preserveSelectionFromNewSession()
  230. mounted.editor.reconnect(startupDirectory)
  231. expect(socket.closed).toBeFalse()
  232. expect(mounted.editor.selection()).toEqual(expectedSelection(path.join(startupDirectory, "file.ts")))
  233. expect(mounted.editor.labelState()).toBe("sent")
  234. mounted.editor.reconnect(startupDirectory)
  235. expect(mounted.editor.selection()).toBeUndefined()
  236. expect(mounted.editor.labelState()).toBe("none")
  237. mounted.dispose()
  238. })
  239. test("useEditorContext connects with KIRINCODE_EDITOR_SSE_PORT", async () => {
  240. await using tmp = await tmpdir()
  241. process.env.CLAUDE_CODE_SSE_PORT = undefined
  242. process.env.KIRINCODE_EDITOR_SSE_PORT = "4020"
  243. spyOn(process, "cwd").mockImplementation(() => tmp.path)
  244. const socket = new FakeWebSocket("ws://127.0.0.1:4020")
  245. const mounted = mountEditorContext(createWebSocketImpl(socket))
  246. await nextTick()
  247. expect(socket.closed).toBeFalse()
  248. mounted.dispose()
  249. })