prompt.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. import path from "path"
  2. import { describe, expect, test } from "bun:test"
  3. import { NamedError } from "@opencode-ai/shared/util/error"
  4. import { fileURLToPath } from "url"
  5. import { Effect, Layer } from "effect"
  6. import { Instance } from "../../src/project/instance"
  7. import { ModelID, ProviderID } from "../../src/provider/schema"
  8. import { Session } from "../../src/session"
  9. import { MessageV2 } from "../../src/session/message-v2"
  10. import { SessionPrompt } from "../../src/session/prompt"
  11. import { Log } from "../../src/util/log"
  12. import { tmpdir } from "../fixture/fixture"
  13. Log.init({ print: false })
  14. function run<A, E>(fx: Effect.Effect<A, E, SessionPrompt.Service | Session.Service>) {
  15. return Effect.runPromise(
  16. fx.pipe(Effect.scoped, Effect.provide(Layer.mergeAll(SessionPrompt.defaultLayer, Session.defaultLayer))),
  17. )
  18. }
  19. function defer<T>() {
  20. let resolve!: (value: T | PromiseLike<T>) => void
  21. const promise = new Promise<T>((done) => {
  22. resolve = done
  23. })
  24. return { promise, resolve }
  25. }
  26. function chat(text: string) {
  27. const payload =
  28. [
  29. `data: ${JSON.stringify({
  30. id: "chatcmpl-1",
  31. object: "chat.completion.chunk",
  32. choices: [{ delta: { role: "assistant" } }],
  33. })}`,
  34. `data: ${JSON.stringify({
  35. id: "chatcmpl-1",
  36. object: "chat.completion.chunk",
  37. choices: [{ delta: { content: text } }],
  38. })}`,
  39. `data: ${JSON.stringify({
  40. id: "chatcmpl-1",
  41. object: "chat.completion.chunk",
  42. choices: [{ delta: {}, finish_reason: "stop" }],
  43. })}`,
  44. "data: [DONE]",
  45. ].join("\n\n") + "\n\n"
  46. const encoder = new TextEncoder()
  47. return new ReadableStream<Uint8Array>({
  48. start(ctrl) {
  49. ctrl.enqueue(encoder.encode(payload))
  50. ctrl.close()
  51. },
  52. })
  53. }
  54. function hanging(ready: () => void) {
  55. const encoder = new TextEncoder()
  56. let timer: ReturnType<typeof setTimeout> | undefined
  57. const first = `data: ${JSON.stringify({
  58. id: "chatcmpl-1",
  59. object: "chat.completion.chunk",
  60. choices: [{ delta: { role: "assistant" } }],
  61. })}\n\n`
  62. const rest =
  63. [
  64. `data: ${JSON.stringify({
  65. id: "chatcmpl-1",
  66. object: "chat.completion.chunk",
  67. choices: [{ delta: { content: "late" } }],
  68. })}`,
  69. `data: ${JSON.stringify({
  70. id: "chatcmpl-1",
  71. object: "chat.completion.chunk",
  72. choices: [{ delta: {}, finish_reason: "stop" }],
  73. })}`,
  74. "data: [DONE]",
  75. ].join("\n\n") + "\n\n"
  76. return new ReadableStream<Uint8Array>({
  77. start(ctrl) {
  78. ctrl.enqueue(encoder.encode(first))
  79. ready()
  80. timer = setTimeout(() => {
  81. ctrl.enqueue(encoder.encode(rest))
  82. ctrl.close()
  83. }, 10000)
  84. },
  85. cancel() {
  86. if (timer) clearTimeout(timer)
  87. },
  88. })
  89. }
  90. describe("session.prompt missing file", () => {
  91. test("does not fail the prompt when a file part is missing", async () => {
  92. await using tmp = await tmpdir({
  93. git: true,
  94. config: {
  95. agent: {
  96. build: {
  97. model: "openai/gpt-5.2",
  98. },
  99. },
  100. },
  101. })
  102. await Instance.provide({
  103. directory: tmp.path,
  104. fn: () =>
  105. run(
  106. Effect.gen(function* () {
  107. const prompt = yield* SessionPrompt.Service
  108. const sessions = yield* Session.Service
  109. const session = yield* sessions.create({})
  110. const missing = path.join(tmp.path, "does-not-exist.ts")
  111. const msg = yield* prompt.prompt({
  112. sessionID: session.id,
  113. agent: "build",
  114. noReply: true,
  115. parts: [
  116. { type: "text", text: "please review @does-not-exist.ts" },
  117. {
  118. type: "file",
  119. mime: "text/plain",
  120. url: `file://${missing}`,
  121. filename: "does-not-exist.ts",
  122. },
  123. ],
  124. })
  125. if (msg.info.role !== "user") throw new Error("expected user message")
  126. const hasFailure = msg.parts.some(
  127. (part) => part.type === "text" && part.synthetic && part.text.includes("Read tool failed to read"),
  128. )
  129. expect(hasFailure).toBe(true)
  130. yield* sessions.remove(session.id)
  131. }),
  132. ),
  133. })
  134. })
  135. test("keeps stored part order stable when file resolution is async", async () => {
  136. await using tmp = await tmpdir({
  137. git: true,
  138. config: {
  139. agent: {
  140. build: {
  141. model: "openai/gpt-5.2",
  142. },
  143. },
  144. },
  145. })
  146. await Instance.provide({
  147. directory: tmp.path,
  148. fn: () =>
  149. run(
  150. Effect.gen(function* () {
  151. const prompt = yield* SessionPrompt.Service
  152. const sessions = yield* Session.Service
  153. const session = yield* sessions.create({})
  154. const missing = path.join(tmp.path, "still-missing.ts")
  155. const msg = yield* prompt.prompt({
  156. sessionID: session.id,
  157. agent: "build",
  158. noReply: true,
  159. parts: [
  160. {
  161. type: "file",
  162. mime: "text/plain",
  163. url: `file://${missing}`,
  164. filename: "still-missing.ts",
  165. },
  166. { type: "text", text: "after-file" },
  167. ],
  168. })
  169. if (msg.info.role !== "user") throw new Error("expected user message")
  170. const stored = MessageV2.get({
  171. sessionID: session.id,
  172. messageID: msg.info.id,
  173. })
  174. const text = stored.parts.filter((part) => part.type === "text").map((part) => part.text)
  175. expect(text[0]?.startsWith("Called the Read tool with the following input:")).toBe(true)
  176. expect(text[1]?.includes("Read tool failed to read")).toBe(true)
  177. expect(text[2]).toBe("after-file")
  178. yield* sessions.remove(session.id)
  179. }),
  180. ),
  181. })
  182. })
  183. })
  184. describe("session.prompt special characters", () => {
  185. test("handles filenames with # character", async () => {
  186. await using tmp = await tmpdir({
  187. git: true,
  188. init: async (dir) => {
  189. await Bun.write(path.join(dir, "file#name.txt"), "special content\n")
  190. },
  191. })
  192. await Instance.provide({
  193. directory: tmp.path,
  194. fn: () =>
  195. run(
  196. Effect.gen(function* () {
  197. const prompt = yield* SessionPrompt.Service
  198. const sessions = yield* Session.Service
  199. const session = yield* sessions.create({})
  200. const template = "Read @file#name.txt"
  201. const parts = yield* prompt.resolvePromptParts(template)
  202. const fileParts = parts.filter((part) => part.type === "file")
  203. expect(fileParts.length).toBe(1)
  204. expect(fileParts[0].filename).toBe("file#name.txt")
  205. expect(fileParts[0].url).toContain("%23")
  206. const decodedPath = fileURLToPath(fileParts[0].url)
  207. expect(decodedPath).toBe(path.join(tmp.path, "file#name.txt"))
  208. const message = yield* prompt.prompt({
  209. sessionID: session.id,
  210. parts,
  211. noReply: true,
  212. })
  213. const stored = MessageV2.get({ sessionID: session.id, messageID: message.info.id })
  214. const textParts = stored.parts.filter((part) => part.type === "text")
  215. const hasContent = textParts.some((part) => part.text.includes("special content"))
  216. expect(hasContent).toBe(true)
  217. yield* sessions.remove(session.id)
  218. }),
  219. ),
  220. })
  221. })
  222. })
  223. describe("session.prompt regression", () => {
  224. test("does not loop empty assistant turns for a simple reply", async () => {
  225. let calls = 0
  226. const server = Bun.serve({
  227. port: 0,
  228. fetch(req) {
  229. const url = new URL(req.url)
  230. if (!url.pathname.endsWith("/chat/completions")) {
  231. return new Response("not found", { status: 404 })
  232. }
  233. calls++
  234. return new Response(chat("packages/opencode/src/session/processor.ts"), {
  235. status: 200,
  236. headers: { "Content-Type": "text/event-stream" },
  237. })
  238. },
  239. })
  240. try {
  241. await using tmp = await tmpdir({
  242. git: true,
  243. init: async (dir) => {
  244. await Bun.write(
  245. path.join(dir, "opencode.json"),
  246. JSON.stringify({
  247. $schema: "https://opencode.ai/config.json",
  248. enabled_providers: ["alibaba"],
  249. provider: {
  250. alibaba: {
  251. options: {
  252. apiKey: "test-key",
  253. baseURL: `${server.url.origin}/v1`,
  254. },
  255. },
  256. },
  257. agent: {
  258. build: {
  259. model: "alibaba/qwen-plus",
  260. },
  261. },
  262. }),
  263. )
  264. },
  265. })
  266. await Instance.provide({
  267. directory: tmp.path,
  268. fn: () =>
  269. run(
  270. Effect.gen(function* () {
  271. const prompt = yield* SessionPrompt.Service
  272. const sessions = yield* Session.Service
  273. const session = yield* sessions.create({ title: "Prompt regression" })
  274. const result = yield* prompt.prompt({
  275. sessionID: session.id,
  276. agent: "build",
  277. parts: [{ type: "text", text: "Where is SessionProcessor?" }],
  278. })
  279. expect(result.info.role).toBe("assistant")
  280. expect(result.parts.some((part) => part.type === "text" && part.text.includes("processor.ts"))).toBe(true)
  281. const msgs = yield* sessions.messages({ sessionID: session.id })
  282. expect(msgs.filter((msg) => msg.info.role === "assistant")).toHaveLength(1)
  283. expect(calls).toBe(1)
  284. }),
  285. ),
  286. })
  287. } finally {
  288. server.stop(true)
  289. }
  290. })
  291. test("records aborted errors when prompt is cancelled mid-stream", async () => {
  292. const ready = defer<void>()
  293. const server = Bun.serve({
  294. port: 0,
  295. fetch(req) {
  296. const url = new URL(req.url)
  297. if (!url.pathname.endsWith("/chat/completions")) {
  298. return new Response("not found", { status: 404 })
  299. }
  300. return new Response(
  301. hanging(() => ready.resolve()),
  302. {
  303. status: 200,
  304. headers: { "Content-Type": "text/event-stream" },
  305. },
  306. )
  307. },
  308. })
  309. try {
  310. await using tmp = await tmpdir({
  311. git: true,
  312. init: async (dir) => {
  313. await Bun.write(
  314. path.join(dir, "opencode.json"),
  315. JSON.stringify({
  316. $schema: "https://opencode.ai/config.json",
  317. enabled_providers: ["alibaba"],
  318. provider: {
  319. alibaba: {
  320. options: {
  321. apiKey: "test-key",
  322. baseURL: `${server.url.origin}/v1`,
  323. },
  324. },
  325. },
  326. agent: {
  327. build: {
  328. model: "alibaba/qwen-plus",
  329. },
  330. },
  331. }),
  332. )
  333. },
  334. })
  335. await Instance.provide({
  336. directory: tmp.path,
  337. fn: () =>
  338. run(
  339. Effect.gen(function* () {
  340. const prompt = yield* SessionPrompt.Service
  341. const sessions = yield* Session.Service
  342. const session = yield* sessions.create({ title: "Prompt cancel regression" })
  343. const task = Effect.runPromise(
  344. prompt.prompt({
  345. sessionID: session.id,
  346. agent: "build",
  347. parts: [{ type: "text", text: "Cancel me" }],
  348. }),
  349. )
  350. yield* Effect.promise(() => ready.promise)
  351. yield* prompt.cancel(session.id)
  352. const result = yield* Effect.promise(() =>
  353. Promise.race([
  354. task,
  355. new Promise<never>((_, reject) =>
  356. setTimeout(() => reject(new Error("timed out waiting for cancel")), 1000),
  357. ),
  358. ]),
  359. )
  360. expect(result.info.role).toBe("assistant")
  361. if (result.info.role === "assistant") {
  362. expect(result.info.error?.name).toBe("MessageAbortedError")
  363. }
  364. const msgs = yield* sessions.messages({ sessionID: session.id })
  365. const last = msgs.findLast((msg) => msg.info.role === "assistant")
  366. expect(last?.info.role).toBe("assistant")
  367. if (last?.info.role === "assistant") {
  368. expect(last.info.error?.name).toBe("MessageAbortedError")
  369. }
  370. }),
  371. ),
  372. })
  373. } finally {
  374. server.stop(true)
  375. }
  376. })
  377. })
  378. describe("session.prompt agent variant", () => {
  379. test("applies agent variant only when using agent model", async () => {
  380. const prev = process.env.OPENAI_API_KEY
  381. process.env.OPENAI_API_KEY = "test-openai-key"
  382. try {
  383. await using tmp = await tmpdir({
  384. git: true,
  385. config: {
  386. agent: {
  387. build: {
  388. model: "openai/gpt-5.2",
  389. variant: "xhigh",
  390. },
  391. },
  392. },
  393. })
  394. await Instance.provide({
  395. directory: tmp.path,
  396. fn: () =>
  397. run(
  398. Effect.gen(function* () {
  399. const prompt = yield* SessionPrompt.Service
  400. const sessions = yield* Session.Service
  401. const session = yield* sessions.create({})
  402. const other = yield* prompt.prompt({
  403. sessionID: session.id,
  404. agent: "build",
  405. model: { providerID: ProviderID.make("opencode"), modelID: ModelID.make("kimi-k2.5-free") },
  406. noReply: true,
  407. parts: [{ type: "text", text: "hello" }],
  408. })
  409. if (other.info.role !== "user") throw new Error("expected user message")
  410. expect(other.info.model.variant).toBeUndefined()
  411. const match = yield* prompt.prompt({
  412. sessionID: session.id,
  413. agent: "build",
  414. noReply: true,
  415. parts: [{ type: "text", text: "hello again" }],
  416. })
  417. if (match.info.role !== "user") throw new Error("expected user message")
  418. expect(match.info.model).toEqual({
  419. providerID: ProviderID.make("openai"),
  420. modelID: ModelID.make("gpt-5.2"),
  421. variant: "xhigh",
  422. })
  423. expect(match.info.model.variant).toBe("xhigh")
  424. const override = yield* prompt.prompt({
  425. sessionID: session.id,
  426. agent: "build",
  427. noReply: true,
  428. variant: "high",
  429. parts: [{ type: "text", text: "hello third" }],
  430. })
  431. if (override.info.role !== "user") throw new Error("expected user message")
  432. expect(override.info.model.variant).toBe("high")
  433. yield* sessions.remove(session.id)
  434. }),
  435. ),
  436. })
  437. } finally {
  438. if (prev === undefined) delete process.env.OPENAI_API_KEY
  439. else process.env.OPENAI_API_KEY = prev
  440. }
  441. })
  442. })
  443. describe("session.agent-resolution", () => {
  444. test("unknown agent throws typed error", async () => {
  445. await using tmp = await tmpdir({ git: true })
  446. await Instance.provide({
  447. directory: tmp.path,
  448. fn: () =>
  449. run(
  450. Effect.gen(function* () {
  451. const prompt = yield* SessionPrompt.Service
  452. const sessions = yield* Session.Service
  453. const session = yield* sessions.create({})
  454. const err = yield* Effect.promise(() =>
  455. Effect.runPromise(
  456. prompt.prompt({
  457. sessionID: session.id,
  458. agent: "nonexistent-agent-xyz",
  459. noReply: true,
  460. parts: [{ type: "text", text: "hello" }],
  461. }),
  462. ).then(
  463. () => undefined,
  464. (e) => e,
  465. ),
  466. )
  467. expect(err).toBeDefined()
  468. expect(err).not.toBeInstanceOf(TypeError)
  469. expect(NamedError.Unknown.isInstance(err)).toBe(true)
  470. if (NamedError.Unknown.isInstance(err)) {
  471. expect(err.data.message).toContain('Agent not found: "nonexistent-agent-xyz"')
  472. }
  473. }),
  474. ),
  475. })
  476. }, 30000)
  477. test("unknown agent error includes available agent names", async () => {
  478. await using tmp = await tmpdir({ git: true })
  479. await Instance.provide({
  480. directory: tmp.path,
  481. fn: () =>
  482. run(
  483. Effect.gen(function* () {
  484. const prompt = yield* SessionPrompt.Service
  485. const sessions = yield* Session.Service
  486. const session = yield* sessions.create({})
  487. const err = yield* Effect.promise(() =>
  488. Effect.runPromise(
  489. prompt.prompt({
  490. sessionID: session.id,
  491. agent: "nonexistent-agent-xyz",
  492. noReply: true,
  493. parts: [{ type: "text", text: "hello" }],
  494. }),
  495. ).then(
  496. () => undefined,
  497. (e) => e,
  498. ),
  499. )
  500. expect(NamedError.Unknown.isInstance(err)).toBe(true)
  501. if (NamedError.Unknown.isInstance(err)) {
  502. expect(err.data.message).toContain("build")
  503. }
  504. }),
  505. ),
  506. })
  507. }, 30000)
  508. test("unknown command throws typed error with available names", async () => {
  509. await using tmp = await tmpdir({ git: true })
  510. await Instance.provide({
  511. directory: tmp.path,
  512. fn: () =>
  513. run(
  514. Effect.gen(function* () {
  515. const prompt = yield* SessionPrompt.Service
  516. const sessions = yield* Session.Service
  517. const session = yield* sessions.create({})
  518. const err = yield* Effect.promise(() =>
  519. Effect.runPromise(
  520. prompt.command({
  521. sessionID: session.id,
  522. command: "nonexistent-command-xyz",
  523. arguments: "",
  524. }),
  525. ).then(
  526. () => undefined,
  527. (e) => e,
  528. ),
  529. )
  530. expect(err).toBeDefined()
  531. expect(err).not.toBeInstanceOf(TypeError)
  532. expect(NamedError.Unknown.isInstance(err)).toBe(true)
  533. if (NamedError.Unknown.isInstance(err)) {
  534. expect(err.data.message).toContain('Command not found: "nonexistent-command-xyz"')
  535. expect(err.data.message).toContain("init")
  536. }
  537. }),
  538. ),
  539. })
  540. }, 30000)
  541. })