tui-runtime-adapter.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. import { describe, expect, it, vi } from "vitest";
  2. import { TuiRuntimeAdapter } from "../../src/runtime/adapter.js";
  3. describe("TuiRuntimeAdapter process-local facades", () => {
  4. it("projects active and recent terminal Runtime background work for the current Session", async () => {
  5. const listBackgroundTasks = vi.fn(
  6. async (input: { statuses?: readonly string[] }) =>
  7. input.statuses?.includes("succeeded")
  8. ? [
  9. {
  10. taskId: "bg-failed",
  11. kind: "bash" as const,
  12. status: "failed" as const,
  13. ownerSessionId: "session-1",
  14. description: "build docs",
  15. metadata: { command: "pnpm build\necho complete" },
  16. createdAt: 100,
  17. updatedAt: 300,
  18. startedAt: 120,
  19. endedAt: 280,
  20. lastError: { message: "exit code 1" },
  21. },
  22. {
  23. taskId: "bg-delivered",
  24. kind: "bash" as const,
  25. status: "succeeded" as const,
  26. ownerSessionId: "session-1",
  27. description: "build docs successfully",
  28. createdAt: 90,
  29. updatedAt: 250,
  30. startedAt: 100,
  31. endedAt: 220,
  32. deliveredAt: 250,
  33. },
  34. ]
  35. : [
  36. {
  37. taskId: "bg-running",
  38. kind: "bash" as const,
  39. status: "running" as const,
  40. ownerSessionId: "session-1",
  41. description: "pnpm test",
  42. createdAt: 100,
  43. updatedAt: 200,
  44. startedAt: 110,
  45. },
  46. ],
  47. );
  48. const adapter = new TuiRuntimeAdapter({ listBackgroundTasks } as never);
  49. await expect(adapter.listBackgroundTasks("session-1")).resolves.toEqual([
  50. {
  51. taskId: "bg-failed",
  52. kind: "bash",
  53. status: "failed",
  54. ownerSessionId: "session-1",
  55. description: "build docs",
  56. command: "pnpm build\necho complete",
  57. createdAtMs: 100,
  58. updatedAtMs: 300,
  59. startedAtMs: 120,
  60. endedAtMs: 280,
  61. lastError: "exit code 1",
  62. },
  63. {
  64. taskId: "bg-delivered",
  65. kind: "bash",
  66. status: "succeeded",
  67. ownerSessionId: "session-1",
  68. description: "build docs successfully",
  69. createdAtMs: 90,
  70. updatedAtMs: 250,
  71. startedAtMs: 100,
  72. endedAtMs: 220,
  73. deliveredAtMs: 250,
  74. },
  75. {
  76. taskId: "bg-running",
  77. kind: "bash",
  78. status: "running",
  79. ownerSessionId: "session-1",
  80. description: "pnpm test",
  81. createdAtMs: 100,
  82. updatedAtMs: 200,
  83. startedAtMs: 110,
  84. },
  85. ]);
  86. expect(listBackgroundTasks).toHaveBeenNthCalledWith(1, {
  87. ownerSessionId: "session-1",
  88. statuses: ["queued", "running", "stopping"],
  89. kinds: ["bash", "workflow", "custom"],
  90. limit: 100,
  91. });
  92. expect(listBackgroundTasks).toHaveBeenNthCalledWith(2, {
  93. ownerSessionId: "session-1",
  94. statuses: ["succeeded", "failed", "canceled", "lost"],
  95. kinds: ["bash", "workflow", "custom"],
  96. limit: 100,
  97. });
  98. });
  99. it.each([undefined, null, 42, { source: "echo hidden" }])(
  100. "does not treat non-string command metadata as Bash source: %s",
  101. async (command) => {
  102. const adapter = new TuiRuntimeAdapter({
  103. listBackgroundTasks: vi.fn(async () => [
  104. {
  105. taskId: "legacy",
  106. kind: "bash",
  107. status: "succeeded",
  108. ownerSessionId: "root",
  109. description: "legacy command...",
  110. createdAt: 1,
  111. updatedAt: 2,
  112. metadata: { command },
  113. },
  114. ]),
  115. } as never);
  116. expect(await adapter.listBackgroundTasks("root")).toEqual([
  117. expect.objectContaining({ description: "legacy command..." }),
  118. ]);
  119. expect((await adapter.listBackgroundTasks("root"))[0]).not.toHaveProperty(
  120. "command",
  121. );
  122. },
  123. );
  124. it("reattaches a foreground Turn without asking resumeSession to drain the Queue", async () => {
  125. const cliService = {
  126. resumeSession: vi.fn(async () => ({
  127. ok: true as const,
  128. source: [{ dataJson: "[DONE]" }],
  129. })),
  130. };
  131. const adapter = new TuiRuntimeAdapter(cliService as never);
  132. const events = [];
  133. for await (const event of adapter.watchSessionTurn(
  134. "session-1",
  135. "turn-queued",
  136. new AbortController().signal,
  137. { afterMsgId: "message-1" },
  138. )) {
  139. events.push(event);
  140. }
  141. expect(cliService.resumeSession).toHaveBeenCalledWith(
  142. {
  143. id: "session-1",
  144. afterMsgId: "message-1",
  145. },
  146. { signal: expect.any(AbortSignal) },
  147. );
  148. expect(events).toEqual([{ type: "done", turnId: "turn-queued" }]);
  149. });
  150. it("uses the process-local Goal facade with TUI attachment snapshots", async () => {
  151. const goal = {
  152. goalId: "goal-1",
  153. sessionId: "session-1",
  154. objective: "Ship TUI Goal support",
  155. status: "active" as const,
  156. createdAt: 10,
  157. updatedAt: 20,
  158. tokensUsed: 0,
  159. turnsUsed: 0,
  160. timeUsedSeconds: 0,
  161. tokenBudget: null,
  162. statusReason: null,
  163. hasKickoffAttachments: true,
  164. };
  165. const cliService = {
  166. isGoalEnabled: vi.fn(() => true),
  167. getGoal: vi.fn(async () => goal),
  168. createGoal: vi.fn(async () => goal),
  169. patchGoal: vi.fn(async () => ({ ...goal, status: "paused" as const })),
  170. clearGoal: vi.fn(async () => true),
  171. };
  172. const adapter = new TuiRuntimeAdapter(cliService as never);
  173. expect(adapter.isGoalEnabled()).toBe(true);
  174. await expect(adapter.getGoal("session-1")).resolves.toBe(goal);
  175. await expect(
  176. adapter.createGoal({
  177. sessionId: "session-1",
  178. objective: goal.objective,
  179. tokenBudget: 50_000,
  180. attachments: [
  181. {
  182. type: "file",
  183. filePath: "/repo/spec.md",
  184. fileName: "spec.md",
  185. mimeType: "text/markdown",
  186. sizeBytes: 100,
  187. },
  188. ],
  189. }),
  190. ).resolves.toBe(goal);
  191. await expect(
  192. adapter.patchGoal("session-1", {
  193. status: "paused",
  194. tokenBudget: null,
  195. }),
  196. ).resolves.toMatchObject({ status: "paused" });
  197. await expect(adapter.clearGoal("session-1")).resolves.toBe(true);
  198. expect(cliService.createGoal).toHaveBeenCalledWith({
  199. sessionId: "session-1",
  200. objective: goal.objective,
  201. tokenBudget: 50_000,
  202. kickoffAttachments: [
  203. {
  204. type: "file",
  205. filePath: "/repo/spec.md",
  206. fileName: "spec.md",
  207. mimeType: "text/markdown",
  208. },
  209. ],
  210. });
  211. expect(cliService.patchGoal).toHaveBeenCalledWith("session-1", {
  212. status: "paused",
  213. tokenBudget: null,
  214. });
  215. });
  216. it("uses process-local questionnaire and permission facades", async () => {
  217. const cliService = {
  218. getPendingQuestionnaire: vi.fn(async () => ({
  219. request: {
  220. id: "question-1",
  221. schemaVersion: 2,
  222. presentation: {
  223. replaceComposer: true,
  224. showProgress: true,
  225. allowBackNavigation: true,
  226. },
  227. steps: [],
  228. },
  229. })),
  230. replyQuestionnaire: vi.fn(async () => ({ ok: true })),
  231. dismissQuestionnaire: vi.fn(async () => ({ ok: true })),
  232. listPendingPermissions: vi.fn(async () => ({
  233. requests: [
  234. {
  235. requestId: "permission-1",
  236. sessionId: "session-1",
  237. agentName: "mavis",
  238. toolName: "bash",
  239. ruleContents: ["pnpm test"],
  240. reason: "Run the relevant tests",
  241. allowAlwaysSupported: true,
  242. createdAt: 1,
  243. },
  244. ],
  245. })),
  246. replyPermission: vi.fn(async () => ({ success: true })),
  247. };
  248. const adapter = new TuiRuntimeAdapter(cliService as never);
  249. await expect(
  250. adapter.getPendingQuestionnaire("mavis", "session-1"),
  251. ).resolves.toMatchObject({
  252. id: "question-1",
  253. });
  254. await expect(
  255. adapter.replyQuestionnaire("mavis", "question-1", []),
  256. ).resolves.toBe(true);
  257. await expect(
  258. adapter.dismissQuestionnaire("mavis", "question-1"),
  259. ).resolves.toBe(true);
  260. await expect(adapter.listPendingPermissions()).resolves.toEqual([
  261. expect.objectContaining({ requestId: "permission-1" }),
  262. ]);
  263. await expect(
  264. adapter.replyPermission("mavis", "permission-1", "allowAlways"),
  265. ).resolves.toBe(true);
  266. expect(cliService.getPendingQuestionnaire).toHaveBeenCalledWith({
  267. name: "mavis",
  268. sessionId: "session-1",
  269. });
  270. expect(cliService.replyQuestionnaire).toHaveBeenCalledWith(
  271. expect.objectContaining({
  272. name: "mavis",
  273. requestId: "question-1",
  274. answers: [],
  275. submittedAt: expect.any(Number),
  276. }),
  277. );
  278. expect(cliService.dismissQuestionnaire).toHaveBeenCalledWith({
  279. name: "mavis",
  280. requestId: "question-1",
  281. });
  282. expect(cliService.replyPermission).toHaveBeenCalledWith({
  283. name: "mavis",
  284. requestId: "permission-1",
  285. reply: 1,
  286. });
  287. });
  288. it("uses process-local product capability facades", async () => {
  289. const cliService = {
  290. listRuntimeSkills: vi.fn(async () => ({
  291. skills: [{ name: "docs", enabled: true }],
  292. refreshedAt: 123,
  293. })),
  294. listMcpServers: vi.fn(async () => ({
  295. servers: [{ name: "browser", enabled: true }],
  296. })),
  297. getSessionUsage: vi.fn(async () => ({
  298. summary: { totalTokens: 120, turns: 1 },
  299. rows: [],
  300. })),
  301. requestCompaction: vi.fn(async () => ({
  302. success: true,
  303. sessionId: "session-1",
  304. compactionId: "compact-1",
  305. })),
  306. };
  307. const adapter = new TuiRuntimeAdapter(cliService as never, {
  308. workspaceDir: "/workspace",
  309. });
  310. await expect(adapter.getSessionUsage("session-1")).resolves.toMatchObject({
  311. summary: { totalTokens: 120 },
  312. });
  313. await expect(
  314. adapter.requestCompaction("session-1", "mavis", "keep evidence"),
  315. ).resolves.toMatchObject({ success: true, compactionId: "compact-1" });
  316. await expect(adapter.listSkills("mavis", "docs")).resolves.toMatchObject({
  317. skills: [expect.objectContaining({ name: "docs" })],
  318. hasMore: false,
  319. });
  320. await expect(adapter.listMcpServers("browser")).resolves.toEqual([
  321. expect.objectContaining({ name: "browser" }),
  322. ]);
  323. expect(cliService.getSessionUsage).toHaveBeenCalledWith({
  324. id: "session-1",
  325. });
  326. expect(cliService.requestCompaction).toHaveBeenCalledWith({
  327. name: "mavis",
  328. id: "session-1",
  329. reason: "ui_request",
  330. customInstructions: "keep evidence",
  331. });
  332. expect(cliService.listRuntimeSkills).toHaveBeenCalledWith({
  333. agentName: "mavis",
  334. workspaceDir: "/workspace",
  335. includePluginSkills: true,
  336. });
  337. expect(cliService.listMcpServers).toHaveBeenCalledWith({
  338. keyword: "browser",
  339. });
  340. });
  341. it("projects Runtime-owned Plugin catalogs without exposing generated DTOs", async () => {
  342. const cliService = {
  343. listInstalledPlugins: vi.fn(async () => ({
  344. plugins: [
  345. {
  346. name: "docs",
  347. displayName: "Documents",
  348. source: 1,
  349. enabled: true,
  350. capabilities: { appCount: 0, mcpServerCount: 0, skillCount: 1 },
  351. },
  352. {
  353. name: "notes",
  354. source: 2,
  355. enabled: false,
  356. capabilities: { appCount: 0, mcpServerCount: 1, skillCount: 0 },
  357. },
  358. {
  359. name: "unknown",
  360. source: 999,
  361. enabled: true,
  362. capabilities: { appCount: 0, mcpServerCount: 0, skillCount: 0 },
  363. },
  364. ],
  365. hasMore: false,
  366. })),
  367. listMarketplacePlugins: vi.fn(async () => ({
  368. plugins: [
  369. {
  370. name: "calendar",
  371. displayName: "Calendar",
  372. installExists: false,
  373. enabled: false,
  374. capabilities: { appCount: 1, mcpServerCount: 0, skillCount: 0 },
  375. },
  376. ],
  377. hasMore: false,
  378. })),
  379. };
  380. const adapter = new TuiRuntimeAdapter(cliService as never);
  381. await expect(
  382. adapter.listInstalledPlugins({ marketplace: "official" }),
  383. ).resolves.toEqual([
  384. {
  385. pluginId: "docs@official",
  386. name: "docs",
  387. displayName: "Documents",
  388. marketplace: "official",
  389. installed: true,
  390. enabled: true,
  391. capabilities: { appCount: 0, mcpServerCount: 0, skillCount: 1 },
  392. },
  393. ]);
  394. await expect(
  395. adapter.listMarketplacePlugins({ marketplace: "local" }),
  396. ).resolves.toEqual([
  397. {
  398. pluginId: "calendar@local",
  399. name: "calendar",
  400. displayName: "Calendar",
  401. marketplace: "local",
  402. installed: false,
  403. enabled: false,
  404. capabilities: { appCount: 1, mcpServerCount: 0, skillCount: 0 },
  405. },
  406. ]);
  407. expect(cliService.listInstalledPlugins).toHaveBeenCalledWith({
  408. limit: 200,
  409. });
  410. expect(cliService.listMarketplacePlugins).toHaveBeenCalledWith({
  411. source: 2,
  412. limit: 200,
  413. });
  414. });
  415. it("routes Plugin mutations and refresh through CliService", async () => {
  416. const cliService = {
  417. installPlugin: vi.fn(async () => ({
  418. installExists: true,
  419. enabled: true,
  420. })),
  421. disablePlugin: vi.fn(async () => ({
  422. installExists: true,
  423. enabled: false,
  424. })),
  425. uninstallPlugin: vi.fn(async () => ({
  426. installExists: false,
  427. enabled: false,
  428. })),
  429. refreshPlugins: vi.fn(async () => undefined),
  430. };
  431. const adapter = new TuiRuntimeAdapter(cliService as never);
  432. await expect(
  433. adapter.mutatePlugin({
  434. action: "install",
  435. plugin: { name: "docs", marketplace: "official" },
  436. }),
  437. ).resolves.toEqual({ installed: true, enabled: true });
  438. await expect(
  439. adapter.mutatePlugin({
  440. action: "disable",
  441. plugin: { name: "notes", marketplace: "local" },
  442. }),
  443. ).resolves.toEqual({ installed: true, enabled: false });
  444. await expect(
  445. adapter.mutatePlugin({
  446. action: "remove",
  447. plugin: { name: "notes", marketplace: "local" },
  448. }),
  449. ).resolves.toEqual({ installed: false, enabled: false });
  450. await expect(adapter.refreshPlugins()).resolves.toBeUndefined();
  451. expect(cliService.installPlugin).toHaveBeenCalledWith({
  452. pluginName: "docs",
  453. source: 1,
  454. });
  455. expect(cliService.disablePlugin).toHaveBeenCalledWith({
  456. pluginName: "notes",
  457. source: 2,
  458. });
  459. expect(cliService.uninstallPlugin).toHaveBeenCalledWith({
  460. pluginName: "notes",
  461. source: 2,
  462. });
  463. expect(cliService.refreshPlugins).toHaveBeenCalledOnce();
  464. });
  465. it("reads Runtime events through CliService", async () => {
  466. const cliService = {
  467. watchEvents: vi.fn(async function* watchEvents() {
  468. yield {
  469. type: "permission.ask",
  470. timestamp: 123,
  471. source: "local-runtime",
  472. payload: { requestId: "permission-1", sessionId: "session-1" },
  473. };
  474. }),
  475. };
  476. const adapter = new TuiRuntimeAdapter(cliService as never);
  477. const events = [];
  478. for await (const event of adapter.watchEvents(
  479. new AbortController().signal,
  480. )) {
  481. events.push(event);
  482. }
  483. expect(events).toEqual([
  484. {
  485. type: "permission.ask",
  486. timestampMs: 123,
  487. source: "local-runtime",
  488. sessionId: "session-1",
  489. request: { requestId: "permission-1", sessionId: "session-1" },
  490. },
  491. ]);
  492. expect(cliService.watchEvents).toHaveBeenCalledOnce();
  493. });
  494. it("exposes the session-mutation Runtime facade through the adapter", async () => {
  495. const cliService = {
  496. listSessionInputSummaries: vi
  497. .fn()
  498. .mockResolvedValueOnce({
  499. summaries: [
  500. {
  501. userInput: { msgId: "msg-user-v1-2", timestamp: 1700000000456 },
  502. },
  503. ],
  504. hasMore: true,
  505. nextCursor: "cursor-older",
  506. })
  507. .mockResolvedValueOnce({
  508. summaries: [
  509. {
  510. userInput: {
  511. msgId: "msg-user-v1-1",
  512. contentHead: "first line",
  513. timestamp: 1700000000000,
  514. },
  515. assistantResponse: {
  516. msgId: "msg-assistant-v1-1",
  517. timestamp: 1700000000123,
  518. },
  519. fileChangeCount: 2,
  520. },
  521. ],
  522. hasMore: false,
  523. }),
  524. getSessionForkOptions: vi.fn(async () => ({
  525. canFork: true,
  526. suggestedTitle: "Fork of: hi",
  527. nextForkOrdinal: 2,
  528. sourceTitle: "hi",
  529. worktreeVisible: true,
  530. worktreeEligible: true,
  531. })),
  532. forkSession: vi.fn(async () => ({
  533. session: {
  534. sessionId: "child-1",
  535. agentName: "mavis",
  536. title: "Fork of: hi",
  537. workspaceDir: "/repo",
  538. },
  539. forkOriginMessageId: "msg-assistant-v1-1",
  540. sourceDisplayMessageId: "msg-assistant-v1-1",
  541. displayRevision: "rev-1",
  542. historyRevision: "hist-1",
  543. })),
  544. getSessionRewindPreview: vi.fn(async () => ({
  545. turns: [
  546. {
  547. turnId: "turn-1",
  548. files: [
  549. { filePath: "/repo/a.ts", action: "modify", skipped: false },
  550. ],
  551. },
  552. ],
  553. })),
  554. rewindSession: vi.fn(async () => ({
  555. rewound: true,
  556. displayRevision: "disp-1",
  557. historyRevision: "hist-1",
  558. deletedMessageIds: ["msg-user-v1-1"],
  559. turnDiffRewind: {
  560. status: "partial",
  561. revertedTurnIds: ["turn-1"],
  562. },
  563. })),
  564. editSessionMessage: vi.fn(async () => ({
  565. rewound: true,
  566. turnId: "turn-edit-1",
  567. userMessageId: "msg-user-v1-edited",
  568. displayRevision: "disp-2",
  569. historyRevision: "hist-2",
  570. deletedMessageIds: ["msg-user-v1-1", "msg-assistant-v1-1"],
  571. })),
  572. };
  573. const adapter = new TuiRuntimeAdapter(cliService as never);
  574. await expect(
  575. adapter.listSessionInputSummaries("session-1", { limit: 50 }),
  576. ).resolves.toEqual([
  577. {
  578. userMessageId: "msg-user-v1-1",
  579. assistantMessageId: "msg-assistant-v1-1",
  580. contentHead: "first line",
  581. timestamp: 1700000000000,
  582. fileChangeCount: 2,
  583. },
  584. {
  585. userMessageId: "msg-user-v1-2",
  586. timestamp: 1700000000456,
  587. fileChangeCount: 0,
  588. },
  589. ]);
  590. expect(cliService.listSessionInputSummaries).toHaveBeenNthCalledWith(1, {
  591. id: "session-1",
  592. limit: 50,
  593. });
  594. expect(cliService.listSessionInputSummaries).toHaveBeenNthCalledWith(2, {
  595. id: "session-1",
  596. limit: 50,
  597. before: "cursor-older",
  598. });
  599. await expect(
  600. adapter.getSessionForkOptions("session-1", "msg-1"),
  601. ).resolves.toEqual({
  602. canFork: true,
  603. suggestedTitle: "Fork of: hi",
  604. nextForkOrdinal: 2,
  605. sourceTitle: "hi",
  606. worktreeVisible: true,
  607. worktreeEligible: true,
  608. });
  609. expect(cliService.getSessionForkOptions).toHaveBeenCalledWith({
  610. id: "session-1",
  611. assistantMessageId: "msg-1",
  612. });
  613. await expect(
  614. adapter.forkSession({
  615. sessionId: "session-1",
  616. assistantMessageId: "msg-assistant-v1-1",
  617. clientRequestId: "fork-req-1",
  618. title: "Fork of: hi",
  619. useSuggestedTitle: false,
  620. createIsolatedWorktree: true,
  621. }),
  622. ).resolves.toEqual({
  623. session: {
  624. sessionId: "child-1",
  625. agentName: "mavis",
  626. title: "Fork of: hi",
  627. workspaceDir: "/repo",
  628. },
  629. forkOriginMessageId: "msg-assistant-v1-1",
  630. sourceDisplayMessageId: "msg-assistant-v1-1",
  631. displayRevision: "rev-1",
  632. historyRevision: "hist-1",
  633. });
  634. expect(cliService.forkSession).toHaveBeenCalledWith({
  635. id: "session-1",
  636. assistantMessageId: "msg-assistant-v1-1",
  637. clientRequestId: "fork-req-1",
  638. title: "Fork of: hi",
  639. useSuggestedTitle: false,
  640. createIsolatedWorktree: true,
  641. });
  642. await expect(
  643. adapter.getSessionRewindPreview({
  644. sessionId: "session-1",
  645. userMessageId: "msg-user-v1-1",
  646. }),
  647. ).resolves.toEqual({
  648. turns: [
  649. {
  650. turnId: "turn-1",
  651. files: [{ filePath: "/repo/a.ts", action: "modify", skipped: false }],
  652. },
  653. ],
  654. });
  655. expect(cliService.getSessionRewindPreview).toHaveBeenCalledWith({
  656. id: "session-1",
  657. userMessageId: "msg-user-v1-1",
  658. });
  659. await expect(
  660. adapter.rewindSession({
  661. sessionId: "session-1",
  662. userMessageId: "msg-user-v1-1",
  663. clientRequestId: "rewind-1",
  664. rewindTurnDiff: true,
  665. }),
  666. ).resolves.toEqual({
  667. rewound: true,
  668. displayRevision: "disp-1",
  669. historyRevision: "hist-1",
  670. deletedMessageIds: ["msg-user-v1-1"],
  671. turnDiffRewind: {
  672. status: "partial",
  673. revertedTurnIds: ["turn-1"],
  674. },
  675. });
  676. expect(cliService.rewindSession).toHaveBeenCalledWith({
  677. id: "session-1",
  678. userMessageId: "msg-user-v1-1",
  679. clientRequestId: "rewind-1",
  680. rewindTurnDiff: true,
  681. });
  682. await expect(
  683. adapter.editSessionMessage({
  684. sessionId: "session-1",
  685. userMessageId: "msg-user-v1-1",
  686. clientRequestId: "edit-1",
  687. content: "updated prompt",
  688. attachments: [
  689. {
  690. type: "file",
  691. filePath: "/repo/spec.md",
  692. fileName: "spec.md",
  693. mimeType: "text/markdown",
  694. sizeBytes: 42,
  695. },
  696. ],
  697. rewindTurnDiff: true,
  698. }),
  699. ).resolves.toEqual({
  700. rewound: true,
  701. turnId: "turn-edit-1",
  702. userMessageId: "msg-user-v1-edited",
  703. displayRevision: "disp-2",
  704. historyRevision: "hist-2",
  705. deletedMessageIds: ["msg-user-v1-1", "msg-assistant-v1-1"],
  706. });
  707. expect(cliService.editSessionMessage).toHaveBeenCalledWith({
  708. id: "session-1",
  709. userMessageId: "msg-user-v1-1",
  710. clientRequestId: "edit-1",
  711. content: "updated prompt",
  712. attachments: [
  713. {
  714. meta: {
  715. attachmentType: "file",
  716. fileName: "spec.md",
  717. mimeType: "text/markdown",
  718. sizeBytes: 42,
  719. },
  720. local: { filePath: "/repo/spec.md" },
  721. },
  722. ],
  723. rewindTurnDiff: true,
  724. });
  725. });
  726. it("fails closed when the Runtime omits the forked Session", async () => {
  727. const adapter = new TuiRuntimeAdapter({
  728. forkSession: vi.fn(async () => ({})),
  729. } as never);
  730. await expect(
  731. adapter.forkSession({
  732. sessionId: "session-1",
  733. assistantMessageId: "msg-assistant-v1-1",
  734. clientRequestId: "fork-req-1",
  735. }),
  736. ).rejects.toThrow("Runtime did not return the created Session.");
  737. });
  738. it.each([false, true] as const)(
  739. "forwards rewindTurnDiff=%s without generating an operation id",
  740. async (rewindTurnDiff) => {
  741. const cliService = {
  742. rewindSession: vi.fn(async (input: { rewindTurnDiff?: boolean }) => ({
  743. rewound: true,
  744. turnDiffRewind: { status: "rewound" },
  745. rewindTurnDiff: input.rewindTurnDiff,
  746. })),
  747. };
  748. const adapter = new TuiRuntimeAdapter(cliService as never);
  749. const result = await adapter.rewindSession({
  750. sessionId: "session-1",
  751. userMessageId: "msg-user-v1-target",
  752. clientRequestId: "caller-supplied-op-id",
  753. ...(rewindTurnDiff ? { rewindTurnDiff: true } : {}),
  754. });
  755. expect(result.rewound).toBe(true);
  756. expect(cliService.rewindSession).toHaveBeenCalledWith({
  757. id: "session-1",
  758. userMessageId: "msg-user-v1-target",
  759. clientRequestId: "caller-supplied-op-id",
  760. ...(rewindTurnDiff ? { rewindTurnDiff: true } : {}),
  761. });
  762. },
  763. );
  764. });