maybe fix codex subturns

This commit is contained in:
Julius Marminge committed 2026-03-18 15:47:34 -07:00
1 parent 654ca0da91
commit ef843d400e
4 files changed
+334 -16

No files matched your search

@@ -37,6 +37,7 @@ function createSendTurnHarness() {
planType: null,
sparkEnabled: true,
},
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -75,6 +76,7 @@ function createThreadControlHarness() {
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -117,6 +119,7 @@ function createPendingUserInputHarness() {
},
],
]),
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -135,6 +138,43 @@ function createPendingUserInputHarness() {
return { manager, context, requireSession, writeMessage, emitEvent };
}
function createCollabNotificationHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
provider: "codex",
status: "running",
threadId: asThreadId("thread_1"),
runtimeMode: "full-access",
model: "gpt-5.3-codex",
activeTurnId: "turn_parent",
resumeCursor: { threadId: "provider_parent" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map<string, string>(),
nextRequestId: 1,
stopping: false,
};
const emitEvent = vi
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
.mockImplementation(() => {});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, emitEvent, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -721,6 +761,7 @@ describe("respondToUserInput", () => {
},
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
};
type ApprovalRequestContext = {
session: typeof context.session;
@@ -748,6 +789,152 @@ describe("respondToUserInput", () => {
});
});
describe("collab child conversation routing", () => {
it("rewrites child notification turn ids onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/agentMessage/delta",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "msg_child_1",
delta: "working",
},
});
expect(emitEvent).toHaveBeenLastCalledWith(
expect.objectContaining({
method: "item/agentMessage/delta",
turnId: "turn_parent",
itemId: "msg_child_1",
}),
);
});
it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
updateSession.mockClear();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/started",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1" },
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/completed",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1", status: "completed" },
},
});
expect(emitEvent).not.toHaveBeenCalled();
expect(updateSession).not.toHaveBeenCalled();
});
it("rewrites child approval requests onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
(
manager as unknown as {
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
}
).handleServerRequest(context, {
id: 42,
method: "item/commandExecution/requestApproval",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "call_child_1",
command: "bun install",
},
});
expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
expect.objectContaining({
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/commandExecution/requestApproval",
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
});
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
+94 -10
View File
@@ -70,6 +70,7 @@ interface CodexSessionContext {
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
collabReceiverTurns: Map<string, TurnId>;
nextRequestId: number;
stopping: boolean;
}
@@ -571,6 +572,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
nextRequestId: 1,
stopping: false,
};
@@ -732,6 +734,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
const context = this.requireSession(input.threadId);
context.collabReceiverTurns.clear();
const turnInput: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
@@ -1121,7 +1124,16 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context: CodexSessionContext,
notification: JsonRpcNotification,
): void {
const route = this.readRouteFields(notification.params);
const rawRoute = this.readRouteFields(notification.params);
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
const isChildConversation = childParentTurnId !== undefined;
if (
isChildConversation &&
this.shouldSuppressChildConversationNotification(notification.method)
) {
return;
}
const textDelta =
notification.method === "item/agentMessage/delta"
? this.readString(notification.params, "delta")
@@ -1134,8 +1146,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: notification.method,
turnId: route.turnId,
itemId: route.itemId,
...((childParentTurnId ?? rawRoute.turnId)
? { turnId: childParentTurnId ?? rawRoute.turnId }
: {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
textDelta,
payload: notification.params,
});
@@ -1151,6 +1165,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/started") {
if (isChildConversation) {
return;
}
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
this.updateSession(context, {
status: "running",
@@ -1160,6 +1177,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/completed") {
if (isChildConversation) {
return;
}
context.collabReceiverTurns.clear();
const turn = this.readObject(notification.params, "turn");
const status = this.readString(turn, "status");
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
@@ -1172,6 +1193,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "error") {
if (isChildConversation) {
return;
}
const message = this.readString(this.readObject(notification.params)?.error, "message");
const willRetry = this.readBoolean(notification.params, "willRetry");
@@ -1183,7 +1207,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
const route = this.readRouteFields(request.params);
const rawRoute = this.readRouteFields(request.params);
const childParentTurnId = this.readChildParentTurnId(context, request.params);
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
const requestKind = this.requestKindForMethod(request.method);
let requestId: ApprovalRequestId | undefined;
if (requestKind) {
@@ -1199,8 +1225,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
: "item/fileChange/requestApproval",
requestKind,
threadId: context.session.threadId,
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
};
context.pendingApprovals.set(requestId, pendingRequest);
}
@@ -1211,8 +1237,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
requestId,
jsonRpcId: request.id,
threadId: context.session.threadId,
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
});
}
@@ -1223,8 +1249,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: request.method,
turnId: route.turnId,
itemId: route.itemId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
requestId,
requestKind,
payload: request.params,
@@ -1451,6 +1477,64 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return route;
}
private readProviderConversationId(params: unknown): string | undefined {
return (
this.readString(params, "threadId") ??
this.readString(this.readObject(params, "thread"), "id") ??
this.readString(params, "conversationId")
);
}
private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
const providerConversationId = this.readProviderConversationId(params);
if (!providerConversationId) {
return undefined;
}
return context.collabReceiverTurns.get(providerConversationId);
}
private rememberCollabReceiverTurns(
context: CodexSessionContext,
params: unknown,
parentTurnId: TurnId | undefined,
): void {
if (!parentTurnId) {
return;
}
const payload = this.readObject(params);
const item = this.readObject(payload, "item") ?? payload;
const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
if (itemType !== "collabAgentToolCall") {
return;
}
const receiverThreadIds =
this.readArray(item, "receiverThreadIds")
?.map((value) => (typeof value === "string" ? value : null))
.filter((value): value is string => value !== null) ?? [];
for (const receiverThreadId of receiverThreadIds) {
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
}
}
private shouldSuppressChildConversationNotification(method: string): boolean {
return (
method === "thread/started" ||
method === "thread/status/changed" ||
method === "thread/archived" ||
method === "thread/unarchived" ||
method === "thread/closed" ||
method === "thread/compacted" ||
method === "thread/name/updated" ||
method === "thread/tokenUsage/updated" ||
method === "turn/started" ||
method === "turn/completed" ||
method === "turn/aborted" ||
method === "turn/plan/updated" ||
method === "item/plan/delta"
);
}
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
const target =
key === undefined
@@ -800,6 +800,45 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}
}),
);
it.effect("prefers manager-assigned turn ids for Codex task events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-started-parent-turn"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-parent"),
createdAt: new Date().toISOString(),
method: "codex/event/task_started",
payload: {
id: "turn-child",
msg: {
type: "task_started",
turn_id: "turn-child",
collaboration_mode_kind: "default",
},
conversationId: "child-provider-thread",
},
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "task.started");
if (firstEvent.value.type !== "task.started") {
return;
}
assert.equal(firstEvent.value.turnId, "turn-parent");
assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent");
assert.equal(firstEvent.value.payload.taskId, "turn-child");
}),
);
});
afterAll(() => {
@@ -109,6 +109,14 @@ function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function toTurnId(value: string | undefined): TurnId | undefined {
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
}
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
return value?.trim() ? ProviderItemId.makeUnsafe(value) : undefined;
}
function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" {
switch (value) {
case "completed":
@@ -415,27 +423,27 @@ function codexEventBase(
): Omit<ProviderRuntimeEvent, "type" | "payload"> {
const payload = asObject(event.payload);
const msg = codexEventMessage(payload);
const turnId = asString(msg?.turn_id) ?? asString(msg?.turnId);
const itemId = asString(msg?.item_id) ?? asString(msg?.itemId);
const turnId = event.turnId ?? toTurnId(asString(msg?.turn_id) ?? asString(msg?.turnId));
const itemId = event.itemId ?? toProviderItemId(asString(msg?.item_id) ?? asString(msg?.itemId));
const requestId = asString(msg?.request_id) ?? asString(msg?.requestId);
const base = runtimeEventBase(event, canonicalThreadId);
const providerRefs = base.providerRefs
? {
...base.providerRefs,
...(turnId ? { providerTurnId: turnId } : {}),
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
...(itemId ? { providerItemId: itemId } : {}),
...(requestId ? { providerRequestId: requestId } : {}),
}
: {
...(turnId ? { providerTurnId: turnId } : {}),
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
...(itemId ? { providerItemId: itemId } : {}),
...(requestId ? { providerRequestId: requestId } : {}),
};
return {
...base,
...(turnId ? { turnId: TurnId.makeUnsafe(turnId) } : {}),
...(itemId ? { itemId: asRuntimeItemId(ProviderItemId.makeUnsafe(itemId)) } : {}),
...(turnId ? { turnId } : {}),
...(itemId ? { itemId: asRuntimeItemId(itemId) } : {}),
...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}),
...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}),
};