v4-native-fork-edit-retry.test.ts 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  1. // L2:fork/edit/retry 命令组(M4 最后一组)。
  2. // 语义要点(08-phasing M4 完成定义的 L2 层):
  3. // - rowId→messageId 翻译是原生决策:翻译不到 reject(绝不静默兜底 latestCheckpoint);
  4. // - editUserQuery = core branch cut + 原生 prompt turn 重发新文本;
  5. // - retryTurn = 原文在 rewind **之前**解析(截断后 transcript 已无该消息)+ 截断 + 重发;
  6. // 原文解析不到只截断不重发;
  7. // - latest real user query running 时先 stop active turn,再 rewind + rerun;
  8. // - 历史 user query 直接拒绝,且不打断当前 active turn;
  9. // - retry 只允许全时间线最后一条 assistant 回复,历史回复直接拒绝;
  10. // - forkAssistant 经过 stable resolver 后走 conversation-only fork,result 带 forkedSessionId。
  11. import { describe, expect, it, vi } from "vitest";
  12. import { RewindStrategy, SessionEventType } from "@zcode/contracts";
  13. import type { CommandEnvelope } from "@zcode/shared/zcode-protocol-v4";
  14. import { V4CommandExecutor } from "../src/zcode-protocol-v4/commands/executor.js";
  15. import {
  16. V4EditTargetNotLatestError,
  17. V4RetryTargetNotLatestError,
  18. V4RowTranslationError,
  19. } from "../src/zcode-protocol-v4/commands/handlers/fork-edit-retry.js";
  20. import type {
  21. V4CommandCoreHost,
  22. V4SessionRecordView,
  23. } from "../src/zcode-protocol-v4/commands/types.js";
  24. function makeApp(overrides: Record<string, unknown> = {}) {
  25. const runtimeOverrides =
  26. typeof overrides.runtime === "object" && overrides.runtime !== null ? overrides.runtime : {};
  27. return {
  28. sessionId: "s1",
  29. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  30. options?.onTurnStartedObserved?.({
  31. id: "event-started",
  32. type: SessionEventType.TurnStarted,
  33. payload: { messageId: "msg-event-started" },
  34. });
  35. return {
  36. completion: Promise.resolve({}),
  37. kind: "started_turn",
  38. turnId: "turn-1",
  39. };
  40. }),
  41. submitPrompt: vi.fn().mockResolvedValue({}),
  42. steerTurn: vi.fn().mockResolvedValue({}),
  43. readTarget: vi.fn().mockResolvedValue(null),
  44. updateTargetStatus: vi.fn().mockResolvedValue(null),
  45. ...overrides,
  46. runtime: {
  47. rewindConversationToMessage: vi.fn().mockResolvedValue({
  48. strategy: RewindStrategy.ActiveChain,
  49. }),
  50. ...runtimeOverrides,
  51. },
  52. };
  53. }
  54. function makeRecord(
  55. overrides: Partial<V4SessionRecordView> & { app?: ReturnType<typeof makeApp> } = {},
  56. ): V4SessionRecordView {
  57. return {
  58. app: (overrides.app ?? makeApp()) as unknown as V4SessionRecordView["app"],
  59. traceContext: { traceId: "trace-1", sessionId: "s1" } as never,
  60. workspace: { workspacePath: "/w" },
  61. persistence: "immediate",
  62. ...overrides,
  63. } as V4SessionRecordView;
  64. }
  65. function makeHost(
  66. record: V4SessionRecordView,
  67. overrides: Partial<V4CommandCoreHost> = {},
  68. ): V4CommandCoreHost {
  69. const host: V4CommandCoreHost = {
  70. getRecord: (id) => (id === "s1" ? record : undefined),
  71. isLatestEditableUserRow: () => true,
  72. isLatestRetryAssistantRow: () => true,
  73. waitForProjectionEventCommit: async () => {},
  74. ...overrides,
  75. };
  76. host.resolveRowActionTarget ??= (_sessionId, target, action) => {
  77. if (action === "editUserQuery") {
  78. if (host.isLatestEditableUserRow?.("s1", target.rowId) !== true) {
  79. return {
  80. ok: false,
  81. status: "rejected",
  82. reasonCode: "guard.actionUnavailable",
  83. };
  84. }
  85. const transcriptMessageId = host.getTurnRewindAnchor?.("s1", target.rowId);
  86. if (!transcriptMessageId) {
  87. return {
  88. ok: false,
  89. status: "rejected",
  90. reasonCode: "guard.actionUnavailable",
  91. };
  92. }
  93. return {
  94. ok: true,
  95. action,
  96. row: {} as never,
  97. editTarget: {
  98. entityId: target.entityId,
  99. productTurnId: `turn-${target.rowId}`,
  100. transcriptMessageId,
  101. coveredByStableCompact: false,
  102. intent: { kind: "sendText", text: "原始问题" },
  103. },
  104. };
  105. }
  106. if (action === "retryTurn") {
  107. const messageId = host.getMessageIdForRow?.("s1", target.rowId);
  108. if (host.isLatestRetryAssistantRow?.("s1", target.rowId) !== true || !messageId) {
  109. return {
  110. ok: false,
  111. status: "rejected",
  112. reasonCode: "guard.actionUnavailable",
  113. };
  114. }
  115. return {
  116. ok: true,
  117. action,
  118. row: {} as never,
  119. messageId,
  120. editTarget: {
  121. entityId: `user-${target.entityId}`,
  122. productTurnId: `turn-${target.rowId}`,
  123. transcriptMessageId: `user-${messageId}`,
  124. coveredByStableCompact: false,
  125. intent: { kind: "sendText", text: "原始问题" },
  126. },
  127. };
  128. }
  129. if (action === "applyFileRewind") {
  130. return {
  131. ok: true,
  132. action,
  133. row: {
  134. turnId: host.getTurnIdForRow?.("s1", target.rowId) ?? `turn-${target.rowId}`,
  135. } as never,
  136. messageIds: host.getMessageIdsForTurnRow?.("s1", target.rowId) ?? [],
  137. };
  138. }
  139. return {
  140. ok: true,
  141. action,
  142. row: {} as never,
  143. messageId: `msg-${target.rowId}`,
  144. };
  145. };
  146. return host;
  147. }
  148. function envelope(type: string, payload: unknown): CommandEnvelope {
  149. return {
  150. type,
  151. payload,
  152. sessionId: "s1",
  153. commandId: "cmd-1",
  154. baseRevision: 0,
  155. baseLogEpoch: "epoch-1",
  156. clientId: "client-new",
  157. } as unknown as CommandEnvelope;
  158. }
  159. async function settle() {
  160. // 原生 prompt turn 是 void 起跑的微任务链,flush 两轮保证 finally 执行完。
  161. await new Promise((r) => setTimeout(r, 0));
  162. await new Promise((r) => setTimeout(r, 0));
  163. }
  164. /**
  165. * 加速轮的协议原形:Selection 指向隐藏的加速卡内建 Provider(端点/能力都由 Provider Config
  166. * 提供),只有卡 JWT 与卡 ID 作为本次执行的动态鉴权随 modelExecution 下发。
  167. */
  168. const HIGHSPEED_MODEL_SELECTION = {
  169. providerId: "account:bigmodel-highspeed-card",
  170. modelId: "GLM-5.3",
  171. };
  172. const HIGHSPEED_MODEL_EXECUTION = {
  173. selectionScope: "execution" as const,
  174. requestAuth: {
  175. apiKey: "card-edit-jwt",
  176. headers: { Authorization: "Bearer card-edit-jwt", "X-Highspeed-Card-ID": "card-edit" },
  177. },
  178. selectionFallback: {
  179. providerId: "account:bigmodel-highspeed-card",
  180. rules: [
  181. { reason: "highspeed_card_expired" as const, providerErrorCode: "3402" },
  182. { reason: "highspeed_request_failed" as const },
  183. ],
  184. },
  185. };
  186. const originalEditAttachments = [
  187. {
  188. ref: "/work/first.txt",
  189. fileName: "first.txt",
  190. mime: "text/plain",
  191. bytes: 12,
  192. },
  193. {
  194. ref: "/work/second.txt",
  195. fileName: "second.txt",
  196. mime: "text/plain",
  197. bytes: 24,
  198. },
  199. ];
  200. function attachmentEditTarget() {
  201. return {
  202. ok: true as const,
  203. action: "editUserQuery" as const,
  204. row: { rowId: 7, turnId: "turn-7" } as never,
  205. editTarget: {
  206. entityId: "entity-7",
  207. productTurnId: "turn-7",
  208. transcriptMessageId: "msg-user",
  209. coveredByStableCompact: false,
  210. intent: {
  211. kind: "sendText" as const,
  212. text: "原始问题",
  213. attachments: originalEditAttachments,
  214. },
  215. },
  216. };
  217. }
  218. describe("v4 原生 editUserQuery", () => {
  219. it("正路径:rewind 截断(同 turn assistant 锚点)后原生 turn 重发新文本", async () => {
  220. const app = makeApp();
  221. const record = makeRecord({ app });
  222. const info = vi.fn();
  223. const host = makeHost(record, {
  224. getTurnRewindAnchor: (sessionId, rowId) =>
  225. sessionId === "s1" && rowId === 7 ? "msg-a" : null,
  226. logger: { info },
  227. });
  228. await new V4CommandExecutor(host).execute(
  229. envelope("editUserQuery", {
  230. target: { rowId: 7, entityId: "entity-7" },
  231. newText: "改过的问题",
  232. }),
  233. );
  234. await settle();
  235. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  236. expect.objectContaining({ targetMessageId: "msg-a" }),
  237. );
  238. // 重发走原生 prompt turn(sendInput),inputId=commandId 权威锚点。
  239. expect(app.sendInput).toHaveBeenCalledWith(
  240. { text: "改过的问题" },
  241. expect.objectContaining({ inputId: "cmd-1" }),
  242. );
  243. // 顺序:先截断后重发。
  244. expect(app.runtime.rewindConversationToMessage.mock.invocationCallOrder[0]).toBeLessThan(
  245. app.sendInput.mock.invocationCallOrder[0],
  246. );
  247. expect(info).toHaveBeenCalledWith(
  248. "v4 editUserQuery completed",
  249. expect.objectContaining({
  250. attachmentCount: 0,
  251. clientId: "client-new",
  252. commandId: "cmd-1",
  253. event: "conversation.command.edit_user_query.completed",
  254. intentKind: "sendText",
  255. sessionId: "s1",
  256. status: "completed",
  257. targetEntityId: "entity-7",
  258. targetRowId: 7,
  259. traceId: "trace-1",
  260. workspaceMode: "preserve",
  261. }),
  262. );
  263. const editLogFields = info.mock.calls.find(
  264. ([message]) => message === "v4 editUserQuery completed",
  265. )?.[1];
  266. expect(editLogFields).not.toHaveProperty("newText");
  267. expect(editLogFields).not.toHaveProperty("text");
  268. });
  269. it("编辑重发会应用本次新准备的 Highspeed Selection 与执行材料", async () => {
  270. const app = makeApp();
  271. const record = makeRecord({ app });
  272. const highspeedMeta = {
  273. schemaVersion: 1 as const,
  274. cardId: "card-edit",
  275. taskId: "s1",
  276. provider: "bigmodel",
  277. model: "GLM-5.3",
  278. issuedAt: 1,
  279. expiresAt: Date.now() + 60_000,
  280. };
  281. const host = makeHost(record, { getTurnRewindAnchor: () => "msg-user" });
  282. await new V4CommandExecutor(host).execute(
  283. envelope("editUserQuery", {
  284. target: { rowId: 7, entityId: "entity-7" },
  285. newText: "改过的问题",
  286. highspeedMeta,
  287. modelSelection: HIGHSPEED_MODEL_SELECTION,
  288. modelExecution: HIGHSPEED_MODEL_EXECUTION,
  289. }),
  290. );
  291. await settle();
  292. // Selection 可投影(要进 intent 让 transcript 复原时知道这轮走了加速 Provider)。
  293. expect(app.sendInput).toHaveBeenCalledWith(
  294. { text: "改过的问题" },
  295. expect.objectContaining({
  296. intent: expect.objectContaining({
  297. highspeed: highspeedMeta,
  298. modelSelection: HIGHSPEED_MODEL_SELECTION,
  299. }),
  300. }),
  301. );
  302. const options = app.sendInput.mock.calls[0]?.[1];
  303. expect(options.modelExecution.selectionScope).toBe("execution");
  304. expect(options.modelExecution.selectionFallback).toEqual(
  305. HIGHSPEED_MODEL_EXECUTION.selectionFallback,
  306. );
  307. // 卡 JWT 只能作为本轮执行依赖惰性解析,绝不能进入可持久化的 intent。
  308. await expect(
  309. options.modelExecution.requestDependencies.requestAuth.source.resolve(),
  310. ).resolves.toEqual(HIGHSPEED_MODEL_EXECUTION.requestAuth);
  311. expect(options.intent).not.toHaveProperty("modelExecution");
  312. });
  313. it("卡已过期的编辑重发退回会话常驻 Selection,不保留无鉴权的加速 Selection", async () => {
  314. // CR-01 回归:被编辑的那轮是 Highspeed 轮,canonical intent 里留着 account:*-highspeed-card;
  315. // 本次没有有效新卡(已过期),旧实现只是不传 modelExecution 却沿用该 Selection,Core 会以
  316. // ModelRequestAuthMissing 失败,且该 Selection 被固定进新 intent,污染后续普通发送。
  317. const setModel = vi.fn();
  318. const app = makeApp({ getModel: () => "builtin:bigmodel-coding-plan/GLM-5.3", setModel });
  319. const record = makeRecord({ app });
  320. const host = makeHost(record, {
  321. resolveRowActionTarget: () => ({
  322. ok: true,
  323. action: "editUserQuery",
  324. row: {} as never,
  325. editTarget: {
  326. entityId: "entity-7",
  327. productTurnId: "turn-7",
  328. transcriptMessageId: "msg-user",
  329. coveredByStableCompact: false,
  330. intent: {
  331. kind: "sendText",
  332. text: "原始问题",
  333. modelSelection: HIGHSPEED_MODEL_SELECTION,
  334. },
  335. },
  336. }),
  337. });
  338. await new V4CommandExecutor(host).execute(
  339. envelope("editUserQuery", {
  340. target: { rowId: 7, entityId: "entity-7" },
  341. newText: "改过的问题",
  342. highspeedMeta: {
  343. schemaVersion: 1 as const,
  344. cardId: "card-edit",
  345. taskId: "s1",
  346. provider: "bigmodel",
  347. model: "GLM-5.3",
  348. issuedAt: 1,
  349. expiresAt: Date.now() - 1,
  350. },
  351. modelSelection: HIGHSPEED_MODEL_SELECTION,
  352. modelExecution: HIGHSPEED_MODEL_EXECUTION,
  353. }),
  354. );
  355. await settle();
  356. const options = app.sendInput.mock.calls[0]?.[1];
  357. expect(options.intent.modelSelection).toEqual({
  358. providerId: "builtin:bigmodel-coding-plan",
  359. modelId: "GLM-5.3",
  360. });
  361. expect(options.intent).not.toHaveProperty("highspeed");
  362. expect(options).not.toHaveProperty("modelExecution");
  363. // 只改本轮 intent,不改 session 常驻模型。
  364. expect(setModel).not.toHaveBeenCalled();
  365. });
  366. it("Highspeed admission 遇到收口竞态时保留编辑文本并进入队列", async () => {
  367. const app = makeApp({
  368. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  369. if (options?.requireQueue) {
  370. return { kind: "queued", queueItemId: "queue-edited" };
  371. }
  372. return { kind: "rejected", reason: "turn_not_steerable" };
  373. }),
  374. });
  375. const record = makeRecord({ app });
  376. const highspeedMeta = {
  377. schemaVersion: 1 as const,
  378. cardId: "card-edit",
  379. taskId: "s1",
  380. provider: "bigmodel",
  381. model: "GLM-5.3",
  382. issuedAt: 1,
  383. expiresAt: Date.now() + 60_000,
  384. };
  385. const host = makeHost(record, {
  386. getTurnRewindAnchor: () => "msg-user",
  387. retainQueuedTurnExecution: vi.fn(),
  388. deleteQueuedTurnExecution: vi.fn(),
  389. });
  390. await new V4CommandExecutor(host).execute(
  391. envelope("editUserQuery", {
  392. target: { rowId: 7, entityId: "entity-7" },
  393. newText: "竞态下的新问题",
  394. highspeedMeta,
  395. modelSelection: HIGHSPEED_MODEL_SELECTION,
  396. modelExecution: HIGHSPEED_MODEL_EXECUTION,
  397. }),
  398. );
  399. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  400. expect.objectContaining({ targetMessageId: "msg-user" }),
  401. );
  402. expect(app.sendInput).toHaveBeenNthCalledWith(
  403. 1,
  404. { text: "竞态下的新问题" },
  405. expect.objectContaining({
  406. modelExecution: expect.objectContaining({ selectionScope: "execution" }),
  407. }),
  408. );
  409. // 入队路径不能把凭据交给 turn(此时还没有 turn),只投影 Selection + 卡元数据。
  410. expect(app.sendInput).toHaveBeenNthCalledWith(
  411. 2,
  412. { text: "竞态下的新问题" },
  413. expect.objectContaining({
  414. requireQueue: true,
  415. intent: expect.objectContaining({
  416. highspeed: highspeedMeta,
  417. modelSelection: HIGHSPEED_MODEL_SELECTION,
  418. }),
  419. }),
  420. );
  421. expect(app.sendInput.mock.calls[1]?.[1]).not.toHaveProperty("modelExecution");
  422. // 凭据改由宿主按 commandId 暂存在内存,提升队列项时再冻结成执行上下文。
  423. expect(host.retainQueuedTurnExecution).toHaveBeenCalledWith(
  424. "s1",
  425. "cmd-1",
  426. HIGHSPEED_MODEL_EXECUTION,
  427. );
  428. });
  429. it("attachments 缺省时稳定保留 canonical 原 refs", async () => {
  430. const app = makeApp();
  431. const record = makeRecord({ app });
  432. const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
  433. await new V4CommandExecutor(host).execute(
  434. envelope("editUserQuery", {
  435. target: { rowId: 7, entityId: "entity-7" },
  436. newText: "只改正文",
  437. }),
  438. );
  439. await settle();
  440. expect(app.sendInput).toHaveBeenCalledWith(
  441. {
  442. text: "只改正文",
  443. attachments: [
  444. expect.objectContaining({ path: "/work/first.txt" }),
  445. expect.objectContaining({ path: "/work/second.txt" }),
  446. ],
  447. },
  448. expect.objectContaining({
  449. intent: expect.objectContaining({ attachmentRefs: originalEditAttachments }),
  450. }),
  451. );
  452. });
  453. it("仅附件 edit 使用新数组替换原 refs,并保持剩余顺序", async () => {
  454. const app = makeApp();
  455. const record = makeRecord({ app });
  456. const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
  457. await new V4CommandExecutor(host).execute(
  458. envelope("editUserQuery", {
  459. target: { rowId: 7, entityId: "entity-7" },
  460. newText: "",
  461. attachments: [originalEditAttachments[1]],
  462. }),
  463. );
  464. await settle();
  465. expect(app.sendInput).toHaveBeenCalledWith(
  466. {
  467. text: "",
  468. attachments: [expect.objectContaining({ path: "/work/second.txt" })],
  469. },
  470. expect.objectContaining({
  471. intent: expect.objectContaining({ attachmentRefs: [originalEditAttachments[1]] }),
  472. }),
  473. );
  474. });
  475. it("显式 [] 清空原 refs,而不是恢复 canonical attachments", async () => {
  476. const app = makeApp();
  477. const record = makeRecord({ app });
  478. const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
  479. await new V4CommandExecutor(host).execute(
  480. envelope("editUserQuery", {
  481. target: { rowId: 7, entityId: "entity-7" },
  482. newText: "保留正文",
  483. attachments: [],
  484. }),
  485. );
  486. await settle();
  487. expect(app.sendInput).toHaveBeenCalledWith(
  488. { text: "保留正文" },
  489. expect.objectContaining({
  490. intent: expect.objectContaining({ attachmentRefs: [] }),
  491. }),
  492. );
  493. });
  494. it("正文与显式附件数组都为空时在 branch cut 前拒绝", async () => {
  495. const app = makeApp();
  496. const record = makeRecord({ app });
  497. const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
  498. await expect(
  499. new V4CommandExecutor(host).execute(
  500. envelope("editUserQuery", {
  501. target: { rowId: 7, entityId: "entity-7" },
  502. newText: " ",
  503. attachments: [],
  504. }),
  505. ),
  506. ).rejects.toMatchObject({ reasonCode: "proto.invalidPayload" });
  507. expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
  508. expect(app.sendInput).not.toHaveBeenCalled();
  509. });
  510. it("workspaceMode=rewind:安全文件先恢复,再提交 branch cut 并原 session 重发", async () => {
  511. const previewWorkspaceFileRewind = vi.fn().mockResolvedValue({
  512. canApply: true,
  513. safeFiles: [{ action: "restore", operationCount: 1, path: "/w/a.ts", toolNames: ["Edit"] }],
  514. unsafeFiles: [],
  515. ignoredFiles: [],
  516. });
  517. const applyWorkspaceFileRewind = vi.fn().mockImplementation(async (options) => {
  518. await options.commitAfterApply();
  519. return {
  520. applied: true,
  521. response: "ok",
  522. preview: await previewWorkspaceFileRewind(),
  523. };
  524. });
  525. const app = makeApp({ runtime: { previewWorkspaceFileRewind, applyWorkspaceFileRewind } });
  526. const record = makeRecord({ app });
  527. const host = makeHost(record, {
  528. getMessageIdsForTurnRow: () => ["msg-user", "msg-assistant"],
  529. resolveRowActionTarget: () => ({
  530. ok: true,
  531. action: "editUserQuery",
  532. row: { rowId: 7, turnId: "turn-7" } as never,
  533. editTarget: {
  534. entityId: "entity-7",
  535. productTurnId: "turn-7",
  536. transcriptMessageId: "msg-user",
  537. coveredByStableCompact: true,
  538. intent: { kind: "sendText", text: "old" },
  539. },
  540. }),
  541. });
  542. const result = await new V4CommandExecutor(host).execute(
  543. envelope("editUserQuery", {
  544. target: { rowId: 7, entityId: "entity-7" },
  545. newText: "edited",
  546. workspaceMode: "rewind",
  547. }),
  548. );
  549. expect(previewWorkspaceFileRewind).toHaveBeenCalledWith(
  550. expect.objectContaining({ targetMessageIds: ["msg-user", "msg-assistant"] }),
  551. );
  552. expect(applyWorkspaceFileRewind).toHaveBeenCalledWith(
  553. expect.objectContaining({ commitAfterApply: expect.any(Function) }),
  554. );
  555. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  556. expect.objectContaining({ targetMessageId: "msg-user" }),
  557. );
  558. expect(result).toEqual({ type: "editUserQuery", disposition: "rewind", sessionId: "s1" });
  559. });
  560. it("workspaceMode=rewind:unsafe/ignored 结构化 blocked,不裁对话也不发模型请求", async () => {
  561. const preview = {
  562. canApply: false,
  563. safeFiles: [],
  564. unsafeFiles: [
  565. {
  566. operationCount: 1,
  567. path: "/w/a.ts",
  568. reason: "external_modified",
  569. toolNames: ["Edit"],
  570. },
  571. ],
  572. ignoredFiles: [],
  573. } as const;
  574. const previewWorkspaceFileRewind = vi.fn().mockResolvedValue(preview);
  575. const applyWorkspaceFileRewind = vi.fn();
  576. const app = makeApp({ runtime: { previewWorkspaceFileRewind, applyWorkspaceFileRewind } });
  577. const record = makeRecord({ app });
  578. const cancelInputCommand = vi.fn().mockResolvedValue(undefined);
  579. const host = makeHost(record, {
  580. cancelInputCommand,
  581. resolveRowActionTarget: () => ({
  582. ok: true,
  583. action: "editUserQuery",
  584. row: { rowId: 7, turnId: "turn-7" } as never,
  585. editTarget: {
  586. entityId: "entity-7",
  587. productTurnId: "turn-7",
  588. transcriptMessageId: "msg-user",
  589. coveredByStableCompact: false,
  590. intent: { kind: "sendText", text: "old" },
  591. },
  592. }),
  593. });
  594. const result = await new V4CommandExecutor(host).execute(
  595. envelope("editUserQuery", {
  596. target: { rowId: 7, entityId: "entity-7" },
  597. newText: "edited",
  598. workspaceMode: "rewind",
  599. }),
  600. );
  601. expect(result).toEqual({
  602. type: "editUserQuery",
  603. disposition: "blocked",
  604. sessionId: "s1",
  605. reasonCode: "guard.workspaceRewindUnsafeFiles",
  606. preview,
  607. });
  608. expect(cancelInputCommand).toHaveBeenCalledWith(
  609. "s1",
  610. "queue_cmd-1",
  611. "guard.workspaceRewindUnsafeFiles",
  612. );
  613. expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
  614. expect(app.sendInput).not.toHaveBeenCalled();
  615. expect(applyWorkspaceFileRewind).not.toHaveBeenCalled();
  616. });
  617. it("翻译不到锚点:reject,不静默兜底", async () => {
  618. const record = makeRecord();
  619. const info = vi.fn();
  620. const host = makeHost(record, {
  621. getTurnRewindAnchor: () => null,
  622. logger: { info },
  623. resolveUserMessageIdForRow: async () => null,
  624. });
  625. await expect(
  626. new V4CommandExecutor(host).execute(
  627. envelope("editUserQuery", {
  628. target: { rowId: 99, entityId: "entity-99" },
  629. newText: "x",
  630. }),
  631. ),
  632. ).rejects.toThrow(V4EditTargetNotLatestError);
  633. expect(info).not.toHaveBeenCalledWith("v4 editUserQuery completed", expect.anything());
  634. });
  635. it("无 assistant anchor 时回查 user messageId 作为 rewind 锚点", async () => {
  636. const app = makeApp();
  637. const record = makeRecord({ app });
  638. const host = makeHost(record, {
  639. getTurnRewindAnchor: (_sessionId, rowId) => (rowId === 7 ? "msg-user-7" : null),
  640. });
  641. await new V4CommandExecutor(host).execute(
  642. envelope("editUserQuery", {
  643. target: { rowId: 7, entityId: "entity-7" },
  644. newText: "改过的问题",
  645. }),
  646. );
  647. await settle();
  648. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  649. expect.objectContaining({ targetMessageId: "msg-user-7" }),
  650. );
  651. expect(app.sendInput).toHaveBeenCalledWith(
  652. { text: "改过的问题" },
  653. expect.objectContaining({ inputId: "cmd-1" }),
  654. );
  655. });
  656. it("running latest query:abort → idle → rewind → rerun", async () => {
  657. const calls: string[] = [];
  658. const app = makeApp({
  659. runtime: {
  660. rewindConversationToMessage: vi.fn().mockImplementation(async () => {
  661. calls.push("rewind");
  662. return { strategy: RewindStrategy.ActiveChain };
  663. }),
  664. getActiveTurnInfo: vi
  665. .fn()
  666. .mockReturnValueOnce({ turnId: "turn-old" })
  667. .mockReturnValue(undefined),
  668. },
  669. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  670. calls.push("rerun");
  671. options?.onTurnStartedObserved?.({
  672. id: "event-started",
  673. type: SessionEventType.TurnStarted,
  674. payload: { messageId: "msg-event-started" },
  675. });
  676. return {};
  677. }),
  678. });
  679. const controller = new AbortController();
  680. controller.signal.addEventListener("abort", () => {
  681. calls.push("abort");
  682. setTimeout(() => {
  683. calls.push("idle");
  684. record.activeAbortController = undefined;
  685. }, 0);
  686. });
  687. const record = makeRecord({ app, activeAbortController: controller });
  688. const host = makeHost(record, {
  689. getTurnRewindAnchor: () => "msg-a",
  690. isLatestEditableUserRow: () => true,
  691. });
  692. await new V4CommandExecutor(host).execute(
  693. envelope("editUserQuery", {
  694. target: { rowId: 7, entityId: "entity-7" },
  695. newText: "改过的问题",
  696. }),
  697. );
  698. await settle();
  699. expect(calls).toEqual(["abort", "idle", "rewind", "rerun"]);
  700. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  701. expect.objectContaining({ targetMessageId: "msg-a" }),
  702. );
  703. });
  704. it("runtime-only active turn:没有 Bootstrap controller 也必须先 stop 再 rewind", async () => {
  705. const calls: string[] = [];
  706. const app = makeApp({
  707. runtime: {
  708. getActiveTurnInfo: vi
  709. .fn()
  710. .mockReturnValueOnce({ turnId: "turn-old" })
  711. .mockReturnValue(undefined),
  712. stopActiveForegroundExecution: vi.fn().mockImplementation(() => {
  713. calls.push("stop");
  714. return { kind: "stopped", foregroundExecutionId: "foreground-old" };
  715. }),
  716. rewindConversationToMessage: vi.fn().mockImplementation(async () => {
  717. calls.push("rewind");
  718. return { strategy: RewindStrategy.ActiveChain };
  719. }),
  720. },
  721. sendInput: vi.fn().mockImplementation(async () => {
  722. calls.push("rerun");
  723. return {};
  724. }),
  725. });
  726. const record = makeRecord({ app });
  727. const host = makeHost(record, { getTurnRewindAnchor: () => "msg-a" });
  728. await new V4CommandExecutor(host).execute(
  729. envelope("editUserQuery", {
  730. target: { rowId: 7, entityId: "entity-7" },
  731. newText: "runtime-only 编辑",
  732. }),
  733. );
  734. expect(calls).toEqual(["stop", "rewind", "rerun"]);
  735. expect(app.runtime.stopActiveForegroundExecution).toHaveBeenCalledWith(
  736. expect.objectContaining({ reason: "v4 editUserQuery preempts active turn" }),
  737. );
  738. });
  739. it("running 历史 user query:直接拒绝,且不 stop 当前 turn", async () => {
  740. const calls: string[] = [];
  741. const controller = new AbortController();
  742. controller.signal.addEventListener("abort", () => {
  743. calls.push("abort");
  744. });
  745. const record = makeRecord({ activeAbortController: controller });
  746. const host = makeHost(record, {
  747. getTurnRewindAnchor: () => "msg-a",
  748. isLatestEditableUserRow: () => false,
  749. });
  750. await expect(
  751. new V4CommandExecutor(host).execute(
  752. envelope("editUserQuery", {
  753. target: { rowId: 7, entityId: "entity-7" },
  754. newText: "x",
  755. }),
  756. ),
  757. ).rejects.toThrow(V4EditTargetNotLatestError);
  758. expect(calls).toEqual([]);
  759. expect(record.activeAbortController).toBe(controller);
  760. });
  761. });
  762. describe("v4 原生 retryTurn", () => {
  763. it("Task3:从 canonical cause 以新 commandId 重建完整 intent 与 provenance", async () => {
  764. const app = makeApp();
  765. const record = makeRecord({ app });
  766. const attachment = {
  767. ref: "/work/spec.md",
  768. fileName: "spec.md",
  769. mime: "text/markdown",
  770. bytes: 12,
  771. };
  772. const host = makeHost(record, {
  773. resolveRowActionTarget: () => ({
  774. ok: true,
  775. action: "retryTurn",
  776. row: {} as never,
  777. messageId: "msg-assistant",
  778. editTarget: {
  779. entityId: "msg-user",
  780. productTurnId: "turn-product",
  781. transcriptMessageId: "msg-user",
  782. coveredByStableCompact: false,
  783. intent: {
  784. kind: "sendText",
  785. text: "original canonical text",
  786. sourceCommandId: "cmd-original",
  787. clientId: "client-original",
  788. queueItemId: "queue-original",
  789. requestedDelivery: "guide",
  790. admittedDelivery: "queue",
  791. fallbackReasonCode: "guide.attachmentsUnsupported",
  792. modelSelection: {
  793. providerId: "original-provider",
  794. modelId: "original-model",
  795. options: { reasoningLevel: "high" },
  796. },
  797. mode: "edit",
  798. attachments: [attachment],
  799. },
  800. },
  801. }),
  802. });
  803. await new V4CommandExecutor(host).execute(
  804. envelope("retryTurn", {
  805. target: { rowId: 5, entityId: "msg-assistant" },
  806. }),
  807. );
  808. await settle();
  809. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  810. expect.objectContaining({ targetMessageId: "msg-assistant" }),
  811. );
  812. expect(app.sendInput).toHaveBeenCalledWith(
  813. expect.objectContaining({
  814. text: "original canonical text",
  815. attachments: [expect.objectContaining({ path: "/work/spec.md" })],
  816. }),
  817. expect.objectContaining({
  818. inputId: "cmd-1",
  819. intent: expect.objectContaining({
  820. sourceCommandId: "cmd-1",
  821. kind: "sendText",
  822. text: "original canonical text",
  823. requestedDelivery: "guide",
  824. admittedDelivery: "queue",
  825. fallbackReasonCode: "guide.attachmentsUnsupported",
  826. modelSelection: {
  827. providerId: "original-provider",
  828. modelId: "original-model",
  829. options: { reasoningLevel: "high" },
  830. },
  831. mode: "edit",
  832. provenance: {
  833. sourceCommandId: "cmd-original",
  834. queueItemId: "queue-original",
  835. clientId: "client-original",
  836. },
  837. }),
  838. }),
  839. );
  840. });
  841. it("retry Highspeed 轮时没有新执行材料,退回会话常驻 Selection 且不改 session 模型", async () => {
  842. // CR-01 回归:retry 从 canonical intent 复制历史 Selection;Highspeed 轮的 Selection 是
  843. // account:*-highspeed-card,本次 retry 没有任何执行材料,必须显式改写回会话常驻 Selection。
  844. const setModel = vi.fn();
  845. const app = makeApp({ getModel: () => "builtin:bigmodel-coding-plan/GLM-5.3", setModel });
  846. const record = makeRecord({ app });
  847. const host = makeHost(record, {
  848. resolveRowActionTarget: () => ({
  849. ok: true,
  850. action: "retryTurn",
  851. row: {} as never,
  852. messageId: "msg-assistant",
  853. editTarget: {
  854. entityId: "msg-user",
  855. productTurnId: "turn-product",
  856. transcriptMessageId: "msg-user",
  857. coveredByStableCompact: false,
  858. intent: {
  859. kind: "sendText",
  860. text: "accelerated prompt",
  861. sourceCommandId: "cmd-original",
  862. modelSelection: HIGHSPEED_MODEL_SELECTION,
  863. },
  864. },
  865. }),
  866. });
  867. await new V4CommandExecutor(host).execute(
  868. envelope("retryTurn", { target: { rowId: 5, entityId: "msg-assistant" } }),
  869. );
  870. await settle();
  871. const options = app.sendInput.mock.calls[0]?.[1];
  872. expect(options.intent.modelSelection).toEqual({
  873. providerId: "builtin:bigmodel-coding-plan",
  874. modelId: "GLM-5.3",
  875. });
  876. expect(options.intent).not.toHaveProperty("highspeed");
  877. expect(options).not.toHaveProperty("modelExecution");
  878. expect(setModel).not.toHaveBeenCalled();
  879. });
  880. it("retry-of-retry 保留最初 provenance,不被中间 retry 的 queue/client 覆盖", async () => {
  881. const app = makeApp();
  882. const record = makeRecord({ app });
  883. const host = makeHost(record, {
  884. resolveRowActionTarget: () => ({
  885. ok: true,
  886. action: "retryTurn",
  887. row: {} as never,
  888. messageId: "msg-retry-assistant",
  889. editTarget: {
  890. entityId: "msg-retry-user",
  891. productTurnId: "turn-retry",
  892. transcriptMessageId: "msg-retry-user",
  893. coveredByStableCompact: false,
  894. intent: {
  895. kind: "sendText",
  896. text: "retry canonical text",
  897. sourceCommandId: "cmd-middle-retry",
  898. queueItemId: "queue-middle-retry",
  899. clientId: "client-middle-retry",
  900. provenance: {
  901. sourceCommandId: "cmd-original",
  902. queueItemId: "queue-original",
  903. clientId: "client-original",
  904. },
  905. },
  906. },
  907. }),
  908. });
  909. await new V4CommandExecutor(host).execute(
  910. envelope("retryTurn", {
  911. target: { rowId: 8, entityId: "msg-retry-assistant" },
  912. }),
  913. );
  914. await settle();
  915. expect(app.sendInput).toHaveBeenCalledWith(
  916. expect.anything(),
  917. expect.objectContaining({
  918. intent: expect.objectContaining({
  919. sourceCommandId: "cmd-1",
  920. provenance: {
  921. sourceCommandId: "cmd-original",
  922. queueItemId: "queue-original",
  923. clientId: "client-original",
  924. },
  925. }),
  926. }),
  927. );
  928. });
  929. it("goal retry preserves sendGoalCommand kind", async () => {
  930. const app = makeApp({
  931. getMode: vi.fn().mockReturnValue("plan"),
  932. setTarget: vi.fn().mockResolvedValue({
  933. targetID: "g1",
  934. objective: "goal",
  935. status: "active",
  936. }),
  937. });
  938. const record = makeRecord({ app });
  939. const host = makeHost(record, {
  940. resolveRowActionTarget: () => ({
  941. ok: true,
  942. action: "retryTurn",
  943. row: {} as never,
  944. messageId: "msg-goal-assistant",
  945. editTarget: {
  946. entityId: "msg-goal-user",
  947. productTurnId: "turn-goal",
  948. transcriptMessageId: "msg-goal-user",
  949. coveredByStableCompact: false,
  950. intent: {
  951. kind: "sendGoalCommand",
  952. text: "goal",
  953. sourceCommandId: "cmd-goal-original",
  954. },
  955. },
  956. }),
  957. });
  958. await new V4CommandExecutor(host).execute(
  959. envelope("retryTurn", {
  960. target: { rowId: 6, entityId: "msg-goal-assistant" },
  961. }),
  962. );
  963. expect(app.setTarget).toHaveBeenCalledWith(
  964. expect.objectContaining({
  965. objective: "goal",
  966. intent: expect.objectContaining({
  967. kind: "sendGoalCommand",
  968. sourceCommandId: "cmd-1",
  969. }),
  970. }),
  971. );
  972. expect(app.sendInput).not.toHaveBeenCalled();
  973. });
  974. it("正路径:原文在 rewind 前解析 → 截断 → 重发原 prompt", async () => {
  975. const app = makeApp();
  976. const record = makeRecord({ app });
  977. const resolveOrder: string[] = [];
  978. const host = makeHost(record, {
  979. getMessageIdForRow: (_s, rowId) => (rowId === 5 ? "msg-b" : null),
  980. resolveTurnUserPrompt: async (_s, messageId) => {
  981. resolveOrder.push("resolve");
  982. return messageId === "msg-b" ? "原始问题" : null;
  983. },
  984. });
  985. app.runtime.rewindConversationToMessage.mockImplementation(async () => {
  986. resolveOrder.push("rewind");
  987. return { strategy: RewindStrategy.ActiveChain };
  988. });
  989. await new V4CommandExecutor(host).execute(
  990. envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
  991. );
  992. await settle();
  993. // canonical intent 已由 projection resolver 在截断前给出,不再回读 raw transcript 文本。
  994. expect(resolveOrder).toEqual(["rewind"]);
  995. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  996. expect.objectContaining({ targetMessageId: "msg-b" }),
  997. );
  998. expect(app.sendInput).toHaveBeenCalledWith(
  999. { text: "原始问题" },
  1000. expect.objectContaining({ inputId: "cmd-1" }),
  1001. );
  1002. });
  1003. it("canonical cause 不可解析:直接拒绝且不截断", async () => {
  1004. const app = makeApp();
  1005. const record = makeRecord({ app });
  1006. const host = makeHost(record, {
  1007. resolveRowActionTarget: () => ({
  1008. ok: false,
  1009. status: "rejected",
  1010. reasonCode: "guard.actionUnavailable",
  1011. }),
  1012. });
  1013. await expect(
  1014. new V4CommandExecutor(host).execute(
  1015. envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
  1016. ),
  1017. ).rejects.toThrow(V4RetryTargetNotLatestError);
  1018. expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
  1019. expect(app.sendInput).not.toHaveBeenCalled();
  1020. });
  1021. it("翻译不到 messageId:reject", async () => {
  1022. const record = makeRecord();
  1023. const host = makeHost(record, { getMessageIdForRow: () => null });
  1024. await expect(
  1025. new V4CommandExecutor(host).execute(
  1026. envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
  1027. ),
  1028. ).rejects.toThrow(V4RetryTargetNotLatestError);
  1029. });
  1030. it("handler 不按 activeAbortController 二次拒绝,而是进入 resolver 授权后的执行路径", async () => {
  1031. const record = makeRecord({ activeAbortController: new AbortController() });
  1032. const host = makeHost(record, { getMessageIdForRow: () => "msg-b" });
  1033. await expect(
  1034. new V4CommandExecutor(host).execute(
  1035. envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
  1036. ),
  1037. ).resolves.toBeUndefined();
  1038. expect(record.app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  1039. expect.objectContaining({ targetMessageId: "msg-b" }),
  1040. );
  1041. expect(record.app.sendInput).toHaveBeenCalled();
  1042. });
  1043. it("非最后一轮 assistant retry 直接拒绝,不解析原文也不 rewind", async () => {
  1044. const app = makeApp();
  1045. const record = makeRecord({ app });
  1046. const resolveTurnUserPrompt = vi.fn().mockResolvedValue("历史问题");
  1047. const host = makeHost(record, {
  1048. getMessageIdForRow: () => "msg-old",
  1049. isLatestRetryAssistantRow: () => false,
  1050. resolveTurnUserPrompt,
  1051. } as Partial<V4CommandCoreHost>);
  1052. await expect(
  1053. new V4CommandExecutor(host).execute(
  1054. envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
  1055. ),
  1056. ).rejects.toThrow(V4RetryTargetNotLatestError);
  1057. expect(resolveTurnUserPrompt).not.toHaveBeenCalled();
  1058. expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
  1059. expect(app.sendInput).not.toHaveBeenCalled();
  1060. });
  1061. });
  1062. describe("v4 Task3 canonical edit disposition", () => {
  1063. it("goal edit rewind 后仍走 goal command,并返回 destination ACK", async () => {
  1064. const app = makeApp({
  1065. getMode: vi.fn().mockReturnValue("plan"),
  1066. setTarget: vi.fn().mockResolvedValue({
  1067. targetID: "g1",
  1068. objective: "new goal",
  1069. status: "active",
  1070. }),
  1071. });
  1072. const record = makeRecord({ app });
  1073. const host = makeHost(record, {
  1074. resolveRowActionTarget: () => ({
  1075. ok: true,
  1076. action: "editUserQuery",
  1077. row: {} as never,
  1078. editTarget: {
  1079. entityId: "msg-goal",
  1080. productTurnId: "turn-goal",
  1081. transcriptMessageId: "msg-goal",
  1082. coveredByStableCompact: false,
  1083. intent: {
  1084. kind: "sendGoalCommand",
  1085. text: "old goal",
  1086. sourceCommandId: "cmd-old-goal",
  1087. },
  1088. },
  1089. }),
  1090. });
  1091. const result = await new V4CommandExecutor(host).execute(
  1092. envelope("editUserQuery", {
  1093. target: { rowId: 7, entityId: "msg-goal" },
  1094. newText: "new goal",
  1095. }),
  1096. );
  1097. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  1098. expect.objectContaining({ targetMessageId: "msg-goal" }),
  1099. );
  1100. expect(app.setTarget).toHaveBeenCalledWith(
  1101. expect.objectContaining({
  1102. objective: "new goal",
  1103. intent: expect.objectContaining({
  1104. kind: "sendGoalCommand",
  1105. sourceCommandId: "cmd-1",
  1106. }),
  1107. }),
  1108. );
  1109. expect(app.sendInput).not.toHaveBeenCalled();
  1110. expect(result).toEqual({
  1111. type: "editUserQuery",
  1112. disposition: "rewind",
  1113. sessionId: "s1",
  1114. });
  1115. });
  1116. it("compact-covered latest edit rewinds in the original session and never starts a child", async () => {
  1117. const parentApp = makeApp();
  1118. const childApp = makeApp({ sessionId: "s-child" });
  1119. const parent = makeRecord({ app: parentApp });
  1120. const child = makeRecord({ app: childApp });
  1121. const records = new Map([
  1122. ["s1", parent],
  1123. ["s-child", child],
  1124. ]);
  1125. const forkConversationBeforeInput = vi.fn().mockResolvedValue({
  1126. forkedSessionId: "s-child",
  1127. });
  1128. const host = makeHost(parent, {
  1129. getRecord: (sessionId) => records.get(sessionId),
  1130. forkConversationBeforeInput,
  1131. resolveRowActionTarget: () => ({
  1132. ok: true,
  1133. action: "editUserQuery",
  1134. row: {} as never,
  1135. editTarget: {
  1136. entityId: "msg-user",
  1137. productTurnId: "turn-product",
  1138. transcriptMessageId: "msg-user",
  1139. coveredByStableCompact: true,
  1140. intent: {
  1141. kind: "sendText",
  1142. text: "old text",
  1143. sourceCommandId: "cmd-old",
  1144. },
  1145. },
  1146. }),
  1147. });
  1148. const result = await new V4CommandExecutor(host).execute(
  1149. envelope("editUserQuery", {
  1150. target: { rowId: 7, entityId: "msg-user" },
  1151. newText: "edited in parent",
  1152. }),
  1153. );
  1154. await settle();
  1155. expect(forkConversationBeforeInput).not.toHaveBeenCalled();
  1156. expect(parentApp.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  1157. expect.objectContaining({ targetMessageId: "msg-user" }),
  1158. );
  1159. expect(parentApp.sendInput).toHaveBeenCalledWith(
  1160. { text: "edited in parent" },
  1161. expect.objectContaining({ inputId: "cmd-1" }),
  1162. );
  1163. expect(childApp.sendInput).not.toHaveBeenCalled();
  1164. expect(result).toEqual({
  1165. type: "editUserQuery",
  1166. disposition: "rewind",
  1167. sessionId: "s1",
  1168. });
  1169. });
  1170. it("compact edit ignores legacy child failure hooks", async () => {
  1171. const parent = makeRecord({ app: makeApp() });
  1172. const childApp = makeApp({ sessionId: "s-child" });
  1173. const child = makeRecord({
  1174. app: childApp,
  1175. restoreWarning: { message: "model unavailable", type: "model" },
  1176. });
  1177. const recordForkStartFailure = vi.fn().mockResolvedValue(undefined);
  1178. const host = makeHost(parent, {
  1179. getRecord: (sessionId) => (sessionId === "s1" ? parent : child),
  1180. forkConversationBeforeInput: vi.fn().mockResolvedValue({ forkedSessionId: "s-child" }),
  1181. recordForkStartFailure,
  1182. resolveRowActionTarget: () => ({
  1183. ok: true,
  1184. action: "editUserQuery",
  1185. row: {} as never,
  1186. editTarget: {
  1187. entityId: "msg-user",
  1188. productTurnId: "turn-product",
  1189. transcriptMessageId: "msg-user",
  1190. coveredByStableCompact: true,
  1191. intent: { kind: "sendText", text: "old", sourceCommandId: "cmd-old" },
  1192. },
  1193. }),
  1194. });
  1195. await expect(
  1196. new V4CommandExecutor(host).execute(
  1197. envelope("editUserQuery", {
  1198. target: { rowId: 7, entityId: "msg-user" },
  1199. newText: "edited",
  1200. }),
  1201. ),
  1202. ).resolves.toEqual({
  1203. type: "editUserQuery",
  1204. disposition: "rewind",
  1205. sessionId: "s1",
  1206. });
  1207. expect(parent.app.sendInput).toHaveBeenCalled();
  1208. expect(childApp.sendInput).not.toHaveBeenCalled();
  1209. expect(recordForkStartFailure).not.toHaveBeenCalled();
  1210. });
  1211. it("compact edit remains same-session when legacy child registration is unavailable", async () => {
  1212. const parent = makeRecord({ app: makeApp() });
  1213. const recordForkStartFailure = vi.fn().mockRejectedValue(new Error("failure store offline"));
  1214. const host = makeHost(parent, {
  1215. getRecord: (sessionId) => (sessionId === "s1" ? parent : undefined),
  1216. forkConversationBeforeInput: vi.fn().mockResolvedValue({ forkedSessionId: "s-child" }),
  1217. recordForkStartFailure,
  1218. resolveRowActionTarget: () => ({
  1219. ok: true,
  1220. action: "editUserQuery",
  1221. row: {} as never,
  1222. editTarget: {
  1223. entityId: "msg-user",
  1224. productTurnId: "turn-product",
  1225. transcriptMessageId: "msg-user",
  1226. coveredByStableCompact: true,
  1227. intent: { kind: "sendText", text: "old", sourceCommandId: "cmd-old" },
  1228. },
  1229. }),
  1230. });
  1231. await expect(
  1232. new V4CommandExecutor(host).execute(
  1233. envelope("editUserQuery", {
  1234. target: { rowId: 7, entityId: "msg-user" },
  1235. newText: "edited",
  1236. }),
  1237. ),
  1238. ).resolves.toEqual({
  1239. type: "editUserQuery",
  1240. disposition: "rewind",
  1241. sessionId: "s1",
  1242. });
  1243. expect(recordForkStartFailure).not.toHaveBeenCalled();
  1244. });
  1245. });
  1246. describe("v4 原生 forkAssistant", () => {
  1247. const stableTarget = {
  1248. productTurnId: "turn-product-1",
  1249. transcriptTurnId: "turn-runtime-1",
  1250. orderedMessageIds: ["msg-user", "msg-tool", "msg-c"],
  1251. boundaryMessageId: "msg-c",
  1252. };
  1253. const goalBoundary = { kind: "none" as const };
  1254. it("PV4-08:running 时解析稳定 logical turn 后走 conversation-only fork", async () => {
  1255. const record = makeRecord();
  1256. record.activeAbortController = new AbortController();
  1257. const info = vi.fn();
  1258. const resolveStableForkTarget = vi
  1259. .fn()
  1260. .mockResolvedValue({ ok: true, target: stableTarget, goalBoundary });
  1261. const forkStableConversation = vi.fn().mockResolvedValue({ forkedSessionId: "s-fork" });
  1262. const host = makeHost(record, {
  1263. resolveStableForkTarget,
  1264. forkStableConversation,
  1265. logger: { info },
  1266. });
  1267. const result = await new V4CommandExecutor(host).execute(
  1268. envelope("forkAssistant", { target: { rowId: 3, entityId: "entity-3" } }),
  1269. );
  1270. expect(resolveStableForkTarget).toHaveBeenCalledWith("s1", 3);
  1271. expect(forkStableConversation).toHaveBeenCalledWith("s1", {
  1272. target: stableTarget,
  1273. goalBoundary,
  1274. sourceCommandId: "cmd-1",
  1275. revisionAtDecision: 0,
  1276. });
  1277. expect(result).toEqual({ type: "forkAssistant", sessionId: "s-fork" });
  1278. expect(info).toHaveBeenCalledWith(
  1279. "v4 forkAssistant completed",
  1280. expect.objectContaining({
  1281. childSessionId: "s-fork",
  1282. clientId: "client-new",
  1283. commandId: "cmd-1",
  1284. event: "conversation.command.fork_assistant.completed",
  1285. parentSessionId: "s1",
  1286. revisionAtDecision: 0,
  1287. sessionId: "s1",
  1288. status: "completed",
  1289. targetBoundaryMessageId: "msg-c",
  1290. targetEntityId: "entity-3",
  1291. targetRowId: 3,
  1292. traceId: "trace-1",
  1293. }),
  1294. );
  1295. });
  1296. it("目标是 streaming/interrupted/中间段时按稳定 resolver reasonCode 拒绝", async () => {
  1297. const record = makeRecord();
  1298. const info = vi.fn();
  1299. const forkStableConversation = vi.fn();
  1300. const host = makeHost(record, {
  1301. logger: { info },
  1302. resolveStableForkTarget: async () => ({
  1303. ok: false,
  1304. reasonCode: "guard.forkTargetNotStable",
  1305. }),
  1306. forkStableConversation,
  1307. });
  1308. await expect(
  1309. new V4CommandExecutor(host).execute(
  1310. envelope("forkAssistant", {
  1311. target: { rowId: 3, entityId: "entity-3" },
  1312. }),
  1313. ),
  1314. ).rejects.toMatchObject({ reasonCode: "guard.forkTargetNotStable" });
  1315. expect(forkStableConversation).not.toHaveBeenCalled();
  1316. expect(info).not.toHaveBeenCalledWith("v4 forkAssistant completed", expect.anything());
  1317. });
  1318. it("stable fork capability 缺失时不回落带 ensureNoActiveTurn 的 legacy bridge", async () => {
  1319. const record = makeRecord();
  1320. const host = makeHost(record, {
  1321. resolveStableForkTarget: async () => ({ ok: true, target: stableTarget, goalBoundary }),
  1322. });
  1323. await expect(
  1324. new V4CommandExecutor(host).execute(
  1325. envelope("forkAssistant", {
  1326. target: { rowId: 3, entityId: "entity-3" },
  1327. }),
  1328. ),
  1329. ).rejects.toThrow("forkStableConversation");
  1330. });
  1331. });
  1332. describe("v4 原生 applyFileRewind", () => {
  1333. it("rowId 解析为同 turn messageIds 后只执行 workspace file rewind", async () => {
  1334. const app = makeApp({
  1335. runtime: {
  1336. applyWorkspaceFileRewind: vi.fn().mockResolvedValue({
  1337. applied: true,
  1338. response: "Rewound 2 files from summary checkpoints.",
  1339. preview: {
  1340. canApply: true,
  1341. safeFiles: [
  1342. {
  1343. action: "restore",
  1344. operationCount: 1,
  1345. path: "/work/src/a.ts",
  1346. toolNames: ["Edit"],
  1347. },
  1348. ],
  1349. unsafeFiles: [],
  1350. ignoredFiles: [],
  1351. },
  1352. }),
  1353. },
  1354. });
  1355. const record = makeRecord({ app });
  1356. const host = makeHost(record, {
  1357. getMessageIdsForTurnRow: (sessionId, rowId) =>
  1358. sessionId === "s1" && rowId === 3 ? ["msg-a1", "msg-a2"] : [],
  1359. });
  1360. const result = await new V4CommandExecutor(host).execute(
  1361. envelope("applyFileRewind", {
  1362. target: { rowId: 3, entityId: "entity-3" },
  1363. }),
  1364. );
  1365. expect(app.runtime.applyWorkspaceFileRewind).toHaveBeenCalledWith({
  1366. targetMessageIds: ["msg-a1", "msg-a2"],
  1367. targetTurnId: "turn-3",
  1368. });
  1369. expect(app.submitPrompt).not.toHaveBeenCalled();
  1370. expect(result).toMatchObject({
  1371. type: "applyFileRewind",
  1372. applied: true,
  1373. response: "Rewound 2 files from summary checkpoints.",
  1374. });
  1375. });
  1376. it("handler 不按 activeAbortController 二次拒绝 resolver 已授权的文件撤销", async () => {
  1377. const app = makeApp({
  1378. runtime: {
  1379. applyWorkspaceFileRewind: vi.fn().mockResolvedValue({
  1380. applied: false,
  1381. response: "no changes",
  1382. preview: { canApply: false, safeFiles: [], unsafeFiles: [], ignoredFiles: [] },
  1383. }),
  1384. },
  1385. });
  1386. const record = makeRecord({
  1387. app,
  1388. activeAbortController: new AbortController(),
  1389. });
  1390. const host = makeHost(record, {
  1391. getMessageIdsForTurnRow: () => ["msg-a1"],
  1392. });
  1393. await expect(
  1394. new V4CommandExecutor(host).execute(
  1395. envelope("applyFileRewind", {
  1396. target: { rowId: 3, entityId: "entity-3" },
  1397. }),
  1398. ),
  1399. ).resolves.toMatchObject({ type: "applyFileRewind" });
  1400. expect(app.runtime.applyWorkspaceFileRewind).toHaveBeenCalledTimes(1);
  1401. });
  1402. });