editor.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import { onCleanup, onMount } from "solid-js"
  2. import { createStore } from "solid-js/store"
  3. import { Option, Schema, SchemaGetter } from "effect"
  4. import { isRecord } from "../util/record"
  5. import { useTuiPaths } from "./runtime"
  6. import { createSimpleContext } from "./helper"
  7. import { editorIntegration } from "../editor"
  8. const MCP_PROTOCOL_VERSION = "2025-11-25"
  9. const JsonRpcMessageSchema = Schema.Struct({
  10. id: Schema.optional(Schema.Union([Schema.Number, Schema.String, Schema.Null])),
  11. method: Schema.optional(Schema.String),
  12. params: Schema.optional(Schema.Unknown),
  13. result: Schema.optional(Schema.Unknown),
  14. error: Schema.optional(
  15. Schema.Struct({
  16. code: Schema.optional(Schema.Number),
  17. message: Schema.optional(Schema.String),
  18. }),
  19. ),
  20. })
  21. const PositionSchema = Schema.Struct({
  22. line: Schema.Number,
  23. character: Schema.Number,
  24. })
  25. const EditorSelectionRangeSchema = Schema.Struct({
  26. text: Schema.String,
  27. selection: Schema.Struct({
  28. start: PositionSchema,
  29. end: PositionSchema,
  30. }),
  31. })
  32. const EditorSelectionRangesSchema = Schema.Struct({
  33. filePath: Schema.String,
  34. source: Schema.optional(Schema.Literals(["websocket", "zed"])),
  35. ranges: Schema.mutable(Schema.Array(EditorSelectionRangeSchema).check(Schema.isMinLength(1))),
  36. })
  37. const EditorSelectionSchema = Schema.Union([
  38. EditorSelectionRangesSchema,
  39. Schema.Struct({
  40. text: Schema.String,
  41. filePath: Schema.String,
  42. source: Schema.optional(Schema.Literals(["websocket", "zed"])),
  43. selection: Schema.Struct({
  44. start: PositionSchema,
  45. end: PositionSchema,
  46. }),
  47. }),
  48. ]).pipe(
  49. Schema.decodeTo(EditorSelectionRangesSchema, {
  50. decode: SchemaGetter.transform((value) =>
  51. "ranges" in value
  52. ? value
  53. : {
  54. filePath: value.filePath,
  55. source: value.source,
  56. ranges: [
  57. {
  58. text: value.text,
  59. selection: value.selection,
  60. },
  61. ],
  62. },
  63. ),
  64. encode: SchemaGetter.passthrough({ strict: false }),
  65. }),
  66. )
  67. const EditorMentionSchema = Schema.Struct({
  68. filePath: Schema.String,
  69. lineStart: Schema.Number,
  70. lineEnd: Schema.Number,
  71. })
  72. const EditorServerInfoSchema = Schema.Struct({
  73. protocolVersion: Schema.optional(Schema.String),
  74. serverInfo: Schema.optional(
  75. Schema.Struct({
  76. name: Schema.optional(Schema.String),
  77. version: Schema.optional(Schema.String),
  78. }),
  79. ),
  80. })
  81. const decodeJsonRpcMessage = Schema.decodeUnknownOption(JsonRpcMessageSchema)
  82. const decodeEditorSelection = Schema.decodeUnknownOption(EditorSelectionSchema)
  83. const decodeEditorMention = Schema.decodeUnknownOption(EditorMentionSchema)
  84. const decodeEditorServerInfo = Schema.decodeUnknownOption(EditorServerInfoSchema)
  85. type JsonRpcMessage = Schema.Schema.Type<typeof JsonRpcMessageSchema>
  86. export type EditorSelection = Schema.Schema.Type<typeof EditorSelectionSchema>
  87. export type EditorMention = Schema.Schema.Type<typeof EditorMentionSchema>
  88. export type EditorLabelState = "pending" | "sent" | "none"
  89. type EditorServerInfo = Schema.Schema.Type<typeof EditorServerInfoSchema>
  90. type EditorConnection = {
  91. url: string
  92. authToken?: string
  93. source: string
  94. }
  95. export type EditorIntegration = Readonly<{
  96. connection?(directory: string): EditorConnection | undefined
  97. selection?(directory: string): Promise<unknown>
  98. }>
  99. export const { use: useEditorContext, provider: EditorContextProvider } = createSimpleContext({
  100. name: "EditorContext",
  101. init: (props: { integration?: EditorIntegration; WebSocketImpl?: typeof WebSocket }) => {
  102. const paths = useTuiPaths()
  103. const editor = props.integration ?? editorIntegration
  104. const value = process.env.CLAUDE_CODE_SSE_PORT || process.env.OPENCODE_EDITOR_SSE_PORT
  105. const parsedPort = value ? Number.parseInt(value, 10) : undefined
  106. const port =
  107. parsedPort && Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535 ? parsedPort : undefined
  108. const zedTerminal = process.env.ZED_TERM === "true" || process.env.TERM_PROGRAM?.toLowerCase() === "zed"
  109. const mentionListeners = new Set<(mention: EditorMention) => void>()
  110. const WebSocketImpl = props.WebSocketImpl ?? WebSocket
  111. const [store, setStore] = createStore<{
  112. status: "disabled" | "connecting" | "connected"
  113. selection: EditorSelection | undefined
  114. selectionSent: boolean
  115. server: EditorServerInfo | undefined
  116. }>({
  117. status: "disabled",
  118. selection: undefined,
  119. selectionSent: false,
  120. server: undefined,
  121. })
  122. let socket: WebSocket | undefined
  123. let closed = false
  124. let reconnect: ReturnType<typeof setTimeout> | undefined
  125. let attempt = 0
  126. let requestID = 0
  127. let zedSelection: Promise<void> | undefined
  128. let lastZedSelectionKey: string | undefined
  129. let directory = paths.cwd
  130. let preserveSelectionOnReconnect = false
  131. const pending = new Map<number, string>()
  132. const setSelection = (selection: EditorSelection | undefined) => {
  133. const changed = editorSelectionKey(selection) !== editorSelectionKey(store.selection)
  134. setStore("selection", selection)
  135. if (changed) setStore("selectionSent", false)
  136. }
  137. const clearSelectionForReconnect = (options?: { resetZedSelectionKey?: boolean }) => {
  138. if (preserveSelectionOnReconnect) {
  139. preserveSelectionOnReconnect = false
  140. return
  141. }
  142. if (options?.resetZedSelectionKey) lastZedSelectionKey = undefined
  143. setSelection(undefined)
  144. }
  145. const send = (payload: JsonRpcMessage) => {
  146. if (!socket || socket.readyState !== 1) return
  147. socket.send(JSON.stringify({ jsonrpc: "2.0", ...payload }))
  148. }
  149. const request = (method: string, params?: unknown) => {
  150. requestID += 1
  151. pending.set(requestID, method)
  152. send({ id: requestID, method, params })
  153. }
  154. const connect = () => {
  155. if (closed) return
  156. const connection = resolveEditorConnection(directory, port, editor.connection)
  157. if (!connection) {
  158. if (!zedTerminal) {
  159. setStore("status", "disabled")
  160. scheduleReconnect()
  161. return
  162. }
  163. if (!editor.selection) {
  164. setStore("status", "disabled")
  165. scheduleReconnect()
  166. return
  167. }
  168. zedSelection ??= editor
  169. .selection(directory)
  170. .then((result) => {
  171. if (closed || socket) return
  172. if (!isRecord(result) || result.type === "unavailable") return
  173. const decoded = result.type === "selection" ? decodeEditorSelection(result.selection) : Option.none()
  174. const selection = Option.getOrUndefined(decoded)
  175. const key = editorSelectionKey(selection)
  176. if (key !== lastZedSelectionKey) {
  177. lastZedSelectionKey = key
  178. setSelection(selection)
  179. setStore("status", selection ? "connected" : "disabled")
  180. }
  181. })
  182. .catch(() => {
  183. // Keep the last known Zed selection for transient polling failures.
  184. })
  185. .finally(() => {
  186. zedSelection = undefined
  187. })
  188. scheduleZedPoll()
  189. return
  190. }
  191. setStore("status", "connecting")
  192. const current = openEditorSocket(connection, WebSocketImpl)
  193. socket = current
  194. current.addEventListener("open", () => {
  195. if (socket !== current) {
  196. current.close()
  197. return
  198. }
  199. attempt = 0
  200. setStore("status", "connected")
  201. request("initialize", {
  202. protocolVersion: MCP_PROTOCOL_VERSION,
  203. capabilities: {},
  204. clientInfo: { name: "opencode", version: "0.0.0" },
  205. })
  206. })
  207. current.addEventListener("message", (event) => {
  208. const message = parseMessage(event.data)
  209. if (!message) return
  210. const selection = message.method === "selection_changed" ? decodeEditorSelection(message.params) : Option.none()
  211. if (Option.isSome(selection)) {
  212. setSelection({ ...selection.value, source: "websocket" })
  213. return
  214. }
  215. const mention = message.method === "at_mentioned" ? decodeEditorMention(message.params) : Option.none()
  216. if (Option.isSome(mention)) {
  217. mentionListeners.forEach((listener) => listener(mention.value))
  218. return
  219. }
  220. if (typeof message.id !== "number") return
  221. const method = pending.get(message.id)
  222. if (!method) return
  223. pending.delete(message.id)
  224. if (message.error) return
  225. const initialize = method === "initialize" ? decodeEditorServerInfo(message.result) : Option.none()
  226. if (Option.isSome(initialize)) {
  227. setStore("server", initialize.value)
  228. send({ method: "notifications/initialized" })
  229. return
  230. }
  231. })
  232. current.addEventListener("close", () => {
  233. if (socket !== current) return
  234. socket = undefined
  235. pending.clear()
  236. if (closed) return
  237. setStore("status", "connecting")
  238. scheduleReconnect()
  239. })
  240. }
  241. const scheduleReconnect = () => {
  242. if (closed) return
  243. if (reconnect) clearTimeout(reconnect)
  244. attempt += 1
  245. const delay = Math.min(1000 * 2 ** (attempt - 1), 10_000)
  246. reconnect = setTimeout(connect, delay)
  247. }
  248. const scheduleZedPoll = () => {
  249. if (closed) return
  250. if (reconnect) clearTimeout(reconnect)
  251. reconnect = setTimeout(connect, 1000)
  252. }
  253. const reconnectWithDirectory = (nextDirectory?: string) => {
  254. const resolved = nextDirectory || paths.cwd
  255. const sameDirectory = directory === resolved
  256. clearSelectionForReconnect({ resetZedSelectionKey: !sameDirectory })
  257. if (sameDirectory) return
  258. directory = resolved
  259. attempt = 0
  260. pending.clear()
  261. if (reconnect) clearTimeout(reconnect)
  262. reconnect = undefined
  263. if (socket) {
  264. const current = socket
  265. socket = undefined
  266. current.close()
  267. }
  268. setStore("status", "disabled")
  269. setStore("server", undefined)
  270. connect()
  271. }
  272. onMount(() => {
  273. connect()
  274. onCleanup(() => {
  275. closed = true
  276. if (reconnect) clearTimeout(reconnect)
  277. socket?.close()
  278. })
  279. })
  280. return {
  281. enabled() {
  282. return Boolean(resolveEditorConnection(directory, port, editor.connection) || (zedTerminal && editor.selection))
  283. },
  284. connected() {
  285. return store.status === "connected"
  286. },
  287. selection() {
  288. return store.selection
  289. },
  290. clearSelection() {
  291. lastZedSelectionKey = undefined
  292. zedSelection = undefined
  293. setSelection(undefined)
  294. },
  295. preserveSelectionFromNewSession() {
  296. preserveSelectionOnReconnect = true
  297. },
  298. markSelectionSent() {
  299. if (!store.selection) return
  300. setStore("selectionSent", true)
  301. },
  302. labelState(): EditorLabelState {
  303. if (!store.selection) return "none"
  304. return store.selectionSent ? "sent" : "pending"
  305. },
  306. onMention(listener: (mention: EditorMention) => void) {
  307. mentionListeners.add(listener)
  308. return () => mentionListeners.delete(listener)
  309. },
  310. server() {
  311. return store.server
  312. },
  313. reconnect(directory?: string) {
  314. reconnectWithDirectory(directory)
  315. },
  316. }
  317. },
  318. })
  319. function resolveEditorConnection(
  320. directory: string,
  321. port: number | undefined,
  322. discover: ((directory: string) => EditorConnection | undefined) | undefined,
  323. ): EditorConnection | undefined {
  324. if (port) {
  325. return {
  326. url: `ws://127.0.0.1:${port}`,
  327. source: `env:${port}`,
  328. }
  329. }
  330. return discover?.(directory)
  331. }
  332. export function editorSelectionKey(selection: EditorSelection | undefined) {
  333. if (!selection) return ""
  334. return [
  335. selection.filePath,
  336. ...selection.ranges.flatMap((range) => [
  337. range.selection.start.line,
  338. range.selection.start.character,
  339. range.selection.end.line,
  340. range.selection.end.character,
  341. range.text,
  342. ]),
  343. ].join("\0")
  344. }
  345. function openEditorSocket(connection: EditorConnection, WebSocketImpl: typeof WebSocket) {
  346. if (!connection.authToken) return new WebSocketImpl(connection.url)
  347. return new WebSocketImpl(connection.url, {
  348. headers: {
  349. "x-claude-code-ide-authorization": connection.authToken,
  350. },
  351. } as any)
  352. }
  353. function parseMessage(value: unknown) {
  354. if (typeof value !== "string") return
  355. try {
  356. return Option.getOrUndefined(decodeJsonRpcMessage(JSON.parse(value)))
  357. } catch {
  358. return
  359. }
  360. }