Skip to content

Commit 02f7c7a

Browse files
authored
fix(cron): initialize detached hook run sessions (#115765)
1 parent 85afb97 commit 02f7c7a

2 files changed

Lines changed: 80 additions & 19 deletions

File tree

‎src/cron/isolated-agent.session-identity.test.ts‎

Lines changed: 75 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import fs from "node:fs/promises";
44
import path from "node:path";
55
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
66
import * as modelThinkingDefault from "../agents/model-thinking-default.js";
7+
import { SessionManager } from "../agents/sessions/index.js";
78
import { upsertSessionEntry } from "../config/sessions/session-accessor.js";
89
import { runCronIsolatedAgentTurn } from "./isolated-agent.js";
910
import {
@@ -78,6 +79,48 @@ function lastEmbeddedAgentCall(): {
7879
};
7980
}
8081

82+
function mockEmbeddedTranscriptWrite(
83+
storePath: string,
84+
content: string,
85+
resultMeta?: {
86+
sessionId?: string;
87+
sessionFile?: string;
88+
compactionCount?: number;
89+
compactionTokensAfter?: number;
90+
},
91+
): void {
92+
runEmbeddedAgentMock.mockImplementationOnce(async (input: Record<string, unknown>) => {
93+
const agentId = typeof input.agentId === "string" ? input.agentId : "main";
94+
const sessionId = typeof input.sessionId === "string" ? input.sessionId : "";
95+
const sessionKey = typeof input.sessionKey === "string" ? input.sessionKey : "";
96+
const workspaceDir =
97+
typeof input.workspaceDir === "string" ? input.workspaceDir : process.cwd();
98+
const manager = SessionManager.open(
99+
{ agentId, sessionId, sessionKey, storePath },
100+
workspaceDir,
101+
);
102+
manager.appendMessage({ role: "user", content, timestamp: Date.now() });
103+
return {
104+
payloads: [{ text: "ok" }],
105+
meta: {
106+
durationMs: 5,
107+
agentMeta: {
108+
sessionId: resultMeta?.sessionId ?? sessionId,
109+
...(resultMeta?.sessionFile ? { sessionFile: resultMeta.sessionFile } : {}),
110+
provider: "anthropic",
111+
model: "claude-opus-4-6",
112+
...(resultMeta?.compactionCount !== undefined
113+
? { compactionCount: resultMeta.compactionCount }
114+
: {}),
115+
...(resultMeta?.compactionTokensAfter !== undefined
116+
? { compactionTokensAfter: resultMeta.compactionTokensAfter }
117+
: {}),
118+
},
119+
},
120+
};
121+
});
122+
}
123+
81124
describe("runCronIsolatedAgentTurn session identity", () => {
82125
beforeAll(async () => {
83126
resetRunCronIsolatedAgentTurnHarness();
@@ -178,6 +221,32 @@ describe("runCronIsolatedAgentTurn session identity", () => {
178221
});
179222
});
180223

224+
it.each([
225+
["cron", "cron:job-1"],
226+
["hook", "hook:webhook:request-1"],
227+
])("initializes the exact %s run session before transcript writes", async (_name, sessionKey) => {
228+
await useRealCronSessionState();
229+
await withTempHome(async (home) => {
230+
const storePath = await writeSessionStore(home, { lastProvider: "webchat", lastTo: "" });
231+
mockEmbeddedTranscriptWrite(storePath, `${sessionKey} transcript`);
232+
233+
const { res } = await runCronTurn(home, {
234+
jobPayload: {
235+
kind: "agentTurn",
236+
message: "persist this turn",
237+
...(sessionKey.startsWith("hook:") ? { externalContentSource: "webhook" as const } : {}),
238+
},
239+
message: "persist this turn",
240+
mockTexts: null,
241+
sessionKey,
242+
storePath,
243+
});
244+
245+
expect(res.status, res.status === "error" ? res.error : undefined).toBe("ok");
246+
expect(res.sessionKey).toMatch(/^agent:main:cron:job-1:run:/);
247+
});
248+
});
249+
181250
it("persists rotated transcript identity for current-bound cron runs", async () => {
182251
await withTempHome(async (home) => {
183252
const deps = makeDeps();
@@ -194,20 +263,6 @@ describe("runCronIsolatedAgentTurn session identity", () => {
194263
systemSent: true,
195264
},
196265
});
197-
runEmbeddedAgentMock.mockResolvedValueOnce({
198-
payloads: [{ text: "ok" }],
199-
meta: {
200-
durationMs: 5,
201-
agentMeta: {
202-
sessionId: "bound-session-rotated",
203-
sessionFile: rotatedSessionFile,
204-
provider: "anthropic",
205-
model: "claude-opus-4-6",
206-
compactionCount: 1,
207-
compactionTokensAfter: 42,
208-
},
209-
},
210-
});
211266
const currentBoundJob = normalizeCronJobCreate(
212267
{
213268
...makeJob(DEFAULT_AGENT_TURN_PAYLOAD),
@@ -217,6 +272,12 @@ describe("runCronIsolatedAgentTurn session identity", () => {
217272
{ sessionContext: { sessionKey: boundSessionKey } },
218273
) as CronJob;
219274
const executionSessionKey = `agent:main:cron:${currentBoundJob.id}`;
275+
mockEmbeddedTranscriptWrite(storePath, "current-bound transcript", {
276+
sessionId: "bound-session-rotated",
277+
sessionFile: rotatedSessionFile,
278+
compactionCount: 1,
279+
compactionTokensAfter: 42,
280+
});
220281

221282
const res = await runCronIsolatedAgentTurn({
222283
cfg: makeCfg(home, storePath),

‎src/cron/isolated-agent/run-prepare.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -248,10 +248,10 @@ export async function prepareCronRunContext(params: {
248248
}
249249
const runSessionId = cronSession.sessionEntry.sessionId;
250250
const currentRunSessionId = () => cronSession.sessionEntry.sessionId ?? runSessionId;
251-
const runSessionKey =
252-
usesDetachedRunSession || baseSessionKey.startsWith("cron:")
253-
? `${agentSessionKey}:run:${runSessionId}`
254-
: agentSessionKey;
251+
const usesExactRunSession = usesDetachedRunSession || baseSessionKey.startsWith("cron:");
252+
const runSessionKey = usesExactRunSession
253+
? `${agentSessionKey}:run:${runSessionId}`
254+
: agentSessionKey;
255255
const persistCronSessionRow = async ({
256256
storePath,
257257
sessionKey,
@@ -663,7 +663,7 @@ export async function prepareCronRunContext(params: {
663663
? cronSession.sessionEntry.authProfileOverrideSource
664664
: undefined,
665665
};
666-
const runContinuationSession = baseSessionKey.startsWith("cron:")
666+
const runContinuationSession = usesExactRunSession
667667
? createCronRunContinuationSession({
668668
cronSession,
669669
runSessionKey,

0 commit comments

Comments
 (0)