"use client"; import { useMemo, useState } from "react"; import Link from "next/link"; import { toast } from "sonner"; import { Sparkles } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Skeleton } from "@/components/ui/skeleton"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Slider } from "@/components/ui/slider"; import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, } from "@/components/ui/sheet"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { useApplyDreamActions } from "@/hooks/use-apply-dream-actions"; import { useDreamActions } from "@/hooks/use-dream-actions"; import { useMemoryUnit } from "@/hooks/use-memory-unit"; import type { DreamActionFilter, DreamActionListOrderBy, DreamActionRecord, DreamActionStatus, DreamActionType, MemoryScope, } from "@/types/memory"; import { cn } from "@/lib/utils"; import { useI18n } from "@/i18n/i18n-context"; import type { MessageKey, TranslateFn } from "@/i18n/i18n-context"; import { MemoryDreamApplyConfirmDialog } from "./memory-dream-apply-confirm-dialog"; interface DreamActionsTableProps { memoryStoreName: string; dreamId: string; taskType?: string; artifactWikiHref?: (action: DreamActionRecord) => string | undefined; } const STATUS_CLASS: Record = { proposed: "bg-info-soft text-info", applied: "bg-success-soft text-success", skipped: "bg-muted text-muted-foreground", failed: "bg-danger-soft text-danger", }; const STATUS_LABEL_KEY: Record = { proposed: "memory.actionStatus.proposed", applied: "memory.actionStatus.applied", skipped: "memory.actionStatus.skipped", failed: "memory.actionStatus.failed", }; const ACTION_CLASS: Record = { ADD: "bg-success-soft text-success", UPDATE: "bg-info-soft text-info", DELETE: "bg-danger-soft text-danger", MERGE: "bg-[hsl(var(--primary-soft))] text-[hsl(var(--primary))]", NOOP: "bg-muted text-muted-foreground", EMIT_SKILL: "bg-success-soft text-success", EMIT_PROFILE: "bg-[hsl(var(--primary-soft))] text-[hsl(var(--primary))]", }; function ActionBadge({ action }: { action: DreamActionType }) { return ( {action} ); } /** * Action-type-aware preview rendered in the row "影响" column. * * The single piece of text most users want at-a-glance differs by action: * - ADD: the new memory's content (only the "after" exists) * - UPDATE: 旧 → 新 contrast, but loading both per-row blows up the table * with N+1 fetches; we fall back to "新文" with a hint that the * drawer shows full diff. * - DELETE: 原文 (the thing being removed) — without it the row is opaque. * Cheap to render — see InlineMemoryPreview below. * - MERGE: same shape as DELETE — show 被合并的原文. * - NOOP: reason takes the slot since there is no memory text to show. * * Memory fetches are scoped to actions where the row preview is the only * way to make the action legible (DELETE / MERGE / NOOP), so the table * does at most one fetch per such row instead of every row. */ function ActionRowPreview({ action, memoryStoreName, t, }: { action: DreamActionRecord; memoryStoreName: string; t: TranslateFn; }) { const { action: type, newMemory, newExtract, targetMemoryId, targetScope, reason, } = action; if (type === "EMIT_SKILL" || type === "EMIT_PROFILE") { if (!newExtract) return —; return ( {type === "EMIT_SKILL" ? t("memory.dream.actions.skill") : t("memory.dream.actions.profile")} {newExtract.name} {newExtract.description && ( {" "} — {newExtract.description} )} ); } if (type === "ADD" || type === "UPDATE") { const text = newMemory?.text; if (!text) return —; return ( {type === "UPDATE" && ( {t("memory.dream.actions.new")} )} {text} ); } if (type === "NOOP") { return ( {reason || t("memory.dream.actions.noop")} ); } // DELETE / MERGE — render the original memory text inline. return ( ); } /** * Lazy memory text loader for a single row. Skipped fetches return a dash * placeholder so the column never shows a hot spinner that would distract * from rows that *do* have text inline. */ function InlineMemoryPreview({ memoryStoreName, memoryId, scope, verbPrefix, t, }: { memoryStoreName: string; memoryId: string | undefined; scope: MemoryScope; verbPrefix: string; t: TranslateFn; }) { const query = useMemoryUnit(memoryStoreName, memoryId, scope); if (!memoryId) { return —; } if (query.isLoading) { return ; } const text = query.data?.memory?.text; if (!text) { return ( {t("memory.dream.actions.memoryUnreadable", { verb: verbPrefix })} ); } return ( {verbPrefix} {text} ); } function StatusPill({ status, t, }: { status: DreamActionStatus; t: TranslateFn; }) { const labelKey = STATUS_LABEL_KEY[status]; return ( {labelKey ? t(labelKey) : status} ); } function scopeLabel(scope?: MemoryScope): string { if (!scope) return "-"; return ( [scope.appId, scope.tenantId, scope.agentId, scope.runId] .filter(Boolean) .join(" / ") || "-" ); } export function MemoryDreamActionsTable({ memoryStoreName, dreamId, taskType, artifactWikiHref, }: DreamActionsTableProps) { const { t } = useI18n(); const STATUS_OPTIONS = useMemo< Array<{ value: DreamActionStatus | "all"; label: string }> >( () => [ { value: "all", label: t("memory.dream.actions.allStatus") }, { value: "proposed", label: t("memory.actionStatus.proposed") }, { value: "applied", label: t("memory.actionStatus.applied") }, { value: "skipped", label: t("memory.actionStatus.skipped") }, { value: "failed", label: t("memory.actionStatus.failed") }, ], [t], ); const ACTION_OPTIONS = useMemo< Array<{ value: DreamActionType | "all"; label: string }> >( () => [ { value: "all", label: t("memory.dream.actions.allTypes") }, { value: "ADD", label: "ADD" }, { value: "UPDATE", label: "UPDATE" }, { value: "DELETE", label: "DELETE" }, { value: "MERGE", label: "MERGE" }, { value: "NOOP", label: "NOOP" }, { value: "EMIT_SKILL", label: "EMIT_SKILL" }, { value: "EMIT_PROFILE", label: "EMIT_PROFILE" }, ], [t], ); const ORDER_OPTIONS = useMemo< Array<{ value: DreamActionListOrderBy; label: string }> >( () => [ { value: "created_at_asc", label: t("memory.dream.actions.orderCreatedAsc"), }, { value: "created_at_desc", label: t("memory.dream.actions.orderCreatedDesc"), }, { value: "confidence_desc", label: t("memory.dream.actions.orderConfidenceDesc"), }, ], [t], ); const isExtractTask = taskType === "skill" || taskType === "profile"; const [statusFilter, setStatusFilter] = useState("all"); const [actionFilter, setActionFilter] = useState("all"); const [orderBy, setOrderBy] = useState("created_at_asc"); const [minConfidence, setMinConfidence] = useState(0); const filter: DreamActionFilter = useMemo(() => { const f: DreamActionFilter = { orderBy }; if (statusFilter !== "all") f.status = statusFilter as DreamActionStatus; if (actionFilter !== "all") f.action = actionFilter as DreamActionType; if (minConfidence > 0) f.minConfidence = minConfidence; return f; }, [statusFilter, actionFilter, orderBy, minConfidence]); const query = useDreamActions(memoryStoreName, dreamId, filter, { limit: 100, }); const actions = query.data?.items ?? []; const [selected, setSelected] = useState>(new Set()); const [detail, setDetail] = useState(null); const [confirmOpen, setConfirmOpen] = useState(false); const applyMutation = useApplyDreamActions(memoryStoreName, dreamId); const isApplyable = (a: DreamActionRecord) => a.status === "proposed" && a.action !== "EMIT_SKILL" && a.action !== "EMIT_PROFILE"; const proposedCount = actions.filter(isApplyable).length; const allSelectedProposedSelected = proposedCount > 0 && actions.every((a) => !isApplyable(a) || selected.has(a.actionId)); const toggleAll = () => { if (allSelectedProposedSelected) { setSelected(new Set()); } else { setSelected(new Set(actions.filter(isApplyable).map((a) => a.actionId))); } }; const toggleOne = (id: string) => { setSelected((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); }; const onApply = async () => { try { const result = await applyMutation.mutateAsync({ actionIds: Array.from(selected), }); toast.success( t("memory.dream.actions.applyResult", { applied: result.applied, failed: result.failed, }), ); setSelected(new Set()); setConfirmOpen(false); } catch (err) { const message = err instanceof Error ? err.message : t("memory.dream.actions.applyFailed"); toast.error(message); } }; return (
{!isExtractTask && ( )} {!isExtractTask && ( <>
{t("memory.dream.actions.minConfidence")} setMinConfidence(v[0] ?? 0)} className="w-32" /> {minConfidence.toFixed(2)}
{t("memory.dream.actions.selectedCount", { count: selected.size, })}
)}
{query.isLoading ? (
) : actions.length === 0 ? (
{isExtractTask ? t("memory.dream.actions.emptyExtract") : t("memory.dream.actions.emptyFiltered")}
) : (
{!isExtractTask && ( )} {isExtractTask ? t("memory.dream.actions.colOutputType") : t("memory.dream.actions.colType")} {t("memory.dream.actions.colStatus")} {t("memory.common.targetScope")} {isExtractTask ? t("memory.dream.actions.colContent") : t("memory.dream.actions.colImpact")} {!isExtractTask && ( {t("memory.dream.actions.colConfidence")} )} {actions.map((action) => { const canApply = isApplyable(action); const wikiHref = artifactWikiHref?.(action); return ( setDetail(action)} > {!isExtractTask && ( e.stopPropagation()}> {canApply ? ( toggleOne(action.actionId)} aria-label={t( "memory.dream.actions.selectAction", )} /> ) : ( {t("memory.dream.actions.onlyProposedApply")} )} )} {scopeLabel(action.targetScope)} {wikiHref ? ( event.stopPropagation()} > {t("memory.dream.actions.openInWiki")} ) : null} {!isExtractTask && ( {action.confidence !== undefined ? action.confidence.toFixed(2) : "-"} )} ); })}
)} !o && setDetail(null)} > {detail && ( )} selected.has(a.actionId))} onConfirm={onApply} busy={applyMutation.isPending} />
); } /** * Side-by-side "before / after" panel keyed off action type: * * - ADD: only "新记忆" matters (no before). * - UPDATE: 原 memory text → newMemory.text, the canonical diff. * - DELETE: 原 memory text alone, with the "after = removed" framing. * - MERGE: same as DELETE — the merge target is the surviving memory, * which we don't try to fetch here because the SDK doesn't * give us a stable `mergedIntoMemoryId` field. * - NOOP: no memory to show; reason carries the explanation. * * The before-panel calls useMemoryUnit only when targetMemoryId exists * and the action type actually wants a "before" — so ADD never triggers * an unnecessary fetch. */ function ActionMemoryPreviewPanel({ detail, memoryStoreName, t, }: { detail: DreamActionRecord; memoryStoreName: string; t: TranslateFn; }) { const isExtract = detail.action === "EMIT_SKILL" || detail.action === "EMIT_PROFILE"; const wantsBefore = !isExtract && (detail.action === "UPDATE" || detail.action === "DELETE" || detail.action === "MERGE"); const beforeQuery = useMemoryUnit( memoryStoreName, wantsBefore ? detail.targetMemoryId : undefined, wantsBefore ? detail.targetScope : null, wantsBefore, ); const newText = detail.newMemory?.text; if (isExtract) { const extract = detail.newExtract; if (!extract) { return (
{t("memory.dream.actions.noExtractResult")}
); } const isSkill = detail.action === "EMIT_SKILL" || extract.kind === "skill"; return (
{isSkill ? t("memory.dream.actions.skill") : t("memory.dream.actions.profile")} {extract.name}
{extract.description && (

{extract.description}

)} {extract.instructions && (

{t("memory.dream.actions.instructions")}

              {extract.instructions}
            
)}
); } if (detail.action === "NOOP") { return (
{t("memory.dream.actions.noopNoChange")}
); } const beforeText = beforeQuery.data?.memory?.text; const beforeUnitType = beforeQuery.data?.memory?.unit_type; return (
{wantsBefore && (

{t("memory.dream.actions.beforeModify")} {t("memory.dream.actions.targetMemory")} {beforeUnitType && ( · {beforeUnitType} )}

{beforeQuery.isLoading ? ( ) : beforeText ? (
              {beforeText}
            
) : (

{t("memory.dream.actions.originalUnreadable")}

)}
)} {newText && (

{detail.action === "ADD" ? t("memory.dream.actions.willAdd") : t("memory.dream.actions.afterModify")} {t("memory.dream.actions.newMemory")} {detail.newMemory?.unitType && ( · {detail.newMemory.unitType} )}

            {newText}
          
)} {detail.action === "DELETE" && (

{t("memory.dream.actions.willDelete")}

)} {detail.action === "MERGE" && (

{t("memory.dream.actions.willMerge")}

)}
); } function ActionDetailSheetBody({ detail, memoryStoreName, t, }: { detail: DreamActionRecord; memoryStoreName: string; t: TranslateFn; }) { return ( <> {" "} {t("memory.dream.actions.detailTitle")} {detail.actionId}
{detail.targetMemoryId && ( )} {detail.resultMemoryId && ( )}
{detail.reason && (

{t("memory.dream.actions.reason")}

              {detail.reason}
            
)} {detail.skippedReason && ( )} {detail.error && (

{t("memory.dream.actions.error")}

              {detail.error}
            
)}
); } function DetailRow({ label, value, mono, children, }: { label: string; value?: string; mono?: boolean; children?: React.ReactNode; }) { return (

{label}

{children ? (
{children}
) : (

{value ?? "-"}

)}
); }