"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { useForm, useFieldArray } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { toast } from "sonner"; import { HelpCircle, Plus, Trash2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Collapsible, CollapsibleContent, CollapsibleTrigger, } from "@/components/ui/collapsible"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { useCreateDreamTask } from "@/hooks/use-create-dream-task"; import { ScopeCombobox } from "@/components/memory/scope-combobox"; import { useI18n } from "@/i18n/i18n-context"; import type { MessageKey, TranslateFn } from "@/i18n/i18n-context"; import { DREAM_APPLICATION_MODES, dreamModeForcedEffort, normalizeDreamMode, } from "@/lib/dream-create-options"; import { cn } from "@/lib/utils"; import type { CreateDreamTaskRequest, DreamApplyMode, DreamEffort, DreamScopeOutputMode, DreamTaskType, MemoryScope, } from "@/types/memory"; interface DreamCreateDialogProps { memoryStoreName: string; /** Pre-fill the first scope row from the current ScopeBar selection. */ initialScope?: MemoryScope | null; open: boolean; onOpenChange: (open: boolean) => void; } interface DreamSchemaMessages { appIdRequired: string; atLeastOneNonWildcard: string; atLeastOneScope: string; scopesLimit: string; highEffortScopesLimit: string; effortCombination: string; taskTypeExactScope: string; instructionsLimit: string; maxSessionsRange: string; maxMessagesRange: string; maxMemoriesRange: string; expandedScopeLimitRange: string; thresholdRange: string; timestampInvalid: string; timestampOrder: string; } const DEFAULT_SCHEMA_MESSAGES: DreamSchemaMessages = { appIdRequired: "appId 必填", atLeastOneNonWildcard: "至少指定一个非通配符字段", atLeastOneScope: "至少一个 scope", scopesLimit: "scope 最多 20 个", highEffortScopesLimit: "高 effort Dream scope 最多 8 个", effortCombination: "effort 与应用模式组合无效", taskTypeExactScope: "技能与画像任务必须且只能使用一个无通配符的精确 scope", instructionsLimit: "指令不能超过 4000 字节(UTF-8)", maxSessionsRange: "最大会话数必须是 0 到 100 之间的整数", maxMessagesRange: "最大消息数必须是 0 到 20000 之间的整数", maxMemoriesRange: "最大记忆数必须是 0 到 5000 之间的整数", expandedScopeLimitRange: "展开 scope 上限必须是 0 到 1000 之间的整数", thresholdRange: "置信度阈值必须在 0 到 1 之间", timestampInvalid: "时间格式不正确", timestampOrder: "最晚时间不能早于最早时间", }; function createDreamScopeSchema(messages: DreamSchemaMessages) { return z .object({ appId: z.string().trim().min(1, messages.appIdRequired), tenantId: z.string().trim().optional(), agentId: z.string().trim().optional(), runId: z.string().trim().optional(), }) .refine((s) => Object.values(s).some((v) => v && v !== "*"), { message: messages.atLeastOneNonWildcard, path: ["appId"], }); } function optionalIntegerString(max: number, message: string) { return z .string() .trim() .optional() .superRefine((value, ctx) => { if (!value) return; const parsed = Number(value); if (!Number.isInteger(parsed) || parsed < 0 || parsed > max) { ctx.addIssue({ code: z.ZodIssueCode.custom, message }); } }); } function optionalThresholdString(message: string) { return z .string() .trim() .optional() .superRefine((value, ctx) => { if (!value) return; const parsed = Number(value); if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) { ctx.addIssue({ code: z.ZodIssueCode.custom, message }); } }); } function optionalTimestampString(message: string) { return z .string() .trim() .optional() .superRefine((value, ctx) => { if (value && !Number.isFinite(Date.parse(value))) { ctx.addIssue({ code: z.ZodIssueCode.custom, message }); } }); } function createDreamFormSchema(messages: DreamSchemaMessages) { const scopeSchema = createDreamScopeSchema(messages); return z .object({ taskType: z.enum(["memory", "skill", "profile"]), effort: z.enum(["low", "high"]), scopes: z .array(scopeSchema) .min(1, messages.atLeastOneScope) .max(20, messages.scopesLimit), applyMode: z.enum(["proposal", "safe_auto", "plan"]).optional(), incremental: z.boolean().optional(), scopeOutputMode: z.enum(["preserve_scope", "promote_scope"]).optional(), minTimestamp: optionalTimestampString(messages.timestampInvalid), maxTimestamp: optionalTimestampString(messages.timestampInvalid), maxSessions: optionalIntegerString(100, messages.maxSessionsRange), maxMessages: optionalIntegerString(20_000, messages.maxMessagesRange), maxMemories: optionalIntegerString(5_000, messages.maxMemoriesRange), expandedScopeLimit: optionalIntegerString( 1_000, messages.expandedScopeLimitRange, ), instructions: z .string() .optional() .superRefine((value, ctx) => { if (value && new TextEncoder().encode(value).byteLength > 4_000) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: messages.instructionsLimit, }); } }), clientToken: z.string().optional(), thresholdAdd: optionalThresholdString(messages.thresholdRange), thresholdUpdate: optionalThresholdString(messages.thresholdRange), thresholdMerge: optionalThresholdString(messages.thresholdRange), }) .superRefine((values, ctx) => { if (values.minTimestamp && values.maxTimestamp) { const minTimestamp = Date.parse(values.minTimestamp); const maxTimestamp = Date.parse(values.maxTimestamp); if ( Number.isFinite(minTimestamp) && Number.isFinite(maxTimestamp) && maxTimestamp < minTimestamp ) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: messages.timestampOrder, path: ["maxTimestamp"], }); } } if (values.taskType !== "memory") { if ( values.effort === "high" && (values.scopes.length !== 1 || values.scopes.some((scope) => [scope.appId, scope.tenantId, scope.agentId, scope.runId].some( (segment) => !segment || segment === "*", ), )) ) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: messages.taskTypeExactScope, path: ["scopes"], }); } if (values.applyMode !== undefined) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: messages.effortCombination, path: ["applyMode"], }); } return; } if (values.applyMode === undefined) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: messages.effortCombination, path: ["applyMode"], }); } else if (values.effort === "low" && values.applyMode === "plan") { ctx.addIssue({ code: z.ZodIssueCode.custom, message: messages.effortCombination, path: ["applyMode"], }); } else if (values.effort === "high" && values.applyMode === "proposal") { ctx.addIssue({ code: z.ZodIssueCode.custom, message: messages.effortCombination, path: ["applyMode"], }); } if (values.effort === "high" && values.scopes.length > 8) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: messages.highEffortScopesLimit, path: ["scopes"], }); } }); } export const dreamScopeSchema = createDreamScopeSchema(DEFAULT_SCHEMA_MESSAGES); export const dreamCreateFormSchema = createDreamFormSchema( DEFAULT_SCHEMA_MESSAGES, ); function buildFormSchema(t: TranslateFn) { return createDreamFormSchema({ appIdRequired: t("memory.dream.appIdRequired"), atLeastOneNonWildcard: t("memory.dream.atLeastOneNonWildcard"), atLeastOneScope: t("memory.dream.atLeastOneScope"), scopesLimit: t("memory.dream.scopesLimit"), highEffortScopesLimit: t("memory.dream.highEffortScopesLimit"), effortCombination: t("memory.dream.effortCombination"), taskTypeExactScope: t("memory.dream.taskTypeExactScope"), instructionsLimit: t("memory.dream.instructionsLimit"), maxSessionsRange: t("memory.dream.maxSessionsRange"), maxMessagesRange: t("memory.dream.maxMessagesRange"), maxMemoriesRange: t("memory.dream.maxMemoriesRange"), expandedScopeLimitRange: t("memory.dream.expandedScopeLimitRange"), thresholdRange: t("memory.dream.thresholdRange"), timestampInvalid: t("memory.dream.timestampInvalid"), timestampOrder: t("memory.dream.timestampOrder"), }); } export type DreamCreateFormValues = z.infer; type FormValues = DreamCreateFormValues; const DREAM_EFFORTS = ["low", "high"] as const; export function dreamEffortOptions( _taskType: DreamTaskType, ): readonly (typeof DREAM_EFFORTS)[number][] { return DREAM_EFFORTS; } export function normalizeTaskTypeChange( taskType: DreamTaskType, current: Pick & Partial< Pick< DreamCreateFormValues, | "scopeOutputMode" | "thresholdAdd" | "thresholdUpdate" | "thresholdMerge" > >, ) { if (taskType === "memory") { return { ...current, applyMode: current.applyMode ?? (current.effort === "high" ? "safe_auto" : "proposal"), scopeOutputMode: current.scopeOutputMode ?? "preserve_scope", }; } return { ...current, applyMode: undefined, scopeOutputMode: undefined, thresholdAdd: undefined, thresholdUpdate: undefined, thresholdMerge: undefined, scopes: current.effort === "high" ? current.scopes.slice(0, 1) : current.scopes, }; } const APPLICATION_MODE_KEYS: Record< DreamApplyMode, { title: MessageKey; summary: MessageKey; help: MessageKey } > = { proposal: { title: "memory.dream.applyModeRequestApproval", summary: "memory.dream.applyModeRequestApprovalSummary", help: "memory.dream.applyModeRequestApprovalHelp", }, safe_auto: { title: "memory.dream.applyModeHelpMeApprove", summary: "memory.dream.applyModeHelpMeApproveSummary", help: "memory.dream.applyModeHelpMeApproveHelp", }, plan: { title: "memory.dream.applyModePlanMode", summary: "memory.dream.applyModePlanModeSummary", help: "memory.dream.applyModePlanModeHelp", }, }; export function DreamApplicationModeCards({ value, effort, onChange, t, }: { value: DreamApplyMode; effort: DreamEffort; onChange: (value: DreamApplyMode, effort: DreamEffort) => void; t: TranslateFn; }) { return (
{DREAM_APPLICATION_MODES.map((mode) => { const keys = APPLICATION_MODE_KEYS[mode.value]; const selected = value === mode.value; return (
{t(keys.help)}
); })}
); } const OUTPUT_LOCATIONS: ReadonlyArray<{ value: DreamScopeOutputMode; title: MessageKey; summary: MessageKey; }> = [ { value: "preserve_scope", title: "memory.dream.preserveScope", summary: "memory.dream.preserveScopeSummary", }, { value: "promote_scope", title: "memory.dream.promoteScope", summary: "memory.dream.promoteScopeSummary", }, ]; export function DreamOutputLocationCards({ value, onChange, t, }: { value: DreamScopeOutputMode; onChange: (value: DreamScopeOutputMode) => void; t: TranslateFn; }) { return (
{OUTPUT_LOCATIONS.map((option) => { const selected = value === option.value; return ( ); })}
{value === "promote_scope" ? (

{t("memory.dream.promoteScopeHint")}

) : null}
); } function parseOptionalInt(raw: string | undefined): number | undefined { if (raw === undefined || raw.trim() === "") return undefined; const n = Number(raw); if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) return undefined; return n; } function parseOptionalThreshold(raw: string | undefined): number | undefined { if (!raw) return undefined; const n = Number(raw); if (!Number.isFinite(n)) return undefined; return n; } export function buildDreamCreateRequest( values: DreamCreateFormValues, ): CreateDreamTaskRequest { const thresholds: Record = {}; const thresholdAdd = parseOptionalThreshold(values.thresholdAdd); const thresholdUpdate = parseOptionalThreshold(values.thresholdUpdate); const thresholdMerge = parseOptionalThreshold(values.thresholdMerge); if (thresholdAdd !== undefined) thresholds.add = thresholdAdd; if (thresholdUpdate !== undefined) thresholds.update = thresholdUpdate; if (thresholdMerge !== undefined) thresholds.merge = thresholdMerge; const isMemory = values.taskType === "memory"; return { scopes: values.scopes.map((scope) => { const result: MemoryScope = { appId: scope.appId }; if (scope.tenantId) result.tenantId = scope.tenantId; if (scope.agentId) result.agentId = scope.agentId; if (scope.runId) result.runId = scope.runId; return result; }), taskType: values.taskType, effort: values.effort, incremental: Boolean(values.incremental), ...(isMemory && values.applyMode && { applyMode: values.applyMode }), ...(isMemory && values.scopeOutputMode && { scopeOutputMode: values.scopeOutputMode, }), ...(values.minTimestamp && { minTimestamp: Date.parse(values.minTimestamp), }), ...(values.maxTimestamp && { maxTimestamp: Date.parse(values.maxTimestamp), }), ...(parseOptionalInt(values.maxSessions) !== undefined && { maxSessions: parseOptionalInt(values.maxSessions), }), ...(parseOptionalInt(values.maxMessages) !== undefined && { maxMessages: parseOptionalInt(values.maxMessages), }), ...(parseOptionalInt(values.maxMemories) !== undefined && { maxMemories: parseOptionalInt(values.maxMemories), }), ...(parseOptionalInt(values.expandedScopeLimit) !== undefined && { expandedScopeLimit: parseOptionalInt(values.expandedScopeLimit), }), ...(values.instructions && { instructions: values.instructions }), ...(values.clientToken && { clientToken: values.clientToken }), ...(isMemory && Object.keys(thresholds).length > 0 && { confidenceThresholds: thresholds, }), }; } export function MemoryDreamCreateDialog(props: DreamCreateDialogProps) { const { locale } = useI18n(); return ; } function MemoryDreamCreateDialogInner({ memoryStoreName, initialScope, open, onOpenChange, }: DreamCreateDialogProps) { const router = useRouter(); const createMutation = useCreateDreamTask(memoryStoreName); const { t } = useI18n(); const form = useForm({ resolver: zodResolver(buildFormSchema(t)), defaultValues: { taskType: "memory", scopes: [ { // Filter out wildcard "*" placeholder values from the URL ScopeBar // so the dream task is created against real ids only. appId: initialScope?.appId && initialScope.appId !== "*" ? initialScope.appId : "", tenantId: initialScope?.tenantId && initialScope.tenantId !== "*" ? initialScope.tenantId : "", agentId: initialScope?.agentId && initialScope.agentId !== "*" ? initialScope.agentId : "", runId: initialScope?.runId && initialScope.runId !== "*" ? initialScope.runId : "", }, ], effort: "low", applyMode: "proposal", scopeOutputMode: "preserve_scope", incremental: false, }, }); const { fields, append, remove } = useFieldArray({ control: form.control, name: "scopes", }); const taskType = form.watch("taskType"); const effort = form.watch("effort"); const applyMode = form.watch("applyMode") ?? "proposal"; const forcedEffort = dreamModeForcedEffort(applyMode); const isMemoryType = taskType === "memory"; const [advancedOpen, setAdvancedOpen] = useState(false); const [thresholdsOpen, setThresholdsOpen] = useState(false); const onSubmit = async (values: FormValues) => { try { const result = await createMutation.mutateAsync( buildDreamCreateRequest(values), ); const TOAST_MSG: Record = { memory: t("memory.dream.toastMemoryCreated"), skill: t("memory.dream.toastSkillCreated"), profile: t("memory.dream.toastProfileCreated"), }; toast.success(TOAST_MSG[values.taskType]); onOpenChange(false); form.reset(); router.push( `/memory/${encodeURIComponent(memoryStoreName)}/dream/${encodeURIComponent(result.dreamId)}`, ); } catch (err) { const message = err instanceof Error ? err.message : t("memory.dream.createFailed"); toast.error(message); } }; return ( {t("memory.dream.createTitle")} {t("memory.dream.createDescription")}
( {t("memory.dream.taskType")} )} />
{(isMemoryType || effort === "low") && ( )}
{fields.map((field, index) => (
{ form.setValue(`scopes.${index}.appId`, s.appId ?? ""); form.setValue( `scopes.${index}.tenantId`, s.tenantId ?? "", ); form.setValue( `scopes.${index}.agentId`, s.agentId ?? "", ); form.setValue(`scopes.${index}.runId`, s.runId ?? ""); }} />
{fields.length > 1 && (
)}
))}
{isMemoryType ? ( ( {t("memory.dream.applyMode")} { field.onChange(value); form.setValue("effort", normalizedEffort, { shouldValidate: true, }); }} /> )} /> ) : null}
( {t("memory.dream.effort")} {isMemoryType && forcedEffort ? ( {t( forcedEffort === "low" ? "memory.dream.effortLockedLow" : "memory.dream.effortLockedHigh", )} ) : null} )} />
{isMemoryType ? ( ( {t("memory.dream.scopeOutputMode")} )} /> ) : null} { const placeholder: Record = { memory: t("memory.dream.instructionsPlaceholderMemory"), skill: t("memory.dream.instructionsPlaceholderSkill"), profile: t("memory.dream.instructionsPlaceholderProfile"), }; return ( {t("memory.dream.instructionsLabel")}