Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 157 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9543,6 +9543,156 @@ describe("CodexAdapterV2 post-settle continuation", () => {
],
});

const computerUseItem = (input: {
readonly threadId: string;
readonly turnId: string;
}): ReadonlyArray<CodexReplay.CodexAppServerReplayEntry> =>
(["inProgress", "completed"] as const).map((status) => ({
type: "emit_inbound",
label: `computer-use/${status}`,
frame: {
method: status === "inProgress" ? "item/started" : "item/completed",
params: {
item: {
type: "mcpToolCall",
id: "call-codex-computer-use",
server: "cua_repl",
tool: "js",
status,
arguments: { code: 'let app = await cua.getApp("Calculator")' },
},
threadId: input.threadId,
turnId: input.turnId,
},
},
}));

it.effect.each(["root", "subagent"] as const)(
"asks to unload promptly until every thread that used Computer Use (%s) is unloaded",
(usedBy) =>
Effect.gen(function* () {
const unsubscribed: Array<string> = [];
const unsubscribe = (
id: number,
threadId: string,
): CodexReplay.CodexAppServerReplayEntry[] => [
{
type: "expect_outbound",
label: `unsubscribe ${threadId}`,
frame: { id, method: "thread/unsubscribe", params: { threadId } },
},
{
type: "emit_inbound",
label: `unsubscribed ${threadId}`,
frame: { id, result: { status: "unsubscribed" } },
},
];
const harness = yield* makeCodexReplayHarness(
makeCodexReplayTranscript({
scenario: "codex-computer-use-prompt-unload",
entries: [
...codexReplayPreamble({
nativeThreadId: RESUME_NATIVE_THREAD,
nativeTurnId: RESUME_NATIVE_TURN,
prompt: RESUME_PROMPT,
}),
...(usedBy === "root"
? computerUseItem({ threadId: RESUME_NATIVE_THREAD, turnId: RESUME_NATIVE_TURN })
: [
{
type: "emit_inbound" as const,
label: "item/completed/subAgentActivity-started",
frame: {
method: "item/completed",
params: {
item: {
type: "subAgentActivity",
id: "call-codex-resume-spawn",
kind: "started",
agentThreadId: RESUME_CHILD_THREAD,
agentPath: "/root/resume_agent",
},
threadId: RESUME_NATIVE_THREAD,
turnId: RESUME_NATIVE_TURN,
},
},
},
childTurnStarted(RESUME_CHILD_TURN_1),
...computerUseItem({
threadId: RESUME_CHILD_THREAD,
turnId: RESUME_CHILD_TURN_1,
}),
childTurnCompleted(RESUME_CHILD_TURN_1),
]),
{
type: "emit_inbound",
label: "turn/completed/root",
frame: {
method: "turn/completed",
params: {
threadId: RESUME_NATIVE_THREAD,
turn: makeCodexReplayTurn({ id: RESUME_NATIVE_TURN, status: "completed" }),
},
},
},
...unsubscribe(4, RESUME_NATIVE_THREAD),
...(usedBy === "subagent" ? unsubscribe(5, RESUME_CHILD_THREAD) : []),
],
}),
undefined,
(method, params) =>
Effect.sync(() => {
if (method === "thread/unsubscribe") {
unsubscribed.push((params as { readonly threadId: string }).threadId);
}
}),
);
const shouldUnloadPromptly = () =>
harness.runtime.shouldUnloadThreadPromptly!(harness.providerThread);
assert.isFalse(yield* shouldUnloadPromptly());

yield* harness.runtime.startTurn(
makeCodexTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now: yield* DateTime.now,
attemptId: RunAttemptId.make("attempt-codex-computer-use"),
text: RESUME_PROMPT,
}),
);
yield* harness.firstTerminal;
assert.isTrue(yield* shouldUnloadPromptly());

yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread });
if (usedBy === "subagent") {
// Unloading the parent leaves the child loaded, so the manager must unload it too.
assert.isTrue(yield* shouldUnloadPromptly());
const child = harness.events.findLast(
(event) =>
event.type === "provider_thread.updated" &&
event.providerThread.nativeThreadRef?.nativeId === RESUME_CHILD_THREAD,
);
assert(child?.type === "provider_thread.updated");
assert.isTrue(yield* harness.runtime.shouldUnloadThreadPromptly!(child.providerThread));
yield* harness.runtime.unloadThread!({ providerThread: child.providerThread });
}
assert.isFalse(yield* shouldUnloadPromptly());
assert.deepEqual(
unsubscribed,
usedBy === "root" ? [RESUME_NATIVE_THREAD] : [RESUME_NATIVE_THREAD, RESUME_CHILD_THREAD],
);
}).pipe(
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
),
),
),
);

it.effect("wakes the parent when a native child finishes after the parent's turn", () =>
Effect.gen(function* () {
const entries = resumeSubagentTranscript.entries;
Expand Down Expand Up @@ -9579,12 +9729,19 @@ describe("CodexAdapterV2 post-settle continuation", () => {
yield* harness.awaitTerminal(1);
assert.equal(harness.terminalEvents()[0]?.status, "completed");
assert.lengthOf(harness.continuationRequests, 0);
// The running child must keep the parent loaded once its own turn has settled.
assert.isTrue(
yield* harness.runtime.hasPendingBackgroundWorkForThread!(harness.providerThread),
);

yield* TestClock.adjust("60 seconds");
yield* harness.until(
() => harness.subagentUpdates().at(-1)?.subagent.result === "NATIVE_CHILD_16900_DONE",
);
assert.equal(harness.subagentUpdates().at(-1)?.subagent.status, "completed");
assert.isFalse(
yield* harness.runtime.hasPendingBackgroundWorkForThread!(harness.providerThread),
);
assert.lengthOf(harness.continuationRequests, 1);
assert.include(harness.continuationRequests[0]?.detail, "NATIVE_CHILD_16900_DONE");
assert.equal(harness.continuationRequests[0]?.delivery, "message_text");
Expand Down
47 changes: 42 additions & 5 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1460,6 +1460,17 @@ const isDescendantCodexTurn = (
return false;
};

const isCodexTurnOnThread = (
context: ActiveCodexTurnContext,
providerThreadId: OrchestrationV2ProviderThread["id"],
): boolean => {
for (let turn: ActiveCodexTurnContext | undefined = context; turn !== undefined;) {
if (turn.providerThread.id === providerThreadId) return true;
turn = turn.subagent?.parentContext;
}
return false;
};

interface PendingCodexSubagentTurnStarted {
readonly nativeTurnId: string;
readonly startedAt: DateTime.Utc;
Expand Down Expand Up @@ -2227,6 +2238,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
);
/** Completed by thread/closed after this connection unsubscribes from the native thread. */
const threadClosings = new Map<string, Deferred.Deferred<void>>();
// On macOS the Computer Use service outlives its turn until the thread's MCP servers exit.
// Keyed by the native thread that ran it (a subagent's own), valued by its root provider thread.
const computerUseNativeThreads = new Map<string, OrchestrationV2ProviderThread["id"]>();
/** Codex acceptForSession covers only the exact command or patch, not future commands. */
const sessionApprovals = new Map<
string,
Expand Down Expand Up @@ -4316,6 +4330,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
const projection = yield* projectCodexDynamicToolItem(item).pipe(
Effect.provideService(Digest.Digest, digest),
);
const nativeThreadId = context.providerThread.nativeThreadRef?.nativeId;
if (projection.toolSurface === "computer" && nativeThreadId != null) {
computerUseNativeThreads.set(
nativeThreadId,
approvalOwnerCodexTurn(context).owner.providerThread.id,
);
}
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: context.projectionThreadId,
Expand Down Expand Up @@ -5428,6 +5449,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
Effect.gen(function* () {
const closing = threadClosings.get(payload.threadId);
threadClosings.delete(payload.threadId);
computerUseNativeThreads.delete(payload.threadId);
if (closing !== undefined) yield* Deferred.succeed(closing, undefined);
const completedAt = yield* DateTime.now;
for (const context of (yield* Ref.get(settledTurns)).values()) {
Expand Down Expand Up @@ -8039,21 +8061,35 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
...(yield* Ref.get(activeTurns)).values(),
...(yield* Ref.get(settledTurns)).values(),
];
const roots = contexts.filter(
(context) => context.providerThread.id === providerThread.id,
);
for (const context of contexts) {
if (!roots.some((root) => context === root || isDescendantCodexTurn(context, root)))
continue;
// Walk the lineage, so a child still running after its parent's turn settled counts.
if (!isCodexTurnOnThread(context, providerThread.id)) continue;
if (yield* turnHasRetainedBackgroundWork(context.nativeTurnId)) return true;
if (
context.subagent !== null &&
(yield* Ref.get(activeTurns)).has(context.nativeTurnId)
)
return true;
}
// A spawned child counts before its first turn/started arrives.
for (const subagent of (yield* Ref.get(subagentThreads)).values()) {
if (
subagent.task.status === "running" &&
isCodexTurnOnThread(subagent.parentContext, providerThread.id)
)
return true;
}
return false;
}),
// A root stays prompt while a native subagent that used Computer Use is still loaded.
shouldUnloadThreadPromptly: (providerThread) =>
Effect.sync(() => {
const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
return (
(nativeThreadId != null && computerUseNativeThreads.has(nativeThreadId)) ||
Array.from(computerUseNativeThreads.values()).includes(providerThread.id)
);
}),
ensureThread: (threadInput) =>
ensureInitialized.pipe(
Effect.andThen(
Expand Down Expand Up @@ -8365,6 +8401,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
}
yield* client.request("thread/unsubscribe", { threadId: nativeThreadId });
}
computerUseNativeThreads.delete(nativeThreadId);
// No turn/completed arrives for an unloaded thread, so a Stop Codex never
// confirmed would otherwise keep its turn open for the life of the session.
const interrupting = yield* Ref.get(interruptingNativeTurns);
Expand Down
Loading
Loading