"use client"; import { WikiBuildError } from "./wiki-build-error"; import { useEffect, useMemo, useReducer, useRef } from "react"; import Link from "next/link"; import { useSearchParams } from "next/navigation"; import { Play } from "lucide-react"; import { toast } from "sonner"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { type IngestWikiVariables, useIngestWiki, useWikiArtifacts, useWikiSources, } from "@/hooks/use-wikis"; import { useI18n, type MessageKey } from "@/i18n/i18n-context"; import { showApiError } from "@/lib/api-error-toast"; import type { WikiBuild, WikiBuildStatus, WikiDreamActionRef, WikiDreamArtifact, WikiScope, } from "@/types/wiki"; const MAX_SELECTED_ARTIFACTS = 100; export function artifactRefKey(dreamId: string, actionId: string): string { return `${dreamId}\0${actionId}`; } export function wikiBuildSelectionScopeKey( memoryStoreName: string, scope: WikiScope, ): string { return JSON.stringify([ memoryStoreName, scope.appId, scope.tenantId, scope.agentId, ]); } export function dedupeDreamActionRefs( refs: WikiDreamActionRef[], ): WikiDreamActionRef[] { const seen = new Set(); const result: WikiDreamActionRef[] = []; for (const ref of refs) { const key = artifactRefKey(ref.dreamId, ref.actionId); if (seen.has(key)) continue; seen.add(key); result.push({ dreamId: ref.dreamId, actionId: ref.actionId }); if (result.length === MAX_SELECTED_ARTIFACTS) break; } return result; } export interface WikiBuildConfirmationSnapshot { scopeKey: string; memoryStoreName: string; scope: WikiScope; clientToken: string; dreamActionRefs: WikiDreamActionRef[]; } export interface WikiBuildSelectionState { scopeKey: string; selected: Set; confirmation?: WikiBuildConfirmationSnapshot; } export type WikiBuildSelectionAction = | { type: "toggle"; scopeKey: string; key: string } | { type: "hint"; scopeKey: string; key: string } | { type: "confirm"; scopeKey: string; memoryStoreName: string; scope: WikiScope; clientToken: string; dreamActionRefs: WikiDreamActionRef[]; } | { type: "scope_changed"; scopeKey: string } | { type: "clear"; scopeKey: string } | { type: "submission_failed" }; export function createWikiBuildSelectionState( scopeKey: string, ): WikiBuildSelectionState { return { scopeKey, selected: new Set() }; } export function wikiBuildSelectionReducer( state: WikiBuildSelectionState, action: WikiBuildSelectionAction, ): WikiBuildSelectionState { if (action.type === "submission_failed") return state; if (action.type === "clear") { return createWikiBuildSelectionState(action.scopeKey); } if (action.type === "scope_changed") { return state.scopeKey === action.scopeKey ? state : createWikiBuildSelectionState(action.scopeKey); } const current = state.scopeKey === action.scopeKey ? state : createWikiBuildSelectionState(action.scopeKey); if (action.type === "hint" && current.confirmation) return current; if (action.type === "confirm") { return { ...current, confirmation: { scopeKey: action.scopeKey, memoryStoreName: action.memoryStoreName, scope: { ...action.scope }, clientToken: action.clientToken, dreamActionRefs: dedupeDreamActionRefs(action.dreamActionRefs), }, }; } const selected = new Set(current.selected); if (action.type === "toggle" && selected.has(action.key)) { selected.delete(action.key); } else if (!selected.has(action.key)) { if (selected.size >= MAX_SELECTED_ARTIFACTS) return current; selected.add(action.key); } else { return current; } return { scopeKey: action.scopeKey, selected }; } export function getSelectedDreamActionRefs( selected: Set, artifacts: WikiDreamArtifact[], ): WikiDreamActionRef[] { return dedupeDreamActionRefs( artifacts .filter((artifact) => selected.has(artifactRefKey(artifact.dreamId, artifact.actionId)), ) .map(({ dreamId, actionId }) => ({ dreamId, actionId })), ); } export function buildWikiIngestVariables( memoryStoreName: string, scope: WikiScope, clientToken: string, refs: WikiDreamActionRef[], ): IngestWikiVariables { return { memoryStoreName, scope, clientToken, dreamActionRefs: dedupeDreamActionRefs(refs), }; } export function buildConfirmedWikiIngestVariables( confirmation: WikiBuildConfirmationSnapshot, ): IngestWikiVariables { return buildWikiIngestVariables( confirmation.memoryStoreName, confirmation.scope, confirmation.clientToken, confirmation.dreamActionRefs, ); } export function canSubmitWikiBuild(input: { rawSourceCount: number; selectedRefCount: number; confirmation?: WikiBuildConfirmationSnapshot; }): boolean { return Boolean( input.confirmation?.dreamActionRefs.length || input.rawSourceCount > 0 || input.selectedRefCount > 0, ); } export function findHintedArtifactRef( hint: { dreamId?: string; actionId?: string }, artifacts: WikiDreamArtifact[], ): WikiDreamActionRef | undefined { if (!hint.dreamId || !hint.actionId) return undefined; const matched = artifacts.find( (artifact) => artifact.dreamId === hint.dreamId && artifact.actionId === hint.actionId, ); return matched ? { dreamId: matched.dreamId, actionId: matched.actionId } : undefined; } function createClientToken(): string { const suffix = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`; return `wiki-build-${suffix}`; } const BUILD_STATUS_KEY: Record = { pending: "wiki.buildStatus.pending", processing: "wiki.buildStatus.processing", accepting_output: "wiki.buildStatus.acceptingOutput", sealing: "wiki.buildStatus.sealing", validating: "wiki.buildStatus.validating", indexing: "wiki.buildStatus.indexing", publishing: "wiki.buildStatus.publishing", ready: "wiki.buildStatus.ready", failed: "wiki.buildStatus.failed", conflict: "wiki.buildStatus.conflict", }; function elapsedBetween(start: number, end: number): number | undefined { return Number.isFinite(start) && Number.isFinite(end) && end >= start ? end - start : undefined; } export function getWikiBuildElapsedMs(build: WikiBuild): number | undefined { const start = Date.parse(build.createdAt); const end = Date.parse(build.finishedAt ?? build.updatedAt); return elapsedBetween(start, end); } export function WikiBuildPanel({ memoryStoreName, scope, build, onBuildStarted, }: { memoryStoreName: string; scope: WikiScope; build?: WikiBuild; onBuildStarted: (status: WikiBuild["status"]) => void; }) { const { t } = useI18n(); const searchParams = useSearchParams(); const ingest = useIngestWiki(); const rawQuery = useWikiSources(memoryStoreName, scope, { limit: 100 }); const skillQuery = useWikiArtifacts(memoryStoreName, scope, { kind: "skill", limit: 100, }); const profileQuery = useWikiArtifacts(memoryStoreName, scope, { kind: "profile", limit: 100, }); const selectionScopeKey = wikiBuildSelectionScopeKey(memoryStoreName, scope); const [selectionState, dispatchSelection] = useReducer( wikiBuildSelectionReducer, selectionScopeKey, createWikiBuildSelectionState, ); const handledHint = useRef(undefined); const selectionMatchesScope = selectionState.scopeKey === selectionScopeKey; const selected = selectionMatchesScope ? selectionState.selected : new Set(); const confirmation = selectionMatchesScope ? selectionState.confirmation : undefined; useEffect(() => { handledHint.current = undefined; dispatchSelection({ type: "scope_changed", scopeKey: selectionScopeKey }); }, [selectionScopeKey]); const rawSources = useMemo( () => rawQuery.data?.pages.flatMap((page) => page.sources) ?? [], [rawQuery.data], ); const skillArtifacts = useMemo( () => skillQuery.data?.pages.flatMap((page) => page.artifacts) ?? [], [skillQuery.data], ); const profileArtifacts = useMemo( () => profileQuery.data?.pages.flatMap((page) => page.artifacts) ?? [], [profileQuery.data], ); const artifacts = useMemo( () => [...skillArtifacts, ...profileArtifacts], [profileArtifacts, skillArtifacts], ); const selectedRefs = getSelectedDreamActionRefs(selected, artifacts); const hintDreamId = searchParams.get("dreamId")?.trim() || undefined; const hintActionId = searchParams.get("actionId")?.trim() || undefined; useEffect(() => { const hintKey = hintDreamId && hintActionId ? artifactRefKey(hintDreamId, hintActionId) : undefined; if (!hintKey || handledHint.current === hintKey) return; const matched = findHintedArtifactRef( { dreamId: hintDreamId, actionId: hintActionId }, artifacts, ); if (!matched) return; handledHint.current = hintKey; dispatchSelection({ type: "hint", scopeKey: selectionScopeKey, key: hintKey, }); }, [artifacts, hintActionId, hintDreamId, selectionScopeKey]); const rawBytes = rawSources.reduce( (total, source) => total + source.contentSizeBytes, 0, ); const discoveryLoading = rawQuery.isLoading || skillQuery.isLoading || profileQuery.isLoading; const hasBuildInput = canSubmitWikiBuild({ rawSourceCount: rawSources.length, selectedRefCount: selectedRefs.length, confirmation, }); function toggleArtifact(artifact: WikiDreamArtifact) { dispatchSelection({ type: "toggle", scopeKey: selectionScopeKey, key: artifactRefKey(artifact.dreamId, artifact.actionId), }); } async function handleIngest() { if (!confirmation) { dispatchSelection({ type: "confirm", scopeKey: selectionScopeKey, memoryStoreName, scope, clientToken: createClientToken(), dreamActionRefs: selectedRefs, }); return; } try { const result = await ingest.mutateAsync( buildConfirmedWikiIngestVariables(confirmation), ); onBuildStarted(result.status); toast.success( t( result.skipped ? "wiki.build.ingestSkipped" : result.reused ? "wiki.build.ingestReused" : "wiki.build.ingestSubmitted", ), ); dispatchSelection({ type: "clear", scopeKey: selectionScopeKey }); } catch (error) { dispatchSelection({ type: "submission_failed" }); showApiError(error, { fallbackTitle: t("wiki.build.ingestFailed") }); } } return (

{t("wiki.build.ingestTitle")}

{t("wiki.build.ingestWarning")}

{t("wiki.build.rawSources")}

{t("wiki.build.rawSourceSummary", { count: rawSources.length, bytes: rawBytes, })}

{rawSources.map((source) => ( {source.path} ))}
void skillQuery.fetchNextPage()} selected={selected} onToggle={toggleArtifact} memoryStoreName={memoryStoreName} /> void profileQuery.fetchNextPage()} selected={selected} onToggle={toggleArtifact} memoryStoreName={memoryStoreName} />

{t("wiki.build.artifactSelectionSummary", { count: selectedRefs.length, max: MAX_SELECTED_ARTIFACTS, })}

{!discoveryLoading && !hasBuildInput ? (

{t("wiki.build.noBuildInput")}

) : null} {confirmation ? (

{t("wiki.build.ingestConfirm")}

) : null}

{t("wiki.build.latestTitle")}

{build ? ( ) : (

{t("wiki.build.none")}

)}
); } function ArtifactChoices({ title, artifacts, error, loading, hasNextPage, fetchingNextPage, onLoadMore, selected, onToggle, memoryStoreName, }: { title: string; artifacts: WikiDreamArtifact[]; error: Error | null; loading: boolean; hasNextPage: boolean; fetchingNextPage: boolean; onLoadMore: () => void; selected: Set; onToggle: (artifact: WikiDreamArtifact) => void; memoryStoreName: string; }) { const { t } = useI18n(); return (

{title}

{error ? (

{t("wiki.build.artifactLoadFailed")}

) : null} {loading ? (

{t("common.loading")}

) : null}
{artifacts.map((artifact) => { const key = artifactRefKey(artifact.dreamId, artifact.actionId); const checked = selected.has(key); return (
= MAX_SELECTED_ARTIFACTS} onCheckedChange={() => onToggle(artifact)} aria-label={t("wiki.build.selectArtifact", { name: artifact.name, })} />
{artifact.name}

{artifact.description}

{t("wiki.build.openDream")}
); })} {!loading && !artifacts.length && !error ? (

{t("wiki.build.noArtifacts")}

) : null}
{hasNextPage ? ( ) : null}
); } function BuildFields({ build }: { build: WikiBuild }) { const { t } = useI18n(); const elapsedMs = getWikiBuildElapsedMs(build); const elapsedSeconds = elapsedMs === undefined ? undefined : Math.floor(elapsedMs / 1_000); const elapsed = elapsedSeconds === undefined ? undefined : t("wiki.build.elapsedValue", { minutes: Math.floor(elapsedSeconds / 60), seconds: elapsedSeconds % 60, }); const fields: Array<[string, string | number | undefined]> = [ [t("wiki.build.status"), t(BUILD_STATUS_KEY[build.status])], [t("wiki.build.step"), build.step], [t("wiki.build.progress"), build.progress], [t("wiki.build.elapsed"), elapsed], [t("wiki.build.pageCount"), build.pageCount], [t("wiki.build.totalBytes"), build.totalBytes], [t("wiki.build.createdAt"), build.createdAt], [t("wiki.build.updatedAt"), build.updatedAt], [t("wiki.build.finishedAt"), build.finishedAt], ]; const changeFields: Array<[string, number]> = [ [t("wiki.build.changesAdded"), build.changes.added], [t("wiki.build.changesModified"), build.changes.modified], [t("wiki.build.changesDeleted"), build.changes.deleted], [t("wiki.build.changesAffectedPages"), build.changes.affectedPages], ]; const qualityFields: Array<[string, string | number]> = build.quality ? [ [ t("wiki.build.qualitySourceCoverage"), `${Math.round(build.quality.sourceCoverage * 100)}%`, ], [ t("wiki.build.qualityGroundedPageRate"), `${Math.round(build.quality.groundedPageRate * 100)}%`, ], [t("wiki.build.qualityBrokenLinks"), build.quality.brokenLinkCount], [t("wiki.build.qualityOrphanPages"), build.quality.orphanPageCount], [t("wiki.build.qualityUncitedPages"), build.quality.uncitedPageCount], [ t("wiki.build.qualityDuplicateTitles"), build.quality.duplicateTitleCount, ], ] : []; return ( <>
{fields.map(([label, value]) => (
{label}
{value ?? "-"}
))}

{t("wiki.build.incrementalAnalysis")}

{t("wiki.build.completePublication")}

{build.errorMessage && (build.status === "failed" || build.status === "conflict") ? (
) : null} {qualityFields.length ? ( ) : null} ); } function PublicMetricFields({ fields, }: { fields: Array<[string, string | number]>; }) { return (
{fields.map(([label, value]) => (
{label}
{value}
))}
); }