tool-shell.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. import fs from "fs/promises"
  2. import { realpathSync } from "node:fs"
  3. import path from "path"
  4. import { describe, expect, test } from "bun:test"
  5. import { DateTime, 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/core/effect/layer-node"
  9. import { makeGlobalNode } from "@opencode-ai/core/effect/app-node"
  10. import { filesystem } from "@opencode-ai/core/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/core/fs-util"
  14. import { Global } from "@opencode-ai/core/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, settleTool, 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 bodyExitCommand = isWindows
  155. ? "[Console]::Out.Write('body'); Start-Sleep -Milliseconds 100; exit 7"
  156. : "printf body && exit 7"
  157. const overflowCommand = (bytes: number) =>
  158. isWindows
  159. ? `[Console]::Out.Write(('x' * ${bytes})); Start-Sleep -Milliseconds 100`
  160. : `head -c ${bytes} /dev/zero | tr '\\0' 'x'`
  161. const progressOverflowCommand = (bytes: number) =>
  162. isWindows
  163. ? `[Console]::Out.Write(('x' * ${bytes})); Start-Sleep -Milliseconds 1500`
  164. : `head -c ${bytes} /dev/zero | tr '\\0' 'x'; sleep 1.5`
  165. const withSession = <A, E, R>(directory: string, body: (registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>) =>
  166. Effect.gen(function* () {
  167. const sessions = yield* SessionV2.Service
  168. const location = Location.Ref.make({ directory: AbsolutePath.make(directory) })
  169. yield* sessions.create({
  170. id: sessionID,
  171. title: "shell test",
  172. location,
  173. model: sessionModel,
  174. })
  175. const locations = yield* LocationServiceMap.Service
  176. const locationLayer = locations.get(location)
  177. return yield* Effect.gen(function* () {
  178. const registry = yield* ToolRegistry.Service
  179. yield* waitForTool(registry, ShellTool.name)
  180. return yield* body(registry)
  181. }).pipe(Effect.provide(locationLayer), Effect.ensuring(locations.invalidate(location)))
  182. })
  183. describe("ShellTool", () => {
  184. it.live("registers and returns real successful output from the active Location", () =>
  185. Effect.acquireUseRelease(
  186. Effect.promise(() => tmpdir()),
  187. (tmp) => {
  188. reset()
  189. return withSession(tmp.path, (registry) =>
  190. Effect.gen(function* () {
  191. const definitions = yield* toolDefinitions(registry)
  192. const shell = definitions.find((tool) => tool.name === "shell")
  193. expect(shell).toBeDefined()
  194. expect(shell?.outputSchema).not.toHaveProperty("properties.output")
  195. expect(
  196. (yield* toolDefinitions(registry, [{ action: "shell", resource: "*", effect: "deny" }])).map(
  197. (tool) => tool.name,
  198. ),
  199. ).not.toContain("shell")
  200. const settled = yield* settleTool(registry, call({ command: helloCommand }))
  201. expect(settled.output?.structured).toMatchObject({ exit: 0, truncated: false })
  202. expect(settled.output?.content[0]).toEqual({ type: "text", text: "hello" })
  203. expect(settled.output?.content[1]).toMatchObject({
  204. type: "text",
  205. text: expect.stringContaining("Command exited with code 0."),
  206. })
  207. expect(assertions).toMatchObject([{ sessionID, action: "shell", resources: [helloCommand] }])
  208. }),
  209. )
  210. },
  211. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  212. ),
  213. )
  214. it.live("resolves a relative workdir from the active Location", () =>
  215. Effect.acquireUseRelease(
  216. Effect.promise(() => tmpdir()),
  217. (tmp) => {
  218. reset()
  219. return Effect.promise(() => fs.mkdir(path.join(tmp.path, "src"))).pipe(
  220. Effect.andThen(
  221. withSession(tmp.path, (registry) => settleTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  222. ),
  223. Effect.andThen((settled) =>
  224. Effect.sync(() =>
  225. expect(settled.output?.content[0]).toMatchObject({
  226. type: "text",
  227. text: expect.stringContaining(realpathSync(path.join(tmp.path, "src"))),
  228. }),
  229. ),
  230. ),
  231. )
  232. },
  233. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  234. ),
  235. )
  236. it.live("captures stderr-only and mixed stdout/stderr output", () =>
  237. Effect.acquireUseRelease(
  238. Effect.promise(() => tmpdir()),
  239. (tmp) => {
  240. reset()
  241. return withSession(tmp.path, (registry) =>
  242. Effect.gen(function* () {
  243. const stderr = yield* settleTool(registry, call({ command: stderrCommand }, "call-stderr"))
  244. expect(stderr.output?.structured).toMatchObject({ exit: 0, truncated: false })
  245. expect(stderr.output?.content[0]).toEqual({ type: "text", text: "stderr only" })
  246. const mixed = yield* settleTool(registry, call({ command: mixedOutputCommand }, "call-mixed"))
  247. expect(mixed.output?.structured).toMatchObject({ exit: 0, truncated: false })
  248. const output = mixed.output?.content[0]?.type === "text" ? mixed.output.content[0].text : ""
  249. expect(output).toContain("stdout")
  250. expect(output).toContain("stderr")
  251. }),
  252. )
  253. },
  254. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  255. ),
  256. )
  257. it.live("rejects a workdir that stops being a directory during approval", () =>
  258. Effect.acquireUseRelease(
  259. Effect.promise(() => tmpdir()),
  260. (tmp) => {
  261. reset()
  262. const workdir = path.join(tmp.path, "src")
  263. afterPermission = (input) =>
  264. input.action === "shell"
  265. ? Effect.promise(async () => {
  266. await fs.rm(workdir, { recursive: true })
  267. await fs.writeFile(workdir, "not a directory")
  268. }).pipe(Effect.orDie)
  269. : Effect.void
  270. return Effect.promise(() => fs.mkdir(workdir)).pipe(
  271. Effect.andThen(
  272. withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  273. ),
  274. Effect.andThen(Effect.sync(() => expect(assertions.map((input) => input.action)).toEqual(["shell"]))),
  275. )
  276. },
  277. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  278. ),
  279. )
  280. it.live("approves an explicit external workdir before shell execution", () =>
  281. Effect.acquireUseRelease(
  282. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  283. ([active, outside]) => {
  284. reset()
  285. return withSession(active.path, (registry) =>
  286. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  287. ).pipe(
  288. Effect.andThen(
  289. Effect.sync(() => {
  290. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"])
  291. expect(assertions[0]).toMatchObject({
  292. resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")],
  293. })
  294. }),
  295. ),
  296. )
  297. },
  298. ([active, outside]) =>
  299. Effect.promise(() =>
  300. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  301. ),
  302. ),
  303. )
  304. it.live("does not execute after external-directory or shell denial", () =>
  305. Effect.acquireUseRelease(
  306. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  307. ([active, outside]) =>
  308. Effect.gen(function* () {
  309. reset()
  310. denyAction = "external_directory"
  311. yield* withSession(active.path, (registry) =>
  312. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  313. )
  314. expect(assertions.map((item) => item.action)).toEqual(["external_directory"])
  315. reset()
  316. denyAction = "shell"
  317. yield* withSession(active.path, (registry) => executeTool(registry, call({ command: cwdCommand })))
  318. expect(assertions.map((item) => item.action)).toEqual(["shell"])
  319. }),
  320. ([active, outside]) =>
  321. Effect.promise(() =>
  322. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  323. ),
  324. ),
  325. )
  326. it.live("reports external command arguments as advisory warnings without enforcing approval", () =>
  327. Effect.acquireUseRelease(
  328. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  329. ([active, outside]) => {
  330. reset()
  331. denyAction = "external_directory"
  332. const target = path.join(outside.path, "secret.txt")
  333. return withSession(active.path, (registry) => settleTool(registry, call({ command: `cat ${target}` }))).pipe(
  334. Effect.andThen((settled) =>
  335. Effect.sync(() => {
  336. expect(assertions.map((item) => item.action)).toEqual(["shell"])
  337. expect(settled.output?.structured).not.toHaveProperty("warnings")
  338. expect(settled.output?.content[1]).toMatchObject({
  339. type: "text",
  340. text: expect.stringContaining("Warnings:"),
  341. })
  342. }),
  343. ),
  344. )
  345. },
  346. ([active, outside]) =>
  347. Effect.promise(() =>
  348. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  349. ),
  350. ),
  351. )
  352. it.live("keeps non-zero exits useful", () =>
  353. Effect.acquireUseRelease(
  354. Effect.promise(() => tmpdir()),
  355. (tmp) => {
  356. reset()
  357. return withSession(tmp.path, (registry) =>
  358. settleTool(registry, call({ command: bodyExitCommand }, "call-nonzero")),
  359. ).pipe(
  360. Effect.andThen((settled) =>
  361. Effect.sync(() => {
  362. expect(settled.output?.structured).toMatchObject({ exit: 7, truncated: false })
  363. expect(settled.output?.content[0]).toEqual({ type: "text", text: "body" })
  364. expect(settled.output?.content[1]).toMatchObject({
  365. type: "text",
  366. text: expect.stringContaining("Command exited with code 7"),
  367. })
  368. }),
  369. ),
  370. )
  371. },
  372. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  373. ),
  374. )
  375. it.live("truncates the model view and points at the saved output file when output overflows", () =>
  376. Effect.acquireUseRelease(
  377. Effect.promise(() => tmpdir()),
  378. (tmp) => {
  379. reset()
  380. const bytes = ShellTool.MAX_CAPTURE_BYTES + 1024
  381. return withSession(tmp.path, (registry) =>
  382. settleTool(registry, call({ command: overflowCommand(bytes) }, "call-overflow")),
  383. ).pipe(
  384. Effect.andThen((settled) =>
  385. Effect.sync(() => {
  386. expect(settled.output?.structured).toMatchObject({ exit: 0, truncated: true })
  387. expect(settled.output?.content[0]).toMatchObject({
  388. type: "text",
  389. text: expect.stringContaining("output truncated; full output saved to:"),
  390. })
  391. }),
  392. ),
  393. )
  394. },
  395. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  396. ),
  397. )
  398. it.live("reports bounded output progress for a running command", () =>
  399. Effect.acquireUseRelease(
  400. Effect.promise(() => tmpdir()),
  401. (tmp) => {
  402. reset()
  403. const bytes = ShellTool.MAX_CAPTURE_BYTES + 1024
  404. return withSession(tmp.path, (registry) =>
  405. Effect.gen(function* () {
  406. const progress: ToolRegistry.Progress[] = []
  407. yield* settleTool(registry, {
  408. ...call({ command: progressOverflowCommand(bytes) }, "call-progress"),
  409. progress: (update) => Effect.sync(() => progress.push(update)),
  410. })
  411. expect(progress).toHaveLength(1)
  412. expect(progress[0]?.structured).toEqual({ truncated: true })
  413. const content = progress[0]?.content[0]
  414. expect(content?.type).toBe("text")
  415. if (content?.type !== "text") return
  416. expect(content.text.indexOf("\n\n[output truncated; full output saved to:")).toBe(
  417. ShellTool.MAX_CAPTURE_BYTES,
  418. )
  419. }),
  420. )
  421. },
  422. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  423. ),
  424. )
  425. it.live("returns a useful timeout settlement", () =>
  426. Effect.acquireUseRelease(
  427. Effect.promise(() => tmpdir()),
  428. (tmp) => {
  429. reset()
  430. return withSession(tmp.path, (registry) =>
  431. settleTool(registry, call({ command: idleCommand, timeout: 50 })),
  432. ).pipe(
  433. Effect.andThen((settled) =>
  434. Effect.sync(() => {
  435. expect(settled.output?.structured).toMatchObject({ timeout: true, truncated: false })
  436. expect(settled.output?.content[1]).toMatchObject({
  437. type: "text",
  438. text: expect.stringContaining("Command timed out"),
  439. })
  440. }),
  441. ),
  442. )
  443. },
  444. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  445. ),
  446. )
  447. it.live("returns the shell id for a background command", () =>
  448. Effect.acquireUseRelease(
  449. Effect.promise(() => tmpdir()),
  450. (tmp) => {
  451. reset()
  452. return withSession(tmp.path, (registry) =>
  453. Effect.gen(function* () {
  454. const events = yield* EventV2.Service
  455. const admitted = yield* events.subscribe(SessionEvent.InputAdmitted).pipe(
  456. Stream.filter((event) => event.data.sessionID === sessionID && event.data.input.type === "synthetic"),
  457. Stream.runHead,
  458. Effect.forkScoped({ startImmediately: true }),
  459. )
  460. const settled = yield* settleTool(registry, call({ command: idleCommand, timeout: 50, background: true }))
  461. const structured = settled.output?.structured as Record<string, unknown> | undefined
  462. const shellID = typeof structured?.shellID === "string" ? structured.shellID : undefined
  463. expect(settled.output?.structured).toMatchObject({ truncated: false })
  464. expect(shellID).toStartWith("sh_")
  465. const shell = yield* Shell.Service
  466. if (!shellID) return
  467. const id = ShellSchema.ID.make(shellID)
  468. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  469. expect((yield* shell.wait(id)).status).toBe("timeout")
  470. expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.input.data).toMatchObject({
  471. description: idleCommand,
  472. metadata: {
  473. source: "shell",
  474. state: "completed",
  475. },
  476. })
  477. }),
  478. )
  479. },
  480. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  481. ),
  482. )
  483. it.live("updates and clears a running shell timeout", () =>
  484. Effect.acquireUseRelease(
  485. Effect.promise(() => tmpdir()),
  486. (tmp) => {
  487. reset()
  488. return withSession(tmp.path, (registry) =>
  489. Effect.gen(function* () {
  490. const shell = yield* Shell.Service
  491. const timed = yield* settleTool(
  492. registry,
  493. call({ command: idleCommand, background: true }, "call-updated-timeout"),
  494. )
  495. const timedID = (timed.output?.structured as Record<string, unknown> | undefined)?.shellID
  496. expect(typeof timedID).toBe("string")
  497. if (typeof timedID !== "string") return
  498. const timedShellID = ShellSchema.ID.make(timedID)
  499. yield* shell.timeout(timedShellID, 50)
  500. expect((yield* shell.wait(timedShellID)).status).toBe("timeout")
  501. const cleared = yield* settleTool(
  502. registry,
  503. call({ command: idleCommand, timeout: 50, background: true }, "call-cleared-timeout"),
  504. )
  505. const clearedID = (cleared.output?.structured as Record<string, unknown> | undefined)?.shellID
  506. expect(typeof clearedID).toBe("string")
  507. if (typeof clearedID !== "string") return
  508. const clearedShellID = ShellSchema.ID.make(clearedID)
  509. yield* shell.timeout(clearedShellID, 0)
  510. yield* Effect.sleep(Duration.millis(100))
  511. expect((yield* shell.get(clearedShellID)).status).toBe("running")
  512. yield* shell.remove(clearedShellID)
  513. }),
  514. )
  515. },
  516. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  517. ),
  518. )
  519. it.live("backgrounds a foreground command when the session is signaled", () =>
  520. Effect.acquireUseRelease(
  521. Effect.promise(() => tmpdir()),
  522. (tmp) => {
  523. reset()
  524. return withSession(tmp.path, (registry) =>
  525. Effect.gen(function* () {
  526. const jobs = yield* Job.Service
  527. const scope = yield* Scope.Scope
  528. const waiting = yield* settleTool(
  529. registry,
  530. call({ command: idleCommand, timeout: 50 }, "call-background-signal"),
  531. ).pipe(Effect.forkIn(scope, { startImmediately: true }))
  532. const backgroundWhenReady = (remaining = 1000): Effect.Effect<Job.Info[], Error> =>
  533. Effect.gen(function* () {
  534. const backgrounded = yield* jobs.backgroundAll({ sessionID })
  535. if (backgrounded.length > 0) return backgrounded
  536. if (remaining <= 0) return yield* Effect.fail(new Error("Timed out waiting for foreground shell job"))
  537. yield* Effect.promise(() => Bun.sleep(1))
  538. return yield* backgroundWhenReady(remaining - 1)
  539. })
  540. expect(yield* backgroundWhenReady()).toMatchObject([{ id: "call-background-signal", type: "shell" }])
  541. const settled = yield* Fiber.join(waiting)
  542. const structured = settled.output?.structured as Record<string, unknown> | undefined
  543. const shellID = typeof structured?.shellID === "string" ? structured.shellID : undefined
  544. expect(settled.output?.structured).toMatchObject({ truncated: false })
  545. expect(settled.output?.content[0]).toEqual({
  546. type: "text",
  547. text: "The command was moved to the background.",
  548. })
  549. expect(settled.output?.content[1]).toMatchObject({
  550. type: "text",
  551. text: expect.stringContaining("DO NOT sleep, poll"),
  552. })
  553. expect(shellID).toStartWith("sh_")
  554. const shell = yield* Shell.Service
  555. if (!shellID) return
  556. const id = ShellSchema.ID.make(shellID)
  557. yield* Effect.sleep(Duration.millis(100))
  558. expect((yield* shell.get(id)).status).toBe("running")
  559. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  560. yield* shell.remove(id)
  561. }),
  562. )
  563. },
  564. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  565. ),
  566. )
  567. })
  568. test("keeps locked deferred parity TODOs visible", async () => {
  569. const source = await fs.readFile(new URL("../src/tool/shell.ts", import.meta.url), "utf8")
  570. for (const todo of [
  571. "Port tree-sitter bash / PowerShell parser-based approval reduction.",
  572. "Port BashArity reusable command-prefix approvals.",
  573. "Replace token-based command-argument external-directory advisories with parser-based detection.",
  574. "Restore PowerShell and cmd-specific invocation/path handling on Windows.",
  575. "Add plugin shell.env environment augmentation once V2 plugin hooks exist.",
  576. "Persist job status and define restart recovery before exposing remote observation.",
  577. "Revisit process-group cleanup and platform coverage with shell-specific tests if current AppProcess semantics do not fully cover it.",
  578. "Revisit binary output handling if stdout/stderr decoding is text-only.",
  579. "Stream full shell output into managed storage while retaining only a bounded in-memory preview.",
  580. ]) {
  581. expect(source).toContain(`TODO: ${todo}`)
  582. }
  583. })