|
| 1 | +// Proves the pinned fallback decision survives the complete reply-entry path. |
| 2 | +import path from "node:path"; |
| 3 | +import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; |
| 4 | +import type { MsgContext } from "../auto-reply/templating.js"; |
| 5 | +import { |
| 6 | + clearRuntimeConfigSnapshot, |
| 7 | + setRuntimeConfigSnapshot, |
| 8 | + type OpenClawConfig, |
| 9 | +} from "../config/config.js"; |
| 10 | +import { replaceSessionEntry } from "../config/sessions/session-accessor.js"; |
| 11 | +import { createEmptyPluginRegistry } from "../plugins/registry-empty.js"; |
| 12 | +import type { EmbeddedRunAttemptResult } from "./embedded-agent-runner/run/types.js"; |
| 13 | +import { resetFallbackSkipCacheForTest } from "./fallback-skip-cache.test-support.js"; |
| 14 | +import { |
| 15 | + makeModelFallbackConfig, |
| 16 | + withModelFallbackWorkspace, |
| 17 | + writeFallbackMultiProfileAuthStore, |
| 18 | +} from "./model-fallback.run-embedded.e2e.test-support.js"; |
| 19 | +import { |
| 20 | + buildEmbeddedRunnerAssistant, |
| 21 | + createResolvedEmbeddedRunnerModel, |
| 22 | + makeEmbeddedRunnerAttempt, |
| 23 | +} from "./test-helpers/embedded-agent-runner-e2e-fixtures.js"; |
| 24 | +import { |
| 25 | + installEmbeddedRunnerBackoffE2eMocks, |
| 26 | + installEmbeddedRunnerBaseE2eMocks, |
| 27 | + installEmbeddedRunnerFastRunE2eMocks, |
| 28 | +} from "./test-helpers/embedded-agent-runner-e2e-mocks.js"; |
| 29 | + |
| 30 | +const runEmbeddedAttemptMock = vi.fn<(params: unknown) => Promise<EmbeddedRunAttemptResult>>(); |
| 31 | +const emptyPluginRegistry = createEmptyPluginRegistry(); |
| 32 | +const suspendSessionMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined)); |
| 33 | +const { computeBackoffMock, sleepWithAbortMock } = vi.hoisted(() => ({ |
| 34 | + computeBackoffMock: vi.fn( |
| 35 | + ( |
| 36 | + _policy: { initialMs: number; maxMs: number; factor: number; jitter: number }, |
| 37 | + _attempt: number, |
| 38 | + ) => 321, |
| 39 | + ), |
| 40 | + sleepWithAbortMock: vi.fn(async (_ms: number, _abortSignal?: AbortSignal) => undefined), |
| 41 | +})); |
| 42 | + |
| 43 | +vi.mock("./models-config.js", async () => { |
| 44 | + const mod = await vi.importActual<typeof import("./models-config.js")>("./models-config.js"); |
| 45 | + return { ...mod, ensureOpenClawModelsJson: vi.fn(async () => ({ wrote: false })) }; |
| 46 | +}); |
| 47 | + |
| 48 | +function installReplyEntryMocks() { |
| 49 | + vi.doMock("../plugins/runtime.js", () => ({ |
| 50 | + getActivePluginRegistry: () => null, |
| 51 | + getActivePluginRegistryWorkspaceDir: () => undefined, |
| 52 | + getPluginRegistryForContext: () => emptyPluginRegistry, |
| 53 | + requireActivePluginRegistry: () => emptyPluginRegistry, |
| 54 | + })); |
| 55 | + vi.doMock("./harness/runtime-plugin.js", () => ({ |
| 56 | + ensureSelectedAgentHarnessPlugin: vi.fn(async () => undefined), |
| 57 | + })); |
| 58 | + installEmbeddedRunnerBaseE2eMocks(); |
| 59 | + installEmbeddedRunnerFastRunE2eMocks({ |
| 60 | + runEmbeddedAttempt: (params) => runEmbeddedAttemptMock(params), |
| 61 | + }); |
| 62 | + installEmbeddedRunnerBackoffE2eMocks({ |
| 63 | + computeBackoff: (policy, attempt) => computeBackoffMock(policy, attempt), |
| 64 | + sleepWithAbort: (ms, abortSignal) => sleepWithAbortMock(ms, abortSignal), |
| 65 | + }); |
| 66 | + vi.doMock("./embedded-agent-runner/model.js", () => ({ |
| 67 | + resolveModelAsync: async (provider: string, modelId: string) => |
| 68 | + createResolvedEmbeddedRunnerModel(provider, modelId), |
| 69 | + })); |
| 70 | + vi.doMock("./session-suspension.js", async () => { |
| 71 | + const actual = |
| 72 | + await vi.importActual<typeof import("./session-suspension.js")>("./session-suspension.js"); |
| 73 | + return { ...actual, suspendSession: suspendSessionMock }; |
| 74 | + }); |
| 75 | +} |
| 76 | + |
| 77 | +let getReplyFromConfig: typeof import("../auto-reply/reply.js").getReplyFromConfig; |
| 78 | +let withFullRuntimeReplyConfig: typeof import("../auto-reply/reply/get-reply-fast-path.js").withFullRuntimeReplyConfig; |
| 79 | +const RATE_LIMIT_ERROR_MESSAGE = "rate limit exceeded"; |
| 80 | + |
| 81 | +beforeAll(async () => { |
| 82 | + installReplyEntryMocks(); |
| 83 | + ({ getReplyFromConfig } = await import("../auto-reply/reply.js")); |
| 84 | + ({ withFullRuntimeReplyConfig } = await import("../auto-reply/reply/get-reply-fast-path.js")); |
| 85 | +}); |
| 86 | + |
| 87 | +beforeEach(() => { |
| 88 | + vi.stubEnv("OPENCLAW_ALLOW_SLOW_REPLY_TESTS", "1"); |
| 89 | + resetFallbackSkipCacheForTest(); |
| 90 | + runEmbeddedAttemptMock.mockReset(); |
| 91 | + suspendSessionMock.mockClear(); |
| 92 | + computeBackoffMock.mockClear(); |
| 93 | + sleepWithAbortMock.mockClear(); |
| 94 | +}); |
| 95 | + |
| 96 | +function countProviderAttempts(provider: string): number { |
| 97 | + return runEmbeddedAttemptMock.mock.calls.filter( |
| 98 | + (call) => (call[0] as { provider?: string })?.provider === provider, |
| 99 | + ).length; |
| 100 | +} |
| 101 | + |
| 102 | +describe("getReplyFromConfig fallback availability", () => { |
| 103 | + it("returns the pinned rate-limit surface through the reply entry", async () => { |
| 104 | + // Pre-fix this chain returned "The AI service is temporarily rate-limited. Please try again |
| 105 | + // in a moment." because run preparation rebuilt fallbackConfigured from config defaults instead |
| 106 | + // of carrying the disabled model-fallback availability into the embedded runner. |
| 107 | + await withModelFallbackWorkspace(async ({ agentDir, workspaceDir }) => { |
| 108 | + await writeFallbackMultiProfileAuthStore(agentDir); |
| 109 | + const baseConfig = makeModelFallbackConfig(); |
| 110 | + const groqProvider = baseConfig.models?.providers?.groq; |
| 111 | + if (!groqProvider) { |
| 112 | + throw new Error("expected fallback provider fixture"); |
| 113 | + } |
| 114 | + const sessionKey = "agent:test:telegram:111"; |
| 115 | + const storePath = path.join(path.dirname(agentDir), "sessions.json"); |
| 116 | + const cfg: OpenClawConfig = { |
| 117 | + ...baseConfig, |
| 118 | + agents: { |
| 119 | + ...baseConfig.agents, |
| 120 | + defaults: { |
| 121 | + ...baseConfig.agents?.defaults, |
| 122 | + workspace: workspaceDir, |
| 123 | + model: { primary: "openai/mock-1", fallbacks: ["anthropic/mock-2"] }, |
| 124 | + }, |
| 125 | + list: [{ id: "test", agentDir, workspace: workspaceDir }], |
| 126 | + }, |
| 127 | + models: { |
| 128 | + ...baseConfig.models, |
| 129 | + providers: { |
| 130 | + ...baseConfig.models?.providers, |
| 131 | + anthropic: { ...groqProvider, baseUrl: "https://example.com/anthropic" }, |
| 132 | + }, |
| 133 | + }, |
| 134 | + session: { store: storePath }, |
| 135 | + }; |
| 136 | + await replaceSessionEntry( |
| 137 | + { sessionKey, storePath }, |
| 138 | + { |
| 139 | + sessionId: "session-pinned-rate-limit", |
| 140 | + updatedAt: Date.now(), |
| 141 | + providerOverride: "openai", |
| 142 | + modelOverride: "mock-1", |
| 143 | + modelOverrideSource: "user", |
| 144 | + }, |
| 145 | + ); |
| 146 | + runEmbeddedAttemptMock.mockImplementation(async (params: unknown) => { |
| 147 | + const attemptParams = params as { provider: string; modelId?: string }; |
| 148 | + if (attemptParams.provider !== "openai") { |
| 149 | + throw new Error(`unexpected fallback attempt: ${attemptParams.provider}`); |
| 150 | + } |
| 151 | + return makeEmbeddedRunnerAttempt({ |
| 152 | + assistantTexts: [], |
| 153 | + lastAssistant: buildEmbeddedRunnerAssistant({ |
| 154 | + provider: "openai", |
| 155 | + model: attemptParams.modelId ?? "mock-1", |
| 156 | + stopReason: "error", |
| 157 | + errorMessage: RATE_LIMIT_ERROR_MESSAGE, |
| 158 | + }), |
| 159 | + }); |
| 160 | + }); |
| 161 | + |
| 162 | + const ctx: MsgContext = { |
| 163 | + Body: "hello", |
| 164 | + From: "telegram:111", |
| 165 | + To: "telegram:111", |
| 166 | + ChatType: "direct", |
| 167 | + Provider: "telegram", |
| 168 | + Surface: "telegram", |
| 169 | + SessionKey: sessionKey, |
| 170 | + CommandAuthorized: true, |
| 171 | + }; |
| 172 | + const replyConfig = withFullRuntimeReplyConfig(cfg); |
| 173 | + setRuntimeConfigSnapshot(replyConfig, replyConfig); |
| 174 | + let result: Awaited<ReturnType<typeof getReplyFromConfig>>; |
| 175 | + try { |
| 176 | + result = await getReplyFromConfig(ctx, undefined, replyConfig); |
| 177 | + } finally { |
| 178 | + clearRuntimeConfigSnapshot(); |
| 179 | + } |
| 180 | + const text = Array.isArray(result) ? result[0]?.text : result?.text; |
| 181 | + expect(countProviderAttempts("openai")).toBeGreaterThan(2); |
| 182 | + expect(countProviderAttempts("anthropic")).toBe(0); |
| 183 | + expect(text).toContain("API rate limit reached"); |
| 184 | + }); |
| 185 | + }); |
| 186 | +}); |
0 commit comments