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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725
  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 ORDINARY_MODEL_SELECTION = {
  169. providerId: "builtin:bigmodel-coding-plan",
  170. modelId: "GLM-5.3",
  171. };
  172. const HIGHSPEED_MODEL_SELECTION = {
  173. providerId: "account:bigmodel-highspeed-card",
  174. modelId: "GLM-5.3",
  175. };
  176. const HIGHSPEED_MODEL_EXECUTION = {
  177. selectionScope: "execution" as const,
  178. requestAuth: {
  179. apiKey: "card-edit-jwt",
  180. headers: { Authorization: "Bearer card-edit-jwt", "X-Highspeed-Card-ID": "card-edit" },
  181. },
  182. selectionFallback: {
  183. providerId: "account:bigmodel-highspeed-card",
  184. target: ORDINARY_MODEL_SELECTION,
  185. rules: [
  186. { reason: "highspeed_card_expired" as const, providerErrorCode: "3402" },
  187. { reason: "highspeed_request_failed" as const },
  188. ],
  189. },
  190. };
  191. const originalEditAttachments = [
  192. {
  193. ref: "/work/first.txt",
  194. fileName: "first.txt",
  195. mime: "text/plain",
  196. bytes: 12,
  197. },
  198. {
  199. ref: "/work/second.txt",
  200. fileName: "second.txt",
  201. mime: "text/plain",
  202. bytes: 24,
  203. },
  204. ];
  205. function attachmentEditTarget() {
  206. return {
  207. ok: true as const,
  208. action: "editUserQuery" as const,
  209. row: { rowId: 7, turnId: "turn-7" } as never,
  210. editTarget: {
  211. entityId: "entity-7",
  212. productTurnId: "turn-7",
  213. transcriptMessageId: "msg-user",
  214. coveredByStableCompact: false,
  215. intent: {
  216. kind: "sendText" as const,
  217. text: "原始问题",
  218. attachments: originalEditAttachments,
  219. },
  220. },
  221. };
  222. }
  223. describe("v4 原生 editUserQuery", () => {
  224. it("正路径:rewind 截断(同 turn assistant 锚点)后原生 turn 重发新文本", async () => {
  225. const app = makeApp();
  226. const record = makeRecord({ app });
  227. const info = vi.fn();
  228. const host = makeHost(record, {
  229. getTurnRewindAnchor: (sessionId, rowId) =>
  230. sessionId === "s1" && rowId === 7 ? "msg-a" : null,
  231. logger: { info },
  232. });
  233. await new V4CommandExecutor(host).execute(
  234. envelope("editUserQuery", {
  235. target: { rowId: 7, entityId: "entity-7" },
  236. newText: "改过的问题",
  237. }),
  238. );
  239. await settle();
  240. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  241. expect.objectContaining({ targetMessageId: "msg-a" }),
  242. );
  243. // 重发走原生 prompt turn(sendInput),inputId=commandId 权威锚点。
  244. expect(app.sendInput).toHaveBeenCalledWith(
  245. { text: "改过的问题" },
  246. expect.objectContaining({ inputId: "cmd-1" }),
  247. );
  248. // 顺序:先截断后重发。
  249. expect(app.runtime.rewindConversationToMessage.mock.invocationCallOrder[0]).toBeLessThan(
  250. app.sendInput.mock.invocationCallOrder[0],
  251. );
  252. expect(info).toHaveBeenCalledWith(
  253. "v4 editUserQuery completed",
  254. expect.objectContaining({
  255. attachmentCount: 0,
  256. clientId: "client-new",
  257. commandId: "cmd-1",
  258. event: "conversation.command.edit_user_query.completed",
  259. intentKind: "sendText",
  260. sessionId: "s1",
  261. status: "completed",
  262. targetEntityId: "entity-7",
  263. targetRowId: 7,
  264. traceId: "trace-1",
  265. workspaceMode: "preserve",
  266. }),
  267. );
  268. const editLogFields = info.mock.calls.find(
  269. ([message]) => message === "v4 editUserQuery completed",
  270. )?.[1];
  271. expect(editLogFields).not.toHaveProperty("newText");
  272. expect(editLogFields).not.toHaveProperty("text");
  273. });
  274. it("编辑重发会应用本次新准备的 Highspeed Selection 与执行材料", async () => {
  275. const app = makeApp();
  276. const record = makeRecord({ app });
  277. const highspeedMeta = {
  278. schemaVersion: 1 as const,
  279. cardId: "card-edit",
  280. taskId: "s1",
  281. provider: "bigmodel",
  282. model: "GLM-5.3",
  283. issuedAt: 1,
  284. expiresAt: Date.now() + 60_000,
  285. };
  286. const host = makeHost(record, { getTurnRewindAnchor: () => "msg-user" });
  287. await new V4CommandExecutor(host).execute(
  288. envelope("editUserQuery", {
  289. target: { rowId: 7, entityId: "entity-7" },
  290. newText: "改过的问题",
  291. highspeedMeta,
  292. modelSelection: HIGHSPEED_MODEL_SELECTION,
  293. modelExecution: HIGHSPEED_MODEL_EXECUTION,
  294. }),
  295. );
  296. await settle();
  297. // Selection 可投影(要进 intent 让 transcript 复原时知道这轮走了加速 Provider)。
  298. expect(app.sendInput).toHaveBeenCalledWith(
  299. { text: "改过的问题" },
  300. expect.objectContaining({
  301. intent: expect.objectContaining({
  302. highspeed: highspeedMeta,
  303. modelSelection: HIGHSPEED_MODEL_SELECTION,
  304. }),
  305. }),
  306. );
  307. const options = app.sendInput.mock.calls[0]?.[1];
  308. expect(options.modelExecution.selectionScope).toBe("execution");
  309. expect(options.modelExecution.selectionFallback).toEqual(
  310. HIGHSPEED_MODEL_EXECUTION.selectionFallback,
  311. );
  312. // 卡 JWT 只能作为本轮执行依赖惰性解析,绝不能进入可持久化的 intent。
  313. await expect(
  314. options.modelExecution.requestDependencies.requestAuth.source.resolve(),
  315. ).resolves.toEqual(HIGHSPEED_MODEL_EXECUTION.requestAuth);
  316. expect(options.intent).not.toHaveProperty("modelExecution");
  317. });
  318. it("Highspeed 执行模型可用但退回目标缺失时仍允许编辑重发", async () => {
  319. const fallbackTarget = {
  320. providerId: "account:bigmodel-start-plan",
  321. modelId: "GLM-5.3",
  322. };
  323. const app = makeApp({
  324. listModels: () => [{ ref: HIGHSPEED_MODEL_SELECTION }],
  325. });
  326. const record = makeRecord({ app });
  327. const host = makeHost(record, { getTurnRewindAnchor: () => "msg-user" });
  328. await expect(
  329. new V4CommandExecutor(host).execute(
  330. envelope("editUserQuery", {
  331. target: { rowId: 7, entityId: "entity-7" },
  332. newText: "执行模型仍可用",
  333. highspeedMeta: {
  334. schemaVersion: 1 as const,
  335. cardId: "card-edit",
  336. taskId: "s1",
  337. provider: "bigmodel",
  338. model: "GLM-5.3",
  339. issuedAt: 1,
  340. expiresAt: Date.now() + 60_000,
  341. },
  342. modelSelection: HIGHSPEED_MODEL_SELECTION,
  343. modelExecution: {
  344. ...HIGHSPEED_MODEL_EXECUTION,
  345. selectionFallback: {
  346. ...HIGHSPEED_MODEL_EXECUTION.selectionFallback,
  347. target: fallbackTarget,
  348. },
  349. },
  350. }),
  351. ),
  352. ).resolves.toBeDefined();
  353. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledTimes(1);
  354. expect(app.sendInput).toHaveBeenCalledTimes(1);
  355. });
  356. it("编辑预检通过后 Registry 变化仍提交 replacement input", async () => {
  357. const listModels = vi
  358. .fn()
  359. .mockReturnValueOnce([{ ref: HIGHSPEED_MODEL_SELECTION }])
  360. .mockReturnValue([]);
  361. const app = makeApp({ listModels });
  362. const record = makeRecord({ app });
  363. const host = makeHost(record, { getTurnRewindAnchor: () => "msg-user" });
  364. await expect(
  365. new V4CommandExecutor(host).execute(
  366. envelope("editUserQuery", {
  367. target: { rowId: 7, entityId: "entity-7" },
  368. newText: "目录变化后仍需保留的编辑内容",
  369. highspeedMeta: {
  370. schemaVersion: 1 as const,
  371. cardId: "card-edit-race",
  372. taskId: "s1",
  373. provider: "bigmodel",
  374. model: "GLM-5.3",
  375. issuedAt: 1,
  376. expiresAt: Date.now() + 60_000,
  377. },
  378. modelSelection: HIGHSPEED_MODEL_SELECTION,
  379. modelExecution: {
  380. ...HIGHSPEED_MODEL_EXECUTION,
  381. selectionFallback: {
  382. ...HIGHSPEED_MODEL_EXECUTION.selectionFallback,
  383. target: { providerId: "user-provider", modelId: "user-model" },
  384. },
  385. },
  386. }),
  387. ),
  388. ).resolves.toBeDefined();
  389. // 破坏性操作前只读取一次目录;branch cut 后由 Core 接纳并对创建失败落权威输入。
  390. expect(listModels).toHaveBeenCalledTimes(1);
  391. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledTimes(1);
  392. expect(app.sendInput).toHaveBeenCalledTimes(1);
  393. });
  394. it("Highspeed 执行模型与退回目标都缺失时在历史和文件回退前拒绝编辑", async () => {
  395. const previewWorkspaceFileRewind = vi.fn().mockResolvedValue({
  396. canApply: true,
  397. safeFiles: [{ action: "restore", operationCount: 1, path: "/w/a.ts", toolNames: ["Edit"] }],
  398. unsafeFiles: [],
  399. ignoredFiles: [],
  400. });
  401. const applyWorkspaceFileRewind = vi.fn().mockImplementation(async (options) => {
  402. await options.commitAfterApply();
  403. return {
  404. applied: true,
  405. response: "ok",
  406. preview: await previewWorkspaceFileRewind(),
  407. };
  408. });
  409. const app = makeApp({
  410. listModels: () => [],
  411. runtime: { previewWorkspaceFileRewind, applyWorkspaceFileRewind },
  412. });
  413. const record = makeRecord({ app });
  414. const host = makeHost(record, { getTurnRewindAnchor: () => "msg-user" });
  415. await expect(
  416. new V4CommandExecutor(host).execute(
  417. envelope("editUserQuery", {
  418. target: { rowId: 7, entityId: "entity-7" },
  419. newText: "不能丢失的编辑内容",
  420. workspaceMode: "rewind",
  421. highspeedMeta: {
  422. schemaVersion: 1 as const,
  423. cardId: "card-edit",
  424. taskId: "s1",
  425. provider: "bigmodel",
  426. model: "GLM-5.3",
  427. issuedAt: 1,
  428. expiresAt: Date.now() + 60_000,
  429. },
  430. modelSelection: HIGHSPEED_MODEL_SELECTION,
  431. modelExecution: {
  432. ...HIGHSPEED_MODEL_EXECUTION,
  433. selectionFallback: {
  434. ...HIGHSPEED_MODEL_EXECUTION.selectionFallback,
  435. target: {
  436. providerId: "account:bigmodel-start-plan",
  437. modelId: "GLM-5.3",
  438. },
  439. },
  440. },
  441. }),
  442. ),
  443. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  444. // 模型准入是破坏性编辑的前置条件;失败时没有 branch cut,也没有文件副作用。
  445. expect(previewWorkspaceFileRewind).not.toHaveBeenCalled();
  446. expect(applyWorkspaceFileRewind).not.toHaveBeenCalled();
  447. expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
  448. expect(app.sendInput).not.toHaveBeenCalled();
  449. });
  450. it("卡已过期的编辑重发退回会话常驻 Selection,不保留无鉴权的加速 Selection", async () => {
  451. // CR-01 回归:被编辑的那轮是 Highspeed 轮,canonical intent 里留着 account:*-highspeed-card;
  452. // 本次没有有效新卡(已过期),旧实现只是不传 modelExecution 却沿用该 Selection,Core 会以
  453. // ModelRequestAuthMissing 失败,且该 Selection 被固定进新 intent,污染后续普通发送。
  454. const setModel = vi.fn();
  455. const app = makeApp({ getModel: () => "builtin:bigmodel-coding-plan/GLM-5.3", setModel });
  456. const record = makeRecord({ app });
  457. const host = makeHost(record, {
  458. resolveRowActionTarget: () => ({
  459. ok: true,
  460. action: "editUserQuery",
  461. row: {} as never,
  462. editTarget: {
  463. entityId: "entity-7",
  464. productTurnId: "turn-7",
  465. transcriptMessageId: "msg-user",
  466. coveredByStableCompact: false,
  467. intent: {
  468. kind: "sendText",
  469. text: "原始问题",
  470. modelSelection: HIGHSPEED_MODEL_SELECTION,
  471. },
  472. },
  473. }),
  474. });
  475. await new V4CommandExecutor(host).execute(
  476. envelope("editUserQuery", {
  477. target: { rowId: 7, entityId: "entity-7" },
  478. newText: "改过的问题",
  479. highspeedMeta: {
  480. schemaVersion: 1 as const,
  481. cardId: "card-edit",
  482. taskId: "s1",
  483. provider: "bigmodel",
  484. model: "GLM-5.3",
  485. issuedAt: 1,
  486. expiresAt: Date.now() - 1,
  487. },
  488. modelSelection: HIGHSPEED_MODEL_SELECTION,
  489. modelExecution: HIGHSPEED_MODEL_EXECUTION,
  490. }),
  491. );
  492. await settle();
  493. const options = app.sendInput.mock.calls[0]?.[1];
  494. expect(options.intent.modelSelection).toEqual({
  495. providerId: "builtin:bigmodel-coding-plan",
  496. modelId: "GLM-5.3",
  497. });
  498. expect(options.intent).not.toHaveProperty("highspeed");
  499. expect(options).not.toHaveProperty("modelExecution");
  500. // 只改本轮 intent,不改 session 常驻模型。
  501. expect(setModel).not.toHaveBeenCalled();
  502. });
  503. it("Highspeed admission 遇到收口竞态时保留编辑文本并进入队列", async () => {
  504. const pollutedFallbackExecution = {
  505. ...HIGHSPEED_MODEL_EXECUTION,
  506. selectionFallback: {
  507. ...HIGHSPEED_MODEL_EXECUTION.selectionFallback,
  508. target: HIGHSPEED_MODEL_SELECTION,
  509. },
  510. };
  511. const app = makeApp({
  512. getModel: () => "builtin:bigmodel-coding-plan/GLM-5.3",
  513. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  514. if (options?.requireQueue) {
  515. return { kind: "queued", queueItemId: "queue-edited" };
  516. }
  517. return { kind: "rejected", reason: "turn_not_steerable" };
  518. }),
  519. });
  520. const record = makeRecord({ app });
  521. const highspeedMeta = {
  522. schemaVersion: 1 as const,
  523. cardId: "card-edit",
  524. taskId: "s1",
  525. provider: "bigmodel",
  526. model: "GLM-5.3",
  527. issuedAt: 1,
  528. expiresAt: Date.now() + 60_000,
  529. };
  530. const host = makeHost(record, {
  531. getTurnRewindAnchor: () => "msg-user",
  532. retainQueuedTurnExecution: vi.fn(),
  533. deleteQueuedTurnExecution: vi.fn(),
  534. });
  535. await new V4CommandExecutor(host).execute(
  536. envelope("editUserQuery", {
  537. target: { rowId: 7, entityId: "entity-7" },
  538. newText: "竞态下的新问题",
  539. highspeedMeta,
  540. modelSelection: HIGHSPEED_MODEL_SELECTION,
  541. modelExecution: pollutedFallbackExecution,
  542. }),
  543. );
  544. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  545. expect.objectContaining({ targetMessageId: "msg-user" }),
  546. );
  547. expect(app.sendInput).toHaveBeenNthCalledWith(
  548. 1,
  549. { text: "竞态下的新问题" },
  550. expect.objectContaining({
  551. modelExecution: expect.objectContaining({ selectionScope: "execution" }),
  552. }),
  553. );
  554. // 入队路径不能把凭据交给 turn(此时还没有 turn),只投影 Selection + 卡元数据。
  555. expect(app.sendInput).toHaveBeenNthCalledWith(
  556. 2,
  557. { text: "竞态下的新问题" },
  558. expect.objectContaining({
  559. requireQueue: true,
  560. intent: expect.objectContaining({
  561. highspeed: highspeedMeta,
  562. modelSelection: ORDINARY_MODEL_SELECTION,
  563. }),
  564. }),
  565. );
  566. expect(app.sendInput.mock.calls[1]?.[1]).not.toHaveProperty("modelExecution");
  567. // 凭据改由宿主按 commandId 暂存在内存,提升队列项时再冻结成执行上下文。
  568. expect(host.retainQueuedTurnExecution).toHaveBeenCalledWith("s1", "cmd-1", {
  569. modelSelection: HIGHSPEED_MODEL_SELECTION,
  570. modelExecution: pollutedFallbackExecution,
  571. });
  572. });
  573. it("attachments 缺省时稳定保留 canonical 原 refs", async () => {
  574. const app = makeApp();
  575. const record = makeRecord({ app });
  576. const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
  577. await new V4CommandExecutor(host).execute(
  578. envelope("editUserQuery", {
  579. target: { rowId: 7, entityId: "entity-7" },
  580. newText: "只改正文",
  581. }),
  582. );
  583. await settle();
  584. expect(app.sendInput).toHaveBeenCalledWith(
  585. {
  586. text: "只改正文",
  587. attachments: [
  588. expect.objectContaining({ path: "/work/first.txt" }),
  589. expect.objectContaining({ path: "/work/second.txt" }),
  590. ],
  591. },
  592. expect.objectContaining({
  593. intent: expect.objectContaining({ attachmentRefs: originalEditAttachments }),
  594. }),
  595. );
  596. });
  597. it("仅附件 edit 使用新数组替换原 refs,并保持剩余顺序", async () => {
  598. const app = makeApp();
  599. const record = makeRecord({ app });
  600. const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
  601. await new V4CommandExecutor(host).execute(
  602. envelope("editUserQuery", {
  603. target: { rowId: 7, entityId: "entity-7" },
  604. newText: "",
  605. attachments: [originalEditAttachments[1]],
  606. }),
  607. );
  608. await settle();
  609. expect(app.sendInput).toHaveBeenCalledWith(
  610. {
  611. text: "",
  612. attachments: [expect.objectContaining({ path: "/work/second.txt" })],
  613. },
  614. expect.objectContaining({
  615. intent: expect.objectContaining({ attachmentRefs: [originalEditAttachments[1]] }),
  616. }),
  617. );
  618. });
  619. it("显式 [] 清空原 refs,而不是恢复 canonical attachments", async () => {
  620. const app = makeApp();
  621. const record = makeRecord({ app });
  622. const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
  623. await new V4CommandExecutor(host).execute(
  624. envelope("editUserQuery", {
  625. target: { rowId: 7, entityId: "entity-7" },
  626. newText: "保留正文",
  627. attachments: [],
  628. }),
  629. );
  630. await settle();
  631. expect(app.sendInput).toHaveBeenCalledWith(
  632. { text: "保留正文" },
  633. expect.objectContaining({
  634. intent: expect.objectContaining({ attachmentRefs: [] }),
  635. }),
  636. );
  637. });
  638. it("正文与显式附件数组都为空时在 branch cut 前拒绝", async () => {
  639. const app = makeApp();
  640. const record = makeRecord({ app });
  641. const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
  642. await expect(
  643. new V4CommandExecutor(host).execute(
  644. envelope("editUserQuery", {
  645. target: { rowId: 7, entityId: "entity-7" },
  646. newText: " ",
  647. attachments: [],
  648. }),
  649. ),
  650. ).rejects.toMatchObject({ reasonCode: "proto.invalidPayload" });
  651. expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
  652. expect(app.sendInput).not.toHaveBeenCalled();
  653. });
  654. it("workspaceMode=rewind:安全文件先恢复,再提交 branch cut 并原 session 重发", async () => {
  655. const previewWorkspaceFileRewind = vi.fn().mockResolvedValue({
  656. canApply: true,
  657. safeFiles: [{ action: "restore", operationCount: 1, path: "/w/a.ts", toolNames: ["Edit"] }],
  658. unsafeFiles: [],
  659. ignoredFiles: [],
  660. });
  661. const applyWorkspaceFileRewind = vi.fn().mockImplementation(async (options) => {
  662. await options.commitAfterApply();
  663. return {
  664. applied: true,
  665. response: "ok",
  666. preview: await previewWorkspaceFileRewind(),
  667. };
  668. });
  669. const app = makeApp({ runtime: { previewWorkspaceFileRewind, applyWorkspaceFileRewind } });
  670. const record = makeRecord({ app });
  671. const host = makeHost(record, {
  672. getMessageIdsForTurnRow: () => ["msg-user", "msg-assistant"],
  673. resolveRowActionTarget: () => ({
  674. ok: true,
  675. action: "editUserQuery",
  676. row: { rowId: 7, turnId: "turn-7" } as never,
  677. editTarget: {
  678. entityId: "entity-7",
  679. productTurnId: "turn-7",
  680. transcriptMessageId: "msg-user",
  681. coveredByStableCompact: true,
  682. intent: { kind: "sendText", text: "old" },
  683. },
  684. }),
  685. });
  686. const result = await new V4CommandExecutor(host).execute(
  687. envelope("editUserQuery", {
  688. target: { rowId: 7, entityId: "entity-7" },
  689. newText: "edited",
  690. workspaceMode: "rewind",
  691. }),
  692. );
  693. expect(previewWorkspaceFileRewind).toHaveBeenCalledWith(
  694. expect.objectContaining({ targetMessageIds: ["msg-user", "msg-assistant"] }),
  695. );
  696. expect(applyWorkspaceFileRewind).toHaveBeenCalledWith(
  697. expect.objectContaining({ commitAfterApply: expect.any(Function) }),
  698. );
  699. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  700. expect.objectContaining({ targetMessageId: "msg-user" }),
  701. );
  702. expect(result).toEqual({ type: "editUserQuery", disposition: "rewind", sessionId: "s1" });
  703. });
  704. it("workspaceMode=rewind:unsafe/ignored 结构化 blocked,不裁对话也不发模型请求", async () => {
  705. const preview = {
  706. canApply: false,
  707. safeFiles: [],
  708. unsafeFiles: [
  709. {
  710. operationCount: 1,
  711. path: "/w/a.ts",
  712. reason: "external_modified",
  713. toolNames: ["Edit"],
  714. },
  715. ],
  716. ignoredFiles: [],
  717. } as const;
  718. const previewWorkspaceFileRewind = vi.fn().mockResolvedValue(preview);
  719. const applyWorkspaceFileRewind = vi.fn();
  720. const app = makeApp({ runtime: { previewWorkspaceFileRewind, applyWorkspaceFileRewind } });
  721. const record = makeRecord({ app });
  722. const cancelInputCommand = vi.fn().mockResolvedValue(undefined);
  723. const host = makeHost(record, {
  724. cancelInputCommand,
  725. resolveRowActionTarget: () => ({
  726. ok: true,
  727. action: "editUserQuery",
  728. row: { rowId: 7, turnId: "turn-7" } as never,
  729. editTarget: {
  730. entityId: "entity-7",
  731. productTurnId: "turn-7",
  732. transcriptMessageId: "msg-user",
  733. coveredByStableCompact: false,
  734. intent: { kind: "sendText", text: "old" },
  735. },
  736. }),
  737. });
  738. const result = await new V4CommandExecutor(host).execute(
  739. envelope("editUserQuery", {
  740. target: { rowId: 7, entityId: "entity-7" },
  741. newText: "edited",
  742. workspaceMode: "rewind",
  743. }),
  744. );
  745. expect(result).toEqual({
  746. type: "editUserQuery",
  747. disposition: "blocked",
  748. sessionId: "s1",
  749. reasonCode: "guard.workspaceRewindUnsafeFiles",
  750. preview,
  751. });
  752. expect(cancelInputCommand).toHaveBeenCalledWith(
  753. "s1",
  754. "queue_cmd-1",
  755. "guard.workspaceRewindUnsafeFiles",
  756. );
  757. expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
  758. expect(app.sendInput).not.toHaveBeenCalled();
  759. expect(applyWorkspaceFileRewind).not.toHaveBeenCalled();
  760. });
  761. it("翻译不到锚点:reject,不静默兜底", async () => {
  762. const record = makeRecord();
  763. const info = vi.fn();
  764. const host = makeHost(record, {
  765. getTurnRewindAnchor: () => null,
  766. logger: { info },
  767. resolveUserMessageIdForRow: async () => null,
  768. });
  769. await expect(
  770. new V4CommandExecutor(host).execute(
  771. envelope("editUserQuery", {
  772. target: { rowId: 99, entityId: "entity-99" },
  773. newText: "x",
  774. }),
  775. ),
  776. ).rejects.toThrow(V4EditTargetNotLatestError);
  777. expect(info).not.toHaveBeenCalledWith("v4 editUserQuery completed", expect.anything());
  778. });
  779. it("running latest query:abort → idle → rewind → rerun", async () => {
  780. const calls: string[] = [];
  781. const app = makeApp({
  782. runtime: {
  783. rewindConversationToMessage: vi.fn().mockImplementation(async () => {
  784. calls.push("rewind");
  785. return { strategy: RewindStrategy.ActiveChain };
  786. }),
  787. getActiveTurnInfo: vi
  788. .fn()
  789. .mockReturnValueOnce({ turnId: "turn-old" })
  790. .mockReturnValue(undefined),
  791. },
  792. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  793. calls.push("rerun");
  794. options?.onTurnStartedObserved?.({
  795. id: "event-started",
  796. type: SessionEventType.TurnStarted,
  797. payload: { messageId: "msg-event-started" },
  798. });
  799. return {};
  800. }),
  801. });
  802. const controller = new AbortController();
  803. controller.signal.addEventListener("abort", () => {
  804. calls.push("abort");
  805. setTimeout(() => {
  806. calls.push("idle");
  807. record.activeAbortController = undefined;
  808. }, 0);
  809. });
  810. const record = makeRecord({ app, activeAbortController: controller });
  811. const host = makeHost(record, {
  812. getTurnRewindAnchor: () => "msg-a",
  813. isLatestEditableUserRow: () => true,
  814. });
  815. await new V4CommandExecutor(host).execute(
  816. envelope("editUserQuery", {
  817. target: { rowId: 7, entityId: "entity-7" },
  818. newText: "改过的问题",
  819. }),
  820. );
  821. await settle();
  822. expect(calls).toEqual(["abort", "idle", "rewind", "rerun"]);
  823. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  824. expect.objectContaining({ targetMessageId: "msg-a" }),
  825. );
  826. });
  827. it("runtime-only active turn:没有 Bootstrap controller 也必须先 stop 再 rewind", async () => {
  828. const calls: string[] = [];
  829. const app = makeApp({
  830. runtime: {
  831. getActiveTurnInfo: vi
  832. .fn()
  833. .mockReturnValueOnce({ turnId: "turn-old" })
  834. .mockReturnValue(undefined),
  835. stopActiveForegroundExecution: vi.fn().mockImplementation(() => {
  836. calls.push("stop");
  837. return { kind: "stopped", foregroundExecutionId: "foreground-old" };
  838. }),
  839. rewindConversationToMessage: vi.fn().mockImplementation(async () => {
  840. calls.push("rewind");
  841. return { strategy: RewindStrategy.ActiveChain };
  842. }),
  843. },
  844. sendInput: vi.fn().mockImplementation(async () => {
  845. calls.push("rerun");
  846. return {};
  847. }),
  848. });
  849. const record = makeRecord({ app });
  850. const host = makeHost(record, { getTurnRewindAnchor: () => "msg-a" });
  851. await new V4CommandExecutor(host).execute(
  852. envelope("editUserQuery", {
  853. target: { rowId: 7, entityId: "entity-7" },
  854. newText: "runtime-only 编辑",
  855. }),
  856. );
  857. expect(calls).toEqual(["stop", "rewind", "rerun"]);
  858. expect(app.runtime.stopActiveForegroundExecution).toHaveBeenCalledWith(
  859. expect.objectContaining({ reason: "v4 editUserQuery preempts active turn" }),
  860. );
  861. });
  862. it("running 历史 user query:直接拒绝,且不 stop 当前 turn", async () => {
  863. const calls: string[] = [];
  864. const controller = new AbortController();
  865. controller.signal.addEventListener("abort", () => {
  866. calls.push("abort");
  867. });
  868. const record = makeRecord({ activeAbortController: controller });
  869. const host = makeHost(record, {
  870. getTurnRewindAnchor: () => "msg-a",
  871. isLatestEditableUserRow: () => false,
  872. });
  873. await expect(
  874. new V4CommandExecutor(host).execute(
  875. envelope("editUserQuery", {
  876. target: { rowId: 7, entityId: "entity-7" },
  877. newText: "x",
  878. }),
  879. ),
  880. ).rejects.toThrow(V4EditTargetNotLatestError);
  881. expect(calls).toEqual([]);
  882. expect(record.activeAbortController).toBe(controller);
  883. });
  884. });
  885. describe("v4 原生 retryTurn", () => {
  886. it("Task3:从 canonical cause 以新 commandId 重建完整 intent 与 provenance", async () => {
  887. const app = makeApp();
  888. const record = makeRecord({ app });
  889. const attachment = {
  890. ref: "/work/spec.md",
  891. fileName: "spec.md",
  892. mime: "text/markdown",
  893. bytes: 12,
  894. };
  895. const host = makeHost(record, {
  896. resolveRowActionTarget: () => ({
  897. ok: true,
  898. action: "retryTurn",
  899. row: {} as never,
  900. messageId: "msg-assistant",
  901. editTarget: {
  902. entityId: "msg-user",
  903. productTurnId: "turn-product",
  904. transcriptMessageId: "msg-user",
  905. coveredByStableCompact: false,
  906. intent: {
  907. kind: "sendText",
  908. text: "original canonical text",
  909. sourceCommandId: "cmd-original",
  910. clientId: "client-original",
  911. queueItemId: "queue-original",
  912. requestedDelivery: "guide",
  913. admittedDelivery: "queue",
  914. fallbackReasonCode: "guide.attachmentsUnsupported",
  915. modelSelection: {
  916. providerId: "original-provider",
  917. modelId: "original-model",
  918. options: { reasoningLevel: "high" },
  919. },
  920. mode: "edit",
  921. attachments: [attachment],
  922. },
  923. },
  924. }),
  925. });
  926. await new V4CommandExecutor(host).execute(
  927. envelope("retryTurn", {
  928. target: { rowId: 5, entityId: "msg-assistant" },
  929. }),
  930. );
  931. await settle();
  932. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  933. expect.objectContaining({ targetMessageId: "msg-user" }),
  934. );
  935. expect(app.sendInput).toHaveBeenCalledWith(
  936. expect.objectContaining({
  937. text: "original canonical text",
  938. attachments: [expect.objectContaining({ path: "/work/spec.md" })],
  939. }),
  940. expect.objectContaining({
  941. inputId: "cmd-1",
  942. intent: expect.objectContaining({
  943. sourceCommandId: "cmd-1",
  944. kind: "sendText",
  945. text: "original canonical text",
  946. requestedDelivery: "guide",
  947. admittedDelivery: "queue",
  948. fallbackReasonCode: "guide.attachmentsUnsupported",
  949. modelSelection: {
  950. providerId: "original-provider",
  951. modelId: "original-model",
  952. options: { reasoningLevel: "high" },
  953. },
  954. mode: "edit",
  955. provenance: {
  956. sourceCommandId: "cmd-original",
  957. queueItemId: "queue-original",
  958. clientId: "client-original",
  959. },
  960. }),
  961. }),
  962. );
  963. });
  964. it("retry Highspeed 轮时没有新执行材料,退回会话常驻 Selection 且不改 session 模型", async () => {
  965. // CR-01 回归:retry 从 canonical intent 复制历史 Selection;Highspeed 轮的 Selection 是
  966. // account:*-highspeed-card,本次 retry 没有任何执行材料,必须显式改写回会话常驻 Selection。
  967. const setModel = vi.fn();
  968. const app = makeApp({ getModel: () => "builtin:bigmodel-coding-plan/GLM-5.3", setModel });
  969. const record = makeRecord({ app });
  970. const host = makeHost(record, {
  971. resolveRowActionTarget: () => ({
  972. ok: true,
  973. action: "retryTurn",
  974. row: {} as never,
  975. messageId: "msg-assistant",
  976. editTarget: {
  977. entityId: "msg-user",
  978. productTurnId: "turn-product",
  979. transcriptMessageId: "msg-user",
  980. coveredByStableCompact: false,
  981. intent: {
  982. kind: "sendText",
  983. text: "accelerated prompt",
  984. sourceCommandId: "cmd-original",
  985. modelSelection: HIGHSPEED_MODEL_SELECTION,
  986. },
  987. },
  988. }),
  989. });
  990. await new V4CommandExecutor(host).execute(
  991. envelope("retryTurn", { target: { rowId: 5, entityId: "msg-assistant" } }),
  992. );
  993. await settle();
  994. const options = app.sendInput.mock.calls[0]?.[1];
  995. expect(options.intent.modelSelection).toEqual({
  996. providerId: "builtin:bigmodel-coding-plan",
  997. modelId: "GLM-5.3",
  998. });
  999. expect(options.intent).not.toHaveProperty("highspeed");
  1000. expect(options).not.toHaveProperty("modelExecution");
  1001. expect(setModel).not.toHaveBeenCalled();
  1002. });
  1003. it("retry-of-retry 保留最初 provenance,不被中间 retry 的 queue/client 覆盖", async () => {
  1004. const app = makeApp();
  1005. const record = makeRecord({ app });
  1006. const host = makeHost(record, {
  1007. resolveRowActionTarget: () => ({
  1008. ok: true,
  1009. action: "retryTurn",
  1010. row: {} as never,
  1011. messageId: "msg-retry-assistant",
  1012. editTarget: {
  1013. entityId: "msg-retry-user",
  1014. productTurnId: "turn-retry",
  1015. transcriptMessageId: "msg-retry-user",
  1016. coveredByStableCompact: false,
  1017. intent: {
  1018. kind: "sendText",
  1019. text: "retry canonical text",
  1020. sourceCommandId: "cmd-middle-retry",
  1021. queueItemId: "queue-middle-retry",
  1022. clientId: "client-middle-retry",
  1023. provenance: {
  1024. sourceCommandId: "cmd-original",
  1025. queueItemId: "queue-original",
  1026. clientId: "client-original",
  1027. },
  1028. },
  1029. },
  1030. }),
  1031. });
  1032. await new V4CommandExecutor(host).execute(
  1033. envelope("retryTurn", {
  1034. target: { rowId: 8, entityId: "msg-retry-assistant" },
  1035. }),
  1036. );
  1037. await settle();
  1038. expect(app.sendInput).toHaveBeenCalledWith(
  1039. expect.anything(),
  1040. expect.objectContaining({
  1041. intent: expect.objectContaining({
  1042. sourceCommandId: "cmd-1",
  1043. provenance: {
  1044. sourceCommandId: "cmd-original",
  1045. queueItemId: "queue-original",
  1046. clientId: "client-original",
  1047. },
  1048. }),
  1049. }),
  1050. );
  1051. });
  1052. it("goal retry preserves sendGoalCommand kind", async () => {
  1053. const app = makeApp({
  1054. getMode: vi.fn().mockReturnValue("plan"),
  1055. setTarget: vi.fn().mockResolvedValue({
  1056. targetID: "g1",
  1057. objective: "goal",
  1058. status: "active",
  1059. }),
  1060. });
  1061. const record = makeRecord({ app });
  1062. const host = makeHost(record, {
  1063. resolveRowActionTarget: () => ({
  1064. ok: true,
  1065. action: "retryTurn",
  1066. row: {} as never,
  1067. messageId: "msg-goal-assistant",
  1068. editTarget: {
  1069. entityId: "msg-goal-user",
  1070. productTurnId: "turn-goal",
  1071. transcriptMessageId: "msg-goal-user",
  1072. coveredByStableCompact: false,
  1073. intent: {
  1074. kind: "sendGoalCommand",
  1075. text: "goal",
  1076. sourceCommandId: "cmd-goal-original",
  1077. },
  1078. },
  1079. }),
  1080. });
  1081. await new V4CommandExecutor(host).execute(
  1082. envelope("retryTurn", {
  1083. target: { rowId: 6, entityId: "msg-goal-assistant" },
  1084. }),
  1085. );
  1086. expect(app.setTarget).toHaveBeenCalledWith(
  1087. expect.objectContaining({
  1088. objective: "goal",
  1089. intent: expect.objectContaining({
  1090. kind: "sendGoalCommand",
  1091. sourceCommandId: "cmd-1",
  1092. }),
  1093. }),
  1094. );
  1095. expect(app.sendInput).not.toHaveBeenCalled();
  1096. });
  1097. it("重试模型不可用时在 branch cut 前拒绝", async () => {
  1098. const app = makeApp({ listModels: () => [] });
  1099. const record = makeRecord({ app });
  1100. const host = makeHost(record, {
  1101. getMessageIdForRow: () => "msg-assistant",
  1102. resolveRowActionTarget: () => ({
  1103. ok: true,
  1104. action: "retryTurn",
  1105. row: {} as never,
  1106. messageId: "msg-assistant",
  1107. editTarget: {
  1108. entityId: "user-entity-7",
  1109. productTurnId: "turn-7",
  1110. transcriptMessageId: "msg-user",
  1111. coveredByStableCompact: false,
  1112. intent: {
  1113. kind: "sendText",
  1114. text: "原始问题",
  1115. modelSelection: { providerId: "missing-provider", modelId: "missing-model" },
  1116. },
  1117. },
  1118. }),
  1119. });
  1120. await expect(
  1121. new V4CommandExecutor(host).execute(
  1122. envelope("retryTurn", { target: { rowId: 7, entityId: "entity-7" } }),
  1123. ),
  1124. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1125. expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
  1126. expect(app.sendInput).not.toHaveBeenCalled();
  1127. });
  1128. it("重试预检通过后 Registry 变化仍提交 replacement input", async () => {
  1129. const selection = { providerId: "user-provider", modelId: "user-model" };
  1130. const listModels = vi
  1131. .fn()
  1132. .mockReturnValueOnce([{ ref: selection }])
  1133. .mockReturnValue([]);
  1134. const app = makeApp({ listModels });
  1135. const record = makeRecord({ app });
  1136. const host = makeHost(record, {
  1137. resolveRowActionTarget: () => ({
  1138. ok: true,
  1139. action: "retryTurn",
  1140. row: {} as never,
  1141. messageId: "msg-assistant",
  1142. editTarget: {
  1143. entityId: "user-entity-7",
  1144. productTurnId: "turn-7",
  1145. transcriptMessageId: "msg-user",
  1146. coveredByStableCompact: false,
  1147. intent: { kind: "sendText", text: "必须保留的重试内容", modelSelection: selection },
  1148. },
  1149. }),
  1150. });
  1151. await expect(
  1152. new V4CommandExecutor(host).execute(
  1153. envelope("retryTurn", { target: { rowId: 7, entityId: "entity-7" } }),
  1154. ),
  1155. ).resolves.toBeUndefined();
  1156. expect(listModels).toHaveBeenCalledTimes(1);
  1157. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledTimes(1);
  1158. expect(app.sendInput).toHaveBeenCalledTimes(1);
  1159. });
  1160. it("canonical resolver 给出的原文在 rewind 后重发", async () => {
  1161. const app = makeApp();
  1162. const record = makeRecord({ app });
  1163. const resolveOrder: string[] = [];
  1164. const host = makeHost(record, {
  1165. getMessageIdForRow: (_s, rowId) => (rowId === 5 ? "msg-b" : null),
  1166. resolveTurnUserPrompt: async (_s, messageId) => {
  1167. resolveOrder.push("resolve");
  1168. return messageId === "msg-b" ? "原始问题" : null;
  1169. },
  1170. });
  1171. app.runtime.rewindConversationToMessage.mockImplementation(async () => {
  1172. resolveOrder.push("rewind");
  1173. return { strategy: RewindStrategy.ActiveChain };
  1174. });
  1175. await new V4CommandExecutor(host).execute(
  1176. envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
  1177. );
  1178. await settle();
  1179. // canonical intent 已由 projection resolver 在截断前给出,不再回读 raw transcript 文本。
  1180. expect(resolveOrder).toEqual(["rewind"]);
  1181. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  1182. expect.objectContaining({ targetMessageId: "user-msg-b" }),
  1183. );
  1184. expect(app.sendInput).toHaveBeenCalledWith(
  1185. { text: "原始问题" },
  1186. expect.objectContaining({ inputId: "cmd-1" }),
  1187. );
  1188. });
  1189. it("canonical cause 不可解析:直接拒绝且不截断", async () => {
  1190. const app = makeApp();
  1191. const record = makeRecord({ app });
  1192. const host = makeHost(record, {
  1193. resolveRowActionTarget: () => ({
  1194. ok: false,
  1195. status: "rejected",
  1196. reasonCode: "guard.actionUnavailable",
  1197. }),
  1198. });
  1199. await expect(
  1200. new V4CommandExecutor(host).execute(
  1201. envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
  1202. ),
  1203. ).rejects.toThrow(V4RetryTargetNotLatestError);
  1204. expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
  1205. expect(app.sendInput).not.toHaveBeenCalled();
  1206. });
  1207. it("handler 不按 activeAbortController 二次拒绝,而是进入 resolver 授权后的执行路径", async () => {
  1208. const record = makeRecord({ activeAbortController: new AbortController() });
  1209. const host = makeHost(record, { getMessageIdForRow: () => "msg-b" });
  1210. await expect(
  1211. new V4CommandExecutor(host).execute(
  1212. envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
  1213. ),
  1214. ).resolves.toBeUndefined();
  1215. expect(record.app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  1216. expect.objectContaining({ targetMessageId: "user-msg-b" }),
  1217. );
  1218. expect(record.app.sendInput).toHaveBeenCalled();
  1219. });
  1220. it("非最后一轮 assistant retry 直接拒绝,不解析原文也不 rewind", async () => {
  1221. const app = makeApp();
  1222. const record = makeRecord({ app });
  1223. const resolveTurnUserPrompt = vi.fn().mockResolvedValue("历史问题");
  1224. const host = makeHost(record, {
  1225. getMessageIdForRow: () => "msg-old",
  1226. isLatestRetryAssistantRow: () => false,
  1227. resolveTurnUserPrompt,
  1228. } as Partial<V4CommandCoreHost>);
  1229. await expect(
  1230. new V4CommandExecutor(host).execute(
  1231. envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
  1232. ),
  1233. ).rejects.toThrow(V4RetryTargetNotLatestError);
  1234. expect(resolveTurnUserPrompt).not.toHaveBeenCalled();
  1235. expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
  1236. expect(app.sendInput).not.toHaveBeenCalled();
  1237. });
  1238. });
  1239. describe("v4 Task3 canonical edit disposition", () => {
  1240. it("goal edit rewind 后仍走 goal command,并返回 destination ACK", async () => {
  1241. const app = makeApp({
  1242. getMode: vi.fn().mockReturnValue("plan"),
  1243. setTarget: vi.fn().mockResolvedValue({
  1244. targetID: "g1",
  1245. objective: "new goal",
  1246. status: "active",
  1247. }),
  1248. });
  1249. const record = makeRecord({ app });
  1250. const host = makeHost(record, {
  1251. resolveRowActionTarget: () => ({
  1252. ok: true,
  1253. action: "editUserQuery",
  1254. row: {} as never,
  1255. editTarget: {
  1256. entityId: "msg-goal",
  1257. productTurnId: "turn-goal",
  1258. transcriptMessageId: "msg-goal",
  1259. coveredByStableCompact: false,
  1260. intent: {
  1261. kind: "sendGoalCommand",
  1262. text: "old goal",
  1263. sourceCommandId: "cmd-old-goal",
  1264. },
  1265. },
  1266. }),
  1267. });
  1268. const result = await new V4CommandExecutor(host).execute(
  1269. envelope("editUserQuery", {
  1270. target: { rowId: 7, entityId: "msg-goal" },
  1271. newText: "new goal",
  1272. }),
  1273. );
  1274. expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  1275. expect.objectContaining({ targetMessageId: "msg-goal" }),
  1276. );
  1277. expect(app.setTarget).toHaveBeenCalledWith(
  1278. expect.objectContaining({
  1279. objective: "new goal",
  1280. intent: expect.objectContaining({
  1281. kind: "sendGoalCommand",
  1282. sourceCommandId: "cmd-1",
  1283. }),
  1284. }),
  1285. );
  1286. expect(app.sendInput).not.toHaveBeenCalled();
  1287. expect(result).toEqual({
  1288. type: "editUserQuery",
  1289. disposition: "rewind",
  1290. sessionId: "s1",
  1291. });
  1292. });
  1293. it("compact-covered latest edit rewinds in the original session and never starts a child", async () => {
  1294. const parentApp = makeApp();
  1295. const childApp = makeApp({ sessionId: "s-child" });
  1296. const parent = makeRecord({ app: parentApp });
  1297. const child = makeRecord({ app: childApp });
  1298. const records = new Map([
  1299. ["s1", parent],
  1300. ["s-child", child],
  1301. ]);
  1302. const forkConversationBeforeInput = vi.fn().mockResolvedValue({
  1303. forkedSessionId: "s-child",
  1304. });
  1305. const host = makeHost(parent, {
  1306. getRecord: (sessionId) => records.get(sessionId),
  1307. forkConversationBeforeInput,
  1308. resolveRowActionTarget: () => ({
  1309. ok: true,
  1310. action: "editUserQuery",
  1311. row: {} as never,
  1312. editTarget: {
  1313. entityId: "msg-user",
  1314. productTurnId: "turn-product",
  1315. transcriptMessageId: "msg-user",
  1316. coveredByStableCompact: true,
  1317. intent: {
  1318. kind: "sendText",
  1319. text: "old text",
  1320. sourceCommandId: "cmd-old",
  1321. },
  1322. },
  1323. }),
  1324. });
  1325. const result = await new V4CommandExecutor(host).execute(
  1326. envelope("editUserQuery", {
  1327. target: { rowId: 7, entityId: "msg-user" },
  1328. newText: "edited in parent",
  1329. }),
  1330. );
  1331. await settle();
  1332. expect(forkConversationBeforeInput).not.toHaveBeenCalled();
  1333. expect(parentApp.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
  1334. expect.objectContaining({ targetMessageId: "msg-user" }),
  1335. );
  1336. expect(parentApp.sendInput).toHaveBeenCalledWith(
  1337. { text: "edited in parent" },
  1338. expect.objectContaining({ inputId: "cmd-1" }),
  1339. );
  1340. expect(childApp.sendInput).not.toHaveBeenCalled();
  1341. expect(result).toEqual({
  1342. type: "editUserQuery",
  1343. disposition: "rewind",
  1344. sessionId: "s1",
  1345. });
  1346. });
  1347. it("compact edit ignores legacy child failure hooks", async () => {
  1348. const parent = makeRecord({ app: makeApp() });
  1349. const childApp = makeApp({ sessionId: "s-child" });
  1350. const child = makeRecord({
  1351. app: childApp,
  1352. restoreWarning: { message: "model unavailable", type: "model" },
  1353. });
  1354. const recordForkStartFailure = vi.fn().mockResolvedValue(undefined);
  1355. const host = makeHost(parent, {
  1356. getRecord: (sessionId) => (sessionId === "s1" ? parent : child),
  1357. forkConversationBeforeInput: vi.fn().mockResolvedValue({ forkedSessionId: "s-child" }),
  1358. recordForkStartFailure,
  1359. resolveRowActionTarget: () => ({
  1360. ok: true,
  1361. action: "editUserQuery",
  1362. row: {} as never,
  1363. editTarget: {
  1364. entityId: "msg-user",
  1365. productTurnId: "turn-product",
  1366. transcriptMessageId: "msg-user",
  1367. coveredByStableCompact: true,
  1368. intent: { kind: "sendText", text: "old", sourceCommandId: "cmd-old" },
  1369. },
  1370. }),
  1371. });
  1372. await expect(
  1373. new V4CommandExecutor(host).execute(
  1374. envelope("editUserQuery", {
  1375. target: { rowId: 7, entityId: "msg-user" },
  1376. newText: "edited",
  1377. }),
  1378. ),
  1379. ).resolves.toEqual({
  1380. type: "editUserQuery",
  1381. disposition: "rewind",
  1382. sessionId: "s1",
  1383. });
  1384. expect(parent.app.sendInput).toHaveBeenCalled();
  1385. expect(childApp.sendInput).not.toHaveBeenCalled();
  1386. expect(recordForkStartFailure).not.toHaveBeenCalled();
  1387. });
  1388. });
  1389. describe("v4 原生 forkAssistant", () => {
  1390. const stableTarget = {
  1391. productTurnId: "turn-product-1",
  1392. transcriptTurnId: "turn-runtime-1",
  1393. orderedMessageIds: ["msg-user", "msg-tool", "msg-c"],
  1394. boundaryMessageId: "msg-c",
  1395. };
  1396. const goalBoundary = { kind: "none" as const };
  1397. it("PV4-08:running 时解析稳定 logical turn 后走 conversation-only fork", async () => {
  1398. const record = makeRecord();
  1399. record.activeAbortController = new AbortController();
  1400. const info = vi.fn();
  1401. const resolveStableForkTarget = vi
  1402. .fn()
  1403. .mockResolvedValue({ ok: true, target: stableTarget, goalBoundary });
  1404. const forkStableConversation = vi.fn().mockResolvedValue({ forkedSessionId: "s-fork" });
  1405. const host = makeHost(record, {
  1406. resolveStableForkTarget,
  1407. forkStableConversation,
  1408. logger: { info },
  1409. });
  1410. const result = await new V4CommandExecutor(host).execute(
  1411. envelope("forkAssistant", { target: { rowId: 3, entityId: "entity-3" } }),
  1412. );
  1413. expect(resolveStableForkTarget).toHaveBeenCalledWith("s1", 3);
  1414. expect(forkStableConversation).toHaveBeenCalledWith("s1", {
  1415. target: stableTarget,
  1416. goalBoundary,
  1417. sourceCommandId: "cmd-1",
  1418. revisionAtDecision: 0,
  1419. });
  1420. expect(result).toEqual({ type: "forkAssistant", sessionId: "s-fork" });
  1421. expect(info).toHaveBeenCalledWith(
  1422. "v4 forkAssistant completed",
  1423. expect.objectContaining({
  1424. childSessionId: "s-fork",
  1425. clientId: "client-new",
  1426. commandId: "cmd-1",
  1427. event: "conversation.command.fork_assistant.completed",
  1428. parentSessionId: "s1",
  1429. revisionAtDecision: 0,
  1430. sessionId: "s1",
  1431. status: "completed",
  1432. targetBoundaryMessageId: "msg-c",
  1433. targetEntityId: "entity-3",
  1434. targetRowId: 3,
  1435. traceId: "trace-1",
  1436. }),
  1437. );
  1438. });
  1439. it("带 targetCwd:原样透传给宿主 fork,ACK 指向宿主返回的 child", async () => {
  1440. const record = makeRecord();
  1441. const forkStableConversation = vi.fn().mockResolvedValue({ forkedSessionId: "ses_wt_child" });
  1442. const host = makeHost(record, {
  1443. resolveStableForkTarget: vi
  1444. .fn()
  1445. .mockResolvedValue({ ok: true, target: stableTarget, goalBoundary }),
  1446. forkStableConversation,
  1447. });
  1448. const targetCwd = {
  1449. cwd: "/Users/dev/.zcode/worktrees/3f2a/project",
  1450. childSessionId: "ses_wt_child",
  1451. worktreeCreation: {
  1452. path: "/Users/dev/.zcode/worktrees/3f2a/project",
  1453. sha: "9e6d2f72d4",
  1454. ref: null,
  1455. output: "",
  1456. },
  1457. };
  1458. const result = await new V4CommandExecutor(host).execute(
  1459. envelope("forkAssistant", {
  1460. target: { rowId: 3, entityId: "entity-3" },
  1461. targetCwd,
  1462. }),
  1463. );
  1464. expect(forkStableConversation).toHaveBeenCalledWith("s1", {
  1465. target: stableTarget,
  1466. goalBoundary,
  1467. sourceCommandId: "cmd-1",
  1468. revisionAtDecision: 0,
  1469. targetCwd,
  1470. });
  1471. expect(result).toEqual({ type: "forkAssistant", sessionId: "ses_wt_child" });
  1472. });
  1473. it("不带 targetCwd:宿主参数中不出现 targetCwd 键", async () => {
  1474. const record = makeRecord();
  1475. const forkStableConversation = vi.fn().mockResolvedValue({ forkedSessionId: "s-fork" });
  1476. const host = makeHost(record, {
  1477. resolveStableForkTarget: vi
  1478. .fn()
  1479. .mockResolvedValue({ ok: true, target: stableTarget, goalBoundary }),
  1480. forkStableConversation,
  1481. });
  1482. await new V4CommandExecutor(host).execute(
  1483. envelope("forkAssistant", { target: { rowId: 3, entityId: "entity-3" } }),
  1484. );
  1485. expect(forkStableConversation.mock.calls[0]?.[1]).not.toHaveProperty("targetCwd");
  1486. });
  1487. it("目标是 streaming/interrupted/中间段时按稳定 resolver reasonCode 拒绝", async () => {
  1488. const record = makeRecord();
  1489. const info = vi.fn();
  1490. const forkStableConversation = vi.fn();
  1491. const host = makeHost(record, {
  1492. logger: { info },
  1493. resolveStableForkTarget: async () => ({
  1494. ok: false,
  1495. reasonCode: "guard.forkTargetNotStable",
  1496. }),
  1497. forkStableConversation,
  1498. });
  1499. await expect(
  1500. new V4CommandExecutor(host).execute(
  1501. envelope("forkAssistant", {
  1502. target: { rowId: 3, entityId: "entity-3" },
  1503. }),
  1504. ),
  1505. ).rejects.toMatchObject({ reasonCode: "guard.forkTargetNotStable" });
  1506. expect(forkStableConversation).not.toHaveBeenCalled();
  1507. expect(info).not.toHaveBeenCalledWith("v4 forkAssistant completed", expect.anything());
  1508. });
  1509. it("stable fork capability 缺失时不回落带 ensureNoActiveTurn 的 legacy bridge", async () => {
  1510. const record = makeRecord();
  1511. const host = makeHost(record, {
  1512. resolveStableForkTarget: async () => ({ ok: true, target: stableTarget, goalBoundary }),
  1513. });
  1514. await expect(
  1515. new V4CommandExecutor(host).execute(
  1516. envelope("forkAssistant", {
  1517. target: { rowId: 3, entityId: "entity-3" },
  1518. }),
  1519. ),
  1520. ).rejects.toThrow("forkStableConversation");
  1521. });
  1522. });
  1523. describe("v4 原生 applyFileRewind", () => {
  1524. it("rowId 解析为同 turn messageIds 后只执行 workspace file rewind", async () => {
  1525. const app = makeApp({
  1526. runtime: {
  1527. applyWorkspaceFileRewind: vi.fn().mockResolvedValue({
  1528. applied: true,
  1529. response: "Rewound 2 files from summary checkpoints.",
  1530. preview: {
  1531. canApply: true,
  1532. safeFiles: [
  1533. {
  1534. action: "restore",
  1535. operationCount: 1,
  1536. path: "/work/src/a.ts",
  1537. toolNames: ["Edit"],
  1538. },
  1539. ],
  1540. unsafeFiles: [],
  1541. ignoredFiles: [],
  1542. },
  1543. }),
  1544. },
  1545. });
  1546. const record = makeRecord({ app });
  1547. const host = makeHost(record, {
  1548. getMessageIdsForTurnRow: (sessionId, rowId) =>
  1549. sessionId === "s1" && rowId === 3 ? ["msg-a1", "msg-a2"] : [],
  1550. });
  1551. const result = await new V4CommandExecutor(host).execute(
  1552. envelope("applyFileRewind", {
  1553. target: { rowId: 3, entityId: "entity-3" },
  1554. }),
  1555. );
  1556. expect(app.runtime.applyWorkspaceFileRewind).toHaveBeenCalledWith({
  1557. targetMessageIds: ["msg-a1", "msg-a2"],
  1558. targetTurnId: "turn-3",
  1559. });
  1560. expect(app.submitPrompt).not.toHaveBeenCalled();
  1561. expect(result).toMatchObject({
  1562. type: "applyFileRewind",
  1563. applied: true,
  1564. response: "Rewound 2 files from summary checkpoints.",
  1565. });
  1566. });
  1567. it("handler 不按 activeAbortController 二次拒绝 resolver 已授权的文件撤销", async () => {
  1568. const app = makeApp({
  1569. runtime: {
  1570. applyWorkspaceFileRewind: vi.fn().mockResolvedValue({
  1571. applied: false,
  1572. response: "no changes",
  1573. preview: { canApply: false, safeFiles: [], unsafeFiles: [], ignoredFiles: [] },
  1574. }),
  1575. },
  1576. });
  1577. const record = makeRecord({
  1578. app,
  1579. activeAbortController: new AbortController(),
  1580. });
  1581. const host = makeHost(record, {
  1582. getMessageIdsForTurnRow: () => ["msg-a1"],
  1583. });
  1584. await expect(
  1585. new V4CommandExecutor(host).execute(
  1586. envelope("applyFileRewind", {
  1587. target: { rowId: 3, entityId: "entity-3" },
  1588. }),
  1589. ),
  1590. ).resolves.toMatchObject({ type: "applyFileRewind" });
  1591. expect(app.runtime.applyWorkspaceFileRewind).toHaveBeenCalledTimes(1);
  1592. });
  1593. });
  1594. it("history edit retains the original Gen UI snapshot with the changed text", async () => {
  1595. const app = makeApp();
  1596. const target = attachmentEditTarget();
  1597. const genUiContext = [{ path: "/project/page.html", state: "ORIGINAL_STATE" }];
  1598. const host = makeHost(makeRecord({ app }), {
  1599. resolveRowActionTarget: () => ({
  1600. ...target,
  1601. editTarget: {
  1602. ...target.editTarget,
  1603. intent: { kind: "sendText", text: "Original", genUiContext },
  1604. },
  1605. }),
  1606. });
  1607. await new V4CommandExecutor(host).execute(
  1608. envelope("editUserQuery", {
  1609. target: { rowId: 7, entityId: "entity-7" },
  1610. newText: "Changed",
  1611. }),
  1612. );
  1613. await settle();
  1614. expect(app.sendInput).toHaveBeenCalledWith(
  1615. { text: "Changed" },
  1616. expect.objectContaining({
  1617. intent: expect.objectContaining({ genUiContext }),
  1618. }),
  1619. );
  1620. });