Skip to content

Commit 91d3f53

Browse files
authored
fix: new sessions open promptly in Git workspaces (#124796)
* fix(gateway): unblock new session creation * fix(gateway): fence session baseline capture * chore(types): keep baseline claim private * fix(sessions): settle reset diff baselines * fix(sessions): preserve baseline invalidation * test(agents): consolidate compaction ownership cases * fix(sessions): fail closed on baseline persistence * fix(sessions): fence baseline generations * test(sessions): align authoritative baseline fixtures
1 parent e298277 commit 91d3f53

44 files changed

Lines changed: 1878 additions & 282 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/agents/agent-command.compaction-rotation.test.ts‎

Lines changed: 69 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,17 @@ import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
55
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
6-
import type { SessionEntry } from "../config/sessions.js";
6+
import type { InternalSessionEntry, SessionEntry } from "../config/sessions.js";
77
import { formatSqliteSessionFileMarker } from "../config/sessions/legacy-sqlite-marker.js";
8+
import { SessionWorkStartInvalidatedError } from "../config/sessions/lifecycle.js";
89
import {
910
appendTranscriptEvent,
1011
appendTranscriptMessage,
1112
listSessionEntriesCore,
1213
loadTranscriptEvents,
1314
replaceSessionEntry,
1415
} from "../config/sessions/session-accessor.js";
16+
import { createSessionDiffBaselineCaptureClaim } from "../config/sessions/session-diff-baseline-capture.js";
1517
import type { OpenClawConfig } from "../config/types.openclaw.js";
1618
import { rotateAgentEventLifecycleGeneration } from "../infra/agent-events.js";
1719
import { defaultRuntime } from "../runtime.js";
@@ -23,6 +25,8 @@ import { createAgentRunRestartAbortError } from "./run-termination.js";
2325
type ProviderModelNormalizationParams = { provider: string; context: { modelId: string } };
2426
type LoadManifestModelCatalogParams = Parameters<typeof loadManifestModelCatalog>[0];
2527
type RunAgentAttempt = typeof runAgentAttempt;
28+
type CaptureSessionDiffBaseline =
29+
(typeof import("../sessions/session-diff.js"))["captureSessionDiffBaseline"];
2630
type CliCompactionParams = {
2731
sessionId: string;
2832
sessionEntry?: SessionEntry;
@@ -50,6 +54,13 @@ const state = vi.hoisted(() => ({
5054
deliverAgentCommandResultMock: vi.fn(),
5155
emitAgentEventMock: vi.fn(),
5256
deliveryFreshEntries: [] as Array<SessionEntry | undefined>,
57+
captureSessionDiffBaselineMock: vi.fn<CaptureSessionDiffBaseline>(),
58+
}));
59+
60+
vi.mock("../sessions/session-diff.js", async (importOriginal) => ({
61+
...(await importOriginal<typeof import("../sessions/session-diff.js")>()),
62+
captureSessionDiffBaseline: (params: Parameters<CaptureSessionDiffBaseline>[0]) =>
63+
state.captureSessionDiffBaselineMock(params),
5364
}));
5465

5566
vi.mock("../config/io.js", () => ({
@@ -336,6 +347,46 @@ const COMPACTION_ERROR =
336347
"CLI transcript compaction failed for openai/gpt-5.5: Summarization failed: Connection error.";
337348

338349
describe("agentCommand compaction transcript rotation", () => {
350+
it.each([
351+
["settles a precreated baseline claim before embedded execution", false],
352+
["does not execute after baseline work-start invalidation", true],
353+
] as const)("%s", async (_name, invalidated) => {
354+
const sessionId = invalidated ? "invalidated-agent-command" : "precreated-agent-command",
355+
sessionKey = `agent:main:explicit:${sessionId}`;
356+
await replaceSessionEntry({ sessionKey, storePath: requireStorePath() }, {
357+
sessionId,
358+
sessionDiffBaselineCapture: createSessionDiffBaselineCaptureClaim(),
359+
updatedAt: Date.now(),
360+
} as InternalSessionEntry);
361+
if (invalidated) {
362+
const error = new SessionWorkStartInvalidatedError(
363+
"session changed during baseline settlement",
364+
);
365+
state.captureSessionDiffBaselineMock.mockRejectedValueOnce(error);
366+
await expect(
367+
agentCommand({ message: "must not execute", sessionId, sessionKey }),
368+
).rejects.toBe(error);
369+
expect(state.runAgentAttemptMock).not.toHaveBeenCalled();
370+
return;
371+
}
372+
state.captureSessionDiffBaselineMock.mockResolvedValueOnce({
373+
version: 1,
374+
sessionId,
375+
root: "/workspace",
376+
files: [],
377+
});
378+
state.runAgentAttemptMock.mockImplementationOnce(async () => {
379+
expect(findStoredSessionEntry(sessionKey)?.sessionDiffBaseline).toMatchObject({
380+
version: 1,
381+
sessionId,
382+
});
383+
return makeResult({ sessionId, text: "captured before execution" });
384+
});
385+
386+
await agentCommand({ message: "write after capture", sessionId, sessionKey });
387+
expect(state.captureSessionDiffBaselineMock).toHaveBeenCalledOnce();
388+
});
389+
339390
it("does not re-normalize an exact configured custom provider through plugin runtime", async () => {
340391
state.normalizeProviderModelIdWithRuntimeMock.mockImplementation(
341392
({ provider }: ProviderModelNormalizationParams) => {
@@ -776,17 +827,27 @@ describe("agentCommand compaction transcript rotation", () => {
776827
});
777828
});
778829

779-
it("does not deliver or clear the pending final when restart aborts compaction", async () => {
780-
const sessionId = "restart-during-compaction";
830+
it.each([
831+
["restart-during-compaction", "reply owned by restart recovery"],
832+
["restart-after-successful-compaction", "reply owned by restart recovery after compaction"],
833+
["stale-during-compaction", "reply owned by the next gateway lifecycle"],
834+
] as const)("does not deliver or clear the pending final for %s", async (sessionId, text) => {
835+
const restart = sessionId !== "stale-during-compaction";
781836
const sessionKey = `agent:main:explicit:${sessionId}`;
782-
const text = "reply owned by restart recovery";
783837
const abortController = new AbortController();
784838
state.runAgentAttemptMock.mockResolvedValueOnce(makeResult({ sessionId, text }));
785839
state.runCliTurnCompactionLifecycleMock.mockImplementationOnce(async (params) => {
786840
expect(params.sessionEntry).toMatchObject({
787841
pendingFinalDelivery: { kind: "replayable", text },
788842
});
789-
abortController.abort(createAgentRunRestartAbortError());
843+
if (restart) {
844+
abortController.abort(createAgentRunRestartAbortError());
845+
} else {
846+
rotateAgentEventLifecycleGeneration();
847+
}
848+
if (sessionId === "restart-after-successful-compaction") {
849+
return params.sessionEntry;
850+
}
790851
throw new Error(COMPACTION_ERROR);
791852
});
792853

@@ -802,73 +863,9 @@ describe("agentCommand compaction transcript rotation", () => {
802863
deliver: true,
803864
abortSignal: abortController.signal,
804865
}),
805-
).rejects.toThrow("agent run aborted for restart");
806-
807-
expect(state.deliverAgentCommandResultMock).not.toHaveBeenCalled();
808-
expect(findStoredSessionEntry(sessionKey)).toMatchObject({
809-
pendingFinalDelivery: { kind: "replayable", text },
810-
});
811-
});
812-
813-
it("does not deliver or clear the pending final when restart wins after successful compaction", async () => {
814-
const sessionId = "restart-after-successful-compaction";
815-
const sessionKey = `agent:main:explicit:${sessionId}`;
816-
const text = "reply owned by restart recovery after compaction";
817-
const abortController = new AbortController();
818-
state.runAgentAttemptMock.mockResolvedValueOnce(makeResult({ sessionId, text }));
819-
state.runCliTurnCompactionLifecycleMock.mockImplementationOnce(async (params) => {
820-
expect(params.sessionEntry).toMatchObject({
821-
pendingFinalDelivery: { kind: "replayable", text },
822-
});
823-
abortController.abort(createAgentRunRestartAbortError());
824-
return params.sessionEntry;
825-
});
826-
827-
await expect(
828-
agentCommand({
829-
message: "room message",
830-
sessionId,
831-
sessionKey,
832-
cwd: state.workspaceDir,
833-
channel: "discord",
834-
to: "discord:dm:123",
835-
accountId: "main",
836-
deliver: true,
837-
abortSignal: abortController.signal,
838-
}),
839-
).rejects.toThrow("agent run aborted for restart");
840-
841-
expect(state.deliverAgentCommandResultMock).not.toHaveBeenCalled();
842-
expect(findStoredSessionEntry(sessionKey)).toMatchObject({
843-
pendingFinalDelivery: { kind: "replayable", text },
844-
});
845-
});
846-
847-
it("does not deliver or clear the pending final after lifecycle ownership turns stale", async () => {
848-
const sessionId = "stale-during-compaction";
849-
const sessionKey = `agent:main:explicit:${sessionId}`;
850-
const text = "reply owned by the next gateway lifecycle";
851-
state.runAgentAttemptMock.mockResolvedValueOnce(makeResult({ sessionId, text }));
852-
state.runCliTurnCompactionLifecycleMock.mockImplementationOnce(async (params) => {
853-
expect(params.sessionEntry).toMatchObject({
854-
pendingFinalDelivery: { kind: "replayable", text },
855-
});
856-
rotateAgentEventLifecycleGeneration();
857-
throw new Error(COMPACTION_ERROR);
858-
});
859-
860-
await expect(
861-
agentCommand({
862-
message: "room message",
863-
sessionId,
864-
sessionKey,
865-
cwd: state.workspaceDir,
866-
channel: "discord",
867-
to: "discord:dm:123",
868-
accountId: "main",
869-
deliver: true,
870-
}),
871-
).rejects.toThrow("Agent run belongs to a stale gateway lifecycle");
866+
).rejects.toThrow(
867+
restart ? "agent run aborted for restart" : "Agent run belongs to a stale gateway lifecycle",
868+
);
872869

873870
expect(state.deliverAgentCommandResultMock).not.toHaveBeenCalled();
874871
expect(findStoredSessionEntry(sessionKey)).toMatchObject({

‎src/agents/agent-command.live-model-switch.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,16 @@ const state = vi.hoisted(() => ({
141141
enqueueExecutionIdentityContextAtAdmissionMock: vi.fn(),
142142
}));
143143

144+
vi.mock("../sessions/session-diff-baseline.js", async (importOriginal) => {
145+
const actual = await importOriginal<typeof import("../sessions/session-diff-baseline.js")>();
146+
return {
147+
...actual,
148+
ensureSessionDiffBaseline: vi.fn(
149+
async (params: Parameters<typeof actual.ensureSessionDiffBaseline>[0]) => params.entry,
150+
),
151+
};
152+
});
153+
144154
vi.mock("./model-fallback-runner.js", () => ({
145155
runWithModelFallback: (params: unknown) => state.runWithModelFallbackMock(params),
146156
}));

‎src/agents/agent-command.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@ import { coerceErrorMessage } from "@openclaw/normalization-core/error-coercion"
33
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
44
import type { VerboseLevel } from "../auto-reply/thinking.js";
55
import type { CliDeps } from "../cli/deps.types.js";
6-
import { resolveSessionWorkStartError } from "../config/sessions/lifecycle.js";
6+
import {
7+
isSessionWorkStartInvalidatedError,
8+
resolveSessionWorkStartError,
9+
} from "../config/sessions/lifecycle.js";
710
import { buildRestartRecoveryClaimCleanupPatch } from "../config/sessions/restart-recovery-state.js";
811
import type { RestartRecoveryTerminalDeliveryEvidenceResult } from "../config/sessions/restart-recovery-types.js";
9-
import type { SessionEntry } from "../config/sessions/types.js";
12+
import type { InternalSessionEntry } from "../config/sessions/types.js";
1013
import {
1114
assertAgentRunLifecycleGenerationCurrent,
1215
captureAgentRunLifecycleGeneration,
@@ -277,7 +280,7 @@ async function agentCommandInternal(
277280
}
278281

279282
let currentRunDeliveryPrepared = false;
280-
const prepareDeliveryForRun = async (candidateSessionEntry?: SessionEntry) => {
283+
const prepareDeliveryForRun = async (candidateSessionEntry?: InternalSessionEntry) => {
281284
if (currentRunDeliveryPrepared || opts.deliver !== true) {
282285
return;
283286
}
@@ -335,7 +338,7 @@ async function agentCommandInternal(
335338
? runId
336339
: undefined;
337340
assertAgentRunLifecycleGenerationCurrent(lifecycleGeneration);
338-
const next: SessionEntry = {
341+
const next: InternalSessionEntry = {
339342
...entry,
340343
sessionId,
341344
updatedAt: now,
@@ -386,6 +389,9 @@ async function agentCommandInternal(
386389
sessionStore[sessionKey] = sessionEntry;
387390
}
388391
} catch (error) {
392+
if (isSessionWorkStartInvalidatedError(error)) {
393+
throw error;
394+
}
389395
log.warn(
390396
`session diff baseline capture failed; continuing without attribution filtering: ${coerceErrorMessage(error)}`,
391397
);
@@ -550,7 +556,7 @@ async function agentCommandInternal(
550556
try {
551557
const entry = sessionStore[sessionKey] ?? sessionEntry;
552558
if (entry?.restartRecoveryDeliveryRunId === runId) {
553-
const next: SessionEntry = {
559+
const next: InternalSessionEntry = {
554560
...entry,
555561
...buildRestartRecoveryClaimCleanupPatch({
556562
entry,

‎src/agents/command/session.ts‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ import {
3333
resolvePersistedSessionStoreOwner,
3434
resolvePersistedSessionStoreOwnerForKey,
3535
} from "../../config/sessions/session-store-owner.js";
36-
import type { InternalSessionEntry as SessionEntry } from "../../config/sessions/types.js";
36+
import type { InternalSessionEntry } from "../../config/sessions/types.js";
3737
import type { OpenClawConfig } from "../../config/types.openclaw.js";
3838
import {
3939
classifySessionKeyShape,
@@ -58,8 +58,8 @@ import { transitionMainSessionRecovery } from "../main-session-recovery/main-ses
5858
type SessionResolution = {
5959
sessionId: string;
6060
sessionKey?: string;
61-
sessionEntry?: SessionEntry;
62-
sessionStore?: Record<string, SessionEntry>;
61+
sessionEntry?: InternalSessionEntry;
62+
sessionStore?: Record<string, InternalSessionEntry>;
6363
storePath: string;
6464
isNewSession: boolean;
6565
previousSessionId?: string;
@@ -70,11 +70,11 @@ type SessionResolution = {
7070
type SessionKeyResolution = {
7171
agentId?: string;
7272
sessionKey?: string;
73-
sessionStore: Record<string, SessionEntry>;
73+
sessionStore: Record<string, InternalSessionEntry>;
7474
storePath: string;
7575
};
7676

77-
export function clearRotatedSessionMetadata(entry: SessionEntry): SessionEntry {
77+
export function clearRotatedSessionMetadata(entry: InternalSessionEntry): InternalSessionEntry {
7878
const next = {
7979
...entry,
8080
sessionFile: undefined,
@@ -104,6 +104,7 @@ export function clearRotatedSessionMetadata(entry: SessionEntry): SessionEntry {
104104
restartRecoveryTerminalRunIds: undefined,
105105
sessionStartedAt: undefined,
106106
sessionDiffBaseline: undefined,
107+
sessionDiffBaselineCapture: undefined,
107108
lastInteractionAt: undefined,
108109
pendingTranscriptRepair: undefined,
109110
};
@@ -119,7 +120,7 @@ type SessionIdMatchSet = {
119120

120121
type SessionIdMatchCandidate = {
121122
sessionKey: string;
122-
entry: SessionEntry;
123+
entry: InternalSessionEntry;
123124
resolution: SessionKeyResolution;
124125
primary: boolean;
125126
};
@@ -153,7 +154,7 @@ function loadCommandSessionStore(params: {
153154
agentId?: string;
154155
clone?: boolean;
155156
storePath: string;
156-
}): Record<string, SessionEntry> {
157+
}): Record<string, InternalSessionEntry> {
157158
return Object.fromEntries(
158159
listSessionEntriesCore({
159160
storePath: params.storePath,
@@ -173,7 +174,7 @@ export function buildExplicitSessionIdSessionKey(params: {
173174

174175
function collectSessionIdMatchesForRequest(opts: {
175176
cfg: OpenClawConfig;
176-
sessionStore: Record<string, SessionEntry>;
177+
sessionStore: Record<string, InternalSessionEntry>;
177178
storePath: string;
178179
storeAgentId?: string;
179180
sessionId: string;
@@ -196,7 +197,7 @@ function collectSessionIdMatchesForRequest(opts: {
196197
}
197198

198199
const addMatches = (
199-
candidateStore: Record<string, SessionEntry>,
200+
candidateStore: Record<string, InternalSessionEntry>,
200201
candidateStorePath: string,
201202
candidateAgentId: string | undefined,
202203
options?: { primary?: boolean },

‎src/auto-reply/reply/agent-runner-direct-runtime-config.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
44
import { FailoverError } from "../../agents/failover-error.js";
55
import { replaceSessionEntry } from "../../config/sessions/session-accessor.js";
66
import type { SessionEntry } from "../../config/sessions/types.js";
7+
import { createDeferredCore } from "../../shared/deferred.js";
78
import { withTestDir } from "../../test-helpers/temp-dir.js";
89
import { getReplyPayloadMetadata } from "../reply-payload.js";
910
import type { TemplateContext } from "../templating.js";
@@ -429,6 +430,7 @@ describe("runReplyAgent runtime config", () => {
429430
};
430431
},
431432
);
433+
const baselineSettlement = createDeferredCore();
432434
resetReplyRunSessionMock.mockImplementation(async (params: unknown) => {
433435
const resetParams = params as {
434436
activeSessionEntry?: SessionEntry;
@@ -448,14 +450,19 @@ describe("runReplyAgent runtime config", () => {
448450
resetParams.activeSessionStore[sessionKey] = nextEntry;
449451
}
450452
await replaceSessionEntry({ storePath, sessionKey }, nextEntry);
453+
await baselineSettlement.promise;
451454
resetParams.followupRun.run.sessionId = nextEntry.sessionId;
452455
resetParams.followupRun.run.sessionFile = sessionFile;
453456
resetParams.onActiveSessionEntry(nextEntry);
454457
resetParams.onNewSession(nextEntry.sessionId, sessionFile);
455458
return true;
456459
});
457460

458-
const result = await runReplyAgent(replyParams);
461+
const resultPromise = runReplyAgent(replyParams);
462+
await vi.waitFor(() => expect(resetReplyRunSessionMock).toHaveBeenCalledOnce());
463+
expect(executeAgentTurnMock).not.toHaveBeenCalled();
464+
baselineSettlement.resolve();
465+
const result = await resultPromise;
459466

460467
expect(result).toEqual({ text: "main reply" });
461468
expect(resetReplyRunSessionMock).toHaveBeenCalledOnce();

0 commit comments

Comments
 (0)