pty-session.test.ts 9.1 KB

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