fix(chat): migrate legacy character cache identities

This commit is contained in:
2026-07-20 17:44:22 +08:00
parent 10132652c7
commit 159e8bfd59
6 changed files with 435 additions and 8 deletions
+37
View File
@@ -1,6 +1,9 @@
import type { ChatMediaKind } from "@/data/schemas/chat";
import { normalizeLegacyCharacterId } from "@/data/constants/character_id_aliases";
const CHARACTER_NAMESPACE = "::character:";
const LEGACY_OWNER_KEY_PATTERN = /^(?:user|device):.+$/u;
const LEGACY_DEFAULT_CHARACTER_ID = "elio";
export function buildChatConversationKey(
ownerKey: string,
@@ -19,3 +22,37 @@ export function buildChatMediaCacheKey(input: {
}): string {
return `${input.ownerKey}:${input.messageId}:${input.kind}`;
}
/**
* Migrates both pre-character owner keys and keys containing the first
* frontend-only character IDs. This is intentionally idempotent so it can be
* used by database upgrades and compatibility reads.
*/
export function migrateLegacyChatConversationKey(ownerKey: string): string {
const namespaceIndex = ownerKey.lastIndexOf(CHARACTER_NAMESPACE);
if (namespaceIndex < 0) {
return LEGACY_OWNER_KEY_PATTERN.test(ownerKey)
? buildChatConversationKey(ownerKey, LEGACY_DEFAULT_CHARACTER_ID)
: ownerKey;
}
const encodedCharacterId = ownerKey.slice(
namespaceIndex + CHARACTER_NAMESPACE.length,
);
if (encodedCharacterId.length === 0) return ownerKey;
let characterId: string;
try {
characterId = decodeURIComponent(encodedCharacterId);
} catch {
return ownerKey;
}
const normalizedCharacterId = normalizeLegacyCharacterId(characterId);
if (normalizedCharacterId === characterId) return ownerKey;
return buildChatConversationKey(
ownerKey.slice(0, namespaceIndex),
normalizedCharacterId,
);
}