import type { FileMemoryScope } from "@/types/file-memory"; export const MAX_RECENT_FILE_SCOPES = 10; const STORAGE_KEY_PREFIX = "tsagent.fileScopes.v1"; type ScopeStorage = Pick; export function getRecentFileScopeStorageKey( dataScopeKey: string, memoryStoreName: string, ): string { return `${STORAGE_KEY_PREFIX}:${JSON.stringify([dataScopeKey, memoryStoreName])}`; } export function normalizeExactFileMemoryScope( value: Partial | null | undefined, ): FileMemoryScope | null { if (!value) return null; const fields = [value.appId, value.tenantId, value.agentId, value.runId]; if ( fields.some( (field) => typeof field !== "string" || !field.trim() || field.trim() === "*", ) ) { return null; } return { appId: value.appId!.trim(), tenantId: value.tenantId!.trim(), agentId: value.agentId!.trim(), runId: value.runId!.trim(), }; } export function isExactFileMemoryScope( value: Partial | null | undefined, ): value is FileMemoryScope { return normalizeExactFileMemoryScope(value) !== null; } export function applyFileScopeToSearchParams( current: URLSearchParams, scope: FileMemoryScope, ): URLSearchParams { const next = new URLSearchParams(current); next.set("view", "files"); next.set("appId", scope.appId); next.set("tenantId", scope.tenantId); next.set("agentId", scope.agentId); next.set("runId", scope.runId); next.delete("file"); return next; } export function readRecentFileScopes( storage: Pick, dataScopeKey: string, memoryStoreName: string, ): FileMemoryScope[] { try { const raw = storage.getItem( getRecentFileScopeStorageKey(dataScopeKey, memoryStoreName), ); if (!raw) return []; const parsed = JSON.parse(raw) as unknown; if (!Array.isArray(parsed)) return []; return parsed .map((item) => normalizeExactFileMemoryScope( item && typeof item === "object" ? (item as Partial) : null, ), ) .filter((item): item is FileMemoryScope => item !== null) .slice(0, MAX_RECENT_FILE_SCOPES); } catch { return []; } } export function rememberRecentFileScope( storage: ScopeStorage, dataScopeKey: string, memoryStoreName: string, value: Partial, ): FileMemoryScope[] { const scope = normalizeExactFileMemoryScope(value); if (!scope) return readRecentFileScopes(storage, dataScopeKey, memoryStoreName); const identity = JSON.stringify(scope); const next = [ scope, ...readRecentFileScopes(storage, dataScopeKey, memoryStoreName).filter( (item) => JSON.stringify(item) !== identity, ), ].slice(0, MAX_RECENT_FILE_SCOPES); try { storage.setItem( getRecentFileScopeStorageKey(dataScopeKey, memoryStoreName), JSON.stringify(next), ); } catch { // Recent navigation history must never block file-memory access. } return next; }