Skip to content

Commit e308bb4

Browse files
committed
fix(gateway): serialize same-session agent hooks
1 parent 993c975 commit e308bb4

2 files changed

Lines changed: 176 additions & 65 deletions

File tree

‎src/gateway/server/hooks.agent-trust.test.ts‎

Lines changed: 87 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,22 @@ function buildAgentPayload(name: string, agentId?: string) {
9595
}
9696

9797
function dispatchAgentHook(payload: unknown): unknown {
98+
return resolveDispatchAgentHook()(payload);
99+
}
100+
101+
function resolveDispatchAgentHook(): (...args: unknown[]) => unknown {
98102
if (!capturedDispatchAgentHook) {
99103
throw new Error("dispatchAgentHook missing");
100104
}
101-
return capturedDispatchAgentHook(payload);
105+
return capturedDispatchAgentHook;
106+
}
107+
108+
function createDeferred() {
109+
let resolve!: () => void;
110+
const promise = new Promise<void>((innerResolve) => {
111+
resolve = innerResolve;
112+
});
113+
return { promise, resolve };
102114
}
103115

104116
type HookLogMeta = {
@@ -180,6 +192,80 @@ describe("dispatchAgentHook trust handling", () => {
180192
expect(getActiveGatewayRootWorkCount()).toBe(0);
181193
});
182194

195+
it("serializes same-session agent hook runs in dispatch order", async () => {
196+
const dispatch = resolveDispatchAgentHook();
197+
const firstGate = createDeferred();
198+
runCronIsolatedAgentTurnMock.mockImplementationOnce(async () => {
199+
await firstGate.promise;
200+
return { status: "ok", summary: "first done", delivered: false };
201+
});
202+
runCronIsolatedAgentTurnMock.mockResolvedValueOnce({
203+
status: "ok",
204+
summary: "second done",
205+
delivered: false,
206+
});
207+
208+
dispatch({
209+
...buildAgentPayload("First"),
210+
message: "first",
211+
sessionKey: "shared-session",
212+
});
213+
dispatch({
214+
...buildAgentPayload("Second"),
215+
message: "second",
216+
sessionKey: "shared-session",
217+
});
218+
219+
await waitForFast(() => expect(runCronIsolatedAgentTurnMock).toHaveBeenCalledTimes(1));
220+
expect(runCronIsolatedAgentTurnMock.mock.calls[0]?.[0]).toMatchObject({
221+
message: "first",
222+
sessionKey: "shared-session",
223+
});
224+
225+
firstGate.resolve();
226+
227+
await waitForFast(() => expect(runCronIsolatedAgentTurnMock).toHaveBeenCalledTimes(2));
228+
expect(runCronIsolatedAgentTurnMock.mock.calls[1]?.[0]).toMatchObject({
229+
message: "second",
230+
sessionKey: "shared-session",
231+
});
232+
});
233+
234+
it("continues a same-session hook queue after a failed run", async () => {
235+
const dispatch = resolveDispatchAgentHook();
236+
runCronIsolatedAgentTurnMock.mockRejectedValueOnce(new Error("agent exploded"));
237+
runCronIsolatedAgentTurnMock.mockResolvedValueOnce({
238+
status: "ok",
239+
summary: "second done",
240+
delivered: false,
241+
});
242+
243+
dispatch({
244+
...buildAgentPayload("First"),
245+
message: "first",
246+
sessionKey: "shared-session",
247+
});
248+
dispatch({
249+
...buildAgentPayload("Second"),
250+
message: "second",
251+
sessionKey: "shared-session",
252+
});
253+
254+
await waitForFast(() =>
255+
expect(enqueueSystemEventMock).toHaveBeenCalledWith(
256+
"Hook First (error): Error: agent exploded",
257+
{
258+
sessionKey: "agent:main:main",
259+
},
260+
),
261+
);
262+
await waitForFast(() => expect(runCronIsolatedAgentTurnMock).toHaveBeenCalledTimes(2));
263+
expect(runCronIsolatedAgentTurnMock.mock.calls[1]?.[0]).toMatchObject({
264+
message: "second",
265+
sessionKey: "shared-session",
266+
});
267+
});
268+
183269
it("does not announce successful deliver:false hook results", async () => {
184270
runCronIsolatedAgentTurnMock.mockResolvedValueOnce({
185271
status: "ok",

‎src/gateway/server/hooks.ts‎

Lines changed: 89 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,28 @@ function formatHookRunWarningConsoleMessage(params: {
9393
return parts.join(" ");
9494
}
9595

96+
function createSessionKeyedHookDispatchQueue() {
97+
const hookAgentDispatchTails = new Map<string, Promise<void>>();
98+
99+
return (sessionKey: string, operation: () => Promise<void>) => {
100+
const previousTail = hookAgentDispatchTails.get(sessionKey);
101+
const run = previousTail ? previousTail.catch(() => undefined).then(operation) : operation();
102+
const tail = run.then(
103+
() => undefined,
104+
() => undefined,
105+
);
106+
hookAgentDispatchTails.set(sessionKey, tail);
107+
// Same-session hook agent runs append to one Codex session. Serializing avoids
108+
// optimistic lifecycle-claim races while preserving parallelism across sessions.
109+
void tail.finally(() => {
110+
if (hookAgentDispatchTails.get(sessionKey) === tail) {
111+
hookAgentDispatchTails.delete(sessionKey);
112+
}
113+
});
114+
return run;
115+
};
116+
}
117+
96118
/** Creates the HTTP handler used by gateway hook endpoints. */
97119
export function createGatewayHooksRequestHandler(params: {
98120
deps: CliDeps;
@@ -103,6 +125,7 @@ export function createGatewayHooksRequestHandler(params: {
103125
logHooks: SubsystemLogger;
104126
}) {
105127
const { deps, getHooksConfig, getClientIpConfig, bindHost, port, logHooks } = params;
128+
const enqueueHookAgentDispatch = createSessionKeyedHookDispatchQueue();
106129

107130
const dispatchWakeHook = (value: { text: string; mode: "now" | "next-heartbeat" }) => {
108131
const sessionKey = resolveMainSessionKeyFromConfig();
@@ -151,79 +174,81 @@ export function createGatewayHooksRequestHandler(params: {
151174
};
152175

153176
let hookEventSessionKey: string | undefined;
154-
void runWithGatewayIndependentRootWorkContinuation(async () => {
155-
try {
156-
// Agent hooks run after the HTTP response path has returned, so failure
157-
// handling must record a system event instead of throwing to the caller.
158-
const cfg = getRuntimeConfig();
159-
hookEventSessionKey = resolveHookEventSessionKey({
160-
cfg,
161-
agentId: value.agentId,
162-
});
163-
const { runCronIsolatedAgentTurn } = await import("../../cron/isolated-agent.js");
164-
const result = await runCronIsolatedAgentTurn({
165-
cfg,
166-
deps,
167-
job,
168-
message: value.message,
169-
sessionKey,
170-
lane: "cron",
171-
});
172-
const summary = resolveHookRunSummary(result);
173-
const prefix =
174-
result.status === "ok" ? `Hook ${safeName}` : `Hook ${safeName} (${result.status})`;
175-
const shouldAnnounce = shouldAnnounceHookRunResult({ deliver: value.deliver, result });
176-
if (result.status !== "ok") {
177-
logHooks.warn("hook agent run returned non-ok status", {
178-
sourcePath: value.sourcePath,
179-
name: safeName,
180-
runId,
181-
jobId,
177+
void runWithGatewayIndependentRootWorkContinuation(() =>
178+
enqueueHookAgentDispatch(sessionKey, async () => {
179+
try {
180+
// Agent hooks run after the HTTP response path has returned, so failure
181+
// handling must record a system event instead of throwing to the caller.
182+
const cfg = getRuntimeConfig();
183+
hookEventSessionKey = resolveHookEventSessionKey({
184+
cfg,
182185
agentId: value.agentId,
186+
});
187+
const { runCronIsolatedAgentTurn } = await import("../../cron/isolated-agent.js");
188+
const result = await runCronIsolatedAgentTurn({
189+
cfg,
190+
deps,
191+
job,
192+
message: value.message,
183193
sessionKey,
184-
status: result.status,
185-
model: value.model,
186-
summary,
187-
consoleMessage: formatHookRunWarningConsoleMessage({
194+
lane: "cron",
195+
});
196+
const summary = resolveHookRunSummary(result);
197+
const prefix =
198+
result.status === "ok" ? `Hook ${safeName}` : `Hook ${safeName} (${result.status})`;
199+
const shouldAnnounce = shouldAnnounceHookRunResult({ deliver: value.deliver, result });
200+
if (result.status !== "ok") {
201+
logHooks.warn("hook agent run returned non-ok status", {
202+
sourcePath: value.sourcePath,
203+
name: safeName,
204+
runId,
205+
jobId,
206+
agentId: value.agentId,
207+
sessionKey,
188208
status: result.status,
189209
model: value.model,
190210
summary,
191-
}),
192-
});
193-
}
194-
if (shouldAnnounce) {
195-
const eventSessionKey = hookEventSessionKey ?? resolveMainSessionKeyFromConfig();
196-
enqueueSystemEvent(`${prefix}: ${summary}`.trim(), {
197-
sessionKey: eventSessionKey,
211+
consoleMessage: formatHookRunWarningConsoleMessage({
212+
status: result.status,
213+
model: value.model,
214+
summary,
215+
}),
216+
});
217+
}
218+
if (shouldAnnounce) {
219+
const eventSessionKey = hookEventSessionKey ?? resolveMainSessionKeyFromConfig();
220+
enqueueSystemEvent(`${prefix}: ${summary}`.trim(), {
221+
sessionKey: eventSessionKey,
222+
});
223+
if (value.wakeMode === "now") {
224+
requestHeartbeat({ source: "hook", intent: "immediate", reason: `hook:${jobId}` });
225+
}
226+
} else if (result.status === "ok" && !value.deliver) {
227+
logHooks.info("hook agent run completed without announcement", {
228+
sourcePath: value.sourcePath,
229+
name: safeName,
230+
runId,
231+
jobId,
232+
agentId: value.agentId,
233+
sessionKey,
234+
completedAt: new Date().toISOString(),
235+
});
236+
}
237+
} catch (err) {
238+
logHooks.warn(`hook agent failed: ${String(err)}`);
239+
enqueueSystemEvent(`Hook ${safeName} (error): ${String(err)}`, {
240+
sessionKey: hookEventSessionKey ?? resolveMainSessionKeyFromConfig(),
198241
});
199242
if (value.wakeMode === "now") {
200-
requestHeartbeat({ source: "hook", intent: "immediate", reason: `hook:${jobId}` });
243+
requestHeartbeat({
244+
source: "hook",
245+
intent: "immediate",
246+
reason: `hook:${jobId}:error`,
247+
});
201248
}
202-
} else if (result.status === "ok" && !value.deliver) {
203-
logHooks.info("hook agent run completed without announcement", {
204-
sourcePath: value.sourcePath,
205-
name: safeName,
206-
runId,
207-
jobId,
208-
agentId: value.agentId,
209-
sessionKey,
210-
completedAt: new Date().toISOString(),
211-
});
212249
}
213-
} catch (err) {
214-
logHooks.warn(`hook agent failed: ${String(err)}`);
215-
enqueueSystemEvent(`Hook ${safeName} (error): ${String(err)}`, {
216-
sessionKey: hookEventSessionKey ?? resolveMainSessionKeyFromConfig(),
217-
});
218-
if (value.wakeMode === "now") {
219-
requestHeartbeat({
220-
source: "hook",
221-
intent: "immediate",
222-
reason: `hook:${jobId}:error`,
223-
});
224-
}
225-
}
226-
});
250+
}),
251+
);
227252

228253
return runId;
229254
};

0 commit comments

Comments
 (0)