Skip to content
Closed
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
165 changes: 164 additions & 1 deletion apps/server/src/codexAppServerManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,12 @@ function createCollabNotificationHarness() {
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
sessionApprovalOverride: undefined as
| undefined
| {
approvalPolicy: "never";
sandboxPolicy: { type: "dangerFullAccess" };
},
collabReceiverTurns: new Map<string, string>(),
collabReceiverParents: new Map<string, string>(),
reviewTurnIds: new Set<string>(),
Expand All @@ -290,8 +296,41 @@ function createCollabNotificationHarness() {
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
const requireSession = vi
.spyOn(
manager as unknown as { requireSession: (threadId: ThreadId) => unknown },
"requireSession",
)
.mockReturnValue(context);
const writeMessage = vi
.spyOn(manager as unknown as { writeMessage: (...args: unknown[]) => void }, "writeMessage")
.mockImplementation(() => {});

return { manager, context, emitEvent, updateSession, requireSession, writeMessage };
}

function handleServerNotificationForTest(
manager: CodexAppServerManager,
context: unknown,
notification: Record<string, unknown>,
): void {
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, notification);
}

return { manager, context, emitEvent, updateSession };
function handleServerRequestForTest(
manager: CodexAppServerManager,
context: unknown,
request: Record<string, unknown>,
): void {
(
manager as unknown as {
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
}
).handleServerRequest(context, request);
}

function createProcessOutputHarness() {
Expand Down Expand Up @@ -2565,6 +2604,130 @@ describe("collab child conversation routing", () => {
);
});

it("routes unmapped child events through the active provider thread", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();

handleServerNotificationForTest(manager, context, {
method: "item/agentMessage/delta",
params: {
threadId: "child_provider_unmapped",
turnId: "turn_child_unmapped",
itemId: "msg_child_unmapped",
delta: "working",
},
});

expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/agentMessage/delta",
turnId: "turn_child_unmapped",
itemId: "msg_child_unmapped",
providerThreadId: "child_provider_unmapped",
providerParentThreadId: "provider_parent",
}),
);
});

it("does not infer a provider parent for the active parent or an inactive session", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();

handleServerNotificationForTest(manager, context, {
method: "item/agentMessage/delta",
params: {
threadId: "provider_parent",
turnId: "turn_parent",
itemId: "msg_parent",
delta: "parent",
},
});
context.session.status = "ready";
handleServerNotificationForTest(manager, context, {
method: "item/agentMessage/delta",
params: {
threadId: "another_provider_thread",
turnId: "turn_other",
itemId: "msg_other",
delta: "other",
},
});

const activeParentEvent = emitEvent.mock.calls[0]?.[0] as Record<string, unknown>;
const inactiveSessionEvent = emitEvent.mock.calls[1]?.[0] as Record<string, unknown>;
expect(activeParentEvent.providerThreadId).toBe("provider_parent");
expect(activeParentEvent).not.toHaveProperty("providerParentThreadId");
expect(inactiveSessionEvent.providerThreadId).toBe("another_provider_thread");
expect(inactiveSessionEvent).not.toHaveProperty("providerParentThreadId");
});

it("preserves inferred child routing through approval decisions", async () => {
const { manager, context, emitEvent, writeMessage } = createCollabNotificationHarness();

handleServerRequestForTest(manager, context, {
id: 42,
method: "item/commandExecution/requestApproval",
params: {
threadId: "child_provider_unmapped",
turnId: "turn_child_unmapped",
itemId: "call_child_unmapped",
command: "bun install",
},
});

const pendingRequest = Array.from(context.pendingApprovals.values())[0];
expect(pendingRequest).toEqual(
expect.objectContaining({
providerThreadId: "child_provider_unmapped",
providerParentThreadId: "provider_parent",
}),
);
await manager.respondToRequest(asThreadId("thread_1"), pendingRequest.requestId, "accept");

expect(writeMessage).toHaveBeenCalledWith(context, {
id: 42,
result: { decision: "accept" },
});
expect(emitEvent).toHaveBeenLastCalledWith(
expect.objectContaining({
method: "item/requestApproval/decision",
turnId: "turn_child_unmapped",
providerThreadId: "child_provider_unmapped",
providerParentThreadId: "provider_parent",
}),
);
});

it("preserves inferred child routing through user-input answers", async () => {
const { manager, context, emitEvent, writeMessage } = createCollabNotificationHarness();

handleServerRequestForTest(manager, context, {
id: 43,
method: "item/tool/requestUserInput",
params: {
threadId: "child_provider_unmapped",
turnId: "turn_child_unmapped",
itemId: "tool_child_unmapped",
questions: [],
},
});

const pendingRequest = Array.from(context.pendingUserInputs.values())[0];
await manager.respondToUserInput(asThreadId("thread_1"), pendingRequest.requestId, {
scope: "child",
});

expect(writeMessage).toHaveBeenCalledWith(context, {
id: 43,
result: { answers: { scope: { answers: ["child"] } } },
});
expect(emitEvent).toHaveBeenLastCalledWith(
expect.objectContaining({
method: "item/tool/requestUserInput/answered",
providerThreadId: "child_provider_unmapped",
providerParentThreadId: "provider_parent",
}),
);
});

it("suppresses child lifecycle notifications without mutating the parent session state", () => {
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();

Expand Down
111 changes: 78 additions & 33 deletions apps/server/src/codexAppServerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,28 @@ interface PendingApprovalRequest {
requestKind: ProviderRequestKind;
threadId: ThreadId;
turnId?: TurnId;
parentTurnId?: TurnId;
itemId?: ProviderItemId;
providerThreadId?: string;
providerParentThreadId?: string;
}

interface PendingUserInputRequest {
requestId: ApprovalRequestId;
jsonRpcId: string | number;
threadId: ThreadId;
turnId?: TurnId;
parentTurnId?: TurnId;
itemId?: ProviderItemId;
providerThreadId?: string;
providerParentThreadId?: string;
}

interface ResolvedCollaborationRoute {
readonly parentTurnId?: TurnId;
readonly providerThreadId?: string;
readonly providerParentThreadId?: string;
readonly isChildConversation: boolean;
}

interface CodexUserInputAnswer {
Expand Down Expand Up @@ -1681,7 +1694,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
createdAt: new Date().toISOString(),
method: "item/requestApproval/decision",
turnId: pendingRequest.turnId,
parentTurnId: pendingRequest.parentTurnId,
itemId: pendingRequest.itemId,
providerThreadId: pendingRequest.providerThreadId,
providerParentThreadId: pendingRequest.providerParentThreadId,
requestId: pendingRequest.requestId,
requestKind: pendingRequest.requestKind,
payload: {
Expand Down Expand Up @@ -1749,7 +1765,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
turnId: pendingRequest.turnId,
parentTurnId: pendingRequest.parentTurnId,
itemId: pendingRequest.itemId,
providerThreadId: pendingRequest.providerThreadId,
providerParentThreadId: pendingRequest.providerParentThreadId,
requestId: pendingRequest.requestId,
payload: {
requestId: pendingRequest.requestId,
Expand Down Expand Up @@ -2330,34 +2349,13 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
): void {
const rawRoute = this.readRouteFields(notification.params);
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
const providerThreadId = normalizeProviderThreadId(
this.readProviderConversationId(notification.params),
);
const providerParentThreadId = this.readChildParentProviderThreadId(
context,
notification.params,
);
const activeProviderThreadId = normalizeProviderThreadId(
readResumeThreadId({
threadId: context.session.threadId,
runtimeMode: context.session.runtimeMode,
resumeCursor: context.session.resumeCursor,
}),
);
// A child can emit turn/started before its collab tool-call payload has
// populated the receiver maps. While a parent turn is live, a notification
// from another provider thread must not replace the parent's active turn.
const isUnmappedChildConversation =
context.session.status === "running" &&
context.session.activeTurnId !== undefined &&
providerThreadId !== undefined &&
activeProviderThreadId !== undefined &&
providerThreadId !== activeProviderThreadId;
const isChildConversation =
childParentTurnId !== undefined ||
providerParentThreadId !== undefined ||
isUnmappedChildConversation;
const resolvedCollaborationRoute = this.resolveCollaborationRoute(context, notification.params);
const {
parentTurnId: childParentTurnId,
providerThreadId,
providerParentThreadId,
isChildConversation,
} = resolvedCollaborationRoute;
if (
isChildConversation &&
this.shouldSuppressChildConversationNotification(notification.method)
Expand Down Expand Up @@ -2545,11 +2543,12 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve

private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
const rawRoute = this.readRouteFields(request.params);
const childParentTurnId = this.readChildParentTurnId(context, request.params);
const providerThreadId = normalizeProviderThreadId(
this.readProviderConversationId(request.params),
);
const providerParentThreadId = this.readChildParentProviderThreadId(context, request.params);
const resolvedCollaborationRoute = this.resolveCollaborationRoute(context, request.params);
const {
parentTurnId: childParentTurnId,
providerThreadId,
providerParentThreadId,
} = resolvedCollaborationRoute;
const requestKind = this.requestKindForMethod(request.method);
let requestId: ApprovalRequestId | undefined;
if (requestKind) {
Expand All @@ -2566,7 +2565,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
requestKind,
threadId: context.session.threadId,
...(rawRoute.turnId ? { turnId: rawRoute.turnId } : {}),
...(childParentTurnId ? { parentTurnId: childParentTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(providerThreadId ? { providerThreadId } : {}),
...(providerParentThreadId ? { providerParentThreadId } : {}),
};
if (context.sessionApprovalOverride) {
this.resolveApprovalRequest(context, pendingRequest, "acceptForSession");
Expand All @@ -2582,7 +2584,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
jsonRpcId: request.id,
threadId: context.session.threadId,
...(rawRoute.turnId ? { turnId: rawRoute.turnId } : {}),
...(childParentTurnId ? { parentTurnId: childParentTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(providerThreadId ? { providerThreadId } : {}),
...(providerParentThreadId ? { providerParentThreadId } : {}),
});
}

Expand Down Expand Up @@ -2924,6 +2929,46 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return context.collabReceiverParents.get(providerConversationId);
}

private resolveCollaborationRoute(
context: CodexSessionContext,
params: unknown,
): ResolvedCollaborationRoute {
const parentTurnId = this.readChildParentTurnId(context, params);
const providerThreadId = normalizeProviderThreadId(this.readProviderConversationId(params));
const mappedProviderParentThreadId = this.readChildParentProviderThreadId(context, params);
const activeProviderThreadId = normalizeProviderThreadId(
readResumeThreadId({
threadId: context.session.threadId,
runtimeMode: context.session.runtimeMode,
resumeCursor: context.session.resumeCursor,
}),
);
// A child can emit events before its collaboration tool-call payload
// populates the receiver maps. During a live parent turn, another provider
// thread belongs to that active conversation. Preserve an explicit mapping
// when available; otherwise retain the active provider thread as its parent.
const isUnmappedChildConversation =
mappedProviderParentThreadId === undefined &&
context.session.status === "running" &&
context.session.activeTurnId !== undefined &&
providerThreadId !== undefined &&
activeProviderThreadId !== undefined &&
providerThreadId !== activeProviderThreadId;
const providerParentThreadId =
mappedProviderParentThreadId ??
(isUnmappedChildConversation ? activeProviderThreadId : undefined);

return {
...(parentTurnId ? { parentTurnId } : {}),
...(providerThreadId ? { providerThreadId } : {}),
...(providerParentThreadId ? { providerParentThreadId } : {}),
isChildConversation:
parentTurnId !== undefined ||
providerParentThreadId !== undefined ||
isUnmappedChildConversation,
};
}

private rememberCollabReceiverTurns(
context: CodexSessionContext,
params: unknown,
Expand Down
Loading
Loading