tool-shell.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. import fs from "fs/promises"
  2. import { realpathSync } from "node:fs"
  3. import path from "path"
  4. import { describe, expect } from "bun:test"
  5. import { DateTime, Deferred, Duration, Effect, Fiber, Layer, Scope, Stream } from "effect"
  6. import { Money } from "@opencode-ai/schema/money"
  7. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  8. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  9. import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
  10. import { filesystem } from "@opencode-ai/util/effect/app-node-platform"
  11. import { Database } from "@opencode-ai/core/database/database"
  12. import { EventV2 } from "@opencode-ai/core/event"
  13. import { FSUtil } from "@opencode-ai/util/fs-util"
  14. import { Global } from "@opencode-ai/util/global"
  15. import { Location } from "@opencode-ai/core/location"
  16. import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
  17. import { ModelV2 } from "@opencode-ai/core/model"
  18. import { ProviderV2 } from "@opencode-ai/core/provider"
  19. import { AbsolutePath } from "@opencode-ai/core/schema"
  20. import { AgentV2 } from "@opencode-ai/core/agent"
  21. import { Job } from "@opencode-ai/core/job"
  22. import { SessionV2 } from "@opencode-ai/core/session"
  23. import { SessionEvent } from "@opencode-ai/core/session/event"
  24. import { SessionExecution } from "@opencode-ai/core/session/execution"
  25. import { SessionMessage } from "@opencode-ai/core/session/message"
  26. import { SessionStore } from "@opencode-ai/core/session/store"
  27. import { PermissionV2 } from "@opencode-ai/core/permission"
  28. import { PluginRuntime } from "@opencode-ai/core/plugin/runtime"
  29. import { Shell } from "@opencode-ai/core/shell"
  30. import { Shell as ShellSchema } from "@opencode-ai/schema/shell"
  31. import { ShellTool } from "@opencode-ai/core/tool/shell"
  32. import { ToolRegistry } from "@opencode-ai/core/tool/registry"
  33. import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
  34. import { tmpdir } from "./fixture/tmpdir"
  35. import { testEffect } from "./lib/effect"
  36. import { toolIdentity, executeTool, toolDefinitions, waitForTool } from "./lib/tool"
  37. const sessionID = SessionV2.ID.make("ses_shell_tool_test")
  38. const sessionModel = ModelV2.Ref.make({ id: ModelV2.ID.make("test"), providerID: ProviderV2.ID.make("test") })
  39. const assertions: PermissionV2.AssertInput[] = []
  40. let denyAction: string | undefined
  41. let afterPermission = (_input: PermissionV2.AssertInput): Effect.Effect<void> => Effect.void
  42. const permission = Layer.succeed(
  43. PermissionV2.Service,
  44. PermissionV2.Service.of({
  45. assert: (input) =>
  46. Effect.sync(() => assertions.push(input)).pipe(
  47. Effect.andThen(Effect.suspend(() => afterPermission(input))),
  48. Effect.andThen(
  49. input.action === denyAction
  50. ? Effect.fail(
  51. new PermissionV2.BlockedError({
  52. rules: [],
  53. permission: input.action,
  54. resources: input.resources,
  55. }),
  56. )
  57. : Effect.void,
  58. ),
  59. ),
  60. ask: () => Effect.die("unused"),
  61. reply: () => Effect.die("unused"),
  62. get: () => Effect.die("unused"),
  63. forSession: () => Effect.die("unused"),
  64. list: () => Effect.die("unused"),
  65. }),
  66. )
  67. const reset = () => {
  68. assertions.length = 0
  69. denyAction = undefined
  70. afterPermission = () => Effect.void
  71. }
  72. const executionNode = makeGlobalNode({
  73. service: SessionExecution.Service,
  74. layer: Layer.effect(
  75. SessionExecution.Service,
  76. Effect.gen(function* () {
  77. const events = yield* EventV2.Service
  78. const store = yield* SessionStore.Service
  79. const complete = Effect.fn("ShellTest.complete")(function* (id: SessionV2.ID) {
  80. const session = yield* store.get(id)
  81. if (!session) return
  82. const assistantMessageID = SessionMessage.ID.create()
  83. yield* events.publish(SessionEvent.Step.Started, {
  84. sessionID: id,
  85. assistantMessageID,
  86. agent: session.agent ?? AgentV2.ID.make("code"),
  87. model: sessionModel,
  88. })
  89. yield* events.publish(SessionEvent.Text.Started, {
  90. sessionID: id,
  91. assistantMessageID,
  92. ordinal: 0,
  93. })
  94. yield* events.publish(SessionEvent.Text.Ended, {
  95. sessionID: id,
  96. assistantMessageID,
  97. ordinal: 0,
  98. text: "ok",
  99. })
  100. yield* events.publish(SessionEvent.Step.Ended, {
  101. sessionID: id,
  102. assistantMessageID,
  103. finish: "stop",
  104. cost: Money.USD.zero,
  105. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  106. })
  107. })
  108. return SessionExecution.Service.of({
  109. active: Effect.succeed(new Set()),
  110. resume: complete,
  111. wake: () => Effect.void,
  112. interrupt: () => Effect.void,
  113. awaitIdle: (id) => complete(id).pipe(Effect.exit, Effect.asVoid),
  114. })
  115. }),
  116. ),
  117. deps: [EventV2.node, SessionStore.node],
  118. })
  119. const layer = AppNodeBuilder.build(
  120. LayerNode.group([
  121. Database.node,
  122. EventV2.node,
  123. Job.node,
  124. ToolOutputStore.cleanupNode,
  125. SessionV2.node,
  126. SessionExecution.node,
  127. PluginRuntime.providerNode,
  128. LocationServiceMap.node,
  129. filesystem,
  130. FSUtil.node,
  131. Global.node,
  132. ]),
  133. [
  134. [SessionExecution.node, executionNode],
  135. [PermissionV2.node, permission],
  136. ],
  137. )
  138. const it = testEffect(layer)
  139. const call = (input: typeof ShellTool.Input.Type, id = "call-shell") => ({
  140. sessionID,
  141. ...toolIdentity,
  142. call: { type: "tool-call" as const, id, name: "shell", input },
  143. })
  144. const isWindows = process.platform === "win32"
  145. const cwdCommand = isWindows ? "(Get-Location).Path; Start-Sleep -Milliseconds 100" : "pwd"
  146. const helloCommand = isWindows ? "[Console]::Out.Write('hello'); Start-Sleep -Milliseconds 100" : "printf hello"
  147. const stderrCommand = isWindows
  148. ? "[Console]::Error.Write('stderr only'); Start-Sleep -Milliseconds 100"
  149. : "printf 'stderr only' >&2"
  150. const mixedOutputCommand = isWindows
  151. ? "[Console]::Out.Write('stdout'); Start-Sleep -Milliseconds 50; [Console]::Error.Write('stderr'); Start-Sleep -Milliseconds 100"
  152. : "printf stdout; sleep 0.05; printf stderr >&2"
  153. const idleCommand = isWindows ? "Start-Sleep -Seconds 60" : "sleep 60"
  154. const steadyProgressCommand = isWindows
  155. ? "[Console]::Out.Write('steady'); Start-Sleep -Milliseconds 3400"
  156. : "printf steady; sleep 3.4"
  157. const bodyExitCommand = isWindows
  158. ? "[Console]::Out.Write('body'); Start-Sleep -Milliseconds 100; exit 7"
  159. : "printf body && exit 7"
  160. const overflowCommand = (bytes: number) =>
  161. isWindows
  162. ? `[Console]::Out.Write(('x' * ${bytes})); Start-Sleep -Milliseconds 100`
  163. : `head -c ${bytes} /dev/zero | tr '\\0' 'x'`
  164. const progressOverflowCommand = (bytes: number, release: string) =>
  165. isWindows
  166. ? `[Console]::Out.Write(('x' * ${bytes})); while (!(Test-Path -LiteralPath '${release}')) { Start-Sleep -Milliseconds 50 }`
  167. : `head -c ${bytes} /dev/zero | tr '\\0' 'x'; while [ ! -e '${release}' ]; do sleep 0.05; done`
  168. const withSession = <A, E, R>(directory: string, body: (registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>) =>
  169. Effect.gen(function* () {
  170. const sessions = yield* SessionV2.Service
  171. const location = Location.Ref.make({ directory: AbsolutePath.make(directory) })
  172. yield* sessions.create({
  173. id: sessionID,
  174. title: "shell test",
  175. location,
  176. model: sessionModel,
  177. })
  178. const locations = yield* LocationServiceMap.Service
  179. const locationLayer = locations.get(location)
  180. return yield* Effect.gen(function* () {
  181. const registry = yield* ToolRegistry.Service
  182. yield* waitForTool(registry, ShellTool.name)
  183. return yield* body(registry)
  184. }).pipe(Effect.provide(locationLayer), Effect.ensuring(locations.invalidate(location)))
  185. })
  186. describe("ShellTool", () => {
  187. it.live("registers and returns real successful output from the active Location", () =>
  188. Effect.acquireUseRelease(
  189. Effect.promise(() => tmpdir()),
  190. (tmp) => {
  191. reset()
  192. return withSession(tmp.path, (registry) =>
  193. Effect.gen(function* () {
  194. const definitions = yield* toolDefinitions(registry)
  195. const shell = definitions.find((tool) => tool.name === "shell")
  196. expect(shell).toBeDefined()
  197. // Code Mode receives the declared output schema, including the command output text.
  198. expect(shell?.outputSchema).toHaveProperty("properties.output")
  199. expect(
  200. (yield* toolDefinitions(registry, [{ action: "shell", resource: "*", effect: "deny" }])).map(
  201. (tool) => tool.name,
  202. ),
  203. ).not.toContain("shell")
  204. const settled = yield* executeTool(registry, call({ command: helloCommand }))
  205. expect(settled.status).toBe("completed")
  206. expect(settled.metadata).toMatchObject({ exit: 0, truncated: false })
  207. expect(settled.content?.[0]).toEqual({ type: "text", text: "hello" })
  208. expect(settled.content?.[1]).toMatchObject({
  209. type: "text",
  210. text: expect.stringContaining("Command exited with code 0."),
  211. })
  212. expect(assertions).toMatchObject([{ sessionID, action: "shell", resources: [helloCommand] }])
  213. }),
  214. )
  215. },
  216. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  217. ),
  218. )
  219. it.live("resolves a relative workdir from the active Location", () =>
  220. Effect.acquireUseRelease(
  221. Effect.promise(() => tmpdir()),
  222. (tmp) => {
  223. reset()
  224. return Effect.promise(() => fs.mkdir(path.join(tmp.path, "src"))).pipe(
  225. Effect.andThen(
  226. withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  227. ),
  228. Effect.andThen((settled) =>
  229. Effect.sync(() =>
  230. expect(settled.content?.[0]).toMatchObject({
  231. type: "text",
  232. text: expect.stringContaining(realpathSync(path.join(tmp.path, "src"))),
  233. }),
  234. ),
  235. ),
  236. )
  237. },
  238. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  239. ),
  240. )
  241. it.live("captures stderr-only and mixed stdout/stderr output", () =>
  242. Effect.acquireUseRelease(
  243. Effect.promise(() => tmpdir()),
  244. (tmp) => {
  245. reset()
  246. return withSession(tmp.path, (registry) =>
  247. Effect.gen(function* () {
  248. const stderr = yield* executeTool(registry, call({ command: stderrCommand }, "call-stderr"))
  249. expect(stderr.metadata).toMatchObject({ exit: 0, truncated: false })
  250. expect(stderr.content?.[0]).toEqual({ type: "text", text: "stderr only" })
  251. const mixed = yield* executeTool(registry, call({ command: mixedOutputCommand }, "call-mixed"))
  252. expect(mixed.metadata).toMatchObject({ exit: 0, truncated: false })
  253. const output = mixed.content?.[0]?.type === "text" ? mixed.content[0].text : ""
  254. expect(output).toContain("stdout")
  255. expect(output).toContain("stderr")
  256. }),
  257. )
  258. },
  259. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  260. ),
  261. )
  262. it.live("rejects a workdir that stops being a directory during approval", () =>
  263. Effect.acquireUseRelease(
  264. Effect.promise(() => tmpdir()),
  265. (tmp) => {
  266. reset()
  267. const workdir = path.join(tmp.path, "src")
  268. afterPermission = (input) =>
  269. input.action === "shell"
  270. ? Effect.promise(async () => {
  271. await fs.rm(workdir, { recursive: true })
  272. await fs.writeFile(workdir, "not a directory")
  273. }).pipe(Effect.orDie)
  274. : Effect.void
  275. return Effect.promise(() => fs.mkdir(workdir)).pipe(
  276. Effect.andThen(
  277. withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  278. ),
  279. Effect.andThen(Effect.sync(() => expect(assertions.map((input) => input.action)).toEqual(["shell"]))),
  280. )
  281. },
  282. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  283. ),
  284. )
  285. it.live("approves an explicit external workdir before shell execution", () =>
  286. Effect.acquireUseRelease(
  287. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  288. ([active, outside]) => {
  289. reset()
  290. return withSession(active.path, (registry) =>
  291. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  292. ).pipe(
  293. Effect.andThen(
  294. Effect.sync(() => {
  295. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"])
  296. expect(assertions[0]).toMatchObject({
  297. resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")],
  298. })
  299. }),
  300. ),
  301. )
  302. },
  303. ([active, outside]) =>
  304. Effect.promise(() =>
  305. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  306. ),
  307. ),
  308. )
  309. it.live("does not execute after external-directory or shell denial", () =>
  310. Effect.acquireUseRelease(
  311. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  312. ([active, outside]) =>
  313. Effect.gen(function* () {
  314. reset()
  315. denyAction = "external_directory"
  316. yield* withSession(active.path, (registry) =>
  317. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  318. )
  319. expect(assertions.map((item) => item.action)).toEqual(["external_directory"])
  320. reset()
  321. denyAction = "shell"
  322. yield* withSession(active.path, (registry) => executeTool(registry, call({ command: cwdCommand })))
  323. expect(assertions.map((item) => item.action)).toEqual(["shell"])
  324. }),
  325. ([active, outside]) =>
  326. Effect.promise(() =>
  327. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  328. ),
  329. ),
  330. )
  331. it.live("reports external command arguments as advisory warnings without enforcing approval", () =>
  332. Effect.acquireUseRelease(
  333. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  334. ([active, outside]) => {
  335. reset()
  336. denyAction = "external_directory"
  337. const target = path.join(outside.path, "secret.txt")
  338. return withSession(active.path, (registry) => executeTool(registry, call({ command: `cat ${target}` }))).pipe(
  339. Effect.andThen((settled) =>
  340. Effect.sync(() => {
  341. expect(assertions.map((item) => item.action)).toEqual(["shell"])
  342. expect(settled.metadata).not.toHaveProperty("warnings")
  343. expect(settled.content?.[1]).toMatchObject({
  344. type: "text",
  345. text: expect.stringContaining("Warnings:"),
  346. })
  347. }),
  348. ),
  349. )
  350. },
  351. ([active, outside]) =>
  352. Effect.promise(() =>
  353. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  354. ),
  355. ),
  356. )
  357. it.live("keeps non-zero exits useful", () =>
  358. Effect.acquireUseRelease(
  359. Effect.promise(() => tmpdir()),
  360. (tmp) => {
  361. reset()
  362. return withSession(tmp.path, (registry) =>
  363. executeTool(registry, call({ command: bodyExitCommand }, "call-nonzero")),
  364. ).pipe(
  365. Effect.andThen((settled) =>
  366. Effect.sync(() => {
  367. expect(settled.status).toBe("completed")
  368. expect(settled.metadata).toMatchObject({ exit: 7, truncated: false })
  369. expect(settled.content?.[0]).toEqual({ type: "text", text: "body" })
  370. expect(settled.content?.[1]).toMatchObject({
  371. type: "text",
  372. text: expect.stringContaining("Command exited with code 7"),
  373. })
  374. }),
  375. ),
  376. )
  377. },
  378. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  379. ),
  380. )
  381. it.live("truncates the model view and points at the saved output file when output overflows", () =>
  382. Effect.acquireUseRelease(
  383. Effect.promise(() => tmpdir()),
  384. (tmp) => {
  385. reset()
  386. const bytes = ShellTool.MAX_CAPTURE_BYTES + 1024
  387. return withSession(tmp.path, (registry) =>
  388. executeTool(registry, call({ command: overflowCommand(bytes) }, "call-overflow")),
  389. ).pipe(
  390. Effect.andThen((settled) =>
  391. Effect.sync(() => {
  392. expect(settled.metadata).toMatchObject({ exit: 0, truncated: true })
  393. expect(settled.content?.[0]).toMatchObject({
  394. type: "text",
  395. text: expect.stringContaining("output truncated; full output saved to:"),
  396. })
  397. }),
  398. ),
  399. )
  400. },
  401. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  402. ),
  403. )
  404. it.live(
  405. "reports the shell ID for a running command",
  406. () =>
  407. Effect.acquireUseRelease(
  408. Effect.promise(() => tmpdir()),
  409. (tmp) => {
  410. reset()
  411. const release = "shell-progress-release"
  412. const releasePath = path.join(tmp.path, release)
  413. return withSession(tmp.path, (registry) =>
  414. Effect.gen(function* () {
  415. const observed = yield* Deferred.make<string>()
  416. yield* executeTool(registry, {
  417. ...call(
  418. { command: progressOverflowCommand(ShellTool.MAX_CAPTURE_BYTES + 1024, release) },
  419. "call-progress",
  420. ),
  421. progress: (update) =>
  422. Effect.gen(function* () {
  423. if (typeof update.shellID !== "string") return
  424. yield* Deferred.succeed(observed, update.shellID)
  425. yield* Effect.promise(() => fs.writeFile(releasePath, ""))
  426. }),
  427. })
  428. expect(yield* Deferred.await(observed)).toMatch(/^sh_/)
  429. }).pipe(Effect.ensuring(Effect.promise(() => fs.writeFile(releasePath, "")).pipe(Effect.ignore))),
  430. )
  431. },
  432. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  433. ),
  434. { timeout: 15_000 },
  435. )
  436. it.live(
  437. "does not repeat shell ID progress",
  438. () =>
  439. Effect.acquireUseRelease(
  440. Effect.promise(() => tmpdir()),
  441. (tmp) => {
  442. reset()
  443. return withSession(tmp.path, (registry) =>
  444. Effect.gen(function* () {
  445. const updates: ToolRegistry.Progress[] = []
  446. yield* executeTool(registry, {
  447. ...call({ command: steadyProgressCommand }, "call-steady-progress"),
  448. progress: (update) => Effect.sync(() => updates.push(update)),
  449. })
  450. expect(updates).toHaveLength(1)
  451. expect(updates[0]?.shellID).toMatch(/^sh_/)
  452. }),
  453. )
  454. },
  455. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  456. ),
  457. { timeout: 10_000 },
  458. )
  459. it.live("returns a useful timeout outcome", () =>
  460. Effect.acquireUseRelease(
  461. Effect.promise(() => tmpdir()),
  462. (tmp) => {
  463. reset()
  464. return withSession(tmp.path, (registry) =>
  465. executeTool(registry, call({ command: idleCommand, timeout: 50 })),
  466. ).pipe(
  467. Effect.andThen((settled) =>
  468. Effect.sync(() => {
  469. expect(settled.metadata).toMatchObject({ timeout: true, truncated: false })
  470. expect(settled.content?.[1]).toMatchObject({
  471. type: "text",
  472. text: expect.stringContaining("Command timed out"),
  473. })
  474. }),
  475. ),
  476. )
  477. },
  478. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  479. ),
  480. )
  481. it.live("returns the shell id for a background command", () =>
  482. Effect.acquireUseRelease(
  483. Effect.promise(() => tmpdir()),
  484. (tmp) => {
  485. reset()
  486. return withSession(tmp.path, (registry) =>
  487. Effect.gen(function* () {
  488. const events = yield* EventV2.Service
  489. const admitted = yield* events.subscribe(SessionEvent.InputAdmitted).pipe(
  490. Stream.filter((event) => event.data.sessionID === sessionID && event.data.input.type === "synthetic"),
  491. Stream.runHead,
  492. Effect.forkScoped({ startImmediately: true }),
  493. )
  494. const settled = yield* executeTool(registry, call({ command: idleCommand, timeout: 50, background: true }))
  495. const shellID = typeof settled.metadata?.shellID === "string" ? settled.metadata.shellID : undefined
  496. expect(settled.metadata).toMatchObject({ truncated: false })
  497. expect(shellID).toStartWith("sh_")
  498. const shell = yield* Shell.Service
  499. if (!shellID) return
  500. const id = ShellSchema.ID.make(shellID)
  501. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  502. expect((yield* shell.wait(id)).status).toBe("timeout")
  503. expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.input.data).toMatchObject({
  504. description: idleCommand,
  505. metadata: {
  506. source: "shell",
  507. state: "completed",
  508. },
  509. })
  510. }),
  511. )
  512. },
  513. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  514. ),
  515. )
  516. it.live("updates and clears a running shell timeout", () =>
  517. Effect.acquireUseRelease(
  518. Effect.promise(() => tmpdir()),
  519. (tmp) => {
  520. reset()
  521. return withSession(tmp.path, (registry) =>
  522. Effect.gen(function* () {
  523. const shell = yield* Shell.Service
  524. const timed = yield* executeTool(
  525. registry,
  526. call({ command: idleCommand, background: true }, "call-updated-timeout"),
  527. )
  528. const timedID = timed.metadata?.shellID
  529. expect(typeof timedID).toBe("string")
  530. if (typeof timedID !== "string") return
  531. const timedShellID = ShellSchema.ID.make(timedID)
  532. yield* shell.timeout(timedShellID, 50)
  533. expect((yield* shell.wait(timedShellID)).status).toBe("timeout")
  534. const cleared = yield* executeTool(
  535. registry,
  536. call({ command: idleCommand, timeout: 50, background: true }, "call-cleared-timeout"),
  537. )
  538. const clearedID = cleared.metadata?.shellID
  539. expect(typeof clearedID).toBe("string")
  540. if (typeof clearedID !== "string") return
  541. const clearedShellID = ShellSchema.ID.make(clearedID)
  542. yield* shell.timeout(clearedShellID, 0)
  543. yield* Effect.sleep(Duration.millis(100))
  544. expect((yield* shell.get(clearedShellID)).status).toBe("running")
  545. yield* shell.remove(clearedShellID)
  546. }),
  547. )
  548. },
  549. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  550. ),
  551. )
  552. it.live("backgrounds a foreground command when the session is signaled", () =>
  553. Effect.acquireUseRelease(
  554. Effect.promise(() => tmpdir()),
  555. (tmp) => {
  556. reset()
  557. return withSession(tmp.path, (registry) =>
  558. Effect.gen(function* () {
  559. const jobs = yield* Job.Service
  560. const scope = yield* Scope.Scope
  561. const waiting = yield* executeTool(
  562. registry,
  563. call({ command: idleCommand, timeout: 50 }, "call-background-signal"),
  564. ).pipe(Effect.forkIn(scope, { startImmediately: true }))
  565. const backgroundWhenReady = (remaining = 1000): Effect.Effect<Job.Info[], Error> =>
  566. Effect.gen(function* () {
  567. const backgrounded = yield* jobs.backgroundAll({ sessionID })
  568. if (backgrounded.length > 0) return backgrounded
  569. if (remaining <= 0) return yield* Effect.fail(new Error("Timed out waiting for foreground shell job"))
  570. yield* Effect.promise(() => Bun.sleep(1))
  571. return yield* backgroundWhenReady(remaining - 1)
  572. })
  573. expect(yield* backgroundWhenReady()).toMatchObject([{ id: "call-background-signal", type: "shell" }])
  574. const settled = yield* Fiber.join(waiting)
  575. const shellID = typeof settled.metadata?.shellID === "string" ? settled.metadata.shellID : undefined
  576. expect(settled.metadata).toMatchObject({ truncated: false })
  577. expect(settled.content?.[0]).toEqual({
  578. type: "text",
  579. text: "The command was moved to the background.",
  580. })
  581. expect(settled.content?.[1]).toMatchObject({
  582. type: "text",
  583. text: expect.stringContaining("DO NOT sleep, poll"),
  584. })
  585. expect(shellID).toStartWith("sh_")
  586. const shell = yield* Shell.Service
  587. if (!shellID) return
  588. const id = ShellSchema.ID.make(shellID)
  589. yield* Effect.sleep(Duration.millis(100))
  590. expect((yield* shell.get(id)).status).toBe("running")
  591. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  592. yield* shell.remove(id)
  593. }),
  594. )
  595. },
  596. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  597. ),
  598. )
  599. })