|
| 1 | +import fs from "node:fs/promises"; |
| 2 | +import path from "node:path"; |
| 3 | +import type { EmbeddedRunAttemptParamsV2 as EmbeddedRunAttemptParams } from "openclaw/plugin-sdk/agent-harness-runtime"; |
| 4 | +import { createAgentHarnessHostCapabilitiesForTest } from "openclaw/plugin-sdk/plugin-test-runtime"; |
| 5 | +import { upsertSessionEntry } from "openclaw/plugin-sdk/session-store-runtime"; |
| 6 | +import { readSessionTranscriptEvents } from "openclaw/plugin-sdk/session-transcript-runtime"; |
| 7 | +import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env"; |
| 8 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 9 | +import { |
| 10 | + resolveCodexAppServerHomeDir, |
| 11 | + resolveCodexAppServerUserHomeDir, |
| 12 | +} from "./auth-start-options.js"; |
| 13 | +import { resolveCodexAppServerRuntimeOptions } from "./config.js"; |
| 14 | +import { setManagedCodexPluginRoot } from "./managed-binary.js"; |
| 15 | +import { isJsonObject } from "./protocol.js"; |
| 16 | +import { runCodexAppServerAttempt } from "./run-attempt.js"; |
| 17 | +import { |
| 18 | + createCodexTestBindingStore, |
| 19 | + sessionBindingIdentity, |
| 20 | +} from "./session-binding.test-helpers.js"; |
| 21 | +import { createIsolatedCodexAppServerClient } from "./shared-client.js"; |
| 22 | + |
| 23 | +const LIVE = |
| 24 | + process.env.OPENCLAW_LIVE_TEST === "1" && process.env.OPENCLAW_LIVE_CODEX_ASYNC_QUESTIONS === "1"; |
| 25 | +const describeLive = LIVE ? describe : describe.skip; |
| 26 | +const tempDirs = useAutoCleanupTempDirTracker(afterEach); |
| 27 | + |
| 28 | +afterEach(() => { |
| 29 | + setManagedCodexPluginRoot(undefined); |
| 30 | + vi.unstubAllEnvs(); |
| 31 | +}); |
| 32 | + |
| 33 | +describeLive("Codex async questions real-binary bridge", () => { |
| 34 | + it("continues work before an answer and consumes a later ordinary reply on the same thread", async () => { |
| 35 | + const runtimeModelId = process.env.OPENCLAW_LIVE_CODEX_MODEL?.trim(); |
| 36 | + if (!runtimeModelId) { |
| 37 | + throw new Error("Set OPENCLAW_LIVE_CODEX_MODEL to a model with async question support"); |
| 38 | + } |
| 39 | + const root = tempDirs.make("openclaw-codex-async-questions-"); |
| 40 | + const workspace = path.join(root, "workspace"); |
| 41 | + const agentDir = path.join(root, "agent"); |
| 42 | + const nativeHome = resolveCodexAppServerHomeDir(agentDir); |
| 43 | + await fs.mkdir(workspace, { recursive: true }); |
| 44 | + await fs.mkdir(nativeHome, { recursive: true, mode: 0o700 }); |
| 45 | + // Copy only the existing login into the disposable home, never user config or sessions. |
| 46 | + const authFile = path.join(nativeHome, "auth.json"); |
| 47 | + await fs.copyFile(path.join(resolveCodexAppServerUserHomeDir(), "auth.json"), authFile); |
| 48 | + await fs.chmod(authFile, 0o600); |
| 49 | + vi.stubEnv("OPENCLAW_STATE_DIR", path.join(root, "state")); |
| 50 | + setManagedCodexPluginRoot(path.resolve(import.meta.dirname, "../..")); |
| 51 | + |
| 52 | + const pluginConfig = { appServer: { homeScope: "agent" } }; |
| 53 | + const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig, env: {} }); |
| 54 | + const client = await createIsolatedCodexAppServerClient({ |
| 55 | + startOptions: runtime.start, |
| 56 | + agentDir, |
| 57 | + authProfileId: null, |
| 58 | + timeoutMs: 120_000, |
| 59 | + }); |
| 60 | + let closeHost: (() => void) | undefined; |
| 61 | + try { |
| 62 | + const completedKinds: string[] = []; |
| 63 | + const questionItemIds: string[] = []; |
| 64 | + const serverRequestMethods: string[] = []; |
| 65 | + client.addRequestHandler((request) => { |
| 66 | + serverRequestMethods.push(request.method); |
| 67 | + return undefined; |
| 68 | + }); |
| 69 | + client.addNotificationHandler((notification) => { |
| 70 | + if (notification.method !== "item/completed" || !isJsonObject(notification.params)) { |
| 71 | + return; |
| 72 | + } |
| 73 | + const item = notification.params.item; |
| 74 | + if (!isJsonObject(item) || typeof item.type !== "string") { |
| 75 | + return; |
| 76 | + } |
| 77 | + if ( |
| 78 | + item.type === "agentMessage" && |
| 79 | + item.delivery === "async" && |
| 80 | + Array.isArray(item.questions) && |
| 81 | + typeof item.id === "string" |
| 82 | + ) { |
| 83 | + questionItemIds.push(item.id); |
| 84 | + completedKinds.push("asyncQuestion"); |
| 85 | + } else { |
| 86 | + completedKinds.push(item.type); |
| 87 | + } |
| 88 | + }); |
| 89 | + |
| 90 | + const questions = [ |
| 91 | + { title: "Which output format?", options: ["Markdown", "Plain text"] }, |
| 92 | + { title: "Who is the audience?" }, |
| 93 | + ]; |
| 94 | + const deliveredTexts: string[] = []; |
| 95 | + const modelId = runtimeModelId; |
| 96 | + const sessionTarget = { |
| 97 | + agentId: "async-questions", |
| 98 | + sessionId: "async-questions-session", |
| 99 | + sessionKey: "agent:async-questions:main", |
| 100 | + storePath: path.join(agentDir, "openclaw-agent.sqlite"), |
| 101 | + }; |
| 102 | + const params = { |
| 103 | + agentId: sessionTarget.agentId, |
| 104 | + sessionId: sessionTarget.sessionId, |
| 105 | + sessionKey: sessionTarget.sessionKey, |
| 106 | + sessionTarget, |
| 107 | + sessionFile: path.join(root, "session.jsonl"), |
| 108 | + workspaceDir: workspace, |
| 109 | + cwd: workspace, |
| 110 | + agentDir, |
| 111 | + provider: "openai", |
| 112 | + modelId, |
| 113 | + model: { |
| 114 | + id: modelId, |
| 115 | + name: modelId, |
| 116 | + provider: "openai", |
| 117 | + api: "openai-chatgpt-responses", |
| 118 | + reasoning: true, |
| 119 | + input: ["text"], |
| 120 | + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, |
| 121 | + contextWindow: 200_000, |
| 122 | + maxTokens: 8_000, |
| 123 | + compat: { supportsTools: false }, |
| 124 | + }, |
| 125 | + prompt: [ |
| 126 | + "This is a synthetic async question integration check. All files belong to this disposable workspace.", |
| 127 | + "First call request_user_input_async exactly once with these exact arguments:", |
| 128 | + JSON.stringify({ questions }), |
| 129 | + "These are optional preferences. Immediately after that tool returns, continue independent work without waiting for an answer.", |
| 130 | + "Use a native shell command to create async-question-marker.txt containing exactly AFTER_ASYNC_QUESTION followed by a newline.", |
| 131 | + "Then end this turn with QUESTION_READY. Do not use request_user_input or ask another question.", |
| 132 | + ].join("\n"), |
| 133 | + runId: "async-questions-first-run", |
| 134 | + contextTokenBudget: 150_000, |
| 135 | + contextWindowInfo: { |
| 136 | + tokens: 150_000, |
| 137 | + referenceTokens: 200_000, |
| 138 | + source: "agentContextTokens", |
| 139 | + }, |
| 140 | + thinkLevel: "medium", |
| 141 | + disableTools: false, |
| 142 | + config: { tools: { web: { search: { enabled: false } } } }, |
| 143 | + timeoutMs: 180_000, |
| 144 | + trigger: "user", |
| 145 | + oneShotCliRun: true, |
| 146 | + senderIsOwner: true, |
| 147 | + authStorage: {}, |
| 148 | + authProfileStore: { version: 1, profiles: {} }, |
| 149 | + modelRegistry: {}, |
| 150 | + onBlockReply: async (payload: { text?: string }) => { |
| 151 | + if (payload.text) { |
| 152 | + deliveredTexts.push(payload.text); |
| 153 | + } |
| 154 | + }, |
| 155 | + } as unknown as EmbeddedRunAttemptParams; |
| 156 | + await upsertSessionEntry({ |
| 157 | + ...sessionTarget, |
| 158 | + entry: { |
| 159 | + sessionId: sessionTarget.sessionId, |
| 160 | + sessionFile: params.sessionFile, |
| 161 | + updatedAt: Date.now(), |
| 162 | + }, |
| 163 | + }); |
| 164 | + const host = await createAgentHarnessHostCapabilitiesForTest({ |
| 165 | + attempt: params, |
| 166 | + pluginId: "codex", |
| 167 | + }); |
| 168 | + params.hostCapabilities = host.capabilities; |
| 169 | + closeHost = host.close; |
| 170 | + const bindingStore = createCodexTestBindingStore(); |
| 171 | + const options = { |
| 172 | + bindingStore, |
| 173 | + pluginConfig, |
| 174 | + clientFactory: async () => client, |
| 175 | + }; |
| 176 | + const first = await runCodexAppServerAttempt(params, options); |
| 177 | + |
| 178 | + expect(first.terminal.kind).toBe("ok"); |
| 179 | + expect(questionItemIds).toHaveLength(1); |
| 180 | + expect(completedKinds.indexOf("commandExecution")).toBeGreaterThan( |
| 181 | + completedKinds.indexOf("asyncQuestion"), |
| 182 | + ); |
| 183 | + expect(await fs.readFile(path.join(workspace, "async-question-marker.txt"), "utf8")).toBe( |
| 184 | + "AFTER_ASYNC_QUESTION\n", |
| 185 | + ); |
| 186 | + expect( |
| 187 | + first.messagesSnapshot.filter( |
| 188 | + (message) => message.role === "assistant" && "openclawAsyncDelivery" in message, |
| 189 | + ), |
| 190 | + ).toEqual([ |
| 191 | + expect.objectContaining({ |
| 192 | + openclawAsyncDelivery: { itemId: questionItemIds[0], questions }, |
| 193 | + }), |
| 194 | + ]); |
| 195 | + expect(deliveredTexts).toHaveLength(1); |
| 196 | + expect(deliveredTexts[0]).toContain("Which output format?"); |
| 197 | + expect(deliveredTexts[0]).toContain("Who is the audience?"); |
| 198 | + const persisted = await readSessionTranscriptEvents(sessionTarget); |
| 199 | + expect( |
| 200 | + persisted.filter( |
| 201 | + (event) => |
| 202 | + isJsonObject(event) && |
| 203 | + isJsonObject(event.message) && |
| 204 | + isJsonObject(event.message.openclawAsyncDelivery), |
| 205 | + ), |
| 206 | + ).toHaveLength(1); |
| 207 | + expect(serverRequestMethods).not.toContain("item/tool/requestUserInput"); |
| 208 | + const firstBinding = bindingStore.read(sessionBindingIdentity(params)); |
| 209 | + expect(firstBinding).toBeDefined(); |
| 210 | + expect(firstBinding?.model === runtimeModelId).toBe(true); |
| 211 | + const firstThreadId = firstBinding?.threadId; |
| 212 | + expect(firstThreadId).toEqual(expect.any(String)); |
| 213 | + |
| 214 | + closeHost(); |
| 215 | + closeHost = undefined; |
| 216 | + const followUp = { |
| 217 | + ...params, |
| 218 | + runId: "async-questions-answer-run", |
| 219 | + prompt: [ |
| 220 | + "> Which output format?", |
| 221 | + "", |
| 222 | + "Plain text", |
| 223 | + "", |
| 224 | + "> Who is the audience?", |
| 225 | + "", |
| 226 | + "release reviewers", |
| 227 | + "", |
| 228 | + "Use those answers to create async-question-answer.txt containing the chosen format, a vertical bar, then the audience, followed by a newline.", |
| 229 | + "Do not ask further questions. Then reply ANSWER_USED.", |
| 230 | + ].join("\n"), |
| 231 | + }; |
| 232 | + const answerHost = await createAgentHarnessHostCapabilitiesForTest({ |
| 233 | + attempt: followUp, |
| 234 | + pluginId: "codex", |
| 235 | + }); |
| 236 | + followUp.hostCapabilities = answerHost.capabilities; |
| 237 | + closeHost = answerHost.close; |
| 238 | + const answered = await runCodexAppServerAttempt(followUp, options); |
| 239 | + |
| 240 | + expect(answered.terminal.kind).toBe("ok"); |
| 241 | + expect(bindingStore.read(sessionBindingIdentity(followUp))?.threadId).toBe(firstThreadId); |
| 242 | + expect(await fs.readFile(path.join(workspace, "async-question-answer.txt"), "utf8")).toBe( |
| 243 | + "Plain text|release reviewers\n", |
| 244 | + ); |
| 245 | + expect(serverRequestMethods).not.toContain("item/tool/requestUserInput"); |
| 246 | + } finally { |
| 247 | + closeHost?.(); |
| 248 | + await client.closeAndWait(); |
| 249 | + } |
| 250 | + }, 480_000); |
| 251 | +}); |
0 commit comments