fix: canonicalize legacy main session aliases

This commit is contained in:
Gustavo Madeira Santana
2026-04-19 17:59:46 -04:00
parent 1a98cc03b9
commit c79a5f324e
6 changed files with 158 additions and 7 deletions

View File

@@ -1,7 +1,8 @@
import { resolveStorePath, updateSessionStore } from "../config/sessions.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { resolveStoredSessionOwnerAgentId } from "../gateway/session-store-key.js";
import { getLogger } from "../logging/logger.js";
import { resolveAgentIdFromSessionKey } from "../routing/session-key.js";
import { normalizeAgentId } from "../routing/session-key.js";
import type { RuntimeEnv } from "../runtime.js";
import {
requireValidConfigFileSnapshot as requireValidConfigFileSnapshotBase,
@@ -26,10 +27,17 @@ export async function purgeAgentSessionStoreEntries(
agentId: string,
): Promise<void> {
try {
const storePath = resolveStorePath(cfg.session?.store, { agentId });
const normalizedAgentId = normalizeAgentId(agentId);
const storePath = resolveStorePath(cfg.session?.store, { agentId: normalizedAgentId });
await updateSessionStore(storePath, (store) => {
for (const key of Object.keys(store)) {
if (resolveAgentIdFromSessionKey(key) === agentId) {
if (
resolveStoredSessionOwnerAgentId({
cfg,
agentId: normalizedAgentId,
sessionKey: key,
}) === normalizedAgentId
) {
delete store[key];
}
}

View File

@@ -41,7 +41,7 @@ describe("agents delete command", () => {
it("purges deleted agent entries from the session store", async () => {
await withStateDirEnv("openclaw-agents-delete-", async ({ stateDir }) => {
const cfg = {
const cfg: OpenClawConfig = {
agents: {
list: [
{ id: "main", workspace: path.join(stateDir, "workspace-main") },
@@ -81,4 +81,39 @@ describe("agents delete command", () => {
});
});
});
it("purges legacy main-alias entries owned by the deleted default agent", async () => {
await withStateDirEnv("openclaw-agents-delete-main-alias-", async ({ stateDir }) => {
const cfg: OpenClawConfig = {
agents: {
list: [{ id: "ops", default: true, workspace: path.join(stateDir, "workspace-ops") }],
},
};
const storePath = resolveStorePath(cfg.session?.store, { agentId: "ops" });
await saveSessionStore(storePath, {
"agent:main:main": { sessionId: "sess-default-alias", updatedAt: 1 },
"agent:ops:discord:direct:u1": { sessionId: "sess-ops-direct", updatedAt: 2 },
"agent:main:discord:direct:u2": { sessionId: "sess-stale-main", updatedAt: 3 },
global: { sessionId: "sess-global", updatedAt: 4 },
});
await fs.mkdir(path.join(stateDir, "workspace-ops"), { recursive: true });
await fs.mkdir(path.join(stateDir, "agents", "ops", "agent"), { recursive: true });
configMocks.readConfigFileSnapshot.mockResolvedValue({
...baseConfigSnapshot,
config: cfg,
runtimeConfig: cfg,
sourceConfig: cfg,
resolved: cfg,
});
await agentsDeleteCommand({ id: "ops", force: true, json: true }, runtime);
expect(runtime.exit).not.toHaveBeenCalled();
expect(loadSessionStore(storePath, { skipCache: true })).toEqual({
"agent:main:discord:direct:u2": { sessionId: "sess-stale-main", updatedAt: 3 },
global: { sessionId: "sess-global", updatedAt: 4 },
});
});
});
});

View File

@@ -69,6 +69,7 @@ describe("sessions.send completed subagent follow-up status", () => {
};
loadSessionEntryMock.mockReturnValue({
cfg: {},
canonicalKey: childSessionKey,
storePath: "/tmp/sessions.json",
entry: { sessionId: "sess-followup" },

View File

@@ -107,6 +107,35 @@ export function resolveSessionStoreAgentId(cfg: OpenClawConfig, canonicalKey: st
return resolveDefaultStoreAgentId(cfg);
}
export function resolveStoredSessionKeyForAgentStore(params: {
cfg: OpenClawConfig;
agentId: string;
sessionKey: string;
}): string {
const raw = normalizeOptionalString(params.sessionKey) ?? "";
if (!raw) {
return raw;
}
const lowered = normalizeLowercaseStringOrEmpty(raw);
if (lowered === "global" || lowered === "unknown") {
return lowered;
}
const key = parseAgentSessionKey(raw) ? raw : canonicalizeSessionKeyForAgent(params.agentId, raw);
return resolveSessionStoreKey({ cfg: params.cfg, sessionKey: key });
}
export function resolveStoredSessionOwnerAgentId(params: {
cfg: OpenClawConfig;
agentId: string;
sessionKey: string;
}): string | null {
const canonicalKey = resolveStoredSessionKeyForAgentStore(params);
if (canonicalKey === "global" || canonicalKey === "unknown") {
return null;
}
return resolveSessionStoreAgentId(params.cfg, canonicalKey);
}
export function canonicalizeSpawnedByForAgent(
cfg: OpenClawConfig,
agentId: string,

View File

@@ -63,10 +63,10 @@ import {
import { normalizeSessionDeliveryFields } from "../utils/delivery-context.shared.js";
import { estimateUsageCost, resolveModelCostConfig } from "../utils/usage-format.js";
import {
canonicalizeSessionKeyForAgent,
canonicalizeSpawnedByForAgent,
resolveSessionStoreAgentId,
resolveSessionStoreKey,
resolveStoredSessionKeyForAgentStore,
} from "./session-store-key.js";
import {
readLatestSessionUsageFromTranscript,
@@ -927,7 +927,11 @@ export function loadCombinedSessionStoreForGateway(cfg: OpenClawConfig): {
const store = loadSessionStore(storePath);
const combined: Record<string, SessionEntry> = {};
for (const [key, entry] of Object.entries(store)) {
const canonicalKey = canonicalizeSessionKeyForAgent(defaultAgentId, key);
const canonicalKey = resolveStoredSessionKeyForAgentStore({
cfg,
agentId: defaultAgentId,
sessionKey: key,
});
mergeSessionEntryIntoCombined({
cfg,
combined,
@@ -946,7 +950,11 @@ export function loadCombinedSessionStoreForGateway(cfg: OpenClawConfig): {
const storePath = target.storePath;
const store = loadSessionStore(storePath);
for (const [key, entry] of Object.entries(store)) {
const canonicalKey = canonicalizeSessionKeyForAgent(agentId, key);
const canonicalKey = resolveStoredSessionKeyForAgentStore({
cfg,
agentId,
sessionKey: key,
});
mergeSessionEntryIntoCombined({
cfg,
combined,

View File

@@ -0,0 +1,70 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { saveSessionStore } from "../config/sessions.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { withStateDirEnv } from "../test-helpers/state-dir-env.js";
import { ErrorCodes } from "./protocol/index.js";
import { resolveSessionKeyFromResolveParams } from "./sessions-resolve.js";
describe("resolveSessionKeyFromResolveParams store canonicalization", () => {
it("resolves legacy main-alias matches by sessionId and label for the configured default agent", async () => {
await withStateDirEnv("openclaw-sessions-resolve-alias-", async ({ stateDir }) => {
const storePath = path.join(stateDir, "sessions.json");
const cfg = {
session: { store: storePath, mainKey: "main" },
agents: { list: [{ id: "ops", default: true }] },
} satisfies OpenClawConfig;
await saveSessionStore(storePath, {
"agent:main:main": {
sessionId: "sess-default-alias",
label: "default-alias",
updatedAt: 1,
},
});
await expect(
resolveSessionKeyFromResolveParams({
cfg,
p: { sessionId: "sess-default-alias" },
}),
).resolves.toEqual({ ok: true, key: "agent:ops:main" });
await expect(
resolveSessionKeyFromResolveParams({
cfg,
p: { label: "default-alias" },
}),
).resolves.toEqual({ ok: true, key: "agent:ops:main" });
});
});
it("still rejects non-alias agent:main matches when main is no longer configured", async () => {
await withStateDirEnv("openclaw-sessions-resolve-stale-main-", async ({ stateDir }) => {
const storePath = path.join(stateDir, "sessions.json");
const cfg = {
session: { store: storePath, mainKey: "main" },
agents: { list: [{ id: "ops", default: true }] },
} satisfies OpenClawConfig;
await saveSessionStore(storePath, {
"agent:main:discord:direct:u1": {
sessionId: "sess-stale-main",
label: "stale-main",
updatedAt: 1,
},
});
await expect(
resolveSessionKeyFromResolveParams({
cfg,
p: { sessionId: "sess-stale-main" },
}),
).resolves.toEqual({
ok: false,
error: {
code: ErrorCodes.INVALID_REQUEST,
message: 'Agent "main" no longer exists in configuration',
},
});
});
});
});