|
| 1 | +import { describe, expect, it, vi } from "vitest"; |
| 2 | +import { createEmbeddedRunReplayState, type EmbeddedRunReplayState } from "./replay-state.js"; |
| 3 | +import { normalizeEmbeddedRunAttempt } from "./run/attempt-normalization.js"; |
| 4 | +import { createEmbeddedRunContextRecoveryState } from "./run/context-recovery-state.js"; |
| 5 | +import { createIdleTimeoutBreakerState } from "./run/idle-timeout-breaker.js"; |
| 6 | +import type { EmbeddedRunAttemptResult } from "./run/types.js"; |
| 7 | +import { createUsageAccumulator } from "./usage-accumulator.js"; |
| 8 | + |
| 9 | +function makeAttempt( |
| 10 | + preflightRecovery?: EmbeddedRunAttemptResult["preflightRecovery"], |
| 11 | +): EmbeddedRunAttemptResult { |
| 12 | + return { |
| 13 | + terminal: { kind: "ok" }, |
| 14 | + preflightRecovery, |
| 15 | + sessionIdUsed: "session-1", |
| 16 | + messagesSnapshot: [], |
| 17 | + assistantTexts: [], |
| 18 | + toolMetas: [], |
| 19 | + lastAssistant: undefined, |
| 20 | + didSendViaMessagingTool: false, |
| 21 | + messagingToolSentTexts: [], |
| 22 | + messagingToolSentMediaUrls: [], |
| 23 | + messagingToolSentTargets: [], |
| 24 | + cloudCodeAssistFormatError: false, |
| 25 | + replayMetadata: { hadPotentialSideEffects: false, replaySafe: true }, |
| 26 | + itemLifecycle: { startedCount: 0, completedCount: 0, activeCount: 0 }, |
| 27 | + }; |
| 28 | +} |
| 29 | + |
| 30 | +function makePromptState(options: { waitForPersistence?: () => Promise<void> } = {}) { |
| 31 | + const activePrompt = { persisted: false, internal: false }; |
| 32 | + const state = { |
| 33 | + sessionId: "session-1", |
| 34 | + sessionFile: "agent:main:main", |
| 35 | + sessionTarget: { |
| 36 | + agentId: "main", |
| 37 | + sessionId: "session-1", |
| 38 | + sessionKey: "agent:main:main", |
| 39 | + storePath: "/tmp/sessions.json", |
| 40 | + }, |
| 41 | + activePrompt, |
| 42 | + suppressNextUserMessagePersistence: false, |
| 43 | + adoptSessionId: vi.fn(), |
| 44 | + waitForCurrentUserMessagePersistence: vi.fn( |
| 45 | + options.waitForPersistence ?? (async () => undefined), |
| 46 | + ), |
| 47 | + continueFromCurrentTranscript: vi.fn(), |
| 48 | + }; |
| 49 | + return state; |
| 50 | +} |
| 51 | + |
| 52 | +function makeNormalizationInput( |
| 53 | + attempt: EmbeddedRunAttemptResult, |
| 54 | + sessionPromptState: ReturnType<typeof makePromptState>, |
| 55 | + replayState: EmbeddedRunReplayState = createEmbeddedRunReplayState(), |
| 56 | +): Parameters<typeof normalizeEmbeddedRunAttempt>[0] { |
| 57 | + return { |
| 58 | + runInput: { |
| 59 | + runParams: { |
| 60 | + sessionId: "session-1", |
| 61 | + sessionFile: "agent:main:main", |
| 62 | + config: {}, |
| 63 | + }, |
| 64 | + laneController: { throwIfAborted: vi.fn() }, |
| 65 | + fallbackConfigured: false, |
| 66 | + startedAtMs: Date.now(), |
| 67 | + resolvedSessionKey: "agent:main:main", |
| 68 | + } as never, |
| 69 | + preparedRuntime: { |
| 70 | + nativeModelOwned: false, |
| 71 | + model: { id: "gpt-5.6-luna" }, |
| 72 | + attemptAuthProfileStore: { profiles: {} }, |
| 73 | + snapshot: () => ({ |
| 74 | + effectiveModel: { provider: "openai", id: "gpt-5.6-luna" }, |
| 75 | + outerContextTokenMeta: {}, |
| 76 | + lastProfileId: undefined, |
| 77 | + }), |
| 78 | + } as never, |
| 79 | + dispatchedAttempt: { rawAttempt: attempt, cancellationRequested: false } as never, |
| 80 | + sessionPromptState: sessionPromptState as never, |
| 81 | + provider: "openai", |
| 82 | + modelId: "gpt-5.6-luna", |
| 83 | + bootstrapPromptWarningSignaturesSeen: [], |
| 84 | + usageAccumulator: createUsageAccumulator(), |
| 85 | + lastRunPromptUsage: undefined, |
| 86 | + idleTimeoutBreakerState: createIdleTimeoutBreakerState(), |
| 87 | + contextRecoveryState: createEmbeddedRunContextRecoveryState(), |
| 88 | + replayState, |
| 89 | + lastRetryFailoverReason: null, |
| 90 | + }; |
| 91 | +} |
| 92 | + |
| 93 | +describe("normalizeEmbeddedRunAttempt", () => { |
| 94 | + it("waits for pending user-turn persistence before deriving retry suppression", async () => { |
| 95 | + let releasePersistence: (() => void) | undefined; |
| 96 | + const persistence = new Promise<void>((resolve) => { |
| 97 | + releasePersistence = resolve; |
| 98 | + }); |
| 99 | + const state = makePromptState({ |
| 100 | + waitForPersistence: async () => { |
| 101 | + await persistence; |
| 102 | + state.activePrompt.persisted = true; |
| 103 | + }, |
| 104 | + }); |
| 105 | + let settled = false; |
| 106 | + |
| 107 | + const resultPromise = normalizeEmbeddedRunAttempt( |
| 108 | + makeNormalizationInput(makeAttempt(), state), |
| 109 | + ).then((result) => { |
| 110 | + settled = true; |
| 111 | + return result; |
| 112 | + }); |
| 113 | + |
| 114 | + await Promise.resolve(); |
| 115 | + expect(state.waitForCurrentUserMessagePersistence).toHaveBeenCalledOnce(); |
| 116 | + expect(settled).toBe(false); |
| 117 | + expect(state.suppressNextUserMessagePersistence).toBe(false); |
| 118 | + |
| 119 | + releasePersistence?.(); |
| 120 | + const result = await resultPromise; |
| 121 | + |
| 122 | + expect(result.action).toBe("proceed"); |
| 123 | + expect(state.suppressNextUserMessagePersistence).toBe(true); |
| 124 | + }); |
| 125 | + |
| 126 | + it("retries the original prompt after handled preflight truncation", async () => { |
| 127 | + const state = makePromptState(); |
| 128 | + |
| 129 | + const result = await normalizeEmbeddedRunAttempt( |
| 130 | + makeNormalizationInput( |
| 131 | + makeAttempt({ |
| 132 | + route: "truncate_tool_results_only", |
| 133 | + handled: true, |
| 134 | + truncatedCount: 2, |
| 135 | + }), |
| 136 | + state, |
| 137 | + ), |
| 138 | + ); |
| 139 | + |
| 140 | + expect(result.action).toBe("retry"); |
| 141 | + expect(state.continueFromCurrentTranscript).not.toHaveBeenCalled(); |
| 142 | + }); |
| 143 | + |
| 144 | + it("continues from the current transcript after handled mid-turn truncation", async () => { |
| 145 | + const state = makePromptState(); |
| 146 | + |
| 147 | + const result = await normalizeEmbeddedRunAttempt( |
| 148 | + makeNormalizationInput( |
| 149 | + makeAttempt({ |
| 150 | + route: "truncate_tool_results_only", |
| 151 | + source: "mid-turn", |
| 152 | + handled: true, |
| 153 | + truncatedCount: 2, |
| 154 | + }), |
| 155 | + state, |
| 156 | + ), |
| 157 | + ); |
| 158 | + |
| 159 | + expect(result.action).toBe("retry"); |
| 160 | + expect(state.continueFromCurrentTranscript).toHaveBeenCalledOnce(); |
| 161 | + }); |
| 162 | + |
| 163 | + it("keeps replay state unsafe after a later clean attempt", async () => { |
| 164 | + const state = makePromptState(); |
| 165 | + const dirty = await normalizeEmbeddedRunAttempt( |
| 166 | + makeNormalizationInput( |
| 167 | + { |
| 168 | + ...makeAttempt(), |
| 169 | + replayMetadata: { replaySafe: false, hadPotentialSideEffects: true }, |
| 170 | + }, |
| 171 | + state, |
| 172 | + ), |
| 173 | + ); |
| 174 | + if (dirty.action !== "proceed") { |
| 175 | + throw new Error(`expected dirty attempt to proceed, got ${dirty.action}`); |
| 176 | + } |
| 177 | + |
| 178 | + const clean = await normalizeEmbeddedRunAttempt( |
| 179 | + makeNormalizationInput( |
| 180 | + { |
| 181 | + ...makeAttempt(), |
| 182 | + replayMetadata: { replaySafe: true, hadPotentialSideEffects: false }, |
| 183 | + }, |
| 184 | + state, |
| 185 | + dirty.replayState, |
| 186 | + ), |
| 187 | + ); |
| 188 | + |
| 189 | + if (clean.action !== "proceed") { |
| 190 | + throw new Error(`expected clean attempt to proceed, got ${clean.action}`); |
| 191 | + } |
| 192 | + expect(clean.replayState).toEqual({ replayInvalid: true, hadPotentialSideEffects: true }); |
| 193 | + }); |
| 194 | +}); |
0 commit comments