pty-session.test.ts 9.1 KB

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