import type { DreamTask, MemoryScope } from "@/types/memory"; /** Read the console's range; omitted dimensions mean the displayed “All”. */ export function buildMemoryScope(searchParams: URLSearchParams): MemoryScope { return { appId: searchParams.get("appId")?.trim() || "*", tenantId: searchParams.get("tenantId")?.trim() || "*", agentId: searchParams.get("agentId")?.trim() || "*", runId: searchParams.get("runId")?.trim() || "*", }; } export function hasWildcardScope(scope: MemoryScope): boolean { return Object.values(scope).some((value) => value === "*"); } /** All four scope fields are present and none is `*`. */ export function hasPreciseScope(scope: MemoryScope): boolean { return [scope.appId, scope.tenantId, scope.agentId, scope.runId].every( (value) => typeof value === "string" && value.trim().length > 0 && value.trim() !== "*", ); } /** The current SearchMemories contract only requires an exact appId. */ export function hasSearchableScope(scope: MemoryScope): boolean { return !!scope.appId && scope.appId !== "*"; } export function scopeToSearchParams(scope: MemoryScope): URLSearchParams { const params = new URLSearchParams(); params.set("appId", scope.appId); if (scope.tenantId) params.set("tenantId", scope.tenantId); if (scope.agentId) params.set("agentId", scope.agentId); if (scope.runId) params.set("runId", scope.runId); return params; } export function formatScope(scope?: MemoryScope): string { if (!scope) return "-"; return [scope.appId, scope.tenantId, scope.agentId, scope.runId] .filter(Boolean) .join(" / "); } /** * Positional four-tuple label for the scope pickers. Unlike * {@link formatScope}, an empty dimension keeps its slot as `—`, so rows line * up column-wise in a dropdown and "no tenant" reads differently from "no * agent". Shared by both pickers (ScopeCombobox and the ScopeBar) so their * labels can't drift apart. */ export function scopeLabel(scope: MemoryScope): string { return [scope.appId, scope.tenantId, scope.agentId, scope.runId] .map((v) => v || "—") .join(" / "); } /** * A set of dream tasks that share the same input scope. * * The Dream list API returns tasks scope-major (grouped by scope partition, * `createdAt` descending *within* each partition) but NOT globally time * sorted across scopes. Under the default wildcard scope the raw list looks * like its creation times jump around at every scope boundary. Grouping makes * that structure explicit: one header per scope, `createdAt` descending * inside, with the most recently active scope on top. */ export interface DreamTaskGroup { /** Stable identifier for the group (derived from the scope(s)). */ key: string; /** Representative scope — the first input scope of the group's tasks. */ scope: MemoryScope; /** Human-readable scope label, e.g. `app / tenant / agent / run`. */ label: string; /** Tasks in the group, sorted by `createdAt` descending. */ tasks: DreamTask[]; /** Epoch ms of the newest task in the group (used to order groups). */ latest: number; } const MISSING_SCOPE_LABEL = "未知 scope"; function dreamTaskCreatedMs(task: DreamTask): number { const ms = Date.parse(task.createdAt); return Number.isFinite(ms) ? ms : 0; } /** * Group dream tasks by their input scope for display. * * - Multi-scope dreams (more than one `inputScopes` entry) get their own * combined group and never merge into a single-scope group. * - Tasks within a group are sorted by `createdAt` descending (defensive — * the backend already returns them that way within a scope). * - Groups are ordered by their most recent task, descending, so the scope * with the latest activity appears first. */ export function groupDreamTasksByScope(tasks: DreamTask[]): DreamTaskGroup[] { const groups = new Map(); for (const task of tasks) { const scopes = task.inputScopes ?? []; const key = scopes.length > 0 ? scopes.map((s) => formatScope(s)).join(" + ") : MISSING_SCOPE_LABEL; const label = key; let group = groups.get(key); if (!group) { group = { key, scope: scopes[0] ?? { appId: "" }, label, tasks: [], latest: 0, }; groups.set(key, group); } group.tasks.push(task); group.latest = Math.max(group.latest, dreamTaskCreatedMs(task)); } const result = Array.from(groups.values()); for (const group of result) { group.tasks.sort((a, b) => dreamTaskCreatedMs(b) - dreamTaskCreatedMs(a)); } result.sort((a, b) => b.latest - a.latest); return result; } /** How the dream task list is ordered/grouped in the UI. */ export type DreamTaskSortMode = "time_desc" | "time_asc" | "scope"; /** * Order dream tasks globally by `createdAt`, ignoring scope. * * The Dream list API returns tasks scope-major (createdAt desc *within* a * scope, but not globally), so a coherent global timeline must be computed * client-side. Returns a new array; the input is left untouched. Ties break by * `dreamId` so the order is stable across re-renders regardless of direction. */ export function sortDreamTasksByCreatedAt( tasks: DreamTask[], direction: "desc" | "asc", ): DreamTask[] { const sign = direction === "asc" ? 1 : -1; return [...tasks].sort((a, b) => { const diff = dreamTaskCreatedMs(a) - dreamTaskCreatedMs(b); if (diff !== 0) return sign * diff; return sign * a.dreamId.localeCompare(b.dreamId); }); } export function parseJsonObject( value: string, ): Record | undefined { if (!value.trim()) return undefined; let parsed: unknown; try { parsed = JSON.parse(value) as unknown; } catch { throw new Error( '元数据 JSON 格式不正确,请检查引号与括号,例如 {"source":"chat"}', ); } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { throw new Error('元数据需为 JSON 对象,例如 {"source":"chat"}'); } return parsed as Record; } export function parseJsonArray(value: string): T[] | undefined { if (!value.trim()) return undefined; let parsed: unknown; try { parsed = JSON.parse(value) as unknown; } catch { throw new Error("JSON 格式不正确,请检查引号与括号后重试"); } if (!Array.isArray(parsed)) { throw new Error('需要 JSON 数组,例如 [{"key":"value"}]'); } return parsed as T[]; }