| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493 |
- // L2:fork/edit/retry 命令组(M4 最后一组)。
- // 语义要点(08-phasing M4 完成定义的 L2 层):
- // - rowId→messageId 翻译是原生决策:翻译不到 reject(绝不静默兜底 latestCheckpoint);
- // - editUserQuery = core branch cut + 原生 prompt turn 重发新文本;
- // - retryTurn = 原文在 rewind **之前**解析(截断后 transcript 已无该消息)+ 截断 + 重发;
- // 原文解析不到只截断不重发;
- // - latest real user query running 时先 stop active turn,再 rewind + rerun;
- // - 历史 user query 直接拒绝,且不打断当前 active turn;
- // - retry 只允许全时间线最后一条 assistant 回复,历史回复直接拒绝;
- // - forkAssistant 经过 stable resolver 后走 conversation-only fork,result 带 forkedSessionId。
- import { describe, expect, it, vi } from "vitest";
- import { RewindStrategy, SessionEventType } from "@zcode/contracts";
- import type { CommandEnvelope } from "@zcode/shared/zcode-protocol-v4";
- import { V4CommandExecutor } from "../src/zcode-protocol-v4/commands/executor.js";
- import {
- V4EditTargetNotLatestError,
- V4RetryTargetNotLatestError,
- V4RowTranslationError,
- } from "../src/zcode-protocol-v4/commands/handlers/fork-edit-retry.js";
- import type {
- V4CommandCoreHost,
- V4SessionRecordView,
- } from "../src/zcode-protocol-v4/commands/types.js";
- function makeApp(overrides: Record<string, unknown> = {}) {
- const runtimeOverrides =
- typeof overrides.runtime === "object" && overrides.runtime !== null ? overrides.runtime : {};
- return {
- sessionId: "s1",
- sendInput: vi.fn().mockImplementation(async (_input, options) => {
- options?.onTurnStartedObserved?.({
- id: "event-started",
- type: SessionEventType.TurnStarted,
- payload: { messageId: "msg-event-started" },
- });
- return {
- completion: Promise.resolve({}),
- kind: "started_turn",
- turnId: "turn-1",
- };
- }),
- submitPrompt: vi.fn().mockResolvedValue({}),
- steerTurn: vi.fn().mockResolvedValue({}),
- readTarget: vi.fn().mockResolvedValue(null),
- updateTargetStatus: vi.fn().mockResolvedValue(null),
- ...overrides,
- runtime: {
- rewindConversationToMessage: vi.fn().mockResolvedValue({
- strategy: RewindStrategy.ActiveChain,
- }),
- ...runtimeOverrides,
- },
- };
- }
- function makeRecord(
- overrides: Partial<V4SessionRecordView> & { app?: ReturnType<typeof makeApp> } = {},
- ): V4SessionRecordView {
- return {
- app: (overrides.app ?? makeApp()) as unknown as V4SessionRecordView["app"],
- traceContext: { traceId: "trace-1", sessionId: "s1" } as never,
- workspace: { workspacePath: "/w" },
- persistence: "immediate",
- ...overrides,
- } as V4SessionRecordView;
- }
- function makeHost(
- record: V4SessionRecordView,
- overrides: Partial<V4CommandCoreHost> = {},
- ): V4CommandCoreHost {
- const host: V4CommandCoreHost = {
- getRecord: (id) => (id === "s1" ? record : undefined),
- isLatestEditableUserRow: () => true,
- isLatestRetryAssistantRow: () => true,
- waitForProjectionEventCommit: async () => {},
- ...overrides,
- };
- host.resolveRowActionTarget ??= (_sessionId, target, action) => {
- if (action === "editUserQuery") {
- if (host.isLatestEditableUserRow?.("s1", target.rowId) !== true) {
- return {
- ok: false,
- status: "rejected",
- reasonCode: "guard.actionUnavailable",
- };
- }
- const transcriptMessageId = host.getTurnRewindAnchor?.("s1", target.rowId);
- if (!transcriptMessageId) {
- return {
- ok: false,
- status: "rejected",
- reasonCode: "guard.actionUnavailable",
- };
- }
- return {
- ok: true,
- action,
- row: {} as never,
- editTarget: {
- entityId: target.entityId,
- productTurnId: `turn-${target.rowId}`,
- transcriptMessageId,
- coveredByStableCompact: false,
- intent: { kind: "sendText", text: "原始问题" },
- },
- };
- }
- if (action === "retryTurn") {
- const messageId = host.getMessageIdForRow?.("s1", target.rowId);
- if (host.isLatestRetryAssistantRow?.("s1", target.rowId) !== true || !messageId) {
- return {
- ok: false,
- status: "rejected",
- reasonCode: "guard.actionUnavailable",
- };
- }
- return {
- ok: true,
- action,
- row: {} as never,
- messageId,
- editTarget: {
- entityId: `user-${target.entityId}`,
- productTurnId: `turn-${target.rowId}`,
- transcriptMessageId: `user-${messageId}`,
- coveredByStableCompact: false,
- intent: { kind: "sendText", text: "原始问题" },
- },
- };
- }
- if (action === "applyFileRewind") {
- return {
- ok: true,
- action,
- row: {
- turnId: host.getTurnIdForRow?.("s1", target.rowId) ?? `turn-${target.rowId}`,
- } as never,
- messageIds: host.getMessageIdsForTurnRow?.("s1", target.rowId) ?? [],
- };
- }
- return {
- ok: true,
- action,
- row: {} as never,
- messageId: `msg-${target.rowId}`,
- };
- };
- return host;
- }
- function envelope(type: string, payload: unknown): CommandEnvelope {
- return {
- type,
- payload,
- sessionId: "s1",
- commandId: "cmd-1",
- baseRevision: 0,
- baseLogEpoch: "epoch-1",
- clientId: "client-new",
- } as unknown as CommandEnvelope;
- }
- async function settle() {
- // 原生 prompt turn 是 void 起跑的微任务链,flush 两轮保证 finally 执行完。
- await new Promise((r) => setTimeout(r, 0));
- await new Promise((r) => setTimeout(r, 0));
- }
- /**
- * 加速轮的协议原形:Selection 指向隐藏的加速卡内建 Provider(端点/能力都由 Provider Config
- * 提供),只有卡 JWT 与卡 ID 作为本次执行的动态鉴权随 modelExecution 下发。
- */
- const HIGHSPEED_MODEL_SELECTION = {
- providerId: "account:bigmodel-highspeed-card",
- modelId: "GLM-5.3",
- };
- const HIGHSPEED_MODEL_EXECUTION = {
- selectionScope: "execution" as const,
- requestAuth: {
- apiKey: "card-edit-jwt",
- headers: { Authorization: "Bearer card-edit-jwt", "X-Highspeed-Card-ID": "card-edit" },
- },
- selectionFallback: {
- providerId: "account:bigmodel-highspeed-card",
- rules: [
- { reason: "highspeed_card_expired" as const, providerErrorCode: "3402" },
- { reason: "highspeed_request_failed" as const },
- ],
- },
- };
- const originalEditAttachments = [
- {
- ref: "/work/first.txt",
- fileName: "first.txt",
- mime: "text/plain",
- bytes: 12,
- },
- {
- ref: "/work/second.txt",
- fileName: "second.txt",
- mime: "text/plain",
- bytes: 24,
- },
- ];
- function attachmentEditTarget() {
- return {
- ok: true as const,
- action: "editUserQuery" as const,
- row: { rowId: 7, turnId: "turn-7" } as never,
- editTarget: {
- entityId: "entity-7",
- productTurnId: "turn-7",
- transcriptMessageId: "msg-user",
- coveredByStableCompact: false,
- intent: {
- kind: "sendText" as const,
- text: "原始问题",
- attachments: originalEditAttachments,
- },
- },
- };
- }
- describe("v4 原生 editUserQuery", () => {
- it("正路径:rewind 截断(同 turn assistant 锚点)后原生 turn 重发新文本", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const info = vi.fn();
- const host = makeHost(record, {
- getTurnRewindAnchor: (sessionId, rowId) =>
- sessionId === "s1" && rowId === 7 ? "msg-a" : null,
- logger: { info },
- });
- await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "改过的问题",
- }),
- );
- await settle();
- expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageId: "msg-a" }),
- );
- // 重发走原生 prompt turn(sendInput),inputId=commandId 权威锚点。
- expect(app.sendInput).toHaveBeenCalledWith(
- { text: "改过的问题" },
- expect.objectContaining({ inputId: "cmd-1" }),
- );
- // 顺序:先截断后重发。
- expect(app.runtime.rewindConversationToMessage.mock.invocationCallOrder[0]).toBeLessThan(
- app.sendInput.mock.invocationCallOrder[0],
- );
- expect(info).toHaveBeenCalledWith(
- "v4 editUserQuery completed",
- expect.objectContaining({
- attachmentCount: 0,
- clientId: "client-new",
- commandId: "cmd-1",
- event: "conversation.command.edit_user_query.completed",
- intentKind: "sendText",
- sessionId: "s1",
- status: "completed",
- targetEntityId: "entity-7",
- targetRowId: 7,
- traceId: "trace-1",
- workspaceMode: "preserve",
- }),
- );
- const editLogFields = info.mock.calls.find(
- ([message]) => message === "v4 editUserQuery completed",
- )?.[1];
- expect(editLogFields).not.toHaveProperty("newText");
- expect(editLogFields).not.toHaveProperty("text");
- });
- it("编辑重发会应用本次新准备的 Highspeed Selection 与执行材料", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const highspeedMeta = {
- schemaVersion: 1 as const,
- cardId: "card-edit",
- taskId: "s1",
- provider: "bigmodel",
- model: "GLM-5.3",
- issuedAt: 1,
- expiresAt: Date.now() + 60_000,
- };
- const host = makeHost(record, { getTurnRewindAnchor: () => "msg-user" });
- await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "改过的问题",
- highspeedMeta,
- modelSelection: HIGHSPEED_MODEL_SELECTION,
- modelExecution: HIGHSPEED_MODEL_EXECUTION,
- }),
- );
- await settle();
- // Selection 可投影(要进 intent 让 transcript 复原时知道这轮走了加速 Provider)。
- expect(app.sendInput).toHaveBeenCalledWith(
- { text: "改过的问题" },
- expect.objectContaining({
- intent: expect.objectContaining({
- highspeed: highspeedMeta,
- modelSelection: HIGHSPEED_MODEL_SELECTION,
- }),
- }),
- );
- const options = app.sendInput.mock.calls[0]?.[1];
- expect(options.modelExecution.selectionScope).toBe("execution");
- expect(options.modelExecution.selectionFallback).toEqual(
- HIGHSPEED_MODEL_EXECUTION.selectionFallback,
- );
- // 卡 JWT 只能作为本轮执行依赖惰性解析,绝不能进入可持久化的 intent。
- await expect(
- options.modelExecution.requestDependencies.requestAuth.source.resolve(),
- ).resolves.toEqual(HIGHSPEED_MODEL_EXECUTION.requestAuth);
- expect(options.intent).not.toHaveProperty("modelExecution");
- });
- it("卡已过期的编辑重发退回会话常驻 Selection,不保留无鉴权的加速 Selection", async () => {
- // CR-01 回归:被编辑的那轮是 Highspeed 轮,canonical intent 里留着 account:*-highspeed-card;
- // 本次没有有效新卡(已过期),旧实现只是不传 modelExecution 却沿用该 Selection,Core 会以
- // ModelRequestAuthMissing 失败,且该 Selection 被固定进新 intent,污染后续普通发送。
- const setModel = vi.fn();
- const app = makeApp({ getModel: () => "builtin:bigmodel-coding-plan/GLM-5.3", setModel });
- const record = makeRecord({ app });
- const host = makeHost(record, {
- resolveRowActionTarget: () => ({
- ok: true,
- action: "editUserQuery",
- row: {} as never,
- editTarget: {
- entityId: "entity-7",
- productTurnId: "turn-7",
- transcriptMessageId: "msg-user",
- coveredByStableCompact: false,
- intent: {
- kind: "sendText",
- text: "原始问题",
- modelSelection: HIGHSPEED_MODEL_SELECTION,
- },
- },
- }),
- });
- await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "改过的问题",
- highspeedMeta: {
- schemaVersion: 1 as const,
- cardId: "card-edit",
- taskId: "s1",
- provider: "bigmodel",
- model: "GLM-5.3",
- issuedAt: 1,
- expiresAt: Date.now() - 1,
- },
- modelSelection: HIGHSPEED_MODEL_SELECTION,
- modelExecution: HIGHSPEED_MODEL_EXECUTION,
- }),
- );
- await settle();
- const options = app.sendInput.mock.calls[0]?.[1];
- expect(options.intent.modelSelection).toEqual({
- providerId: "builtin:bigmodel-coding-plan",
- modelId: "GLM-5.3",
- });
- expect(options.intent).not.toHaveProperty("highspeed");
- expect(options).not.toHaveProperty("modelExecution");
- // 只改本轮 intent,不改 session 常驻模型。
- expect(setModel).not.toHaveBeenCalled();
- });
- it("Highspeed admission 遇到收口竞态时保留编辑文本并进入队列", async () => {
- const app = makeApp({
- sendInput: vi.fn().mockImplementation(async (_input, options) => {
- if (options?.requireQueue) {
- return { kind: "queued", queueItemId: "queue-edited" };
- }
- return { kind: "rejected", reason: "turn_not_steerable" };
- }),
- });
- const record = makeRecord({ app });
- const highspeedMeta = {
- schemaVersion: 1 as const,
- cardId: "card-edit",
- taskId: "s1",
- provider: "bigmodel",
- model: "GLM-5.3",
- issuedAt: 1,
- expiresAt: Date.now() + 60_000,
- };
- const host = makeHost(record, {
- getTurnRewindAnchor: () => "msg-user",
- retainQueuedTurnExecution: vi.fn(),
- deleteQueuedTurnExecution: vi.fn(),
- });
- await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "竞态下的新问题",
- highspeedMeta,
- modelSelection: HIGHSPEED_MODEL_SELECTION,
- modelExecution: HIGHSPEED_MODEL_EXECUTION,
- }),
- );
- expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageId: "msg-user" }),
- );
- expect(app.sendInput).toHaveBeenNthCalledWith(
- 1,
- { text: "竞态下的新问题" },
- expect.objectContaining({
- modelExecution: expect.objectContaining({ selectionScope: "execution" }),
- }),
- );
- // 入队路径不能把凭据交给 turn(此时还没有 turn),只投影 Selection + 卡元数据。
- expect(app.sendInput).toHaveBeenNthCalledWith(
- 2,
- { text: "竞态下的新问题" },
- expect.objectContaining({
- requireQueue: true,
- intent: expect.objectContaining({
- highspeed: highspeedMeta,
- modelSelection: HIGHSPEED_MODEL_SELECTION,
- }),
- }),
- );
- expect(app.sendInput.mock.calls[1]?.[1]).not.toHaveProperty("modelExecution");
- // 凭据改由宿主按 commandId 暂存在内存,提升队列项时再冻结成执行上下文。
- expect(host.retainQueuedTurnExecution).toHaveBeenCalledWith(
- "s1",
- "cmd-1",
- HIGHSPEED_MODEL_EXECUTION,
- );
- });
- it("attachments 缺省时稳定保留 canonical 原 refs", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
- await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "只改正文",
- }),
- );
- await settle();
- expect(app.sendInput).toHaveBeenCalledWith(
- {
- text: "只改正文",
- attachments: [
- expect.objectContaining({ path: "/work/first.txt" }),
- expect.objectContaining({ path: "/work/second.txt" }),
- ],
- },
- expect.objectContaining({
- intent: expect.objectContaining({ attachmentRefs: originalEditAttachments }),
- }),
- );
- });
- it("仅附件 edit 使用新数组替换原 refs,并保持剩余顺序", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
- await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "",
- attachments: [originalEditAttachments[1]],
- }),
- );
- await settle();
- expect(app.sendInput).toHaveBeenCalledWith(
- {
- text: "",
- attachments: [expect.objectContaining({ path: "/work/second.txt" })],
- },
- expect.objectContaining({
- intent: expect.objectContaining({ attachmentRefs: [originalEditAttachments[1]] }),
- }),
- );
- });
- it("显式 [] 清空原 refs,而不是恢复 canonical attachments", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
- await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "保留正文",
- attachments: [],
- }),
- );
- await settle();
- expect(app.sendInput).toHaveBeenCalledWith(
- { text: "保留正文" },
- expect.objectContaining({
- intent: expect.objectContaining({ attachmentRefs: [] }),
- }),
- );
- });
- it("正文与显式附件数组都为空时在 branch cut 前拒绝", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const host = makeHost(record, { resolveRowActionTarget: attachmentEditTarget });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: " ",
- attachments: [],
- }),
- ),
- ).rejects.toMatchObject({ reasonCode: "proto.invalidPayload" });
- expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
- expect(app.sendInput).not.toHaveBeenCalled();
- });
- it("workspaceMode=rewind:安全文件先恢复,再提交 branch cut 并原 session 重发", async () => {
- const previewWorkspaceFileRewind = vi.fn().mockResolvedValue({
- canApply: true,
- safeFiles: [{ action: "restore", operationCount: 1, path: "/w/a.ts", toolNames: ["Edit"] }],
- unsafeFiles: [],
- ignoredFiles: [],
- });
- const applyWorkspaceFileRewind = vi.fn().mockImplementation(async (options) => {
- await options.commitAfterApply();
- return {
- applied: true,
- response: "ok",
- preview: await previewWorkspaceFileRewind(),
- };
- });
- const app = makeApp({ runtime: { previewWorkspaceFileRewind, applyWorkspaceFileRewind } });
- const record = makeRecord({ app });
- const host = makeHost(record, {
- getMessageIdsForTurnRow: () => ["msg-user", "msg-assistant"],
- resolveRowActionTarget: () => ({
- ok: true,
- action: "editUserQuery",
- row: { rowId: 7, turnId: "turn-7" } as never,
- editTarget: {
- entityId: "entity-7",
- productTurnId: "turn-7",
- transcriptMessageId: "msg-user",
- coveredByStableCompact: true,
- intent: { kind: "sendText", text: "old" },
- },
- }),
- });
- const result = await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "edited",
- workspaceMode: "rewind",
- }),
- );
- expect(previewWorkspaceFileRewind).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageIds: ["msg-user", "msg-assistant"] }),
- );
- expect(applyWorkspaceFileRewind).toHaveBeenCalledWith(
- expect.objectContaining({ commitAfterApply: expect.any(Function) }),
- );
- expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageId: "msg-user" }),
- );
- expect(result).toEqual({ type: "editUserQuery", disposition: "rewind", sessionId: "s1" });
- });
- it("workspaceMode=rewind:unsafe/ignored 结构化 blocked,不裁对话也不发模型请求", async () => {
- const preview = {
- canApply: false,
- safeFiles: [],
- unsafeFiles: [
- {
- operationCount: 1,
- path: "/w/a.ts",
- reason: "external_modified",
- toolNames: ["Edit"],
- },
- ],
- ignoredFiles: [],
- } as const;
- const previewWorkspaceFileRewind = vi.fn().mockResolvedValue(preview);
- const applyWorkspaceFileRewind = vi.fn();
- const app = makeApp({ runtime: { previewWorkspaceFileRewind, applyWorkspaceFileRewind } });
- const record = makeRecord({ app });
- const cancelInputCommand = vi.fn().mockResolvedValue(undefined);
- const host = makeHost(record, {
- cancelInputCommand,
- resolveRowActionTarget: () => ({
- ok: true,
- action: "editUserQuery",
- row: { rowId: 7, turnId: "turn-7" } as never,
- editTarget: {
- entityId: "entity-7",
- productTurnId: "turn-7",
- transcriptMessageId: "msg-user",
- coveredByStableCompact: false,
- intent: { kind: "sendText", text: "old" },
- },
- }),
- });
- const result = await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "edited",
- workspaceMode: "rewind",
- }),
- );
- expect(result).toEqual({
- type: "editUserQuery",
- disposition: "blocked",
- sessionId: "s1",
- reasonCode: "guard.workspaceRewindUnsafeFiles",
- preview,
- });
- expect(cancelInputCommand).toHaveBeenCalledWith(
- "s1",
- "queue_cmd-1",
- "guard.workspaceRewindUnsafeFiles",
- );
- expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
- expect(app.sendInput).not.toHaveBeenCalled();
- expect(applyWorkspaceFileRewind).not.toHaveBeenCalled();
- });
- it("翻译不到锚点:reject,不静默兜底", async () => {
- const record = makeRecord();
- const info = vi.fn();
- const host = makeHost(record, {
- getTurnRewindAnchor: () => null,
- logger: { info },
- resolveUserMessageIdForRow: async () => null,
- });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 99, entityId: "entity-99" },
- newText: "x",
- }),
- ),
- ).rejects.toThrow(V4EditTargetNotLatestError);
- expect(info).not.toHaveBeenCalledWith("v4 editUserQuery completed", expect.anything());
- });
- it("无 assistant anchor 时回查 user messageId 作为 rewind 锚点", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const host = makeHost(record, {
- getTurnRewindAnchor: (_sessionId, rowId) => (rowId === 7 ? "msg-user-7" : null),
- });
- await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "改过的问题",
- }),
- );
- await settle();
- expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageId: "msg-user-7" }),
- );
- expect(app.sendInput).toHaveBeenCalledWith(
- { text: "改过的问题" },
- expect.objectContaining({ inputId: "cmd-1" }),
- );
- });
- it("running latest query:abort → idle → rewind → rerun", async () => {
- const calls: string[] = [];
- const app = makeApp({
- runtime: {
- rewindConversationToMessage: vi.fn().mockImplementation(async () => {
- calls.push("rewind");
- return { strategy: RewindStrategy.ActiveChain };
- }),
- getActiveTurnInfo: vi
- .fn()
- .mockReturnValueOnce({ turnId: "turn-old" })
- .mockReturnValue(undefined),
- },
- sendInput: vi.fn().mockImplementation(async (_input, options) => {
- calls.push("rerun");
- options?.onTurnStartedObserved?.({
- id: "event-started",
- type: SessionEventType.TurnStarted,
- payload: { messageId: "msg-event-started" },
- });
- return {};
- }),
- });
- const controller = new AbortController();
- controller.signal.addEventListener("abort", () => {
- calls.push("abort");
- setTimeout(() => {
- calls.push("idle");
- record.activeAbortController = undefined;
- }, 0);
- });
- const record = makeRecord({ app, activeAbortController: controller });
- const host = makeHost(record, {
- getTurnRewindAnchor: () => "msg-a",
- isLatestEditableUserRow: () => true,
- });
- await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "改过的问题",
- }),
- );
- await settle();
- expect(calls).toEqual(["abort", "idle", "rewind", "rerun"]);
- expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageId: "msg-a" }),
- );
- });
- it("runtime-only active turn:没有 Bootstrap controller 也必须先 stop 再 rewind", async () => {
- const calls: string[] = [];
- const app = makeApp({
- runtime: {
- getActiveTurnInfo: vi
- .fn()
- .mockReturnValueOnce({ turnId: "turn-old" })
- .mockReturnValue(undefined),
- stopActiveForegroundExecution: vi.fn().mockImplementation(() => {
- calls.push("stop");
- return { kind: "stopped", foregroundExecutionId: "foreground-old" };
- }),
- rewindConversationToMessage: vi.fn().mockImplementation(async () => {
- calls.push("rewind");
- return { strategy: RewindStrategy.ActiveChain };
- }),
- },
- sendInput: vi.fn().mockImplementation(async () => {
- calls.push("rerun");
- return {};
- }),
- });
- const record = makeRecord({ app });
- const host = makeHost(record, { getTurnRewindAnchor: () => "msg-a" });
- await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "runtime-only 编辑",
- }),
- );
- expect(calls).toEqual(["stop", "rewind", "rerun"]);
- expect(app.runtime.stopActiveForegroundExecution).toHaveBeenCalledWith(
- expect.objectContaining({ reason: "v4 editUserQuery preempts active turn" }),
- );
- });
- it("running 历史 user query:直接拒绝,且不 stop 当前 turn", async () => {
- const calls: string[] = [];
- const controller = new AbortController();
- controller.signal.addEventListener("abort", () => {
- calls.push("abort");
- });
- const record = makeRecord({ activeAbortController: controller });
- const host = makeHost(record, {
- getTurnRewindAnchor: () => "msg-a",
- isLatestEditableUserRow: () => false,
- });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "entity-7" },
- newText: "x",
- }),
- ),
- ).rejects.toThrow(V4EditTargetNotLatestError);
- expect(calls).toEqual([]);
- expect(record.activeAbortController).toBe(controller);
- });
- });
- describe("v4 原生 retryTurn", () => {
- it("Task3:从 canonical cause 以新 commandId 重建完整 intent 与 provenance", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const attachment = {
- ref: "/work/spec.md",
- fileName: "spec.md",
- mime: "text/markdown",
- bytes: 12,
- };
- const host = makeHost(record, {
- resolveRowActionTarget: () => ({
- ok: true,
- action: "retryTurn",
- row: {} as never,
- messageId: "msg-assistant",
- editTarget: {
- entityId: "msg-user",
- productTurnId: "turn-product",
- transcriptMessageId: "msg-user",
- coveredByStableCompact: false,
- intent: {
- kind: "sendText",
- text: "original canonical text",
- sourceCommandId: "cmd-original",
- clientId: "client-original",
- queueItemId: "queue-original",
- requestedDelivery: "guide",
- admittedDelivery: "queue",
- fallbackReasonCode: "guide.attachmentsUnsupported",
- modelSelection: {
- providerId: "original-provider",
- modelId: "original-model",
- options: { reasoningLevel: "high" },
- },
- mode: "edit",
- attachments: [attachment],
- },
- },
- }),
- });
- await new V4CommandExecutor(host).execute(
- envelope("retryTurn", {
- target: { rowId: 5, entityId: "msg-assistant" },
- }),
- );
- await settle();
- expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageId: "msg-assistant" }),
- );
- expect(app.sendInput).toHaveBeenCalledWith(
- expect.objectContaining({
- text: "original canonical text",
- attachments: [expect.objectContaining({ path: "/work/spec.md" })],
- }),
- expect.objectContaining({
- inputId: "cmd-1",
- intent: expect.objectContaining({
- sourceCommandId: "cmd-1",
- kind: "sendText",
- text: "original canonical text",
- requestedDelivery: "guide",
- admittedDelivery: "queue",
- fallbackReasonCode: "guide.attachmentsUnsupported",
- modelSelection: {
- providerId: "original-provider",
- modelId: "original-model",
- options: { reasoningLevel: "high" },
- },
- mode: "edit",
- provenance: {
- sourceCommandId: "cmd-original",
- queueItemId: "queue-original",
- clientId: "client-original",
- },
- }),
- }),
- );
- });
- it("retry Highspeed 轮时没有新执行材料,退回会话常驻 Selection 且不改 session 模型", async () => {
- // CR-01 回归:retry 从 canonical intent 复制历史 Selection;Highspeed 轮的 Selection 是
- // account:*-highspeed-card,本次 retry 没有任何执行材料,必须显式改写回会话常驻 Selection。
- const setModel = vi.fn();
- const app = makeApp({ getModel: () => "builtin:bigmodel-coding-plan/GLM-5.3", setModel });
- const record = makeRecord({ app });
- const host = makeHost(record, {
- resolveRowActionTarget: () => ({
- ok: true,
- action: "retryTurn",
- row: {} as never,
- messageId: "msg-assistant",
- editTarget: {
- entityId: "msg-user",
- productTurnId: "turn-product",
- transcriptMessageId: "msg-user",
- coveredByStableCompact: false,
- intent: {
- kind: "sendText",
- text: "accelerated prompt",
- sourceCommandId: "cmd-original",
- modelSelection: HIGHSPEED_MODEL_SELECTION,
- },
- },
- }),
- });
- await new V4CommandExecutor(host).execute(
- envelope("retryTurn", { target: { rowId: 5, entityId: "msg-assistant" } }),
- );
- await settle();
- const options = app.sendInput.mock.calls[0]?.[1];
- expect(options.intent.modelSelection).toEqual({
- providerId: "builtin:bigmodel-coding-plan",
- modelId: "GLM-5.3",
- });
- expect(options.intent).not.toHaveProperty("highspeed");
- expect(options).not.toHaveProperty("modelExecution");
- expect(setModel).not.toHaveBeenCalled();
- });
- it("retry-of-retry 保留最初 provenance,不被中间 retry 的 queue/client 覆盖", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const host = makeHost(record, {
- resolveRowActionTarget: () => ({
- ok: true,
- action: "retryTurn",
- row: {} as never,
- messageId: "msg-retry-assistant",
- editTarget: {
- entityId: "msg-retry-user",
- productTurnId: "turn-retry",
- transcriptMessageId: "msg-retry-user",
- coveredByStableCompact: false,
- intent: {
- kind: "sendText",
- text: "retry canonical text",
- sourceCommandId: "cmd-middle-retry",
- queueItemId: "queue-middle-retry",
- clientId: "client-middle-retry",
- provenance: {
- sourceCommandId: "cmd-original",
- queueItemId: "queue-original",
- clientId: "client-original",
- },
- },
- },
- }),
- });
- await new V4CommandExecutor(host).execute(
- envelope("retryTurn", {
- target: { rowId: 8, entityId: "msg-retry-assistant" },
- }),
- );
- await settle();
- expect(app.sendInput).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- intent: expect.objectContaining({
- sourceCommandId: "cmd-1",
- provenance: {
- sourceCommandId: "cmd-original",
- queueItemId: "queue-original",
- clientId: "client-original",
- },
- }),
- }),
- );
- });
- it("goal retry preserves sendGoalCommand kind", async () => {
- const app = makeApp({
- getMode: vi.fn().mockReturnValue("plan"),
- setTarget: vi.fn().mockResolvedValue({
- targetID: "g1",
- objective: "goal",
- status: "active",
- }),
- });
- const record = makeRecord({ app });
- const host = makeHost(record, {
- resolveRowActionTarget: () => ({
- ok: true,
- action: "retryTurn",
- row: {} as never,
- messageId: "msg-goal-assistant",
- editTarget: {
- entityId: "msg-goal-user",
- productTurnId: "turn-goal",
- transcriptMessageId: "msg-goal-user",
- coveredByStableCompact: false,
- intent: {
- kind: "sendGoalCommand",
- text: "goal",
- sourceCommandId: "cmd-goal-original",
- },
- },
- }),
- });
- await new V4CommandExecutor(host).execute(
- envelope("retryTurn", {
- target: { rowId: 6, entityId: "msg-goal-assistant" },
- }),
- );
- expect(app.setTarget).toHaveBeenCalledWith(
- expect.objectContaining({
- objective: "goal",
- intent: expect.objectContaining({
- kind: "sendGoalCommand",
- sourceCommandId: "cmd-1",
- }),
- }),
- );
- expect(app.sendInput).not.toHaveBeenCalled();
- });
- it("正路径:原文在 rewind 前解析 → 截断 → 重发原 prompt", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const resolveOrder: string[] = [];
- const host = makeHost(record, {
- getMessageIdForRow: (_s, rowId) => (rowId === 5 ? "msg-b" : null),
- resolveTurnUserPrompt: async (_s, messageId) => {
- resolveOrder.push("resolve");
- return messageId === "msg-b" ? "原始问题" : null;
- },
- });
- app.runtime.rewindConversationToMessage.mockImplementation(async () => {
- resolveOrder.push("rewind");
- return { strategy: RewindStrategy.ActiveChain };
- });
- await new V4CommandExecutor(host).execute(
- envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
- );
- await settle();
- // canonical intent 已由 projection resolver 在截断前给出,不再回读 raw transcript 文本。
- expect(resolveOrder).toEqual(["rewind"]);
- expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageId: "msg-b" }),
- );
- expect(app.sendInput).toHaveBeenCalledWith(
- { text: "原始问题" },
- expect.objectContaining({ inputId: "cmd-1" }),
- );
- });
- it("canonical cause 不可解析:直接拒绝且不截断", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const host = makeHost(record, {
- resolveRowActionTarget: () => ({
- ok: false,
- status: "rejected",
- reasonCode: "guard.actionUnavailable",
- }),
- });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
- ),
- ).rejects.toThrow(V4RetryTargetNotLatestError);
- expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
- expect(app.sendInput).not.toHaveBeenCalled();
- });
- it("翻译不到 messageId:reject", async () => {
- const record = makeRecord();
- const host = makeHost(record, { getMessageIdForRow: () => null });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
- ),
- ).rejects.toThrow(V4RetryTargetNotLatestError);
- });
- it("handler 不按 activeAbortController 二次拒绝,而是进入 resolver 授权后的执行路径", async () => {
- const record = makeRecord({ activeAbortController: new AbortController() });
- const host = makeHost(record, { getMessageIdForRow: () => "msg-b" });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
- ),
- ).resolves.toBeUndefined();
- expect(record.app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageId: "msg-b" }),
- );
- expect(record.app.sendInput).toHaveBeenCalled();
- });
- it("非最后一轮 assistant retry 直接拒绝,不解析原文也不 rewind", async () => {
- const app = makeApp();
- const record = makeRecord({ app });
- const resolveTurnUserPrompt = vi.fn().mockResolvedValue("历史问题");
- const host = makeHost(record, {
- getMessageIdForRow: () => "msg-old",
- isLatestRetryAssistantRow: () => false,
- resolveTurnUserPrompt,
- } as Partial<V4CommandCoreHost>);
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("retryTurn", { target: { rowId: 5, entityId: "entity-5" } }),
- ),
- ).rejects.toThrow(V4RetryTargetNotLatestError);
- expect(resolveTurnUserPrompt).not.toHaveBeenCalled();
- expect(app.runtime.rewindConversationToMessage).not.toHaveBeenCalled();
- expect(app.sendInput).not.toHaveBeenCalled();
- });
- });
- describe("v4 Task3 canonical edit disposition", () => {
- it("goal edit rewind 后仍走 goal command,并返回 destination ACK", async () => {
- const app = makeApp({
- getMode: vi.fn().mockReturnValue("plan"),
- setTarget: vi.fn().mockResolvedValue({
- targetID: "g1",
- objective: "new goal",
- status: "active",
- }),
- });
- const record = makeRecord({ app });
- const host = makeHost(record, {
- resolveRowActionTarget: () => ({
- ok: true,
- action: "editUserQuery",
- row: {} as never,
- editTarget: {
- entityId: "msg-goal",
- productTurnId: "turn-goal",
- transcriptMessageId: "msg-goal",
- coveredByStableCompact: false,
- intent: {
- kind: "sendGoalCommand",
- text: "old goal",
- sourceCommandId: "cmd-old-goal",
- },
- },
- }),
- });
- const result = await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "msg-goal" },
- newText: "new goal",
- }),
- );
- expect(app.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageId: "msg-goal" }),
- );
- expect(app.setTarget).toHaveBeenCalledWith(
- expect.objectContaining({
- objective: "new goal",
- intent: expect.objectContaining({
- kind: "sendGoalCommand",
- sourceCommandId: "cmd-1",
- }),
- }),
- );
- expect(app.sendInput).not.toHaveBeenCalled();
- expect(result).toEqual({
- type: "editUserQuery",
- disposition: "rewind",
- sessionId: "s1",
- });
- });
- it("compact-covered latest edit rewinds in the original session and never starts a child", async () => {
- const parentApp = makeApp();
- const childApp = makeApp({ sessionId: "s-child" });
- const parent = makeRecord({ app: parentApp });
- const child = makeRecord({ app: childApp });
- const records = new Map([
- ["s1", parent],
- ["s-child", child],
- ]);
- const forkConversationBeforeInput = vi.fn().mockResolvedValue({
- forkedSessionId: "s-child",
- });
- const host = makeHost(parent, {
- getRecord: (sessionId) => records.get(sessionId),
- forkConversationBeforeInput,
- resolveRowActionTarget: () => ({
- ok: true,
- action: "editUserQuery",
- row: {} as never,
- editTarget: {
- entityId: "msg-user",
- productTurnId: "turn-product",
- transcriptMessageId: "msg-user",
- coveredByStableCompact: true,
- intent: {
- kind: "sendText",
- text: "old text",
- sourceCommandId: "cmd-old",
- },
- },
- }),
- });
- const result = await new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "msg-user" },
- newText: "edited in parent",
- }),
- );
- await settle();
- expect(forkConversationBeforeInput).not.toHaveBeenCalled();
- expect(parentApp.runtime.rewindConversationToMessage).toHaveBeenCalledWith(
- expect.objectContaining({ targetMessageId: "msg-user" }),
- );
- expect(parentApp.sendInput).toHaveBeenCalledWith(
- { text: "edited in parent" },
- expect.objectContaining({ inputId: "cmd-1" }),
- );
- expect(childApp.sendInput).not.toHaveBeenCalled();
- expect(result).toEqual({
- type: "editUserQuery",
- disposition: "rewind",
- sessionId: "s1",
- });
- });
- it("compact edit ignores legacy child failure hooks", async () => {
- const parent = makeRecord({ app: makeApp() });
- const childApp = makeApp({ sessionId: "s-child" });
- const child = makeRecord({
- app: childApp,
- restoreWarning: { message: "model unavailable", type: "model" },
- });
- const recordForkStartFailure = vi.fn().mockResolvedValue(undefined);
- const host = makeHost(parent, {
- getRecord: (sessionId) => (sessionId === "s1" ? parent : child),
- forkConversationBeforeInput: vi.fn().mockResolvedValue({ forkedSessionId: "s-child" }),
- recordForkStartFailure,
- resolveRowActionTarget: () => ({
- ok: true,
- action: "editUserQuery",
- row: {} as never,
- editTarget: {
- entityId: "msg-user",
- productTurnId: "turn-product",
- transcriptMessageId: "msg-user",
- coveredByStableCompact: true,
- intent: { kind: "sendText", text: "old", sourceCommandId: "cmd-old" },
- },
- }),
- });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "msg-user" },
- newText: "edited",
- }),
- ),
- ).resolves.toEqual({
- type: "editUserQuery",
- disposition: "rewind",
- sessionId: "s1",
- });
- expect(parent.app.sendInput).toHaveBeenCalled();
- expect(childApp.sendInput).not.toHaveBeenCalled();
- expect(recordForkStartFailure).not.toHaveBeenCalled();
- });
- it("compact edit remains same-session when legacy child registration is unavailable", async () => {
- const parent = makeRecord({ app: makeApp() });
- const recordForkStartFailure = vi.fn().mockRejectedValue(new Error("failure store offline"));
- const host = makeHost(parent, {
- getRecord: (sessionId) => (sessionId === "s1" ? parent : undefined),
- forkConversationBeforeInput: vi.fn().mockResolvedValue({ forkedSessionId: "s-child" }),
- recordForkStartFailure,
- resolveRowActionTarget: () => ({
- ok: true,
- action: "editUserQuery",
- row: {} as never,
- editTarget: {
- entityId: "msg-user",
- productTurnId: "turn-product",
- transcriptMessageId: "msg-user",
- coveredByStableCompact: true,
- intent: { kind: "sendText", text: "old", sourceCommandId: "cmd-old" },
- },
- }),
- });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("editUserQuery", {
- target: { rowId: 7, entityId: "msg-user" },
- newText: "edited",
- }),
- ),
- ).resolves.toEqual({
- type: "editUserQuery",
- disposition: "rewind",
- sessionId: "s1",
- });
- expect(recordForkStartFailure).not.toHaveBeenCalled();
- });
- });
- describe("v4 原生 forkAssistant", () => {
- const stableTarget = {
- productTurnId: "turn-product-1",
- transcriptTurnId: "turn-runtime-1",
- orderedMessageIds: ["msg-user", "msg-tool", "msg-c"],
- boundaryMessageId: "msg-c",
- };
- const goalBoundary = { kind: "none" as const };
- it("PV4-08:running 时解析稳定 logical turn 后走 conversation-only fork", async () => {
- const record = makeRecord();
- record.activeAbortController = new AbortController();
- const info = vi.fn();
- const resolveStableForkTarget = vi
- .fn()
- .mockResolvedValue({ ok: true, target: stableTarget, goalBoundary });
- const forkStableConversation = vi.fn().mockResolvedValue({ forkedSessionId: "s-fork" });
- const host = makeHost(record, {
- resolveStableForkTarget,
- forkStableConversation,
- logger: { info },
- });
- const result = await new V4CommandExecutor(host).execute(
- envelope("forkAssistant", { target: { rowId: 3, entityId: "entity-3" } }),
- );
- expect(resolveStableForkTarget).toHaveBeenCalledWith("s1", 3);
- expect(forkStableConversation).toHaveBeenCalledWith("s1", {
- target: stableTarget,
- goalBoundary,
- sourceCommandId: "cmd-1",
- revisionAtDecision: 0,
- });
- expect(result).toEqual({ type: "forkAssistant", sessionId: "s-fork" });
- expect(info).toHaveBeenCalledWith(
- "v4 forkAssistant completed",
- expect.objectContaining({
- childSessionId: "s-fork",
- clientId: "client-new",
- commandId: "cmd-1",
- event: "conversation.command.fork_assistant.completed",
- parentSessionId: "s1",
- revisionAtDecision: 0,
- sessionId: "s1",
- status: "completed",
- targetBoundaryMessageId: "msg-c",
- targetEntityId: "entity-3",
- targetRowId: 3,
- traceId: "trace-1",
- }),
- );
- });
- it("目标是 streaming/interrupted/中间段时按稳定 resolver reasonCode 拒绝", async () => {
- const record = makeRecord();
- const info = vi.fn();
- const forkStableConversation = vi.fn();
- const host = makeHost(record, {
- logger: { info },
- resolveStableForkTarget: async () => ({
- ok: false,
- reasonCode: "guard.forkTargetNotStable",
- }),
- forkStableConversation,
- });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("forkAssistant", {
- target: { rowId: 3, entityId: "entity-3" },
- }),
- ),
- ).rejects.toMatchObject({ reasonCode: "guard.forkTargetNotStable" });
- expect(forkStableConversation).not.toHaveBeenCalled();
- expect(info).not.toHaveBeenCalledWith("v4 forkAssistant completed", expect.anything());
- });
- it("stable fork capability 缺失时不回落带 ensureNoActiveTurn 的 legacy bridge", async () => {
- const record = makeRecord();
- const host = makeHost(record, {
- resolveStableForkTarget: async () => ({ ok: true, target: stableTarget, goalBoundary }),
- });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("forkAssistant", {
- target: { rowId: 3, entityId: "entity-3" },
- }),
- ),
- ).rejects.toThrow("forkStableConversation");
- });
- });
- describe("v4 原生 applyFileRewind", () => {
- it("rowId 解析为同 turn messageIds 后只执行 workspace file rewind", async () => {
- const app = makeApp({
- runtime: {
- applyWorkspaceFileRewind: vi.fn().mockResolvedValue({
- applied: true,
- response: "Rewound 2 files from summary checkpoints.",
- preview: {
- canApply: true,
- safeFiles: [
- {
- action: "restore",
- operationCount: 1,
- path: "/work/src/a.ts",
- toolNames: ["Edit"],
- },
- ],
- unsafeFiles: [],
- ignoredFiles: [],
- },
- }),
- },
- });
- const record = makeRecord({ app });
- const host = makeHost(record, {
- getMessageIdsForTurnRow: (sessionId, rowId) =>
- sessionId === "s1" && rowId === 3 ? ["msg-a1", "msg-a2"] : [],
- });
- const result = await new V4CommandExecutor(host).execute(
- envelope("applyFileRewind", {
- target: { rowId: 3, entityId: "entity-3" },
- }),
- );
- expect(app.runtime.applyWorkspaceFileRewind).toHaveBeenCalledWith({
- targetMessageIds: ["msg-a1", "msg-a2"],
- targetTurnId: "turn-3",
- });
- expect(app.submitPrompt).not.toHaveBeenCalled();
- expect(result).toMatchObject({
- type: "applyFileRewind",
- applied: true,
- response: "Rewound 2 files from summary checkpoints.",
- });
- });
- it("handler 不按 activeAbortController 二次拒绝 resolver 已授权的文件撤销", async () => {
- const app = makeApp({
- runtime: {
- applyWorkspaceFileRewind: vi.fn().mockResolvedValue({
- applied: false,
- response: "no changes",
- preview: { canApply: false, safeFiles: [], unsafeFiles: [], ignoredFiles: [] },
- }),
- },
- });
- const record = makeRecord({
- app,
- activeAbortController: new AbortController(),
- });
- const host = makeHost(record, {
- getMessageIdsForTurnRow: () => ["msg-a1"],
- });
- await expect(
- new V4CommandExecutor(host).execute(
- envelope("applyFileRewind", {
- target: { rowId: 3, entityId: "entity-3" },
- }),
- ),
- ).resolves.toMatchObject({ type: "applyFileRewind" });
- expect(app.runtime.applyWorkspaceFileRewind).toHaveBeenCalledTimes(1);
- });
- });
|