pty-session.test.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import { describe, expect } from "bun:test"
  2. import { Cause, Deferred, Effect, Exit, Layer, Queue } from "effect"
  3. import { Config } from "@opencode-ai/core/config"
  4. import { EventV2 } from "@opencode-ai/core/event"
  5. import { Location } from "@opencode-ai/core/location"
  6. import { Pty } from "@opencode-ai/core/pty"
  7. import type { PtyID } from "@opencode-ai/core/pty/schema"
  8. import { AbsolutePath } from "@opencode-ai/core/schema"
  9. import { location } from "../fixture/location"
  10. import { testEffect } from "../lib/effect"
  11. type PtyEvent = { type: "created" | "exited" | "deleted"; id: PtyID }
  12. const locationLayer = Layer.succeed(
  13. Location.Service,
  14. Location.Service.of(location({ directory: AbsolutePath.make("/tmp") })),
  15. )
  16. const configLayer = Layer.mock(Config.Service)({ entries: () => Effect.succeed([]) })
  17. const it = testEffect(
  18. Pty.layer.pipe(
  19. Layer.provide(configLayer),
  20. Layer.provideMerge(EventV2.defaultLayer),
  21. Layer.provideMerge(locationLayer),
  22. ),
  23. )
  24. const ptyTest = process.platform === "win32" ? it.live.skip : it.live
  25. const subscribePtyEvents = Effect.fn("PtySessionTest.subscribePtyEvents")(function* () {
  26. const source = yield* EventV2.Service
  27. const events = yield* Queue.unbounded<PtyEvent>()
  28. const unsubscribe = yield* source.listen((event) => {
  29. if (event.type === Pty.Event.Created.type)
  30. Queue.offerUnsafe(events, { type: "created", id: (event.data as typeof Pty.Event.Created.data.Type).info.id })
  31. if (event.type === Pty.Event.Exited.type)
  32. Queue.offerUnsafe(events, { type: "exited", id: (event.data as typeof Pty.Event.Exited.data.Type).id })
  33. if (event.type === Pty.Event.Deleted.type)
  34. Queue.offerUnsafe(events, { type: "deleted", id: (event.data as typeof Pty.Event.Deleted.data.Type).id })
  35. return Effect.void
  36. })
  37. yield* Effect.addFinalizer(() => unsubscribe)
  38. return events
  39. })
  40. const createPty = Effect.fn("PtySessionTest.createPty")(function* (command: string, args: string[] = []) {
  41. const pty = yield* Pty.Service
  42. return yield* Effect.acquireRelease(
  43. pty.create({ command, args, cwd: "/tmp", env: { TERM: "xterm-256color", OPENCODE_TERMINAL: "1" } }),
  44. (info) => pty.remove(info.id).pipe(Effect.ignore),
  45. )
  46. })
  47. const waitForEvents = (events: Queue.Queue<PtyEvent>, id: PtyID, count: number) =>
  48. Effect.gen(function* () {
  49. const picked: Array<PtyEvent["type"]> = []
  50. while (picked.length < count) {
  51. const evt = yield* Queue.take(events)
  52. if (evt.id === id) picked.push(evt.type)
  53. }
  54. return picked
  55. }).pipe(
  56. Effect.timeoutOrElse({
  57. duration: "5 seconds",
  58. orElse: () => Effect.fail(new Error("timeout waiting for pty events")),
  59. }),
  60. )
  61. const attachCollecting = Effect.fn("PtySessionTest.attachCollecting")(function* (id: PtyID, cursor?: number) {
  62. const pty = yield* Pty.Service
  63. const output = yield* Queue.unbounded<string>()
  64. const ended = yield* Deferred.make<{ exitCode?: number }>()
  65. const attachment = yield* pty.attach(id, {
  66. cursor,
  67. onData: (chunk) => Queue.offerUnsafe(output, chunk),
  68. onEnd: (event) => Deferred.doneUnsafe(ended, Effect.succeed(event)),
  69. })
  70. attachment.activate()
  71. return { attachment, output, ended }
  72. })
  73. const waitForOutput = (output: Queue.Queue<string>, text: string) =>
  74. Effect.gen(function* () {
  75. let received = ""
  76. while (!received.includes(text)) received += yield* Queue.take(output)
  77. return received
  78. }).pipe(
  79. Effect.timeoutOrElse({
  80. duration: "5 seconds",
  81. orElse: () => Effect.fail(new Error(`timeout waiting for output containing ${JSON.stringify(text)}`)),
  82. }),
  83. )
  84. describe("pty", () => {
  85. it.live("returns typed not found errors for missing sessions", () =>
  86. Effect.gen(function* () {
  87. const pty = yield* Pty.Service
  88. const id = "pty_missing" as PtyID
  89. for (const result of [
  90. yield* pty.get(id).pipe(Effect.asVoid, Effect.exit),
  91. yield* pty.update(id, { title: "missing" }).pipe(Effect.asVoid, Effect.exit),
  92. yield* pty.remove(id).pipe(Effect.exit),
  93. yield* pty.write(id, "input").pipe(Effect.exit),
  94. yield* pty.attach(id, { onData: () => {}, onEnd: () => {} }).pipe(Effect.asVoid, Effect.exit),
  95. ]) {
  96. expect(Exit.isFailure(result)).toBe(true)
  97. if (Exit.isFailure(result))
  98. expect(Cause.squash(result.cause)).toMatchObject({ _tag: "Pty.NotFoundError", ptyID: id })
  99. }
  100. }),
  101. )
  102. ptyTest("retains exited sessions until removed", () =>
  103. Effect.gen(function* () {
  104. const pty = yield* Pty.Service
  105. const events = yield* subscribePtyEvents()
  106. const info = yield* createPty("/usr/bin/env", ["sh", "-c", "exit 3"])
  107. expect(yield* waitForEvents(events, info.id, 2)).toEqual(["created", "exited"])
  108. const exited = yield* pty.get(info.id)
  109. expect(exited.status).toBe("exited")
  110. expect(exited.exitCode).toBe(3)
  111. yield* pty.remove(info.id)
  112. expect(yield* waitForEvents(events, info.id, 1)).toEqual(["deleted"])
  113. const missing = yield* pty.get(info.id).pipe(Effect.exit)
  114. expect(Exit.isFailure(missing)).toBe(true)
  115. }),
  116. )
  117. ptyTest("replays buffered output and streams live output to attachments", () =>
  118. Effect.gen(function* () {
  119. const pty = yield* Pty.Service
  120. const info = yield* createPty("cat")
  121. yield* pty.write(info.id, "AAA\n")
  122. const first = yield* attachCollecting(info.id)
  123. expect(yield* waitForOutput(first.output, "AAA")).toContain("AAA")
  124. first.attachment.write("BBB\n")
  125. yield* waitForOutput(first.output, "BBB")
  126. // A later attachment replays everything already buffered.
  127. const replayed = yield* attachCollecting(info.id)
  128. expect(replayed.attachment.replay).toContain("AAA")
  129. expect(replayed.attachment.replay).toContain("BBB")
  130. expect(replayed.attachment.cursor).toBeGreaterThan(0)
  131. // Tail attachments skip the buffer and only see subsequent output.
  132. const tail = yield* attachCollecting(info.id, -1)
  133. expect(tail.attachment.replay).toBe("")
  134. expect(tail.attachment.cursor).toBe(replayed.attachment.cursor)
  135. }),
  136. )
  137. ptyTest("stops delivering output after detach", () =>
  138. Effect.gen(function* () {
  139. const pty = yield* Pty.Service
  140. const info = yield* createPty("cat")
  141. const attached = yield* attachCollecting(info.id, -1)
  142. attached.attachment.detach()
  143. yield* pty.write(info.id, "AAA\n")
  144. const verify = yield* attachCollecting(info.id)
  145. yield* waitForOutput(verify.output, "AAA")
  146. const leaked = yield* Queue.poll(attached.output)
  147. expect(leaked._tag).toBe("None")
  148. }),
  149. )
  150. ptyTest("isolates output between sessions", () =>
  151. Effect.gen(function* () {
  152. const pty = yield* Pty.Service
  153. const a = yield* createPty("cat")
  154. const b = yield* createPty("cat")
  155. const attachedA = yield* attachCollecting(a.id)
  156. const attachedB = yield* attachCollecting(b.id)
  157. yield* pty.write(a.id, "AAA\n")
  158. yield* waitForOutput(attachedA.output, "AAA")
  159. const leaked = yield* Queue.poll(attachedB.output)
  160. expect(leaked._tag).toBe("None")
  161. }),
  162. )
  163. ptyTest("notifies attachments with the exit code and rejects attach after exit", () =>
  164. Effect.gen(function* () {
  165. const pty = yield* Pty.Service
  166. const events = yield* subscribePtyEvents()
  167. const info = yield* createPty("cat")
  168. const attached = yield* attachCollecting(info.id)
  169. yield* pty.write(info.id, "\u0004")
  170. expect(yield* Deferred.await(attached.ended).pipe(Effect.timeout("5 seconds"))).toEqual({ exitCode: 0 })
  171. yield* waitForEvents(events, info.id, 2)
  172. const result = yield* pty.attach(info.id, { onData: () => {}, onEnd: () => {} }).pipe(Effect.exit)
  173. expect(Exit.isFailure(result)).toBe(true)
  174. if (Exit.isFailure(result))
  175. expect(Cause.squash(result.cause)).toMatchObject({ _tag: "Pty.ExitedError", ptyID: info.id })
  176. }),
  177. )
  178. })
  179. const configuredShell = process.platform === "win32" ? undefined : Bun.which("bash")
  180. const configuredIt = testEffect(
  181. Pty.layer.pipe(
  182. Layer.provide(
  183. Layer.mock(Config.Service)({
  184. entries: () =>
  185. Effect.succeed(
  186. configuredShell
  187. ? [new Config.Document({ type: "document", info: new Config.Info({ shell: configuredShell }) })]
  188. : [],
  189. ),
  190. }),
  191. ),
  192. Layer.provideMerge(EventV2.defaultLayer),
  193. Layer.provideMerge(locationLayer),
  194. ),
  195. )
  196. const configuredTest = process.platform === "win32" ? configuredIt.live.skip : configuredIt.live
  197. describe("pty create defaults", () => {
  198. configuredTest("defaults command, login args, and cwd from config and location", () =>
  199. Effect.gen(function* () {
  200. if (!configuredShell) return
  201. const pty = yield* Pty.Service
  202. const info = yield* Effect.acquireRelease(pty.create({ title: "configured" }), (created) =>
  203. pty.remove(created.id).pipe(Effect.ignore),
  204. )
  205. expect(info.command).toBe(configuredShell)
  206. expect(info.args).toEqual(["-l"])
  207. expect(info.cwd).toBe("/tmp")
  208. expect(info.title).toBe("configured")
  209. }),
  210. )
  211. })