noninteractive.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. import { afterEach, describe, expect, mock, spyOn, test } from "bun:test"
  2. import {
  3. OpenCode,
  4. type EventSubscribeOutput,
  5. type SessionMessageAssistantTool,
  6. type SessionMessageInfo,
  7. } from "@opencode-ai/client/promise"
  8. import { runNonInteractivePrompt } from "../../src/run/noninteractive"
  9. type V2Event = EventSubscribeOutput
  10. type FormInfo = Extract<V2Event, { type: "form.created" }>["data"]["form"]
  11. const location = { directory: "/work tree", workspaceID: "wrk_1" }
  12. function ok<T>(data: T) {
  13. return Promise.resolve(data)
  14. }
  15. function form(id: string, sessionID: string): FormInfo {
  16. return {
  17. id,
  18. sessionID,
  19. title: "Input requested",
  20. fields: [{ key: "authorization", type: "external", url: "https://example.com/form" }],
  21. }
  22. }
  23. function formCreated(info: FormInfo, eventLocation = location): V2Event {
  24. return { id: `evt_${info.id}`, created: 0, type: "form.created", location: eventLocation, data: { form: info } }
  25. }
  26. function prompted(inputID: string): V2Event {
  27. return {
  28. id: "evt_prompted",
  29. created: 0,
  30. type: "session.input.promoted",
  31. durable: { aggregateID: "ses_1", seq: 0, version: 1 },
  32. data: { sessionID: "ses_1", inputID },
  33. }
  34. }
  35. function settled(outcome: "success" | "interrupted" = "success"): V2Event {
  36. if (outcome === "interrupted")
  37. return {
  38. id: "evt_interrupted",
  39. created: 0,
  40. type: "session.execution.interrupted",
  41. durable: { aggregateID: "ses_1", seq: 1, version: 1 },
  42. data: { sessionID: "ses_1", reason: "user" },
  43. }
  44. return {
  45. id: "evt_succeeded",
  46. created: 0,
  47. type: "session.execution.succeeded",
  48. durable: { aggregateID: "ses_1", seq: 1, version: 1 },
  49. data: { sessionID: "ses_1" },
  50. }
  51. }
  52. function stepStarted(): V2Event {
  53. return {
  54. id: "evt_step_started",
  55. created: 1,
  56. type: "session.step.started",
  57. durable: { aggregateID: "ses_1", seq: 1, version: 1 },
  58. data: {
  59. sessionID: "ses_1",
  60. assistantMessageID: "msg_assistant",
  61. agent: "build",
  62. model: { providerID: "test", id: "test-model" },
  63. },
  64. }
  65. }
  66. function stepFailed(message: string): V2Event {
  67. return {
  68. id: "evt_step_failed",
  69. created: 2,
  70. type: "session.step.failed",
  71. durable: { aggregateID: "ses_1", seq: 2, version: 1 },
  72. data: {
  73. sessionID: "ses_1",
  74. assistantMessageID: "msg_assistant",
  75. error: { type: "provider.transport", message },
  76. },
  77. }
  78. }
  79. function executionFailed(message: string): V2Event {
  80. return {
  81. id: "evt_execution_failed",
  82. created: 3,
  83. type: "session.execution.failed",
  84. durable: { aggregateID: "ses_1", seq: 3, version: 1 },
  85. data: {
  86. sessionID: "ses_1",
  87. error: { type: "provider.transport", message },
  88. },
  89. }
  90. }
  91. function failedTool(inputID: string): V2Event[] {
  92. return [
  93. prompted(inputID),
  94. {
  95. id: "evt_failed_tool_input",
  96. created: 1,
  97. type: "session.tool.input.started",
  98. durable: { aggregateID: "ses_1", seq: 1, version: 1 },
  99. data: {
  100. sessionID: "ses_1",
  101. assistantMessageID: "msg_failed_tool",
  102. callID: "call_failed_tool",
  103. name: "shell",
  104. },
  105. },
  106. {
  107. id: "evt_failed_tool_called",
  108. created: 2,
  109. type: "session.tool.called",
  110. durable: { aggregateID: "ses_1", seq: 2, version: 1 },
  111. data: {
  112. sessionID: "ses_1",
  113. assistantMessageID: "msg_failed_tool",
  114. callID: "call_failed_tool",
  115. input: { command: "printf partial && false" },
  116. executed: true,
  117. },
  118. },
  119. {
  120. id: "evt_failed_tool_progress",
  121. created: 3,
  122. type: "session.tool.progress",
  123. data: {
  124. sessionID: "ses_1",
  125. assistantMessageID: "msg_failed_tool",
  126. callID: "call_failed_tool",
  127. structured: { checkpoint: 1 },
  128. content: [{ type: "text", text: "partial output" }],
  129. },
  130. },
  131. {
  132. id: "evt_failed_tool_terminal",
  133. created: 4,
  134. type: "session.tool.failed",
  135. durable: { aggregateID: "ses_1", seq: 4, version: 1 },
  136. data: {
  137. sessionID: "ses_1",
  138. assistantMessageID: "msg_failed_tool",
  139. callID: "call_failed_tool",
  140. error: { type: "unknown", message: "tool failed" },
  141. metadata: { checkpoint: 1 },
  142. content: [{ type: "text", text: "partial output" }],
  143. executed: true,
  144. },
  145. },
  146. settled(),
  147. ]
  148. }
  149. function successfulGrep(inputID: string): V2Event[] {
  150. const text = "Found 2 matches\n/src/a.ts:\n Line 1: needle\n/src/b.ts:\n Line 2: needle"
  151. return [
  152. prompted(inputID),
  153. {
  154. id: "evt_grep_input",
  155. created: 1,
  156. type: "session.tool.input.started",
  157. durable: { aggregateID: "ses_1", seq: 1, version: 1 },
  158. data: {
  159. sessionID: "ses_1",
  160. assistantMessageID: "msg_grep",
  161. callID: "call_grep",
  162. name: "grep",
  163. },
  164. },
  165. {
  166. id: "evt_grep_called",
  167. created: 2,
  168. type: "session.tool.called",
  169. durable: { aggregateID: "ses_1", seq: 2, version: 1 },
  170. data: {
  171. sessionID: "ses_1",
  172. assistantMessageID: "msg_grep",
  173. callID: "call_grep",
  174. input: { pattern: "needle" },
  175. executed: true,
  176. },
  177. },
  178. {
  179. id: "evt_grep_success",
  180. created: 3,
  181. type: "session.tool.success",
  182. durable: { aggregateID: "ses_1", seq: 3, version: 1 },
  183. data: {
  184. sessionID: "ses_1",
  185. assistantMessageID: "msg_grep",
  186. callID: "call_grep",
  187. structured: { matches: 2 },
  188. content: [{ type: "text", text }],
  189. executed: false,
  190. },
  191. },
  192. settled(),
  193. ]
  194. }
  195. // Runs one non-interactive prompt against a mocked SDK. `turn` produces the
  196. // live events the prompt admission triggers, keyed by the generated message ID.
  197. async function run(input: {
  198. turn: (inputID: string) => V2Event[]
  199. pendingForms?: FormInfo[]
  200. attached?: boolean
  201. format?: "default" | "json"
  202. compatibility?: "v1"
  203. cancel?: (input: { sessionID: string; formID: string }) => Promise<void>
  204. renderTool?: (part: SessionMessageAssistantTool) => Promise<void>
  205. renderToolError?: (part: SessionMessageAssistantTool) => Promise<void>
  206. messages?: (inputID: string) => SessionMessageInfo[]
  207. wait?: () => Promise<void>
  208. terminalDelay?: number
  209. }) {
  210. const sdk = OpenCode.make({ baseUrl: "https://opencode.test" })
  211. const values: V2Event[] = [{ id: "evt_connected", type: "server.connected", data: {} }]
  212. let wake: (() => void) | undefined
  213. const wait = Promise.withResolvers<void>()
  214. const stream = (async function* (): AsyncGenerator<V2Event, void, unknown> {
  215. while (true) {
  216. const value = values.shift()
  217. if (!value) {
  218. await new Promise<void>((resolve) => {
  219. wake = resolve
  220. })
  221. continue
  222. }
  223. if (value.type.startsWith("session.execution.")) {
  224. if (input.terminalDelay) await Bun.sleep(input.terminalDelay)
  225. setTimeout(wait.resolve, 0)
  226. }
  227. yield value
  228. }
  229. })()
  230. spyOn(sdk.event, "subscribe").mockImplementation(() => stream)
  231. spyOn(sdk.permission, "list").mockImplementation(() => ok([]) as never)
  232. spyOn(sdk.question, "list").mockImplementation(() => ok([]) as never)
  233. spyOn(sdk.question, "reject").mockImplementation(() => ok(undefined) as never)
  234. spyOn(sdk.form, "list").mockImplementation(
  235. (request) => ok(input.pendingForms?.filter((item) => item.sessionID === request.sessionID) ?? []) as never,
  236. )
  237. spyOn(sdk.form.request, "list").mockImplementation(
  238. () =>
  239. ok({
  240. location: { ...location, project: { id: "proj_1", directory: location.directory } },
  241. data: input.pendingForms?.filter((item) => item.sessionID === "global") ?? [],
  242. }) as never,
  243. )
  244. spyOn(sdk.form, "cancel").mockImplementation((request) => (input.cancel?.(request) ?? ok(undefined)) as never)
  245. let promptID = "msg_prompt"
  246. spyOn(sdk.session, "wait").mockImplementation(() => input.wait?.() ?? wait.promise)
  247. spyOn(sdk.message, "list").mockImplementation(() =>
  248. ok({
  249. data: input.messages?.(promptID) ?? [
  250. { id: promptID, type: "user", text: "hello", time: { created: 1 } },
  251. ],
  252. cursor: {},
  253. }),
  254. )
  255. spyOn(sdk.session, "prompt").mockImplementation((request) => {
  256. const messageID = request.id ?? "msg_prompt"
  257. promptID = messageID
  258. values.push(...input.turn(messageID))
  259. wake?.()
  260. wake = undefined
  261. return ok({ admittedSeq: 1, id: messageID, sessionID: "ses_1", timeCreated: 1 }) as never
  262. })
  263. await runNonInteractivePrompt({
  264. client: sdk,
  265. sessionID: "ses_1",
  266. location,
  267. message: "hello",
  268. files: [],
  269. thinking: false,
  270. format: input.format ?? "default",
  271. auto: false,
  272. attached: input.attached ?? false,
  273. compatibility: input.compatibility,
  274. renderTool: input.renderTool ?? (() => Promise.resolve()),
  275. renderToolError: input.renderToolError ?? (() => Promise.resolve()),
  276. })
  277. return sdk
  278. }
  279. async function capture(input: Parameters<typeof run>[0]) {
  280. const stdout: string[] = []
  281. const stderr: string[] = []
  282. const exitCode = process.exitCode
  283. const stdoutWrite = spyOn(process.stdout, "write").mockImplementation((chunk) => {
  284. stdout.push(String(chunk))
  285. return true
  286. })
  287. const stderrWrite = spyOn(process.stderr, "write").mockImplementation((chunk) => {
  288. stderr.push(String(chunk))
  289. return true
  290. })
  291. try {
  292. await run(input)
  293. return { stdout: stdout.join(""), stderr: stderr.join(""), exitCode: process.exitCode }
  294. } finally {
  295. process.exitCode = exitCode ?? 0
  296. stdoutWrite.mockRestore()
  297. stderrWrite.mockRestore()
  298. }
  299. }
  300. afterEach(() => {
  301. mock.restore()
  302. })
  303. describe("runNonInteractivePrompt", () => {
  304. test("keeps formatted tool output and compact structured metadata in JSON", async () => {
  305. const output = await capture({ format: "json", turn: successfulGrep })
  306. const events = output.stdout
  307. .split("\n")
  308. .filter(Boolean)
  309. .map((line) => JSON.parse(line))
  310. expect(events).toHaveLength(1)
  311. expect(events[0]).toMatchObject({
  312. type: "tool_use",
  313. part: {
  314. tool: "grep",
  315. state: {
  316. status: "completed",
  317. output: expect.stringContaining("Found 2 matches"),
  318. metadata: {
  319. structured: { matches: 2 },
  320. content: [{ type: "text", text: expect.stringContaining("/src/a.ts") }],
  321. },
  322. },
  323. },
  324. })
  325. expect(events[0].part.state.metadata.structured).toEqual({ matches: 2 })
  326. expect(events[0].part.state.metadata.result).toBeUndefined()
  327. })
  328. test("uses session.wait then reconciles projected output without a terminal event", async () => {
  329. const idle = Promise.withResolvers<void>()
  330. let done = false
  331. const task = capture({
  332. format: "json",
  333. turn: (messageID) => [prompted(messageID)],
  334. wait: () => idle.promise,
  335. messages: (messageID) => [
  336. {
  337. id: "msg_assistant",
  338. type: "assistant",
  339. agent: "build",
  340. model: { providerID: "test", id: "test-model" },
  341. content: [{ type: "text", text: "projected answer" }],
  342. finish: "stop",
  343. time: { created: 2, completed: 3 },
  344. },
  345. { id: messageID, type: "user", text: "hello", time: { created: 1 } },
  346. ],
  347. }).then((output) => {
  348. done = true
  349. return output
  350. })
  351. await Bun.sleep(0)
  352. await Bun.sleep(0)
  353. expect(done).toBe(false)
  354. idle.resolve()
  355. const output = await task
  356. expect(
  357. output.stdout
  358. .split("\n")
  359. .filter(Boolean)
  360. .map((line) => JSON.parse(line)),
  361. ).toEqual([expect.objectContaining({ type: "text", part: expect.objectContaining({ text: "projected answer" }) })])
  362. })
  363. test("reports an observed execution failure before prompt promotion", async () => {
  364. const output = await capture({
  365. format: "json",
  366. turn: () => [executionFailed("instructions unavailable")],
  367. messages: () => [],
  368. })
  369. expect(
  370. output.stdout
  371. .split("\n")
  372. .filter(Boolean)
  373. .map((line) => JSON.parse(line)),
  374. ).toEqual([
  375. expect.objectContaining({
  376. type: "error",
  377. error: { type: "provider.transport", message: "instructions unavailable" },
  378. }),
  379. ])
  380. expect(output.exitCode).toBe(1)
  381. })
  382. test("waits for a terminal failure when idle wins before projection", async () => {
  383. for (const promotedBeforeFailure of [true, false]) {
  384. const output = await capture({
  385. format: "json",
  386. turn: (messageID) => [
  387. ...(promotedBeforeFailure ? [prompted(messageID)] : []),
  388. executionFailed("selection unavailable"),
  389. ],
  390. messages: (messageID) =>
  391. promotedBeforeFailure ? [{ id: messageID, type: "user", text: "hello", time: { created: 1 } }] : [],
  392. wait: () => Promise.resolve(),
  393. terminalDelay: 10,
  394. })
  395. expect(output.exitCode).toBe(1)
  396. expect(output.stdout).toContain("selection unavailable")
  397. }
  398. })
  399. test("cancels session and global form blockers and exits on pre-promotion interrupt", async () => {
  400. const sdk = await run({
  401. pendingForms: [form("frm_pending", "ses_1"), form("frm_pending_global", "global")],
  402. // No prompted event: the execution settles interrupted before promotion,
  403. // which must not leave the consume loop waiting forever.
  404. turn: () => [formCreated(form("frm_live", "global")), settled("interrupted")],
  405. })
  406. const globalOptions = {
  407. headers: {
  408. "x-opencode-directory": "%2Fwork%20tree",
  409. "x-opencode-workspace": "wrk_1",
  410. },
  411. }
  412. expect(sdk.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }, globalOptions)
  413. expect(sdk.form.cancel).toHaveBeenCalledWith({ sessionID: "ses_1", formID: "frm_pending" })
  414. expect(sdk.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_pending_global" }, globalOptions)
  415. expect(sdk.form.request.list).toHaveBeenCalledWith({
  416. location: { directory: "/work tree", workspace: "wrk_1" },
  417. })
  418. expect(sdk.question.list).not.toHaveBeenCalled()
  419. expect(sdk.question.reject).not.toHaveBeenCalled()
  420. })
  421. test("attach mode cancels only session-owned forms", async () => {
  422. const sdk = await run({
  423. attached: true,
  424. pendingForms: [form("frm_pending", "ses_1"), form("frm_pending_global", "global")],
  425. turn: (messageID) => [formCreated(form("frm_live", "global")), prompted(messageID), settled()],
  426. })
  427. expect(sdk.form.cancel).toHaveBeenCalledWith({ sessionID: "ses_1", formID: "frm_pending" })
  428. expect(sdk.form.request.list).not.toHaveBeenCalled()
  429. expect(sdk.form.cancel).not.toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }, expect.anything())
  430. expect(sdk.form.cancel).not.toHaveBeenCalledWith(
  431. { sessionID: "global", formID: "frm_pending_global" },
  432. expect.anything(),
  433. )
  434. })
  435. test("V1 JSON output flushes step_start before an unrelated step failure", async () => {
  436. const output = await capture({
  437. compatibility: "v1",
  438. format: "json",
  439. turn: (messageID) => [
  440. prompted(messageID),
  441. stepStarted(),
  442. stepFailed("Provider request failed"),
  443. executionFailed("Provider request failed"),
  444. ],
  445. })
  446. expect(
  447. output.stdout
  448. .split("\n")
  449. .filter(Boolean)
  450. .map((line) => JSON.parse(line)),
  451. ).toEqual([
  452. expect.objectContaining({ type: "step_start", part: expect.objectContaining({ type: "step-start" }) }),
  453. expect.objectContaining({
  454. type: "error",
  455. error: { type: "provider.transport", message: "Provider request failed" },
  456. }),
  457. ])
  458. expect(output.stderr).toBe("")
  459. const sdk = await run({ compatibility: "v1", turn: (messageID) => [prompted(messageID), settled()] })
  460. expect(sdk.session.wait).not.toHaveBeenCalled()
  461. expect(sdk.message.list).not.toHaveBeenCalled()
  462. })
  463. test("V1 default output flushes step_start before an unrelated execution failure", async () => {
  464. const output = await capture({
  465. compatibility: "v1",
  466. turn: (messageID) => [prompted(messageID), stepStarted(), executionFailed("Execution failed")],
  467. })
  468. expect(output.stdout).toBe("")
  469. expect(output.stderr).toContain("> build · test-model")
  470. expect(output.stderr).toContain("Error: \u001b[0mExecution failed")
  471. expect(output.stderr.indexOf("> build · test-model")).toBeLessThan(output.stderr.indexOf("Execution failed"))
  472. })
  473. test("V1 preserves terminal-finish failure suppression before content", async () => {
  474. const output = await capture({
  475. compatibility: "v1",
  476. format: "json",
  477. turn: (messageID) => [
  478. prompted(messageID),
  479. stepStarted(),
  480. stepFailed("Provider stream ended without a terminal finish event"),
  481. executionFailed("Provider stream ended without a terminal finish event"),
  482. ],
  483. })
  484. expect(output).toEqual({ stdout: "", stderr: "", exitCode: 0 })
  485. })
  486. test("renders a native terminal failure snapshot when live progress was missed", async () => {
  487. const rendered: SessionMessageAssistantTool[] = []
  488. const failed: SessionMessageAssistantTool[] = []
  489. await capture({
  490. turn: (inputID) => failedTool(inputID).filter((event) => event.type !== "session.tool.progress"),
  491. renderTool: (part) => {
  492. rendered.push(part)
  493. return Promise.resolve()
  494. },
  495. renderToolError: (part) => {
  496. failed.push(part)
  497. return Promise.resolve()
  498. },
  499. })
  500. expect(rendered).toMatchObject([
  501. {
  502. id: "call_failed_tool",
  503. state: {
  504. status: "completed",
  505. structured: { checkpoint: 1 },
  506. content: [{ type: "text", text: "partial output" }],
  507. },
  508. },
  509. ])
  510. expect(failed).toMatchObject([
  511. {
  512. id: "call_failed_tool",
  513. state: {
  514. status: "error",
  515. structured: { checkpoint: 1 },
  516. content: [{ type: "text", text: "partial output" }],
  517. error: { message: "tool failed" },
  518. },
  519. },
  520. ])
  521. })
  522. test("keeps failed tool partial output out of the explicit V1 JSON bridge shape", async () => {
  523. const output = await capture({ compatibility: "v1", format: "json", turn: failedTool })
  524. const events = output.stdout
  525. .split("\n")
  526. .filter(Boolean)
  527. .map((line) => JSON.parse(line))
  528. expect(events).toHaveLength(1)
  529. expect(events[0]).toMatchObject({
  530. type: "tool_use",
  531. part: {
  532. type: "tool",
  533. callID: "call_failed_tool",
  534. tool: "shell",
  535. state: {
  536. status: "error",
  537. input: { command: "printf partial && false" },
  538. error: "tool failed",
  539. },
  540. },
  541. })
  542. expect(events[0].part.state.output).toBeUndefined()
  543. expect(events[0].part.state.metadata.structured).toBeUndefined()
  544. expect(events[0].part.state.metadata.content).toBeUndefined()
  545. expect(output.stderr).toBe("")
  546. })
  547. })