Skip to content

Commit 1dd88c6

Browse files
committed
fix(sessions): harden session id resolution
1 parent 1337be3 commit 1dd88c6

5 files changed

Lines changed: 207 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Docs: https://docs.openclaw.ai
5959
- Discord/proxy: keep Carbon REST, monitor startup, and webhook sends on the configured Discord proxy while falling back cleanly when the proxy URL is invalid, so Discord replies and deploys do not hard-fail on malformed proxy config. (#57465) Thanks @geekhuashan.
6060
- Mobile pairing/device approval: mint both node and operator device tokens when one approval grants merged roles, so mixed mobile bootstrap pairings stop reconnecting as operator-only and showing the node offline. (#60208) Thanks @obviyus.
6161
- Agents/tool policy: stop `tools.profile` warnings from flagging runtime-gated baseline core tools as unknown when the coding profile is missing tools like `code_execution`, `x_search`, `image`, or `image_generate`, while still warning on explicit extra allowlist entries. Thanks @vincentkoc.
62+
- Sessions/resolution: collapse alias-duplicate session-id matches before scoring, keep distinct structural ties ambiguous, and prefer current-store reuse when resolving equal cross-store duplicates so follow-up turns stop dropping or duplicating sessions on timestamp ties.
6263

6364
## 2026.4.2
6465

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { OpenClawConfig } from "../../config/config.js";
3+
import type { SessionEntry } from "../../config/sessions/types.js";
4+
5+
const hoisted = vi.hoisted(() => ({
6+
loadSessionStoreMock: vi.fn<(storePath: string) => Record<string, SessionEntry>>(),
7+
listAgentIdsMock: vi.fn<() => string[]>(),
8+
}));
9+
10+
vi.mock("../../config/sessions.js", async () => {
11+
const actual = await vi.importActual<typeof import("../../config/sessions.js")>(
12+
"../../config/sessions.js",
13+
);
14+
return {
15+
...actual,
16+
loadSessionStore: (storePath: string) => hoisted.loadSessionStoreMock(storePath),
17+
resolveStorePath: (store?: string, params?: { agentId?: string }) =>
18+
`/stores/${params?.agentId ?? "main"}.json`,
19+
resolveAgentIdFromSessionKey: () => "main",
20+
resolveExplicitAgentSessionKey: () => undefined,
21+
};
22+
});
23+
24+
vi.mock("../agent-scope.js", () => ({
25+
listAgentIds: () => hoisted.listAgentIdsMock(),
26+
}));
27+
28+
const { resolveSessionKeyForRequest } = await import("./session.js");
29+
30+
describe("resolveSessionKeyForRequest", () => {
31+
beforeEach(() => {
32+
hoisted.loadSessionStoreMock.mockReset();
33+
hoisted.listAgentIdsMock.mockReset();
34+
hoisted.listAgentIdsMock.mockReturnValue(["main", "other"]);
35+
});
36+
37+
it("prefers the current store when equal duplicates exist across stores", () => {
38+
const mainStore = {
39+
"agent:main:main": { sessionId: "sid", updatedAt: 10 },
40+
} satisfies Record<string, SessionEntry>;
41+
const otherStore = {
42+
"agent:other:main": { sessionId: "sid", updatedAt: 10 },
43+
} satisfies Record<string, SessionEntry>;
44+
hoisted.loadSessionStoreMock.mockImplementation((storePath) => {
45+
if (storePath === "/stores/main.json") {
46+
return mainStore;
47+
}
48+
if (storePath === "/stores/other.json") {
49+
return otherStore;
50+
}
51+
return {};
52+
});
53+
54+
const result = resolveSessionKeyForRequest({
55+
cfg: {
56+
session: {
57+
store: "/stores/{agentId}.json",
58+
},
59+
} satisfies OpenClawConfig,
60+
sessionId: "sid",
61+
});
62+
63+
expect(result.sessionKey).toBe("agent:main:main");
64+
expect(result.sessionStore).toBe(mainStore);
65+
expect(result.storePath).toBe("/stores/main.json");
66+
});
67+
});

‎src/agents/command/session.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,16 +76,21 @@ export function resolveSessionKeyForRequest(opts: {
7676
(!sessionKey || sessionStore[sessionKey]?.sessionId !== opts.sessionId)
7777
) {
7878
const matches: Array<[string, SessionEntry]> = [];
79+
const primaryStoreMatches: Array<[string, SessionEntry]> = [];
7980
const storeByKey = new Map<string, SessionKeyResolution>();
8081
const addMatches = (
8182
candidateStore: Record<string, SessionEntry>,
8283
candidateStorePath: string,
84+
options?: { primary?: boolean },
8385
): void => {
8486
for (const [candidateKey, candidateEntry] of Object.entries(candidateStore)) {
8587
if (candidateEntry?.sessionId !== opts.sessionId) {
8688
continue;
8789
}
8890
matches.push([candidateKey, candidateEntry]);
91+
if (options?.primary) {
92+
primaryStoreMatches.push([candidateKey, candidateEntry]);
93+
}
8994
storeByKey.set(candidateKey, {
9095
sessionKey: candidateKey,
9196
sessionStore: candidateStore,
@@ -94,7 +99,7 @@ export function resolveSessionKeyForRequest(opts: {
9499
}
95100
};
96101

97-
addMatches(sessionStore, storePath);
102+
addMatches(sessionStore, storePath, { primary: true });
98103
const allAgentIds = listAgentIds(opts.cfg);
99104
for (const agentId of allAgentIds) {
100105
if (agentId === storeAgentId) {
@@ -106,12 +111,15 @@ export function resolveSessionKeyForRequest(opts: {
106111
}
107112

108113
const preferredKey = resolvePreferredSessionKeyForSessionIdMatches(matches, opts.sessionId);
109-
if (preferredKey) {
110-
const preferred = storeByKey.get(preferredKey);
114+
const currentStorePreferredKey =
115+
preferredKey ??
116+
resolvePreferredSessionKeyForSessionIdMatches(primaryStoreMatches, opts.sessionId);
117+
if (currentStorePreferredKey) {
118+
const preferred = storeByKey.get(currentStorePreferredKey);
111119
if (preferred) {
112120
return preferred;
113121
}
114-
sessionKey = preferredKey;
122+
sessionKey = currentStorePreferredKey;
115123
}
116124
}
117125

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { describe, expect, it } from "vitest";
2+
import type { SessionEntry } from "../config/sessions/types.js";
3+
import { resolvePreferredSessionKeyForSessionIdMatches } from "./session-id-resolution.js";
4+
5+
function entry(updatedAt: number, sessionId = "s1"): SessionEntry {
6+
return { sessionId, updatedAt };
7+
}
8+
9+
describe("resolvePreferredSessionKeyForSessionIdMatches", () => {
10+
it("returns undefined for empty matches", () => {
11+
expect(resolvePreferredSessionKeyForSessionIdMatches([], "s1")).toBeUndefined();
12+
});
13+
14+
it("returns the only match for a single-element array", () => {
15+
const matches: Array<[string, SessionEntry]> = [["agent:main:main", entry(10)]];
16+
expect(resolvePreferredSessionKeyForSessionIdMatches(matches, "s1")).toBe("agent:main:main");
17+
});
18+
19+
it("collapses alias duplicates before resolving structural ties", () => {
20+
const matches: Array<[string, SessionEntry]> = [
21+
["agent:main:MAIN", entry(10, "main")],
22+
["agent:main:main", entry(10, "main")],
23+
];
24+
25+
expect(resolvePreferredSessionKeyForSessionIdMatches(matches, "main")).toBe("agent:main:main");
26+
});
27+
28+
it("returns the freshest match when timestamps differ", () => {
29+
const matches: Array<[string, SessionEntry]> = [
30+
["agent:main:alpha", entry(10)],
31+
["agent:main:beta", entry(20)],
32+
];
33+
expect(resolvePreferredSessionKeyForSessionIdMatches(matches, "s1")).toBe("agent:main:beta");
34+
});
35+
36+
it("returns undefined for fuzzy-only matches with tied timestamps", () => {
37+
const matches: Array<[string, SessionEntry]> = [
38+
["agent:main:beta", entry(10)],
39+
["agent:main:alpha", entry(10)],
40+
];
41+
expect(resolvePreferredSessionKeyForSessionIdMatches(matches, "s1")).toBeUndefined();
42+
});
43+
44+
it("prefers the freshest structural match over a fresher fuzzy match", () => {
45+
const matches: Array<[string, SessionEntry]> = [
46+
["agent:main:other", entry(999, "run-dup")],
47+
["agent:main:acp:run-dup", entry(100, "run-dup")],
48+
["agent:main:acp2:run-dup", entry(50, "run-dup")],
49+
];
50+
51+
expect(resolvePreferredSessionKeyForSessionIdMatches(matches, "run-dup")).toBe(
52+
"agent:main:acp:run-dup",
53+
);
54+
});
55+
56+
it("preserves ambiguity for distinct structural ties", () => {
57+
const matches: Array<[string, SessionEntry]> = [
58+
["agent:main:b:sid", entry(10, "sid")],
59+
["agent:main:a:sid", entry(10, "sid")],
60+
["agent:main:extra", entry(500, "sid")],
61+
];
62+
63+
expect(resolvePreferredSessionKeyForSessionIdMatches(matches, "sid")).toBeUndefined();
64+
});
65+
});

‎src/sessions/session-id-resolution.ts‎

Lines changed: 62 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,50 @@
11
import type { SessionEntry } from "../config/sessions.js";
22
import { toAgentRequestSessionKey } from "../routing/session-key.js";
33

4+
type SessionIdMatch = [string, SessionEntry];
5+
6+
function compareUpdatedAtDescending(a: SessionIdMatch, b: SessionIdMatch): number {
7+
return (b[1]?.updatedAt ?? 0) - (a[1]?.updatedAt ?? 0);
8+
}
9+
10+
function compareStoreKeys(a: string, b: string): number {
11+
return a < b ? -1 : a > b ? 1 : 0;
12+
}
13+
14+
function collapseAliasMatches(matches: SessionIdMatch[]): SessionIdMatch[] {
15+
const grouped = new Map<string, SessionIdMatch[]>();
16+
for (const match of matches) {
17+
const requestKey = toAgentRequestSessionKey(match[0]) ?? match[0];
18+
const normalizedRequestKey = requestKey.trim().toLowerCase();
19+
const bucket = grouped.get(normalizedRequestKey);
20+
if (bucket) {
21+
bucket.push(match);
22+
} else {
23+
grouped.set(normalizedRequestKey, [match]);
24+
}
25+
}
26+
27+
return Array.from(grouped.values(), (group) => {
28+
if (group.length === 1) {
29+
return group[0];
30+
}
31+
return [...group].toSorted((a, b) => {
32+
const timeDiff = compareUpdatedAtDescending(a, b);
33+
if (timeDiff !== 0) {
34+
return timeDiff;
35+
}
36+
const aNormalizedKey = a[0].trim().toLowerCase();
37+
const bNormalizedKey = b[0].trim().toLowerCase();
38+
const aIsCanonical = a[0] === aNormalizedKey;
39+
const bIsCanonical = b[0] === bNormalizedKey;
40+
if (aIsCanonical !== bIsCanonical) {
41+
return aIsCanonical ? -1 : 1;
42+
}
43+
return compareStoreKeys(aNormalizedKey, bNormalizedKey);
44+
})[0];
45+
});
46+
}
47+
448
export function resolvePreferredSessionKeyForSessionIdMatches(
549
matches: Array<[string, SessionEntry]>,
650
sessionId: string,
@@ -13,7 +57,11 @@ export function resolvePreferredSessionKeyForSessionIdMatches(
1357
}
1458

1559
const loweredSessionId = sessionId.trim().toLowerCase();
16-
const structuralMatches = matches.filter(([storeKey]) => {
60+
const canonicalMatches = collapseAliasMatches(matches);
61+
if (canonicalMatches.length === 1) {
62+
return canonicalMatches[0][0];
63+
}
64+
const structuralMatches = canonicalMatches.filter(([storeKey]) => {
1765
const requestKey = toAgentRequestSessionKey(storeKey)?.toLowerCase();
1866
return (
1967
storeKey.toLowerCase().endsWith(`:${loweredSessionId}`) ||
@@ -25,12 +73,21 @@ export function resolvePreferredSessionKeyForSessionIdMatches(
2573
return structuralMatches[0][0];
2674
}
2775

28-
const sortedMatches = [...matches].toSorted(
29-
(a, b) => (b[1]?.updatedAt ?? 0) - (a[1]?.updatedAt ?? 0),
30-
);
76+
const structuralSorted = [...structuralMatches].toSorted(compareUpdatedAtDescending);
77+
const [freshestStructural, secondFreshestStructural] = structuralSorted;
78+
if (structuralMatches.length > 1) {
79+
if (
80+
(freshestStructural?.[1]?.updatedAt ?? 0) > (secondFreshestStructural?.[1]?.updatedAt ?? 0)
81+
) {
82+
return freshestStructural[0];
83+
}
84+
return undefined;
85+
}
86+
87+
const sortedMatches = [...canonicalMatches].toSorted(compareUpdatedAtDescending);
3188
const [freshest, secondFreshest] = sortedMatches;
3289
if ((freshest?.[1]?.updatedAt ?? 0) > (secondFreshest?.[1]?.updatedAt ?? 0)) {
33-
return freshest?.[0];
90+
return freshest[0];
3491
}
3592

3693
return undefined;

0 commit comments

Comments
 (0)