autosnippet 3.0.7 → 3.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dashboard/dist/assets/index-D13KZZ6B.css +1 -0
  2. package/dashboard/dist/assets/{index-B3Nnkdxi.js → index-I2ySoCmF.js} +54 -55
  3. package/dashboard/dist/index.html +2 -2
  4. package/lib/cli/SetupService.js +35 -7
  5. package/lib/core/AstAnalyzer.js +5 -14
  6. package/lib/core/ast/ensure-grammars.js +47 -152
  7. package/lib/core/ast/index.js +66 -73
  8. package/lib/core/ast/lang-dart.js +4 -8
  9. package/lib/core/ast/lang-go.js +3 -7
  10. package/lib/core/ast/lang-java.js +3 -7
  11. package/lib/core/ast/lang-javascript.js +4 -8
  12. package/lib/core/ast/lang-kotlin.js +3 -7
  13. package/lib/core/ast/lang-objc.js +3 -7
  14. package/lib/core/ast/lang-python.js +3 -7
  15. package/lib/core/ast/lang-rust.js +3 -7
  16. package/lib/core/ast/lang-swift.js +3 -7
  17. package/lib/core/ast/lang-typescript.js +6 -12
  18. package/lib/core/ast/parser-init.js +82 -0
  19. package/lib/infrastructure/config/Paths.js +6 -1
  20. package/lib/infrastructure/external/ClipboardManager.js +86 -10
  21. package/lib/infrastructure/external/NativeUi.js +38 -10
  22. package/lib/infrastructure/external/OpenBrowser.js +11 -5
  23. package/lib/service/guard/GuardCheckEngine.js +172 -8
  24. package/lib/shared/PathGuard.js +5 -2
  25. package/package.json +4 -41
  26. package/resources/grammars/tree-sitter-dart.wasm +0 -0
  27. package/resources/grammars/tree-sitter-go.wasm +0 -0
  28. package/resources/grammars/tree-sitter-java.wasm +0 -0
  29. package/resources/grammars/tree-sitter-javascript.wasm +0 -0
  30. package/resources/grammars/tree-sitter-kotlin.wasm +0 -0
  31. package/resources/grammars/tree-sitter-objc.wasm +0 -0
  32. package/resources/grammars/tree-sitter-python.wasm +0 -0
  33. package/resources/grammars/tree-sitter-rust.wasm +0 -0
  34. package/resources/grammars/tree-sitter-swift.wasm +0 -0
  35. package/resources/grammars/tree-sitter-tsx.wasm +0 -0
  36. package/resources/grammars/tree-sitter-typescript.wasm +0 -0
  37. package/scripts/install-vscode-copilot.js +1 -1
  38. package/dashboard/dist/assets/index-BFNDAqh3.css +0 -1
@@ -1,4 +1,4 @@
1
- import{r as o,j as e,z as wa,l as sl,h as ka,o as Ca,m as Sa,M as al,a as ll,R as Ct,F as rl,b as nl}from"./vendor-CEnWn7aV.js";import{a as ss}from"./axios-C0Zqfgkc.js";import{Z as et,L as Aa,S as ol,B as rs,H as as,C as il,a as ut,W as cl,G as _s,b as tt,c as lt,d as ws,e as dl,f as ul,D as Da,g as ns,P as pl,h as Pt,i as xl,F as wt,j as xt,k as Ls,l as nt,M as Lt,m as ml,n as $s,o as hl,p as gl,q as Qe,E as os,r as bl,s as fl,U as Ia,t as yl,u as Nt,X as Xe,v as Fe,w as kt,R as Ra,x as rt,y as Bs,A as Ta,z as ft,I as jl,J as Ea,K as Gt,N as yt,O as vl,Q as Nl,T as wl,V as kl,Y as is,_ as Cl,$ as Sl,a0 as Pa,a1 as Al,a2 as Dl,a3 as Et,a4 as ot,a5 as ls,a6 as ht,a7 as Gs,a8 as Cs,a9 as Ht,aa as Ss,ab as Hs,ac as jt,ad as La,ae as Xt,af as Il,ag as Ys,ah as Qs,ai as fs,aj as Ma,ak as cs,al as ys,am as qt,an as Xs,ao as Ot,ap as Rl,aq as Fa,ar as Ms,as as Rt,at as Tl,au as za,av as _a,aw as $a,ax as El,ay as Pl,az as Fs,aA as Ll,aB as qs,aC as Ml,aD as Fl,aE as zl,aF as _l,aG as $l}from"./icons-eQ_rWCus.js";import"./yaml-qRaU8Ldn.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const d of document.querySelectorAll('link[rel="modulepreload"]'))l(d);new MutationObserver(d=>{for(const i of d)if(i.type==="childList")for(const u of i.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&l(u)}).observe(document,{childList:!0,subtree:!0});function a(d){const i={};return d.integrity&&(i.integrity=d.integrity),d.referrerPolicy&&(i.referrerPolicy=d.referrerPolicy),d.crossOrigin==="use-credentials"?i.credentials="include":d.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function l(d){if(d.ep)return;d.ep=!0;const i=a(d);fetch(d.href,i)}})();const zs={common:{save:"保存",saving:"保存中...",saved:"已保存",cancel:"取消",confirm:"确认",delete:"删除",edit:"编辑",close:"关闭",copy:"复制",copied:"已复制",loading:"加载中...",retry:"重试",refresh:"刷新页面",back:"返回",search:"搜索",noData:"暂无数据",operationFailed:"操作失败",saveFailed:"保存失败",deleteFailed:"删除失败",loadFailed:"加载失败",areYouSure:"Are you sure?",yes:"是",no:"否",all:"全部",none:"无",preview:"预览",apply:"应用",applying:"应用中...",stop:"停止",export:"导出",import:"导入",more:"更多",collapse:"折叠",expand:"展开"},sidebar:{recipes:"Recipes",moduleExplorer:"Modules",candidates:"候选 ({count})",batchManage:"批量管理",depGraph:"依赖关系",knowledgeGraph:"知识图谱",guard:"代码审计",skills:"Skills",repoWiki:"Wiki",aiAssistant:"AI 助手",help:"使用说明",collapseNav:"折叠导航",expandNav:"展开导航",roleDeveloper:"开发者",roleAgent:"Agent",roleChatAgent:"ChatAgent",modeLogin:"登录",modeProbe:"探针",logout:"登出",tokenLabel:"7日 Token",tokenCalls:"次调用",tokenCallsFull:"{count} 次 AI 调用"},header:{searchPlaceholder:"搜索知识库...",semanticSearch:"语义搜索",semanticSearchTitle:"语义搜索 (AI 向量检索)",semanticSearchFailed:"语义搜索失败。请确保已运行 asd embed 构建索引。",aiSwitchFailed:"切换 AI 失败,请检查项目根目录是否可写。",aiNotConfigured:"AI 未配置 — 点击设置 LLM",configureLlm:"配置 LLM",clickSwitchAi:"点击切换 AI 提供商",switchAi:"切换 AI",editEnvConfig:"修改 .env 配置",closeAiChat:"关闭 AI 对话",openAiChat:"打开 AI 对话",aiChat:"AI 对话",newRecipe:"新建 Recipe",syncSnippets:"同步 Snippets",langSwitch:"中 / EN"},login:{title:"AutoSnippet",subtitle:"连接开发者、AI 与项目知识库",heading:"登录 Dashboard",username:"用户名",password:"密码",usernamePlaceholder:"输入用户名",passwordPlaceholder:"输入密码",usernameRequired:"请输入用户名",passwordRequired:"请输入密码",loginFailed:"登录失败,请重试",loggingIn:"登录中...",loginBtn:"登录",envHint:"登录功能由 VITE_AUTH_ENABLED 环境变量控制"},pagination:{showing:"显示 {start}-{end},共 {total} 条",perPage:"每页",unit:"条",firstPage:"第一页",prevPage:"上一页",nextPage:"下一页",lastPage:"最后一页"},recipes:{title:"Recipe 知识库",sortNewest:"最新",sortAlpha:"字母",sortQuality:"质量",filterAll:"全部类型",filterSnippet:"仅 Snippet",filterKnowledge:"仅 Knowledge",searchPlaceholder:"搜索 Recipes...",totalCount:"共 {count} 条",noResults:"没有匹配的 Recipe",batchActions:"批量操作",selectAll:"全选",deselectAll:"取消全选",batchDelete:"删除选中",batchDeleteConfirm:"确定删除选中的 {count} 条 Recipe?",batchDeleteDone:"已删除 {count} 条",qualityAuthorityScore:"权威分",qualityExcellent:"Excellent",qualityGreat:"Great",qualitySolid:"Solid",qualityGood:"Good",qualityBasic:"Basic",knowledgeType:"类型",typeSnippet:"Snippet",typeKnowledge:"Knowledge",sourceLabel:"来源",sourceBootstrap:"bootstrap",sourceManual:"manual",sourceAiScan:"ai-scan",sourceExtract:"extract",sourceClipboard:"clipboard",editRecipe:"编辑",deleteRecipe:"删除",pushToCandidate:"推入候选",recipeDetail:"Recipe 详情",editBtn:"Edit",description:"描述",markdown:"Markdown",code:"代码",designRationale:"设计原理",steps:"实施步骤",codeChanges:"代码变更",validation:"验证方法",tags:"标签",constraints:"约束条件",guardRules:"Guard 规则",boundaryConstraints:"边界约束",preconditions:"前置条件",sideEffects:"副作用",relations:"关系图 (Relations)",headers:"Headers",noContent:"No content",semanticResults:"语义搜索结果",semanticSimilarity:"相似度",insertToFile:"插入到文件",viewInRecipes:"在 Recipes 中查看",reasoning:"推理依据",sourceColon:"来源:",confidenceColon:"置信度:",alternativesLabel:"备选:",qualityGrade:"质量评级",qualityCompleteness:"完整性",qualityAdaptation:"适配度",qualityDocumentation:"文档度",usageCount:"使用 {count}",emptyValue:"(空)",verificationMethod:"方法:",verificationExpected:"预期:",knowledgeTypes:{codePattern:"代码模式",architecture:"架构设计",bestPractice:"最佳实践",codeStandard:"代码规范",callChain:"调用链路",rule:"规则"}},candidates:{title:"Candidate 审核池",tabs:{pending:"待审",approved:"已批准",rejected:"已拒绝"},sortNewest:"最新优先",sortOldest:"最早优先",sortConfidence:"按置信度",searchPlaceholder:"搜索候选...",totalCount:"共 {count} 条待审",noResults:"没有待审候选",noPending:"已全部审核",confidenceHigh:"高",confidenceMedium:"中",confidenceLow:"低",sourceBootstrap:"冷启动",sourceManual:"manual",sourceAiScan:"ai-scan",sourceExtract:"extract",sourceClipboard:"clipboard",sourceSignal:"signal",approve:"批准",reject:"拒绝",approveAndSave:"批准并保存为 Recipe",batchApprove:"批量批准 ({count})",batchReject:"批量拒绝 ({count})",batchDeleteConfirm:"确定移除选中的 {count} 条候选?",batchDeleteDone:"已删除 {count} 条",approveSuccess:"已批准为 Recipe",rejectSuccess:"已拒绝",aiRefine:"AI 润色",viewDetail:"查看详情",selectAll:"全选",deselectAll:"取消全选",silent:"静默",expandedDetail:"展开详情",collapse:"收起",qualityDimensions:"质量维度",authorityScore:"权威分",trigger:"Trigger",category:"Category",language:"Language",path:"Path",description:"描述",code:"代码",markdown:"Markdown",rationale:"设计原理",tags:"标签",headers:"Headers",confidence:"置信度",source:"来源",createdAt:"创建时间",updatedAt:"更新时间",groupByTarget:"按 Target 分组",clearGroup:"确定移除「{name}」下的全部候选?",clearGroupDone:"已移除 {name} 下的全部候选",coldStartTitle:"冷启动:结构收集 + 9 维度 Candidate 创建(与 MCP 一致)",enrichTitle:"① 结构补齐:填充缺失的 rationale / knowledgeType / complexity / scope / steps / constraints(只填空不覆盖,建议先于润色执行)",refineTitle:"② 内容润色:改善 summary 描述、补充架构洞察、推断 relations 关联、调整 confidence 评分(逐条 AI 精炼,建议在结构补齐之后执行)",withCode:"(含代码 {count})",emptyHint:"点击下方按钮冷启动知识库,或使用 CLI 命令手动创建",fullScanBtn:"全量扫描 ·",clipboardCreate:"从剪贴板创建",scanningHint:"各维度知识正在后台提取并接受 AI 审查,完成后候选内容将自动展示",scannedAt:"扫描于 {time}",similarOnly:"只看相似",resetFilters:"重置",approveCurrentPage:"当前页进入审核",removeCurrentPage:"移除当前页",deleteAll:"全部删除",overallScore:"综合 {score}",similarPrefix:"相似",linesCount:"{count} 行",enrichTitleSingle:"① 结构补齐:填充缺失的语义字段(rationale / knowledgeType / complexity 等)",refineTitleSingle:"② 内容润色:改善描述、补充洞察、推断关联(支持自定义提示词)",projectProfile:"项目特写",recipeCompare:"Recipe 对比",refineEnhanced:"润色增强信息",agentNotes:"Agent 笔记:",similarRecipe:"相似 Recipe",similarWith:"与 {name} 相似 {score}%",enrichShort:"补齐",refineShort:"润色",enrichTitleBottom:"① 结构补齐",refineTitleBottom:"② 内容润色",timeJustNow:"刚刚",timeMinutesAgo:"{n} 分钟前",timeHoursAgo:"{n} 小时前",timeDaysAgo:"{n} 天前",confidenceHighLabel:"高",confidenceMediumLabel:"中",confidenceMediumLowLabel:"中低",confidenceLowLabel:"低",sourceAiScanLabel:"AI 全量扫描",sourceMcpLabel:"MCP 提交",sourceManualLabel:"手动创建",sourceFileWatcherLabel:"文件监听",sourceClipboardLabel:"剪贴板",sourceSignalLabel:"信号",sourceSubmitCheckLabel:"AI 审查提交"},knowledge:{title:"批量管理",lifecycle:"生命周期",lifecycleCandidate:"Candidate",lifecycleRecipe:"Recipe",lifecycleArchived:"Archived",searchPlaceholder:"搜索知识条目...",totalCount:"共 {count} 条",noResults:"无匹配条目",batchActions:"批量操作",batchPromote:"批量晋升",batchDemote:"批量降级",batchArchive:"批量归档",batchDelete:"批量删除",batchDeleteConfirm:"确定删除选中的 {count} 条知识?",batchDeleteDone:"已删除 {count} 条",selectAll:"全选",deselectAll:"取消全选",detail:"知识详情",detailContent:"内容",detailQuality:"质量",detailMeta:"元数据",qualityCompleteness:"完整度",qualityClarity:"清晰度",qualityRelevance:"关联性",qualityAccuracy:"精确度",qualityUsability:"可用性",authorityScore:"权威分",source:"来源",category:"分类",language:"语言",createdAt:"创建时间",updatedAt:"更新时间",path:"路径",trigger:"触发词",lifecyclePending:"待审核",lifecycleActive:"已发布",lifecycleDeprecated:"已废弃",actionPublish:"发布",actionDeprecate:"废弃",actionReactivate:"重新激活",sourceBootstrap:"AI 全量扫描",sourceMcp:"MCP 提交",sourceManual:"手动创建",sourceFileWatcher:"文件监听",sourceClipboard:"剪贴板",sourceCli:"CLI",sourceAgent:"AI Agent",sourceSubmitCheck:"AI 审查提交",allCategories:"所有分类",selectedCount:"已选 {count} 条",batchPublish:"批量发布",quickBatchPublish:"快速批量发布",batchPublishResult:"发布 {success} 条,失败 {fail} 条",batchPublishFailed:"批量发布失败",batchPublishComplete:"批量发布完成",noAutoApprovable:"当前没有可自动通过的待审核条目",noPublishable:"无可发布项",autoPublishResult:"已发布 {count} 条可自动通过的条目",autoApprovable:"可自动通过",clearFilters:"清除筛选条件",loadFailed:"加载知识条目失败",operationSuccess:"操作成功",deleteConfirmMsg:"确定删除「{title}」?此操作不可恢复。",deleteSuccess:"已删除「{title}」",deleteFailed:"删除失败",deprecateReasonPrompt:"请输入废弃原因:",rejectionReason:"驳回原因",summary:"摘要",relatedKnowledge:"关联知识",reasoning:"推理依据",confidence:"置信度",alternatives:"备选",qualityGrade:"质量评级",qualityAdaptation:"适配度",qualityDocumentation:"文档度",qualityCompletionLabel:"完整性",markdownDoc:"Markdown 文档",importHeaders:"导入头文件",codePattern:"代码 / 标准用法",designRationale:"设计原理",implementSteps:"实施步骤",constraintsLabel:"约束条件",aiInsight:"AI 洞察",lifecycleHistoryLabel:"生命周期历史",scope:"范围",scopeUniversal:"通用",scopeProject:"项目级",scopeModule:"模块级",complexity:"复杂度",complexityAdvanced:"高级",complexityIntermediate:"中级",complexityBeginner:"初级",sourceFile:"源文件",prev:"上一条",next:"下一条",narrow:"收窄",widen:"展宽",guardHits:"Guard",adoptions:"采纳",searchHits:"搜索",statViews:"浏览",statApplications:"应用",published:"发布"},knowledgeGraph:{title:"知识图谱",nodeTypes:"节点类型",nodeRecipe:"Recipe",nodeModule:"Module",nodeFile:"File",nodeSymbol:"Symbol",relationInherits:"继承",relationImplements:"实现",relationCalls:"调用",relationDependsOn:"依赖",relationDataFlow:"数据流",relationConflicts:"冲突",relationExtends:"扩展",relationAssociates:"关联",relationContains:"包含",relationImports:"导入",relationOverrides:"覆盖",relationComposedOf:"组合",relationReferencedBy:"被引用",relationTestedBy:"被测试",relationDocumentedIn:"被记录",tools:"工具",zoomIn:"放大",zoomOut:"缩小",resetView:"重置视图",fitView:"适应画布",toggleLabels:"显示/隐藏标签",nodeDetail:"节点详情",relatedNodes:"关联节点",noSelection:"点击节点查看详情",legend:"图例",searchPlaceholder:"搜索节点...",noResults:"没有匹配的节点",totalNodes:"共 {count} 个节点",totalEdges:"共 {count} 条边",loadFailed:"加载知识图谱失败",empty:"知识图谱为空",emptyDesc:"当前没有 Recipe 之间的关系数据。点击下方按钮让 AI 自动分析已有 Recipe 之间的潜在关系(requires / extends / enforces / calls 等)。",discoverRelations:"AI 发现关系",discovering:"AI 分析中…",refresh:"刷新",retry:"重试",statsLabel:"{nodes} 节点 · {edges} 关系",cancelSelection:"取消选中",outEdges:"出边(依赖)",inEdges:"入边(被依赖)",none:"无",relationRequires:"需要",relationEnforces:"约束",relationPrerequisite:"前置",relationReferences:"引用",relationAlternative:"替代",relationDeprecatedBy:"废弃",relationSolves:"解决",discoverAnalyzing:"AI 分析中…(已运行 {elapsed}s)",discoverPollTimeout:"轮询超时,任务可能仍在后台运行。请稍后刷新页面查看结果。",discoverNoResults:"分析完成,共检查 {pairs} 对 Recipe,未发现关系。待 Recipe 数量增加后可再次尝试。",discoverBatchErrors:"分析完成,但 {errors} 个批次 AI 调用失败,未发现关系。请检查 AI Provider 配置。",discoverSuccess:"发现 {count} 条关系(共分析 {pairs} 对{failMsg})",discoverBatchFailed:",{count} 个批次失败",discoverAiNotConfigured:"AI 服务未配置: {error}",discoverTimeout:"任务超时: {error}",discoverFailed:"发现失败: {error}",discoverRunning:"AI 分析仍在进行中…",discoverStarted:"AI 分析已启动,正在后台运行…",discoverInsufficientRecipes:"Recipe 数量不足,无法分析",discoverPreviousTimeout:"上次任务超时,请重试",discoverAiUnavailable:"AI 服务不可用: {error}",discoverStartFailed:"启动失败: {error}",unknownError:"未知错误",discoverTooltip:"AI 自动发现 Recipe 关系"},guard:{title:"Guard 审计",summary:"概览",totalViolations:"共 {count} 项违规",noViolations:"没有违规项",searchPlaceholder:"搜索规则或文件...",severityError:"错误",severityWarning:"警告",severityInfo:"信息",ruleId:"规则 ID",file:"文件",line:"行",message:"消息",severity:"严重性",statusOpen:"待处理",statusResolved:"已解决",statusIgnored:"已忽略",resolve:"标记为已解决",ignore:"忽略",reopen:"重新打开",aiGenRule:"AI 生成规则",aiGenRuleDesc:"描述你想要检测的模式,AI 将生成 Guard 规则",aiGenPlaceholder:"例: 禁止在 View 中直接调用网络请求",aiGenerating:"AI 生成中...",aiGenSuccess:"规则已生成",aiGenFailed:"规则生成失败",refreshAudit:"刷新审计",refreshing:"审计刷新中...",refreshSuccess:"审计已刷新",reportIssue:"提交误报",clearHistory:"清空历史",clearConfirm:"确定清空所有 Guard 违反记录?",addRuleValidation:"请填写规则 ID、说明、正则和至少一种语言",patternLabel:"正则(对每行匹配,JSON 中反斜杠需双写)",languagesLabel:"语言",dimensionLabel:"审查规模",noteLabel:"备注",allLanguages:"所有语言",noMatchingRules:"无匹配规则,请调整筛选条件",violationRecords:"违反记录(共 {runs} 次运行,{count} 处违反)",dimFile:"同文件",dimTarget:"同 target",dimProject:"同项目",rationale:"技术原因",fixSuggestion:"修复建议",sourceRecipe:"来源 Recipe",categorySafety:"安全",categoryCorrectness:"正确性",categoryPerformance:"性能",categoryStyle:"风格",category:"分类",currentProject:"当前项目",generatedRuleId:"已生成规则 ID",dimNoLimit:"不限制",notePlaceholder:"仅作简单模式提示",copyFixSuggestion:"复制修复建议",tableHeaders:{rule:"规则",file:"文件",line:"行号",message:"描述",severity:"级别",status:"状态",actions:"操作"}},skills:{title:"Skills 管理",searchPlaceholder:"搜索 Skills...",totalCount:"共 {count} 条",noResults:"没有匹配的 Skill",addSkill:"新增 Skill",editSkill:"编辑 Skill",deleteSkill:"删除 Skill",deleteConfirm:"确定删除此 Skill?",deleteSuccess:"已删除",saveSuccess:"已保存",skillName:"名称",skillNamePlaceholder:"输入 Skill 名称",skillDescription:"描述",skillDescPlaceholder:"输入 Skill 描述",skillTrigger:"触发器",skillTriggerPlaceholder:"输入触发条件",skillAction:"动作",skillActionPlaceholder:"输入动作内容",skillEnabled:"已启用",skillDisabled:"已禁用",toggleEnable:"启用/禁用",aiRecommend:"AI 推荐",aiRecommendDesc:"基于项目分析,AI 推荐以下 Skills",aiRecommending:"AI 分析中...",aiRecommendSuccess:"已推荐 {count} 条",aiRecommendFailed:"推荐失败",acceptRecommend:"采纳",rejectRecommend:"忽略",bulkAccept:"全部采纳",signalBadge:"信号",category:"类别",priority:"优先级",priorityHigh:"高",priorityMedium:"中",priorityLow:"低",subtitle:"Agent 技能文档 — 指导 AI 如何正确使用 AutoSnippet 工具",fetchFailed:"获取 Skills 列表失败",loadError:"不存在或读取出错",loadSkillFailed:"加载 Skill 失败",updateSuccess:"更新成功",updateFailed:"更新 Skill 失败",deleteFailed:"删除 Skill 失败",createSuccess:"创建成功",createFailed:"创建 Skill 失败",createAddedToKB:"已创建并加入知识库",filterProject:"项目级",filterBuiltin:"内置",noRecommendations:"当前暂无推荐。继续使用后会积累更多信号。",aiRecommendTooltip:"基于使用模式分析推荐 Skill",creating:"创建中",useCase:"适用",chars:"字符",related:"相关",confirmDelete:"确认删除",deleteSkillConfirmMsg:'删除 Skill "{name}"?此操作不可撤销。',selectToView:"选择左侧 Skill 查看详情",checkGenerated:"请检查并确认生成的内容",aiGenerated:"AI 已生成 Skill",aiGenFailed:"AI 生成失败",fillRequired:"请填写名称、描述和内容",savedToKB:"已保存到知识库",aiGenMode:"AI 生成",manualMode:"手动填写",describeSkill:"描述你想创建的 Skill",aiGeneratingContent:"AI 正在生成...",generateSkill:"生成 Skill",skillContent:"Skill 文档内容",createdBy:{manual:"手动创建","user-ai":"AI 协助创建","system-ai":"自动创建","external-ai":"外部 AI 创建"}},depGraph:{title:"依赖关系图",searchPlaceholder:"搜索模块...",noResults:"没有匹配的模块",totalModules:"共 {count} 个模块",totalDeps:"共 {count} 条依赖",layout:"布局",layoutTree:"树形",layoutForce:"力导向",layoutCircular:"环形",zoomIn:"放大",zoomOut:"缩小",resetView:"重置视图",fitView:"适应画布",nodeDetail:"模块详情",dependencies:"依赖",dependents:"被依赖",legend:"图例",noSelection:"点击节点查看详情",depTypes:{direct:"直接依赖",transitive:"传递依赖",devOnly:"开发依赖"},refresh:"刷新",retry:"重试",noDataTitle:"当前项目内未扫描到模块依赖关系。",noDataDesc:"请确保项目包含模块定义文件(go.mod / package.json / Package.swift / build.gradle 等),然后点击 Refresh 重新扫描。",filterAll:"全部",filterInternal:"内部包",filterExternal:"外部依赖",packages:"包",packageList:"包列表",depRelations:"依赖关系(小图)",depRelationsDesc:"主图不显示连线,点击节点可在浮窗查看该包依赖;此处列出全部 From → To。",labelExternal:"外部",labelInternal:"内部",labelIndirect:"间接",projectRoot:"项目根",close:"关闭",none:"无",visualization:"模块依赖结构可视化",targetHint:"Target 级节点格式:"},bootstrap:{title:"冷启动进度",pipelineSteps:{collecting:"收集项目结构",scanning:"扫描源代码",analyzing:"AI 分析",enriching:"知识增强",indexing:"建立索引"},taskStatus:{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",skipped:"已跳过"},stats:{totalFiles:"文件总数",totalTargets:"Target 数",totalRecipes:"Recipe 数",totalTime:"总耗时",aiCalls:"AI 调用数"},notifications:{started:"冷启动已开始",completed:"冷启动完成",failed:"冷启动失败",partialComplete:"部分完成"},retryFailed:"重试失败任务",viewDetails:"查看详情",dimLabels:{architecture:"架构与设计",bestPractice:"规范与实践",eventAndDataFlow:"事件与数据流",objcDeepScan:"深度扫描",agentGuidelines:"Agent 注意事项",bootstrap:"Bootstrap",codeStandard:"代码规范",codePattern:"设计模式",projectProfile:"项目特征",categoryScan:"Category 分类方法"},pipelineLabels:{"project-profile":"项目概貌","objc-deep-scan":"深度扫描(常量/Hook)","category-scan":"基础类分类方法扫描","code-standard":"代码规范",architecture:"架构模式","code-pattern":"设计模式","event-and-data-flow":"事件与数据流","best-practice":"最佳实践","agent-guidelines":"Agent 开发注意事项"},statusLabels:{skeleton:"等待中",filling:"填充中",completed:"已完成",failed:"失败"},allCompleted:"全部完成",completedWithErrors:"完成(有错误)",elapsed:"已用",estimatedRemaining:"预计剩余",toolCalls:"工具调用",dimensions:"{done}/{total} 维度",notifySuccess:"{completed} 个维度全部填充成功",notifyPartial:"{completed}/{total} 成功,{failed} 失败",coldStartComplete:"冷启动完成",close:"关闭",reviewPipeline:"AI 审查管线",reviewRounds:{round1Label:"资格审查",round1Desc:"过滤误报 · 识别合并",round2Label:"内容精炼",round2Desc:"AI 改写摘要 · 动态置信度",round3Label:"去重 & 关系",round3Desc:"语义去重 · 关系推断"},round1Done:"保留 {kept} · 合并 {merged} · 丢弃 {dropped}",round2Progress:"{current}/{total} 条",round2Done:"已精炼 {refined}/{total} 条",round3Done:"去重后 {afterDedup} 条 · {relationsFound} 条关系",noMatch:"✓ 无匹配内容",featuresOnly:"✓ {sourceCount} 项特征",featuresAndCandidates:"✓ {sourceCount} 项特征 · {extracted} 条候选",candidatesOnly:"✓ {extracted} 条候选"},wiki:{title:"Repo Wiki",sidebar:"Wiki",fileCount:"{count} 篇",searchPlaceholder:"搜索文件...",generating:"文件生成中,新文档将自动出现…",backToList:"返回文件列表",aiBadge:"AI 增强",copySuccess:"已复制",copyBtn:"复制",loadFailed:"加载失败",incrementalUpdate:"增量更新",fullGeneration:"全量生成",genStarted:"Wiki 生成已启动",genFailed:"生成失败",selectPlaceholder:"从左侧文件树选择,或使用下方快捷入口",phases:{outline:"大纲",content:"内容",review:"审校"},fileTypes:{overview:"概述",module:"模块",api:"API",guide:"指南"},synced:"同步",wikiGenerating:"Wiki 正在生成中",outOfDateHint:"检测到代码变更,Wiki 可能已过期,建议增量更新",emptyTitle:"尚未生成 Repo Wiki",emptyDesc:"Wiki 在冷启动时自动全量生成,后续通过增量更新保持同步",emptyHint:"运行 asd setup 冷启动 · asd wiki --update 增量更新",quickOverview:"项目概述",quickOverviewDesc:"项目信息、技术栈与数据统计",quickArch:"架构总览",quickArchDesc:"模块依赖图、项目结构分析",quickStart:"快速上手",quickStartDesc:"构建、运行与入口分析",quickProtocols:"协议与组件",quickProtocolsDesc:"核心协议、委托和组件关系",selectFile:"选择一个文件开始阅读",lastGenerated:"最后生成",duration:"耗时",incrementalUpdating:"增量更新中...",loadFailedDesc:"无法读取文件内容。"},aiChat:{title:"AI Assistant",emptyTitle:"开始与 AI 对话",emptyDesc:"你可以询问项目相关问题,AI 将帮你分析代码、推荐模式。",inputPlaceholder:"输入你的问题...",inputHint:"Enter 发送 · Shift+Enter 换行",thinking:"AI 思考中...",analyzing:"AI 正在分析...",topicPanel:"话题列表",newTopic:"开启新话题",deleteTopic:"删除话题",deleteTopicConfirm:"确定删除此话题?",quickPrompts:{analyzeArch:"分析项目架构",findDuplicates:"查找重复代码",suggestOptimize:"推荐优化方向"},timeJustNow:"刚刚",timeMinutesAgo:"{n} 分钟前",timeHoursAgo:"{n} 小时前",timeDaysAgo:"{n} 天前",codeBlock:"代码块",diffView:"变更对比",diffBefore:"Before",diffAfter:"After",contextLabel:"AI Context / 项目特写",copyCode:"复制代码",topicRecords:"话题记录",noHistory:"暂无聊天记录",autoSaveHint:"开始对话后自动保存",topicCount:"{count} 个话题 · 本地存储",askAnything:"询问任何关于项目的问题",startChat:"开始 AI 对话",emptyDescLong:"询问关于你项目的任何问题 — 代码分析、架构建议、优化方向等。",aiAssistant:"AI 助手",messageCount:"{n} 条",requestFailed:"请求失败: {error}",cancelled:"(已取消)",expandTopics:"展开话题列表",diffEmpty:"(空)",quickPromptSummarize:"总结项目概况"},help:{title:"使用说明",gettingStarted:"快速开始",commands:"命令参考",faq:"常见问题",tokenUsage:"Token 用量",about:"关于",pageTitle:"AutoSnippet V3 使用说明",subtitle:"连接开发者、AI 与项目知识库:ChatAgent 智能对话 · Skills 开放平台 · 知识库持续生长",techSpecs:"Node.js ≥ 20 · 13 Skills · AI 可自建 · 16 MCP 工具 · ChatAgent 对话 · 4 层检索管线",viewGithub:"查看 GitHub",fullDocs:"完整文档",tokenUsageLast7Days:"Token 用量(近 7 日)",quickStart:"快速开始",coreConcepts:"核心概念",coreFeatures:"核心功能",editorDirectives:"编辑器指令",cursorIntegration:"Cursor AI 集成",v3Architecture:"V3 架构",cliReference:"命令行速查",step1Title:"安装与初始化",step2Title:"启动 Dashboard",step2Desc:"启动 HTTP API + Dashboard + FileWatcher",step3Title:"IDE 集成",step3Desc:"安装 MCP + Skills + Cursor Rules",step4Title:"创建第一个 Recipe",step4Desc1:"Dashboard → New Recipe",step4Desc2:"Use Copied Code → AI 填充 → 保存",threeRoles:"三大角色",roleColumn:"角色",responsibilityColumn:"职责",capabilityColumn:"能力",roleDeveloper:"开发者",roleCursorAgent:"Cursor Agent",roleChatAgent:"ChatAgent",developerResp:"审核与决策、维护项目标准",cursorAgentResp:"按规范生成代码、检索知识库",chatAgentResp:"提取、摘要、扫描、审查",coreComponents:"核心组件",bootstrapLabel:"Bootstrap(冷启动)",bootstrapDesc:"9 维度自动知识提取引擎",candidatesLabel:"Candidates(候选)",candidatesDesc:"待审核的 Recipe 草案",recipeLabel:"Recipe(配方)",recipeDesc:"Markdown 知识文档(Source of Truth)",chatAgentLabel:"ChatAgent(智能对话)",chatAgentDesc:"多 Agent 协作架构,可持续扩展",searchPipelineLabel:"4 层检索管线",searchPipelineDesc:"多模式语义搜索引擎",guardLabel:"Guard(代码审查)",guardDesc:"知识库驱动的代码审查",knowledgeLoop:"知识库闭环",loopStep1:"扫描提取",loopStep1Sub:"AI/Cursor",loopStep2:"人工审核",loopStep2Sub:"Dashboard",loopStep3:"知识沉淀",loopStep3Sub:".md 落盘",loopStep4:"智能使用",loopStep4Sub:"Cursor/Xcode",loopStep5:"持续优化",loopStep5Sub:"asd sync",knowledgeBuild:"知识库构建",semanticSearchLabel:"语义检索",codeAudit:"代码审查(Audit)",dataSync:"数据同步",usageExamples:"使用示例",exampleSearchKB:"检索知识库",exampleSearchKBDesc:'对 Cursor 说:"查找网络请求错误处理的代码"',exampleBatchScan:"批量扫描",exampleBatchScanDesc:'对 Cursor 说:"扫描 NetworkModule,生成 Recipes 到候选"',exampleSubmitCode:"提交代码",exampleSubmitCodeDesc:'对 Cursor 说:"把这段代码保存为 Recipe"',skills10:"10 个 Skills",mcp16:"16 个 MCP 工具(V3 参数化统合)",bootstrapEngine:"Bootstrap 冷启动引擎",bootstrapEngineDesc:"3 步完成知识库从 0 → 1:",fourLayerPipeline:"4 层检索管线",fourLayerPipelineDesc:"多信号融合的精准检索:",chatAgentSystem:"ChatAgent 对话系统",chatAgentSystemDesc:"多 Agent 协作架构,可持续扩展:",fiveEntryChannels:"五个入口通道",initAndEnv:"初始化与环境",kbManagement:"知识库管理",searchAndAudit:"搜索与审查",maintenanceUpgrade:"维护与升级",footerHint:"需要更详细的说明?查看 {link} 或运行 {cmd} 检查环境",footerGithubReadme:"GitHub README",mcpWriteNote:"写操作工具(submit_knowledge、guard、bootstrap 等)通过 Gateway 权限 / 宪法 / 审计三重保护。",editorDirectivesNote:"需先运行 asd watch 或 asd ui;支持快捷写法 asc / ass / asa",createDirective:"创建 Recipe/Snippet",searchDirective:"搜索并插入",auditDirective:"代码审查",includeDirective:"自动注入头文件/模块",developerCap:'Dashboard 审核候选、保存 Recipe;Snippet 补全、<code class="bg-slate-100 px-1 rounded">// as:search</code>;运行 <code class="bg-slate-100 px-1 rounded">asd ui</code>',cursorAgentCap:"13 个 Skills 理解规范;16 个 MCP 工具按需检索、提交候选;写操作经 Gateway 审核",chatAgentCap:'<code class="bg-slate-100 px-1 rounded">asd ais</code> 批量扫描;分析剪贴板;Guard 审查;Dashboard RAG',bootstrapBullet1:"扫描项目模块 + AST 分析源码",bootstrapBullet2:"启发式提取 → AI 精炼 → 生成 Candidate",bootstrapBullet3:'MCP 工具:<code class="bg-green-100 px-1 rounded">bootstrap</code>(operation: knowledge / refine / scan)',candidatesBullet1:"来源:AI 扫描、Cursor、剪贴板、Dashboard",candidatesBullet2:"审核后入库为 Recipe,确保质量",candidatesBullet3:"Reasoning 字段记录 AI 推理过程",recipeBullet1:'位置:<code class="bg-blue-100 px-1 rounded">AutoSnippet/recipes/*.md</code>',recipeBullet2:".md 文件 = 唯一数据源,DB 仅作索引缓存",recipeBullet3:'<code class="bg-blue-100 px-1 rounded">asd sync</code> 增量同步 .md → DB',chatAgentCompBullet1:"AnalystAgent 分析意图 → ProducerAgent 执行操作",chatAgentCompBullet2:"HandoffProtocol 自动切换 + 轻量记忆持久化",chatAgentCompBullet3:"项目感知:自动注入知识库状态上下文",searchPipelineBullet1:"InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",searchPipelineBullet2:"BM25 + keyword + semantic 三路融合",searchPipelineBullet3:"search MCP 工具:mode 参数路由 auto / keyword / semantic / context 四种模式",guardCompBullet1:"内建规则 + 自定义规则 + Recipe 关联",guardCompBullet3:'MCP:<code class="bg-rose-100 px-1 rounded">guard</code>(code=单文件 / files=批量)、<code class="bg-rose-100 px-1 rounded">bootstrap</code>(operation: scan)',kbBuildBullet1:'<strong>AI 扫描</strong>:<code class="bg-slate-100 px-1 rounded text-xs">asd ais [Target]</code> 批量提取',kbBuildBullet2:'<strong>Cursor 扫描</strong>:对 Copilot 说 "扫描 Module"',kbBuildBullet3:"<strong>手动创建</strong>:New Recipe → Use Copied Code",kbBuildBullet4:'<strong>编辑器内</strong>:复制代码 → <code class="bg-slate-100 px-1 rounded text-xs">// as:create -c</code>',semSearchBullet1:"<strong>4 层管线</strong>:InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",semSearchBullet2:'<strong>编辑器内</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:search keyword</code>',semSearchBullet3:"<strong>Cursor MCP</strong>:search 统合工具(mode 路由 4 种模式)",semSearchBullet4:"<strong>Dashboard</strong>:搜索框支持语义 + 关键词",auditFeatureBullet1:'<strong>文件审查</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:audit</code>',auditFeatureBullet2:'<strong>Target 审查</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:audit target</code>',auditFeatureBullet3:'<strong>Guard 审查</strong>:MCP <code class="bg-slate-100 px-1 rounded text-xs">guard</code>(code / files 参数)',auditFeatureBullet4:"<strong>Dashboard</strong>:Guard 页面可视化审查",syncBullet1:'<strong>同步</strong>:<code class="bg-slate-100 px-1 rounded text-xs">asd sync</code> .md → DB(增量)',syncBullet2:'<strong>Hash 校验</strong>:<code class="bg-slate-100 px-1 rounded text-xs">_contentHash</code> 检测手动编辑',syncBullet3:"<strong>向量索引</strong>:启动时自动构建语义索引",syncBullet4:'<strong>依赖图</strong>:<code class="bg-slate-100 px-1 rounded text-xs">structure</code>(operation: targets / files)MCP 工具',createDirBullet1:"无选项:打开 Dashboard",createDirBullet2:"<code>-c</code>:从剪贴板静默创建",createDirBullet3:"<code>-f</code>:扫描当前文件",searchDirBullet1:"从知识库检索 Recipe/Snippet",searchDirBullet2:"选择后插入代码,替换该行",searchDirBullet3:"记录一次人工使用",auditDirBullet1:"无后缀:审查当前文件",auditDirBullet2:"<code>target</code>:审查当前 Target",auditDirBullet3:"<code>project</code>:审查整个项目",includeDirBullet1:"Snippet 中包含此标记",includeDirBullet2:"补全后自动注入 import",skillIntent:"意图路由",skillConcepts:"概念教学",skillCandidates:"候选提交",skillRecipes:"Recipe 检索",skillGuard:"代码合规",skillStructure:"项目结构",skillAnalysis:"深度分析",skillColdstart:"冷启动",skillCreate:"引导创建",skillLifecycle:"生命周期",mcpLayerHeader:"层级",mcpToolHeader:"工具",mcpDescHeader:"说明",mcpAgentLayerHeader:"Agent 层(12 个)— 默认对外暴露",mcpAdminLayerHeader:"Admin 层(4 个)— 需设置 ASD_MCP_TIER=admin",mcpHealthDesc:"服务健康检查",mcpCapabilitiesDesc:"服务能力清单(Agent 自发现)",mcpGuardDesc:"code=单文件审查 / files=批量审查",mcpSubmitDesc:"提交候选 / 批量 / 保存文档",mcpEnrichDesc:"AI 润色 / 校验 / 查重",mcpLifecycleDesc:"批量生命周期操作",mcpSearchDesc:"mode 路由 auto / keyword / semantic / context",mcpKnowledgeDesc:"operation 路由 list / get / insights / confirm_usage",mcpStructureDesc:"operation 路由 targets / files / metadata",mcpGraphDesc:"operation 路由 query / impact / path / stats",mcpSkillDesc:"operation 路由 list / load / create / update / delete / suggest",mcpBootstrapDesc:"operation 路由 knowledge / refine / scan",archBootstrapStep1:"① 项目扫描 → 依赖 / 目录 / 入口分析",archBootstrapStep2:"② AI 批量提取 → Candidate 候选列表",archBootstrapStep3:"③ 审阅 + Promote → Recipe 知识库就绪",archBootstrapNote:"支持 bootstrap 工具(operation: refine)持续迭代、resume 断点续跑",archPipelineL1:"InvertedIndex — 倒排索引快速召回",archPipelineL2:"CoarseRanker — BM25 + TF-IDF 粗排",archPipelineL3:"MultiSignalRanker — 多维信号精排",archPipelineL4:"RetrievalFunnel — 漏斗截断 + 上下文装配",archAnalystAgent:"<strong>AnalystAgent</strong>:分析用户意图 → 检索知识库 → 给出建议 → 信心信号分级",archProducerAgent:"<strong>ProducerAgent</strong>:生成代码 → 创建候选 → 执行操作 → 结果聚合",archHandoff:"<strong>HandoffProtocol</strong>:两个 Agent 之间的自动切换协议",archMemory:"<strong>轻量记忆</strong>:跨对话偏好/决策/上下文持久化(JSONL,TTL 过期)",archProjectAware:"<strong>项目感知</strong>:自动注入知识库状态(Recipe 分布、候选积压量、Guard 规则数)",archCliDesc:"asd × 10 命令",archMcpDesc:"stdio × 16 工具",archHttpDesc:"Express × 14 路由模块",archSkillsDesc:"13 个 Cursor/Copilot",cliSetupDesc:"初始化项目",cliStatusDesc:"环境自检",cliUiDesc:"启动 Dashboard",cliUpgradeDesc:"升级 IDE 集成",cliSyncDesc:".md → DB 增量同步",cliAisDesc:"AI 扫描提取 Candidates",cliAisForceDesc:"强制重新扫描全量",cliWatchDesc:"文件监控 + 指令触发",cliSearchDesc:"搜索知识库",cliSearchSemanticDesc:"语义搜索模式",cliGuardDesc:"Guard 规则检查",cliServerDesc:"单独启动 API 服务",cliUpgradeMcpDesc:"升级 MCP / Skills / Rules",cliInstallFullDesc:"全量安装 IDE 集成",cliSyncForceDesc:"全量重建 DB",cliSyncDryDesc:"预览同步变更"},moduleExplorer:{title:"Module Explorer",scanTargets:"扫描 Targets",scanning:"扫描中...",scanComplete:"扫描完成",targetFiles:"{count} 个文件",noTargets:"未发现 Target",recipesInTarget:"关联 Recipes",guardSummary:"Guard 概况",guardViolations:"{count} 项违规",noViolations:"无违规",openFile:"打开文件",refreshTree:"刷新文件树",extractFromFile:"提取代码",fileDetail:"文件详情",projectModules:"项目模块 ({count})",addFolderScan:"添加目录扫描",refreshProject:"刷新项目结构",discovererFolderScan:"目录扫描",removeFolder:"移除此目录",fullProjectResults:"全项目扫描结果",moduleLabel:"模块: {name}",reviewResults:"审核提取结果",resultsCount:"{count} 条",candidateSuffix:" Candidate",fullProjectScanning:"全项目扫描中",moduleScanLabel:"模块扫描: {name}",filesInScan:"本次扫描的文件 ({count})",knowledgeExtract:"知识提取",knowledgeExtractHint:"在左侧选择模块扫描,或点击 + 添加任意目录。提取代码模式并生成 Recipe 知识卡片。",guardAuditSummary:"Guard 审计摘要",auditedFiles:"已审计文件:",totalViolationsLabel:"违反总数:",errorsCount:"{count} 错误",warningsCount:"{count} 警告",recipeNotExist:"「{name}」不存在于当前知识库",recipeNotExistTitle:"Recipe 不存在",loadRecipeFailed:"加载 Recipe 失败",browseFailedTitle:"目录浏览失败",browseFailedDefault:"无法加载目录列表",selectFolderTitle:"选择要扫描的目录",scanningDirs:"正在扫描项目目录...",noDirs:"未发现可扫描的目录",sourceFileCount:"{count} 文件",selectFolderHint:"选择包含源码文件的目录,系统将自动检测语言并执行 AI 扫描",modulesTabLabel:"模块 ({count})",foldersTabLabel:"目录"},search:{title:"智能搜索",searchPlaceholder:"输入搜索关键词...",noResults:"未找到匹配结果",resultCount:"找到 {count} 条结果",relevance:"相关度",source:"来源",category:"分类",language:"语言",matchType:"匹配类型",matchExact:"精确",matchFuzzy:"模糊",matchSemantic:"语义匹配",matchKeyword:"关键词匹配",viewRecipe:"查看 Recipe",insertCode:"插入代码",searchFailed:"搜索失败。请重试。",searching:"搜索中...",searchBtn:"搜索",emptyHint:"输入关键词后点击搜索",contextRelevant:"上下文相关",authorityScore:"权威分",usage:"使用",usageCount:"{count}次",recommendReason:"推荐理由",viewFullContent:"查看完整内容",similarity:"相似度",quality:"质量",noContent:"无内容",useSnippet:"使用此片段",importedFrameworks:"导入的框架:",relatedApis:"相关 APIs:"},scanResult:{title:"扫描结果",trigger:"Trigger",triggerPlaceholder:"@kebab-case-id",description:"描述",descPlaceholder:"中文简述 ≤80 字,引用真实类名",category:"分类",language:"语言",code:"代码模板",markdown:"项目特写",rationale:"设计原理",tags:"标签",tagsPlaceholder:"标签: 按 Enter/逗号添加...",headers:"Imports",headersPlaceholder:"#import <Header.h>",confidence:"置信度",confidenceHigh:"高",confidenceMedium:"中",confidenceLow:"低",source:"来源",authorityScore:"权威分",saveAsRecipe:"保存为 Recipe",saveAsKnowledge:"保存知识",discard:"丢弃",keepCandidate:"保留候选",qualityWarning:"质量提醒",lowQualityHint:"该条目质量较低,建议润色后再保存",editBeforeSave:"编辑后保存",triggerRequired:"请输入 Trigger",savedAsRecipe:"已保存并发布为 Recipe",savedToKb:"已保存到 KB",validation:"验证方法",validationMethod:"方法:",validationExpected:"预期:",steps:"实施步骤",codeChanges:"代码变更",constraints:"约束条件",guardRules:"Guard 规则",boundaryConstraints:"边界约束",preconditions:"前置条件",sideEffects:"副作用",relations:"关系图 (Relations)",knowledgeEntryTitle:"知识条目标题",aiScan:"AI 扫描",lifecyclePending:"待审核",lifecycleActive:"已发布",lifecycleDeprecated:"已废弃",saving:"保存中...",cursorDelivery:"Cursor Delivery",aiReasoning:"AI 推理",confidenceLabel:"置信度 {value}%",sourceLabel:"来源:",noArticle:"(无项目特写内容)",noCode:"(无代码模板)",done:"完成",formatHeaders:"格式化",cleanUnused:"清理未引用",addHeader:"+ 添加",usedInCode:"代码中有引用",unusedInCode:"代码中未找到引用",unknown:"无法判断",unreferenced:"未引用",removeTag:"移除",deleteHeader:"删除",module:"模块",mode:"模式",difficulty:"难度",difficultyBeginner:"初级",difficultyIntermediate:"中级",difficultyAdvanced:"高级",highDuplicateRisk:"高重复风险:",compareBeforeSave:"建议先对比再保存",similarRecipes:"相似 Recipe:",referenced:"引用",collapseHeaders:"收起",editHeaders:"编辑"},createModal:{title:"New Recipe",importFromPath:"Import from Project Path",or:"Or",importFromClipboard:"Import from Clipboard",scanFile:"Scan File",useClipboard:"Use Copied Code",pathPlaceholder:"e.g. Sources/MyModule/Auth.swift",aiThinking:"AI is thinking..."},llmConfig:{title:"LLM 配置",provider:"AI Provider",model:"Model",apiKey:"API Key",proxy:"代理",optional:"(可选)",apiKeyPlaceholderSet:"留空保持当前 Key 不变",apiKeyPlaceholderEmpty:"请输入 API Key",envWarning:"项目尚未配置 .env 文件,保存后将自动创建。",cancel:"取消",saved:"已保存",saveToEnv:"保存到 .env",apiKeyRequired:"请填写 API Key",configured:"已配置:",saveSuccess:"保存成功",saveFailed:"保存失败",providers:{gemini:"Google Gemini",openai:"OpenAI",deepseek:"DeepSeek",claude:"Claude",ollama:"Ollama (本地)"}},recipeEditor:{title:"Edit Recipe",authorityScore:"权威分",path:"Path",description:"描述",markdown:"Markdown 文档",code:"代码 / 标准用法",rationale:"设计原理",steps:"实施步骤",codeChanges:"代码变更",validation:"验证方法",validationMethod:"方法:",validationExpected:"预期:",tags:"标签",constraints:"约束条件",guardRules:"Guard 规则",boundaryConstraints:"边界约束",preconditions:"前置条件",sideEffects:"副作用",relations:"关系图 (Relations)",preview:"Preview",edit:"Edit",cancel:"Cancel",saveChanges:"Save Changes",saving:"保存中...",qualityLevels:{basic:"Basic",good:"Good",solid:"Solid",great:"Great",excellent:"Excellent"},descPlaceholder:"Recipe 摘要描述...",rationalePlaceholder:"为何采用此方案...",relationTypes:{inherits:"继承",implements:"实现",calls:"调用",dependsOn:"依赖",dataFlow:"数据流",conflicts:"冲突",extends:"扩展",associates:"关联"},noContent:"No content",authorityFailed:"设置权威分失败:"},searchModal:{title:"as:search — 选择并插入",keyword:"关键词:",keywordAll:"(全部)",insertTo:"插入到:",noResults:"未找到匹配的 Recipe",quality:"质量:",insertBtn:"插入",inserting:"插入中...",insertSuccess:"✅ 已插入到",insertFailed:"❌ 插入失败"},refineProgress:{refining:"润色中",completed:"已完成",reviewing:"审核中",progress:"{current}/{total}",fields:"字段:",timeElapsed:"已用时",eta:"预计剩余",title:"AI 润色",doneTitle:"AI 润色完成",runningTitle:"AI 润色中",doneMsg:"{refined} 条已更新",doneMsgWithFail:"{refined} 条已更新,{failed} 条失败",progressMsg:"{done}/{total} 条候选",closeBtn:"关闭"},spmCompare:{title:"SPM 版本对比",current:"当前版本",latest:"最新版本",diff:"差异",added:"新增",removed:"移除",changed:"变更",unchanged:"未变",updateAvailable:"可更新",upToDate:"已是最新",updateBtn:"更新依赖",closeBtn:"关闭",package:"包名",from:"从",to:"到",noChanges:"无变更",candidateCopied:"候选内容已复制到剪贴板",recipeCopied:"Recipe 内容已复制到剪贴板",copied:"已复制",deleteConfirm:"确定删除该候选?",deleteFailed:"删除失败",compareTitle:"对比:候选 vs Recipe",deleteCandidate:"删除候选",auditCandidate:"审核候选",editRecipe:"编辑 Recipe",switchRecipe:"切换 Recipe:",candidateTitle:"候选:{title}",copyCandidate:"复制候选",noCode:"(无代码)",aiContextProfile:"AI Context / 项目特写",noGuide:"(无使用指南)",copyRecipe:"复制 Recipe"},silentLabels:{watch:"as:create",draft:"草稿",cli:"CLI",pending:"待审核(24h)",recipe:"新建片段"},lifecycle:{pending:"待审核",active:"已发布",deprecated:"已废弃"},kind:{rule:"规则",pattern:"模式",fact:"事实"},app:{errorBoundary:{title:"页面出现异常",refreshBtn:"刷新页面"},sync:{success:"Recipes 已同步到 IDE Snippets",successTitle:"Snippet 同步成功",failed:"同步失败",failedHint:"请检查 IDE 配置并重试"},projectRefresh:{success:"Target 列表与文件树已更新",successTitle:"项目结构已刷新",failed:"刷新失败"},extract:{success:"提取结果已进入候选池,请在 Candidates 页审核",successTitle:"提取完成",markerSuccess:"精准锁定标记代码,已加入候选池",normalSuccess:"提取结果已加入候选池",noMarker:"未找到 ASD 标记,AI 将分析完整文件",extracting:"提取中",failed:"Extraction failed"},clipboard:{empty:"请先复制代码到剪贴板",emptyTitle:"剪贴板为空",analyzing:"已收到代码,AI 正在识别可复用模式...",analyzingTitle:"剪贴板分析中",resultMulti:"已识别 {count} 条 Recipe,请在候选池审核",resultTitle:"AI 识别完成",aiFailed:"AI 识别失败",permissionError:"浏览器可能未授权剪贴板访问",permissionTitle:"剪贴板读取失败"},load:{failed:"无法加载项目数据",failedTitle:"加载失败",failedHint:"请确认项目路径有效后重试"},scan:{events:{initializing:"正在启动扫描...",filesLoaded:"已加载 {count} 个源文件",readingFiles:"正在读取 {count} 个文件内容...",aiAnalyzing:"正在 AI 分析提取可复用模式...",enriching:"正在增强 {count} 条结果...",completing:"扫描完成,正在加载结果..."},streamInit:"正在建立流式连接...",completed:"扫描完成",targetSuccess:"发现 {count} 条可复用代码模式,请在右侧审核",targetSuccessTitle:"Target 扫描完成",aiNotConfigured:"AI 未配置",noResults:"AI 扫描未返回结果",noSnippets:"该 Target 中未找到可复用的代码片段",scanComplete:"扫描完成",scanFailedHint:"请确认 Target 包含有效的源代码文件",scanFailed:"扫描失败",timeout:"扫描超时,请尝试减少 Target 文件数量",timeoutTitle:"扫描超时",scanError:"扫描出错"},coldStart:{collecting:"正在收集项目结构...",skeletonCreated:"骨架已创建,正在后台填充...",skeletonDetail:"冷启动骨架已创建: {targets} 个 Target, {files} 个文件, {deps} 条依赖...正在后台逐维度填充...",guardSuffix:"Guard: {count} 项违规",timeout:"冷启动超时,请检查项目文件数量"},fullScan:{collecting:"正在收集所有 Target 文件...",phase5:"正在收集源文件...",phase15:"正在 AI 分析代码模式...",phase25:"AI 提取中(大项目可能需要数分钟)...",phase35:"AI 提取中...",phase45:"AI 深度分析中...",phase55:"持续处理中...",phase65:"正在运行 Guard 审计...",phase75:"正在汇总结果...",phase85:"即将完成...",partialComplete:"扫描部分完成(超时)",completed:"全项目扫描完成",resultDetail:"全项目扫描完成: {count} 条候选",guardSuffix:"Guard: {count} 处违反",timeoutSuffix:"(部分结果,AI 超时)",noContent:"全项目扫描完成,未发现可提取内容",timeout:"扫描超时,请尝试减少项目文件数量或分 Target 扫描",timeoutTitle:"扫描超时",scanError:"扫描出错"},recipe:{triggerRequired:"请输入 Trigger",savedAsRecipe:"已保存并发布为 Recipe",savedToKb:"已保存到 KB",saveFailed:"保存失败",saveRecipeFailed:"保存 Recipe 失败",deleteFailed:"删除失败"},candidate:{clearConfirm:"确定移除「{name}」下的全部候选?",clearDone:"已移除 {name} 下的全部候选",pushSuccess:"已加入 Candidate 待审核队列",pushFailed:"创建 Candidate 失败"}},globalChat:{refineFields:{summary:"摘要",code:"代码/标准用法",markdown:"Markdown 文档",rationale:"设计原理",tags:"标签",confidence:"置信度",aiInsights:"AI 洞察",agentNotes:"Agent 笔记",relations:"关联关系"},diff:{noChanges:"未检测到变更",excludedRestore:"已排除 · 恢复",exclude:"排除",before:"Before",after:"After",empty:"(空)"},system:{refinePrefix:`🎯 润色模式 — **{title}**
1
+ import{r as o,j as e,z as wa,l as sl,h as ka,o as Ca,m as Sa,M as al,a as ll,R as Ct,F as rl,b as nl}from"./vendor-CEnWn7aV.js";import{a as ss}from"./axios-C0Zqfgkc.js";import{Z as et,L as Aa,S as ol,B as rs,H as as,C as il,a as dt,W as cl,G as _s,b as tt,c as lt,d as ws,e as dl,f as ul,D as Da,g as ns,P as pl,h as Pt,i as xl,F as wt,j as xt,k as Ls,l as nt,M as Lt,m as ml,n as $s,o as hl,p as gl,q as Qe,E as os,r as bl,s as fl,U as Ia,t as yl,u as Nt,X as Xe,v as Me,w as kt,R as Ra,x as rt,y as Bs,A as Ta,z as ft,I as jl,J as Ea,K as Gt,N as yt,O as vl,Q as Nl,T as wl,V as kl,Y as is,_ as Cl,$ as Sl,a0 as Pa,a1 as Al,a2 as Dl,a3 as Et,a4 as ot,a5 as ls,a6 as ht,a7 as Gs,a8 as Cs,a9 as Ht,aa as Ss,ab as Hs,ac as jt,ad as La,ae as Xt,af as Il,ag as Ys,ah as Qs,ai as fs,aj as Ma,ak as cs,al as ys,am as qt,an as Xs,ao as Ot,ap as Rl,aq as Fa,ar as Ms,as as Rt,at as Tl,au as za,av as _a,aw as $a,ax as El,ay as Pl,az as Fs,aA as Ll,aB as qs,aC as Ml,aD as Fl,aE as zl,aF as _l,aG as $l}from"./icons-eQ_rWCus.js";import"./yaml-qRaU8Ldn.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const d of document.querySelectorAll('link[rel="modulepreload"]'))l(d);new MutationObserver(d=>{for(const c of d)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&l(u)}).observe(document,{childList:!0,subtree:!0});function a(d){const c={};return d.integrity&&(c.integrity=d.integrity),d.referrerPolicy&&(c.referrerPolicy=d.referrerPolicy),d.crossOrigin==="use-credentials"?c.credentials="include":d.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function l(d){if(d.ep)return;d.ep=!0;const c=a(d);fetch(d.href,c)}})();const zs={common:{save:"保存",saving:"保存中...",saved:"已保存",cancel:"取消",confirm:"确认",delete:"删除",edit:"编辑",close:"关闭",copy:"复制",copied:"已复制",loading:"加载中...",retry:"重试",refresh:"刷新页面",back:"返回",search:"搜索",noData:"暂无数据",operationFailed:"操作失败",saveFailed:"保存失败",deleteFailed:"删除失败",loadFailed:"加载失败",areYouSure:"Are you sure?",yes:"是",no:"否",all:"全部",none:"无",preview:"预览",apply:"应用",applying:"应用中...",stop:"停止",export:"导出",import:"导入",more:"更多",collapse:"折叠",expand:"展开"},sidebar:{recipes:"Recipes",moduleExplorer:"Modules",candidates:"候选 ({count})",batchManage:"批量管理",depGraph:"依赖关系",knowledgeGraph:"知识图谱",guard:"代码审计",skills:"Skills",repoWiki:"Wiki",aiAssistant:"AI 助手",help:"使用说明",collapseNav:"折叠导航",expandNav:"展开导航",roleDeveloper:"开发者",roleAgent:"Agent",roleChatAgent:"ChatAgent",modeLogin:"登录",modeProbe:"探针",logout:"登出",tokenLabel:"7日 Token",tokenCalls:"次调用",tokenCallsFull:"{count} 次 AI 调用"},header:{searchPlaceholder:"搜索知识库...",semanticSearch:"语义搜索",semanticSearchTitle:"语义搜索 (AI 向量检索)",semanticSearchFailed:"语义搜索失败。请确保已运行 asd embed 构建索引。",aiSwitchFailed:"切换 AI 失败,请检查项目根目录是否可写。",aiNotConfigured:"AI 未配置 — 点击设置 LLM",configureLlm:"配置 LLM",clickSwitchAi:"点击切换 AI 提供商",switchAi:"切换 AI",editEnvConfig:"修改 .env 配置",closeAiChat:"关闭 AI 对话",openAiChat:"打开 AI 对话",aiChat:"AI 对话",newRecipe:"新建 Recipe",syncSnippets:"同步 Snippets",langSwitch:"中 / EN"},login:{title:"AutoSnippet",subtitle:"连接开发者、AI 与项目知识库",heading:"登录 Dashboard",username:"用户名",password:"密码",usernamePlaceholder:"输入用户名",passwordPlaceholder:"输入密码",usernameRequired:"请输入用户名",passwordRequired:"请输入密码",loginFailed:"登录失败,请重试",loggingIn:"登录中...",loginBtn:"登录",envHint:"登录功能由 VITE_AUTH_ENABLED 环境变量控制"},pagination:{showing:"显示 {start}-{end},共 {total} 条",perPage:"每页",unit:"条",firstPage:"第一页",prevPage:"上一页",nextPage:"下一页",lastPage:"最后一页"},recipes:{title:"Recipe 知识库",sortNewest:"最新",sortAlpha:"字母",sortQuality:"质量",filterAll:"全部类型",filterSnippet:"仅 Snippet",filterKnowledge:"仅 Knowledge",searchPlaceholder:"搜索 Recipes...",totalCount:"共 {count} 条",noResults:"没有匹配的 Recipe",batchActions:"批量操作",selectAll:"全选",deselectAll:"取消全选",batchDelete:"删除选中",batchDeleteConfirm:"确定删除选中的 {count} 条 Recipe?",batchDeleteDone:"已删除 {count} 条",qualityAuthorityScore:"权威分",qualityExcellent:"Excellent",qualityGreat:"Great",qualitySolid:"Solid",qualityGood:"Good",qualityBasic:"Basic",knowledgeType:"类型",typeSnippet:"Snippet",typeKnowledge:"Knowledge",sourceLabel:"来源",sourceBootstrap:"bootstrap",sourceManual:"manual",sourceAiScan:"ai-scan",sourceExtract:"extract",sourceClipboard:"clipboard",editRecipe:"编辑",deleteRecipe:"删除",pushToCandidate:"推入候选",recipeDetail:"Recipe 详情",editBtn:"Edit",description:"描述",markdown:"Markdown",code:"代码",designRationale:"设计原理",steps:"实施步骤",codeChanges:"代码变更",validation:"验证方法",tags:"标签",constraints:"约束条件",guardRules:"Guard 规则",boundaryConstraints:"边界约束",preconditions:"前置条件",sideEffects:"副作用",relations:"关系图 (Relations)",headers:"Headers",noContent:"No content",semanticResults:"语义搜索结果",semanticSimilarity:"相似度",insertToFile:"插入到文件",viewInRecipes:"在 Recipes 中查看",reasoning:"推理依据",sourceColon:"来源:",confidenceColon:"置信度:",alternativesLabel:"备选:",qualityGrade:"质量评级",qualityCompleteness:"完整性",qualityAdaptation:"适配度",qualityDocumentation:"文档度",usageCount:"使用 {count}",emptyValue:"(空)",verificationMethod:"方法:",verificationExpected:"预期:",knowledgeTypes:{codePattern:"代码模式",architecture:"架构设计",bestPractice:"最佳实践",codeStandard:"代码规范",callChain:"调用链路",rule:"规则"}},candidates:{title:"Candidate 审核池",tabs:{pending:"待审",approved:"已批准",rejected:"已拒绝"},sortNewest:"最新优先",sortOldest:"最早优先",sortConfidence:"按置信度",searchPlaceholder:"搜索候选...",totalCount:"共 {count} 条待审",noResults:"没有待审候选",noPending:"已全部审核",confidenceHigh:"高",confidenceMedium:"中",confidenceLow:"低",sourceBootstrap:"冷启动",sourceManual:"manual",sourceAiScan:"ai-scan",sourceExtract:"extract",sourceClipboard:"clipboard",sourceSignal:"signal",approve:"批准",reject:"拒绝",approveAndSave:"批准并保存为 Recipe",batchApprove:"批量批准 ({count})",batchReject:"批量拒绝 ({count})",batchDeleteConfirm:"确定移除选中的 {count} 条候选?",batchDeleteDone:"已删除 {count} 条",approveSuccess:"已批准为 Recipe",rejectSuccess:"已拒绝",aiRefine:"AI 润色",viewDetail:"查看详情",selectAll:"全选",deselectAll:"取消全选",silent:"静默",expandedDetail:"展开详情",collapse:"收起",qualityDimensions:"质量维度",authorityScore:"权威分",trigger:"Trigger",category:"Category",language:"Language",path:"Path",description:"描述",code:"代码",markdown:"Markdown",rationale:"设计原理",tags:"标签",headers:"Headers",confidence:"置信度",source:"来源",createdAt:"创建时间",updatedAt:"更新时间",groupByTarget:"按 Target 分组",clearGroup:"确定移除「{name}」下的全部候选?",clearGroupDone:"已移除 {name} 下的全部候选",coldStartTitle:"冷启动:结构收集 + 9 维度 Candidate 创建(与 MCP 一致)",enrichTitle:"① 结构补齐:填充缺失的 rationale / knowledgeType / complexity / scope / steps / constraints(只填空不覆盖,建议先于润色执行)",refineTitle:"② 内容润色:改善 summary 描述、补充架构洞察、推断 relations 关联、调整 confidence 评分(逐条 AI 精炼,建议在结构补齐之后执行)",withCode:"(含代码 {count})",emptyHint:"点击下方按钮冷启动知识库,或使用 CLI 命令手动创建",fullScanBtn:"全量扫描 ·",clipboardCreate:"从剪贴板创建",scanningHint:"各维度知识正在后台提取并接受 AI 审查,完成后候选内容将自动展示",scannedAt:"扫描于 {time}",similarOnly:"只看相似",resetFilters:"重置",approveCurrentPage:"当前页进入审核",removeCurrentPage:"移除当前页",deleteAll:"全部删除",overallScore:"综合 {score}",similarPrefix:"相似",linesCount:"{count} 行",enrichTitleSingle:"① 结构补齐:填充缺失的语义字段(rationale / knowledgeType / complexity 等)",refineTitleSingle:"② 内容润色:改善描述、补充洞察、推断关联(支持自定义提示词)",projectProfile:"项目特写",recipeCompare:"Recipe 对比",refineEnhanced:"润色增强信息",agentNotes:"Agent 笔记:",similarRecipe:"相似 Recipe",similarWith:"与 {name} 相似 {score}%",enrichShort:"补齐",refineShort:"润色",enrichTitleBottom:"① 结构补齐",refineTitleBottom:"② 内容润色",timeJustNow:"刚刚",timeMinutesAgo:"{n} 分钟前",timeHoursAgo:"{n} 小时前",timeDaysAgo:"{n} 天前",confidenceHighLabel:"高",confidenceMediumLabel:"中",confidenceMediumLowLabel:"中低",confidenceLowLabel:"低",sourceAiScanLabel:"AI 全量扫描",sourceMcpLabel:"MCP 提交",sourceManualLabel:"手动创建",sourceFileWatcherLabel:"文件监听",sourceClipboardLabel:"剪贴板",sourceSignalLabel:"信号",sourceSubmitCheckLabel:"AI 审查提交"},knowledge:{title:"批量管理",lifecycle:"生命周期",lifecycleCandidate:"Candidate",lifecycleRecipe:"Recipe",lifecycleArchived:"Archived",searchPlaceholder:"搜索知识条目...",totalCount:"共 {count} 条",noResults:"无匹配条目",batchActions:"批量操作",batchPromote:"批量晋升",batchDemote:"批量降级",batchArchive:"批量归档",batchDelete:"批量删除",batchDeleteConfirm:"确定删除选中的 {count} 条知识?",batchDeleteDone:"已删除 {count} 条",selectAll:"全选",deselectAll:"取消全选",detail:"知识详情",detailContent:"内容",detailQuality:"质量",detailMeta:"元数据",qualityCompleteness:"完整度",qualityClarity:"清晰度",qualityRelevance:"关联性",qualityAccuracy:"精确度",qualityUsability:"可用性",authorityScore:"权威分",source:"来源",category:"分类",language:"语言",createdAt:"创建时间",updatedAt:"更新时间",path:"路径",trigger:"触发词",lifecyclePending:"待审核",lifecycleActive:"已发布",lifecycleDeprecated:"已废弃",actionPublish:"发布",actionDeprecate:"废弃",actionReactivate:"重新激活",sourceBootstrap:"AI 全量扫描",sourceMcp:"MCP 提交",sourceManual:"手动创建",sourceFileWatcher:"文件监听",sourceClipboard:"剪贴板",sourceCli:"CLI",sourceAgent:"AI Agent",sourceSubmitCheck:"AI 审查提交",allCategories:"所有分类",selectedCount:"已选 {count} 条",batchPublish:"批量发布",quickBatchPublish:"快速批量发布",batchPublishResult:"发布 {success} 条,失败 {fail} 条",batchPublishFailed:"批量发布失败",batchPublishComplete:"批量发布完成",noAutoApprovable:"当前没有可自动通过的待审核条目",noPublishable:"无可发布项",autoPublishResult:"已发布 {count} 条可自动通过的条目",autoApprovable:"可自动通过",clearFilters:"清除筛选条件",loadFailed:"加载知识条目失败",operationSuccess:"操作成功",deleteConfirmMsg:"确定删除「{title}」?此操作不可恢复。",deleteSuccess:"已删除「{title}」",deleteFailed:"删除失败",deprecateReasonPrompt:"请输入废弃原因:",rejectionReason:"驳回原因",summary:"摘要",relatedKnowledge:"关联知识",reasoning:"推理依据",confidence:"置信度",alternatives:"备选",qualityGrade:"质量评级",qualityAdaptation:"适配度",qualityDocumentation:"文档度",qualityCompletionLabel:"完整性",markdownDoc:"Markdown 文档",importHeaders:"导入头文件",codePattern:"代码 / 标准用法",designRationale:"设计原理",implementSteps:"实施步骤",constraintsLabel:"约束条件",aiInsight:"AI 洞察",lifecycleHistoryLabel:"生命周期历史",scope:"范围",scopeUniversal:"通用",scopeProject:"项目级",scopeModule:"模块级",complexity:"复杂度",complexityAdvanced:"高级",complexityIntermediate:"中级",complexityBeginner:"初级",sourceFile:"源文件",prev:"上一条",next:"下一条",narrow:"收窄",widen:"展宽",guardHits:"Guard",adoptions:"采纳",searchHits:"搜索",statViews:"浏览",statApplications:"应用",published:"发布"},knowledgeGraph:{title:"知识图谱",nodeTypes:"节点类型",nodeRecipe:"Recipe",nodeModule:"Module",nodeFile:"File",nodeSymbol:"Symbol",relationInherits:"继承",relationImplements:"实现",relationCalls:"调用",relationDependsOn:"依赖",relationDataFlow:"数据流",relationConflicts:"冲突",relationExtends:"扩展",relationAssociates:"关联",relationContains:"包含",relationImports:"导入",relationOverrides:"覆盖",relationComposedOf:"组合",relationReferencedBy:"被引用",relationTestedBy:"被测试",relationDocumentedIn:"被记录",tools:"工具",zoomIn:"放大",zoomOut:"缩小",resetView:"重置视图",fitView:"适应画布",toggleLabels:"显示/隐藏标签",nodeDetail:"节点详情",relatedNodes:"关联节点",noSelection:"点击节点查看详情",legend:"图例",searchPlaceholder:"搜索节点...",noResults:"没有匹配的节点",totalNodes:"共 {count} 个节点",totalEdges:"共 {count} 条边",loadFailed:"加载知识图谱失败",empty:"知识图谱为空",emptyDesc:"当前没有 Recipe 之间的关系数据。点击下方按钮让 AI 自动分析已有 Recipe 之间的潜在关系(requires / extends / enforces / calls 等)。",discoverRelations:"AI 发现关系",discovering:"AI 分析中…",refresh:"刷新",retry:"重试",statsLabel:"{nodes} 节点 · {edges} 关系",cancelSelection:"取消选中",outEdges:"出边(依赖)",inEdges:"入边(被依赖)",none:"无",relationRequires:"需要",relationEnforces:"约束",relationPrerequisite:"前置",relationReferences:"引用",relationAlternative:"替代",relationDeprecatedBy:"废弃",relationSolves:"解决",discoverAnalyzing:"AI 分析中…(已运行 {elapsed}s)",discoverPollTimeout:"轮询超时,任务可能仍在后台运行。请稍后刷新页面查看结果。",discoverNoResults:"分析完成,共检查 {pairs} 对 Recipe,未发现关系。待 Recipe 数量增加后可再次尝试。",discoverBatchErrors:"分析完成,但 {errors} 个批次 AI 调用失败,未发现关系。请检查 AI Provider 配置。",discoverSuccess:"发现 {count} 条关系(共分析 {pairs} 对{failMsg})",discoverBatchFailed:",{count} 个批次失败",discoverAiNotConfigured:"AI 服务未配置: {error}",discoverTimeout:"任务超时: {error}",discoverFailed:"发现失败: {error}",discoverRunning:"AI 分析仍在进行中…",discoverStarted:"AI 分析已启动,正在后台运行…",discoverInsufficientRecipes:"Recipe 数量不足,无法分析",discoverPreviousTimeout:"上次任务超时,请重试",discoverAiUnavailable:"AI 服务不可用: {error}",discoverStartFailed:"启动失败: {error}",unknownError:"未知错误",discoverTooltip:"AI 自动发现 Recipe 关系"},guard:{title:"Guard 审计",summary:"概览",totalViolations:"共 {count} 项违规",noViolations:"没有违规项",searchPlaceholder:"搜索规则或文件...",severityError:"错误",severityWarning:"警告",severityInfo:"信息",ruleId:"规则 ID",file:"文件",line:"行",message:"消息",severity:"严重性",statusOpen:"待处理",statusResolved:"已解决",statusIgnored:"已忽略",resolve:"标记为已解决",ignore:"忽略",reopen:"重新打开",aiGenRule:"AI 生成规则",aiGenRuleDesc:"描述你想要检测的模式,AI 将生成 Guard 规则",aiGenPlaceholder:"例: 禁止在 View 中直接调用网络请求",aiGenerating:"AI 生成中...",aiGenSuccess:"规则已生成",aiGenFailed:"规则生成失败",refreshAudit:"刷新审计",refreshing:"审计刷新中...",refreshSuccess:"审计已刷新",reportIssue:"提交误报",clearHistory:"清空历史",clearConfirm:"确定清空所有 Guard 违反记录?",addRuleValidation:"请填写规则 ID、说明、正则和至少一种语言",patternLabel:"正则(对每行匹配,JSON 中反斜杠需双写)",languagesLabel:"语言",dimensionLabel:"审查规模",noteLabel:"备注",allLanguages:"所有语言",noMatchingRules:"无匹配规则,请调整筛选条件",violationRecords:"违反记录(共 {runs} 次运行,{count} 处违反)",dimFile:"同文件",dimTarget:"同 target",dimProject:"同项目",rationale:"技术原因",fixSuggestion:"修复建议",sourceRecipe:"来源 Recipe",categorySafety:"安全",categoryCorrectness:"正确性",categoryPerformance:"性能",categoryStyle:"风格",category:"分类",currentProject:"当前项目",generatedRuleId:"已生成规则 ID",dimNoLimit:"不限制",notePlaceholder:"仅作简单模式提示",copyFixSuggestion:"复制修复建议",tableHeaders:{rule:"规则",file:"文件",line:"行号",message:"描述",severity:"级别",status:"状态",actions:"操作"}},skills:{title:"Skills 管理",searchPlaceholder:"搜索 Skills...",totalCount:"共 {count} 条",noResults:"没有匹配的 Skill",addSkill:"新增 Skill",editSkill:"编辑 Skill",deleteSkill:"删除 Skill",deleteConfirm:"确定删除此 Skill?",deleteSuccess:"已删除",saveSuccess:"已保存",skillName:"名称",skillNamePlaceholder:"输入 Skill 名称",skillDescription:"描述",skillDescPlaceholder:"输入 Skill 描述",skillTrigger:"触发器",skillTriggerPlaceholder:"输入触发条件",skillAction:"动作",skillActionPlaceholder:"输入动作内容",skillEnabled:"已启用",skillDisabled:"已禁用",toggleEnable:"启用/禁用",aiRecommend:"AI 推荐",aiRecommendDesc:"基于项目分析,AI 推荐以下 Skills",aiRecommending:"AI 分析中...",aiRecommendSuccess:"已推荐 {count} 条",aiRecommendFailed:"推荐失败",acceptRecommend:"采纳",rejectRecommend:"忽略",bulkAccept:"全部采纳",signalBadge:"信号",category:"类别",priority:"优先级",priorityHigh:"高",priorityMedium:"中",priorityLow:"低",subtitle:"Agent 技能文档 — 指导 AI 如何正确使用 AutoSnippet 工具",fetchFailed:"获取 Skills 列表失败",loadError:"不存在或读取出错",loadSkillFailed:"加载 Skill 失败",updateSuccess:"更新成功",updateFailed:"更新 Skill 失败",deleteFailed:"删除 Skill 失败",createSuccess:"创建成功",createFailed:"创建 Skill 失败",createAddedToKB:"已创建并加入知识库",filterProject:"项目级",filterBuiltin:"内置",noRecommendations:"当前暂无推荐。继续使用后会积累更多信号。",aiRecommendTooltip:"基于使用模式分析推荐 Skill",creating:"创建中",useCase:"适用",chars:"字符",related:"相关",confirmDelete:"确认删除",deleteSkillConfirmMsg:'删除 Skill "{name}"?此操作不可撤销。',selectToView:"选择左侧 Skill 查看详情",checkGenerated:"请检查并确认生成的内容",aiGenerated:"AI 已生成 Skill",aiGenFailed:"AI 生成失败",fillRequired:"请填写名称、描述和内容",savedToKB:"已保存到知识库",aiGenMode:"AI 生成",manualMode:"手动填写",describeSkill:"描述你想创建的 Skill",aiGeneratingContent:"AI 正在生成...",generateSkill:"生成 Skill",skillContent:"Skill 文档内容",createdBy:{manual:"手动创建","user-ai":"AI 协助创建","system-ai":"自动创建","external-ai":"外部 AI 创建"}},depGraph:{title:"依赖关系图",searchPlaceholder:"搜索模块...",noResults:"没有匹配的模块",totalModules:"共 {count} 个模块",totalDeps:"共 {count} 条依赖",layout:"布局",layoutTree:"树形",layoutForce:"力导向",layoutCircular:"环形",zoomIn:"放大",zoomOut:"缩小",resetView:"重置视图",fitView:"适应画布",nodeDetail:"模块详情",dependencies:"依赖",dependents:"被依赖",legend:"图例",noSelection:"点击节点查看详情",depTypes:{direct:"直接依赖",transitive:"传递依赖",devOnly:"开发依赖"},refresh:"刷新",retry:"重试",noDataTitle:"当前项目内未扫描到模块依赖关系。",noDataDesc:"请确保项目包含模块定义文件(go.mod / package.json / Package.swift / build.gradle 等),然后点击 Refresh 重新扫描。",filterAll:"全部",filterInternal:"内部包",filterExternal:"外部依赖",packages:"包",packageList:"包列表",depRelations:"依赖关系(小图)",depRelationsDesc:"主图不显示连线,点击节点可在浮窗查看该包依赖;此处列出全部 From → To。",labelExternal:"外部",labelInternal:"内部",labelIndirect:"间接",projectRoot:"项目根",close:"关闭",none:"无",visualization:"模块依赖结构可视化",targetHint:"Target 级节点格式:"},bootstrap:{title:"冷启动进度",pipelineSteps:{collecting:"收集项目结构",scanning:"扫描源代码",analyzing:"AI 分析",enriching:"知识增强",indexing:"建立索引"},taskStatus:{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",skipped:"已跳过"},stats:{totalFiles:"文件总数",totalTargets:"Target 数",totalRecipes:"Recipe 数",totalTime:"总耗时",aiCalls:"AI 调用数"},notifications:{started:"冷启动已开始",completed:"冷启动完成",failed:"冷启动失败",partialComplete:"部分完成"},retryFailed:"重试失败任务",viewDetails:"查看详情",dimLabels:{architecture:"架构与设计",bestPractice:"规范与实践",eventAndDataFlow:"事件与数据流",objcDeepScan:"深度扫描",agentGuidelines:"Agent 注意事项",bootstrap:"Bootstrap",codeStandard:"代码规范",codePattern:"设计模式",projectProfile:"项目特征",categoryScan:"Category 分类方法"},pipelineLabels:{"project-profile":"项目概貌","objc-deep-scan":"深度扫描(常量/Hook)","category-scan":"基础类分类方法扫描","code-standard":"代码规范",architecture:"架构模式","code-pattern":"设计模式","event-and-data-flow":"事件与数据流","best-practice":"最佳实践","agent-guidelines":"Agent 开发注意事项"},statusLabels:{skeleton:"等待中",filling:"填充中",completed:"已完成",failed:"失败"},allCompleted:"全部完成",completedWithErrors:"完成(有错误)",elapsed:"已用",estimatedRemaining:"预计剩余",toolCalls:"工具调用",dimensions:"{done}/{total} 维度",notifySuccess:"{completed} 个维度全部填充成功",notifyPartial:"{completed}/{total} 成功,{failed} 失败",coldStartComplete:"冷启动完成",close:"关闭",reviewPipeline:"AI 审查管线",reviewRounds:{round1Label:"资格审查",round1Desc:"过滤误报 · 识别合并",round2Label:"内容精炼",round2Desc:"AI 改写摘要 · 动态置信度",round3Label:"去重 & 关系",round3Desc:"语义去重 · 关系推断"},round1Done:"保留 {kept} · 合并 {merged} · 丢弃 {dropped}",round2Progress:"{current}/{total} 条",round2Done:"已精炼 {refined}/{total} 条",round3Done:"去重后 {afterDedup} 条 · {relationsFound} 条关系",noMatch:"✓ 无匹配内容",featuresOnly:"✓ {sourceCount} 项特征",featuresAndCandidates:"✓ {sourceCount} 项特征 · {extracted} 条候选",candidatesOnly:"✓ {extracted} 条候选"},wiki:{title:"Repo Wiki",sidebar:"Wiki",fileCount:"{count} 篇",searchPlaceholder:"搜索文件...",generating:"文件生成中,新文档将自动出现…",backToList:"返回文件列表",aiBadge:"AI 增强",copySuccess:"已复制",copyBtn:"复制",loadFailed:"加载失败",incrementalUpdate:"增量更新",fullGeneration:"全量生成",genStarted:"Wiki 生成已启动",genFailed:"生成失败",selectPlaceholder:"从左侧文件树选择,或使用下方快捷入口",phases:{outline:"大纲",content:"内容",review:"审校"},fileTypes:{overview:"概述",module:"模块",api:"API",guide:"指南"},synced:"同步",wikiGenerating:"Wiki 正在生成中",outOfDateHint:"检测到代码变更,Wiki 可能已过期,建议增量更新",emptyTitle:"尚未生成 Repo Wiki",emptyDesc:"Wiki 在冷启动时自动全量生成,后续通过增量更新保持同步",emptyHint:"运行 asd setup 冷启动 · asd wiki --update 增量更新",quickOverview:"项目概述",quickOverviewDesc:"项目信息、技术栈与数据统计",quickArch:"架构总览",quickArchDesc:"模块依赖图、项目结构分析",quickStart:"快速上手",quickStartDesc:"构建、运行与入口分析",quickProtocols:"协议与组件",quickProtocolsDesc:"核心协议、委托和组件关系",selectFile:"选择一个文件开始阅读",lastGenerated:"最后生成",duration:"耗时",incrementalUpdating:"增量更新中...",loadFailedDesc:"无法读取文件内容。"},aiChat:{title:"AI Assistant",emptyTitle:"开始与 AI 对话",emptyDesc:"你可以询问项目相关问题,AI 将帮你分析代码、推荐模式。",inputPlaceholder:"输入你的问题...",inputHint:"Enter 发送 · Shift+Enter 换行",thinking:"AI 思考中...",analyzing:"AI 正在分析...",topicPanel:"话题列表",newTopic:"开启新话题",deleteTopic:"删除话题",deleteTopicConfirm:"确定删除此话题?",quickPrompts:{analyzeArch:"分析项目架构",findDuplicates:"查找重复代码",suggestOptimize:"推荐优化方向"},timeJustNow:"刚刚",timeMinutesAgo:"{n} 分钟前",timeHoursAgo:"{n} 小时前",timeDaysAgo:"{n} 天前",codeBlock:"代码块",diffView:"变更对比",diffBefore:"Before",diffAfter:"After",contextLabel:"AI Context / 项目特写",copyCode:"复制代码",topicRecords:"话题记录",noHistory:"暂无聊天记录",autoSaveHint:"开始对话后自动保存",topicCount:"{count} 个话题 · 本地存储",askAnything:"询问任何关于项目的问题",startChat:"开始 AI 对话",emptyDescLong:"询问关于你项目的任何问题 — 代码分析、架构建议、优化方向等。",aiAssistant:"AI 助手",messageCount:"{n} 条",requestFailed:"请求失败: {error}",cancelled:"(已取消)",expandTopics:"展开话题列表",diffEmpty:"(空)",quickPromptSummarize:"总结项目概况"},help:{title:"使用说明",gettingStarted:"快速开始",commands:"命令参考",faq:"常见问题",tokenUsage:"Token 用量",about:"关于",pageTitle:"AutoSnippet V3 使用说明",subtitle:"连接开发者、AI 与项目知识库:ChatAgent 智能对话 · Skills 开放平台 · 知识库持续生长",techSpecs:"Node.js ≥ 20 · 13 Skills · AI 可自建 · 16 MCP 工具 · ChatAgent 对话 · 4 层检索管线",viewGithub:"查看 GitHub",fullDocs:"完整文档",tokenUsageLast7Days:"Token 用量(近 7 日)",quickStart:"快速开始",coreConcepts:"核心概念",coreFeatures:"核心功能",editorDirectives:"编辑器指令",cursorIntegration:"Cursor AI 集成",v3Architecture:"V3 架构",cliReference:"命令行速查",step1Title:"安装与初始化",step2Title:"启动 Dashboard",step2Desc:"启动 HTTP API + Dashboard + FileWatcher",step3Title:"IDE 集成",step3Desc:"安装 MCP + Skills + Cursor Rules",step4Title:"创建第一个 Recipe",step4Desc1:"Dashboard → New Recipe",step4Desc2:"Use Copied Code → AI 填充 → 保存",threeRoles:"三大角色",roleColumn:"角色",responsibilityColumn:"职责",capabilityColumn:"能力",roleDeveloper:"开发者",roleCursorAgent:"Cursor Agent",roleChatAgent:"ChatAgent",developerResp:"审核与决策、维护项目标准",cursorAgentResp:"按规范生成代码、检索知识库",chatAgentResp:"提取、摘要、扫描、审查",coreComponents:"核心组件",bootstrapLabel:"Bootstrap(冷启动)",bootstrapDesc:"9 维度自动知识提取引擎",candidatesLabel:"Candidates(候选)",candidatesDesc:"待审核的 Recipe 草案",recipeLabel:"Recipe(配方)",recipeDesc:"Markdown 知识文档(Source of Truth)",chatAgentLabel:"ChatAgent(智能对话)",chatAgentDesc:"多 Agent 协作架构,可持续扩展",searchPipelineLabel:"4 层检索管线",searchPipelineDesc:"多模式语义搜索引擎",guardLabel:"Guard(代码审查)",guardDesc:"知识库驱动的代码审查",knowledgeLoop:"知识库闭环",loopStep1:"扫描提取",loopStep1Sub:"AI/Cursor",loopStep2:"人工审核",loopStep2Sub:"Dashboard",loopStep3:"知识沉淀",loopStep3Sub:".md 落盘",loopStep4:"智能使用",loopStep4Sub:"Cursor/Xcode",loopStep5:"持续优化",loopStep5Sub:"asd sync",knowledgeBuild:"知识库构建",semanticSearchLabel:"语义检索",codeAudit:"代码审查(Audit)",dataSync:"数据同步",usageExamples:"使用示例",exampleSearchKB:"检索知识库",exampleSearchKBDesc:'对 Cursor 说:"查找网络请求错误处理的代码"',exampleBatchScan:"批量扫描",exampleBatchScanDesc:'对 Cursor 说:"扫描 NetworkModule,生成 Recipes 到候选"',exampleSubmitCode:"提交代码",exampleSubmitCodeDesc:'对 Cursor 说:"把这段代码保存为 Recipe"',skills10:"10 个 Skills",mcp16:"16 个 MCP 工具(V3 参数化统合)",bootstrapEngine:"Bootstrap 冷启动引擎",bootstrapEngineDesc:"3 步完成知识库从 0 → 1:",fourLayerPipeline:"4 层检索管线",fourLayerPipelineDesc:"多信号融合的精准检索:",chatAgentSystem:"ChatAgent 对话系统",chatAgentSystemDesc:"多 Agent 协作架构,可持续扩展:",fiveEntryChannels:"五个入口通道",initAndEnv:"初始化与环境",kbManagement:"知识库管理",searchAndAudit:"搜索与审查",maintenanceUpgrade:"维护与升级",footerHint:"需要更详细的说明?查看 {link} 或运行 {cmd} 检查环境",footerGithubReadme:"GitHub README",mcpWriteNote:"写操作工具(submit_knowledge、guard、bootstrap 等)通过 Gateway 权限 / 宪法 / 审计三重保护。",editorDirectivesNote:"需先运行 asd watch 或 asd ui;支持快捷写法 asc / ass / asa",createDirective:"创建 Recipe/Snippet",searchDirective:"搜索并插入",auditDirective:"代码审查",includeDirective:"自动注入头文件/模块",developerCap:'Dashboard 审核候选、保存 Recipe;Snippet 补全、<code class="bg-slate-100 px-1 rounded">// as:search</code>;运行 <code class="bg-slate-100 px-1 rounded">asd ui</code>',cursorAgentCap:"13 个 Skills 理解规范;16 个 MCP 工具按需检索、提交候选;写操作经 Gateway 审核",chatAgentCap:'<code class="bg-slate-100 px-1 rounded">asd ais</code> 批量扫描;分析剪贴板;Guard 审查;Dashboard RAG',bootstrapBullet1:"扫描项目模块 + AST 分析源码",bootstrapBullet2:"启发式提取 → AI 精炼 → 生成 Candidate",bootstrapBullet3:'MCP 工具:<code class="bg-green-100 px-1 rounded">bootstrap</code>(operation: knowledge / refine / scan)',candidatesBullet1:"来源:AI 扫描、Cursor、剪贴板、Dashboard",candidatesBullet2:"审核后入库为 Recipe,确保质量",candidatesBullet3:"Reasoning 字段记录 AI 推理过程",recipeBullet1:'位置:<code class="bg-blue-100 px-1 rounded">AutoSnippet/recipes/*.md</code>',recipeBullet2:".md 文件 = 唯一数据源,DB 仅作索引缓存",recipeBullet3:'<code class="bg-blue-100 px-1 rounded">asd sync</code> 增量同步 .md → DB',chatAgentCompBullet1:"AnalystAgent 分析意图 → ProducerAgent 执行操作",chatAgentCompBullet2:"HandoffProtocol 自动切换 + 轻量记忆持久化",chatAgentCompBullet3:"项目感知:自动注入知识库状态上下文",searchPipelineBullet1:"InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",searchPipelineBullet2:"BM25 + keyword + semantic 三路融合",searchPipelineBullet3:"search MCP 工具:mode 参数路由 auto / keyword / semantic / context 四种模式",guardCompBullet1:"内建规则 + 自定义规则 + Recipe 关联",guardCompBullet3:'MCP:<code class="bg-rose-100 px-1 rounded">guard</code>(code=单文件 / files=批量)、<code class="bg-rose-100 px-1 rounded">bootstrap</code>(operation: scan)',kbBuildBullet1:'<strong>AI 扫描</strong>:<code class="bg-slate-100 px-1 rounded text-xs">asd ais [Target]</code> 批量提取',kbBuildBullet2:'<strong>Cursor 扫描</strong>:对 Copilot 说 "扫描 Module"',kbBuildBullet3:"<strong>手动创建</strong>:New Recipe → Use Copied Code",kbBuildBullet4:'<strong>编辑器内</strong>:复制代码 → <code class="bg-slate-100 px-1 rounded text-xs">// as:create -c</code>',semSearchBullet1:"<strong>4 层管线</strong>:InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",semSearchBullet2:'<strong>编辑器内</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:search keyword</code>',semSearchBullet3:"<strong>Cursor MCP</strong>:search 统合工具(mode 路由 4 种模式)",semSearchBullet4:"<strong>Dashboard</strong>:搜索框支持语义 + 关键词",auditFeatureBullet1:'<strong>文件审查</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:audit</code>',auditFeatureBullet2:'<strong>Target 审查</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:audit target</code>',auditFeatureBullet3:'<strong>Guard 审查</strong>:MCP <code class="bg-slate-100 px-1 rounded text-xs">guard</code>(code / files 参数)',auditFeatureBullet4:"<strong>Dashboard</strong>:Guard 页面可视化审查",syncBullet1:'<strong>同步</strong>:<code class="bg-slate-100 px-1 rounded text-xs">asd sync</code> .md → DB(增量)',syncBullet2:'<strong>Hash 校验</strong>:<code class="bg-slate-100 px-1 rounded text-xs">_contentHash</code> 检测手动编辑',syncBullet3:"<strong>向量索引</strong>:启动时自动构建语义索引",syncBullet4:'<strong>依赖图</strong>:<code class="bg-slate-100 px-1 rounded text-xs">structure</code>(operation: targets / files)MCP 工具',createDirBullet1:"无选项:打开 Dashboard",createDirBullet2:"<code>-c</code>:从剪贴板静默创建",createDirBullet3:"<code>-f</code>:扫描当前文件",searchDirBullet1:"从知识库检索 Recipe/Snippet",searchDirBullet2:"选择后插入代码,替换该行",searchDirBullet3:"记录一次人工使用",auditDirBullet1:"无后缀:审查当前文件",auditDirBullet2:"<code>target</code>:审查当前 Target",auditDirBullet3:"<code>project</code>:审查整个项目",includeDirBullet1:"Snippet 中包含此标记",includeDirBullet2:"补全后自动注入 import",skillIntent:"意图路由",skillConcepts:"概念教学",skillCandidates:"候选提交",skillRecipes:"Recipe 检索",skillGuard:"代码合规",skillStructure:"项目结构",skillAnalysis:"深度分析",skillColdstart:"冷启动",skillCreate:"引导创建",skillLifecycle:"生命周期",mcpLayerHeader:"层级",mcpToolHeader:"工具",mcpDescHeader:"说明",mcpAgentLayerHeader:"Agent 层(12 个)— 默认对外暴露",mcpAdminLayerHeader:"Admin 层(4 个)— 需设置 ASD_MCP_TIER=admin",mcpHealthDesc:"服务健康检查",mcpCapabilitiesDesc:"服务能力清单(Agent 自发现)",mcpGuardDesc:"code=单文件审查 / files=批量审查",mcpSubmitDesc:"提交候选 / 批量 / 保存文档",mcpEnrichDesc:"AI 润色 / 校验 / 查重",mcpLifecycleDesc:"批量生命周期操作",mcpSearchDesc:"mode 路由 auto / keyword / semantic / context",mcpKnowledgeDesc:"operation 路由 list / get / insights / confirm_usage",mcpStructureDesc:"operation 路由 targets / files / metadata",mcpGraphDesc:"operation 路由 query / impact / path / stats",mcpSkillDesc:"operation 路由 list / load / create / update / delete / suggest",mcpBootstrapDesc:"operation 路由 knowledge / refine / scan",archBootstrapStep1:"① 项目扫描 → 依赖 / 目录 / 入口分析",archBootstrapStep2:"② AI 批量提取 → Candidate 候选列表",archBootstrapStep3:"③ 审阅 + Promote → Recipe 知识库就绪",archBootstrapNote:"支持 bootstrap 工具(operation: refine)持续迭代、resume 断点续跑",archPipelineL1:"InvertedIndex — 倒排索引快速召回",archPipelineL2:"CoarseRanker — BM25 + TF-IDF 粗排",archPipelineL3:"MultiSignalRanker — 多维信号精排",archPipelineL4:"RetrievalFunnel — 漏斗截断 + 上下文装配",archAnalystAgent:"<strong>AnalystAgent</strong>:分析用户意图 → 检索知识库 → 给出建议 → 信心信号分级",archProducerAgent:"<strong>ProducerAgent</strong>:生成代码 → 创建候选 → 执行操作 → 结果聚合",archHandoff:"<strong>HandoffProtocol</strong>:两个 Agent 之间的自动切换协议",archMemory:"<strong>轻量记忆</strong>:跨对话偏好/决策/上下文持久化(JSONL,TTL 过期)",archProjectAware:"<strong>项目感知</strong>:自动注入知识库状态(Recipe 分布、候选积压量、Guard 规则数)",archCliDesc:"asd × 10 命令",archMcpDesc:"stdio × 16 工具",archHttpDesc:"Express × 14 路由模块",archSkillsDesc:"13 个 Cursor/Copilot",cliSetupDesc:"初始化项目",cliStatusDesc:"环境自检",cliUiDesc:"启动 Dashboard",cliUpgradeDesc:"升级 IDE 集成",cliSyncDesc:".md → DB 增量同步",cliAisDesc:"AI 扫描提取 Candidates",cliAisForceDesc:"强制重新扫描全量",cliWatchDesc:"文件监控 + 指令触发",cliSearchDesc:"搜索知识库",cliSearchSemanticDesc:"语义搜索模式",cliGuardDesc:"Guard 规则检查",cliServerDesc:"单独启动 API 服务",cliUpgradeMcpDesc:"升级 MCP / Skills / Rules",cliInstallFullDesc:"全量安装 IDE 集成",cliSyncForceDesc:"全量重建 DB",cliSyncDryDesc:"预览同步变更"},moduleExplorer:{title:"Module Explorer",scanTargets:"扫描 Targets",scanning:"扫描中...",scanComplete:"扫描完成",targetFiles:"{count} 个文件",noTargets:"未发现 Target",recipesInTarget:"关联 Recipes",guardSummary:"Guard 概况",guardViolations:"{count} 项违规",noViolations:"无违规",openFile:"打开文件",refreshTree:"刷新文件树",extractFromFile:"提取代码",fileDetail:"文件详情",projectModules:"项目模块 ({count})",addFolderScan:"添加目录扫描",refreshProject:"刷新项目结构",discovererFolderScan:"目录扫描",removeFolder:"移除此目录",fullProjectResults:"全项目扫描结果",moduleLabel:"模块: {name}",reviewResults:"审核提取结果",resultsCount:"{count} 条",candidateSuffix:" Candidate",fullProjectScanning:"全项目扫描中",moduleScanLabel:"模块扫描: {name}",filesInScan:"本次扫描的文件 ({count})",knowledgeExtract:"知识提取",knowledgeExtractHint:"在左侧选择模块扫描,或点击 + 添加任意目录。提取代码模式并生成 Recipe 知识卡片。",guardAuditSummary:"Guard 审计摘要",auditedFiles:"已审计文件:",totalViolationsLabel:"违反总数:",errorsCount:"{count} 错误",warningsCount:"{count} 警告",recipeNotExist:"「{name}」不存在于当前知识库",recipeNotExistTitle:"Recipe 不存在",loadRecipeFailed:"加载 Recipe 失败",browseFailedTitle:"目录浏览失败",browseFailedDefault:"无法加载目录列表",selectFolderTitle:"选择要扫描的目录",scanningDirs:"正在扫描项目目录...",noDirs:"未发现可扫描的目录",sourceFileCount:"{count} 文件",selectFolderHint:"选择包含源码文件的目录,系统将自动检测语言并执行 AI 扫描",modulesTabLabel:"模块 ({count})",foldersTabLabel:"目录"},search:{title:"智能搜索",searchPlaceholder:"输入搜索关键词...",noResults:"未找到匹配结果",resultCount:"找到 {count} 条结果",relevance:"相关度",source:"来源",category:"分类",language:"语言",matchType:"匹配类型",matchExact:"精确",matchFuzzy:"模糊",matchSemantic:"语义匹配",matchKeyword:"关键词匹配",viewRecipe:"查看 Recipe",insertCode:"插入代码",searchFailed:"搜索失败。请重试。",searching:"搜索中...",searchBtn:"搜索",emptyHint:"输入关键词后点击搜索",contextRelevant:"上下文相关",authorityScore:"权威分",usage:"使用",usageCount:"{count}次",recommendReason:"推荐理由",viewFullContent:"查看完整内容",similarity:"相似度",quality:"质量",noContent:"无内容",useSnippet:"使用此片段",importedFrameworks:"导入的框架:",relatedApis:"相关 APIs:"},scanResult:{title:"扫描结果",trigger:"Trigger",triggerPlaceholder:"@kebab-case-id",description:"描述",descPlaceholder:"中文简述 ≤80 字,引用真实类名",category:"分类",language:"语言",code:"代码模板",markdown:"项目特写",rationale:"设计原理",tags:"标签",tagsPlaceholder:"标签: 按 Enter/逗号添加...",headers:"Imports",headersPlaceholder:"#import <Header.h>",confidence:"置信度",confidenceHigh:"高",confidenceMedium:"中",confidenceLow:"低",source:"来源",authorityScore:"权威分",saveAsRecipe:"保存为 Recipe",saveAsKnowledge:"保存知识",discard:"丢弃",keepCandidate:"保留候选",qualityWarning:"质量提醒",lowQualityHint:"该条目质量较低,建议润色后再保存",editBeforeSave:"编辑后保存",triggerRequired:"请输入 Trigger",savedAsRecipe:"已保存并发布为 Recipe",savedToKb:"已保存到 KB",validation:"验证方法",validationMethod:"方法:",validationExpected:"预期:",steps:"实施步骤",codeChanges:"代码变更",constraints:"约束条件",guardRules:"Guard 规则",boundaryConstraints:"边界约束",preconditions:"前置条件",sideEffects:"副作用",relations:"关系图 (Relations)",knowledgeEntryTitle:"知识条目标题",aiScan:"AI 扫描",lifecyclePending:"待审核",lifecycleActive:"已发布",lifecycleDeprecated:"已废弃",saving:"保存中...",cursorDelivery:"Cursor Delivery",aiReasoning:"AI 推理",confidenceLabel:"置信度 {value}%",sourceLabel:"来源:",noArticle:"(无项目特写内容)",noCode:"(无代码模板)",done:"完成",formatHeaders:"格式化",cleanUnused:"清理未引用",addHeader:"+ 添加",usedInCode:"代码中有引用",unusedInCode:"代码中未找到引用",unknown:"无法判断",unreferenced:"未引用",removeTag:"移除",deleteHeader:"删除",module:"模块",mode:"模式",difficulty:"难度",difficultyBeginner:"初级",difficultyIntermediate:"中级",difficultyAdvanced:"高级",highDuplicateRisk:"高重复风险:",compareBeforeSave:"建议先对比再保存",similarRecipes:"相似 Recipe:",referenced:"引用",collapseHeaders:"收起",editHeaders:"编辑"},createModal:{title:"New Recipe",importFromPath:"Import from Project Path",or:"Or",importFromClipboard:"Import from Clipboard",scanFile:"Scan File",useClipboard:"Use Copied Code",pathPlaceholder:"e.g. Sources/MyModule/Auth.swift",aiThinking:"AI is thinking..."},llmConfig:{title:"LLM 配置",provider:"AI Provider",model:"Model",apiKey:"API Key",proxy:"代理",optional:"(可选)",apiKeyPlaceholderSet:"留空保持当前 Key 不变",apiKeyPlaceholderEmpty:"请输入 API Key",envWarning:"项目尚未配置 .env 文件,保存后将自动创建。",cancel:"取消",saved:"已保存",saveToEnv:"保存到 .env",apiKeyRequired:"请填写 API Key",configured:"已配置:",saveSuccess:"保存成功",saveFailed:"保存失败",providers:{gemini:"Google Gemini",openai:"OpenAI",deepseek:"DeepSeek",claude:"Claude",ollama:"Ollama (本地)"}},recipeEditor:{title:"Edit Recipe",authorityScore:"权威分",path:"Path",description:"描述",markdown:"Markdown 文档",code:"代码 / 标准用法",rationale:"设计原理",steps:"实施步骤",codeChanges:"代码变更",validation:"验证方法",validationMethod:"方法:",validationExpected:"预期:",tags:"标签",constraints:"约束条件",guardRules:"Guard 规则",boundaryConstraints:"边界约束",preconditions:"前置条件",sideEffects:"副作用",relations:"关系图 (Relations)",preview:"Preview",edit:"Edit",cancel:"Cancel",saveChanges:"Save Changes",saving:"保存中...",qualityLevels:{basic:"Basic",good:"Good",solid:"Solid",great:"Great",excellent:"Excellent"},descPlaceholder:"Recipe 摘要描述...",rationalePlaceholder:"为何采用此方案...",relationTypes:{inherits:"继承",implements:"实现",calls:"调用",dependsOn:"依赖",dataFlow:"数据流",conflicts:"冲突",extends:"扩展",associates:"关联"},noContent:"No content",authorityFailed:"设置权威分失败:"},searchModal:{title:"as:search — 选择并插入",keyword:"关键词:",keywordAll:"(全部)",insertTo:"插入到:",noResults:"未找到匹配的 Recipe",quality:"质量:",insertBtn:"插入",inserting:"插入中...",insertSuccess:"✅ 已插入到",insertFailed:"❌ 插入失败"},refineProgress:{refining:"润色中",completed:"已完成",reviewing:"审核中",progress:"{current}/{total}",fields:"字段:",timeElapsed:"已用时",eta:"预计剩余",title:"AI 润色",doneTitle:"AI 润色完成",runningTitle:"AI 润色中",doneMsg:"{refined} 条已更新",doneMsgWithFail:"{refined} 条已更新,{failed} 条失败",progressMsg:"{done}/{total} 条候选",closeBtn:"关闭"},spmCompare:{title:"SPM 版本对比",current:"当前版本",latest:"最新版本",diff:"差异",added:"新增",removed:"移除",changed:"变更",unchanged:"未变",updateAvailable:"可更新",upToDate:"已是最新",updateBtn:"更新依赖",closeBtn:"关闭",package:"包名",from:"从",to:"到",noChanges:"无变更",candidateCopied:"候选内容已复制到剪贴板",recipeCopied:"Recipe 内容已复制到剪贴板",copied:"已复制",deleteConfirm:"确定删除该候选?",deleteFailed:"删除失败",compareTitle:"对比:候选 vs Recipe",deleteCandidate:"删除候选",auditCandidate:"审核候选",editRecipe:"编辑 Recipe",switchRecipe:"切换 Recipe:",candidateTitle:"候选:{title}",copyCandidate:"复制候选",noCode:"(无代码)",aiContextProfile:"AI Context / 项目特写",noGuide:"(无使用指南)",copyRecipe:"复制 Recipe"},silentLabels:{watch:"as:create",draft:"草稿",cli:"CLI",pending:"待审核(24h)",recipe:"新建片段"},lifecycle:{pending:"待审核",active:"已发布",deprecated:"已废弃"},kind:{rule:"规则",pattern:"模式",fact:"事实"},app:{errorBoundary:{title:"页面出现异常",refreshBtn:"刷新页面"},sync:{success:"Recipes 已同步到 IDE Snippets",successTitle:"Snippet 同步成功",failed:"同步失败",failedHint:"请检查 IDE 配置并重试"},projectRefresh:{success:"Target 列表与文件树已更新",successTitle:"项目结构已刷新",failed:"刷新失败"},extract:{success:"提取结果已进入候选池,请在 Candidates 页审核",successTitle:"提取完成",markerSuccess:"精准锁定标记代码,已加入候选池",normalSuccess:"提取结果已加入候选池",noMarker:"未找到 ASD 标记,AI 将分析完整文件",extracting:"提取中",failed:"Extraction failed"},clipboard:{empty:"请先复制代码到剪贴板",emptyTitle:"剪贴板为空",analyzing:"已收到代码,AI 正在识别可复用模式...",analyzingTitle:"剪贴板分析中",resultMulti:"已识别 {count} 条 Recipe,请在候选池审核",resultTitle:"AI 识别完成",aiFailed:"AI 识别失败",permissionError:"浏览器可能未授权剪贴板访问",permissionTitle:"剪贴板读取失败"},load:{failed:"无法加载项目数据",failedTitle:"加载失败",failedHint:"请确认项目路径有效后重试"},scan:{events:{initializing:"正在启动扫描...",filesLoaded:"已加载 {count} 个源文件",readingFiles:"正在读取 {count} 个文件内容...",aiAnalyzing:"正在 AI 分析提取可复用模式...",enriching:"正在增强 {count} 条结果...",completing:"扫描完成,正在加载结果..."},streamInit:"正在建立流式连接...",completed:"扫描完成",targetSuccess:"发现 {count} 条可复用代码模式,请在右侧审核",targetSuccessTitle:"Target 扫描完成",aiNotConfigured:"AI 未配置",noResults:"AI 扫描未返回结果",noSnippets:"该 Target 中未找到可复用的代码片段",scanComplete:"扫描完成",scanFailedHint:"请确认 Target 包含有效的源代码文件",scanFailed:"扫描失败",timeout:"扫描超时,请尝试减少 Target 文件数量",timeoutTitle:"扫描超时",scanError:"扫描出错"},coldStart:{collecting:"正在收集项目结构...",skeletonCreated:"骨架已创建,正在后台填充...",skeletonDetail:"冷启动骨架已创建: {targets} 个 Target, {files} 个文件, {deps} 条依赖...正在后台逐维度填充...",guardSuffix:"Guard: {count} 项违规",timeout:"冷启动超时,请检查项目文件数量"},fullScan:{collecting:"正在收集所有 Target 文件...",phase5:"正在收集源文件...",phase15:"正在 AI 分析代码模式...",phase25:"AI 提取中(大项目可能需要数分钟)...",phase35:"AI 提取中...",phase45:"AI 深度分析中...",phase55:"持续处理中...",phase65:"正在运行 Guard 审计...",phase75:"正在汇总结果...",phase85:"即将完成...",partialComplete:"扫描部分完成(超时)",completed:"全项目扫描完成",resultDetail:"全项目扫描完成: {count} 条候选",guardSuffix:"Guard: {count} 处违反",timeoutSuffix:"(部分结果,AI 超时)",noContent:"全项目扫描完成,未发现可提取内容",timeout:"扫描超时,请尝试减少项目文件数量或分 Target 扫描",timeoutTitle:"扫描超时",scanError:"扫描出错"},recipe:{triggerRequired:"请输入 Trigger",savedAsRecipe:"已保存并发布为 Recipe",savedToKb:"已保存到 KB",saveFailed:"保存失败",saveRecipeFailed:"保存 Recipe 失败",deleteFailed:"删除失败"},candidate:{clearConfirm:"确定移除「{name}」下的全部候选?",clearDone:"已移除 {name} 下的全部候选",pushSuccess:"已加入 Candidate 待审核队列",pushFailed:"创建 Candidate 失败"}},globalChat:{refineFields:{summary:"摘要",code:"代码/标准用法",markdown:"Markdown 文档",rationale:"设计原理",tags:"标签",confidence:"置信度",aiInsights:"AI 洞察",agentNotes:"Agent 笔记",relations:"关联关系"},diff:{noChanges:"未检测到变更",excludedRestore:"已排除 · 恢复",exclude:"排除",before:"Before",after:"After",empty:"(空)"},system:{refinePrefix:`🎯 润色模式 — **{title}**
2
2
 
3
3
  当前摘要: {description}
4
4
 
@@ -14,15 +14,15 @@ Current summary: {description}
14
14
 
15
15
  ## Use Cases
16
16
 
17
- ## Steps`},guardRuleMessages:{"no-main-thread-sync":"Do not use dispatch_sync(main) on the main thread — risk of deadlock","main-thread-sync-swift":"Do not use DispatchQueue.main.sync on the main thread — risk of deadlock","objc-dealloc-async":"Do not call dispatch_async / dispatch_after / postNotification inside dealloc","objc-block-retain-cycle":"Using self directly in a block may cause a retain cycle — use weakSelf","objc-assign-object":"assign on object types creates dangling pointers — use weak or strong","swift-force-cast":"Force cast as! crashes on failure — use as? or guard let instead","swift-force-try":"try! crashes on error — use do-catch or try? instead","objc-timer-retain-cycle":"NSTimer strongly retains self as target — invalidate before dealloc or use block API","objc-possible-main-thread-blocking":"sleep/usleep may block the main thread","js-no-eval":"eval() poses security and performance risks — avoid using it","js-no-var":"Use let/const instead of var to avoid hoisting issues","js-no-console-log":"Remove console.log from production code — use a dedicated logger","js-no-debugger":"Production code should not contain debugger statements","js-no-alert":"Do not use alert() in production code — poor user experience","ts-no-non-null-assertion":"Non-null assertion ! may mask null/undefined errors","py-no-bare-except":"Bare except: catches all exceptions (incl. SystemExit) — specify the exception type","py-no-exec":"exec() poses security risks — avoid using it","py-no-mutable-default":"Mutable default arguments (list/dict/set) cause shared-state bugs","py-no-star-import":"from module import * pollutes the namespace — use explicit imports","py-no-assert-in-prod":"assert is removed under -O flag — do not use for production logic validation","java-no-system-exit":"System.exit() terminates the JVM directly — throw an exception or return a status code","java-no-raw-type":"Use generic collections instead of raw types (e.g., List<String> instead of List)","java-no-empty-catch":"Empty catch blocks silently swallow exceptions — at least log the error","java-no-thread-stop":"Thread.stop() is deprecated and unsafe — use interrupt() for cooperative termination","kotlin-no-force-unwrap":"!! throws NPE when value is null — use ?. or ?: for safe access","go-no-panic":"panic should only be used for unrecoverable errors — library code should return error","go-no-err-ignored":"Errors should not be ignored with _ — handle or explicitly annotate them","go-no-init-abuse":"init() side effects are hard to trace — avoid complex logic in init","go-no-global-var":"Global mutable variables cause concurrency issues — consider dependency injection","dart-no-print":"Use a logger instead of print() in production code — enables log levels and toggling","dart-avoid-dynamic":"Avoid the dynamic type — use concrete types or generics for type safety","dart-no-set-state-after-dispose":"Check mounted before calling setState — avoid calling after dispose","dart-avoid-bang-operator":"Avoid the ! null assertion operator — prefer ?? default value or ?. safe call","dart-prefer-const-constructor":"Declare constructor as const when all fields are final to optimize Widget rebuilds","dart-no-relative-import":"Use package: absolute imports inside lib/ — avoid relative path imports","dart-dispose-controller":"TextEditingController/AnimationController etc. must be disposed in dispose()","dart-no-build-context-across-async":"BuildContext should not be used across async gaps — may reference an unmounted Widget"},guardRuleFixSuggestions:{"objc-block-retain-cycle":"Declare __weak typeof(self) weakSelf = self; then use weakSelf inside the block","swift-force-cast":"Use as? with guard let / if let for safe casting","kotlin-no-force-unwrap":"Use ?. for safe calls or ?: for default values","dart-no-set-state-after-dispose":"Use if (mounted) setState(...) as a guard","dart-avoid-bang-operator":"Use ?. for safe calls or ?? for default values","dart-prefer-const-constructor":"Remove the new keyword and add const before Widget constructor calls","dart-dispose-controller":"Call controller.dispose() in State.dispose()","dart-no-build-context-across-async":"Cache needed data before await or check mounted after await"}},Zs={zh:zs,en:Bl},js="asd-dashboard-lang";function Gl(){try{const t=localStorage.getItem(js);if(t==="en"||t==="zh")return t}catch{}return"zh"}function ea(t,s){const a=s.split(".");let l=t;for(const d of a){if(l==null||typeof l!="object")return;l=l[d]}return typeof l=="string"?l:void 0}function Hl(t,s){return s?t.replace(/\{(\w+)\}/g,(a,l)=>{const d=s[l];return d!=null?String(d):`{${l}}`}):t}const Ba=o.createContext(null);function ql({children:t}){const[s,a]=o.useState(Gl);o.useEffect(()=>{const u=localStorage.getItem(js);u==="en"||u==="zh"?fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:u})}).catch(()=>{}):fetch("/api/v1/ai/lang").then(p=>p.json()).then(p=>{var g;const n=(g=p==null?void 0:p.data)==null?void 0:g.lang;if(n==="en"||n==="zh"){a(n);try{localStorage.setItem(js,n)}catch{}}}).catch(()=>{})},[]);const l=o.useCallback(u=>{a(u);try{localStorage.setItem(js,u)}catch{}fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:u})}).catch(()=>{})},[]),d=o.useCallback((u,p)=>{const n=ea(Zs[s],u)??ea(Zs.zh,u)??u;return Hl(n,p)},[s]),i=o.useMemo(()=>({lang:s,setLang:l,t:d}),[s,l,d]);return e.jsx(Ba.Provider,{value:i,children:t})}function _e(){const t=o.useContext(Ba);if(!t)throw new Error("useI18n must be used within <I18nProvider>");return t}const Ga="asd-dashboard-theme";function Ol(){return typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches}function Kl(){try{const t=localStorage.getItem(Ga);if(t==="light"||t==="dark"||t==="system")return t}catch{}return"system"}const Ha=o.createContext(null);function Ul({children:t}){const[s,a]=o.useState(Kl),[l,d]=o.useState(Ol);o.useEffect(()=>{const g=window.matchMedia("(prefers-color-scheme: dark)"),f=h=>d(h.matches);return g.addEventListener("change",f),()=>g.removeEventListener("change",f)},[]);const i=s==="dark"?!0:s==="light"?!1:l;o.useEffect(()=>{const g=document.documentElement;i?g.classList.add("dark"):g.classList.remove("dark")},[i]);const u=o.useCallback(g=>{a(g);try{localStorage.setItem(Ga,g)}catch{}},[]),p=o.useCallback(()=>{u(i?"light":"dark")},[i,u]),n=o.useMemo(()=>({isDark:i,mode:s,toggle:p,setTheme:u}),[i,s,p,u]);return e.jsx(Ha.Provider,{value:n,children:t})}function St(){const t=o.useContext(Ha);if(!t)throw new Error("useTheme must be used within <ThemeProvider>");return t}const Wl="AutoSnippet";function Vl(t){if(typeof window>"u"||!("Notification"in window))return;const s=()=>{try{new Notification(Wl,{body:t,tag:"autosnippet"})}catch{}};if(Notification.permission==="granted"){s();return}Notification.permission!=="denied"&&Notification.requestPermission().then(a=>{a==="granted"&&s()})}const Jl={success:5e3,error:8e3,info:5e3},ta={success:{bg:"linear-gradient(135deg,#ecfdf5 0%,#f0fdf4 100%)",border:"#10b981",bar:"#10b981",darkBg:"linear-gradient(135deg,#0c1a14 0%,#0f1f18 100%)",darkBorder:"#059669"},error:{bg:"linear-gradient(135deg,#fef2f2 0%,#fff1f2 100%)",border:"#ef4444",bar:"#ef4444",darkBg:"linear-gradient(135deg,#1c0f0f 0%,#1f1012 100%)",darkBorder:"#dc2626"},info:{bg:"linear-gradient(135deg,#eff6ff 0%,#f0f9ff 100%)",border:"#3b82f6",bar:"#3b82f6",darkBg:"linear-gradient(135deg,#0f1524 0%,#101828 100%)",darkBorder:"#2563eb"}},Yl=()=>e.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",className:"w-5 h-5 text-emerald-500 shrink-0",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})}),Ql=()=>e.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",className:"w-5 h-5 text-red-400 shrink-0",children:e.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})}),qa=()=>e.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",className:"w-5 h-5 text-blue-400 shrink-0",children:e.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})}),Xl={success:Yl,error:Ql,info:qa},Zl=({visible:t,toastId:s,body:a,type:l,title:d,duration:i})=>{const u=ta[l]||ta.info,p=Xl[l]||qa,n=typeof document<"u"&&document.documentElement.classList.contains("dark");return e.jsxs("div",{onClick:()=>wa.dismiss(s),style:{background:n?u.darkBg:u.bg,borderLeft:`4px solid ${n?u.darkBorder:u.border}`,borderRadius:10,boxShadow:n?"0 8px 30px rgba(0,0,0,.4),0 2px 8px rgba(0,0,0,.25)":"0 8px 30px rgba(0,0,0,.12),0 2px 8px rgba(0,0,0,.06)",padding:"12px 16px 10px 14px",display:"flex",alignItems:"flex-start",gap:10,minWidth:280,maxWidth:420,position:"relative",overflow:"hidden",cursor:"pointer",opacity:t?1:0,transform:`translateY(${t?0:-8}px)`,transition:"opacity .25s ease, transform .25s ease"},children:[e.jsx("div",{style:{marginTop:1},children:e.jsx(p,{})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[d&&e.jsx("div",{style:{fontWeight:600,fontSize:13,lineHeight:1.3,color:n?"#e2e8f0":"#1e293b",marginBottom:2},children:d}),e.jsx("div",{style:{fontSize:12.5,lineHeight:1.45,color:n?"#94a3b8":"#475569",wordBreak:"break-word"},children:a})]}),e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:3,width:"100%",background:u.bar,opacity:.45,animation:`toast-progress ${i}ms linear forwards`}})]})};function re(t,s){const a=(s==null?void 0:s.type)??"success",l=s==null?void 0:s.title,d=(s==null?void 0:s.duration)??Jl[a]??5e3;typeof document<"u"&&document.visibilityState==="visible"?er(t,a,l,d):Vl(l?`${l}: ${t}`:t)}function er(t,s,a,l){wa.custom(d=>e.jsx(Zl,{visible:d.visible,toastId:d.id,body:t,type:s,title:a,duration:l}),{duration:l})}if(typeof document<"u"){const t="asd-toast-progress-style";if(!document.getElementById(t)){const s=document.createElement("style");s.id=t,s.textContent=`
17
+ ## Steps`},guardRuleMessages:{"no-main-thread-sync":"Do not use dispatch_sync(main) on the main thread — risk of deadlock","main-thread-sync-swift":"Do not use DispatchQueue.main.sync on the main thread — risk of deadlock","objc-dealloc-async":"Do not call dispatch_async / dispatch_after / postNotification inside dealloc","objc-block-retain-cycle":"Using self directly in a block may cause a retain cycle — use weakSelf","objc-assign-object":"assign on object types creates dangling pointers — use weak or strong","swift-force-cast":"Force cast as! crashes on failure — use as? or guard let instead","swift-force-try":"try! crashes on error — use do-catch or try? instead","objc-timer-retain-cycle":"NSTimer strongly retains self as target — invalidate before dealloc or use block API","objc-possible-main-thread-blocking":"sleep/usleep may block the main thread","js-no-eval":"eval() poses security and performance risks — avoid using it","js-no-var":"Use let/const instead of var to avoid hoisting issues","js-no-console-log":"Remove console.log from production code — use a dedicated logger","js-no-debugger":"Production code should not contain debugger statements","js-no-alert":"Do not use alert() in production code — poor user experience","ts-no-non-null-assertion":"Non-null assertion ! may mask null/undefined errors","py-no-bare-except":"Bare except: catches all exceptions (incl. SystemExit) — specify the exception type","py-no-exec":"exec() poses security risks — avoid using it","py-no-mutable-default":"Mutable default arguments (list/dict/set) cause shared-state bugs","py-no-star-import":"from module import * pollutes the namespace — use explicit imports","py-no-assert-in-prod":"assert is removed under -O flag — do not use for production logic validation","java-no-system-exit":"System.exit() terminates the JVM directly — throw an exception or return a status code","java-no-raw-type":"Use generic collections instead of raw types (e.g., List<String> instead of List)","java-no-empty-catch":"Empty catch blocks silently swallow exceptions — at least log the error","java-no-thread-stop":"Thread.stop() is deprecated and unsafe — use interrupt() for cooperative termination","kotlin-no-force-unwrap":"!! throws NPE when value is null — use ?. or ?: for safe access","go-no-panic":"panic should only be used for unrecoverable errors — library code should return error","go-no-err-ignored":"Errors should not be ignored with _ — handle or explicitly annotate them","go-no-init-abuse":"init() side effects are hard to trace — avoid complex logic in init","go-no-global-var":"Global mutable variables cause concurrency issues — consider dependency injection","dart-no-print":"Use a logger instead of print() in production code — enables log levels and toggling","dart-avoid-dynamic":"Avoid the dynamic type — use concrete types or generics for type safety","dart-no-set-state-after-dispose":"Check mounted before calling setState — avoid calling after dispose","dart-avoid-bang-operator":"Avoid the ! null assertion operator — prefer ?? default value or ?. safe call","dart-prefer-const-constructor":"Declare constructor as const when all fields are final to optimize Widget rebuilds","dart-no-relative-import":"Use package: absolute imports inside lib/ — avoid relative path imports","dart-dispose-controller":"TextEditingController/AnimationController etc. must be disposed in dispose()","dart-no-build-context-across-async":"BuildContext should not be used across async gaps — may reference an unmounted Widget"},guardRuleFixSuggestions:{"objc-block-retain-cycle":"Declare __weak typeof(self) weakSelf = self; then use weakSelf inside the block","swift-force-cast":"Use as? with guard let / if let for safe casting","kotlin-no-force-unwrap":"Use ?. for safe calls or ?: for default values","dart-no-set-state-after-dispose":"Use if (mounted) setState(...) as a guard","dart-avoid-bang-operator":"Use ?. for safe calls or ?? for default values","dart-prefer-const-constructor":"Remove the new keyword and add const before Widget constructor calls","dart-dispose-controller":"Call controller.dispose() in State.dispose()","dart-no-build-context-across-async":"Cache needed data before await or check mounted after await"}},Zs={zh:zs,en:Bl},js="asd-dashboard-lang";function Gl(){try{const t=localStorage.getItem(js);if(t==="en"||t==="zh")return t}catch{}return"zh"}function ea(t,s){const a=s.split(".");let l=t;for(const d of a){if(l==null||typeof l!="object")return;l=l[d]}return typeof l=="string"?l:void 0}function Hl(t,s){return s?t.replace(/\{(\w+)\}/g,(a,l)=>{const d=s[l];return d!=null?String(d):`{${l}}`}):t}const Ba=o.createContext(null);function ql({children:t}){const[s,a]=o.useState(Gl);o.useEffect(()=>{const u=localStorage.getItem(js);u==="en"||u==="zh"?fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:u})}).catch(()=>{}):fetch("/api/v1/ai/lang").then(p=>p.json()).then(p=>{var g;const n=(g=p==null?void 0:p.data)==null?void 0:g.lang;if(n==="en"||n==="zh"){a(n);try{localStorage.setItem(js,n)}catch{}}}).catch(()=>{})},[]);const l=o.useCallback(u=>{a(u);try{localStorage.setItem(js,u)}catch{}fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:u})}).catch(()=>{})},[]),d=o.useCallback((u,p)=>{const n=ea(Zs[s],u)??ea(Zs.zh,u)??u;return Hl(n,p)},[s]),c=o.useMemo(()=>({lang:s,setLang:l,t:d}),[s,l,d]);return e.jsx(Ba.Provider,{value:c,children:t})}function _e(){const t=o.useContext(Ba);if(!t)throw new Error("useI18n must be used within <I18nProvider>");return t}const Ga="asd-dashboard-theme";function Ol(){return typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches}function Kl(){try{const t=localStorage.getItem(Ga);if(t==="light"||t==="dark"||t==="system")return t}catch{}return"system"}const Ha=o.createContext(null);function Ul({children:t}){const[s,a]=o.useState(Kl),[l,d]=o.useState(Ol);o.useEffect(()=>{const g=window.matchMedia("(prefers-color-scheme: dark)"),f=h=>d(h.matches);return g.addEventListener("change",f),()=>g.removeEventListener("change",f)},[]);const c=s==="dark"?!0:s==="light"?!1:l;o.useEffect(()=>{const g=document.documentElement;c?g.classList.add("dark"):g.classList.remove("dark")},[c]);const u=o.useCallback(g=>{a(g);try{localStorage.setItem(Ga,g)}catch{}},[]),p=o.useCallback(()=>{u(c?"light":"dark")},[c,u]),n=o.useMemo(()=>({isDark:c,mode:s,toggle:p,setTheme:u}),[c,s,p,u]);return e.jsx(Ha.Provider,{value:n,children:t})}function St(){const t=o.useContext(Ha);if(!t)throw new Error("useTheme must be used within <ThemeProvider>");return t}const Wl="AutoSnippet";function Vl(t){if(typeof window>"u"||!("Notification"in window))return;const s=()=>{try{new Notification(Wl,{body:t,tag:"autosnippet"})}catch{}};if(Notification.permission==="granted"){s();return}Notification.permission!=="denied"&&Notification.requestPermission().then(a=>{a==="granted"&&s()})}const Jl={success:5e3,error:8e3,info:5e3},ta={success:{bg:"linear-gradient(135deg,#ecfdf5 0%,#f0fdf4 100%)",border:"#10b981",bar:"#10b981",darkBg:"linear-gradient(135deg,#0c1a14 0%,#0f1f18 100%)",darkBorder:"#059669"},error:{bg:"linear-gradient(135deg,#fef2f2 0%,#fff1f2 100%)",border:"#ef4444",bar:"#ef4444",darkBg:"linear-gradient(135deg,#1c0f0f 0%,#1f1012 100%)",darkBorder:"#dc2626"},info:{bg:"linear-gradient(135deg,#eff6ff 0%,#f0f9ff 100%)",border:"#3b82f6",bar:"#3b82f6",darkBg:"linear-gradient(135deg,#0f1524 0%,#101828 100%)",darkBorder:"#2563eb"}},Yl=()=>e.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",className:"w-5 h-5 text-emerald-500 shrink-0",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})}),Ql=()=>e.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",className:"w-5 h-5 text-red-400 shrink-0",children:e.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})}),qa=()=>e.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",className:"w-5 h-5 text-blue-400 shrink-0",children:e.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})}),Xl={success:Yl,error:Ql,info:qa},Zl=({visible:t,toastId:s,body:a,type:l,title:d,duration:c})=>{const u=ta[l]||ta.info,p=Xl[l]||qa,n=typeof document<"u"&&document.documentElement.classList.contains("dark");return e.jsxs("div",{onClick:()=>wa.dismiss(s),style:{background:n?u.darkBg:u.bg,borderLeft:`4px solid ${n?u.darkBorder:u.border}`,borderRadius:10,boxShadow:n?"0 8px 30px rgba(0,0,0,.4),0 2px 8px rgba(0,0,0,.25)":"0 8px 30px rgba(0,0,0,.12),0 2px 8px rgba(0,0,0,.06)",padding:"12px 16px 10px 14px",display:"flex",alignItems:"flex-start",gap:10,minWidth:280,maxWidth:420,position:"relative",overflow:"hidden",cursor:"pointer",opacity:t?1:0,transform:`translateY(${t?0:-8}px)`,transition:"opacity .25s ease, transform .25s ease"},children:[e.jsx("div",{style:{marginTop:1},children:e.jsx(p,{})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[d&&e.jsx("div",{style:{fontWeight:600,fontSize:13,lineHeight:1.3,color:n?"#e2e8f0":"#1e293b",marginBottom:2},children:d}),e.jsx("div",{style:{fontSize:12.5,lineHeight:1.45,color:n?"#94a3b8":"#475569",wordBreak:"break-word"},children:a})]}),e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:3,width:"100%",background:u.bar,opacity:.45,animation:`toast-progress ${c}ms linear forwards`}})]})};function re(t,s){const a=(s==null?void 0:s.type)??"success",l=s==null?void 0:s.title,d=(s==null?void 0:s.duration)??Jl[a]??5e3;typeof document<"u"&&document.visibilityState==="visible"?er(t,a,l,d):Vl(l?`${l}: ${t}`:t)}function er(t,s,a,l){wa.custom(d=>e.jsx(Zl,{visible:d.visible,toastId:d.id,body:t,type:s,title:a,duration:l}),{duration:l})}if(typeof document<"u"){const t="asd-toast-progress-style";if(!document.getElementById(t)){const s=document.createElement("style");s.id=t,s.textContent=`
18
18
  @keyframes toast-progress {
19
19
  from { width: 100%; }
20
20
  to { width: 0%; }
21
- }`,document.head.appendChild(s)}}const ct={All:{icon:Pt,color:"text-slate-600",bg:"bg-slate-100",border:"border-slate-200"},View:{icon:pl,color:"text-pink-600",bg:"bg-pink-50",border:"border-pink-100"},Service:{icon:ns,color:"text-indigo-600",bg:"bg-indigo-50",border:"border-indigo-100"},Tool:{icon:et,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},Model:{icon:Da,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},Network:{icon:ul,color:"text-blue-600",bg:"bg-blue-50",border:"border-blue-100"},Storage:{icon:dl,color:"text-purple-600",bg:"bg-purple-50",border:"border-purple-100"},UI:{icon:ws,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},Utility:{icon:lt,color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-100"},"code-standard":{icon:tt,color:"text-violet-600",bg:"bg-violet-50",border:"border-violet-100"},"code-pattern":{icon:_s,color:"text-fuchsia-600",bg:"bg-fuchsia-50",border:"border-fuchsia-100"},architecture:{icon:cl,color:"text-sky-600",bg:"bg-sky-50",border:"border-sky-100"},"best-practice":{icon:ut,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},"event-and-data-flow":{icon:il,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},"project-profile":{icon:as,color:"text-teal-600",bg:"bg-teal-50",border:"border-teal-100"},"agent-guidelines":{icon:rs,color:"text-rose-600",bg:"bg-rose-50",border:"border-rose-100"},"objc-deep-scan":{icon:ol,color:"text-indigo-600",bg:"bg-indigo-50",border:"border-indigo-100"},"category-scan":{icon:Aa,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},bootstrap:{icon:et,color:"text-violet-600",bg:"bg-violet-50",border:"border-violet-100"}},tr=["All","View","Service","Tool","Model","Network","Storage","UI","Utility"],sr=["recipes","ai","spm","candidates","knowledge","depgraph","knowledgegraph","guard","skills","wiki","help"],Bt=[{id:"swift",label:"Swift"},{id:"objectivec",label:"ObjC",aliases:["objc","objective-c","obj-c"]},{id:"go",label:"Go"},{id:"javascript",label:"JavaScript",aliases:["js"]},{id:"typescript",label:"TypeScript",aliases:["ts"]},{id:"python",label:"Python",aliases:["py"]},{id:"java",label:"Java"},{id:"kotlin",label:"Kotlin",aliases:["kt"]},{id:"rust",label:"Rust",aliases:["rs"]},{id:"dart",label:"Dart"},{id:"c",label:"C"},{id:"cpp",label:"C++",aliases:["c++"]},{id:"csharp",label:"C#",aliases:["cs"]},{id:"ruby",label:"Ruby",aliases:["rb"]}];function Os(t){var a;if(!t)return"";const s=t.toLowerCase().trim();for(const l of Bt)if(l.id===s||(a=l.aliases)!=null&&a.includes(s))return l.id;return s}function sa(t){switch(Os(t)){case"objectivec":return"#import <Module/Header.h>";case"swift":return"import ModuleName";case"go":return'import "package/path"';case"python":return"import module_name";case"java":case"kotlin":return"import com.example.ClassName";case"javascript":case"typescript":return"import { name } from 'module'";case"rust":return"use crate::module::name;";case"dart":return"import 'package:name/name.dart';";case"csharp":return"using Namespace.Name;";case"ruby":return"require 'module_name'";case"c":case"cpp":return"#include <header.h>";default:return"import module"}}const ar="https://github.com/GxFn/AutoSnippet/issues/new?title=Guard%20误报%2F建议%3A%20&body=请描述误报的规则ID、代码片段或改进建议。",us=t=>["Example","Demo","Sample","Tests","Spec","Mock","Runner"].some(a=>t.endsWith(a)||t.includes(a)),lr=t=>t.startsWith("_"),rr=t=>t==="_pending",nr="您暂无写入权限,无法保存。如需此权限请联系管理员;请勿擅自修改核心代码或安装包,以免影响团队协作与数据安全。";function vs(t){var d,i;const s=t==null?void 0:t.response;if((s==null?void 0:s.status)!==403)return null;const a=(d=s.data)==null?void 0:d.code,l=(i=s.data)==null?void 0:i.error;return a==="RECIPE_WRITE_FORBIDDEN"||typeof l=="string"&&l.includes("没权限")?nr:null}const or="保存过于频繁,请稍后再试。";function aa(t){var a;const s=t==null?void 0:t.response;return s!=null&&s.data?s.status===403?vs(t)??null:s.status===429&&((a=s.data)==null?void 0:a.code)==="RECIPE_SAVE_RATE_LIMIT"?or:null:null}const oe=ss.create({baseURL:"/api/v1"});function la(t){const s=t.quality||{},a=t.stats||t.statistics||{},l=t.content||{},d=t.trigger||"@"+(t.title||"").replace(/[\s_-]+(.)?/g,(u,p)=>p?p.toUpperCase():""),i={authority:a.authority||s.overall||0,authorityScore:a.authority||s.overall||0,guardUsageCount:a.applications||0,humanUsageCount:a.adoptions||0,aiUsageCount:0,lastUsedAt:t.updatedAt||null};return{id:t.id,name:(t.title||t.name||t.id)+".md",content:l,category:t.category||"",language:t.language||"",description:t.description||"",status:t.lifecycle||t.status||"pending",kind:t.kind||void 0,knowledgeType:t.knowledgeType||void 0,relations:t.relations||null,constraints:t.constraints||null,tags:t.tags||[],stats:i,trigger:d,source:t.source||"",sourceFile:t.sourceFile||"",moduleName:t.moduleName||"",usageGuide:l.markdown||t.doClause||"",reasoning:t.reasoning||null,quality:t.quality||null,scope:t.scope||"",complexity:t.complexity||"",difficulty:t.difficulty||t.complexity||"",version:t.version||"",headers:t.headers||[],updatedAt:t.updatedAt||null}}function ir(t){let s="",a="general",l="",d="",i="",u="",p="",n="",g="",f=[],h=[],x="",c=0,j="1.0.0",w="",C="",E="",S="",G="",z="",P="",Z="",X="",H="",q=t;const R=t.match(/^---\n([\s\S]*?)\n---/);if(R){const M=R[1],_=ae=>{const ue=M.match(new RegExp(`^${ae}:\\s*(.+)$`,"m"));return ue?ue[1].trim():null};s=_("language")||s,a=_("category")||a,l=_("title")||l,d=_("trigger")||"",i=_("summary_cn")||_("summary")||_("description")||i,u=_("summary_en")||"",p=_("knowledge_type")||_("knowledgeType")||"",n=_("complexity")||"",g=_("scope")||"",x=_("difficulty")||"",j=_("version")||"1.0.0";const m=_("authority");m&&(c=parseInt(m)||0);const N=_("tags");if(N)try{f=JSON.parse(N)}catch{f=N.split(",").map(ae=>ae.trim()).filter(Boolean)}const y=_("headers");if(y)try{h=JSON.parse(y)}catch{h=[y]}z=_("kind")||"",P=_("doClause")||"",Z=_("dontClause")||"",X=_("whenClause")||"",H=_("topicHint")||"";const W=t.match(/```[\w]*\n([\s\S]*?)```/);W&&(q=W[1].trim());const O=t.replace(/^---\n[\s\S]*?\n---/,"").trim(),be=O.match(/## (?:AI Context \/ )?Usage Guide(?:\s*\(CN\))?\n\n([\s\S]*?)(?=\n## |$)/);be&&(w=be[1].trim());const we=O.match(/## (?:AI Context \/ )?Usage Guide\s*\(EN\)\n\n([\s\S]*?)(?=\n## |$)/);we&&(C=we[1].trim());const ye=O.match(/## Architecture Usage\n\n([\s\S]*?)(?=\n## |$)/);ye&&(E=ye[1].trim());const v=O.match(/## Best Practices\n\n([\s\S]*?)(?=\n## |$)/);v&&(S=v[1].trim());const ee=O.match(/## Standards\n\n([\s\S]*?)(?=\n## |$)/);ee&&(G=ee[1].trim())}return{title:l,language:s,category:a,trigger:d,summary:i,summaryEn:u,knowledgeType:p,complexity:n,scope:g,tags:f,headers:h,difficulty:x,authority:c,version:j,codePattern:q,usageGuide:w,usageGuideEn:C,rationaleText:E,bestPracticesText:S,standardsText:G,kind:z,doClause:P,dontClause:Z,whenClause:X,topicHint:H}}function cr(t,s,a){var d;const l=Array.isArray(t.category)?t.category[0]:t.category||s||"general";return{title:t.title||"Untitled",content:t.content||{pattern:((d=t.content)==null?void 0:d.pattern)||"",markdown:"",rationale:""},description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:l,kind:t.kind||"pattern",knowledgeType:t.knowledgeType||"code-pattern",complexity:t.complexity||"intermediate",source:a,lifecycle:"pending",tags:t.tags||[],sourceFile:t.sourceFile||"",moduleName:t.moduleName||"",headers:t.headers||[],headerPaths:t.headerPaths||[],reasoning:{whyStandard:t.description||t.title||"Extracted from project",sources:[a],confidence:.6},metadata:{targetName:s||"",title:t.title||"",trigger:t.trigger||"",description:t.description||"",category:l,headers:t.headers||[],headerPaths:t.headerPaths||[],moduleName:t.moduleName||"",isMarked:t.isMarked||!1}}}async function _t(t){var i,u,p;const s=t.replace(/\.md$/i,"");if(/^[a-f0-9-]{8,}$/i.test(s))return s;const a=await oe.get("/knowledge?limit=1000"),d=(((u=(i=a.data)==null?void 0:i.data)==null?void 0:u.data)||((p=a.data)==null?void 0:p.data)||[]).find(n=>{const g=n.title||n.name||"";return g===s||g+".md"===t});if(d!=null&&d.id)return d.id;throw new Error(`Knowledge entry not found: ${t}`)}async function dr(t,s){var u;const a=(u=t.body)==null?void 0:u.getReader();if(!a)throw new Error("ReadableStream not available");const l=new TextDecoder;let d="",i="";for(;;){const{done:p,value:n}=await a.read();if(p)break;const g=l.decode(n,{stream:!0});d+=g;const f=d.split(`
22
- `);d=f.pop()||"";for(const h of f){if(h.startsWith(":")||!h.startsWith("data: "))continue;const x=h.slice(6).trim();if(!(!x||x==="[DONE]"))try{const c=JSON.parse(x);if(s(c),c.type==="text:delta"&&c.delta)i+=c.delta;else if(c.type==="stream:done"&&c.text)i=c.text;else if(c.type==="stream:error")throw new Error(c.message||"Stream error")}catch(c){if(c instanceof SyntaxError)continue;throw c}}}return i}const se={async fetchData(){var h,x,c,j,w,C,E;const[t,s,a]=await Promise.all([oe.get("/knowledge?limit=1000").catch(()=>({data:{success:!0,data:{data:[]}}})),oe.get("/ai/config").catch(()=>({data:{success:!0,data:{provider:"",model:""}}})),oe.get("/modules/project-info").catch(()=>({data:{success:!0,data:{projectRoot:""}}}))]),l=((x=(h=t.data)==null?void 0:h.data)==null?void 0:x.data)||((j=(c=t.data)==null?void 0:c.data)==null?void 0:j.items)||[],i=l.filter(S=>S.lifecycle==="active").map(la),u=l.filter(S=>S.lifecycle==="pending"),p={};for(const S of u){const G=S.category||S.language||"_pending";p[G]||(p[G]={targetName:G,scanTime:S.createdAt,items:[]}),p[G].items.push(S)}const n=((w=s.data)==null?void 0:w.data)||{provider:"",model:""},g={};for(const S of l)S.id&&S.title&&(g[S.id]=S.title);const f=((E=(C=a.data)==null?void 0:C.data)==null?void 0:E.projectRoot)||"";return{rootSpec:{list:[]},recipes:i,candidates:p,projectRoot:f,watcherStatus:"active",aiConfig:{provider:n.provider||"",model:n.model||""},idTitleMap:g}},async fetchTargets(){var a;return(((a=(await oe.get("/modules/targets")).data)==null?void 0:a.data)||{}).targets||[]},async getTargetFiles(t,s){var d,i;const l=((d=(await oe.post("/modules/target-files",{target:t},{signal:s})).data)==null?void 0:d.data)||{};return{files:l.files||[],count:l.total||((i=l.files)==null?void 0:i.length)||0}},async scanTarget(t,s){var i;const l=((i=(await oe.post("/modules/scan",{target:t},{signal:s,timeout:6e5})).data)==null?void 0:i.data)||{};return{recipes:l.recipes||l.result||[],scannedFiles:l.scannedFiles||[],message:l.message||"",noAi:!!l.noAi}},async scanTargetStream(t,s,a){let l;const d=await fetch("/api/v1/modules/scan/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t}),signal:a});if(!d.ok)throw new Error(`Scan stream start failed: ${d.status}`);if(l=(await d.json()).sessionId,!l)throw new Error("No sessionId returned");return new Promise((u,p)=>{const n=`/api/v1/modules/scan/events/${l}`,g=new EventSource(n);let f=!1,h={recipes:[],scannedFiles:[],message:"",noAi:!1};function x(){g.close()}if(g.onmessage=c=>{try{const j=JSON.parse(c.data);s(j),j.type==="scan:result"&&(h={recipes:j.recipes||[],scannedFiles:j.scannedFiles||[],message:j.message||"",noAi:!!j.noAi}),j.type==="stream:done"&&(x(),f=!0,u(h)),j.type==="stream:error"&&(x(),f=!0,p(new Error(j.message||"Scan stream error")))}catch{}},g.onerror=()=>{f||(x(),f=!0,h.recipes.length>0?u(h):p(new Error("EventSource connection failed")))},a){const c=()=>{f||(x(),f=!0,p(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){c();return}a.addEventListener("abort",c,{once:!0})}})},async scanProject(t){var l;const a=((l=(await oe.post("/modules/scan-project",{},{signal:t,timeout:6e5})).data)==null?void 0:l.data)||{};return{targets:a.targets||[],recipes:a.recipes||[],guardAudit:a.guardAudit||null,scannedFiles:a.scannedFiles||[],partial:a.partial||!1}},async browseDirectories(t="",s=3){var d,i;const a=new URLSearchParams;return t&&a.set("path",t),s&&a.set("depth",String(s)),((i=(d=(await oe.get(`/modules/browse-dirs?${a.toString()}`)).data)==null?void 0:d.data)==null?void 0:i.directories)||[]},async scanFolderStream(t,s,a){const l=await fetch("/api/v1/modules/scan-folder/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t}),signal:a});if(!l.ok)throw new Error(`Scan folder start failed: ${l.status}`);const i=(await l.json()).sessionId;if(!i)throw new Error("No sessionId returned");return new Promise((u,p)=>{const n=`/api/v1/modules/scan/events/${i}`,g=new EventSource(n);let f=!1,h={recipes:[],scannedFiles:[],message:"",noAi:!1};function x(){g.close()}if(g.onmessage=c=>{try{const j=JSON.parse(c.data);s(j),j.type==="scan:result"&&(h={recipes:j.recipes||[],scannedFiles:j.scannedFiles||[],message:j.message||"",noAi:!!j.noAi}),j.type==="stream:done"&&(x(),f=!0,u(h)),j.type==="stream:error"&&(x(),f=!0,p(new Error(j.message||"Scan folder stream error")))}catch{}},g.onerror=()=>{f||(x(),f=!0,h.recipes.length>0?u(h):p(new Error("EventSource connection failed")))},a){const c=()=>{f||(x(),f=!0,p(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){c();return}a.addEventListener("abort",c,{once:!0})}})},async bootstrap(t){var l;const a=((l=(await oe.post("/modules/bootstrap",{},{signal:t,timeout:3e5})).data)==null?void 0:l.data)||{};return{report:a.report||{},targets:a.targets||[],filesByTarget:a.filesByTarget||{},dependencyGraph:a.dependencyGraph||null,languageStats:a.languageStats||{},primaryLanguage:a.primaryLanguage||"",guardSummary:a.guardSummary||null,guardViolationFiles:a.guardViolationFiles||[],bootstrapCandidates:a.bootstrapCandidates||{created:0,failed:0},bootstrapSession:a.bootstrapSession||null,asyncFill:a.asyncFill||!1,message:a.message||""}},async getBootstrapStatus(){var s;return((s=(await oe.get("/modules/bootstrap/status")).data)==null?void 0:s.data)||{status:"idle"}},async getDepGraph(t){var a;return((a=(await oe.get(`/modules/dep-graph?level=${t}`)).data)==null?void 0:a.data)||{}},async getProjectInfo(){var t;try{return((t=(await oe.get("/modules/project-info")).data)==null?void 0:t.data)||{}}catch{return{primaryLanguage:"unknown",discoverers:[],hasSpm:!1}}},async syncSnippets(t="all"){return(await oe.post("/commands/install",{target:t})).data},async refreshProject(){try{await oe.post("/modules/update-map")}catch{await oe.post("/commands/spm-map")}},async extractFromPath(t){var l;const a=((l=(await oe.post("/extract/path",{relativePath:t})).data)==null?void 0:l.data)||{};return{result:a.result||[],isMarked:a.isMarked||!1}},async extractFromText(t,s){var d;const l=((d=(await oe.post("/extract/text",{text:t,...s?{relativePath:s}:{}})).data)==null?void 0:d.data)||{};return Array.isArray(l.result)&&l.result.length>0?l.result[0]:l},async saveRecipe(t,s){const a=ir(s),l=a.title||t.replace(/\.md$/,""),d={trigger:a.trigger,headers:a.headers,difficulty:a.difficulty,authority:a.authority,version:a.version},i={pattern:a.codePattern||"",rationale:a.rationaleText||"",steps:a.bestPracticesText?[a.bestPracticesText]:[],codeChanges:[],verification:null,markdown:a.usageGuide||""},u={};if(a.standardsText){const n=a.standardsText.split(`
23
- `).map(h=>h.trim()).filter(Boolean),g=n.filter(h=>h.startsWith("- ")).map(h=>h.slice(2).trim());g.length>0&&(u.preconditions=g);const f=n.filter(h=>!h.startsWith("- ")&&!h.startsWith("**"));f.length>0&&(u.boundaries=f)}const p={title:l,language:a.language,category:a.category,description:a.summary,knowledgeType:a.knowledgeType||"code-pattern",complexity:a.complexity||"intermediate",scope:a.scope||null,tags:a.tags||[],content:i,constraints:u,dimensions:d};a.kind&&(p.kind=a.kind),a.doClause&&(p.doClause=a.doClause),a.dontClause&&(p.dontClause=a.dontClause),a.whenClause&&(p.whenClause=a.whenClause),a.topicHint&&(p.topicHint=a.topicHint);try{const n=await _t(t);await oe.patch(`/knowledge/${n}`,p);return}catch{}await oe.post("/knowledge",p)},async deleteRecipe(t){const s=await _t(t);await oe.delete(`/knowledge/${s}`)},async getRecipeByName(t){var i;const s=await _t(t),l=(i=(await oe.get(`/knowledge/${s}`)).data)==null?void 0:i.data;if(!l)throw new Error("Recipe not found");const d=l.content||{};return{name:t,content:d.pattern||d.markdown||""}},async setRecipeAuthority(t,s){const a=await _t(t);await oe.patch(`/knowledge/${a}/quality`,{codeCompleteness:s,projectAdaptation:s,documentationClarity:s})},async updateRecipeRelations(t,s){const a=await _t(t);await oe.patch(`/knowledge/${a}`,{relations:s})},async getCandidate(t){var l;const a=(l=(await oe.get(`/knowledge/${t}`)).data)==null?void 0:l.data;if(!a)throw new Error("Knowledge entry not found");return a},async deleteCandidate(t){await oe.delete(`/knowledge/${t}`)},async promoteCandidateToRecipe(t,s){var d;const l=(d=(await oe.patch(`/knowledge/${t}/publish`)).data)==null?void 0:d.data;return{recipe:l,candidate:l}},async enrichCandidates(t){var a;return((a=(await oe.post("/candidates/enrich",{candidateIds:t})).data)==null?void 0:a.data)||{enriched:0,total:0,results:[]}},async bootstrapRefine(t,s,a){var d;return((d=(await oe.post("/candidates/bootstrap-refine",{candidateIds:t,userPrompt:s,dryRun:a},{timeout:3e5})).data)==null?void 0:d.data)||{refined:0,total:0,errors:[],results:[]}},async refinePreview(t,s){var l;return((l=(await oe.post("/candidates/refine-preview",{candidateId:t,userPrompt:s},{timeout:12e4})).data)==null?void 0:l.data)||{}},async refineApply(t,s,a){var d;return((d=(await oe.post("/candidates/refine-apply",{candidateId:t,userPrompt:s,preview:a},{timeout:12e4})).data)==null?void 0:d.data)||{}},async getKnowledgeGraph(t=500){var a;return((a=(await oe.get(`/search/graph/all?limit=${t}`)).data)==null?void 0:a.data)||{edges:[],nodeLabels:{},nodeTypes:{},nodeCategories:{}}},async getGraphStats(){var s;return((s=(await oe.get("/search/graph/stats")).data)==null?void 0:s.data)||{totalEdges:0,byRelation:{},nodeTypes:[]}},async discoverRelations(t=20){var a,l,d,i;const s=await oe.post("/recipes/discover-relations",{batchSize:t});if(!((a=s.data)!=null&&a.success))throw new Error(((d=(l=s.data)==null?void 0:l.error)==null?void 0:d.message)||"启动失败");return((i=s.data)==null?void 0:i.data)||{status:"unknown"}},async getDiscoverRelationsStatus(){var s;return((s=(await oe.get("/recipes/discover-relations/status")).data)==null?void 0:s.data)||{status:"idle"}},async deleteAllCandidatesInTarget(t){var d,i;const a=((i=(d=(await oe.get(`/knowledge?category=${encodeURIComponent(t)}&limit=1000`)).data)==null?void 0:d.data)==null?void 0:i.data)||[];let l=0;for(const u of a)try{await oe.delete(`/knowledge/${u.id}`),l++}catch{}return{deleted:l}},async promoteToCandidate(t,s){var d,i;const a=cr(t,s,"review-promote");return{ok:!0,candidateId:((i=(d=(await oe.post("/knowledge",a)).data)==null?void 0:d.data)==null?void 0:i.id)||""}},async getCandidateSimilarity(t,s){var l;return((l=(await oe.post("/search/similarity",{code:t,language:s}).catch(()=>({data:{data:{similar:[]}}}))).data)==null?void 0:l.data)||{similar:[]}},async getCandidateSimilarityEx(t){var a;return((a=(await oe.post("/search/similarity",t).catch(()=>({data:{data:{similar:[]}}}))).data)==null?void 0:a.data)||{similar:[]}},async getRecipeContentByName(t){var p;const s=await _t(t),l=(p=(await oe.get(`/knowledge/${s}`)).data)==null?void 0:p.data;if(!l)throw new Error("Recipe not found");const i=la(l).content,u=[i==null?void 0:i.pattern,i==null?void 0:i.markdown].filter(Boolean).join(`
21
+ }`,document.head.appendChild(s)}}const pt={All:{icon:Pt,color:"text-slate-600",bg:"bg-slate-100",border:"border-slate-200"},View:{icon:pl,color:"text-pink-600",bg:"bg-pink-50",border:"border-pink-100"},Service:{icon:ns,color:"text-indigo-600",bg:"bg-indigo-50",border:"border-indigo-100"},Tool:{icon:et,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},Model:{icon:Da,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},Network:{icon:ul,color:"text-blue-600",bg:"bg-blue-50",border:"border-blue-100"},Storage:{icon:dl,color:"text-purple-600",bg:"bg-purple-50",border:"border-purple-100"},UI:{icon:ws,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},Utility:{icon:lt,color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-100"},"code-standard":{icon:tt,color:"text-violet-600",bg:"bg-violet-50",border:"border-violet-100"},"code-pattern":{icon:_s,color:"text-fuchsia-600",bg:"bg-fuchsia-50",border:"border-fuchsia-100"},architecture:{icon:cl,color:"text-sky-600",bg:"bg-sky-50",border:"border-sky-100"},"best-practice":{icon:dt,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},"event-and-data-flow":{icon:il,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},"project-profile":{icon:as,color:"text-teal-600",bg:"bg-teal-50",border:"border-teal-100"},"agent-guidelines":{icon:rs,color:"text-rose-600",bg:"bg-rose-50",border:"border-rose-100"},"objc-deep-scan":{icon:ol,color:"text-indigo-600",bg:"bg-indigo-50",border:"border-indigo-100"},"category-scan":{icon:Aa,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},bootstrap:{icon:et,color:"text-violet-600",bg:"bg-violet-50",border:"border-violet-100"}},tr=["All","View","Service","Tool","Model","Network","Storage","UI","Utility"],sr=["recipes","ai","spm","candidates","knowledge","depgraph","knowledgegraph","guard","skills","wiki","help"],Bt=[{id:"swift",label:"Swift"},{id:"objectivec",label:"ObjC",aliases:["objc","objective-c","obj-c"]},{id:"go",label:"Go"},{id:"javascript",label:"JavaScript",aliases:["js"]},{id:"typescript",label:"TypeScript",aliases:["ts"]},{id:"python",label:"Python",aliases:["py"]},{id:"java",label:"Java"},{id:"kotlin",label:"Kotlin",aliases:["kt"]},{id:"rust",label:"Rust",aliases:["rs"]},{id:"dart",label:"Dart"},{id:"c",label:"C"},{id:"cpp",label:"C++",aliases:["c++"]},{id:"csharp",label:"C#",aliases:["cs"]},{id:"ruby",label:"Ruby",aliases:["rb"]}];function Os(t){var a;if(!t)return"";const s=t.toLowerCase().trim();for(const l of Bt)if(l.id===s||(a=l.aliases)!=null&&a.includes(s))return l.id;return s}function sa(t){switch(Os(t)){case"objectivec":return"#import <Module/Header.h>";case"swift":return"import ModuleName";case"go":return'import "package/path"';case"python":return"import module_name";case"java":case"kotlin":return"import com.example.ClassName";case"javascript":case"typescript":return"import { name } from 'module'";case"rust":return"use crate::module::name;";case"dart":return"import 'package:name/name.dart';";case"csharp":return"using Namespace.Name;";case"ruby":return"require 'module_name'";case"c":case"cpp":return"#include <header.h>";default:return"import module"}}const ar="https://github.com/GxFn/AutoSnippet/issues/new?title=Guard%20误报%2F建议%3A%20&body=请描述误报的规则ID、代码片段或改进建议。",us=t=>["Example","Demo","Sample","Tests","Spec","Mock","Runner"].some(a=>t.endsWith(a)||t.includes(a)),lr=t=>t.startsWith("_"),rr=t=>t==="_pending",nr="您暂无写入权限,无法保存。如需此权限请联系管理员;请勿擅自修改核心代码或安装包,以免影响团队协作与数据安全。";function vs(t){var d,c;const s=t==null?void 0:t.response;if((s==null?void 0:s.status)!==403)return null;const a=(d=s.data)==null?void 0:d.code,l=(c=s.data)==null?void 0:c.error;return a==="RECIPE_WRITE_FORBIDDEN"||typeof l=="string"&&l.includes("没权限")?nr:null}const or="保存过于频繁,请稍后再试。";function aa(t){var a;const s=t==null?void 0:t.response;return s!=null&&s.data?s.status===403?vs(t)??null:s.status===429&&((a=s.data)==null?void 0:a.code)==="RECIPE_SAVE_RATE_LIMIT"?or:null:null}const oe=ss.create({baseURL:"/api/v1"});function la(t){const s=t.quality||{},a=t.stats||t.statistics||{},l=t.content||{},d=t.trigger||"@"+(t.title||"").replace(/[\s_-]+(.)?/g,(u,p)=>p?p.toUpperCase():""),c={authority:a.authority||s.overall||0,authorityScore:a.authority||s.overall||0,guardUsageCount:a.applications||0,humanUsageCount:a.adoptions||0,aiUsageCount:0,lastUsedAt:t.updatedAt||null};return{id:t.id,name:(t.title||t.name||t.id)+".md",content:l,category:t.category||"",language:t.language||"",description:t.description||"",status:t.lifecycle||t.status||"pending",kind:t.kind||void 0,knowledgeType:t.knowledgeType||void 0,relations:t.relations||null,constraints:t.constraints||null,tags:t.tags||[],stats:c,trigger:d,source:t.source||"",sourceFile:t.sourceFile||"",moduleName:t.moduleName||"",usageGuide:l.markdown||t.doClause||"",reasoning:t.reasoning||null,quality:t.quality||null,scope:t.scope||"",complexity:t.complexity||"",difficulty:t.difficulty||t.complexity||"",version:t.version||"",headers:t.headers||[],updatedAt:t.updatedAt||null}}function ir(t){let s="",a="general",l="",d="",c="",u="",p="",n="",g="",f=[],h=[],x="",i=0,y="1.0.0",k="",w="",T="",A="",G="",_="",E="",Z="",X="",H="",q=t;const I=t.match(/^---\n([\s\S]*?)\n---/);if(I){const L=I[1],$=te=>{const de=L.match(new RegExp(`^${te}:\\s*(.+)$`,"m"));return de?de[1].trim():null};s=$("language")||s,a=$("category")||a,l=$("title")||l,d=$("trigger")||"",c=$("summary_cn")||$("summary")||$("description")||c,u=$("summary_en")||"",p=$("knowledge_type")||$("knowledgeType")||"",n=$("complexity")||"",g=$("scope")||"",x=$("difficulty")||"",y=$("version")||"1.0.0";const m=$("authority");m&&(i=parseInt(m)||0);const N=$("tags");if(N)try{f=JSON.parse(N)}catch{f=N.split(",").map(te=>te.trim()).filter(Boolean)}const j=$("headers");if(j)try{h=JSON.parse(j)}catch{h=[j]}_=$("kind")||"",E=$("doClause")||"",Z=$("dontClause")||"",X=$("whenClause")||"",H=$("topicHint")||"";const W=t.match(/```[\w]*\n([\s\S]*?)```/);W&&(q=W[1].trim());const O=t.replace(/^---\n[\s\S]*?\n---/,"").trim(),ye=O.match(/## (?:AI Context \/ )?Usage Guide(?:\s*\(CN\))?\n\n([\s\S]*?)(?=\n## |$)/);ye&&(k=ye[1].trim());const Ne=O.match(/## (?:AI Context \/ )?Usage Guide\s*\(EN\)\n\n([\s\S]*?)(?=\n## |$)/);Ne&&(w=Ne[1].trim());const je=O.match(/## Architecture Usage\n\n([\s\S]*?)(?=\n## |$)/);je&&(T=je[1].trim());const v=O.match(/## Best Practices\n\n([\s\S]*?)(?=\n## |$)/);v&&(A=v[1].trim());const ee=O.match(/## Standards\n\n([\s\S]*?)(?=\n## |$)/);ee&&(G=ee[1].trim())}return{title:l,language:s,category:a,trigger:d,summary:c,summaryEn:u,knowledgeType:p,complexity:n,scope:g,tags:f,headers:h,difficulty:x,authority:i,version:y,codePattern:q,usageGuide:k,usageGuideEn:w,rationaleText:T,bestPracticesText:A,standardsText:G,kind:_,doClause:E,dontClause:Z,whenClause:X,topicHint:H}}function cr(t,s,a){var d;const l=Array.isArray(t.category)?t.category[0]:t.category||s||"general";return{title:t.title||"Untitled",content:t.content||{pattern:((d=t.content)==null?void 0:d.pattern)||"",markdown:"",rationale:""},description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:l,kind:t.kind||"pattern",knowledgeType:t.knowledgeType||"code-pattern",complexity:t.complexity||"intermediate",source:a,lifecycle:"pending",tags:t.tags||[],sourceFile:t.sourceFile||"",moduleName:t.moduleName||"",headers:t.headers||[],headerPaths:t.headerPaths||[],reasoning:{whyStandard:t.description||t.title||"Extracted from project",sources:[a],confidence:.6},metadata:{targetName:s||"",title:t.title||"",trigger:t.trigger||"",description:t.description||"",category:l,headers:t.headers||[],headerPaths:t.headerPaths||[],moduleName:t.moduleName||"",isMarked:t.isMarked||!1}}}async function _t(t){var c,u,p;const s=t.replace(/\.md$/i,"");if(/^[a-f0-9-]{8,}$/i.test(s))return s;const a=await oe.get("/knowledge?limit=1000"),d=(((u=(c=a.data)==null?void 0:c.data)==null?void 0:u.data)||((p=a.data)==null?void 0:p.data)||[]).find(n=>{const g=n.title||n.name||"";return g===s||g+".md"===t});if(d!=null&&d.id)return d.id;throw new Error(`Knowledge entry not found: ${t}`)}async function dr(t,s){var u;const a=(u=t.body)==null?void 0:u.getReader();if(!a)throw new Error("ReadableStream not available");const l=new TextDecoder;let d="",c="";for(;;){const{done:p,value:n}=await a.read();if(p)break;const g=l.decode(n,{stream:!0});d+=g;const f=d.split(`
22
+ `);d=f.pop()||"";for(const h of f){if(h.startsWith(":")||!h.startsWith("data: "))continue;const x=h.slice(6).trim();if(!(!x||x==="[DONE]"))try{const i=JSON.parse(x);if(s(i),i.type==="text:delta"&&i.delta)c+=i.delta;else if(i.type==="stream:done"&&i.text)c=i.text;else if(i.type==="stream:error")throw new Error(i.message||"Stream error")}catch(i){if(i instanceof SyntaxError)continue;throw i}}}return c}const ae={async fetchData(){var h,x,i,y,k,w,T;const[t,s,a]=await Promise.all([oe.get("/knowledge?limit=1000").catch(()=>({data:{success:!0,data:{data:[]}}})),oe.get("/ai/config").catch(()=>({data:{success:!0,data:{provider:"",model:""}}})),oe.get("/modules/project-info").catch(()=>({data:{success:!0,data:{projectRoot:""}}}))]),l=((x=(h=t.data)==null?void 0:h.data)==null?void 0:x.data)||((y=(i=t.data)==null?void 0:i.data)==null?void 0:y.items)||[],c=l.filter(A=>A.lifecycle==="active").map(la),u=l.filter(A=>A.lifecycle==="pending"),p={};for(const A of u){const G=A.category||A.language||"_pending";p[G]||(p[G]={targetName:G,scanTime:A.createdAt,items:[]}),p[G].items.push(A)}const n=((k=s.data)==null?void 0:k.data)||{provider:"",model:""},g={};for(const A of l)A.id&&A.title&&(g[A.id]=A.title);const f=((T=(w=a.data)==null?void 0:w.data)==null?void 0:T.projectRoot)||"";return{rootSpec:{list:[]},recipes:c,candidates:p,projectRoot:f,watcherStatus:"active",aiConfig:{provider:n.provider||"",model:n.model||""},idTitleMap:g}},async fetchTargets(){var a;return(((a=(await oe.get("/modules/targets")).data)==null?void 0:a.data)||{}).targets||[]},async getTargetFiles(t,s){var d,c;const l=((d=(await oe.post("/modules/target-files",{target:t},{signal:s})).data)==null?void 0:d.data)||{};return{files:l.files||[],count:l.total||((c=l.files)==null?void 0:c.length)||0}},async scanTarget(t,s){var c;const l=((c=(await oe.post("/modules/scan",{target:t},{signal:s,timeout:6e5})).data)==null?void 0:c.data)||{};return{recipes:l.recipes||l.result||[],scannedFiles:l.scannedFiles||[],message:l.message||"",noAi:!!l.noAi}},async scanTargetStream(t,s,a){let l;const d=await fetch("/api/v1/modules/scan/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t}),signal:a});if(!d.ok)throw new Error(`Scan stream start failed: ${d.status}`);if(l=(await d.json()).sessionId,!l)throw new Error("No sessionId returned");return new Promise((u,p)=>{const n=`/api/v1/modules/scan/events/${l}`,g=new EventSource(n);let f=!1,h={recipes:[],scannedFiles:[],message:"",noAi:!1};function x(){g.close()}if(g.onmessage=i=>{try{const y=JSON.parse(i.data);s(y),y.type==="scan:result"&&(h={recipes:y.recipes||[],scannedFiles:y.scannedFiles||[],message:y.message||"",noAi:!!y.noAi}),y.type==="stream:done"&&(x(),f=!0,u(h)),y.type==="stream:error"&&(x(),f=!0,p(new Error(y.message||"Scan stream error")))}catch{}},g.onerror=()=>{f||(x(),f=!0,h.recipes.length>0?u(h):p(new Error("EventSource connection failed")))},a){const i=()=>{f||(x(),f=!0,p(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){i();return}a.addEventListener("abort",i,{once:!0})}})},async scanProject(t){var l;const a=((l=(await oe.post("/modules/scan-project",{},{signal:t,timeout:6e5})).data)==null?void 0:l.data)||{};return{targets:a.targets||[],recipes:a.recipes||[],guardAudit:a.guardAudit||null,scannedFiles:a.scannedFiles||[],partial:a.partial||!1}},async browseDirectories(t="",s=3){var d,c;const a=new URLSearchParams;return t&&a.set("path",t),s&&a.set("depth",String(s)),((c=(d=(await oe.get(`/modules/browse-dirs?${a.toString()}`)).data)==null?void 0:d.data)==null?void 0:c.directories)||[]},async scanFolderStream(t,s,a){const l=await fetch("/api/v1/modules/scan-folder/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t}),signal:a});if(!l.ok)throw new Error(`Scan folder start failed: ${l.status}`);const c=(await l.json()).sessionId;if(!c)throw new Error("No sessionId returned");return new Promise((u,p)=>{const n=`/api/v1/modules/scan/events/${c}`,g=new EventSource(n);let f=!1,h={recipes:[],scannedFiles:[],message:"",noAi:!1};function x(){g.close()}if(g.onmessage=i=>{try{const y=JSON.parse(i.data);s(y),y.type==="scan:result"&&(h={recipes:y.recipes||[],scannedFiles:y.scannedFiles||[],message:y.message||"",noAi:!!y.noAi}),y.type==="stream:done"&&(x(),f=!0,u(h)),y.type==="stream:error"&&(x(),f=!0,p(new Error(y.message||"Scan folder stream error")))}catch{}},g.onerror=()=>{f||(x(),f=!0,h.recipes.length>0?u(h):p(new Error("EventSource connection failed")))},a){const i=()=>{f||(x(),f=!0,p(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){i();return}a.addEventListener("abort",i,{once:!0})}})},async bootstrap(t){var l;const a=((l=(await oe.post("/modules/bootstrap",{},{signal:t,timeout:3e5})).data)==null?void 0:l.data)||{};return{report:a.report||{},targets:a.targets||[],filesByTarget:a.filesByTarget||{},dependencyGraph:a.dependencyGraph||null,languageStats:a.languageStats||{},primaryLanguage:a.primaryLanguage||"",guardSummary:a.guardSummary||null,guardViolationFiles:a.guardViolationFiles||[],bootstrapCandidates:a.bootstrapCandidates||{created:0,failed:0},bootstrapSession:a.bootstrapSession||null,asyncFill:a.asyncFill||!1,message:a.message||""}},async getBootstrapStatus(){var s;return((s=(await oe.get("/modules/bootstrap/status")).data)==null?void 0:s.data)||{status:"idle"}},async getDepGraph(t){var a;return((a=(await oe.get(`/modules/dep-graph?level=${t}`)).data)==null?void 0:a.data)||{}},async getProjectInfo(){var t;try{return((t=(await oe.get("/modules/project-info")).data)==null?void 0:t.data)||{}}catch{return{primaryLanguage:"unknown",discoverers:[],hasSpm:!1}}},async syncSnippets(t="all"){return(await oe.post("/commands/install",{target:t})).data},async refreshProject(){try{await oe.post("/modules/update-map")}catch{await oe.post("/commands/spm-map")}},async extractFromPath(t){var l;const a=((l=(await oe.post("/extract/path",{relativePath:t})).data)==null?void 0:l.data)||{};return{result:a.result||[],isMarked:a.isMarked||!1}},async extractFromText(t,s){var d;const l=((d=(await oe.post("/extract/text",{text:t,...s?{relativePath:s}:{}})).data)==null?void 0:d.data)||{};return Array.isArray(l.result)&&l.result.length>0?l.result[0]:l},async saveRecipe(t,s){const a=ir(s),l=a.title||t.replace(/\.md$/,""),d={trigger:a.trigger,headers:a.headers,difficulty:a.difficulty,authority:a.authority,version:a.version},c={pattern:a.codePattern||"",rationale:a.rationaleText||"",steps:a.bestPracticesText?[a.bestPracticesText]:[],codeChanges:[],verification:null,markdown:a.usageGuide||""},u={};if(a.standardsText){const n=a.standardsText.split(`
23
+ `).map(h=>h.trim()).filter(Boolean),g=n.filter(h=>h.startsWith("- ")).map(h=>h.slice(2).trim());g.length>0&&(u.preconditions=g);const f=n.filter(h=>!h.startsWith("- ")&&!h.startsWith("**"));f.length>0&&(u.boundaries=f)}const p={title:l,language:a.language,category:a.category,description:a.summary,knowledgeType:a.knowledgeType||"code-pattern",complexity:a.complexity||"intermediate",scope:a.scope||null,tags:a.tags||[],content:c,constraints:u,dimensions:d};a.kind&&(p.kind=a.kind),a.doClause&&(p.doClause=a.doClause),a.dontClause&&(p.dontClause=a.dontClause),a.whenClause&&(p.whenClause=a.whenClause),a.topicHint&&(p.topicHint=a.topicHint);try{const n=await _t(t);await oe.patch(`/knowledge/${n}`,p);return}catch{}await oe.post("/knowledge",p)},async deleteRecipe(t){const s=await _t(t);await oe.delete(`/knowledge/${s}`)},async getRecipeByName(t){var c;const s=await _t(t),l=(c=(await oe.get(`/knowledge/${s}`)).data)==null?void 0:c.data;if(!l)throw new Error("Recipe not found");const d=l.content||{};return{name:t,content:d.pattern||d.markdown||""}},async setRecipeAuthority(t,s){const a=await _t(t);await oe.patch(`/knowledge/${a}/quality`,{codeCompleteness:s,projectAdaptation:s,documentationClarity:s})},async updateRecipeRelations(t,s){const a=await _t(t);await oe.patch(`/knowledge/${a}`,{relations:s})},async getCandidate(t){var l;const a=(l=(await oe.get(`/knowledge/${t}`)).data)==null?void 0:l.data;if(!a)throw new Error("Knowledge entry not found");return a},async deleteCandidate(t){await oe.delete(`/knowledge/${t}`)},async promoteCandidateToRecipe(t,s){var d;const l=(d=(await oe.patch(`/knowledge/${t}/publish`)).data)==null?void 0:d.data;return{recipe:l,candidate:l}},async enrichCandidates(t){var a;return((a=(await oe.post("/candidates/enrich",{candidateIds:t})).data)==null?void 0:a.data)||{enriched:0,total:0,results:[]}},async bootstrapRefine(t,s,a){var d;return((d=(await oe.post("/candidates/bootstrap-refine",{candidateIds:t,userPrompt:s,dryRun:a},{timeout:3e5})).data)==null?void 0:d.data)||{refined:0,total:0,errors:[],results:[]}},async refinePreview(t,s){var l;return((l=(await oe.post("/candidates/refine-preview",{candidateId:t,userPrompt:s},{timeout:12e4})).data)==null?void 0:l.data)||{}},async refineApply(t,s,a){var d;return((d=(await oe.post("/candidates/refine-apply",{candidateId:t,userPrompt:s,preview:a},{timeout:12e4})).data)==null?void 0:d.data)||{}},async getKnowledgeGraph(t=500){var a;return((a=(await oe.get(`/search/graph/all?limit=${t}`)).data)==null?void 0:a.data)||{edges:[],nodeLabels:{},nodeTypes:{},nodeCategories:{}}},async getGraphStats(){var s;return((s=(await oe.get("/search/graph/stats")).data)==null?void 0:s.data)||{totalEdges:0,byRelation:{},nodeTypes:[]}},async discoverRelations(t=20){var a,l,d,c;const s=await oe.post("/recipes/discover-relations",{batchSize:t});if(!((a=s.data)!=null&&a.success))throw new Error(((d=(l=s.data)==null?void 0:l.error)==null?void 0:d.message)||"启动失败");return((c=s.data)==null?void 0:c.data)||{status:"unknown"}},async getDiscoverRelationsStatus(){var s;return((s=(await oe.get("/recipes/discover-relations/status")).data)==null?void 0:s.data)||{status:"idle"}},async deleteAllCandidatesInTarget(t){var d,c;const a=((c=(d=(await oe.get(`/knowledge?category=${encodeURIComponent(t)}&limit=1000`)).data)==null?void 0:d.data)==null?void 0:c.data)||[];let l=0;for(const u of a)try{await oe.delete(`/knowledge/${u.id}`),l++}catch{}return{deleted:l}},async promoteToCandidate(t,s){var d,c;const a=cr(t,s,"review-promote");return{ok:!0,candidateId:((c=(d=(await oe.post("/knowledge",a)).data)==null?void 0:d.data)==null?void 0:c.id)||""}},async getCandidateSimilarity(t,s){var l;return((l=(await oe.post("/search/similarity",{code:t,language:s}).catch(()=>({data:{data:{similar:[]}}}))).data)==null?void 0:l.data)||{similar:[]}},async getCandidateSimilarityEx(t){var a;return((a=(await oe.post("/search/similarity",t).catch(()=>({data:{data:{similar:[]}}}))).data)==null?void 0:a.data)||{similar:[]}},async getRecipeContentByName(t){var p;const s=await _t(t),l=(p=(await oe.get(`/knowledge/${s}`)).data)==null?void 0:p.data;if(!l)throw new Error("Recipe not found");const c=la(l).content,u=[c==null?void 0:c.pattern,c==null?void 0:c.markdown].filter(Boolean).join(`
24
24
 
25
- `)||"";return{name:t,content:u}},async getAiProviders(){var s;return((s=(await oe.get("/ai/providers")).data)==null?void 0:s.data)||[]},async setAiConfig(t,s){var l;return((l=(await oe.post("/ai/config",{provider:t,model:s})).data)==null?void 0:l.data)||{provider:t,model:s}},async chat(t,s,a){var i;const d=((i=(await oe.post("/ai/chat",{prompt:t,history:s},{signal:a})).data)==null?void 0:i.data)||{};return{text:d.reply||d.text||"",hasContext:d.hasContext}},async chatStream(t,s,a,l,d){const i=await fetch("/api/v1/ai/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:t,history:s,...d?{lang:d}:{}}),signal:l});if(!i.ok)throw new Error(`Chat start failed: ${i.status}`);if((i.headers.get("content-type")||"").includes("text/event-stream")){let g={text:""};const f=await dr(i,h=>{a(h),h.type==="stream:done"&&(h.text&&(g.text=h.text),g.toolCalls=h.toolCalls,g.hasContext=h.hasContext)});return!g.text&&f&&(g.text=f),g}const p=await i.json(),n=p.sessionId;if(!n)throw new Error(`No sessionId returned: ${JSON.stringify(p)}`);return new Promise((g,f)=>{const h=`/api/v1/ai/chat/events/${n}`,x=new EventSource(h);let c="",j={text:""},w=!1;function C(){x.close()}if(x.onmessage=E=>{try{const S=JSON.parse(E.data);if(S.type==="stream:start")return;a(S),S.type==="text:delta"&&S.delta&&(c+=S.delta),S.type==="stream:done"&&(j={text:S.text||c,toolCalls:S.toolCalls,hasContext:S.hasContext},C(),w=!0,g(j)),S.type==="stream:error"&&(C(),w=!0,f(new Error(S.message||"Stream error")))}catch{}},x.onerror=()=>{w||(C(),c?(w=!0,g({text:c})):(w=!0,f(new Error("EventSource connection failed"))))},l){const E=()=>{w||(C(),w=!0,f(new DOMException("The operation was aborted.","AbortError")))};l.aborted?E():l.addEventListener("abort",E,{once:!0})}})},async refinePreviewStream(t,s,a,l){const d=await fetch("/api/v1/candidates/refine-preview-stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({candidateId:t,userPrompt:s}),signal:l});if(!d.ok)throw new Error(`Refine stream start failed: ${d.status}`);const u=(await d.json()).sessionId;if(!u)throw new Error("No sessionId returned");return new Promise((p,n)=>{const g=`/api/v1/candidates/refine-preview/events/${u}`,f=new EventSource(g);let h=!1;function x(){f.close()}l&&l.addEventListener("abort",()=>{x(),h||(h=!0,n(new DOMException("Aborted","AbortError")))},{once:!0}),f.onmessage=c=>{try{const j=JSON.parse(c.data);a(j),j.type==="stream:done"&&(x(),h=!0,p({candidateId:j.candidateId||t,before:j.before||{},after:j.after||{},preview:j.preview||null})),j.type==="stream:error"&&(x(),h=!0,n(new Error(j.message||"Refine stream error")))}catch{}},f.onerror=()=>{x(),h||(h=!0,n(new Error("Refine EventSource connection lost")))}})},async summarizeCode(t,s){var l;const a=await oe.post("/ai/summarize",{code:t,language:s});return((l=a.data)==null?void 0:l.data)||a.data||{}},async translate(t,s){var d,i;const a=await oe.post("/ai/translate",{summary:t,usageGuide:s}),l=((d=a.data)==null?void 0:d.data)||{summaryEn:"",usageGuideEn:""};return(i=a.data)!=null&&i.warning&&(l.warning=a.data.warning),l},async search(t,s={}){var x,c;const{mode:a="bm25",type:l,limit:d=20,signal:i,context:u}=s,p=j=>{if(!j)return{};if(typeof j=="object")return j;try{return JSON.parse(j)}catch{return{markdown:j}}};if(u){const w=((x=(await oe.post("/search/context-aware",{keyword:t,limit:d,language:u.language,sessionHistory:u.sessionHistory||[]},{signal:i}).catch(()=>({data:{data:{}}}))).data)==null?void 0:x.data)||{},C=(w.results||[]).map(E=>{const S=p(E.content);return{title:(E.name||"").replace(/\.md$/,""),content:S,score:E.similarity||0,qualityScore:E.qualityScore||0,usageCount:E.usageCount||0,authorityScore:E.authority||0,matchType:E.matchType}});return{items:C,total:w.total||C.length,mode:"bm25",ranked:!0}}const n=new URLSearchParams({q:t,mode:a,limit:String(d)});l&&n.set("type",l);const f=((c=(await oe.get(`/search?${n}`,{signal:i})).data)==null?void 0:c.data)||{},h=(f.items||[]).map(j=>({...j,content:p(j.content)}));return{items:h,total:f.totalResults||f.total||h.length,mode:f.mode,ranked:f.ranked}},async semanticSearch(t,s=10){return(await this.search(t,{mode:"semantic",limit:s})).items.map(l=>{var d,i,u;return{name:(l.title||l.name||"")+".md",content:((d=l.content)==null?void 0:d.pattern)||((i=l.content)==null?void 0:i.markdown)||((u=l.content)==null?void 0:u.code)||"",similarity:l.score||0,metadata:{type:"recipe",name:(l.title||l.name||"")+".md"}}})},async contextAwareSearch(t){var a;return((a=(await oe.post("/search/context-aware",t).catch(()=>({data:{data:{}}}))).data)==null?void 0:a.data)||{}},async xcodeSimulateSearch(t){var a;return((a=(await oe.post("/search/xcode-simulate",t).catch(()=>({data:{data:{}}}))).data)==null?void 0:a.data)||{}},async getGuardRules(){var d;const s=((d=(await oe.get("/rules?limit=100")).data)==null?void 0:d.data)||{},a=s.data||s.items||[],l={};for(const i of a)l[i.id]=i;return{rules:l,projectLanguages:s.projectLanguages||[]}},async getGuardViolations(){var a;const s=((a=(await oe.get("/violations")).data)==null?void 0:a.data)||{};return{runs:s.data||s.items||[]}},async clearViolations(){await oe.post("/violations/clear")},async generateGuardRule(t){var a;return((a=(await oe.post("/violations/rules/generate",t)).data)==null?void 0:a.data)||{}},async saveGuardRule(t){var a;return((a=(await oe.post("/rules",t)).data)==null?void 0:a.data)||{}},async insertAtSearchMark(t){return{success:!1}},async searchRecipesForModal(t,s){const a=await this.search(t,{mode:"bm25",type:"recipe",signal:s});return{results:a.items.map(l=>({name:(l.title||l.name||"")+".md",path:"",content:l.content,qualityScore:(l.quality||{}).overall||l.qualityScore||0,recommendReason:""})),total:a.total}},async listSkills(){var s;return((s=(await oe.get("/skills")).data)==null?void 0:s.data)||{skills:[],total:0}},async loadSkill(t,s){var d;const a=s?`?section=${encodeURIComponent(s)}`:"";return((d=(await oe.get(`/skills/${encodeURIComponent(t)}${a}`)).data)==null?void 0:d.data)||{}},async createSkill(t){var a;return((a=(await oe.post("/skills",t)).data)==null?void 0:a.data)||{}},async updateSkill(t,s){var l;return((l=(await oe.put(`/skills/${encodeURIComponent(t)}`,s)).data)==null?void 0:l.data)||{}},async deleteSkill(t){var a;return((a=(await oe.delete(`/skills/${encodeURIComponent(t)}`)).data)==null?void 0:a.data)||{}},async suggestSkills(){var s;return((s=(await oe.get("/skills/suggest")).data)==null?void 0:s.data)||{suggestions:[],analysisContext:{}}},async getSignalStatus(){var s;return((s=(await oe.get("/skills/signal-status")).data)==null?void 0:s.data)||{running:!1,mode:"off",snapshot:null}},async aiGenerateSkill(t){var l;return((l=(await oe.post("/ai/chat",{prompt:`你是一个 AutoSnippet Skill 文档生成助手。用户会描述他们想创建的 Skill,你需要生成完整的 SKILL.md 内容。
25
+ `)||"";return{name:t,content:u}},async getAiProviders(){var s;return((s=(await oe.get("/ai/providers")).data)==null?void 0:s.data)||[]},async setAiConfig(t,s){var l;return((l=(await oe.post("/ai/config",{provider:t,model:s})).data)==null?void 0:l.data)||{provider:t,model:s}},async chat(t,s,a){var c;const d=((c=(await oe.post("/ai/chat",{prompt:t,history:s},{signal:a})).data)==null?void 0:c.data)||{};return{text:d.reply||d.text||"",hasContext:d.hasContext}},async chatStream(t,s,a,l,d){const c=await fetch("/api/v1/ai/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:t,history:s,...d?{lang:d}:{}}),signal:l});if(!c.ok)throw new Error(`Chat start failed: ${c.status}`);if((c.headers.get("content-type")||"").includes("text/event-stream")){let g={text:""};const f=await dr(c,h=>{a(h),h.type==="stream:done"&&(h.text&&(g.text=h.text),g.toolCalls=h.toolCalls,g.hasContext=h.hasContext)});return!g.text&&f&&(g.text=f),g}const p=await c.json(),n=p.sessionId;if(!n)throw new Error(`No sessionId returned: ${JSON.stringify(p)}`);return new Promise((g,f)=>{const h=`/api/v1/ai/chat/events/${n}`,x=new EventSource(h);let i="",y={text:""},k=!1;function w(){x.close()}if(x.onmessage=T=>{try{const A=JSON.parse(T.data);if(A.type==="stream:start")return;a(A),A.type==="text:delta"&&A.delta&&(i+=A.delta),A.type==="stream:done"&&(y={text:A.text||i,toolCalls:A.toolCalls,hasContext:A.hasContext},w(),k=!0,g(y)),A.type==="stream:error"&&(w(),k=!0,f(new Error(A.message||"Stream error")))}catch{}},x.onerror=()=>{k||(w(),i?(k=!0,g({text:i})):(k=!0,f(new Error("EventSource connection failed"))))},l){const T=()=>{k||(w(),k=!0,f(new DOMException("The operation was aborted.","AbortError")))};l.aborted?T():l.addEventListener("abort",T,{once:!0})}})},async refinePreviewStream(t,s,a,l){const d=await fetch("/api/v1/candidates/refine-preview-stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({candidateId:t,userPrompt:s}),signal:l});if(!d.ok)throw new Error(`Refine stream start failed: ${d.status}`);const u=(await d.json()).sessionId;if(!u)throw new Error("No sessionId returned");return new Promise((p,n)=>{const g=`/api/v1/candidates/refine-preview/events/${u}`,f=new EventSource(g);let h=!1;function x(){f.close()}l&&l.addEventListener("abort",()=>{x(),h||(h=!0,n(new DOMException("Aborted","AbortError")))},{once:!0}),f.onmessage=i=>{try{const y=JSON.parse(i.data);a(y),y.type==="stream:done"&&(x(),h=!0,p({candidateId:y.candidateId||t,before:y.before||{},after:y.after||{},preview:y.preview||null})),y.type==="stream:error"&&(x(),h=!0,n(new Error(y.message||"Refine stream error")))}catch{}},f.onerror=()=>{x(),h||(h=!0,n(new Error("Refine EventSource connection lost")))}})},async summarizeCode(t,s){var l;const a=await oe.post("/ai/summarize",{code:t,language:s});return((l=a.data)==null?void 0:l.data)||a.data||{}},async translate(t,s){var d,c;const a=await oe.post("/ai/translate",{summary:t,usageGuide:s}),l=((d=a.data)==null?void 0:d.data)||{summaryEn:"",usageGuideEn:""};return(c=a.data)!=null&&c.warning&&(l.warning=a.data.warning),l},async search(t,s={}){var x,i;const{mode:a="bm25",type:l,limit:d=20,signal:c,context:u}=s,p=y=>{if(!y)return{};if(typeof y=="object")return y;try{return JSON.parse(y)}catch{return{markdown:y}}};if(u){const k=((x=(await oe.post("/search/context-aware",{keyword:t,limit:d,language:u.language,sessionHistory:u.sessionHistory||[]},{signal:c}).catch(()=>({data:{data:{}}}))).data)==null?void 0:x.data)||{},w=(k.results||[]).map(T=>{const A=p(T.content);return{title:(T.name||"").replace(/\.md$/,""),content:A,score:T.similarity||0,qualityScore:T.qualityScore||0,usageCount:T.usageCount||0,authorityScore:T.authority||0,matchType:T.matchType}});return{items:w,total:k.total||w.length,mode:"bm25",ranked:!0}}const n=new URLSearchParams({q:t,mode:a,limit:String(d)});l&&n.set("type",l);const f=((i=(await oe.get(`/search?${n}`,{signal:c})).data)==null?void 0:i.data)||{},h=(f.items||[]).map(y=>({...y,content:p(y.content)}));return{items:h,total:f.totalResults||f.total||h.length,mode:f.mode,ranked:f.ranked}},async semanticSearch(t,s=10){return(await this.search(t,{mode:"semantic",limit:s})).items.map(l=>{var d,c,u;return{name:(l.title||l.name||"")+".md",content:((d=l.content)==null?void 0:d.pattern)||((c=l.content)==null?void 0:c.markdown)||((u=l.content)==null?void 0:u.code)||"",similarity:l.score||0,metadata:{type:"recipe",name:(l.title||l.name||"")+".md"}}})},async contextAwareSearch(t){var a;return((a=(await oe.post("/search/context-aware",t).catch(()=>({data:{data:{}}}))).data)==null?void 0:a.data)||{}},async xcodeSimulateSearch(t){var a;return((a=(await oe.post("/search/xcode-simulate",t).catch(()=>({data:{data:{}}}))).data)==null?void 0:a.data)||{}},async getGuardRules(){var d;const s=((d=(await oe.get("/rules?limit=100")).data)==null?void 0:d.data)||{},a=s.data||s.items||[],l={};for(const c of a)l[c.id]=c;return{rules:l,projectLanguages:s.projectLanguages||[]}},async getGuardViolations(){var a;const s=((a=(await oe.get("/violations")).data)==null?void 0:a.data)||{};return{runs:s.data||s.items||[]}},async clearViolations(){await oe.post("/violations/clear")},async generateGuardRule(t){var a;return((a=(await oe.post("/violations/rules/generate",t)).data)==null?void 0:a.data)||{}},async saveGuardRule(t){var a;return((a=(await oe.post("/rules",t)).data)==null?void 0:a.data)||{}},async insertAtSearchMark(t){return{success:!1}},async searchRecipesForModal(t,s){const a=await this.search(t,{mode:"bm25",type:"recipe",signal:s});return{results:a.items.map(l=>({name:(l.title||l.name||"")+".md",path:"",content:l.content,qualityScore:(l.quality||{}).overall||l.qualityScore||0,recommendReason:""})),total:a.total}},async listSkills(){var s;return((s=(await oe.get("/skills")).data)==null?void 0:s.data)||{skills:[],total:0}},async loadSkill(t,s){var d;const a=s?`?section=${encodeURIComponent(s)}`:"";return((d=(await oe.get(`/skills/${encodeURIComponent(t)}${a}`)).data)==null?void 0:d.data)||{}},async createSkill(t){var a;return((a=(await oe.post("/skills",t)).data)==null?void 0:a.data)||{}},async updateSkill(t,s){var l;return((l=(await oe.put(`/skills/${encodeURIComponent(t)}`,s)).data)==null?void 0:l.data)||{}},async deleteSkill(t){var a;return((a=(await oe.delete(`/skills/${encodeURIComponent(t)}`)).data)==null?void 0:a.data)||{}},async suggestSkills(){var s;return((s=(await oe.get("/skills/suggest")).data)==null?void 0:s.data)||{suggestions:[],analysisContext:{}}},async getSignalStatus(){var s;return((s=(await oe.get("/skills/signal-status")).data)==null?void 0:s.data)||{running:!1,mode:"off",snapshot:null}},async aiGenerateSkill(t){var l;return((l=(await oe.post("/ai/chat",{prompt:`你是一个 AutoSnippet Skill 文档生成助手。用户会描述他们想创建的 Skill,你需要生成完整的 SKILL.md 内容。
26
26
 
27
27
  Skill 文档格式要求:
28
28
  1. 开头用 Markdown 标题说明 Skill 的目的
@@ -45,89 +45,88 @@ Skill 文档格式要求:
45
45
  ## 使用场景
46
46
  ...
47
47
 
48
- 用户需求:${t}`,history:[]})).data)==null?void 0:l.data)||{reply:""}},async getLlmEnvConfig(){var s;return((s=(await oe.get("/ai/env-config")).data)==null?void 0:s.data)||{vars:{},hasEnvFile:!1,llmReady:!1}},async getTokenUsage7Days(){var s;return((s=(await oe.get("/ai/token-usage")).data)==null?void 0:s.data)||{daily:[],bySource:[],summary:{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}}},async saveLlmEnvConfig(t){var a;return((a=(await oe.post("/ai/env-config",t)).data)==null?void 0:a.data)||{vars:{},hasEnvFile:!1,llmReady:!1}},async knowledgeList(t={}){var d;const s=new URLSearchParams;t.page&&s.set("page",String(t.page)),t.limit&&s.set("limit",String(t.limit)),t.lifecycle&&s.set("lifecycle",t.lifecycle),t.kind&&s.set("kind",t.kind),t.category&&s.set("category",t.category),t.language&&s.set("language",t.language),t.keyword&&s.set("keyword",t.keyword),t.tag&&s.set("tag",t.tag),t.source&&s.set("source",t.source);const a=s.toString();return((d=(await oe.get(`/knowledge${a?`?${a}`:""}`)).data)==null?void 0:d.data)||{data:[],pagination:{page:1,pageSize:20,total:0}}},async knowledgeStats(){var s;return((s=(await oe.get("/knowledge/stats")).data)==null?void 0:s.data)||{total:0,pending:0,active:0,deprecated:0,rules:0,patterns:0,facts:0}},async knowledgeGet(t){var a;return(a=(await oe.get(`/knowledge/${t}`)).data)==null?void 0:a.data},async knowledgeCreate(t){var a;return(a=(await oe.post("/knowledge",t)).data)==null?void 0:a.data},async knowledgeUpdate(t,s){var l;return(l=(await oe.patch(`/knowledge/${t}`,s)).data)==null?void 0:l.data},async knowledgeDelete(t){await oe.delete(`/knowledge/${t}`)},async knowledgeLifecycle(t,s,a){var d;return(d=(await oe.patch(`/knowledge/${t}/${s}`,a?{reason:a}:{})).data)==null?void 0:d.data},async knowledgeBatchPublish(t){var a;return((a=(await oe.post("/knowledge/batch-publish",{ids:t})).data)==null?void 0:a.data)||{published:[],failed:[],successCount:0,failureCount:0}},async knowledgeRecordUsage(t,s="adoption",a){await oe.post(`/knowledge/${t}/usage`,{type:s,feedback:a})},async knowledgeUpdateQuality(t){var a;return((a=(await oe.patch(`/knowledge/${t}/quality`)).data)==null?void 0:a.data)||{quality:{}}},async wikiGenerate(){await oe.post("/wiki/generate")},async wikiUpdate(){await oe.post("/wiki/update")},async wikiAbort(){await oe.post("/wiki/abort")},async wikiStatus(){var s;return((s=(await oe.get("/wiki/status")).data)==null?void 0:s.data)||{task:{status:"idle"}}},async wikiFiles(){var s;return((s=(await oe.get("/wiki/files")).data)==null?void 0:s.data)||{files:[],exists:!1}},async wikiFileContent(t){var a;return((a=(await oe.get(`/wiki/file/${t}`)).data)==null?void 0:a.data)||{path:t,content:"",size:0}},async getLang(){var s,a;return((a=(s=(await oe.get("/ai/lang")).data)==null?void 0:s.data)==null?void 0:a.lang)||"zh"},async setLang(t){await oe.post("/ai/lang",{lang:t})}},ur=!1,Ds="auth_token",Is="auth_user";function pr(){const[t,s]=o.useState(()=>localStorage.getItem(Ds)),[a,l]=o.useState(()=>{try{const g=localStorage.getItem(Is);return g?JSON.parse(g):null}catch{return null}}),[d,i]=o.useState(!1),u=o.useCallback(async(g,f)=>{var h,x,c,j;i(!0);try{const C=(await ss.post("/api/v1/auth/login",{username:g,password:f})).data;if(C.success){const E=C.data.token,S=C.data.user??{username:g,role:"developer"};return localStorage.setItem(Ds,E),localStorage.setItem(Is,JSON.stringify(S)),s(E),l(S),{success:!0}}return{success:!1,error:((h=C.error)==null?void 0:h.message)||"登录失败"}}catch(w){return{success:!1,error:((j=(c=(x=w.response)==null?void 0:x.data)==null?void 0:c.error)==null?void 0:j.message)||w.message||"网络错误"}}finally{i(!1)}},[]),p=o.useCallback(()=>{localStorage.removeItem(Ds),localStorage.removeItem(Is),s(null),l(null)},[]);o.useEffect(()=>{},[]);const n=o.useMemo(()=>!0,[t,a]);return{authEnabled:ur,isAuthenticated:n,isLoading:d,user:a,login:u,logout:p}}const xr={developer:["*"],external_agent:["read:recipes","read:guard_rules","create:candidates","submit:knowledge","read:audit_logs:self","knowledge:bootstrap"],chat_agent:["read:recipes","read:candidates","create:candidates","read:guard_rules"]};function mr(t){const[s,a]=o.useState(()=>"developer"),[l,d]=o.useState("anonymous"),[i,u]=o.useState("probe"),[p,n]=o.useState(!0),[g,f]=o.useState(null),h=o.useCallback(async()=>{n(!0);try{const C=localStorage.getItem("auth_token"),E={};C&&(E.Authorization=`Bearer ${C}`);const S=await ss.get("/api/v1/auth/probe",{headers:E});if(S.data.success){const G=S.data.data;a(G.role),d(G.user),u(G.mode),f(G.probeCache??null)}}catch{a("developer")}finally{n(!1)}},[]);o.useEffect(()=>{h()},[t,h]);const x=o.useCallback((C,E)=>{const S=xr[s]||[];if(S.includes("*"))return!0;const G=E?`${C}:${E}`:C;if(S.includes(G))return!0;const z=C.split(":")[0];return!!(S.includes(`${z}:*`)||z==="read"&&S.includes("read:*"))},[s]),c=o.useMemo(()=>s==="developer",[s]),j=o.useMemo(()=>s==="developer",[s]),w=o.useMemo(()=>s!=="developer",[s]);return{role:s,user:l,mode:i,isLoading:p,isAdmin:c,canWrite:j,isReadOnly:w,can:x,probeCache:g,refresh:h}}let Ut=null;function Ks(){return Ut||(Ut=sl(window.location.origin,{path:"/socket.io",transports:["websocket"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:2e3,reconnectionDelayMax:1e4}),Ut.on("connect",()=>{Ut.emit("join-notifications")})),Ut}const Rs={activeRound:0,round1:{status:"idle"},round2:{status:"idle"},round3:{status:"idle"}};function hr(){const[t,s]=o.useState(null),[a,l]=o.useState(!1),[d,i]=o.useState(Rs),[u,p]=o.useState(0),n=o.useRef(null),g=o.useRef(null);o.useEffect(()=>{const c=Ks(),j=()=>{l(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>C(),500)},w=()=>l(!1),C=async()=>{try{const N=await se.getBootstrapStatus();N&&N.status==="running"&&N.tasks&&s(y=>!y||y.id===N.id||N.progress>((y==null?void 0:y.progress)??0)?(n.current=N.id,N):y)}catch{}},E=()=>C(),S=N=>{n.current=N.sessionId,i(Rs),s({id:N.sessionId,status:"running",progress:0,total:N.total,completed:0,failed:0,filling:0,skeleton:N.total,startedAt:N.startedAt||Date.now(),totalToolCalls:0,elapsedMs:0,tasks:N.tasks.map(y=>({id:y.id,status:"skeleton",meta:{type:y.type,dimId:y.dimId,label:y.label,skillWorthy:y.skillWorthy,skillMeta:y.skillMeta}}))})},G=N=>{s(y=>{if(!y)return y;const W=y.tasks.map(O=>O.id===N.taskId?{...O,status:"filling",startedAt:Date.now()}:O);return{...y,progress:N.progress,tasks:W,filling:W.filter(O=>O.status==="filling").length,skeleton:W.filter(O=>O.status==="skeleton").length}})},z=N=>{var W,O;s(be=>{if(!be)return be;const we=be.tasks.map(ye=>ye.id===N.taskId?{...ye,status:"completed",completedAt:Date.now(),result:N.result}:ye);return{...be,progress:N.progress,completed:N.completed,total:N.total,totalToolCalls:N.totalToolCalls??be.totalToolCalls,elapsedMs:N.elapsedMs??be.elapsedMs,tasks:we,filling:we.filter(ye=>ye.status==="filling").length,skeleton:we.filter(ye=>ye.status==="skeleton").length}}),(Number((W=N.result)==null?void 0:W.created)||Number((O=N.result)==null?void 0:O.extracted)||0)>0&&p(be=>be+1)},P=N=>{s(y=>{if(!y)return y;const W=y.tasks.map(O=>O.id===N.taskId?{...O,status:"failed",completedAt:Date.now(),error:N.error}:O);return{...y,progress:N.progress,failed:W.filter(O=>O.status==="failed").length,tasks:W,filling:W.filter(O=>O.status==="filling").length,skeleton:W.filter(O=>O.status==="skeleton").length}})},Z=N=>{s(y=>{if(!y||N.sessionId&&y.id!==N.sessionId)return y;const W=y.tasks.map(O=>O.status==="skeleton"||O.status==="filling"?{...O,status:"completed",completedAt:Date.now()}:O);return{...y,status:W.some(O=>O.status==="failed")?"completed_with_errors":"completed",progress:100,completed:W.filter(O=>O.status==="completed").length,summary:N.summary,tasks:W,filling:0,skeleton:0}})},X=N=>{i(y=>({...y,activeRound:1,round1:{status:"running",total:N.total}}))},H=N=>{i(y=>({...y,activeRound:1,round1:{status:"completed",total:N.total,kept:N.kept,dropped:N.dropped,merged:N.merged}}))},q=N=>{i(y=>({...y,activeRound:2,round2:{status:"running",total:N.total}}))},R=N=>{i(y=>({...y,activeRound:2,round2:{...y.round2,status:"running",current:N.current,total:N.total,progress:N.progress}}))},M=N=>{i(y=>({...y,activeRound:2,round2:{status:"completed",total:N.total,refined:N.refined,progress:100}}))},_=N=>{i(y=>({...y,activeRound:3,round3:{status:"running",total:N.total}}))},m=N=>{i(y=>({...y,activeRound:3,round3:{status:"completed",total:N.total,afterDedup:N.afterDedup,relationsFound:N.relationsFound}}))};return c.on("connect",j),c.on("disconnect",w),c.io.on("reconnect",E),c.on("bootstrap:started",S),c.on("bootstrap:task-started",G),c.on("bootstrap:task-completed",z),c.on("bootstrap:task-failed",P),c.on("bootstrap:all-completed",Z),c.on("review:round1-started",X),c.on("review:round1-completed",H),c.on("review:round2-started",q),c.on("review:round2-progress",R),c.on("review:round2-completed",M),c.on("review:round3-started",_),c.on("review:round3-completed",m),l(c.connected),c.connected&&C(),()=>{g.current&&clearTimeout(g.current),c.off("connect",j),c.off("disconnect",w),c.io.off("reconnect",E),c.off("bootstrap:started",S),c.off("bootstrap:task-started",G),c.off("bootstrap:task-completed",z),c.off("bootstrap:task-failed",P),c.off("bootstrap:all-completed",Z),c.off("review:round1-started",X),c.off("review:round1-completed",H),c.off("review:round2-started",q),c.off("review:round2-progress",R),c.off("review:round2-completed",M),c.off("review:round3-started",_),c.off("review:round3-completed",m)}},[]);const f=o.useCallback(()=>{n.current=null,s(null),i(Rs)},[]),h=o.useCallback(c=>{c&&s(j=>{if(j&&j.id===c.id){const w=(j.filling??0)+(j.completed??0)+(j.failed??0),C=(c.filling??0)+(c.completed??0)+(c.failed??0);if(j.progress>c.progress||w>C)return j}return n.current=c.id,c})},[]),x=(t==null?void 0:t.status)==="completed"||(t==null?void 0:t.status)==="completed_with_errors";return{session:t,isConnected:a,isAllDone:x,reviewState:d,candidateCreatedTick:u,resetSession:f,initFromApiResponse:h}}const F={xs:12,sm:14,md:16,lg:20,xl:24,xxl:32,xxxl:48};function ra(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}const na={developer:{key:"sidebar.roleDeveloper",color:"text-emerald-700",bg:"bg-emerald-50 border-emerald-200"},external_agent:{key:"sidebar.roleAgent",color:"text-purple-700",bg:"bg-purple-50 border-purple-200"},chat_agent:{key:"sidebar.roleChatAgent",color:"text-blue-700",bg:"bg-blue-50 border-blue-200"}},gr={token:bl,probe:os},br=({activeTab:t,navigateToTab:s,candidateCount:a,signalSuggestionCount:l=0,currentUser:d,currentRole:i,permissionMode:u,onLogout:p,collapsed:n=!1,onToggleCollapse:g})=>{const{t:f}=_e(),{isDark:h}=St(),x=na[i||""]||na.developer,c=gr[u||"probe"]||os,[j,w]=o.useState(null),C=o.useCallback(()=>{se.getTokenUsage7Days().then(z=>w(z.summary)).catch(()=>{})},[]);o.useEffect(()=>{C();const z=Ks(),P=()=>C();return z.on("candidate-created",P),z.on("bootstrap:all-completed",P),z.on("token-usage-updated",P),()=>{z.off("candidate-created",P),z.off("bootstrap:all-completed",P),z.off("token-usage-updated",P)}},[C]);const E=[{tab:"recipes",icon:xl,label:f("sidebar.recipes")},{tab:"spm",icon:wt,label:f("sidebar.moduleExplorer")},{tab:"candidates",icon:xt,label:f("sidebar.candidates",{count:a})},{tab:"knowledge",icon:Aa,label:f("sidebar.batchManage")},{tab:"depgraph",icon:_s,label:f("sidebar.depGraph")},{tab:"knowledgegraph",icon:Ls,label:f("sidebar.knowledgeGraph")},{tab:"guard",icon:ut,label:f("sidebar.guard")},{tab:"skills",icon:tt,label:f("sidebar.skills"),badge:l>0?l:void 0,badgeColor:"bg-amber-100 text-amber-700"},{tab:"wiki",icon:nt,label:f("sidebar.repoWiki")},{tab:"ai",icon:Lt,label:f("sidebar.aiAssistant")},{tab:"help",icon:ml,label:f("sidebar.help")}],S=h?"bg-blue-900/30 text-blue-400 font-medium":"bg-blue-50 text-blue-700 font-medium",G=h?"text-slate-300 hover:bg-slate-700/50":"text-slate-600 hover:bg-slate-50";return e.jsxs("aside",{className:`${n?"w-16":"w-64"} ${h?"bg-[#252526] border-r border-[#3e3e42]":"bg-white border-r border-slate-200"} flex flex-col shrink-0 transition-all duration-200`,children:[e.jsxs("div",{className:`${n?"px-3 py-4":"p-6"} border-b ${h?"border-[#3e3e42]":"border-slate-100"} flex items-center ${n?"justify-center":"justify-between"}`,children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center text-white shrink-0",children:e.jsx($s,{size:F.lg})}),!n&&e.jsx("h1",{className:"font-bold text-lg truncate",children:"AutoSnippet"})]}),g&&!n&&e.jsx("button",{onClick:g,className:`p-1 rounded-md transition-colors ${h?"text-slate-500 hover:text-slate-300 hover:bg-slate-700/50":"text-slate-400 hover:text-slate-600 hover:bg-slate-100"}`,title:f("sidebar.collapseNav"),children:e.jsx(hl,{size:16})})]}),n&&g&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsx("button",{onClick:g,className:`p-1.5 rounded-md transition-colors ${h?"text-slate-500 hover:text-slate-300 hover:bg-slate-700/50":"text-slate-400 hover:text-slate-600 hover:bg-slate-100"}`,title:f("sidebar.expandNav"),children:e.jsx(gl,{size:16})})}),e.jsx("nav",{className:`flex-1 ${n?"px-2 py-2":"p-4"} space-y-1 overflow-y-auto scrollbar-light`,children:E.map(({tab:z,icon:P,label:Z,badge:X,badgeColor:H})=>e.jsxs("button",{type:"button",onClick:()=>s(z),title:n?Z:void 0,className:`w-full flex items-center ${n?"justify-center px-2 py-2.5 relative":"gap-3 px-4 py-2"} rounded-lg transition-colors ${t===z?S:G}`,children:[e.jsx(P,{size:F.lg,className:"shrink-0"}),!n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-left truncate text-[13px]",children:Z}),X!=null&&e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[10px] font-bold ${H||"bg-blue-100 text-blue-700"}`,children:[e.jsx(Qe,{size:10}),X]})]}),n&&X!=null&&e.jsx("span",{className:"absolute top-0 right-0 w-2 h-2 rounded-full bg-amber-400"})]},z))}),e.jsxs("div",{className:`${n?"px-2 py-3":"p-4"} ${h?"border-t border-[#3e3e42]":"border-t border-slate-100"}`,children:[!n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex items-center gap-1.5 mb-3 px-2 py-1.5 rounded-lg border text-[10px] font-bold uppercase tracking-wider ${h?"bg-slate-700/30 border-slate-600 text-slate-400":x.bg+" "+x.color}`,children:[e.jsx(c,{size:F.xs}),e.jsx("span",{children:f(u==="token"?"sidebar.modeLogin":"sidebar.modeProbe")}),e.jsx("span",{className:"mx-0.5",children:"·"}),e.jsx(fl,{size:F.xs}),e.jsx("span",{children:f(x.key)})]}),d&&e.jsxs("div",{className:`flex items-center justify-between mb-3 px-2 py-1.5 rounded-lg ${h?"bg-slate-700/30":"bg-slate-50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ia,{size:F.sm,className:h?"text-slate-400":"text-slate-500"}),e.jsx("span",{className:`text-xs font-medium truncate ${h?"text-slate-300":"text-slate-600"}`,children:d})]}),p&&e.jsx("button",{onClick:p,title:f("sidebar.logout"),className:`shrink-0 p-1 rounded transition-colors ${h?"text-slate-500 hover:text-red-400 hover:bg-slate-700/50":"text-slate-400 hover:text-red-500 hover:bg-red-50"}`,children:e.jsx(yl,{size:F.sm})})]})]}),j&&j.total_tokens>0&&e.jsxs("button",{onClick:()=>s("help"),title:n?`${f("sidebar.tokenLabel")}: ${ra(j.total_tokens)} (${f("sidebar.tokenCallsFull",{count:j.call_count})})`:void 0,className:`w-full flex items-center ${n?"justify-center py-2 mb-1":"gap-2 px-2 py-1.5 mb-2"} rounded-lg transition-colors ${h?"bg-slate-700/30 hover:bg-slate-700/50 text-slate-400":"bg-amber-50 hover:bg-amber-100 text-amber-700"}`,children:[e.jsx(et,{size:n?F.lg:F.sm,className:h?"text-amber-400":"text-amber-500"}),!n&&e.jsxs("div",{className:"flex flex-col items-start min-w-0",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",children:f("sidebar.tokenLabel")}),e.jsxs("span",{className:`text-xs font-mono font-semibold ${h?"text-amber-300":"text-amber-800"}`,children:[ra(j.total_tokens),e.jsxs("span",{className:`ml-1 text-[10px] font-normal ${h?"text-slate-500":"text-amber-600/70"}`,children:["(",j.call_count,f("sidebar.tokenCalls"),")"]})]})]})]})]})]})},fr={objectivec:"objectivec",objc:"objectivec","objective-c":"objectivec","obj-c":"objectivec",swift:"swift",go:"go",javascript:"javascript",js:"javascript",typescript:"typescript",ts:"typescript",python:"python",py:"python",java:"java",kotlin:"kotlin",kt:"kotlin",rust:"rust",rs:"rust",dart:"dart",c:"c",cpp:"cpp","c++":"cpp",csharp:"csharp",cs:"csharp",ruby:"ruby",rb:"ruby",markdown:"markdown",md:"markdown",json:"json",yaml:"yaml",xml:"xml",bash:"bash",sh:"bash",shell:"bash",sql:"sql",html:"html",css:"css",text:"text"};function Us(t){if(!t)return t;let s=t;!s.includes(`
48
+ 用户需求:${t}`,history:[]})).data)==null?void 0:l.data)||{reply:""}},async getLlmEnvConfig(){var s;return((s=(await oe.get("/ai/env-config")).data)==null?void 0:s.data)||{vars:{},hasEnvFile:!1,llmReady:!1}},async getTokenUsage7Days(){var s;return((s=(await oe.get("/ai/token-usage")).data)==null?void 0:s.data)||{daily:[],bySource:[],summary:{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}}},async saveLlmEnvConfig(t){var a;return((a=(await oe.post("/ai/env-config",t)).data)==null?void 0:a.data)||{vars:{},hasEnvFile:!1,llmReady:!1}},async knowledgeList(t={}){var d;const s=new URLSearchParams;t.page&&s.set("page",String(t.page)),t.limit&&s.set("limit",String(t.limit)),t.lifecycle&&s.set("lifecycle",t.lifecycle),t.kind&&s.set("kind",t.kind),t.category&&s.set("category",t.category),t.language&&s.set("language",t.language),t.keyword&&s.set("keyword",t.keyword),t.tag&&s.set("tag",t.tag),t.source&&s.set("source",t.source);const a=s.toString();return((d=(await oe.get(`/knowledge${a?`?${a}`:""}`)).data)==null?void 0:d.data)||{data:[],pagination:{page:1,pageSize:20,total:0}}},async knowledgeStats(){var s;return((s=(await oe.get("/knowledge/stats")).data)==null?void 0:s.data)||{total:0,pending:0,active:0,deprecated:0,rules:0,patterns:0,facts:0}},async knowledgeGet(t){var a;return(a=(await oe.get(`/knowledge/${t}`)).data)==null?void 0:a.data},async knowledgeCreate(t){var a;return(a=(await oe.post("/knowledge",t)).data)==null?void 0:a.data},async knowledgeUpdate(t,s){var l;return(l=(await oe.patch(`/knowledge/${t}`,s)).data)==null?void 0:l.data},async knowledgeDelete(t){await oe.delete(`/knowledge/${t}`)},async knowledgeLifecycle(t,s,a){var d;return(d=(await oe.patch(`/knowledge/${t}/${s}`,a?{reason:a}:{})).data)==null?void 0:d.data},async knowledgeBatchPublish(t){var a;return((a=(await oe.post("/knowledge/batch-publish",{ids:t})).data)==null?void 0:a.data)||{published:[],failed:[],successCount:0,failureCount:0}},async knowledgeRecordUsage(t,s="adoption",a){await oe.post(`/knowledge/${t}/usage`,{type:s,feedback:a})},async knowledgeUpdateQuality(t){var a;return((a=(await oe.patch(`/knowledge/${t}/quality`)).data)==null?void 0:a.data)||{quality:{}}},async wikiGenerate(){await oe.post("/wiki/generate")},async wikiUpdate(){await oe.post("/wiki/update")},async wikiAbort(){await oe.post("/wiki/abort")},async wikiStatus(){var s;return((s=(await oe.get("/wiki/status")).data)==null?void 0:s.data)||{task:{status:"idle"}}},async wikiFiles(){var s;return((s=(await oe.get("/wiki/files")).data)==null?void 0:s.data)||{files:[],exists:!1}},async wikiFileContent(t){var a;return((a=(await oe.get(`/wiki/file/${t}`)).data)==null?void 0:a.data)||{path:t,content:"",size:0}},async getLang(){var s,a;return((a=(s=(await oe.get("/ai/lang")).data)==null?void 0:s.data)==null?void 0:a.lang)||"zh"},async setLang(t){await oe.post("/ai/lang",{lang:t})}},ur=!1,Ds="auth_token",Is="auth_user";function pr(){const[t,s]=o.useState(()=>localStorage.getItem(Ds)),[a,l]=o.useState(()=>{try{const g=localStorage.getItem(Is);return g?JSON.parse(g):null}catch{return null}}),[d,c]=o.useState(!1),u=o.useCallback(async(g,f)=>{var h,x,i,y;c(!0);try{const w=(await ss.post("/api/v1/auth/login",{username:g,password:f})).data;if(w.success){const T=w.data.token,A=w.data.user??{username:g,role:"developer"};return localStorage.setItem(Ds,T),localStorage.setItem(Is,JSON.stringify(A)),s(T),l(A),{success:!0}}return{success:!1,error:((h=w.error)==null?void 0:h.message)||"登录失败"}}catch(k){return{success:!1,error:((y=(i=(x=k.response)==null?void 0:x.data)==null?void 0:i.error)==null?void 0:y.message)||k.message||"网络错误"}}finally{c(!1)}},[]),p=o.useCallback(()=>{localStorage.removeItem(Ds),localStorage.removeItem(Is),s(null),l(null)},[]);o.useEffect(()=>{},[]);const n=o.useMemo(()=>!0,[t,a]);return{authEnabled:ur,isAuthenticated:n,isLoading:d,user:a,login:u,logout:p}}const xr={developer:["*"],external_agent:["read:recipes","read:guard_rules","create:candidates","submit:knowledge","read:audit_logs:self","knowledge:bootstrap"],chat_agent:["read:recipes","read:candidates","create:candidates","read:guard_rules"]};function mr(t){const[s,a]=o.useState(()=>"developer"),[l,d]=o.useState("anonymous"),[c,u]=o.useState("probe"),[p,n]=o.useState(!0),[g,f]=o.useState(null),h=o.useCallback(async()=>{n(!0);try{const w=localStorage.getItem("auth_token"),T={};w&&(T.Authorization=`Bearer ${w}`);const A=await ss.get("/api/v1/auth/probe",{headers:T});if(A.data.success){const G=A.data.data;a(G.role),d(G.user),u(G.mode),f(G.probeCache??null)}}catch{a("developer")}finally{n(!1)}},[]);o.useEffect(()=>{h()},[t,h]);const x=o.useCallback((w,T)=>{const A=xr[s]||[];if(A.includes("*"))return!0;const G=T?`${w}:${T}`:w;if(A.includes(G))return!0;const _=w.split(":")[0];return!!(A.includes(`${_}:*`)||_==="read"&&A.includes("read:*"))},[s]),i=o.useMemo(()=>s==="developer",[s]),y=o.useMemo(()=>s==="developer",[s]),k=o.useMemo(()=>s!=="developer",[s]);return{role:s,user:l,mode:c,isLoading:p,isAdmin:i,canWrite:y,isReadOnly:k,can:x,probeCache:g,refresh:h}}let Ut=null;function Ks(){return Ut||(Ut=sl(window.location.origin,{path:"/socket.io",transports:["websocket"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:2e3,reconnectionDelayMax:1e4}),Ut.on("connect",()=>{Ut.emit("join-notifications")})),Ut}const Rs={activeRound:0,round1:{status:"idle"},round2:{status:"idle"},round3:{status:"idle"}};function hr(){const[t,s]=o.useState(null),[a,l]=o.useState(!1),[d,c]=o.useState(Rs),[u,p]=o.useState(0),n=o.useRef(null),g=o.useRef(null);o.useEffect(()=>{const i=Ks(),y=()=>{l(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>w(),500)},k=()=>l(!1),w=async()=>{try{const N=await ae.getBootstrapStatus();N&&N.status==="running"&&N.tasks&&s(j=>!j||j.id===N.id||N.progress>((j==null?void 0:j.progress)??0)?(n.current=N.id,N):j)}catch{}},T=()=>w(),A=N=>{n.current=N.sessionId,c(Rs),s({id:N.sessionId,status:"running",progress:0,total:N.total,completed:0,failed:0,filling:0,skeleton:N.total,startedAt:N.startedAt||Date.now(),totalToolCalls:0,elapsedMs:0,tasks:N.tasks.map(j=>({id:j.id,status:"skeleton",meta:{type:j.type,dimId:j.dimId,label:j.label,skillWorthy:j.skillWorthy,skillMeta:j.skillMeta}}))})},G=N=>{s(j=>{if(!j)return j;const W=j.tasks.map(O=>O.id===N.taskId?{...O,status:"filling",startedAt:Date.now()}:O);return{...j,progress:N.progress,tasks:W,filling:W.filter(O=>O.status==="filling").length,skeleton:W.filter(O=>O.status==="skeleton").length}})},_=N=>{var W,O;s(ye=>{if(!ye)return ye;const Ne=ye.tasks.map(je=>je.id===N.taskId?{...je,status:"completed",completedAt:Date.now(),result:N.result}:je);return{...ye,progress:N.progress,completed:N.completed,total:N.total,totalToolCalls:N.totalToolCalls??ye.totalToolCalls,elapsedMs:N.elapsedMs??ye.elapsedMs,tasks:Ne,filling:Ne.filter(je=>je.status==="filling").length,skeleton:Ne.filter(je=>je.status==="skeleton").length}}),(Number((W=N.result)==null?void 0:W.created)||Number((O=N.result)==null?void 0:O.extracted)||0)>0&&p(ye=>ye+1)},E=N=>{s(j=>{if(!j)return j;const W=j.tasks.map(O=>O.id===N.taskId?{...O,status:"failed",completedAt:Date.now(),error:N.error}:O);return{...j,progress:N.progress,failed:W.filter(O=>O.status==="failed").length,tasks:W,filling:W.filter(O=>O.status==="filling").length,skeleton:W.filter(O=>O.status==="skeleton").length}})},Z=N=>{s(j=>{if(!j||N.sessionId&&j.id!==N.sessionId)return j;const W=j.tasks.map(O=>O.status==="skeleton"||O.status==="filling"?{...O,status:"completed",completedAt:Date.now()}:O);return{...j,status:W.some(O=>O.status==="failed")?"completed_with_errors":"completed",progress:100,completed:W.filter(O=>O.status==="completed").length,summary:N.summary,tasks:W,filling:0,skeleton:0}})},X=N=>{c(j=>({...j,activeRound:1,round1:{status:"running",total:N.total}}))},H=N=>{c(j=>({...j,activeRound:1,round1:{status:"completed",total:N.total,kept:N.kept,dropped:N.dropped,merged:N.merged}}))},q=N=>{c(j=>({...j,activeRound:2,round2:{status:"running",total:N.total}}))},I=N=>{c(j=>({...j,activeRound:2,round2:{...j.round2,status:"running",current:N.current,total:N.total,progress:N.progress}}))},L=N=>{c(j=>({...j,activeRound:2,round2:{status:"completed",total:N.total,refined:N.refined,progress:100}}))},$=N=>{c(j=>({...j,activeRound:3,round3:{status:"running",total:N.total}}))},m=N=>{c(j=>({...j,activeRound:3,round3:{status:"completed",total:N.total,afterDedup:N.afterDedup,relationsFound:N.relationsFound}}))};return i.on("connect",y),i.on("disconnect",k),i.io.on("reconnect",T),i.on("bootstrap:started",A),i.on("bootstrap:task-started",G),i.on("bootstrap:task-completed",_),i.on("bootstrap:task-failed",E),i.on("bootstrap:all-completed",Z),i.on("review:round1-started",X),i.on("review:round1-completed",H),i.on("review:round2-started",q),i.on("review:round2-progress",I),i.on("review:round2-completed",L),i.on("review:round3-started",$),i.on("review:round3-completed",m),l(i.connected),i.connected&&w(),()=>{g.current&&clearTimeout(g.current),i.off("connect",y),i.off("disconnect",k),i.io.off("reconnect",T),i.off("bootstrap:started",A),i.off("bootstrap:task-started",G),i.off("bootstrap:task-completed",_),i.off("bootstrap:task-failed",E),i.off("bootstrap:all-completed",Z),i.off("review:round1-started",X),i.off("review:round1-completed",H),i.off("review:round2-started",q),i.off("review:round2-progress",I),i.off("review:round2-completed",L),i.off("review:round3-started",$),i.off("review:round3-completed",m)}},[]);const f=o.useCallback(()=>{n.current=null,s(null),c(Rs)},[]),h=o.useCallback(i=>{i&&s(y=>{if(y&&y.id===i.id){const k=(y.filling??0)+(y.completed??0)+(y.failed??0),w=(i.filling??0)+(i.completed??0)+(i.failed??0);if(y.progress>i.progress||k>w)return y}return n.current=i.id,i})},[]),x=(t==null?void 0:t.status)==="completed"||(t==null?void 0:t.status)==="completed_with_errors";return{session:t,isConnected:a,isAllDone:x,reviewState:d,candidateCreatedTick:u,resetSession:f,initFromApiResponse:h}}const z={xs:12,sm:14,md:16,lg:20,xl:24,xxl:32,xxxl:48};function ra(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}const na={developer:{key:"sidebar.roleDeveloper",color:"text-emerald-700",bg:"bg-emerald-50 border-emerald-200"},external_agent:{key:"sidebar.roleAgent",color:"text-purple-700",bg:"bg-purple-50 border-purple-200"},chat_agent:{key:"sidebar.roleChatAgent",color:"text-blue-700",bg:"bg-blue-50 border-blue-200"}},gr={token:bl,probe:os},br=({activeTab:t,navigateToTab:s,candidateCount:a,signalSuggestionCount:l=0,currentUser:d,currentRole:c,permissionMode:u,onLogout:p,collapsed:n=!1,onToggleCollapse:g})=>{const{t:f}=_e(),{isDark:h}=St(),x=na[c||""]||na.developer,i=gr[u||"probe"]||os,[y,k]=o.useState(null),w=o.useCallback(()=>{ae.getTokenUsage7Days().then(_=>k(_.summary)).catch(()=>{})},[]);o.useEffect(()=>{w();const _=Ks(),E=()=>w();return _.on("candidate-created",E),_.on("bootstrap:all-completed",E),_.on("token-usage-updated",E),()=>{_.off("candidate-created",E),_.off("bootstrap:all-completed",E),_.off("token-usage-updated",E)}},[w]);const T=[{tab:"recipes",icon:xl,label:f("sidebar.recipes")},{tab:"spm",icon:wt,label:f("sidebar.moduleExplorer")},{tab:"candidates",icon:xt,label:f("sidebar.candidates",{count:a})},{tab:"knowledge",icon:Aa,label:f("sidebar.batchManage")},{tab:"depgraph",icon:_s,label:f("sidebar.depGraph")},{tab:"knowledgegraph",icon:Ls,label:f("sidebar.knowledgeGraph")},{tab:"guard",icon:dt,label:f("sidebar.guard")},{tab:"skills",icon:tt,label:f("sidebar.skills"),badge:l>0?l:void 0,badgeColor:"bg-amber-100 text-amber-700"},{tab:"wiki",icon:nt,label:f("sidebar.repoWiki")},{tab:"ai",icon:Lt,label:f("sidebar.aiAssistant")},{tab:"help",icon:ml,label:f("sidebar.help")}],A=h?"bg-blue-900/30 text-blue-400 font-medium":"bg-blue-50 text-blue-700 font-medium",G=h?"text-slate-300 hover:bg-slate-700/50":"text-slate-600 hover:bg-slate-50";return e.jsxs("aside",{className:`${n?"w-16":"w-64"} ${h?"bg-[#252526] border-r border-[#3e3e42]":"bg-white border-r border-slate-200"} flex flex-col shrink-0 transition-all duration-200`,children:[e.jsxs("div",{className:`${n?"px-3 py-4":"p-6"} border-b ${h?"border-[#3e3e42]":"border-slate-100"} flex items-center ${n?"justify-center":"justify-between"}`,children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center text-white shrink-0",children:e.jsx($s,{size:z.lg})}),!n&&e.jsx("h1",{className:"font-bold text-lg truncate",children:"AutoSnippet"})]}),g&&!n&&e.jsx("button",{onClick:g,className:`p-1 rounded-md transition-colors ${h?"text-slate-500 hover:text-slate-300 hover:bg-slate-700/50":"text-slate-400 hover:text-slate-600 hover:bg-slate-100"}`,title:f("sidebar.collapseNav"),children:e.jsx(hl,{size:16})})]}),n&&g&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsx("button",{onClick:g,className:`p-1.5 rounded-md transition-colors ${h?"text-slate-500 hover:text-slate-300 hover:bg-slate-700/50":"text-slate-400 hover:text-slate-600 hover:bg-slate-100"}`,title:f("sidebar.expandNav"),children:e.jsx(gl,{size:16})})}),e.jsx("nav",{className:`flex-1 ${n?"px-2 py-2":"p-4"} space-y-1 overflow-y-auto scrollbar-light`,children:T.map(({tab:_,icon:E,label:Z,badge:X,badgeColor:H})=>e.jsxs("button",{type:"button",onClick:()=>s(_),title:n?Z:void 0,className:`w-full flex items-center ${n?"justify-center px-2 py-2.5 relative":"gap-3 px-4 py-2"} rounded-lg transition-colors ${t===_?A:G}`,children:[e.jsx(E,{size:z.lg,className:"shrink-0"}),!n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-left truncate text-[13px]",children:Z}),X!=null&&e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[10px] font-bold ${H||"bg-blue-100 text-blue-700"}`,children:[e.jsx(Qe,{size:10}),X]})]}),n&&X!=null&&e.jsx("span",{className:"absolute top-0 right-0 w-2 h-2 rounded-full bg-amber-400"})]},_))}),e.jsxs("div",{className:`${n?"px-2 py-3":"p-4"} ${h?"border-t border-[#3e3e42]":"border-t border-slate-100"}`,children:[!n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex items-center gap-1.5 mb-3 px-2 py-1.5 rounded-lg border text-[10px] font-bold uppercase tracking-wider ${h?"bg-slate-700/30 border-slate-600 text-slate-400":x.bg+" "+x.color}`,children:[e.jsx(i,{size:z.xs}),e.jsx("span",{children:f(u==="token"?"sidebar.modeLogin":"sidebar.modeProbe")}),e.jsx("span",{className:"mx-0.5",children:"·"}),e.jsx(fl,{size:z.xs}),e.jsx("span",{children:f(x.key)})]}),d&&e.jsxs("div",{className:`flex items-center justify-between mb-3 px-2 py-1.5 rounded-lg ${h?"bg-slate-700/30":"bg-slate-50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ia,{size:z.sm,className:h?"text-slate-400":"text-slate-500"}),e.jsx("span",{className:`text-xs font-medium truncate ${h?"text-slate-300":"text-slate-600"}`,children:d})]}),p&&e.jsx("button",{onClick:p,title:f("sidebar.logout"),className:`shrink-0 p-1 rounded transition-colors ${h?"text-slate-500 hover:text-red-400 hover:bg-slate-700/50":"text-slate-400 hover:text-red-500 hover:bg-red-50"}`,children:e.jsx(yl,{size:z.sm})})]})]}),y&&y.total_tokens>0&&e.jsxs("button",{onClick:()=>s("help"),title:n?`${f("sidebar.tokenLabel")}: ${ra(y.total_tokens)} (${f("sidebar.tokenCallsFull",{count:y.call_count})})`:void 0,className:`w-full flex items-center ${n?"justify-center py-2 mb-1":"gap-2 px-2 py-1.5 mb-2"} rounded-lg transition-colors ${h?"bg-slate-700/30 hover:bg-slate-700/50 text-slate-400":"bg-amber-50 hover:bg-amber-100 text-amber-700"}`,children:[e.jsx(et,{size:n?z.lg:z.sm,className:h?"text-amber-400":"text-amber-500"}),!n&&e.jsxs("div",{className:"flex flex-col items-start min-w-0",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",children:f("sidebar.tokenLabel")}),e.jsxs("span",{className:`text-xs font-mono font-semibold ${h?"text-amber-300":"text-amber-800"}`,children:[ra(y.total_tokens),e.jsxs("span",{className:`ml-1 text-[10px] font-normal ${h?"text-slate-500":"text-amber-600/70"}`,children:["(",y.call_count,f("sidebar.tokenCalls"),")"]})]})]})]})]})]})},fr={objectivec:"objectivec",objc:"objectivec","objective-c":"objectivec","obj-c":"objectivec",swift:"swift",go:"go",javascript:"javascript",js:"javascript",typescript:"typescript",ts:"typescript",python:"python",py:"python",java:"java",kotlin:"kotlin",kt:"kotlin",rust:"rust",rs:"rust",dart:"dart",c:"c",cpp:"cpp","c++":"cpp",csharp:"csharp",cs:"csharp",ruby:"ruby",rb:"ruby",markdown:"markdown",md:"markdown",json:"json",yaml:"yaml",xml:"xml",bash:"bash",sh:"bash",shell:"bash",sql:"sql",html:"html",css:"css",text:"text"};function Us(t){if(!t)return t;let s=t;!s.includes(`
49
49
  `)&&s.includes("\\n")&&(s=s.replace(/\\n/g,`
50
- `));const a=s.match(/\\(?=[\[\]{}()*+?^$.|])/g);return a&&a.length>=3&&(s=s.replace(/\\([\[\]{}()*+?^$.|])/g,"$1")),s}const dt=({code:t,language:s="text",className:a="",showLineNumbers:l=!1})=>{const d=fr[s==null?void 0:s.toLowerCase()]||(s==null?void 0:s.toLowerCase())||"text",i=a.includes("!rounded-none"),u=Us(t);return e.jsx("div",{className:`rounded-xl overflow-x-auto text-sm min-w-0 ${a}`,children:e.jsx(ka,{language:d,style:Ca,showLineNumbers:l,customStyle:{margin:0,padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,borderRadius:i?0:"0.75rem",overflowX:"auto"},codeTagProps:{className:"language-highlighted",style:{fontFamily:"ui-monospace, monospace"}},PreTag:"div",children:u})})};let yr=0,oa="";function jr(t){const s=t?"dark":"default";s!==oa&&(Sa.initialize({startOnLoad:!1,theme:s,securityLevel:"loose",fontFamily:"ui-sans-serif, system-ui, -apple-system, sans-serif",...t?{themeVariables:{darkMode:!0,background:"#1e1e1e",primaryColor:"#2d3748",primaryTextColor:"#e2e8f0",primaryBorderColor:"#4a5568",lineColor:"#94a3b8",secondaryColor:"#283040",tertiaryColor:"#1a2332",noteBkgColor:"#283040",noteTextColor:"#e2e8f0",noteBorderColor:"#4a5568"}}:{}}),oa=s)}const Oa=({code:t})=>{const{t:s}=_e(),{isDark:a}=St(),[l,d]=o.useState(""),[i,u]=o.useState("");return o.useEffect(()=>{let p=!1;const n=`mermaid_${yr++}`;async function g(){var f;jr(a);try{const{svg:h}=await Sa.render(n,t.trim());p||(d(h),u(""))}catch(h){p||(u((h==null?void 0:h.message)||"Mermaid render failed"),d(""));try{(f=document.getElementById("d"+n))==null||f.remove()}catch{}}}return g(),()=>{p=!0}},[t,a]),i?e.jsx("div",{className:"my-4 p-4 bg-slate-800 text-slate-200 rounded-lg overflow-x-auto text-sm font-mono whitespace-pre-wrap",children:t}):l?e.jsx("div",{className:`my-5 flex justify-center overflow-x-auto rounded-lg border p-4 ${a?"border-slate-700 bg-[#1e1e1e]":"border-slate-200 bg-white"}`,dangerouslySetInnerHTML:{__html:l}}):e.jsx("div",{className:"my-4 flex items-center justify-center py-8 text-slate-400 text-sm",children:s("shared.renderingChart")})};function Ws(t){return!t||typeof t!="string"?t:t.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,"").trim()||t}function vr(t){return!t||typeof t!="string"?t:t.replace(/\\\\n/g,`
50
+ `));const a=s.match(/\\(?=[\[\]{}()*+?^$.|])/g);return a&&a.length>=3&&(s=s.replace(/\\([\[\]{}()*+?^$.|])/g,"$1")),s}const ct=({code:t,language:s="text",className:a="",showLineNumbers:l=!1})=>{const d=fr[s==null?void 0:s.toLowerCase()]||(s==null?void 0:s.toLowerCase())||"text",c=a.includes("!rounded-none"),u=Us(t);return e.jsx("div",{className:`rounded-xl overflow-x-auto text-sm min-w-0 ${a}`,children:e.jsx(ka,{language:d,style:Ca,showLineNumbers:l,customStyle:{margin:0,padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,borderRadius:c?0:"0.75rem",overflowX:"auto"},codeTagProps:{className:"language-highlighted",style:{fontFamily:"ui-monospace, monospace"}},PreTag:"div",children:u})})};let yr=0,oa="";function jr(t){const s=t?"dark":"default";s!==oa&&(Sa.initialize({startOnLoad:!1,theme:s,securityLevel:"loose",fontFamily:"ui-sans-serif, system-ui, -apple-system, sans-serif",...t?{themeVariables:{darkMode:!0,background:"#1e1e1e",primaryColor:"#2d3748",primaryTextColor:"#e2e8f0",primaryBorderColor:"#4a5568",lineColor:"#94a3b8",secondaryColor:"#283040",tertiaryColor:"#1a2332",noteBkgColor:"#283040",noteTextColor:"#e2e8f0",noteBorderColor:"#4a5568"}}:{}}),oa=s)}const Oa=({code:t})=>{const{t:s}=_e(),{isDark:a}=St(),[l,d]=o.useState(""),[c,u]=o.useState("");return o.useEffect(()=>{let p=!1;const n=`mermaid_${yr++}`;async function g(){var f;jr(a);try{const{svg:h}=await Sa.render(n,t.trim());p||(d(h),u(""))}catch(h){p||(u((h==null?void 0:h.message)||"Mermaid render failed"),d(""));try{(f=document.getElementById("d"+n))==null||f.remove()}catch{}}}return g(),()=>{p=!0}},[t,a]),c?e.jsx("div",{className:"my-4 p-4 bg-slate-800 text-slate-200 rounded-lg overflow-x-auto text-sm font-mono whitespace-pre-wrap",children:t}):l?e.jsx("div",{className:`my-5 flex justify-center overflow-x-auto rounded-lg border p-4 ${a?"border-slate-700 bg-[#1e1e1e]":"border-slate-200 bg-white"}`,dangerouslySetInnerHTML:{__html:l}}):e.jsx("div",{className:"my-4 flex items-center justify-center py-8 text-slate-400 text-sm",children:s("shared.renderingChart")})};function Ws(t){return!t||typeof t!="string"?t:t.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,"").trim()||t}function vr(t){return!t||typeof t!="string"?t:t.replace(/\\\\n/g,`
51
51
  `)}function Nr(t){if(!t||typeof t!="string")return t;const s=t.split(`
52
- `),a=[];let l=!1;for(let d=0;d<s.length;d++){const i=s[d];if(/^\s*(`{3,}|~{3,})/.test(i)){l=!l,a.push(i);continue}if(l){a.push(i);continue}const u=s[d+1];i!==""&&u!==void 0&&u!==""?a.push(i+" "):a.push(i)}return a.join(`
52
+ `),a=[];let l=!1;for(let d=0;d<s.length;d++){const c=s[d];if(/^\s*(`{3,}|~{3,})/.test(c)){l=!l,a.push(c);continue}if(l){a.push(c);continue}const u=s[d+1];c!==""&&u!==void 0&&u!==""?a.push(c+" "):a.push(c)}return a.join(`
53
53
  `)}const wr=/^\s*(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|gitGraph|mindmap|timeline|journey|quadrantChart|sankey|xychart|block)\b/i;function kr(t){const s=[],a=t.split(`
54
- `);let l=[],d=!1,i=!1,u=[];for(let p=0;p<a.length;p++){const n=a[p],g=/^\s*(`{3,}|~{3,})(.*)$/.exec(n);if(g&&!i&&!d)if(g[2].trim().toLowerCase()==="mermaid"){l.length>0&&(s.push({type:"markdown",content:l.join(`
55
- `)}),l=[]),d=!0,u=[];continue}else{i=!0,l.push(n);continue}if(d&&g){s.push({type:"mermaid",content:u.join(`
56
- `)}),d=!1,u=[];continue}if(i&&g){i=!1,l.push(n);continue}d?u.push(n):l.push(n)}return d&&u.length>0&&s.push({type:"mermaid",content:u.join(`
54
+ `);let l=[],d=!1,c=!1,u=[];for(let p=0;p<a.length;p++){const n=a[p],g=/^\s*(`{3,}|~{3,})(.*)$/.exec(n);if(g&&!c&&!d)if(g[2].trim().toLowerCase()==="mermaid"){l.length>0&&(s.push({type:"markdown",content:l.join(`
55
+ `)}),l=[]),d=!0,u=[];continue}else{c=!0,l.push(n);continue}if(d&&g){s.push({type:"mermaid",content:u.join(`
56
+ `)}),d=!1,u=[];continue}if(c&&g){c=!1,l.push(n);continue}d?u.push(n):l.push(n)}return d&&u.length>0&&s.push({type:"mermaid",content:u.join(`
57
57
  `)}),l.length>0&&s.push({type:"markdown",content:l.join(`
58
- `)}),s}const Cr=t=>({pre({children:s}){return e.jsx("div",{className:"min-w-0",children:s})},code({node:s,className:a,children:l,...d}){const i=/language-(\w+)/.exec(a||""),u=Array.isArray(l)?l.join(""):String(l),p=u.replace(/\n$/,""),n=u.includes(`
59
- `)||!!i;return n&&wr.test(p)?e.jsx(Oa,{code:p}):n&&i?e.jsx(dt,{code:p,language:i[1],showLineNumbers:t}):n?e.jsx(dt,{code:p,language:"text",showLineNumbers:t}):e.jsx("code",{className:"px-1.5 py-0.5 bg-slate-100 text-slate-800 rounded text-[0.9em] font-mono border border-slate-200/60",...d,children:l})},p:({children:s})=>e.jsx("p",{className:"mb-4 leading-7 last:mb-0",children:s}),h1:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h1",{id:l,className:"text-[1.75rem] font-bold mb-4 mt-8 first:mt-0 pb-2 border-b border-slate-200/70 text-slate-900 leading-tight scroll-mt-20",...a,children:s})},h2:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h2",{id:l,className:"text-xl font-bold mb-3 mt-8 pb-1.5 border-b border-slate-100 text-slate-800 leading-snug scroll-mt-20",...a,children:s})},h3:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h3",{id:l,className:"text-lg font-semibold mb-2 mt-6 text-slate-800 leading-snug scroll-mt-20",...a,children:s})},h4:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h4",{id:l,className:"text-base font-semibold mb-2 mt-5 text-slate-700 scroll-mt-20",...a,children:s})},strong:({children:s})=>e.jsx("strong",{className:"font-semibold text-slate-900",children:s}),em:({children:s})=>e.jsx("em",{className:"italic text-slate-600",children:s}),del:({children:s})=>e.jsx("del",{className:"line-through text-slate-400",children:s}),hr:()=>e.jsx("hr",{className:"my-8 border-0 h-px bg-slate-200"}),ul:({children:s})=>e.jsx("ul",{className:"list-disc pl-6 mb-4 space-y-1.5 marker:text-slate-400",children:s}),ol:({children:s})=>e.jsx("ol",{className:"list-decimal pl-6 mb-4 space-y-1.5 marker:text-slate-500",children:s}),li:({children:s,...a})=>{var i,u,p,n;const l=a.node,d=((u=(i=l==null?void 0:l.children)==null?void 0:i[0])==null?void 0:u.type)==="element"&&((n=(p=l==null?void 0:l.children)==null?void 0:p[0])==null?void 0:n.tagName)==="input";return e.jsx("li",{className:`leading-7 ${d?"list-none -ml-6 flex items-start gap-2":""}`,children:s})},blockquote:({children:s})=>e.jsx("blockquote",{className:"border-l-4 border-blue-300 bg-blue-50/40 pl-4 pr-3 py-2 my-4 text-slate-600 rounded-r-lg [&>p]:mb-2 [&>p:last-child]:mb-0",children:s}),a:({href:s,children:a})=>s!=null&&s.startsWith("#")?e.jsx("a",{href:s,className:"text-blue-600 hover:text-blue-700 hover:underline underline-offset-2 decoration-blue-300/70 transition-colors",children:a}):e.jsx("a",{href:s,className:"text-blue-600 hover:text-blue-700 hover:underline underline-offset-2 decoration-blue-300/70 transition-colors",target:"_blank",rel:"noopener noreferrer",children:a}),img:({src:s,alt:a})=>e.jsx("img",{src:s,alt:a||"",className:"max-w-full h-auto rounded-lg border border-slate-200 my-4",loading:"lazy"}),table:({children:s})=>e.jsx("div",{className:"my-5 overflow-x-auto rounded-lg border border-slate-200",children:e.jsx("table",{className:"w-full border-collapse text-sm",children:s})}),thead:({children:s})=>e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:s}),tbody:({children:s})=>e.jsx("tbody",{className:"divide-y divide-slate-100",children:s}),tr:({children:s})=>e.jsx("tr",{className:"hover:bg-slate-50/50 transition-colors",children:s}),th:({children:s})=>e.jsx("th",{className:"px-4 py-2.5 text-left text-xs font-semibold text-slate-600 uppercase tracking-wider",children:s}),td:({children:s})=>e.jsx("td",{className:"px-4 py-2.5 text-slate-700 align-top",children:s}),input:({checked:s})=>e.jsx("input",{type:"checkbox",checked:s,readOnly:!0,className:"mt-1 w-4 h-4 rounded border-slate-300 text-blue-600 cursor-default"})}),gt=({content:t,className:s="",showLineNumbers:a=!1,stripFrontmatter:l=!1})=>{const d=o.useMemo(()=>Cr(a),[a]),i=o.useMemo(()=>{let u=l?Ws(t):t;return u=vr(u),u=Nr(u),kr(u)},[t,l]);return e.jsx("div",{className:`markdown-body text-slate-700 ${s}`,children:i.map((u,p)=>u.type==="mermaid"?e.jsx(Oa,{code:u.content},`mermaid-${p}`):e.jsx(al,{remarkPlugins:[ll],components:d,children:u.content},`md-${p}`))})},Ka="asd-chat-topics",Sr=50;function Ar(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}function Dr(t){const s=t.find(l=>l.role==="user");if(!s)return"新话题";const a=s.content.trim().replace(/\n/g," ");return a.length>30?a.slice(0,30)+"…":a}function Ir(){try{const t=localStorage.getItem(Ka);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s:[]}catch{return[]}}function Rr(t){try{const s=t.slice(0,Sr);localStorage.setItem(Ka,JSON.stringify(s))}catch(s){console.warn("[ChatTopics] localStorage save failed:",s)}}function Ua(){const[t,s]=o.useState(()=>Ir()),[a,l]=o.useState(null),d=o.useRef(t);o.useEffect(()=>{d.current=t},[t]);const i=o.useCallback(x=>{s(c=>{const j=typeof x=="function"?x(c):x;return Rr(j),j})},[]),u=o.useCallback(x=>{const c=Ar(),j={id:c,title:x||"新话题",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return i(w=>[j,...w]),l(c),c},[i]),p=o.useCallback(x=>{i(c=>c.filter(j=>j.id!==x)),l(c=>c===x?null:c)},[i]),n=o.useCallback((x,c)=>{i(j=>{const w=j.findIndex(G=>G.id===x);if(w<0)return j;const C={...j[w],messages:c,updatedAt:Date.now()},E=Dr(c);E!=="新话题"&&(C.title=E);const S=[...j];return S[w]=C,S.splice(w,1),S.unshift(C),S})},[i]),g=o.useCallback(x=>d.current.find(c=>c.id===x),[]),f=o.useCallback(x=>{l(x)},[]),h=t.find(x=>x.id===a)??null;return{topics:t,activeTopicId:a,activeTopic:h,createTopic:u,deleteTopic:p,saveTopic:n,getTopic:g,switchTopic:f,setActiveTopicId:l}}function Tr(t,s){const a=`chatStream.tools.${s}`,l=t(a);return l===a?s:l}function Er(t,s,a){if(!a)return"";switch(s){case"read_project_file":{const l=a.filePath||(Array.isArray(a.filePaths)?a.filePaths[0]:"");if(!l)return"";const d=String(l).split("/").pop()||l,i=Array.isArray(a.filePaths)&&a.filePaths.length>1?t("chatStream.andNFiles",{n:a.filePaths.length}):"";return`${d}${i}`}case"list_project_structure":{const l=a.directory||a.path||"";return l?String(l):""}case"search_project_code":{const l=a.patterns||a.pattern||a.query||"";return Array.isArray(l)?l.slice(0,2).join(", ")+(l.length>2?" …":""):String(l).slice(0,40)}case"semantic_search_code":case"search_knowledge":case"search_recipes":case"search_candidates":{const l=a.query||a.keyword||"";return String(l).slice(0,40)}case"get_class_info":case"get_protocol_info":return a.className||a.name||a.protocolName||"";case"get_file_summary":{const l=a.filePath||"";return l&&String(l).split("/").pop()||""}case"summarize_code":case"analyze_code":{const l=a.language||"";return l?`${l}`:""}case"get_class_hierarchy":return a.rootClass||"";case"check_duplicate":return a.title||"";default:return""}}function ia(t,s,a){const l=Tr(t,s),d=Er(t,s,a);return d?`${l}: ${d}`:l}function Wa(t,s,a){const l=[],d=[];let i="";function u(n){s(g=>g.map(f=>f.id===t?{...f,content:n}:f))}function p(n){switch(n.type){case"step:start":{const g=n.phase==="user"?"":` [${n.phase}]`,f=a("chatStream.stepProgress",{step:n.step,maxSteps:n.maxSteps})+g+"...",h=l.length>0?l.join(`
58
+ `)}),s}const Cr=t=>({pre({children:s}){return e.jsx("div",{className:"min-w-0",children:s})},code({node:s,className:a,children:l,...d}){const c=/language-(\w+)/.exec(a||""),u=Array.isArray(l)?l.join(""):String(l),p=u.replace(/\n$/,""),n=u.includes(`
59
+ `)||!!c;return n&&wr.test(p)?e.jsx(Oa,{code:p}):n&&c?e.jsx(ct,{code:p,language:c[1],showLineNumbers:t}):n?e.jsx(ct,{code:p,language:"text",showLineNumbers:t}):e.jsx("code",{className:"px-1.5 py-0.5 bg-slate-100 text-slate-800 rounded text-[0.9em] font-mono border border-slate-200/60",...d,children:l})},p:({children:s})=>e.jsx("p",{className:"mb-4 leading-7 last:mb-0",children:s}),h1:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h1",{id:l,className:"text-[1.75rem] font-bold mb-4 mt-8 first:mt-0 pb-2 border-b border-slate-200/70 text-slate-900 leading-tight scroll-mt-20",...a,children:s})},h2:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h2",{id:l,className:"text-xl font-bold mb-3 mt-8 pb-1.5 border-b border-slate-100 text-slate-800 leading-snug scroll-mt-20",...a,children:s})},h3:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h3",{id:l,className:"text-lg font-semibold mb-2 mt-6 text-slate-800 leading-snug scroll-mt-20",...a,children:s})},h4:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h4",{id:l,className:"text-base font-semibold mb-2 mt-5 text-slate-700 scroll-mt-20",...a,children:s})},strong:({children:s})=>e.jsx("strong",{className:"font-semibold text-slate-900",children:s}),em:({children:s})=>e.jsx("em",{className:"italic text-slate-600",children:s}),del:({children:s})=>e.jsx("del",{className:"line-through text-slate-400",children:s}),hr:()=>e.jsx("hr",{className:"my-8 border-0 h-px bg-slate-200"}),ul:({children:s})=>e.jsx("ul",{className:"list-disc pl-6 mb-4 space-y-1.5 marker:text-slate-400",children:s}),ol:({children:s})=>e.jsx("ol",{className:"list-decimal pl-6 mb-4 space-y-1.5 marker:text-slate-500",children:s}),li:({children:s,...a})=>{var c,u,p,n;const l=a.node,d=((u=(c=l==null?void 0:l.children)==null?void 0:c[0])==null?void 0:u.type)==="element"&&((n=(p=l==null?void 0:l.children)==null?void 0:p[0])==null?void 0:n.tagName)==="input";return e.jsx("li",{className:`leading-7 ${d?"list-none -ml-6 flex items-start gap-2":""}`,children:s})},blockquote:({children:s})=>e.jsx("blockquote",{className:"border-l-4 border-blue-300 bg-blue-50/40 pl-4 pr-3 py-2 my-4 text-slate-600 rounded-r-lg [&>p]:mb-2 [&>p:last-child]:mb-0",children:s}),a:({href:s,children:a})=>s!=null&&s.startsWith("#")?e.jsx("a",{href:s,className:"text-blue-600 hover:text-blue-700 hover:underline underline-offset-2 decoration-blue-300/70 transition-colors",children:a}):e.jsx("a",{href:s,className:"text-blue-600 hover:text-blue-700 hover:underline underline-offset-2 decoration-blue-300/70 transition-colors",target:"_blank",rel:"noopener noreferrer",children:a}),img:({src:s,alt:a})=>e.jsx("img",{src:s,alt:a||"",className:"max-w-full h-auto rounded-lg border border-slate-200 my-4",loading:"lazy"}),table:({children:s})=>e.jsx("div",{className:"my-5 overflow-x-auto rounded-lg border border-slate-200",children:e.jsx("table",{className:"w-full border-collapse text-sm",children:s})}),thead:({children:s})=>e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:s}),tbody:({children:s})=>e.jsx("tbody",{className:"divide-y divide-slate-100",children:s}),tr:({children:s})=>e.jsx("tr",{className:"hover:bg-slate-50/50 transition-colors",children:s}),th:({children:s})=>e.jsx("th",{className:"px-4 py-2.5 text-left text-xs font-semibold text-slate-600 uppercase tracking-wider",children:s}),td:({children:s})=>e.jsx("td",{className:"px-4 py-2.5 text-slate-700 align-top",children:s}),input:({checked:s})=>e.jsx("input",{type:"checkbox",checked:s,readOnly:!0,className:"mt-1 w-4 h-4 rounded border-slate-300 text-blue-600 cursor-default"})}),gt=({content:t,className:s="",showLineNumbers:a=!1,stripFrontmatter:l=!1})=>{const d=o.useMemo(()=>Cr(a),[a]),c=o.useMemo(()=>{let u=l?Ws(t):t;return u=vr(u),u=Nr(u),kr(u)},[t,l]);return e.jsx("div",{className:`markdown-body text-slate-700 ${s}`,children:c.map((u,p)=>u.type==="mermaid"?e.jsx(Oa,{code:u.content},`mermaid-${p}`):e.jsx(al,{remarkPlugins:[ll],components:d,children:u.content},`md-${p}`))})},Ka="asd-chat-topics",Sr=50;function Ar(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}function Dr(t){const s=t.find(l=>l.role==="user");if(!s)return"新话题";const a=s.content.trim().replace(/\n/g," ");return a.length>30?a.slice(0,30)+"…":a}function Ir(){try{const t=localStorage.getItem(Ka);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s:[]}catch{return[]}}function Rr(t){try{const s=t.slice(0,Sr);localStorage.setItem(Ka,JSON.stringify(s))}catch(s){console.warn("[ChatTopics] localStorage save failed:",s)}}function Ua(){const[t,s]=o.useState(()=>Ir()),[a,l]=o.useState(null),d=o.useRef(t);o.useEffect(()=>{d.current=t},[t]);const c=o.useCallback(x=>{s(i=>{const y=typeof x=="function"?x(i):x;return Rr(y),y})},[]),u=o.useCallback(x=>{const i=Ar(),y={id:i,title:x||"新话题",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return c(k=>[y,...k]),l(i),i},[c]),p=o.useCallback(x=>{c(i=>i.filter(y=>y.id!==x)),l(i=>i===x?null:i)},[c]),n=o.useCallback((x,i)=>{c(y=>{const k=y.findIndex(G=>G.id===x);if(k<0)return y;const w={...y[k],messages:i,updatedAt:Date.now()},T=Dr(i);T!=="新话题"&&(w.title=T);const A=[...y];return A[k]=w,A.splice(k,1),A.unshift(w),A})},[c]),g=o.useCallback(x=>d.current.find(i=>i.id===x),[]),f=o.useCallback(x=>{l(x)},[]),h=t.find(x=>x.id===a)??null;return{topics:t,activeTopicId:a,activeTopic:h,createTopic:u,deleteTopic:p,saveTopic:n,getTopic:g,switchTopic:f,setActiveTopicId:l}}function Tr(t,s){const a=`chatStream.tools.${s}`,l=t(a);return l===a?s:l}function Er(t,s,a){if(!a)return"";switch(s){case"read_project_file":{const l=a.filePath||(Array.isArray(a.filePaths)?a.filePaths[0]:"");if(!l)return"";const d=String(l).split("/").pop()||l,c=Array.isArray(a.filePaths)&&a.filePaths.length>1?t("chatStream.andNFiles",{n:a.filePaths.length}):"";return`${d}${c}`}case"list_project_structure":{const l=a.directory||a.path||"";return l?String(l):""}case"search_project_code":{const l=a.patterns||a.pattern||a.query||"";return Array.isArray(l)?l.slice(0,2).join(", ")+(l.length>2?" …":""):String(l).slice(0,40)}case"semantic_search_code":case"search_knowledge":case"search_recipes":case"search_candidates":{const l=a.query||a.keyword||"";return String(l).slice(0,40)}case"get_class_info":case"get_protocol_info":return a.className||a.name||a.protocolName||"";case"get_file_summary":{const l=a.filePath||"";return l&&String(l).split("/").pop()||""}case"summarize_code":case"analyze_code":{const l=a.language||"";return l?`${l}`:""}case"get_class_hierarchy":return a.rootClass||"";case"check_duplicate":return a.title||"";default:return""}}function ia(t,s,a){const l=Tr(t,s),d=Er(t,s,a);return d?`${l}: ${d}`:l}function Wa(t,s,a){const l=[],d=[];let c="";function u(n){s(g=>g.map(f=>f.id===t?{...f,content:n}:f))}function p(n){switch(n.type){case"step:start":{const g=n.phase==="user"?"":` [${n.phase}]`,f=a("chatStream.stepProgress",{step:n.step,maxSteps:n.maxSteps})+g+"...",h=l.length>0?l.join(`
60
60
  `)+`
61
61
 
62
62
  `+f:f;u(h);break}case"tool:start":{l.push(`🔧 ${ia(a,n.tool,n.args)}...`),d.push({tool:n.tool,args:n.args}),u(l.join(`
63
63
  `));break}case"tool:end":{const g=l.length-1;if(g>=0){const f=d[g]||{tool:n.tool},h=ia(a,f.tool,f.args);if(n.status==="error"||n.error)l[g]=`❌ ${h} ${a("chatStream.toolFailed")} (${n.duration}ms)`;else{const x=n.resultSize>1e3?`${(n.resultSize/1024).toFixed(1)}KB`:a("chatStream.toolResultChars",{size:n.resultSize});l[g]=`✅ ${h} → ${x} (${n.duration}ms)`}u(l.join(`
64
- `))}break}case"text:start":{i="";break}case"text:delta":{i+=n.delta||"";const g=l.length>0?l.join(`
64
+ `))}break}case"text:start":{c="";break}case"text:delta":{c+=n.delta||"";const g=l.length>0?l.join(`
65
65
  `)+`
66
66
 
67
67
  ---
68
68
 
69
- `:"";u(g+i);break}}}return{onEvent:p,getState:()=>({answerText:i,toolLogs:l})}}const Va=o.createContext({openChat:()=>{},openRefine:()=>{},close:()=>{},toggle:()=>{},newTopic:()=>{},isOpen:!1}),ds=()=>o.useContext(Va),$t=()=>Math.random().toString(36).substring(2,10),Pr=[{key:"description",labelKey:"globalChat.refineFields.summary"},{key:"pattern",labelKey:"globalChat.refineFields.code"},{key:"markdown",labelKey:"globalChat.refineFields.markdown"},{key:"rationale",labelKey:"globalChat.refineFields.rationale"},{key:"tags",labelKey:"globalChat.refineFields.tags",format:t=>Array.isArray(t)?t.join(", "):String(t||"")},{key:"confidence",labelKey:"globalChat.refineFields.confidence",format:t=>String(t??"—")},{key:"aiInsight",labelKey:"globalChat.refineFields.aiInsights"},{key:"agentNotes",labelKey:"globalChat.refineFields.agentNotes",format:t=>Array.isArray(t)?t.join(`
70
- `):String(t||"")},{key:"relations",labelKey:"globalChat.refineFields.relations",format:t=>JSON.stringify(t||{},null,2)}];function Lr(t,s,a){const l=[];for(const d of Pr){const i=d.format||(n=>String(n??"")),u=i(t[d.key]),p=i(s[d.key]);p&&p!==u&&l.push({field:d.key,label:a(d.labelKey),before:u,after:p})}return l}function ca(t){var s,a,l,d;return{title:t.title||"",description:t.description||"",pattern:((s=t.content)==null?void 0:s.pattern)||"",markdown:((a=t.content)==null?void 0:a.markdown)||"",rationale:((l=t.content)==null?void 0:l.rationale)||"",tags:t.tags||[],confidence:((d=t.reasoning)==null?void 0:d.confidence)??.6,relations:t.relations||{},aiInsight:t.aiInsight||null,agentNotes:t.agentNotes||null}}const Mr=({diff:t,excludedFields:s=[],onToggleField:a})=>{const{t:l}=_e();return t.length===0?e.jsx("p",{className:"text-xs text-slate-400 italic py-2",children:l("globalChat.diff.noChanges")}):e.jsx("div",{className:"space-y-2 mt-2",children:t.map(d=>{const i=s.includes(d.field);return e.jsxs("div",{className:`border rounded-lg overflow-hidden transition-opacity ${i?"border-slate-100 opacity-45":"border-slate-200"}`,children:[e.jsxs("div",{className:`px-2.5 py-1.5 border-b flex items-center gap-1.5 ${i?"bg-slate-50/50 border-slate-100":"bg-slate-50 border-slate-200"}`,children:[e.jsx(Ta,{size:10,className:i?"text-slate-300":"text-emerald-500"}),e.jsx("span",{className:`text-[10px] font-bold flex-1 ${i?"text-slate-400 line-through":"text-slate-600"}`,children:d.label}),a&&(i?e.jsx("button",{onClick:()=>a(d.field),className:"px-2 py-0.5 text-[9px] font-bold rounded-full bg-slate-200 text-slate-500 hover:bg-emerald-100 hover:text-emerald-600 transition-colors",title:l("globalChat.diff.excludedRestore"),children:l("globalChat.diff.excludedRestore")}):e.jsxs("button",{onClick:()=>a(d.field),className:"group flex items-center gap-0.5 px-1.5 py-0.5 text-[9px] font-medium rounded-full text-slate-400 hover:bg-red-50 hover:text-red-500 transition-colors",title:l("globalChat.diff.exclude"),children:[e.jsx(Xe,{size:10,className:"opacity-60 group-hover:opacity-100"}),l("globalChat.diff.exclude")]}))]}),!i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-2 bg-red-50/30 border-b border-slate-200",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:l("globalChat.diff.before")}),e.jsx("pre",{className:"text-[11px] text-slate-600 whitespace-pre-wrap break-words max-h-40 overflow-auto font-mono leading-relaxed scrollbar-light",children:d.before||e.jsx("span",{className:"italic text-slate-300",children:l("globalChat.diff.empty")})})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/30",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:l("globalChat.diff.after")}),e.jsx("pre",{className:"text-[11px] text-slate-700 whitespace-pre-wrap break-words max-h-40 overflow-auto font-mono leading-relaxed scrollbar-light",children:d.after})]})]})]},d.field)})})},Ja=o.createContext(null),Fr=({children:t})=>{const{t:s}=_e(),[a,l]=o.useState(!1),[d,i]=o.useState([]),[u,p]=o.useState(!1),[n,g]=o.useState(!1),[f,h]=o.useState(null),[x,c]=o.useState(new Set),[j,w]=o.useState(""),C=o.useRef([]),E=!!f,S=f?f.candidateIds[f.currentIdx]:null,G=f?f.candidates.find(_=>_.id===S):void 0,z=f?f.candidateIds.length>1:!1;o.useEffect(()=>{f&&G&&(i(_=>[..._,{id:$t(),role:"system",content:s("globalChat.system.refinePrefix",{title:G.title,description:G.description||s("globalChat.system.noDescription")}),timestamp:Date.now()}]),w(""))},[f==null?void 0:f.currentIdx]);const P=o.useCallback(()=>{h(null),l(!0)},[]),Z=o.useCallback(_=>{h({..._,currentIdx:0}),c(new Set),i([]),C.current=[],l(!0)},[]),X=o.useCallback(()=>l(!1),[]),H=o.useCallback(()=>l(_=>!_),[]),q=o.useCallback(()=>{i([]),C.current=[],w(""),h(null),c(new Set)},[]),R={openChat:P,openRefine:Z,close:X,toggle:H,newTopic:q,isOpen:a},M={messages:d,setMessages:i,loading:u,setLoading:p,applying:n,setApplying:g,refineCtx:f,setRefineCtx:h,applied:x,setApplied:c,lastPrompt:j,setLastPrompt:w,chatHistoryRef:C,isRefineMode:E,currentRefineId:S,currentRefineCandidate:G,isBatchRefine:z,close:X};return e.jsx(Va.Provider,{value:R,children:e.jsx(Ja.Provider,{value:M,children:t})})},zr=()=>{const{t,lang:s}=_e(),a=o.useContext(Ja),{messages:l,setMessages:d,loading:i,setLoading:u,applying:p,setApplying:n,refineCtx:g,setRefineCtx:f,applied:h,setApplied:x,lastPrompt:c,setLastPrompt:j,chatHistoryRef:w,isRefineMode:C,currentRefineId:E,currentRefineCandidate:S,isBatchRefine:G,close:z}=a,P=o.useRef(null),Z=o.useRef(null),[X,H]=o.useState(""),q=Ua(),R=o.useRef(null),M=o.useRef(!1);o.useEffect(()=>{if(C&&S){M.current=!0;const v=q.createTopic(t("globalChat.refineTopicPrefix",{title:S.title||t("globalChat.untitled")}));R.current=v,setTimeout(()=>{M.current=!1},50)}},[g]),o.useEffect(()=>{M.current||R.current&&l.length>0&&q.saveTopic(R.current,l)},[l]);const _=o.useCallback(()=>{if(!R.current){M.current=!0;const v=q.createTopic();R.current=v,setTimeout(()=>{M.current=!1},50)}},[q]);o.useEffect(()=>{var v;(v=P.current)==null||v.scrollIntoView({behavior:"smooth"})},[l,i]),o.useEffect(()=>{setTimeout(()=>{var v;return(v=Z.current)==null?void 0:v.focus()},200)},[]);const m=C&&E&&l.some(v=>{if(v.role!=="assistant"||!v.diff||v.diff.length===0)return!1;const ee=v.excludedFields||[];return v.diff.some(ae=>!ee.includes(ae.field))})&&!h.has(E),N=o.useCallback((v,ee)=>{d(ae=>ae.map(ue=>{if(ue.id!==v)return ue;const fe=ue.excludedFields||[],he=fe.includes(ee)?fe.filter(ce=>ce!==ee):[...fe,ee];return{...ue,excludedFields:he}}))},[]),y=o.useRef(null),W=o.useCallback(async()=>{const v=X.trim();if(!(!v||i)){if(C||_(),H(""),d(ee=>[...ee,{id:$t(),role:"user",content:v,timestamp:Date.now()}]),u(!0),C&&E){j(v);const ee=$t();d(ue=>[...ue,{id:ee,role:"assistant",content:t("globalChat.system.refining"),timestamp:Date.now()}]);const ae=new AbortController;y.current=ae;try{const ue=await se.refinePreviewStream(E,v,ce=>{if(ce.type==="data:progress"){const je=ce.message||ce.stage||t("globalChat.system.processing");d($=>$.map(K=>K.id===ee?{...K,content:`🔄 ${je}`}:K))}},ae.signal),fe=ue.before||(S?ca(S):{}),he=Lr(fe,ue.after||{},t);d(ce=>ce.map(je=>je.id===ee?{...je,content:he.length>0?t("globalChat.previewGenerated",{count:he.length}):t("globalChat.noChangeHint"),diff:he.length>0?he:void 0,preview:he.length>0?ue.preview??void 0:void 0,excludedFields:[]}:je))}catch(ue){ue.name==="AbortError"?d(fe=>fe.map(he=>he.id===ee?{...he,content:t("globalChat.system.cancelled")}:he)):d(fe=>fe.map(he=>{var ce,je;return he.id===ee?{...he,content:t("globalChat.refinePreviewFailed",{error:((je=(ce=ue.response)==null?void 0:ce.data)==null?void 0:je.error)||ue.message})}:he}))}finally{y.current=null}}else{w.current.push({role:"user",content:v});const ee=$t();d(ce=>[...ce,{id:ee,role:"assistant",content:t("globalChat.system.thinking"),timestamp:Date.now()}]);const ae=new AbortController;y.current=ae;const{onEvent:ue,getState:fe}=Wa(ee,d,t);let he="";try{const je=(await se.chatStream(v,w.current,$=>{ue($),he=fe().answerText},ae.signal,s)).text||he;w.current.push({role:"model",content:je}),d($=>$.map(K=>K.id===ee?{...K,content:je}:K))}catch(ce){if(ce.name==="AbortError"){const{answerText:je,toolLogs:$}=fe(),K=je||($.length>0?$.join(`
69
+ `:"";u(g+c);break}}}return{onEvent:p,getState:()=>({answerText:c,toolLogs:l})}}const Va=o.createContext({openChat:()=>{},openRefine:()=>{},close:()=>{},toggle:()=>{},newTopic:()=>{},isOpen:!1}),ds=()=>o.useContext(Va),$t=()=>Math.random().toString(36).substring(2,10),Pr=[{key:"description",labelKey:"globalChat.refineFields.summary"},{key:"pattern",labelKey:"globalChat.refineFields.code"},{key:"markdown",labelKey:"globalChat.refineFields.markdown"},{key:"rationale",labelKey:"globalChat.refineFields.rationale"},{key:"tags",labelKey:"globalChat.refineFields.tags",format:t=>Array.isArray(t)?t.join(", "):String(t||"")},{key:"confidence",labelKey:"globalChat.refineFields.confidence",format:t=>String(t??"—")},{key:"aiInsight",labelKey:"globalChat.refineFields.aiInsights"},{key:"agentNotes",labelKey:"globalChat.refineFields.agentNotes",format:t=>Array.isArray(t)?t.join(`
70
+ `):String(t||"")},{key:"relations",labelKey:"globalChat.refineFields.relations",format:t=>JSON.stringify(t||{},null,2)}];function Lr(t,s,a){const l=[];for(const d of Pr){const c=d.format||(n=>String(n??"")),u=c(t[d.key]),p=c(s[d.key]);p&&p!==u&&l.push({field:d.key,label:a(d.labelKey),before:u,after:p})}return l}function ca(t){var s,a,l,d;return{title:t.title||"",description:t.description||"",pattern:((s=t.content)==null?void 0:s.pattern)||"",markdown:((a=t.content)==null?void 0:a.markdown)||"",rationale:((l=t.content)==null?void 0:l.rationale)||"",tags:t.tags||[],confidence:((d=t.reasoning)==null?void 0:d.confidence)??.6,relations:t.relations||{},aiInsight:t.aiInsight||null,agentNotes:t.agentNotes||null}}const Mr=({diff:t,excludedFields:s=[],onToggleField:a})=>{const{t:l}=_e();return t.length===0?e.jsx("p",{className:"text-xs text-slate-400 italic py-2",children:l("globalChat.diff.noChanges")}):e.jsx("div",{className:"space-y-2 mt-2",children:t.map(d=>{const c=s.includes(d.field);return e.jsxs("div",{className:`border rounded-lg overflow-hidden transition-opacity ${c?"border-slate-100 opacity-45":"border-slate-200"}`,children:[e.jsxs("div",{className:`px-2.5 py-1.5 border-b flex items-center gap-1.5 ${c?"bg-slate-50/50 border-slate-100":"bg-slate-50 border-slate-200"}`,children:[e.jsx(Ta,{size:10,className:c?"text-slate-300":"text-emerald-500"}),e.jsx("span",{className:`text-[10px] font-bold flex-1 ${c?"text-slate-400 line-through":"text-slate-600"}`,children:d.label}),a&&(c?e.jsx("button",{onClick:()=>a(d.field),className:"px-2 py-0.5 text-[9px] font-bold rounded-full bg-slate-200 text-slate-500 hover:bg-emerald-100 hover:text-emerald-600 transition-colors",title:l("globalChat.diff.excludedRestore"),children:l("globalChat.diff.excludedRestore")}):e.jsxs("button",{onClick:()=>a(d.field),className:"group flex items-center gap-0.5 px-1.5 py-0.5 text-[9px] font-medium rounded-full text-slate-400 hover:bg-red-50 hover:text-red-500 transition-colors",title:l("globalChat.diff.exclude"),children:[e.jsx(Xe,{size:10,className:"opacity-60 group-hover:opacity-100"}),l("globalChat.diff.exclude")]}))]}),!c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-2 bg-red-50/30 border-b border-slate-200",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:l("globalChat.diff.before")}),e.jsx("pre",{className:"text-[11px] text-slate-600 whitespace-pre-wrap break-words max-h-40 overflow-auto font-mono leading-relaxed scrollbar-light",children:d.before||e.jsx("span",{className:"italic text-slate-300",children:l("globalChat.diff.empty")})})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/30",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:l("globalChat.diff.after")}),e.jsx("pre",{className:"text-[11px] text-slate-700 whitespace-pre-wrap break-words max-h-40 overflow-auto font-mono leading-relaxed scrollbar-light",children:d.after})]})]})]},d.field)})})},Ja=o.createContext(null),Fr=({children:t})=>{const{t:s}=_e(),[a,l]=o.useState(!1),[d,c]=o.useState([]),[u,p]=o.useState(!1),[n,g]=o.useState(!1),[f,h]=o.useState(null),[x,i]=o.useState(new Set),[y,k]=o.useState(""),w=o.useRef([]),T=!!f,A=f?f.candidateIds[f.currentIdx]:null,G=f?f.candidates.find($=>$.id===A):void 0,_=f?f.candidateIds.length>1:!1;o.useEffect(()=>{f&&G&&(c($=>[...$,{id:$t(),role:"system",content:s("globalChat.system.refinePrefix",{title:G.title,description:G.description||s("globalChat.system.noDescription")}),timestamp:Date.now()}]),k(""))},[f==null?void 0:f.currentIdx]);const E=o.useCallback(()=>{h(null),l(!0)},[]),Z=o.useCallback($=>{h({...$,currentIdx:0}),i(new Set),c([]),w.current=[],l(!0)},[]),X=o.useCallback(()=>l(!1),[]),H=o.useCallback(()=>l($=>!$),[]),q=o.useCallback(()=>{c([]),w.current=[],k(""),h(null),i(new Set)},[]),I={openChat:E,openRefine:Z,close:X,toggle:H,newTopic:q,isOpen:a},L={messages:d,setMessages:c,loading:u,setLoading:p,applying:n,setApplying:g,refineCtx:f,setRefineCtx:h,applied:x,setApplied:i,lastPrompt:y,setLastPrompt:k,chatHistoryRef:w,isRefineMode:T,currentRefineId:A,currentRefineCandidate:G,isBatchRefine:_,close:X};return e.jsx(Va.Provider,{value:I,children:e.jsx(Ja.Provider,{value:L,children:t})})},zr=()=>{const{t,lang:s}=_e(),a=o.useContext(Ja),{messages:l,setMessages:d,loading:c,setLoading:u,applying:p,setApplying:n,refineCtx:g,setRefineCtx:f,applied:h,setApplied:x,lastPrompt:i,setLastPrompt:y,chatHistoryRef:k,isRefineMode:w,currentRefineId:T,currentRefineCandidate:A,isBatchRefine:G,close:_}=a,E=o.useRef(null),Z=o.useRef(null),[X,H]=o.useState(""),q=Ua(),I=o.useRef(null),L=o.useRef(!1);o.useEffect(()=>{if(w&&A){L.current=!0;const v=q.createTopic(t("globalChat.refineTopicPrefix",{title:A.title||t("globalChat.untitled")}));I.current=v,setTimeout(()=>{L.current=!1},50)}},[g]),o.useEffect(()=>{L.current||I.current&&l.length>0&&q.saveTopic(I.current,l)},[l]);const $=o.useCallback(()=>{if(!I.current){L.current=!0;const v=q.createTopic();I.current=v,setTimeout(()=>{L.current=!1},50)}},[q]);o.useEffect(()=>{var v;(v=E.current)==null||v.scrollIntoView({behavior:"smooth"})},[l,c]),o.useEffect(()=>{setTimeout(()=>{var v;return(v=Z.current)==null?void 0:v.focus()},200)},[]);const m=w&&T&&l.some(v=>{if(v.role!=="assistant"||!v.diff||v.diff.length===0)return!1;const ee=v.excludedFields||[];return v.diff.some(te=>!ee.includes(te.field))})&&!h.has(T),N=o.useCallback((v,ee)=>{d(te=>te.map(de=>{if(de.id!==v)return de;const ve=de.excludedFields||[],fe=ve.includes(ee)?ve.filter(ie=>ie!==ee):[...ve,ee];return{...de,excludedFields:fe}}))},[]),j=o.useRef(null),W=o.useCallback(async()=>{const v=X.trim();if(!(!v||c)){if(w||$(),H(""),d(ee=>[...ee,{id:$t(),role:"user",content:v,timestamp:Date.now()}]),u(!0),w&&T){y(v);const ee=$t();d(de=>[...de,{id:ee,role:"assistant",content:t("globalChat.system.refining"),timestamp:Date.now()}]);const te=new AbortController;j.current=te;try{const de=await ae.refinePreviewStream(T,v,ie=>{if(ie.type==="data:progress"){const be=ie.message||ie.stage||t("globalChat.system.processing");d(B=>B.map(K=>K.id===ee?{...K,content:`🔄 ${be}`}:K))}},te.signal),ve=de.before||(A?ca(A):{}),fe=Lr(ve,de.after||{},t);d(ie=>ie.map(be=>be.id===ee?{...be,content:fe.length>0?t("globalChat.previewGenerated",{count:fe.length}):t("globalChat.noChangeHint"),diff:fe.length>0?fe:void 0,preview:fe.length>0?de.preview??void 0:void 0,excludedFields:[]}:be))}catch(de){de.name==="AbortError"?d(ve=>ve.map(fe=>fe.id===ee?{...fe,content:t("globalChat.system.cancelled")}:fe)):d(ve=>ve.map(fe=>{var ie,be;return fe.id===ee?{...fe,content:t("globalChat.refinePreviewFailed",{error:((be=(ie=de.response)==null?void 0:ie.data)==null?void 0:be.error)||de.message})}:fe}))}finally{j.current=null}}else{k.current.push({role:"user",content:v});const ee=$t();d(ie=>[...ie,{id:ee,role:"assistant",content:t("globalChat.system.thinking"),timestamp:Date.now()}]);const te=new AbortController;j.current=te;const{onEvent:de,getState:ve}=Wa(ee,d,t);let fe="";try{const be=(await ae.chatStream(v,k.current,B=>{de(B),fe=ve().answerText},te.signal,s)).text||fe;k.current.push({role:"model",content:be}),d(B=>B.map(K=>K.id===ee?{...K,content:be}:K))}catch(ie){if(ie.name==="AbortError"){const{answerText:be,toolLogs:B}=ve(),K=be||(B.length>0?B.join(`
71
71
  `)+`
72
72
 
73
- `+t("globalChat.system.cancelled"):t("globalChat.system.cancelled"));je&&w.current.push({role:"model",content:je}),d(xe=>xe.map(L=>L.id===ee?{...L,content:K}:L))}else d(je=>je.map($=>$.id===ee?{...$,content:t("globalChat.requestFailed",{error:ce.message})}:$))}finally{y.current=null}}u(!1)}},[X,i,C,E,S,_]),O=o.useCallback(async()=>{var v,ee,ae,ue;if(!(p||!E||!g)){n(!0);try{const fe=[...l].reverse().find(ce=>ce.role==="assistant"&&ce.preview);let he=fe==null?void 0:fe.preview;if(he&&((v=fe==null?void 0:fe.excludedFields)!=null&&v.length)&&fe.diff){he={...he};const ce=S?ca(S):{};for(const je of fe.excludedFields)je in ce&&(he[je]=ce[je])}await se.refineApply(E,c,he),x(ce=>new Set(ce).add(E)),(ee=g.onCandidateUpdated)==null||ee.call(g,E),d(ce=>[...ce,{id:$t(),role:"system",content:t("globalChat.system.changesApplied"),timestamp:Date.now()}]),re(t("globalChat.applySuccess"),{title:t("globalChat.applySuccessTitle")})}catch(fe){const he=(ue=(ae=fe.response)==null?void 0:ae.data)==null?void 0:ue.error;re(typeof he=="string"?he:(he==null?void 0:he.message)||fe.message,{title:t("globalChat.applyFailed"),type:"error"})}finally{n(!1)}}},[p,E,c,g]),be=o.useCallback(()=>{!g||g.currentIdx>=g.candidateIds.length-1||f(v=>v?{...v,currentIdx:v.currentIdx+1}:null)},[g]),we=o.useCallback(()=>{R.current=null,f(null),d(v=>[...v,{id:$t(),role:"system",content:t("globalChat.system.exitedRefine"),timestamp:Date.now()}])},[]),ye=o.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),W())},[W]);return e.jsxs("aside",{className:"w-[420px] h-full bg-white border-l border-slate-200 flex flex-col shrink-0",children:[e.jsxs("div",{className:"px-4 py-2.5 border-b border-slate-200 flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center",children:C?e.jsx(Qe,{className:"text-emerald-500",size:16}):e.jsx(Lt,{className:"text-blue-600",size:16})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-[13px] font-bold text-slate-800 flex items-center gap-2",children:[t(C?"globalChat.refineTitle":"globalChat.chatTitle"),C&&G&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-emerald-50 text-emerald-600 font-medium",children:[((g==null?void 0:g.currentIdx)??0)+1,"/",g==null?void 0:g.candidateIds.length]})]}),e.jsx("p",{className:"text-[10px] text-slate-400 truncate max-w-[250px]",children:C?(S==null?void 0:S.title)||t("globalChat.refineSubtitle"):t("globalChat.chatSubtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[C&&e.jsx("button",{onClick:we,className:"px-2 py-1 text-[10px] font-medium text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-md transition-colors",children:t("globalChat.exitRefine")}),!C&&l.length>0&&e.jsx("button",{onClick:()=>{R.current=null,d([]),w.current=[],j("")},className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",title:t("globalChat.newTopic"),children:e.jsx(Nt,{size:16,className:"text-slate-400"})}),e.jsx("button",{onClick:z,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",title:t("globalChat.closeChat"),children:e.jsx(Xe,{size:16,className:"text-slate-400"})})]})]}),C&&S&&e.jsx("div",{className:"border-b border-slate-100 bg-emerald-50/30 px-4 py-2 shrink-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-bold text-emerald-700 truncate flex-1",children:S.title}),S.language&&e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100",children:S.language})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 min-h-0 scrollbar-light",children:[l.length===0&&!C&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-10",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-blue-50 border border-blue-100 flex items-center justify-center mb-3",children:e.jsx(Lt,{className:"text-blue-500",size:20})}),e.jsx("h4",{className:"text-sm font-bold text-slate-700 mb-1",children:t("globalChat.emptyTitle")}),e.jsx("p",{className:"text-xs text-slate-400 max-w-[280px] leading-relaxed mb-3",children:t("globalChat.emptyDesc")}),e.jsx("div",{className:"flex flex-wrap gap-1.5 justify-center",children:[t("globalChat.quickPrompts.analyzeArch"),t("globalChat.quickPrompts.findDuplicates"),t("globalChat.quickPrompts.suggestOptimize")].map(v=>e.jsx("button",{onClick:()=>{var ee;H(v),(ee=Z.current)==null||ee.focus()},className:"text-[10px] px-2.5 py-1 rounded-md bg-slate-100 text-slate-600 hover:bg-blue-50 hover:text-blue-700 transition-colors",children:v},v))})]}),C&&l.length<=1&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-2",children:[t("globalChat.refinePrompts.addExamples"),t("globalChat.refinePrompts.optimizeComments"),t("globalChat.refinePrompts.addCaveats"),t("globalChat.refinePrompts.improveSummary"),t("globalChat.refinePrompts.addPerformance")].map(v=>e.jsx("button",{onClick:()=>{var ee;H(v),(ee=Z.current)==null||ee.focus()},className:"text-[10px] px-2.5 py-1 rounded-md bg-emerald-50 text-emerald-700 border border-emerald-200 hover:bg-emerald-100 transition-colors",children:v},v))}),l.map(v=>e.jsx("div",{className:`flex ${v.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[95%] ${v.role==="user"?"bg-blue-600 text-white rounded-2xl rounded-tr-md px-3.5 py-2":v.role==="system"?"bg-slate-50 border border-slate-200 text-slate-600 rounded-2xl px-3.5 py-2 w-full":"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-3.5 py-2.5 shadow-sm w-full"}`,children:[v.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx(rs,{size:12,className:C?"text-emerald-500":"text-blue-500"}),e.jsx("span",{className:`text-[10px] font-bold ${C?"text-emerald-600":"text-blue-600"}`,children:t(C?"globalChat.assistantRefine":"globalChat.assistantChat")})]}),v.role==="assistant"&&!v.diff?e.jsx(gt,{content:v.content,className:"text-xs text-slate-700"}):e.jsx("p",{className:`text-xs leading-relaxed whitespace-pre-wrap ${v.role==="user"?"":v.role==="system"?"text-slate-500":"text-slate-700"}`,children:v.content}),v.diff&&v.diff.length>0&&e.jsx(Mr,{diff:v.diff,excludedFields:v.excludedFields,onToggleField:C&&!h.has(E)?ee=>N(v.id,ee):void 0})]})},v.id)),i&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-3.5 py-2.5 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{size:12,className:`animate-spin ${C?"text-emerald-500":"text-blue-500"}`}),e.jsx("span",{className:"text-xs text-slate-500",children:t(C?"globalChat.loading.analyzing":"globalChat.loading.thinking")}),y.current&&e.jsx("button",{onClick:()=>{var v;return(v=y.current)==null?void 0:v.abort()},className:"ml-1 px-1.5 py-0.5 text-[10px] font-bold text-red-500 border border-red-200 rounded hover:bg-red-50 transition-colors",children:t("globalChat.stopBtn")})]})})}),e.jsx("div",{ref:P})]}),C&&m&&!i&&(()=>{var fe,he;const v=[...l].reverse().find(ce=>ce.role==="assistant"&&ce.diff&&ce.diff.length>0),ee=((fe=v==null?void 0:v.diff)==null?void 0:fe.length)||0,ae=((he=v==null?void 0:v.excludedFields)==null?void 0:he.length)||0,ue=ee-ae;return e.jsxs("div",{className:"px-4 py-2 border-t border-slate-100 bg-emerald-50/50 flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:O,disabled:p,className:"flex items-center gap-1 px-3 py-1.5 text-[11px] font-bold text-white bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700 rounded-lg shadow-sm disabled:opacity-50",children:[p?e.jsx(Fe,{size:11,className:"animate-spin"}):e.jsx(kt,{size:11}),p?t("globalChat.applyingBtn"):ae>0?t("globalChat.confirmApplyN",{i:ue,total:ee}):t("globalChat.confirmApply")]}),e.jsxs("button",{className:"flex items-center gap-1 px-2.5 py-1.5 text-[11px] font-bold text-slate-500 hover:text-slate-700 rounded-lg hover:bg-slate-100 transition-colors",children:[e.jsx(Ra,{size:11})," ",t("globalChat.continueAdjust")]}),G&&h.has(E)&&g.currentIdx<g.candidateIds.length-1&&e.jsxs("button",{onClick:be,className:"flex items-center gap-1 px-2.5 py-1.5 text-[11px] font-bold text-blue-600 hover:text-blue-700 rounded-lg hover:bg-blue-50 transition-colors ml-auto",children:[t("globalChat.nextItem")," ",e.jsx(rt,{size:11})]})]})})(),C&&!m&&!i&&G&&h.has(E)&&g.currentIdx<g.candidateIds.length-1&&e.jsx("div",{className:"px-4 py-2 border-t border-slate-100 flex items-center justify-center shrink-0",children:e.jsxs("button",{onClick:be,className:"flex items-center gap-1 px-3 py-1.5 text-[11px] font-bold text-blue-600 hover:text-blue-700 rounded-lg bg-blue-50 hover:bg-blue-100 transition-colors",children:[t("globalChat.nextItem")," (",((g==null?void 0:g.currentIdx)??0)+2,"/",g==null?void 0:g.candidateIds.length,") ",e.jsx(rt,{size:12})]})}),e.jsxs("div",{className:"px-4 py-2.5 border-t border-slate-200 bg-white shrink-0",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{ref:Z,value:X,onChange:v=>H(v.target.value),onKeyDown:ye,placeholder:t(C?"globalChat.refinePlaceholder":"globalChat.chatPlaceholder"),rows:2,className:`flex-1 px-3 py-2 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 ${C?"focus:ring-emerald-200 focus:border-emerald-400":"focus:ring-blue-200 focus:border-blue-400"} resize-none placeholder:text-slate-300`,disabled:i||p}),e.jsx("button",{onClick:W,disabled:!X.trim()||i||p,className:`self-stretch w-9 flex items-center justify-center rounded-xl bg-gradient-to-r ${C?"from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700":"from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700"} text-white disabled:opacity-40 disabled:cursor-not-allowed transition-all shadow-sm shrink-0`,children:e.jsx(Bs,{size:14})})]}),e.jsx("p",{className:"text-[9px] text-slate-400 mt-1",children:t(C?"globalChat.inputHintRefine":"globalChat.inputHintChat")})]})]})},_r=({searchQuery:t,setSearchQuery:s,setShowCreateModal:a,handleSyncSnippets:l,aiConfig:d,llmReady:i=!0,onOpenLlmConfig:u,onSemanticSearchResults:p,onBeforeAiSwitch:n,onAiConfigChange:g})=>{const{toggle:f,isOpen:h}=ds(),{t:x,lang:c,setLang:j}=_e(),{isDark:w,toggle:C}=St(),[E,S]=o.useState(!1),[G,z]=o.useState(!1),[P,Z]=o.useState([]),[X,H]=o.useState(!1),q=o.useRef(null);o.useEffect(()=>{G&&P.length===0&&se.getAiProviders().then(_=>Z(_)).catch(()=>{})},[G,P.length]),o.useEffect(()=>{const _=m=>{q.current&&!q.current.contains(m.target)&&z(!1)};return document.addEventListener("click",_),()=>document.removeEventListener("click",_)},[]);const R=async()=>{if(t){S(!0);try{const m=((await se.search(t,{mode:"semantic"})).items||[]).map(N=>{var y,W,O;return{name:(N.title||N.name||"")+".md",content:((y=N.content)==null?void 0:y.pattern)||((W=N.content)==null?void 0:W.markdown)||((O=N.content)==null?void 0:O.code)||"",similarity:N.score||0,metadata:{type:"recipe",name:(N.title||N.name||"")+".md"}}});p&&p(m)}catch(_){console.error("Semantic search failed",_),alert(x("header.semanticSearchFailed"))}finally{S(!1)}}},M=async _=>{H(!0);try{n==null||n(),await se.setAiConfig(_.id,_.defaultModel),z(!1),g&&g()}catch(m){console.error("AI config update failed",m),alert(x("header.aiSwitchFailed"))}finally{H(!1)}};return e.jsxs("header",{className:`h-16 ${w?"bg-[#252526] border-b border-[#3e3e42]":"bg-white border-b border-slate-200"} flex items-center justify-between px-8 shrink-0`,children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative w-96",children:[e.jsx(ft,{className:`absolute left-3 top-1/2 -translate-y-1/2 ${w?"text-slate-500":"text-slate-400"}`,size:F.md}),e.jsx("input",{type:"text",placeholder:x("header.searchPlaceholder"),className:`w-full pl-10 pr-4 py-2 ${w?"bg-[#1e1e1e] text-slate-300 placeholder-slate-500":"bg-slate-100 text-slate-900"} border-transparent rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-500/20 transition-all`,value:t,onChange:_=>s(_.target.value),onKeyDown:_=>_.key==="Enter"&&R()})]}),e.jsxs("button",{onClick:R,disabled:!t||E,className:`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-bold transition-all ${E?w?"bg-blue-900/30 text-blue-300":"bg-blue-50 text-blue-400":w?"bg-blue-900/30 text-blue-400 hover:bg-blue-900/50":"bg-blue-50 text-blue-600 hover:bg-blue-100"}`,title:x("header.semanticSearchTitle"),children:[E?e.jsx(Fe,{size:F.sm,className:"animate-spin"}):e.jsx(jl,{size:F.sm}),x("header.semanticSearch")]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[i?d?e.jsxs("div",{className:"relative",ref:q,children:[e.jsxs("button",{type:"button",onClick:_=>{_.stopPropagation(),z(m=>!m)},className:`flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${w?"bg-slate-700 text-slate-300 hover:bg-slate-600":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,title:x("header.clickSwitchAi"),children:[e.jsx(ns,{size:F.sm}),d.provider," / ",d.model,e.jsx(Gt,{size:F.xs,className:G?"rotate-180":""})]}),G&&e.jsxs("div",{className:`absolute top-full right-0 mt-1 py-1 rounded-lg border shadow-lg z-20 min-w-[200px] ${w?"bg-[#252526] border-[#3e3e42]":"bg-white border-slate-200"}`,children:[e.jsx("div",{className:`px-3 py-2 text-xs border-b ${w?"text-slate-400 border-[#3e3e42]":"text-slate-500 border-slate-100"}`,children:x("header.switchAi")}),e.jsx("div",{className:`px-3 py-1.5 text-[11px] border-b ${w?"text-slate-500 border-[#3e3e42]":"text-slate-400 border-slate-100"}`,children:e.jsx("button",{type:"button",onClick:()=>{z(!1),u==null||u()},className:"text-blue-500 hover:underline",children:x("header.editEnvConfig")})}),P.length===0?e.jsx("div",{className:`px-3 py-2 text-xs ${w?"text-slate-500":"text-slate-400"}`,children:x("common.loading")}):P.map(_=>e.jsxs("button",{type:"button",disabled:X,onClick:()=>M(_),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between ${d.provider===_.id?w?"bg-blue-900/30 text-blue-400 font-medium":"bg-blue-50 text-blue-700 font-medium":w?"text-slate-300 hover:bg-slate-700/50":"text-slate-700 hover:bg-slate-50"}`,children:[e.jsx("span",{children:_.label}),d.provider===_.id&&e.jsx("span",{className:"text-xs",children:"✓"})]},_.id))]})]}):null:e.jsxs("button",{type:"button",onClick:u,className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors animate-pulse ${w?"bg-amber-900/30 text-amber-300 border-amber-700 hover:bg-amber-900/50":"bg-amber-50 text-amber-700 border-amber-200 hover:bg-amber-100"}`,title:x("header.aiNotConfigured"),children:[e.jsx(Ea,{size:F.sm}),x("header.configureLlm")]}),e.jsxs("button",{onClick:f,className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-150 ${h?w?"bg-blue-500/20 text-blue-300 ring-1 ring-blue-500/30 hover:bg-blue-500/35 hover:brightness-125":"bg-blue-100 text-blue-700 ring-1 ring-blue-200 hover:bg-blue-200":w?"bg-slate-700 text-slate-300 hover:bg-slate-500 hover:text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,title:x(h?"header.closeAiChat":"header.openAiChat"),children:[e.jsx(Lt,{size:F.sm}),!h&&e.jsx("span",{className:"text-xs",children:x("header.aiChat")})]}),e.jsxs("button",{onClick:()=>a(!0),className:`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-150 border ${w?"bg-slate-200 text-slate-900 border-slate-300 hover:bg-white hover:border-white hover:shadow-[0_0_12px_rgba(255,255,255,0.15)]":"bg-slate-900 text-white border-slate-900 hover:bg-slate-800 hover:border-slate-800"}`,children:[e.jsx(Nt,{size:F.md})," ",x("header.newRecipe")]}),e.jsxs("button",{onClick:l,className:`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-150 border ${w?"bg-blue-500/20 text-blue-300 border-blue-500/30 hover:bg-blue-500/40 hover:text-blue-200 hover:border-blue-400/50":"bg-blue-600 text-white border-blue-600 hover:bg-blue-700 hover:border-blue-700"}`,children:[e.jsx(yt,{size:F.md})," ",x("header.syncSnippets")]}),e.jsxs("button",{onClick:()=>j(c==="zh"?"en":"zh"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-all duration-150 ${w?"bg-slate-700 text-slate-300 hover:bg-slate-500 hover:text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,title:c==="zh"?"Switch to English":x("shared.switchToChinese"),children:[e.jsx(vl,{size:F.sm}),x("header.langSwitch")]}),e.jsx("button",{onClick:C,className:`flex items-center p-2 rounded-lg transition-all duration-150 ${w?"bg-slate-700 text-amber-300 hover:bg-slate-500 hover:text-amber-200":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,title:w?"Light mode":"Dark mode",children:w?e.jsx(Nl,{size:F.sm}):e.jsx(wl,{size:F.sm})})]})]})},$r=({selectedCategory:t,setSelectedCategory:s})=>e.jsx("div",{className:"bg-white border-b border-slate-100 shrink-0 overflow-hidden",children:e.jsx("div",{className:"flex items-center gap-2 overflow-x-auto no-scrollbar px-8 py-3",children:Object.entries(ct).map(([a,l])=>{const d=l.icon,i=t===a;return e.jsxs("button",{onClick:()=>s(a),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-[10px] font-bold transition-all border whitespace-nowrap
74
- ${i?`${l.bg} ${l.color} ${l.border} shadow-sm scale-105`:"bg-white text-slate-400 border-slate-100 hover:border-slate-200 hover:text-slate-600"}`,children:[e.jsx(d,{size:F.xs}),a]},a)})})}),Ya="asd-drawer-wide";function Br(){try{return localStorage.getItem(Ya)==="1"}catch{return!1}}function Vs(){const[t,s]=o.useState(Br),a=o.useCallback(()=>{s(l=>{const d=!l;try{localStorage.setItem(Ya,d?"1":"0")}catch{}return d})},[]);return{isWide:t,toggle:a}}const Js=({currentPage:t,totalPages:s,totalItems:a,pageSize:l,onPageChange:d,onPageSizeChange:i,pageSizeOptions:u=[12,24,48,96]})=>{if(s<=1&&a<=u[0])return null;const{t:p}=_e(),n=(t-1)*l+1,g=Math.min(t*l,a),f=()=>{const h=[];if(s<=7)for(let c=1;c<=s;c++)h.push(c);else if(t<=3){for(let c=1;c<=5;c++)h.push(c);h.push("..."),h.push(s)}else if(t>=s-2){h.push(1),h.push("...");for(let c=s-5+1;c<=s;c++)h.push(c)}else{h.push(1),h.push("...");for(let c=t-1;c<=t+1;c++)h.push(c);h.push("..."),h.push(s)}return h};return e.jsxs("div",{className:"flex items-center justify-between mt-6 px-2",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"text-sm text-slate-500",children:p("pagination.showing",{start:n,end:g,total:a})}),i&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-slate-500",children:p("pagination.perPage")}),e.jsx("select",{value:l,onChange:h=>i(Number(h.target.value)),className:"text-sm border border-slate-200 rounded-md px-2 py-1 bg-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent",children:u.map(h=>e.jsx("option",{value:h,children:h},h))}),e.jsx("span",{className:"text-sm text-slate-500",children:p("pagination.unit")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>d(1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.firstPage"),children:e.jsx(kl,{size:F.md,className:"text-slate-600"})}),e.jsx("button",{onClick:()=>d(t-1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.prevPage"),children:e.jsx(is,{size:F.md,className:"text-slate-600"})}),e.jsx("div",{className:"flex items-center gap-1 mx-2",children:f().map((h,x)=>typeof h=="number"?e.jsx("button",{onClick:()=>d(h),className:`min-w-[32px] h-8 px-2 rounded-md text-sm font-medium transition-colors ${t===h?"bg-blue-600 text-white":"hover:bg-slate-100 text-slate-600"}`,children:h},x):e.jsx("span",{className:"px-1 text-slate-400",children:h},x))}),e.jsx("button",{onClick:()=>d(t+1),disabled:t===s,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.nextPage"),children:e.jsx(rt,{size:F.md,className:"text-slate-600"})}),e.jsx("button",{onClick:()=>d(s),disabled:t===s,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.lastPage"),children:e.jsx(Cl,{size:F.md,className:"text-slate-600"})})]})]})},Gr=Ct.memo(({code:t,lang:s,editorStyles:a})=>e.jsx(ka,{language:s,style:Ca,showLineNumbers:!1,customStyle:{margin:0,padding:a.padding,fontSize:a.fontSize,lineHeight:a.lineHeight,borderRadius:"0",whiteSpace:"pre",verticalAlign:"top",display:"inline-block",minWidth:"100%",minHeight:"100%",backgroundColor:"#282c34"},codeTagProps:{style:{fontFamily:a.fontFamily,whiteSpace:"pre",verticalAlign:"top",fontSize:a.fontSize,lineHeight:a.lineHeight}},PreTag:"div",children:(()=>{const l=t;return l[l.length-1]===`
75
- `?l+" ":l})()})),ps=19.5,Hr=Ct.memo(({totalLines:t,scrollTop:s,viewportHeight:a,fontSize:l,lineHeight:d,fontFamily:i})=>{const p=Math.max(0,Math.floor(s/ps)-10),n=Math.ceil(a/ps)+20,g=Math.min(t,p+n),f=p*ps,h=Math.max(0,(t-g)*ps),x=[];for(let c=p;c<g;c++)x.push(e.jsx("div",{children:c+1},c));return e.jsx("div",{style:{paddingTop:f,paddingBottom:h,fontSize:l,lineHeight:d,fontFamily:i},children:x})}),ks=({value:t,onChange:s,onCursorChange:a,language:l="javascript",height:d="400px",className:i="",placeholder:u="",rows:p,showLineNumbers:n=!0})=>{const g=o.useRef(null),f=o.useRef(null),h=o.useRef(null),x=o.useRef(null),[c,j]=o.useState(t),w=o.useRef(void 0);o.useEffect(()=>{const q=t.length>5e3?200:t.length>1e3?80:0;if(q===0){j(t);return}return w.current=setTimeout(()=>j(t),q),()=>clearTimeout(w.current)},[t]);const[C,E]=o.useState({top:0,height:400}),G={objectivec:"objectivec","objective-c":"objectivec","obj-c":"objectivec",objc:"objectivec",swift:"swift",javascript:"javascript",js:"javascript",typescript:"typescript",ts:"typescript",python:"python",py:"python",bash:"bash",shell:"bash",markdown:"markdown",md:"markdown",json:"json",text:"text"}[l==null?void 0:l.toLowerCase()]||(l==null?void 0:l.toLowerCase())||"text",z=o.useMemo(()=>({padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,fontFamily:"ui-monospace, monospace",minHeight:"200px"}),[]),P=o.useCallback(q=>{const R=q.currentTarget;h.current&&(h.current.scrollTop=R.scrollTop,h.current.scrollLeft=R.scrollLeft),x.current&&(x.current.scrollTop=R.scrollTop),E({top:R.scrollTop,height:R.clientHeight})},[]),Z=o.useCallback(q=>{s(q.target.value),a&&a(q.target.selectionStart||0)},[s,a]),X=o.useCallback(q=>{a&&a(q.currentTarget.selectionStart||0)},[a]),H=o.useMemo(()=>(t||"").split(`
76
- `).length,[t]);return o.useEffect(()=>{f.current&&E(q=>({...q,height:f.current.clientHeight}))},[]),e.jsxs("div",{ref:g,className:`relative overflow-hidden ${i}`,style:{height:p?"auto":d,minHeight:z.minHeight,display:"flex",borderRadius:"0",backgroundColor:"#282c34"},children:[n&&e.jsx("div",{ref:x,className:"flex-shrink-0 overflow-hidden pointer-events-none select-none",style:{width:"3.5em",backgroundColor:"#282c34",color:"#5c6370",textAlign:"right",paddingTop:"1rem",paddingRight:"0.75em",paddingBottom:"1rem",borderRadius:"0",borderRight:"1px solid #333842"},children:e.jsx(Hr,{totalLines:H,scrollTop:C.top,viewportHeight:C.height,fontSize:z.fontSize,lineHeight:z.lineHeight,fontFamily:z.fontFamily})}),e.jsxs("div",{className:"relative flex-1",style:{borderRadius:"0",backgroundColor:"#282c34"},children:[e.jsx("div",{ref:h,className:"absolute inset-0 pointer-events-none highlight-scroll-hidden",style:{zIndex:0,overflow:"scroll"},children:e.jsx(Gr,{code:c||u,lang:G,editorStyles:z})}),e.jsx("textarea",{ref:f,value:t,onChange:Z,onSelect:X,onKeyUp:X,onClick:X,onScroll:P,rows:p,placeholder:u,className:"absolute inset-0 w-full h-full resize-none outline-none editor-with-dark-scrollbar",style:{padding:z.padding,lineHeight:z.lineHeight,fontSize:z.fontSize,fontFamily:z.fontFamily,caretColor:"#61afef",backgroundColor:"transparent",color:"transparent",WebkitTextFillColor:"transparent",zIndex:10,border:"none",margin:0,overflow:"auto",overflowX:"hidden",WebkitAppearance:"none",appearance:"none",boxSizing:"border-box",whiteSpace:"pre"}})]})]})},qr=420,Or=({className:t="bg-black/20 backdrop-blur-[1px]"})=>e.jsx("div",{className:`absolute inset-0 ${t}`}),Ze=({children:t,onClick:s,className:a="",style:l})=>{const{isOpen:d}=ds();return e.jsx("div",{className:`fixed inset-0 overflow-hidden ${a}`,style:{right:d?qr:0,...l},onClick:s,children:t})};Ze.Backdrop=Or;const Kr={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:ut},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:jt},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:tt}},da={"code-pattern":"recipes.knowledgeTypes.codePattern",architecture:"recipes.knowledgeTypes.architecture","best-practice":"recipes.knowledgeTypes.bestPractice","code-standard":"recipes.knowledgeTypes.codeStandard","call-chain":"recipes.knowledgeTypes.callChain",rule:"recipes.knowledgeTypes.rule"};function at(t){return(t.name||t.title||"Untitled").replace(/\.md$/i,"")}function Ur(t){const s=t.content;if(!s)return"";if(typeof s=="string")return s;const a=[];return s.pattern&&a.push(s.pattern),s.markdown&&a.push(s.markdown),a.length>0?a.join(`
73
+ `+t("globalChat.system.cancelled"):t("globalChat.system.cancelled"));be&&k.current.push({role:"model",content:be}),d(xe=>xe.map(P=>P.id===ee?{...P,content:K}:P))}else d(be=>be.map(B=>B.id===ee?{...B,content:t("globalChat.requestFailed",{error:ie.message})}:B))}finally{j.current=null}}u(!1)}},[X,c,w,T,A,$]),O=o.useCallback(async()=>{var v,ee,te,de;if(!(p||!T||!g)){n(!0);try{const ve=[...l].reverse().find(ie=>ie.role==="assistant"&&ie.preview);let fe=ve==null?void 0:ve.preview;if(fe&&((v=ve==null?void 0:ve.excludedFields)!=null&&v.length)&&ve.diff){fe={...fe};const ie=A?ca(A):{};for(const be of ve.excludedFields)be in ie&&(fe[be]=ie[be])}await ae.refineApply(T,i,fe),x(ie=>new Set(ie).add(T)),(ee=g.onCandidateUpdated)==null||ee.call(g,T),d(ie=>[...ie,{id:$t(),role:"system",content:t("globalChat.system.changesApplied"),timestamp:Date.now()}]),re(t("globalChat.applySuccess"),{title:t("globalChat.applySuccessTitle")})}catch(ve){const fe=(de=(te=ve.response)==null?void 0:te.data)==null?void 0:de.error;re(typeof fe=="string"?fe:(fe==null?void 0:fe.message)||ve.message,{title:t("globalChat.applyFailed"),type:"error"})}finally{n(!1)}}},[p,T,i,g]),ye=o.useCallback(()=>{!g||g.currentIdx>=g.candidateIds.length-1||f(v=>v?{...v,currentIdx:v.currentIdx+1}:null)},[g]),Ne=o.useCallback(()=>{I.current=null,f(null),d(v=>[...v,{id:$t(),role:"system",content:t("globalChat.system.exitedRefine"),timestamp:Date.now()}])},[]),je=o.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),W())},[W]);return e.jsxs("aside",{className:"w-[420px] h-full bg-white border-l border-slate-200 flex flex-col shrink-0",children:[e.jsxs("div",{className:"px-4 py-2.5 border-b border-slate-200 flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center",children:w?e.jsx(Qe,{className:"text-emerald-500",size:16}):e.jsx(Lt,{className:"text-blue-600",size:16})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-[13px] font-bold text-slate-800 flex items-center gap-2",children:[t(w?"globalChat.refineTitle":"globalChat.chatTitle"),w&&G&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-emerald-50 text-emerald-600 font-medium",children:[((g==null?void 0:g.currentIdx)??0)+1,"/",g==null?void 0:g.candidateIds.length]})]}),e.jsx("p",{className:"text-[10px] text-slate-400 truncate max-w-[250px]",children:w?(A==null?void 0:A.title)||t("globalChat.refineSubtitle"):t("globalChat.chatSubtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[w&&e.jsx("button",{onClick:Ne,className:"px-2 py-1 text-[10px] font-medium text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-md transition-colors",children:t("globalChat.exitRefine")}),!w&&l.length>0&&e.jsx("button",{onClick:()=>{I.current=null,d([]),k.current=[],y("")},className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",title:t("globalChat.newTopic"),children:e.jsx(Nt,{size:16,className:"text-slate-400"})}),e.jsx("button",{onClick:_,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",title:t("globalChat.closeChat"),children:e.jsx(Xe,{size:16,className:"text-slate-400"})})]})]}),w&&A&&e.jsx("div",{className:"border-b border-slate-100 bg-emerald-50/30 px-4 py-2 shrink-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-bold text-emerald-700 truncate flex-1",children:A.title}),A.language&&e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100",children:A.language})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 min-h-0 scrollbar-light",children:[l.length===0&&!w&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-10",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-blue-50 border border-blue-100 flex items-center justify-center mb-3",children:e.jsx(Lt,{className:"text-blue-500",size:20})}),e.jsx("h4",{className:"text-sm font-bold text-slate-700 mb-1",children:t("globalChat.emptyTitle")}),e.jsx("p",{className:"text-xs text-slate-400 max-w-[280px] leading-relaxed mb-3",children:t("globalChat.emptyDesc")}),e.jsx("div",{className:"flex flex-wrap gap-1.5 justify-center",children:[t("globalChat.quickPrompts.analyzeArch"),t("globalChat.quickPrompts.findDuplicates"),t("globalChat.quickPrompts.suggestOptimize")].map(v=>e.jsx("button",{onClick:()=>{var ee;H(v),(ee=Z.current)==null||ee.focus()},className:"text-[10px] px-2.5 py-1 rounded-md bg-slate-100 text-slate-600 hover:bg-blue-50 hover:text-blue-700 transition-colors",children:v},v))})]}),w&&l.length<=1&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-2",children:[t("globalChat.refinePrompts.addExamples"),t("globalChat.refinePrompts.optimizeComments"),t("globalChat.refinePrompts.addCaveats"),t("globalChat.refinePrompts.improveSummary"),t("globalChat.refinePrompts.addPerformance")].map(v=>e.jsx("button",{onClick:()=>{var ee;H(v),(ee=Z.current)==null||ee.focus()},className:"text-[10px] px-2.5 py-1 rounded-md bg-emerald-50 text-emerald-700 border border-emerald-200 hover:bg-emerald-100 transition-colors",children:v},v))}),l.map(v=>e.jsx("div",{className:`flex ${v.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[95%] ${v.role==="user"?"bg-blue-600 text-white rounded-2xl rounded-tr-md px-3.5 py-2":v.role==="system"?"bg-slate-50 border border-slate-200 text-slate-600 rounded-2xl px-3.5 py-2 w-full":"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-3.5 py-2.5 shadow-sm w-full"}`,children:[v.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx(rs,{size:12,className:w?"text-emerald-500":"text-blue-500"}),e.jsx("span",{className:`text-[10px] font-bold ${w?"text-emerald-600":"text-blue-600"}`,children:t(w?"globalChat.assistantRefine":"globalChat.assistantChat")})]}),v.role==="assistant"&&!v.diff?e.jsx(gt,{content:v.content,className:"text-xs text-slate-700"}):e.jsx("p",{className:`text-xs leading-relaxed whitespace-pre-wrap ${v.role==="user"?"":v.role==="system"?"text-slate-500":"text-slate-700"}`,children:v.content}),v.diff&&v.diff.length>0&&e.jsx(Mr,{diff:v.diff,excludedFields:v.excludedFields,onToggleField:w&&!h.has(T)?ee=>N(v.id,ee):void 0})]})},v.id)),c&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-3.5 py-2.5 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{size:12,className:`animate-spin ${w?"text-emerald-500":"text-blue-500"}`}),e.jsx("span",{className:"text-xs text-slate-500",children:t(w?"globalChat.loading.analyzing":"globalChat.loading.thinking")}),j.current&&e.jsx("button",{onClick:()=>{var v;return(v=j.current)==null?void 0:v.abort()},className:"ml-1 px-1.5 py-0.5 text-[10px] font-bold text-red-500 border border-red-200 rounded hover:bg-red-50 transition-colors",children:t("globalChat.stopBtn")})]})})}),e.jsx("div",{ref:E})]}),w&&m&&!c&&(()=>{var ve,fe;const v=[...l].reverse().find(ie=>ie.role==="assistant"&&ie.diff&&ie.diff.length>0),ee=((ve=v==null?void 0:v.diff)==null?void 0:ve.length)||0,te=((fe=v==null?void 0:v.excludedFields)==null?void 0:fe.length)||0,de=ee-te;return e.jsxs("div",{className:"px-4 py-2 border-t border-slate-100 bg-emerald-50/50 flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:O,disabled:p,className:"flex items-center gap-1 px-3 py-1.5 text-[11px] font-bold text-white bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700 rounded-lg shadow-sm disabled:opacity-50",children:[p?e.jsx(Me,{size:11,className:"animate-spin"}):e.jsx(kt,{size:11}),p?t("globalChat.applyingBtn"):te>0?t("globalChat.confirmApplyN",{i:de,total:ee}):t("globalChat.confirmApply")]}),e.jsxs("button",{className:"flex items-center gap-1 px-2.5 py-1.5 text-[11px] font-bold text-slate-500 hover:text-slate-700 rounded-lg hover:bg-slate-100 transition-colors",children:[e.jsx(Ra,{size:11})," ",t("globalChat.continueAdjust")]}),G&&h.has(T)&&g.currentIdx<g.candidateIds.length-1&&e.jsxs("button",{onClick:ye,className:"flex items-center gap-1 px-2.5 py-1.5 text-[11px] font-bold text-blue-600 hover:text-blue-700 rounded-lg hover:bg-blue-50 transition-colors ml-auto",children:[t("globalChat.nextItem")," ",e.jsx(rt,{size:11})]})]})})(),w&&!m&&!c&&G&&h.has(T)&&g.currentIdx<g.candidateIds.length-1&&e.jsx("div",{className:"px-4 py-2 border-t border-slate-100 flex items-center justify-center shrink-0",children:e.jsxs("button",{onClick:ye,className:"flex items-center gap-1 px-3 py-1.5 text-[11px] font-bold text-blue-600 hover:text-blue-700 rounded-lg bg-blue-50 hover:bg-blue-100 transition-colors",children:[t("globalChat.nextItem")," (",((g==null?void 0:g.currentIdx)??0)+2,"/",g==null?void 0:g.candidateIds.length,") ",e.jsx(rt,{size:12})]})}),e.jsxs("div",{className:"px-4 py-2.5 border-t border-slate-200 bg-white shrink-0",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{ref:Z,value:X,onChange:v=>H(v.target.value),onKeyDown:je,placeholder:t(w?"globalChat.refinePlaceholder":"globalChat.chatPlaceholder"),rows:2,className:`flex-1 px-3 py-2 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 ${w?"focus:ring-emerald-200 focus:border-emerald-400":"focus:ring-blue-200 focus:border-blue-400"} resize-none placeholder:text-slate-300`,disabled:c||p}),e.jsx("button",{onClick:W,disabled:!X.trim()||c||p,className:`self-stretch w-9 flex items-center justify-center rounded-xl bg-gradient-to-r ${w?"from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700":"from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700"} text-white disabled:opacity-40 disabled:cursor-not-allowed transition-all shadow-sm shrink-0`,children:e.jsx(Bs,{size:14})})]}),e.jsx("p",{className:"text-[9px] text-slate-400 mt-1",children:t(w?"globalChat.inputHintRefine":"globalChat.inputHintChat")})]})]})},_r=({searchQuery:t,setSearchQuery:s,setShowCreateModal:a,handleSyncSnippets:l,aiConfig:d,llmReady:c=!0,onOpenLlmConfig:u,onSemanticSearchResults:p,onBeforeAiSwitch:n,onAiConfigChange:g})=>{const{toggle:f,isOpen:h}=ds(),{t:x,lang:i,setLang:y}=_e(),{isDark:k,toggle:w}=St(),[T,A]=o.useState(!1),[G,_]=o.useState(!1),[E,Z]=o.useState([]),[X,H]=o.useState(!1),q=o.useRef(null);o.useEffect(()=>{G&&E.length===0&&ae.getAiProviders().then($=>Z($)).catch(()=>{})},[G,E.length]),o.useEffect(()=>{const $=m=>{q.current&&!q.current.contains(m.target)&&_(!1)};return document.addEventListener("click",$),()=>document.removeEventListener("click",$)},[]);const I=async()=>{if(t){A(!0);try{const m=((await ae.search(t,{mode:"semantic"})).items||[]).map(N=>{var j,W,O;return{name:(N.title||N.name||"")+".md",content:((j=N.content)==null?void 0:j.pattern)||((W=N.content)==null?void 0:W.markdown)||((O=N.content)==null?void 0:O.code)||"",similarity:N.score||0,metadata:{type:"recipe",name:(N.title||N.name||"")+".md"}}});p&&p(m)}catch($){console.error("Semantic search failed",$),alert(x("header.semanticSearchFailed"))}finally{A(!1)}}},L=async $=>{H(!0);try{n==null||n(),await ae.setAiConfig($.id,$.defaultModel),_(!1),g&&g()}catch(m){console.error("AI config update failed",m),alert(x("header.aiSwitchFailed"))}finally{H(!1)}};return e.jsxs("header",{className:`h-16 ${k?"bg-[#252526] border-b border-[#3e3e42]":"bg-white border-b border-slate-200"} flex items-center justify-between px-4 xl:px-6 2xl:px-8 shrink-0 gap-3`,children:[e.jsxs("div",{className:"flex items-center gap-2 xl:gap-3 2xl:gap-4 min-w-0 flex-1",children:[e.jsxs("div",{className:"relative w-40 xl:w-60 2xl:w-80 min-w-[10rem] shrink",children:[e.jsx(ft,{className:`absolute left-3 top-1/2 -translate-y-1/2 ${k?"text-slate-500":"text-slate-400"}`,size:z.md}),e.jsx("input",{type:"text",placeholder:x("header.searchPlaceholder"),className:`w-full pl-10 pr-4 py-2 ${k?"bg-[#1e1e1e] text-slate-300 placeholder-slate-500":"bg-slate-100 text-slate-900"} border-transparent rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-500/20 transition-all`,value:t,onChange:$=>s($.target.value),onKeyDown:$=>$.key==="Enter"&&I()})]}),e.jsxs("button",{onClick:I,disabled:!t||T,className:`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-bold transition-all ${T?k?"bg-blue-900/30 text-blue-300":"bg-blue-50 text-blue-400":k?"bg-blue-900/30 text-blue-400 hover:bg-blue-900/50":"bg-blue-50 text-blue-600 hover:bg-blue-100"}`,title:x("header.semanticSearchTitle"),children:[T?e.jsx(Me,{size:z.sm,className:"animate-spin"}):e.jsx(jl,{size:z.sm}),x("header.semanticSearch")]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 xl:gap-2 2xl:gap-3 shrink-0",children:[c?d?e.jsxs("div",{className:"relative",ref:q,children:[e.jsxs("button",{type:"button",onClick:$=>{$.stopPropagation(),_(m=>!m)},className:`flex items-center gap-1.5 px-2 xl:px-3 py-1.5 rounded-lg text-xs font-medium border transition-all duration-150 max-w-[180px] 2xl:max-w-none ${k?"bg-[#2a2d35] border-[#3e3e42] text-slate-300 hover:border-slate-500 hover:bg-[#333842]":"bg-white border-slate-200 text-slate-600 hover:border-slate-300 hover:bg-slate-50"}`,title:x("header.clickSwitchAi"),children:[e.jsx(ns,{size:z.sm,className:"shrink-0"}),e.jsxs("span",{className:"truncate",children:[d.provider," / ",d.model]}),e.jsx(Gt,{size:z.xs,className:`shrink-0 ${G?"rotate-180":""}`})]}),G&&e.jsxs("div",{className:`absolute top-full right-0 mt-1 py-1 rounded-lg border shadow-lg z-20 min-w-[200px] ${k?"bg-[#252526] border-[#3e3e42]":"bg-white border-slate-200"}`,children:[e.jsx("div",{className:`px-3 py-2 text-xs border-b ${k?"text-slate-400 border-[#3e3e42]":"text-slate-500 border-slate-100"}`,children:x("header.switchAi")}),e.jsx("div",{className:`px-3 py-1.5 text-[11px] border-b ${k?"text-slate-500 border-[#3e3e42]":"text-slate-400 border-slate-100"}`,children:e.jsx("button",{type:"button",onClick:()=>{_(!1),u==null||u()},className:"text-blue-500 hover:underline",children:x("header.editEnvConfig")})}),E.length===0?e.jsx("div",{className:`px-3 py-2 text-xs ${k?"text-slate-500":"text-slate-400"}`,children:x("common.loading")}):E.map($=>e.jsxs("button",{type:"button",disabled:X,onClick:()=>L($),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between ${d.provider===$.id?k?"bg-blue-900/30 text-blue-400 font-medium":"bg-blue-50 text-blue-700 font-medium":k?"text-slate-300 hover:bg-slate-700/50":"text-slate-700 hover:bg-slate-50"}`,children:[e.jsx("span",{children:$.label}),d.provider===$.id&&e.jsx("span",{className:"text-xs",children:"✓"})]},$.id))]})]}):null:e.jsxs("button",{type:"button",onClick:u,className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors animate-pulse ${k?"bg-amber-900/30 text-amber-300 border-amber-700 hover:bg-amber-900/50":"bg-amber-50 text-amber-700 border-amber-200 hover:bg-amber-100"}`,title:x("header.aiNotConfigured"),children:[e.jsx(Ea,{size:z.sm}),x("header.configureLlm")]}),e.jsxs("button",{onClick:f,className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium border transition-all duration-150 ${h?k?"bg-blue-500/20 border-blue-500/40 text-blue-300 ring-1 ring-blue-500/30 hover:border-blue-400/60 hover:bg-blue-500/30":"bg-blue-50 border-blue-300 text-blue-700 ring-1 ring-blue-200 hover:border-blue-400 hover:bg-blue-100":k?"bg-[#2a2d35] border-[#3e3e42] text-slate-300 hover:border-slate-500 hover:bg-[#333842]":"bg-white border-slate-200 text-slate-600 hover:border-slate-300 hover:bg-slate-50"}`,title:x(h?"header.closeAiChat":"header.openAiChat"),children:[e.jsx(Lt,{size:z.sm}),!h&&e.jsx("span",{className:"text-xs",children:x("header.aiChat")})]}),e.jsxs("button",{onClick:()=>a(!0),className:`flex items-center gap-1.5 px-2.5 xl:px-3 2xl:px-4 py-2 rounded-lg text-xs xl:text-sm font-medium transition-all duration-150 border whitespace-nowrap ${k?"bg-[#2a2d35] border-[#3e3e42] text-slate-300 hover:border-slate-500 hover:bg-[#333842]":"bg-white border-slate-200 text-slate-600 hover:border-slate-300 hover:bg-slate-50"}`,title:x("header.newRecipe"),children:[e.jsx(Nt,{size:z.md})," ",e.jsx("span",{className:"hidden xl:inline",children:x("header.newRecipe")})]}),e.jsxs("button",{onClick:l,className:`flex items-center gap-1.5 px-2.5 xl:px-3 2xl:px-4 py-2 rounded-lg text-xs xl:text-sm font-medium transition-all duration-150 border whitespace-nowrap ${k?"bg-blue-500/20 border-blue-500/40 text-blue-300 hover:border-blue-400/60 hover:bg-blue-500/30":"bg-blue-50 border-blue-300 text-blue-600 hover:border-blue-400 hover:bg-blue-100"}`,title:x("header.syncSnippets"),children:[e.jsx(yt,{size:z.md})," ",e.jsx("span",{className:"hidden xl:inline",children:x("header.syncSnippets")})]}),e.jsxs("button",{onClick:()=>y(i==="zh"?"en":"zh"),className:`flex items-center gap-1 px-2 xl:px-3 py-2 rounded-lg text-xs font-medium border transition-all duration-150 ${k?"bg-[#2a2d35] border-[#3e3e42] text-slate-300 hover:border-slate-500 hover:bg-[#333842]":"bg-white border-slate-200 text-slate-600 hover:border-slate-300 hover:bg-slate-50"}`,title:i==="zh"?"Switch to English":x("shared.switchToChinese"),children:[e.jsx(vl,{size:z.sm}),e.jsx("span",{className:"hidden 2xl:inline",children:x("header.langSwitch")})]}),e.jsx("button",{onClick:w,className:`flex items-center p-2 rounded-lg border transition-all duration-150 ${k?"bg-[#2a2d35] border-[#3e3e42] text-amber-300 hover:border-slate-500 hover:bg-[#333842]":"bg-white border-slate-200 text-slate-600 hover:border-slate-300 hover:bg-slate-50"}`,title:k?"Light mode":"Dark mode",children:k?e.jsx(Nl,{size:z.sm}):e.jsx(wl,{size:z.sm})})]})]})},Ya="asd-drawer-wide";function $r(){try{return localStorage.getItem(Ya)==="1"}catch{return!1}}function Vs(){const[t,s]=o.useState($r),a=o.useCallback(()=>{s(l=>{const d=!l;try{localStorage.setItem(Ya,d?"1":"0")}catch{}return d})},[]);return{isWide:t,toggle:a}}const Js=({currentPage:t,totalPages:s,totalItems:a,pageSize:l,onPageChange:d,onPageSizeChange:c,pageSizeOptions:u=[12,24,48,96]})=>{if(s<=1&&a<=u[0])return null;const{t:p}=_e(),n=(t-1)*l+1,g=Math.min(t*l,a),f=()=>{const h=[];if(s<=7)for(let i=1;i<=s;i++)h.push(i);else if(t<=3){for(let i=1;i<=5;i++)h.push(i);h.push("..."),h.push(s)}else if(t>=s-2){h.push(1),h.push("...");for(let i=s-5+1;i<=s;i++)h.push(i)}else{h.push(1),h.push("...");for(let i=t-1;i<=t+1;i++)h.push(i);h.push("..."),h.push(s)}return h};return e.jsxs("div",{className:"flex items-center justify-between mt-6 px-2",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"text-sm text-slate-500",children:p("pagination.showing",{start:n,end:g,total:a})}),c&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-slate-500",children:p("pagination.perPage")}),e.jsx("select",{value:l,onChange:h=>c(Number(h.target.value)),className:"text-sm border border-slate-200 rounded-md px-2 py-1 bg-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent",children:u.map(h=>e.jsx("option",{value:h,children:h},h))}),e.jsx("span",{className:"text-sm text-slate-500",children:p("pagination.unit")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>d(1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.firstPage"),children:e.jsx(kl,{size:z.md,className:"text-slate-600"})}),e.jsx("button",{onClick:()=>d(t-1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.prevPage"),children:e.jsx(is,{size:z.md,className:"text-slate-600"})}),e.jsx("div",{className:"flex items-center gap-1 mx-2",children:f().map((h,x)=>typeof h=="number"?e.jsx("button",{onClick:()=>d(h),className:`min-w-[32px] h-8 px-2 rounded-md text-sm font-medium transition-colors ${t===h?"bg-blue-600 text-white":"hover:bg-slate-100 text-slate-600"}`,children:h},x):e.jsx("span",{className:"px-1 text-slate-400",children:h},x))}),e.jsx("button",{onClick:()=>d(t+1),disabled:t===s,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.nextPage"),children:e.jsx(rt,{size:z.md,className:"text-slate-600"})}),e.jsx("button",{onClick:()=>d(s),disabled:t===s,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.lastPage"),children:e.jsx(Cl,{size:z.md,className:"text-slate-600"})})]})]})},Br=Ct.memo(({code:t,lang:s,editorStyles:a})=>e.jsx(ka,{language:s,style:Ca,showLineNumbers:!1,customStyle:{margin:0,padding:a.padding,fontSize:a.fontSize,lineHeight:a.lineHeight,borderRadius:"0",whiteSpace:"pre",verticalAlign:"top",display:"inline-block",minWidth:"100%",minHeight:"100%",backgroundColor:"#282c34"},codeTagProps:{style:{fontFamily:a.fontFamily,whiteSpace:"pre",verticalAlign:"top",fontSize:a.fontSize,lineHeight:a.lineHeight}},PreTag:"div",children:(()=>{const l=t;return l[l.length-1]===`
74
+ `?l+" ":l})()})),ps=19.5,Gr=Ct.memo(({totalLines:t,scrollTop:s,viewportHeight:a,fontSize:l,lineHeight:d,fontFamily:c})=>{const p=Math.max(0,Math.floor(s/ps)-10),n=Math.ceil(a/ps)+20,g=Math.min(t,p+n),f=p*ps,h=Math.max(0,(t-g)*ps),x=[];for(let i=p;i<g;i++)x.push(e.jsx("div",{children:i+1},i));return e.jsx("div",{style:{paddingTop:f,paddingBottom:h,fontSize:l,lineHeight:d,fontFamily:c},children:x})}),ks=({value:t,onChange:s,onCursorChange:a,language:l="javascript",height:d="400px",className:c="",placeholder:u="",rows:p,showLineNumbers:n=!0})=>{const g=o.useRef(null),f=o.useRef(null),h=o.useRef(null),x=o.useRef(null),[i,y]=o.useState(t),k=o.useRef(void 0);o.useEffect(()=>{const q=t.length>5e3?200:t.length>1e3?80:0;if(q===0){y(t);return}return k.current=setTimeout(()=>y(t),q),()=>clearTimeout(k.current)},[t]);const[w,T]=o.useState({top:0,height:400}),G={objectivec:"objectivec","objective-c":"objectivec","obj-c":"objectivec",objc:"objectivec",swift:"swift",javascript:"javascript",js:"javascript",typescript:"typescript",ts:"typescript",python:"python",py:"python",bash:"bash",shell:"bash",markdown:"markdown",md:"markdown",json:"json",text:"text"}[l==null?void 0:l.toLowerCase()]||(l==null?void 0:l.toLowerCase())||"text",_=o.useMemo(()=>({padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,fontFamily:"ui-monospace, monospace",minHeight:"200px"}),[]),E=o.useCallback(q=>{const I=q.currentTarget;h.current&&(h.current.scrollTop=I.scrollTop,h.current.scrollLeft=I.scrollLeft),x.current&&(x.current.scrollTop=I.scrollTop),T({top:I.scrollTop,height:I.clientHeight})},[]),Z=o.useCallback(q=>{s(q.target.value),a&&a(q.target.selectionStart||0)},[s,a]),X=o.useCallback(q=>{a&&a(q.currentTarget.selectionStart||0)},[a]),H=o.useMemo(()=>(t||"").split(`
75
+ `).length,[t]);return o.useEffect(()=>{f.current&&T(q=>({...q,height:f.current.clientHeight}))},[]),e.jsxs("div",{ref:g,className:`relative overflow-hidden ${c}`,style:{height:p?"auto":d,minHeight:_.minHeight,display:"flex",borderRadius:"0",backgroundColor:"#282c34"},children:[n&&e.jsx("div",{ref:x,className:"flex-shrink-0 overflow-hidden pointer-events-none select-none",style:{width:"3.5em",backgroundColor:"#282c34",color:"#5c6370",textAlign:"right",paddingTop:"1rem",paddingRight:"0.75em",paddingBottom:"1rem",borderRadius:"0",borderRight:"1px solid #333842"},children:e.jsx(Gr,{totalLines:H,scrollTop:w.top,viewportHeight:w.height,fontSize:_.fontSize,lineHeight:_.lineHeight,fontFamily:_.fontFamily})}),e.jsxs("div",{className:"relative flex-1",style:{borderRadius:"0",backgroundColor:"#282c34"},children:[e.jsx("div",{ref:h,className:"absolute inset-0 pointer-events-none highlight-scroll-hidden",style:{zIndex:0,overflow:"scroll"},children:e.jsx(Br,{code:i||u,lang:G,editorStyles:_})}),e.jsx("textarea",{ref:f,value:t,onChange:Z,onSelect:X,onKeyUp:X,onClick:X,onScroll:E,rows:p,placeholder:u,className:"absolute inset-0 w-full h-full resize-none outline-none editor-with-dark-scrollbar",style:{padding:_.padding,lineHeight:_.lineHeight,fontSize:_.fontSize,fontFamily:_.fontFamily,caretColor:"#61afef",backgroundColor:"transparent",color:"transparent",WebkitTextFillColor:"transparent",zIndex:10,border:"none",margin:0,overflow:"auto",overflowX:"hidden",WebkitAppearance:"none",appearance:"none",boxSizing:"border-box",whiteSpace:"pre"}})]})]})},Hr=420,qr=({className:t="bg-black/20 backdrop-blur-[1px]"})=>e.jsx("div",{className:`absolute inset-0 ${t}`}),Ze=({children:t,onClick:s,className:a="",style:l})=>{const{isOpen:d}=ds();return e.jsx("div",{className:`fixed inset-0 overflow-hidden ${a}`,style:{right:d?Hr:0,...l},onClick:s,children:t})};Ze.Backdrop=qr;const Or={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:dt},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:jt},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:tt}},da={"code-pattern":"recipes.knowledgeTypes.codePattern",architecture:"recipes.knowledgeTypes.architecture","best-practice":"recipes.knowledgeTypes.bestPractice","code-standard":"recipes.knowledgeTypes.codeStandard","call-chain":"recipes.knowledgeTypes.callChain",rule:"recipes.knowledgeTypes.rule"};function at(t){return(t.name||t.title||"Untitled").replace(/\.md$/i,"")}function Kr(t){const s=t.content;if(!s)return"";if(typeof s=="string")return s;const a=[];return s.pattern&&a.push(s.pattern),s.markdown&&a.push(s.markdown),a.length>0?a.join(`
77
76
 
78
- `):JSON.stringify(s,null,2)}function ua(t){var s;return((s=t.content)==null?void 0:s.pattern)||""}function pa(t){const s=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(s)?"objectivec":t.language||"text"}function Qa(t){if(t==null)return!1;const s=typeof t=="string"?new Date(t).getTime():t;return!isNaN(s)&&s>9466848e5}function xa(t){return Qa(t)?(typeof t=="string"?new Date(t):new Date(t)).toLocaleDateString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit"}):""}const Wr=({recipes:t,handleDeleteRecipe:s,onRefresh:a,idTitleMap:l,currentPage:d,onPageChange:i,pageSize:u,onPageSizeChange:p})=>{const{t:n}=_e(),[g,f]=o.useState("default"),[h,x]=o.useState("desc"),c=[{key:"default",label:n("recipes.sortNewest"),defaultDir:"desc"},{key:"authorityScore",label:n("recipes.qualityAuthorityScore"),defaultDir:"desc"},{key:"authority",label:n("recipes.qualityExcellent"),defaultDir:"desc"},{key:"totalUsage",label:n("recipes.qualityBasic"),defaultDir:"desc"},{key:"lastUsed",label:n("recipes.sortQuality"),defaultDir:"desc"},{key:"name",label:n("recipes.sortAlpha"),defaultDir:"asc"},{key:"category",label:n("recipes.knowledgeType"),defaultDir:"asc"}],[j,w]=o.useState(1),[C,E]=o.useState(12),S=d??j,G=u??C,z=i??w,P=p?r=>p(r):r=>{E(r),w(1)},{isWide:Z,toggle:X}=Vs(),[H,q]=o.useState(null),[R,M]=o.useState("view"),[_,m]=o.useState(""),[N,y]=o.useState({title:"",description:"",markdown:"",codePattern:"",rationale:"",tags:[],tagInput:""}),[W,O]=o.useState(!1),be=o.useRef(!0),[we,ye]=o.useState(!1),[v,ee]=o.useState("related"),[ae,ue]=o.useState("");o.useEffect(()=>()=>{be.current=!1},[]);const fe=[{key:"related",label:n("knowledgeGraph.relationAssociates"),icon:"∼"},{key:"dependsOn",label:n("knowledgeGraph.relationDependsOn"),icon:"⊕"},{key:"inherits",label:n("knowledgeGraph.relationInherits"),icon:"↑"},{key:"implements",label:n("knowledgeGraph.relationImplements"),icon:"◇"},{key:"calls",label:n("knowledgeGraph.relationCalls"),icon:"→"},{key:"dataFlow",label:n("knowledgeGraph.relationDataFlow"),icon:"⇢"},{key:"conflicts",label:n("knowledgeGraph.relationConflicts"),icon:"✕"},{key:"extends",label:n("knowledgeGraph.relationExtends"),icon:"⊃"}],he=r=>{var k,b,B,D;q(r),M("view"),m(Ur(r)),y({title:((k=r.name)==null?void 0:k.replace(/\.md$/,""))||"",description:r.description||"",markdown:((b=r.content)==null?void 0:b.markdown)||"",codePattern:((B=r.content)==null?void 0:B.pattern)||"",rationale:((D=r.content)==null?void 0:D.rationale)||"",tags:r.tags||[],tagInput:""}),ye(!1),ue("")},ce=()=>{q(null),M("view"),ye(!1),ue("")},je=async()=>{if(!(!H||W)){O(!0);try{const r=H.id||H.name;await se.knowledgeUpdate(r,{title:N.title,description:N.description,tags:N.tags,content:{...H.content||{},pattern:N.codePattern,markdown:N.markdown,rationale:N.rationale}}),be.current&&(M("view"),a==null||a())}catch(r){re((r==null?void 0:r.message)||n("common.saveFailed"),{title:n("common.operationFailed"),type:"error"})}finally{be.current&&O(!1)}}},$=async r=>{if(H)try{await se.setRecipeAuthority(H.id||H.name,r),a==null||a()}catch(k){re((k==null?void 0:k.message)||n("common.operationFailed"),{title:n("common.operationFailed"),type:"error"})}},K=r=>{const k=r.replace(/\.md$/i,"").toLowerCase();return t.find(b=>at(b).toLowerCase()===k)},xe=o.useMemo(()=>{const r=new Map;if(l)for(const[k,b]of Object.entries(l))r.set(k,b);for(const k of t)k.id&&r.set(k.id,at(k)),k.name&&r.set(k.name,at(k));return r},[t,l]),L=async(r,k)=>{if(!H)return;const b={};if(H.relations)for(const[U,te]of Object.entries(H.relations))b[U]=[...te];const B=b[r]||[],D=k.replace(/\.md$/i,"");if(!B.some(U=>(typeof U=="string"?U:U.id||U.title||"").replace(/\.md$/i,"").toLowerCase()===D.toLowerCase())){b[r]=[...B,D];try{await se.updateRecipeRelations(H.id||H.name,b),q({...H,relations:b}),ye(!1),ue(""),a==null||a()}catch(U){re((U==null?void 0:U.message)||n("common.operationFailed"),{title:n("common.operationFailed"),type:"error"})}}},T=async(r,k)=>{if(!H)return;const b={};if(H.relations)for(const[D,U]of Object.entries(H.relations))b[D]=[...U];const B=b[r]||[];b[r]=B.filter(D=>(typeof D=="string"?D:D.id||D.title||"").replace(/\.md$/i,"").toLowerCase()!==k.replace(/\.md$/i,"").toLowerCase()),b[r].length===0&&delete b[r];try{await se.updateRecipeRelations(H.id||H.name,b),q({...H,relations:b}),a==null||a()}catch(D){re((D==null?void 0:D.message)||n("common.operationFailed"),{title:n("common.operationFailed"),type:"error"})}};o.useEffect(()=>{H&&!t.find(r=>at(r)===at(H))&&ce()},[t,H]),o.useEffect(()=>{d==null&&w(1)},[t.length,d]);const Q=Ct.useMemo(()=>{if(g==="default")return t;const r=[...t],k=h==="asc"?1:-1;return r.sort((b,B)=>{var te,de,me,I,V,Ce,Ae,Re,Be,Ye,J,Le;let D=0,U=0;switch(g){case"name":return D=at(b).toLowerCase(),U=at(B).toLowerCase(),k*(D<U?-1:D>U?1:0);case"authorityScore":D=((te=b.stats)==null?void 0:te.authorityScore)??-1,U=((de=B.stats)==null?void 0:de.authorityScore)??-1;break;case"authority":D=((me=b.stats)==null?void 0:me.authority)??-1,U=((I=B.stats)==null?void 0:I.authority)??-1;break;case"totalUsage":D=(((V=b.stats)==null?void 0:V.guardUsageCount)??0)+(((Ce=b.stats)==null?void 0:Ce.humanUsageCount)??0)+(((Ae=b.stats)==null?void 0:Ae.aiUsageCount)??0),U=(((Re=B.stats)==null?void 0:Re.guardUsageCount)??0)+(((Be=B.stats)==null?void 0:Be.humanUsageCount)??0)+(((Ye=B.stats)==null?void 0:Ye.aiUsageCount)??0);break;case"lastUsed":{const qe=(J=b.stats)!=null&&J.lastUsedAt?new Date(b.stats.lastUsedAt).getTime():0,ze=(Le=B.stats)!=null&&Le.lastUsedAt?new Date(B.stats.lastUsedAt).getTime():0;D=isNaN(qe)?0:qe,U=isNaN(ze)?0:ze;break}case"category":return D=(b.category||"").toLowerCase(),U=(B.category||"").toLowerCase(),k*(D<U?-1:D>U?1:0)}return k*(D-U)}),r},[t,g,h]),ie=Math.ceil(Q.length/G),ke=(S-1)*G,Ue=Q.slice(ke,ke+G),Ie=r=>{z(r),window.scrollTo({top:0,behavior:"smooth"})},ne=H?Q.findIndex(r=>at(r)===at(H)):-1,ve=()=>{ne>0&&he(Q[ne-1])},He=()=>{ne<Q.length-1&&he(Q[ne+1])},Pe=({recipe:r,compact:k})=>{const b=r.kind?Kr[r.kind]:null,B=(b==null?void 0:b.icon)||nt,D=r.category||"Utility",U=ct[D]||ct.Utility,te=U.icon,de=r.knowledgeType,me=k?"text-[8px]":"text-[9px]";return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[b&&e.jsxs("span",{className:`${me} font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${b.bg} ${b.color} ${b.border}`,children:[e.jsx(B,{size:k?9:10}),b.label]}),e.jsxs("span",{className:`${me} font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${U.bg} ${U.color} ${U.border}`,children:[e.jsx(te,{size:k?9:10}),D]}),de&&e.jsx("span",{className:`${me} font-medium px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-100`,children:da[de]?n(da[de]):de}),r.language&&e.jsx("span",{className:`${me} font-medium px-1.5 py-0.5 rounded bg-slate-100 text-slate-500 uppercase`,children:r.language}),r.trigger&&e.jsx("span",{className:`${me} font-mono font-bold px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100`,children:r.trigger})]})},Ne=({recipe:r})=>{const k=[];return r.scope&&k.push({icon:Pt,iconClass:"text-teal-400",label:n("candidates.path"),value:r.scope==="universal"?n("common.all"):r.scope==="project-specific"?n("candidates.category"):r.scope}),r.complexity&&k.push({icon:lt,iconClass:"text-orange-400",label:n("candidates.category"),value:r.complexity==="advanced"?n("candidates.confidenceHigh"):r.complexity==="intermediate"?n("candidates.confidenceMedium"):r.complexity==="basic"?n("candidates.confidenceLow"):r.complexity}),r.difficulty&&r.difficulty!==r.complexity&&k.push({icon:lt,iconClass:"text-amber-400",label:n("candidates.category"),value:r.difficulty}),r.moduleName&&k.push({icon:lt,iconClass:"text-purple-400",label:n("candidates.category"),value:r.moduleName,mono:!0}),r.source&&r.source!=="unknown"&&k.push({icon:Pt,iconClass:"text-violet-400",label:n("recipes.sourceLabel"),value:r.source==="bootstrap-scan"?n("recipes.sourceBootstrap"):r.source==="agent"?n("recipes.sourceAiScan"):r.source}),r.version&&k.push({icon:as,iconClass:"text-slate-400",label:n("candidates.language"),value:r.version}),r.updatedAt&&Qa(r.updatedAt)&&k.push({icon:as,iconClass:"text-slate-400",label:n("candidates.updatedAt"),value:xa(r.updatedAt)}),k.length===0&&!r.sourceFile?null:e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:[k.map((b,B)=>{const D=b.icon;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(D,{size:11,className:`${b.iconClass} shrink-0`}),e.jsx("span",{className:"text-slate-400",children:b.label}),e.jsx("span",{className:`font-medium text-slate-600 ${b.mono?"font-mono text-[11px]":""}`,children:b.value})]},B)}),r.sourceFile&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full mt-0.5",children:[e.jsx(wt,{size:11,className:"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-slate-400",children:n("candidates.path")}),e.jsx("code",{className:"font-mono text-[11px] text-slate-500 break-all",title:r.sourceFile,children:r.sourceFile})]})]})};return e.jsxs("div",{className:"relative",children:[t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-24 text-center",children:[e.jsx(Sl,{size:48,className:"text-slate-200 mb-4"}),e.jsx("p",{className:"font-medium text-slate-600 mb-1",children:n("recipes.noResults")}),e.jsx("p",{className:"text-sm text-slate-400",children:n("recipes.noContent")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 text-xs",children:[e.jsx(Pa,{size:14,className:"text-slate-400 shrink-0"}),c.map(r=>{const k=g===r.key;return e.jsxs("button",{onClick:()=>{k?x(b=>b==="asc"?"desc":"asc"):(f(r.key),x(r.defaultDir)),z(1)},className:`px-2 py-1 rounded-md flex items-center gap-0.5 transition-colors ${k?"bg-blue-50 text-blue-700 font-medium border border-blue-200":"text-slate-500 hover:bg-slate-100 border border-transparent"}`,children:[r.label,k&&g!=="default"&&(h==="asc"?e.jsx(Al,{size:12}):e.jsx(Dl,{size:12}))]},r.key)}),e.jsx("span",{className:"ml-auto text-slate-400",children:n("recipes.totalCount",{count:t.length})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:Ue.map(r=>{var U,te;const k=at(r),b=ua(r),B=r.description||r.usageGuide||"",D=H&&at(H)===k;return e.jsxs("div",{onClick:()=>he(r),className:`bg-white rounded-xl border shadow-sm hover:shadow-md transition-all group relative cursor-pointer overflow-hidden ${D?"border-blue-300 ring-1 ring-blue-200":"border-slate-200"}`,children:[e.jsxs("div",{className:"absolute top-3 right-3 flex gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:de=>{de.stopPropagation(),he(r),M("edit")},className:"p-1.5 bg-white/90 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-md transition-colors shadow-sm border border-slate-100",title:n("recipes.editRecipe"),children:e.jsx(Et,{size:F.sm})}),e.jsx("button",{onClick:de=>{de.stopPropagation(),s(r.name||r.id)},className:"p-1.5 bg-white/90 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-md transition-colors shadow-sm border border-slate-100",title:n("recipes.deleteRecipe"),children:e.jsx(ot,{size:F.sm})})]}),e.jsxs("div",{className:"px-5 pt-4 pb-3",children:[e.jsx("h3",{className:"font-bold text-slate-900 text-sm mb-2 pr-16 break-words leading-snug",children:k}),e.jsx(Pe,{recipe:r,compact:!0})]}),r.tags&&r.tags.length>0&&e.jsxs("div",{className:"px-5 pb-2 flex flex-wrap gap-1",children:[r.tags.slice(0,4).map((de,me)=>e.jsxs("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 flex items-center gap-0.5",children:[e.jsx(ls,{size:7}),de]},me)),r.tags.length>4&&e.jsxs("span",{className:"text-[9px] text-slate-400",children:["+",r.tags.length-4]})]}),B&&e.jsx("div",{className:"px-5 pb-3",children:e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed",children:B.replace(/^#+\s*/gm,"").replace(/\*\*/g,"")})}),((U=r.content)==null?void 0:U.markdown)&&e.jsxs("div",{className:"mx-4 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1 px-0.5",children:[e.jsx(nt,{size:9,className:"text-blue-400"}),e.jsx("span",{className:"text-[9px] font-bold text-blue-400 uppercase",children:"Markdown"})]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-lg px-3 py-2 max-h-[60px] overflow-hidden",children:e.jsx("p",{className:"text-[11px] text-slate-600 line-clamp-2 leading-relaxed",children:r.content.markdown.replace(/^#+\s*/gm,"").replace(/\*\*/g,"").replace(/```[\s\S]*?```/g,"").trim().slice(0,200)})})]}),b&&e.jsxs("div",{className:"mx-4 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1 px-0.5",children:[e.jsx(ht,{size:9,className:"text-emerald-400"}),e.jsx("span",{className:"text-[9px] font-bold text-emerald-400 uppercase",children:"Code"})]}),e.jsx("div",{className:"rounded-lg overflow-hidden max-h-[120px]",children:e.jsx(dt,{code:b.split(`
77
+ `):JSON.stringify(s,null,2)}function ua(t){var s;return((s=t.content)==null?void 0:s.pattern)||""}function pa(t){const s=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(s)?"objectivec":t.language||"text"}function Qa(t){if(t==null)return!1;const s=typeof t=="string"?new Date(t).getTime():t;return!isNaN(s)&&s>9466848e5}function xa(t){return Qa(t)?(typeof t=="string"?new Date(t):new Date(t)).toLocaleDateString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit"}):""}const Ur=({recipes:t,handleDeleteRecipe:s,onRefresh:a,idTitleMap:l,currentPage:d,onPageChange:c,pageSize:u,onPageSizeChange:p})=>{const{t:n}=_e(),[g,f]=o.useState("default"),[h,x]=o.useState("desc"),i=[{key:"default",label:n("recipes.sortNewest"),defaultDir:"desc"},{key:"authorityScore",label:n("recipes.qualityAuthorityScore"),defaultDir:"desc"},{key:"authority",label:n("recipes.qualityExcellent"),defaultDir:"desc"},{key:"totalUsage",label:n("recipes.qualityBasic"),defaultDir:"desc"},{key:"lastUsed",label:n("recipes.sortQuality"),defaultDir:"desc"},{key:"name",label:n("recipes.sortAlpha"),defaultDir:"asc"},{key:"category",label:n("recipes.knowledgeType"),defaultDir:"asc"}],[y,k]=o.useState(1),[w,T]=o.useState(12),A=d??y,G=u??w,_=c??k,E=p?r=>p(r):r=>{T(r),k(1)},{isWide:Z,toggle:X}=Vs(),[H,q]=o.useState(null),[I,L]=o.useState("view"),[$,m]=o.useState(""),[N,j]=o.useState({title:"",description:"",markdown:"",codePattern:"",rationale:"",tags:[],tagInput:""}),[W,O]=o.useState(!1),ye=o.useRef(!0),[Ne,je]=o.useState(!1),[v,ee]=o.useState("related"),[te,de]=o.useState("");o.useEffect(()=>()=>{ye.current=!1},[]);const ve=[{key:"related",label:n("knowledgeGraph.relationAssociates"),icon:"∼"},{key:"dependsOn",label:n("knowledgeGraph.relationDependsOn"),icon:"⊕"},{key:"inherits",label:n("knowledgeGraph.relationInherits"),icon:"↑"},{key:"implements",label:n("knowledgeGraph.relationImplements"),icon:"◇"},{key:"calls",label:n("knowledgeGraph.relationCalls"),icon:"→"},{key:"dataFlow",label:n("knowledgeGraph.relationDataFlow"),icon:"⇢"},{key:"conflicts",label:n("knowledgeGraph.relationConflicts"),icon:"✕"},{key:"extends",label:n("knowledgeGraph.relationExtends"),icon:"⊃"}],fe=r=>{var C,b,F,M;q(r),L("view"),m(Kr(r)),j({title:((C=r.name)==null?void 0:C.replace(/\.md$/,""))||"",description:r.description||"",markdown:((b=r.content)==null?void 0:b.markdown)||"",codePattern:((F=r.content)==null?void 0:F.pattern)||"",rationale:((M=r.content)==null?void 0:M.rationale)||"",tags:r.tags||[],tagInput:""}),je(!1),de("")},ie=()=>{q(null),L("view"),je(!1),de("")},be=async()=>{if(!(!H||W)){O(!0);try{const r=H.id||H.name;await ae.knowledgeUpdate(r,{title:N.title,description:N.description,tags:N.tags,content:{...H.content||{},pattern:N.codePattern,markdown:N.markdown,rationale:N.rationale}}),ye.current&&(L("view"),a==null||a())}catch(r){re((r==null?void 0:r.message)||n("common.saveFailed"),{title:n("common.operationFailed"),type:"error"})}finally{ye.current&&O(!1)}}},B=async r=>{if(H)try{await ae.setRecipeAuthority(H.id||H.name,r),a==null||a()}catch(C){re((C==null?void 0:C.message)||n("common.operationFailed"),{title:n("common.operationFailed"),type:"error"})}},K=r=>{const C=r.replace(/\.md$/i,"").toLowerCase();return t.find(b=>at(b).toLowerCase()===C)},xe=o.useMemo(()=>{const r=new Map;if(l)for(const[C,b]of Object.entries(l))r.set(C,b);for(const C of t)C.id&&r.set(C.id,at(C)),C.name&&r.set(C.name,at(C));return r},[t,l]),P=async(r,C)=>{if(!H)return;const b={};if(H.relations)for(const[U,se]of Object.entries(H.relations))b[U]=[...se];const F=b[r]||[],M=C.replace(/\.md$/i,"");if(!F.some(U=>(typeof U=="string"?U:U.id||U.title||"").replace(/\.md$/i,"").toLowerCase()===M.toLowerCase())){b[r]=[...F,M];try{await ae.updateRecipeRelations(H.id||H.name,b),q({...H,relations:b}),je(!1),de(""),a==null||a()}catch(U){re((U==null?void 0:U.message)||n("common.operationFailed"),{title:n("common.operationFailed"),type:"error"})}}},R=async(r,C)=>{if(!H)return;const b={};if(H.relations)for(const[M,U]of Object.entries(H.relations))b[M]=[...U];const F=b[r]||[];b[r]=F.filter(M=>(typeof M=="string"?M:M.id||M.title||"").replace(/\.md$/i,"").toLowerCase()!==C.replace(/\.md$/i,"").toLowerCase()),b[r].length===0&&delete b[r];try{await ae.updateRecipeRelations(H.id||H.name,b),q({...H,relations:b}),a==null||a()}catch(M){re((M==null?void 0:M.message)||n("common.operationFailed"),{title:n("common.operationFailed"),type:"error"})}};o.useEffect(()=>{H&&!t.find(r=>at(r)===at(H))&&ie()},[t,H]),o.useEffect(()=>{d==null&&k(1)},[t.length,d]);const Q=Ct.useMemo(()=>{if(g==="default")return t;const r=[...t],C=h==="asc"?1:-1;return r.sort((b,F)=>{var se,ue,he,D,V,ke,Ce,Ie,Be,Ye,J,Pe;let M=0,U=0;switch(g){case"name":return M=at(b).toLowerCase(),U=at(F).toLowerCase(),C*(M<U?-1:M>U?1:0);case"authorityScore":M=((se=b.stats)==null?void 0:se.authorityScore)??-1,U=((ue=F.stats)==null?void 0:ue.authorityScore)??-1;break;case"authority":M=((he=b.stats)==null?void 0:he.authority)??-1,U=((D=F.stats)==null?void 0:D.authority)??-1;break;case"totalUsage":M=(((V=b.stats)==null?void 0:V.guardUsageCount)??0)+(((ke=b.stats)==null?void 0:ke.humanUsageCount)??0)+(((Ce=b.stats)==null?void 0:Ce.aiUsageCount)??0),U=(((Ie=F.stats)==null?void 0:Ie.guardUsageCount)??0)+(((Be=F.stats)==null?void 0:Be.humanUsageCount)??0)+(((Ye=F.stats)==null?void 0:Ye.aiUsageCount)??0);break;case"lastUsed":{const qe=(J=b.stats)!=null&&J.lastUsedAt?new Date(b.stats.lastUsedAt).getTime():0,ze=(Pe=F.stats)!=null&&Pe.lastUsedAt?new Date(F.stats.lastUsedAt).getTime():0;M=isNaN(qe)?0:qe,U=isNaN(ze)?0:ze;break}case"category":return M=(b.category||"").toLowerCase(),U=(F.category||"").toLowerCase(),C*(M<U?-1:M>U?1:0)}return C*(M-U)}),r},[t,g,h]),ce=Math.ceil(Q.length/G),we=(A-1)*G,Ue=Q.slice(we,we+G),Se=r=>{_(r),window.scrollTo({top:0,behavior:"smooth"})},ne=H?Q.findIndex(r=>at(r)===at(H)):-1,pe=()=>{ne>0&&fe(Q[ne-1])},Le=()=>{ne<Q.length-1&&fe(Q[ne+1])},He=({recipe:r,compact:C})=>{const b=r.kind?Or[r.kind]:null,F=(b==null?void 0:b.icon)||nt,M=r.category||"Utility",U=pt[M]||pt.Utility,se=U.icon,ue=r.knowledgeType,he=C?"text-[8px]":"text-[9px]";return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[b&&e.jsxs("span",{className:`${he} font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${b.bg} ${b.color} ${b.border}`,children:[e.jsx(F,{size:C?9:10}),b.label]}),e.jsxs("span",{className:`${he} font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${U.bg} ${U.color} ${U.border}`,children:[e.jsx(se,{size:C?9:10}),M]}),ue&&e.jsx("span",{className:`${he} font-medium px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-100`,children:da[ue]?n(da[ue]):ue}),r.language&&e.jsx("span",{className:`${he} font-medium px-1.5 py-0.5 rounded bg-slate-100 text-slate-500 uppercase`,children:r.language}),r.trigger&&e.jsx("span",{className:`${he} font-mono font-bold px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100`,children:r.trigger})]})},De=({recipe:r})=>{const C=[];return r.scope&&C.push({icon:Pt,iconClass:"text-teal-400",label:n("candidates.path"),value:r.scope==="universal"?n("common.all"):r.scope==="project-specific"?n("candidates.category"):r.scope}),r.complexity&&C.push({icon:lt,iconClass:"text-orange-400",label:n("candidates.category"),value:r.complexity==="advanced"?n("candidates.confidenceHigh"):r.complexity==="intermediate"?n("candidates.confidenceMedium"):r.complexity==="basic"?n("candidates.confidenceLow"):r.complexity}),r.difficulty&&r.difficulty!==r.complexity&&C.push({icon:lt,iconClass:"text-amber-400",label:n("candidates.category"),value:r.difficulty}),r.moduleName&&C.push({icon:lt,iconClass:"text-purple-400",label:n("candidates.category"),value:r.moduleName,mono:!0}),r.source&&r.source!=="unknown"&&C.push({icon:Pt,iconClass:"text-violet-400",label:n("recipes.sourceLabel"),value:r.source==="bootstrap-scan"?n("recipes.sourceBootstrap"):r.source==="agent"?n("recipes.sourceAiScan"):r.source}),r.version&&C.push({icon:as,iconClass:"text-slate-400",label:n("candidates.language"),value:r.version}),r.updatedAt&&Qa(r.updatedAt)&&C.push({icon:as,iconClass:"text-slate-400",label:n("candidates.updatedAt"),value:xa(r.updatedAt)}),C.length===0&&!r.sourceFile?null:e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:[C.map((b,F)=>{const M=b.icon;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(M,{size:11,className:`${b.iconClass} shrink-0`}),e.jsx("span",{className:"text-slate-400",children:b.label}),e.jsx("span",{className:`font-medium text-slate-600 ${b.mono?"font-mono text-[11px]":""}`,children:b.value})]},F)}),r.sourceFile&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full mt-0.5",children:[e.jsx(wt,{size:11,className:"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-slate-400",children:n("candidates.path")}),e.jsx("code",{className:"font-mono text-[11px] text-slate-500 break-all",title:r.sourceFile,children:r.sourceFile})]})]})};return e.jsxs("div",{className:"relative",children:[t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-24 text-center",children:[e.jsx(Sl,{size:48,className:"text-slate-200 mb-4"}),e.jsx("p",{className:"font-medium text-slate-600 mb-1",children:n("recipes.noResults")}),e.jsx("p",{className:"text-sm text-slate-400",children:n("recipes.noContent")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 text-xs",children:[e.jsx(Pa,{size:14,className:"text-slate-400 shrink-0"}),i.map(r=>{const C=g===r.key;return e.jsxs("button",{onClick:()=>{C?x(b=>b==="asc"?"desc":"asc"):(f(r.key),x(r.defaultDir)),_(1)},className:`px-2 py-1 rounded-md flex items-center gap-0.5 transition-colors ${C?"bg-blue-50 text-blue-700 font-medium border border-blue-200":"text-slate-500 hover:bg-slate-100 border border-transparent"}`,children:[r.label,C&&g!=="default"&&(h==="asc"?e.jsx(Al,{size:12}):e.jsx(Dl,{size:12}))]},r.key)}),e.jsx("span",{className:"ml-auto text-slate-400",children:n("recipes.totalCount",{count:t.length})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:Ue.map(r=>{var U,se;const C=at(r),b=ua(r),F=r.description||r.usageGuide||"",M=H&&at(H)===C;return e.jsxs("div",{onClick:()=>fe(r),className:`bg-white rounded-xl border shadow-sm hover:shadow-md transition-all group relative cursor-pointer overflow-hidden ${M?"border-blue-300 ring-1 ring-blue-200":"border-slate-200"}`,children:[e.jsxs("div",{className:"absolute top-3 right-3 flex gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:ue=>{ue.stopPropagation(),fe(r),L("edit")},className:"p-1.5 bg-white/90 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-md transition-colors shadow-sm border border-slate-100",title:n("recipes.editRecipe"),children:e.jsx(Et,{size:z.sm})}),e.jsx("button",{onClick:ue=>{ue.stopPropagation(),s(r.name||r.id)},className:"p-1.5 bg-white/90 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-md transition-colors shadow-sm border border-slate-100",title:n("recipes.deleteRecipe"),children:e.jsx(ot,{size:z.sm})})]}),e.jsxs("div",{className:"px-5 pt-4 pb-3",children:[e.jsx("h3",{className:"font-bold text-slate-900 text-sm mb-2 pr-16 break-words leading-snug",children:C}),e.jsx(He,{recipe:r,compact:!0})]}),r.tags&&r.tags.length>0&&e.jsxs("div",{className:"px-5 pb-2 flex flex-wrap gap-1",children:[r.tags.slice(0,4).map((ue,he)=>e.jsxs("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 flex items-center gap-0.5",children:[e.jsx(ls,{size:7}),ue]},he)),r.tags.length>4&&e.jsxs("span",{className:"text-[9px] text-slate-400",children:["+",r.tags.length-4]})]}),F&&e.jsx("div",{className:"px-5 pb-3",children:e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed",children:F.replace(/^#+\s*/gm,"").replace(/\*\*/g,"")})}),((U=r.content)==null?void 0:U.markdown)&&e.jsxs("div",{className:"mx-4 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1 px-0.5",children:[e.jsx(nt,{size:9,className:"text-blue-400"}),e.jsx("span",{className:"text-[9px] font-bold text-blue-400 uppercase",children:"Markdown"})]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-lg px-3 py-2 max-h-[60px] overflow-hidden",children:e.jsx("p",{className:"text-[11px] text-slate-600 line-clamp-2 leading-relaxed",children:r.content.markdown.replace(/^#+\s*/gm,"").replace(/\*\*/g,"").replace(/```[\s\S]*?```/g,"").trim().slice(0,200)})})]}),b&&e.jsxs("div",{className:"mx-4 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1 px-0.5",children:[e.jsx(ht,{size:9,className:"text-emerald-400"}),e.jsx("span",{className:"text-[9px] font-bold text-emerald-400 uppercase",children:"Code"})]}),e.jsx("div",{className:"rounded-lg overflow-hidden max-h-[120px]",children:e.jsx(ct,{code:b.split(`
79
78
  `).slice(0,6).join(`
80
- `),language:pa(r)})})]}),e.jsxs("div",{className:"px-5 py-2.5 bg-slate-50/80 dark:bg-[#252a36] border-t border-slate-100 dark:border-slate-700 flex items-center gap-3 text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-bold text-amber-600",children:["★ ",((te=r.stats)==null?void 0:te.authority)??0]}),e.jsx("span",{children:n("recipes.usageCount",{count:r.stats?r.stats.guardUsageCount+r.stats.humanUsageCount+r.stats.aiUsageCount:0})}),r.source&&r.source!=="unknown"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-200",children:"|"}),e.jsx("span",{children:r.source==="bootstrap-scan"?n("recipes.sourceBootstrap"):r.source==="agent"?n("recipes.sourceAiScan"):r.source})]}),r.moduleName&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-200",children:"|"}),e.jsx("span",{className:"font-mono",children:r.moduleName})]}),r.relations&&Object.values(r.relations).flat().length>0&&e.jsxs("span",{className:"ml-auto text-purple-500 font-medium",children:[n("recipes.relations")," ",Object.values(r.relations).flat().length]})]})]},r.id||k)})})]}),t.length>0&&e.jsx(Js,{currentPage:S,totalPages:ie,totalItems:Q.length,pageSize:G,onPageChange:Ie,onPageSizeChange:P}),H&&(()=>{var U,te,de,me;const r=H,k=at(r),b=ua(r),B=pa(r),D=r.content;return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:ce,children:[e.jsx(Ze.Backdrop,{}),e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col ${Z?"w-[min(92vw,1100px)]":"w-[min(92vw,800px)]"}`,style:{animation:"slideInRight 0.25s ease-out"},onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-700 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] shrink-0",children:[e.jsx("div",{className:"flex-1 min-w-0 mr-3",children:e.jsx("h3",{className:"font-bold text-slate-800 text-lg leading-snug break-words",children:k})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:ve,disabled:ne<=0,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:n("common.back"),children:e.jsx(is,{size:F.md})}),e.jsxs("span",{className:"text-xs text-slate-400 tabular-nums",children:[ne+1,"/",Q.length]}),e.jsx("button",{onClick:He,disabled:ne>=Q.length-1,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:n("common.more"),children:e.jsx(rt,{size:F.md})}),e.jsx("div",{className:"w-px h-5 bg-slate-200 mx-1"}),e.jsxs("div",{className:"flex bg-slate-100 p-0.5 rounded-lg mr-1",children:[e.jsxs("button",{onClick:()=>M("view"),className:`px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1 ${R==="view"?"bg-white shadow-sm text-blue-600":"text-slate-400 hover:text-slate-600"}`,children:[e.jsx(os,{size:F.sm})," ",n("common.preview")]}),e.jsxs("button",{onClick:()=>{M("edit")},className:`px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1 ${R==="edit"?"bg-white shadow-sm text-blue-600":"text-slate-400 hover:text-slate-600"}`,children:[e.jsx(Et,{size:F.sm})," ",n("common.edit")]})]}),e.jsx("button",{onClick:X,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400",title:n(Z?"common.collapse":"common.expand"),children:Z?e.jsx(Gs,{size:F.md}):e.jsx(Cs,{size:F.md})}),e.jsx("button",{onClick:()=>{s(r.name||r.id),ce()},className:"p-1.5 hover:bg-red-50 rounded-lg text-red-500 transition-colors",title:n("recipes.deleteRecipe"),children:e.jsx(ot,{size:F.md})}),e.jsx("button",{onClick:ce,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:F.md})})]})]}),R==="edit"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 overflow-y-auto p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.recipeDetail")}),e.jsx("input",{type:"text",value:N.title,onChange:I=>y(V=>({...V,title:I.target.value})),className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 focus:border-blue-300"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.description")}),e.jsx("textarea",{value:N.description,onChange:I=>y(V=>({...V,description:I.target.value})),rows:2,className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.tags")}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:N.tags.map((I,V)=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:[I,e.jsx("button",{onClick:()=>y(Ce=>({...Ce,tags:Ce.tags.filter((Ae,Re)=>Re!==V)})),className:"text-blue-400 hover:text-red-500",children:e.jsx(Xe,{size:10})})]},V))}),e.jsx("div",{className:"flex gap-2",children:e.jsx("input",{type:"text",value:N.tagInput,onChange:I=>y(V=>({...V,tagInput:I.target.value})),onKeyDown:I=>{I.key==="Enter"&&N.tagInput.trim()&&(I.preventDefault(),y(V=>({...V,tags:[...V.tags,V.tagInput.trim()],tagInput:""})))},placeholder:n("recipes.tags"),className:"flex-1 px-3 py-1.5 text-xs border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300"})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",n("recipes.markdown")]}),e.jsx("textarea",{value:N.markdown,onChange:I=>y(V=>({...V,markdown:I.target.value})),rows:4,className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-y font-mono",placeholder:n("recipes.markdown")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block flex items-center gap-1.5",children:[e.jsx(Ht,{size:11,className:"text-emerald-500"})," ",n("recipes.code")]}),e.jsx("div",{className:"border border-slate-200 rounded-lg overflow-hidden",style:{minHeight:200},children:e.jsx(ks,{value:N.codePattern,onChange:I=>y(V=>({...V,codePattern:I})),language:B,height:"200px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.designRationale")}),e.jsx("textarea",{value:N.rationale,onChange:I=>y(V=>({...V,rationale:I.target.value})),rows:3,className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-y",placeholder:n("recipes.designRationale")})]})]}),e.jsxs("div",{className:"px-5 py-3 border-t border-slate-200 flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-slate-400",children:n("recipes.qualityAuthorityScore")}),e.jsx("select",{className:"font-bold text-amber-600 bg-amber-50 border border-amber-100 px-2 py-1 rounded-lg outline-none text-[10px]",value:((U=r.stats)==null?void 0:U.authority)??3,onChange:I=>$(parseInt(I.target.value)),children:[1,2,3,4,5].map(I=>e.jsxs("option",{value:I,children:["⭐".repeat(I)," ",I]},I))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>M("view"),disabled:W,className:"px-4 py-1.5 text-sm text-slate-600 font-medium rounded-lg hover:bg-slate-50",children:n("common.cancel")}),e.jsxs("button",{onClick:je,disabled:W,className:"px-5 py-1.5 bg-blue-600 text-white text-sm font-medium rounded-lg flex items-center gap-1.5 hover:bg-blue-700 disabled:opacity-60",children:[W?e.jsx(Fe,{size:F.sm,className:"animate-spin"}):e.jsx(Ss,{size:F.sm}),n(W?"common.saving":"common.save")]})]})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 space-y-3",children:[e.jsx(Pe,{recipe:r}),e.jsx(Ne,{recipe:r})]}),r.tags&&r.tags.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100 flex flex-wrap items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-slate-300 mr-0.5"}),r.tags.map((I,V)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:I},V))]}),e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Hs,{size:12,className:"text-purple-400"}),e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:n("recipes.relations")}),(()=>{const I=r.relations?Object.values(r.relations).flat().length:0;return I>0?e.jsx("span",{className:"text-[9px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded-full font-bold",children:I}):null})()]}),e.jsx("button",{onClick:()=>{ye(!we),ue("")},className:`text-[9px] px-2 py-0.5 rounded font-bold flex items-center gap-1 transition-colors ${we?"bg-slate-200 text-slate-600":"bg-purple-500 text-white hover:bg-purple-600"}`,children:we?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{size:10})," ",n("common.cancel")]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{size:10})," ",n("recipes.editBtn")]})})]}),we&&e.jsxs("div",{className:"mb-3 bg-purple-50/80 border border-purple-200 rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("select",{value:v,onChange:I=>ee(I.target.value),className:"text-[10px] font-bold bg-white border border-purple-200 text-purple-700 rounded px-2 py-1 outline-none",children:fe.map(I=>e.jsxs("option",{value:I.key,children:[I.icon," ",I.label]},I.key))}),e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(ft,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-slate-300"}),e.jsx("input",{type:"text",placeholder:n("recipes.searchPlaceholder"),value:ae,onChange:I=>ue(I.target.value),className:"w-full text-xs bg-white border border-purple-200 rounded pl-7 pr-2 py-1 outline-none",autoFocus:!0})]})]}),ae.length>0&&e.jsx("div",{className:"max-h-36 overflow-y-auto rounded border border-purple-100 bg-white divide-y divide-slate-100",children:(()=>{const I=t.filter(V=>at(V)===k?!1:at(V).toLowerCase().includes(ae.toLowerCase())).slice(0,10);return I.length?I.map(V=>{const Ce=at(V),Ae=r.relations&&Object.values(r.relations).flat().some(Re=>(typeof Re=="string"?Re:Re.target||Re.id||Re.title||"").replace(/\.md$/i,"").toLowerCase()===Ce.toLowerCase());return e.jsxs("div",{className:`flex items-center justify-between px-3 py-1.5 text-xs ${Ae?"bg-slate-50 text-slate-400":"hover:bg-purple-50 cursor-pointer"}`,onClick:()=>!Ae&&L(v,Ce),children:[e.jsx("span",{className:"font-medium truncate mr-2",children:Ce}),Ae?e.jsx("span",{className:"text-[9px] text-slate-400 font-bold shrink-0",children:n("recipes.relations")}):e.jsxs("span",{className:"text-[9px] text-purple-600 font-bold shrink-0",children:["+ ",n("recipes.editBtn")]})]},Ce)}):e.jsx("div",{className:"text-xs text-slate-400 py-3 text-center",children:n("recipes.noResults")})})()})]}),r.relations&&Object.entries(r.relations).some(([,I])=>Array.isArray(I)&&I.length>0)?e.jsx("div",{className:"space-y-1.5",children:fe.map(({key:I,label:V,icon:Ce})=>{var Re;const Ae=(Re=r.relations)==null?void 0:Re[I];return!Ae||!Array.isArray(Ae)||Ae.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"text-[10px] font-mono text-slate-500 w-14 shrink-0 pt-0.5",children:[Ce," ",V]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:Ae.map((Be,Ye)=>{const J=typeof Be=="string"?Be:Be.target||Be.id||Be.title||JSON.stringify(Be),Le=K(J)||(xe.has(J)?K(xe.get(J)):void 0),qe=Le?at(Le):xe.get(J)||J;return e.jsxs("span",{className:`group/rel inline-flex items-center gap-1 px-1.5 py-0.5 border rounded text-[10px] font-mono transition-colors ${Le?"bg-purple-50 border-purple-200 text-purple-700 cursor-pointer hover:bg-purple-100":"bg-white border-slate-200 text-slate-600"}`,onClick:()=>Le&&he(Le),title:Le?n("candidates.viewDetail"):qe,children:[qe.replace(/\.md$/i,""),e.jsx("button",{onClick:ze=>{ze.stopPropagation(),T(I,J)},className:"opacity-0 group-hover/rel:opacity-100 text-red-400 hover:text-red-600 transition-opacity ml-0.5",title:n("common.delete"),children:e.jsx(Xe,{size:10})})]},Ye)})})]},I)})}):!we&&e.jsx("div",{className:"text-xs text-slate-300 py-2 text-center",children:n("recipes.noContent")})]}),e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-amber-50/60 dark:bg-amber-900/20 rounded-xl p-3 text-center border border-amber-100 dark:border-amber-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:((te=r.stats)==null?void 0:te.authority)??"—"}),e.jsx("div",{className:"text-[10px] text-amber-500 font-medium",children:n("recipes.qualityAuthorityScore")})]}),e.jsxs("div",{className:"bg-blue-50/60 dark:bg-blue-900/20 rounded-xl p-3 text-center border border-blue-100 dark:border-blue-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:((de=r.stats)==null?void 0:de.authorityScore)!=null?r.stats.authorityScore.toFixed(1):"—"}),e.jsx("div",{className:"text-[10px] text-blue-500 font-medium",children:n("recipes.qualityGreat")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-lg font-bold text-slate-800",children:r.stats?r.stats.guardUsageCount+r.stats.humanUsageCount+r.stats.aiUsageCount:0}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:n("recipes.qualitySolid")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-sm font-bold text-slate-700",children:xa((me=r.stats)==null?void 0:me.lastUsedAt)||n("recipes.noContent")}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:n("recipes.qualityGood")})]})]}),r.stats!=null&&(r.stats.guardUsageCount>0||r.stats.humanUsageCount>0||r.stats.aiUsageCount>0)&&e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-slate-400",children:[e.jsxs("span",{children:["Guard: ",r.stats.guardUsageCount]}),e.jsxs("span",{children:["Human: ",r.stats.humanUsageCount]}),e.jsxs("span",{children:["AI: ",r.stats.aiUsageCount]})]})]}),r.reasoning&&(r.reasoning.whyStandard||r.reasoning.sources&&r.reasoning.sources.length>0)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-amber-400"})," ",n("recipes.reasoning")]}),e.jsxs("div",{className:"bg-amber-50/30 dark:bg-amber-900/15 border border-amber-100 dark:border-amber-800/40 rounded-xl p-4 space-y-2.5",children:[r.reasoning.whyStandard&&e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:r.reasoning.whyStandard}),r.reasoning.sources&&r.reasoning.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:n("recipes.sourceColon")}),r.reasoning.sources.map((I,V)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-white border border-amber-200 rounded text-amber-700 font-mono",children:I},V))]}),r.reasoning.confidence!=null&&r.reasoning.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:n("recipes.confidenceColon")}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round(r.reasoning.confidence*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round(r.reasoning.confidence*100),"%"]})]}),r.reasoning.alternatives&&r.reasoning.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:n("recipes.alternativesLabel")}),r.reasoning.alternatives.map((I,V)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-slate-100 border border-slate-200 rounded text-slate-600",children:I},V))]})]})]}),r.quality&&r.quality.grade&&r.quality.grade!=="F"&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.qualityGrade")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${r.quality.grade==="A"?"text-emerald-600":r.quality.grade==="B"?"text-blue-600":r.quality.grade==="C"?"text-amber-600":r.quality.grade==="D"?"text-orange-600":"text-slate-400"}`,children:r.quality.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-[10px]",children:[r.quality.completeness!=null&&r.quality.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:r.quality.completeness}),e.jsx("div",{className:"text-slate-400",children:n("recipes.qualityCompleteness")})]}),r.quality.adaptation!=null&&r.quality.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:r.quality.adaptation}),e.jsx("div",{className:"text-slate-400",children:n("recipes.qualityAdaptation")})]}),r.quality.documentation!=null&&r.quality.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:r.quality.documentation}),e.jsx("div",{className:"text-slate-400",children:n("recipes.qualityDocumentation")})]})]})]})]}),r.description&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.description")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:r.description})]}),(D==null?void 0:D.markdown)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",n("recipes.markdown")]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 leading-relaxed",children:e.jsx(gt,{content:D.markdown})})})]}),r.headers&&r.headers.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.headers")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.headers.map((I,V)=>e.jsx("code",{className:"px-2.5 py-1 bg-violet-50 text-violet-700 border border-violet-100 rounded-md text-[10px] font-mono font-medium",children:I},V))})]}),b&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ht,{size:11,className:"text-emerald-500"})," ",n("recipes.code")]}),e.jsx(dt,{code:b,language:B,showLineNumbers:!0})]}),(D==null?void 0:D.rationale)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.designRationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:D.rationale})})]}),(D==null?void 0:D.steps)&&D.steps.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.steps")}),e.jsx("div",{className:"space-y-2",children:D.steps.map((I,V)=>{if(typeof I=="string")return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:V+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:I})]},V);const Ce=typeof I.title=="string"?I.title:"",Ae=typeof I.description=="string"?I.description:"",Re=typeof I.code=="string"?I.code:"";return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:V+1}),Ce&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:Ce})]}),Ae&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:Ae}),Re&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:Re})]},V)})})]}),(D==null?void 0:D.codeChanges)&&D.codeChanges.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.codeChanges")}),e.jsx("div",{className:"space-y-2",children:D.codeChanges.map((I,V)=>e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-slate-50 border-b border-slate-200 flex items-center gap-2",children:[e.jsx(ht,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-slate-600",children:I.file})]}),I.explanation&&e.jsx("p",{className:"text-[11px] text-slate-500 px-3 py-1.5 border-b border-slate-100 bg-yellow-50/30",children:I.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/20 border-b border-slate-100",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:"Before"}),e.jsx("pre",{className:"text-[11px] text-slate-600 whitespace-pre-wrap break-words font-mono",children:I.before||n("recipes.emptyValue")})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/20",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:"After"}),e.jsx("pre",{className:"text-[11px] text-slate-700 whitespace-pre-wrap break-words font-mono",children:I.after})]})]},V))})]}),(D==null?void 0:D.verification)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.validation")}),e.jsxs("div",{className:"bg-teal-50/50 border border-teal-100 rounded-xl p-4 space-y-1.5",children:[D.verification.method&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:n("recipes.verificationMethod")})," ",D.verification.method]}),D.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:n("recipes.verificationExpected")})," ",D.verification.expectedResult]}),D.verification.testCode&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md overflow-x-auto whitespace-pre-wrap mt-1",children:D.verification.testCode})]})]}),r.constraints&&(()=>{var Ce,Ae,Re,Be,Ye,J,Le,qe;const I=r.constraints,V=(((Ce=I.guards)==null?void 0:Ce.length)||0)+(((Ae=I.boundaries)==null?void 0:Ae.length)||0)+(((Re=I.preconditions)==null?void 0:Re.length)||0)+(((Be=I.sideEffects)==null?void 0:Be.length)||0);return V?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ut,{size:11,className:"text-amber-500"})," ",n("recipes.constraints")," ",e.jsx("span",{className:"text-amber-500 font-mono",children:V})]}),e.jsxs("div",{className:"space-y-1.5 text-xs text-slate-600",children:[(Ye=I.guards)==null?void 0:Ye.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${ze.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-[10px] bg-slate-100 px-1.5 py-0.5 rounded",children:ze.pattern}),ze.message&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["— ",ze.message]})]},Ve)),(J=I.boundaries)==null?void 0:J.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),ze]},Ve)),(Le=I.preconditions)==null?void 0:Le.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),ze]},Ve)),(qe=I.sideEffects)==null?void 0:qe.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),ze]},Ve))]})]}):null})()]})]})]})})()]})};function Dt(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}function Vr(t){const s=new Map(t.map(l=>[l.date,l])),a=[];for(let l=6;l>=0;l--){const d=new Date;d.setDate(d.getDate()-l);const i=d.toISOString().slice(0,10);a.push(s.get(i)||{date:i,input_tokens:0,output_tokens:0,total_tokens:0,call_count:0})}return a}const Jr={user:"bg-blue-500",mcp:"bg-purple-500",bootstrap:"bg-amber-500",guard:"bg-rose-500",analyst:"bg-indigo-500",producer:"bg-green-500"},Yr=()=>{const{t}=_e(),[s,a]=o.useState([]),[l,d]=o.useState([]),[i,u]=o.useState({input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}),[p,n]=o.useState(!0),[g,f]=o.useState(null);o.useEffect(()=>{let j=!1;return(async()=>{try{const w=await se.getTokenUsage7Days();if(j)return;a(w.daily||[]),d(w.bySource||[]),u(w.summary||{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0})}catch(w){j||f(w.message||t("tokenUsageChart.loadFailed"))}finally{j||n(!1)}})(),()=>{j=!0}},[]);const h=o.useMemo(()=>Vr(s),[s]),x=o.useMemo(()=>Math.max(...h.map(j=>j.total_tokens),1),[h]);if(p)return e.jsxs("div",{className:"flex items-center justify-center py-10",children:[e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-blue-500 border-t-transparent"}),e.jsx("span",{className:"ml-2 text-slate-500 text-sm",children:t("tokenUsageChart.loading")})]});if(g)return e.jsx("p",{className:"text-red-500 text-sm py-4 text-center",children:g});const c=i.total_tokens===0;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(xs,{label:t("tokenUsageChart.totalToken"),value:Dt(i.total_tokens),sub:t("tokenUsageChart.totalSub"),color:"blue"}),e.jsx(xs,{label:t("tokenUsageChart.input"),value:Dt(i.input_tokens),sub:"Prompt",color:"green"}),e.jsx(xs,{label:t("tokenUsageChart.output"),value:Dt(i.output_tokens),sub:"Completion",color:"purple"}),e.jsx(xs,{label:t("tokenUsageChart.calls"),value:String(i.call_count),sub:t("tokenUsageChart.avgPerCall",{avg:Dt(i.avg_per_call)}),color:"amber"})]}),c?e.jsx("div",{className:"text-center py-8 text-slate-400 text-sm",children:t("tokenUsageChart.emptyState")}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-slate-700 mb-3",children:t("tokenUsageChart.dailyUsage")}),e.jsx("div",{className:"flex items-end gap-1.5 h-40",children:h.map(j=>{const w=j.input_tokens/x*100,C=j.output_tokens/x*100,E=t(`tokenUsageChart.weekday${new Date(j.date+"T00:00:00").getDay()}`);return e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-1 group relative",children:[e.jsxs("div",{className:"absolute -top-16 left-1/2 -translate-x-1/2 bg-slate-800 text-white text-xs rounded px-2 py-1 opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-10",children:[e.jsx("p",{children:j.date}),e.jsx("p",{children:t("tokenUsageChart.dailyDetail",{input:Dt(j.input_tokens),output:Dt(j.output_tokens)})}),e.jsx("p",{children:t("tokenUsageChart.dailyCalls",{count:String(j.call_count)})})]}),e.jsxs("div",{className:"w-full flex flex-col justify-end",style:{height:"120px"},children:[e.jsx("div",{className:"bg-green-400 rounded-t-sm w-full transition-all",style:{height:`${w}%`,minHeight:j.input_tokens>0?"2px":"0"}}),e.jsx("div",{className:"bg-purple-400 rounded-b-sm w-full transition-all",style:{height:`${C}%`,minHeight:j.output_tokens>0?"2px":"0"}})]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:E})]},j.date)})}),e.jsxs("div",{className:"flex gap-4 mt-2 text-xs text-slate-500 justify-center",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-green-400 inline-block"})," ",t("tokenUsageChart.legendInput")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-purple-400 inline-block"})," ",t("tokenUsageChart.legendOutput")]})]})]}),l.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-slate-700 mb-3",children:t("tokenUsageChart.sourceDistribution")}),e.jsx("div",{className:"space-y-2",children:l.map(j=>{const w=i.total_tokens>0?j.total_tokens/i.total_tokens*100:0,C=Jr[j.source]||"bg-slate-400";return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"w-20 text-xs text-slate-600 text-right truncate",children:j.source}),e.jsx("div",{className:"flex-1 bg-slate-100 rounded-full h-3 overflow-hidden",children:e.jsx("div",{className:`${C} h-full rounded-full transition-all`,style:{width:`${w}%`,minWidth:w>0?"4px":"0"}})}),e.jsx("span",{className:"w-16 text-xs text-slate-500 text-right",children:Dt(j.total_tokens)}),e.jsxs("span",{className:"w-12 text-xs text-slate-400 text-right",children:[w.toFixed(0),"%"]})]},j.source)})})]})]})]})};function xs({label:t,value:s,sub:a,color:l}){const d={blue:"bg-blue-50 border-blue-200 text-blue-700",green:"bg-green-50 border-green-200 text-green-700",purple:"bg-purple-50 border-purple-200 text-purple-700",amber:"bg-amber-50 border-amber-200 text-amber-700"},i=d[l]||d.blue;return e.jsxs("div",{className:`rounded-lg border p-3 ${i}`,children:[e.jsx("p",{className:"text-xs opacity-70",children:t}),e.jsx("p",{className:"text-xl font-bold",children:s}),e.jsx("p",{className:"text-[10px] opacity-60",children:a})]})}const vt=({id:t,title:s,icon:a,isExpanded:l,onToggle:d,children:i})=>e.jsxs("section",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>d(t),className:"w-full flex items-center justify-between p-4 bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[a,e.jsx("h2",{className:"text-lg font-bold text-slate-800",children:s})]}),l?e.jsx(Gt,{size:F.lg}):e.jsx(rt,{size:F.lg})]}),l&&e.jsx("div",{className:"p-4 bg-white",children:i})]}),Qr=()=>{const{t}=_e(),[s,a]=o.useState(new Set(["quick-start"])),l=d=>{const i=new Set(s);i.has(d)?i.delete(d):i.add(d),a(i)};return e.jsxs("div",{className:"max-w-5xl mx-auto py-8 px-4",children:[e.jsxs("div",{className:"mb-8 text-center",children:[e.jsxs("h1",{className:"text-4xl font-bold text-slate-900 mb-4 flex items-center justify-center gap-3",children:[e.jsx(tt,{size:F.xxl,className:"text-blue-600"}),t("help.pageTitle")]}),e.jsx("p",{className:"text-slate-600 text-lg max-w-3xl mx-auto whitespace-nowrap",children:t("help.subtitle")}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:t("help.techSpecs")}),e.jsxs("div",{className:"mt-6 flex gap-4 justify-center text-sm",children:[e.jsx("a",{href:"https://github.com/GxFn/AutoSnippet",target:"_blank",rel:"noopener noreferrer",className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:t("help.viewGithub")}),e.jsx("a",{href:"https://github.com/GxFn/AutoSnippet/blob/main/README.md",target:"_blank",rel:"noopener noreferrer",className:"px-4 py-2 border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 transition-colors",children:t("help.fullDocs")})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(vt,{id:"token-usage",title:t("help.tokenUsageLast7Days"),icon:e.jsx(La,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("token-usage"),onToggle:l,children:e.jsx(Yr,{})}),e.jsx(vt,{id:"quick-start",title:t("help.quickStart"),icon:e.jsx(Xt,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("quick-start"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-blue-50 rounded-lg p-4 border border-blue-200",children:[e.jsx("div",{className:"bg-blue-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"1"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.step1Title")}),e.jsx("pre",{className:"bg-blue-100/70 text-blue-900 px-3 py-2 rounded text-xs overflow-hidden",children:e.jsxs("code",{children:["npm install -g autosnippet",`
79
+ `),language:pa(r)})})]}),e.jsxs("div",{className:"px-5 py-2.5 bg-slate-50/80 dark:bg-[#252a36] border-t border-slate-100 dark:border-slate-700 flex items-center gap-3 text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-bold text-amber-600",children:["★ ",((se=r.stats)==null?void 0:se.authority)??0]}),e.jsx("span",{children:n("recipes.usageCount",{count:r.stats?r.stats.guardUsageCount+r.stats.humanUsageCount+r.stats.aiUsageCount:0})}),r.source&&r.source!=="unknown"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-200",children:"|"}),e.jsx("span",{children:r.source==="bootstrap-scan"?n("recipes.sourceBootstrap"):r.source==="agent"?n("recipes.sourceAiScan"):r.source})]}),r.moduleName&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-200",children:"|"}),e.jsx("span",{className:"font-mono",children:r.moduleName})]}),r.relations&&Object.values(r.relations).flat().length>0&&e.jsxs("span",{className:"ml-auto text-purple-500 font-medium",children:[n("recipes.relations")," ",Object.values(r.relations).flat().length]})]})]},r.id||C)})})]}),t.length>0&&e.jsx(Js,{currentPage:A,totalPages:ce,totalItems:Q.length,pageSize:G,onPageChange:Se,onPageSizeChange:E}),H&&(()=>{var U,se,ue,he;const r=H,C=at(r),b=ua(r),F=pa(r),M=r.content;return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:ie,children:[e.jsx(Ze.Backdrop,{}),e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col ${Z?"w-[min(92vw,1100px)]":"w-[min(92vw,800px)]"}`,style:{animation:"slideInRight 0.25s ease-out"},onClick:D=>D.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-700 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] shrink-0",children:[e.jsx("div",{className:"flex-1 min-w-0 mr-3",children:e.jsx("h3",{className:"font-bold text-slate-800 text-lg leading-snug break-words",children:C})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:pe,disabled:ne<=0,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:n("common.back"),children:e.jsx(is,{size:z.md})}),e.jsxs("span",{className:"text-xs text-slate-400 tabular-nums",children:[ne+1,"/",Q.length]}),e.jsx("button",{onClick:Le,disabled:ne>=Q.length-1,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:n("common.more"),children:e.jsx(rt,{size:z.md})}),e.jsx("div",{className:"w-px h-5 bg-slate-200 mx-1"}),e.jsxs("div",{className:"flex bg-slate-100 p-0.5 rounded-lg mr-1",children:[e.jsxs("button",{onClick:()=>L("view"),className:`px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1 ${I==="view"?"bg-white shadow-sm text-blue-600":"text-slate-400 hover:text-slate-600"}`,children:[e.jsx(os,{size:z.sm})," ",n("common.preview")]}),e.jsxs("button",{onClick:()=>{L("edit")},className:`px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1 ${I==="edit"?"bg-white shadow-sm text-blue-600":"text-slate-400 hover:text-slate-600"}`,children:[e.jsx(Et,{size:z.sm})," ",n("common.edit")]})]}),e.jsx("button",{onClick:X,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400",title:n(Z?"common.collapse":"common.expand"),children:Z?e.jsx(Gs,{size:z.md}):e.jsx(Cs,{size:z.md})}),e.jsx("button",{onClick:()=>{s(r.name||r.id),ie()},className:"p-1.5 hover:bg-red-50 rounded-lg text-red-500 transition-colors",title:n("recipes.deleteRecipe"),children:e.jsx(ot,{size:z.md})}),e.jsx("button",{onClick:ie,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:z.md})})]})]}),I==="edit"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 overflow-y-auto p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.recipeDetail")}),e.jsx("input",{type:"text",value:N.title,onChange:D=>j(V=>({...V,title:D.target.value})),className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 focus:border-blue-300"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.description")}),e.jsx("textarea",{value:N.description,onChange:D=>j(V=>({...V,description:D.target.value})),rows:2,className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.tags")}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:N.tags.map((D,V)=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:[D,e.jsx("button",{onClick:()=>j(ke=>({...ke,tags:ke.tags.filter((Ce,Ie)=>Ie!==V)})),className:"text-blue-400 hover:text-red-500",children:e.jsx(Xe,{size:10})})]},V))}),e.jsx("div",{className:"flex gap-2",children:e.jsx("input",{type:"text",value:N.tagInput,onChange:D=>j(V=>({...V,tagInput:D.target.value})),onKeyDown:D=>{D.key==="Enter"&&N.tagInput.trim()&&(D.preventDefault(),j(V=>({...V,tags:[...V.tags,V.tagInput.trim()],tagInput:""})))},placeholder:n("recipes.tags"),className:"flex-1 px-3 py-1.5 text-xs border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300"})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",n("recipes.markdown")]}),e.jsx("textarea",{value:N.markdown,onChange:D=>j(V=>({...V,markdown:D.target.value})),rows:4,className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-y font-mono",placeholder:n("recipes.markdown")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block flex items-center gap-1.5",children:[e.jsx(Ht,{size:11,className:"text-emerald-500"})," ",n("recipes.code")]}),e.jsx("div",{className:"border border-slate-200 rounded-lg overflow-hidden",style:{minHeight:200},children:e.jsx(ks,{value:N.codePattern,onChange:D=>j(V=>({...V,codePattern:D})),language:F,height:"200px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.designRationale")}),e.jsx("textarea",{value:N.rationale,onChange:D=>j(V=>({...V,rationale:D.target.value})),rows:3,className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-y",placeholder:n("recipes.designRationale")})]})]}),e.jsxs("div",{className:"px-5 py-3 border-t border-slate-200 flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-slate-400",children:n("recipes.qualityAuthorityScore")}),e.jsx("select",{className:"font-bold text-amber-600 bg-amber-50 border border-amber-100 px-2 py-1 rounded-lg outline-none text-[10px]",value:((U=r.stats)==null?void 0:U.authority)??3,onChange:D=>B(parseInt(D.target.value)),children:[1,2,3,4,5].map(D=>e.jsxs("option",{value:D,children:["⭐".repeat(D)," ",D]},D))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>L("view"),disabled:W,className:"px-4 py-1.5 text-sm text-slate-600 font-medium rounded-lg hover:bg-slate-50",children:n("common.cancel")}),e.jsxs("button",{onClick:be,disabled:W,className:"px-5 py-1.5 bg-blue-600 text-white text-sm font-medium rounded-lg flex items-center gap-1.5 hover:bg-blue-700 disabled:opacity-60",children:[W?e.jsx(Me,{size:z.sm,className:"animate-spin"}):e.jsx(Ss,{size:z.sm}),n(W?"common.saving":"common.save")]})]})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 space-y-3",children:[e.jsx(He,{recipe:r}),e.jsx(De,{recipe:r})]}),r.tags&&r.tags.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100 flex flex-wrap items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-slate-300 mr-0.5"}),r.tags.map((D,V)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:D},V))]}),e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Hs,{size:12,className:"text-purple-400"}),e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:n("recipes.relations")}),(()=>{const D=r.relations?Object.values(r.relations).flat().length:0;return D>0?e.jsx("span",{className:"text-[9px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded-full font-bold",children:D}):null})()]}),e.jsx("button",{onClick:()=>{je(!Ne),de("")},className:`text-[9px] px-2 py-0.5 rounded font-bold flex items-center gap-1 transition-colors ${Ne?"bg-slate-200 text-slate-600":"bg-purple-500 text-white hover:bg-purple-600"}`,children:Ne?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{size:10})," ",n("common.cancel")]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{size:10})," ",n("recipes.editBtn")]})})]}),Ne&&e.jsxs("div",{className:"mb-3 bg-purple-50/80 border border-purple-200 rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("select",{value:v,onChange:D=>ee(D.target.value),className:"text-[10px] font-bold bg-white border border-purple-200 text-purple-700 rounded px-2 py-1 outline-none",children:ve.map(D=>e.jsxs("option",{value:D.key,children:[D.icon," ",D.label]},D.key))}),e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(ft,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-slate-300"}),e.jsx("input",{type:"text",placeholder:n("recipes.searchPlaceholder"),value:te,onChange:D=>de(D.target.value),className:"w-full text-xs bg-white border border-purple-200 rounded pl-7 pr-2 py-1 outline-none",autoFocus:!0})]})]}),te.length>0&&e.jsx("div",{className:"max-h-36 overflow-y-auto rounded border border-purple-100 bg-white divide-y divide-slate-100",children:(()=>{const D=t.filter(V=>at(V)===C?!1:at(V).toLowerCase().includes(te.toLowerCase())).slice(0,10);return D.length?D.map(V=>{const ke=at(V),Ce=r.relations&&Object.values(r.relations).flat().some(Ie=>(typeof Ie=="string"?Ie:Ie.target||Ie.id||Ie.title||"").replace(/\.md$/i,"").toLowerCase()===ke.toLowerCase());return e.jsxs("div",{className:`flex items-center justify-between px-3 py-1.5 text-xs ${Ce?"bg-slate-50 text-slate-400":"hover:bg-purple-50 cursor-pointer"}`,onClick:()=>!Ce&&P(v,ke),children:[e.jsx("span",{className:"font-medium truncate mr-2",children:ke}),Ce?e.jsx("span",{className:"text-[9px] text-slate-400 font-bold shrink-0",children:n("recipes.relations")}):e.jsxs("span",{className:"text-[9px] text-purple-600 font-bold shrink-0",children:["+ ",n("recipes.editBtn")]})]},ke)}):e.jsx("div",{className:"text-xs text-slate-400 py-3 text-center",children:n("recipes.noResults")})})()})]}),r.relations&&Object.entries(r.relations).some(([,D])=>Array.isArray(D)&&D.length>0)?e.jsx("div",{className:"space-y-1.5",children:ve.map(({key:D,label:V,icon:ke})=>{var Ie;const Ce=(Ie=r.relations)==null?void 0:Ie[D];return!Ce||!Array.isArray(Ce)||Ce.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"text-[10px] font-mono text-slate-500 shrink-0 whitespace-nowrap pt-0.5",children:[ke," ",V]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:Ce.map((Be,Ye)=>{const J=typeof Be=="string"?Be:Be.target||Be.id||Be.title||JSON.stringify(Be),Pe=K(J)||(xe.has(J)?K(xe.get(J)):void 0),qe=Pe?at(Pe):xe.get(J)||J;return e.jsxs("span",{className:`group/rel inline-flex items-center gap-1 px-1.5 py-0.5 border rounded text-[10px] font-mono transition-colors ${Pe?"bg-purple-50 border-purple-200 text-purple-700 cursor-pointer hover:bg-purple-100":"bg-white border-slate-200 text-slate-600"}`,onClick:()=>Pe&&fe(Pe),title:Pe?n("candidates.viewDetail"):qe,children:[qe.replace(/\.md$/i,""),e.jsx("button",{onClick:ze=>{ze.stopPropagation(),R(D,J)},className:"opacity-0 group-hover/rel:opacity-100 text-red-400 hover:text-red-600 transition-opacity ml-0.5",title:n("common.delete"),children:e.jsx(Xe,{size:10})})]},Ye)})})]},D)})}):!Ne&&e.jsx("div",{className:"text-xs text-slate-300 py-2 text-center",children:n("recipes.noContent")})]}),e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-amber-50/60 dark:bg-amber-900/20 rounded-xl p-3 text-center border border-amber-100 dark:border-amber-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:((se=r.stats)==null?void 0:se.authority)??"—"}),e.jsx("div",{className:"text-[10px] text-amber-500 font-medium",children:n("recipes.qualityAuthorityScore")})]}),e.jsxs("div",{className:"bg-blue-50/60 dark:bg-blue-900/20 rounded-xl p-3 text-center border border-blue-100 dark:border-blue-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:((ue=r.stats)==null?void 0:ue.authorityScore)!=null?r.stats.authorityScore.toFixed(1):"—"}),e.jsx("div",{className:"text-[10px] text-blue-500 font-medium",children:n("recipes.qualityGreat")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-lg font-bold text-slate-800",children:r.stats?r.stats.guardUsageCount+r.stats.humanUsageCount+r.stats.aiUsageCount:0}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:n("recipes.qualitySolid")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-sm font-bold text-slate-700",children:xa((he=r.stats)==null?void 0:he.lastUsedAt)||n("recipes.noContent")}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:n("recipes.qualityGood")})]})]}),r.stats!=null&&(r.stats.guardUsageCount>0||r.stats.humanUsageCount>0||r.stats.aiUsageCount>0)&&e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-slate-400",children:[e.jsxs("span",{children:["Guard: ",r.stats.guardUsageCount]}),e.jsxs("span",{children:["Human: ",r.stats.humanUsageCount]}),e.jsxs("span",{children:["AI: ",r.stats.aiUsageCount]})]})]}),r.reasoning&&(r.reasoning.whyStandard||r.reasoning.sources&&r.reasoning.sources.length>0)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-amber-400"})," ",n("recipes.reasoning")]}),e.jsxs("div",{className:"bg-amber-50/30 dark:bg-amber-900/15 border border-amber-100 dark:border-amber-800/40 rounded-xl p-4 space-y-2.5",children:[r.reasoning.whyStandard&&e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:r.reasoning.whyStandard}),r.reasoning.sources&&r.reasoning.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:n("recipes.sourceColon")}),r.reasoning.sources.map((D,V)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-white border border-amber-200 rounded text-amber-700 font-mono",children:D},V))]}),r.reasoning.confidence!=null&&r.reasoning.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:n("recipes.confidenceColon")}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round(r.reasoning.confidence*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round(r.reasoning.confidence*100),"%"]})]}),r.reasoning.alternatives&&r.reasoning.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:n("recipes.alternativesLabel")}),r.reasoning.alternatives.map((D,V)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-slate-100 border border-slate-200 rounded text-slate-600",children:D},V))]})]})]}),r.quality&&r.quality.grade&&r.quality.grade!=="F"&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.qualityGrade")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${r.quality.grade==="A"?"text-emerald-600":r.quality.grade==="B"?"text-blue-600":r.quality.grade==="C"?"text-amber-600":r.quality.grade==="D"?"text-orange-600":"text-slate-400"}`,children:r.quality.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-[10px]",children:[r.quality.completeness!=null&&r.quality.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:r.quality.completeness}),e.jsx("div",{className:"text-slate-400",children:n("recipes.qualityCompleteness")})]}),r.quality.adaptation!=null&&r.quality.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:r.quality.adaptation}),e.jsx("div",{className:"text-slate-400",children:n("recipes.qualityAdaptation")})]}),r.quality.documentation!=null&&r.quality.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:r.quality.documentation}),e.jsx("div",{className:"text-slate-400",children:n("recipes.qualityDocumentation")})]})]})]})]}),r.description&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.description")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:r.description})]}),(M==null?void 0:M.markdown)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",n("recipes.markdown")]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 leading-relaxed",children:e.jsx(gt,{content:M.markdown})})})]}),r.headers&&r.headers.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.headers")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.headers.map((D,V)=>e.jsx("code",{className:"px-2.5 py-1 bg-violet-50 text-violet-700 border border-violet-100 rounded-md text-[10px] font-mono font-medium",children:D},V))})]}),b&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ht,{size:11,className:"text-emerald-500"})," ",n("recipes.code")]}),e.jsx(ct,{code:b,language:F,showLineNumbers:!0})]}),(M==null?void 0:M.rationale)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.designRationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:M.rationale})})]}),(M==null?void 0:M.steps)&&M.steps.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.steps")}),e.jsx("div",{className:"space-y-2",children:M.steps.map((D,V)=>{if(typeof D=="string")return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:V+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:D})]},V);const ke=typeof D.title=="string"?D.title:"",Ce=typeof D.description=="string"?D.description:"",Ie=typeof D.code=="string"?D.code:"";return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:V+1}),ke&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:ke})]}),Ce&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:Ce}),Ie&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:Ie})]},V)})})]}),(M==null?void 0:M.codeChanges)&&M.codeChanges.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.codeChanges")}),e.jsx("div",{className:"space-y-2",children:M.codeChanges.map((D,V)=>e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-slate-50 border-b border-slate-200 flex items-center gap-2",children:[e.jsx(ht,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-slate-600",children:D.file})]}),D.explanation&&e.jsx("p",{className:"text-[11px] text-slate-500 px-3 py-1.5 border-b border-slate-100 bg-yellow-50/30",children:D.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/20 border-b border-slate-100",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:"Before"}),e.jsx("pre",{className:"text-[11px] text-slate-600 whitespace-pre-wrap break-words font-mono",children:D.before||n("recipes.emptyValue")})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/20",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:"After"}),e.jsx("pre",{className:"text-[11px] text-slate-700 whitespace-pre-wrap break-words font-mono",children:D.after})]})]},V))})]}),(M==null?void 0:M.verification)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.validation")}),e.jsxs("div",{className:"bg-teal-50/50 border border-teal-100 rounded-xl p-4 space-y-1.5",children:[M.verification.method&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:n("recipes.verificationMethod")})," ",M.verification.method]}),M.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:n("recipes.verificationExpected")})," ",M.verification.expectedResult]}),M.verification.testCode&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md overflow-x-auto whitespace-pre-wrap mt-1",children:M.verification.testCode})]})]}),r.constraints&&(()=>{var ke,Ce,Ie,Be,Ye,J,Pe,qe;const D=r.constraints,V=(((ke=D.guards)==null?void 0:ke.length)||0)+(((Ce=D.boundaries)==null?void 0:Ce.length)||0)+(((Ie=D.preconditions)==null?void 0:Ie.length)||0)+(((Be=D.sideEffects)==null?void 0:Be.length)||0);return V?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(dt,{size:11,className:"text-amber-500"})," ",n("recipes.constraints")," ",e.jsx("span",{className:"text-amber-500 font-mono",children:V})]}),e.jsxs("div",{className:"space-y-1.5 text-xs text-slate-600",children:[(Ye=D.guards)==null?void 0:Ye.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${ze.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-[10px] bg-slate-100 px-1.5 py-0.5 rounded",children:ze.pattern}),ze.message&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["— ",ze.message]})]},Ve)),(J=D.boundaries)==null?void 0:J.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),ze]},Ve)),(Pe=D.preconditions)==null?void 0:Pe.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),ze]},Ve)),(qe=D.sideEffects)==null?void 0:qe.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),ze]},Ve))]})]}):null})()]})]})]})})()]})};function Dt(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}function Wr(t){const s=new Map(t.map(l=>[l.date,l])),a=[];for(let l=6;l>=0;l--){const d=new Date;d.setDate(d.getDate()-l);const c=d.toISOString().slice(0,10);a.push(s.get(c)||{date:c,input_tokens:0,output_tokens:0,total_tokens:0,call_count:0})}return a}const Vr={user:"bg-blue-500",mcp:"bg-purple-500",bootstrap:"bg-amber-500",guard:"bg-rose-500",analyst:"bg-indigo-500",producer:"bg-green-500"},Jr=()=>{const{t}=_e(),[s,a]=o.useState([]),[l,d]=o.useState([]),[c,u]=o.useState({input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}),[p,n]=o.useState(!0),[g,f]=o.useState(null);o.useEffect(()=>{let y=!1;return(async()=>{try{const k=await ae.getTokenUsage7Days();if(y)return;a(k.daily||[]),d(k.bySource||[]),u(k.summary||{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0})}catch(k){y||f(k.message||t("tokenUsageChart.loadFailed"))}finally{y||n(!1)}})(),()=>{y=!0}},[]);const h=o.useMemo(()=>Wr(s),[s]),x=o.useMemo(()=>Math.max(...h.map(y=>y.total_tokens),1),[h]);if(p)return e.jsxs("div",{className:"flex items-center justify-center py-10",children:[e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-blue-500 border-t-transparent"}),e.jsx("span",{className:"ml-2 text-slate-500 text-sm",children:t("tokenUsageChart.loading")})]});if(g)return e.jsx("p",{className:"text-red-500 text-sm py-4 text-center",children:g});const i=c.total_tokens===0;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(xs,{label:t("tokenUsageChart.totalToken"),value:Dt(c.total_tokens),sub:t("tokenUsageChart.totalSub"),color:"blue"}),e.jsx(xs,{label:t("tokenUsageChart.input"),value:Dt(c.input_tokens),sub:"Prompt",color:"green"}),e.jsx(xs,{label:t("tokenUsageChart.output"),value:Dt(c.output_tokens),sub:"Completion",color:"purple"}),e.jsx(xs,{label:t("tokenUsageChart.calls"),value:String(c.call_count),sub:t("tokenUsageChart.avgPerCall",{avg:Dt(c.avg_per_call)}),color:"amber"})]}),i?e.jsx("div",{className:"text-center py-8 text-slate-400 text-sm",children:t("tokenUsageChart.emptyState")}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-slate-700 mb-3",children:t("tokenUsageChart.dailyUsage")}),e.jsx("div",{className:"flex items-end gap-1.5 h-40",children:h.map(y=>{const k=y.input_tokens/x*100,w=y.output_tokens/x*100,T=t(`tokenUsageChart.weekday${new Date(y.date+"T00:00:00").getDay()}`);return e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-1 group relative",children:[e.jsxs("div",{className:"absolute -top-16 left-1/2 -translate-x-1/2 bg-slate-800 text-white text-xs rounded px-2 py-1 opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-10",children:[e.jsx("p",{children:y.date}),e.jsx("p",{children:t("tokenUsageChart.dailyDetail",{input:Dt(y.input_tokens),output:Dt(y.output_tokens)})}),e.jsx("p",{children:t("tokenUsageChart.dailyCalls",{count:String(y.call_count)})})]}),e.jsxs("div",{className:"w-full flex flex-col justify-end",style:{height:"120px"},children:[e.jsx("div",{className:"bg-green-400 rounded-t-sm w-full transition-all",style:{height:`${k}%`,minHeight:y.input_tokens>0?"2px":"0"}}),e.jsx("div",{className:"bg-purple-400 rounded-b-sm w-full transition-all",style:{height:`${w}%`,minHeight:y.output_tokens>0?"2px":"0"}})]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:T})]},y.date)})}),e.jsxs("div",{className:"flex gap-4 mt-2 text-xs text-slate-500 justify-center",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-green-400 inline-block"})," ",t("tokenUsageChart.legendInput")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-purple-400 inline-block"})," ",t("tokenUsageChart.legendOutput")]})]})]}),l.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-slate-700 mb-3",children:t("tokenUsageChart.sourceDistribution")}),e.jsx("div",{className:"space-y-2",children:l.map(y=>{const k=c.total_tokens>0?y.total_tokens/c.total_tokens*100:0,w=Vr[y.source]||"bg-slate-400";return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"w-20 text-xs text-slate-600 text-right truncate",children:y.source}),e.jsx("div",{className:"flex-1 bg-slate-100 rounded-full h-3 overflow-hidden",children:e.jsx("div",{className:`${w} h-full rounded-full transition-all`,style:{width:`${k}%`,minWidth:k>0?"4px":"0"}})}),e.jsx("span",{className:"w-16 text-xs text-slate-500 text-right",children:Dt(y.total_tokens)}),e.jsxs("span",{className:"w-12 text-xs text-slate-400 text-right",children:[k.toFixed(0),"%"]})]},y.source)})})]})]})]})};function xs({label:t,value:s,sub:a,color:l}){const d={blue:"bg-blue-50 border-blue-200 text-blue-700",green:"bg-green-50 border-green-200 text-green-700",purple:"bg-purple-50 border-purple-200 text-purple-700",amber:"bg-amber-50 border-amber-200 text-amber-700"},c=d[l]||d.blue;return e.jsxs("div",{className:`rounded-lg border p-3 ${c}`,children:[e.jsx("p",{className:"text-xs opacity-70",children:t}),e.jsx("p",{className:"text-xl font-bold",children:s}),e.jsx("p",{className:"text-[10px] opacity-60",children:a})]})}const vt=({id:t,title:s,icon:a,isExpanded:l,onToggle:d,children:c})=>e.jsxs("section",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>d(t),className:"w-full flex items-center justify-between p-4 bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[a,e.jsx("h2",{className:"text-lg font-bold text-slate-800",children:s})]}),l?e.jsx(Gt,{size:z.lg}):e.jsx(rt,{size:z.lg})]}),l&&e.jsx("div",{className:"p-4 bg-white",children:c})]}),Yr=()=>{const{t}=_e(),[s,a]=o.useState(new Set(["quick-start"])),l=d=>{const c=new Set(s);c.has(d)?c.delete(d):c.add(d),a(c)};return e.jsxs("div",{className:"max-w-5xl mx-auto py-8 px-4",children:[e.jsxs("div",{className:"mb-8 text-center",children:[e.jsxs("h1",{className:"text-4xl font-bold text-slate-900 mb-4 flex items-center justify-center gap-3",children:[e.jsx(tt,{size:z.xxl,className:"text-blue-600"}),t("help.pageTitle")]}),e.jsx("p",{className:"text-slate-600 text-lg max-w-3xl mx-auto whitespace-nowrap",children:t("help.subtitle")}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:t("help.techSpecs")}),e.jsxs("div",{className:"mt-6 flex gap-4 justify-center text-sm",children:[e.jsx("a",{href:"https://github.com/GxFn/AutoSnippet",target:"_blank",rel:"noopener noreferrer",className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:t("help.viewGithub")}),e.jsx("a",{href:"https://github.com/GxFn/AutoSnippet/blob/main/README.md",target:"_blank",rel:"noopener noreferrer",className:"px-4 py-2 border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 transition-colors",children:t("help.fullDocs")})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(vt,{id:"token-usage",title:t("help.tokenUsageLast7Days"),icon:e.jsx(La,{size:z.xl,className:"text-blue-600"}),isExpanded:s.has("token-usage"),onToggle:l,children:e.jsx(Jr,{})}),e.jsx(vt,{id:"quick-start",title:t("help.quickStart"),icon:e.jsx(Xt,{size:z.xl,className:"text-blue-600"}),isExpanded:s.has("quick-start"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-blue-50 rounded-lg p-4 border border-blue-200",children:[e.jsx("div",{className:"bg-blue-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"1"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.step1Title")}),e.jsx("pre",{className:"bg-blue-100/70 text-blue-900 px-3 py-2 rounded text-xs overflow-hidden",children:e.jsxs("code",{children:["npm install -g autosnippet",`
81
80
  `,"cd your-project",`
82
- `,"asd setup"]})})]}),e.jsxs("div",{className:"bg-green-50 rounded-lg p-4 border border-green-200",children:[e.jsx("div",{className:"bg-green-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"2"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.step2Title")}),e.jsx("pre",{className:"bg-green-100/70 text-green-900 px-3 py-2 rounded text-xs overflow-hidden",children:e.jsx("code",{children:"asd ui"})}),e.jsx("p",{className:"text-slate-600 text-xs mt-2",children:t("help.step2Desc")})]}),e.jsxs("div",{className:"bg-purple-50 rounded-lg p-4 border border-purple-200",children:[e.jsx("div",{className:"bg-purple-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"3"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.step3Title")}),e.jsx("pre",{className:"bg-purple-100/70 text-purple-900 px-3 py-2 rounded text-xs overflow-hidden",children:e.jsx("code",{children:"asd upgrade"})}),e.jsx("p",{className:"text-slate-600 text-xs mt-2",children:t("help.step3Desc")})]}),e.jsxs("div",{className:"bg-amber-50 rounded-lg p-4 border border-amber-200",children:[e.jsx("div",{className:"bg-amber-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"4"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.step4Title")}),e.jsx("p",{className:"text-slate-600 text-sm mb-1",children:t("help.step4Desc1")}),e.jsx("p",{className:"text-slate-600 text-sm",children:t("help.step4Desc2")})]})]})}),e.jsxs(vt,{id:"concepts",title:t("help.coreConcepts"),icon:e.jsx(Da,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("concepts"),onToggle:l,children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-3",children:t("help.threeRoles")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-slate-200 rounded-lg text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50",children:[e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.roleColumn")}),e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.responsibilityColumn")}),e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.capabilityColumn")})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:"px-4 py-3 border-b font-medium text-blue-700",children:t("help.roleDeveloper")}),e.jsx("td",{className:"px-4 py-3 border-b",children:t("help.developerResp")}),e.jsx("td",{className:"px-4 py-3 border-b text-xs",dangerouslySetInnerHTML:{__html:t("help.developerCap")}})]}),e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:"px-4 py-3 border-b font-medium text-green-700",children:t("help.roleCursorAgent")}),e.jsx("td",{className:"px-4 py-3 border-b",children:t("help.cursorAgentResp")}),e.jsx("td",{className:"px-4 py-3 border-b text-xs",dangerouslySetInnerHTML:{__html:t("help.cursorAgentCap")}})]}),e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:"px-4 py-3 font-medium text-purple-700",children:t("help.roleChatAgent")}),e.jsx("td",{className:"px-4 py-3",children:t("help.chatAgentResp")}),e.jsx("td",{className:"px-4 py-3 text-xs",dangerouslySetInnerHTML:{__html:t("help.chatAgentCap")}})]})]})]})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-3",children:t("help.coreComponents")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-green-50 rounded-lg p-4 border border-green-200",children:[e.jsxs("h4",{className:"font-semibold text-green-900 mb-2 flex items-center gap-2",children:[e.jsx(et,{size:F.lg}),t("help.bootstrapLabel")]}),e.jsx("p",{className:"text-green-800 text-sm mb-3",children:t("help.bootstrapDesc")}),e.jsxs("ul",{className:"text-green-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.bootstrapBullet1")}),e.jsx("li",{children:t("help.bootstrapBullet2")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.bootstrapBullet3")}})]})]}),e.jsxs("div",{className:"bg-purple-50 rounded-lg p-4 border border-purple-200",children:[e.jsxs("h4",{className:"font-semibold text-purple-900 mb-2 flex items-center gap-2",children:[e.jsx(Il,{size:F.lg}),t("help.candidatesLabel")]}),e.jsx("p",{className:"text-purple-800 text-sm mb-3",children:t("help.candidatesDesc")}),e.jsxs("ul",{className:"text-purple-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.candidatesBullet1")}),e.jsx("li",{children:t("help.candidatesBullet2")}),e.jsx("li",{children:t("help.candidatesBullet3")})]})]}),e.jsxs("div",{className:"bg-blue-50 rounded-lg p-4 border border-blue-200",children:[e.jsxs("h4",{className:"font-semibold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(ht,{size:F.lg}),t("help.recipeLabel")]}),e.jsx("p",{className:"text-blue-800 text-sm mb-3",children:t("help.recipeDesc")}),e.jsxs("ul",{className:"text-blue-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.recipeBullet1")}}),e.jsx("li",{children:t("help.recipeBullet2")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.recipeBullet3")}})]})]}),e.jsxs("div",{className:"bg-indigo-50 rounded-lg p-4 border border-indigo-200",children:[e.jsxs("h4",{className:"font-semibold text-indigo-900 mb-2 flex items-center gap-2",children:[e.jsx(Ys,{size:F.lg}),t("help.chatAgentLabel")]}),e.jsx("p",{className:"text-indigo-800 text-sm mb-3",children:t("help.chatAgentDesc")}),e.jsxs("ul",{className:"text-indigo-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.chatAgentCompBullet1")}),e.jsx("li",{children:t("help.chatAgentCompBullet2")}),e.jsx("li",{children:t("help.chatAgentCompBullet3")})]})]}),e.jsxs("div",{className:"bg-amber-50 rounded-lg p-4 border border-amber-200",children:[e.jsxs("h4",{className:"font-semibold text-amber-900 mb-2 flex items-center gap-2",children:[e.jsx(ft,{size:F.lg}),t("help.searchPipelineLabel")]}),e.jsx("p",{className:"text-amber-800 text-sm mb-3",children:t("help.searchPipelineDesc")}),e.jsxs("ul",{className:"text-amber-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.searchPipelineBullet1")}),e.jsx("li",{children:t("help.searchPipelineBullet2")}),e.jsx("li",{children:t("help.searchPipelineBullet3")})]})]}),e.jsxs("div",{className:"bg-rose-50 rounded-lg p-4 border border-rose-200",children:[e.jsxs("h4",{className:"font-semibold text-rose-900 mb-2 flex items-center gap-2",children:[e.jsx(ut,{size:F.lg}),t("help.guardLabel")]}),e.jsx("p",{className:"text-rose-800 text-sm mb-3",children:t("help.guardDesc")}),e.jsxs("ul",{className:"text-rose-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.guardCompBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet3")}})]})]})]})]}),e.jsxs("div",{className:"mt-6 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-5 border border-slate-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-4",children:t("help.knowledgeLoop")}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-blue-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"1"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep1")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep1Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-green-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"2"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep2")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep2Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-purple-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"3"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep3")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep3Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-amber-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"4"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep4")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep4Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-rose-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"5"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep5")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep5Sub")})]})]})]})]}),e.jsx(vt,{id:"features",title:t("help.coreFeatures"),icon:e.jsx(et,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("features"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:[e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx($s,{size:F.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.knowledgeBuild")})]}),e.jsxs("ul",{className:"text-slate-600 text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet4")}})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ft,{size:F.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.semanticSearchLabel")})]}),e.jsxs("ul",{className:"text-slate-600 text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet4")}})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ut,{size:F.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.codeAudit")})]}),e.jsxs("ul",{className:"text-slate-600 text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet4")}})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(yt,{size:F.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.dataSync")})]}),e.jsxs("ul",{className:"text-slate-600 text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet4")}})]})]})]})}),e.jsxs(vt,{id:"editor-directives",title:t("help.editorDirectives"),icon:e.jsx(Qs,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("editor-directives"),onToggle:l,children:[e.jsx("p",{className:"text-slate-600 text-sm mb-4",children:t("help.editorDirectivesNote")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:create"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"asc"})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.createDirective")}),e.jsxs("ul",{className:"text-slate-600 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.createDirBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.createDirBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.createDirBullet3")}})]})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:search"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"ass"})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.searchDirective")}),e.jsxs("ul",{className:"text-slate-600 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.searchDirBullet1")}),e.jsx("li",{children:t("help.searchDirBullet2")}),e.jsx("li",{children:t("help.searchDirBullet3")})]})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:audit"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"asa"})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.auditDirective")}),e.jsxs("ul",{className:"text-slate-600 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.auditDirBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditDirBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditDirBullet3")}})]})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:include"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:import"})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.includeDirective")}),e.jsxs("ul",{className:"text-slate-600 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.includeDirBullet1")}),e.jsx("li",{children:t("help.includeDirBullet2")})]})]})]})]}),e.jsxs(vt,{id:"cursor-integration",title:t("help.cursorIntegration"),icon:e.jsx(Lt,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("cursor-integration"),onToggle:l,children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-3",children:t("help.skills10")}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-2",children:[{name:"intent",descKey:"help.skillIntent"},{name:"concepts",descKey:"help.skillConcepts"},{name:"candidates",descKey:"help.skillCandidates"},{name:"recipes",descKey:"help.skillRecipes"},{name:"guard",descKey:"help.skillGuard"},{name:"structure",descKey:"help.skillStructure"},{name:"analysis",descKey:"help.skillAnalysis"},{name:"coldstart",descKey:"help.skillColdstart"},{name:"create",descKey:"help.skillCreate"},{name:"lifecycle",descKey:"help.skillLifecycle"}].map(d=>e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-center",children:[e.jsx("p",{className:"text-xs font-mono text-blue-600",children:d.name}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:t(d.descKey)})]},d.name))})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-3",children:t("help.mcp16")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-slate-200 rounded-lg text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50",children:[e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpLayerHeader")}),e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpToolHeader")}),e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpDescHeader")})]})}),e.jsxs("tbody",{children:[e.jsx("tr",{className:"bg-blue-50/30",children:e.jsx("td",{colSpan:3,className:"px-3 py-1.5 border-b font-semibold text-blue-700 text-xs",children:t("help.mcpAgentLayerHeader")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"health"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpHealthDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"capabilities"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpCapabilitiesDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"search"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSearchDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"knowledge"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpKnowledgeDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"structure"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpStructureDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"graph"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpGraphDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"guard"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpGuardDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"submit_knowledge"})," / ",e.jsx("code",{children:"submit_knowledge_batch"})," / ",e.jsx("code",{children:"save_document"})]}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSubmitDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"skill"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSkillDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"bootstrap"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpBootstrapDesc")})]}),e.jsx("tr",{className:"bg-amber-50/30",children:e.jsx("td",{colSpan:3,className:"px-3 py-1.5 border-b font-semibold text-amber-700 text-xs",children:t("help.mcpAdminLayerHeader")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"admin"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"enrich_candidates"})," / ",e.jsx("code",{children:"validate_candidate"})," / ",e.jsx("code",{children:"check_duplicate"})]}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpEnrichDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-medium",children:"admin"}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("code",{children:"knowledge_lifecycle"})}),e.jsx("td",{className:"px-3 py-2",children:t("help.mcpLifecycleDesc")})]})]})]})}),e.jsx("p",{className:"text-xs text-slate-500 mt-2",children:t("help.mcpWriteNote")})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-3",children:t("help.usageExamples")}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-blue-50 rounded p-3 border border-blue-200",children:[e.jsx("p",{className:"font-medium text-blue-900 text-sm mb-1",children:t("help.exampleSearchKB")}),e.jsx("p",{className:"text-blue-800 text-xs",children:t("help.exampleSearchKBDesc")})]}),e.jsxs("div",{className:"bg-green-50 rounded p-3 border border-green-200",children:[e.jsx("p",{className:"font-medium text-green-900 text-sm mb-1",children:t("help.exampleBatchScan")}),e.jsx("p",{className:"text-green-800 text-xs",children:t("help.exampleBatchScanDesc")})]}),e.jsxs("div",{className:"bg-purple-50 rounded p-3 border border-purple-200",children:[e.jsx("p",{className:"font-medium text-purple-900 text-sm mb-1",children:t("help.exampleSubmitCode")}),e.jsx("p",{className:"text-purple-800 text-xs",children:t("help.exampleSubmitCodeDesc")})]})]})]})]}),e.jsx(vt,{id:"v2-architecture",title:t("help.v3Architecture"),icon:e.jsx(lt,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("v2-architecture"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:[e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(et,{size:F.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.bootstrapEngine")})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.bootstrapEngineDesc")}),e.jsxs("div",{className:"bg-slate-50 rounded p-3 text-xs font-mono text-slate-700 space-y-1",children:[e.jsx("p",{children:t("help.archBootstrapStep1")}),e.jsx("p",{children:t("help.archBootstrapStep2")}),e.jsx("p",{children:t("help.archBootstrapStep3")})]}),e.jsx("p",{className:"text-slate-500 text-xs mt-2",children:t("help.archBootstrapNote")})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ft,{size:F.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.fourLayerPipeline")})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.fourLayerPipelineDesc")}),e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-blue-100 text-blue-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L1"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL1")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-green-100 text-green-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L2"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL2")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-amber-100 text-amber-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L3"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL3")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-red-100 text-red-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L4"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL4")})]})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Ys,{size:F.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.chatAgentSystem")})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.chatAgentSystemDesc")}),e.jsxs("div",{className:"bg-slate-50 rounded p-3 text-xs text-slate-700 space-y-1.5",children:[e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archAnalystAgent")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archProducerAgent")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archHandoff")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archMemory")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archProjectAware")}})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(_s,{size:F.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.fiveEntryChannels")})]}),e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"CLI"}),e.jsx("span",{className:"text-slate-500",children:t("help.archCliDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"MCP Server"}),e.jsx("span",{className:"text-slate-500",children:t("help.archMcpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"HTTP API"}),e.jsx("span",{className:"text-slate-500",children:t("help.archHttpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"Dashboard"}),e.jsx("span",{className:"text-slate-500",children:"React 19 + Vite 6 + Tailwind 4"})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"Skills"}),e.jsx("span",{className:"text-slate-500",children:t("help.archSkillsDesc")})]})]})]})]})}),e.jsx(vt,{id:"cli-reference",title:t("help.cliReference"),icon:e.jsx(Qs,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("cli-reference"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.initAndEnv")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd setup"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSetupDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd status"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliStatusDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ui"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliUiDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliUpgradeDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.kbManagement")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSyncDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ais [Target]"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliAisDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ais --force"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliAisForceDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd watch"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliWatchDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.searchAndAudit")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd search <query>"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSearchDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd search -m semantic"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSearchSemanticDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard <file>"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliGuardDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd server"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliServerDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.maintenanceUpgrade")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliUpgradeMcpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd install:full"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliInstallFullDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --force"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSyncForceDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --dry-run"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSyncDryDesc")})]})]})]})]})})]}),e.jsx("div",{className:"mt-8 p-4 bg-blue-50 border border-blue-200 rounded-lg text-center",children:e.jsx("p",{className:"text-slate-700 text-sm",dangerouslySetInnerHTML:{__html:t("help.footerHint",{link:`<a href="https://github.com/GxFn/AutoSnippet" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:underline font-medium">${t("help.footerGithubReadme")}</a>`,cmd:'<code class="bg-blue-100 px-1.5 py-0.5 rounded text-xs">asd status</code>'})}})})]})};function Xr(){const[t,s]=o.useState(null);o.useEffect(()=>{const i=Ks(),u=h=>{s({status:"running",total:h.total,current:0,progress:0,refined:0,failed:0,items:h.candidateIds.map(x=>({candidateId:x,title:"",status:"pending"}))})},p=h=>{s(x=>x&&{...x,current:h.current,progress:h.progress,items:x.items.map(c=>c.candidateId===h.candidateId?{...c,title:h.title,status:"refining"}:c)})},n=h=>{s(x=>x&&{...x,current:h.current,progress:h.progress,refined:h.refinedSoFar,items:x.items.map(c=>c.candidateId===h.candidateId?{...c,title:h.title,status:"done",refined:h.refined}:c)})},g=h=>{s(x=>x&&{...x,current:h.current,progress:h.progress,failed:x.failed+1,items:x.items.map(c=>c.candidateId===h.candidateId?{...c,title:h.title,status:"failed",error:h.error}:c)})},f=h=>{s(x=>x&&{...x,status:"completed",progress:100,refined:h.refined,failed:h.failed})};return i.on("refine:started",u),i.on("refine:item-started",p),i.on("refine:item-completed",n),i.on("refine:item-failed",g),i.on("refine:completed",f),()=>{i.off("refine:started",u),i.off("refine:item-started",p),i.off("refine:item-completed",n),i.off("refine:item-failed",g),i.off("refine:completed",f)}},[]);const a=o.useCallback(()=>s(null),[]),l=(t==null?void 0:t.status)==="running",d=(t==null?void 0:t.status)==="completed";return{refine:t,isRefining:l,isRefineDone:d,resetRefine:a}}const Zr=({refine:t,isRefineDone:s,onDismiss:a})=>{const{t:l}=_e(),d=o.useRef(!1);if(o.useEffect(()=>{if(s&&t&&!d.current){d.current=!0;const p=t.failed>0?l("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):l("refineProgress.doneMsg",{refined:String(t.refined)});re(p,{title:l("refineProgress.doneTitle"),type:t.failed>0?"error":"success"})}},[s,t]),o.useEffect(()=>{t||(d.current=!1)},[t]),!t)return null;const i=t.items.find(p=>p.status==="refining"),u=t.items.filter(p=>p.status==="done"||p.status==="failed").length;return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4 mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`p-1.5 rounded-lg ${s?"bg-emerald-50":"bg-blue-50"}`,children:s?e.jsx(kt,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Qe,{className:"w-4 h-4 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-800",children:l(s?"refineProgress.doneTitle":"refineProgress.runningTitle")}),e.jsxs("p",{className:"text-xs text-slate-500",children:[s?t.failed>0?l("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):l("refineProgress.doneMsg",{refined:String(t.refined)}):l("refineProgress.progressMsg",{done:String(u),total:String(t.total)}),i&&!s&&e.jsxs("span",{className:"ml-2 text-blue-600",children:[e.jsx(Fe,{className:"w-3 h-3 inline animate-spin mr-1"}),i.title||i.candidateId.slice(0,8)]})]})]})]}),s&&a&&e.jsx("button",{onClick:a,className:"text-xs px-2.5 py-1 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors",children:l("refineProgress.closeBtn")})]}),e.jsx("div",{className:"w-full h-1.5 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-500 ease-out ${s?t.failed>0?"bg-amber-400":"bg-emerald-500":"bg-blue-500"}`,style:{width:`${t.progress}%`}})}),s&&t.failed>0&&e.jsxs("div",{className:"mt-2 text-xs text-red-500 flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),t.items.filter(p=>p.status==="failed").map(p=>p.title||p.candidateId.slice(0,8)).join("、")]})]})},ms={_watch:"silentLabels.watch",_draft:"silentLabels.draft",_cli:"silentLabels.cli",_pending:"silentLabels.pending",_recipe:"silentLabels.recipe"},hs={architecture:"bootstrap.dimLabels.architecture","best-practice":"bootstrap.dimLabels.bestPractice","event-and-data-flow":"bootstrap.dimLabels.eventAndDataFlow","objc-deep-scan":"bootstrap.dimLabels.objcDeepScan","agent-guidelines":"bootstrap.dimLabels.agentGuidelines",bootstrap:"bootstrap.dimLabels.bootstrap","code-standard":"bootstrap.dimLabels.codeStandard","code-pattern":"bootstrap.dimLabels.codePattern","project-profile":"bootstrap.dimLabels.projectProfile","category-scan":"bootstrap.dimLabels.categoryScan"};function en(t,s,a,l){return[...t].sort(([d],[i])=>{const u=l(d),p=l(i);if(u&&!p)return 1;if(!u&&p)return-1;const n=a(d),g=a(i);if(n&&!g)return-1;if(!n&&g)return 1;const f=s(d),h=s(i);return f&&!h?1:!f&&h?-1:d.localeCompare(i)})}function Wt(t,s){if(!t)return"";const a=typeof t=="number"?t:Number(t),l=a<1e12?a*1e3:a,d=new Date(l);if(isNaN(d.getTime())||d.getFullYear()<2e3)return"";const u=new Date().getTime()-d.getTime();if(u<0)return d.toLocaleDateString();const p=Math.floor(u/6e4);if(p<1)return s("candidates.timeJustNow");if(p<60)return s("candidates.timeMinutesAgo",{n:p});const n=Math.floor(p/60);if(n<24)return s("candidates.timeHoursAgo",{n});const g=Math.floor(n/24);return g<7?s("candidates.timeDaysAgo",{n:g}):d.toLocaleDateString()}function tn(t,s=4){return t?Us(t).split(`
81
+ `,"asd setup"]})})]}),e.jsxs("div",{className:"bg-green-50 rounded-lg p-4 border border-green-200",children:[e.jsx("div",{className:"bg-green-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"2"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.step2Title")}),e.jsx("pre",{className:"bg-green-100/70 text-green-900 px-3 py-2 rounded text-xs overflow-hidden",children:e.jsx("code",{children:"asd ui"})}),e.jsx("p",{className:"text-slate-600 text-xs mt-2",children:t("help.step2Desc")})]}),e.jsxs("div",{className:"bg-purple-50 rounded-lg p-4 border border-purple-200",children:[e.jsx("div",{className:"bg-purple-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"3"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.step3Title")}),e.jsx("pre",{className:"bg-purple-100/70 text-purple-900 px-3 py-2 rounded text-xs overflow-hidden",children:e.jsx("code",{children:"asd upgrade"})}),e.jsx("p",{className:"text-slate-600 text-xs mt-2",children:t("help.step3Desc")})]}),e.jsxs("div",{className:"bg-amber-50 rounded-lg p-4 border border-amber-200",children:[e.jsx("div",{className:"bg-amber-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"4"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.step4Title")}),e.jsx("p",{className:"text-slate-600 text-sm mb-1",children:t("help.step4Desc1")}),e.jsx("p",{className:"text-slate-600 text-sm",children:t("help.step4Desc2")})]})]})}),e.jsxs(vt,{id:"concepts",title:t("help.coreConcepts"),icon:e.jsx(Da,{size:z.xl,className:"text-blue-600"}),isExpanded:s.has("concepts"),onToggle:l,children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-3",children:t("help.threeRoles")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-slate-200 rounded-lg text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50",children:[e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.roleColumn")}),e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.responsibilityColumn")}),e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.capabilityColumn")})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:"px-4 py-3 border-b font-medium text-blue-700",children:t("help.roleDeveloper")}),e.jsx("td",{className:"px-4 py-3 border-b",children:t("help.developerResp")}),e.jsx("td",{className:"px-4 py-3 border-b text-xs",dangerouslySetInnerHTML:{__html:t("help.developerCap")}})]}),e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:"px-4 py-3 border-b font-medium text-green-700",children:t("help.roleCursorAgent")}),e.jsx("td",{className:"px-4 py-3 border-b",children:t("help.cursorAgentResp")}),e.jsx("td",{className:"px-4 py-3 border-b text-xs",dangerouslySetInnerHTML:{__html:t("help.cursorAgentCap")}})]}),e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:"px-4 py-3 font-medium text-purple-700",children:t("help.roleChatAgent")}),e.jsx("td",{className:"px-4 py-3",children:t("help.chatAgentResp")}),e.jsx("td",{className:"px-4 py-3 text-xs",dangerouslySetInnerHTML:{__html:t("help.chatAgentCap")}})]})]})]})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-3",children:t("help.coreComponents")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-green-50 rounded-lg p-4 border border-green-200",children:[e.jsxs("h4",{className:"font-semibold text-green-900 mb-2 flex items-center gap-2",children:[e.jsx(et,{size:z.lg}),t("help.bootstrapLabel")]}),e.jsx("p",{className:"text-green-800 text-sm mb-3",children:t("help.bootstrapDesc")}),e.jsxs("ul",{className:"text-green-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.bootstrapBullet1")}),e.jsx("li",{children:t("help.bootstrapBullet2")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.bootstrapBullet3")}})]})]}),e.jsxs("div",{className:"bg-purple-50 rounded-lg p-4 border border-purple-200",children:[e.jsxs("h4",{className:"font-semibold text-purple-900 mb-2 flex items-center gap-2",children:[e.jsx(Il,{size:z.lg}),t("help.candidatesLabel")]}),e.jsx("p",{className:"text-purple-800 text-sm mb-3",children:t("help.candidatesDesc")}),e.jsxs("ul",{className:"text-purple-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.candidatesBullet1")}),e.jsx("li",{children:t("help.candidatesBullet2")}),e.jsx("li",{children:t("help.candidatesBullet3")})]})]}),e.jsxs("div",{className:"bg-blue-50 rounded-lg p-4 border border-blue-200",children:[e.jsxs("h4",{className:"font-semibold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(ht,{size:z.lg}),t("help.recipeLabel")]}),e.jsx("p",{className:"text-blue-800 text-sm mb-3",children:t("help.recipeDesc")}),e.jsxs("ul",{className:"text-blue-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.recipeBullet1")}}),e.jsx("li",{children:t("help.recipeBullet2")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.recipeBullet3")}})]})]}),e.jsxs("div",{className:"bg-indigo-50 rounded-lg p-4 border border-indigo-200",children:[e.jsxs("h4",{className:"font-semibold text-indigo-900 mb-2 flex items-center gap-2",children:[e.jsx(Ys,{size:z.lg}),t("help.chatAgentLabel")]}),e.jsx("p",{className:"text-indigo-800 text-sm mb-3",children:t("help.chatAgentDesc")}),e.jsxs("ul",{className:"text-indigo-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.chatAgentCompBullet1")}),e.jsx("li",{children:t("help.chatAgentCompBullet2")}),e.jsx("li",{children:t("help.chatAgentCompBullet3")})]})]}),e.jsxs("div",{className:"bg-amber-50 rounded-lg p-4 border border-amber-200",children:[e.jsxs("h4",{className:"font-semibold text-amber-900 mb-2 flex items-center gap-2",children:[e.jsx(ft,{size:z.lg}),t("help.searchPipelineLabel")]}),e.jsx("p",{className:"text-amber-800 text-sm mb-3",children:t("help.searchPipelineDesc")}),e.jsxs("ul",{className:"text-amber-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.searchPipelineBullet1")}),e.jsx("li",{children:t("help.searchPipelineBullet2")}),e.jsx("li",{children:t("help.searchPipelineBullet3")})]})]}),e.jsxs("div",{className:"bg-rose-50 rounded-lg p-4 border border-rose-200",children:[e.jsxs("h4",{className:"font-semibold text-rose-900 mb-2 flex items-center gap-2",children:[e.jsx(dt,{size:z.lg}),t("help.guardLabel")]}),e.jsx("p",{className:"text-rose-800 text-sm mb-3",children:t("help.guardDesc")}),e.jsxs("ul",{className:"text-rose-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.guardCompBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet3")}})]})]})]})]}),e.jsxs("div",{className:"mt-6 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-5 border border-slate-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-4",children:t("help.knowledgeLoop")}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-blue-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"1"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep1")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep1Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-green-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"2"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep2")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep2Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-purple-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"3"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep3")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep3Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-amber-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"4"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep4")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep4Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-rose-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"5"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep5")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep5Sub")})]})]})]})]}),e.jsx(vt,{id:"features",title:t("help.coreFeatures"),icon:e.jsx(et,{size:z.xl,className:"text-blue-600"}),isExpanded:s.has("features"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:[e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx($s,{size:z.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.knowledgeBuild")})]}),e.jsxs("ul",{className:"text-slate-600 text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet4")}})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ft,{size:z.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.semanticSearchLabel")})]}),e.jsxs("ul",{className:"text-slate-600 text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet4")}})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(dt,{size:z.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.codeAudit")})]}),e.jsxs("ul",{className:"text-slate-600 text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet4")}})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(yt,{size:z.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.dataSync")})]}),e.jsxs("ul",{className:"text-slate-600 text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet4")}})]})]})]})}),e.jsxs(vt,{id:"editor-directives",title:t("help.editorDirectives"),icon:e.jsx(Qs,{size:z.xl,className:"text-blue-600"}),isExpanded:s.has("editor-directives"),onToggle:l,children:[e.jsx("p",{className:"text-slate-600 text-sm mb-4",children:t("help.editorDirectivesNote")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:create"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"asc"})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.createDirective")}),e.jsxs("ul",{className:"text-slate-600 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.createDirBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.createDirBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.createDirBullet3")}})]})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:search"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"ass"})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.searchDirective")}),e.jsxs("ul",{className:"text-slate-600 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.searchDirBullet1")}),e.jsx("li",{children:t("help.searchDirBullet2")}),e.jsx("li",{children:t("help.searchDirBullet3")})]})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:audit"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"asa"})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.auditDirective")}),e.jsxs("ul",{className:"text-slate-600 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.auditDirBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditDirBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditDirBullet3")}})]})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:include"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:import"})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.includeDirective")}),e.jsxs("ul",{className:"text-slate-600 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.includeDirBullet1")}),e.jsx("li",{children:t("help.includeDirBullet2")})]})]})]})]}),e.jsxs(vt,{id:"cursor-integration",title:t("help.cursorIntegration"),icon:e.jsx(Lt,{size:z.xl,className:"text-blue-600"}),isExpanded:s.has("cursor-integration"),onToggle:l,children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-3",children:t("help.skills10")}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-2",children:[{name:"intent",descKey:"help.skillIntent"},{name:"concepts",descKey:"help.skillConcepts"},{name:"candidates",descKey:"help.skillCandidates"},{name:"recipes",descKey:"help.skillRecipes"},{name:"guard",descKey:"help.skillGuard"},{name:"structure",descKey:"help.skillStructure"},{name:"analysis",descKey:"help.skillAnalysis"},{name:"coldstart",descKey:"help.skillColdstart"},{name:"create",descKey:"help.skillCreate"},{name:"lifecycle",descKey:"help.skillLifecycle"}].map(d=>e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-center",children:[e.jsx("p",{className:"text-xs font-mono text-blue-600",children:d.name}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:t(d.descKey)})]},d.name))})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-3",children:t("help.mcp16")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-slate-200 rounded-lg text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50",children:[e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpLayerHeader")}),e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpToolHeader")}),e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpDescHeader")})]})}),e.jsxs("tbody",{children:[e.jsx("tr",{className:"bg-blue-50/30",children:e.jsx("td",{colSpan:3,className:"px-3 py-1.5 border-b font-semibold text-blue-700 text-xs",children:t("help.mcpAgentLayerHeader")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"health"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpHealthDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"capabilities"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpCapabilitiesDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"search"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSearchDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"knowledge"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpKnowledgeDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"structure"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpStructureDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"graph"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpGraphDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"guard"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpGuardDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"submit_knowledge"})," / ",e.jsx("code",{children:"submit_knowledge_batch"})," / ",e.jsx("code",{children:"save_document"})]}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSubmitDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"skill"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSkillDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"bootstrap"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpBootstrapDesc")})]}),e.jsx("tr",{className:"bg-amber-50/30",children:e.jsx("td",{colSpan:3,className:"px-3 py-1.5 border-b font-semibold text-amber-700 text-xs",children:t("help.mcpAdminLayerHeader")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"admin"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"enrich_candidates"})," / ",e.jsx("code",{children:"validate_candidate"})," / ",e.jsx("code",{children:"check_duplicate"})]}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpEnrichDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-medium",children:"admin"}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("code",{children:"knowledge_lifecycle"})}),e.jsx("td",{className:"px-3 py-2",children:t("help.mcpLifecycleDesc")})]})]})]})}),e.jsx("p",{className:"text-xs text-slate-500 mt-2",children:t("help.mcpWriteNote")})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-3",children:t("help.usageExamples")}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-blue-50 rounded p-3 border border-blue-200",children:[e.jsx("p",{className:"font-medium text-blue-900 text-sm mb-1",children:t("help.exampleSearchKB")}),e.jsx("p",{className:"text-blue-800 text-xs",children:t("help.exampleSearchKBDesc")})]}),e.jsxs("div",{className:"bg-green-50 rounded p-3 border border-green-200",children:[e.jsx("p",{className:"font-medium text-green-900 text-sm mb-1",children:t("help.exampleBatchScan")}),e.jsx("p",{className:"text-green-800 text-xs",children:t("help.exampleBatchScanDesc")})]}),e.jsxs("div",{className:"bg-purple-50 rounded p-3 border border-purple-200",children:[e.jsx("p",{className:"font-medium text-purple-900 text-sm mb-1",children:t("help.exampleSubmitCode")}),e.jsx("p",{className:"text-purple-800 text-xs",children:t("help.exampleSubmitCodeDesc")})]})]})]})]}),e.jsx(vt,{id:"v2-architecture",title:t("help.v3Architecture"),icon:e.jsx(lt,{size:z.xl,className:"text-blue-600"}),isExpanded:s.has("v2-architecture"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:[e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(et,{size:z.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.bootstrapEngine")})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.bootstrapEngineDesc")}),e.jsxs("div",{className:"bg-slate-50 rounded p-3 text-xs font-mono text-slate-700 space-y-1",children:[e.jsx("p",{children:t("help.archBootstrapStep1")}),e.jsx("p",{children:t("help.archBootstrapStep2")}),e.jsx("p",{children:t("help.archBootstrapStep3")})]}),e.jsx("p",{className:"text-slate-500 text-xs mt-2",children:t("help.archBootstrapNote")})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ft,{size:z.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.fourLayerPipeline")})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.fourLayerPipelineDesc")}),e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-blue-100 text-blue-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L1"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL1")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-green-100 text-green-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L2"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL2")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-amber-100 text-amber-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L3"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL3")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-red-100 text-red-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L4"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL4")})]})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Ys,{size:z.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.chatAgentSystem")})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.chatAgentSystemDesc")}),e.jsxs("div",{className:"bg-slate-50 rounded p-3 text-xs text-slate-700 space-y-1.5",children:[e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archAnalystAgent")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archProducerAgent")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archHandoff")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archMemory")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archProjectAware")}})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(_s,{size:z.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.fiveEntryChannels")})]}),e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"CLI"}),e.jsx("span",{className:"text-slate-500",children:t("help.archCliDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"MCP Server"}),e.jsx("span",{className:"text-slate-500",children:t("help.archMcpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"HTTP API"}),e.jsx("span",{className:"text-slate-500",children:t("help.archHttpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"Dashboard"}),e.jsx("span",{className:"text-slate-500",children:"React 19 + Vite 6 + Tailwind 4"})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"Skills"}),e.jsx("span",{className:"text-slate-500",children:t("help.archSkillsDesc")})]})]})]})]})}),e.jsx(vt,{id:"cli-reference",title:t("help.cliReference"),icon:e.jsx(Qs,{size:z.xl,className:"text-blue-600"}),isExpanded:s.has("cli-reference"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.initAndEnv")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd setup"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSetupDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd status"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliStatusDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ui"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliUiDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliUpgradeDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.kbManagement")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSyncDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ais [Target]"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliAisDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ais --force"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliAisForceDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd watch"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliWatchDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.searchAndAudit")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd search <query>"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSearchDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd search -m semantic"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSearchSemanticDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard <file>"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliGuardDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd server"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliServerDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.maintenanceUpgrade")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliUpgradeMcpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd install:full"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliInstallFullDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --force"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSyncForceDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --dry-run"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSyncDryDesc")})]})]})]})]})})]}),e.jsx("div",{className:"mt-8 p-4 bg-blue-50 border border-blue-200 rounded-lg text-center",children:e.jsx("p",{className:"text-slate-700 text-sm",dangerouslySetInnerHTML:{__html:t("help.footerHint",{link:`<a href="https://github.com/GxFn/AutoSnippet" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:underline font-medium">${t("help.footerGithubReadme")}</a>`,cmd:'<code class="bg-blue-100 px-1.5 py-0.5 rounded text-xs">asd status</code>'})}})})]})};function Qr(){const[t,s]=o.useState(null);o.useEffect(()=>{const c=Ks(),u=h=>{s({status:"running",total:h.total,current:0,progress:0,refined:0,failed:0,items:h.candidateIds.map(x=>({candidateId:x,title:"",status:"pending"}))})},p=h=>{s(x=>x&&{...x,current:h.current,progress:h.progress,items:x.items.map(i=>i.candidateId===h.candidateId?{...i,title:h.title,status:"refining"}:i)})},n=h=>{s(x=>x&&{...x,current:h.current,progress:h.progress,refined:h.refinedSoFar,items:x.items.map(i=>i.candidateId===h.candidateId?{...i,title:h.title,status:"done",refined:h.refined}:i)})},g=h=>{s(x=>x&&{...x,current:h.current,progress:h.progress,failed:x.failed+1,items:x.items.map(i=>i.candidateId===h.candidateId?{...i,title:h.title,status:"failed",error:h.error}:i)})},f=h=>{s(x=>x&&{...x,status:"completed",progress:100,refined:h.refined,failed:h.failed})};return c.on("refine:started",u),c.on("refine:item-started",p),c.on("refine:item-completed",n),c.on("refine:item-failed",g),c.on("refine:completed",f),()=>{c.off("refine:started",u),c.off("refine:item-started",p),c.off("refine:item-completed",n),c.off("refine:item-failed",g),c.off("refine:completed",f)}},[]);const a=o.useCallback(()=>s(null),[]),l=(t==null?void 0:t.status)==="running",d=(t==null?void 0:t.status)==="completed";return{refine:t,isRefining:l,isRefineDone:d,resetRefine:a}}const Xr=({refine:t,isRefineDone:s,onDismiss:a})=>{const{t:l}=_e(),d=o.useRef(!1);if(o.useEffect(()=>{if(s&&t&&!d.current){d.current=!0;const p=t.failed>0?l("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):l("refineProgress.doneMsg",{refined:String(t.refined)});re(p,{title:l("refineProgress.doneTitle"),type:t.failed>0?"error":"success"})}},[s,t]),o.useEffect(()=>{t||(d.current=!1)},[t]),!t)return null;const c=t.items.find(p=>p.status==="refining"),u=t.items.filter(p=>p.status==="done"||p.status==="failed").length;return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4 mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`p-1.5 rounded-lg ${s?"bg-emerald-50":"bg-blue-50"}`,children:s?e.jsx(kt,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Qe,{className:"w-4 h-4 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-800",children:l(s?"refineProgress.doneTitle":"refineProgress.runningTitle")}),e.jsxs("p",{className:"text-xs text-slate-500",children:[s?t.failed>0?l("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):l("refineProgress.doneMsg",{refined:String(t.refined)}):l("refineProgress.progressMsg",{done:String(u),total:String(t.total)}),c&&!s&&e.jsxs("span",{className:"ml-2 text-blue-600",children:[e.jsx(Me,{className:"w-3 h-3 inline animate-spin mr-1"}),c.title||c.candidateId.slice(0,8)]})]})]})]}),s&&a&&e.jsx("button",{onClick:a,className:"text-xs px-2.5 py-1 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors",children:l("refineProgress.closeBtn")})]}),e.jsx("div",{className:"w-full h-1.5 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-500 ease-out ${s?t.failed>0?"bg-amber-400":"bg-emerald-500":"bg-blue-500"}`,style:{width:`${t.progress}%`}})}),s&&t.failed>0&&e.jsxs("div",{className:"mt-2 text-xs text-red-500 flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),t.items.filter(p=>p.status==="failed").map(p=>p.title||p.candidateId.slice(0,8)).join("、")]})]})},ms={_watch:"silentLabels.watch",_draft:"silentLabels.draft",_cli:"silentLabels.cli",_pending:"silentLabels.pending",_recipe:"silentLabels.recipe"},hs={architecture:"bootstrap.dimLabels.architecture","best-practice":"bootstrap.dimLabels.bestPractice","event-and-data-flow":"bootstrap.dimLabels.eventAndDataFlow","objc-deep-scan":"bootstrap.dimLabels.objcDeepScan","agent-guidelines":"bootstrap.dimLabels.agentGuidelines",bootstrap:"bootstrap.dimLabels.bootstrap","code-standard":"bootstrap.dimLabels.codeStandard","code-pattern":"bootstrap.dimLabels.codePattern","project-profile":"bootstrap.dimLabels.projectProfile","category-scan":"bootstrap.dimLabels.categoryScan"};function Zr(t,s,a,l){return[...t].sort(([d],[c])=>{const u=l(d),p=l(c);if(u&&!p)return 1;if(!u&&p)return-1;const n=a(d),g=a(c);if(n&&!g)return-1;if(!n&&g)return 1;const f=s(d),h=s(c);return f&&!h?1:!f&&h?-1:d.localeCompare(c)})}function Wt(t,s){if(!t)return"";const a=typeof t=="number"?t:Number(t),l=a<1e12?a*1e3:a,d=new Date(l);if(isNaN(d.getTime())||d.getFullYear()<2e3)return"";const u=new Date().getTime()-d.getTime();if(u<0)return d.toLocaleDateString();const p=Math.floor(u/6e4);if(p<1)return s("candidates.timeJustNow");if(p<60)return s("candidates.timeMinutesAgo",{n:p});const n=Math.floor(p/60);if(n<24)return s("candidates.timeHoursAgo",{n});const g=Math.floor(n/24);return g<7?s("candidates.timeDaysAgo",{n:g}):d.toLocaleDateString()}function en(t,s=4){return t?Us(t).split(`
83
82
  `).slice(0,s).join(`
84
- `):""}function sn(t){return t==null?{ring:"stroke-slate-200",text:"text-slate-400",bg:"bg-slate-50",labelKey:""}:t>=.8?{ring:"stroke-emerald-500",text:"text-emerald-700",bg:"bg-emerald-50",labelKey:"candidates.confidenceHighLabel"}:t>=.6?{ring:"stroke-blue-500",text:"text-blue-700",bg:"bg-blue-50",labelKey:"candidates.confidenceMediumLabel"}:t>=.4?{ring:"stroke-amber-500",text:"text-amber-700",bg:"bg-amber-50",labelKey:"candidates.confidenceMediumLowLabel"}:{ring:"stroke-red-500",text:"text-red-700",bg:"bg-red-50",labelKey:"candidates.confidenceLowLabel"}}const ma={"bootstrap-scan":{labelKey:"candidates.sourceAiScanLabel",color:"text-violet-600 bg-violet-50 border-violet-200"},mcp:{labelKey:"candidates.sourceMcpLabel",color:"text-blue-600 bg-blue-50 border-blue-200"},manual:{labelKey:"candidates.sourceManualLabel",color:"text-emerald-600 bg-emerald-50 border-emerald-200"},"file-watcher":{labelKey:"candidates.sourceFileWatcherLabel",color:"text-orange-600 bg-orange-50 border-orange-200"},clipboard:{labelKey:"candidates.sourceClipboardLabel",color:"text-pink-600 bg-pink-50 border-pink-200"},cli:{labelKey:"CLI",color:"text-slate-600 bg-slate-50 border-slate-200"},agent:{labelKey:"AI Agent",color:"text-violet-600 bg-violet-50 border-violet-200"},submit_with_check:{labelKey:"candidates.sourceSubmitCheckLabel",color:"text-teal-600 bg-teal-50 border-teal-200"}},an=({value:t,size:s=36})=>{const a=(s-6)/2,l=2*Math.PI*a,d=t!=null?Math.max(0,Math.min(1,t)):0,i=l*(1-d),{ring:u,text:p}=sn(t);return e.jsxs("div",{className:"relative flex items-center justify-center",style:{width:s,height:s},children:[e.jsxs("svg",{width:s,height:s,className:"-rotate-90",children:[e.jsx("circle",{cx:s/2,cy:s/2,r:a,fill:"none",stroke:"currentColor",strokeWidth:3,className:"text-slate-100"}),e.jsx("circle",{cx:s/2,cy:s/2,r:a,fill:"none",strokeWidth:3,strokeLinecap:"round",className:u,strokeDasharray:l,strokeDashoffset:i,style:{transition:"stroke-dashoffset 0.5s ease"}})]}),e.jsx("span",{className:`absolute text-[9px] font-bold ${p}`,children:t!=null?`${Math.round(t*100)}`:"—"})]})},ln=({data:t,isShellTarget:s,isSilentTarget:a=()=>!1,isPendingTarget:l=()=>!1,handleDeleteCandidate:d,handleDeleteAllInTarget:i,onAuditCandidate:u,onAuditAllInTarget:p,onEditRecipe:n,onColdStart:g,isScanning:f,isBootstrapping:h,onRefresh:x})=>{var Ne;const{t:c}=_e(),[j,w]=o.useState(null),{isWide:C,toggle:E}=Vs(),[S,G]=o.useState(new Set),[z,P]=o.useState(new Set),[Z,X]=o.useState(!1),[H,q]=o.useState(!1),R=ds(),{refine:M,isRefining:_,isRefineDone:m,resetRefine:N}=Xr(),[y,W]=o.useState({}),[O,be]=o.useState(null),[we,ye]=o.useState({}),[v,ee]=o.useState(null),[ae,ue]=o.useState({}),[fe,he]=o.useState({sort:"default",onlySimilar:!1}),[ce,je]=o.useState(null),$=o.useRef(new Set),K=o.useCallback(async(r,k)=>{if(!$.current.has(k)){$.current.add(k),ee(k);try{const b=await se.getCandidateSimilarityEx({targetName:r,candidateId:k});ye(B=>({...B,[k]:b.similar||[]}))}catch{ye(B=>({...B,[k]:[]}))}finally{ee(null)}}},[]),xe=o.useCallback(async(r,k,b,B=[])=>{var me,I,V,Ce;const D=b.replace(/\.md$/i,"");let U="";const te=(me=t==null?void 0:t.recipes)==null?void 0:me.find(Ae=>Ae.name===D||Ae.name.endsWith("/"+D));if(te!=null&&te.content)U=[te.content.pattern,te.content.markdown].filter(Boolean).join(`
83
+ `):""}function tn(t){return t==null?{ring:"stroke-slate-200",text:"text-slate-400",bg:"bg-slate-50",labelKey:""}:t>=.8?{ring:"stroke-emerald-500",text:"text-emerald-700",bg:"bg-emerald-50",labelKey:"candidates.confidenceHighLabel"}:t>=.6?{ring:"stroke-blue-500",text:"text-blue-700",bg:"bg-blue-50",labelKey:"candidates.confidenceMediumLabel"}:t>=.4?{ring:"stroke-amber-500",text:"text-amber-700",bg:"bg-amber-50",labelKey:"candidates.confidenceMediumLowLabel"}:{ring:"stroke-red-500",text:"text-red-700",bg:"bg-red-50",labelKey:"candidates.confidenceLowLabel"}}const ma={"bootstrap-scan":{labelKey:"candidates.sourceAiScanLabel",color:"text-violet-600 bg-violet-50 border-violet-200"},mcp:{labelKey:"candidates.sourceMcpLabel",color:"text-blue-600 bg-blue-50 border-blue-200"},manual:{labelKey:"candidates.sourceManualLabel",color:"text-emerald-600 bg-emerald-50 border-emerald-200"},"file-watcher":{labelKey:"candidates.sourceFileWatcherLabel",color:"text-orange-600 bg-orange-50 border-orange-200"},clipboard:{labelKey:"candidates.sourceClipboardLabel",color:"text-pink-600 bg-pink-50 border-pink-200"},cli:{labelKey:"CLI",color:"text-slate-600 bg-slate-50 border-slate-200"},agent:{labelKey:"AI Agent",color:"text-violet-600 bg-violet-50 border-violet-200"},submit_with_check:{labelKey:"candidates.sourceSubmitCheckLabel",color:"text-teal-600 bg-teal-50 border-teal-200"}},sn=({value:t,size:s=36})=>{const a=(s-6)/2,l=2*Math.PI*a,d=t!=null?Math.max(0,Math.min(1,t)):0,c=l*(1-d),{ring:u,text:p}=tn(t);return e.jsxs("div",{className:"relative flex items-center justify-center",style:{width:s,height:s},children:[e.jsxs("svg",{width:s,height:s,className:"-rotate-90",children:[e.jsx("circle",{cx:s/2,cy:s/2,r:a,fill:"none",stroke:"currentColor",strokeWidth:3,className:"text-slate-100"}),e.jsx("circle",{cx:s/2,cy:s/2,r:a,fill:"none",strokeWidth:3,strokeLinecap:"round",className:u,strokeDasharray:l,strokeDashoffset:c,style:{transition:"stroke-dashoffset 0.5s ease"}})]}),e.jsx("span",{className:`absolute text-[9px] font-bold ${p}`,children:t!=null?`${Math.round(t*100)}`:"—"})]})},an=({data:t,isShellTarget:s,isSilentTarget:a=()=>!1,isPendingTarget:l=()=>!1,handleDeleteCandidate:d,handleDeleteAllInTarget:c,onAuditCandidate:u,onAuditAllInTarget:p,onEditRecipe:n,onColdStart:g,isScanning:f,isBootstrapping:h,onRefresh:x})=>{var De;const{t:i}=_e(),[y,k]=o.useState(null),{isWide:w,toggle:T}=Vs(),[A,G]=o.useState(new Set),[_,E]=o.useState(new Set),[Z,X]=o.useState(!1),[H,q]=o.useState(!1),I=ds(),{refine:L,isRefining:$,isRefineDone:m,resetRefine:N}=Qr(),[j,W]=o.useState({}),[O,ye]=o.useState(null),[Ne,je]=o.useState({}),[v,ee]=o.useState(null),[te,de]=o.useState({}),[ve,fe]=o.useState({sort:"default",onlySimilar:!1}),[ie,be]=o.useState(null),B=o.useRef(new Set),K=o.useCallback(async(r,C)=>{if(!B.current.has(C)){B.current.add(C),ee(C);try{const b=await ae.getCandidateSimilarityEx({targetName:r,candidateId:C});je(F=>({...F,[C]:b.similar||[]}))}catch{je(F=>({...F,[C]:[]}))}finally{ee(null)}}},[]),xe=o.useCallback(async(r,C,b,F=[])=>{var he,D,V,ke;const M=b.replace(/\.md$/i,"");let U="";const se=(he=t==null?void 0:t.recipes)==null?void 0:he.find(Ce=>Ce.name===M||Ce.name.endsWith("/"+M));if(se!=null&&se.content)U=[se.content.pattern,se.content.markdown].filter(Boolean).join(`
85
84
 
86
- `)||"";else try{U=(await se.getRecipeContentByName(D)).content}catch(Ae){const Re=(I=Ae.response)==null?void 0:I.status,Be=((Ce=(V=Ae.response)==null?void 0:V.data)==null?void 0:Ce.message)||Ae.message;Re===404?re(`"${D}" ${c("common.operationFailed")}`,{title:c("common.operationFailed"),type:"error"}):re(Be,{title:c("common.loadFailed"),type:"error"});return}const de={[D]:U};w(r.id),je({candidate:r,targetName:k,recipeName:D,recipeContent:U,similarList:B.slice(0,3),recipeContents:de})},[t==null?void 0:t.recipes]),L=t!=null&&t.candidates?Object.entries(t.candidates):[],T=en(L,s,a,l),Q=T.map(([r])=>r),ie=O&&Q.includes(O)?O:Q[0]??null;o.useEffect(()=>{Q.length>0&&(!O||!Q.includes(O))&&be(Q[0])},[Q.join(","),O]),o.useEffect(()=>{j&&ie&&K(ie,j)},[j,ie,K]);const ke=o.useMemo(()=>{var U;if(!ie||!((U=t==null?void 0:t.candidates)!=null&&U[ie]))return null;const r=t.candidates[ie].items,k=r.length,b=r.reduce((te,de)=>{var me;return te+(((me=de.reasoning)==null?void 0:me.confidence)??0)},0)/(k||1),B=r.filter(te=>{var de;return((de=te.content)==null?void 0:de.pattern)&&te.content.pattern.trim().length>0}).length,D=new Map;return r.forEach(te=>{const de=te.source||"unknown";D.set(de,(D.get(de)||0)+1)}),{total:k,avgConfidence:b,withCode:B,sources:D}},[ie,t==null?void 0:t.candidates]),Ue=o.useMemo(()=>{const r=new Map;if(t!=null&&t.idTitleMap)for(const[k,b]of Object.entries(t.idTitleMap))r.set(k,b);if(t!=null&&t.candidates)for(const k of Object.values(t.candidates))for(const b of k.items)b.id&&b.title&&r.set(b.id,b.title);if(t!=null&&t.recipes)for(const k of t.recipes)k.id&&k.name&&r.set(k.id,k.name.replace(/\.md$/i,""));return r},[t==null?void 0:t.idTitleMap,t==null?void 0:t.candidates,t==null?void 0:t.recipes]),Ie=o.useCallback(async r=>{var k,b,B,D,U;if(!S.has(r)){G(te=>new Set(te).add(r));try{const te=await se.enrichCandidates([r]);te.enriched>0?re(`${((B=(b=(k=te.results)==null?void 0:k[0])==null?void 0:b.filledFields)==null?void 0:B.length)||0} ${c("candidates.approveSuccess")}`,{title:c("candidates.aiRefine")}):re(c("recipes.noContent"),{title:c("candidates.aiRefine"),type:"info"});try{const de=await se.getCandidate(r);ue(me=>({...me,[r]:de}))}catch{}}catch(te){const de=(U=(D=te.response)==null?void 0:D.data)==null?void 0:U.error;re(typeof de=="string"?de:(de==null?void 0:de.message)||te.message,{title:c("common.operationFailed"),type:"error"})}finally{G(te=>{const de=new Set(te);return de.delete(r),de})}}},[S,x]),ne=o.useCallback(async()=>{var k,b,B;if(Z||!ie||!((k=t==null?void 0:t.candidates)!=null&&k[ie]))return;const r=t.candidates[ie].items;if(r.length!==0){X(!0);try{let D=0;for(let U=0;U<r.length;U+=20){const te=r.slice(U,U+20).map(me=>me.id),de=await se.enrichCandidates(te);D+=de.enriched}re(`${D}/${r.length} ${c("candidates.batchDeleteDone",{count:D})}`,{title:c("candidates.aiRefine")}),x==null||x()}catch(D){const U=(B=(b=D.response)==null?void 0:b.data)==null?void 0:B.error;re(typeof U=="string"?U:(U==null?void 0:U.message)||D.message,{title:c("common.operationFailed"),type:"error"})}finally{X(!1)}}},[Z,ie,t==null?void 0:t.candidates,x]),ve=o.useCallback(async r=>{try{const k=await se.getCandidate(r);ue(b=>({...b,[r]:k}))}catch{}},[]),He=o.useCallback(()=>{var b;if(!ie||!((b=t==null?void 0:t.candidates)!=null&&b[ie]))return;const r=t.candidates[ie].items,k=r.map(B=>B.id);R.openRefine({candidateIds:k,candidates:r,onCandidateUpdated:ve})},[ie,t==null?void 0:t.candidates,R,ve]),Pe=o.useCallback(r=>{var b;if(!ie||!((b=t==null?void 0:t.candidates)!=null&&b[ie]))return;je(null),w(r);const k=t.candidates[ie].items;R.openRefine({candidateIds:[r],candidates:k,onCandidateUpdated:ve})},[ie,t==null?void 0:t.candidates,R,ve]);return e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex justify-between items-center shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center",children:e.jsx(Qe,{className:"text-blue-600",size:20})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-800",children:"AI Scan Candidates"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:c("candidates.title")})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g&&!h&&e.jsxs("button",{onClick:g,disabled:f,className:`flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold transition-all ${f?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-white bg-gradient-to-r from-violet-500 to-purple-600 hover:from-violet-600 hover:to-purple-700 shadow-sm hover:shadow"}`,title:c("candidates.coldStartTitle"),children:[f?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(Xt,{size:14}),c(f?"common.loading":"candidates.sourceBootstrap")]}),ke&&ke.total>0&&e.jsxs("button",{onClick:ne,disabled:Z||H,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${Z||H?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-amber-700 bg-amber-50 border border-amber-200 hover:bg-amber-100"}`,title:c("candidates.enrichTitle"),children:[Z?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(fs,{size:14}),c(Z?"common.loading":"candidates.aiRefine")]}),ke&&ke.total>0&&e.jsxs("button",{onClick:He,disabled:H||Z||_,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${H||Z||_?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-emerald-700 bg-emerald-50 border border-emerald-200 hover:bg-emerald-100"}`,title:c("candidates.refineTitle"),children:[H||_?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(Qe,{size:14}),c(H||_?"common.loading":"candidates.aiRefine")]}),ke&&e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-50 border border-slate-100",children:[e.jsx(La,{size:14,className:"text-slate-400"}),e.jsx("span",{className:"text-slate-500",children:c("candidates.totalCount",{count:ke.total})}),ke.withCode<ke.total&&e.jsx("span",{className:"text-slate-400 ml-1",children:c("candidates.withCode",{count:ke.withCode})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-100",children:[e.jsx("span",{className:"text-emerald-500",children:c("candidates.confidence")}),e.jsxs("strong",{className:"text-emerald-700",children:[Math.round(ke.avgConfidence*100),"%"]})]})]})]})]}),M&&e.jsx(Zr,{refine:M,isRefineDone:m,onDismiss:()=>{N(),x==null||x()}}),L.length>0&&e.jsx("div",{className:"shrink-0 bg-white border border-slate-100 rounded-xl px-3 py-2 mb-4 shadow-sm",children:e.jsx("div",{className:"flex items-center gap-1.5 overflow-x-auto no-scrollbar",children:Q.map(r=>{var de;s(r);const k=a(r),b=ms[r]?c(ms[r]):void 0,B=t.candidates[r],D=((de=B==null?void 0:B.items)==null?void 0:de.length)??0,U=ie===r,te=ct[r]||ct.All;return e.jsxs("button",{onClick:()=>be(r),className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-bold whitespace-nowrap transition-all border
87
- ${U?`${(te==null?void 0:te.bg)||"bg-blue-50"} ${(te==null?void 0:te.color)||"text-blue-700"} ${(te==null?void 0:te.border)||"border-blue-200"} shadow-sm ring-1 ring-inset ${(te==null?void 0:te.border)||"ring-blue-200"}`:"bg-slate-50/80 text-slate-600 border-slate-100 hover:border-slate-200 hover:bg-slate-100"}`,children:[(()=>{const me=(te==null?void 0:te.icon)||ws;return e.jsx(me,{size:F.sm,className:U?"":"text-slate-400"})})(),e.jsx("span",{children:hs[r]?c(hs[r]):r}),k&&b&&e.jsx("span",{className:"text-[9px] text-amber-600 border border-amber-200 px-1 rounded",children:b}),e.jsx("span",{className:`text-[10px] font-normal rounded-full px-1.5 ${U?"bg-white/60":"bg-slate-200/60 text-slate-400"}`,children:D})]},r)})})}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1",children:[(!(t!=null&&t.candidates)||Object.keys(t.candidates).length===0)&&!h&&e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-white rounded-2xl border border-dashed border-slate-200 text-slate-400",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-slate-50 flex items-center justify-center mb-4",children:e.jsx(Ma,{size:32,className:"text-slate-300"})}),e.jsx("p",{className:"text-sm font-medium text-slate-500",children:c("candidates.noResults")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-slate-400",children:c("candidates.emptyHint")}),g&&e.jsxs("button",{onClick:g,disabled:f,className:`mt-4 flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${f?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-white bg-gradient-to-r from-violet-500 to-purple-600 hover:from-violet-600 hover:to-purple-700 shadow-md hover:shadow-lg"}`,children:[f?e.jsx(Fe,{size:16,className:"animate-spin"}):e.jsx(Xt,{size:16}),c(f?"common.loading":"candidates.sourceBootstrap")]}),e.jsxs("p",{className:"mt-3 text-[11px] text-slate-400",children:["或 ",e.jsx("code",{className:"text-blue-600 bg-blue-50 px-1 rounded",children:"asd ais --all"})," ",c("candidates.fullScanBtn"),e.jsx("code",{className:"text-blue-600 bg-blue-50 px-1 rounded ml-1",children:"asd candidate"})," ",c("candidates.clipboardCreate")]})]}),(!(t!=null&&t.candidates)||Object.keys(t.candidates).length===0)&&h&&e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-white rounded-2xl border border-dashed border-violet-200 text-slate-400",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-violet-50 flex items-center justify-center mb-4",children:e.jsx(Fe,{size:32,className:"text-violet-400 animate-spin"})}),e.jsx("p",{className:"text-sm font-medium text-violet-600",children:c("common.loading")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-slate-400",children:c("candidates.scanningHint")})]}),t&&ie&&T.filter(([r])=>r===ie).map(([r,k])=>{const b=s(r),B=a(r),D=ms[r]?c(ms[r]):c("candidates.silent"),U=y[r]||{page:1,pageSize:12},te=U.page,de=U.pageSize,me=k.items.filter(J=>{var Le;if(fe.onlySimilar){const qe=(Le=J.relations)==null?void 0:Le.related;if(!Array.isArray(qe)||qe.length===0)return!1}return!0}).sort((J,Le)=>{var qe,ze,Ve,ge,Oe,We;if(fe.sort==="default")return 0;if(fe.sort==="score-desc")return(((qe=Le.quality)==null?void 0:qe.overall)??0)-(((ze=J.quality)==null?void 0:ze.overall)??0);if(fe.sort==="score-asc")return(((Ve=J.quality)==null?void 0:Ve.overall)??0)-(((ge=Le.quality)==null?void 0:ge.overall)??0);if(fe.sort==="confidence-desc")return(((Oe=Le.reasoning)==null?void 0:Oe.confidence)??0)-(((We=J.reasoning)==null?void 0:We.confidence)??0);if(fe.sort==="date-desc"){const Ge=typeof J.createdAt=="number"?J.createdAt:0;return(typeof Le.createdAt=="number"?Le.createdAt:0)-Ge}return 0}),I=me.length,V=Math.ceil(I/de),Ce=(te-1)*de,Ae=me.slice(Ce,Ce+de),Re=J=>{W(Le=>({...Le,[r]:{...U,page:J}}))},Be=J=>{W(Le=>({...Le,[r]:{page:1,pageSize:J}}))},Ye=ct[r]||ct.All;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 rounded-xl bg-white border border-slate-100 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[(()=>{const J=(Ye==null?void 0:Ye.icon)||ws;return e.jsx(J,{size:18,className:(Ye==null?void 0:Ye.color)||"text-blue-600"})})(),e.jsx("span",{className:"text-base font-bold text-slate-800 truncate",children:hs[r]?c(hs[r]):r}),B&&e.jsx("span",{className:"text-[10px] font-bold text-amber-600 border border-amber-200 bg-amber-50 px-1.5 py-0.5 rounded",children:D}),b&&!B&&e.jsx("span",{className:"text-[10px] font-bold text-slate-400 border border-slate-200 bg-slate-50 px-1.5 py-0.5 rounded",children:"SHELL"}),e.jsxs("span",{className:"text-[11px] text-slate-400 flex items-center gap-1",children:[e.jsx(xt,{size:11}),c("candidates.scannedAt",{time:Wt(k.scanTime,c)||new Date(k.scanTime).toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 rounded-lg bg-slate-50 border border-slate-100",children:[e.jsx(Pa,{size:12,className:"text-slate-400"}),e.jsxs("select",{className:"text-[11px] font-medium bg-transparent border-none outline-none text-slate-600 pr-1 cursor-pointer",value:fe.sort,onChange:J=>he(Le=>({...Le,sort:J.target.value})),children:[e.jsx("option",{value:"default",children:c("candidates.sortNewest")}),e.jsxs("option",{value:"score-desc",children:[c("candidates.sortConfidence")," ↓"]}),e.jsxs("option",{value:"score-asc",children:[c("candidates.sortConfidence")," ↑"]}),e.jsxs("option",{value:"confidence-desc",children:[c("candidates.confidence")," ↓"]}),e.jsx("option",{value:"date-desc",children:c("candidates.sortOldest")})]})]}),e.jsxs("label",{className:"text-[11px] font-medium text-slate-500 flex items-center gap-1.5 px-2 py-1 rounded-lg bg-slate-50 border border-slate-100 cursor-pointer hover:bg-slate-100 transition-colors select-none",children:[e.jsx("input",{type:"checkbox",checked:fe.onlySimilar,onChange:J=>he(Le=>({...Le,onlySimilar:J.target.checked})),className:"rounded text-blue-600 w-3 h-3"}),c("candidates.similarOnly")]}),(fe.sort!=="default"||fe.onlySimilar)&&e.jsx("button",{onClick:()=>he({sort:"default",onlySimilar:!1}),className:"text-[11px] font-medium text-slate-500 hover:text-slate-700 px-2 py-1 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition-colors",children:c("candidates.resetFilters")})]}),e.jsx("div",{className:"h-5 w-px bg-slate-200"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-slate-400 font-medium",children:c("candidates.totalCount",{count:I})}),e.jsx("button",{onClick:()=>p(Ae,r),className:"text-[11px] font-bold text-blue-600 hover:text-blue-700 px-2.5 py-1.5 rounded-lg hover:bg-blue-50 transition-colors",children:c("candidates.approveCurrentPage")}),e.jsx("button",{onClick:async()=>{if(!window.confirm(c("candidates.batchDeleteConfirm",{count:Ae.length})))return;const Le=(await Promise.allSettled(Ae.map(qe=>d(r,qe.id)))).filter(qe=>qe.status==="rejected").length;Le>0&&re(`${Le} ${c("common.deleteFailed")}`,{title:c("common.operationFailed"),type:"error"}),x==null||x()},className:"text-[11px] font-bold text-orange-500 hover:text-orange-600 px-2.5 py-1.5 rounded-lg hover:bg-orange-50 transition-colors",children:c("candidates.removeCurrentPage")}),e.jsx("button",{onClick:()=>i(r),className:"text-[11px] font-bold text-red-500 hover:text-red-600 px-2.5 py-1.5 rounded-lg hover:bg-red-50 transition-colors border border-red-200",children:c("candidates.deleteAll")})]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:Ae.map(J=>{var pt,Mt,Ft,zt,$e;const Le=j===J.id,qe=((pt=J.reasoning)==null?void 0:pt.confidence)??null,ze=(((Mt=J.quality)==null?void 0:Mt.overall)??0)>0?J.quality.overall:null,ge=(((Ft=J.relations)==null?void 0:Ft.related)||[])[0],Oe=we[J.id]||[],We=ma[J.source||""]||{labelKey:J.source||"",color:"text-slate-500 bg-slate-50 border-slate-200"},Ge=ct[J.category||""]||ct.All||{};return e.jsxs("div",{onClick:()=>w(Le?null:J.id),className:`bg-white rounded-xl border overflow-hidden hover:shadow-lg transition-all duration-200 flex flex-col group cursor-pointer
85
+ `)||"";else try{U=(await ae.getRecipeContentByName(M)).content}catch(Ce){const Ie=(D=Ce.response)==null?void 0:D.status,Be=((ke=(V=Ce.response)==null?void 0:V.data)==null?void 0:ke.message)||Ce.message;Ie===404?re(`"${M}" ${i("common.operationFailed")}`,{title:i("common.operationFailed"),type:"error"}):re(Be,{title:i("common.loadFailed"),type:"error"});return}const ue={[M]:U};k(r.id),be({candidate:r,targetName:C,recipeName:M,recipeContent:U,similarList:F.slice(0,3),recipeContents:ue})},[t==null?void 0:t.recipes]),P=t!=null&&t.candidates?Object.entries(t.candidates):[],R=Zr(P,s,a,l),Q=R.map(([r])=>r),ce=O&&Q.includes(O)?O:Q[0]??null;o.useEffect(()=>{Q.length>0&&(!O||!Q.includes(O))&&ye(Q[0])},[Q.join(","),O]),o.useEffect(()=>{y&&ce&&K(ce,y)},[y,ce,K]);const we=o.useMemo(()=>{var U;if(!ce||!((U=t==null?void 0:t.candidates)!=null&&U[ce]))return null;const r=t.candidates[ce].items,C=r.length,b=r.reduce((se,ue)=>{var he;return se+(((he=ue.reasoning)==null?void 0:he.confidence)??0)},0)/(C||1),F=r.filter(se=>{var ue;return((ue=se.content)==null?void 0:ue.pattern)&&se.content.pattern.trim().length>0}).length,M=new Map;return r.forEach(se=>{const ue=se.source||"unknown";M.set(ue,(M.get(ue)||0)+1)}),{total:C,avgConfidence:b,withCode:F,sources:M}},[ce,t==null?void 0:t.candidates]),Ue=o.useMemo(()=>{const r=new Map;if(t!=null&&t.idTitleMap)for(const[C,b]of Object.entries(t.idTitleMap))r.set(C,b);if(t!=null&&t.candidates)for(const C of Object.values(t.candidates))for(const b of C.items)b.id&&b.title&&r.set(b.id,b.title);if(t!=null&&t.recipes)for(const C of t.recipes)C.id&&C.name&&r.set(C.id,C.name.replace(/\.md$/i,""));return r},[t==null?void 0:t.idTitleMap,t==null?void 0:t.candidates,t==null?void 0:t.recipes]),Se=o.useCallback(async r=>{var C,b,F,M,U;if(!A.has(r)){G(se=>new Set(se).add(r));try{const se=await ae.enrichCandidates([r]);se.enriched>0?re(`${((F=(b=(C=se.results)==null?void 0:C[0])==null?void 0:b.filledFields)==null?void 0:F.length)||0} ${i("candidates.approveSuccess")}`,{title:i("candidates.aiRefine")}):re(i("recipes.noContent"),{title:i("candidates.aiRefine"),type:"info"});try{const ue=await ae.getCandidate(r);de(he=>({...he,[r]:ue}))}catch{}}catch(se){const ue=(U=(M=se.response)==null?void 0:M.data)==null?void 0:U.error;re(typeof ue=="string"?ue:(ue==null?void 0:ue.message)||se.message,{title:i("common.operationFailed"),type:"error"})}finally{G(se=>{const ue=new Set(se);return ue.delete(r),ue})}}},[A,x]),ne=o.useCallback(async()=>{var C,b,F;if(Z||!ce||!((C=t==null?void 0:t.candidates)!=null&&C[ce]))return;const r=t.candidates[ce].items;if(r.length!==0){X(!0);try{let M=0;for(let U=0;U<r.length;U+=20){const se=r.slice(U,U+20).map(he=>he.id),ue=await ae.enrichCandidates(se);M+=ue.enriched}re(`${M}/${r.length} ${i("candidates.batchDeleteDone",{count:M})}`,{title:i("candidates.aiRefine")}),x==null||x()}catch(M){const U=(F=(b=M.response)==null?void 0:b.data)==null?void 0:F.error;re(typeof U=="string"?U:(U==null?void 0:U.message)||M.message,{title:i("common.operationFailed"),type:"error"})}finally{X(!1)}}},[Z,ce,t==null?void 0:t.candidates,x]),pe=o.useCallback(async r=>{try{const C=await ae.getCandidate(r);de(b=>({...b,[r]:C}))}catch{}},[]),Le=o.useCallback(()=>{var b;if(!ce||!((b=t==null?void 0:t.candidates)!=null&&b[ce]))return;const r=t.candidates[ce].items,C=r.map(F=>F.id);I.openRefine({candidateIds:C,candidates:r,onCandidateUpdated:pe})},[ce,t==null?void 0:t.candidates,I,pe]),He=o.useCallback(r=>{var b;if(!ce||!((b=t==null?void 0:t.candidates)!=null&&b[ce]))return;be(null),k(r);const C=t.candidates[ce].items;I.openRefine({candidateIds:[r],candidates:C,onCandidateUpdated:pe})},[ce,t==null?void 0:t.candidates,I,pe]);return e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap justify-between items-center gap-3 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0",children:e.jsx(Qe,{className:"text-blue-600",size:20})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-slate-800",children:"AI Scan Candidates"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5 truncate",children:i("candidates.title")})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[g&&!h&&e.jsxs("button",{onClick:g,disabled:f,className:`flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold transition-all ${f?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-white bg-gradient-to-r from-violet-500 to-purple-600 hover:from-violet-600 hover:to-purple-700 shadow-sm hover:shadow"}`,title:i("candidates.coldStartTitle"),children:[f?e.jsx(Me,{size:14,className:"animate-spin"}):e.jsx(Xt,{size:14}),i(f?"common.loading":"candidates.sourceBootstrap")]}),we&&we.total>0&&e.jsxs("button",{onClick:ne,disabled:Z||H,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${Z||H?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-amber-700 bg-amber-50 border border-amber-200 hover:bg-amber-100"}`,title:i("candidates.enrichTitle"),children:[Z?e.jsx(Me,{size:14,className:"animate-spin"}):e.jsx(fs,{size:14}),i(Z?"common.loading":"candidates.aiRefine")]}),we&&we.total>0&&e.jsxs("button",{onClick:Le,disabled:H||Z||$,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${H||Z||$?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-emerald-700 bg-emerald-50 border border-emerald-200 hover:bg-emerald-100"}`,title:i("candidates.refineTitle"),children:[H||$?e.jsx(Me,{size:14,className:"animate-spin"}):e.jsx(Qe,{size:14}),i(H||$?"common.loading":"candidates.aiRefine")]}),we&&e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-50 border border-slate-100",children:[e.jsx(La,{size:14,className:"text-slate-400"}),e.jsx("span",{className:"text-slate-500",children:i("candidates.totalCount",{count:we.total})}),we.withCode<we.total&&e.jsx("span",{className:"text-slate-400 ml-1",children:i("candidates.withCode",{count:we.withCode})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-100",children:[e.jsx("span",{className:"text-emerald-500",children:i("candidates.confidence")}),e.jsxs("strong",{className:"text-emerald-700",children:[Math.round(we.avgConfidence*100),"%"]})]})]})]})]}),L&&e.jsx(Xr,{refine:L,isRefineDone:m,onDismiss:()=>{N(),x==null||x()}}),P.length>0&&e.jsx("div",{className:"shrink-0 bg-white border border-slate-100 rounded-xl px-3 py-2 mb-4 shadow-sm",children:e.jsx("div",{className:"flex items-center gap-1.5 overflow-x-auto no-scrollbar",children:Q.map(r=>{var ue;s(r);const C=a(r),b=ms[r]?i(ms[r]):void 0,F=t.candidates[r],M=((ue=F==null?void 0:F.items)==null?void 0:ue.length)??0,U=ce===r,se=pt[r]||pt.All;return e.jsxs("button",{onClick:()=>ye(r),className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-bold whitespace-nowrap transition-all border
86
+ ${U?`${(se==null?void 0:se.bg)||"bg-blue-50"} ${(se==null?void 0:se.color)||"text-blue-700"} ${(se==null?void 0:se.border)||"border-blue-200"} shadow-sm ring-1 ring-inset ${(se==null?void 0:se.border)||"ring-blue-200"}`:"bg-slate-50/80 text-slate-600 border-slate-100 hover:border-slate-200 hover:bg-slate-100"}`,children:[(()=>{const he=(se==null?void 0:se.icon)||ws;return e.jsx(he,{size:z.sm,className:U?"":"text-slate-400"})})(),e.jsx("span",{children:hs[r]?i(hs[r]):r}),C&&b&&e.jsx("span",{className:"text-[9px] text-amber-600 border border-amber-200 px-1 rounded",children:b}),e.jsx("span",{className:`text-[10px] font-normal rounded-full px-1.5 ${U?"bg-white/60":"bg-slate-200/60 text-slate-400"}`,children:M})]},r)})})}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1",children:[(!(t!=null&&t.candidates)||Object.keys(t.candidates).length===0)&&!h&&e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-white rounded-2xl border border-dashed border-slate-200 text-slate-400",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-slate-50 flex items-center justify-center mb-4",children:e.jsx(Ma,{size:32,className:"text-slate-300"})}),e.jsx("p",{className:"text-sm font-medium text-slate-500",children:i("candidates.noResults")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-slate-400",children:i("candidates.emptyHint")}),g&&e.jsxs("button",{onClick:g,disabled:f,className:`mt-4 flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${f?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-white bg-gradient-to-r from-violet-500 to-purple-600 hover:from-violet-600 hover:to-purple-700 shadow-md hover:shadow-lg"}`,children:[f?e.jsx(Me,{size:16,className:"animate-spin"}):e.jsx(Xt,{size:16}),i(f?"common.loading":"candidates.sourceBootstrap")]}),e.jsxs("p",{className:"mt-3 text-[11px] text-slate-400",children:["或 ",e.jsx("code",{className:"text-blue-600 bg-blue-50 px-1 rounded",children:"asd ais --all"})," ",i("candidates.fullScanBtn"),e.jsx("code",{className:"text-blue-600 bg-blue-50 px-1 rounded ml-1",children:"asd candidate"})," ",i("candidates.clipboardCreate")]})]}),(!(t!=null&&t.candidates)||Object.keys(t.candidates).length===0)&&h&&e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-white rounded-2xl border border-dashed border-violet-200 text-slate-400",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-violet-50 flex items-center justify-center mb-4",children:e.jsx(Me,{size:32,className:"text-violet-400 animate-spin"})}),e.jsx("p",{className:"text-sm font-medium text-violet-600",children:i("common.loading")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-slate-400",children:i("candidates.scanningHint")})]}),t&&ce&&R.filter(([r])=>r===ce).map(([r,C])=>{const b=s(r),F=a(r),M=ms[r]?i(ms[r]):i("candidates.silent"),U=j[r]||{page:1,pageSize:12},se=U.page,ue=U.pageSize,he=C.items.filter(J=>{var Pe;if(ve.onlySimilar){const qe=(Pe=J.relations)==null?void 0:Pe.related;if(!Array.isArray(qe)||qe.length===0)return!1}return!0}).sort((J,Pe)=>{var qe,ze,Ve,ge,Oe,We;if(ve.sort==="default")return 0;if(ve.sort==="score-desc")return(((qe=Pe.quality)==null?void 0:qe.overall)??0)-(((ze=J.quality)==null?void 0:ze.overall)??0);if(ve.sort==="score-asc")return(((Ve=J.quality)==null?void 0:Ve.overall)??0)-(((ge=Pe.quality)==null?void 0:ge.overall)??0);if(ve.sort==="confidence-desc")return(((Oe=Pe.reasoning)==null?void 0:Oe.confidence)??0)-(((We=J.reasoning)==null?void 0:We.confidence)??0);if(ve.sort==="date-desc"){const Ge=typeof J.createdAt=="number"?J.createdAt:0;return(typeof Pe.createdAt=="number"?Pe.createdAt:0)-Ge}return 0}),D=he.length,V=Math.ceil(D/ue),ke=(se-1)*ue,Ce=he.slice(ke,ke+ue),Ie=J=>{W(Pe=>({...Pe,[r]:{...U,page:J}}))},Be=J=>{W(Pe=>({...Pe,[r]:{page:1,pageSize:J}}))},Ye=pt[r]||pt.All;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 rounded-xl bg-white border border-slate-100 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[(()=>{const J=(Ye==null?void 0:Ye.icon)||ws;return e.jsx(J,{size:18,className:(Ye==null?void 0:Ye.color)||"text-blue-600"})})(),e.jsx("span",{className:"text-base font-bold text-slate-800 truncate",children:hs[r]?i(hs[r]):r}),F&&e.jsx("span",{className:"text-[10px] font-bold text-amber-600 border border-amber-200 bg-amber-50 px-1.5 py-0.5 rounded",children:M}),b&&!F&&e.jsx("span",{className:"text-[10px] font-bold text-slate-400 border border-slate-200 bg-slate-50 px-1.5 py-0.5 rounded",children:"SHELL"}),e.jsxs("span",{className:"text-[11px] text-slate-400 flex items-center gap-1",children:[e.jsx(xt,{size:11}),i("candidates.scannedAt",{time:Wt(C.scanTime,i)||new Date(C.scanTime).toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 rounded-lg bg-slate-50 border border-slate-100",children:[e.jsx(Pa,{size:12,className:"text-slate-400"}),e.jsxs("select",{className:"text-[11px] font-medium bg-transparent border-none outline-none text-slate-600 pr-1 cursor-pointer",value:ve.sort,onChange:J=>fe(Pe=>({...Pe,sort:J.target.value})),children:[e.jsx("option",{value:"default",children:i("candidates.sortNewest")}),e.jsxs("option",{value:"score-desc",children:[i("candidates.sortConfidence")," ↓"]}),e.jsxs("option",{value:"score-asc",children:[i("candidates.sortConfidence")," ↑"]}),e.jsxs("option",{value:"confidence-desc",children:[i("candidates.confidence")," ↓"]}),e.jsx("option",{value:"date-desc",children:i("candidates.sortOldest")})]})]}),e.jsxs("label",{className:"text-[11px] font-medium text-slate-500 flex items-center gap-1.5 px-2 py-1 rounded-lg bg-slate-50 border border-slate-100 cursor-pointer hover:bg-slate-100 transition-colors select-none",children:[e.jsx("input",{type:"checkbox",checked:ve.onlySimilar,onChange:J=>fe(Pe=>({...Pe,onlySimilar:J.target.checked})),className:"rounded text-blue-600 w-3 h-3"}),i("candidates.similarOnly")]}),(ve.sort!=="default"||ve.onlySimilar)&&e.jsx("button",{onClick:()=>fe({sort:"default",onlySimilar:!1}),className:"text-[11px] font-medium text-slate-500 hover:text-slate-700 px-2 py-1 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition-colors",children:i("candidates.resetFilters")})]}),e.jsx("div",{className:"h-5 w-px bg-slate-200"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-slate-400 font-medium",children:i("candidates.totalCount",{count:D})}),e.jsx("button",{onClick:()=>p(Ce,r),className:"text-[11px] font-bold text-blue-600 hover:text-blue-700 px-2.5 py-1.5 rounded-lg hover:bg-blue-50 transition-colors",children:i("candidates.approveCurrentPage")}),e.jsx("button",{onClick:async()=>{if(!window.confirm(i("candidates.batchDeleteConfirm",{count:Ce.length})))return;const Pe=(await Promise.allSettled(Ce.map(qe=>d(r,qe.id)))).filter(qe=>qe.status==="rejected").length;Pe>0&&re(`${Pe} ${i("common.deleteFailed")}`,{title:i("common.operationFailed"),type:"error"}),x==null||x()},className:"text-[11px] font-bold text-orange-500 hover:text-orange-600 px-2.5 py-1.5 rounded-lg hover:bg-orange-50 transition-colors",children:i("candidates.removeCurrentPage")}),e.jsx("button",{onClick:()=>c(r),className:"text-[11px] font-bold text-red-500 hover:text-red-600 px-2.5 py-1.5 rounded-lg hover:bg-red-50 transition-colors border border-red-200",children:i("candidates.deleteAll")})]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:Ce.map(J=>{var ut,Mt,Ft,zt,$e;const Pe=y===J.id,qe=((ut=J.reasoning)==null?void 0:ut.confidence)??null,ze=(((Mt=J.quality)==null?void 0:Mt.overall)??0)>0?J.quality.overall:null,ge=(((Ft=J.relations)==null?void 0:Ft.related)||[])[0],Oe=Ne[J.id]||[],We=ma[J.source||""]||{labelKey:J.source||"",color:"text-slate-500 bg-slate-50 border-slate-200"},Ge=pt[J.category||""]||pt.All||{};return e.jsxs("div",{onClick:()=>k(Pe?null:J.id),className:`bg-white rounded-xl border overflow-hidden hover:shadow-lg transition-all duration-200 flex flex-col group cursor-pointer
88
87
  ${b?"opacity-75":""}
89
- ${Le?"ring-2 ring-blue-300 border-blue-300 shadow-md":"border-slate-200 hover:border-slate-300"}`,children:[e.jsx("div",{className:"px-4 pt-3.5 pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-1.5",children:[e.jsxs("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${(Ge==null?void 0:Ge.bg)||"bg-slate-50"} ${(Ge==null?void 0:Ge.color)||"text-slate-400"} ${(Ge==null?void 0:Ge.border)||"border-slate-100"}`,children:[(()=>{const Je=(Ge==null?void 0:Ge.icon)||lt;return e.jsx(Je,{size:10})})(),J.category||"general"]}),J.knowledgeType&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-100",children:J.knowledgeType}),J.source&&J.source!=="unknown"&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${We.color}`,children:We.labelKey.startsWith("candidates.")?c(We.labelKey):We.labelKey}),J.complexity&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border
90
- ${J.complexity==="advanced"?"bg-red-50 text-red-600 border-red-100":J.complexity==="intermediate"?"bg-amber-50 text-amber-600 border-amber-100":"bg-emerald-50 text-emerald-600 border-emerald-100"}`,children:J.complexity==="advanced"?c("candidates.confidenceHigh"):J.complexity==="intermediate"?c("candidates.confidenceMedium"):c("candidates.confidenceLow")})]}),e.jsx("h3",{className:"font-bold text-sm text-slate-800 leading-snug mb-1 line-clamp-1",children:J.title}),e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed",children:J.description||""})]}),e.jsxs("div",{className:"flex flex-col items-center gap-1 shrink-0",children:[e.jsx(an,{value:qe}),e.jsx("span",{className:"text-[9px] text-slate-400 font-medium",children:c("candidates.confidence")})]})]})}),((zt=J.reasoning)==null?void 0:zt.whyStandard)&&!/^Submitted via /i.test(J.reasoning.whyStandard)&&e.jsx("div",{className:"px-4 py-2 bg-gradient-to-r from-indigo-50/50 to-transparent border-t border-indigo-50",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(rs,{size:12,className:"text-indigo-400 mt-0.5 shrink-0"}),e.jsx("p",{className:"text-[11px] text-indigo-600/80 line-clamp-1 leading-relaxed",children:J.reasoning.whyStandard})]})}),(ze!=null||ge)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-4 py-2 border-t border-slate-50",children:[ze!=null&&e.jsxs("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 flex items-center gap-1",children:[e.jsx(cs,{size:10}),c("candidates.overallScore",{score:(ze*100).toFixed(0)+"%"})]}),ge&&e.jsxs("button",{onClick:Je=>{Je.stopPropagation();const st=String(ge.target||"").trim();st&&xe(J,r,st,Oe)},className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700 border border-amber-200 hover:bg-amber-100 transition-colors flex items-center gap-1",title:c("candidates.viewDetail"),children:[e.jsx(ys,{size:10}),c("candidates.similarPrefix")," ",Ue.get(String(ge.target||""))||String(ge.target||"").replace(/\.md$/i,"")]})]}),(($e=J.content)==null?void 0:$e.pattern)&&e.jsxs("div",{className:"overflow-hidden border-t border-slate-200/60",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5",style:{background:"#282c34"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{size:11,className:"text-slate-500"}),e.jsx("span",{className:"text-[10px] text-slate-400 font-mono uppercase tracking-wide",children:J.language||"code"})]}),e.jsx("span",{className:"text-[10px] text-slate-500 font-mono tabular-nums",children:c("candidates.linesCount",{count:J.content.pattern.split(`
91
- `).length})})]}),e.jsxs("div",{className:"relative max-h-[80px] overflow-hidden",children:[e.jsx(dt,{code:tn(J.content.pattern,3),language:J.language==="objc"?"objectivec":J.language,className:"!rounded-none"}),J.content.pattern.split(`
92
- `).length>3&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-6 bg-gradient-to-t from-[#282c34] to-transparent pointer-events-none"})]})]}),e.jsxs("div",{className:"flex justify-between items-center px-4 py-2.5 border-t border-slate-100 bg-slate-50/50 dark:bg-[#252a36] dark:border-slate-700 mt-auto",onClick:Je=>Je.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap min-w-0",children:[J.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded-md bg-white border border-slate-200 text-slate-600 font-bold",children:J.trigger}),e.jsx("span",{className:"text-[10px] uppercase font-bold text-slate-400 bg-white border border-slate-200 px-1.5 py-0.5 rounded-md",children:J.language}),J.tags&&J.tags.length>0&&J.tags.slice(0,3).map((Je,st)=>e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-md bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:typeof Je=="string"?Je:String(Je)},st)),J.tags&&J.tags.length>3&&e.jsxs("span",{className:"text-[9px] text-slate-400",children:["+",J.tags.length-3]}),J.createdAt&&Wt(J.createdAt,c)&&e.jsxs("span",{className:"text-[9px] text-slate-400 flex items-center gap-0.5",children:[e.jsx(xt,{size:9}),Wt(J.createdAt,c)]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("button",{onClick:()=>Ie(J.id),disabled:S.has(J.id),title:c("candidates.enrichTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${S.has(J.id)?"text-slate-300 cursor-not-allowed":"text-amber-500 hover:text-amber-600 hover:bg-amber-50"}`,children:S.has(J.id)?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(fs,{size:14})}),e.jsx("button",{onClick:()=>Pe(J.id),disabled:z.has(J.id),title:c("candidates.refineTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${z.has(J.id)?"text-slate-300 cursor-not-allowed":"text-emerald-500 hover:text-emerald-600 hover:bg-emerald-50"}`,children:z.has(J.id)?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(Qe,{size:14})}),e.jsx("button",{onClick:()=>{d(r,J.id),j===J.id&&(w(null),je(null))},title:c("common.delete"),className:"p-1.5 hover:bg-red-50 text-slate-400 hover:text-red-500 rounded-lg transition-colors",children:e.jsx(ot,{size:14})}),e.jsxs("button",{onClick:()=>u(J,r),className:"text-[11px] font-bold text-blue-600 hover:text-blue-700 px-3 py-1.5 rounded-lg bg-blue-50 hover:bg-blue-100 transition-colors flex items-center gap-1",children:[e.jsx(Et,{size:12})," ",c("candidates.approveAndSave")]}),J.lifecycle==="pending"&&e.jsxs("button",{onClick:async()=>{try{await se.promoteCandidateToRecipe(J.id),re(c("candidates.approveSuccess"),{title:c("candidates.approveSuccess")}),x==null||x()}catch(Je){re(Je.message,{title:c("common.operationFailed"),type:"error"})}},className:"text-[11px] font-bold text-emerald-600 hover:text-emerald-700 px-3 py-1.5 rounded-lg bg-emerald-50 hover:bg-emerald-100 transition-colors flex items-center gap-1",title:c("candidates.approve"),children:[e.jsx(Xt,{size:12})," ",c("candidates.approve")]})]})]})]},J.id)})}),I>12&&e.jsx(Js,{currentPage:te,totalPages:V,totalItems:I,pageSize:de,onPageChange:Re,onPageSizeChange:Be})]},r)})]}),j&&ie&&((Ne=t==null?void 0:t.candidates)==null?void 0:Ne[ie])&&(()=>{var Ye,J,Le,qe,ze,Ve;const r=t.candidates[ie].items,k=r.find(ge=>ge.id===j);if(!k)return null;const b=ae[j]||k,B=r.findIndex(ge=>ge.id===j),D=B>0,U=B<r.length-1,te=()=>{D&&(w(r[B-1].id),je(null))},de=()=>{U&&(w(r[B+1].id),je(null))},me=b.reasoning,I=(me==null?void 0:me.whyStandard)&&!/^Submitted via /i.test(me.whyStandard),V=me&&(I||me.sources&&me.sources.length>0||me.confidence!=null),Ce=we[b.id]||[],Ae=v===b.id,Re=ct[b.category||""]||ct.All||{},Be=ma[b.source||""]||{labelKey:b.source||"",color:"text-slate-500 bg-slate-50 border-slate-200"};return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:()=>{w(null),je(null)},children:[e.jsx(Ze.Backdrop,{className:"bg-black/15 backdrop-blur-[1px]"}),ce&&(()=>{const ge=ce.candidate,Oe=ge.language==="objc"||ge.language==="objective-c"?"objectivec":ge.language||"text",We=()=>{var Je,st;const $e=[];(Je=ge.content)!=null&&Je.pattern&&$e.push("## Snippet / Code Reference\n\n```"+Oe+`
88
+ ${Pe?"ring-2 ring-blue-300 border-blue-300 shadow-md":"border-slate-200 hover:border-slate-300"}`,children:[e.jsx("div",{className:"px-4 pt-3.5 pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-1.5",children:[e.jsxs("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${(Ge==null?void 0:Ge.bg)||"bg-slate-50"} ${(Ge==null?void 0:Ge.color)||"text-slate-400"} ${(Ge==null?void 0:Ge.border)||"border-slate-100"}`,children:[(()=>{const Je=(Ge==null?void 0:Ge.icon)||lt;return e.jsx(Je,{size:10})})(),J.category||"general"]}),J.knowledgeType&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-100",children:J.knowledgeType}),J.source&&J.source!=="unknown"&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${We.color}`,children:We.labelKey.startsWith("candidates.")?i(We.labelKey):We.labelKey}),J.complexity&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border
89
+ ${J.complexity==="advanced"?"bg-red-50 text-red-600 border-red-100":J.complexity==="intermediate"?"bg-amber-50 text-amber-600 border-amber-100":"bg-emerald-50 text-emerald-600 border-emerald-100"}`,children:J.complexity==="advanced"?i("candidates.confidenceHigh"):J.complexity==="intermediate"?i("candidates.confidenceMedium"):i("candidates.confidenceLow")})]}),e.jsx("h3",{className:"font-bold text-sm text-slate-800 leading-snug mb-1 line-clamp-1",children:J.title}),e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed",children:J.description||""})]}),e.jsxs("div",{className:"flex flex-col items-center gap-1 shrink-0",children:[e.jsx(sn,{value:qe}),e.jsx("span",{className:"text-[9px] text-slate-400 font-medium",children:i("candidates.confidence")})]})]})}),((zt=J.reasoning)==null?void 0:zt.whyStandard)&&!/^Submitted via /i.test(J.reasoning.whyStandard)&&e.jsx("div",{className:"px-4 py-2 bg-gradient-to-r from-indigo-50/50 to-transparent border-t border-indigo-50",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(rs,{size:12,className:"text-indigo-400 mt-0.5 shrink-0"}),e.jsx("p",{className:"text-[11px] text-indigo-600/80 line-clamp-1 leading-relaxed",children:J.reasoning.whyStandard})]})}),(ze!=null||ge)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-4 py-2 border-t border-slate-50",children:[ze!=null&&e.jsxs("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 flex items-center gap-1",children:[e.jsx(cs,{size:10}),i("candidates.overallScore",{score:(ze*100).toFixed(0)+"%"})]}),ge&&e.jsxs("button",{onClick:Je=>{Je.stopPropagation();const st=String(ge.target||"").trim();st&&xe(J,r,st,Oe)},className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700 border border-amber-200 hover:bg-amber-100 transition-colors flex items-center gap-1",title:i("candidates.viewDetail"),children:[e.jsx(ys,{size:10}),i("candidates.similarPrefix")," ",Ue.get(String(ge.target||""))||String(ge.target||"").replace(/\.md$/i,"")]})]}),(($e=J.content)==null?void 0:$e.pattern)&&e.jsxs("div",{className:"overflow-hidden border-t border-slate-200/60",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5",style:{background:"#282c34"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{size:11,className:"text-slate-500"}),e.jsx("span",{className:"text-[10px] text-slate-400 font-mono uppercase tracking-wide",children:J.language||"code"})]}),e.jsx("span",{className:"text-[10px] text-slate-500 font-mono tabular-nums",children:i("candidates.linesCount",{count:J.content.pattern.split(`
90
+ `).length})})]}),e.jsxs("div",{className:"relative max-h-[80px] overflow-hidden",children:[e.jsx(ct,{code:en(J.content.pattern,3),language:J.language==="objc"?"objectivec":J.language,className:"!rounded-none"}),J.content.pattern.split(`
91
+ `).length>3&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-6 bg-gradient-to-t from-[#282c34] to-transparent pointer-events-none"})]})]}),e.jsxs("div",{className:"flex justify-between items-center px-4 py-2.5 border-t border-slate-100 bg-slate-50/50 dark:bg-[#252a36] dark:border-slate-700 mt-auto",onClick:Je=>Je.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap min-w-0",children:[J.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded-md bg-white border border-slate-200 text-slate-600 font-bold",children:J.trigger}),e.jsx("span",{className:"text-[10px] uppercase font-bold text-slate-400 bg-white border border-slate-200 px-1.5 py-0.5 rounded-md",children:J.language}),J.tags&&J.tags.length>0&&J.tags.slice(0,3).map((Je,st)=>e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-md bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:typeof Je=="string"?Je:String(Je)},st)),J.tags&&J.tags.length>3&&e.jsxs("span",{className:"text-[9px] text-slate-400",children:["+",J.tags.length-3]}),J.createdAt&&Wt(J.createdAt,i)&&e.jsxs("span",{className:"text-[9px] text-slate-400 flex items-center gap-0.5",children:[e.jsx(xt,{size:9}),Wt(J.createdAt,i)]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("button",{onClick:()=>Se(J.id),disabled:A.has(J.id),title:i("candidates.enrichTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${A.has(J.id)?"text-slate-300 cursor-not-allowed":"text-amber-500 hover:text-amber-600 hover:bg-amber-50"}`,children:A.has(J.id)?e.jsx(Me,{size:14,className:"animate-spin"}):e.jsx(fs,{size:14})}),e.jsx("button",{onClick:()=>He(J.id),disabled:_.has(J.id),title:i("candidates.refineTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${_.has(J.id)?"text-slate-300 cursor-not-allowed":"text-emerald-500 hover:text-emerald-600 hover:bg-emerald-50"}`,children:_.has(J.id)?e.jsx(Me,{size:14,className:"animate-spin"}):e.jsx(Qe,{size:14})}),e.jsx("button",{onClick:()=>{d(r,J.id),y===J.id&&(k(null),be(null))},title:i("common.delete"),className:"p-1.5 hover:bg-red-50 text-slate-400 hover:text-red-500 rounded-lg transition-colors",children:e.jsx(ot,{size:14})}),e.jsxs("button",{onClick:()=>u(J,r),className:"text-[11px] font-bold text-blue-600 hover:text-blue-700 px-3 py-1.5 rounded-lg bg-blue-50 hover:bg-blue-100 transition-colors flex items-center gap-1",children:[e.jsx(Et,{size:12})," ",i("candidates.approveAndSave")]}),J.lifecycle==="pending"&&e.jsxs("button",{onClick:async()=>{try{await ae.promoteCandidateToRecipe(J.id),re(i("candidates.approveSuccess"),{title:i("candidates.approveSuccess")}),x==null||x()}catch(Je){re(Je.message,{title:i("common.operationFailed"),type:"error"})}},className:"text-[11px] font-bold text-emerald-600 hover:text-emerald-700 px-3 py-1.5 rounded-lg bg-emerald-50 hover:bg-emerald-100 transition-colors flex items-center gap-1",title:i("candidates.approve"),children:[e.jsx(Xt,{size:12})," ",i("candidates.approve")]})]})]})]},J.id)})}),D>12&&e.jsx(Js,{currentPage:se,totalPages:V,totalItems:D,pageSize:ue,onPageChange:Ie,onPageSizeChange:Be})]},r)})]}),y&&ce&&((De=t==null?void 0:t.candidates)==null?void 0:De[ce])&&(()=>{var Ye,J,Pe,qe,ze,Ve;const r=t.candidates[ce].items,C=r.find(ge=>ge.id===y);if(!C)return null;const b=te[y]||C,F=r.findIndex(ge=>ge.id===y),M=F>0,U=F<r.length-1,se=()=>{M&&(k(r[F-1].id),be(null))},ue=()=>{U&&(k(r[F+1].id),be(null))},he=b.reasoning,D=(he==null?void 0:he.whyStandard)&&!/^Submitted via /i.test(he.whyStandard),V=he&&(D||he.sources&&he.sources.length>0||he.confidence!=null),ke=Ne[b.id]||[],Ce=v===b.id,Ie=pt[b.category||""]||pt.All||{},Be=ma[b.source||""]||{labelKey:b.source||"",color:"text-slate-500 bg-slate-50 border-slate-200"};return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:()=>{k(null),be(null)},children:[e.jsx(Ze.Backdrop,{className:"bg-black/15 backdrop-blur-[1px]"}),ie&&(()=>{const ge=ie.candidate,Oe=ge.language==="objc"||ge.language==="objective-c"?"objectivec":ge.language||"text",We=()=>{var Je,st;const $e=[];(Je=ge.content)!=null&&Je.pattern&&$e.push("## Snippet / Code Reference\n\n```"+Oe+`
93
92
  `+ge.content.pattern+"\n```"),(st=ge.content)!=null&&st.markdown?$e.push(`
94
- ## `+c("candidates.projectProfile")+`
93
+ ## `+i("candidates.projectProfile")+`
95
94
 
96
95
  `+ge.content.markdown):ge.doClause&&$e.push(`
97
96
  ## AI Context / Usage Guide
98
97
 
99
98
  `+ge.doClause),navigator.clipboard.writeText($e.join(`
100
- `)||"").then(()=>re(c("common.copied"),{title:c("common.copied")}))},Ge=()=>{const $e=Ws(ce.recipeContent);navigator.clipboard.writeText($e).then(()=>re(c("common.copied"),{title:c("common.copied")}))},pt=async $e=>{var st;if($e===ce.recipeName)return;const Je=ce.recipeContents[$e];if(Je)je(A=>A?{...A,recipeName:$e,recipeContent:Je}:null);else{let A="";const le=(st=t==null?void 0:t.recipes)==null?void 0:st.find(Y=>Y.name===$e||Y.name.endsWith("/"+$e));if(le!=null&&le.content)A=[le.content.pattern,le.content.markdown].filter(Boolean).join(`
99
+ `)||"").then(()=>re(i("common.copied"),{title:i("common.copied")}))},Ge=()=>{const $e=Ws(ie.recipeContent);navigator.clipboard.writeText($e).then(()=>re(i("common.copied"),{title:i("common.copied")}))},ut=async $e=>{var st;if($e===ie.recipeName)return;const Je=ie.recipeContents[$e];if(Je)be(S=>S?{...S,recipeName:$e,recipeContent:Je}:null);else{let S="";const le=(st=t==null?void 0:t.recipes)==null?void 0:st.find(Y=>Y.name===$e||Y.name.endsWith("/"+$e));if(le!=null&&le.content)S=[le.content.pattern,le.content.markdown].filter(Boolean).join(`
101
100
 
102
- `)||"";else try{A=(await se.getRecipeContentByName($e)).content}catch{return}je(Y=>Y?{...Y,recipeName:$e,recipeContent:A,recipeContents:{...Y.recipeContents,[$e]:A}}:null)}},Mt=async()=>{if(window.confirm(c("common.areYouSure")))try{await d(ce.targetName,ge.id),je(null)}catch($e){re(($e==null?void 0:$e.message)||c("common.deleteFailed"),{title:c("common.deleteFailed"),type:"error"})}},Ft=()=>{u(ge,ce.targetName),je(null)},zt=()=>{var Je;const $e=(Je=t==null?void 0:t.recipes)==null?void 0:Je.find(st=>st.name===ce.recipeName||st.name.endsWith("/"+ce.recipeName));$e?n==null||n($e):n==null||n({name:ce.recipeName,content:{markdown:ce.recipeContent}}),je(null)};return e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col border-l border-slate-200 dark:border-slate-700 ${C?"w-[800px] max-w-[55vw]":"w-[600px] max-w-[45vw]"}`,style:{animation:"slideInRight 0.2s ease-out"},onClick:$e=>$e.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3.5 border-b border-slate-200 dark:border-slate-700 shrink-0 bg-emerald-50/60 dark:bg-emerald-900/20",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-br from-emerald-500 to-teal-600 flex items-center justify-center",children:e.jsx(ys,{size:16,className:"text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-bold text-sm text-emerald-800 truncate",children:c("candidates.recipeCompare")}),e.jsx("span",{className:"text-[11px] text-emerald-600 truncate block",children:ce.recipeName.replace(/\.md$/i,"")})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[e.jsx("button",{onClick:()=>Ge(),className:"p-1.5 hover:bg-emerald-100 rounded-lg text-emerald-600 transition-colors",title:c("common.copy"),children:e.jsx(qt,{size:14})}),e.jsx("button",{onClick:zt,className:"text-[11px] font-medium text-emerald-600 hover:bg-emerald-100 px-2 py-1.5 rounded-lg transition-colors",children:c("candidates.approveAndSave")}),e.jsx("button",{onClick:()=>je(null),className:"p-1.5 hover:bg-slate-200 rounded-lg transition-colors text-slate-400",children:e.jsx(Xe,{size:16})})]})]}),ce.similarList.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1 px-5 py-2 border-b border-slate-100 bg-white shrink-0",children:ce.similarList.map($e=>e.jsxs("button",{onClick:()=>pt($e.recipeName),className:`text-[10px] font-bold px-2 py-1 rounded transition-colors ${ce.recipeName===$e.recipeName?"bg-emerald-200 text-emerald-800":"bg-white text-emerald-600 hover:bg-emerald-50 border border-emerald-100"}`,children:[$e.recipeName.replace(/\.md$/i,"")," ",($e.similarity*100).toFixed(0),"%"]},$e.recipeName))}),e.jsxs("div",{className:"flex items-center gap-1.5 px-5 py-2 border-b border-slate-100 bg-white shrink-0",children:[e.jsxs("button",{onClick:Mt,className:"text-xs font-medium text-red-600 hover:bg-red-50 px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(ot,{size:12})," ",c("common.delete")]}),e.jsxs("button",{onClick:Ft,className:"text-xs font-medium text-blue-600 hover:bg-blue-50 px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(Et,{size:12})," ",c("candidates.approveAndSave")]}),e.jsxs("button",{onClick:()=>We(),className:"text-xs font-medium text-slate-500 hover:bg-slate-50 px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(qt,{size:12})," ",c("common.copy")]})]}),e.jsx("div",{className:"flex-1 overflow-auto p-5 min-h-0",children:e.jsx(gt,{content:ce.recipeContent,stripFrontmatter:!0})})]})})(),e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col border-l border-slate-200 dark:border-slate-700 ${C?"w-[960px] max-w-[92vw]":"w-[700px] max-w-[92vw]"}`,style:{animation:"slideInRight 0.25s ease-out"},onClick:ge=>ge.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-700 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] shrink-0",children:[e.jsx("div",{className:"flex-1 min-w-0 mr-3",children:e.jsx("h3",{className:"font-bold text-slate-800 text-lg leading-snug break-words",children:b.title})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:te,disabled:!D,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:c("common.back"),children:e.jsx(is,{size:F.md})}),e.jsxs("span",{className:"text-xs text-slate-400 tabular-nums",children:[B+1,"/",r.length]}),e.jsx("button",{onClick:de,disabled:!U,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:c("common.more"),children:e.jsx(rt,{size:F.md})}),e.jsx("div",{className:"w-px h-5 bg-slate-200 mx-1"}),e.jsx("button",{onClick:E,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400",title:c(C?"common.collapse":"common.expand"),children:C?e.jsx(Gs,{size:F.md}):e.jsx(Cs,{size:F.md})}),e.jsx("button",{onClick:()=>{d(ie,b.id),w(null),je(null)},className:"p-1.5 hover:bg-red-50 rounded-lg text-red-500 transition-colors",title:c("common.delete"),children:e.jsx(ot,{size:F.md})}),e.jsx("button",{onClick:()=>{w(null),je(null)},className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:F.md})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${(Re==null?void 0:Re.bg)||"bg-slate-50"} ${(Re==null?void 0:Re.color)||"text-slate-400"} ${(Re==null?void 0:Re.border)||"border-slate-100"}`,children:b.category||"general"}),b.knowledgeType&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-purple-50 text-purple-700 border border-purple-200",children:b.knowledgeType}),b.language&&e.jsx("span",{className:"text-[10px] uppercase font-bold text-slate-500 bg-slate-50 border border-slate-200 px-1.5 py-0.5 rounded",children:b.language}),b.complexity&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${b.complexity==="advanced"?"bg-red-50 text-red-600 border-red-100":b.complexity==="intermediate"?"bg-amber-50 text-amber-600 border-amber-100":"bg-emerald-50 text-emerald-600 border-emerald-100"}`,children:b.complexity==="advanced"?c("candidates.confidenceHigh"):b.complexity==="intermediate"?c("candidates.confidenceMedium"):c("candidates.confidenceLow")}),b.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200 font-bold",children:b.trigger}),b.source&&b.source!=="unknown"&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${Be.color}`,children:Be.labelKey.startsWith("candidates.")?c(Be.labelKey):Be.labelKey}),b.lifecycle&&b.lifecycle!=="pending"&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-200",children:b.lifecycle})]}),e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:(()=>{const ge=[];return b.scope&&ge.push({icon:Pt,iconClass:"text-teal-400",label:c("candidates.path"),value:b.scope==="universal"?c("common.all"):b.scope==="project-specific"||b.scope==="module-level"?c("candidates.category"):b.scope}),b.source&&b.source!=="unknown"&&ge.push({icon:Pt,iconClass:"text-violet-400",label:c("candidates.source"),value:Be.labelKey.startsWith("candidates.")?c(Be.labelKey):Be.labelKey}),b.createdAt&&Wt(b.createdAt,c)&&ge.push({icon:xt,iconClass:"text-slate-400",label:c("candidates.createdAt"),value:Wt(b.createdAt,c)}),ge.map((Oe,We)=>{const Ge=Oe.icon;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ge,{size:11,className:`${Oe.iconClass} shrink-0`}),e.jsx("span",{className:"text-slate-400",children:Oe.label}),e.jsx("span",{className:`font-medium text-slate-600 ${Oe.mono?"font-mono text-[11px]":""}`,children:Oe.value})]},We)})})()})]}),b.tags&&b.tags.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100 flex flex-wrap items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-slate-300 mr-0.5"}),b.tags.slice(0,10).map((ge,Oe)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:typeof ge=="string"?ge:String(ge)},Oe))]}),b.description&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:c("candidates.description")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:b.description})]}),V&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-amber-400"})," ",c("knowledge.reasoning")]}),e.jsxs("div",{className:"bg-amber-50/30 dark:bg-amber-900/15 border border-amber-100 dark:border-amber-800/40 rounded-xl p-4 space-y-2.5",children:[me.whyStandard&&!/^Submitted via /i.test(me.whyStandard)&&e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:me.whyStandard}),me.sources&&me.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[c("candidates.source"),":"]}),me.sources.map((ge,Oe)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-white border border-amber-200 rounded text-amber-700 font-mono",children:ge},Oe))]}),me.confidence!=null&&me.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[c("candidates.confidence"),":"]}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round((me.confidence??0)*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round((me.confidence??0)*100),"%"]})]}),me.alternatives&&me.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[c("candidates.viewDetail"),":"]}),me.alternatives.map((ge,Oe)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-slate-100 border border-slate-200 rounded text-slate-600",children:ge},Oe))]})]})]}),b.quality&&b.quality.grade&&b.quality.grade!=="F"&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("candidates.qualityDimensions")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${b.quality.grade==="A"?"text-emerald-600":b.quality.grade==="B"?"text-blue-600":b.quality.grade==="C"?"text-amber-600":b.quality.grade==="D"?"text-orange-600":"text-slate-400"}`,children:b.quality.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-[10px]",children:[b.quality.completeness!=null&&b.quality.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:b.quality.completeness}),e.jsx("div",{className:"text-slate-400",children:c("candidates.qualityDimensions")})]}),b.quality.adaptation!=null&&b.quality.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:b.quality.adaptation}),e.jsx("div",{className:"text-slate-400",children:c("candidates.qualityDimensions")})]}),b.quality.documentation!=null&&b.quality.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:b.quality.documentation}),e.jsx("div",{className:"text-slate-400",children:c("candidates.qualityDimensions")})]})]})]})]}),(()=>{const ge=b.relations?Object.entries(b.relations).flatMap(([We,Ge])=>Array.isArray(Ge)?Ge.map(pt=>({...pt,type:We})):[]):[];return b.agentNotes||b.aiInsight||ge.length>0?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-emerald-400"})," ",c("candidates.refineEnhanced")]}),e.jsxs("div",{className:"bg-emerald-50/30 dark:bg-emerald-900/15 border border-emerald-100 dark:border-emerald-800/40 rounded-xl p-4 space-y-2.5 text-xs",children:[b.aiInsight&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[c("candidates.viewDetail"),":"]}),e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed mt-0.5",children:b.aiInsight})]}),b.agentNotes&&b.agentNotes.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:c("candidates.agentNotes")}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:b.agentNotes.map((We,Ge)=>e.jsxs("li",{className:"flex items-start gap-1.5 text-slate-600",children:[e.jsx("span",{className:"text-emerald-400 mt-0.5",children:"•"}),We]},Ge))})]}),ge.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[c("recipes.relations"),":"]}),e.jsx("div",{className:"mt-1 space-y-1",children:ge.map((We,Ge)=>e.jsxs("div",{className:"flex items-start gap-1.5 text-slate-600",children:[e.jsx("span",{className:"text-[9px] font-bold px-1 py-0.5 rounded bg-emerald-100 text-emerald-700 shrink-0 uppercase",children:We.type}),e.jsx("span",{className:"font-medium text-slate-700",children:Ue.get(We.target)||We.target}),We.description&&e.jsxs("span",{className:"text-slate-400",children:["— ",We.description]})]},Ge))})]})]})]}):null})(),Ce.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[c("candidates.similarRecipe"),Ae&&e.jsx("span",{className:"text-[10px] text-slate-400 animate-pulse",children:c("common.loading")})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ce.slice(0,5).map(ge=>e.jsxs("button",{onClick:()=>xe(b,ie,ge.recipeName,Ce),className:"text-[10px] font-bold px-2 py-1 rounded-lg bg-amber-50 text-amber-700 border border-amber-200 hover:bg-amber-100 transition-colors flex items-center gap-1",title:c("candidates.similarWith",{name:ge.recipeName,score:(ge.similarity*100).toFixed(0)}),children:[e.jsx(ys,{size:10}),ge.recipeName.replace(/\.md$/i,"")," ",(ge.similarity*100).toFixed(0),"%"]},ge.recipeName))})]}),((Ye=b.content)==null?void 0:Ye.pattern)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ht,{size:11,className:"text-emerald-500"})," ",c("knowledge.codePattern")]}),e.jsx(dt,{code:b.content.pattern,language:b.language==="objc"?"objectivec":b.language,showLineNumbers:!0})]}),((J=b.content)==null?void 0:J.markdown)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",c("knowledge.markdownDoc")]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 dark:text-slate-300 leading-relaxed",children:e.jsx(gt,{content:b.content.markdown})})})]}),(b.doClause||b.whenClause||b.dontClause||b.topicHint||b.coreCode)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(lt,{size:11,className:"text-indigo-400"})," Cursor Delivery"]}),e.jsxs("div",{className:"bg-indigo-50/30 dark:bg-indigo-900/15 border border-indigo-100 dark:border-indigo-800/40 rounded-xl p-4 text-xs space-y-1.5",children:[b.topicHint&&e.jsxs("div",{children:[e.jsx("span",{className:"text-indigo-500 font-medium",children:"Topic:"}),e.jsx("span",{className:"text-slate-700",children:b.topicHint})]}),b.whenClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-500 font-medium",children:"When:"}),e.jsx("span",{className:"text-slate-700",children:b.whenClause})]}),b.doClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-emerald-500 font-medium",children:"Do:"}),e.jsx("span",{className:"text-slate-700",children:b.doClause})]}),b.dontClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-red-500 font-medium",children:"Don't:"}),e.jsx("span",{className:"text-slate-700",children:b.dontClause})]}),b.coreCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-purple-500 font-medium",children:"Core Code:"}),e.jsx("div",{className:"mt-1",children:e.jsx(dt,{code:b.coreCode,language:b.language==="objectivec"||b.language==="objc"?"objectivec":b.language||"text"})})]})]})]}),(b.scope||b.headers&&b.headers.length>0||((Le=b.content)==null?void 0:Le.steps)&&b.content.steps.length>0||((qe=b.content)==null?void 0:qe.rationale))&&e.jsxs(e.Fragment,{children:[((ze=b.content)==null?void 0:ze.rationale)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("candidates.rationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:b.content.rationale})})]}),b.headers&&b.headers.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("candidates.headers")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:b.headers.map((ge,Oe)=>e.jsx("code",{className:"px-2.5 py-1 bg-violet-50 text-violet-700 border border-violet-100 rounded-md text-[10px] font-mono font-medium",children:ge},Oe))})]}),((Ve=b.content)==null?void 0:Ve.steps)&&b.content.steps.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("recipes.steps")}),e.jsx("div",{className:"space-y-2",children:b.content.steps.map((ge,Oe)=>{if(typeof ge=="string")return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:Oe+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:ge})]},Oe);const We=typeof ge.title=="string"?ge.title:"",Ge=typeof ge.description=="string"?ge.description:"",pt=typeof ge.code=="string"?ge.code:"";return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:Oe+1}),We&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:We})]}),Ge&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:Ge}),pt&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:pt})]},Oe)})})]})]})]}),e.jsxs("div",{className:"shrink-0 border-t border-slate-200 dark:border-slate-700 px-5 py-3 bg-gradient-to-b from-slate-50/80 to-white dark:from-[#252526] dark:to-[#1e1e1e] flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>Ie(b.id),disabled:S.has(b.id),title:c("candidates.enrichTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${S.has(b.id)?"text-slate-300 cursor-not-allowed":"text-amber-600 hover:bg-amber-50 border border-amber-200"}`,children:[S.has(b.id)?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(fs,{size:14}),c("candidates.enrichShort")]}),e.jsxs("button",{onClick:()=>Pe(b.id),disabled:z.has(b.id),title:c("candidates.refineTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${z.has(b.id)?"text-slate-300 cursor-not-allowed":"text-emerald-600 hover:bg-emerald-50 border border-emerald-200"}`,children:[z.has(b.id)?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(Qe,{size:14}),c("candidates.refineShort")]}),e.jsxs("button",{onClick:()=>{d(ie,b.id),w(null),je(null)},title:c("common.delete"),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-red-500 hover:bg-red-50 border border-red-200 transition-colors",children:[e.jsx(ot,{size:14})," ",c("common.delete")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[b.lifecycle==="pending"&&e.jsxs("button",{onClick:async()=>{try{await se.promoteCandidateToRecipe(b.id),re(c("candidates.approveSuccess"),{title:c("candidates.approveSuccess")}),x==null||x()}catch(ge){re(ge.message,{title:c("common.operationFailed"),type:"error"})}},className:"flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold text-emerald-700 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200 transition-colors",children:[e.jsx(Xt,{size:14})," ",c("candidates.approve")]}),e.jsxs("button",{onClick:()=>{u(b,ie),w(null),je(null)},className:"flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold text-white bg-blue-600 hover:bg-blue-700 transition-colors shadow-sm",children:[e.jsx(Et,{size:14})," ",c("candidates.approveAndSave")]})]})]})]})]})})()]})},rn=({isOpen:t,onClose:s,currentFile:a,targetName:l,language:d="",onSelectRecipe:i})=>{var X,H,q,R;const{t:u}=_e(),[p,n]=o.useState(""),[g,f]=o.useState([]),[h,x]=o.useState(null),[c,j]=o.useState(!1),[w,C]=o.useState(null),[E,S]=o.useState(!1),[G,z]=o.useState(null),P=async()=>{if(p.trim()){j(!0);try{const M=await se.search(p,{context:{language:d},limit:10});f((M.items||[]).map(_=>{var m,N,y;return{name:(_.title||_.name||"")+".md",content:((m=_.content)==null?void 0:m.pattern)||((N=_.content)==null?void 0:N.markdown)||((y=_.content)==null?void 0:y.code)||"",similarity:_.score||0,authority:_.authorityScore||0,matchType:_.matchType||"ranked",qualityScore:_.qualityScore||0,usageCount:_.usageCount||0}})),x(null)}catch(M){console.error("Context-aware search failed:",M),alert(u("search.searchFailed"))}finally{j(!1)}}},Z=M=>{M.key==="Enter"&&P()};return t?e.jsxs(Ze,{className:"z-30 flex",children:[e.jsx(Ze.Backdrop,{className:"bg-black/20"}),e.jsxs("div",{className:"relative w-full max-w-2xl ml-auto bg-white shadow-xl flex flex-col max-h-screen",children:[e.jsxs("div",{className:"border-b border-slate-200 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:u("search.title")}),e.jsx("button",{onClick:s,className:"p-1 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:F.lg,className:"text-slate-500"})})]}),h&&e.jsx("div",{className:"mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(et,{size:F.md,className:"text-blue-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[((X=h.targetInfo)==null?void 0:X.targetName)&&e.jsxs("div",{className:"text-blue-900 font-medium flex items-center gap-2 mb-1",children:[e.jsx(Xs,{size:F.sm}),"Target: ",h.targetInfo.targetName]}),((H=h.fileInfo)==null?void 0:H.imports)&&h.fileInfo.imports.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-2",children:[e.jsx("strong",{children:u("search.importedFrameworks")})," ",h.fileInfo.imports.slice(0,3).join(", "),h.fileInfo.imports.length>3&&` +${h.fileInfo.imports.length-3}`]}),((q=h.targetInfo)==null?void 0:q.suggestedApis)&&h.targetInfo.suggestedApis.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-1",children:[e.jsx("strong",{children:u("search.relatedApis")})," ",h.targetInfo.suggestedApis.slice(0,3).join(", ")]})]})]})}),e.jsxs("div",{className:"relative",children:[e.jsx(ft,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:F.md}),e.jsx("input",{type:"text",placeholder:u("search.searchPlaceholder"),value:p,onChange:M=>n(M.target.value),onKeyDown:Z,className:"w-full pl-10 pr-4 py-2 border border-slate-300 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-500/20 transition-all"})]}),e.jsxs("button",{onClick:P,disabled:!p.trim()||c,className:"mt-3 w-full py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:bg-blue-300 transition-colors flex items-center justify-center gap-2",children:[c&&e.jsx(Fe,{size:F.sm,className:"animate-spin"}),u(c?"search.searching":"search.searchBtn")]})]}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[g.length===0&&!c&&e.jsx("div",{className:"flex items-center justify-center h-full text-slate-500",children:e.jsxs("div",{className:"text-center",children:[e.jsx($s,{size:F.xxl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:u("search.emptyHint")})]})}),g.map((M,_)=>e.jsxs("div",{className:"border-b border-slate-200 p-4 hover:bg-slate-50 transition-colors cursor-pointer",onClick:()=>{C(w===_?null:_),M.name&&(i==null||i(M.name))},children:[e.jsxs("div",{className:"flex items-start justify-between mb-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-slate-900 text-sm",children:M.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-slate-100 rounded text-xs text-slate-600",children:[e.jsx(et,{size:F.xs}),Math.round(M.similarity*100),"%"]}),M.isContextRelevant&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-green-100 rounded text-xs text-green-700",children:[e.jsx(Xs,{size:F.xs}),u("search.contextRelevant")]}),M.matchType&&e.jsx("span",{className:"text-xs text-slate-500",children:M.matchType==="semantic"?u("search.matchSemantic"):u("search.matchKeyword")})]})]}),e.jsx("button",{onClick:m=>{m.stopPropagation(),C(w===_?null:_)},className:"p-1 hover:bg-slate-200 rounded transition-colors",children:w===_?"▼":"▶"})]}),M.stats&&e.jsxs("div",{className:"text-xs text-slate-500 mb-2 flex gap-3",children:[M.stats.authorityScore!==void 0&&e.jsxs("span",{children:[u("search.authorityScore"),": ",M.stats.authorityScore]}),M.usageCount!==void 0&&e.jsxs("span",{children:[u("search.usage"),": ",u("search.usageCount",{count:M.usageCount})]})]}),w===_&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-slate-200",children:[M.recommendReason&&e.jsxs("div",{className:"text-xs text-slate-600 bg-blue-50 p-2 rounded mb-2 border border-blue-100",children:[e.jsx("p",{className:"font-medium text-blue-700 mb-0.5",children:u("search.recommendReason")}),e.jsx("p",{children:M.recommendReason})]}),e.jsxs("div",{className:"text-xs text-slate-600 max-h-[200px] overflow-auto bg-slate-50 p-3 rounded",children:[M.content.substring(0,500),"..."]}),e.jsx("button",{onClick:m=>{m.stopPropagation(),z(M),S(!0)},className:"mt-2 w-full py-1.5 bg-blue-50 text-blue-600 rounded text-xs font-medium hover:bg-blue-100 transition-colors",children:u("search.viewFullContent")})]})]},_)),c&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(Fe,{size:F.lg,className:"animate-spin text-blue-600"})}),g.length===0&&p&&!c&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsxs("div",{className:"text-center text-slate-500",children:[e.jsx(Ot,{size:F.xl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:u("search.noResults")})]})})]})]}),E&&G&&e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-black/40"}),e.jsxs("div",{className:"relative bg-white rounded-lg shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"border-b border-slate-200 p-6 flex items-start justify-between shrink-0",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-slate-900",children:G.name}),e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsxs("span",{className:"text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded",children:[u("search.similarity"),": ",Math.round(G.similarity*100),"%"]}),G.isContextRelevant&&e.jsxs("span",{className:"text-xs bg-green-100 text-green-700 px-2 py-1 rounded",children:["✓ ",u("search.contextRelevant")]}),G.qualityScore!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 rounded text-xs text-blue-700 font-medium",children:["🤖 ",u("search.quality"),": ",(G.qualityScore*100).toFixed(0),"%"]}),((R=G.stats)==null?void 0:R.authorityScore)!==void 0&&e.jsxs("span",{className:"text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded",children:[u("search.authorityScore"),": ",Math.round(G.stats.authorityScore*100)/100]})]})]}),e.jsx("button",{onClick:()=>S(!1),className:"p-1 hover:bg-slate-100 rounded transition-colors shrink-0",children:e.jsx(Xe,{size:F.lg,className:"text-slate-500"})})]}),e.jsx("div",{className:"overflow-auto flex-1 p-6",children:e.jsx("div",{className:"prose prose-sm max-w-none",children:G.content?e.jsx(dt,{code:G.content,language:"markdown"}):e.jsx("p",{className:"text-slate-500 text-sm",children:u("search.noContent")})})}),e.jsxs("div",{className:"border-t border-slate-200 p-4 bg-slate-50 flex justify-end gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>S(!1),className:"px-4 py-2 text-slate-700 hover:bg-slate-200 rounded transition-colors text-sm font-medium",children:u("common.close")}),i&&e.jsxs("button",{onClick:()=>{i(G.name),S(!1)},className:"px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 rounded transition-colors text-sm font-medium flex items-center gap-2",children:[e.jsx(rt,{size:F.md}),u("search.useSnippet")]})]})]})]})]}):null},ha=t=>Os(t.language)||"text";function nn(t){const s=[],a=t.match(/#import\s+"([^"]+)"/);if(a){const u=a[1].replace(/\.h$/,"");s.push(u)}const l=t.match(/#import\s+<([^>]+)>/);if(l){const u=l[1].replace(/\.h$/,"").split("/");s.push(...u)}const d=t.match(/^import\s+(\w+)/);d&&s.push(d[1]);const i=t.match(/@import\s+(\w+)/);return i&&s.push(i[1]),[...new Set(s.filter(Boolean))]}function Vt(t,s){if(!s||!s.trim())return"unknown";const a=nn(t);return a.length===0?"unknown":a.some(l=>s.includes(l))?"used":"unused"}function on(t){return t.startsWith("#import ")||t.startsWith("import ")||t.startsWith("@import ")?t.trim():t.startsWith("<")||t.startsWith('"')?`#import ${t.trim()}`:t.trim()}const cn=[{value:"",label:"—"},{value:"networking",label:"Networking"},{value:"ui",label:"UI"},{value:"data",label:"Data"},{value:"architecture",label:"Architecture"},{value:"conventions",label:"Conventions"}],dn=t=>{var d;const s=(((d=t.content)==null?void 0:d.pattern)||"").trim();if(!s)return!1;const a=s.split(`
103
- `).filter(i=>i.trim());return!(a.filter(i=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(i)).length>a.length*.3)},un=({res:t,index:s,editingCodeIndex:a,setEditingCodeIndex:l,expandedEditIndex:d,setExpandedEditIndex:i,similarityMap:u,handleUpdateScanResult:p,handleSaveExtracted:n,handlePromoteToCandidate:g,openCompare:f,isSavingRecipe:h=!1})=>{var X,H,q;const{t:x}=_e(),[c,j]=o.useState(!1),w=d===s,C=t.headers||[],E=((X=t.content)==null?void 0:X.pattern)||"",S=((H=t.content)==null?void 0:H.markdown)||"",G=t.description||"",z=t.tags||[],P=dn(t),Z=(R,M)=>{p(s,{content:{...t.content||{},[R]:M}})};return e.jsxs("div",{className:"bg-slate-50 dark:bg-[#1a1d24] rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden shadow-sm",children:[e.jsxs("div",{className:"px-5 pt-4 pb-3 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] border-b border-slate-100 dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5",children:x("scanResult.knowledgeEntryTitle")}),t.scanMode==="project"?e.jsxs("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded bg-indigo-100 text-indigo-700 border border-indigo-200 flex items-center gap-1",children:[e.jsx(lt,{size:10})," PROJECT"]}):t.scanMode==="target"?e.jsxs("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 flex items-center gap-1",children:[e.jsx(et,{size:10})," ",t.candidateTargetName||"TARGET"]}):t.lifecycle?e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded flex items-center gap-1 ${t.lifecycle==="pending"?"bg-amber-100 text-amber-700 border border-amber-200":t.lifecycle==="active"?"bg-green-100 text-green-700 border border-green-200":"bg-slate-100 text-slate-600 border border-slate-200"}`,children:t.lifecycle==="pending"?x("scanResult.lifecyclePending"):t.lifecycle==="active"?x("scanResult.lifecycleActive"):t.lifecycle==="deprecated"?x("scanResult.lifecycleDeprecated"):t.lifecycle}):null,t.source&&t.source!=="unknown"&&e.jsx("span",{className:"text-[9px] font-medium px-1.5 py-0.5 rounded bg-violet-50 text-violet-600 border border-violet-100",children:t.source==="agent"?"AI Agent":t.source==="bootstrap-scan"?x("scanResult.aiScan"):t.source})]}),e.jsx("input",{className:"font-semibold bg-transparent border-b-2 border-transparent hover:border-slate-200 focus:border-blue-500 outline-none px-0.5 text-lg w-full text-slate-800 placeholder:text-slate-300",value:t.title||"",onChange:R=>p(s,{title:R.target.value})})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 pt-3",children:[g&&e.jsxs("button",{onClick:()=>g(t,s),className:"text-xs px-4 py-2 rounded-lg font-bold transition-all shadow-sm flex items-center gap-1.5 active:scale-95 bg-white dark:bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-700/40 hover:bg-emerald-50 dark:hover:bg-emerald-500/20 whitespace-nowrap",children:[e.jsx(Rl,{size:F.md}),"Candidate"]}),e.jsxs("button",{onClick:()=>n(t),disabled:h,className:`text-xs px-4 py-2 rounded-lg font-bold transition-all shadow-sm flex items-center gap-1.5 active:scale-95 disabled:opacity-60 disabled:cursor-not-allowed whitespace-nowrap ${P&&t.mode==="full"?"bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-500/20 dark:text-blue-300 dark:hover:bg-blue-500/30 dark:border dark:border-blue-500/30":"bg-amber-600 text-white hover:bg-amber-700 dark:bg-amber-500/20 dark:text-amber-300 dark:hover:bg-amber-500/30 dark:border dark:border-amber-500/30"}`,children:[h?e.jsx(Fe,{size:F.md,className:"animate-spin"}):e.jsx(Fa,{size:F.md}),x(h?"scanResult.saving":P?"scanResult.saveAsRecipe":"scanResult.saveAsKnowledge")]})]})]}),e.jsxs("div",{className:"flex items-end gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.trigger")}),e.jsx("input",{className:"font-mono font-bold text-blue-600 bg-blue-50/80 border border-blue-100 px-2.5 py-1 rounded-md outline-none text-xs focus:ring-2 focus:ring-blue-500/20 w-44",value:t.trigger||"",placeholder:x("scanResult.triggerPlaceholder"),onChange:R=>p(s,{trigger:R.target.value})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:"Kind"}),e.jsxs("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:t.kind||"pattern",onChange:R=>p(s,{kind:R.target.value}),children:[e.jsx("option",{value:"rule",children:"Rule"}),e.jsx("option",{value:"pattern",children:"Pattern"}),e.jsx("option",{value:"fact",children:"Fact"})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:"Topic"}),e.jsx("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:t.topicHint||"",onChange:R=>p(s,{topicHint:R.target.value}),children:cn.map(R=>e.jsx("option",{value:R.value,children:R.label},R.value))})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.category")}),e.jsx("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:t.category||"",onChange:R=>p(s,{category:R.target.value}),children:tr.filter(R=>R!=="All").map(R=>e.jsx("option",{value:R,children:R},R))})]}),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.language")}),e.jsx("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:Os(t.language),onChange:R=>p(s,{language:R.target.value}),children:Bt.map(R=>e.jsx("option",{value:R.id,children:R.label},R.id))})]})]}),t.moduleName&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.module")}),e.jsx("span",{className:"text-[11px] bg-purple-50 text-purple-700 border border-purple-100 px-2 py-1 rounded-md font-mono font-bold",children:t.moduleName})]})]}),e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),P&&e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.mode")}),e.jsxs("div",{className:"flex bg-white dark:bg-[#252a36] p-0.5 rounded-md border border-slate-200 dark:border-slate-600",children:[e.jsx("button",{onClick:()=>p(s,{mode:"full"}),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${t.mode==="full"?"bg-blue-100 shadow-sm text-blue-600":"text-slate-400 hover:text-slate-500"}`,children:"Snippet+Recipe"}),e.jsx("button",{onClick:()=>p(s,{mode:"preview"}),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${t.mode==="preview"?"bg-amber-100 shadow-sm text-amber-600":"text-slate-400 hover:text-slate-500"}`,children:"Recipe Only"})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.difficulty")}),e.jsxs("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-purple-500/20",value:t.difficulty||"intermediate",onChange:R=>p(s,{difficulty:R.target.value,complexity:R.target.value}),children:[e.jsx("option",{value:"beginner",children:x("scanResult.difficultyBeginner")}),e.jsx("option",{value:"intermediate",children:x("scanResult.difficultyIntermediate")}),e.jsx("option",{value:"advanced",children:x("scanResult.difficultyAdvanced")})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.authorityScore")}),e.jsxs("select",{className:"font-bold text-amber-600 bg-amber-50/60 border border-amber-100 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-amber-500/20",value:t.authority??((q=t.stats)==null?void 0:q.authority)??3,onChange:R=>p(s,{authority:parseInt(R.target.value)}),children:[e.jsx("option",{value:"1",children:"⭐ 1"}),e.jsx("option",{value:"2",children:"⭐⭐ 2"}),e.jsx("option",{value:"3",children:"⭐⭐⭐ 3"}),e.jsx("option",{value:"4",children:"⭐⭐⭐⭐ 4"}),e.jsx("option",{value:"5",children:"⭐⭐⭐⭐⭐ 5"})]})]})]}),e.jsx("div",{className:"mt-2.5",children:e.jsxs("div",{className:"flex flex-wrap gap-1 items-center bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-md px-1.5 py-0.5 min-h-[28px] focus-within:ring-2 focus-within:ring-blue-500/20",children:[z.map((R,M)=>e.jsxs("span",{className:"flex items-center gap-0.5 text-[10px] font-bold bg-blue-50 text-blue-700 border border-blue-200 px-1.5 py-0 rounded",children:[R,e.jsx("button",{onClick:()=>{const _=[...z];_.splice(M,1),p(s,{tags:_})},className:"text-blue-400 hover:text-red-500 transition-colors leading-none text-[10px]",title:"{t('scanResult.removeTag')}",children:"×"})]},M)),e.jsx("input",{className:"flex-1 min-w-[80px] text-[11px] text-slate-600 outline-none bg-transparent py-0.5",placeholder:z.length===0?x("scanResult.tagsPlaceholder"):"",onKeyDown:R=>{const M=R.currentTarget,_=M.value.trim();if((R.key==="Enter"||R.key===","||R.key===",")&&_){R.preventDefault();const m=_.replace(/[,,]/g,"").trim();m&&!z.includes(m)&&p(s,{tags:[...z,m]}),M.value=""}else if(R.key==="Backspace"&&!M.value&&z.length>0){const m=[...z];m.pop(),p(s,{tags:m})}},onBlur:R=>{const M=R.currentTarget.value.trim().replace(/[,,]/g,"").trim();M&&!z.includes(M)&&p(s,{tags:[...z,M]}),R.currentTarget.value=""}})]})}),P&&C.length>0&&e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:x("scanResult.headers")}),e.jsxs("button",{onClick:()=>i(d===s?null:s),className:`text-[10px] font-bold px-2 py-0.5 rounded-md transition-colors border ${w?"text-blue-700 bg-blue-100 border-blue-300":"text-blue-600 bg-blue-50 border-blue-100 hover:bg-blue-100"}`,children:[x(w?"scanResult.collapseHeaders":"scanResult.editHeaders")," (",C.length,")"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[9px] text-slate-400",children:"Snippet:"}),e.jsx("button",{onClick:()=>p(s,{includeHeaders:t.includeHeaders===!1}),className:`w-7 h-4 rounded-full relative transition-colors ${t.includeHeaders!==!1?"bg-blue-600":"bg-slate-300"}`,title:t.includeHeaders!==!1?x("scanResultCard.includeMarkOn"):x("scanResultCard.includeMarkOff"),children:e.jsx("div",{className:`absolute top-0.5 w-2.5 h-2.5 bg-white rounded-full transition-all ${t.includeHeaders!==!1?"right-0.5":"left-0.5"}`})}),e.jsx("span",{className:"text-[9px] font-bold text-slate-600",children:t.includeHeaders!==!1?"ON":"OFF"})]}),(()=>{const R=C.filter(_=>Vt(_,E)==="used").length,M=C.filter(_=>Vt(_,E)==="unused").length;return e.jsxs("span",{className:"text-[9px] text-slate-400",children:[R>0&&e.jsxs("span",{className:"text-green-600 font-bold",children:[R," ",x("scanResult.referenced")]}),R>0&&M>0&&" · ",M>0&&e.jsxs("span",{className:"text-amber-600 font-bold",children:[M," ",x("scanResult.unreferenced")]})]})})()]}),w&&e.jsxs("div",{className:"space-y-2 bg-slate-50/80 dark:bg-[#1e2028] rounded-lg p-3 border border-slate-200 dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[e.jsx("button",{onClick:()=>{const R=C.map(M=>on(M));p(s,{headers:R})},className:"text-[9px] px-2 py-0.5 bg-slate-200 text-slate-600 rounded hover:bg-slate-300 font-bold",title:x("scanResultCard.formatHeaders"),children:x("scanResult.formatHeaders")}),C.some(R=>Vt(R,E)==="unused")&&e.jsx("button",{onClick:()=>{const R=C.filter(M=>Vt(M,E)!=="unused");p(s,{headers:R})},className:"text-[9px] px-2 py-0.5 bg-amber-100 text-amber-700 rounded hover:bg-amber-200 font-bold",title:x("scanResultCard.cleanUnused"),children:x("scanResult.cleanUnused")}),e.jsx("button",{onClick:()=>{const R=[...C,sa(t.language)];p(s,{headers:R})},className:"text-[9px] px-2 py-0.5 bg-green-500 text-white rounded hover:bg-green-600 font-bold",children:x("scanResult.addHeader")})]}),e.jsx("div",{className:"space-y-1",children:C.map((R,M)=>{const _=Vt(R,E);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${_==="used"?"bg-green-500":_==="unused"?"bg-amber-400":"bg-slate-300"}`,title:x(_==="used"?"scanResult.usedInCode":_==="unused"?"scanResult.unusedInCode":"scanResult.unknown")}),e.jsx("input",{className:`flex-1 text-xs font-mono bg-white dark:bg-[#252a36] border rounded px-2 py-1 outline-none focus:border-blue-400 ${_==="unused"?"border-amber-300 text-amber-700 dark:border-amber-700 dark:text-amber-400":"border-slate-200 dark:border-slate-600"}`,value:R,onChange:m=>{const N=[...C];N[M]=m.target.value,p(s,{headers:N})},placeholder:sa(t.language)}),_==="unused"&&e.jsx("span",{className:"text-[8px] text-amber-500 font-bold shrink-0",children:x("scanResult.unreferenced")}),e.jsx("button",{onClick:()=>{const m=C.filter((N,y)=>y!==M);p(s,{headers:m})},className:"px-2 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-[9px] font-bold shrink-0",children:x("scanResult.deleteHeader")})]},M)})})]})]})]}),e.jsxs("div",{className:"px-6 pb-6 pt-4 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-cyan-200 dark:border-cyan-800/40 bg-gradient-to-br from-cyan-50/60 to-blue-50/40 dark:from-cyan-900/15 dark:to-blue-900/10 p-4 space-y-3",children:[e.jsxs("div",{className:"text-[10px] font-bold text-cyan-700 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(et,{size:12}),x("scanResult.cursorDelivery")]}),e.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-2 items-start",children:[e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase pt-1.5 select-none",children:"Do"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.doClause||"",onChange:R=>p(s,{doClause:R.target.value}),placeholder:"English imperative ≤60 tokens, e.g. Use dispatch_once for thread-safe singleton"}),e.jsx("span",{className:"text-[10px] font-bold text-red-500 uppercase pt-1.5 select-none",children:"Don't"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.dontClause||"",onChange:R=>p(s,{dontClause:R.target.value}),placeholder:"English constraint (omit 'Don't' prefix), e.g. use @synchronized for singleton"}),e.jsx("span",{className:"text-[10px] font-bold text-amber-600 uppercase pt-1.5 select-none",children:"When"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.whenClause||"",onChange:R=>p(s,{whenClause:R.target.value}),placeholder:"When implementing singleton pattern or global shared instance"})]})]}),t.reasoning&&(t.reasoning.confidence!=null||t.reasoning.whyStandard&&!/^Submitted via /i.test(t.reasoning.whyStandard))&&e.jsxs("div",{className:"rounded-xl border border-indigo-100 dark:border-indigo-800/40 bg-indigo-50/40 dark:bg-indigo-900/15 p-3 text-xs space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-indigo-600 font-bold text-[10px]",children:[x("scanResult.aiReasoning"),t.reasoning.confidence!=null&&e.jsx("span",{className:`ml-auto font-mono text-[10px] ${t.reasoning.confidence>=.7?"text-emerald-600":t.reasoning.confidence>=.4?"text-amber-600":"text-red-600"}`,children:x("scanResult.confidenceLabel",{value:Math.round(t.reasoning.confidence*100)})})]}),t.reasoning.whyStandard&&!/^Submitted via /i.test(t.reasoning.whyStandard)&&e.jsx("p",{className:"text-slate-600",children:t.reasoning.whyStandard}),t.reasoning.sources&&t.reasoning.sources.length>0&&e.jsxs("p",{className:"text-slate-400",children:[x("scanResult.sourceLabel")," ",t.reasoning.sources.join(", ")]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-bold text-slate-400 uppercase mb-1",children:x("scanResult.description")}),e.jsx("textarea",{rows:1,className:"w-full text-sm text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 outline-none resize-none leading-relaxed focus:ring-2 focus:ring-blue-500/10",value:G,onChange:R=>p(s,{description:R.target.value,summary:R.target.value}),placeholder:x("scanResult.descPlaceholder")})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:x("scanResult.markdown")}),e.jsx("button",{type:"button",onClick:()=>j(!c),className:`flex items-center gap-1 text-[10px] font-bold px-2 py-1 rounded transition-colors ${c?"text-blue-600 hover:text-blue-700 bg-blue-50":"text-slate-500 hover:text-slate-700 hover:bg-slate-100"}`,children:c?e.jsxs(e.Fragment,{children:[e.jsx(kt,{size:F.xs})," ",x("scanResult.done")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ms,{size:F.xs})," ",x("common.edit")]})})]}),c?e.jsx("textarea",{rows:Math.max(6,(S||"").split(`
104
- `).length),className:"w-full text-sm text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 outline-none resize-y leading-relaxed focus:ring-2 focus:ring-blue-500/10 font-mono",value:S,onChange:R=>Z("markdown",R.target.value)}):S?e.jsx("div",{className:"text-sm text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-xl px-4 py-3 leading-relaxed whitespace-pre-wrap max-h-64 overflow-y-auto",children:S}):e.jsx("p",{className:"text-xs text-slate-400 italic py-2",children:x("scanResult.noArticle")})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:x("scanResult.code")}),a===s?e.jsxs("button",{type:"button",onClick:()=>l(null),className:"flex items-center gap-1 text-[10px] font-bold text-blue-600 hover:text-blue-700 px-2 py-1 rounded bg-blue-50",children:[e.jsx(kt,{size:F.xs})," ",x("scanResult.done")]}):e.jsxs("button",{type:"button",onClick:()=>l(s),className:"flex items-center gap-1 text-[10px] font-bold text-slate-500 hover:text-slate-700 px-2 py-1 rounded hover:bg-slate-100",title:x("common.edit"),children:[e.jsx(Ms,{size:F.xs})," ",x("common.edit")]})]}),a===s?e.jsx("div",{className:"rounded-xl overflow-hidden",children:e.jsx(ks,{value:E,onChange:R=>Z("pattern",R),language:ha(t),height:`${Math.min(12,E.split(`
105
- `).length)*20+16}px`})}):E?e.jsx(dt,{code:E,language:ha(t),showLineNumbers:!0}):e.jsx("p",{className:"text-xs text-slate-400 italic py-4",children:x("scanResult.noCode")})]}),(()=>{const R=t.candidateId??t.id??`scan-${s}`,M=u[R],_=(M||[]).filter(y=>y.similarity>=.6);if(_.length===0)return null;const m=_.filter(y=>y.similarity>=.85),N=m.length>0;return e.jsxs("div",{className:"space-y-1.5",children:[N&&e.jsxs("div",{className:"flex items-center gap-2 bg-red-50 border border-red-200 rounded-lg px-3 py-2",children:[e.jsx("span",{className:"text-red-500 text-sm",children:"⚠️"}),e.jsx("span",{className:"text-[11px] font-bold text-red-700",children:x("scanResult.highDuplicateRisk")}),m.map(y=>e.jsxs("button",{onClick:()=>f(t,y.recipeName,M||[]),className:"text-[11px] font-bold px-2 py-0.5 rounded bg-red-100 text-red-800 border border-red-300 hover:bg-red-200 transition-colors",children:[y.recipeName.replace(/\.md$/i,"")," ",(y.similarity*100).toFixed(0),"%"]},y.recipeName)),e.jsx("span",{className:"text-[10px] text-red-500",children:x("scanResult.compareBeforeSave")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:x("scanResult.similarRecipes")}),_.slice(0,5).map(y=>e.jsxs("button",{onClick:()=>f(t,y.recipeName,M||[]),className:`text-[10px] font-bold px-2 py-1 rounded border transition-colors flex items-center gap-1 ${y.similarity>=.85?"bg-red-50 text-red-700 border-red-200 hover:bg-red-100":"bg-amber-50 text-amber-700 border-amber-200 hover:bg-amber-100"}`,title:x("scanResultCard.similarWithClick",{name:y.recipeName,score:(y.similarity*100).toFixed(0)}),children:[e.jsx(ys,{size:F.xs}),y.recipeName.replace(/\.md$/i,"")," ",(y.similarity*100).toFixed(0),"%"]},y.recipeName))]})]})})()]})]})},pn=t=>{const s=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(s)?"objectivec":t.language||"text"},xn=({data:t,onClose:s,onDataChange:a,recipes:l,handleSaveExtracted:d,handleDeleteCandidate:i,onEditRecipe:u,isSavingRecipe:p=!1})=>{var E,S,G,z;const{t:n}=_e(),g=t.candidate,f=pn(g),h=()=>{var H,q;const P=[],Z=((H=g.content)==null?void 0:H.pattern)||"",X=((q=g.content)==null?void 0:q.markdown)||g.doClause||"";Z&&P.push("## Snippet / Code Reference\n\n```"+f+`
106
- `+Z+"\n```"),X&&P.push(`
101
+ `)||"";else try{S=(await ae.getRecipeContentByName($e)).content}catch{return}be(Y=>Y?{...Y,recipeName:$e,recipeContent:S,recipeContents:{...Y.recipeContents,[$e]:S}}:null)}},Mt=async()=>{if(window.confirm(i("common.areYouSure")))try{await d(ie.targetName,ge.id),be(null)}catch($e){re(($e==null?void 0:$e.message)||i("common.deleteFailed"),{title:i("common.deleteFailed"),type:"error"})}},Ft=()=>{u(ge,ie.targetName),be(null)},zt=()=>{var Je;const $e=(Je=t==null?void 0:t.recipes)==null?void 0:Je.find(st=>st.name===ie.recipeName||st.name.endsWith("/"+ie.recipeName));$e?n==null||n($e):n==null||n({name:ie.recipeName,content:{markdown:ie.recipeContent}}),be(null)};return e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col border-l border-slate-200 dark:border-slate-700 ${w?"w-[800px] max-w-[55vw]":"w-[600px] max-w-[45vw]"}`,style:{animation:"slideInRight 0.2s ease-out"},onClick:$e=>$e.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3.5 border-b border-slate-200 dark:border-slate-700 shrink-0 bg-emerald-50/60 dark:bg-emerald-900/20",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-br from-emerald-500 to-teal-600 flex items-center justify-center",children:e.jsx(ys,{size:16,className:"text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-bold text-sm text-emerald-800 truncate",children:i("candidates.recipeCompare")}),e.jsx("span",{className:"text-[11px] text-emerald-600 truncate block",children:ie.recipeName.replace(/\.md$/i,"")})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[e.jsx("button",{onClick:()=>Ge(),className:"p-1.5 hover:bg-emerald-100 rounded-lg text-emerald-600 transition-colors",title:i("common.copy"),children:e.jsx(qt,{size:14})}),e.jsx("button",{onClick:zt,className:"text-[11px] font-medium text-emerald-600 hover:bg-emerald-100 px-2 py-1.5 rounded-lg transition-colors",children:i("candidates.approveAndSave")}),e.jsx("button",{onClick:()=>be(null),className:"p-1.5 hover:bg-slate-200 rounded-lg transition-colors text-slate-400",children:e.jsx(Xe,{size:16})})]})]}),ie.similarList.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1 px-5 py-2 border-b border-slate-100 bg-white shrink-0",children:ie.similarList.map($e=>e.jsxs("button",{onClick:()=>ut($e.recipeName),className:`text-[10px] font-bold px-2 py-1 rounded transition-colors ${ie.recipeName===$e.recipeName?"bg-emerald-200 text-emerald-800":"bg-white text-emerald-600 hover:bg-emerald-50 border border-emerald-100"}`,children:[$e.recipeName.replace(/\.md$/i,"")," ",($e.similarity*100).toFixed(0),"%"]},$e.recipeName))}),e.jsxs("div",{className:"flex items-center gap-1.5 px-5 py-2 border-b border-slate-100 bg-white shrink-0",children:[e.jsxs("button",{onClick:Mt,className:"text-xs font-medium text-red-600 hover:bg-red-50 px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(ot,{size:12})," ",i("common.delete")]}),e.jsxs("button",{onClick:Ft,className:"text-xs font-medium text-blue-600 hover:bg-blue-50 px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(Et,{size:12})," ",i("candidates.approveAndSave")]}),e.jsxs("button",{onClick:()=>We(),className:"text-xs font-medium text-slate-500 hover:bg-slate-50 px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(qt,{size:12})," ",i("common.copy")]})]}),e.jsx("div",{className:"flex-1 overflow-auto p-5 min-h-0",children:e.jsx(gt,{content:ie.recipeContent,stripFrontmatter:!0})})]})})(),e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col border-l border-slate-200 dark:border-slate-700 ${w?"w-[960px] max-w-[92vw]":"w-[700px] max-w-[92vw]"}`,style:{animation:"slideInRight 0.25s ease-out"},onClick:ge=>ge.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-700 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] shrink-0",children:[e.jsx("div",{className:"flex-1 min-w-0 mr-3",children:e.jsx("h3",{className:"font-bold text-slate-800 text-lg leading-snug break-words",children:b.title})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:se,disabled:!M,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:i("common.back"),children:e.jsx(is,{size:z.md})}),e.jsxs("span",{className:"text-xs text-slate-400 tabular-nums",children:[F+1,"/",r.length]}),e.jsx("button",{onClick:ue,disabled:!U,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:i("common.more"),children:e.jsx(rt,{size:z.md})}),e.jsx("div",{className:"w-px h-5 bg-slate-200 mx-1"}),e.jsx("button",{onClick:T,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400",title:i(w?"common.collapse":"common.expand"),children:w?e.jsx(Gs,{size:z.md}):e.jsx(Cs,{size:z.md})}),e.jsx("button",{onClick:()=>{d(ce,b.id),k(null),be(null)},className:"p-1.5 hover:bg-red-50 rounded-lg text-red-500 transition-colors",title:i("common.delete"),children:e.jsx(ot,{size:z.md})}),e.jsx("button",{onClick:()=>{k(null),be(null)},className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:z.md})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${(Ie==null?void 0:Ie.bg)||"bg-slate-50"} ${(Ie==null?void 0:Ie.color)||"text-slate-400"} ${(Ie==null?void 0:Ie.border)||"border-slate-100"}`,children:b.category||"general"}),b.knowledgeType&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-purple-50 text-purple-700 border border-purple-200",children:b.knowledgeType}),b.language&&e.jsx("span",{className:"text-[10px] uppercase font-bold text-slate-500 bg-slate-50 border border-slate-200 px-1.5 py-0.5 rounded",children:b.language}),b.complexity&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${b.complexity==="advanced"?"bg-red-50 text-red-600 border-red-100":b.complexity==="intermediate"?"bg-amber-50 text-amber-600 border-amber-100":"bg-emerald-50 text-emerald-600 border-emerald-100"}`,children:b.complexity==="advanced"?i("candidates.confidenceHigh"):b.complexity==="intermediate"?i("candidates.confidenceMedium"):i("candidates.confidenceLow")}),b.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200 font-bold",children:b.trigger}),b.source&&b.source!=="unknown"&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${Be.color}`,children:Be.labelKey.startsWith("candidates.")?i(Be.labelKey):Be.labelKey}),b.lifecycle&&b.lifecycle!=="pending"&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-200",children:b.lifecycle})]}),e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:(()=>{const ge=[];return b.scope&&ge.push({icon:Pt,iconClass:"text-teal-400",label:i("candidates.path"),value:b.scope==="universal"?i("common.all"):b.scope==="project-specific"||b.scope==="module-level"?i("candidates.category"):b.scope}),b.source&&b.source!=="unknown"&&ge.push({icon:Pt,iconClass:"text-violet-400",label:i("candidates.source"),value:Be.labelKey.startsWith("candidates.")?i(Be.labelKey):Be.labelKey}),b.createdAt&&Wt(b.createdAt,i)&&ge.push({icon:xt,iconClass:"text-slate-400",label:i("candidates.createdAt"),value:Wt(b.createdAt,i)}),ge.map((Oe,We)=>{const Ge=Oe.icon;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ge,{size:11,className:`${Oe.iconClass} shrink-0`}),e.jsx("span",{className:"text-slate-400",children:Oe.label}),e.jsx("span",{className:`font-medium text-slate-600 ${Oe.mono?"font-mono text-[11px]":""}`,children:Oe.value})]},We)})})()})]}),b.tags&&b.tags.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100 flex flex-wrap items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-slate-300 mr-0.5"}),b.tags.slice(0,10).map((ge,Oe)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:typeof ge=="string"?ge:String(ge)},Oe))]}),b.description&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:i("candidates.description")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:b.description})]}),V&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-amber-400"})," ",i("knowledge.reasoning")]}),e.jsxs("div",{className:"bg-amber-50/30 dark:bg-amber-900/15 border border-amber-100 dark:border-amber-800/40 rounded-xl p-4 space-y-2.5",children:[he.whyStandard&&!/^Submitted via /i.test(he.whyStandard)&&e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:he.whyStandard}),he.sources&&he.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[i("candidates.source"),":"]}),he.sources.map((ge,Oe)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-white border border-amber-200 rounded text-amber-700 font-mono",children:ge},Oe))]}),he.confidence!=null&&he.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[i("candidates.confidence"),":"]}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round((he.confidence??0)*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round((he.confidence??0)*100),"%"]})]}),he.alternatives&&he.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[i("candidates.viewDetail"),":"]}),he.alternatives.map((ge,Oe)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-slate-100 border border-slate-200 rounded text-slate-600",children:ge},Oe))]})]})]}),b.quality&&b.quality.grade&&b.quality.grade!=="F"&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("candidates.qualityDimensions")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${b.quality.grade==="A"?"text-emerald-600":b.quality.grade==="B"?"text-blue-600":b.quality.grade==="C"?"text-amber-600":b.quality.grade==="D"?"text-orange-600":"text-slate-400"}`,children:b.quality.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-[10px]",children:[b.quality.completeness!=null&&b.quality.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:b.quality.completeness}),e.jsx("div",{className:"text-slate-400",children:i("candidates.qualityDimensions")})]}),b.quality.adaptation!=null&&b.quality.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:b.quality.adaptation}),e.jsx("div",{className:"text-slate-400",children:i("candidates.qualityDimensions")})]}),b.quality.documentation!=null&&b.quality.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:b.quality.documentation}),e.jsx("div",{className:"text-slate-400",children:i("candidates.qualityDimensions")})]})]})]})]}),(()=>{const ge=b.relations?Object.entries(b.relations).flatMap(([We,Ge])=>Array.isArray(Ge)?Ge.map(ut=>({...ut,type:We})):[]):[];return b.agentNotes||b.aiInsight||ge.length>0?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-emerald-400"})," ",i("candidates.refineEnhanced")]}),e.jsxs("div",{className:"bg-emerald-50/30 dark:bg-emerald-900/15 border border-emerald-100 dark:border-emerald-800/40 rounded-xl p-4 space-y-2.5 text-xs",children:[b.aiInsight&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[i("candidates.viewDetail"),":"]}),e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed mt-0.5",children:b.aiInsight})]}),b.agentNotes&&b.agentNotes.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:i("candidates.agentNotes")}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:b.agentNotes.map((We,Ge)=>e.jsxs("li",{className:"flex items-start gap-1.5 text-slate-600",children:[e.jsx("span",{className:"text-emerald-400 mt-0.5",children:"•"}),We]},Ge))})]}),ge.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[i("recipes.relations"),":"]}),e.jsx("div",{className:"mt-1 space-y-1",children:ge.map((We,Ge)=>e.jsxs("div",{className:"flex items-start gap-1.5 text-slate-600",children:[e.jsx("span",{className:"text-[9px] font-bold px-1 py-0.5 rounded bg-emerald-100 text-emerald-700 shrink-0 uppercase",children:We.type}),e.jsx("span",{className:"font-medium text-slate-700",children:Ue.get(We.target)||We.target}),We.description&&e.jsxs("span",{className:"text-slate-400",children:["— ",We.description]})]},Ge))})]})]})]}):null})(),ke.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[i("candidates.similarRecipe"),Ce&&e.jsx("span",{className:"text-[10px] text-slate-400 animate-pulse",children:i("common.loading")})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:ke.slice(0,5).map(ge=>e.jsxs("button",{onClick:()=>xe(b,ce,ge.recipeName,ke),className:"text-[10px] font-bold px-2 py-1 rounded-lg bg-amber-50 text-amber-700 border border-amber-200 hover:bg-amber-100 transition-colors flex items-center gap-1",title:i("candidates.similarWith",{name:ge.recipeName,score:(ge.similarity*100).toFixed(0)}),children:[e.jsx(ys,{size:10}),ge.recipeName.replace(/\.md$/i,"")," ",(ge.similarity*100).toFixed(0),"%"]},ge.recipeName))})]}),((Ye=b.content)==null?void 0:Ye.pattern)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ht,{size:11,className:"text-emerald-500"})," ",i("knowledge.codePattern")]}),e.jsx(ct,{code:b.content.pattern,language:b.language==="objc"?"objectivec":b.language,showLineNumbers:!0})]}),((J=b.content)==null?void 0:J.markdown)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",i("knowledge.markdownDoc")]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 dark:text-slate-300 leading-relaxed",children:e.jsx(gt,{content:b.content.markdown})})})]}),(b.doClause||b.whenClause||b.dontClause||b.topicHint||b.coreCode)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(lt,{size:11,className:"text-indigo-400"})," Cursor Delivery"]}),e.jsxs("div",{className:"bg-indigo-50/30 dark:bg-indigo-900/15 border border-indigo-100 dark:border-indigo-800/40 rounded-xl p-4 text-xs space-y-1.5",children:[b.topicHint&&e.jsxs("div",{children:[e.jsx("span",{className:"text-indigo-500 font-medium",children:"Topic:"}),e.jsx("span",{className:"text-slate-700",children:b.topicHint})]}),b.whenClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-500 font-medium",children:"When:"}),e.jsx("span",{className:"text-slate-700",children:b.whenClause})]}),b.doClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-emerald-500 font-medium",children:"Do:"}),e.jsx("span",{className:"text-slate-700",children:b.doClause})]}),b.dontClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-red-500 font-medium",children:"Don't:"}),e.jsx("span",{className:"text-slate-700",children:b.dontClause})]}),b.coreCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-purple-500 font-medium",children:"Core Code:"}),e.jsx("div",{className:"mt-1",children:e.jsx(ct,{code:b.coreCode,language:b.language==="objectivec"||b.language==="objc"?"objectivec":b.language||"text"})})]})]})]}),(b.scope||b.headers&&b.headers.length>0||((Pe=b.content)==null?void 0:Pe.steps)&&b.content.steps.length>0||((qe=b.content)==null?void 0:qe.rationale))&&e.jsxs(e.Fragment,{children:[((ze=b.content)==null?void 0:ze.rationale)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("candidates.rationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:b.content.rationale})})]}),b.headers&&b.headers.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("candidates.headers")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:b.headers.map((ge,Oe)=>e.jsx("code",{className:"px-2.5 py-1 bg-violet-50 text-violet-700 border border-violet-100 rounded-md text-[10px] font-mono font-medium",children:ge},Oe))})]}),((Ve=b.content)==null?void 0:Ve.steps)&&b.content.steps.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("recipes.steps")}),e.jsx("div",{className:"space-y-2",children:b.content.steps.map((ge,Oe)=>{if(typeof ge=="string")return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:Oe+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:ge})]},Oe);const We=typeof ge.title=="string"?ge.title:"",Ge=typeof ge.description=="string"?ge.description:"",ut=typeof ge.code=="string"?ge.code:"";return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:Oe+1}),We&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:We})]}),Ge&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:Ge}),ut&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:ut})]},Oe)})})]})]})]}),e.jsxs("div",{className:"shrink-0 border-t border-slate-200 dark:border-slate-700 px-5 py-3 bg-gradient-to-b from-slate-50/80 to-white dark:from-[#252526] dark:to-[#1e1e1e] flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>Se(b.id),disabled:A.has(b.id),title:i("candidates.enrichTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${A.has(b.id)?"text-slate-300 cursor-not-allowed":"text-amber-600 hover:bg-amber-50 border border-amber-200"}`,children:[A.has(b.id)?e.jsx(Me,{size:14,className:"animate-spin"}):e.jsx(fs,{size:14}),i("candidates.enrichShort")]}),e.jsxs("button",{onClick:()=>He(b.id),disabled:_.has(b.id),title:i("candidates.refineTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${_.has(b.id)?"text-slate-300 cursor-not-allowed":"text-emerald-600 hover:bg-emerald-50 border border-emerald-200"}`,children:[_.has(b.id)?e.jsx(Me,{size:14,className:"animate-spin"}):e.jsx(Qe,{size:14}),i("candidates.refineShort")]}),e.jsxs("button",{onClick:()=>{d(ce,b.id),k(null),be(null)},title:i("common.delete"),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-red-500 hover:bg-red-50 border border-red-200 transition-colors",children:[e.jsx(ot,{size:14})," ",i("common.delete")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[b.lifecycle==="pending"&&e.jsxs("button",{onClick:async()=>{try{await ae.promoteCandidateToRecipe(b.id),re(i("candidates.approveSuccess"),{title:i("candidates.approveSuccess")}),x==null||x()}catch(ge){re(ge.message,{title:i("common.operationFailed"),type:"error"})}},className:"flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold text-emerald-700 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200 transition-colors",children:[e.jsx(Xt,{size:14})," ",i("candidates.approve")]}),e.jsxs("button",{onClick:()=>{u(b,ce),k(null),be(null)},className:"flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold text-white bg-blue-600 hover:bg-blue-700 transition-colors shadow-sm",children:[e.jsx(Et,{size:14})," ",i("candidates.approveAndSave")]})]})]})]})]})})()]})},ln=({isOpen:t,onClose:s,currentFile:a,targetName:l,language:d="",onSelectRecipe:c})=>{var X,H,q,I;const{t:u}=_e(),[p,n]=o.useState(""),[g,f]=o.useState([]),[h,x]=o.useState(null),[i,y]=o.useState(!1),[k,w]=o.useState(null),[T,A]=o.useState(!1),[G,_]=o.useState(null),E=async()=>{if(p.trim()){y(!0);try{const L=await ae.search(p,{context:{language:d},limit:10});f((L.items||[]).map($=>{var m,N,j;return{name:($.title||$.name||"")+".md",content:((m=$.content)==null?void 0:m.pattern)||((N=$.content)==null?void 0:N.markdown)||((j=$.content)==null?void 0:j.code)||"",similarity:$.score||0,authority:$.authorityScore||0,matchType:$.matchType||"ranked",qualityScore:$.qualityScore||0,usageCount:$.usageCount||0}})),x(null)}catch(L){console.error("Context-aware search failed:",L),alert(u("search.searchFailed"))}finally{y(!1)}}},Z=L=>{L.key==="Enter"&&E()};return t?e.jsxs(Ze,{className:"z-30 flex",children:[e.jsx(Ze.Backdrop,{className:"bg-black/20"}),e.jsxs("div",{className:"relative w-full max-w-2xl ml-auto bg-white shadow-xl flex flex-col max-h-screen",children:[e.jsxs("div",{className:"border-b border-slate-200 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:u("search.title")}),e.jsx("button",{onClick:s,className:"p-1 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:z.lg,className:"text-slate-500"})})]}),h&&e.jsx("div",{className:"mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(et,{size:z.md,className:"text-blue-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[((X=h.targetInfo)==null?void 0:X.targetName)&&e.jsxs("div",{className:"text-blue-900 font-medium flex items-center gap-2 mb-1",children:[e.jsx(Xs,{size:z.sm}),"Target: ",h.targetInfo.targetName]}),((H=h.fileInfo)==null?void 0:H.imports)&&h.fileInfo.imports.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-2",children:[e.jsx("strong",{children:u("search.importedFrameworks")})," ",h.fileInfo.imports.slice(0,3).join(", "),h.fileInfo.imports.length>3&&` +${h.fileInfo.imports.length-3}`]}),((q=h.targetInfo)==null?void 0:q.suggestedApis)&&h.targetInfo.suggestedApis.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-1",children:[e.jsx("strong",{children:u("search.relatedApis")})," ",h.targetInfo.suggestedApis.slice(0,3).join(", ")]})]})]})}),e.jsxs("div",{className:"relative",children:[e.jsx(ft,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:z.md}),e.jsx("input",{type:"text",placeholder:u("search.searchPlaceholder"),value:p,onChange:L=>n(L.target.value),onKeyDown:Z,className:"w-full pl-10 pr-4 py-2 border border-slate-300 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-500/20 transition-all"})]}),e.jsxs("button",{onClick:E,disabled:!p.trim()||i,className:"mt-3 w-full py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:bg-blue-300 transition-colors flex items-center justify-center gap-2",children:[i&&e.jsx(Me,{size:z.sm,className:"animate-spin"}),u(i?"search.searching":"search.searchBtn")]})]}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[g.length===0&&!i&&e.jsx("div",{className:"flex items-center justify-center h-full text-slate-500",children:e.jsxs("div",{className:"text-center",children:[e.jsx($s,{size:z.xxl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:u("search.emptyHint")})]})}),g.map((L,$)=>e.jsxs("div",{className:"border-b border-slate-200 p-4 hover:bg-slate-50 transition-colors cursor-pointer",onClick:()=>{w(k===$?null:$),L.name&&(c==null||c(L.name))},children:[e.jsxs("div",{className:"flex items-start justify-between mb-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-slate-900 text-sm",children:L.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-slate-100 rounded text-xs text-slate-600",children:[e.jsx(et,{size:z.xs}),Math.round(L.similarity*100),"%"]}),L.isContextRelevant&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-green-100 rounded text-xs text-green-700",children:[e.jsx(Xs,{size:z.xs}),u("search.contextRelevant")]}),L.matchType&&e.jsx("span",{className:"text-xs text-slate-500",children:L.matchType==="semantic"?u("search.matchSemantic"):u("search.matchKeyword")})]})]}),e.jsx("button",{onClick:m=>{m.stopPropagation(),w(k===$?null:$)},className:"p-1 hover:bg-slate-200 rounded transition-colors",children:k===$?"▼":"▶"})]}),L.stats&&e.jsxs("div",{className:"text-xs text-slate-500 mb-2 flex gap-3",children:[L.stats.authorityScore!==void 0&&e.jsxs("span",{children:[u("search.authorityScore"),": ",L.stats.authorityScore]}),L.usageCount!==void 0&&e.jsxs("span",{children:[u("search.usage"),": ",u("search.usageCount",{count:L.usageCount})]})]}),k===$&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-slate-200",children:[L.recommendReason&&e.jsxs("div",{className:"text-xs text-slate-600 bg-blue-50 p-2 rounded mb-2 border border-blue-100",children:[e.jsx("p",{className:"font-medium text-blue-700 mb-0.5",children:u("search.recommendReason")}),e.jsx("p",{children:L.recommendReason})]}),e.jsxs("div",{className:"text-xs text-slate-600 max-h-[200px] overflow-auto bg-slate-50 p-3 rounded",children:[L.content.substring(0,500),"..."]}),e.jsx("button",{onClick:m=>{m.stopPropagation(),_(L),A(!0)},className:"mt-2 w-full py-1.5 bg-blue-50 text-blue-600 rounded text-xs font-medium hover:bg-blue-100 transition-colors",children:u("search.viewFullContent")})]})]},$)),i&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(Me,{size:z.lg,className:"animate-spin text-blue-600"})}),g.length===0&&p&&!i&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsxs("div",{className:"text-center text-slate-500",children:[e.jsx(Ot,{size:z.xl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:u("search.noResults")})]})})]})]}),T&&G&&e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-black/40"}),e.jsxs("div",{className:"relative bg-white rounded-lg shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"border-b border-slate-200 p-6 flex items-start justify-between shrink-0",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-slate-900",children:G.name}),e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsxs("span",{className:"text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded",children:[u("search.similarity"),": ",Math.round(G.similarity*100),"%"]}),G.isContextRelevant&&e.jsxs("span",{className:"text-xs bg-green-100 text-green-700 px-2 py-1 rounded",children:["✓ ",u("search.contextRelevant")]}),G.qualityScore!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 rounded text-xs text-blue-700 font-medium",children:["🤖 ",u("search.quality"),": ",(G.qualityScore*100).toFixed(0),"%"]}),((I=G.stats)==null?void 0:I.authorityScore)!==void 0&&e.jsxs("span",{className:"text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded",children:[u("search.authorityScore"),": ",Math.round(G.stats.authorityScore*100)/100]})]})]}),e.jsx("button",{onClick:()=>A(!1),className:"p-1 hover:bg-slate-100 rounded transition-colors shrink-0",children:e.jsx(Xe,{size:z.lg,className:"text-slate-500"})})]}),e.jsx("div",{className:"overflow-auto flex-1 p-6",children:e.jsx("div",{className:"prose prose-sm max-w-none",children:G.content?e.jsx(ct,{code:G.content,language:"markdown"}):e.jsx("p",{className:"text-slate-500 text-sm",children:u("search.noContent")})})}),e.jsxs("div",{className:"border-t border-slate-200 p-4 bg-slate-50 flex justify-end gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>A(!1),className:"px-4 py-2 text-slate-700 hover:bg-slate-200 rounded transition-colors text-sm font-medium",children:u("common.close")}),c&&e.jsxs("button",{onClick:()=>{c(G.name),A(!1)},className:"px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 rounded transition-colors text-sm font-medium flex items-center gap-2",children:[e.jsx(rt,{size:z.md}),u("search.useSnippet")]})]})]})]})]}):null},ha=t=>Os(t.language)||"text";function rn(t){const s=[],a=t.match(/#import\s+"([^"]+)"/);if(a){const u=a[1].replace(/\.h$/,"");s.push(u)}const l=t.match(/#import\s+<([^>]+)>/);if(l){const u=l[1].replace(/\.h$/,"").split("/");s.push(...u)}const d=t.match(/^import\s+(\w+)/);d&&s.push(d[1]);const c=t.match(/@import\s+(\w+)/);return c&&s.push(c[1]),[...new Set(s.filter(Boolean))]}function Vt(t,s){if(!s||!s.trim())return"unknown";const a=rn(t);return a.length===0?"unknown":a.some(l=>s.includes(l))?"used":"unused"}function nn(t){return t.startsWith("#import ")||t.startsWith("import ")||t.startsWith("@import ")?t.trim():t.startsWith("<")||t.startsWith('"')?`#import ${t.trim()}`:t.trim()}const on=[{value:"",label:"—"},{value:"networking",label:"Networking"},{value:"ui",label:"UI"},{value:"data",label:"Data"},{value:"architecture",label:"Architecture"},{value:"conventions",label:"Conventions"}],cn=t=>{var d;const s=(((d=t.content)==null?void 0:d.pattern)||"").trim();if(!s)return!1;const a=s.split(`
102
+ `).filter(c=>c.trim());return!(a.filter(c=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(c)).length>a.length*.3)},dn=({res:t,index:s,editingCodeIndex:a,setEditingCodeIndex:l,expandedEditIndex:d,setExpandedEditIndex:c,similarityMap:u,handleUpdateScanResult:p,handleSaveExtracted:n,handlePromoteToCandidate:g,openCompare:f,isSavingRecipe:h=!1})=>{var X,H,q;const{t:x}=_e(),[i,y]=o.useState(!1),k=d===s,w=t.headers||[],T=((X=t.content)==null?void 0:X.pattern)||"",A=((H=t.content)==null?void 0:H.markdown)||"",G=t.description||"",_=t.tags||[],E=cn(t),Z=(I,L)=>{p(s,{content:{...t.content||{},[I]:L}})};return e.jsxs("div",{className:"bg-slate-50 dark:bg-[#1a1d24] rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden shadow-sm",children:[e.jsxs("div",{className:"px-5 pt-4 pb-3 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] border-b border-slate-100 dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5",children:x("scanResult.knowledgeEntryTitle")}),t.scanMode==="project"?e.jsxs("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded bg-indigo-100 text-indigo-700 border border-indigo-200 flex items-center gap-1",children:[e.jsx(lt,{size:10})," PROJECT"]}):t.scanMode==="target"?e.jsxs("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 flex items-center gap-1",children:[e.jsx(et,{size:10})," ",t.candidateTargetName||"TARGET"]}):t.lifecycle?e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded flex items-center gap-1 ${t.lifecycle==="pending"?"bg-amber-100 text-amber-700 border border-amber-200":t.lifecycle==="active"?"bg-green-100 text-green-700 border border-green-200":"bg-slate-100 text-slate-600 border border-slate-200"}`,children:t.lifecycle==="pending"?x("scanResult.lifecyclePending"):t.lifecycle==="active"?x("scanResult.lifecycleActive"):t.lifecycle==="deprecated"?x("scanResult.lifecycleDeprecated"):t.lifecycle}):null,t.source&&t.source!=="unknown"&&e.jsx("span",{className:"text-[9px] font-medium px-1.5 py-0.5 rounded bg-violet-50 text-violet-600 border border-violet-100",children:t.source==="agent"?"AI Agent":t.source==="bootstrap-scan"?x("scanResult.aiScan"):t.source})]}),e.jsx("input",{className:"font-semibold bg-transparent border-b-2 border-transparent hover:border-slate-200 focus:border-blue-500 outline-none px-0.5 text-lg w-full text-slate-800 placeholder:text-slate-300",value:t.title||"",onChange:I=>p(s,{title:I.target.value})})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 pt-3",children:[g&&e.jsxs("button",{onClick:()=>g(t,s),className:"text-xs px-4 py-2 rounded-lg font-bold transition-all shadow-sm flex items-center gap-1.5 active:scale-95 bg-white dark:bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-700/40 hover:bg-emerald-50 dark:hover:bg-emerald-500/20 whitespace-nowrap",children:[e.jsx(Rl,{size:z.md}),"Candidate"]}),e.jsxs("button",{onClick:()=>n(t),disabled:h,className:`text-xs px-4 py-2 rounded-lg font-bold transition-all shadow-sm flex items-center gap-1.5 active:scale-95 disabled:opacity-60 disabled:cursor-not-allowed whitespace-nowrap ${E&&t.mode==="full"?"bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-500/20 dark:text-blue-300 dark:hover:bg-blue-500/30 dark:border dark:border-blue-500/30":"bg-amber-600 text-white hover:bg-amber-700 dark:bg-amber-500/20 dark:text-amber-300 dark:hover:bg-amber-500/30 dark:border dark:border-amber-500/30"}`,children:[h?e.jsx(Me,{size:z.md,className:"animate-spin"}):e.jsx(Fa,{size:z.md}),x(h?"scanResult.saving":E?"scanResult.saveAsRecipe":"scanResult.saveAsKnowledge")]})]})]}),e.jsxs("div",{className:"flex items-end gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.trigger")}),e.jsx("input",{className:"font-mono font-bold text-blue-600 bg-blue-50/80 border border-blue-100 px-2.5 py-1 rounded-md outline-none text-xs focus:ring-2 focus:ring-blue-500/20 w-44",value:t.trigger||"",placeholder:x("scanResult.triggerPlaceholder"),onChange:I=>p(s,{trigger:I.target.value})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:"Kind"}),e.jsxs("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:t.kind||"pattern",onChange:I=>p(s,{kind:I.target.value}),children:[e.jsx("option",{value:"rule",children:"Rule"}),e.jsx("option",{value:"pattern",children:"Pattern"}),e.jsx("option",{value:"fact",children:"Fact"})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:"Topic"}),e.jsx("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:t.topicHint||"",onChange:I=>p(s,{topicHint:I.target.value}),children:on.map(I=>e.jsx("option",{value:I.value,children:I.label},I.value))})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.category")}),e.jsx("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:t.category||"",onChange:I=>p(s,{category:I.target.value}),children:tr.filter(I=>I!=="All").map(I=>e.jsx("option",{value:I,children:I},I))})]}),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.language")}),e.jsx("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:Os(t.language),onChange:I=>p(s,{language:I.target.value}),children:Bt.map(I=>e.jsx("option",{value:I.id,children:I.label},I.id))})]})]}),t.moduleName&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.module")}),e.jsx("span",{className:"text-[11px] bg-purple-50 text-purple-700 border border-purple-100 px-2 py-1 rounded-md font-mono font-bold",children:t.moduleName})]})]}),e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),E&&e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.mode")}),e.jsxs("div",{className:"flex bg-white dark:bg-[#252a36] p-0.5 rounded-md border border-slate-200 dark:border-slate-600",children:[e.jsx("button",{onClick:()=>p(s,{mode:"full"}),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${t.mode==="full"?"bg-blue-100 shadow-sm text-blue-600":"text-slate-400 hover:text-slate-500"}`,children:"Snippet+Recipe"}),e.jsx("button",{onClick:()=>p(s,{mode:"preview"}),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${t.mode==="preview"?"bg-amber-100 shadow-sm text-amber-600":"text-slate-400 hover:text-slate-500"}`,children:"Recipe Only"})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.difficulty")}),e.jsxs("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-purple-500/20",value:t.difficulty||"intermediate",onChange:I=>p(s,{difficulty:I.target.value,complexity:I.target.value}),children:[e.jsx("option",{value:"beginner",children:x("scanResult.difficultyBeginner")}),e.jsx("option",{value:"intermediate",children:x("scanResult.difficultyIntermediate")}),e.jsx("option",{value:"advanced",children:x("scanResult.difficultyAdvanced")})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.authorityScore")}),e.jsxs("select",{className:"font-bold text-amber-600 bg-amber-50/60 border border-amber-100 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-amber-500/20",value:t.authority??((q=t.stats)==null?void 0:q.authority)??3,onChange:I=>p(s,{authority:parseInt(I.target.value)}),children:[e.jsx("option",{value:"1",children:"⭐ 1"}),e.jsx("option",{value:"2",children:"⭐⭐ 2"}),e.jsx("option",{value:"3",children:"⭐⭐⭐ 3"}),e.jsx("option",{value:"4",children:"⭐⭐⭐⭐ 4"}),e.jsx("option",{value:"5",children:"⭐⭐⭐⭐⭐ 5"})]})]})]}),e.jsx("div",{className:"mt-2.5",children:e.jsxs("div",{className:"flex flex-wrap gap-1 items-center bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-md px-1.5 py-0.5 min-h-[28px] focus-within:ring-2 focus-within:ring-blue-500/20",children:[_.map((I,L)=>e.jsxs("span",{className:"flex items-center gap-0.5 text-[10px] font-bold bg-blue-50 text-blue-700 border border-blue-200 px-1.5 py-0 rounded",children:[I,e.jsx("button",{onClick:()=>{const $=[..._];$.splice(L,1),p(s,{tags:$})},className:"text-blue-400 hover:text-red-500 transition-colors leading-none text-[10px]",title:"{t('scanResult.removeTag')}",children:"×"})]},L)),e.jsx("input",{className:"flex-1 min-w-[80px] text-[11px] text-slate-600 outline-none bg-transparent py-0.5",placeholder:_.length===0?x("scanResult.tagsPlaceholder"):"",onKeyDown:I=>{const L=I.currentTarget,$=L.value.trim();if((I.key==="Enter"||I.key===","||I.key===",")&&$){I.preventDefault();const m=$.replace(/[,,]/g,"").trim();m&&!_.includes(m)&&p(s,{tags:[..._,m]}),L.value=""}else if(I.key==="Backspace"&&!L.value&&_.length>0){const m=[..._];m.pop(),p(s,{tags:m})}},onBlur:I=>{const L=I.currentTarget.value.trim().replace(/[,,]/g,"").trim();L&&!_.includes(L)&&p(s,{tags:[..._,L]}),I.currentTarget.value=""}})]})}),E&&w.length>0&&e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:x("scanResult.headers")}),e.jsxs("button",{onClick:()=>c(d===s?null:s),className:`text-[10px] font-bold px-2 py-0.5 rounded-md transition-colors border ${k?"text-blue-700 bg-blue-100 border-blue-300":"text-blue-600 bg-blue-50 border-blue-100 hover:bg-blue-100"}`,children:[x(k?"scanResult.collapseHeaders":"scanResult.editHeaders")," (",w.length,")"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[9px] text-slate-400",children:"Snippet:"}),e.jsx("button",{onClick:()=>p(s,{includeHeaders:t.includeHeaders===!1}),className:`w-7 h-4 rounded-full relative transition-colors ${t.includeHeaders!==!1?"bg-blue-600":"bg-slate-300"}`,title:t.includeHeaders!==!1?x("scanResultCard.includeMarkOn"):x("scanResultCard.includeMarkOff"),children:e.jsx("div",{className:`absolute top-0.5 w-2.5 h-2.5 bg-white rounded-full transition-all ${t.includeHeaders!==!1?"right-0.5":"left-0.5"}`})}),e.jsx("span",{className:"text-[9px] font-bold text-slate-600",children:t.includeHeaders!==!1?"ON":"OFF"})]}),(()=>{const I=w.filter($=>Vt($,T)==="used").length,L=w.filter($=>Vt($,T)==="unused").length;return e.jsxs("span",{className:"text-[9px] text-slate-400",children:[I>0&&e.jsxs("span",{className:"text-green-600 font-bold",children:[I," ",x("scanResult.referenced")]}),I>0&&L>0&&" · ",L>0&&e.jsxs("span",{className:"text-amber-600 font-bold",children:[L," ",x("scanResult.unreferenced")]})]})})()]}),k&&e.jsxs("div",{className:"space-y-2 bg-slate-50/80 dark:bg-[#1e2028] rounded-lg p-3 border border-slate-200 dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[e.jsx("button",{onClick:()=>{const I=w.map(L=>nn(L));p(s,{headers:I})},className:"text-[9px] px-2 py-0.5 bg-slate-200 text-slate-600 rounded hover:bg-slate-300 font-bold",title:x("scanResultCard.formatHeaders"),children:x("scanResult.formatHeaders")}),w.some(I=>Vt(I,T)==="unused")&&e.jsx("button",{onClick:()=>{const I=w.filter(L=>Vt(L,T)!=="unused");p(s,{headers:I})},className:"text-[9px] px-2 py-0.5 bg-amber-100 text-amber-700 rounded hover:bg-amber-200 font-bold",title:x("scanResultCard.cleanUnused"),children:x("scanResult.cleanUnused")}),e.jsx("button",{onClick:()=>{const I=[...w,sa(t.language)];p(s,{headers:I})},className:"text-[9px] px-2 py-0.5 bg-green-500 text-white rounded hover:bg-green-600 font-bold",children:x("scanResult.addHeader")})]}),e.jsx("div",{className:"space-y-1",children:w.map((I,L)=>{const $=Vt(I,T);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${$==="used"?"bg-green-500":$==="unused"?"bg-amber-400":"bg-slate-300"}`,title:x($==="used"?"scanResult.usedInCode":$==="unused"?"scanResult.unusedInCode":"scanResult.unknown")}),e.jsx("input",{className:`flex-1 text-xs font-mono bg-white dark:bg-[#252a36] border rounded px-2 py-1 outline-none focus:border-blue-400 ${$==="unused"?"border-amber-300 text-amber-700 dark:border-amber-700 dark:text-amber-400":"border-slate-200 dark:border-slate-600"}`,value:I,onChange:m=>{const N=[...w];N[L]=m.target.value,p(s,{headers:N})},placeholder:sa(t.language)}),$==="unused"&&e.jsx("span",{className:"text-[8px] text-amber-500 font-bold shrink-0",children:x("scanResult.unreferenced")}),e.jsx("button",{onClick:()=>{const m=w.filter((N,j)=>j!==L);p(s,{headers:m})},className:"px-2 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-[9px] font-bold shrink-0",children:x("scanResult.deleteHeader")})]},L)})})]})]})]}),e.jsxs("div",{className:"px-6 pb-6 pt-4 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-cyan-200 dark:border-cyan-800/40 bg-gradient-to-br from-cyan-50/60 to-blue-50/40 dark:from-cyan-900/15 dark:to-blue-900/10 p-4 space-y-3",children:[e.jsxs("div",{className:"text-[10px] font-bold text-cyan-700 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(et,{size:12}),x("scanResult.cursorDelivery")]}),e.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-2 items-start",children:[e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase pt-1.5 select-none",children:"Do"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.doClause||"",onChange:I=>p(s,{doClause:I.target.value}),placeholder:"English imperative ≤60 tokens, e.g. Use dispatch_once for thread-safe singleton"}),e.jsx("span",{className:"text-[10px] font-bold text-red-500 uppercase pt-1.5 select-none",children:"Don't"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.dontClause||"",onChange:I=>p(s,{dontClause:I.target.value}),placeholder:"English constraint (omit 'Don't' prefix), e.g. use @synchronized for singleton"}),e.jsx("span",{className:"text-[10px] font-bold text-amber-600 uppercase pt-1.5 select-none",children:"When"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.whenClause||"",onChange:I=>p(s,{whenClause:I.target.value}),placeholder:"When implementing singleton pattern or global shared instance"})]})]}),t.reasoning&&(t.reasoning.confidence!=null||t.reasoning.whyStandard&&!/^Submitted via /i.test(t.reasoning.whyStandard))&&e.jsxs("div",{className:"rounded-xl border border-indigo-100 dark:border-indigo-800/40 bg-indigo-50/40 dark:bg-indigo-900/15 p-3 text-xs space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-indigo-600 font-bold text-[10px]",children:[x("scanResult.aiReasoning"),t.reasoning.confidence!=null&&e.jsx("span",{className:`ml-auto font-mono text-[10px] ${t.reasoning.confidence>=.7?"text-emerald-600":t.reasoning.confidence>=.4?"text-amber-600":"text-red-600"}`,children:x("scanResult.confidenceLabel",{value:Math.round(t.reasoning.confidence*100)})})]}),t.reasoning.whyStandard&&!/^Submitted via /i.test(t.reasoning.whyStandard)&&e.jsx("p",{className:"text-slate-600",children:t.reasoning.whyStandard}),t.reasoning.sources&&t.reasoning.sources.length>0&&e.jsxs("p",{className:"text-slate-400",children:[x("scanResult.sourceLabel")," ",t.reasoning.sources.join(", ")]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-bold text-slate-400 uppercase mb-1",children:x("scanResult.description")}),e.jsx("textarea",{rows:1,className:"w-full text-sm text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 outline-none resize-none leading-relaxed focus:ring-2 focus:ring-blue-500/10",value:G,onChange:I=>p(s,{description:I.target.value,summary:I.target.value}),placeholder:x("scanResult.descPlaceholder")})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:x("scanResult.markdown")}),e.jsx("button",{type:"button",onClick:()=>y(!i),className:`flex items-center gap-1 text-[10px] font-bold px-2 py-1 rounded transition-colors ${i?"text-blue-600 hover:text-blue-700 bg-blue-50":"text-slate-500 hover:text-slate-700 hover:bg-slate-100"}`,children:i?e.jsxs(e.Fragment,{children:[e.jsx(kt,{size:z.xs})," ",x("scanResult.done")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ms,{size:z.xs})," ",x("common.edit")]})})]}),i?e.jsx("textarea",{rows:Math.max(6,(A||"").split(`
103
+ `).length),className:"w-full text-sm text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 outline-none resize-y leading-relaxed focus:ring-2 focus:ring-blue-500/10 font-mono",value:A,onChange:I=>Z("markdown",I.target.value)}):A?e.jsx("div",{className:"text-sm text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-xl px-4 py-3 leading-relaxed whitespace-pre-wrap max-h-64 overflow-y-auto",children:A}):e.jsx("p",{className:"text-xs text-slate-400 italic py-2",children:x("scanResult.noArticle")})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:x("scanResult.code")}),a===s?e.jsxs("button",{type:"button",onClick:()=>l(null),className:"flex items-center gap-1 text-[10px] font-bold text-blue-600 hover:text-blue-700 px-2 py-1 rounded bg-blue-50",children:[e.jsx(kt,{size:z.xs})," ",x("scanResult.done")]}):e.jsxs("button",{type:"button",onClick:()=>l(s),className:"flex items-center gap-1 text-[10px] font-bold text-slate-500 hover:text-slate-700 px-2 py-1 rounded hover:bg-slate-100",title:x("common.edit"),children:[e.jsx(Ms,{size:z.xs})," ",x("common.edit")]})]}),a===s?e.jsx("div",{className:"rounded-xl overflow-hidden",children:e.jsx(ks,{value:T,onChange:I=>Z("pattern",I),language:ha(t),height:`${Math.min(12,T.split(`
104
+ `).length)*20+16}px`})}):T?e.jsx(ct,{code:T,language:ha(t),showLineNumbers:!0}):e.jsx("p",{className:"text-xs text-slate-400 italic py-4",children:x("scanResult.noCode")})]}),(()=>{const I=t.candidateId??t.id??`scan-${s}`,L=u[I],$=(L||[]).filter(j=>j.similarity>=.6);if($.length===0)return null;const m=$.filter(j=>j.similarity>=.85),N=m.length>0;return e.jsxs("div",{className:"space-y-1.5",children:[N&&e.jsxs("div",{className:"flex items-center gap-2 bg-red-50 border border-red-200 rounded-lg px-3 py-2",children:[e.jsx("span",{className:"text-red-500 text-sm",children:"⚠️"}),e.jsx("span",{className:"text-[11px] font-bold text-red-700",children:x("scanResult.highDuplicateRisk")}),m.map(j=>e.jsxs("button",{onClick:()=>f(t,j.recipeName,L||[]),className:"text-[11px] font-bold px-2 py-0.5 rounded bg-red-100 text-red-800 border border-red-300 hover:bg-red-200 transition-colors",children:[j.recipeName.replace(/\.md$/i,"")," ",(j.similarity*100).toFixed(0),"%"]},j.recipeName)),e.jsx("span",{className:"text-[10px] text-red-500",children:x("scanResult.compareBeforeSave")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:x("scanResult.similarRecipes")}),$.slice(0,5).map(j=>e.jsxs("button",{onClick:()=>f(t,j.recipeName,L||[]),className:`text-[10px] font-bold px-2 py-1 rounded border transition-colors flex items-center gap-1 ${j.similarity>=.85?"bg-red-50 text-red-700 border-red-200 hover:bg-red-100":"bg-amber-50 text-amber-700 border-amber-200 hover:bg-amber-100"}`,title:x("scanResultCard.similarWithClick",{name:j.recipeName,score:(j.similarity*100).toFixed(0)}),children:[e.jsx(ys,{size:z.xs}),j.recipeName.replace(/\.md$/i,"")," ",(j.similarity*100).toFixed(0),"%"]},j.recipeName))]})]})})()]})]})},un=t=>{const s=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(s)?"objectivec":t.language||"text"},pn=({data:t,onClose:s,onDataChange:a,recipes:l,handleSaveExtracted:d,handleDeleteCandidate:c,onEditRecipe:u,isSavingRecipe:p=!1})=>{var T,A,G,_;const{t:n}=_e(),g=t.candidate,f=un(g),h=()=>{var H,q;const E=[],Z=((H=g.content)==null?void 0:H.pattern)||"",X=((q=g.content)==null?void 0:q.markdown)||g.doClause||"";Z&&E.push("## Snippet / Code Reference\n\n```"+f+`
105
+ `+Z+"\n```"),X&&E.push(`
107
106
  ## AI Context / Usage Guide
108
107
 
109
- `+X),navigator.clipboard.writeText(P.join(`
110
- `)||"").then(()=>re(n("spmCompare.candidateCopied"),{title:n("spmCompare.copied")}))},x=()=>{const P=Ws(t.recipeContent);navigator.clipboard.writeText(P).then(()=>re(n("spmCompare.recipeCopied"),{title:n("spmCompare.copied")}))},c=async P=>{if(P===t.recipeName)return;const Z=t.recipeContents[P];if(Z)a({...t,recipeName:P,recipeContent:Z});else{let X="";const H=l==null?void 0:l.find(q=>q.name===P||q.name.endsWith("/"+P));if(H!=null&&H.content)X=[H.content.pattern,H.content.markdown].filter(Boolean).join(`
108
+ `+X),navigator.clipboard.writeText(E.join(`
109
+ `)||"").then(()=>re(n("spmCompare.candidateCopied"),{title:n("spmCompare.copied")}))},x=()=>{const E=Ws(t.recipeContent);navigator.clipboard.writeText(E).then(()=>re(n("spmCompare.recipeCopied"),{title:n("spmCompare.copied")}))},i=async E=>{if(E===t.recipeName)return;const Z=t.recipeContents[E];if(Z)a({...t,recipeName:E,recipeContent:Z});else{let X="";const H=l==null?void 0:l.find(q=>q.name===E||q.name.endsWith("/"+E));if(H!=null&&H.content)X=[H.content.pattern,H.content.markdown].filter(Boolean).join(`
111
110
 
112
- `)||"";else try{X=(await se.getRecipeContentByName(P)).content}catch{return}a({...t,recipeName:P,recipeContent:X,recipeContents:{...t.recipeContents,[P]:X}})}},j=async()=>{if(!(!g.candidateId||!t.targetName||!i)&&window.confirm(n("spmCompare.deleteConfirm")))try{await i(t.targetName,g.candidateId),s()}catch(P){re((P==null?void 0:P.message)||n("spmCompare.deleteFailed"),{title:n("spmCompare.deleteFailed"),type:"error"})}},w=()=>{d(g),s()},C=()=>{const P=l==null?void 0:l.find(Z=>Z.name===t.recipeName||Z.name.endsWith("/"+t.recipeName));P?u==null||u(P):u==null||u({name:t.recipeName,content:{markdown:t.recipeContent}}),s()};return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:s,children:[e.jsx(Ze.Backdrop,{className:"bg-black/30 backdrop-blur-[1px]"}),e.jsxs("div",{className:"relative w-[min(96vw,1280px)] h-full bg-white shadow-2xl flex flex-col",style:{animation:"slideInRight 0.25s ease-out"},onClick:P=>P.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("h3",{className:"font-bold text-slate-800",children:n("spmCompare.compareTitle")}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[g.candidateId&&t.targetName&&e.jsx("button",{onClick:j,className:"text-xs text-red-600 hover:bg-red-50 px-2 py-1 rounded transition-colors",children:n("spmCompare.deleteCandidate")}),e.jsxs("button",{onClick:w,disabled:p,className:"text-xs text-blue-600 hover:bg-blue-50 px-2 py-1 rounded disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1 transition-colors",children:[p?e.jsx(Fe,{size:F.xs,className:"animate-spin"}):null,n("spmCompare.auditCandidate")]}),e.jsx("button",{onClick:C,className:"text-xs text-emerald-600 hover:bg-emerald-50 px-2 py-1 rounded transition-colors",children:n("spmCompare.editRecipe")})]})]}),e.jsx("button",{onClick:s,className:"p-2 hover:bg-slate-100 rounded-lg transition-colors shrink-0 ml-2",children:e.jsx(Xe,{size:F.md})})]}),t.similarList.length>1&&e.jsxs("div",{className:"flex flex-wrap gap-1.5 px-5 py-2 border-b border-slate-100 bg-slate-50/50 shrink-0",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold self-center",children:n("spmCompare.switchRecipe")}),t.similarList.map(P=>e.jsxs("button",{onClick:()=>c(P.recipeName),className:`text-[10px] font-bold px-2 py-1 rounded transition-colors ${t.recipeName===P.recipeName?"bg-emerald-200 text-emerald-800":"bg-white text-emerald-600 hover:bg-emerald-100 border border-emerald-200"}`,children:[P.recipeName.replace(/\.md$/i,"")," ",(P.similarity*100).toFixed(0),"%"]},P.recipeName))]}),e.jsxs("div",{className:"flex-1 flex min-h-0",children:[e.jsxs("div",{className:"flex-1 flex flex-col min-w-0 border-r border-slate-200",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-slate-100 bg-blue-50/40 shrink-0",children:[e.jsx("span",{className:"text-xs font-bold text-blue-700 truncate",children:n("spmCompare.candidateTitle",{title:g.title||""})}),e.jsx("button",{onClick:h,className:"p-1 hover:bg-blue-100 rounded text-blue-500 shrink-0",title:n("spmCompare.copyCandidate"),children:e.jsx(qt,{size:F.xs})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsxs("div",{className:"markdown-body text-slate-700 space-y-4",children:[e.jsx("h3",{className:"text-sm font-bold",children:"Snippet / Code Reference"}),(E=g.content)!=null&&E.pattern?e.jsx(dt,{code:((S=g.content)==null?void 0:S.pattern)||"",language:f,className:"!overflow-visible"}):e.jsx("p",{className:"text-slate-400 italic text-xs",children:n("spmCompare.noCode")}),e.jsx("h3",{className:"text-sm font-bold mt-4",children:n("spmCompare.aiContextProfile")}),(G=g.content)!=null&&G.markdown||g.doClause?e.jsx(gt,{content:((z=g.content)==null?void 0:z.markdown)||g.doClause||""}):e.jsx("p",{className:"text-slate-400 italic text-xs",children:n("spmCompare.noGuide")})]})})]}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-slate-100 bg-emerald-50/40 shrink-0",children:[e.jsxs("span",{className:"text-xs font-bold text-emerald-700 truncate",children:["Recipe:",t.recipeName.replace(/\.md$/i,"")]}),e.jsx("button",{onClick:x,className:"p-1 hover:bg-emerald-100 rounded text-emerald-500 shrink-0",title:n("spmCompare.copyRecipe"),children:e.jsx(qt,{size:F.xs})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx(gt,{content:t.recipeContent,stripFrontmatter:!0})})]})]})]})]})},ga={swift:"bg-orange-100 text-orange-700 border-orange-200",objectivec:"bg-blue-100 text-blue-700 border-blue-200",go:"bg-cyan-100 text-cyan-700 border-cyan-200",python:"bg-yellow-100 text-yellow-700 border-yellow-200",java:"bg-red-100 text-red-700 border-red-200",kotlin:"bg-purple-100 text-purple-700 border-purple-200",javascript:"bg-amber-100 text-amber-700 border-amber-200",typescript:"bg-blue-100 text-blue-700 border-blue-200",rust:"bg-orange-100 text-orange-800 border-orange-300",ruby:"bg-rose-100 text-rose-700 border-rose-200",c:"bg-gray-100 text-gray-700 border-gray-200",cpp:"bg-gray-100 text-gray-700 border-gray-200"},ba={swift:"Swift",objectivec:"ObjC",go:"Go",python:"Py",java:"Java",kotlin:"KT",javascript:"JS",typescript:"TS",rust:"RS",ruby:"RB",c:"C",cpp:"C++"},mn=({targets:t,filteredTargets:s,selectedTargetName:a,isScanning:l,scanProgress:d,scanFileList:i,scanResults:u,guardAudit:p,handleScanTarget:n,handleScanProject:g,handleUpdateScanResult:f,handleSaveExtracted:h,handlePromoteToCandidate:x,handleDeleteCandidate:c,onEditRecipe:j,isShellTarget:w,recipes:C=[],isSavingRecipe:E=!1,handleRefreshProject:S,onAddCustomFolder:G,onRemoveCustomFolder:z})=>{var Ue,Ie;const{t:P}=_e(),[Z,X]=o.useState(null),[H,q]=o.useState(null),[R,M]=o.useState({}),[_,m]=o.useState(null),[N,y]=o.useState(null),[W,O]=o.useState(!1),[be,we]=o.useState(),[ye,v]=o.useState(),ee=o.useRef(new Set),ae=o.useRef([]),[ue,fe]=o.useState([]),[he,ce]=o.useState(!1),je=o.useRef(!1),$=3,[K,xe]=o.useState("modules"),L=o.useRef(!1),T=o.useMemo(()=>s.filter(ne=>!w(ne.name)).length,[s,w]);o.useEffect(()=>{L.current||t.length!==0&&(L.current=!0,T<$?xe("folders"):xe("modules"))},[t.length,T]),o.useEffect(()=>{K!=="folders"||je.current||(je.current=!0,ce(!0),se.browseDirectories("",3).then(ne=>{fe(ne)}).catch(()=>{fe([])}).finally(()=>{ce(!1)}))},[K]);const Q=o.useCallback(ne=>{const ve={name:ne.name,packageName:ne.name,packagePath:ne.path,targetDir:ne.path,path:ne.path,type:"directory",language:ne.language||"unknown",discovererId:"folder-scan",discovererName:P("moduleExplorer.discovererFolderScan"),info:{source:"manual-folder-scan",originalPath:ne.path},isVirtual:!0};G==null||G(ve),n(ve),xe("modules")},[n,G,P]),ie=o.useCallback(async(ne,ve)=>{if(!ee.current.has(ne)){ee.current.add(ne),m(ne);try{const He=ve.candidateId&&ve.targetName?{targetName:ve.targetName,candidateId:ve.candidateId}:{candidate:ve.candidate||{}},Pe=await se.getCandidateSimilarityEx(He);M(Ne=>({...Ne,[ne]:Pe.similar||[]}))}catch{M(Pe=>({...Pe,[ne]:[]}))}finally{m(null)}}},[]),ke=o.useCallback(async(ne,ve,He=[])=>{var B,D,U;const Pe=ne.candidateTargetName||"",Ne=ve.replace(/\.md$/i,"");let r="";const k=C==null?void 0:C.find(te=>te.name===Ne||te.name.endsWith("/"+Ne));if(k!=null&&k.content)r=[k.content.pattern,k.content.markdown].filter(Boolean).join(`
111
+ `)||"";else try{X=(await ae.getRecipeContentByName(E)).content}catch{return}a({...t,recipeName:E,recipeContent:X,recipeContents:{...t.recipeContents,[E]:X}})}},y=async()=>{if(!(!g.candidateId||!t.targetName||!c)&&window.confirm(n("spmCompare.deleteConfirm")))try{await c(t.targetName,g.candidateId),s()}catch(E){re((E==null?void 0:E.message)||n("spmCompare.deleteFailed"),{title:n("spmCompare.deleteFailed"),type:"error"})}},k=()=>{d(g),s()},w=()=>{const E=l==null?void 0:l.find(Z=>Z.name===t.recipeName||Z.name.endsWith("/"+t.recipeName));E?u==null||u(E):u==null||u({name:t.recipeName,content:{markdown:t.recipeContent}}),s()};return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:s,children:[e.jsx(Ze.Backdrop,{className:"bg-black/30 backdrop-blur-[1px]"}),e.jsxs("div",{className:"relative w-[min(96vw,1280px)] h-full bg-white shadow-2xl flex flex-col",style:{animation:"slideInRight 0.25s ease-out"},onClick:E=>E.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("h3",{className:"font-bold text-slate-800",children:n("spmCompare.compareTitle")}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[g.candidateId&&t.targetName&&e.jsx("button",{onClick:y,className:"text-xs text-red-600 hover:bg-red-50 px-2 py-1 rounded transition-colors",children:n("spmCompare.deleteCandidate")}),e.jsxs("button",{onClick:k,disabled:p,className:"text-xs text-blue-600 hover:bg-blue-50 px-2 py-1 rounded disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1 transition-colors",children:[p?e.jsx(Me,{size:z.xs,className:"animate-spin"}):null,n("spmCompare.auditCandidate")]}),e.jsx("button",{onClick:w,className:"text-xs text-emerald-600 hover:bg-emerald-50 px-2 py-1 rounded transition-colors",children:n("spmCompare.editRecipe")})]})]}),e.jsx("button",{onClick:s,className:"p-2 hover:bg-slate-100 rounded-lg transition-colors shrink-0 ml-2",children:e.jsx(Xe,{size:z.md})})]}),t.similarList.length>1&&e.jsxs("div",{className:"flex flex-wrap gap-1.5 px-5 py-2 border-b border-slate-100 bg-slate-50/50 shrink-0",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold self-center",children:n("spmCompare.switchRecipe")}),t.similarList.map(E=>e.jsxs("button",{onClick:()=>i(E.recipeName),className:`text-[10px] font-bold px-2 py-1 rounded transition-colors ${t.recipeName===E.recipeName?"bg-emerald-200 text-emerald-800":"bg-white text-emerald-600 hover:bg-emerald-100 border border-emerald-200"}`,children:[E.recipeName.replace(/\.md$/i,"")," ",(E.similarity*100).toFixed(0),"%"]},E.recipeName))]}),e.jsxs("div",{className:"flex-1 flex min-h-0",children:[e.jsxs("div",{className:"flex-1 flex flex-col min-w-0 border-r border-slate-200",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-slate-100 bg-blue-50/40 shrink-0",children:[e.jsx("span",{className:"text-xs font-bold text-blue-700 truncate",children:n("spmCompare.candidateTitle",{title:g.title||""})}),e.jsx("button",{onClick:h,className:"p-1 hover:bg-blue-100 rounded text-blue-500 shrink-0",title:n("spmCompare.copyCandidate"),children:e.jsx(qt,{size:z.xs})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsxs("div",{className:"markdown-body text-slate-700 space-y-4",children:[e.jsx("h3",{className:"text-sm font-bold",children:"Snippet / Code Reference"}),(T=g.content)!=null&&T.pattern?e.jsx(ct,{code:((A=g.content)==null?void 0:A.pattern)||"",language:f,className:"!overflow-visible"}):e.jsx("p",{className:"text-slate-400 italic text-xs",children:n("spmCompare.noCode")}),e.jsx("h3",{className:"text-sm font-bold mt-4",children:n("spmCompare.aiContextProfile")}),(G=g.content)!=null&&G.markdown||g.doClause?e.jsx(gt,{content:((_=g.content)==null?void 0:_.markdown)||g.doClause||""}):e.jsx("p",{className:"text-slate-400 italic text-xs",children:n("spmCompare.noGuide")})]})})]}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-slate-100 bg-emerald-50/40 shrink-0",children:[e.jsxs("span",{className:"text-xs font-bold text-emerald-700 truncate",children:["Recipe:",t.recipeName.replace(/\.md$/i,"")]}),e.jsx("button",{onClick:x,className:"p-1 hover:bg-emerald-100 rounded text-emerald-500 shrink-0",title:n("spmCompare.copyRecipe"),children:e.jsx(qt,{size:z.xs})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx(gt,{content:t.recipeContent,stripFrontmatter:!0})})]})]})]})]})},ga={swift:"bg-orange-100 text-orange-700 border-orange-200",objectivec:"bg-blue-100 text-blue-700 border-blue-200",go:"bg-cyan-100 text-cyan-700 border-cyan-200",python:"bg-yellow-100 text-yellow-700 border-yellow-200",java:"bg-red-100 text-red-700 border-red-200",kotlin:"bg-purple-100 text-purple-700 border-purple-200",javascript:"bg-amber-100 text-amber-700 border-amber-200",typescript:"bg-blue-100 text-blue-700 border-blue-200",rust:"bg-orange-100 text-orange-800 border-orange-300",ruby:"bg-rose-100 text-rose-700 border-rose-200",c:"bg-gray-100 text-gray-700 border-gray-200",cpp:"bg-gray-100 text-gray-700 border-gray-200"},ba={swift:"Swift",objectivec:"ObjC",go:"Go",python:"Py",java:"Java",kotlin:"KT",javascript:"JS",typescript:"TS",rust:"RS",ruby:"RB",c:"C",cpp:"C++"},xn=({targets:t,filteredTargets:s,selectedTargetName:a,isScanning:l,scanProgress:d,scanFileList:c,scanResults:u,guardAudit:p,handleScanTarget:n,handleScanProject:g,handleUpdateScanResult:f,handleSaveExtracted:h,handlePromoteToCandidate:x,handleDeleteCandidate:i,onEditRecipe:y,isShellTarget:k,recipes:w=[],isSavingRecipe:T=!1,handleRefreshProject:A,onAddCustomFolder:G,onRemoveCustomFolder:_})=>{var Ue,Se;const{t:E}=_e(),[Z,X]=o.useState(null),[H,q]=o.useState(null),[I,L]=o.useState({}),[$,m]=o.useState(null),[N,j]=o.useState(null),[W,O]=o.useState(!1),[ye,Ne]=o.useState(),[je,v]=o.useState(),ee=o.useRef(new Set),te=o.useRef([]),[de,ve]=o.useState([]),[fe,ie]=o.useState(!1),be=o.useRef(!1),B=3,[K,xe]=o.useState("modules"),P=o.useRef(!1),R=o.useMemo(()=>s.filter(ne=>!k(ne.name)).length,[s,k]);o.useEffect(()=>{P.current||t.length!==0&&(P.current=!0,R<B?xe("folders"):xe("modules"))},[t.length,R]),o.useEffect(()=>{K!=="folders"||be.current||(be.current=!0,ie(!0),ae.browseDirectories("",3).then(ne=>{ve(ne)}).catch(()=>{ve([])}).finally(()=>{ie(!1)}))},[K]);const Q=o.useCallback(ne=>{const pe={name:ne.name,packageName:ne.name,packagePath:ne.path,targetDir:ne.path,path:ne.path,type:"directory",language:ne.language||"unknown",discovererId:"folder-scan",discovererName:E("moduleExplorer.discovererFolderScan"),info:{source:"manual-folder-scan",originalPath:ne.path},isVirtual:!0};G==null||G(pe),n(pe),xe("modules")},[n,G,E]),ce=o.useCallback(async(ne,pe)=>{if(!ee.current.has(ne)){ee.current.add(ne),m(ne);try{const Le=pe.candidateId&&pe.targetName?{targetName:pe.targetName,candidateId:pe.candidateId}:{candidate:pe.candidate||{}},He=await ae.getCandidateSimilarityEx(Le);L(De=>({...De,[ne]:He.similar||[]}))}catch{L(He=>({...He,[ne]:[]}))}finally{m(null)}}},[]),we=o.useCallback(async(ne,pe,Le=[])=>{var F,M,U;const He=ne.candidateTargetName||"",De=pe.replace(/\.md$/i,"");let r="";const C=w==null?void 0:w.find(se=>se.name===De||se.name.endsWith("/"+De));if(C!=null&&C.content)r=[C.content.pattern,C.content.markdown].filter(Boolean).join(`
113
112
 
114
- `)||"";else try{r=(await se.getRecipeContentByName(Ne)).content}catch(te){const de=(B=te.response)==null?void 0:B.status,me=((U=(D=te.response)==null?void 0:D.data)==null?void 0:U.message)||te.message;de===404?re(P("moduleExplorer.recipeNotExist",{name:Ne}),{title:P("moduleExplorer.recipeNotExistTitle"),type:"error"}):re(me,{title:P("moduleExplorer.loadRecipeFailed"),type:"error"});return}const b={[Ne]:r};y({candidate:ne,targetName:Pe,recipeName:Ne,recipeContent:r,similarList:He.slice(0,3),recipeContents:b})},[C]);return o.useEffect(()=>{const ne=u.map((Ne,r)=>Ne.candidateId??`scan-${r}`),ve=ae.current;(ne.length!==ve.length||ne.some((Ne,r)=>Ne!==ve[r]))&&(ee.current.clear(),ae.current=ne);const Pe=setTimeout(()=>{u.forEach((Ne,r)=>{var b,B;const k=Ne.candidateId??Ne.id??`scan-${r}`;Ne.candidateId&&Ne.candidateTargetName?ie(k,{targetName:Ne.candidateTargetName,candidateId:Ne.candidateId}):ie(k,{candidate:{title:Ne.title,summary:Ne.description||"",code:((b=Ne.content)==null?void 0:b.pattern)||"",usageGuide:((B=Ne.content)==null?void 0:B.markdown)||""}})})},800);return()=>clearTimeout(Pe)},[u,ie]),e.jsxs("div",{className:"flex gap-8 h-full",children:[e.jsxs("div",{className:"w-80 bg-white rounded-xl border border-slate-200 flex flex-col overflow-hidden shrink-0",children:[e.jsx("div",{className:"p-3 bg-slate-50 border-b border-slate-200",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-0.5 bg-slate-200/60 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>xe("modules"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${K==="modules"?"bg-white text-blue-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:P("moduleExplorer.modulesTabLabel",{count:T})}),e.jsx("button",{onClick:()=>xe("folders"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${K==="folders"?"bg-white text-blue-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:P("moduleExplorer.foldersTabLabel")})]}),S&&e.jsx("button",{onClick:S,title:P("moduleExplorer.refreshProject"),className:"p-1.5 rounded-md hover:bg-blue-50 text-slate-500 hover:text-blue-600 border border-transparent hover:border-blue-200 transition-all",children:e.jsx(yt,{size:F.md})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-1",children:K==="modules"?e.jsx(e.Fragment,{children:s.map(ne=>{const ve=w(ne.name),He=a===ne.name,Pe=ne.isVirtual||ne.discovererId==="folder-scan",Ne=ne.language||"",r=ga[Ne]||"bg-slate-100 text-slate-500 border-slate-200",k=ne.packageName&&ne.packageName!==ne.name?ne.packageName:ne.discovererName||"";return e.jsxs("button",{onClick:()=>n(ne),disabled:l,className:`w-full text-left p-3 rounded-lg flex items-center justify-between group transition-all border ${l?"opacity-50 cursor-not-allowed":"hover:bg-slate-50"} ${He?"bg-blue-50 border-blue-200 ring-1 ring-blue-200":"bg-white border-transparent"} ${ve?"opacity-90":""}`,children:[e.jsxs("div",{className:`flex flex-col max-w-[85%] ${ve?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[!ve&&e.jsx("div",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${Pe?"bg-emerald-500":"bg-blue-600"}`}),e.jsx("span",{className:`text-sm truncate ${ve?"font-medium":"font-bold"} ${He?"text-blue-700":""}`,children:ne.name}),Ne&&!ve&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${r}`,children:ba[Ne]||Ne.toUpperCase()}),Pe&&e.jsx("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 bg-emerald-50 text-emerald-600 border-emerald-200",children:"FOLDER"})]}),k&&e.jsx("span",{className:"text-[10px] text-slate-400 truncate pl-3",children:k})]}),ve?e.jsx("span",{className:"text-[9px] font-bold text-slate-300 border border-slate-100 px-1 rounded",children:"SHELL"}):Pe&&z?e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[e.jsx(et,{size:F.sm,className:`${He?"text-blue-500 opacity-100":"text-blue-500 opacity-0 group-hover:opacity-100"} transition-opacity`}),e.jsx("button",{onClick:b=>{b.stopPropagation(),z(ne.path||"")},title:P("moduleExplorer.removeFolder"),className:"p-0.5 rounded text-slate-300 hover:text-red-500 hover:bg-red-50 opacity-0 group-hover:opacity-100 transition-all",children:e.jsx(ot,{size:12})})]}):e.jsx(et,{size:F.sm,className:`shrink-0 ${He?"text-blue-500 opacity-100":"text-blue-500 opacity-0 group-hover:opacity-100"} transition-opacity`})]},`${ne.discovererId||"default"}::${ne.name}`)})}):e.jsxs(e.Fragment,{children:[he?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-slate-400",children:[e.jsx(Fe,{size:F.lg,className:"animate-spin mb-3 opacity-40"}),e.jsx("p",{className:"text-xs",children:P("moduleExplorer.scanningDirs")})]}):ue.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-slate-400",children:[e.jsx(wt,{size:F.xl,className:"mb-3 opacity-20"}),e.jsx("p",{className:"text-xs text-center px-4 leading-relaxed",children:P("moduleExplorer.noDirs")})]}):ue.map(ne=>{const ve=ga[ne.language]||"bg-slate-100 text-slate-500 border-slate-200";return e.jsxs("button",{onClick:()=>Q(ne),disabled:l||!ne.hasSourceFiles,className:`w-full text-left p-2.5 rounded-lg flex items-center gap-2.5 transition-all border border-transparent
113
+ `)||"";else try{r=(await ae.getRecipeContentByName(De)).content}catch(se){const ue=(F=se.response)==null?void 0:F.status,he=((U=(M=se.response)==null?void 0:M.data)==null?void 0:U.message)||se.message;ue===404?re(E("moduleExplorer.recipeNotExist",{name:De}),{title:E("moduleExplorer.recipeNotExistTitle"),type:"error"}):re(he,{title:E("moduleExplorer.loadRecipeFailed"),type:"error"});return}const b={[De]:r};j({candidate:ne,targetName:He,recipeName:De,recipeContent:r,similarList:Le.slice(0,3),recipeContents:b})},[w]);return o.useEffect(()=>{const ne=u.map((De,r)=>De.candidateId??`scan-${r}`),pe=te.current;(ne.length!==pe.length||ne.some((De,r)=>De!==pe[r]))&&(ee.current.clear(),te.current=ne);const He=setTimeout(()=>{u.forEach((De,r)=>{var b,F;const C=De.candidateId??De.id??`scan-${r}`;De.candidateId&&De.candidateTargetName?ce(C,{targetName:De.candidateTargetName,candidateId:De.candidateId}):ce(C,{candidate:{title:De.title,summary:De.description||"",code:((b=De.content)==null?void 0:b.pattern)||"",usageGuide:((F=De.content)==null?void 0:F.markdown)||""}})})},800);return()=>clearTimeout(He)},[u,ce]),e.jsxs("div",{className:"flex gap-4 xl:gap-6 2xl:gap-8 h-full",children:[e.jsxs("div",{className:"w-64 xl:w-72 2xl:w-80 bg-white rounded-xl border border-slate-200 flex flex-col overflow-hidden shrink-0",children:[e.jsx("div",{className:"p-3 bg-slate-50 border-b border-slate-200",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-0.5 bg-slate-200/60 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>xe("modules"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${K==="modules"?"bg-white text-blue-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:E("moduleExplorer.modulesTabLabel",{count:R})}),e.jsx("button",{onClick:()=>xe("folders"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${K==="folders"?"bg-white text-blue-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:E("moduleExplorer.foldersTabLabel")})]}),A&&e.jsx("button",{onClick:A,title:E("moduleExplorer.refreshProject"),className:"p-1.5 rounded-md hover:bg-blue-50 text-slate-500 hover:text-blue-600 border border-transparent hover:border-blue-200 transition-all",children:e.jsx(yt,{size:z.md})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-1",children:K==="modules"?e.jsx(e.Fragment,{children:s.map(ne=>{const pe=k(ne.name),Le=a===ne.name,He=ne.isVirtual||ne.discovererId==="folder-scan",De=ne.language||"",r=ga[De]||"bg-slate-100 text-slate-500 border-slate-200",C=ne.packageName&&ne.packageName!==ne.name?ne.packageName:ne.discovererName||"";return e.jsxs("button",{onClick:()=>n(ne),disabled:l,className:`w-full text-left p-3 rounded-lg flex items-center justify-between group transition-all border ${l?"opacity-50 cursor-not-allowed":"hover:bg-slate-50"} ${Le?"bg-blue-50 border-blue-200 ring-1 ring-blue-200":"bg-white border-transparent"} ${pe?"opacity-90":""}`,children:[e.jsxs("div",{className:`flex flex-col max-w-[85%] ${pe?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[!pe&&e.jsx("div",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${He?"bg-emerald-500":"bg-blue-600"}`}),e.jsx("span",{className:`text-sm truncate ${pe?"font-medium":"font-bold"} ${Le?"text-blue-700":""}`,children:ne.name}),De&&!pe&&!He&&De!=="unknown"&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${r}`,children:ba[De]||De.toUpperCase()})]}),C&&e.jsx("span",{className:"text-[10px] text-slate-400 truncate pl-3",children:C})]}),pe?e.jsx("span",{className:"text-[9px] font-bold text-slate-300 border border-slate-100 px-1 rounded",children:"SHELL"}):He&&_?e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[e.jsx(et,{size:z.sm,className:`${Le?"text-blue-500 opacity-100":"text-blue-500 opacity-0 group-hover:opacity-100"} transition-opacity`}),e.jsx("button",{onClick:b=>{b.stopPropagation(),_(ne.path||"")},title:E("moduleExplorer.removeFolder"),className:"p-0.5 rounded text-slate-300 hover:text-red-500 hover:bg-red-50 opacity-0 group-hover:opacity-100 transition-all",children:e.jsx(ot,{size:12})})]}):e.jsx(et,{size:z.sm,className:`shrink-0 ${Le?"text-blue-500 opacity-100":"text-blue-500 opacity-0 group-hover:opacity-100"} transition-opacity`})]},`${ne.discovererId||"default"}::${ne.name}`)})}):e.jsxs(e.Fragment,{children:[fe?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-slate-400",children:[e.jsx(Me,{size:z.lg,className:"animate-spin mb-3 opacity-40"}),e.jsx("p",{className:"text-xs",children:E("moduleExplorer.scanningDirs")})]}):de.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-slate-400",children:[e.jsx(wt,{size:z.xl,className:"mb-3 opacity-20"}),e.jsx("p",{className:"text-xs text-center px-4 leading-relaxed",children:E("moduleExplorer.noDirs")})]}):de.map(ne=>{const pe=ga[ne.language]||"bg-slate-100 text-slate-500 border-slate-200";return e.jsxs("button",{onClick:()=>Q(ne),disabled:l||!ne.hasSourceFiles,className:`w-full text-left p-2.5 rounded-lg flex items-center gap-2.5 transition-all border border-transparent
115
114
  ${ne.hasSourceFiles?l?"opacity-50 cursor-not-allowed":"hover:bg-emerald-50 hover:border-emerald-200 cursor-pointer":"opacity-40 cursor-not-allowed"}
116
- `,style:{paddingLeft:`${ne.depth*14+10}px`},children:[e.jsx(wt,{size:F.sm,className:ne.hasSourceFiles?"text-emerald-500 shrink-0":"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-sm font-medium flex-1 truncate",children:ne.name}),ne.hasSourceFiles&&ne.language!=="unknown"&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${ve}`,children:ba[ne.language]||ne.language.toUpperCase()}),ne.hasSourceFiles&&e.jsx("span",{className:"text-[10px] text-slate-400 shrink-0",children:P("moduleExplorer.sourceFileCount",{count:ne.sourceFileCount})}),e.jsx(rt,{size:12,className:"text-slate-300 shrink-0"})]},ne.path)}),e.jsx("div",{className:"px-3 py-2 text-[10px] text-slate-400 text-center",children:P("moduleExplorer.selectFolderHint")})]})})]}),e.jsxs("div",{className:"flex-1 bg-white rounded-xl border border-slate-200 flex flex-col overflow-hidden relative",children:[e.jsx("div",{className:"p-4 bg-slate-50 border-b border-slate-200 font-bold text-sm flex justify-between items-center",children:e.jsxs("div",{className:"flex items-center gap-2",children:[a==="__project__"?e.jsxs(e.Fragment,{children:[e.jsx(lt,{size:F.md,className:"text-indigo-500"}),e.jsx("span",{children:P("moduleExplorer.fullProjectResults")}),u.length>0&&e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 border border-indigo-200",children:"PROJECT"})]}):a?e.jsxs(e.Fragment,{children:[e.jsx(et,{size:F.md,className:"text-blue-500"}),e.jsx("span",{children:P("moduleExplorer.moduleLabel",{name:a})}),u.length>0&&e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 border border-blue-200",children:"MODULE"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Et,{size:F.md,className:"text-slate-400"}),e.jsx("span",{children:P("moduleExplorer.reviewResults")})]}),u.length>0&&e.jsxs("span",{className:"text-slate-400 font-normal text-xs ml-1",children:["(",P("moduleExplorer.resultsCount",{count:u.length}),(Ue=u[0])!=null&&Ue.trigger?P("moduleExplorer.candidateSuffix"):"",")"]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-8 relative",children:[l&&e.jsxs("div",{className:"absolute inset-0 bg-white/90 backdrop-blur-[2px] z-10 flex flex-col items-center justify-center text-blue-600 px-8 overflow-y-auto",children:[e.jsxs("div",{className:"relative mb-6",children:[e.jsx("div",{className:"w-16 h-16 border-4 border-blue-100 border-t-blue-600 rounded-full animate-spin"}),e.jsx(ns,{size:F.xxl,className:"absolute inset-0 m-auto text-blue-600 animate-pulse"})]}),e.jsx("p",{className:"font-bold text-lg animate-pulse mb-1",children:a==="__project__"?P("moduleExplorer.fullProjectScanning"):P("moduleExplorer.moduleScanLabel",{name:a||"..."})}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:d.status}),e.jsx("div",{className:"w-full max-w-md bg-slate-100 rounded-full h-2.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-600 rounded-full transition-all duration-500 ease-out",style:{width:`${Math.min(d.total?d.current/d.total*100:0,98)}%`}})}),e.jsx("p",{className:"text-xs text-slate-400 mt-3",children:d.total?`${Math.round(d.current/d.total*100)}%`:"0%"})]}),!l&&u.length===0&&e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-slate-400 text-center",children:[e.jsx(ws,{size:F.xxxl,className:"mb-4 opacity-20"}),e.jsx("p",{className:"font-medium text-slate-600",children:P("moduleExplorer.knowledgeExtract")}),e.jsx("p",{className:"text-xs mt-2 max-w-sm leading-relaxed",children:P("moduleExplorer.knowledgeExtractHint")})]}),!l&&a==="__project__"&&(p==null?void 0:p.summary)&&e.jsxs("div",{className:`rounded-xl border p-4 ${p.summary.totalViolations>0?"border-amber-200 bg-amber-50":"border-emerald-200 bg-emerald-50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ut,{size:F.md,className:p.summary.totalViolations>0?"text-amber-600":"text-emerald-600"}),e.jsx("span",{className:"text-sm font-bold text-slate-700",children:P("moduleExplorer.guardAuditSummary")}),e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 border border-indigo-200",children:"PROJECT SCAN"})]}),e.jsxs("div",{className:"flex gap-6 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-slate-500",children:P("moduleExplorer.auditedFiles")}),e.jsx("span",{className:"font-bold text-slate-700",children:p.summary.totalFiles})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-slate-500",children:P("moduleExplorer.totalViolationsLabel")}),e.jsx("span",{className:`font-bold ${p.summary.totalViolations>0?"text-amber-700":"text-emerald-700"}`,children:p.summary.totalViolations})]}),p.summary.errors>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Rt,{size:F.sm,className:"text-red-500"}),e.jsx("span",{className:"font-bold text-red-700",children:P("moduleExplorer.errorsCount",{count:p.summary.errors})})]}),p.summary.warnings>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Rt,{size:F.sm,className:"text-amber-500"}),e.jsx("span",{className:"font-bold text-amber-700",children:P("moduleExplorer.warningsCount",{count:p.summary.warnings})})]})]})]}),u.map((ne,ve)=>e.jsx(un,{res:ne,index:ve,editingCodeIndex:Z,setEditingCodeIndex:X,expandedEditIndex:H,setExpandedEditIndex:q,similarityMap:R,handleUpdateScanResult:f,handleSaveExtracted:h,handlePromoteToCandidate:x,openCompare:ke,isSavingRecipe:E},ve))]})]}),N&&e.jsx(xn,{data:N,onClose:()=>y(null),onDataChange:y,recipes:C,handleSaveExtracted:h,handleDeleteCandidate:c,onEditRecipe:j,isSavingRecipe:E}),e.jsx(rn,{isOpen:W,onClose:()=>O(!1),targetName:ye,currentFile:be,language:((Ie=s.find(ne=>ne.name===a))==null?void 0:Ie.language)||"unknown",onSelectRecipe:ne=>{}})]})},hn=72,gn=52,Ns=24,es=40,Xa=36,Tt=140,Zt=40,ts=8;function bn(t,s){const a=new Set(t.map(p=>p.id)),l=new Map;for(const p of s)!a.has(p.from)||!a.has(p.to)||(l.has(p.from)||l.set(p.from,[]),l.get(p.from).push(p.to));const d=new Map,i=new Set;function u(p){if(d.has(p))return d.get(p);if(i.has(p))return 0;i.add(p);const n=l.get(p);if(!n||n.length===0)return d.set(p,0),i.delete(p),0;const g=1+Math.max(...n.map(u));return d.set(p,g),i.delete(p),g}return t.forEach(p=>u(p.id)),d}function fn(t){return Math.ceil(t/ts)}function yn(t,s){const a=bn(t,s),l=new Map;for(const h of t){const x=a.get(h.id)??0;l.has(x)||l.set(x,[]),l.get(x).push(h.id)}const d=[...new Set(a.values())].sort((h,x)=>h-x),i=[...d].reverse(),u=new Map,p=new Map,n=Math.min(ts,Math.max(...d.map(h=>(l.get(h)??[]).length),1)),g=(n-1)*Ns+n*Tt;let f=es;return i.forEach(h=>{const x=l.get(h)??[],c=fn(x.length),j=f;for(let C=0;C<c;C++){const E=x.slice(C*ts,(C+1)*ts),S=(E.length-1)*Ns+E.length*Tt,G=(g-S)/2;E.forEach((z,P)=>{const Z=es+Xa+G+P*(Tt+Ns)+Tt/2,X=f+Zt/2;u.set(z,{x:Z,y:X})}),f+=C<c-1?gn:hn}const w=f-j;p.set(h,{y:j,h:w})}),{positions:u,tiers:a,tierOrder:d,tierYRanges:p}}const jn=()=>{const{t}=_e(),{isDark:s}=St(),[a,l]=o.useState(null),[d,i]=o.useState(!0),[u,p]=o.useState(null),[n,g]=o.useState(null),[f,h]=o.useState("package"),[x,c]=o.useState("all"),j=async()=>{var v,ee;i(!0),p(null);try{const ae=await se.getDepGraph(f);l({nodes:Array.isArray(ae==null?void 0:ae.nodes)?ae.nodes:[],edges:Array.isArray(ae==null?void 0:ae.edges)?ae.edges:[],projectRoot:(ae==null?void 0:ae.projectRoot)??null,generatedAt:ae==null?void 0:ae.generatedAt})}catch(ae){p(((ee=(v=ae.response)==null?void 0:v.data)==null?void 0:ee.error)||ae.message||"Failed to load dependency graph")}finally{i(!1)}};o.useEffect(()=>{j()},[f]);const w=Array.isArray(a==null?void 0:a.nodes)?a.nodes:[],C=Array.isArray(a==null?void 0:a.edges)?a.edges:[],E=w.some(v=>v.type==="internal"||v.type==="external"),S=o.useMemo(()=>!E||x==="all"?w:x==="internal"?w.filter(v=>v.type!=="external"):w.filter(v=>v.type!=="internal"),[w,x,E]),G=o.useMemo(()=>new Set(S.map(v=>v.id)),[S]),z=o.useMemo(()=>C.filter(v=>G.has(v.from)||G.has(v.to)),[C,G]),{positions:P,tiers:Z,tierOrder:X,tierYRanges:H}=o.useMemo(()=>yn(S,z),[S,z]),q=o.useMemo(()=>{const v=new Map;return S.forEach(ee=>{const ae=Z.get(ee.id)??0;v.has(ae)||v.set(ae,[]),v.get(ae).push(ee.id)}),v},[S,Z]),R=o.useMemo(()=>[...X].reverse(),[X]),{dependsOn:M,dependedBy:_}=o.useMemo(()=>{const v=new Map,ee=new Map;return z.forEach(ae=>{v.has(ae.from)||v.set(ae.from,[]),v.get(ae.from).push(ae.to),ee.has(ae.to)||ee.set(ae.to,[]),ee.get(ae.to).push(ae.from)}),{dependsOn:v,dependedBy:ee}},[z]),m=Math.min(ts,Math.max(...X.map(v=>(q.get(v)??[]).length),1)),y=(m-1)*Ns+m*Tt+Xa*2,W=Math.max(600,es*2+y),O=Math.max(...[...P.values()].map(v=>v.y),0),be=Math.max(420,O+Zt/2+es+20),we=s?[{bg:"rgba(59, 130, 246, 0.14)",border:"rgba(59, 130, 246, 0.40)",text:"rgb(147 197 253)"},{bg:"rgba(34, 197, 94, 0.14)",border:"rgba(34, 197, 94, 0.40)",text:"rgb(134 239 172)"},{bg:"rgba(234, 179, 8, 0.14)",border:"rgba(234, 179, 8, 0.40)",text:"rgb(253 224 71)"},{bg:"rgba(249, 115, 22, 0.14)",border:"rgba(249, 115, 22, 0.40)",text:"rgb(253 186 116)"},{bg:"rgba(139, 92, 246, 0.14)",border:"rgba(139, 92, 246, 0.40)",text:"rgb(196 181 253)"}]:[{bg:"rgb(239 246 255)",border:"rgb(147 197 253)",text:"rgb(30 64 175)"},{bg:"rgb(240 253 244)",border:"rgb(134 239 172)",text:"rgb(22 101 52)"},{bg:"rgb(254 249 195)",border:"rgb(253 224 71)",text:"rgb(113 63 18)"},{bg:"rgb(254 243 199)",border:"rgb(253 186 116)",text:"rgb(154 52 18)"},{bg:"rgb(243 232 255)",border:"rgb(216 180 254)",text:"rgb(91 33 182)"}],ye=v=>we[Math.min(v,we.length-1)]??we[0];return d?e.jsx("div",{className:"flex items-center justify-center min-h-[320px]",children:e.jsx("div",{className:"animate-spin rounded-full h-10 w-10 border-2 border-blue-600 border-t-transparent"})}):u?e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-6 text-red-700 shadow-sm",children:[e.jsx("p",{children:u}),e.jsx("button",{type:"button",onClick:j,className:"mt-4 px-4 py-2 rounded-lg bg-red-100 hover:bg-red-200 text-red-800 font-medium text-sm transition-colors",children:t("depGraph.retry")})]}):!a||w.length===0?e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50 p-8 text-slate-600 shadow-sm",children:[e.jsx("p",{className:"font-medium text-slate-700",children:t("depGraph.noDataTitle")}),e.jsx("p",{className:"mt-2 text-sm",children:t("depGraph.noDataDesc")})]}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex justify-between items-center shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center",children:e.jsx(lt,{className:"text-blue-600",size:20})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-800",children:t("depGraph.title")}),e.jsxs("p",{className:"text-xs text-slate-400 mt-0.5",children:[t("depGraph.visualization"),a.projectRoot&&e.jsxs("span",{className:"ml-1",children:["· ",a.projectRoot]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[E&&e.jsx("div",{className:"flex items-center border border-slate-200 rounded-lg overflow-hidden text-xs",children:["all","internal","external"].map(v=>e.jsx("button",{type:"button",onClick:()=>c(v),className:`px-3 py-1.5 font-medium transition-colors ${x===v?"bg-blue-600 text-white":"bg-white text-slate-600 hover:bg-slate-50"}`,children:t(v==="all"?"depGraph.filterAll":v==="internal"?"depGraph.filterInternal":"depGraph.filterExternal")},v))}),e.jsxs("button",{type:"button",onClick:()=>{j()},className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-slate-600 bg-slate-50 border border-slate-200 hover:bg-slate-100",children:[e.jsx(yt,{size:14})," ",t("depGraph.refresh")]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-50 border border-slate-100",children:[e.jsx(lt,{size:14,className:"text-slate-400"}),e.jsxs("span",{className:"text-slate-500",children:[t("depGraph.packages")," ",e.jsx("strong",{className:"text-slate-700",children:S.length})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-100",children:[e.jsx("span",{className:"text-emerald-500",children:t("depGraph.dependencies")}),e.jsx("strong",{className:"text-emerald-700",children:z.length})]}),a.generatedAt&&e.jsx("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-blue-50 border border-blue-100",children:e.jsx("span",{className:"text-blue-500",children:new Date(a.generatedAt).toLocaleString("zh-CN")})})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1 space-y-6",children:[E&&e.jsxs("div",{className:"flex items-center gap-4 text-xs text-slate-500 px-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-slate-300 bg-white"})," ",t("depGraph.projectRoot")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-green-400 bg-green-50"})," ",t("depGraph.filterInternal")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-amber-400 bg-amber-50 border-dashed"})," ",t("depGraph.filterExternal")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-amber-400 bg-amber-50 border-dashed opacity-50"})," ",t("depGraph.labelIndirect")]})]}),e.jsxs("div",{className:`rounded-xl border overflow-auto shadow-sm min-h-[480px] flex items-center justify-center relative ${s?"border-slate-700 bg-[#13151c]":"border-slate-200 bg-slate-50/50"}`,children:[e.jsxs("svg",{width:"100%",height:be,viewBox:`0 0 ${W} ${be}`,className:"block min-h-[480px] w-full",style:{maxHeight:640},children:[e.jsx("defs",{children:e.jsx("filter",{id:"nodeShadow",x:"-20%",y:"-20%",width:"140%",height:"140%",children:e.jsx("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.12"})})}),R.map((v,ee)=>{const ae=ye(ee),ue=H.get(v);return ue?e.jsx("rect",{x:es,y:ue.y-Zt/2-4,width:y,height:ue.h+8,rx:8,fill:ae.bg,stroke:ae.border,strokeWidth:s?1.5:1,opacity:s?1:.6},v):null}),S.map(v=>{const ee=P.get(v.id);if(!ee)return null;const ae=Z.get(v.id)??0,ue=ye(R.indexOf(ae)),fe=v.label.length>14?v.label.slice(0,13)+"…":v.label,he=n===v.id,ce=n?(M.get(n)??[]).includes(v.id):!1,je=n?(_.get(n)??[]).includes(v.id):!1,$=n&&!he&&!ce&&!je,K=v.type==="external"?s?{fill:"rgba(234, 179, 8, 0.1)",stroke:"rgb(202 138 4)",text:"rgb(253 224 71)",badge:"EXT"}:{fill:"rgb(254 252 232)",stroke:"rgb(234 179 8)",text:"rgb(113 63 18)",badge:"EXT"}:v.type==="internal"?s?{fill:"rgba(34, 197, 94, 0.1)",stroke:"rgb(22 163 74)",text:"rgb(134 239 172)",badge:""}:{fill:"rgb(240 253 244)",stroke:"rgb(74 222 128)",text:"rgb(22 101 52)",badge:""}:s?{fill:"#1e2433",stroke:ue.border,text:ue.text,badge:""}:{fill:"white",stroke:ue.border,text:ue.text,badge:""},xe=n?he?s?{fill:"#283040",stroke:"rgb(59 130 246)",text:"rgb(147 197 253)",strokeWidth:3,opacity:1}:{fill:"white",stroke:"rgb(59 130 246)",text:"rgb(30 64 175)",strokeWidth:3,opacity:1}:ce?s?{fill:"rgba(34, 197, 94, 0.12)",stroke:"rgb(34 197 94)",text:"rgb(134 239 172)",strokeWidth:2,opacity:1}:{fill:"rgb(240 253 244)",stroke:"rgb(34 197 94)",text:"rgb(22 101 52)",strokeWidth:2,opacity:1}:je?s?{fill:"rgba(139, 92, 246, 0.12)",stroke:"rgb(139 92 246)",text:"rgb(196 181 253)",strokeWidth:2,opacity:1}:{fill:"rgb(245 243 255)",stroke:"rgb(139 92 246)",text:"rgb(91 33 182)",strokeWidth:2,opacity:1}:s?{fill:"#1a1b23",stroke:"rgb(51 65 85)",text:"rgb(100 116 139)",strokeWidth:1,opacity:.6}:{fill:"rgb(248 250 252)",stroke:"rgb(203 213 225)",text:"rgb(148 163 184)",strokeWidth:1,opacity:.6}:{fill:K.fill,stroke:K.stroke,text:K.text,strokeWidth:2,opacity:v.indirect?.55:1};return e.jsxs("g",{style:{cursor:"pointer",opacity:xe.opacity},onClick:()=>g(he?null:v.id),children:[e.jsx("rect",{x:ee.x-Tt/2,y:ee.y-Zt/2,width:Tt,height:Zt,rx:10,ry:10,fill:xe.fill,stroke:xe.stroke,strokeWidth:xe.strokeWidth,filter:$?void 0:"url(#nodeShadow)",strokeDasharray:v.type==="external"?"4 2":void 0}),e.jsx("text",{x:ee.x,y:ee.y+(K.badge?-2:0),textAnchor:"middle",dominantBaseline:"middle",fontSize:"12",fontWeight:"600",fill:xe.text,pointerEvents:"none",children:fe}),K.badge&&e.jsx("text",{x:ee.x,y:ee.y+12,textAnchor:"middle",dominantBaseline:"middle",fontSize:"8",fontWeight:"500",fill:K.text,opacity:.6,pointerEvents:"none",children:K.badge})]},v.id)})]}),n&&e.jsxs("div",{className:"absolute top-4 right-4 w-72 rounded-xl border border-slate-200 bg-white shadow-lg z-10 p-4",role:"dialog","aria-label":t("depGraph.dependencies"),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 pb-2 border-b border-slate-100",children:[e.jsx("span",{className:"font-bold text-slate-800",children:n}),e.jsx("button",{type:"button",onClick:()=>g(null),className:"text-slate-400 hover:text-slate-600 text-lg leading-none","aria-label":t("depGraph.close"),children:"×"})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-slate-600 mb-1",children:t("depGraph.dependencies")}),e.jsx("ul",{className:"text-slate-700 space-y-0.5",children:(M.get(n)??[]).length===0?e.jsx("li",{className:"text-slate-400",children:t("depGraph.none")}):(M.get(n)??[]).map(v=>e.jsxs("li",{children:["→ ",v]},v))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-slate-600 mb-1",children:t("depGraph.dependents")}),e.jsx("ul",{className:"text-slate-700 space-y-0.5",children:(_.get(n)??[]).length===0?e.jsx("li",{className:"text-slate-400",children:t("depGraph.none")}):(_.get(n)??[]).map(v=>e.jsxs("li",{children:["← ",v]},v))})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-5 shadow-sm",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-3 pb-2 border-b border-slate-100",children:[t("depGraph.packageList")," (",S.length,")"]}),e.jsx("ul",{className:"text-sm space-y-3 max-h-[280px] overflow-y-auto pr-1",children:S.map(v=>e.jsxs("li",{className:"pb-3 border-b border-slate-100 last:border-0 last:pb-0",children:[e.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-slate-800",children:v.label||v.id}),v.type==="external"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200 font-medium",children:t("depGraph.labelExternal")}),v.type==="internal"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-emerald-50 text-emerald-700 border border-emerald-200 font-medium",children:t("depGraph.labelInternal")}),v.indirect&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-slate-50 text-slate-500 border border-slate-200 font-medium",children:t("depGraph.labelIndirect")}),v.packageDir&&e.jsxs("span",{className:"text-slate-500 text-xs",children:["· ",v.packageDir]})]}),v.fullPath&&e.jsx("div",{className:"mt-1 text-slate-400 text-xs truncate",children:v.fullPath}),v.targets&&v.targets.length>0&&e.jsxs("div",{className:"mt-1.5 text-slate-500 text-xs pl-0",children:["Targets: ",e.jsx("span",{className:"text-slate-600",children:v.targets.join(", ")})]})]},v.id))})]}),e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-5 shadow-sm",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-3 pb-2 border-b border-slate-100",children:[t("depGraph.depRelations")," (",z.length,")"]}),e.jsx("p",{className:"text-xs text-slate-500 mb-2",children:t("depGraph.depRelationsDesc")}),e.jsx("ul",{className:"text-sm space-y-2 max-h-[280px] overflow-y-auto pr-1",children:z.map((v,ee)=>e.jsxs("li",{className:"flex items-center gap-2 text-slate-700",children:[e.jsx("span",{className:"font-semibold text-slate-800",children:v.from}),e.jsx("span",{className:"text-slate-400 shrink-0",children:"→"}),e.jsx("span",{className:"font-semibold text-slate-800",children:v.to})]},`${v.from}-${v.to}-${ee}`))})]}),f==="target"&&e.jsxs("p",{className:"text-xs text-slate-500 mt-2",children:[t("depGraph.targetHint"),e.jsx("span",{className:"font-mono",children:"Package::Target"})]})]})]})]})},vn=({onRefresh:t})=>{const{t:s}=_e(),[a,l]=o.useState({}),[d,i]=o.useState([]),[u,p]=o.useState([]),[n,g]=o.useState(null),[f,h]=o.useState(!0),[x,c]=o.useState(!1),[j,w]=o.useState(!1),[C,E]=o.useState(""),[S,G]=o.useState(!1),[z,P]=o.useState({ruleId:"",message:"",severity:"warning",pattern:"",languages:[],note:"",dimension:""}),[Z,X]=o.useState(!1),[H,q]=o.useState(""),R=async()=>{try{const[$,K]=await Promise.all([se.getGuardRules(),se.getGuardViolations()]);l(($==null?void 0:$.rules)||{}),p(($==null?void 0:$.projectLanguages)||[]),i((K==null?void 0:K.runs)||[])}catch{l({}),i([])}finally{h(!1)}};o.useEffect(()=>{R()},[]);const M=async()=>{if(window.confirm(s("guard.clearConfirm")))try{await se.clearViolations(),R(),t==null||t()}catch($){re(($==null?void 0:$.message)||s("common.operationFailed"),{title:s("common.operationFailed"),type:"error"})}},_=$=>{P(K=>({...K,languages:K.languages.includes($)?K.languages.filter(xe=>xe!==$):[...K.languages,$]}))},m=async()=>{var $,K;if(!C.trim()){q(s("guard.aiGenPlaceholder"));return}q(""),G(!0);try{const L=await se.generateGuardRule({description:C.trim()}),T=L.dimension;P({ruleId:L.ruleId||"",message:L.message||"",severity:L.severity==="error"?"error":"warning",pattern:L.pattern||"",languages:Array.isArray(L.languages)&&L.languages.length>0?L.languages:[],note:L.note!=null?String(L.note):"",dimension:T==="file"||T==="target"||T==="project"?T:""}),w(!0)}catch(xe){q(((K=($=xe==null?void 0:xe.response)==null?void 0:$.data)==null?void 0:K.error)||(xe==null?void 0:xe.message)||s("guard.aiGenFailed"))}finally{G(!1)}},N=async $=>{var K,xe;if($.preventDefault(),q(""),!z.ruleId.trim()||!z.message.trim()||!z.pattern.trim()||z.languages.length===0){q(s("guard.addRuleValidation"));return}X(!0);try{await se.saveGuardRule({ruleId:z.ruleId.trim(),message:z.message.trim(),severity:z.severity,pattern:z.pattern.trim(),languages:z.languages,note:z.note.trim()||void 0,...z.dimension?{dimension:z.dimension}:{}}),P({ruleId:"",message:"",severity:"warning",pattern:"",languages:[],note:"",dimension:""}),E(""),w(!1),R(),t==null||t()}catch(L){q(((xe=(K=L==null?void 0:L.response)==null?void 0:K.data)==null?void 0:xe.error)||(L==null?void 0:L.message)||s("common.saveFailed"))}finally{X(!1)}},W=o.useMemo(()=>{const $=Object.entries(a);return u.length===0?$:$.filter(([,K])=>!K.languages||K.languages.length===0?!0:K.languages.some(xe=>u.includes(xe)))},[a,u]),O=d.reduce(($,K)=>$+K.violations.length,0),[be,we]=o.useState("all"),[ye,v]=o.useState("all"),ee=o.useMemo(()=>{const $=new Set;for(const[,xe]of W)(xe.languages||[]).forEach(L=>$.add(L));const K=Bt.filter(xe=>$.has(xe.id)).map(xe=>xe.id);for(const xe of $)K.includes(xe)||K.push(xe);return K},[W]),ae=$=>{var K;return((K=Bt.find(xe=>xe.id===$))==null?void 0:K.label)||$},ue=o.useMemo(()=>{const $={error:0,warning:0,info:0};for(const[,K]of W){const xe=K.severity;$[xe]!==void 0&&$[xe]++}return $},[W]),fe=$=>{const K={safety:s("guard.categorySafety"),correctness:s("guard.categoryCorrectness"),performance:s("guard.categoryPerformance"),style:s("guard.categoryStyle")};return $?K[$]||$:"—"},he=($,K)=>{const xe=`guardRuleMessages.${$}`,L=s(xe);return L!==xe?L:K},ce=($,K)=>{if(!K)return K;const xe=`guardRuleFixSuggestions.${$}`,L=s(xe);return L!==xe?L:K},je=o.useMemo(()=>W.filter(([,$])=>!(be!=="all"&&!($.languages||[]).includes(be)||ye!=="all"&&$.severity!==ye)),[W,be,ye]);return f?e.jsx("div",{className:"p-6 text-slate-500",children:s("common.loading")}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex justify-between items-center shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center",children:e.jsx(ut,{className:"text-blue-600",size:20})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-800",children:s("guard.title")}),e.jsxs("p",{className:"text-xs text-slate-400 mt-0.5",children:[s("guard.summary"),u.length>0&&e.jsxs("span",{className:"ml-1.5",children:["· ",s("guard.currentProject"),":",u.map($=>ae($)).join(" / ")]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("a",{href:ar,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-slate-600 bg-slate-50 border border-slate-200 hover:bg-slate-100",children:[e.jsx(Tl,{size:14})," ",s("guard.reportIssue")]}),e.jsxs("button",{type:"button",onClick:()=>c(!x),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-blue-700 bg-blue-50 border border-blue-200 hover:bg-blue-100",children:[x?e.jsx(Gt,{size:14}):e.jsx(rt,{size:14}),s("guard.aiGenRule")]}),d.length>0&&e.jsxs("button",{type:"button",onClick:M,className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-red-600 bg-red-50 border border-red-200 hover:bg-red-100",children:[e.jsx(ot,{size:14})," ",s("guard.clearHistory")]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-50 border border-slate-100",children:[e.jsx(ut,{size:14,className:"text-slate-400"}),e.jsxs("span",{className:"text-slate-500",children:[s("guard.tableHeaders.rule")," ",e.jsx("strong",{className:"text-slate-700",children:W.length})]})]}),O>0&&e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-amber-50 border border-amber-100",children:[e.jsx(Rt,{size:14,className:"text-amber-400"}),e.jsx("span",{className:"text-amber-600",children:s("guard.totalViolations",{count:O})})]})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1",children:[x&&e.jsxs("section",{className:"mb-6",children:[e.jsxs("div",{className:"p-4 bg-slate-50 border border-slate-200 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"semantic-input",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.aiGenRuleDesc")}),e.jsx("textarea",{id:"semantic-input",name:"semanticInput",value:C,onChange:$=>{E($.target.value),q("")},className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm resize-y min-h-[80px]",placeholder:s("guard.aiGenPlaceholder"),rows:3}),e.jsx("button",{type:"button",onClick:m,disabled:S||!C.trim(),className:"mt-2 px-4 py-2 bg-slate-600 text-white text-sm rounded-lg hover:bg-slate-700 disabled:opacity-50",children:s(S?"guard.aiGenerating":"guard.aiGenRule")}),H&&e.jsx("p",{className:"mt-2 text-sm text-red-600",children:H})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>w(!j),className:"text-sm font-medium text-blue-600 hover:text-blue-700",children:s(j?"common.collapse":"common.expand")}),z.ruleId&&e.jsxs("span",{className:"text-xs text-slate-500",children:[s("guard.generatedRuleId"),":",z.ruleId]})]})]}),j&&e.jsxs("form",{onSubmit:N,className:"mt-3 p-4 bg-white border border-slate-200 rounded-xl space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-id",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.ruleId")}),e.jsx("input",{id:"rule-id",name:"ruleId",type:"text",value:z.ruleId,onChange:$=>P(K=>({...K,ruleId:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",placeholder:"my-rule-id"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-severity",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.severity")}),e.jsxs("select",{id:"rule-severity",name:"severity",value:z.severity,onChange:$=>P(K=>({...K,severity:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",children:[e.jsx("option",{value:"warning",children:"warning"}),e.jsx("option",{value:"error",children:"error"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-message",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.message")}),e.jsx("input",{id:"rule-message",name:"message",type:"text",value:z.message,onChange:$=>P(K=>({...K,message:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",placeholder:s("guard.aiGenPlaceholder")})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-pattern",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.patternLabel")}),e.jsx("input",{id:"rule-pattern",name:"pattern",type:"text",value:z.pattern,onChange:$=>P(K=>({...K,pattern:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm font-mono",placeholder:"dispatch_sync\\\\s*\\\\([^)]*main"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.languagesLabel")}),e.jsx("div",{className:"flex gap-3 flex-wrap",children:(u.length>0?Bt.filter($=>u.includes($.id)):Bt.slice(0,8)).map($=>e.jsxs("label",{htmlFor:`lang-${$.id}`,className:"flex items-center gap-1.5 text-sm",children:[e.jsx("input",{id:`lang-${$.id}`,name:"languages",type:"checkbox",checked:z.languages.includes($.id),onChange:()=>_($.id)}),$.label]},$.id))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-dimension",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.dimensionLabel")}),e.jsxs("select",{id:"rule-dimension",name:"dimension",value:z.dimension,onChange:$=>P(K=>({...K,dimension:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",children:[e.jsx("option",{value:"",children:s("guard.dimNoLimit")}),e.jsx("option",{value:"file",children:s("guard.dimFile")}),e.jsx("option",{value:"target",children:s("guard.dimTarget")}),e.jsx("option",{value:"project",children:s("guard.dimProject")})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-note",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.noteLabel")}),e.jsx("input",{id:"rule-note",name:"note",type:"text",value:z.note,onChange:$=>P(K=>({...K,note:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",placeholder:s("guard.notePlaceholder")})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"submit",disabled:Z,className:"px-4 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 disabled:opacity-50",children:s(Z?"common.saving":"common.confirm")}),e.jsx("button",{type:"button",onClick:()=>w(!1),className:"px-4 py-2 text-slate-600 text-sm rounded-lg hover:bg-slate-100",children:s("common.collapse")})]})]})]}),e.jsxs("section",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 gap-3 flex-wrap",children:[e.jsxs("h3",{className:"text-sm font-semibold text-slate-700 flex items-center gap-1.5",children:[e.jsx(za,{size:14,className:"text-slate-400"}),s("guard.tableHeaders.rule"),e.jsxs("span",{className:"text-slate-400 font-normal",children:["(",je.length,"/",W.length,")"]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx("button",{onClick:()=>v("all"),className:`px-2 py-1 rounded-md border transition-all ${ye==="all"?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"}`,children:s("common.all")}),e.jsxs("button",{onClick:()=>v("error"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${ye==="error"?"bg-red-600 text-white border-red-600":"bg-white text-red-600 border-red-200 hover:bg-red-50"}`,children:[e.jsx(Ot,{size:12})," error ",e.jsxs("span",{className:"opacity-70",children:["(",ue.error,")"]})]}),e.jsxs("button",{onClick:()=>v("warning"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${ye==="warning"?"bg-amber-500 text-white border-amber-500":"bg-white text-amber-600 border-amber-200 hover:bg-amber-50"}`,children:[e.jsx(Rt,{size:12})," warning ",e.jsxs("span",{className:"opacity-70",children:["(",ue.warning,")"]})]}),e.jsxs("button",{onClick:()=>v("info"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${ye==="info"?"bg-blue-500 text-white border-blue-500":"bg-white text-blue-600 border-blue-200 hover:bg-blue-50"}`,children:[e.jsx(_a,{size:12})," info ",e.jsxs("span",{className:"opacity-70",children:["(",ue.info,")"]})]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mb-3 flex-wrap",children:[e.jsx("button",{onClick:()=>we("all"),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${be==="all"?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"}`,children:s("guard.allLanguages")}),ee.map($=>{const K=W.filter(([,xe])=>(xe.languages||[]).includes($)).length;return e.jsxs("button",{onClick:()=>we(be===$?"all":$),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${be===$?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"}`,children:[ae($)," ",e.jsxs("span",{className:"opacity-60",children:["(",K,")"]})]},$)})]}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600",children:s("guard.ruleId")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600 w-20",children:s("guard.severity")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600",children:s("guard.message")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600 w-28",children:s("guard.languagesLabel")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600 w-20",children:s("guard.category")})]})}),e.jsx("tbody",{children:je.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"py-4 px-4 text-slate-500 text-center",children:W.length===0?s("common.noData"):s("guard.noMatchingRules")})}):je.map(([$,K])=>e.jsxs("tr",{className:"border-b border-slate-100 last:border-0 hover:bg-slate-50/50",children:[e.jsx("td",{className:"py-2 px-4 font-mono text-xs text-slate-700",children:$}),e.jsx("td",{className:"py-2 px-4",children:e.jsx("span",{className:`text-xs font-medium px-1.5 py-0.5 rounded ${K.severity==="error"?"bg-red-100 text-red-700":K.severity==="info"?"bg-blue-100 text-blue-700":"bg-amber-100 text-amber-700"}`,children:K.severity})}),e.jsxs("td",{className:"py-2 px-4 text-slate-700",children:[he($,K.message),K.fixSuggestion&&e.jsx("span",{className:"ml-1.5 text-xs text-emerald-600",title:ce($,K.fixSuggestion),children:"💡"})]}),e.jsx("td",{className:"py-2 px-4",children:e.jsx("div",{className:"flex flex-wrap gap-1",children:(K.languages||[]).map(xe=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-100 font-medium",children:ae(xe)},xe))})}),e.jsx("td",{className:"py-2 px-4 text-xs text-slate-500",children:fe(K.category)})]},$))})]})})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-700 mb-3",children:s("guard.violationRecords",{runs:d.length,count:O})}),d.length===0?e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-xl py-12 text-center text-slate-500",children:s("guard.noViolations")}):e.jsx("div",{className:"space-y-2",children:d.map($=>{const K=n===$.id,xe=$.violations.length>0;return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-xl overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>g(K?null:$.id),className:"w-full flex items-center gap-2 py-3 px-4 text-left hover:bg-slate-50 transition-colors",children:[K?e.jsx(Gt,{size:F.md}):e.jsx(rt,{size:F.md}),e.jsx("span",{className:"font-mono text-sm text-slate-700",children:$.filePath}),e.jsx("span",{className:"text-xs text-slate-400",children:new Date($.triggeredAt).toLocaleString()}),xe?e.jsxs("span",{className:"ml-auto flex items-center gap-1 text-amber-600 text-xs font-medium",children:[e.jsx(Rt,{size:F.sm})," ",s("guard.totalViolations",{count:$.violations.length})]}):e.jsx("span",{className:"ml-auto text-slate-400 text-xs",children:s("guard.noViolations")})]}),K&&e.jsx("div",{className:"border-t border-slate-100 bg-slate-50/50 dark:bg-[#283040] p-4",children:$.violations.length===0?e.jsx("p",{className:"text-sm text-slate-500",children:s("guard.noViolations")}):e.jsx("ul",{className:"space-y-2",children:$.violations.map((L,T)=>{var ie;const Q=a[L.ruleId];return e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[L.severity==="error"?e.jsx(Ot,{size:F.md,className:"text-red-500 shrink-0 mt-0.5"}):e.jsx(Rt,{size:F.md,className:"text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsxs("div",{children:[e.jsxs("span",{className:"font-mono text-xs text-slate-500",children:["[",L.ruleId,"] ",L.filePath?`${L.filePath}:${L.line}`:`L${L.line}`]}),L.dimension&&e.jsx("span",{className:"ml-1.5 text-xs px-1.5 py-0.5 rounded bg-slate-200 text-slate-600",children:L.dimension==="file"?s("guard.dimFile"):L.dimension==="target"?s("guard.dimTarget"):s("guard.dimProject")}),e.jsx("span",{className:"text-slate-700 ml-2",children:he(L.ruleId,L.message)})]}),L.snippet&&e.jsx("pre",{className:"text-xs text-slate-600 bg-[#f1f5f9] dark:bg-[#0f1219] dark:text-slate-400 dark:border dark:border-slate-700 p-2 rounded overflow-x-auto",children:L.snippet}),Q&&(Q.rationale||((ie=Q.fixSuggestions)==null?void 0:ie.length)||Q.sourceRecipe||Q.note)&&e.jsxs("div",{className:"mt-1 rounded-lg border border-blue-100 bg-blue-50/50 p-2.5 text-xs space-y-1.5",children:[Q.rationale&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(tt,{size:12,className:"text-blue-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-bold text-blue-700",children:[s("guard.rationale"),":"]}),e.jsx("span",{className:"text-slate-600",children:Q.rationale})]})]}),Q.fixSuggestions&&Q.fixSuggestions.length>0&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx($a,{size:12,className:"text-emerald-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-bold text-emerald-700",children:[s("guard.fixSuggestion"),":"]}),e.jsx("ul",{className:"mt-0.5 space-y-0.5 text-slate-600",children:Q.fixSuggestions.map((ke,Ue)=>e.jsxs("li",{className:"flex items-start gap-1",children:[e.jsx("span",{className:"text-emerald-400 mt-0.5",children:"•"}),e.jsx("span",{children:ke}),e.jsx("button",{className:"ml-1 text-blue-500 hover:text-blue-700",title:s("guard.copyFixSuggestion"),onClick:()=>navigator.clipboard.writeText(ke),children:"⎘"})]},Ue))})]})]}),Q.sourceRecipe&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Hs,{size:12,className:"text-indigo-500 shrink-0"}),e.jsxs("span",{className:"font-bold text-indigo-700",children:[s("guard.sourceRecipe"),":"]}),e.jsx("span",{className:"text-indigo-600 font-mono",children:Q.sourceRecipe})]}),!Q.rationale&&Q.note&&e.jsxs("div",{className:"text-slate-500 italic",children:[s("guard.noteLabel"),":",Q.note]})]})]})]},T)})})})]},$.id)})})]})]})]})},fa=()=>Math.random().toString(36).substring(2,10),Nn=({d:t})=>{const{t:s}=_e();return e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-2.5 py-1 bg-slate-50 border-b border-slate-200 flex items-center gap-1.5",children:[e.jsx(Ta,{size:10,className:"text-emerald-500"}),e.jsx("span",{className:"text-[10px] font-bold text-slate-600",children:t.label})]}),e.jsxs("div",{className:"p-2.5 bg-red-50/30 border-b border-slate-200",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:s("aiChat.diffBefore")}),e.jsx("pre",{className:"text-[11px] text-slate-600 whitespace-pre-wrap break-words max-h-48 overflow-auto font-mono leading-relaxed scrollbar-light",children:t.before||e.jsx("span",{className:"italic text-slate-300",children:s("aiChat.diffEmpty")})})]}),e.jsxs("div",{className:"p-2.5 bg-emerald-50/30",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:s("aiChat.diffAfter")}),e.jsx("pre",{className:"text-[11px] text-slate-700 whitespace-pre-wrap break-words max-h-48 overflow-auto font-mono leading-relaxed scrollbar-light",children:t.after})]})]})};function wn(t,s){const a=new Date(t),d=new Date().getTime()-a.getTime(),i=Math.floor(d/6e4);if(i<1)return s("aiChat.timeJustNow");if(i<60)return s("aiChat.timeMinutesAgo",{n:i});const u=Math.floor(i/60);if(u<24)return s("aiChat.timeHoursAgo",{n:u});const p=Math.floor(u/24);return p<7?s("aiChat.timeDaysAgo",{n:p}):a.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})}const kn=()=>{const{t,lang:s}=_e(),{close:a,isOpen:l}=ds(),[d,i]=o.useState([]),[u,p]=o.useState(!1),n=o.useRef([]),g=o.useRef(null),f=Ua(),{topics:h,activeTopicId:x,activeTopic:c,createTopic:j,deleteTopic:w,saveTopic:C,switchTopic:E,setActiveTopicId:S}=f,G=o.useRef(null),z=o.useRef(null),[P,Z]=o.useState(""),[X,H]=o.useState(!1),q=o.useRef(!1);o.useEffect(()=>{l&&a()},[]),o.useEffect(()=>{var y;(y=G.current)==null||y.scrollIntoView({behavior:"smooth"})},[d,u]),o.useEffect(()=>{setTimeout(()=>{var y;return(y=z.current)==null?void 0:y.focus()},200)},[]),o.useEffect(()=>{q.current||x&&d.length>0&&C(x,d)},[d,x,C]);const R=o.useCallback(()=>{q.current=!0,j(),i([]),n.current=[],setTimeout(()=>{q.current=!1},50)},[j,i,n]),M=o.useCallback(y=>{if(y===x)return;q.current=!0,E(y);const W=f.getTopic(y);W?(i(W.messages),n.current=W.messages.filter(O=>O.role==="user"||O.role==="assistant").map(O=>({role:O.role==="assistant"?"model":O.role,content:O.content}))):(i([]),n.current=[]),setTimeout(()=>{q.current=!1},50)},[x,E,f,i,n]),_=o.useCallback((y,W)=>{y.stopPropagation(),w(W),W===x&&(q.current=!0,i([]),n.current=[],setTimeout(()=>{q.current=!1},50))},[w,x,i,n]),m=o.useCallback(async()=>{const y=P.trim();if(!y||u)return;let W=x;W||(q.current=!0,W=j(),setTimeout(()=>{q.current=!1},50)),Z(""),i(we=>[...we,{id:fa(),role:"user",content:y,timestamp:Date.now()}]),p(!0);const O=fa();i(we=>[...we,{id:O,role:"assistant",content:`🔄 ${t("aiChat.thinking")}`,timestamp:Date.now()}]),n.current.push({role:"user",content:y});const be=new AbortController;g.current=be;try{const{onEvent:we,getState:ye}=Wa(O,i,t),ee=(await se.chatStream(y,n.current,ae=>{we(ae)},be.signal,s)).text||ye().answerText;n.current.push({role:"model",content:ee}),i(ae=>ae.map(ue=>ue.id===O?{...ue,content:ee}:ue))}catch(we){if(we.name==="AbortError"){const ye=t("aiChat.cancelled");i(v=>v.map(ee=>ee.id===O?{...ee,content:ye}:ee))}else i(ye=>ye.map(v=>v.id===O?{...v,content:t("aiChat.requestFailed",{error:we.message})}:v))}finally{g.current=null}p(!1)},[P,u,x,j]),N=o.useCallback(y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),m())},[m]);return e.jsxs("div",{className:"flex-1 flex h-full bg-slate-50",children:[e.jsx("div",{className:`${X?"w-10":"w-64"} shrink-0 bg-white border-r border-slate-200 flex flex-col transition-all duration-200`,children:X?e.jsxs("div",{className:"flex flex-col items-center py-3 gap-2",children:[e.jsx("button",{onClick:()=>H(!1),className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400 hover:text-slate-600",title:t("aiChat.expandTopics"),children:e.jsx(rt,{size:16})}),e.jsx("button",{onClick:R,className:"p-1.5 hover:bg-blue-50 rounded-lg transition-colors text-blue-500",title:t("aiChat.newTopic"),children:e.jsx(Nt,{size:16})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-3 py-2.5 border-b border-slate-100 flex items-center justify-between shrink-0",children:[e.jsx("span",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:t("aiChat.topicRecords")}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx("button",{onClick:R,className:"p-1.5 hover:bg-blue-50 rounded-lg transition-colors text-slate-400 hover:text-blue-600",title:t("aiChat.newTopic"),children:e.jsx(Nt,{size:14})}),e.jsx("button",{onClick:()=>H(!0),className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400 hover:text-slate-600",title:t("common.collapse"),children:e.jsx(is,{size:14})})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-light",children:h.length===0?e.jsxs("div",{className:"px-4 py-8 text-center",children:[e.jsx(Lt,{size:24,className:"text-slate-200 mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-slate-400",children:t("aiChat.noHistory")}),e.jsx("p",{className:"text-[10px] text-slate-300 mt-1",children:t("aiChat.autoSaveHint")})]}):e.jsx("div",{className:"py-1",children:h.map(y=>{const W=y.id===x,O=y.messages.filter(be=>be.role==="user").length;return e.jsx("div",{onClick:()=>M(y.id),className:`group mx-1.5 mb-0.5 px-3 py-2 rounded-lg cursor-pointer transition-colors ${W?"bg-blue-50 border border-blue-200":"hover:bg-slate-50 border border-transparent"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-1.5",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-xs font-medium truncate leading-snug ${W?"text-blue-700":"text-slate-700"}`,children:y.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 flex items-center gap-0.5",children:[e.jsx(xt,{size:9}),wn(y.updatedAt,t)]}),O>0&&e.jsx("span",{className:"text-[10px] text-slate-300",children:t("aiChat.messageCount",{n:O})})]})]}),e.jsx("button",{onClick:be=>_(be,y.id),className:`p-1 rounded transition-colors shrink-0 ${W?"text-blue-400 hover:text-red-500 hover:bg-red-50":"text-transparent group-hover:text-slate-300 hover:!text-red-500 hover:!bg-red-50"}`,title:t("aiChat.deleteTopic"),children:e.jsx(ot,{size:12})})]})},y.id)})})}),h.length>0&&e.jsx("div",{className:"px-3 py-2 border-t border-slate-100 shrink-0",children:e.jsx("span",{className:"text-[10px] text-slate-400",children:t("aiChat.topicCount",{count:h.length})})})]})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("div",{className:"px-6 py-3 border-b border-slate-200 bg-white flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center",children:e.jsx(Lt,{className:"text-blue-600",size:18})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-bold text-slate-800",children:c?c.title:"AI Chat"}),e.jsx("p",{className:"text-[11px] text-slate-400",children:t("aiChat.askAnything")})]})]}),d.length>0&&e.jsxs("button",{onClick:R,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-slate-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors border border-slate-200 hover:border-blue-200",children:[e.jsx(Nt,{size:14}),t("aiChat.newTopic")]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 scrollbar-light",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-6 space-y-4",children:[d.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center mb-4",children:e.jsx(Qe,{className:"text-blue-500",size:28})}),e.jsx("h3",{className:"text-base font-bold text-slate-700 mb-2",children:t("aiChat.startChat")}),e.jsx("p",{className:"text-sm text-slate-400 max-w-md leading-relaxed mb-5",children:t("aiChat.emptyDescLong")}),e.jsx("div",{className:"flex flex-wrap gap-2 justify-center",children:[{key:"analyzeArch",label:t("aiChat.quickPrompts.analyzeArch")},{key:"findDuplicates",label:t("aiChat.quickPrompts.findDuplicates")},{key:"suggestOptimize",label:t("aiChat.quickPrompts.suggestOptimize")},{key:"summarize",label:t("aiChat.quickPromptSummarize")}].map(y=>e.jsx("button",{onClick:()=>{var W;Z(y.label),(W=z.current)==null||W.focus()},className:"text-xs px-3.5 py-2 rounded-lg bg-white border border-slate-200 text-slate-600 hover:bg-blue-50 hover:text-blue-700 hover:border-blue-200 transition-colors shadow-sm",children:y.label},y.key))})]}),d.map(y=>e.jsx("div",{className:`flex ${y.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] ${y.role==="user"?"bg-blue-600 text-white rounded-2xl rounded-tr-md px-4 py-2.5":y.role==="system"?"bg-slate-100 border border-slate-200 text-slate-600 rounded-2xl px-4 py-2.5 w-full":"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-4 py-3 shadow-sm w-full"}`,children:[y.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(rs,{size:13,className:"text-blue-500"}),e.jsx("span",{className:"text-[11px] font-bold text-blue-600",children:t("aiChat.aiAssistant")})]}),y.role==="assistant"&&!y.diff?e.jsx(gt,{content:y.content,className:"text-sm text-slate-700"}):e.jsx("p",{className:`text-sm leading-relaxed whitespace-pre-wrap ${y.role==="user"?"":"text-slate-600"}`,children:y.content}),y.diff&&y.diff.length>0&&e.jsx("div",{className:"space-y-2 mt-2",children:y.diff.map(W=>e.jsx(Nn,{d:W},W.field))})]})},y.id)),u&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-4 py-3 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{size:14,className:"animate-spin text-blue-500"}),e.jsx("span",{className:"text-sm text-slate-500",children:t("aiChat.thinking")}),g.current&&e.jsx("button",{onClick:()=>{var y;return(y=g.current)==null?void 0:y.abort()},className:"ml-1 px-1.5 py-0.5 text-[10px] font-bold text-red-500 border border-red-200 rounded hover:bg-red-50 transition-colors",children:t("common.stop")})]})})}),e.jsx("div",{ref:G})]})}),e.jsx("div",{className:"border-t border-slate-200 bg-white shrink-0",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-6 py-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{ref:z,value:P,onChange:y=>Z(y.target.value),onKeyDown:N,placeholder:t("aiChat.inputPlaceholder"),rows:2,className:"flex-1 px-4 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-400 resize-none placeholder:text-slate-300",disabled:u}),e.jsx("button",{onClick:m,disabled:!P.trim()||u,className:"self-stretch w-10 flex items-center justify-center rounded-xl bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white disabled:opacity-40 disabled:cursor-not-allowed transition-all shadow-sm shrink-0",children:e.jsx(Bs,{size:16})})]}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-1.5",children:t("aiChat.inputHint")})]})})]})]})},Cn=28,Sn=22,An=50,Dn=11,In=10,bt={depends_on:"#3b82f6",requires:"#3b82f6",extends:"#10b981",implements:"#10b981",inherits:"#10b981",enforces:"#f59e0b",related:"#8b5cf6",conflicts:"#ef4444",calls:"#06b6d4",prerequisite:"#f97316",data_flow_to:"#14b8a6",references:"#6b7280",alternative:"#a855f7",deprecated_by:"#dc2626",solves:"#22c55e"},Rn={depends_on:"依赖",requires:"需要",extends:"扩展",implements:"实现",inherits:"继承",enforces:"约束",related:"关联",conflicts:"冲突",calls:"调用",prerequisite:"前置",data_flow_to:"数据流",references:"引用",alternative:"替代",deprecated_by:"废弃",solves:"解决"},Ts=[{bg:"#eff6ff",border:"#bfdbfe",text:"#1d4ed8"},{bg:"#f0fdf4",border:"#bbf7d0",text:"#15803d"},{bg:"#fef3c7",border:"#fde68a",text:"#b45309"},{bg:"#fdf2f8",border:"#fbcfe8",text:"#be185d"},{bg:"#f5f3ff",border:"#ddd6fe",text:"#7c3aed"},{bg:"#ecfeff",border:"#a5f3fc",text:"#0e7490"},{bg:"#fff7ed",border:"#fed7aa",text:"#c2410c"},{bg:"#f0f9ff",border:"#bae6fd",text:"#0369a1"},{bg:"#fefce8",border:"#fef08a",text:"#a16207"},{bg:"#f1f5f9",border:"#cbd5e1",text:"#475569"}],Tn=[{bg:"rgba(59,130,246,0.08)",border:"rgba(59,130,246,0.25)",text:"#60a5fa"},{bg:"rgba(34,197,94,0.08)",border:"rgba(34,197,94,0.25)",text:"#4ade80"},{bg:"rgba(245,158,11,0.08)",border:"rgba(245,158,11,0.25)",text:"#fbbf24"},{bg:"rgba(236,72,153,0.08)",border:"rgba(236,72,153,0.25)",text:"#f472b6"},{bg:"rgba(139,92,246,0.08)",border:"rgba(139,92,246,0.25)",text:"#a78bfa"},{bg:"rgba(6,182,212,0.08)",border:"rgba(6,182,212,0.25)",text:"#22d3ee"},{bg:"rgba(249,115,22,0.08)",border:"rgba(249,115,22,0.25)",text:"#fb923c"},{bg:"rgba(14,165,233,0.08)",border:"rgba(14,165,233,0.25)",text:"#38bdf8"},{bg:"rgba(234,179,8,0.08)",border:"rgba(234,179,8,0.25)",text:"#facc15"},{bg:"rgba(148,163,184,0.08)",border:"rgba(148,163,184,0.25)",text:"#94a3b8"}];function It(t){return Math.min(An,Math.max(Sn,Cn+t*2))}function ya(t,s){return t.length<=s?t:t.substring(0,s-1)+"…"}function En(t,s,a,l){const d=new Map;for(const f of t)d.set(f.fromId,(d.get(f.fromId)||0)+1),d.set(f.toId,(d.get(f.toId)||0)+1);const i=[...d.keys()],u=[...new Set(i.map(f=>l[f]||"general"))].sort(),p=new Map,n=Math.ceil(Math.sqrt(u.length)),g=400;return u.forEach((f,h)=>{const x=h%n,c=Math.floor(h/n);p.set(f,{x:450+(x-(n-1)/2)*g,y:350+(c-(Math.ceil(u.length/n)-1)/2)*g})}),i.map(f=>{const h=l[f]||"general",x=p.get(h)||{x:450,y:350},c=Math.random()*2*Math.PI,j=40+Math.random()*80;return{id:f,label:s[f]||f,type:a[f]||"recipe",group:h,x:x.x+j*Math.cos(c),y:x.y+j*Math.sin(c),vx:0,vy:0,degree:d.get(f)||1}})}function Pn(t,s,a=200){const l=t.map(u=>({...u})),d=new Map(l.map(u=>[u.id,u]));function i(){const u=new Map;for(const p of l){const n=u.get(p.group);n?(n.x+=p.x,n.y+=p.y,n.count++):u.set(p.group,{x:p.x,y:p.y,count:1})}for(const[,p]of u)p.x/=p.count,p.y/=p.count;return u}for(let u=0;u<a;u++){const p=1-u/a,n=18e3*p,g=.015,f=.8,h=i();for(let c=0;c<l.length;c++)for(let j=c+1;j<l.length;j++){const w=l[c],C=l[j];let E=C.x-w.x,S=C.y-w.y,G=Math.sqrt(E*E+S*S)||1;const z=It(w.degree)+It(C.degree)+60,P=Math.max(G,1),Z=w.group===C.group?.6:1.4,X=n*Z/(P*P),H=G<z?(z-G)*.5:0,q=X+H,R=E/P*q,M=S/P*q;w.vx-=R,w.vy-=M,C.vx+=R,C.vy+=M}for(const c of s){const j=d.get(c.fromId),w=d.get(c.toId);if(!j||!w)continue;let C=w.x-j.x,E=w.y-j.y,S=Math.sqrt(C*C+E*E)||1;const G=j.group===w.group?140:280,z=g*(S-G),P=C/S*z,Z=E/S*z;j.vx+=P,j.vy+=Z,w.vx-=P,w.vy-=Z}const x=.008*p;for(const c of l){const j=h.get(c.group);j&&(c.vx+=(j.x-c.x)*x,c.vy+=(j.y-c.y)*x)}for(const c of l)c.vx*=f,c.vy*=f,c.x+=c.vx,c.y+=c.vy}return l}function Ln(t,s,a,l,d,i,u=0){const p=a-t,n=l-s,g=Math.sqrt(p*p+n*n)||1,f=p/g,h=n/g,x=t+f*d,c=s+h*d,j=a-f*i,w=l-h*i;if(u===0)return`M${x},${c}L${j},${w}`;const C=(x+j)/2+-h*u,E=(c+w)/2+f*u;return`M${x},${c}Q${C},${E},${j},${w}`}const Mn=()=>{const{t}=_e(),{isDark:s}=St(),a=s?Tn:Ts,l=r=>{const k={depends_on:"knowledgeGraph.relationDependsOn",requires:"knowledgeGraph.relationRequires",extends:"knowledgeGraph.relationExtends",implements:"knowledgeGraph.relationImplements",inherits:"knowledgeGraph.relationInherits",enforces:"knowledgeGraph.relationEnforces",related:"knowledgeGraph.relationAssociates",conflicts:"knowledgeGraph.relationConflicts",calls:"knowledgeGraph.relationCalls",prerequisite:"knowledgeGraph.relationPrerequisite",data_flow_to:"knowledgeGraph.relationDataFlow",references:"knowledgeGraph.relationReferences",alternative:"knowledgeGraph.relationAlternative",deprecated_by:"knowledgeGraph.relationDeprecatedBy",solves:"knowledgeGraph.relationSolves"};return k[r]?t(k[r]):Rn[r]||r},[d,i]=o.useState([]),[u,p]=o.useState({}),[n,g]=o.useState({}),[f,h]=o.useState({}),[x,c]=o.useState(null),[j,w]=o.useState(!0),[C,E]=o.useState(null),[S,G]=o.useState(null),[z,P]=o.useState(null),[Z,X]=o.useState(null),[H,q]=o.useState(!1),[R,M]=o.useState(null),[_,m]=o.useState(!1),[N,y]=o.useState(1),[W,O]=o.useState({x:0,y:0}),be=o.useRef(null),we=o.useRef(null),ye=o.useRef(!1),v=o.useRef({x:0,y:0}),ee=async()=>{var r,k;w(!0),E(null);try{const[b,B]=await Promise.all([se.getKnowledgeGraph(),se.getGraphStats()]);i(b.edges||[]),p(b.nodeLabels||{}),g(b.nodeTypes||{}),h(b.nodeCategories||{}),c(B)}catch(b){E(((k=(r=b.response)==null?void 0:r.data)==null?void 0:k.error)||b.message||t("knowledgeGraph.loadFailed"))}finally{w(!1)}};o.useEffect(()=>{ee()},[]),o.useEffect(()=>{se.getDiscoverRelationsStatus().then(r=>{r.status==="running"&&(q(!0),M(t("knowledgeGraph.discoverAnalyzing",{elapsed:r.elapsed??0})))}).catch(()=>{})},[]),o.useEffect(()=>{if(!H)return;let r=0;const k=240,b=setInterval(async()=>{if(r++,r>k){clearInterval(b),q(!1),m(!0),M(t("knowledgeGraph.discoverPollTimeout"));return}try{const B=await se.getDiscoverRelationsStatus();if(B.status==="done"){q(!1);const D=B.discovered??0,U=B.totalPairs??0,te=B.batchErrors??0;if(D===0&&te===0)m(!1),M(t("knowledgeGraph.discoverNoResults",{pairs:U}));else if(D===0&&te>0)m(!0),M(t("knowledgeGraph.discoverBatchErrors",{errors:te}));else{m(!1);const de=te>0?t("knowledgeGraph.discoverBatchFailed",{count:te}):"";M(t("knowledgeGraph.discoverSuccess",{count:D,pairs:U,failMsg:de}))}ee()}else if(B.status==="error"){q(!1),m(!0);const D=B.error||t("knowledgeGraph.unknownError");D.includes("AI Provider")||D.includes("API Key")?M(t("knowledgeGraph.discoverAiNotConfigured",{error:D})):D.includes("超时")||D.includes("timeout")?M(t("knowledgeGraph.discoverTimeout",{error:D})):M(t("knowledgeGraph.discoverFailed",{error:D}))}else B.status==="running"&&M(t("knowledgeGraph.discoverAnalyzing",{elapsed:B.elapsed??0}))}catch{}},3e3);return()=>clearInterval(b)},[H]);const ae=o.useCallback(async()=>{var r,k,b;M(null),m(!1);try{const B=await se.discoverRelations();if(B.status==="empty"){M(B.message||t("knowledgeGraph.discoverInsufficientRecipes"));return}if(B.status==="timeout"){m(!0),M(B.error||t("knowledgeGraph.discoverPreviousTimeout"));return}if(B.status==="running"){q(!0),M(t("knowledgeGraph.discoverRunning"));return}q(!0),M(t("knowledgeGraph.discoverStarted"))}catch(B){m(!0);const D=((b=(k=(r=B==null?void 0:B.response)==null?void 0:r.data)==null?void 0:k.error)==null?void 0:b.message)||B.message||t("knowledgeGraph.unknownError");D.includes("ChatAgent")||D.includes("AI Provider")?M(t("knowledgeGraph.discoverAiUnavailable",{error:D})):M(t("knowledgeGraph.discoverStartFailed",{error:D}))}},[t]),ue=o.useMemo(()=>{if(d.length===0)return[];const r=En(d,u,n,f);return Pn(r,d)},[d,u,n,f]),fe=o.useMemo(()=>{const r=new Map;for(const B of ue){const D=r.get(B.group)||[];D.push(B),r.set(B.group,D)}const k=[],b=[...r.keys()].sort();for(const B of b){const D=r.get(B);if(D.length===0)continue;let U=0,te=0;for(const I of D)U+=I.x,te+=I.y;U/=D.length,te/=D.length;let de=0,me=0;for(const I of D){const V=It(I.degree);de=Math.max(de,Math.abs(I.x-U)+V+35),me=Math.max(me,Math.abs(I.y-te)+V+35)}k.push({group:B,cx:U,cy:te,rx:Math.max(de,60),ry:Math.max(me,60),count:D.length})}return k},[ue]),he=o.useMemo(()=>{const r=[...new Set(ue.map(b=>b.group))].sort(),k={};return r.forEach((b,B)=>{k[b]=a[B%a.length]}),k},[ue,a]),ce=o.useMemo(()=>{if(ue.length===0)return{x:0,y:0,w:900,h:700};let r=1/0,k=1/0,b=-1/0,B=-1/0;for(const D of ue){const U=It(D.degree);r=Math.min(r,D.x-U-80),k=Math.min(k,D.y-U-40),b=Math.max(b,D.x+U+80),B=Math.max(B,D.y+U+40)}return{x:r,y:k,w:b-r,h:B-k}},[ue]),je=o.useMemo(()=>new Map(ue.map(r=>[r.id,r])),[ue]),{connectedEdgeIds:$,connectedNodeIds:K}=o.useMemo(()=>{const r=S||z;if(!r)return{connectedEdgeIds:new Set,connectedNodeIds:new Set};const k=new Set,b=new Set([r]);for(const B of d)(B.fromId===r||B.toId===r)&&(k.add(B.id),b.add(B.fromId),b.add(B.toId));return{connectedEdgeIds:k,connectedNodeIds:b}},[S,z,d]),xe=o.useMemo(()=>{const r=new Map,k=new Map;for(const B of d){const D=[B.fromId,B.toId].sort().join("|"),U=r.get(D)||0;k.set(B.id,U),r.set(D,U+1)}const b=new Map;for(const B of d){const D=[B.fromId,B.toId].sort().join("|"),U=r.get(D)||1;if(U<=1){b.set(B.id,0);continue}const te=k.get(B.id)||0;b.set(B.id,(te-(U-1)/2)*40)}return b},[d]),[L,T]=o.useState(new Set);o.useEffect(()=>{T(new Set(d.map(r=>r.relation)))},[d]);const Q=o.useMemo(()=>d.filter(r=>L.has(r.relation)),[d,L]),ie=r=>{T(k=>{const b=new Set(k);return b.has(r)?b.delete(r):b.add(r),b})},ke=o.useCallback(r=>{r.button===0&&(ye.current=!0,v.current={x:r.clientX,y:r.clientY})},[]),Ue=o.useCallback(r=>{if(!ye.current)return;const k=r.clientX-v.current.x,b=r.clientY-v.current.y;v.current={x:r.clientX,y:r.clientY},O(B=>({x:B.x+k,y:B.y+b}))},[]),Ie=o.useCallback(()=>{ye.current=!1},[]),ne=o.useCallback(r=>{r.preventDefault();const k=r.deltaY>0?-.1:.1;y(b=>Math.min(3,Math.max(.2,b+k)))},[]),ve=r=>`kg-arrow-${r.replace(/[^a-z_]/g,"")}`;if(j)return e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})});if(C)return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4",children:[e.jsx("p",{className:"text-red-500",children:C}),e.jsx("button",{onClick:ee,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:t("knowledgeGraph.retry")})]});if(d.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-slate-500",children:[e.jsx(Ls,{size:48,className:"text-slate-300"}),e.jsx("p",{className:"text-lg font-medium",children:t("knowledgeGraph.empty")}),e.jsx("p",{className:"text-sm text-center max-w-md",children:t("knowledgeGraph.emptyDesc")}),R&&e.jsx("p",{className:`text-sm ${_?"text-red-500":"text-green-600"}`,children:R}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:ae,disabled:H,className:"px-4 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 transition-colors flex items-center gap-2 disabled:opacity-50",children:H?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"})," ",t("knowledgeGraph.discovering")]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{size:F.sm})," ",t("knowledgeGraph.discoverRelations")]})}),e.jsxs("button",{onClick:ee,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2",children:[e.jsx(yt,{size:F.sm})," ",t("knowledgeGraph.refresh")]})]})]});const He=[...new Set(d.map(r=>r.relation))].sort(),Ne=!!(S||z);return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ls,{size:F.lg,className:"text-blue-600"}),e.jsx("h2",{className:`text-lg font-bold ${s?"text-slate-100":"text-slate-800"}`,children:t("knowledgeGraph.title")}),x&&e.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${s?"text-slate-400 bg-slate-700/60":"text-slate-500 bg-slate-100"}`,children:t("knowledgeGraph.statsLabel",{nodes:ue.length,edges:x.totalEdges})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>y(r=>Math.min(r+.2,3)),className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.zoomIn"),children:e.jsx(El,{size:F.sm})}),e.jsx("button",{onClick:()=>y(r=>Math.max(r-.2,.2)),className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.zoomOut"),children:e.jsx(Pl,{size:F.sm})}),e.jsx("button",{onClick:()=>{y(1),O({x:0,y:0})},className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.resetView"),children:e.jsx(Cs,{size:F.sm})}),e.jsx("button",{onClick:ee,className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.refresh"),children:e.jsx(yt,{size:F.sm})}),e.jsx("button",{onClick:ae,disabled:H,className:`flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 ${s?"bg-violet-500/15 hover:bg-violet-500/25 text-violet-400":"bg-violet-50 hover:bg-violet-100 text-violet-700"}`,title:t("knowledgeGraph.discoverTooltip"),children:H?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-3 w-3 border-b-2 border-violet-600"})," ",t("knowledgeGraph.discovering")]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{size:F.sm})," ",t("knowledgeGraph.discoverRelations")]})})]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-3 flex-shrink-0",children:He.map(r=>{var k;return e.jsxs("button",{onClick:()=>ie(r),className:`flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium transition-all border ${L.has(r)?"border-transparent shadow-sm":s?"border-slate-600 bg-slate-800 text-slate-500 opacity-40":"border-slate-200 bg-white text-slate-400 opacity-40"}`,style:L.has(r)?{backgroundColor:(bt[r]||"#6b7280")+"18",color:bt[r]||"#6b7280"}:{},children:[e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:bt[r]||"#6b7280"}}),l(r),((k=x==null?void 0:x.byRelation)==null?void 0:k[r])!=null&&e.jsxs("span",{className:"opacity-60",children:["(",x.byRelation[r],")"]})]},r)})}),e.jsxs("div",{ref:we,className:`flex-1 rounded-xl border overflow-hidden relative min-h-0 ${s?"border-slate-700 bg-[#13151c]":"border-slate-200 bg-gradient-to-br from-slate-50 to-white"}`,style:{cursor:ye.current?"grabbing":"grab"},onWheel:ne,children:[e.jsxs("svg",{ref:be,width:"100%",height:"100%",viewBox:`${ce.x} ${ce.y} ${ce.w} ${ce.h}`,onMouseDown:ke,onMouseMove:Ue,onMouseUp:Ie,onMouseLeave:Ie,style:{transform:`scale(${N}) translate(${W.x/N}px, ${W.y/N}px)`},children:[e.jsxs("defs",{children:[He.map(r=>e.jsx("marker",{id:ve(r),viewBox:"0 0 10 8",refX:"10",refY:"4",markerWidth:"7",markerHeight:"5",orient:"auto-start-reverse",children:e.jsx("path",{d:"M0,0 L10,4 L0,8 Z",fill:bt[r]||"#6b7280"})},r)),e.jsxs("filter",{id:"kg-glow",x:"-50%",y:"-50%",width:"200%",height:"200%",children:[e.jsx("feGaussianBlur",{in:"SourceAlpha",stdDeviation:"4",result:"blur"}),e.jsx("feFlood",{floodColor:"#3b82f6",floodOpacity:"0.3",result:"color"}),e.jsx("feComposite",{in:"color",in2:"blur",operator:"in",result:"shadow"}),e.jsxs("feMerge",{children:[e.jsx("feMergeNode",{in:"shadow"}),e.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),e.jsx("g",{children:fe.map(r=>{const k=he[r.group]||Ts[0];return e.jsxs("g",{children:[e.jsx("ellipse",{cx:r.cx,cy:r.cy,rx:r.rx,ry:r.ry,fill:k.bg,stroke:k.border,strokeWidth:1.5,strokeDasharray:"6,4",opacity:.6}),e.jsxs("text",{x:r.cx,y:r.cy-r.ry+14,textAnchor:"middle",fontSize:11,fontWeight:600,fill:k.text,opacity:.8,style:{pointerEvents:"none",userSelect:"none"},children:[r.group||"general"," (",r.count,")"]})]},r.group)})}),e.jsx("g",{children:Q.map(r=>{const k=je.get(r.fromId),b=je.get(r.toId);if(!k||!b)return null;const B=Ne?$.has(r.id):!1,D=Z===r.id,U=Ne?B?.85:.06:D?.9:.35,te=It(k.degree),de=It(b.degree),me=xe.get(r.id)||0,I=Ln(k.x,k.y,b.x,b.y,te,de,me);return e.jsxs("g",{children:[e.jsx("path",{d:I,fill:"none",stroke:"transparent",strokeWidth:12,onMouseEnter:()=>X(r.id),onMouseLeave:()=>X(null),style:{cursor:"pointer"}}),e.jsx("path",{d:I,fill:"none",stroke:bt[r.relation]||"#6b7280",strokeWidth:D||B?2:1.2,opacity:U,markerEnd:`url(#${ve(r.relation)})`,strokeDasharray:r.relation==="related"?"6,3":void 0,style:{transition:"opacity 0.25s, stroke-width 0.15s",pointerEvents:"none"}}),D&&(()=>{const V=(k.x+b.x)/2,Ce=(k.y+b.y)/2;return e.jsxs("g",{children:[e.jsx("rect",{x:V-24,y:Ce-16,width:48,height:18,rx:4,fill:s?"#252526":"white",stroke:bt[r.relation]||"#6b7280",strokeWidth:.8,opacity:.95}),e.jsx("text",{x:V,y:Ce-4,textAnchor:"middle",fontSize:9,fontWeight:600,fill:bt[r.relation]||"#6b7280",children:l(r.relation)})]})})()]},r.id)})}),e.jsx("g",{children:ue.map(r=>{const k=It(r.degree),b=S===r.id,B=Ne&&K.has(r.id),D=b||r.id===z,U=Ne&&!B,te=U?.12:1,de=he[r.group]||Ts[0],me=D?de.border:de.bg,I=D?de.text:de.border,V=D?"#ffffff":de.text,Ce=D?de.text:s?"#9ca3af":"#64748b";return e.jsxs("g",{onClick:Ae=>{Ae.stopPropagation(),G(b?null:r.id)},onMouseEnter:()=>P(r.id),onMouseLeave:()=>P(null),style:{cursor:"pointer",transition:"opacity 0.25s"},opacity:te,filter:D?"url(#kg-glow)":void 0,children:[e.jsx("circle",{cx:r.x,cy:r.y,r:k,fill:me,stroke:I,strokeWidth:D?2.5:1.5}),e.jsx("text",{x:r.x,y:r.y+4,textAnchor:"middle",fontSize:Math.min(Dn,k*.7),fill:V,fontWeight:700,style:{pointerEvents:"none",userSelect:"none"},children:ya(r.label,4).toUpperCase()}),e.jsx("text",{x:r.x,y:r.y+k+14,textAnchor:"middle",fontSize:In,fill:Ce,fontWeight:D?600:400,style:{pointerEvents:"none",userSelect:"none"},children:ya(r.label,18)}),r.degree>=3&&!U&&e.jsxs("g",{children:[e.jsx("circle",{cx:r.x+k*.7,cy:r.y-k*.7,r:8,fill:"#3b82f6",stroke:s?"#1e1e1e":"white",strokeWidth:1.5}),e.jsx("text",{x:r.x+k*.7,y:r.y-k*.7+3.5,textAnchor:"middle",fontSize:8,fill:"white",fontWeight:700,style:{pointerEvents:"none"},children:r.degree})]})]},r.id)})})]}),S&&e.jsx("button",{className:`absolute top-2 right-2 text-xs px-2 py-1 rounded-md shadow-sm border ${s?"text-slate-400 hover:text-slate-200 bg-[#252526]/90 border-slate-600":"text-slate-400 hover:text-slate-600 bg-white/90 border-slate-200"}`,onClick:()=>G(null),children:t("knowledgeGraph.cancelSelection")})]}),S&&e.jsxs("div",{className:`mt-3 p-4 rounded-xl border shadow-sm flex-shrink-0 max-h-48 overflow-y-auto scrollbar-light ${s?"bg-[#1e1e1e] border-slate-700":"bg-white border-slate-200"}`,children:[e.jsxs("div",{className:`flex items-center gap-2 mb-3 pb-2 border-b ${s?"border-slate-700":"border-slate-100"}`,children:[e.jsx(_a,{size:14,className:"text-blue-500"}),e.jsx("h3",{className:`font-semibold text-sm ${s?"text-slate-200":"text-slate-800"}`,children:u[S]||S}),e.jsxs("span",{className:"text-[10px] text-slate-400 ml-auto",children:["ID: ",S]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 font-medium",children:t("knowledgeGraph.outEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[d.filter(r=>r.fromId===S&&L.has(r.relation)).map(r=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:bt[r.relation]||"#6b7280"}}),e.jsx("span",{className:"text-slate-500",children:l(r.relation)}),e.jsx("span",{className:"text-slate-400",children:"→"}),e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>G(r.toId),children:u[r.toId]||r.toId.substring(0,16)})]},r.id)),d.filter(r=>r.fromId===S&&L.has(r.relation)).length===0&&e.jsx("li",{className:"text-slate-400",children:t("knowledgeGraph.none")})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 font-medium",children:t("knowledgeGraph.inEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[d.filter(r=>r.toId===S&&L.has(r.relation)).map(r=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>G(r.fromId),children:u[r.fromId]||r.fromId.substring(0,16)}),e.jsx("span",{className:"text-slate-400",children:"→"}),e.jsx("span",{className:"text-slate-500",children:l(r.relation)}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:bt[r.relation]||"#6b7280"}})]},r.id)),d.filter(r=>r.toId===S&&L.has(r.relation)).length===0&&e.jsx("li",{className:"text-slate-400",children:t("knowledgeGraph.none")})]})]})]})]})]})},mt={pending:{labelKey:"lifecycle.pending",color:"text-amber-700",bg:"bg-amber-50",border:"border-amber-200",icon:xt},active:{labelKey:"lifecycle.active",color:"text-green-700",bg:"bg-green-50",border:"border-green-200",icon:cs},deprecated:{labelKey:"lifecycle.deprecated",color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-200",icon:Fs}},Jt={rule:{labelKey:"kind.rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:ut},pattern:{labelKey:"kind.pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:jt},fact:{labelKey:"kind.fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:tt}},Fn={pending:[{action:"publish",labelKey:"knowledge.actionPublish",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:cs},{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:Fs,needsReason:!0}],active:[{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:Fs,needsReason:!0}],deprecated:[{action:"reactivate",labelKey:"knowledge.actionReactivate",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:Ra}]};function Yt(t,s){if(!t)return"";const a=t<1e12?t*1e3:t,l=new Date(a);if(isNaN(l.getTime())||l.getFullYear()<2e3)return"";const i=Date.now()-a;if(i<0)return l.toLocaleDateString();const u=Math.floor(i/6e4);if(u<1)return s("candidates.timeJustNow");if(u<60)return s("candidates.timeMinutesAgo",{n:u});const p=Math.floor(u/60);if(p<24)return s("candidates.timeHoursAgo",{n:p});const n=Math.floor(p/24);return n<7?s("candidates.timeDaysAgo",{n}):l.toLocaleDateString()}function zn(t){return t==null?{ring:"stroke-slate-200",text:"text-slate-400",bg:"bg-slate-50",labelKey:""}:t>=.8?{ring:"stroke-emerald-500",text:"text-emerald-700",bg:"bg-emerald-50",labelKey:"candidates.confidenceHighLabel"}:t>=.6?{ring:"stroke-blue-500",text:"text-blue-700",bg:"bg-blue-50",labelKey:"candidates.confidenceMediumLabel"}:t>=.4?{ring:"stroke-amber-500",text:"text-amber-700",bg:"bg-amber-50",labelKey:"candidates.confidenceMediumLowLabel"}:{ring:"stroke-red-500",text:"text-red-700",bg:"bg-red-50",labelKey:"candidates.confidenceLowLabel"}}function _n(t,s=4){return t?Us(t).split(`
115
+ `,style:{paddingLeft:`${ne.depth*14+10}px`},children:[e.jsx(wt,{size:z.sm,className:ne.hasSourceFiles?"text-emerald-500 shrink-0":"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-sm font-medium flex-1 truncate",children:ne.name}),ne.hasSourceFiles&&ne.language!=="unknown"&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${pe}`,children:ba[ne.language]||ne.language.toUpperCase()}),ne.hasSourceFiles&&e.jsx("span",{className:"text-[10px] text-slate-400 shrink-0",children:E("moduleExplorer.sourceFileCount",{count:ne.sourceFileCount})}),e.jsx(rt,{size:12,className:"text-slate-300 shrink-0"})]},ne.path)}),e.jsx("div",{className:"px-3 py-2 text-[10px] text-slate-400 text-center",children:E("moduleExplorer.selectFolderHint")})]})})]}),e.jsxs("div",{className:"flex-1 bg-white rounded-xl border border-slate-200 flex flex-col overflow-hidden relative",children:[e.jsx("div",{className:"p-4 bg-slate-50 border-b border-slate-200 font-bold text-sm flex justify-between items-center",children:e.jsxs("div",{className:"flex items-center gap-2",children:[a==="__project__"?e.jsxs(e.Fragment,{children:[e.jsx(lt,{size:z.md,className:"text-indigo-500"}),e.jsx("span",{children:E("moduleExplorer.fullProjectResults")}),u.length>0&&e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 border border-indigo-200",children:"PROJECT"})]}):a?e.jsxs(e.Fragment,{children:[e.jsx(et,{size:z.md,className:"text-blue-500"}),e.jsx("span",{children:E("moduleExplorer.moduleLabel",{name:a})}),u.length>0&&e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 border border-blue-200",children:"MODULE"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Et,{size:z.md,className:"text-slate-400"}),e.jsx("span",{children:E("moduleExplorer.reviewResults")})]}),u.length>0&&e.jsxs("span",{className:"text-slate-400 font-normal text-xs ml-1",children:["(",E("moduleExplorer.resultsCount",{count:u.length}),(Ue=u[0])!=null&&Ue.trigger?E("moduleExplorer.candidateSuffix"):"",")"]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-8 relative",children:[l&&e.jsxs("div",{className:"absolute inset-0 bg-white/90 backdrop-blur-[2px] z-10 flex flex-col items-center justify-center text-blue-600 px-4 xl:px-8 overflow-y-auto",children:[e.jsxs("div",{className:"relative mb-6",children:[e.jsx("div",{className:"w-16 h-16 border-4 border-blue-100 border-t-blue-600 rounded-full animate-spin"}),e.jsx(ns,{size:z.xxl,className:"absolute inset-0 m-auto text-blue-600 animate-pulse"})]}),e.jsx("p",{className:"font-bold text-lg animate-pulse mb-1",children:a==="__project__"?E("moduleExplorer.fullProjectScanning"):E("moduleExplorer.moduleScanLabel",{name:a||"..."})}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:d.status}),e.jsx("div",{className:"w-full max-w-md bg-slate-100 rounded-full h-2.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-600 rounded-full transition-all duration-500 ease-out",style:{width:`${Math.min(d.total?d.current/d.total*100:0,98)}%`}})}),e.jsx("p",{className:"text-xs text-slate-400 mt-3",children:d.total?`${Math.round(d.current/d.total*100)}%`:"0%"})]}),!l&&u.length===0&&e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-slate-400 text-center",children:[e.jsx(ws,{size:z.xxxl,className:"mb-4 opacity-20"}),e.jsx("p",{className:"font-medium text-slate-600",children:E("moduleExplorer.knowledgeExtract")}),e.jsx("p",{className:"text-xs mt-2 max-w-sm leading-relaxed",children:E("moduleExplorer.knowledgeExtractHint")})]}),!l&&a==="__project__"&&(p==null?void 0:p.summary)&&e.jsxs("div",{className:`rounded-xl border p-4 ${p.summary.totalViolations>0?"border-amber-200 bg-amber-50":"border-emerald-200 bg-emerald-50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(dt,{size:z.md,className:p.summary.totalViolations>0?"text-amber-600":"text-emerald-600"}),e.jsx("span",{className:"text-sm font-bold text-slate-700",children:E("moduleExplorer.guardAuditSummary")}),e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 border border-indigo-200",children:"PROJECT SCAN"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 xl:gap-6 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-slate-500",children:E("moduleExplorer.auditedFiles")}),e.jsx("span",{className:"font-bold text-slate-700",children:p.summary.totalFiles})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-slate-500",children:E("moduleExplorer.totalViolationsLabel")}),e.jsx("span",{className:`font-bold ${p.summary.totalViolations>0?"text-amber-700":"text-emerald-700"}`,children:p.summary.totalViolations})]}),p.summary.errors>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Rt,{size:z.sm,className:"text-red-500"}),e.jsx("span",{className:"font-bold text-red-700",children:E("moduleExplorer.errorsCount",{count:p.summary.errors})})]}),p.summary.warnings>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Rt,{size:z.sm,className:"text-amber-500"}),e.jsx("span",{className:"font-bold text-amber-700",children:E("moduleExplorer.warningsCount",{count:p.summary.warnings})})]})]})]}),u.map((ne,pe)=>e.jsx(dn,{res:ne,index:pe,editingCodeIndex:Z,setEditingCodeIndex:X,expandedEditIndex:H,setExpandedEditIndex:q,similarityMap:I,handleUpdateScanResult:f,handleSaveExtracted:h,handlePromoteToCandidate:x,openCompare:we,isSavingRecipe:T},pe))]})]}),N&&e.jsx(pn,{data:N,onClose:()=>j(null),onDataChange:j,recipes:w,handleSaveExtracted:h,handleDeleteCandidate:i,onEditRecipe:y,isSavingRecipe:T}),e.jsx(ln,{isOpen:W,onClose:()=>O(!1),targetName:je,currentFile:ye,language:((Se=s.find(ne=>ne.name===a))==null?void 0:Se.language)||"unknown",onSelectRecipe:ne=>{}})]})},mn=72,hn=52,Ns=24,es=40,Xa=36,Tt=140,Zt=40,ts=8;function gn(t,s){const a=new Set(t.map(p=>p.id)),l=new Map;for(const p of s)!a.has(p.from)||!a.has(p.to)||(l.has(p.from)||l.set(p.from,[]),l.get(p.from).push(p.to));const d=new Map,c=new Set;function u(p){if(d.has(p))return d.get(p);if(c.has(p))return 0;c.add(p);const n=l.get(p);if(!n||n.length===0)return d.set(p,0),c.delete(p),0;const g=1+Math.max(...n.map(u));return d.set(p,g),c.delete(p),g}return t.forEach(p=>u(p.id)),d}function bn(t){return Math.ceil(t/ts)}function fn(t,s){const a=gn(t,s),l=new Map;for(const h of t){const x=a.get(h.id)??0;l.has(x)||l.set(x,[]),l.get(x).push(h.id)}const d=[...new Set(a.values())].sort((h,x)=>h-x),c=[...d].reverse(),u=new Map,p=new Map,n=Math.min(ts,Math.max(...d.map(h=>(l.get(h)??[]).length),1)),g=(n-1)*Ns+n*Tt;let f=es;return c.forEach(h=>{const x=l.get(h)??[],i=bn(x.length),y=f;for(let w=0;w<i;w++){const T=x.slice(w*ts,(w+1)*ts),A=(T.length-1)*Ns+T.length*Tt,G=(g-A)/2;T.forEach((_,E)=>{const Z=es+Xa+G+E*(Tt+Ns)+Tt/2,X=f+Zt/2;u.set(_,{x:Z,y:X})}),f+=w<i-1?hn:mn}const k=f-y;p.set(h,{y,h:k})}),{positions:u,tiers:a,tierOrder:d,tierYRanges:p}}const yn=()=>{const{t}=_e(),{isDark:s}=St(),[a,l]=o.useState(null),[d,c]=o.useState(!0),[u,p]=o.useState(null),[n,g]=o.useState(null),[f,h]=o.useState("package"),[x,i]=o.useState("all"),y=async()=>{var v,ee;c(!0),p(null);try{const te=await ae.getDepGraph(f);l({nodes:Array.isArray(te==null?void 0:te.nodes)?te.nodes:[],edges:Array.isArray(te==null?void 0:te.edges)?te.edges:[],projectRoot:(te==null?void 0:te.projectRoot)??null,generatedAt:te==null?void 0:te.generatedAt})}catch(te){p(((ee=(v=te.response)==null?void 0:v.data)==null?void 0:ee.error)||te.message||"Failed to load dependency graph")}finally{c(!1)}};o.useEffect(()=>{y()},[f]);const k=Array.isArray(a==null?void 0:a.nodes)?a.nodes:[],w=Array.isArray(a==null?void 0:a.edges)?a.edges:[],T=k.some(v=>v.type==="internal"||v.type==="external"),A=o.useMemo(()=>!T||x==="all"?k:x==="internal"?k.filter(v=>v.type!=="external"):k.filter(v=>v.type!=="internal"),[k,x,T]),G=o.useMemo(()=>new Set(A.map(v=>v.id)),[A]),_=o.useMemo(()=>w.filter(v=>G.has(v.from)||G.has(v.to)),[w,G]),{positions:E,tiers:Z,tierOrder:X,tierYRanges:H}=o.useMemo(()=>fn(A,_),[A,_]),q=o.useMemo(()=>{const v=new Map;return A.forEach(ee=>{const te=Z.get(ee.id)??0;v.has(te)||v.set(te,[]),v.get(te).push(ee.id)}),v},[A,Z]),I=o.useMemo(()=>[...X].reverse(),[X]),{dependsOn:L,dependedBy:$}=o.useMemo(()=>{const v=new Map,ee=new Map;return _.forEach(te=>{v.has(te.from)||v.set(te.from,[]),v.get(te.from).push(te.to),ee.has(te.to)||ee.set(te.to,[]),ee.get(te.to).push(te.from)}),{dependsOn:v,dependedBy:ee}},[_]),m=Math.min(ts,Math.max(...X.map(v=>(q.get(v)??[]).length),1)),j=(m-1)*Ns+m*Tt+Xa*2,W=Math.max(600,es*2+j),O=Math.max(...[...E.values()].map(v=>v.y),0),ye=Math.max(420,O+Zt/2+es+20),Ne=s?[{bg:"rgba(59, 130, 246, 0.14)",border:"rgba(59, 130, 246, 0.40)",text:"rgb(147 197 253)"},{bg:"rgba(34, 197, 94, 0.14)",border:"rgba(34, 197, 94, 0.40)",text:"rgb(134 239 172)"},{bg:"rgba(234, 179, 8, 0.14)",border:"rgba(234, 179, 8, 0.40)",text:"rgb(253 224 71)"},{bg:"rgba(249, 115, 22, 0.14)",border:"rgba(249, 115, 22, 0.40)",text:"rgb(253 186 116)"},{bg:"rgba(139, 92, 246, 0.14)",border:"rgba(139, 92, 246, 0.40)",text:"rgb(196 181 253)"}]:[{bg:"rgb(239 246 255)",border:"rgb(147 197 253)",text:"rgb(30 64 175)"},{bg:"rgb(240 253 244)",border:"rgb(134 239 172)",text:"rgb(22 101 52)"},{bg:"rgb(254 249 195)",border:"rgb(253 224 71)",text:"rgb(113 63 18)"},{bg:"rgb(254 243 199)",border:"rgb(253 186 116)",text:"rgb(154 52 18)"},{bg:"rgb(243 232 255)",border:"rgb(216 180 254)",text:"rgb(91 33 182)"}],je=v=>Ne[Math.min(v,Ne.length-1)]??Ne[0];return d?e.jsx("div",{className:"flex items-center justify-center min-h-[320px]",children:e.jsx("div",{className:"animate-spin rounded-full h-10 w-10 border-2 border-blue-600 border-t-transparent"})}):u?e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-6 text-red-700 shadow-sm",children:[e.jsx("p",{children:u}),e.jsx("button",{type:"button",onClick:y,className:"mt-4 px-4 py-2 rounded-lg bg-red-100 hover:bg-red-200 text-red-800 font-medium text-sm transition-colors",children:t("depGraph.retry")})]}):!a||k.length===0?e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50 p-8 text-slate-600 shadow-sm",children:[e.jsx("p",{className:"font-medium text-slate-700",children:t("depGraph.noDataTitle")}),e.jsx("p",{className:"mt-2 text-sm",children:t("depGraph.noDataDesc")})]}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap justify-between items-center gap-3 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0",children:e.jsx(lt,{className:"text-blue-600",size:20})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-slate-800",children:t("depGraph.title")}),e.jsxs("p",{className:"text-xs text-slate-400 mt-0.5 truncate",children:[t("depGraph.visualization"),a.projectRoot&&e.jsxs("span",{className:"ml-1",children:["· ",a.projectRoot]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[T&&e.jsx("div",{className:"flex items-center border border-slate-200 rounded-lg overflow-hidden text-xs",children:["all","internal","external"].map(v=>e.jsx("button",{type:"button",onClick:()=>i(v),className:`px-3 py-1.5 font-medium transition-colors ${x===v?"bg-blue-600 text-white":"bg-white text-slate-600 hover:bg-slate-50"}`,children:t(v==="all"?"depGraph.filterAll":v==="internal"?"depGraph.filterInternal":"depGraph.filterExternal")},v))}),e.jsxs("button",{type:"button",onClick:()=>{y()},className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-slate-600 bg-slate-50 border border-slate-200 hover:bg-slate-100",children:[e.jsx(yt,{size:14})," ",t("depGraph.refresh")]}),e.jsxs("div",{className:"flex items-center gap-2 xl:gap-3 text-xs flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-50 border border-slate-100",children:[e.jsx(lt,{size:14,className:"text-slate-400"}),e.jsxs("span",{className:"text-slate-500",children:[t("depGraph.packages")," ",e.jsx("strong",{className:"text-slate-700",children:A.length})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-100",children:[e.jsx("span",{className:"text-emerald-500",children:t("depGraph.dependencies")}),e.jsx("strong",{className:"text-emerald-700",children:_.length})]}),a.generatedAt&&e.jsx("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-blue-50 border border-blue-100",children:e.jsx("span",{className:"text-blue-500",children:new Date(a.generatedAt).toLocaleString("zh-CN")})})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1 space-y-6",children:[T&&e.jsxs("div",{className:"flex items-center gap-4 text-xs text-slate-500 px-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-slate-300 bg-white"})," ",t("depGraph.projectRoot")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-green-400 bg-green-50"})," ",t("depGraph.filterInternal")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-amber-400 bg-amber-50 border-dashed"})," ",t("depGraph.filterExternal")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-amber-400 bg-amber-50 border-dashed opacity-50"})," ",t("depGraph.labelIndirect")]})]}),e.jsxs("div",{className:`rounded-xl border overflow-auto shadow-sm min-h-[480px] flex items-center justify-center relative ${s?"border-slate-700 bg-[#13151c]":"border-slate-200 bg-slate-50/50"}`,children:[e.jsxs("svg",{width:"100%",height:ye,viewBox:`0 0 ${W} ${ye}`,className:"block min-h-[480px] w-full",style:{maxHeight:640},children:[e.jsx("defs",{children:e.jsx("filter",{id:"nodeShadow",x:"-20%",y:"-20%",width:"140%",height:"140%",children:e.jsx("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.12"})})}),I.map((v,ee)=>{const te=je(ee),de=H.get(v);return de?e.jsx("rect",{x:es,y:de.y-Zt/2-4,width:j,height:de.h+8,rx:8,fill:te.bg,stroke:te.border,strokeWidth:s?1.5:1,opacity:s?1:.6},v):null}),A.map(v=>{const ee=E.get(v.id);if(!ee)return null;const te=Z.get(v.id)??0,de=je(I.indexOf(te)),ve=v.label.length>14?v.label.slice(0,13)+"…":v.label,fe=n===v.id,ie=n?(L.get(n)??[]).includes(v.id):!1,be=n?($.get(n)??[]).includes(v.id):!1,B=n&&!fe&&!ie&&!be,K=v.type==="external"?s?{fill:"rgba(234, 179, 8, 0.1)",stroke:"rgb(202 138 4)",text:"rgb(253 224 71)",badge:"EXT"}:{fill:"rgb(254 252 232)",stroke:"rgb(234 179 8)",text:"rgb(113 63 18)",badge:"EXT"}:v.type==="internal"?s?{fill:"rgba(34, 197, 94, 0.1)",stroke:"rgb(22 163 74)",text:"rgb(134 239 172)",badge:""}:{fill:"rgb(240 253 244)",stroke:"rgb(74 222 128)",text:"rgb(22 101 52)",badge:""}:s?{fill:"#1e2433",stroke:de.border,text:de.text,badge:""}:{fill:"white",stroke:de.border,text:de.text,badge:""},xe=n?fe?s?{fill:"#283040",stroke:"rgb(59 130 246)",text:"rgb(147 197 253)",strokeWidth:3,opacity:1}:{fill:"white",stroke:"rgb(59 130 246)",text:"rgb(30 64 175)",strokeWidth:3,opacity:1}:ie?s?{fill:"rgba(34, 197, 94, 0.12)",stroke:"rgb(34 197 94)",text:"rgb(134 239 172)",strokeWidth:2,opacity:1}:{fill:"rgb(240 253 244)",stroke:"rgb(34 197 94)",text:"rgb(22 101 52)",strokeWidth:2,opacity:1}:be?s?{fill:"rgba(139, 92, 246, 0.12)",stroke:"rgb(139 92 246)",text:"rgb(196 181 253)",strokeWidth:2,opacity:1}:{fill:"rgb(245 243 255)",stroke:"rgb(139 92 246)",text:"rgb(91 33 182)",strokeWidth:2,opacity:1}:s?{fill:"#1a1b23",stroke:"rgb(51 65 85)",text:"rgb(100 116 139)",strokeWidth:1,opacity:.6}:{fill:"rgb(248 250 252)",stroke:"rgb(203 213 225)",text:"rgb(148 163 184)",strokeWidth:1,opacity:.6}:{fill:K.fill,stroke:K.stroke,text:K.text,strokeWidth:2,opacity:v.indirect?.55:1};return e.jsxs("g",{style:{cursor:"pointer",opacity:xe.opacity},onClick:()=>g(fe?null:v.id),children:[e.jsx("rect",{x:ee.x-Tt/2,y:ee.y-Zt/2,width:Tt,height:Zt,rx:10,ry:10,fill:xe.fill,stroke:xe.stroke,strokeWidth:xe.strokeWidth,filter:B?void 0:"url(#nodeShadow)",strokeDasharray:v.type==="external"?"4 2":void 0}),e.jsx("text",{x:ee.x,y:ee.y+(K.badge?-2:0),textAnchor:"middle",dominantBaseline:"middle",fontSize:"12",fontWeight:"600",fill:xe.text,pointerEvents:"none",children:ve}),K.badge&&e.jsx("text",{x:ee.x,y:ee.y+12,textAnchor:"middle",dominantBaseline:"middle",fontSize:"8",fontWeight:"500",fill:K.text,opacity:.6,pointerEvents:"none",children:K.badge})]},v.id)})]}),n&&e.jsxs("div",{className:"absolute top-4 right-4 w-72 rounded-xl border border-slate-200 bg-white shadow-lg z-10 p-4",role:"dialog","aria-label":t("depGraph.dependencies"),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 pb-2 border-b border-slate-100",children:[e.jsx("span",{className:"font-bold text-slate-800",children:n}),e.jsx("button",{type:"button",onClick:()=>g(null),className:"text-slate-400 hover:text-slate-600 text-lg leading-none","aria-label":t("depGraph.close"),children:"×"})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-slate-600 mb-1",children:t("depGraph.dependencies")}),e.jsx("ul",{className:"text-slate-700 space-y-0.5",children:(L.get(n)??[]).length===0?e.jsx("li",{className:"text-slate-400",children:t("depGraph.none")}):(L.get(n)??[]).map(v=>e.jsxs("li",{children:["→ ",v]},v))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-slate-600 mb-1",children:t("depGraph.dependents")}),e.jsx("ul",{className:"text-slate-700 space-y-0.5",children:($.get(n)??[]).length===0?e.jsx("li",{className:"text-slate-400",children:t("depGraph.none")}):($.get(n)??[]).map(v=>e.jsxs("li",{children:["← ",v]},v))})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-5 shadow-sm",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-3 pb-2 border-b border-slate-100",children:[t("depGraph.packageList")," (",A.length,")"]}),e.jsx("ul",{className:"text-sm space-y-3 max-h-[280px] overflow-y-auto pr-1",children:A.map(v=>e.jsxs("li",{className:"pb-3 border-b border-slate-100 last:border-0 last:pb-0",children:[e.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-slate-800",children:v.label||v.id}),v.type==="external"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200 font-medium",children:t("depGraph.labelExternal")}),v.type==="internal"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-emerald-50 text-emerald-700 border border-emerald-200 font-medium",children:t("depGraph.labelInternal")}),v.indirect&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-slate-50 text-slate-500 border border-slate-200 font-medium",children:t("depGraph.labelIndirect")}),v.packageDir&&e.jsxs("span",{className:"text-slate-500 text-xs",children:["· ",v.packageDir]})]}),v.fullPath&&e.jsx("div",{className:"mt-1 text-slate-400 text-xs truncate",children:v.fullPath}),v.targets&&v.targets.length>0&&e.jsxs("div",{className:"mt-1.5 text-slate-500 text-xs pl-0",children:["Targets: ",e.jsx("span",{className:"text-slate-600",children:v.targets.join(", ")})]})]},v.id))})]}),e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-5 shadow-sm",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-3 pb-2 border-b border-slate-100",children:[t("depGraph.depRelations")," (",_.length,")"]}),e.jsx("p",{className:"text-xs text-slate-500 mb-2",children:t("depGraph.depRelationsDesc")}),e.jsx("ul",{className:"text-sm space-y-2 max-h-[280px] overflow-y-auto pr-1",children:_.map((v,ee)=>e.jsxs("li",{className:"flex items-center gap-2 text-slate-700",children:[e.jsx("span",{className:"font-semibold text-slate-800",children:v.from}),e.jsx("span",{className:"text-slate-400 shrink-0",children:"→"}),e.jsx("span",{className:"font-semibold text-slate-800",children:v.to})]},`${v.from}-${v.to}-${ee}`))})]}),f==="target"&&e.jsxs("p",{className:"text-xs text-slate-500 mt-2",children:[t("depGraph.targetHint"),e.jsx("span",{className:"font-mono",children:"Package::Target"})]})]})]})]})},jn=({onRefresh:t})=>{const{t:s}=_e(),[a,l]=o.useState({}),[d,c]=o.useState([]),[u,p]=o.useState([]),[n,g]=o.useState(null),[f,h]=o.useState(!0),[x,i]=o.useState(!1),[y,k]=o.useState(!1),[w,T]=o.useState(""),[A,G]=o.useState(!1),[_,E]=o.useState({ruleId:"",message:"",severity:"warning",pattern:"",languages:[],note:"",dimension:""}),[Z,X]=o.useState(!1),[H,q]=o.useState(""),I=async()=>{try{const[B,K]=await Promise.all([ae.getGuardRules(),ae.getGuardViolations()]);l((B==null?void 0:B.rules)||{}),p((B==null?void 0:B.projectLanguages)||[]),c((K==null?void 0:K.runs)||[])}catch{l({}),c([])}finally{h(!1)}};o.useEffect(()=>{I()},[]);const L=async()=>{if(window.confirm(s("guard.clearConfirm")))try{await ae.clearViolations(),I(),t==null||t()}catch(B){re((B==null?void 0:B.message)||s("common.operationFailed"),{title:s("common.operationFailed"),type:"error"})}},$=B=>{E(K=>({...K,languages:K.languages.includes(B)?K.languages.filter(xe=>xe!==B):[...K.languages,B]}))},m=async()=>{var B,K;if(!w.trim()){q(s("guard.aiGenPlaceholder"));return}q(""),G(!0);try{const P=await ae.generateGuardRule({description:w.trim()}),R=P.dimension;E({ruleId:P.ruleId||"",message:P.message||"",severity:P.severity==="error"?"error":"warning",pattern:P.pattern||"",languages:Array.isArray(P.languages)&&P.languages.length>0?P.languages:[],note:P.note!=null?String(P.note):"",dimension:R==="file"||R==="target"||R==="project"?R:""}),k(!0)}catch(xe){q(((K=(B=xe==null?void 0:xe.response)==null?void 0:B.data)==null?void 0:K.error)||(xe==null?void 0:xe.message)||s("guard.aiGenFailed"))}finally{G(!1)}},N=async B=>{var K,xe;if(B.preventDefault(),q(""),!_.ruleId.trim()||!_.message.trim()||!_.pattern.trim()||_.languages.length===0){q(s("guard.addRuleValidation"));return}X(!0);try{await ae.saveGuardRule({ruleId:_.ruleId.trim(),message:_.message.trim(),severity:_.severity,pattern:_.pattern.trim(),languages:_.languages,note:_.note.trim()||void 0,..._.dimension?{dimension:_.dimension}:{}}),E({ruleId:"",message:"",severity:"warning",pattern:"",languages:[],note:"",dimension:""}),T(""),k(!1),I(),t==null||t()}catch(P){q(((xe=(K=P==null?void 0:P.response)==null?void 0:K.data)==null?void 0:xe.error)||(P==null?void 0:P.message)||s("common.saveFailed"))}finally{X(!1)}},W=o.useMemo(()=>{const B=Object.entries(a);return u.length===0?B:B.filter(([,K])=>!K.languages||K.languages.length===0?!0:K.languages.some(xe=>u.includes(xe)))},[a,u]),O=d.reduce((B,K)=>B+K.violations.length,0),[ye,Ne]=o.useState("all"),[je,v]=o.useState("all"),ee=o.useMemo(()=>{const B=new Set;for(const[,xe]of W)(xe.languages||[]).forEach(P=>B.add(P));const K=Bt.filter(xe=>B.has(xe.id)).map(xe=>xe.id);for(const xe of B)K.includes(xe)||K.push(xe);return K},[W]),te=B=>{var K;return((K=Bt.find(xe=>xe.id===B))==null?void 0:K.label)||B},de=o.useMemo(()=>{const B={error:0,warning:0,info:0};for(const[,K]of W){const xe=K.severity;B[xe]!==void 0&&B[xe]++}return B},[W]),ve=B=>{const K={safety:s("guard.categorySafety"),correctness:s("guard.categoryCorrectness"),performance:s("guard.categoryPerformance"),style:s("guard.categoryStyle")};return B?K[B]||B:"—"},fe=(B,K)=>{const xe=`guardRuleMessages.${B}`,P=s(xe);return P!==xe?P:K},ie=(B,K)=>{if(!K)return K;const xe=`guardRuleFixSuggestions.${B}`,P=s(xe);return P!==xe?P:K},be=o.useMemo(()=>W.filter(([,B])=>!(ye!=="all"&&!(B.languages||[]).includes(ye)||je!=="all"&&B.severity!==je)),[W,ye,je]);return f?e.jsx("div",{className:"p-6 text-slate-500",children:s("common.loading")}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap justify-between items-center gap-3 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0",children:e.jsx(dt,{className:"text-blue-600",size:20})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-slate-800",children:s("guard.title")}),e.jsxs("p",{className:"text-xs text-slate-400 mt-0.5 truncate",children:[s("guard.summary"),u.length>0&&e.jsxs("span",{className:"ml-1.5",children:["· ",s("guard.currentProject"),":",u.map(B=>te(B)).join(" / ")]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("a",{href:ar,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-slate-600 bg-slate-50 border border-slate-200 hover:bg-slate-100",children:[e.jsx(Tl,{size:14})," ",s("guard.reportIssue")]}),e.jsxs("button",{type:"button",onClick:()=>i(!x),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-blue-700 bg-blue-50 border border-blue-200 hover:bg-blue-100",children:[x?e.jsx(Gt,{size:14}):e.jsx(rt,{size:14}),s("guard.aiGenRule")]}),d.length>0&&e.jsxs("button",{type:"button",onClick:L,className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-red-600 bg-red-50 border border-red-200 hover:bg-red-100",children:[e.jsx(ot,{size:14})," ",s("guard.clearHistory")]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-50 border border-slate-100",children:[e.jsx(dt,{size:14,className:"text-slate-400"}),e.jsxs("span",{className:"text-slate-500",children:[s("guard.tableHeaders.rule")," ",e.jsx("strong",{className:"text-slate-700",children:W.length})]})]}),O>0&&e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-amber-50 border border-amber-100",children:[e.jsx(Rt,{size:14,className:"text-amber-400"}),e.jsx("span",{className:"text-amber-600",children:s("guard.totalViolations",{count:O})})]})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1",children:[x&&e.jsxs("section",{className:"mb-6",children:[e.jsxs("div",{className:"p-4 bg-slate-50 border border-slate-200 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"semantic-input",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.aiGenRuleDesc")}),e.jsx("textarea",{id:"semantic-input",name:"semanticInput",value:w,onChange:B=>{T(B.target.value),q("")},className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm resize-y min-h-[80px]",placeholder:s("guard.aiGenPlaceholder"),rows:3}),e.jsx("button",{type:"button",onClick:m,disabled:A||!w.trim(),className:"mt-2 px-4 py-2 bg-slate-600 text-white text-sm rounded-lg hover:bg-slate-700 disabled:opacity-50",children:s(A?"guard.aiGenerating":"guard.aiGenRule")}),H&&e.jsx("p",{className:"mt-2 text-sm text-red-600",children:H})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>k(!y),className:"text-sm font-medium text-blue-600 hover:text-blue-700",children:s(y?"common.collapse":"common.expand")}),_.ruleId&&e.jsxs("span",{className:"text-xs text-slate-500",children:[s("guard.generatedRuleId"),":",_.ruleId]})]})]}),y&&e.jsxs("form",{onSubmit:N,className:"mt-3 p-4 bg-white border border-slate-200 rounded-xl space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-id",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.ruleId")}),e.jsx("input",{id:"rule-id",name:"ruleId",type:"text",value:_.ruleId,onChange:B=>E(K=>({...K,ruleId:B.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",placeholder:"my-rule-id"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-severity",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.severity")}),e.jsxs("select",{id:"rule-severity",name:"severity",value:_.severity,onChange:B=>E(K=>({...K,severity:B.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",children:[e.jsx("option",{value:"warning",children:"warning"}),e.jsx("option",{value:"error",children:"error"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-message",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.message")}),e.jsx("input",{id:"rule-message",name:"message",type:"text",value:_.message,onChange:B=>E(K=>({...K,message:B.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",placeholder:s("guard.aiGenPlaceholder")})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-pattern",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.patternLabel")}),e.jsx("input",{id:"rule-pattern",name:"pattern",type:"text",value:_.pattern,onChange:B=>E(K=>({...K,pattern:B.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm font-mono",placeholder:"dispatch_sync\\\\s*\\\\([^)]*main"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.languagesLabel")}),e.jsx("div",{className:"flex gap-3 flex-wrap",children:(u.length>0?Bt.filter(B=>u.includes(B.id)):Bt.slice(0,8)).map(B=>e.jsxs("label",{htmlFor:`lang-${B.id}`,className:"flex items-center gap-1.5 text-sm",children:[e.jsx("input",{id:`lang-${B.id}`,name:"languages",type:"checkbox",checked:_.languages.includes(B.id),onChange:()=>$(B.id)}),B.label]},B.id))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-dimension",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.dimensionLabel")}),e.jsxs("select",{id:"rule-dimension",name:"dimension",value:_.dimension,onChange:B=>E(K=>({...K,dimension:B.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",children:[e.jsx("option",{value:"",children:s("guard.dimNoLimit")}),e.jsx("option",{value:"file",children:s("guard.dimFile")}),e.jsx("option",{value:"target",children:s("guard.dimTarget")}),e.jsx("option",{value:"project",children:s("guard.dimProject")})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-note",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.noteLabel")}),e.jsx("input",{id:"rule-note",name:"note",type:"text",value:_.note,onChange:B=>E(K=>({...K,note:B.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",placeholder:s("guard.notePlaceholder")})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"submit",disabled:Z,className:"px-4 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 disabled:opacity-50",children:s(Z?"common.saving":"common.confirm")}),e.jsx("button",{type:"button",onClick:()=>k(!1),className:"px-4 py-2 text-slate-600 text-sm rounded-lg hover:bg-slate-100",children:s("common.collapse")})]})]})]}),e.jsxs("section",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 gap-3 flex-wrap",children:[e.jsxs("h3",{className:"text-sm font-semibold text-slate-700 flex items-center gap-1.5",children:[e.jsx(za,{size:14,className:"text-slate-400"}),s("guard.tableHeaders.rule"),e.jsxs("span",{className:"text-slate-400 font-normal",children:["(",be.length,"/",W.length,")"]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx("button",{onClick:()=>v("all"),className:`px-2 py-1 rounded-md border transition-all ${je==="all"?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"}`,children:s("common.all")}),e.jsxs("button",{onClick:()=>v("error"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${je==="error"?"bg-red-600 text-white border-red-600":"bg-white text-red-600 border-red-200 hover:bg-red-50"}`,children:[e.jsx(Ot,{size:12})," error ",e.jsxs("span",{className:"opacity-70",children:["(",de.error,")"]})]}),e.jsxs("button",{onClick:()=>v("warning"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${je==="warning"?"bg-amber-500 text-white border-amber-500":"bg-white text-amber-600 border-amber-200 hover:bg-amber-50"}`,children:[e.jsx(Rt,{size:12})," warning ",e.jsxs("span",{className:"opacity-70",children:["(",de.warning,")"]})]}),e.jsxs("button",{onClick:()=>v("info"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${je==="info"?"bg-blue-500 text-white border-blue-500":"bg-white text-blue-600 border-blue-200 hover:bg-blue-50"}`,children:[e.jsx(_a,{size:12})," info ",e.jsxs("span",{className:"opacity-70",children:["(",de.info,")"]})]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mb-3 flex-wrap",children:[e.jsx("button",{onClick:()=>Ne("all"),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${ye==="all"?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"}`,children:s("guard.allLanguages")}),ee.map(B=>{const K=W.filter(([,xe])=>(xe.languages||[]).includes(B)).length;return e.jsxs("button",{onClick:()=>Ne(ye===B?"all":B),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${ye===B?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"}`,children:[te(B)," ",e.jsxs("span",{className:"opacity-60",children:["(",K,")"]})]},B)})]}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600",children:s("guard.ruleId")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600 w-20",children:s("guard.severity")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600",children:s("guard.message")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600 w-28",children:s("guard.languagesLabel")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600 w-20",children:s("guard.category")})]})}),e.jsx("tbody",{children:be.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"py-4 px-4 text-slate-500 text-center",children:W.length===0?s("common.noData"):s("guard.noMatchingRules")})}):be.map(([B,K])=>e.jsxs("tr",{className:"border-b border-slate-100 last:border-0 hover:bg-slate-50/50",children:[e.jsx("td",{className:"py-2 px-4 font-mono text-xs text-slate-700",children:B}),e.jsx("td",{className:"py-2 px-4",children:e.jsx("span",{className:`text-xs font-medium px-1.5 py-0.5 rounded ${K.severity==="error"?"bg-red-100 text-red-700":K.severity==="info"?"bg-blue-100 text-blue-700":"bg-amber-100 text-amber-700"}`,children:K.severity})}),e.jsxs("td",{className:"py-2 px-4 text-slate-700",children:[fe(B,K.message),K.fixSuggestion&&e.jsx("span",{className:"ml-1.5 text-xs text-emerald-600",title:ie(B,K.fixSuggestion),children:"💡"})]}),e.jsx("td",{className:"py-2 px-4",children:e.jsx("div",{className:"flex flex-wrap gap-1",children:(K.languages||[]).map(xe=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-100 font-medium",children:te(xe)},xe))})}),e.jsx("td",{className:"py-2 px-4 text-xs text-slate-500",children:ve(K.category)})]},B))})]})})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-700 mb-3",children:s("guard.violationRecords",{runs:d.length,count:O})}),d.length===0?e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-xl py-12 text-center text-slate-500",children:s("guard.noViolations")}):e.jsx("div",{className:"space-y-2",children:d.map(B=>{const K=n===B.id,xe=B.violations.length>0;return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-xl overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>g(K?null:B.id),className:"w-full flex items-center gap-2 py-3 px-4 text-left hover:bg-slate-50 transition-colors",children:[K?e.jsx(Gt,{size:z.md}):e.jsx(rt,{size:z.md}),e.jsx("span",{className:"font-mono text-sm text-slate-700",children:B.filePath}),e.jsx("span",{className:"text-xs text-slate-400",children:new Date(B.triggeredAt).toLocaleString()}),xe?e.jsxs("span",{className:"ml-auto flex items-center gap-1 text-amber-600 text-xs font-medium",children:[e.jsx(Rt,{size:z.sm})," ",s("guard.totalViolations",{count:B.violations.length})]}):e.jsx("span",{className:"ml-auto text-slate-400 text-xs",children:s("guard.noViolations")})]}),K&&e.jsx("div",{className:"border-t border-slate-100 bg-slate-50/50 dark:bg-[#283040] p-4",children:B.violations.length===0?e.jsx("p",{className:"text-sm text-slate-500",children:s("guard.noViolations")}):e.jsx("ul",{className:"space-y-2",children:B.violations.map((P,R)=>{var ce;const Q=a[P.ruleId];return e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[P.severity==="error"?e.jsx(Ot,{size:z.md,className:"text-red-500 shrink-0 mt-0.5"}):e.jsx(Rt,{size:z.md,className:"text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsxs("div",{children:[e.jsxs("span",{className:"font-mono text-xs text-slate-500",children:["[",P.ruleId,"] ",P.filePath?`${P.filePath}:${P.line}`:`L${P.line}`]}),P.dimension&&e.jsx("span",{className:"ml-1.5 text-xs px-1.5 py-0.5 rounded bg-slate-200 text-slate-600",children:P.dimension==="file"?s("guard.dimFile"):P.dimension==="target"?s("guard.dimTarget"):s("guard.dimProject")}),e.jsx("span",{className:"text-slate-700 ml-2",children:fe(P.ruleId,P.message)})]}),P.snippet&&e.jsx("pre",{className:"text-xs text-slate-600 bg-[#f1f5f9] dark:bg-[#0f1219] dark:text-slate-400 dark:border dark:border-slate-700 p-2 rounded overflow-x-auto",children:P.snippet}),Q&&(Q.rationale||((ce=Q.fixSuggestions)==null?void 0:ce.length)||Q.sourceRecipe||Q.note)&&e.jsxs("div",{className:"mt-1 rounded-lg border border-blue-100 bg-blue-50/50 p-2.5 text-xs space-y-1.5",children:[Q.rationale&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(tt,{size:12,className:"text-blue-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-bold text-blue-700",children:[s("guard.rationale"),":"]}),e.jsx("span",{className:"text-slate-600",children:Q.rationale})]})]}),Q.fixSuggestions&&Q.fixSuggestions.length>0&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx($a,{size:12,className:"text-emerald-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-bold text-emerald-700",children:[s("guard.fixSuggestion"),":"]}),e.jsx("ul",{className:"mt-0.5 space-y-0.5 text-slate-600",children:Q.fixSuggestions.map((we,Ue)=>e.jsxs("li",{className:"flex items-start gap-1",children:[e.jsx("span",{className:"text-emerald-400 mt-0.5",children:"•"}),e.jsx("span",{children:we}),e.jsx("button",{className:"ml-1 text-blue-500 hover:text-blue-700",title:s("guard.copyFixSuggestion"),onClick:()=>navigator.clipboard.writeText(we),children:"⎘"})]},Ue))})]})]}),Q.sourceRecipe&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Hs,{size:12,className:"text-indigo-500 shrink-0"}),e.jsxs("span",{className:"font-bold text-indigo-700",children:[s("guard.sourceRecipe"),":"]}),e.jsx("span",{className:"text-indigo-600 font-mono",children:Q.sourceRecipe})]}),!Q.rationale&&Q.note&&e.jsxs("div",{className:"text-slate-500 italic",children:[s("guard.noteLabel"),":",Q.note]})]})]})]},R)})})})]},B.id)})})]})]})]})},fa=()=>Math.random().toString(36).substring(2,10),vn=({d:t})=>{const{t:s}=_e();return e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-2.5 py-1 bg-slate-50 border-b border-slate-200 flex items-center gap-1.5",children:[e.jsx(Ta,{size:10,className:"text-emerald-500"}),e.jsx("span",{className:"text-[10px] font-bold text-slate-600",children:t.label})]}),e.jsxs("div",{className:"p-2.5 bg-red-50/30 border-b border-slate-200",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:s("aiChat.diffBefore")}),e.jsx("pre",{className:"text-[11px] text-slate-600 whitespace-pre-wrap break-words max-h-48 overflow-auto font-mono leading-relaxed scrollbar-light",children:t.before||e.jsx("span",{className:"italic text-slate-300",children:s("aiChat.diffEmpty")})})]}),e.jsxs("div",{className:"p-2.5 bg-emerald-50/30",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:s("aiChat.diffAfter")}),e.jsx("pre",{className:"text-[11px] text-slate-700 whitespace-pre-wrap break-words max-h-48 overflow-auto font-mono leading-relaxed scrollbar-light",children:t.after})]})]})};function Nn(t,s){const a=new Date(t),d=new Date().getTime()-a.getTime(),c=Math.floor(d/6e4);if(c<1)return s("aiChat.timeJustNow");if(c<60)return s("aiChat.timeMinutesAgo",{n:c});const u=Math.floor(c/60);if(u<24)return s("aiChat.timeHoursAgo",{n:u});const p=Math.floor(u/24);return p<7?s("aiChat.timeDaysAgo",{n:p}):a.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})}const wn=()=>{const{t,lang:s}=_e(),{close:a,isOpen:l}=ds(),[d,c]=o.useState([]),[u,p]=o.useState(!1),n=o.useRef([]),g=o.useRef(null),f=Ua(),{topics:h,activeTopicId:x,activeTopic:i,createTopic:y,deleteTopic:k,saveTopic:w,switchTopic:T,setActiveTopicId:A}=f,G=o.useRef(null),_=o.useRef(null),[E,Z]=o.useState(""),[X,H]=o.useState(!1),q=o.useRef(!1);o.useEffect(()=>{l&&a()},[]),o.useEffect(()=>{var j;(j=G.current)==null||j.scrollIntoView({behavior:"smooth"})},[d,u]),o.useEffect(()=>{setTimeout(()=>{var j;return(j=_.current)==null?void 0:j.focus()},200)},[]),o.useEffect(()=>{q.current||x&&d.length>0&&w(x,d)},[d,x,w]);const I=o.useCallback(()=>{q.current=!0,y(),c([]),n.current=[],setTimeout(()=>{q.current=!1},50)},[y,c,n]),L=o.useCallback(j=>{if(j===x)return;q.current=!0,T(j);const W=f.getTopic(j);W?(c(W.messages),n.current=W.messages.filter(O=>O.role==="user"||O.role==="assistant").map(O=>({role:O.role==="assistant"?"model":O.role,content:O.content}))):(c([]),n.current=[]),setTimeout(()=>{q.current=!1},50)},[x,T,f,c,n]),$=o.useCallback((j,W)=>{j.stopPropagation(),k(W),W===x&&(q.current=!0,c([]),n.current=[],setTimeout(()=>{q.current=!1},50))},[k,x,c,n]),m=o.useCallback(async()=>{const j=E.trim();if(!j||u)return;let W=x;W||(q.current=!0,W=y(),setTimeout(()=>{q.current=!1},50)),Z(""),c(Ne=>[...Ne,{id:fa(),role:"user",content:j,timestamp:Date.now()}]),p(!0);const O=fa();c(Ne=>[...Ne,{id:O,role:"assistant",content:`🔄 ${t("aiChat.thinking")}`,timestamp:Date.now()}]),n.current.push({role:"user",content:j});const ye=new AbortController;g.current=ye;try{const{onEvent:Ne,getState:je}=Wa(O,c,t),ee=(await ae.chatStream(j,n.current,te=>{Ne(te)},ye.signal,s)).text||je().answerText;n.current.push({role:"model",content:ee}),c(te=>te.map(de=>de.id===O?{...de,content:ee}:de))}catch(Ne){if(Ne.name==="AbortError"){const je=t("aiChat.cancelled");c(v=>v.map(ee=>ee.id===O?{...ee,content:je}:ee))}else c(je=>je.map(v=>v.id===O?{...v,content:t("aiChat.requestFailed",{error:Ne.message})}:v))}finally{g.current=null}p(!1)},[E,u,x,y]),N=o.useCallback(j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),m())},[m]);return e.jsxs("div",{className:"flex-1 flex h-full bg-slate-50",children:[e.jsx("div",{className:`${X?"w-10":"w-64"} shrink-0 bg-white border-r border-slate-200 flex flex-col transition-all duration-200`,children:X?e.jsxs("div",{className:"flex flex-col items-center py-3 gap-2",children:[e.jsx("button",{onClick:()=>H(!1),className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400 hover:text-slate-600",title:t("aiChat.expandTopics"),children:e.jsx(rt,{size:16})}),e.jsx("button",{onClick:I,className:"p-1.5 hover:bg-blue-50 rounded-lg transition-colors text-blue-500",title:t("aiChat.newTopic"),children:e.jsx(Nt,{size:16})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-3 py-2.5 border-b border-slate-100 flex items-center justify-between shrink-0",children:[e.jsx("span",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:t("aiChat.topicRecords")}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx("button",{onClick:I,className:"p-1.5 hover:bg-blue-50 rounded-lg transition-colors text-slate-400 hover:text-blue-600",title:t("aiChat.newTopic"),children:e.jsx(Nt,{size:14})}),e.jsx("button",{onClick:()=>H(!0),className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400 hover:text-slate-600",title:t("common.collapse"),children:e.jsx(is,{size:14})})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-light",children:h.length===0?e.jsxs("div",{className:"px-4 py-8 text-center",children:[e.jsx(Lt,{size:24,className:"text-slate-200 mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-slate-400",children:t("aiChat.noHistory")}),e.jsx("p",{className:"text-[10px] text-slate-300 mt-1",children:t("aiChat.autoSaveHint")})]}):e.jsx("div",{className:"py-1",children:h.map(j=>{const W=j.id===x,O=j.messages.filter(ye=>ye.role==="user").length;return e.jsx("div",{onClick:()=>L(j.id),className:`group mx-1.5 mb-0.5 px-3 py-2 rounded-lg cursor-pointer transition-colors ${W?"bg-blue-50 border border-blue-200":"hover:bg-slate-50 border border-transparent"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-1.5",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-xs font-medium truncate leading-snug ${W?"text-blue-700":"text-slate-700"}`,children:j.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 flex items-center gap-0.5",children:[e.jsx(xt,{size:9}),Nn(j.updatedAt,t)]}),O>0&&e.jsx("span",{className:"text-[10px] text-slate-300",children:t("aiChat.messageCount",{n:O})})]})]}),e.jsx("button",{onClick:ye=>$(ye,j.id),className:`p-1 rounded transition-colors shrink-0 ${W?"text-blue-400 hover:text-red-500 hover:bg-red-50":"text-transparent group-hover:text-slate-300 hover:!text-red-500 hover:!bg-red-50"}`,title:t("aiChat.deleteTopic"),children:e.jsx(ot,{size:12})})]})},j.id)})})}),h.length>0&&e.jsx("div",{className:"px-3 py-2 border-t border-slate-100 shrink-0",children:e.jsx("span",{className:"text-[10px] text-slate-400",children:t("aiChat.topicCount",{count:h.length})})})]})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("div",{className:"px-6 py-3 border-b border-slate-200 bg-white flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center",children:e.jsx(Lt,{className:"text-blue-600",size:18})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-bold text-slate-800",children:i?i.title:"AI Chat"}),e.jsx("p",{className:"text-[11px] text-slate-400",children:t("aiChat.askAnything")})]})]}),d.length>0&&e.jsxs("button",{onClick:I,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-slate-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors border border-slate-200 hover:border-blue-200",children:[e.jsx(Nt,{size:14}),t("aiChat.newTopic")]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 scrollbar-light",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-6 space-y-4",children:[d.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center mb-4",children:e.jsx(Qe,{className:"text-blue-500",size:28})}),e.jsx("h3",{className:"text-base font-bold text-slate-700 mb-2",children:t("aiChat.startChat")}),e.jsx("p",{className:"text-sm text-slate-400 max-w-md leading-relaxed mb-5",children:t("aiChat.emptyDescLong")}),e.jsx("div",{className:"flex flex-wrap gap-2 justify-center",children:[{key:"analyzeArch",label:t("aiChat.quickPrompts.analyzeArch")},{key:"findDuplicates",label:t("aiChat.quickPrompts.findDuplicates")},{key:"suggestOptimize",label:t("aiChat.quickPrompts.suggestOptimize")},{key:"summarize",label:t("aiChat.quickPromptSummarize")}].map(j=>e.jsx("button",{onClick:()=>{var W;Z(j.label),(W=_.current)==null||W.focus()},className:"text-xs px-3.5 py-2 rounded-lg bg-white border border-slate-200 text-slate-600 hover:bg-blue-50 hover:text-blue-700 hover:border-blue-200 transition-colors shadow-sm",children:j.label},j.key))})]}),d.map(j=>e.jsx("div",{className:`flex ${j.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] ${j.role==="user"?"bg-blue-600 text-white rounded-2xl rounded-tr-md px-4 py-2.5":j.role==="system"?"bg-slate-100 border border-slate-200 text-slate-600 rounded-2xl px-4 py-2.5 w-full":"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-4 py-3 shadow-sm w-full"}`,children:[j.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(rs,{size:13,className:"text-blue-500"}),e.jsx("span",{className:"text-[11px] font-bold text-blue-600",children:t("aiChat.aiAssistant")})]}),j.role==="assistant"&&!j.diff?e.jsx(gt,{content:j.content,className:"text-sm text-slate-700"}):e.jsx("p",{className:`text-sm leading-relaxed whitespace-pre-wrap ${j.role==="user"?"":"text-slate-600"}`,children:j.content}),j.diff&&j.diff.length>0&&e.jsx("div",{className:"space-y-2 mt-2",children:j.diff.map(W=>e.jsx(vn,{d:W},W.field))})]})},j.id)),u&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-4 py-3 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{size:14,className:"animate-spin text-blue-500"}),e.jsx("span",{className:"text-sm text-slate-500",children:t("aiChat.thinking")}),g.current&&e.jsx("button",{onClick:()=>{var j;return(j=g.current)==null?void 0:j.abort()},className:"ml-1 px-1.5 py-0.5 text-[10px] font-bold text-red-500 border border-red-200 rounded hover:bg-red-50 transition-colors",children:t("common.stop")})]})})}),e.jsx("div",{ref:G})]})}),e.jsx("div",{className:"border-t border-slate-200 bg-white shrink-0",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-6 py-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{ref:_,value:E,onChange:j=>Z(j.target.value),onKeyDown:N,placeholder:t("aiChat.inputPlaceholder"),rows:2,className:"flex-1 px-4 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-400 resize-none placeholder:text-slate-300",disabled:u}),e.jsx("button",{onClick:m,disabled:!E.trim()||u,className:"self-stretch w-10 flex items-center justify-center rounded-xl bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white disabled:opacity-40 disabled:cursor-not-allowed transition-all shadow-sm shrink-0",children:e.jsx(Bs,{size:16})})]}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-1.5",children:t("aiChat.inputHint")})]})})]})]})},kn=28,Cn=22,Sn=50,An=11,Dn=10,bt={depends_on:"#3b82f6",requires:"#3b82f6",extends:"#10b981",implements:"#10b981",inherits:"#10b981",enforces:"#f59e0b",related:"#8b5cf6",conflicts:"#ef4444",calls:"#06b6d4",prerequisite:"#f97316",data_flow_to:"#14b8a6",references:"#6b7280",alternative:"#a855f7",deprecated_by:"#dc2626",solves:"#22c55e"},In={depends_on:"依赖",requires:"需要",extends:"扩展",implements:"实现",inherits:"继承",enforces:"约束",related:"关联",conflicts:"冲突",calls:"调用",prerequisite:"前置",data_flow_to:"数据流",references:"引用",alternative:"替代",deprecated_by:"废弃",solves:"解决"},Ts=[{bg:"#eff6ff",border:"#bfdbfe",text:"#1d4ed8"},{bg:"#f0fdf4",border:"#bbf7d0",text:"#15803d"},{bg:"#fef3c7",border:"#fde68a",text:"#b45309"},{bg:"#fdf2f8",border:"#fbcfe8",text:"#be185d"},{bg:"#f5f3ff",border:"#ddd6fe",text:"#7c3aed"},{bg:"#ecfeff",border:"#a5f3fc",text:"#0e7490"},{bg:"#fff7ed",border:"#fed7aa",text:"#c2410c"},{bg:"#f0f9ff",border:"#bae6fd",text:"#0369a1"},{bg:"#fefce8",border:"#fef08a",text:"#a16207"},{bg:"#f1f5f9",border:"#cbd5e1",text:"#475569"}],Rn=[{bg:"rgba(59,130,246,0.08)",border:"rgba(59,130,246,0.25)",text:"#60a5fa"},{bg:"rgba(34,197,94,0.08)",border:"rgba(34,197,94,0.25)",text:"#4ade80"},{bg:"rgba(245,158,11,0.08)",border:"rgba(245,158,11,0.25)",text:"#fbbf24"},{bg:"rgba(236,72,153,0.08)",border:"rgba(236,72,153,0.25)",text:"#f472b6"},{bg:"rgba(139,92,246,0.08)",border:"rgba(139,92,246,0.25)",text:"#a78bfa"},{bg:"rgba(6,182,212,0.08)",border:"rgba(6,182,212,0.25)",text:"#22d3ee"},{bg:"rgba(249,115,22,0.08)",border:"rgba(249,115,22,0.25)",text:"#fb923c"},{bg:"rgba(14,165,233,0.08)",border:"rgba(14,165,233,0.25)",text:"#38bdf8"},{bg:"rgba(234,179,8,0.08)",border:"rgba(234,179,8,0.25)",text:"#facc15"},{bg:"rgba(148,163,184,0.08)",border:"rgba(148,163,184,0.25)",text:"#94a3b8"}];function It(t){return Math.min(Sn,Math.max(Cn,kn+t*2))}function ya(t,s){return t.length<=s?t:t.substring(0,s-1)+"…"}function Tn(t,s,a,l){const d=new Map;for(const f of t)d.set(f.fromId,(d.get(f.fromId)||0)+1),d.set(f.toId,(d.get(f.toId)||0)+1);const c=[...d.keys()],u=[...new Set(c.map(f=>l[f]||"general"))].sort(),p=new Map,n=Math.ceil(Math.sqrt(u.length)),g=400;return u.forEach((f,h)=>{const x=h%n,i=Math.floor(h/n);p.set(f,{x:450+(x-(n-1)/2)*g,y:350+(i-(Math.ceil(u.length/n)-1)/2)*g})}),c.map(f=>{const h=l[f]||"general",x=p.get(h)||{x:450,y:350},i=Math.random()*2*Math.PI,y=40+Math.random()*80;return{id:f,label:s[f]||f,type:a[f]||"recipe",group:h,x:x.x+y*Math.cos(i),y:x.y+y*Math.sin(i),vx:0,vy:0,degree:d.get(f)||1}})}function En(t,s,a=200){const l=t.map(u=>({...u})),d=new Map(l.map(u=>[u.id,u]));function c(){const u=new Map;for(const p of l){const n=u.get(p.group);n?(n.x+=p.x,n.y+=p.y,n.count++):u.set(p.group,{x:p.x,y:p.y,count:1})}for(const[,p]of u)p.x/=p.count,p.y/=p.count;return u}for(let u=0;u<a;u++){const p=1-u/a,n=18e3*p,g=.015,f=.8,h=c();for(let i=0;i<l.length;i++)for(let y=i+1;y<l.length;y++){const k=l[i],w=l[y];let T=w.x-k.x,A=w.y-k.y,G=Math.sqrt(T*T+A*A)||1;const _=It(k.degree)+It(w.degree)+60,E=Math.max(G,1),Z=k.group===w.group?.6:1.4,X=n*Z/(E*E),H=G<_?(_-G)*.5:0,q=X+H,I=T/E*q,L=A/E*q;k.vx-=I,k.vy-=L,w.vx+=I,w.vy+=L}for(const i of s){const y=d.get(i.fromId),k=d.get(i.toId);if(!y||!k)continue;let w=k.x-y.x,T=k.y-y.y,A=Math.sqrt(w*w+T*T)||1;const G=y.group===k.group?140:280,_=g*(A-G),E=w/A*_,Z=T/A*_;y.vx+=E,y.vy+=Z,k.vx-=E,k.vy-=Z}const x=.008*p;for(const i of l){const y=h.get(i.group);y&&(i.vx+=(y.x-i.x)*x,i.vy+=(y.y-i.y)*x)}for(const i of l)i.vx*=f,i.vy*=f,i.x+=i.vx,i.y+=i.vy}return l}function Pn(t,s,a,l,d,c,u=0){const p=a-t,n=l-s,g=Math.sqrt(p*p+n*n)||1,f=p/g,h=n/g,x=t+f*d,i=s+h*d,y=a-f*c,k=l-h*c;if(u===0)return`M${x},${i}L${y},${k}`;const w=(x+y)/2+-h*u,T=(i+k)/2+f*u;return`M${x},${i}Q${w},${T},${y},${k}`}const Ln=()=>{const{t}=_e(),{isDark:s}=St(),a=s?Rn:Ts,l=r=>{const C={depends_on:"knowledgeGraph.relationDependsOn",requires:"knowledgeGraph.relationRequires",extends:"knowledgeGraph.relationExtends",implements:"knowledgeGraph.relationImplements",inherits:"knowledgeGraph.relationInherits",enforces:"knowledgeGraph.relationEnforces",related:"knowledgeGraph.relationAssociates",conflicts:"knowledgeGraph.relationConflicts",calls:"knowledgeGraph.relationCalls",prerequisite:"knowledgeGraph.relationPrerequisite",data_flow_to:"knowledgeGraph.relationDataFlow",references:"knowledgeGraph.relationReferences",alternative:"knowledgeGraph.relationAlternative",deprecated_by:"knowledgeGraph.relationDeprecatedBy",solves:"knowledgeGraph.relationSolves"};return C[r]?t(C[r]):In[r]||r},[d,c]=o.useState([]),[u,p]=o.useState({}),[n,g]=o.useState({}),[f,h]=o.useState({}),[x,i]=o.useState(null),[y,k]=o.useState(!0),[w,T]=o.useState(null),[A,G]=o.useState(null),[_,E]=o.useState(null),[Z,X]=o.useState(null),[H,q]=o.useState(!1),[I,L]=o.useState(null),[$,m]=o.useState(!1),[N,j]=o.useState(1),[W,O]=o.useState({x:0,y:0}),ye=o.useRef(null),Ne=o.useRef(null),je=o.useRef(!1),v=o.useRef({x:0,y:0}),ee=async()=>{var r,C;k(!0),T(null);try{const[b,F]=await Promise.all([ae.getKnowledgeGraph(),ae.getGraphStats()]);c(b.edges||[]),p(b.nodeLabels||{}),g(b.nodeTypes||{}),h(b.nodeCategories||{}),i(F)}catch(b){T(((C=(r=b.response)==null?void 0:r.data)==null?void 0:C.error)||b.message||t("knowledgeGraph.loadFailed"))}finally{k(!1)}};o.useEffect(()=>{ee()},[]),o.useEffect(()=>{ae.getDiscoverRelationsStatus().then(r=>{r.status==="running"&&(q(!0),L(t("knowledgeGraph.discoverAnalyzing",{elapsed:r.elapsed??0})))}).catch(()=>{})},[]),o.useEffect(()=>{if(!H)return;let r=0;const C=240,b=setInterval(async()=>{if(r++,r>C){clearInterval(b),q(!1),m(!0),L(t("knowledgeGraph.discoverPollTimeout"));return}try{const F=await ae.getDiscoverRelationsStatus();if(F.status==="done"){q(!1);const M=F.discovered??0,U=F.totalPairs??0,se=F.batchErrors??0;if(M===0&&se===0)m(!1),L(t("knowledgeGraph.discoverNoResults",{pairs:U}));else if(M===0&&se>0)m(!0),L(t("knowledgeGraph.discoverBatchErrors",{errors:se}));else{m(!1);const ue=se>0?t("knowledgeGraph.discoverBatchFailed",{count:se}):"";L(t("knowledgeGraph.discoverSuccess",{count:M,pairs:U,failMsg:ue}))}ee()}else if(F.status==="error"){q(!1),m(!0);const M=F.error||t("knowledgeGraph.unknownError");M.includes("AI Provider")||M.includes("API Key")?L(t("knowledgeGraph.discoverAiNotConfigured",{error:M})):M.includes("超时")||M.includes("timeout")?L(t("knowledgeGraph.discoverTimeout",{error:M})):L(t("knowledgeGraph.discoverFailed",{error:M}))}else F.status==="running"&&L(t("knowledgeGraph.discoverAnalyzing",{elapsed:F.elapsed??0}))}catch{}},3e3);return()=>clearInterval(b)},[H]);const te=o.useCallback(async()=>{var r,C,b;L(null),m(!1);try{const F=await ae.discoverRelations();if(F.status==="empty"){L(F.message||t("knowledgeGraph.discoverInsufficientRecipes"));return}if(F.status==="timeout"){m(!0),L(F.error||t("knowledgeGraph.discoverPreviousTimeout"));return}if(F.status==="running"){q(!0),L(t("knowledgeGraph.discoverRunning"));return}q(!0),L(t("knowledgeGraph.discoverStarted"))}catch(F){m(!0);const M=((b=(C=(r=F==null?void 0:F.response)==null?void 0:r.data)==null?void 0:C.error)==null?void 0:b.message)||F.message||t("knowledgeGraph.unknownError");M.includes("ChatAgent")||M.includes("AI Provider")?L(t("knowledgeGraph.discoverAiUnavailable",{error:M})):L(t("knowledgeGraph.discoverStartFailed",{error:M}))}},[t]),de=o.useMemo(()=>{if(d.length===0)return[];const r=Tn(d,u,n,f);return En(r,d)},[d,u,n,f]),ve=o.useMemo(()=>{const r=new Map;for(const F of de){const M=r.get(F.group)||[];M.push(F),r.set(F.group,M)}const C=[],b=[...r.keys()].sort();for(const F of b){const M=r.get(F);if(M.length===0)continue;let U=0,se=0;for(const D of M)U+=D.x,se+=D.y;U/=M.length,se/=M.length;let ue=0,he=0;for(const D of M){const V=It(D.degree);ue=Math.max(ue,Math.abs(D.x-U)+V+35),he=Math.max(he,Math.abs(D.y-se)+V+35)}C.push({group:F,cx:U,cy:se,rx:Math.max(ue,60),ry:Math.max(he,60),count:M.length})}return C},[de]),fe=o.useMemo(()=>{const r=[...new Set(de.map(b=>b.group))].sort(),C={};return r.forEach((b,F)=>{C[b]=a[F%a.length]}),C},[de,a]),ie=o.useMemo(()=>{if(de.length===0)return{x:0,y:0,w:900,h:700};let r=1/0,C=1/0,b=-1/0,F=-1/0;for(const M of de){const U=It(M.degree);r=Math.min(r,M.x-U-80),C=Math.min(C,M.y-U-40),b=Math.max(b,M.x+U+80),F=Math.max(F,M.y+U+40)}return{x:r,y:C,w:b-r,h:F-C}},[de]),be=o.useMemo(()=>new Map(de.map(r=>[r.id,r])),[de]),{connectedEdgeIds:B,connectedNodeIds:K}=o.useMemo(()=>{const r=A||_;if(!r)return{connectedEdgeIds:new Set,connectedNodeIds:new Set};const C=new Set,b=new Set([r]);for(const F of d)(F.fromId===r||F.toId===r)&&(C.add(F.id),b.add(F.fromId),b.add(F.toId));return{connectedEdgeIds:C,connectedNodeIds:b}},[A,_,d]),xe=o.useMemo(()=>{const r=new Map,C=new Map;for(const F of d){const M=[F.fromId,F.toId].sort().join("|"),U=r.get(M)||0;C.set(F.id,U),r.set(M,U+1)}const b=new Map;for(const F of d){const M=[F.fromId,F.toId].sort().join("|"),U=r.get(M)||1;if(U<=1){b.set(F.id,0);continue}const se=C.get(F.id)||0;b.set(F.id,(se-(U-1)/2)*40)}return b},[d]),[P,R]=o.useState(new Set);o.useEffect(()=>{R(new Set(d.map(r=>r.relation)))},[d]);const Q=o.useMemo(()=>d.filter(r=>P.has(r.relation)),[d,P]),ce=r=>{R(C=>{const b=new Set(C);return b.has(r)?b.delete(r):b.add(r),b})},we=o.useCallback(r=>{r.button===0&&(je.current=!0,v.current={x:r.clientX,y:r.clientY})},[]),Ue=o.useCallback(r=>{if(!je.current)return;const C=r.clientX-v.current.x,b=r.clientY-v.current.y;v.current={x:r.clientX,y:r.clientY},O(F=>({x:F.x+C,y:F.y+b}))},[]),Se=o.useCallback(()=>{je.current=!1},[]),ne=o.useCallback(r=>{r.preventDefault();const C=r.deltaY>0?-.1:.1;j(b=>Math.min(3,Math.max(.2,b+C)))},[]),pe=r=>`kg-arrow-${r.replace(/[^a-z_]/g,"")}`;if(y)return e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})});if(w)return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4",children:[e.jsx("p",{className:"text-red-500",children:w}),e.jsx("button",{onClick:ee,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:t("knowledgeGraph.retry")})]});if(d.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-slate-500",children:[e.jsx(Ls,{size:48,className:"text-slate-300"}),e.jsx("p",{className:"text-lg font-medium",children:t("knowledgeGraph.empty")}),e.jsx("p",{className:"text-sm text-center max-w-md",children:t("knowledgeGraph.emptyDesc")}),I&&e.jsx("p",{className:`text-sm ${$?"text-red-500":"text-green-600"}`,children:I}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:te,disabled:H,className:"px-4 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 transition-colors flex items-center gap-2 disabled:opacity-50",children:H?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"})," ",t("knowledgeGraph.discovering")]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{size:z.sm})," ",t("knowledgeGraph.discoverRelations")]})}),e.jsxs("button",{onClick:ee,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2",children:[e.jsx(yt,{size:z.sm})," ",t("knowledgeGraph.refresh")]})]})]});const Le=[...new Set(d.map(r=>r.relation))].sort(),De=!!(A||_);return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ls,{size:z.lg,className:"text-blue-600"}),e.jsx("h2",{className:`text-lg font-bold ${s?"text-slate-100":"text-slate-800"}`,children:t("knowledgeGraph.title")}),x&&e.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${s?"text-slate-400 bg-slate-700/60":"text-slate-500 bg-slate-100"}`,children:t("knowledgeGraph.statsLabel",{nodes:de.length,edges:x.totalEdges})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>j(r=>Math.min(r+.2,3)),className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.zoomIn"),children:e.jsx(El,{size:z.sm})}),e.jsx("button",{onClick:()=>j(r=>Math.max(r-.2,.2)),className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.zoomOut"),children:e.jsx(Pl,{size:z.sm})}),e.jsx("button",{onClick:()=>{j(1),O({x:0,y:0})},className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.resetView"),children:e.jsx(Cs,{size:z.sm})}),e.jsx("button",{onClick:ee,className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.refresh"),children:e.jsx(yt,{size:z.sm})}),e.jsx("button",{onClick:te,disabled:H,className:`flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 ${s?"bg-violet-500/15 hover:bg-violet-500/25 text-violet-400":"bg-violet-50 hover:bg-violet-100 text-violet-700"}`,title:t("knowledgeGraph.discoverTooltip"),children:H?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-3 w-3 border-b-2 border-violet-600"})," ",t("knowledgeGraph.discovering")]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{size:z.sm})," ",t("knowledgeGraph.discoverRelations")]})})]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-3 flex-shrink-0",children:Le.map(r=>{var C;return e.jsxs("button",{onClick:()=>ce(r),className:`flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium transition-all border ${P.has(r)?"border-transparent shadow-sm":s?"border-slate-600 bg-slate-800 text-slate-500 opacity-40":"border-slate-200 bg-white text-slate-400 opacity-40"}`,style:P.has(r)?{backgroundColor:(bt[r]||"#6b7280")+"18",color:bt[r]||"#6b7280"}:{},children:[e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:bt[r]||"#6b7280"}}),l(r),((C=x==null?void 0:x.byRelation)==null?void 0:C[r])!=null&&e.jsxs("span",{className:"opacity-60",children:["(",x.byRelation[r],")"]})]},r)})}),e.jsxs("div",{ref:Ne,className:`flex-1 rounded-xl border overflow-hidden relative min-h-0 ${s?"border-slate-700 bg-[#13151c]":"border-slate-200 bg-gradient-to-br from-slate-50 to-white"}`,style:{cursor:je.current?"grabbing":"grab"},onWheel:ne,children:[e.jsxs("svg",{ref:ye,width:"100%",height:"100%",viewBox:`${ie.x} ${ie.y} ${ie.w} ${ie.h}`,onMouseDown:we,onMouseMove:Ue,onMouseUp:Se,onMouseLeave:Se,style:{transform:`scale(${N}) translate(${W.x/N}px, ${W.y/N}px)`},children:[e.jsxs("defs",{children:[Le.map(r=>e.jsx("marker",{id:pe(r),viewBox:"0 0 10 8",refX:"10",refY:"4",markerWidth:"7",markerHeight:"5",orient:"auto-start-reverse",children:e.jsx("path",{d:"M0,0 L10,4 L0,8 Z",fill:bt[r]||"#6b7280"})},r)),e.jsxs("filter",{id:"kg-glow",x:"-50%",y:"-50%",width:"200%",height:"200%",children:[e.jsx("feGaussianBlur",{in:"SourceAlpha",stdDeviation:"4",result:"blur"}),e.jsx("feFlood",{floodColor:"#3b82f6",floodOpacity:"0.3",result:"color"}),e.jsx("feComposite",{in:"color",in2:"blur",operator:"in",result:"shadow"}),e.jsxs("feMerge",{children:[e.jsx("feMergeNode",{in:"shadow"}),e.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),e.jsx("g",{children:ve.map(r=>{const C=fe[r.group]||Ts[0];return e.jsxs("g",{children:[e.jsx("ellipse",{cx:r.cx,cy:r.cy,rx:r.rx,ry:r.ry,fill:C.bg,stroke:C.border,strokeWidth:1.5,strokeDasharray:"6,4",opacity:.6}),e.jsxs("text",{x:r.cx,y:r.cy-r.ry+14,textAnchor:"middle",fontSize:11,fontWeight:600,fill:C.text,opacity:.8,style:{pointerEvents:"none",userSelect:"none"},children:[r.group||"general"," (",r.count,")"]})]},r.group)})}),e.jsx("g",{children:Q.map(r=>{const C=be.get(r.fromId),b=be.get(r.toId);if(!C||!b)return null;const F=De?B.has(r.id):!1,M=Z===r.id,U=De?F?.85:.06:M?.9:.35,se=It(C.degree),ue=It(b.degree),he=xe.get(r.id)||0,D=Pn(C.x,C.y,b.x,b.y,se,ue,he);return e.jsxs("g",{children:[e.jsx("path",{d:D,fill:"none",stroke:"transparent",strokeWidth:12,onMouseEnter:()=>X(r.id),onMouseLeave:()=>X(null),style:{cursor:"pointer"}}),e.jsx("path",{d:D,fill:"none",stroke:bt[r.relation]||"#6b7280",strokeWidth:M||F?2:1.2,opacity:U,markerEnd:`url(#${pe(r.relation)})`,strokeDasharray:r.relation==="related"?"6,3":void 0,style:{transition:"opacity 0.25s, stroke-width 0.15s",pointerEvents:"none"}}),M&&(()=>{const V=(C.x+b.x)/2,ke=(C.y+b.y)/2;return e.jsxs("g",{children:[e.jsx("rect",{x:V-24,y:ke-16,width:48,height:18,rx:4,fill:s?"#252526":"white",stroke:bt[r.relation]||"#6b7280",strokeWidth:.8,opacity:.95}),e.jsx("text",{x:V,y:ke-4,textAnchor:"middle",fontSize:9,fontWeight:600,fill:bt[r.relation]||"#6b7280",children:l(r.relation)})]})})()]},r.id)})}),e.jsx("g",{children:de.map(r=>{const C=It(r.degree),b=A===r.id,F=De&&K.has(r.id),M=b||r.id===_,U=De&&!F,se=U?.12:1,ue=fe[r.group]||Ts[0],he=M?ue.border:ue.bg,D=M?ue.text:ue.border,V=M?"#ffffff":ue.text,ke=M?ue.text:s?"#9ca3af":"#64748b";return e.jsxs("g",{onClick:Ce=>{Ce.stopPropagation(),G(b?null:r.id)},onMouseEnter:()=>E(r.id),onMouseLeave:()=>E(null),style:{cursor:"pointer",transition:"opacity 0.25s"},opacity:se,filter:M?"url(#kg-glow)":void 0,children:[e.jsx("circle",{cx:r.x,cy:r.y,r:C,fill:he,stroke:D,strokeWidth:M?2.5:1.5}),e.jsx("text",{x:r.x,y:r.y+4,textAnchor:"middle",fontSize:Math.min(An,C*.7),fill:V,fontWeight:700,style:{pointerEvents:"none",userSelect:"none"},children:ya(r.label,4).toUpperCase()}),e.jsx("text",{x:r.x,y:r.y+C+14,textAnchor:"middle",fontSize:Dn,fill:ke,fontWeight:M?600:400,style:{pointerEvents:"none",userSelect:"none"},children:ya(r.label,18)}),r.degree>=3&&!U&&e.jsxs("g",{children:[e.jsx("circle",{cx:r.x+C*.7,cy:r.y-C*.7,r:8,fill:"#3b82f6",stroke:s?"#1e1e1e":"white",strokeWidth:1.5}),e.jsx("text",{x:r.x+C*.7,y:r.y-C*.7+3.5,textAnchor:"middle",fontSize:8,fill:"white",fontWeight:700,style:{pointerEvents:"none"},children:r.degree})]})]},r.id)})})]}),A&&e.jsx("button",{className:`absolute top-2 right-2 text-xs px-2 py-1 rounded-md shadow-sm border ${s?"text-slate-400 hover:text-slate-200 bg-[#252526]/90 border-slate-600":"text-slate-400 hover:text-slate-600 bg-white/90 border-slate-200"}`,onClick:()=>G(null),children:t("knowledgeGraph.cancelSelection")})]}),A&&e.jsxs("div",{className:`mt-3 p-4 rounded-xl border shadow-sm flex-shrink-0 max-h-48 overflow-y-auto scrollbar-light ${s?"bg-[#1e1e1e] border-slate-700":"bg-white border-slate-200"}`,children:[e.jsxs("div",{className:`flex items-center gap-2 mb-3 pb-2 border-b ${s?"border-slate-700":"border-slate-100"}`,children:[e.jsx(_a,{size:14,className:"text-blue-500"}),e.jsx("h3",{className:`font-semibold text-sm ${s?"text-slate-200":"text-slate-800"}`,children:u[A]||A}),e.jsxs("span",{className:"text-[10px] text-slate-400 ml-auto",children:["ID: ",A]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 font-medium",children:t("knowledgeGraph.outEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[d.filter(r=>r.fromId===A&&P.has(r.relation)).map(r=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:bt[r.relation]||"#6b7280"}}),e.jsx("span",{className:"text-slate-500",children:l(r.relation)}),e.jsx("span",{className:"text-slate-400",children:"→"}),e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>G(r.toId),children:u[r.toId]||r.toId.substring(0,16)})]},r.id)),d.filter(r=>r.fromId===A&&P.has(r.relation)).length===0&&e.jsx("li",{className:"text-slate-400",children:t("knowledgeGraph.none")})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 font-medium",children:t("knowledgeGraph.inEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[d.filter(r=>r.toId===A&&P.has(r.relation)).map(r=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>G(r.fromId),children:u[r.fromId]||r.fromId.substring(0,16)}),e.jsx("span",{className:"text-slate-400",children:"→"}),e.jsx("span",{className:"text-slate-500",children:l(r.relation)}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:bt[r.relation]||"#6b7280"}})]},r.id)),d.filter(r=>r.toId===A&&P.has(r.relation)).length===0&&e.jsx("li",{className:"text-slate-400",children:t("knowledgeGraph.none")})]})]})]})]})]})},mt={pending:{labelKey:"lifecycle.pending",color:"text-amber-700",bg:"bg-amber-50",border:"border-amber-200",icon:xt},active:{labelKey:"lifecycle.active",color:"text-green-700",bg:"bg-green-50",border:"border-green-200",icon:cs},deprecated:{labelKey:"lifecycle.deprecated",color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-200",icon:Fs}},Jt={rule:{labelKey:"kind.rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:dt},pattern:{labelKey:"kind.pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:jt},fact:{labelKey:"kind.fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:tt}},Mn={pending:[{action:"publish",labelKey:"knowledge.actionPublish",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:cs},{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:Fs,needsReason:!0}],active:[{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:Fs,needsReason:!0}],deprecated:[{action:"reactivate",labelKey:"knowledge.actionReactivate",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:Ra}]};function Yt(t,s){if(!t)return"";const a=t<1e12?t*1e3:t,l=new Date(a);if(isNaN(l.getTime())||l.getFullYear()<2e3)return"";const c=Date.now()-a;if(c<0)return l.toLocaleDateString();const u=Math.floor(c/6e4);if(u<1)return s("candidates.timeJustNow");if(u<60)return s("candidates.timeMinutesAgo",{n:u});const p=Math.floor(u/60);if(p<24)return s("candidates.timeHoursAgo",{n:p});const n=Math.floor(p/24);return n<7?s("candidates.timeDaysAgo",{n}):l.toLocaleDateString()}function Fn(t){return t==null?{ring:"stroke-slate-200",text:"text-slate-400",bg:"bg-slate-50",labelKey:""}:t>=.8?{ring:"stroke-emerald-500",text:"text-emerald-700",bg:"bg-emerald-50",labelKey:"candidates.confidenceHighLabel"}:t>=.6?{ring:"stroke-blue-500",text:"text-blue-700",bg:"bg-blue-50",labelKey:"candidates.confidenceMediumLabel"}:t>=.4?{ring:"stroke-amber-500",text:"text-amber-700",bg:"bg-amber-50",labelKey:"candidates.confidenceMediumLowLabel"}:{ring:"stroke-red-500",text:"text-red-700",bg:"bg-red-50",labelKey:"candidates.confidenceLowLabel"}}function zn(t,s=4){return t?Us(t).split(`
117
116
  `).slice(0,s).join(`
118
- `):""}const Es={"bootstrap-scan":{labelKey:"knowledge.sourceBootstrap",color:"text-violet-600 bg-violet-50 border-violet-200"},mcp:{labelKey:"knowledge.sourceMcp",color:"text-blue-600 bg-blue-50 border-blue-200"},manual:{labelKey:"knowledge.sourceManual",color:"text-emerald-600 bg-emerald-50 border-emerald-200"},"file-watcher":{labelKey:"knowledge.sourceFileWatcher",color:"text-orange-600 bg-orange-50 border-orange-200"},clipboard:{labelKey:"knowledge.sourceClipboard",color:"text-pink-600 bg-pink-50 border-pink-200"},cli:{labelKey:"knowledge.sourceCli",color:"text-slate-600 bg-slate-50 border-slate-200"},agent:{labelKey:"knowledge.sourceAgent",color:"text-violet-600 bg-violet-50 border-violet-200"},submit_with_check:{labelKey:"knowledge.sourceSubmitCheck",color:"text-teal-600 bg-teal-50 border-teal-200"}},$n=({onRefresh:t,idTitleMap:s})=>{const{t:a}=_e(),l=T=>({pending:a("knowledge.lifecyclePending"),active:a("knowledge.lifecycleActive"),deprecated:a("knowledge.lifecycleDeprecated")})[T]||T,d=T=>({publish:a("knowledge.actionPublish"),deprecate:a("knowledge.actionDeprecate"),reactivate:a("knowledge.actionReactivate")})[T]||T,[i,u]=o.useState([]),[p,n]=o.useState(null),[g,f]=o.useState(!0),[h,x]=o.useState(1),[c,j]=o.useState(20),[w,C]=o.useState(0),[E,S]=o.useState(""),[G,z]=o.useState(""),[P,Z]=o.useState(""),[X,H]=o.useState(""),[q,R]=o.useState(""),{isWide:M,toggle:_}=Vs(),[m,N]=o.useState(null),[y,W]=o.useState(!1),[O,be]=o.useState(new Set),[we,ye]=o.useState(!1),v=o.useRef(!0);o.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);const ee=o.useCallback(async()=>{var T;f(!0);try{const Q=await se.knowledgeList({page:h,limit:c,lifecycle:E||void 0,kind:G||void 0,category:P||void 0,keyword:X||void 0});v.current&&(u(Q.data||[]),C(((T=Q.pagination)==null?void 0:T.total)||0))}catch(Q){re((Q==null?void 0:Q.message)||a("knowledge.loadFailed"),{title:a("common.loadFailed"),type:"error"})}finally{v.current&&f(!1)}},[h,c,E,G,P,X]),ae=o.useCallback(async()=>{try{const T=await se.knowledgeStats();v.current&&n(T)}catch{}},[]);o.useEffect(()=>{ee()},[ee]),o.useEffect(()=>{ae()},[ae]),o.useEffect(()=>{const T=setTimeout(()=>{H(q),x(1)},300);return()=>clearTimeout(T)},[q]),o.useEffect(()=>{x(1)},[E,G,P]);const ue=o.useCallback(()=>{ee(),ae(),t==null||t()},[ee,ae,t]),fe=o.useMemo(()=>{const T=new Map;if(s)for(const[Q,ie]of Object.entries(s))T.set(Q,ie);for(const Q of i)Q.id&&Q.title&&T.set(Q.id,Q.title);return T},[i,s]),he=async(T,Q,ie)=>{var ke,Ue,Ie,ne;W(!0);try{const ve=await se.knowledgeLifecycle(T.id,Q,ie);re(`${T.title} → ${a(((ke=mt[ve.lifecycle])==null?void 0:ke.labelKey)||"")||ve.lifecycle}`,{title:a("knowledge.operationSuccess")}),u(He=>He.map(Pe=>Pe.id===T.id?ve:Pe)),(m==null?void 0:m.id)===T.id&&N(ve),ae()}catch(ve){re(((ne=(Ie=(Ue=ve==null?void 0:ve.response)==null?void 0:Ue.data)==null?void 0:Ie.error)==null?void 0:ne.message)||(ve==null?void 0:ve.message)||a("common.operationFailed"),{title:a("common.operationFailed"),type:"error"})}finally{v.current&&W(!1)}},ce=async T=>{if(confirm(a("knowledge.deleteConfirmMsg",{title:T.title})))try{await se.knowledgeDelete(T.id),re(a("knowledge.deleteSuccess",{title:T.title}),{title:a("common.delete")}),u(Q=>Q.filter(ie=>ie.id!==T.id)),(m==null?void 0:m.id)===T.id&&N(null),ae()}catch(Q){re((Q==null?void 0:Q.message)||a("knowledge.deleteFailed"),{title:a("knowledge.deleteFailed"),type:"error"})}},je=async()=>{if(O.size!==0){ye(!0);try{const T=await se.knowledgeBatchPublish([...O]);re(a("knowledge.batchPublishResult",{success:T.successCount,fail:T.failureCount}),{title:a("knowledge.batchPublish")}),be(new Set),ue()}catch(T){re((T==null?void 0:T.message)||a("knowledge.batchPublishFailed"),{title:a("common.operationFailed"),type:"error"})}finally{ye(!1)}}},$=async()=>{ye(!0);try{const Q=((await se.knowledgeList({lifecycle:"pending",limit:500})).data||[]).filter(ke=>ke.autoApprovable).map(ke=>ke.id);if(Q.length===0){re(a("knowledge.noAutoApprovable"),{title:a("knowledge.noPublishable")});return}const ie=await se.knowledgeBatchPublish(Q);re(a("knowledge.autoPublishResult",{count:ie.successCount}),{title:a("knowledge.batchPublishComplete")}),ue()}catch(T){re((T==null?void 0:T.message)||a("knowledge.batchPublishFailed"),{title:a("common.operationFailed"),type:"error"})}finally{ye(!1)}},K=T=>{be(Q=>{const ie=new Set(Q);return ie.has(T)?ie.delete(T):ie.add(T),ie})},xe=()=>{O.size===i.length?be(new Set):be(new Set(i.map(T=>T.id)))},L=(T,Q)=>{const ie=prompt(a("knowledge.deprecateReasonPrompt"));ie&&he(T,Q,ie)};return e.jsxs("div",{className:"space-y-4",children:[p&&e.jsx("div",{className:"grid grid-cols-3 gap-3",children:Object.entries(mt).map(([T,Q])=>{const ie=p[T]||0,ke=Q.icon;return e.jsxs("button",{onClick:()=>{S(E===T?"":T)},className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all text-left ${E===T?`${Q.bg} ${Q.border} ${Q.color} ring-1 ring-current`:"bg-white dark:bg-[#252a36] border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-[#2a3040]"}`,children:[e.jsx(ke,{size:14}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium",children:l(T)}),e.jsx("div",{className:"text-lg font-bold",children:ie})]})]},T)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(ft,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:16}),e.jsx("input",{type:"text",placeholder:a("knowledge.searchPlaceholder"),value:q,onChange:T=>R(T.target.value),className:"w-full pl-9 pr-3 py-2 rounded-lg border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-300"})]}),e.jsx("div",{className:"flex gap-1",children:Object.entries(Jt).map(([T,Q])=>{const ie=Q.icon;return e.jsxs("button",{onClick:()=>z(G===T?"":T),className:`flex items-center gap-1 px-2.5 py-1.5 rounded-md text-xs font-medium border transition-all ${G===T?`${Q.bg} ${Q.border} ${Q.color}`:"bg-white dark:bg-[#252a36] border-slate-200 dark:border-slate-600 text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-[#2a3040]"}`,children:[e.jsx(ie,{size:12}),a(Q.labelKey)]},T)})}),e.jsxs("select",{value:P,onChange:T=>Z(T.target.value),className:"px-2.5 py-1.5 rounded-md text-xs border border-slate-200 dark:border-slate-600 bg-white dark:bg-[#252a36] text-slate-600 dark:text-slate-300 focus:outline-none",children:[e.jsx("option",{value:"",children:a("knowledge.allCategories")}),["View","Service","Tool","Model","Network","Storage","UI","Utility"].map(T=>e.jsx("option",{value:T,children:T},T))]}),e.jsx("button",{onClick:ue,className:"p-2 rounded-md text-slate-400 hover:bg-slate-100",title:a("common.refresh"),children:e.jsx(yt,{size:16})}),O.size>0&&e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsx("span",{className:"text-xs text-slate-500",children:a("knowledge.selectedCount",{count:O.size})}),e.jsx("button",{onClick:je,disabled:we,className:"px-2.5 py-1 text-xs font-medium text-green-700 bg-green-50 border border-green-200 rounded-md hover:bg-green-100 disabled:opacity-50",children:we?e.jsx(Fe,{size:12,className:"animate-spin"}):a("knowledge.batchPublish")}),e.jsx("button",{onClick:()=>be(new Set),className:"p-1 text-slate-400 hover:text-slate-600",children:e.jsx(Xe,{size:14})})]}),O.size===0&&e.jsxs("button",{onClick:$,disabled:we,className:"ml-auto px-3 py-1.5 text-xs font-medium text-cyan-700 bg-cyan-50 border border-cyan-200 rounded-md hover:bg-cyan-100 disabled:opacity-50 flex items-center gap-1.5",children:[we?e.jsx(Fe,{size:12,className:"animate-spin"}):e.jsx(et,{size:12}),a("knowledge.quickBatchPublish")]})]}),g?e.jsxs("div",{className:"flex items-center justify-center py-20 text-slate-400",children:[e.jsx(Fe,{size:24,className:"animate-spin mr-2"}),e.jsx("span",{children:a("common.loading")})]}):i.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-slate-400",children:[e.jsx(tt,{size:48,className:"mb-4 opacity-30"}),e.jsx("p",{className:"text-sm",children:a("knowledge.noResults")}),(X||E||G||P)&&e.jsx("button",{onClick:()=>{R(""),S(""),z(""),Z("")},className:"mt-2 text-xs text-blue-500 hover:text-blue-700",children:a("knowledge.clearFilters")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("input",{type:"checkbox",checked:O.size===i.length&&i.length>0,onChange:xe,className:"rounded border-slate-300"}),e.jsx("span",{className:"text-xs text-slate-400",children:a("knowledge.selectAll")}),e.jsx("span",{className:"text-xs text-slate-400 ml-auto",children:a("knowledge.totalCount",{count:w})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:i.map(T=>{var ne,ve,He,Pe,Ne,r;const Q=mt[T.lifecycle]||mt.pending,ie=Jt[T.kind]||Jt.pattern,ke=Q.icon,Ue=ie.icon,Ie=zn((ne=T.reasoning)==null?void 0:ne.confidence);return e.jsxs("div",{onClick:()=>N(T),className:`group bg-white dark:bg-[#1e2028] rounded-xl border shadow-sm hover:shadow-md cursor-pointer transition-all overflow-hidden ${(m==null?void 0:m.id)===T.id?"ring-2 ring-blue-300 border-blue-200 dark:border-blue-700":"border-slate-200 dark:border-slate-700"}`,children:[e.jsxs("div",{className:"px-4 pt-3 pb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("input",{type:"checkbox",checked:O.has(T.id),onChange:k=>{k.stopPropagation(),K(T.id)},onClick:k=>k.stopPropagation(),className:"rounded border-slate-300"}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${Q.bg} ${Q.color} ${Q.border} border`,children:[e.jsx(ke,{size:10}),l(T.lifecycle)]}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${ie.bg} ${ie.color} ${ie.border} border`,children:[e.jsx(Ue,{size:10}),a(ie.labelKey)]}),T.category&&e.jsx("span",{className:"text-[10px] text-slate-400",children:T.category}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${Ie.bg} ${Ie.text}`,children:((ve=T.reasoning)==null?void 0:ve.confidence)!=null?`${Math.round(T.reasoning.confidence*100)}%`:"—"}),T.autoApprovable&&T.lifecycle==="pending"&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] px-1.5 py-0.5 rounded bg-cyan-50 text-cyan-600 border border-cyan-200",children:[e.jsx(et,{size:9}),a("knowledge.autoApprovable")]})]}),e.jsx("h3",{className:"text-sm font-bold text-slate-900 mb-1 break-words leading-snug",children:T.title}),(T.description||((He=T.content)==null?void 0:He.rationale))&&e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed",children:T.description||((Pe=T.content)==null?void 0:Pe.rationale)||""}),((Ne=T.content)==null?void 0:Ne.pattern)&&e.jsx("pre",{className:"mt-1.5 text-[10px] text-slate-500 bg-slate-50 rounded p-1.5 line-clamp-3 font-mono overflow-hidden",children:_n(T.content.pattern,3)})]}),e.jsxs("div",{className:"px-4 py-2 bg-slate-50/80 dark:bg-[#252a36] border-t border-slate-100 dark:border-slate-700 flex items-center gap-2",children:[(r=T.tags)==null?void 0:r.slice(0,3).map(k=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100",children:k},k)),T.tags&&T.tags.length>3&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["+",T.tags.length-3]}),e.jsxs("span",{className:"text-[10px] text-slate-300 ml-auto",children:[T.trigger&&e.jsx("span",{className:"text-blue-400 mr-2",children:T.trigger}),T.source&&e.jsx("span",{className:"mr-2",children:T.source}),Yt(T.updatedAt,a)]})]})]},T.id)})}),e.jsx(Js,{currentPage:h,totalPages:Math.ceil(w/c),onPageChange:x,pageSize:c,onPageSizeChange:T=>{j(T),x(1)},totalItems:w})]}),m&&(()=>{var k,b,B,D,U,te,de,me;const T=mt[m.lifecycle]||mt.pending,Q=T.icon,ie=Jt[m.kind]||Jt.pattern,ke=ct[m.category||""]||ct.All||{},Ue=Es[m.source||""]||{labelKey:""};Ue.labelKey?a(Ue.labelKey):m.source;const Ie=m.reasoning,ne=Ie&&(Ie.whyStandard||Ie.sources&&Ie.sources.length>0||Ie.confidence!=null),ve=i.findIndex(I=>I.id===m.id),He=ve>0,Pe=ve<i.length-1,Ne=()=>{He&&N(i[ve-1])},r=()=>{Pe&&N(i[ve+1])};return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:()=>N(null),children:[e.jsx(Ze.Backdrop,{className:"bg-black/15 backdrop-blur-[1px]"}),e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col border-l border-slate-200 dark:border-slate-700 ${M?"w-[960px] max-w-[92vw]":"w-[700px] max-w-[92vw]"}`,style:{animation:"slideInRight 0.25s ease-out"},onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-700 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] shrink-0",children:[e.jsx("div",{className:"flex-1 min-w-0 mr-3",children:e.jsx("h3",{className:"font-bold text-slate-800 text-lg leading-snug break-words",children:m.title})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:Ne,disabled:!He,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:a("knowledge.prev"),children:e.jsx(is,{size:F.md})}),e.jsxs("span",{className:"text-xs text-slate-400 tabular-nums",children:[ve+1,"/",i.length]}),e.jsx("button",{onClick:r,disabled:!Pe,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:a("knowledge.next"),children:e.jsx(rt,{size:F.md})}),e.jsx("div",{className:"w-px h-5 bg-slate-200 mx-1"}),e.jsx("button",{onClick:_,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400",title:a(M?"knowledge.narrow":"knowledge.widen"),children:M?e.jsx(Gs,{size:F.md}):e.jsx(Cs,{size:F.md})}),e.jsx("button",{onClick:()=>{ce(m),N(null)},className:"p-1.5 hover:bg-red-50 rounded-lg text-red-500 transition-colors",title:a("common.delete"),children:e.jsx(ot,{size:F.md})}),e.jsx("button",{onClick:()=>N(null),className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:F.md})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[m.rejectionReason&&e.jsxs("div",{className:"px-6 py-3 border-b border-red-200 dark:border-red-800/40 bg-red-50/80 dark:bg-red-900/15",children:[e.jsx("label",{className:"text-[10px] font-bold text-red-500 uppercase mb-1.5 block",children:a("knowledge.rejectionReason")}),e.jsx("p",{className:"text-xs text-red-600",children:m.rejectionReason})]}),e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${T.bg} ${T.color} ${T.border} border`,children:[e.jsx(Q,{size:10}),l(m.lifecycle)]}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${ie.bg} ${ie.color} ${ie.border} border`,children:[Ct.createElement(ie.icon,{size:10}),a(ie.labelKey)]}),e.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${(ke==null?void 0:ke.bg)||"bg-slate-50"} ${(ke==null?void 0:ke.color)||"text-slate-400"} ${(ke==null?void 0:ke.border)||"border-slate-100"}`,children:m.category||"general"}),m.knowledgeType&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-purple-50 text-purple-700 border border-purple-200",children:m.knowledgeType}),m.language&&e.jsx("span",{className:"text-[10px] uppercase font-bold text-slate-500 bg-slate-50 border border-slate-200 px-1.5 py-0.5 rounded",children:m.language}),m.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200 font-bold",children:m.trigger})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:[(()=>{const I=[];return m.scope&&I.push({icon:Pt,iconClass:"text-teal-400",label:a("knowledge.scope"),value:m.scope==="universal"?a("knowledge.scopeUniversal"):m.scope==="project-specific"?a("knowledge.scopeProject"):m.scope==="module-level"?a("knowledge.scopeModule"):m.scope}),m.complexity&&I.push({icon:lt,iconClass:"text-orange-400",label:a("knowledge.complexity"),value:m.complexity==="advanced"?a("knowledge.complexityAdvanced"):m.complexity==="intermediate"?a("knowledge.complexityIntermediate"):m.complexity==="beginner"?a("knowledge.complexityBeginner"):m.complexity}),m.source&&m.source!=="unknown"&&I.push({icon:Pt,iconClass:"text-violet-400",label:a("knowledge.source"),value:Es[m.source||""]?a(Es[m.source||""].labelKey):m.source||"-"}),m.createdAt&&I.push({icon:xt,iconClass:"text-slate-400",label:a("knowledge.createdAt"),value:Yt(m.createdAt,a)}),m.updatedAt&&I.push({icon:xt,iconClass:"text-slate-400",label:a("knowledge.updatedAt"),value:Yt(m.updatedAt,a)}),m.publishedAt&&I.push({icon:cs,iconClass:"text-emerald-400",label:a("knowledge.published"),value:Yt(m.publishedAt,a)}),I.map((V,Ce)=>{const Ae=V.icon;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ae,{size:11,className:`${V.iconClass} shrink-0`}),e.jsx("span",{className:"text-slate-400",children:V.label}),e.jsx("span",{className:`font-medium text-slate-600 ${V.mono?"font-mono text-[11px]":""}`,children:V.value})]},Ce)})})(),e.jsxs("div",{className:"flex items-center gap-1.5 basis-full mt-0.5",children:[e.jsx(as,{size:11,className:"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-slate-400",children:"ID"}),e.jsx("code",{className:"font-mono text-[11px] text-slate-500 break-all",children:m.id})]}),m.sourceFile&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full",children:[e.jsx(wt,{size:11,className:"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-slate-400",children:a("knowledge.sourceFile")}),e.jsx("code",{className:"font-mono text-[11px] text-slate-500 break-all",children:m.sourceFile})]})]})]}),m.tags&&m.tags.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100 flex flex-wrap items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-slate-300 mr-0.5"}),m.tags.map((I,V)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:I},V))]}),m.relations&&Object.entries(m.relations).some(([,I])=>Array.isArray(I)&&I.length>0)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(Hs,{size:12,className:"text-purple-400"}),e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:a("knowledge.relatedKnowledge")}),(()=>{const I=Object.values(m.relations).flat().length;return I>0?e.jsx("span",{className:"text-[9px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded-full font-bold",children:I}):null})()]}),e.jsx("div",{className:"space-y-1.5",children:Object.entries(m.relations).map(([I,V])=>!Array.isArray(V)||V.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-slate-500 w-14 shrink-0 pt-0.5 uppercase",children:I}),e.jsx("div",{className:"flex flex-wrap gap-1",children:V.map((Ce,Ae)=>{const Re=Ce.target||(typeof Ce=="string"?Ce:JSON.stringify(Ce)),Be=fe.get(Re)||Re;return e.jsx("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 border rounded text-[10px] font-mono bg-purple-50 border-purple-200 text-purple-700",title:Re,children:Be},Ae)})})]},I))})]}),m.stats&&Object.values(m.stats).some(I=>I>0)&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-amber-50/60 dark:bg-amber-900/20 rounded-xl p-3 text-center border border-amber-100 dark:border-amber-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:((k=m.stats)==null?void 0:k.authority)??"—"}),e.jsx("div",{className:"text-[10px] text-amber-500 font-medium",children:a("knowledge.authorityScore")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-lg font-bold text-slate-800",children:((b=m.stats)==null?void 0:b.guardHits)??0}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:a("knowledge.guardHits")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-lg font-bold text-slate-800",children:((B=m.stats)==null?void 0:B.adoptions)??0}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:a("knowledge.adoptions")})]}),e.jsxs("div",{className:"bg-blue-50/60 dark:bg-blue-900/20 rounded-xl p-3 text-center border border-blue-100 dark:border-blue-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:((D=m.stats)==null?void 0:D.searchHits)??0}),e.jsx("div",{className:"text-[10px] text-blue-500 font-medium",children:a("knowledge.searchHits")})]})]}),(m.stats.views>0||m.stats.applications>0)&&e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-slate-400",children:[e.jsxs("span",{children:[a("knowledge.statViews"),": ",m.stats.views]}),e.jsxs("span",{children:[a("knowledge.statApplications"),": ",m.stats.applications]})]})]}),ne&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-amber-400"})," ",a("knowledge.reasoning")]}),e.jsxs("div",{className:"bg-amber-50/30 dark:bg-amber-900/15 border border-amber-100 dark:border-amber-800/40 rounded-xl p-4 space-y-2.5",children:[Ie.whyStandard&&!/^Submitted via /i.test(Ie.whyStandard)&&e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:Ie.whyStandard}),Ie.sources&&Ie.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[a("knowledge.source"),":"]}),Ie.sources.map((I,V)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-white dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/40 rounded text-amber-700 dark:text-amber-400 font-mono",children:I},V))]}),Ie.confidence!=null&&Ie.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[a("knowledge.confidence"),":"]}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round((Ie.confidence??0)*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round((Ie.confidence??0)*100),"%"]})]}),Ie.alternatives&&Ie.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[a("knowledge.alternatives"),":"]}),Ie.alternatives.map((I,V)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-slate-100 border border-slate-200 rounded text-slate-600",children:I},V))]})]})]}),m.quality&&m.quality.grade&&m.quality.grade!=="F"&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.qualityGrade")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${m.quality.grade==="A"?"text-emerald-600":m.quality.grade==="B"?"text-blue-600":m.quality.grade==="C"?"text-amber-600":m.quality.grade==="D"?"text-orange-600":"text-slate-400"}`,children:m.quality.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-[10px]",children:[m.quality.completeness!=null&&m.quality.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:m.quality.completeness.toFixed(2)}),e.jsx("div",{className:"text-slate-400",children:a("knowledge.qualityCompletionLabel")})]}),m.quality.adaptation!=null&&m.quality.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:m.quality.adaptation.toFixed(2)}),e.jsx("div",{className:"text-slate-400",children:a("knowledge.qualityAdaptation")})]}),m.quality.documentation!=null&&m.quality.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:m.quality.documentation.toFixed(2)}),e.jsx("div",{className:"text-slate-400",children:a("knowledge.qualityDocumentation")})]})]})]})]}),m.description&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:a("knowledge.summary")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:m.description})]}),((U=m.content)==null?void 0:U.markdown)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",a("knowledge.markdownDoc")]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 leading-relaxed",children:e.jsx(gt,{content:m.content.markdown})})})]}),m.headers&&m.headers.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.importHeaders")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:m.headers.map((I,V)=>e.jsx("code",{className:"px-2.5 py-1 bg-violet-50 text-violet-700 border border-violet-100 rounded-md text-[10px] font-mono font-medium",children:I},V))})]}),((te=m.content)==null?void 0:te.pattern)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ht,{size:11,className:"text-emerald-500"})," ",a("knowledge.codePattern")]}),e.jsx(dt,{code:m.content.pattern,language:m.language==="objc"?"objectivec":m.language,showLineNumbers:!0})]}),(m.doClause||m.whenClause||m.dontClause||m.topicHint||m.coreCode)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(lt,{size:11,className:"text-indigo-400"})," Cursor Delivery"]}),e.jsxs("div",{className:"bg-indigo-50/30 dark:bg-indigo-900/15 border border-indigo-100 dark:border-indigo-800/40 rounded-xl p-4 space-y-1.5 text-xs",children:[m.topicHint&&e.jsxs("div",{children:[e.jsx("span",{className:"text-indigo-500 font-medium",children:"Topic:"}),e.jsx("span",{className:"text-slate-700",children:m.topicHint})]}),m.whenClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-500 font-medium",children:"When:"}),e.jsx("span",{className:"text-slate-700",children:m.whenClause})]}),m.doClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-emerald-500 font-medium",children:"Do:"}),e.jsx("span",{className:"text-slate-700",children:m.doClause})]}),m.dontClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-red-500 font-medium",children:"Don't:"}),e.jsx("span",{className:"text-slate-700",children:m.dontClause})]}),m.coreCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-purple-500 font-medium",children:"Core Code:"}),e.jsx("div",{className:"mt-1",children:e.jsx(dt,{code:m.coreCode,language:m.language==="objc"?"objectivec":m.language||"text"})})]})]})]}),((de=m.content)==null?void 0:de.rationale)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.designRationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:m.content.rationale})})]}),((me=m.content)==null?void 0:me.steps)&&m.content.steps.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.implementSteps")}),e.jsx("div",{className:"space-y-2",children:m.content.steps.map((I,V)=>{if(typeof I=="string")return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:V+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:I})]},V);const Ce=typeof I.title=="string"?I.title:"",Ae=typeof I.description=="string"?I.description:"",Re=typeof I.code=="string"?I.code:"";return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:V+1}),Ce&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:Ce})]}),Ae&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:Ae}),Re&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:Re})]},V)})})]}),m.constraints&&(()=>{var Ce,Ae,Re,Be,Ye,J,Le,qe;const I=m.constraints,V=(((Ce=I.guards)==null?void 0:Ce.length)||0)+(((Ae=I.boundaries)==null?void 0:Ae.length)||0)+(((Re=I.preconditions)==null?void 0:Re.length)||0)+(((Be=I.sideEffects)==null?void 0:Be.length)||0);return V?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ut,{size:11,className:"text-amber-500"})," ",a("knowledge.constraintsLabel")," ",e.jsx("span",{className:"text-amber-500 font-mono",children:V})]}),e.jsxs("div",{className:"space-y-1.5 text-xs text-slate-600",children:[(Ye=I.guards)==null?void 0:Ye.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${ze.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-[10px] bg-slate-100 px-1.5 py-0.5 rounded",children:ze.pattern}),ze.message&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["— ",ze.message]})]},Ve)),(J=I.boundaries)==null?void 0:J.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),ze]},Ve)),(Le=I.preconditions)==null?void 0:Le.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),ze]},Ve)),(qe=I.sideEffects)==null?void 0:qe.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),ze]},Ve))]})]}):null})(),m.aiInsight&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-cyan-400"})," ",a("knowledge.aiInsight")]}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:m.aiInsight})]}),(()=>{const I=Array.isArray(m.lifecycleHistory)?m.lifecycleHistory:(()=>{try{const V=typeof m.lifecycleHistory=="string"?JSON.parse(m.lifecycleHistory):null;return Array.isArray(V)?V:[]}catch{return[]}})();return I.length>0?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(xt,{size:11,className:"text-slate-400"})," ",a("knowledge.lifecycleHistoryLabel")]}),e.jsx("div",{className:"space-y-1",children:I.map((V,Ce)=>{const Ae=mt[V.from]||mt.pending,Re=mt[V.to]||mt.pending;return e.jsxs("div",{className:"flex items-center gap-2 text-[10px]",children:[e.jsx("span",{className:"text-slate-400 w-20 shrink-0",children:Yt(V.at,a)}),e.jsx("span",{className:`${Ae.color}`,children:l(V.from)}),e.jsx("span",{className:"text-slate-300",children:"→"}),e.jsx("span",{className:`${Re.color} font-medium`,children:l(V.to)}),e.jsxs("span",{className:"text-slate-400 ml-auto",children:["by ",V.by]})]},Ce)})})]}):null})()]}),e.jsxs("div",{className:"shrink-0 border-t border-slate-200 dark:border-slate-700 px-5 py-3 bg-gradient-to-b from-slate-50/80 to-white dark:from-[#252526] dark:to-[#1e1e1e] flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("button",{onClick:()=>{ce(m),N(null)},className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-red-500 hover:bg-red-50 border border-red-200 transition-colors",children:[e.jsx(ot,{size:14})," ",a("common.delete")]})}),e.jsx("div",{className:"flex items-center gap-2",children:(Fn[m.lifecycle]||[]).map(I=>{const V=I.icon;return e.jsxs("button",{onClick:()=>I.needsReason?L(m,I.action):he(m,I.action),disabled:y,className:`flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold border transition-colors disabled:opacity-50 ${I.bg} ${I.color} border-current/20`,children:[y?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(V,{size:14}),d(I.action)]},I.action)})})]})]})]})})()]})},gs={manual:{label:"manual",color:"bg-slate-100 text-slate-600",icon:Ia},"user-ai":{label:"user-ai",color:"bg-violet-100 text-violet-600",icon:Qe},"system-ai":{label:"system-ai",color:"bg-amber-100 text-amber-600",icon:ns},"external-ai":{label:"external-ai",color:"bg-cyan-100 text-cyan-600",icon:qs}},Bn=({onRefresh:t,signalSuggestionCount:s=0,onSuggestionCountChange:a})=>{const{t:l}=_e(),[d,i]=o.useState([]),[u,p]=o.useState(!0),[n,g]=o.useState(null),[f,h]=o.useState(!1),[x,c]=o.useState(!1),[j,w]=o.useState("all"),[C,E]=o.useState(!1),[S,G]=o.useState([]),[z,P]=o.useState(!1),[Z,X]=o.useState(!1),[H,q]=o.useState(null),[R,M]=o.useState(!1),[_,m]=o.useState(""),[N,y]=o.useState(!1),[W,O]=o.useState(!1),[be,we]=o.useState(!1),ye=o.useCallback(async()=>{var L;p(!0);try{const T=await se.listSkills();i(T.skills||[])}catch(T){((L=T.response)==null?void 0:L.status)!==404&&re(T.message||"",{title:l("skills.fetchFailed"),type:"error"}),i([])}finally{p(!1)}},[]);o.useEffect(()=>{ye()},[ye]);const v=async L=>{if((n==null?void 0:n.skillName)===L){g(null);return}M(!1),O(!1),h(!0);try{const T=await se.loadSkill(L);g(T)}catch{re(`"${L}" ${l("skills.loadError")}`,{title:l("skills.loadSkillFailed"),type:"error"})}finally{h(!1)}},ee=()=>{n!=null&&n.content&&(navigator.clipboard.writeText(n.content),E(!0),setTimeout(()=>E(!1),2e3))},ae=()=>{n&&(m(n.content),M(!0))},ue=()=>{M(!1),m("")},fe=async()=>{if(!(!n||!_.trim())){y(!0);try{await se.updateSkill(n.skillName,{content:_}),re(l("skills.saveSuccess"),{title:`Skill "${n.skillName}" ${l("skills.updateSuccess")}`}),M(!1);const L=await se.loadSkill(n.skillName);g(L)}catch(L){re(L.message||"",{title:l("skills.updateFailed"),type:"error"})}finally{y(!1)}}},he=async()=>{if(n){we(!0);try{await se.deleteSkill(n.skillName),re(l("skills.deleteSuccess"),{title:`Skill "${n.skillName}" ${l("skills.deleteSuccess")}`}),g(null),O(!1),M(!1),ye(),t==null||t()}catch(L){re(L.message||"",{title:l("skills.deleteFailed"),type:"error"})}finally{we(!1)}}},ce=async()=>{P(!0),X(!0);try{const[L,T]=await Promise.allSettled([se.suggestSkills(),se.getSignalStatus()]),Q=L.status==="fulfilled"?L.value.suggestions||[]:[],ie=T.status==="fulfilled"?T.value.suggestions||[]:[],ke=new Map;for(const Ie of Q)ke.set(Ie.name,Ie);for(const Ie of ie)ke.set(Ie.name,{...ke.get(Ie.name),...Ie});const Ue=[...ke.values()];G(Ue),a==null||a(Ue.length)}catch(L){re(L.message||"",{title:l("skills.aiRecommendFailed"),type:"error"}),G([]),a==null||a(0)}finally{P(!1)}};o.useEffect(()=>{s>0&&S.length===0&&!Z&&ce()},[]);const je=async L=>{q(L.name);try{const T=L.description||L.rationale||L.name,Q=`${l("skillsView.aiPromptPrefix")}
117
+ `):""}const Es={"bootstrap-scan":{labelKey:"knowledge.sourceBootstrap",color:"text-violet-600 bg-violet-50 border-violet-200"},mcp:{labelKey:"knowledge.sourceMcp",color:"text-blue-600 bg-blue-50 border-blue-200"},manual:{labelKey:"knowledge.sourceManual",color:"text-emerald-600 bg-emerald-50 border-emerald-200"},"file-watcher":{labelKey:"knowledge.sourceFileWatcher",color:"text-orange-600 bg-orange-50 border-orange-200"},clipboard:{labelKey:"knowledge.sourceClipboard",color:"text-pink-600 bg-pink-50 border-pink-200"},cli:{labelKey:"knowledge.sourceCli",color:"text-slate-600 bg-slate-50 border-slate-200"},agent:{labelKey:"knowledge.sourceAgent",color:"text-violet-600 bg-violet-50 border-violet-200"},submit_with_check:{labelKey:"knowledge.sourceSubmitCheck",color:"text-teal-600 bg-teal-50 border-teal-200"}},_n=({onRefresh:t,idTitleMap:s})=>{const{t:a}=_e(),l=R=>({pending:a("knowledge.lifecyclePending"),active:a("knowledge.lifecycleActive"),deprecated:a("knowledge.lifecycleDeprecated")})[R]||R,d=R=>({publish:a("knowledge.actionPublish"),deprecate:a("knowledge.actionDeprecate"),reactivate:a("knowledge.actionReactivate")})[R]||R,[c,u]=o.useState([]),[p,n]=o.useState(null),[g,f]=o.useState(!0),[h,x]=o.useState(1),[i,y]=o.useState(20),[k,w]=o.useState(0),[T,A]=o.useState(""),[G,_]=o.useState(""),[E,Z]=o.useState(""),[X,H]=o.useState(""),[q,I]=o.useState(""),{isWide:L,toggle:$}=Vs(),[m,N]=o.useState(null),[j,W]=o.useState(!1),[O,ye]=o.useState(new Set),[Ne,je]=o.useState(!1),v=o.useRef(!0);o.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);const ee=o.useCallback(async()=>{var R;f(!0);try{const Q=await ae.knowledgeList({page:h,limit:i,lifecycle:T||void 0,kind:G||void 0,category:E||void 0,keyword:X||void 0});v.current&&(u(Q.data||[]),w(((R=Q.pagination)==null?void 0:R.total)||0))}catch(Q){re((Q==null?void 0:Q.message)||a("knowledge.loadFailed"),{title:a("common.loadFailed"),type:"error"})}finally{v.current&&f(!1)}},[h,i,T,G,E,X]),te=o.useCallback(async()=>{try{const R=await ae.knowledgeStats();v.current&&n(R)}catch{}},[]);o.useEffect(()=>{ee()},[ee]),o.useEffect(()=>{te()},[te]),o.useEffect(()=>{const R=setTimeout(()=>{H(q),x(1)},300);return()=>clearTimeout(R)},[q]),o.useEffect(()=>{x(1)},[T,G,E]);const de=o.useCallback(()=>{ee(),te(),t==null||t()},[ee,te,t]),ve=o.useMemo(()=>{const R=new Map;if(s)for(const[Q,ce]of Object.entries(s))R.set(Q,ce);for(const Q of c)Q.id&&Q.title&&R.set(Q.id,Q.title);return R},[c,s]),fe=async(R,Q,ce)=>{var we,Ue,Se,ne;W(!0);try{const pe=await ae.knowledgeLifecycle(R.id,Q,ce);re(`${R.title} → ${a(((we=mt[pe.lifecycle])==null?void 0:we.labelKey)||"")||pe.lifecycle}`,{title:a("knowledge.operationSuccess")}),u(Le=>Le.map(He=>He.id===R.id?pe:He)),(m==null?void 0:m.id)===R.id&&N(pe),te()}catch(pe){re(((ne=(Se=(Ue=pe==null?void 0:pe.response)==null?void 0:Ue.data)==null?void 0:Se.error)==null?void 0:ne.message)||(pe==null?void 0:pe.message)||a("common.operationFailed"),{title:a("common.operationFailed"),type:"error"})}finally{v.current&&W(!1)}},ie=async R=>{if(confirm(a("knowledge.deleteConfirmMsg",{title:R.title})))try{await ae.knowledgeDelete(R.id),re(a("knowledge.deleteSuccess",{title:R.title}),{title:a("common.delete")}),u(Q=>Q.filter(ce=>ce.id!==R.id)),(m==null?void 0:m.id)===R.id&&N(null),te()}catch(Q){re((Q==null?void 0:Q.message)||a("knowledge.deleteFailed"),{title:a("knowledge.deleteFailed"),type:"error"})}},be=async()=>{if(O.size!==0){je(!0);try{const R=await ae.knowledgeBatchPublish([...O]);re(a("knowledge.batchPublishResult",{success:R.successCount,fail:R.failureCount}),{title:a("knowledge.batchPublish")}),ye(new Set),de()}catch(R){re((R==null?void 0:R.message)||a("knowledge.batchPublishFailed"),{title:a("common.operationFailed"),type:"error"})}finally{je(!1)}}},B=async()=>{je(!0);try{const Q=((await ae.knowledgeList({lifecycle:"pending",limit:500})).data||[]).filter(we=>we.autoApprovable).map(we=>we.id);if(Q.length===0){re(a("knowledge.noAutoApprovable"),{title:a("knowledge.noPublishable")});return}const ce=await ae.knowledgeBatchPublish(Q);re(a("knowledge.autoPublishResult",{count:ce.successCount}),{title:a("knowledge.batchPublishComplete")}),de()}catch(R){re((R==null?void 0:R.message)||a("knowledge.batchPublishFailed"),{title:a("common.operationFailed"),type:"error"})}finally{je(!1)}},K=R=>{ye(Q=>{const ce=new Set(Q);return ce.has(R)?ce.delete(R):ce.add(R),ce})},xe=()=>{O.size===c.length?ye(new Set):ye(new Set(c.map(R=>R.id)))},P=(R,Q)=>{const ce=prompt(a("knowledge.deprecateReasonPrompt"));ce&&fe(R,Q,ce)};return e.jsxs("div",{className:"space-y-4",children:[p&&e.jsx("div",{className:"grid grid-cols-3 gap-3",children:Object.entries(mt).map(([R,Q])=>{const ce=p[R]||0,we=Q.icon;return e.jsxs("button",{onClick:()=>{A(T===R?"":R)},className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all text-left ${T===R?`${Q.bg} ${Q.border} ${Q.color} ring-1 ring-current`:"bg-white dark:bg-[#252a36] border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-[#2a3040]"}`,children:[e.jsx(we,{size:14}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium",children:l(R)}),e.jsx("div",{className:"text-lg font-bold",children:ce})]})]},R)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(ft,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:16}),e.jsx("input",{type:"text",placeholder:a("knowledge.searchPlaceholder"),value:q,onChange:R=>I(R.target.value),className:"w-full pl-9 pr-3 py-2 rounded-lg border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-300"})]}),e.jsx("div",{className:"flex gap-1",children:Object.entries(Jt).map(([R,Q])=>{const ce=Q.icon;return e.jsxs("button",{onClick:()=>_(G===R?"":R),className:`flex items-center gap-1 px-2.5 py-1.5 rounded-md text-xs font-medium border transition-all ${G===R?`${Q.bg} ${Q.border} ${Q.color}`:"bg-white dark:bg-[#252a36] border-slate-200 dark:border-slate-600 text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-[#2a3040]"}`,children:[e.jsx(ce,{size:12}),a(Q.labelKey)]},R)})}),e.jsxs("select",{value:E,onChange:R=>Z(R.target.value),className:"px-2.5 py-1.5 rounded-md text-xs border border-slate-200 dark:border-slate-600 bg-white dark:bg-[#252a36] text-slate-600 dark:text-slate-300 focus:outline-none",children:[e.jsx("option",{value:"",children:a("knowledge.allCategories")}),["View","Service","Tool","Model","Network","Storage","UI","Utility"].map(R=>e.jsx("option",{value:R,children:R},R))]}),e.jsx("button",{onClick:de,className:"p-2 rounded-md text-slate-400 hover:bg-slate-100",title:a("common.refresh"),children:e.jsx(yt,{size:16})}),O.size>0&&e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsx("span",{className:"text-xs text-slate-500",children:a("knowledge.selectedCount",{count:O.size})}),e.jsx("button",{onClick:be,disabled:Ne,className:"px-2.5 py-1 text-xs font-medium text-green-700 bg-green-50 border border-green-200 rounded-md hover:bg-green-100 disabled:opacity-50",children:Ne?e.jsx(Me,{size:12,className:"animate-spin"}):a("knowledge.batchPublish")}),e.jsx("button",{onClick:()=>ye(new Set),className:"p-1 text-slate-400 hover:text-slate-600",children:e.jsx(Xe,{size:14})})]}),O.size===0&&e.jsxs("button",{onClick:B,disabled:Ne,className:"ml-auto px-3 py-1.5 text-xs font-medium text-cyan-700 bg-cyan-50 border border-cyan-200 rounded-md hover:bg-cyan-100 disabled:opacity-50 flex items-center gap-1.5",children:[Ne?e.jsx(Me,{size:12,className:"animate-spin"}):e.jsx(et,{size:12}),a("knowledge.quickBatchPublish")]})]}),g?e.jsxs("div",{className:"flex items-center justify-center py-20 text-slate-400",children:[e.jsx(Me,{size:24,className:"animate-spin mr-2"}),e.jsx("span",{children:a("common.loading")})]}):c.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-slate-400",children:[e.jsx(tt,{size:48,className:"mb-4 opacity-30"}),e.jsx("p",{className:"text-sm",children:a("knowledge.noResults")}),(X||T||G||E)&&e.jsx("button",{onClick:()=>{I(""),A(""),_(""),Z("")},className:"mt-2 text-xs text-blue-500 hover:text-blue-700",children:a("knowledge.clearFilters")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("input",{type:"checkbox",checked:O.size===c.length&&c.length>0,onChange:xe,className:"rounded border-slate-300"}),e.jsx("span",{className:"text-xs text-slate-400",children:a("knowledge.selectAll")}),e.jsx("span",{className:"text-xs text-slate-400 ml-auto",children:a("knowledge.totalCount",{count:k})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:c.map(R=>{var ne,pe,Le,He,De,r;const Q=mt[R.lifecycle]||mt.pending,ce=Jt[R.kind]||Jt.pattern,we=Q.icon,Ue=ce.icon,Se=Fn((ne=R.reasoning)==null?void 0:ne.confidence);return e.jsxs("div",{onClick:()=>N(R),className:`group bg-white dark:bg-[#1e2028] rounded-xl border shadow-sm hover:shadow-md cursor-pointer transition-all overflow-hidden ${(m==null?void 0:m.id)===R.id?"ring-2 ring-blue-300 border-blue-200 dark:border-blue-700":"border-slate-200 dark:border-slate-700"}`,children:[e.jsxs("div",{className:"px-4 pt-3 pb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("input",{type:"checkbox",checked:O.has(R.id),onChange:C=>{C.stopPropagation(),K(R.id)},onClick:C=>C.stopPropagation(),className:"rounded border-slate-300"}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${Q.bg} ${Q.color} ${Q.border} border`,children:[e.jsx(we,{size:10}),l(R.lifecycle)]}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${ce.bg} ${ce.color} ${ce.border} border`,children:[e.jsx(Ue,{size:10}),a(ce.labelKey)]}),R.category&&e.jsx("span",{className:"text-[10px] text-slate-400",children:R.category}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${Se.bg} ${Se.text}`,children:((pe=R.reasoning)==null?void 0:pe.confidence)!=null?`${Math.round(R.reasoning.confidence*100)}%`:"—"}),R.autoApprovable&&R.lifecycle==="pending"&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] px-1.5 py-0.5 rounded bg-cyan-50 text-cyan-600 border border-cyan-200",children:[e.jsx(et,{size:9}),a("knowledge.autoApprovable")]})]}),e.jsx("h3",{className:"text-sm font-bold text-slate-900 mb-1 break-words leading-snug",children:R.title}),(R.description||((Le=R.content)==null?void 0:Le.rationale))&&e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed",children:R.description||((He=R.content)==null?void 0:He.rationale)||""}),((De=R.content)==null?void 0:De.pattern)&&e.jsx("pre",{className:"mt-1.5 text-[10px] text-slate-500 bg-slate-50 rounded p-1.5 line-clamp-3 font-mono overflow-hidden",children:zn(R.content.pattern,3)})]}),e.jsxs("div",{className:"px-4 py-2 bg-slate-50/80 dark:bg-[#252a36] border-t border-slate-100 dark:border-slate-700 flex items-center gap-2",children:[(r=R.tags)==null?void 0:r.slice(0,3).map(C=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100",children:C},C)),R.tags&&R.tags.length>3&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["+",R.tags.length-3]}),e.jsxs("span",{className:"text-[10px] text-slate-300 ml-auto",children:[R.trigger&&e.jsx("span",{className:"text-blue-400 mr-2",children:R.trigger}),R.source&&e.jsx("span",{className:"mr-2",children:R.source}),Yt(R.updatedAt,a)]})]})]},R.id)})}),e.jsx(Js,{currentPage:h,totalPages:Math.ceil(k/i),onPageChange:x,pageSize:i,onPageSizeChange:R=>{y(R),x(1)},totalItems:k})]}),m&&(()=>{var C,b,F,M,U,se,ue,he;const R=mt[m.lifecycle]||mt.pending,Q=R.icon,ce=Jt[m.kind]||Jt.pattern,we=pt[m.category||""]||pt.All||{},Ue=Es[m.source||""]||{labelKey:""};Ue.labelKey?a(Ue.labelKey):m.source;const Se=m.reasoning,ne=Se&&(Se.whyStandard||Se.sources&&Se.sources.length>0||Se.confidence!=null),pe=c.findIndex(D=>D.id===m.id),Le=pe>0,He=pe<c.length-1,De=()=>{Le&&N(c[pe-1])},r=()=>{He&&N(c[pe+1])};return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:()=>N(null),children:[e.jsx(Ze.Backdrop,{className:"bg-black/15 backdrop-blur-[1px]"}),e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col border-l border-slate-200 dark:border-slate-700 ${L?"w-[960px] max-w-[92vw]":"w-[700px] max-w-[92vw]"}`,style:{animation:"slideInRight 0.25s ease-out"},onClick:D=>D.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-700 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] shrink-0",children:[e.jsx("div",{className:"flex-1 min-w-0 mr-3",children:e.jsx("h3",{className:"font-bold text-slate-800 text-lg leading-snug break-words",children:m.title})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:De,disabled:!Le,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:a("knowledge.prev"),children:e.jsx(is,{size:z.md})}),e.jsxs("span",{className:"text-xs text-slate-400 tabular-nums",children:[pe+1,"/",c.length]}),e.jsx("button",{onClick:r,disabled:!He,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:a("knowledge.next"),children:e.jsx(rt,{size:z.md})}),e.jsx("div",{className:"w-px h-5 bg-slate-200 mx-1"}),e.jsx("button",{onClick:$,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400",title:a(L?"knowledge.narrow":"knowledge.widen"),children:L?e.jsx(Gs,{size:z.md}):e.jsx(Cs,{size:z.md})}),e.jsx("button",{onClick:()=>{ie(m),N(null)},className:"p-1.5 hover:bg-red-50 rounded-lg text-red-500 transition-colors",title:a("common.delete"),children:e.jsx(ot,{size:z.md})}),e.jsx("button",{onClick:()=>N(null),className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:z.md})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[m.rejectionReason&&e.jsxs("div",{className:"px-6 py-3 border-b border-red-200 dark:border-red-800/40 bg-red-50/80 dark:bg-red-900/15",children:[e.jsx("label",{className:"text-[10px] font-bold text-red-500 uppercase mb-1.5 block",children:a("knowledge.rejectionReason")}),e.jsx("p",{className:"text-xs text-red-600",children:m.rejectionReason})]}),e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${R.bg} ${R.color} ${R.border} border`,children:[e.jsx(Q,{size:10}),l(m.lifecycle)]}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${ce.bg} ${ce.color} ${ce.border} border`,children:[Ct.createElement(ce.icon,{size:10}),a(ce.labelKey)]}),e.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${(we==null?void 0:we.bg)||"bg-slate-50"} ${(we==null?void 0:we.color)||"text-slate-400"} ${(we==null?void 0:we.border)||"border-slate-100"}`,children:m.category||"general"}),m.knowledgeType&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-purple-50 text-purple-700 border border-purple-200",children:m.knowledgeType}),m.language&&e.jsx("span",{className:"text-[10px] uppercase font-bold text-slate-500 bg-slate-50 border border-slate-200 px-1.5 py-0.5 rounded",children:m.language}),m.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200 font-bold",children:m.trigger})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:[(()=>{const D=[];return m.scope&&D.push({icon:Pt,iconClass:"text-teal-400",label:a("knowledge.scope"),value:m.scope==="universal"?a("knowledge.scopeUniversal"):m.scope==="project-specific"?a("knowledge.scopeProject"):m.scope==="module-level"?a("knowledge.scopeModule"):m.scope}),m.complexity&&D.push({icon:lt,iconClass:"text-orange-400",label:a("knowledge.complexity"),value:m.complexity==="advanced"?a("knowledge.complexityAdvanced"):m.complexity==="intermediate"?a("knowledge.complexityIntermediate"):m.complexity==="beginner"?a("knowledge.complexityBeginner"):m.complexity}),m.source&&m.source!=="unknown"&&D.push({icon:Pt,iconClass:"text-violet-400",label:a("knowledge.source"),value:Es[m.source||""]?a(Es[m.source||""].labelKey):m.source||"-"}),m.createdAt&&D.push({icon:xt,iconClass:"text-slate-400",label:a("knowledge.createdAt"),value:Yt(m.createdAt,a)}),m.updatedAt&&D.push({icon:xt,iconClass:"text-slate-400",label:a("knowledge.updatedAt"),value:Yt(m.updatedAt,a)}),m.publishedAt&&D.push({icon:cs,iconClass:"text-emerald-400",label:a("knowledge.published"),value:Yt(m.publishedAt,a)}),D.map((V,ke)=>{const Ce=V.icon;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ce,{size:11,className:`${V.iconClass} shrink-0`}),e.jsx("span",{className:"text-slate-400",children:V.label}),e.jsx("span",{className:`font-medium text-slate-600 ${V.mono?"font-mono text-[11px]":""}`,children:V.value})]},ke)})})(),e.jsxs("div",{className:"flex items-center gap-1.5 basis-full mt-0.5",children:[e.jsx(as,{size:11,className:"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-slate-400",children:"ID"}),e.jsx("code",{className:"font-mono text-[11px] text-slate-500 break-all",children:m.id})]}),m.sourceFile&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full",children:[e.jsx(wt,{size:11,className:"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-slate-400",children:a("knowledge.sourceFile")}),e.jsx("code",{className:"font-mono text-[11px] text-slate-500 break-all",children:m.sourceFile})]})]})]}),m.tags&&m.tags.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100 flex flex-wrap items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-slate-300 mr-0.5"}),m.tags.map((D,V)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:D},V))]}),m.relations&&Object.entries(m.relations).some(([,D])=>Array.isArray(D)&&D.length>0)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(Hs,{size:12,className:"text-purple-400"}),e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:a("knowledge.relatedKnowledge")}),(()=>{const D=Object.values(m.relations).flat().length;return D>0?e.jsx("span",{className:"text-[9px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded-full font-bold",children:D}):null})()]}),e.jsx("div",{className:"space-y-1.5",children:Object.entries(m.relations).map(([D,V])=>!Array.isArray(V)||V.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-slate-500 shrink-0 whitespace-nowrap pt-0.5 uppercase",children:D}),e.jsx("div",{className:"flex flex-wrap gap-1",children:V.map((ke,Ce)=>{const Ie=ke.target||(typeof ke=="string"?ke:JSON.stringify(ke)),Be=ve.get(Ie)||Ie;return e.jsx("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 border rounded text-[10px] font-mono bg-purple-50 border-purple-200 text-purple-700",title:Ie,children:Be},Ce)})})]},D))})]}),m.stats&&Object.values(m.stats).some(D=>D>0)&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-amber-50/60 dark:bg-amber-900/20 rounded-xl p-3 text-center border border-amber-100 dark:border-amber-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:((C=m.stats)==null?void 0:C.authority)??"—"}),e.jsx("div",{className:"text-[10px] text-amber-500 font-medium",children:a("knowledge.authorityScore")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-lg font-bold text-slate-800",children:((b=m.stats)==null?void 0:b.guardHits)??0}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:a("knowledge.guardHits")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-lg font-bold text-slate-800",children:((F=m.stats)==null?void 0:F.adoptions)??0}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:a("knowledge.adoptions")})]}),e.jsxs("div",{className:"bg-blue-50/60 dark:bg-blue-900/20 rounded-xl p-3 text-center border border-blue-100 dark:border-blue-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:((M=m.stats)==null?void 0:M.searchHits)??0}),e.jsx("div",{className:"text-[10px] text-blue-500 font-medium",children:a("knowledge.searchHits")})]})]}),(m.stats.views>0||m.stats.applications>0)&&e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-slate-400",children:[e.jsxs("span",{children:[a("knowledge.statViews"),": ",m.stats.views]}),e.jsxs("span",{children:[a("knowledge.statApplications"),": ",m.stats.applications]})]})]}),ne&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-amber-400"})," ",a("knowledge.reasoning")]}),e.jsxs("div",{className:"bg-amber-50/30 dark:bg-amber-900/15 border border-amber-100 dark:border-amber-800/40 rounded-xl p-4 space-y-2.5",children:[Se.whyStandard&&!/^Submitted via /i.test(Se.whyStandard)&&e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:Se.whyStandard}),Se.sources&&Se.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[a("knowledge.source"),":"]}),Se.sources.map((D,V)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-white dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/40 rounded text-amber-700 dark:text-amber-400 font-mono",children:D},V))]}),Se.confidence!=null&&Se.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[a("knowledge.confidence"),":"]}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round((Se.confidence??0)*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round((Se.confidence??0)*100),"%"]})]}),Se.alternatives&&Se.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[a("knowledge.alternatives"),":"]}),Se.alternatives.map((D,V)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-slate-100 border border-slate-200 rounded text-slate-600",children:D},V))]})]})]}),m.quality&&m.quality.grade&&m.quality.grade!=="F"&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.qualityGrade")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${m.quality.grade==="A"?"text-emerald-600":m.quality.grade==="B"?"text-blue-600":m.quality.grade==="C"?"text-amber-600":m.quality.grade==="D"?"text-orange-600":"text-slate-400"}`,children:m.quality.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-[10px]",children:[m.quality.completeness!=null&&m.quality.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:m.quality.completeness.toFixed(2)}),e.jsx("div",{className:"text-slate-400",children:a("knowledge.qualityCompletionLabel")})]}),m.quality.adaptation!=null&&m.quality.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:m.quality.adaptation.toFixed(2)}),e.jsx("div",{className:"text-slate-400",children:a("knowledge.qualityAdaptation")})]}),m.quality.documentation!=null&&m.quality.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:m.quality.documentation.toFixed(2)}),e.jsx("div",{className:"text-slate-400",children:a("knowledge.qualityDocumentation")})]})]})]})]}),m.description&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:a("knowledge.summary")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:m.description})]}),((U=m.content)==null?void 0:U.markdown)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",a("knowledge.markdownDoc")]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 leading-relaxed",children:e.jsx(gt,{content:m.content.markdown})})})]}),m.headers&&m.headers.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.importHeaders")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:m.headers.map((D,V)=>e.jsx("code",{className:"px-2.5 py-1 bg-violet-50 text-violet-700 border border-violet-100 rounded-md text-[10px] font-mono font-medium",children:D},V))})]}),((se=m.content)==null?void 0:se.pattern)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ht,{size:11,className:"text-emerald-500"})," ",a("knowledge.codePattern")]}),e.jsx(ct,{code:m.content.pattern,language:m.language==="objc"?"objectivec":m.language,showLineNumbers:!0})]}),(m.doClause||m.whenClause||m.dontClause||m.topicHint||m.coreCode)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(lt,{size:11,className:"text-indigo-400"})," Cursor Delivery"]}),e.jsxs("div",{className:"bg-indigo-50/30 dark:bg-indigo-900/15 border border-indigo-100 dark:border-indigo-800/40 rounded-xl p-4 space-y-1.5 text-xs",children:[m.topicHint&&e.jsxs("div",{children:[e.jsx("span",{className:"text-indigo-500 font-medium",children:"Topic:"}),e.jsx("span",{className:"text-slate-700",children:m.topicHint})]}),m.whenClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-500 font-medium",children:"When:"}),e.jsx("span",{className:"text-slate-700",children:m.whenClause})]}),m.doClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-emerald-500 font-medium",children:"Do:"}),e.jsx("span",{className:"text-slate-700",children:m.doClause})]}),m.dontClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-red-500 font-medium",children:"Don't:"}),e.jsx("span",{className:"text-slate-700",children:m.dontClause})]}),m.coreCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-purple-500 font-medium",children:"Core Code:"}),e.jsx("div",{className:"mt-1",children:e.jsx(ct,{code:m.coreCode,language:m.language==="objc"?"objectivec":m.language||"text"})})]})]})]}),((ue=m.content)==null?void 0:ue.rationale)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.designRationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:m.content.rationale})})]}),((he=m.content)==null?void 0:he.steps)&&m.content.steps.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.implementSteps")}),e.jsx("div",{className:"space-y-2",children:m.content.steps.map((D,V)=>{if(typeof D=="string")return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:V+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:D})]},V);const ke=typeof D.title=="string"?D.title:"",Ce=typeof D.description=="string"?D.description:"",Ie=typeof D.code=="string"?D.code:"";return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:V+1}),ke&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:ke})]}),Ce&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:Ce}),Ie&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:Ie})]},V)})})]}),m.constraints&&(()=>{var ke,Ce,Ie,Be,Ye,J,Pe,qe;const D=m.constraints,V=(((ke=D.guards)==null?void 0:ke.length)||0)+(((Ce=D.boundaries)==null?void 0:Ce.length)||0)+(((Ie=D.preconditions)==null?void 0:Ie.length)||0)+(((Be=D.sideEffects)==null?void 0:Be.length)||0);return V?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(dt,{size:11,className:"text-amber-500"})," ",a("knowledge.constraintsLabel")," ",e.jsx("span",{className:"text-amber-500 font-mono",children:V})]}),e.jsxs("div",{className:"space-y-1.5 text-xs text-slate-600",children:[(Ye=D.guards)==null?void 0:Ye.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${ze.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-[10px] bg-slate-100 px-1.5 py-0.5 rounded",children:ze.pattern}),ze.message&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["— ",ze.message]})]},Ve)),(J=D.boundaries)==null?void 0:J.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),ze]},Ve)),(Pe=D.preconditions)==null?void 0:Pe.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),ze]},Ve)),(qe=D.sideEffects)==null?void 0:qe.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),ze]},Ve))]})]}):null})(),m.aiInsight&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-cyan-400"})," ",a("knowledge.aiInsight")]}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:m.aiInsight})]}),(()=>{const D=Array.isArray(m.lifecycleHistory)?m.lifecycleHistory:(()=>{try{const V=typeof m.lifecycleHistory=="string"?JSON.parse(m.lifecycleHistory):null;return Array.isArray(V)?V:[]}catch{return[]}})();return D.length>0?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(xt,{size:11,className:"text-slate-400"})," ",a("knowledge.lifecycleHistoryLabel")]}),e.jsx("div",{className:"space-y-1",children:D.map((V,ke)=>{const Ce=mt[V.from]||mt.pending,Ie=mt[V.to]||mt.pending;return e.jsxs("div",{className:"flex items-center gap-2 text-[10px]",children:[e.jsx("span",{className:"text-slate-400 w-20 shrink-0",children:Yt(V.at,a)}),e.jsx("span",{className:`${Ce.color}`,children:l(V.from)}),e.jsx("span",{className:"text-slate-300",children:"→"}),e.jsx("span",{className:`${Ie.color} font-medium`,children:l(V.to)}),e.jsxs("span",{className:"text-slate-400 ml-auto",children:["by ",V.by]})]},ke)})})]}):null})()]}),e.jsxs("div",{className:"shrink-0 border-t border-slate-200 dark:border-slate-700 px-5 py-3 bg-gradient-to-b from-slate-50/80 to-white dark:from-[#252526] dark:to-[#1e1e1e] flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("button",{onClick:()=>{ie(m),N(null)},className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-red-500 hover:bg-red-50 border border-red-200 transition-colors",children:[e.jsx(ot,{size:14})," ",a("common.delete")]})}),e.jsx("div",{className:"flex items-center gap-2",children:(Mn[m.lifecycle]||[]).map(D=>{const V=D.icon;return e.jsxs("button",{onClick:()=>D.needsReason?P(m,D.action):fe(m,D.action),disabled:j,className:`flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold border transition-colors disabled:opacity-50 ${D.bg} ${D.color} border-current/20`,children:[j?e.jsx(Me,{size:14,className:"animate-spin"}):e.jsx(V,{size:14}),d(D.action)]},D.action)})})]})]})]})})()]})},gs={manual:{label:"manual",color:"bg-slate-100 text-slate-600",icon:Ia},"user-ai":{label:"user-ai",color:"bg-violet-100 text-violet-600",icon:Qe},"system-ai":{label:"system-ai",color:"bg-amber-100 text-amber-600",icon:ns},"external-ai":{label:"external-ai",color:"bg-cyan-100 text-cyan-600",icon:qs}},$n=({onRefresh:t,signalSuggestionCount:s=0,onSuggestionCountChange:a})=>{const{t:l}=_e(),[d,c]=o.useState([]),[u,p]=o.useState(!0),[n,g]=o.useState(null),[f,h]=o.useState(!1),[x,i]=o.useState(!1),[y,k]=o.useState("all"),[w,T]=o.useState(!1),[A,G]=o.useState([]),[_,E]=o.useState(!1),[Z,X]=o.useState(!1),[H,q]=o.useState(null),[I,L]=o.useState(!1),[$,m]=o.useState(""),[N,j]=o.useState(!1),[W,O]=o.useState(!1),[ye,Ne]=o.useState(!1),je=o.useCallback(async()=>{var P;p(!0);try{const R=await ae.listSkills();c(R.skills||[])}catch(R){((P=R.response)==null?void 0:P.status)!==404&&re(R.message||"",{title:l("skills.fetchFailed"),type:"error"}),c([])}finally{p(!1)}},[]);o.useEffect(()=>{je()},[je]);const v=async P=>{if((n==null?void 0:n.skillName)===P){g(null);return}L(!1),O(!1),h(!0);try{const R=await ae.loadSkill(P);g(R)}catch{re(`"${P}" ${l("skills.loadError")}`,{title:l("skills.loadSkillFailed"),type:"error"})}finally{h(!1)}},ee=()=>{n!=null&&n.content&&(navigator.clipboard.writeText(n.content),T(!0),setTimeout(()=>T(!1),2e3))},te=()=>{n&&(m(n.content),L(!0))},de=()=>{L(!1),m("")},ve=async()=>{if(!(!n||!$.trim())){j(!0);try{await ae.updateSkill(n.skillName,{content:$}),re(l("skills.saveSuccess"),{title:`Skill "${n.skillName}" ${l("skills.updateSuccess")}`}),L(!1);const P=await ae.loadSkill(n.skillName);g(P)}catch(P){re(P.message||"",{title:l("skills.updateFailed"),type:"error"})}finally{j(!1)}}},fe=async()=>{if(n){Ne(!0);try{await ae.deleteSkill(n.skillName),re(l("skills.deleteSuccess"),{title:`Skill "${n.skillName}" ${l("skills.deleteSuccess")}`}),g(null),O(!1),L(!1),je(),t==null||t()}catch(P){re(P.message||"",{title:l("skills.deleteFailed"),type:"error"})}finally{Ne(!1)}}},ie=async()=>{E(!0),X(!0);try{const[P,R]=await Promise.allSettled([ae.suggestSkills(),ae.getSignalStatus()]),Q=P.status==="fulfilled"?P.value.suggestions||[]:[],ce=R.status==="fulfilled"?R.value.suggestions||[]:[],we=new Map;for(const Se of Q)we.set(Se.name,Se);for(const Se of ce)we.set(Se.name,{...we.get(Se.name),...Se});const Ue=[...we.values()];G(Ue),a==null||a(Ue.length)}catch(P){re(P.message||"",{title:l("skills.aiRecommendFailed"),type:"error"}),G([]),a==null||a(0)}finally{E(!1)}};o.useEffect(()=>{s>0&&A.length===0&&!Z&&ie()},[]);const be=async P=>{q(P.name);try{const R=P.description||P.rationale||P.name,Q=`${l("skillsView.aiPromptPrefix")}
119
118
 
120
- 名称:${L.name}
121
- 描述:${T}
122
- 推荐原因:${L.rationale}
119
+ 名称:${P.name}
120
+ 描述:${R}
121
+ 推荐原因:${P.rationale}
123
122
 
124
- 请直接生成 Skill 正文内容(Markdown 格式),不需要 frontmatter,不需要输出 JSON 元数据。内容应该详细、实用,包含具体的操作指南和示例。`;let ke=(await se.aiGenerateSkill(Q)).reply||L.body||`# ${T}
123
+ 请直接生成 Skill 正文内容(Markdown 格式),不需要 frontmatter,不需要输出 JSON 元数据。内容应该详细、实用,包含具体的操作指南和示例。`;let we=(await ae.aiGenerateSkill(Q)).reply||P.body||`# ${R}
125
124
 
126
- ${L.rationale||""}`;ke=ke.replace(/^\s*\{["']name["']\s*:.*\}\s*\n?/,"").trim(),await se.createSkill({name:L.name,description:T,content:ke,createdBy:"user-ai"}),re(l("skills.createAddedToKB"),{title:`Skill "${L.name}" ${l("skills.createSuccess")}`}),G(Ue=>{const Ie=Ue.filter(ne=>ne.name!==L.name);return a==null||a(Ie.length),Ie}),ye()}catch(T){re(T.message||"",{title:l("skills.createFailed"),type:"error"})}finally{q(null)}},$=d.filter(L=>j==="all"?!0:L.source===j).sort((L,T)=>L.source===T.source?L.name.localeCompare(T.name):L.source==="project"?-1:1),K=d.filter(L=>L.source==="builtin").length,xe=d.filter(L=>L.source==="project").length;return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-violet-100 rounded-xl flex items-center justify-center",children:e.jsx(tt,{size:20,className:"text-violet-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-800",children:l("skills.title")}),e.jsx("p",{className:"text-sm text-slate-500",children:l("skills.subtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:ce,disabled:z,className:"flex items-center gap-2 px-3 py-2 border border-amber-300 text-amber-700 bg-amber-50 rounded-lg hover:bg-amber-100 transition-colors text-sm font-medium disabled:opacity-50",title:l("skills.aiRecommendTooltip"),children:[z?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(jt,{size:14}),l("skills.aiRecommend")]}),e.jsx("button",{onClick:ye,className:"p-2 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors",title:l("common.refresh"),children:e.jsx(yt,{size:16})}),e.jsxs("button",{onClick:()=>c(!0),className:"flex items-center gap-2 px-4 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 transition-colors text-sm font-medium",children:[e.jsx(Qe,{size:14}),l("skills.addSkill")]})]})]}),e.jsx("div",{className:"flex items-center gap-1 mb-4 p-1 bg-slate-100 rounded-lg w-fit",children:[{key:"all",label:l("common.all"),count:d.length},{key:"project",label:l("skills.filterProject"),count:xe,icon:wt},{key:"builtin",label:l("skills.filterBuiltin"),count:K,icon:Ll}].map(L=>e.jsxs("button",{onClick:()=>w(L.key),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${j===L.key?"bg-white text-violet-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[L.icon&&e.jsx(L.icon,{size:12}),L.label,e.jsx("span",{className:`ml-0.5 px-1.5 py-0.5 rounded-full text-[10px] ${j===L.key?"bg-violet-100 text-violet-600":"bg-slate-200 text-slate-500"}`,children:L.count})]},L.key))}),Z&&e.jsxs("div",{className:"mb-4 border border-amber-200 bg-amber-50/50 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{size:16,className:"text-amber-600"}),e.jsx("span",{className:"text-sm font-semibold text-amber-800",children:l("skills.aiRecommendDesc")}),S.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 bg-amber-200 text-amber-700 text-[10px] font-bold rounded-full",children:S.length})]}),e.jsx("button",{onClick:()=>X(!1),className:"p-1 text-amber-400 hover:text-amber-600",children:e.jsx(Xe,{size:14})})]}),z?e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs py-2",children:[e.jsx(Fe,{size:14,className:"animate-spin"}),l("skills.aiRecommending")]}):S.length===0?e.jsx("p",{className:"text-xs text-amber-600/70",children:l("skills.noRecommendations")}):e.jsx("div",{className:"space-y-2",children:S.map(L=>e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-white rounded-lg border border-amber-100",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-mono text-xs font-semibold text-slate-800",children:L.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-bold uppercase ${L.priority==="high"?"bg-red-100 text-red-600":L.priority==="medium"?"bg-amber-100 text-amber-600":"bg-slate-100 text-slate-500"}`,children:L.priority}),e.jsx("span",{className:"text-[10px] text-slate-400",children:L.source})]}),e.jsx("p",{className:"text-xs text-slate-600 mb-1",children:L.description}),e.jsx("p",{className:"text-[11px] text-slate-400 line-clamp-2",children:L.rationale})]}),e.jsx("button",{onClick:()=>je(L),disabled:H===L.name,className:"shrink-0 flex items-center gap-1.5 px-3 py-1.5 bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors text-xs font-medium disabled:opacity-50",children:H===L.name?e.jsxs(e.Fragment,{children:[e.jsx(Fe,{size:12,className:"animate-spin"})," ",l("skills.creating")]}):e.jsxs(e.Fragment,{children:[e.jsx(et,{size:12})," ",l("skills.acceptRecommend")]})})]},L.name))})]}),e.jsxs("div",{className:"flex-1 flex gap-6 min-h-0 overflow-hidden",children:[e.jsx("div",{className:"w-1/2 overflow-y-auto pr-2 space-y-2",children:u?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Fe,{size:24,className:"animate-spin text-violet-400"})}):$.length===0?e.jsxs("div",{className:"text-center py-20 text-slate-400",children:[e.jsx(tt,{size:40,className:"mx-auto mb-3 opacity-40"}),e.jsx("p",{children:l("skills.noResults")})]}):$.map(L=>e.jsx("button",{onClick:()=>v(L.name),className:`w-full text-left p-4 rounded-xl border transition-all ${(n==null?void 0:n.skillName)===L.name?"border-violet-300 bg-violet-50 shadow-sm":"border-slate-200 bg-white hover:border-slate-300 hover:shadow-sm"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`mt-0.5 shrink-0 ${(n==null?void 0:n.skillName)===L.name?"text-violet-500":"text-slate-400"}`,children:(n==null?void 0:n.skillName)===L.name?e.jsx(Gt,{size:16}):e.jsx(rt,{size:16})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-mono text-sm font-semibold text-slate-800",children:L.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${L.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:L.source==="builtin"?l("skills.filterBuiltin"):l("skills.filterProject")}),L.createdBy&&gs[L.createdBy]&&(()=>{const T=gs[L.createdBy],Q=T.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${T.color}`,children:[e.jsx(Q,{size:10}),T.label]})})()]}),e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2",children:L.summary}),L.useCase&&e.jsxs("p",{className:"text-[11px] text-violet-500 mt-1 italic",children:[l("skills.useCase"),":",L.useCase]})]})]})},L.name))}),e.jsx("div",{className:"w-1/2 overflow-y-auto border border-slate-200 rounded-xl bg-white",children:f?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Fe,{size:24,className:"animate-spin text-violet-400"})}):n?e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{size:16,className:"text-violet-500"}),e.jsx("span",{className:"font-mono font-semibold text-sm",children:n.skillName}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase ${n.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:n.source==="builtin"?l("skills.filterBuiltin"):l("skills.filterProject")}),n.createdBy&&gs[n.createdBy]&&(()=>{const L=gs[n.createdBy],T=L.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${L.color}`,children:[e.jsx(T,{size:10}),l(`skills.createdBy.${n.createdBy}`)]})})()]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-slate-400",children:[n.charCount," ",l("skills.chars")]}),e.jsx("button",{onClick:ee,className:"p-1.5 rounded-md hover:bg-slate-100 transition-colors text-slate-400 hover:text-slate-600",title:l("common.copy"),children:C?e.jsx(kt,{size:14,className:"text-emerald-500"}):e.jsx(qt,{size:14})}),n.source==="project"&&!R&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:ae,className:"p-1.5 rounded-md hover:bg-blue-50 transition-colors text-slate-400 hover:text-blue-600",title:l("common.edit"),children:e.jsx(Ms,{size:14})}),e.jsx("button",{onClick:()=>O(!0),className:"p-1.5 rounded-md hover:bg-red-50 transition-colors text-slate-400 hover:text-red-500",title:l("common.delete"),children:e.jsx(ot,{size:14})})]}),R&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:fe,disabled:N,className:"flex items-center gap-1 px-2.5 py-1 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors text-xs font-medium disabled:opacity-50",children:[N?e.jsx(Fe,{size:12,className:"animate-spin"}):e.jsx(Ss,{size:12}),l("common.save")]}),e.jsx("button",{onClick:ue,className:"px-2.5 py-1 border border-slate-200 text-slate-500 rounded-md hover:bg-slate-50 transition-colors text-xs",children:l("common.cancel")})]})]})]}),n.relatedSkills.length>0&&e.jsxs("div",{className:"px-4 py-2 border-b border-slate-50 flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 uppercase font-bold",children:[l("skills.related"),":"]}),n.relatedSkills.map(L=>e.jsx("button",{onClick:()=>v(L),className:"text-[11px] text-violet-600 hover:text-violet-800 bg-violet-50 px-2 py-0.5 rounded-full transition-colors",children:L},L))]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 relative",children:[R?e.jsx("textarea",{value:_,onChange:L=>m(L.target.value),className:"w-full h-full min-h-[300px] text-xs text-slate-700 font-mono leading-relaxed border border-blue-200 rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-blue-300 resize-none bg-blue-50/30",spellCheck:!1}):e.jsx("pre",{className:"whitespace-pre-wrap text-xs text-slate-700 font-mono leading-relaxed",children:n.content}),W&&e.jsx("div",{className:"absolute inset-0 bg-white/90 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsxs("div",{className:"bg-white border border-red-200 rounded-xl shadow-lg p-6 max-w-sm text-center",children:[e.jsx(ot,{size:32,className:"mx-auto mb-3 text-red-400"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:l("skills.deleteConfirm")}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:l("skills.deleteSkillConfirmMsg",{name:n.skillName})}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsx("button",{onClick:()=>O(!1),className:"px-4 py-2 border border-slate-200 text-slate-600 rounded-lg hover:bg-slate-50 text-sm",children:l("common.cancel")}),e.jsxs("button",{onClick:he,disabled:be,className:"flex items-center gap-1.5 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 text-sm font-medium disabled:opacity-50",children:[be?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(ot,{size:14}),l("skills.confirmDelete")]})]})]})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full text-slate-400",children:e.jsxs("div",{className:"text-center",children:[e.jsx(tt,{size:40,className:"mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:l("skills.selectToView")})]})})})]}),x&&e.jsx(Gn,{onClose:()=>c(!1),onCreated:()=>{c(!1),ye(),t==null||t()}})]})},Gn=({onClose:t,onCreated:s})=>{const{t:a}=_e(),[l,d]=o.useState("ai"),[i,u]=o.useState(""),[p,n]=o.useState(!1),[g,f]=o.useState(""),[h,x]=o.useState(""),[c,j]=o.useState(""),[w,C]=o.useState(!1),[E,S]=o.useState(""),[G,z]=o.useState(!1),P=async()=>{if(i.trim()){n(!0),S("");try{const H=(await se.aiGenerateSkill(i)).reply||"";let q="",R="",M=H;const _=/```(?:json)?\s*\n?\s*(\{[^}]*"name"[^}]*\})\s*\n?\s*```/i,m=H.match(_);if(m)try{const N=JSON.parse(m[1]);q=N.name||"",R=N.description||"",M=H.replace(m[0],"").trim()}catch{}if(!q){const N=H.split(`
127
- `);for(let y=0;y<Math.min(N.length,5);y++){const W=N[y].trim();if(!(!W||W.startsWith("```"))&&W.startsWith("{")&&W.endsWith("}"))try{const O=JSON.parse(W);if(O.name){q=O.name,R=O.description||"";let be=y+1;for(;be<N.length&&!N[be].trim();)be++;M=N.slice(be).join(`
128
- `).trim();break}}catch{}}}if(!q){const N=/"name"\s*:\s*"([a-z][a-z0-9-]{1,62}[a-z0-9])"/,y=/"description"\s*:\s*"([^"]+)"/,W=H.match(N),O=H.match(y);W&&(q=W[1]),O&&(R=O[1])}M=M.replace(/```(?:json)?\s*\n?\s*\{[^}]*"name"[^}]*\}\s*\n?\s*```/gi,"").replace(/^\s*\{[^}]*"name"[^}]*\}\s*$/gm,"").trim(),q&&f(q),R&&x(R),j(M||H.trim()),z(!0),d("manual"),re(a("skills.checkGenerated"),{title:a("skills.aiGenerated")})}catch(X){S(a("skills.aiGenFailed")+": "+(X.message||""))}finally{n(!1)}}},Z=async()=>{var X,H,q;if(!g.trim()||!h.trim()||!c.trim()){S(a("skills.fillRequired"));return}C(!0),S("");try{await se.createSkill({name:g.trim(),description:h.trim(),content:c.trim(),createdBy:G?"user-ai":"manual"}),re(a("skills.savedToKB"),{title:`Skill "${g}" ${a("skills.createSuccess")}`}),s()}catch(R){const M=((q=(H=(X=R.response)==null?void 0:X.data)==null?void 0:H.error)==null?void 0:q.message)||R.message||"";S(a("skills.createFailed")+": "+M)}finally{C(!1)}};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center",children:[e.jsx(Ze.Backdrop,{className:"bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white rounded-2xl shadow-2xl w-[720px] max-h-[85vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-violet-100 rounded-lg flex items-center justify-center",children:e.jsx(Qe,{size:16,className:"text-violet-600"})}),e.jsx("h3",{className:"font-bold text-lg",children:a("skills.addSkill")})]}),e.jsx("button",{onClick:t,className:"p-1.5 rounded-lg hover:bg-slate-100 transition-colors",children:e.jsx(Xe,{size:18,className:"text-slate-400"})})]}),e.jsx("div",{className:"px-6 pt-4",children:e.jsxs("div",{className:"inline-flex items-center gap-1 p-1 bg-slate-100 rounded-lg",children:[e.jsxs("button",{onClick:()=>d("ai"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${l==="ai"?"bg-white text-violet-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(Qe,{size:12}),a("skills.aiGenMode")]}),e.jsxs("button",{onClick:()=>d("manual"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${l==="manual"?"bg-white text-violet-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(nt,{size:12}),a("skills.manualMode")]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[l==="ai"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1.5",children:a("skills.describeSkill")}),e.jsx("div",{className:"relative",children:e.jsx("textarea",{value:i,onChange:X=>u(X.target.value),placeholder:a("skillsView.placeholderDesc"),className:"w-full h-32 px-4 py-3 border border-slate-200 rounded-xl text-sm resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400",disabled:p})})]}),e.jsx("button",{onClick:P,disabled:p||!i.trim(),className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-violet-600 text-white rounded-xl hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium",children:p?e.jsxs(e.Fragment,{children:[e.jsx(Fe,{size:16,className:"animate-spin"}),a("skills.aiGeneratingContent")]}):e.jsxs(e.Fragment,{children:[e.jsx(Bs,{size:16}),a("skills.generateSkill")]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-700 mb-1.5",children:[a("skills.skillName")," ",e.jsx("span",{className:"text-slate-400 text-xs",children:"(kebab-case)"})]}),e.jsx("input",{type:"text",value:g,onChange:X=>f(X.target.value),placeholder:"my-custom-skill",className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1.5",children:a("skills.skillDescription")}),e.jsx("input",{type:"text",value:h,onChange:X=>x(X.target.value),placeholder:a("skillsView.placeholderName"),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-700 mb-1.5",children:[a("skills.skillContent")," ",e.jsx("span",{className:"text-slate-400 text-xs",children:"(Markdown)"})]}),e.jsx("textarea",{value:c,onChange:X=>j(X.target.value),placeholder:a("skillsView.placeholderContent"),className:"w-full h-64 px-4 py-3 border border-slate-200 rounded-xl text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400 leading-relaxed"})]})]}),E&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:[e.jsx(Ot,{size:16,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:E})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-slate-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-slate-600 hover:text-slate-800 transition-colors",children:a("common.cancel")}),l==="manual"&&e.jsx("button",{onClick:Z,disabled:w||!g.trim()||!h.trim()||!c.trim(),className:"flex items-center gap-2 px-5 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm font-medium",children:w?e.jsxs(e.Fragment,{children:[e.jsx(Fe,{size:14,className:"animate-spin"}),a("common.saving")]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{size:14}),a("skills.addSkill")]})})]})]})]})},ja=["objc-deep-scan","category-scan","project-profile","code-standard","architecture","code-pattern","event-and-data-flow","best-practice","agent-guidelines"],Hn={"code-standard":e.jsx(tt,{className:"w-5 h-5"}),"code-pattern":e.jsx(Ht,{className:"w-5 h-5"}),architecture:e.jsx(lt,{className:"w-5 h-5"}),"best-practice":e.jsx(Qe,{className:"w-5 h-5"}),"event-and-data-flow":e.jsx(et,{className:"w-5 h-5"}),"project-profile":e.jsx(Ea,{className:"w-5 h-5"}),"agent-guidelines":e.jsx(qs,{className:"w-5 h-5"})};function qn(t){return Hn[t]||e.jsx(Ht,{className:"w-5 h-5"})}const On=({task:t})=>{const{t:s}=_e(),{status:a,meta:l}=t,d={skeleton:"bg-slate-50 border-slate-200",filling:"bg-blue-50 border-blue-300",completed:"bg-emerald-50 border-emerald-300",failed:"bg-red-50 border-red-300"},i={skeleton:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-slate-400",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-300"}),s("bootstrap.statusLabels.skeleton")]}),filling:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-blue-600",children:[e.jsx(Fe,{className:"w-3 h-3 animate-spin"}),s("bootstrap.statusLabels.filling")]}),completed:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-emerald-600",children:[e.jsx(kt,{className:"w-3 h-3"}),s("bootstrap.statusLabels.completed")]}),failed:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-red-600",children:[e.jsx(Xe,{className:"w-3 h-3"}),s("bootstrap.statusLabels.failed")]})};return e.jsxs("div",{className:`relative rounded-xl border p-4 transition-all duration-300 ${d[a]||d.skeleton}`,children:[a==="skeleton"&&e.jsx("div",{className:"absolute inset-0 rounded-xl overflow-hidden",children:e.jsx("div",{className:"animate-pulse bg-gradient-to-r from-transparent via-slate-200/40 to-transparent h-full w-full"})}),a==="filling"&&e.jsx("div",{className:"absolute inset-0 rounded-xl overflow-hidden",children:e.jsx("div",{className:"animate-pulse bg-gradient-to-r from-transparent via-blue-200/30 to-transparent h-full w-full"})}),e.jsxs("div",{className:"relative z-10 flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`flex-shrink-0 p-2 rounded-lg ${a==="completed"?"bg-emerald-100 text-emerald-600":a==="filling"?"bg-blue-100 text-blue-600":a==="failed"?"bg-red-100 text-red-600":"bg-slate-100 text-slate-400"}`,children:qn(t.id)}),e.jsxs("div",{children:[e.jsx("h3",{className:`font-medium text-sm ${a==="skeleton"?"text-slate-400":"text-slate-800"}`,children:(()=>{const u=`bootstrap.pipelineLabels.${l.dimId}`,p=s(u);return p!==u?p:l.label})()}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[l.skillWorthy?"Skill":"Candidate",t.result&&a==="completed"&&e.jsx("span",{className:"ml-2 text-emerald-600",children:(()=>{const u=t.result,p=u.sourceCount??0,n=u.extracted??0;return u.type==="empty"?s("bootstrap.noMatch"):u.type==="skill"?u.empty?s("bootstrap.noMatch"):n>0?s("bootstrap.featuresAndCandidates",{sourceCount:p,extracted:n}):s("bootstrap.featuresOnly",{sourceCount:p}):n>0?s("bootstrap.candidatesOnly",{extracted:n}):s("bootstrap.noMatch")})()}),t.error&&a==="failed"&&e.jsx("span",{className:"ml-2 text-red-500 truncate max-w-[200px] inline-block align-bottom",children:t.error})]})]})]}),e.jsx("div",{className:"flex-shrink-0",children:i[a]})]})]})},Kn=[{key:"round1",labelKey:"bootstrap.reviewRounds.round1Label",descKey:"bootstrap.reviewRounds.round1Desc",icon:e.jsx(za,{className:"w-4 h-4"})},{key:"round2",labelKey:"bootstrap.reviewRounds.round2Label",descKey:"bootstrap.reviewRounds.round2Desc",icon:e.jsx(fs,{className:"w-4 h-4"})},{key:"round3",labelKey:"bootstrap.reviewRounds.round3Label",descKey:"bootstrap.reviewRounds.round3Desc",icon:e.jsx(Ml,{className:"w-4 h-4"})}],Un=({review:t})=>{const{t:s}=_e();return t.activeRound===0?null:e.jsxs("div",{className:"mt-5 border border-purple-200 rounded-xl bg-purple-50/50 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(rs,{className:"w-5 h-5 text-purple-600"}),e.jsx("h3",{className:"text-sm font-semibold text-purple-800",children:s("bootstrap.reviewPipeline")})]}),e.jsx("div",{className:"space-y-2.5",children:Kn.map(({key:a,labelKey:l,descKey:d,icon:i})=>{const u=t[a],p=u.status==="running",n=u.status==="completed",g=u.status==="idle";return e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg border transition-all duration-300 ${p?"border-purple-300 bg-purple-100/60":n?"border-emerald-300 bg-emerald-50/60":"border-slate-200 bg-white/40"}`,children:[e.jsx("div",{className:`flex-shrink-0 p-1.5 rounded-md ${p?"bg-purple-200 text-purple-700":n?"bg-emerald-100 text-emerald-600":"bg-slate-100 text-slate-400"}`,children:i}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-sm font-medium ${g?"text-slate-400":"text-slate-800"}`,children:s(l)}),e.jsx("span",{className:"text-xs text-slate-400",children:s(d)})]}),a==="round1"&&n&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round1Done",{kept:t.round1.kept??"?",merged:t.round1.merged??0,dropped:t.round1.dropped??0})}),a==="round2"&&p&&typeof t.round2.progress=="number"&&e.jsxs("div",{className:"mt-1.5",children:[e.jsx("div",{className:"w-full h-1.5 bg-purple-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-purple-500 rounded-full transition-all duration-300",style:{width:`${t.round2.progress}%`}})}),e.jsx("p",{className:"text-xs text-purple-600 mt-0.5",children:s("bootstrap.round2Progress",{current:t.round2.current??0,total:t.round2.total??"?"})})]}),a==="round2"&&n&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round2Done",{refined:t.round2.refined??"?",total:t.round2.total??"?"})}),a==="round3"&&n&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round3Done",{afterDedup:t.round3.afterDedup??"?",relationsFound:t.round3.relationsFound??0})})]}),e.jsxs("div",{className:"flex-shrink-0",children:[p&&e.jsx(Fe,{className:"w-4 h-4 text-purple-500 animate-spin"}),n&&e.jsx(kt,{className:"w-4 h-4 text-emerald-500"})]})]},a)})})]})};function va(t){if(t<0)return"--";const s=Math.floor(t/1e3),a=Math.floor(s/60),l=s%60;return a===0?`${l}s`:`${a}m ${l.toString().padStart(2,"0")}s`}const Wn=({session:t,isAllDone:s,reviewState:a,onDismiss:l})=>{const{t:d}=_e(),i=o.useRef(!1),[u,p]=o.useState(Date.now());if(o.useEffect(()=>{if(!t||t.status!=="running")return;const w=setInterval(()=>p(Date.now()),1e3);return()=>clearInterval(w)},[t==null?void 0:t.status]),o.useEffect(()=>{if(s&&t&&!i.current){i.current=!0;const w=t.failed>0?d("bootstrap.notifyPartial",{completed:t.completed,total:t.total,failed:t.failed}):d("bootstrap.notifySuccess",{completed:t.completed});re(w,{title:d("bootstrap.coldStartComplete"),type:t.failed>0?"error":"success"})}},[s,t]),o.useEffect(()=>{t||(i.current=!1)},[t==null?void 0:t.id]),!t)return null;const n=t.startedAt?u-t.startedAt:t.elapsedMs??0,g=t.completed+t.failed,f=t.total-g,h=t.elapsedMs??0,x=g>0&&h>0?Math.round(h/g*f):-1,c=t.totalToolCalls??0,j=t.status==="completed"?d("bootstrap.allCompleted"):t.status==="completed_with_errors"?d("bootstrap.completedWithErrors"):null;return e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-800",children:d("bootstrap.title")}),j&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:j})]}),s&&l&&e.jsx("button",{onClick:l,className:"text-sm px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors",children:d("bootstrap.close")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-5 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-slate-600",children:[e.jsx(xt,{size:14,className:"text-slate-400"}),e.jsxs("span",{children:[d("bootstrap.elapsed")," ",e.jsx("span",{className:"font-medium text-slate-800",children:va(n)})]})]}),t.status==="running"&&f>0&&x>0&&e.jsxs("div",{className:"flex items-center gap-1.5 text-slate-600",children:[e.jsx(xt,{size:14,className:"text-blue-400"}),e.jsxs("span",{children:[d("bootstrap.estimatedRemaining")," ",e.jsx("span",{className:"font-medium text-blue-600",children:va(x)})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-slate-600",children:[e.jsx($a,{size:14,className:"text-slate-400"}),e.jsxs("span",{children:[d("bootstrap.toolCalls")," ",e.jsx("span",{className:"font-medium text-slate-800",children:c})]})]}),e.jsx("div",{className:"text-slate-400 text-xs",children:d("bootstrap.dimensions",{done:g,total:t.total})})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:[...t.tasks].sort((w,C)=>{var G,z;const E=ja.indexOf(((G=w.meta)==null?void 0:G.dimId)??w.id),S=ja.indexOf(((z=C.meta)==null?void 0:z.dimId)??C.id);return(E===-1?999:E)-(S===-1?999:S)}).map(w=>e.jsx(On,{task:w},w.id))}),a&&a.activeRound>0&&e.jsx(Un,{review:a})]})},bs={index:{icon:tt,color:"text-blue-600",label:"overview"},architecture:{icon:lt,color:"text-violet-600",label:"architecture"},"getting-started":{icon:ht,color:"text-emerald-600",label:"getting-started"},protocols:{icon:Qe,color:"text-amber-600",label:"protocols"},components:{icon:ht,color:"text-emerald-600",label:"components"},patterns:{icon:Qe,color:"text-amber-600",label:"patterns"},module:{icon:wt,color:"text-cyan-600",label:"module"},document:{icon:nt,color:"text-orange-600",label:"document"},_index:{icon:as,color:"text-slate-500",label:"index"}};function Vn(t){var a;const s=((a=t.split("/").pop())==null?void 0:a.replace(".md",""))||"";return s==="_index"?bs._index:t.startsWith("modules/")?bs.module:t.startsWith("documents/")?bs.document:bs[s]||{icon:nt,color:"text-slate-500",label:"doc"}}const Jn={"cursor-devdocs":{label:"Cursor Docs",color:"text-orange-700",bg:"bg-orange-50 border-orange-200"}},Yn={modules:"modules",documents:"documents"};function Za(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Qn(t){if(!t)return"";const s=new Date(t);if(isNaN(s.getTime()))return"";const l=Date.now()-s.getTime();return l<6e4?"just now":l<36e5?`${Math.floor(l/6e4)} min ago`:l<864e5?`${Math.floor(l/36e5)} hr ago`:l<6048e5?`${Math.floor(l/864e5)} d ago`:s.toLocaleDateString("zh-CN")}const Xn=({task:t,wiki:s})=>{const{t:a}=_e();return t.status==="running"?null:t.status==="error"?e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-xl p-4 mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-red-100 rounded-lg",children:e.jsx(Ot,{size:F.md,className:"text-red-600"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-red-800",children:a("wiki.genFailed")}),e.jsx("span",{className:"text-sm text-red-600 ml-3",children:t.error||a("common.operationFailed")})]})]}):s!=null&&s.exists&&s.hasChanges?e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-amber-100 rounded-lg",children:e.jsx(Ot,{size:F.md,className:"text-amber-600"})}),e.jsx("span",{className:"text-sm text-amber-700",children:a("wiki.outOfDateHint")})]}):null};function Zn(t,s){const a=[],l=new Map((s==null?void 0:s.map(g=>[g.path,g]))||[]),d=[],i=new Map;for(const g of t){const f=g.path.split("/"),h=l.get(g.path);if(f.length===1)d.push({name:f[0],path:g.path,isDir:!1,file:g,metaInfo:h});else{const x=f[0];i.has(x)||i.set(x,[]),i.get(x).push({name:f.slice(1).join("/"),path:g.path,isDir:!1,file:g,metaInfo:h})}}const u=["index.md","architecture.md","getting-started.md","patterns.md","protocols.md","components.md"];d.sort((g,f)=>{const h=u.indexOf(g.name),x=u.indexOf(f.name);return h!==-1&&x!==-1?h-x:h!==-1?-1:x!==-1?1:g.name.localeCompare(f.name)}),a.push(...d);const p=["modules","patterns","documents"],n=[...i.entries()].sort(([g],[f])=>{const h=p.indexOf(g),x=p.indexOf(f);return h!==-1&&x!==-1?h-x:h!==-1?-1:x!==-1?1:g.localeCompare(f)});for(const[g,f]of n){const h=f.filter(x=>!x.name.startsWith("_index")).sort((x,c)=>x.name.localeCompare(c.name));a.push({name:g,path:g,isDir:!0,children:h})}return a}const eo=({tree:t,selectedFile:s,onSelect:a,searchQuery:l})=>{const[d,i]=o.useState(new Set(["modules","documents"])),u=g=>{i(f=>{const h=new Set(f);return h.has(g)?h.delete(g):h.add(g),h})},n=(g=>{if(!l)return g;const f=l.toLowerCase();return g.filter(h=>{var x;return h.isDir?(x=h.children)==null?void 0:x.some(c=>c.name.toLowerCase().includes(f)||c.path.toLowerCase().includes(f)):h.name.toLowerCase().includes(f)||h.path.toLowerCase().includes(f)})})(t);return e.jsx("div",{className:"space-y-0.5",children:n.map(g=>{var f;if(g.isDir){const h=d.has(g.path),x=l.toLowerCase(),c=l?(f=g.children)==null?void 0:f.filter(j=>j.name.toLowerCase().includes(x)||j.path.toLowerCase().includes(x)):g.children;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>u(g.path),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 rounded-lg transition-colors",children:[h?e.jsx(Gt,{size:14,className:"text-slate-400 flex-shrink-0"}):e.jsx(rt,{size:14,className:"text-slate-400 flex-shrink-0"}),e.jsx(wt,{size:14,className:"text-amber-500 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:Yn[g.name]||g.name}),e.jsx("span",{className:"ml-auto text-xs text-slate-400",children:(c==null?void 0:c.length)||0})]}),h&&c&&e.jsx("div",{className:"ml-3",children:c.map(j=>e.jsx(Na,{node:j,isActive:s===j.path,onSelect:a},j.path))})]},g.path)}return e.jsx(Na,{node:g,isActive:s===g.path,onSelect:a},g.path)})})},Na=({node:t,isActive:s,onSelect:a})=>{var p,n;const l=Vn(t.path),d=l.icon,i=(p=t.metaInfo)==null?void 0:p.polished,u=(n=t.metaInfo)==null?void 0:n.source;return e.jsxs("button",{onClick:()=>a(t.path),className:`w-full flex items-center gap-2 px-3 py-2 text-sm rounded-lg transition-all ${s?"bg-blue-50 text-blue-700 border border-blue-200 shadow-sm":"text-slate-600 hover:bg-slate-50"}`,children:[e.jsx(d,{size:14,className:`flex-shrink-0 ${s?"text-blue-500":l.color}`}),e.jsx("span",{className:"truncate text-left",children:t.name.replace(".md","")}),e.jsxs("span",{className:"ml-auto flex items-center gap-1 flex-shrink-0",children:[i&&e.jsx("span",{title:"AI Enhanced",children:e.jsx(Qe,{size:10,className:"text-violet-400"})}),u&&e.jsx("span",{title:`Source: ${u}`,children:e.jsx(zl,{size:10,className:"text-orange-400"})})]})]})},to=({filePath:t,content:s,loading:a,meta:l,onBack:d})=>{var x;const{t:i}=_e(),[u,p]=o.useState(!1),n=(x=l==null?void 0:l.files)==null?void 0:x.find(c=>c.path===t),g=()=>{navigator.clipboard.writeText(s),p(!0),setTimeout(()=>p(!1),2e3)},f=t.split("/"),h=f.map((c,j)=>({label:j===f.length-1?c.replace(".md",""):c,isLast:j===f.length-1}));return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 bg-slate-50 border-b border-slate-200 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:d,className:"p-1.5 hover:bg-slate-200 rounded-lg transition-colors lg:hidden",title:i("wiki.backToList"),children:e.jsx(Fl,{size:F.md})}),e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(tt,{size:14,className:"text-slate-400"}),e.jsx("span",{className:"text-slate-400",children:"wiki"}),h.map((c,j)=>e.jsxs(Ct.Fragment,{children:[e.jsx(rt,{size:12,className:"text-slate-300"}),e.jsx("span",{className:c.isLast?"font-medium text-slate-700":"text-slate-400",children:c.label})]},j))]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(n==null?void 0:n.polished)&&e.jsxs("span",{className:"flex items-center gap-1 text-xs text-violet-700 bg-violet-50 border border-violet-200 px-2 py-0.5 rounded-full",children:[e.jsx(Qe,{size:10}),i("wiki.aiBadge")]}),(n==null?void 0:n.source)&&(()=>{const c=Jn[n.source];return e.jsx("span",{className:`flex items-center gap-1 text-xs border px-2 py-0.5 rounded-full ${(c==null?void 0:c.bg)||"bg-slate-50 border-slate-200"} ${(c==null?void 0:c.color)||"text-slate-600"}`,children:(c==null?void 0:c.label)||n.source})})(),e.jsxs("button",{onClick:g,className:"flex items-center gap-1 px-2.5 py-1 text-xs text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-md transition-colors",children:[u?e.jsx(kt,{size:12,className:"text-emerald-500"}):e.jsx(qt,{size:12}),i(u?"wiki.copySuccess":"wiki.copyBtn")]})]})]}),e.jsx("div",{className:"flex-1 overflow-auto scrollbar-light",style:{scrollbarGutter:"stable"},children:a?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Fe,{size:F.xl,className:"text-blue-500 animate-spin"})}):e.jsx("div",{className:"px-8 py-6 max-w-4xl mx-auto",children:e.jsx(gt,{content:s,className:"wiki-reader"})})})]})},so=()=>{const{t}=_e();return e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-white rounded-2xl border border-dashed border-slate-200 text-slate-400",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-slate-50 flex items-center justify-center mb-4",children:e.jsx(tt,{size:32,className:"text-slate-300"})}),e.jsx("p",{className:"text-sm font-medium text-slate-500",children:t("wiki.emptyTitle")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-slate-400",children:t("wiki.emptyDesc")}),e.jsx("p",{className:"mt-3 text-[11px] text-slate-400",children:t("wiki.emptyHint")})]})},ao=({meta:t,onSelectFile:s,isGenerating:a,progress:l,message:d})=>{var g;const{t:i}=_e(),u=[{path:"index.md",label:i("wiki.quickOverview"),desc:i("wiki.quickOverviewDesc"),icon:tt,color:"bg-blue-50 text-blue-600 border-blue-200"},{path:"architecture.md",label:i("wiki.quickArch"),desc:i("wiki.quickArchDesc"),icon:lt,color:"bg-violet-50 text-violet-600 border-violet-200"},{path:"getting-started.md",label:i("wiki.quickStart"),desc:i("wiki.quickStartDesc"),icon:ht,color:"bg-emerald-50 text-emerald-600 border-emerald-200"},{path:"protocols.md",label:i("wiki.quickProtocols"),desc:i("wiki.quickProtocolsDesc"),icon:Qe,color:"bg-amber-50 text-amber-600 border-amber-200"}],p=new Set(((g=t==null?void 0:t.files)==null?void 0:g.map(f=>f.path||f.name))??[]),n=u.filter(f=>p.size===0||p.has(f.path));return e.jsxs("div",{className:"p-8 overflow-y-auto flex-1",children:[a&&e.jsxs("div",{className:"mb-8 flex flex-col items-center",children:[e.jsxs("div",{className:"relative w-20 h-20 mb-5",children:[e.jsx("span",{className:"absolute inset-0 rounded-full bg-blue-100 animate-ping opacity-20"}),e.jsx("span",{className:"absolute inset-2 rounded-full bg-blue-50 animate-pulse"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(qs,{size:36,className:"text-blue-500 animate-pulse"})})]}),e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-1",children:i("wiki.wikiGenerating")}),e.jsx("p",{className:"text-sm text-slate-500 max-w-md text-center leading-relaxed",children:d||i("wiki.generating")}),typeof l=="number"&&e.jsxs("div",{className:"mt-4 w-48",children:[e.jsx("div",{className:"w-full bg-slate-100 rounded-full h-2",children:e.jsx("div",{className:"bg-gradient-to-r from-blue-500 to-indigo-500 h-2 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(l,3)}%`}})}),e.jsxs("p",{className:"text-xs text-center text-blue-500 mt-1.5 font-mono",children:[l,"%"]})]})]}),!a&&e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-12 h-12 bg-slate-100 rounded-xl flex items-center justify-center mx-auto mb-3",children:e.jsx(nt,{size:24,className:"text-slate-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-700",children:i("wiki.selectFile")}),e.jsx("p",{className:"text-sm text-slate-500 mt-1",children:i("wiki.selectPlaceholder")})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 max-w-lg mx-auto",children:n.map(f=>{const h=f.icon;return e.jsxs("button",{onClick:()=>s(f.path),className:`text-left p-4 rounded-xl border ${f.color} hover:shadow-sm transition-all group`,children:[e.jsx(h,{size:20,className:"mb-2 opacity-70 group-hover:opacity-100"}),e.jsx("div",{className:"font-medium text-sm",children:f.label}),e.jsx("div",{className:"text-xs opacity-60 mt-0.5",children:f.desc})]},f.path)})}),t&&e.jsxs("div",{className:"mt-8 text-center text-xs text-slate-400",children:[t.generatedAt&&`${i("wiki.lastGenerated")}: ${new Date(t.generatedAt).toLocaleString()}`,t.duration!=null&&` · ${i("wiki.duration")} ${Za(t.duration)}`,t.version&&` · v${t.version}`]})]})},lo=()=>{const{t}=_e(),[s,a]=o.useState({task:{status:"idle"}}),[l,d]=o.useState([]),[i,u]=o.useState(!1),[p,n]=o.useState(null),[g,f]=o.useState(""),[h,x]=o.useState(!1),[c,j]=o.useState(!0),[w,C]=o.useState(""),[E,S]=o.useState(null),G=o.useRef(null),z=o.useCallback(async()=>{try{const m=await se.wikiStatus();return a(m),m}catch{return null}},[]),P=o.useCallback(async()=>{try{const m=await se.wikiFiles();d(m.files||[]),u(m.exists)}catch{}},[]),Z=o.useCallback(async()=>{try{const m=await se.wikiFileContent("meta.json");m!=null&&m.content&&S(JSON.parse(m.content))}catch{}},[]);o.useEffect(()=>{(async()=>{j(!0),await Promise.all([z(),P(),Z()]),j(!1)})()},[z,P,Z]),o.useEffect(()=>{if(s.task.status==="running"){let m=0;G.current=setInterval(async()=>{const N=await z();m++,m%3===0&&await P(),N&&N.task.status!=="running"&&(await Promise.all([P(),Z()]),G.current&&clearInterval(G.current))},1500)}else G.current&&clearInterval(G.current);return()=>{G.current&&clearInterval(G.current)}},[s.task.status,z,P,Z]);const X=async()=>{try{await se.wikiUpdate(),a(m=>({...m,task:{...m.task,status:"running",progress:0,message:t("wiki.incrementalUpdating")}}))}catch(m){console.error("Wiki update failed:",m)}},H=async m=>{if(m!=="meta.json"){n(m),x(!0);try{const N=await se.wikiFileContent(m);f(N.content)}catch{f(`# ${t("wiki.loadFailed")}
125
+ ${P.rationale||""}`;we=we.replace(/^\s*\{["']name["']\s*:.*\}\s*\n?/,"").trim(),await ae.createSkill({name:P.name,description:R,content:we,createdBy:"user-ai"}),re(l("skills.createAddedToKB"),{title:`Skill "${P.name}" ${l("skills.createSuccess")}`}),G(Ue=>{const Se=Ue.filter(ne=>ne.name!==P.name);return a==null||a(Se.length),Se}),je()}catch(R){re(R.message||"",{title:l("skills.createFailed"),type:"error"})}finally{q(null)}},B=d.filter(P=>y==="all"?!0:P.source===y).sort((P,R)=>P.source===R.source?P.name.localeCompare(R.name):P.source==="project"?-1:1),K=d.filter(P=>P.source==="builtin").length,xe=d.filter(P=>P.source==="project").length;return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 bg-violet-100 rounded-xl flex items-center justify-center shrink-0",children:e.jsx(tt,{size:20,className:"text-violet-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-slate-800",children:l("skills.title")}),e.jsx("p",{className:"text-sm text-slate-500",children:l("skills.subtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:ie,disabled:_,className:"flex items-center gap-2 px-3 py-2 border border-amber-300 text-amber-700 bg-amber-50 rounded-lg hover:bg-amber-100 transition-colors text-sm font-medium disabled:opacity-50",title:l("skills.aiRecommendTooltip"),children:[_?e.jsx(Me,{size:14,className:"animate-spin"}):e.jsx(jt,{size:14}),l("skills.aiRecommend")]}),e.jsx("button",{onClick:je,className:"p-2 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors",title:l("common.refresh"),children:e.jsx(yt,{size:16})}),e.jsxs("button",{onClick:()=>i(!0),className:"flex items-center gap-2 px-4 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 transition-colors text-sm font-medium",children:[e.jsx(Qe,{size:14}),l("skills.addSkill")]})]})]}),e.jsx("div",{className:"flex items-center gap-1 mb-4 p-1 bg-slate-100 rounded-lg w-fit",children:[{key:"all",label:l("common.all"),count:d.length},{key:"project",label:l("skills.filterProject"),count:xe,icon:wt},{key:"builtin",label:l("skills.filterBuiltin"),count:K,icon:Ll}].map(P=>e.jsxs("button",{onClick:()=>k(P.key),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${y===P.key?"bg-white text-violet-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[P.icon&&e.jsx(P.icon,{size:12}),P.label,e.jsx("span",{className:`ml-0.5 px-1.5 py-0.5 rounded-full text-[10px] ${y===P.key?"bg-violet-100 text-violet-600":"bg-slate-200 text-slate-500"}`,children:P.count})]},P.key))}),Z&&e.jsxs("div",{className:"mb-4 border border-amber-200 bg-amber-50/50 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{size:16,className:"text-amber-600"}),e.jsx("span",{className:"text-sm font-semibold text-amber-800",children:l("skills.aiRecommendDesc")}),A.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 bg-amber-200 text-amber-700 text-[10px] font-bold rounded-full",children:A.length})]}),e.jsx("button",{onClick:()=>X(!1),className:"p-1 text-amber-400 hover:text-amber-600",children:e.jsx(Xe,{size:14})})]}),_?e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs py-2",children:[e.jsx(Me,{size:14,className:"animate-spin"}),l("skills.aiRecommending")]}):A.length===0?e.jsx("p",{className:"text-xs text-amber-600/70",children:l("skills.noRecommendations")}):e.jsx("div",{className:"space-y-2",children:A.map(P=>e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-white rounded-lg border border-amber-100",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-mono text-xs font-semibold text-slate-800",children:P.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-bold uppercase ${P.priority==="high"?"bg-red-100 text-red-600":P.priority==="medium"?"bg-amber-100 text-amber-600":"bg-slate-100 text-slate-500"}`,children:P.priority}),e.jsx("span",{className:"text-[10px] text-slate-400",children:P.source})]}),e.jsx("p",{className:"text-xs text-slate-600 mb-1",children:P.description}),e.jsx("p",{className:"text-[11px] text-slate-400 line-clamp-2",children:P.rationale})]}),e.jsx("button",{onClick:()=>be(P),disabled:H===P.name,className:"shrink-0 flex items-center gap-1.5 px-3 py-1.5 bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors text-xs font-medium disabled:opacity-50",children:H===P.name?e.jsxs(e.Fragment,{children:[e.jsx(Me,{size:12,className:"animate-spin"})," ",l("skills.creating")]}):e.jsxs(e.Fragment,{children:[e.jsx(et,{size:12})," ",l("skills.acceptRecommend")]})})]},P.name))})]}),e.jsxs("div",{className:"flex-1 flex gap-4 xl:gap-6 min-h-0 overflow-hidden",children:[e.jsx("div",{className:"w-1/2 overflow-y-auto pr-2 space-y-2",children:u?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Me,{size:24,className:"animate-spin text-violet-400"})}):B.length===0?e.jsxs("div",{className:"text-center py-20 text-slate-400",children:[e.jsx(tt,{size:40,className:"mx-auto mb-3 opacity-40"}),e.jsx("p",{children:l("skills.noResults")})]}):B.map(P=>e.jsx("button",{onClick:()=>v(P.name),className:`w-full text-left p-4 rounded-xl border transition-all ${(n==null?void 0:n.skillName)===P.name?"border-violet-300 bg-violet-50 shadow-sm":"border-slate-200 bg-white hover:border-slate-300 hover:shadow-sm"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`mt-0.5 shrink-0 ${(n==null?void 0:n.skillName)===P.name?"text-violet-500":"text-slate-400"}`,children:(n==null?void 0:n.skillName)===P.name?e.jsx(Gt,{size:16}):e.jsx(rt,{size:16})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-mono text-sm font-semibold text-slate-800",children:P.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${P.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:P.source==="builtin"?l("skills.filterBuiltin"):l("skills.filterProject")}),P.createdBy&&gs[P.createdBy]&&(()=>{const R=gs[P.createdBy],Q=R.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${R.color}`,children:[e.jsx(Q,{size:10}),R.label]})})()]}),e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2",children:P.summary}),P.useCase&&e.jsxs("p",{className:"text-[11px] text-violet-500 mt-1 italic",children:[l("skills.useCase"),":",P.useCase]})]})]})},P.name))}),e.jsx("div",{className:"w-1/2 overflow-y-auto border border-slate-200 rounded-xl bg-white",children:f?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Me,{size:24,className:"animate-spin text-violet-400"})}):n?e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{size:16,className:"text-violet-500"}),e.jsx("span",{className:"font-mono font-semibold text-sm",children:n.skillName}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase ${n.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:n.source==="builtin"?l("skills.filterBuiltin"):l("skills.filterProject")}),n.createdBy&&gs[n.createdBy]&&(()=>{const P=gs[n.createdBy],R=P.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${P.color}`,children:[e.jsx(R,{size:10}),l(`skills.createdBy.${n.createdBy}`)]})})()]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-slate-400",children:[n.charCount," ",l("skills.chars")]}),e.jsx("button",{onClick:ee,className:"p-1.5 rounded-md hover:bg-slate-100 transition-colors text-slate-400 hover:text-slate-600",title:l("common.copy"),children:w?e.jsx(kt,{size:14,className:"text-emerald-500"}):e.jsx(qt,{size:14})}),n.source==="project"&&!I&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:te,className:"p-1.5 rounded-md hover:bg-blue-50 transition-colors text-slate-400 hover:text-blue-600",title:l("common.edit"),children:e.jsx(Ms,{size:14})}),e.jsx("button",{onClick:()=>O(!0),className:"p-1.5 rounded-md hover:bg-red-50 transition-colors text-slate-400 hover:text-red-500",title:l("common.delete"),children:e.jsx(ot,{size:14})})]}),I&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:ve,disabled:N,className:"flex items-center gap-1 px-2.5 py-1 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors text-xs font-medium disabled:opacity-50",children:[N?e.jsx(Me,{size:12,className:"animate-spin"}):e.jsx(Ss,{size:12}),l("common.save")]}),e.jsx("button",{onClick:de,className:"px-2.5 py-1 border border-slate-200 text-slate-500 rounded-md hover:bg-slate-50 transition-colors text-xs",children:l("common.cancel")})]})]})]}),n.relatedSkills.length>0&&e.jsxs("div",{className:"px-4 py-2 border-b border-slate-50 flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 uppercase font-bold",children:[l("skills.related"),":"]}),n.relatedSkills.map(P=>e.jsx("button",{onClick:()=>v(P),className:"text-[11px] text-violet-600 hover:text-violet-800 bg-violet-50 px-2 py-0.5 rounded-full transition-colors",children:P},P))]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 relative",children:[I?e.jsx("textarea",{value:$,onChange:P=>m(P.target.value),className:"w-full h-full min-h-[300px] text-xs text-slate-700 font-mono leading-relaxed border border-blue-200 rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-blue-300 resize-none bg-blue-50/30",spellCheck:!1}):e.jsx("pre",{className:"whitespace-pre-wrap text-xs text-slate-700 font-mono leading-relaxed",children:n.content}),W&&e.jsx("div",{className:"absolute inset-0 bg-white/90 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsxs("div",{className:"bg-white border border-red-200 rounded-xl shadow-lg p-6 max-w-sm text-center",children:[e.jsx(ot,{size:32,className:"mx-auto mb-3 text-red-400"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:l("skills.deleteConfirm")}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:l("skills.deleteSkillConfirmMsg",{name:n.skillName})}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsx("button",{onClick:()=>O(!1),className:"px-4 py-2 border border-slate-200 text-slate-600 rounded-lg hover:bg-slate-50 text-sm",children:l("common.cancel")}),e.jsxs("button",{onClick:fe,disabled:ye,className:"flex items-center gap-1.5 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 text-sm font-medium disabled:opacity-50",children:[ye?e.jsx(Me,{size:14,className:"animate-spin"}):e.jsx(ot,{size:14}),l("skills.confirmDelete")]})]})]})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full text-slate-400",children:e.jsxs("div",{className:"text-center",children:[e.jsx(tt,{size:40,className:"mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:l("skills.selectToView")})]})})})]}),x&&e.jsx(Bn,{onClose:()=>i(!1),onCreated:()=>{i(!1),je(),t==null||t()}})]})},Bn=({onClose:t,onCreated:s})=>{const{t:a}=_e(),[l,d]=o.useState("ai"),[c,u]=o.useState(""),[p,n]=o.useState(!1),[g,f]=o.useState(""),[h,x]=o.useState(""),[i,y]=o.useState(""),[k,w]=o.useState(!1),[T,A]=o.useState(""),[G,_]=o.useState(!1),E=async()=>{if(c.trim()){n(!0),A("");try{const H=(await ae.aiGenerateSkill(c)).reply||"";let q="",I="",L=H;const $=/```(?:json)?\s*\n?\s*(\{[^}]*"name"[^}]*\})\s*\n?\s*```/i,m=H.match($);if(m)try{const N=JSON.parse(m[1]);q=N.name||"",I=N.description||"",L=H.replace(m[0],"").trim()}catch{}if(!q){const N=H.split(`
126
+ `);for(let j=0;j<Math.min(N.length,5);j++){const W=N[j].trim();if(!(!W||W.startsWith("```"))&&W.startsWith("{")&&W.endsWith("}"))try{const O=JSON.parse(W);if(O.name){q=O.name,I=O.description||"";let ye=j+1;for(;ye<N.length&&!N[ye].trim();)ye++;L=N.slice(ye).join(`
127
+ `).trim();break}}catch{}}}if(!q){const N=/"name"\s*:\s*"([a-z][a-z0-9-]{1,62}[a-z0-9])"/,j=/"description"\s*:\s*"([^"]+)"/,W=H.match(N),O=H.match(j);W&&(q=W[1]),O&&(I=O[1])}L=L.replace(/```(?:json)?\s*\n?\s*\{[^}]*"name"[^}]*\}\s*\n?\s*```/gi,"").replace(/^\s*\{[^}]*"name"[^}]*\}\s*$/gm,"").trim(),q&&f(q),I&&x(I),y(L||H.trim()),_(!0),d("manual"),re(a("skills.checkGenerated"),{title:a("skills.aiGenerated")})}catch(X){A(a("skills.aiGenFailed")+": "+(X.message||""))}finally{n(!1)}}},Z=async()=>{var X,H,q;if(!g.trim()||!h.trim()||!i.trim()){A(a("skills.fillRequired"));return}w(!0),A("");try{await ae.createSkill({name:g.trim(),description:h.trim(),content:i.trim(),createdBy:G?"user-ai":"manual"}),re(a("skills.savedToKB"),{title:`Skill "${g}" ${a("skills.createSuccess")}`}),s()}catch(I){const L=((q=(H=(X=I.response)==null?void 0:X.data)==null?void 0:H.error)==null?void 0:q.message)||I.message||"";A(a("skills.createFailed")+": "+L)}finally{w(!1)}};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center",children:[e.jsx(Ze.Backdrop,{className:"bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white rounded-2xl shadow-2xl w-[720px] max-h-[85vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-violet-100 rounded-lg flex items-center justify-center",children:e.jsx(Qe,{size:16,className:"text-violet-600"})}),e.jsx("h3",{className:"font-bold text-lg",children:a("skills.addSkill")})]}),e.jsx("button",{onClick:t,className:"p-1.5 rounded-lg hover:bg-slate-100 transition-colors",children:e.jsx(Xe,{size:18,className:"text-slate-400"})})]}),e.jsx("div",{className:"px-6 pt-4",children:e.jsxs("div",{className:"inline-flex items-center gap-1 p-1 bg-slate-100 rounded-lg",children:[e.jsxs("button",{onClick:()=>d("ai"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${l==="ai"?"bg-white text-violet-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(Qe,{size:12}),a("skills.aiGenMode")]}),e.jsxs("button",{onClick:()=>d("manual"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${l==="manual"?"bg-white text-violet-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(nt,{size:12}),a("skills.manualMode")]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[l==="ai"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1.5",children:a("skills.describeSkill")}),e.jsx("div",{className:"relative",children:e.jsx("textarea",{value:c,onChange:X=>u(X.target.value),placeholder:a("skillsView.placeholderDesc"),className:"w-full h-32 px-4 py-3 border border-slate-200 rounded-xl text-sm resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400",disabled:p})})]}),e.jsx("button",{onClick:E,disabled:p||!c.trim(),className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-violet-600 text-white rounded-xl hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium",children:p?e.jsxs(e.Fragment,{children:[e.jsx(Me,{size:16,className:"animate-spin"}),a("skills.aiGeneratingContent")]}):e.jsxs(e.Fragment,{children:[e.jsx(Bs,{size:16}),a("skills.generateSkill")]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-700 mb-1.5",children:[a("skills.skillName")," ",e.jsx("span",{className:"text-slate-400 text-xs",children:"(kebab-case)"})]}),e.jsx("input",{type:"text",value:g,onChange:X=>f(X.target.value),placeholder:"my-custom-skill",className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1.5",children:a("skills.skillDescription")}),e.jsx("input",{type:"text",value:h,onChange:X=>x(X.target.value),placeholder:a("skillsView.placeholderName"),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-700 mb-1.5",children:[a("skills.skillContent")," ",e.jsx("span",{className:"text-slate-400 text-xs",children:"(Markdown)"})]}),e.jsx("textarea",{value:i,onChange:X=>y(X.target.value),placeholder:a("skillsView.placeholderContent"),className:"w-full h-64 px-4 py-3 border border-slate-200 rounded-xl text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400 leading-relaxed"})]})]}),T&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:[e.jsx(Ot,{size:16,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:T})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-slate-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-slate-600 hover:text-slate-800 transition-colors",children:a("common.cancel")}),l==="manual"&&e.jsx("button",{onClick:Z,disabled:k||!g.trim()||!h.trim()||!i.trim(),className:"flex items-center gap-2 px-5 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm font-medium",children:k?e.jsxs(e.Fragment,{children:[e.jsx(Me,{size:14,className:"animate-spin"}),a("common.saving")]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{size:14}),a("skills.addSkill")]})})]})]})]})},ja=["objc-deep-scan","category-scan","project-profile","code-standard","architecture","code-pattern","event-and-data-flow","best-practice","agent-guidelines"],Gn={"code-standard":e.jsx(tt,{className:"w-5 h-5"}),"code-pattern":e.jsx(Ht,{className:"w-5 h-5"}),architecture:e.jsx(lt,{className:"w-5 h-5"}),"best-practice":e.jsx(Qe,{className:"w-5 h-5"}),"event-and-data-flow":e.jsx(et,{className:"w-5 h-5"}),"project-profile":e.jsx(Ea,{className:"w-5 h-5"}),"agent-guidelines":e.jsx(qs,{className:"w-5 h-5"})};function Hn(t){return Gn[t]||e.jsx(Ht,{className:"w-5 h-5"})}const qn=({task:t})=>{const{t:s}=_e(),{status:a,meta:l}=t,d={skeleton:"bg-slate-50 border-slate-200",filling:"bg-blue-50 border-blue-300",completed:"bg-emerald-50 border-emerald-300",failed:"bg-red-50 border-red-300"},c={skeleton:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-slate-400",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-300"}),s("bootstrap.statusLabels.skeleton")]}),filling:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-blue-600",children:[e.jsx(Me,{className:"w-3 h-3 animate-spin"}),s("bootstrap.statusLabels.filling")]}),completed:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-emerald-600",children:[e.jsx(kt,{className:"w-3 h-3"}),s("bootstrap.statusLabels.completed")]}),failed:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-red-600",children:[e.jsx(Xe,{className:"w-3 h-3"}),s("bootstrap.statusLabels.failed")]})};return e.jsxs("div",{className:`relative rounded-xl border p-4 transition-all duration-300 ${d[a]||d.skeleton}`,children:[a==="skeleton"&&e.jsx("div",{className:"absolute inset-0 rounded-xl overflow-hidden",children:e.jsx("div",{className:"animate-pulse bg-gradient-to-r from-transparent via-slate-200/40 to-transparent h-full w-full"})}),a==="filling"&&e.jsx("div",{className:"absolute inset-0 rounded-xl overflow-hidden",children:e.jsx("div",{className:"animate-pulse bg-gradient-to-r from-transparent via-blue-200/30 to-transparent h-full w-full"})}),e.jsxs("div",{className:"relative z-10 flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`flex-shrink-0 p-2 rounded-lg ${a==="completed"?"bg-emerald-100 text-emerald-600":a==="filling"?"bg-blue-100 text-blue-600":a==="failed"?"bg-red-100 text-red-600":"bg-slate-100 text-slate-400"}`,children:Hn(t.id)}),e.jsxs("div",{children:[e.jsx("h3",{className:`font-medium text-sm ${a==="skeleton"?"text-slate-400":"text-slate-800"}`,children:(()=>{const u=`bootstrap.pipelineLabels.${l.dimId}`,p=s(u);return p!==u?p:l.label})()}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[l.skillWorthy?"Skill":"Candidate",t.result&&a==="completed"&&e.jsx("span",{className:"ml-2 text-emerald-600",children:(()=>{const u=t.result,p=u.sourceCount??0,n=u.extracted??0;return u.type==="empty"?s("bootstrap.noMatch"):u.type==="skill"?u.empty?s("bootstrap.noMatch"):n>0?s("bootstrap.featuresAndCandidates",{sourceCount:p,extracted:n}):s("bootstrap.featuresOnly",{sourceCount:p}):n>0?s("bootstrap.candidatesOnly",{extracted:n}):s("bootstrap.noMatch")})()}),t.error&&a==="failed"&&e.jsx("span",{className:"ml-2 text-red-500 truncate max-w-[200px] inline-block align-bottom",children:t.error})]})]})]}),e.jsx("div",{className:"flex-shrink-0",children:c[a]})]})]})},On=[{key:"round1",labelKey:"bootstrap.reviewRounds.round1Label",descKey:"bootstrap.reviewRounds.round1Desc",icon:e.jsx(za,{className:"w-4 h-4"})},{key:"round2",labelKey:"bootstrap.reviewRounds.round2Label",descKey:"bootstrap.reviewRounds.round2Desc",icon:e.jsx(fs,{className:"w-4 h-4"})},{key:"round3",labelKey:"bootstrap.reviewRounds.round3Label",descKey:"bootstrap.reviewRounds.round3Desc",icon:e.jsx(Ml,{className:"w-4 h-4"})}],Kn=({review:t})=>{const{t:s}=_e();return t.activeRound===0?null:e.jsxs("div",{className:"mt-5 border border-purple-200 rounded-xl bg-purple-50/50 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(rs,{className:"w-5 h-5 text-purple-600"}),e.jsx("h3",{className:"text-sm font-semibold text-purple-800",children:s("bootstrap.reviewPipeline")})]}),e.jsx("div",{className:"space-y-2.5",children:On.map(({key:a,labelKey:l,descKey:d,icon:c})=>{const u=t[a],p=u.status==="running",n=u.status==="completed",g=u.status==="idle";return e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg border transition-all duration-300 ${p?"border-purple-300 bg-purple-100/60":n?"border-emerald-300 bg-emerald-50/60":"border-slate-200 bg-white/40"}`,children:[e.jsx("div",{className:`flex-shrink-0 p-1.5 rounded-md ${p?"bg-purple-200 text-purple-700":n?"bg-emerald-100 text-emerald-600":"bg-slate-100 text-slate-400"}`,children:c}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-sm font-medium ${g?"text-slate-400":"text-slate-800"}`,children:s(l)}),e.jsx("span",{className:"text-xs text-slate-400",children:s(d)})]}),a==="round1"&&n&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round1Done",{kept:t.round1.kept??"?",merged:t.round1.merged??0,dropped:t.round1.dropped??0})}),a==="round2"&&p&&typeof t.round2.progress=="number"&&e.jsxs("div",{className:"mt-1.5",children:[e.jsx("div",{className:"w-full h-1.5 bg-purple-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-purple-500 rounded-full transition-all duration-300",style:{width:`${t.round2.progress}%`}})}),e.jsx("p",{className:"text-xs text-purple-600 mt-0.5",children:s("bootstrap.round2Progress",{current:t.round2.current??0,total:t.round2.total??"?"})})]}),a==="round2"&&n&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round2Done",{refined:t.round2.refined??"?",total:t.round2.total??"?"})}),a==="round3"&&n&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round3Done",{afterDedup:t.round3.afterDedup??"?",relationsFound:t.round3.relationsFound??0})})]}),e.jsxs("div",{className:"flex-shrink-0",children:[p&&e.jsx(Me,{className:"w-4 h-4 text-purple-500 animate-spin"}),n&&e.jsx(kt,{className:"w-4 h-4 text-emerald-500"})]})]},a)})})]})};function va(t){if(t<0)return"--";const s=Math.floor(t/1e3),a=Math.floor(s/60),l=s%60;return a===0?`${l}s`:`${a}m ${l.toString().padStart(2,"0")}s`}const Un=({session:t,isAllDone:s,reviewState:a,onDismiss:l})=>{const{t:d}=_e(),[c,u]=o.useState(Date.now());if(o.useEffect(()=>{if(!t||t.status!=="running")return;const y=setInterval(()=>u(Date.now()),1e3);return()=>clearInterval(y)},[t==null?void 0:t.status]),!t)return null;const p=t.startedAt?c-t.startedAt:t.elapsedMs??0,n=t.completed+t.failed,g=t.total-n,f=t.elapsedMs??0,h=n>0&&f>0?Math.round(f/n*g):-1,x=t.totalToolCalls??0,i=t.status==="completed"?d("bootstrap.allCompleted"):t.status==="completed_with_errors"?d("bootstrap.completedWithErrors"):null;return e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-800",children:d("bootstrap.title")}),i&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:i})]}),s&&l&&e.jsx("button",{onClick:l,className:"text-sm px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors",children:d("bootstrap.close")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-5 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-slate-600",children:[e.jsx(xt,{size:14,className:"text-slate-400"}),e.jsxs("span",{children:[d("bootstrap.elapsed")," ",e.jsx("span",{className:"font-medium text-slate-800",children:va(p)})]})]}),t.status==="running"&&g>0&&h>0&&e.jsxs("div",{className:"flex items-center gap-1.5 text-slate-600",children:[e.jsx(xt,{size:14,className:"text-blue-400"}),e.jsxs("span",{children:[d("bootstrap.estimatedRemaining")," ",e.jsx("span",{className:"font-medium text-blue-600",children:va(h)})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-slate-600",children:[e.jsx($a,{size:14,className:"text-slate-400"}),e.jsxs("span",{children:[d("bootstrap.toolCalls")," ",e.jsx("span",{className:"font-medium text-slate-800",children:x})]})]}),e.jsx("div",{className:"text-slate-400 text-xs",children:d("bootstrap.dimensions",{done:n,total:t.total})})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:[...t.tasks].sort((y,k)=>{var A,G;const w=ja.indexOf(((A=y.meta)==null?void 0:A.dimId)??y.id),T=ja.indexOf(((G=k.meta)==null?void 0:G.dimId)??k.id);return(w===-1?999:w)-(T===-1?999:T)}).map(y=>e.jsx(qn,{task:y},y.id))}),a&&a.activeRound>0&&e.jsx(Kn,{review:a})]})},bs={index:{icon:tt,color:"text-blue-600",label:"overview"},architecture:{icon:lt,color:"text-violet-600",label:"architecture"},"getting-started":{icon:ht,color:"text-emerald-600",label:"getting-started"},protocols:{icon:Qe,color:"text-amber-600",label:"protocols"},components:{icon:ht,color:"text-emerald-600",label:"components"},patterns:{icon:Qe,color:"text-amber-600",label:"patterns"},module:{icon:wt,color:"text-cyan-600",label:"module"},document:{icon:nt,color:"text-orange-600",label:"document"},_index:{icon:as,color:"text-slate-500",label:"index"}};function Wn(t){var a;const s=((a=t.split("/").pop())==null?void 0:a.replace(".md",""))||"";return s==="_index"?bs._index:t.startsWith("modules/")?bs.module:t.startsWith("documents/")?bs.document:bs[s]||{icon:nt,color:"text-slate-500",label:"doc"}}const Vn={"cursor-devdocs":{label:"Cursor Docs",color:"text-orange-700",bg:"bg-orange-50 border-orange-200"}},Jn={modules:"modules",documents:"documents"};function Za(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Yn(t){if(!t)return"";const s=new Date(t);if(isNaN(s.getTime()))return"";const l=Date.now()-s.getTime();return l<6e4?"just now":l<36e5?`${Math.floor(l/6e4)} min ago`:l<864e5?`${Math.floor(l/36e5)} hr ago`:l<6048e5?`${Math.floor(l/864e5)} d ago`:s.toLocaleDateString("zh-CN")}const Qn=({task:t,wiki:s})=>{const{t:a}=_e();return t.status==="running"?null:t.status==="error"?e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-xl p-4 mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-red-100 rounded-lg",children:e.jsx(Ot,{size:z.md,className:"text-red-600"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-red-800",children:a("wiki.genFailed")}),e.jsx("span",{className:"text-sm text-red-600 ml-3",children:t.error||a("common.operationFailed")})]})]}):s!=null&&s.exists&&s.hasChanges?e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-amber-100 rounded-lg",children:e.jsx(Ot,{size:z.md,className:"text-amber-600"})}),e.jsx("span",{className:"text-sm text-amber-700",children:a("wiki.outOfDateHint")})]}):null};function Xn(t,s){const a=[],l=new Map((s==null?void 0:s.map(g=>[g.path,g]))||[]),d=[],c=new Map;for(const g of t){const f=g.path.split("/"),h=l.get(g.path);if(f.length===1)d.push({name:f[0],path:g.path,isDir:!1,file:g,metaInfo:h});else{const x=f[0];c.has(x)||c.set(x,[]),c.get(x).push({name:f.slice(1).join("/"),path:g.path,isDir:!1,file:g,metaInfo:h})}}const u=["index.md","architecture.md","getting-started.md","patterns.md","protocols.md","components.md"];d.sort((g,f)=>{const h=u.indexOf(g.name),x=u.indexOf(f.name);return h!==-1&&x!==-1?h-x:h!==-1?-1:x!==-1?1:g.name.localeCompare(f.name)}),a.push(...d);const p=["modules","patterns","documents"],n=[...c.entries()].sort(([g],[f])=>{const h=p.indexOf(g),x=p.indexOf(f);return h!==-1&&x!==-1?h-x:h!==-1?-1:x!==-1?1:g.localeCompare(f)});for(const[g,f]of n){const h=f.filter(x=>!x.name.startsWith("_index")).sort((x,i)=>x.name.localeCompare(i.name));a.push({name:g,path:g,isDir:!0,children:h})}return a}const Zn=({tree:t,selectedFile:s,onSelect:a,searchQuery:l})=>{const[d,c]=o.useState(new Set(["modules","documents"])),u=g=>{c(f=>{const h=new Set(f);return h.has(g)?h.delete(g):h.add(g),h})},n=(g=>{if(!l)return g;const f=l.toLowerCase();return g.filter(h=>{var x;return h.isDir?(x=h.children)==null?void 0:x.some(i=>i.name.toLowerCase().includes(f)||i.path.toLowerCase().includes(f)):h.name.toLowerCase().includes(f)||h.path.toLowerCase().includes(f)})})(t);return e.jsx("div",{className:"space-y-0.5",children:n.map(g=>{var f;if(g.isDir){const h=d.has(g.path),x=l.toLowerCase(),i=l?(f=g.children)==null?void 0:f.filter(y=>y.name.toLowerCase().includes(x)||y.path.toLowerCase().includes(x)):g.children;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>u(g.path),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 rounded-lg transition-colors",children:[h?e.jsx(Gt,{size:14,className:"text-slate-400 flex-shrink-0"}):e.jsx(rt,{size:14,className:"text-slate-400 flex-shrink-0"}),e.jsx(wt,{size:14,className:"text-amber-500 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:Jn[g.name]||g.name}),e.jsx("span",{className:"ml-auto text-xs text-slate-400",children:(i==null?void 0:i.length)||0})]}),h&&i&&e.jsx("div",{className:"ml-3",children:i.map(y=>e.jsx(Na,{node:y,isActive:s===y.path,onSelect:a},y.path))})]},g.path)}return e.jsx(Na,{node:g,isActive:s===g.path,onSelect:a},g.path)})})},Na=({node:t,isActive:s,onSelect:a})=>{var p,n;const l=Wn(t.path),d=l.icon,c=(p=t.metaInfo)==null?void 0:p.polished,u=(n=t.metaInfo)==null?void 0:n.source;return e.jsxs("button",{onClick:()=>a(t.path),className:`w-full flex items-center gap-2 px-3 py-2 text-sm rounded-lg transition-all ${s?"bg-blue-50 text-blue-700 border border-blue-200 shadow-sm":"text-slate-600 hover:bg-slate-50"}`,children:[e.jsx(d,{size:14,className:`flex-shrink-0 ${s?"text-blue-500":l.color}`}),e.jsx("span",{className:"truncate text-left",children:t.name.replace(".md","")}),e.jsxs("span",{className:"ml-auto flex items-center gap-1 flex-shrink-0",children:[c&&e.jsx("span",{title:"AI Enhanced",children:e.jsx(Qe,{size:10,className:"text-violet-400"})}),u&&e.jsx("span",{title:`Source: ${u}`,children:e.jsx(zl,{size:10,className:"text-orange-400"})})]})]})},eo=({filePath:t,content:s,loading:a,meta:l,onBack:d})=>{var x;const{t:c}=_e(),[u,p]=o.useState(!1),n=(x=l==null?void 0:l.files)==null?void 0:x.find(i=>i.path===t),g=()=>{navigator.clipboard.writeText(s),p(!0),setTimeout(()=>p(!1),2e3)},f=t.split("/"),h=f.map((i,y)=>({label:y===f.length-1?i.replace(".md",""):i,isLast:y===f.length-1}));return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 bg-slate-50 border-b border-slate-200 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:d,className:"p-1.5 hover:bg-slate-200 rounded-lg transition-colors lg:hidden",title:c("wiki.backToList"),children:e.jsx(Fl,{size:z.md})}),e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(tt,{size:14,className:"text-slate-400"}),e.jsx("span",{className:"text-slate-400",children:"wiki"}),h.map((i,y)=>e.jsxs(Ct.Fragment,{children:[e.jsx(rt,{size:12,className:"text-slate-300"}),e.jsx("span",{className:i.isLast?"font-medium text-slate-700":"text-slate-400",children:i.label})]},y))]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(n==null?void 0:n.polished)&&e.jsxs("span",{className:"flex items-center gap-1 text-xs text-violet-700 bg-violet-50 border border-violet-200 px-2 py-0.5 rounded-full",children:[e.jsx(Qe,{size:10}),c("wiki.aiBadge")]}),(n==null?void 0:n.source)&&(()=>{const i=Vn[n.source];return e.jsx("span",{className:`flex items-center gap-1 text-xs border px-2 py-0.5 rounded-full ${(i==null?void 0:i.bg)||"bg-slate-50 border-slate-200"} ${(i==null?void 0:i.color)||"text-slate-600"}`,children:(i==null?void 0:i.label)||n.source})})(),e.jsxs("button",{onClick:g,className:"flex items-center gap-1 px-2.5 py-1 text-xs text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-md transition-colors",children:[u?e.jsx(kt,{size:12,className:"text-emerald-500"}):e.jsx(qt,{size:12}),c(u?"wiki.copySuccess":"wiki.copyBtn")]})]})]}),e.jsx("div",{className:"flex-1 overflow-auto scrollbar-light",style:{scrollbarGutter:"stable"},children:a?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Me,{size:z.xl,className:"text-blue-500 animate-spin"})}):e.jsx("div",{className:"px-4 xl:px-6 2xl:px-8 py-6 max-w-4xl mx-auto",children:e.jsx(gt,{content:s,className:"wiki-reader"})})})]})},to=()=>{const{t}=_e();return e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-white rounded-2xl border border-dashed border-slate-200 text-slate-400",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-slate-50 flex items-center justify-center mb-4",children:e.jsx(tt,{size:32,className:"text-slate-300"})}),e.jsx("p",{className:"text-sm font-medium text-slate-500",children:t("wiki.emptyTitle")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-slate-400",children:t("wiki.emptyDesc")}),e.jsx("p",{className:"mt-3 text-[11px] text-slate-400",children:t("wiki.emptyHint")})]})},so=({meta:t,onSelectFile:s,isGenerating:a,progress:l,message:d})=>{var g;const{t:c}=_e(),u=[{path:"index.md",label:c("wiki.quickOverview"),desc:c("wiki.quickOverviewDesc"),icon:tt,color:"bg-blue-50 text-blue-600 border-blue-200"},{path:"architecture.md",label:c("wiki.quickArch"),desc:c("wiki.quickArchDesc"),icon:lt,color:"bg-violet-50 text-violet-600 border-violet-200"},{path:"getting-started.md",label:c("wiki.quickStart"),desc:c("wiki.quickStartDesc"),icon:ht,color:"bg-emerald-50 text-emerald-600 border-emerald-200"},{path:"protocols.md",label:c("wiki.quickProtocols"),desc:c("wiki.quickProtocolsDesc"),icon:Qe,color:"bg-amber-50 text-amber-600 border-amber-200"}],p=new Set(((g=t==null?void 0:t.files)==null?void 0:g.map(f=>f.path||f.name))??[]),n=u.filter(f=>p.size===0||p.has(f.path));return e.jsxs("div",{className:"p-4 xl:p-6 2xl:p-8 overflow-y-auto flex-1",children:[a&&e.jsxs("div",{className:"mb-8 flex flex-col items-center",children:[e.jsxs("div",{className:"relative w-20 h-20 mb-5",children:[e.jsx("span",{className:"absolute inset-0 rounded-full bg-blue-100 animate-ping opacity-20"}),e.jsx("span",{className:"absolute inset-2 rounded-full bg-blue-50 animate-pulse"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(qs,{size:36,className:"text-blue-500 animate-pulse"})})]}),e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-1",children:c("wiki.wikiGenerating")}),e.jsx("p",{className:"text-sm text-slate-500 max-w-md text-center leading-relaxed",children:d||c("wiki.generating")}),typeof l=="number"&&e.jsxs("div",{className:"mt-4 w-48",children:[e.jsx("div",{className:"w-full bg-slate-100 rounded-full h-2",children:e.jsx("div",{className:"bg-gradient-to-r from-blue-500 to-indigo-500 h-2 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(l,3)}%`}})}),e.jsxs("p",{className:"text-xs text-center text-blue-500 mt-1.5 font-mono",children:[l,"%"]})]})]}),!a&&e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-12 h-12 bg-slate-100 rounded-xl flex items-center justify-center mx-auto mb-3",children:e.jsx(nt,{size:24,className:"text-slate-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-700",children:c("wiki.selectFile")}),e.jsx("p",{className:"text-sm text-slate-500 mt-1",children:c("wiki.selectPlaceholder")})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 max-w-lg mx-auto",children:n.map(f=>{const h=f.icon;return e.jsxs("button",{onClick:()=>s(f.path),className:`text-left p-4 rounded-xl border ${f.color} hover:shadow-sm transition-all group`,children:[e.jsx(h,{size:20,className:"mb-2 opacity-70 group-hover:opacity-100"}),e.jsx("div",{className:"font-medium text-sm",children:f.label}),e.jsx("div",{className:"text-xs opacity-60 mt-0.5",children:f.desc})]},f.path)})}),t&&e.jsxs("div",{className:"mt-8 text-center text-xs text-slate-400",children:[t.generatedAt&&`${c("wiki.lastGenerated")}: ${new Date(t.generatedAt).toLocaleString()}`,t.duration!=null&&` · ${c("wiki.duration")} ${Za(t.duration)}`,t.version&&` · v${t.version}`]})]})},ao=()=>{const{t}=_e(),[s,a]=o.useState({task:{status:"idle"}}),[l,d]=o.useState([]),[c,u]=o.useState(!1),[p,n]=o.useState(null),[g,f]=o.useState(""),[h,x]=o.useState(!1),[i,y]=o.useState(!0),[k,w]=o.useState(""),[T,A]=o.useState(null),G=o.useRef(null),_=o.useCallback(async()=>{try{const m=await ae.wikiStatus();return a(m),m}catch{return null}},[]),E=o.useCallback(async()=>{try{const m=await ae.wikiFiles();d(m.files||[]),u(m.exists)}catch{}},[]),Z=o.useCallback(async()=>{try{const m=await ae.wikiFileContent("meta.json");m!=null&&m.content&&A(JSON.parse(m.content))}catch{}},[]);o.useEffect(()=>{(async()=>{y(!0),await Promise.all([_(),E(),Z()]),y(!1)})()},[_,E,Z]),o.useEffect(()=>{if(s.task.status==="running"){let m=0;G.current=setInterval(async()=>{const N=await _();m++,m%3===0&&await E(),N&&N.task.status!=="running"&&(await Promise.all([E(),Z()]),G.current&&clearInterval(G.current))},1500)}else G.current&&clearInterval(G.current);return()=>{G.current&&clearInterval(G.current)}},[s.task.status,_,E,Z]);const X=async()=>{try{await ae.wikiUpdate(),a(m=>({...m,task:{...m.task,status:"running",progress:0,message:t("wiki.incrementalUpdating")}}))}catch(m){console.error("Wiki update failed:",m)}},H=async m=>{if(m!=="meta.json"){n(m),x(!0);try{const N=await ae.wikiFileContent(m);f(N.content)}catch{f(`# ${t("wiki.loadFailed")}
129
128
 
130
- ${t("wiki.loadFailedDesc")}`)}finally{x(!1)}}},q=()=>{n(null),f("")},R=o.useMemo(()=>l.filter(m=>m.path!=="meta.json"),[l]),M=o.useMemo(()=>Zn(R,E==null?void 0:E.files),[R,E]);if(c)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(Fe,{size:F.xl,className:"text-blue-500 animate-spin"})});const _=!i&&R.length===0&&s.task.status!=="running";return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden p-6 pt-4",children:[e.jsx(Xn,{task:s.task,wiki:s.wiki}),_?e.jsx(so,{}):e.jsxs(e.Fragment,{children:[s.task.status==="running"&&e.jsxs("div",{className:"mb-3 flex items-center gap-3 px-4 py-2.5 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/70 rounded-xl shrink-0",children:[e.jsxs("div",{className:"relative flex items-center justify-center w-6 h-6",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-30 animate-ping"}),e.jsx(Fe,{size:16,className:"text-blue-600 animate-spin relative"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-blue-800",children:t("wiki.wikiGenerating")}),s.task.message&&e.jsx("span",{className:"text-xs text-blue-500 ml-2 truncate",children:s.task.message})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("div",{className:"w-24 bg-blue-100 rounded-full h-1.5",children:e.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(s.task.progress||0,3)}%`}})}),e.jsxs("span",{className:"text-xs font-mono text-blue-600 w-8 text-right",children:[s.task.progress||0,"%"]})]})]}),e.jsxs("div",{className:"flex gap-4 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:`w-64 flex-shrink-0 bg-white border border-slate-200 rounded-xl flex flex-col overflow-hidden ${p?"hidden lg:flex":""}`,children:[e.jsxs("div",{className:"px-3 pt-3 pb-2 border-b border-slate-100 shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tt,{size:16,className:"text-blue-500"}),e.jsx("span",{className:"text-sm font-semibold text-slate-700",children:"Wiki"}),(E==null?void 0:E.version)&&e.jsxs("span",{className:"text-[10px] text-slate-300",children:["v",E.version]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[i&&e.jsx("span",{className:"text-[10px] text-slate-400",children:t("wiki.fileCount",{count:R.length})}),s.task.status!=="running"&&i&&e.jsx("button",{onClick:X,title:t("wiki.incrementalUpdate"),className:"p-1 rounded-md text-blue-500 hover:bg-blue-50 transition-colors",children:e.jsx(yt,{size:13})})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(ft,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{type:"text",placeholder:t("wiki.searchPlaceholder"),value:w,onChange:m=>C(m.target.value),className:"w-full pl-8 pr-3 py-2 text-sm bg-slate-50 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-300 transition-all"})]})]}),e.jsxs("div",{className:"p-2 overflow-y-auto flex-1 min-h-0 scrollbar-light",children:[e.jsx(eo,{tree:M,selectedFile:p,onSelect:H,searchQuery:w}),s.task.status==="running"&&e.jsxs("div",{className:"mx-2 mt-3 mb-1 flex items-center gap-2 px-3 py-2 bg-blue-50 border border-blue-100 rounded-lg",children:[e.jsx(Fe,{size:12,className:"text-blue-500 animate-spin flex-shrink-0"}),e.jsx("span",{className:"text-[11px] text-blue-600 leading-tight",children:t("wiki.generating")})]})]}),(E==null?void 0:E.generatedAt)&&e.jsx("div",{className:"px-3 py-2 border-t border-slate-100 shrink-0",children:e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-slate-400",children:[e.jsx(xt,{size:10}),e.jsx("span",{children:Qn(E.generatedAt)}),E.duration!=null&&e.jsxs("span",{children:["· ",Za(E.duration)]})]})})]}),e.jsx("div",{className:`flex-1 bg-white border border-slate-200 rounded-xl overflow-hidden flex flex-col min-h-0 ${p?"":"hidden lg:flex"}`,children:p?e.jsx(to,{filePath:p,content:g,loading:h,meta:E,onBack:q}):e.jsx(ao,{meta:E,onSelectFile:H,isGenerating:s.task.status==="running",progress:s.task.progress,message:s.task.message})})]})]})]})},ro={authority:0,guardUsageCount:0,humanUsageCount:0,aiUsageCount:0,lastUsedAt:null,authorityScore:0},no=({editingRecipe:t,setEditingRecipe:s,handleSaveRecipe:a,closeRecipeEdit:l,isSavingRecipe:d=!1})=>{var x,c,j,w,C,E,S,G,z,P,Z,X,H,q,R,M,_;const{t:i}=_e(),[u,p]=o.useState("preview"),n=o.useRef(!0);o.useEffect(()=>()=>{n.current=!1},[]);const g=(()=>{const m=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(m)?"objectivec":t.language||"text"})(),f=async m=>{try{if(await se.setRecipeAuthority(t.name,m),n.current){const N=t.stats?{...t.stats,authority:m}:{...ro,authority:m};s({...t,stats:N})}}catch(N){console.warn(i("recipeEditor.authorityFailed"),N==null?void 0:N.message)}},h=m=>{if(!m)return"";const N=typeof m=="string"?new Date(m).getTime():m;return isNaN(N)?"":new Date(N).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-slate-900/50 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white w-full max-w-6xl rounded-2xl shadow-2xl flex flex-col h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-slate-100 flex justify-between items-center flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-bold",children:i("recipeEditor.title")}),t.kind&&(()=>{const N={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:ut},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:jt},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:tt}}[t.kind];if(!N)return null;const y=N.icon;return e.jsxs("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase flex items-center gap-1 border ${N.bg} ${N.color} ${N.border}`,children:[e.jsx(y,{size:F.sm}),N.label]})})(),t.status&&t.status!=="active"&&t.status!=="published"&&e.jsx("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase border ${t.status==="draft"?"bg-slate-50 text-slate-500 border-slate-200":t.status==="archived"?"bg-orange-50 text-orange-600 border-orange-200":"bg-slate-50 text-slate-500 border-slate-200"}`,children:t.status})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-500",children:i("recipeEditor.authorityScore")}),u==="preview"?e.jsx("span",{className:"text-sm text-slate-700",children:((x=t.stats)==null?void 0:x.authority)??3}):e.jsxs("select",{className:"font-bold text-amber-600 bg-amber-50 border border-amber-100 px-2 py-1 rounded-lg outline-none text-[10px] focus:ring-2 focus:ring-amber-500",value:((c=t.stats)==null?void 0:c.authority)??3,onChange:m=>f(parseInt(m.target.value)),children:[e.jsxs("option",{value:"1",children:["⭐ 1 - ",i("recipeEditor.qualityLevels.basic")]}),e.jsxs("option",{value:"2",children:["⭐⭐ 2 - ",i("recipeEditor.qualityLevels.good")]}),e.jsxs("option",{value:"3",children:["⭐⭐⭐ 3 - ",i("recipeEditor.qualityLevels.solid")]}),e.jsxs("option",{value:"4",children:["⭐⭐⭐⭐ 4 - ",i("recipeEditor.qualityLevels.great")]}),e.jsxs("option",{value:"5",children:["⭐⭐⭐⭐⭐ 5 - ",i("recipeEditor.qualityLevels.excellent")]})]})]}),e.jsxs("div",{className:"flex bg-slate-100 p-1 rounded-lg mr-4",children:[e.jsxs("button",{onClick:()=>p("preview"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${u==="preview"?"bg-white shadow-sm text-blue-600":"text-slate-400"}`,children:[e.jsx(os,{size:F.sm})," ",i("recipeEditor.preview")]}),e.jsxs("button",{onClick:()=>p("edit"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${u==="edit"?"bg-white shadow-sm text-blue-600":"text-slate-400"}`,children:[e.jsx(Et,{size:F.sm})," ",i("recipeEditor.edit")]})]}),e.jsx("button",{onClick:l,className:"p-2 hover:bg-slate-100 rounded-full",children:e.jsx(Xe,{size:F.lg})})]})]}),e.jsx("div",{className:"p-6 space-y-4 flex-1 flex flex-col overflow-hidden",children:e.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:u==="edit"?e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-5 pr-1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1",children:i("recipeEditor.path")}),e.jsx("input",{className:"w-full p-2 bg-slate-50 border border-slate-200 rounded-lg text-sm",value:t.name,onChange:m=>s({...t,name:m.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1",children:i("recipeEditor.description")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-none",rows:2,value:t.description||"",onChange:m=>s({...t,description:m.target.value}),placeholder:i("recipeEditor.descPlaceholder")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",i("recipeEditor.markdown")]}),e.jsx("div",{className:"border border-slate-200 rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ks,{value:((j=t.content)==null?void 0:j.markdown)||"",onChange:m=>s({...t,content:{...t.content,markdown:m}}),language:"markdown",height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(Ht,{size:11,className:"text-emerald-500"})," ",i("recipeEditor.code")]}),e.jsx("div",{className:"border border-slate-200 rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ks,{value:((w=t.content)==null?void 0:w.pattern)||"",onChange:m=>s({...t,content:{...t.content,pattern:m}}),language:g,height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1",children:i("recipeEditor.rationale")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-y",rows:3,value:((C=t.content)==null?void 0:C.rationale)||"",onChange:m=>s({...t,content:{...t.content,rationale:m.target.value}}),placeholder:i("recipeEditor.rationalePlaceholder")})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-6 scrollbar-light",children:[(()=>{const m=[["trigger",t.trigger],["language",t.language],["category",t.category],["kind",t.kind],["knowledgeType",t.knowledgeType],["status",t.status],["complexity",t.complexity],["scope",t.scope],["source",t.source],["updatedAt",t.updatedAt?h(t.updatedAt):void 0]].filter(([,N])=>!!N);return m.length===0?null:e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-4",children:"Recipe Metadata"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-y-4 gap-x-8",children:m.map(([N,y])=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold uppercase mb-1",children:N}),e.jsx("span",{className:"text-sm text-slate-700 break-all font-medium",children:y})]},N))})]})})(),t.description&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("recipeEditor.description")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:t.description})]}),((E=t.content)==null?void 0:E.markdown)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-blue-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",i("recipeEditor.markdown")]}),e.jsx("div",{className:"bg-blue-50/30 border border-blue-100 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 leading-relaxed",children:e.jsx(gt,{content:t.content.markdown})})})]}),((S=t.content)==null?void 0:S.pattern)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-emerald-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(Ht,{size:11,className:"text-emerald-500"})," ",i("recipeEditor.code")]}),e.jsx(dt,{code:t.content.pattern,language:g,showLineNumbers:!0})]}),((G=t.content)==null?void 0:G.rationale)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("recipeEditor.rationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:t.content.rationale})})]}),((z=t.content)==null?void 0:z.steps)&&t.content.steps.length>0&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("recipeEditor.steps")}),e.jsx("div",{className:"space-y-2",children:t.content.steps.map((m,N)=>typeof m=="string"?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:N+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:m})]},N):e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:N+1}),m.title&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:m.title})]}),m.description&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:m.description}),m.code&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:m.code})]},N))})]}),((P=t.content)==null?void 0:P.codeChanges)&&t.content.codeChanges.length>0&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("recipeEditor.codeChanges")}),e.jsx("div",{className:"space-y-2",children:t.content.codeChanges.map((m,N)=>e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-slate-50 border-b border-slate-200 flex items-center gap-2",children:[e.jsx(ht,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-slate-600",children:m.file})]}),m.explanation&&e.jsx("p",{className:"text-[11px] text-slate-500 px-3 py-1.5 border-b border-slate-100 bg-yellow-50/30",children:m.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/20 border-b border-slate-100",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:"Before"}),e.jsx("pre",{className:"text-[11px] text-slate-600 whitespace-pre-wrap break-words font-mono",children:m.before||i("recipes.emptyValue")})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/20",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:"After"}),e.jsx("pre",{className:"text-[11px] text-slate-700 whitespace-pre-wrap break-words font-mono",children:m.after})]})]},N))})]}),((Z=t.content)==null?void 0:Z.verification)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-teal-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("recipeEditor.validation")}),e.jsxs("div",{className:"bg-teal-50/50 border border-teal-100 rounded-xl p-4 space-y-1.5",children:[t.content.verification.method&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:i("recipeEditor.validationMethod")})," ",t.content.verification.method]}),t.content.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:i("recipeEditor.validationExpected")})," ",t.content.verification.expectedResult]}),t.content.verification.testCode&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md overflow-x-auto whitespace-pre-wrap mt-1",children:t.content.verification.testCode})]})]}),t.tags&&t.tags.length>0&&e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-3 flex items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-blue-400"})," ",i("recipeEditor.tags")]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map((m,N)=>e.jsx("span",{className:"px-2.5 py-1 bg-blue-50 text-blue-700 border border-blue-100 rounded-full text-xs font-medium",children:m},N))})]}),!!(t.constraints&&((X=t.constraints.guards)!=null&&X.length||(H=t.constraints.boundaries)!=null&&H.length||(q=t.constraints.preconditions)!=null&&q.length||(R=t.constraints.sideEffects)!=null&&R.length))&&e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6 space-y-4",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest flex items-center gap-1.5",children:[e.jsx(ut,{size:11,className:"text-amber-500"})," ",i("recipeEditor.constraints")]}),t.constraints.guards&&t.constraints.guards.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:i("recipeEditor.guardRules")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.guards.map((m,N)=>e.jsxs("li",{className:"flex gap-2 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${m.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-xs bg-slate-100 px-1.5 py-0.5 rounded",children:m.pattern}),m.message&&e.jsxs("span",{className:"text-xs text-slate-400",children:["— ",m.message]})]},N))})]}),t.constraints.boundaries&&t.constraints.boundaries.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:i("recipeEditor.boundaryConstraints")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.boundaries.map((m,N)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),m]},N))})]}),t.constraints.preconditions&&t.constraints.preconditions.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:i("recipeEditor.preconditions")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.preconditions.map((m,N)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),m]},N))})]}),t.constraints.sideEffects&&t.constraints.sideEffects.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:i("recipeEditor.sideEffects")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.sideEffects.map((m,N)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),m]},N))})]})]}),t.relations&&Object.entries(t.relations).some(([,m])=>Array.isArray(m)&&m.length>0)&&e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-4",children:i("recipeEditor.relations")}),e.jsx("div",{className:"space-y-2",children:[{key:"inherits",label:i("recipeEditor.relationTypes.inherits"),color:"text-green-600",icon:"↑"},{key:"implements",label:i("recipeEditor.relationTypes.implements"),color:"text-blue-600",icon:"◇"},{key:"calls",label:i("recipeEditor.relationTypes.calls"),color:"text-cyan-600",icon:"→"},{key:"dependsOn",label:i("recipeEditor.relationTypes.dependsOn"),color:"text-yellow-600",icon:"⊕"},{key:"dataFlow",label:i("recipeEditor.relationTypes.dataFlow"),color:"text-purple-600",icon:"⇢"},{key:"conflicts",label:i("recipeEditor.relationTypes.conflicts"),color:"text-red-600",icon:"✕"},{key:"extends",label:i("recipeEditor.relationTypes.extends"),color:"text-teal-600",icon:"⊃"},{key:"related",label:i("recipeEditor.relationTypes.associates"),color:"text-slate-500",icon:"∼"}].map(({key:m,label:N,color:y,icon:W})=>{var be;const O=(be=t.relations)==null?void 0:be[m];return!O||!Array.isArray(O)||O.length===0?null:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:`text-xs font-mono ${y} w-16 shrink-0 pt-0.5`,children:[W," ",N]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:O.map((we,ye)=>e.jsx("span",{className:"px-2 py-0.5 bg-white border border-slate-200 text-slate-600 rounded-lg text-xs font-mono",children:typeof we=="string"?we:we.id||we.title||JSON.stringify(we)},ye))})]},m)})})]}),!((M=t.content)!=null&&M.markdown)&&!((_=t.content)!=null&&_.pattern)&&!t.description&&e.jsx("div",{className:"bg-white p-8 rounded-2xl border border-slate-100 shadow-sm min-h-[200px] flex items-center justify-center",children:e.jsx("div",{className:"text-slate-300 italic",children:i("recipeEditor.noContent")})})]})})}),e.jsxs("div",{className:"p-6 border-t border-slate-100 flex justify-end gap-3",children:[e.jsx("button",{onClick:l,disabled:d,className:"px-4 py-2 text-slate-600 font-medium disabled:opacity-50",children:i("recipeEditor.cancel")}),e.jsxs("button",{onClick:a,disabled:d,className:"px-6 py-2 bg-blue-600 text-white rounded-lg font-medium flex items-center gap-2 hover:bg-blue-700 disabled:opacity-60 disabled:cursor-not-allowed",children:[d?e.jsx(Fe,{size:F.lg,className:"animate-spin"}):e.jsx(Ss,{size:F.lg}),i(d?"recipeEditor.saving":"recipeEditor.saveChanges")]})]})]})]})},oo=({setShowCreateModal:t,createPath:s,setCreatePath:a,handleCreateFromPath:l,handleCreateFromClipboard:d,isExtracting:i})=>{const{t:u}=_e(),{isDark:p}=St();return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-slate-900/50 backdrop-blur-sm"}),e.jsxs("div",{className:`relative w-full max-w-lg rounded-2xl shadow-2xl overflow-hidden ${p?"bg-[#1e1e1e]":"bg-white"}`,children:[e.jsxs("div",{className:`p-6 border-b flex justify-between items-center ${p?"bg-[#252526] border-[#3e3e42]":"bg-slate-50 border-slate-100"}`,children:[e.jsxs("h2",{className:`text-xl font-bold flex items-center gap-2 ${p?"text-white":"text-slate-800"}`,children:[e.jsx(Nt,{size:F.xl,className:"text-blue-600"})," ",u("createModal.title")]}),e.jsx("button",{onClick:()=>t(!1),className:`p-2 rounded-full transition-all duration-150 ${p?"text-slate-400 hover:bg-[#3e3e42] hover:text-slate-200":"text-slate-500 hover:bg-white hover:text-slate-700"}`,children:e.jsx(Xe,{size:F.lg})})]}),e.jsxs("div",{className:"p-8 space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-widest ${p?"text-slate-500":"text-slate-400"}`,children:[e.jsx(Ma,{size:F.sm})," ",u("createModal.importFromPath")]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`flex-1 p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 border ${p?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"bg-slate-100 border-slate-200 text-slate-900"}`,placeholder:u("createModal.pathPlaceholder"),value:s,onChange:n=>a(n.target.value)}),e.jsx("button",{onClick:l,disabled:!s||i,className:`px-4 py-2 rounded-xl text-sm font-bold disabled:opacity-50 transition-all duration-150 ${p?"bg-slate-200 text-slate-900 hover:bg-white":"bg-slate-900 text-white hover:bg-slate-800"}`,children:u("createModal.scanFile")})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:`w-full border-t ${p?"border-[#3e3e42]":"border-slate-100"}`})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:`px-2 font-bold ${p?"bg-[#1e1e1e] text-slate-500":"bg-white text-slate-300"}`,children:u("createModal.or")})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-widest ${p?"text-slate-500":"text-slate-400"}`,children:[e.jsx(_l,{size:F.sm})," ",u("createModal.importFromClipboard")]}),e.jsxs("button",{onClick:()=>d(),disabled:i,className:`w-full flex items-center justify-center gap-3 p-4 rounded-xl font-bold transition-all duration-150 border ${p?"bg-blue-500/10 text-blue-300 border-blue-500/20 hover:bg-blue-500/20 hover:border-blue-400/30":"bg-blue-50 text-blue-700 border-blue-100 hover:bg-blue-100"}`,children:[e.jsx(et,{size:F.lg})," ",u("createModal.useClipboard")]})]})]}),i&&e.jsxs("div",{className:"bg-blue-600 text-white p-4 flex items-center justify-center gap-3 animate-pulse",children:[e.jsx(ns,{size:F.lg,className:"animate-spin"}),e.jsx("span",{className:"font-bold text-sm",children:u("createModal.aiThinking")})]})]})]})};function io(t){if(!t)return"";if(typeof t=="object"){const d=t.code||t.pattern||t.markdown||t.snippet||t.body||"";if(d)return d}const a=(typeof t=="string"?t:JSON.stringify(t)).replace(/^---[\s\S]*?---\s*\n?/,"").trim(),l=a.match(/```[\w]*\n([\s\S]*?)```/);return l&&l[1]?l[1].trim():a.slice(0,8e3)}const co=({searchQ:t,insertPath:s,onClose:a})=>{const{t:l}=_e(),[d,i]=o.useState([]),[u,p]=o.useState(!0),[n,g]=o.useState(null),f=o.useRef(!0),h=o.useRef(null);o.useEffect(()=>(f.current=!0,h.current=new AbortController,se.search(t||"",{mode:"bm25",type:"recipe",signal:h.current.signal}).then(c=>{f.current&&i((c.items||[]).map(j=>({name:(j.title||j.name||"")+".md",path:"",content:j.content,qualityScore:(j.quality||{}).overall||j.qualityScore||0,recommendReason:""})))}).catch(c=>{c.name!=="AbortError"&&f.current&&i([])}).finally(()=>{f.current&&p(!1)}),()=>{f.current=!1,h.current&&h.current.abort()}),[t]);const x=async c=>{g(c.name);try{const j=io(c.content);await se.insertAtSearchMark({path:s,content:j}),f.current&&(alert(l("searchModal.insertSuccess")+" "+s),a())}catch{f.current&&alert(l("searchModal.insertFailed"))}finally{f.current&&g(null)}};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-slate-900/50 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-slate-800",children:[e.jsx(ft,{size:F.xl,className:"text-blue-600"})," ",l("searchModal.title")]}),e.jsx("button",{onClick:a,className:"p-2 hover:bg-white rounded-full transition-colors",children:e.jsx(Xe,{size:F.lg})})]}),e.jsxs("div",{className:"p-4 text-sm text-slate-500 border-b border-slate-100",children:[l("searchModal.keyword")," ",t||l("searchModal.keywordAll")," · ",l("searchModal.insertTo")," ",s]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:u?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):d.length===0?e.jsx("div",{className:"text-slate-500 text-center py-8",children:l("searchModal.noResults")}):e.jsx("ul",{className:"space-y-2",children:d.map(c=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>x(c),disabled:n!==null,className:"w-full flex items-center justify-between gap-3 p-4 rounded-xl border border-slate-200 hover:border-blue-300 hover:bg-blue-50/50 transition-all text-left disabled:opacity-50",children:[e.jsxs("div",{className:"flex-1 flex flex-col gap-1",children:[e.jsx("span",{className:"font-medium text-slate-800 truncate",children:c.name}),(c.qualityScore!==void 0||c.recommendReason)&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.qualityScore!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 rounded text-xs text-blue-700 font-medium",children:["🤖 ",l("searchModal.quality")," ",(c.qualityScore*100).toFixed(0),"%"]}),c.recommendReason&&e.jsx("span",{className:"text-xs text-slate-600 italic truncate max-w-xs",children:c.recommendReason})]})]}),n===c.name?e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⏳"})," ",l("searchModal.inserting")]}):e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx(Fa,{size:F.md})," ",l("searchModal.insertBtn")]})]})},c.name))})})]})]})},Ps=[{id:"google",labelKey:"llmConfig.providers.gemini",defaultModel:"gemini-2.0-flash",keyEnv:"ASD_GOOGLE_API_KEY"},{id:"openai",labelKey:"llmConfig.providers.openai",defaultModel:"gpt-4o",keyEnv:"ASD_OPENAI_API_KEY"},{id:"deepseek",labelKey:"llmConfig.providers.deepseek",defaultModel:"deepseek-chat",keyEnv:"ASD_DEEPSEEK_API_KEY"},{id:"claude",labelKey:"llmConfig.providers.claude",defaultModel:"claude-3-5-sonnet-20240620",keyEnv:"ASD_CLAUDE_API_KEY"},{id:"ollama",labelKey:"llmConfig.providers.ollama",defaultModel:"llama3",keyEnv:""}],uo=({onClose:t,onSaved:s})=>{const{t:a}=_e(),{isDark:l}=St(),[d,i]=o.useState(!0),[u,p]=o.useState(!1),[n,g]=o.useState(!1),[f,h]=o.useState("google"),[x,c]=o.useState("gemini-2.0-flash"),[j,w]=o.useState(""),[C,E]=o.useState(""),[S,G]=o.useState(!1),[z,P]=o.useState({}),[Z,X]=o.useState(!1);o.useEffect(()=>{H()},[]);const H=async()=>{i(!0);try{const y=await se.getLlmEnvConfig();g(y.hasEnvFile);const W=y.vars||{};W.ASD_AI_PROVIDER&&h(W.ASD_AI_PROVIDER),W.ASD_AI_MODEL&&c(W.ASD_AI_MODEL),W.ASD_AI_PROXY&&E(W.ASD_AI_PROXY),P(W)}catch{}finally{i(!1)}},q=Ps.find(y=>y.id===f),R=(q==null?void 0:q.keyEnv)||"",M=R?!!z[R]:!0,_=y=>{h(y);const W=Ps.find(O=>O.id===y);W&&c(W.defaultModel),w("")},m=async()=>{if(f){if(R&&!M&&!j.trim()){alert(a("llmConfig.apiKeyRequired"));return}p(!0),X(!1);try{await se.saveLlmEnvConfig({provider:f,model:x||void 0,apiKey:j.trim()||void 0,proxy:C.trim()||void 0}),X(!0),setTimeout(()=>{s(),t()},800)}catch(y){alert((y==null?void 0:y.message)||a("llmConfig.saveFailed"))}finally{p(!1)}}},N=y=>!y||y.length<10?y?"••••••":"":`${y.slice(0,6)}••••${y.slice(-4)}`;return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50",onClick:t,children:e.jsxs("div",{className:`rounded-2xl shadow-2xl w-full max-w-lg mx-4 overflow-hidden ${l?"bg-[#1e1e1e]":"bg-white"}`,onClick:y=>y.stopPropagation(),children:[e.jsxs("div",{className:`flex items-center justify-between px-6 py-4 border-b ${l?"border-[#3e3e42]":"border-slate-100"}`,children:[e.jsx("h2",{className:`text-lg font-semibold ${l?"text-white":"text-slate-800"}`,children:a("llmConfig.title")}),e.jsx("button",{onClick:t,className:`p-1 rounded-lg transition-all duration-150 ${l?"hover:bg-[#3e3e42] text-slate-400 hover:text-slate-200":"hover:bg-slate-100 text-slate-400"}`,children:e.jsx(Xe,{size:F.md})})]}),e.jsx("div",{className:"px-6 py-5 space-y-5",children:d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Fe,{size:24,className:"animate-spin text-blue-500"})}):e.jsxs(e.Fragment,{children:[!n&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-700",children:[e.jsx(Rt,{size:16,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:a("llmConfig.envWarning")})]}),e.jsxs("div",{children:[e.jsx("label",{className:`block text-sm font-medium mb-2 ${l?"text-slate-300":"text-slate-700"}`,children:a("llmConfig.provider")}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:Ps.map(y=>e.jsx("button",{type:"button",onClick:()=>_(y.id),className:`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${f===y.id?l?"bg-blue-500/20 border-blue-500/40 text-blue-300 ring-1 ring-blue-500/30":"bg-blue-50 border-blue-300 text-blue-700 ring-1 ring-blue-200":l?"bg-[#2a2d35] border-[#3e3e42] text-slate-300 hover:border-slate-500 hover:bg-[#333842]":"bg-white border-slate-200 text-slate-600 hover:border-slate-300 hover:bg-slate-50"}`,children:a(y.labelKey)},y.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:`block text-sm font-medium mb-1.5 ${l?"text-slate-300":"text-slate-700"}`,children:a("llmConfig.model")}),e.jsx("input",{type:"text",value:x,onChange:y=>c(y.target.value),placeholder:(q==null?void 0:q.defaultModel)||"",className:`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 ${l?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"border-slate-200"}`})]}),R&&e.jsxs("div",{children:[e.jsxs("label",{className:`block text-sm font-medium mb-1.5 ${l?"text-slate-300":"text-slate-700"}`,children:[a("llmConfig.apiKey"),M&&e.jsxs("span",{className:"ml-2 text-xs text-green-600 font-normal",children:["(",a("llmConfig.configured")," ",N(z[R]),")"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:S?"text":"password",value:j,onChange:y=>w(y.target.value),placeholder:a(M?"llmConfig.apiKeyPlaceholderSet":"llmConfig.apiKeyPlaceholderEmpty"),className:`w-full px-3 py-2 pr-10 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 ${l?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"border-slate-200"}`}),e.jsx("button",{type:"button",onClick:()=>G(y=>!y),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-slate-400 hover:text-slate-600",children:S?e.jsx($l,{size:16}):e.jsx(os,{size:16})})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:`block text-sm font-medium mb-1.5 ${l?"text-slate-300":"text-slate-700"}`,children:[a("llmConfig.proxy")," ",e.jsx("span",{className:`text-xs font-normal ${l?"text-slate-500":"text-slate-400"}`,children:a("llmConfig.optional")})]}),e.jsx("input",{type:"text",value:C,onChange:y=>E(y.target.value),placeholder:"http://127.0.0.1:7890",className:`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 ${l?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"border-slate-200"}`})]})]})}),e.jsxs("div",{className:`flex items-center justify-end gap-3 px-6 py-4 border-t ${l?"border-[#3e3e42] bg-[#252526]":"border-slate-100 bg-slate-50/50"}`,children:[e.jsx("button",{onClick:t,className:`px-4 py-2 text-sm font-medium transition-colors ${l?"text-slate-400 hover:text-slate-200":"text-slate-600 hover:text-slate-800"}`,children:a("llmConfig.cancel")}),e.jsxs("button",{onClick:m,disabled:u||d||Z,className:`flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-medium transition-all ${Z?"bg-green-500 text-white":"bg-blue-600 text-white hover:bg-blue-700 shadow-sm"} disabled:opacity-60`,children:[u?e.jsx(Fe,{size:16,className:"animate-spin"}):Z?e.jsx(cs,{size:16}):e.jsx(Ss,{size:16}),a(Z?"llmConfig.saved":"llmConfig.saveToEnv")]})]})]})})};class po extends Ct.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}render(){var s;return this.state.hasError?e.jsxs("div",{style:{padding:40,textAlign:"center"},children:[e.jsx("h2",{style:{color:"#ef4444",marginBottom:12},children:zs.app.errorBoundary.title}),e.jsx("pre",{style:{fontSize:12,color:"#64748b",whiteSpace:"pre-wrap",maxWidth:600,margin:"0 auto"},children:(s=this.state.error)==null?void 0:s.message}),e.jsx("button",{onClick:()=>{this.setState({hasError:!1,error:null}),window.location.reload()},style:{marginTop:16,padding:"8px 20px",background:"#3b82f6",color:"#fff",border:"none",borderRadius:8,cursor:"pointer"},children:zs.app.errorBoundary.refreshBtn})]}):this.props.children}}function Qt(t,s="ai-scan"){return{title:t.title||"",description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:t.category||"",tags:t.tags||[],kind:t.kind||"",knowledgeType:t.knowledgeType||"",scope:t.scope||"",complexity:t.complexity||"",difficulty:t.difficulty||"",authority:t.authority,lifecycle:t.lifecycle||"pending",source:t.source||s,doClause:t.doClause||"",dontClause:t.dontClause||"",whenClause:t.whenClause||"",topicHint:t.topicHint||"",coreCode:t.coreCode||"",content:t.content||{},constraints:t.constraints||{},reasoning:t.reasoning||{},quality:t.quality||{},stats:t.stats||{},relations:t.relations||{},headers:t.headers||[],headerPaths:t.headerPaths,moduleName:t.moduleName,includeHeaders:t.includeHeaders,createdAt:t.createdAt,updatedAt:t.updatedAt}}const xo=()=>{var Je,st;const t=pr(),s=mr((Je=t.user)==null?void 0:Je.role),a=hr(),{t:l,lang:d}=_e(),i=()=>{const A=window.location.pathname.replace(/^\//,"").split("/")[0]||"";return sr.includes(A)?A:"help"},[u,p]=o.useState(null),[n,g]=o.useState(i()),[f,h]=o.useState(!1),[x,c]=o.useState(""),[j,w]=o.useState(!0),[C,E]=o.useState(null),[S,G]=o.useState([]),[z,P]=o.useState([]),[Z,X]=o.useState(null),[H,q]=o.useState(!1),[R,M]=o.useState({current:0,total:0,status:""}),[_,m]=o.useState([]),[N,y]=o.useState([]),[W,O]=o.useState(null),[be,we]=o.useState("All"),[ye,v]=o.useState(1),[ee,ae]=o.useState(12),[ue,fe]=o.useState(!1),[he,ce]=o.useState(""),[je,$]=o.useState(!1),[K,xe]=o.useState(null),[L,T]=o.useState(null),[Q,ie]=o.useState(!1),[ke,Ue]=o.useState(!0),[Ie,ne]=o.useState(!1),[ve,He]=o.useState(0),Pe=o.useRef(null),Ne=o.useRef(null);o.useEffect(()=>{v(1)},[x,be]),o.useEffect(()=>{if(u!=null&&u.projectRoot)try{const A=`asd:custom-folder-targets:${u.projectRoot}`,le=localStorage.getItem(A);P(le?JSON.parse(le):[])}catch{P([])}},[u==null?void 0:u.projectRoot]);const r=()=>{Pe.current&&Pe.current.abort()};o.useEffect(()=>{let A=!1;const le=async()=>{var pe,De,Te;try{const Ee=await se.getSignalStatus();if(!A){const Me=((pe=Ee==null?void 0:Ee.suggestions)==null?void 0:pe.length)||0,Se=((Te=(De=Ee==null?void 0:Ee.snapshot)==null?void 0:De.lastResult)==null?void 0:Te.newSuggestions)||0;He(Me||Se)}}catch{}};le();const Y=setInterval(le,300*1e3);return()=>{A=!0,clearInterval(Y)}},[]),o.useEffect(()=>{a.isAllDone&&D()},[a.isAllDone]),o.useEffect(()=>{if(a.candidateCreatedTick>0){const A=setTimeout(()=>D(),2e3);return()=>clearTimeout(A)}},[a.candidateCreatedTick]);const k=(A,le)=>{g(A);const Y=le!=null&&le.preserveSearch&&window.location.search?window.location.search:"";window.history.pushState({},document.title,`/${A}${Y}`)},b=A=>{E(A),g("recipes");const le=new URLSearchParams(window.location.search);le.set("edit",encodeURIComponent(A.name)),window.history.pushState({},document.title,`/recipes?${le.toString()}`)},B=()=>{E(null),window.history.replaceState({},document.title,"/recipes")};o.useEffect(()=>{x===""&&xe(null)},[x]),o.useEffect(()=>{g(i())},[]),o.useEffect(()=>{if(!u)return;const A=window.location.pathname.replace(/^\//,"").split("/")[0],Y=new URLSearchParams(window.location.search).get("edit");if(A==="recipes"&&Y&&u.recipes)try{const pe=decodeURIComponent(Y),De=u.recipes.find(Te=>Te.name===pe);De&&!C&&(g("recipes"),b(De))}catch{}},[u]),o.useEffect(()=>{D(),U(),te();const A=()=>{g(i())};window.addEventListener("popstate",A);const le=new URLSearchParams(window.location.search),Y=le.get("action"),pe=le.get("path"),De=le.get("q")||"";return Y==="search"&&pe?T({q:De,path:pe}):Y==="create"&&pe&&(ce(pe),fe(!0),le.get("autoScan")==="1"&&setTimeout(()=>I(pe),500)),Y&&window.history.replaceState({},document.title,window.location.pathname),()=>{window.removeEventListener("popstate",A)}},[]);const D=async()=>{w(!0);try{const A=await se.fetchData();p(A)}catch(A){re((A==null?void 0:A.message)||l("app.load.failed"),{title:l("app.load.failedTitle"),type:"error"})}finally{w(!1)}},U=async()=>{try{const A=await se.fetchTargets();G(A)}catch(A){console.warn("删除候选残留失败:",A==null?void 0:A.message)}},te=async()=>{try{const A=await se.getLlmEnvConfig();Ue(A.llmReady)}catch{}},de=async()=>{try{const A=await se.syncSnippets("all");re(l("app.sync.success"),{title:l("app.sync.successTitle")})}catch{re(l("app.sync.failedHint"),{title:l("app.sync.failed"),type:"error"})}},me=async()=>{try{await se.refreshProject(),U(),re(l("app.projectRefresh.success"),{title:l("app.projectRefresh.successTitle")})}catch{re(l("app.load.failedHint"),{title:l("app.projectRefresh.failed"),type:"error"})}},I=async A=>{var le;$(!0);try{const Y=await se.extractFromPath(A);y(Y.result.map(pe=>({...Qt(pe,"extract"),mode:"full",lang:"cn"}))),k("spm"),fe(!1),D(),((le=Y.result)==null?void 0:le.length)>0&&re(l("app.extract.success"),{title:l("app.extract.successTitle")})}catch{re(l("app.extract.failed"),{type:"error"})}finally{$(!1)}},V=async()=>{var A;if(he){$(!0);try{const le=await se.extractFromPath(he);y(le.result.map(Y=>({...Qt(Y,"extract"),mode:"full",lang:"cn"}))),k("spm"),fe(!1),D(),((A=le.result)==null?void 0:A.length)>0?re(le.isMarked?l("app.extract.markerSuccess"):l("app.extract.normalSuccess"),{title:l("app.extract.successTitle")}):le.isMarked||re(l("app.extract.noMarker"),{title:l("app.extract.extracting"),type:"info"})}catch{re(l("app.extract.failed"),{type:"error"})}finally{$(!1)}}},Ce=async A=>{var le,Y,pe,De;try{const Te=await navigator.clipboard.readText();if(!Te)return re(l("app.clipboard.empty"),{title:l("app.clipboard.emptyTitle"),type:"info"});re(l("app.clipboard.analyzing"),{title:l("app.clipboard.analyzingTitle"),type:"info"}),$(!0);const Ee=A||he;try{const Me=await se.extractFromText(Te,Ee||void 0),Se=Me._multipleCount;y([{...Qt(Me,"clipboard"),mode:"full",lang:"cn"}]),k("spm"),fe(!1),D(),re(Se?l("app.clipboard.resultMulti",{count:Se}):l("app.extract.normalSuccess"),{title:l("app.clipboard.resultTitle")})}catch(Me){const Se=((Y=(le=Me.response)==null?void 0:le.data)==null?void 0:Y.aiError)===!0,Ke=((De=(pe=Me.response)==null?void 0:pe.data)==null?void 0:De.error)||Me.message;Se?re(Ke,{title:l("app.clipboard.aiFailed"),type:"error"}):re(Ke,{title:l("common.operationFailed"),type:"error"})}}catch{re(l("app.clipboard.permissionError"),{title:l("app.clipboard.permissionTitle"),type:"error"})}finally{$(!1)}},Ae={"scan:started":{percent:5,status:l("app.scan.events.initializing")},"scan:files-loaded":{percent:15,status:A=>l("app.scan.events.filesLoaded",{count:A.count||0})},"scan:reading":{percent:25,status:A=>l("app.scan.events.readingFiles",{count:A.count||0})},"scan:ai-extracting":{percent:40,status:l("app.scan.events.aiAnalyzing")},"scan:enriching":{percent:85,status:A=>l("app.scan.events.enriching",{count:A.recipeCount||0})},"scan:completed":{percent:95,status:l("app.scan.events.completing")}},Re=async A=>{var Y;if(H)return;Pe.current&&Pe.current.abort(),Ne.current&&(clearInterval(Ne.current),Ne.current=null);const le=new AbortController;Pe.current=le,X(A.name),q(!0),y([]),O(null),m([]),M({current:0,total:100,status:l("app.scan.streamInit")});try{const pe=await se.scanTargetStream(A,Ee=>{const Me=Ae[Ee.type];if(Me){const Se=typeof Me.status=="function"?Me.status(Ee):Me.status;M({current:Me.percent,total:100,status:Se})}Ee.type==="scan:files-loaded"&&Ee.files&&m(Ee.files),Ee.type==="scan:ai-extracting"&&(Ne.current&&clearInterval(Ne.current),Ne.current=setInterval(()=>{M(Se=>({...Se,current:Math.min(Se.current+1,80)}))},3e3)),(Ee.type==="scan:enriching"||Ee.type==="scan:completed")&&Ne.current&&(clearInterval(Ne.current),Ne.current=null)},le.signal);Ne.current&&(clearInterval(Ne.current),Ne.current=null),M({current:100,total:100,status:l("app.scan.completed")});const De=pe.recipes||[],Te=pe.scannedFiles||[];if(De.length>0||Te.length>0){const Ee=typeof A=="string"?A:(A==null?void 0:A.name)||"unknown",Me=De.map(Se=>({...Qt(Se,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:Ee,scanMode:"target"}));if(y(Me),Te.length>0&&m(Te),D(),De.length>0)re(l("app.scan.targetSuccess",{count:De.length}),{title:l("app.scan.targetSuccessTitle")});else if(pe.message){const Se=pe.noAi;re(pe.message,{title:l(Se?"app.scan.aiNotConfigured":"app.scan.noResults"),type:Se?"info":"error"})}else re(l("app.scan.noSnippets"),{title:l("app.scan.scanComplete"),type:"info"})}else re(l("app.scan.scanFailedHint"),{title:l("app.scan.scanFailed"),type:"error"})}catch(pe){if(Ne.current&&(clearInterval(Ne.current),Ne.current=null),pe.name==="AbortError")return;const De=(Y=pe.message)==null?void 0:Y.includes("timeout"),Te=De?l("app.scan.timeout"):pe.message||l("app.scan.scanError");re(Te,{title:l(De?"app.scan.timeoutTitle":"app.scan.scanError"),type:"error"})}finally{Pe.current===le&&(q(!1),M({current:0,total:0,status:""}),Pe.current=null)}},Be=async()=>{var le,Y,pe,De,Te,Ee;if(H)return;Pe.current&&Pe.current.abort();const A=new AbortController;Pe.current=A,k("candidates"),q(!0),y([]),O(null),m([]),M({current:0,total:100,status:l("app.coldStart.collecting")}),a.resetSession();try{const Me=await se.bootstrap(A.signal);M({current:100,total:100,status:l("app.coldStart.skeletonCreated")}),Me.bootstrapSession&&a.initFromApiResponse(Me.bootstrapSession),D();const Se=Me.report||{},Ke=((le=Me.targets)==null?void 0:le.length)||0,it=((Y=Se.totals)==null?void 0:Y.files)||0,At=((pe=Se.totals)==null?void 0:pe.graphEdges)||0,Kt=Me.guardSummary,As=Kt?`, ${l("app.coldStart.guardSuffix",{count:Kt.totalViolations})}`:"";re(l("app.coldStart.skeletonDetail",{targets:Ke,files:it,deps:At})+As)}catch(Me){if(ss.isCancel(Me))return;const Ke=Me.code==="ECONNABORTED"||((De=Me.message)==null?void 0:De.includes("timeout"))?l("app.coldStart.timeout"):((Ee=(Te=Me.response)==null?void 0:Te.data)==null?void 0:Ee.error)||Me.message;re(Ke,{type:"error"})}finally{Pe.current===A&&(q(!1),M({current:0,total:0,status:""}),Pe.current=null)}},Ye=async()=>{var De,Te,Ee,Me;if(H)return;Pe.current&&Pe.current.abort();const A=new AbortController;Pe.current=A,k("spm"),X("__project__"),q(!0),y([]),O(null),m([]),M({current:0,total:100,status:l("app.fullScan.collecting")});const le=[{status:l("app.fullScan.phase5"),percent:5},{status:l("app.fullScan.phase15"),percent:15},{status:l("app.fullScan.phase25"),percent:25},{status:l("app.fullScan.phase35"),percent:35},{status:l("app.fullScan.phase45"),percent:45},{status:l("app.fullScan.phase55"),percent:55},{status:l("app.fullScan.phase65"),percent:65},{status:l("app.fullScan.phase75"),percent:75},{status:l("app.fullScan.phase85"),percent:85}];let Y=0;const pe=setInterval(()=>{Y=Math.min(Y+1,le.length);const Se=le[Y-1];Se&&M(Ke=>({...Ke,current:Se.percent,status:Se.status}))},15e3);try{const Se=await se.scanProject(A.signal);clearInterval(pe),M({current:100,total:100,status:Se.partial?l("app.fullScan.partialComplete"):l("app.fullScan.completed")});const Ke=Se.recipes||[],it=Se.scannedFiles||[];if(Ke.length>0||it.length>0){const At=Ke.map(tl=>({...Qt(tl,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:"__project__",scanMode:"project"}));y(At),m(it),O(Se.guardAudit||null),D();const Kt=(De=Se.guardAudit)==null?void 0:De.summary,As=Kt?`, ${l("app.fullScan.guardSuffix",{count:Kt.totalViolations})}`:"",el=Se.partial?l("app.fullScan.timeoutSuffix"):"";re(l("app.fullScan.resultDetail",{count:Ke.length})+As+el)}else re(l("app.fullScan.noContent"))}catch(Se){if(clearInterval(pe),ss.isCancel(Se))return;const it=Se.code==="ECONNABORTED"||((Te=Se.message)==null?void 0:Te.includes("timeout"))?l("app.fullScan.timeout"):((Me=(Ee=Se.response)==null?void 0:Ee.data)==null?void 0:Me.error)||Se.message;re(it,{type:"error"})}finally{Pe.current===A&&(q(!1),M({current:0,total:0,status:""}),Pe.current=null)}},J=(A,le)=>{const Y=[...N],pe={...Y[A],...le};Y[A]=pe,y(Y)},Le=async A=>{var le;if(!Q){ie(!0);try{const Y=(((le=A.content)==null?void 0:le.pattern)||"").trim(),pe=(()=>{if(!Y)return!1;const Ke=Y.split(`
131
- `).filter(At=>At.trim());return Ke.filter(At=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(At)).length<=Ke.length*.3})(),De=(A.trigger||"").split(/[,,\s]+/).map(Ke=>Ke.trim()).filter(Boolean);if(pe&&De.length===0){re(l("app.recipe.triggerRequired"),{type:"error"}),ie(!1);return}const Te={title:A.title||"Untitled",description:A.description||"",trigger:De.join(", ")||"",language:A.language||"",category:A.category||"Utility",kind:A.kind||"pattern",knowledgeType:A.knowledgeType||"code-pattern",complexity:A.complexity||"intermediate",scope:A.scope||null,difficulty:A.difficulty||"",tags:A.tags||[],source:A.source||"ai-scan",sourceFile:A.sourceFile||"",moduleName:A.moduleName||"",doClause:A.doClause||"",dontClause:A.dontClause||"",whenClause:A.whenClause||"",topicHint:A.topicHint||"",coreCode:A.coreCode||"",content:A.content||{},reasoning:A.reasoning||{},quality:A.quality||{},constraints:A.constraints||{},relations:A.relations||{},stats:A.stats||{},headers:A.headers||[],headerPaths:A.headerPaths||[],includeHeaders:A.includeHeaders||!1},Ee=await se.knowledgeCreate(Te);if(Ee!=null&&Ee.id)try{await se.knowledgeLifecycle(Ee.id,"publish")}catch(Ke){console.warn("auto-publish after save failed:",Ke)}re(l(pe?"app.recipe.savedAsRecipe":"app.recipe.savedToKb")),y(Ke=>Ke.filter(it=>it.title!==A.title));const Me=A.candidateTargetName,Se=A.candidateId;if(Me&&Se)try{await se.deleteCandidate(Se)}catch{}D()}catch(Y){const pe=aa(Y)??vs(Y);re(pe??l("app.recipe.saveFailed"),{type:"error"})}finally{ie(!1)}}},qe=async()=>{var A,le;if(!(!C||Q)){ie(!0);try{const Y=C.id||((A=C.name)==null?void 0:A.replace(/\.md$/,"")),pe=typeof C.content=="string"?{pattern:C.content,markdown:"",rationale:"",steps:[],codeChanges:[],verification:null}:C.content||{};await se.knowledgeUpdate(Y,{title:((le=C.name)==null?void 0:le.replace(/\.md$/,""))||"",description:C.description||"",content:pe,tags:C.tags||[],kind:C.kind,language:C.language,category:C.category}),B(),D()}catch(Y){const pe=aa(Y)??vs(Y);re(pe??l("app.recipe.saveRecipeFailed"),{type:"error"})}finally{ie(!1)}}},ze=async A=>{if(window.confirm(l("common.areYouSure")))try{await se.deleteRecipe(A),D()}catch(le){const Y=vs(le);re(Y??l("common.deleteFailed"),{type:"error"})}},Ve=async(A,le)=>{try{await se.deleteCandidate(le),y(Y=>Y.filter(pe=>!(pe.candidateId===le&&pe.candidateTargetName===A))),p(Y=>{if(!(Y!=null&&Y.candidates))return Y;const pe={...Y.candidates};if(pe[A]){const De=pe[A].items.filter(Te=>Te.id!==le);De.length===0?delete pe[A]:pe[A]={...pe[A],items:De}}return{...Y,candidates:pe}})}catch{re(l("common.operationFailed"),{type:"error"})}},ge=async A=>{if(window.confirm(l("app.candidate.clearConfirm",{name:A})))try{await se.deleteAllCandidatesInTarget(A),D(),re(l("app.candidate.clearDone",{name:A}))}catch{re(l("common.operationFailed"),{type:"error"})}},Oe=async(A,le)=>{var Y,pe;try{await se.promoteToCandidate(A,A.candidateTargetName||Z||"_review"),re(l("app.candidate.pushSuccess")),y(De=>De.filter((Te,Ee)=>Ee!==le)),D()}catch(De){const Te=(pe=(Y=De.response)==null?void 0:Y.data)==null?void 0:pe.error,Ee=typeof Te=="string"?Te:(Te==null?void 0:Te.message)||l("app.candidate.pushFailed");re(Ee,{type:"error"})}},We=((u==null?void 0:u.recipes)||[]).filter(A=>{var Ee,Me;if(K)return K.some(Se=>Se.metadata.type==="recipe"&&Se.metadata.name===A.name);const le=A.name||"",Y=typeof A.content=="string"?A.content:[(Ee=A.content)==null?void 0:Ee.pattern,(Me=A.content)==null?void 0:Me.markdown].filter(Boolean).join(" "),pe=le.toLowerCase().includes(x.toLowerCase())||Y.toLowerCase().includes(x.toLowerCase())||(A.description||"").toLowerCase().includes(x.toLowerCase());if(be==="All")return pe;const De=Y?Y.match(/category:\s*(.*)/):null,Te=De?De[1].trim():"Utility";return pe&&Te===be}).sort((A,le)=>{var De,Te,Ee,Me;if(K){const Se=((De=K.find(it=>it.metadata.name===A.name))==null?void 0:De.similarity)||0;return(((Te=K.find(it=>it.metadata.name===le.name))==null?void 0:Te.similarity)||0)-Se}const Y=((Ee=A.stats)==null?void 0:Ee.authorityScore)??0;return(((Me=le.stats)==null?void 0:Me.authorityScore)??0)-Y}),Ge=Ct.useMemo(()=>{const A=new Set(S.map(Y=>`${Y.discovererId||""}::${Y.name}`)),le=z.filter(Y=>!A.has(`${Y.discovererId||""}::${Y.name}`));return[...S,...le]},[S,z]),pt=Ge.filter(A=>A.name.toLowerCase().includes(x.toLowerCase())).sort((A,le)=>{const Y=us(A.name),pe=us(le.name);if(Y&&!pe)return 1;if(!Y&&pe)return-1;const De=A.isVirtual?1:0,Te=le.isVirtual?1:0;return De!==Te?De-Te:A.name.localeCompare(le.name)}),Mt=o.useCallback(A=>{P(le=>{if(le.some(pe=>pe.path===A.path))return le;const Y=[...le,A];return u!=null&&u.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${u.projectRoot}`,JSON.stringify(Y)),Y})},[u==null?void 0:u.projectRoot]),Ft=o.useCallback(A=>{P(le=>{const Y=le.filter(pe=>pe.path!==A);return u!=null&&u.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${u.projectRoot}`,JSON.stringify(Y)),Y})},[u==null?void 0:u.projectRoot]),zt=Object.values((u==null?void 0:u.candidates)||{}).reduce((A,le)=>A+le.items.length,0),{isDark:$e}=St();return e.jsx(po,{children:e.jsx(Fr,{children:e.jsxs("div",{className:`flex h-screen ${$e?"bg-[#1e1e1e] text-slate-200":"bg-slate-50 text-slate-900"} overflow-hidden font-sans`,children:[e.jsx(rl,{position:"top-center",toastOptions:{duration:5e3,style:{background:"none",padding:0,boxShadow:"none",border:"none"}},containerStyle:{top:24}}),e.jsx(br,{activeTab:n,navigateToTab:k,candidateCount:zt,signalSuggestionCount:ve,currentUser:s.user!=="anonymous"?s.user:void 0,currentRole:s.role,permissionMode:s.mode,onLogout:void 0,collapsed:f,onToggleCollapse:()=>h(A=>!A)}),e.jsxs("main",{className:"flex-1 flex flex-col overflow-hidden relative",children:[e.jsx(_r,{searchQuery:x,setSearchQuery:c,setShowCreateModal:fe,handleSyncSnippets:de,aiConfig:u==null?void 0:u.aiConfig,llmReady:ke,onOpenLlmConfig:()=>ne(!0),onBeforeAiSwitch:r,onAiConfigChange:D,onSemanticSearchResults:A=>{xe(A),n!=="recipes"&&k("recipes")}}),n==="recipes"&&e.jsx($r,{selectedCategory:be,setSelectedCategory:we}),e.jsx("div",{className:`flex-1 ${n==="wiki"?"overflow-hidden":"overflow-y-auto p-8"}`,children:j?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):n==="recipes"?e.jsx(Wr,{recipes:We,openRecipeEdit:b,handleDeleteRecipe:ze,onRefresh:D,idTitleMap:u==null?void 0:u.idTitleMap,currentPage:ye,onPageChange:v,pageSize:ee,onPageSizeChange:A=>{ae(A),v(1)}}):n==="guard"?e.jsx(vn,{onRefresh:D}):n==="skills"?e.jsx(Bn,{onRefresh:D,signalSuggestionCount:ve,onSuggestionCountChange:He}):n==="candidates"?e.jsxs(e.Fragment,{children:[a.session&&e.jsx("div",{className:"mb-4",children:e.jsx(Wn,{session:a.session,isAllDone:a.isAllDone,reviewState:a.reviewState,onDismiss:()=>a.resetSession()})}),e.jsx(ln,{data:u,isShellTarget:us,isSilentTarget:lr,isPendingTarget:rr,handleDeleteCandidate:Ve,onEditRecipe:b,onColdStart:Be,isScanning:H,isBootstrapping:((st=a.session)==null?void 0:st.status)==="running",onRefresh:D,onAuditCandidate:(A,le)=>{var De,Te;const Y=(((De=A.content)==null?void 0:De.pattern)||"").trim(),pe=!!Y&&(()=>{const Ee=Y.split(`
132
- `).filter(Se=>Se.trim());return Ee.filter(Se=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Se)).length<=Ee.length*.3})();y([{...A,mode:pe?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:A.difficulty||A.complexity||"intermediate",authority:((Te=A.stats)==null?void 0:Te.authority)||3,candidateId:A.id,candidateTargetName:le}]),k("spm")},onAuditAllInTarget:(A,le)=>{y(A.map(Y=>{var Te,Ee;const pe=(((Te=Y.content)==null?void 0:Te.pattern)||"").trim(),De=!!pe&&(()=>{const Me=pe.split(`
133
- `).filter(Ke=>Ke.trim());return Me.filter(Ke=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Ke)).length<=Me.length*.3})();return{...Y,mode:De?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:Y.difficulty||Y.complexity||"intermediate",authority:((Ee=Y.stats)==null?void 0:Ee.authority)||3,candidateId:Y.id,candidateTargetName:le}})),k("spm")},handleDeleteAllInTarget:ge})]}):n==="knowledge"?e.jsx($n,{onRefresh:me,idTitleMap:u==null?void 0:u.idTitleMap}):n==="depgraph"?e.jsx(jn,{}):n==="knowledgegraph"?e.jsx(Mn,{}):n==="spm"?e.jsx(mn,{targets:Ge,filteredTargets:pt,selectedTargetName:Z,isScanning:H,scanProgress:R,scanFileList:_,scanResults:N,guardAudit:W,handleScanTarget:Re,handleScanProject:Ye,handleUpdateScanResult:J,handleSaveExtracted:Le,handlePromoteToCandidate:Oe,handleDeleteCandidate:Ve,onEditRecipe:b,isShellTarget:us,recipes:(u==null?void 0:u.recipes)??[],isSavingRecipe:Q,handleRefreshProject:me,onAddCustomFolder:Mt,onRemoveCustomFolder:Ft}):n==="wiki"?e.jsx(lo,{}):n==="help"?e.jsx(Qr,{}):e.jsx(kn,{})}),C&&e.jsx(no,{editingRecipe:C,setEditingRecipe:E,handleSaveRecipe:qe,closeRecipeEdit:B,isSavingRecipe:Q}),ue&&e.jsx(oo,{setShowCreateModal:fe,createPath:he,setCreatePath:ce,handleCreateFromPath:V,handleCreateFromClipboard:Ce,isExtracting:je}),L&&e.jsx(co,{searchQ:L.q,insertPath:L.path,onClose:()=>{T(null),window.history.replaceState({},document.title,window.location.pathname)}}),Ie&&e.jsx(uo,{onClose:()=>ne(!1),onSaved:()=>{te(),D()}})]}),e.jsx(mo,{})]})})})},mo=()=>{const{isOpen:t}=ds();return t?e.jsx(zr,{}):null};nl.createRoot(document.getElementById("root")).render(e.jsx(Ct.StrictMode,{children:e.jsx(Ul,{children:e.jsx(ql,{children:e.jsx(xo,{})})})}));
129
+ ${t("wiki.loadFailedDesc")}`)}finally{x(!1)}}},q=()=>{n(null),f("")},I=o.useMemo(()=>l.filter(m=>m.path!=="meta.json"),[l]),L=o.useMemo(()=>Xn(I,T==null?void 0:T.files),[I,T]);if(i)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(Me,{size:z.xl,className:"text-blue-500 animate-spin"})});const $=!c&&I.length===0&&s.task.status!=="running";return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden p-6 pt-4",children:[e.jsx(Qn,{task:s.task,wiki:s.wiki}),$?e.jsx(to,{}):e.jsxs(e.Fragment,{children:[s.task.status==="running"&&e.jsxs("div",{className:"mb-3 flex items-center gap-3 px-4 py-2.5 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/70 rounded-xl shrink-0",children:[e.jsxs("div",{className:"relative flex items-center justify-center w-6 h-6",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-30 animate-ping"}),e.jsx(Me,{size:16,className:"text-blue-600 animate-spin relative"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-blue-800",children:t("wiki.wikiGenerating")}),s.task.message&&e.jsx("span",{className:"text-xs text-blue-500 ml-2 truncate",children:s.task.message})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("div",{className:"w-24 bg-blue-100 rounded-full h-1.5",children:e.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(s.task.progress||0,3)}%`}})}),e.jsxs("span",{className:"text-xs font-mono text-blue-600 w-8 text-right",children:[s.task.progress||0,"%"]})]})]}),e.jsxs("div",{className:"flex gap-4 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:`w-64 flex-shrink-0 bg-white border border-slate-200 rounded-xl flex flex-col overflow-hidden ${p?"hidden lg:flex":""}`,children:[e.jsxs("div",{className:"px-3 pt-3 pb-2 border-b border-slate-100 shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tt,{size:16,className:"text-blue-500"}),e.jsx("span",{className:"text-sm font-semibold text-slate-700",children:"Wiki"}),(T==null?void 0:T.version)&&e.jsxs("span",{className:"text-[10px] text-slate-300",children:["v",T.version]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[c&&e.jsx("span",{className:"text-[10px] text-slate-400",children:t("wiki.fileCount",{count:I.length})}),s.task.status!=="running"&&c&&e.jsx("button",{onClick:X,title:t("wiki.incrementalUpdate"),className:"p-1 rounded-md text-blue-500 hover:bg-blue-50 transition-colors",children:e.jsx(yt,{size:13})})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(ft,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{type:"text",placeholder:t("wiki.searchPlaceholder"),value:k,onChange:m=>w(m.target.value),className:"w-full pl-8 pr-3 py-2 text-sm bg-slate-50 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-300 transition-all"})]})]}),e.jsxs("div",{className:"p-2 overflow-y-auto flex-1 min-h-0 scrollbar-light",children:[e.jsx(Zn,{tree:L,selectedFile:p,onSelect:H,searchQuery:k}),s.task.status==="running"&&e.jsxs("div",{className:"mx-2 mt-3 mb-1 flex items-center gap-2 px-3 py-2 bg-blue-50 border border-blue-100 rounded-lg",children:[e.jsx(Me,{size:12,className:"text-blue-500 animate-spin flex-shrink-0"}),e.jsx("span",{className:"text-[11px] text-blue-600 leading-tight",children:t("wiki.generating")})]})]}),(T==null?void 0:T.generatedAt)&&e.jsx("div",{className:"px-3 py-2 border-t border-slate-100 shrink-0",children:e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-slate-400",children:[e.jsx(xt,{size:10}),e.jsx("span",{children:Yn(T.generatedAt)}),T.duration!=null&&e.jsxs("span",{children:["· ",Za(T.duration)]})]})})]}),e.jsx("div",{className:`flex-1 bg-white border border-slate-200 rounded-xl overflow-hidden flex flex-col min-h-0 ${p?"":"hidden lg:flex"}`,children:p?e.jsx(eo,{filePath:p,content:g,loading:h,meta:T,onBack:q}):e.jsx(so,{meta:T,onSelectFile:H,isGenerating:s.task.status==="running",progress:s.task.progress,message:s.task.message})})]})]})]})},lo={authority:0,guardUsageCount:0,humanUsageCount:0,aiUsageCount:0,lastUsedAt:null,authorityScore:0},ro=({editingRecipe:t,setEditingRecipe:s,handleSaveRecipe:a,closeRecipeEdit:l,isSavingRecipe:d=!1})=>{var x,i,y,k,w,T,A,G,_,E,Z,X,H,q,I,L,$;const{t:c}=_e(),[u,p]=o.useState("preview"),n=o.useRef(!0);o.useEffect(()=>()=>{n.current=!1},[]);const g=(()=>{const m=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(m)?"objectivec":t.language||"text"})(),f=async m=>{try{if(await ae.setRecipeAuthority(t.name,m),n.current){const N=t.stats?{...t.stats,authority:m}:{...lo,authority:m};s({...t,stats:N})}}catch(N){console.warn(c("recipeEditor.authorityFailed"),N==null?void 0:N.message)}},h=m=>{if(!m)return"";const N=typeof m=="string"?new Date(m).getTime():m;return isNaN(N)?"":new Date(N).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-slate-900/50 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white w-full max-w-6xl rounded-2xl shadow-2xl flex flex-col h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-slate-100 flex justify-between items-center flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-bold",children:c("recipeEditor.title")}),t.kind&&(()=>{const N={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:dt},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:jt},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:tt}}[t.kind];if(!N)return null;const j=N.icon;return e.jsxs("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase flex items-center gap-1 border ${N.bg} ${N.color} ${N.border}`,children:[e.jsx(j,{size:z.sm}),N.label]})})(),t.status&&t.status!=="active"&&t.status!=="published"&&e.jsx("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase border ${t.status==="draft"?"bg-slate-50 text-slate-500 border-slate-200":t.status==="archived"?"bg-orange-50 text-orange-600 border-orange-200":"bg-slate-50 text-slate-500 border-slate-200"}`,children:t.status})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-500",children:c("recipeEditor.authorityScore")}),u==="preview"?e.jsx("span",{className:"text-sm text-slate-700",children:((x=t.stats)==null?void 0:x.authority)??3}):e.jsxs("select",{className:"font-bold text-amber-600 bg-amber-50 border border-amber-100 px-2 py-1 rounded-lg outline-none text-[10px] focus:ring-2 focus:ring-amber-500",value:((i=t.stats)==null?void 0:i.authority)??3,onChange:m=>f(parseInt(m.target.value)),children:[e.jsxs("option",{value:"1",children:["⭐ 1 - ",c("recipeEditor.qualityLevels.basic")]}),e.jsxs("option",{value:"2",children:["⭐⭐ 2 - ",c("recipeEditor.qualityLevels.good")]}),e.jsxs("option",{value:"3",children:["⭐⭐⭐ 3 - ",c("recipeEditor.qualityLevels.solid")]}),e.jsxs("option",{value:"4",children:["⭐⭐⭐⭐ 4 - ",c("recipeEditor.qualityLevels.great")]}),e.jsxs("option",{value:"5",children:["⭐⭐⭐⭐⭐ 5 - ",c("recipeEditor.qualityLevels.excellent")]})]})]}),e.jsxs("div",{className:"flex bg-slate-100 p-1 rounded-lg mr-4",children:[e.jsxs("button",{onClick:()=>p("preview"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${u==="preview"?"bg-white shadow-sm text-blue-600":"text-slate-400"}`,children:[e.jsx(os,{size:z.sm})," ",c("recipeEditor.preview")]}),e.jsxs("button",{onClick:()=>p("edit"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${u==="edit"?"bg-white shadow-sm text-blue-600":"text-slate-400"}`,children:[e.jsx(Et,{size:z.sm})," ",c("recipeEditor.edit")]})]}),e.jsx("button",{onClick:l,className:"p-2 hover:bg-slate-100 rounded-full",children:e.jsx(Xe,{size:z.lg})})]})]}),e.jsx("div",{className:"p-6 space-y-4 flex-1 flex flex-col overflow-hidden",children:e.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:u==="edit"?e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-5 pr-1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1",children:c("recipeEditor.path")}),e.jsx("input",{className:"w-full p-2 bg-slate-50 border border-slate-200 rounded-lg text-sm",value:t.name,onChange:m=>s({...t,name:m.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1",children:c("recipeEditor.description")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-none",rows:2,value:t.description||"",onChange:m=>s({...t,description:m.target.value}),placeholder:c("recipeEditor.descPlaceholder")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",c("recipeEditor.markdown")]}),e.jsx("div",{className:"border border-slate-200 rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ks,{value:((y=t.content)==null?void 0:y.markdown)||"",onChange:m=>s({...t,content:{...t.content,markdown:m}}),language:"markdown",height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(Ht,{size:11,className:"text-emerald-500"})," ",c("recipeEditor.code")]}),e.jsx("div",{className:"border border-slate-200 rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ks,{value:((k=t.content)==null?void 0:k.pattern)||"",onChange:m=>s({...t,content:{...t.content,pattern:m}}),language:g,height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1",children:c("recipeEditor.rationale")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-y",rows:3,value:((w=t.content)==null?void 0:w.rationale)||"",onChange:m=>s({...t,content:{...t.content,rationale:m.target.value}}),placeholder:c("recipeEditor.rationalePlaceholder")})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-6 scrollbar-light",children:[(()=>{const m=[["trigger",t.trigger],["language",t.language],["category",t.category],["kind",t.kind],["knowledgeType",t.knowledgeType],["status",t.status],["complexity",t.complexity],["scope",t.scope],["source",t.source],["updatedAt",t.updatedAt?h(t.updatedAt):void 0]].filter(([,N])=>!!N);return m.length===0?null:e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-4",children:"Recipe Metadata"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-y-4 gap-x-8",children:m.map(([N,j])=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold uppercase mb-1",children:N}),e.jsx("span",{className:"text-sm text-slate-700 break-all font-medium",children:j})]},N))})]})})(),t.description&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("recipeEditor.description")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:t.description})]}),((T=t.content)==null?void 0:T.markdown)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-blue-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",c("recipeEditor.markdown")]}),e.jsx("div",{className:"bg-blue-50/30 border border-blue-100 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 leading-relaxed",children:e.jsx(gt,{content:t.content.markdown})})})]}),((A=t.content)==null?void 0:A.pattern)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-emerald-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(Ht,{size:11,className:"text-emerald-500"})," ",c("recipeEditor.code")]}),e.jsx(ct,{code:t.content.pattern,language:g,showLineNumbers:!0})]}),((G=t.content)==null?void 0:G.rationale)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("recipeEditor.rationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:t.content.rationale})})]}),((_=t.content)==null?void 0:_.steps)&&t.content.steps.length>0&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("recipeEditor.steps")}),e.jsx("div",{className:"space-y-2",children:t.content.steps.map((m,N)=>typeof m=="string"?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:N+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:m})]},N):e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:N+1}),m.title&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:m.title})]}),m.description&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:m.description}),m.code&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:m.code})]},N))})]}),((E=t.content)==null?void 0:E.codeChanges)&&t.content.codeChanges.length>0&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("recipeEditor.codeChanges")}),e.jsx("div",{className:"space-y-2",children:t.content.codeChanges.map((m,N)=>e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-slate-50 border-b border-slate-200 flex items-center gap-2",children:[e.jsx(ht,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-slate-600",children:m.file})]}),m.explanation&&e.jsx("p",{className:"text-[11px] text-slate-500 px-3 py-1.5 border-b border-slate-100 bg-yellow-50/30",children:m.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/20 border-b border-slate-100",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:"Before"}),e.jsx("pre",{className:"text-[11px] text-slate-600 whitespace-pre-wrap break-words font-mono",children:m.before||c("recipes.emptyValue")})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/20",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:"After"}),e.jsx("pre",{className:"text-[11px] text-slate-700 whitespace-pre-wrap break-words font-mono",children:m.after})]})]},N))})]}),((Z=t.content)==null?void 0:Z.verification)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-teal-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("recipeEditor.validation")}),e.jsxs("div",{className:"bg-teal-50/50 border border-teal-100 rounded-xl p-4 space-y-1.5",children:[t.content.verification.method&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:c("recipeEditor.validationMethod")})," ",t.content.verification.method]}),t.content.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:c("recipeEditor.validationExpected")})," ",t.content.verification.expectedResult]}),t.content.verification.testCode&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md overflow-x-auto whitespace-pre-wrap mt-1",children:t.content.verification.testCode})]})]}),t.tags&&t.tags.length>0&&e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-3 flex items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-blue-400"})," ",c("recipeEditor.tags")]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map((m,N)=>e.jsx("span",{className:"px-2.5 py-1 bg-blue-50 text-blue-700 border border-blue-100 rounded-full text-xs font-medium",children:m},N))})]}),!!(t.constraints&&((X=t.constraints.guards)!=null&&X.length||(H=t.constraints.boundaries)!=null&&H.length||(q=t.constraints.preconditions)!=null&&q.length||(I=t.constraints.sideEffects)!=null&&I.length))&&e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6 space-y-4",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest flex items-center gap-1.5",children:[e.jsx(dt,{size:11,className:"text-amber-500"})," ",c("recipeEditor.constraints")]}),t.constraints.guards&&t.constraints.guards.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:c("recipeEditor.guardRules")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.guards.map((m,N)=>e.jsxs("li",{className:"flex gap-2 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${m.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-xs bg-slate-100 px-1.5 py-0.5 rounded",children:m.pattern}),m.message&&e.jsxs("span",{className:"text-xs text-slate-400",children:["— ",m.message]})]},N))})]}),t.constraints.boundaries&&t.constraints.boundaries.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:c("recipeEditor.boundaryConstraints")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.boundaries.map((m,N)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),m]},N))})]}),t.constraints.preconditions&&t.constraints.preconditions.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:c("recipeEditor.preconditions")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.preconditions.map((m,N)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),m]},N))})]}),t.constraints.sideEffects&&t.constraints.sideEffects.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:c("recipeEditor.sideEffects")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.sideEffects.map((m,N)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),m]},N))})]})]}),t.relations&&Object.entries(t.relations).some(([,m])=>Array.isArray(m)&&m.length>0)&&e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-4",children:c("recipeEditor.relations")}),e.jsx("div",{className:"space-y-2",children:[{key:"inherits",label:c("recipeEditor.relationTypes.inherits"),color:"text-green-600",icon:"↑"},{key:"implements",label:c("recipeEditor.relationTypes.implements"),color:"text-blue-600",icon:"◇"},{key:"calls",label:c("recipeEditor.relationTypes.calls"),color:"text-cyan-600",icon:"→"},{key:"dependsOn",label:c("recipeEditor.relationTypes.dependsOn"),color:"text-yellow-600",icon:"⊕"},{key:"dataFlow",label:c("recipeEditor.relationTypes.dataFlow"),color:"text-purple-600",icon:"⇢"},{key:"conflicts",label:c("recipeEditor.relationTypes.conflicts"),color:"text-red-600",icon:"✕"},{key:"extends",label:c("recipeEditor.relationTypes.extends"),color:"text-teal-600",icon:"⊃"},{key:"related",label:c("recipeEditor.relationTypes.associates"),color:"text-slate-500",icon:"∼"}].map(({key:m,label:N,color:j,icon:W})=>{var ye;const O=(ye=t.relations)==null?void 0:ye[m];return!O||!Array.isArray(O)||O.length===0?null:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:`text-xs font-mono ${j} shrink-0 whitespace-nowrap pt-0.5`,children:[W," ",N]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:O.map((Ne,je)=>e.jsx("span",{className:"px-2 py-0.5 bg-white border border-slate-200 text-slate-600 rounded-lg text-xs font-mono",children:typeof Ne=="string"?Ne:Ne.id||Ne.title||JSON.stringify(Ne)},je))})]},m)})})]}),!((L=t.content)!=null&&L.markdown)&&!(($=t.content)!=null&&$.pattern)&&!t.description&&e.jsx("div",{className:"bg-white p-8 rounded-2xl border border-slate-100 shadow-sm min-h-[200px] flex items-center justify-center",children:e.jsx("div",{className:"text-slate-300 italic",children:c("recipeEditor.noContent")})})]})})}),e.jsxs("div",{className:"p-6 border-t border-slate-100 flex justify-end gap-3",children:[e.jsx("button",{onClick:l,disabled:d,className:"px-4 py-2 text-slate-600 font-medium disabled:opacity-50",children:c("recipeEditor.cancel")}),e.jsxs("button",{onClick:a,disabled:d,className:"px-6 py-2 bg-blue-600 text-white rounded-lg font-medium flex items-center gap-2 hover:bg-blue-700 disabled:opacity-60 disabled:cursor-not-allowed",children:[d?e.jsx(Me,{size:z.lg,className:"animate-spin"}):e.jsx(Ss,{size:z.lg}),c(d?"recipeEditor.saving":"recipeEditor.saveChanges")]})]})]})]})},no=({setShowCreateModal:t,createPath:s,setCreatePath:a,handleCreateFromPath:l,handleCreateFromClipboard:d,isExtracting:c})=>{const{t:u}=_e(),{isDark:p}=St();return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-slate-900/50 backdrop-blur-sm"}),e.jsxs("div",{className:`relative w-full max-w-lg rounded-2xl shadow-2xl overflow-hidden ${p?"bg-[#1e1e1e]":"bg-white"}`,children:[e.jsxs("div",{className:`p-6 border-b flex justify-between items-center ${p?"bg-[#252526] border-[#3e3e42]":"bg-slate-50 border-slate-100"}`,children:[e.jsxs("h2",{className:`text-xl font-bold flex items-center gap-2 ${p?"text-white":"text-slate-800"}`,children:[e.jsx(Nt,{size:z.xl,className:"text-blue-600"})," ",u("createModal.title")]}),e.jsx("button",{onClick:()=>t(!1),className:`p-2 rounded-full transition-all duration-150 ${p?"text-slate-400 hover:bg-[#3e3e42] hover:text-slate-200":"text-slate-500 hover:bg-white hover:text-slate-700"}`,children:e.jsx(Xe,{size:z.lg})})]}),e.jsxs("div",{className:"p-8 space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-widest ${p?"text-slate-500":"text-slate-400"}`,children:[e.jsx(Ma,{size:z.sm})," ",u("createModal.importFromPath")]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`flex-1 p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 border ${p?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"bg-slate-100 border-slate-200 text-slate-900"}`,placeholder:u("createModal.pathPlaceholder"),value:s,onChange:n=>a(n.target.value)}),e.jsx("button",{onClick:l,disabled:!s||c,className:`px-4 py-2 rounded-xl text-sm font-bold disabled:opacity-50 transition-all duration-150 ${p?"bg-slate-200 text-slate-900 hover:bg-white":"bg-slate-900 text-white hover:bg-slate-800"}`,children:u("createModal.scanFile")})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:`w-full border-t ${p?"border-[#3e3e42]":"border-slate-100"}`})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:`px-2 font-bold ${p?"bg-[#1e1e1e] text-slate-500":"bg-white text-slate-300"}`,children:u("createModal.or")})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:`flex items-center gap-2 text-xs font-bold uppercase tracking-widest ${p?"text-slate-500":"text-slate-400"}`,children:[e.jsx(_l,{size:z.sm})," ",u("createModal.importFromClipboard")]}),e.jsxs("button",{onClick:()=>d(),disabled:c,className:`w-full flex items-center justify-center gap-3 p-4 rounded-xl font-bold transition-all duration-150 border ${p?"bg-blue-500/10 text-blue-300 border-blue-500/20 hover:bg-blue-500/20 hover:border-blue-400/30":"bg-blue-50 text-blue-700 border-blue-100 hover:bg-blue-100"}`,children:[e.jsx(et,{size:z.lg})," ",u("createModal.useClipboard")]})]})]}),c&&e.jsxs("div",{className:"bg-blue-600 text-white p-4 flex items-center justify-center gap-3 animate-pulse",children:[e.jsx(ns,{size:z.lg,className:"animate-spin"}),e.jsx("span",{className:"font-bold text-sm",children:u("createModal.aiThinking")})]})]})]})};function oo(t){if(!t)return"";if(typeof t=="object"){const d=t.code||t.pattern||t.markdown||t.snippet||t.body||"";if(d)return d}const a=(typeof t=="string"?t:JSON.stringify(t)).replace(/^---[\s\S]*?---\s*\n?/,"").trim(),l=a.match(/```[\w]*\n([\s\S]*?)```/);return l&&l[1]?l[1].trim():a.slice(0,8e3)}const io=({searchQ:t,insertPath:s,onClose:a})=>{const{t:l}=_e(),[d,c]=o.useState([]),[u,p]=o.useState(!0),[n,g]=o.useState(null),f=o.useRef(!0),h=o.useRef(null);o.useEffect(()=>(f.current=!0,h.current=new AbortController,ae.search(t||"",{mode:"bm25",type:"recipe",signal:h.current.signal}).then(i=>{f.current&&c((i.items||[]).map(y=>({name:(y.title||y.name||"")+".md",path:"",content:y.content,qualityScore:(y.quality||{}).overall||y.qualityScore||0,recommendReason:""})))}).catch(i=>{i.name!=="AbortError"&&f.current&&c([])}).finally(()=>{f.current&&p(!1)}),()=>{f.current=!1,h.current&&h.current.abort()}),[t]);const x=async i=>{g(i.name);try{const y=oo(i.content);await ae.insertAtSearchMark({path:s,content:y}),f.current&&(alert(l("searchModal.insertSuccess")+" "+s),a())}catch{f.current&&alert(l("searchModal.insertFailed"))}finally{f.current&&g(null)}};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-slate-900/50 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-slate-800",children:[e.jsx(ft,{size:z.xl,className:"text-blue-600"})," ",l("searchModal.title")]}),e.jsx("button",{onClick:a,className:"p-2 hover:bg-white rounded-full transition-colors",children:e.jsx(Xe,{size:z.lg})})]}),e.jsxs("div",{className:"p-4 text-sm text-slate-500 border-b border-slate-100",children:[l("searchModal.keyword")," ",t||l("searchModal.keywordAll")," · ",l("searchModal.insertTo")," ",s]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:u?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):d.length===0?e.jsx("div",{className:"text-slate-500 text-center py-8",children:l("searchModal.noResults")}):e.jsx("ul",{className:"space-y-2",children:d.map(i=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>x(i),disabled:n!==null,className:"w-full flex items-center justify-between gap-3 p-4 rounded-xl border border-slate-200 hover:border-blue-300 hover:bg-blue-50/50 transition-all text-left disabled:opacity-50",children:[e.jsxs("div",{className:"flex-1 flex flex-col gap-1",children:[e.jsx("span",{className:"font-medium text-slate-800 truncate",children:i.name}),(i.qualityScore!==void 0||i.recommendReason)&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.qualityScore!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 rounded text-xs text-blue-700 font-medium",children:["🤖 ",l("searchModal.quality")," ",(i.qualityScore*100).toFixed(0),"%"]}),i.recommendReason&&e.jsx("span",{className:"text-xs text-slate-600 italic truncate max-w-xs",children:i.recommendReason})]})]}),n===i.name?e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⏳"})," ",l("searchModal.inserting")]}):e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx(Fa,{size:z.md})," ",l("searchModal.insertBtn")]})]})},i.name))})})]})]})},Ps=[{id:"google",labelKey:"llmConfig.providers.gemini",defaultModel:"gemini-2.0-flash",keyEnv:"ASD_GOOGLE_API_KEY"},{id:"openai",labelKey:"llmConfig.providers.openai",defaultModel:"gpt-4o",keyEnv:"ASD_OPENAI_API_KEY"},{id:"deepseek",labelKey:"llmConfig.providers.deepseek",defaultModel:"deepseek-chat",keyEnv:"ASD_DEEPSEEK_API_KEY"},{id:"claude",labelKey:"llmConfig.providers.claude",defaultModel:"claude-3-5-sonnet-20240620",keyEnv:"ASD_CLAUDE_API_KEY"},{id:"ollama",labelKey:"llmConfig.providers.ollama",defaultModel:"llama3",keyEnv:""}],co=({onClose:t,onSaved:s})=>{const{t:a}=_e(),{isDark:l}=St(),[d,c]=o.useState(!0),[u,p]=o.useState(!1),[n,g]=o.useState(!1),[f,h]=o.useState("google"),[x,i]=o.useState("gemini-2.0-flash"),[y,k]=o.useState(""),[w,T]=o.useState(""),[A,G]=o.useState(!1),[_,E]=o.useState({}),[Z,X]=o.useState(!1);o.useEffect(()=>{H()},[]);const H=async()=>{c(!0);try{const j=await ae.getLlmEnvConfig();g(j.hasEnvFile);const W=j.vars||{};W.ASD_AI_PROVIDER&&h(W.ASD_AI_PROVIDER),W.ASD_AI_MODEL&&i(W.ASD_AI_MODEL),W.ASD_AI_PROXY&&T(W.ASD_AI_PROXY),E(W)}catch{}finally{c(!1)}},q=Ps.find(j=>j.id===f),I=(q==null?void 0:q.keyEnv)||"",L=I?!!_[I]:!0,$=j=>{h(j);const W=Ps.find(O=>O.id===j);W&&i(W.defaultModel),k("")},m=async()=>{if(f){if(I&&!L&&!y.trim()){alert(a("llmConfig.apiKeyRequired"));return}p(!0),X(!1);try{await ae.saveLlmEnvConfig({provider:f,model:x||void 0,apiKey:y.trim()||void 0,proxy:w.trim()||void 0}),X(!0),setTimeout(()=>{s(),t()},800)}catch(j){alert((j==null?void 0:j.message)||a("llmConfig.saveFailed"))}finally{p(!1)}}},N=j=>!j||j.length<10?j?"••••••":"":`${j.slice(0,6)}••••${j.slice(-4)}`;return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50",onClick:t,children:e.jsxs("div",{className:`rounded-2xl shadow-2xl w-full max-w-lg mx-4 overflow-hidden ${l?"bg-[#1e1e1e]":"bg-white"}`,onClick:j=>j.stopPropagation(),children:[e.jsxs("div",{className:`flex items-center justify-between px-6 py-4 border-b ${l?"border-[#3e3e42]":"border-slate-100"}`,children:[e.jsx("h2",{className:`text-lg font-semibold ${l?"text-white":"text-slate-800"}`,children:a("llmConfig.title")}),e.jsx("button",{onClick:t,className:`p-1 rounded-lg transition-all duration-150 ${l?"hover:bg-[#3e3e42] text-slate-400 hover:text-slate-200":"hover:bg-slate-100 text-slate-400"}`,children:e.jsx(Xe,{size:z.md})})]}),e.jsx("div",{className:"px-6 py-5 space-y-5",children:d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Me,{size:24,className:"animate-spin text-blue-500"})}):e.jsxs(e.Fragment,{children:[!n&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-700",children:[e.jsx(Rt,{size:16,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:a("llmConfig.envWarning")})]}),e.jsxs("div",{children:[e.jsx("label",{className:`block text-sm font-medium mb-2 ${l?"text-slate-300":"text-slate-700"}`,children:a("llmConfig.provider")}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:Ps.map(j=>e.jsx("button",{type:"button",onClick:()=>$(j.id),className:`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${f===j.id?l?"bg-blue-500/20 border-blue-500/40 text-blue-300 ring-1 ring-blue-500/30":"bg-blue-50 border-blue-300 text-blue-700 ring-1 ring-blue-200":l?"bg-[#2a2d35] border-[#3e3e42] text-slate-300 hover:border-slate-500 hover:bg-[#333842]":"bg-white border-slate-200 text-slate-600 hover:border-slate-300 hover:bg-slate-50"}`,children:a(j.labelKey)},j.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:`block text-sm font-medium mb-1.5 ${l?"text-slate-300":"text-slate-700"}`,children:a("llmConfig.model")}),e.jsx("input",{type:"text",value:x,onChange:j=>i(j.target.value),placeholder:(q==null?void 0:q.defaultModel)||"",className:`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 ${l?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"border-slate-200"}`})]}),I&&e.jsxs("div",{children:[e.jsxs("label",{className:`block text-sm font-medium mb-1.5 ${l?"text-slate-300":"text-slate-700"}`,children:[a("llmConfig.apiKey"),L&&e.jsxs("span",{className:"ml-2 text-xs text-green-600 font-normal",children:["(",a("llmConfig.configured")," ",N(_[I]),")"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:A?"text":"password",value:y,onChange:j=>k(j.target.value),placeholder:a(L?"llmConfig.apiKeyPlaceholderSet":"llmConfig.apiKeyPlaceholderEmpty"),className:`w-full px-3 py-2 pr-10 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 ${l?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"border-slate-200"}`}),e.jsx("button",{type:"button",onClick:()=>G(j=>!j),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-slate-400 hover:text-slate-600",children:A?e.jsx($l,{size:16}):e.jsx(os,{size:16})})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:`block text-sm font-medium mb-1.5 ${l?"text-slate-300":"text-slate-700"}`,children:[a("llmConfig.proxy")," ",e.jsx("span",{className:`text-xs font-normal ${l?"text-slate-500":"text-slate-400"}`,children:a("llmConfig.optional")})]}),e.jsx("input",{type:"text",value:w,onChange:j=>T(j.target.value),placeholder:"http://127.0.0.1:7890",className:`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 ${l?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"border-slate-200"}`})]})]})}),e.jsxs("div",{className:`flex items-center justify-end gap-3 px-6 py-4 border-t ${l?"border-[#3e3e42] bg-[#252526]":"border-slate-100 bg-slate-50/50"}`,children:[e.jsx("button",{onClick:t,className:`px-4 py-2 text-sm font-medium transition-colors ${l?"text-slate-400 hover:text-slate-200":"text-slate-600 hover:text-slate-800"}`,children:a("llmConfig.cancel")}),e.jsxs("button",{onClick:m,disabled:u||d||Z,className:`flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-medium transition-all ${Z?"bg-green-500 text-white":"bg-blue-600 text-white hover:bg-blue-700 shadow-sm"} disabled:opacity-60`,children:[u?e.jsx(Me,{size:16,className:"animate-spin"}):Z?e.jsx(cs,{size:16}):e.jsx(Ss,{size:16}),a(Z?"llmConfig.saved":"llmConfig.saveToEnv")]})]})]})})};class uo extends Ct.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}render(){var s;return this.state.hasError?e.jsxs("div",{style:{padding:40,textAlign:"center"},children:[e.jsx("h2",{style:{color:"#ef4444",marginBottom:12},children:zs.app.errorBoundary.title}),e.jsx("pre",{style:{fontSize:12,color:"#64748b",whiteSpace:"pre-wrap",maxWidth:600,margin:"0 auto"},children:(s=this.state.error)==null?void 0:s.message}),e.jsx("button",{onClick:()=>{this.setState({hasError:!1,error:null}),window.location.reload()},style:{marginTop:16,padding:"8px 20px",background:"#3b82f6",color:"#fff",border:"none",borderRadius:8,cursor:"pointer"},children:zs.app.errorBoundary.refreshBtn})]}):this.props.children}}function Qt(t,s="ai-scan"){return{title:t.title||"",description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:t.category||"",tags:t.tags||[],kind:t.kind||"",knowledgeType:t.knowledgeType||"",scope:t.scope||"",complexity:t.complexity||"",difficulty:t.difficulty||"",authority:t.authority,lifecycle:t.lifecycle||"pending",source:t.source||s,doClause:t.doClause||"",dontClause:t.dontClause||"",whenClause:t.whenClause||"",topicHint:t.topicHint||"",coreCode:t.coreCode||"",content:t.content||{},constraints:t.constraints||{},reasoning:t.reasoning||{},quality:t.quality||{},stats:t.stats||{},relations:t.relations||{},headers:t.headers||[],headerPaths:t.headerPaths,moduleName:t.moduleName,includeHeaders:t.includeHeaders,createdAt:t.createdAt,updatedAt:t.updatedAt}}const po=()=>{var $e,Je,st;const t=pr(),s=mr(($e=t.user)==null?void 0:$e.role),a=hr(),{t:l,lang:d}=_e(),c=()=>{const S=window.location.pathname.replace(/^\//,"").split("/")[0]||"";return sr.includes(S)?S:"help"},[u,p]=o.useState(null),[n,g]=o.useState(c()),[f,h]=o.useState(!1),[x,i]=o.useState(""),[y,k]=o.useState(!0),[w,T]=o.useState(null),[A,G]=o.useState([]),[_,E]=o.useState([]),[Z,X]=o.useState(null),[H,q]=o.useState(!1),[I,L]=o.useState({current:0,total:0,status:""}),[$,m]=o.useState([]),[N,j]=o.useState([]),[W,O]=o.useState(null),[ye,Ne]=o.useState(1),[je,v]=o.useState(12),[ee,te]=o.useState(!1),[de,ve]=o.useState(""),[fe,ie]=o.useState(!1),[be,B]=o.useState(null),[K,xe]=o.useState(null),[P,R]=o.useState(!1),[Q,ce]=o.useState(!0),[we,Ue]=o.useState(!1),[Se,ne]=o.useState(0),pe=o.useRef(null),Le=o.useRef(null);o.useEffect(()=>{Ne(1)},[x]),o.useEffect(()=>{if(u!=null&&u.projectRoot)try{const S=`asd:custom-folder-targets:${u.projectRoot}`,le=localStorage.getItem(S);E(le?JSON.parse(le):[])}catch{E([])}},[u==null?void 0:u.projectRoot]);const He=()=>{pe.current&&pe.current.abort()};o.useEffect(()=>{let S=!1;const le=async()=>{var me,Ae,Re;try{const Ee=await ae.getSignalStatus();if(!S){const Fe=((me=Ee==null?void 0:Ee.suggestions)==null?void 0:me.length)||0,Te=((Re=(Ae=Ee==null?void 0:Ee.snapshot)==null?void 0:Ae.lastResult)==null?void 0:Re.newSuggestions)||0;ne(Fe||Te)}}catch{}};le();const Y=setInterval(le,300*1e3);return()=>{S=!0,clearInterval(Y)}},[]);const De=o.useRef(null);o.useEffect(()=>{if(a.isAllDone&&a.session){if(De.current!==a.session.id){De.current=a.session.id;const S=a.session.failed>0?l("bootstrap.notifyPartial",{completed:a.session.completed,total:a.session.total,failed:a.session.failed}):l("bootstrap.notifySuccess",{completed:a.session.completed});re(S,{title:l("bootstrap.coldStartComplete"),type:a.session.failed>0?"error":"success"})}F()}},[a.isAllDone,(Je=a.session)==null?void 0:Je.id]),o.useEffect(()=>{if(a.candidateCreatedTick>0){const S=setTimeout(()=>F(),2e3);return()=>clearTimeout(S)}},[a.candidateCreatedTick]);const r=(S,le)=>{g(S);const Y=le!=null&&le.preserveSearch&&window.location.search?window.location.search:"";window.history.pushState({},document.title,`/${S}${Y}`)},C=S=>{T(S),g("recipes");const le=new URLSearchParams(window.location.search);le.set("edit",encodeURIComponent(S.name)),window.history.pushState({},document.title,`/recipes?${le.toString()}`)},b=()=>{T(null),window.history.replaceState({},document.title,"/recipes")};o.useEffect(()=>{x===""&&B(null)},[x]),o.useEffect(()=>{g(c())},[]),o.useEffect(()=>{if(!u)return;const S=window.location.pathname.replace(/^\//,"").split("/")[0],Y=new URLSearchParams(window.location.search).get("edit");if(S==="recipes"&&Y&&u.recipes)try{const me=decodeURIComponent(Y),Ae=u.recipes.find(Re=>Re.name===me);Ae&&!w&&(g("recipes"),C(Ae))}catch{}},[u]),o.useEffect(()=>{F(),M(),U();const S=()=>{g(c())};window.addEventListener("popstate",S);const le=new URLSearchParams(window.location.search),Y=le.get("action"),me=le.get("path"),Ae=le.get("q")||"";return Y==="search"&&me?xe({q:Ae,path:me}):Y==="create"&&me&&(ve(me),te(!0),le.get("autoScan")==="1"&&setTimeout(()=>he(me),500)),Y&&window.history.replaceState({},document.title,window.location.pathname),()=>{window.removeEventListener("popstate",S)}},[]);const F=async()=>{k(!0);try{const S=await ae.fetchData();p(S)}catch(S){re((S==null?void 0:S.message)||l("app.load.failed"),{title:l("app.load.failedTitle"),type:"error"})}finally{k(!1)}},M=async()=>{try{const S=await ae.fetchTargets();G(S)}catch(S){console.warn("删除候选残留失败:",S==null?void 0:S.message)}},U=async()=>{try{const S=await ae.getLlmEnvConfig();ce(S.llmReady)}catch{}},se=async()=>{try{const S=await ae.syncSnippets("all");re(l("app.sync.success"),{title:l("app.sync.successTitle")})}catch{re(l("app.sync.failedHint"),{title:l("app.sync.failed"),type:"error"})}},ue=async()=>{try{await ae.refreshProject(),M(),re(l("app.projectRefresh.success"),{title:l("app.projectRefresh.successTitle")})}catch{re(l("app.load.failedHint"),{title:l("app.projectRefresh.failed"),type:"error"})}},he=async S=>{var le;ie(!0);try{const Y=await ae.extractFromPath(S);j(Y.result.map(me=>({...Qt(me,"extract"),mode:"full",lang:"cn"}))),r("spm"),te(!1),F(),((le=Y.result)==null?void 0:le.length)>0&&re(l("app.extract.success"),{title:l("app.extract.successTitle")})}catch{re(l("app.extract.failed"),{type:"error"})}finally{ie(!1)}},D=async()=>{var S;if(de){ie(!0);try{const le=await ae.extractFromPath(de);j(le.result.map(Y=>({...Qt(Y,"extract"),mode:"full",lang:"cn"}))),r("spm"),te(!1),F(),((S=le.result)==null?void 0:S.length)>0?re(le.isMarked?l("app.extract.markerSuccess"):l("app.extract.normalSuccess"),{title:l("app.extract.successTitle")}):le.isMarked||re(l("app.extract.noMarker"),{title:l("app.extract.extracting"),type:"info"})}catch{re(l("app.extract.failed"),{type:"error"})}finally{ie(!1)}}},V=async S=>{var le,Y,me,Ae;try{const Re=await navigator.clipboard.readText();if(!Re)return re(l("app.clipboard.empty"),{title:l("app.clipboard.emptyTitle"),type:"info"});re(l("app.clipboard.analyzing"),{title:l("app.clipboard.analyzingTitle"),type:"info"}),ie(!0);const Ee=S||de;try{const Fe=await ae.extractFromText(Re,Ee||void 0),Te=Fe._multipleCount;j([{...Qt(Fe,"clipboard"),mode:"full",lang:"cn"}]),r("spm"),te(!1),F(),re(Te?l("app.clipboard.resultMulti",{count:Te}):l("app.extract.normalSuccess"),{title:l("app.clipboard.resultTitle")})}catch(Fe){const Te=((Y=(le=Fe.response)==null?void 0:le.data)==null?void 0:Y.aiError)===!0,Ke=((Ae=(me=Fe.response)==null?void 0:me.data)==null?void 0:Ae.error)||Fe.message;Te?re(Ke,{title:l("app.clipboard.aiFailed"),type:"error"}):re(Ke,{title:l("common.operationFailed"),type:"error"})}}catch{re(l("app.clipboard.permissionError"),{title:l("app.clipboard.permissionTitle"),type:"error"})}finally{ie(!1)}},ke={"scan:started":{percent:5,status:l("app.scan.events.initializing")},"scan:files-loaded":{percent:15,status:S=>l("app.scan.events.filesLoaded",{count:S.count||0})},"scan:reading":{percent:25,status:S=>l("app.scan.events.readingFiles",{count:S.count||0})},"scan:ai-extracting":{percent:40,status:l("app.scan.events.aiAnalyzing")},"scan:enriching":{percent:85,status:S=>l("app.scan.events.enriching",{count:S.recipeCount||0})},"scan:completed":{percent:95,status:l("app.scan.events.completing")}},Ce=async S=>{var Y;if(H)return;pe.current&&pe.current.abort(),Le.current&&(clearInterval(Le.current),Le.current=null);const le=new AbortController;pe.current=le,X(S.name),q(!0),j([]),O(null),m([]),L({current:0,total:100,status:l("app.scan.streamInit")});try{const me=await ae.scanTargetStream(S,Ee=>{const Fe=ke[Ee.type];if(Fe){const Te=typeof Fe.status=="function"?Fe.status(Ee):Fe.status;L({current:Fe.percent,total:100,status:Te})}Ee.type==="scan:files-loaded"&&Ee.files&&m(Ee.files),Ee.type==="scan:ai-extracting"&&(Le.current&&clearInterval(Le.current),Le.current=setInterval(()=>{L(Te=>({...Te,current:Math.min(Te.current+1,80)}))},3e3)),(Ee.type==="scan:enriching"||Ee.type==="scan:completed")&&Le.current&&(clearInterval(Le.current),Le.current=null)},le.signal);Le.current&&(clearInterval(Le.current),Le.current=null),L({current:100,total:100,status:l("app.scan.completed")});const Ae=me.recipes||[],Re=me.scannedFiles||[];if(Ae.length>0||Re.length>0){const Ee=typeof S=="string"?S:(S==null?void 0:S.name)||"unknown",Fe=Ae.map(Te=>({...Qt(Te,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:Ee,scanMode:"target"}));if(j(Fe),Re.length>0&&m(Re),F(),Ae.length>0)re(l("app.scan.targetSuccess",{count:Ae.length}),{title:l("app.scan.targetSuccessTitle")});else if(me.message){const Te=me.noAi;re(me.message,{title:l(Te?"app.scan.aiNotConfigured":"app.scan.noResults"),type:Te?"info":"error"})}else re(l("app.scan.noSnippets"),{title:l("app.scan.scanComplete"),type:"info"})}else re(l("app.scan.scanFailedHint"),{title:l("app.scan.scanFailed"),type:"error"})}catch(me){if(Le.current&&(clearInterval(Le.current),Le.current=null),me.name==="AbortError")return;const Ae=(Y=me.message)==null?void 0:Y.includes("timeout"),Re=Ae?l("app.scan.timeout"):me.message||l("app.scan.scanError");re(Re,{title:l(Ae?"app.scan.timeoutTitle":"app.scan.scanError"),type:"error"})}finally{pe.current===le&&(q(!1),L({current:0,total:0,status:""}),pe.current=null)}},Ie=async()=>{var le,Y,me,Ae,Re,Ee;if(H)return;pe.current&&pe.current.abort();const S=new AbortController;pe.current=S,r("candidates"),q(!0),j([]),O(null),m([]),L({current:0,total:100,status:l("app.coldStart.collecting")}),a.resetSession();try{const Fe=await ae.bootstrap(S.signal);L({current:100,total:100,status:l("app.coldStart.skeletonCreated")}),Fe.bootstrapSession&&a.initFromApiResponse(Fe.bootstrapSession),F();const Te=Fe.report||{},Ke=((le=Fe.targets)==null?void 0:le.length)||0,it=((Y=Te.totals)==null?void 0:Y.files)||0,At=((me=Te.totals)==null?void 0:me.graphEdges)||0,Kt=Fe.guardSummary,As=Kt?`, ${l("app.coldStart.guardSuffix",{count:Kt.totalViolations})}`:"";re(l("app.coldStart.skeletonDetail",{targets:Ke,files:it,deps:At})+As)}catch(Fe){if(ss.isCancel(Fe))return;const Ke=Fe.code==="ECONNABORTED"||((Ae=Fe.message)==null?void 0:Ae.includes("timeout"))?l("app.coldStart.timeout"):((Ee=(Re=Fe.response)==null?void 0:Re.data)==null?void 0:Ee.error)||Fe.message;re(Ke,{type:"error"})}finally{pe.current===S&&(q(!1),L({current:0,total:0,status:""}),pe.current=null)}},Be=async()=>{var Ae,Re,Ee,Fe;if(H)return;pe.current&&pe.current.abort();const S=new AbortController;pe.current=S,r("spm"),X("__project__"),q(!0),j([]),O(null),m([]),L({current:0,total:100,status:l("app.fullScan.collecting")});const le=[{status:l("app.fullScan.phase5"),percent:5},{status:l("app.fullScan.phase15"),percent:15},{status:l("app.fullScan.phase25"),percent:25},{status:l("app.fullScan.phase35"),percent:35},{status:l("app.fullScan.phase45"),percent:45},{status:l("app.fullScan.phase55"),percent:55},{status:l("app.fullScan.phase65"),percent:65},{status:l("app.fullScan.phase75"),percent:75},{status:l("app.fullScan.phase85"),percent:85}];let Y=0;const me=setInterval(()=>{Y=Math.min(Y+1,le.length);const Te=le[Y-1];Te&&L(Ke=>({...Ke,current:Te.percent,status:Te.status}))},15e3);try{const Te=await ae.scanProject(S.signal);clearInterval(me),L({current:100,total:100,status:Te.partial?l("app.fullScan.partialComplete"):l("app.fullScan.completed")});const Ke=Te.recipes||[],it=Te.scannedFiles||[];if(Ke.length>0||it.length>0){const At=Ke.map(tl=>({...Qt(tl,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:"__project__",scanMode:"project"}));j(At),m(it),O(Te.guardAudit||null),F();const Kt=(Ae=Te.guardAudit)==null?void 0:Ae.summary,As=Kt?`, ${l("app.fullScan.guardSuffix",{count:Kt.totalViolations})}`:"",el=Te.partial?l("app.fullScan.timeoutSuffix"):"";re(l("app.fullScan.resultDetail",{count:Ke.length})+As+el)}else re(l("app.fullScan.noContent"))}catch(Te){if(clearInterval(me),ss.isCancel(Te))return;const it=Te.code==="ECONNABORTED"||((Re=Te.message)==null?void 0:Re.includes("timeout"))?l("app.fullScan.timeout"):((Fe=(Ee=Te.response)==null?void 0:Ee.data)==null?void 0:Fe.error)||Te.message;re(it,{type:"error"})}finally{pe.current===S&&(q(!1),L({current:0,total:0,status:""}),pe.current=null)}},Ye=(S,le)=>{const Y=[...N],me={...Y[S],...le};Y[S]=me,j(Y)},J=async S=>{var le;if(!P){R(!0);try{const Y=(((le=S.content)==null?void 0:le.pattern)||"").trim(),me=(()=>{if(!Y)return!1;const Ke=Y.split(`
130
+ `).filter(At=>At.trim());return Ke.filter(At=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(At)).length<=Ke.length*.3})(),Ae=(S.trigger||"").split(/[,,\s]+/).map(Ke=>Ke.trim()).filter(Boolean);if(me&&Ae.length===0){re(l("app.recipe.triggerRequired"),{type:"error"}),R(!1);return}const Re={title:S.title||"Untitled",description:S.description||"",trigger:Ae.join(", ")||"",language:S.language||"",category:S.category||"Utility",kind:S.kind||"pattern",knowledgeType:S.knowledgeType||"code-pattern",complexity:S.complexity||"intermediate",scope:S.scope||null,difficulty:S.difficulty||"",tags:S.tags||[],source:S.source||"ai-scan",sourceFile:S.sourceFile||"",moduleName:S.moduleName||"",doClause:S.doClause||"",dontClause:S.dontClause||"",whenClause:S.whenClause||"",topicHint:S.topicHint||"",coreCode:S.coreCode||"",content:S.content||{},reasoning:S.reasoning||{},quality:S.quality||{},constraints:S.constraints||{},relations:S.relations||{},stats:S.stats||{},headers:S.headers||[],headerPaths:S.headerPaths||[],includeHeaders:S.includeHeaders||!1},Ee=await ae.knowledgeCreate(Re);if(Ee!=null&&Ee.id)try{await ae.knowledgeLifecycle(Ee.id,"publish")}catch(Ke){console.warn("auto-publish after save failed:",Ke)}re(l(me?"app.recipe.savedAsRecipe":"app.recipe.savedToKb")),j(Ke=>Ke.filter(it=>it.title!==S.title));const Fe=S.candidateTargetName,Te=S.candidateId;if(Fe&&Te)try{await ae.deleteCandidate(Te)}catch{}F()}catch(Y){const me=aa(Y)??vs(Y);re(me??l("app.recipe.saveFailed"),{type:"error"})}finally{R(!1)}}},Pe=async()=>{var S,le;if(!(!w||P)){R(!0);try{const Y=w.id||((S=w.name)==null?void 0:S.replace(/\.md$/,"")),me=typeof w.content=="string"?{pattern:w.content,markdown:"",rationale:"",steps:[],codeChanges:[],verification:null}:w.content||{};await ae.knowledgeUpdate(Y,{title:((le=w.name)==null?void 0:le.replace(/\.md$/,""))||"",description:w.description||"",content:me,tags:w.tags||[],kind:w.kind,language:w.language,category:w.category}),b(),F()}catch(Y){const me=aa(Y)??vs(Y);re(me??l("app.recipe.saveRecipeFailed"),{type:"error"})}finally{R(!1)}}},qe=async S=>{if(window.confirm(l("common.areYouSure")))try{await ae.deleteRecipe(S),F()}catch(le){const Y=vs(le);re(Y??l("common.deleteFailed"),{type:"error"})}},ze=async(S,le)=>{try{await ae.deleteCandidate(le),j(Y=>Y.filter(me=>!(me.candidateId===le&&me.candidateTargetName===S))),p(Y=>{if(!(Y!=null&&Y.candidates))return Y;const me={...Y.candidates};if(me[S]){const Ae=me[S].items.filter(Re=>Re.id!==le);Ae.length===0?delete me[S]:me[S]={...me[S],items:Ae}}return{...Y,candidates:me}})}catch{re(l("common.operationFailed"),{type:"error"})}},Ve=async S=>{if(window.confirm(l("app.candidate.clearConfirm",{name:S})))try{await ae.deleteAllCandidatesInTarget(S),F(),re(l("app.candidate.clearDone",{name:S}))}catch{re(l("common.operationFailed"),{type:"error"})}},ge=async(S,le)=>{var Y,me;try{await ae.promoteToCandidate(S,S.candidateTargetName||Z||"_review"),re(l("app.candidate.pushSuccess")),j(Ae=>Ae.filter((Re,Ee)=>Ee!==le)),F()}catch(Ae){const Re=(me=(Y=Ae.response)==null?void 0:Y.data)==null?void 0:me.error,Ee=typeof Re=="string"?Re:(Re==null?void 0:Re.message)||l("app.candidate.pushFailed");re(Ee,{type:"error"})}},Oe=((u==null?void 0:u.recipes)||[]).filter(S=>{var Ae,Re;if(be)return be.some(Ee=>Ee.metadata.type==="recipe"&&Ee.metadata.name===S.name);const le=S.name||"",Y=typeof S.content=="string"?S.content:[(Ae=S.content)==null?void 0:Ae.pattern,(Re=S.content)==null?void 0:Re.markdown].filter(Boolean).join(" ");return le.toLowerCase().includes(x.toLowerCase())||Y.toLowerCase().includes(x.toLowerCase())||(S.description||"").toLowerCase().includes(x.toLowerCase())}).sort((S,le)=>{var Ae,Re,Ee,Fe;if(be){const Te=((Ae=be.find(it=>it.metadata.name===S.name))==null?void 0:Ae.similarity)||0;return(((Re=be.find(it=>it.metadata.name===le.name))==null?void 0:Re.similarity)||0)-Te}const Y=((Ee=S.stats)==null?void 0:Ee.authorityScore)??0;return(((Fe=le.stats)==null?void 0:Fe.authorityScore)??0)-Y}),We=Ct.useMemo(()=>{const S=new Set(A.map(Y=>`${Y.discovererId||""}::${Y.name}`)),le=_.filter(Y=>!S.has(`${Y.discovererId||""}::${Y.name}`));return[...A,...le]},[A,_]),Ge=We.filter(S=>S.name.toLowerCase().includes(x.toLowerCase())).sort((S,le)=>{const Y=us(S.name),me=us(le.name);if(Y&&!me)return 1;if(!Y&&me)return-1;const Ae=S.isVirtual?1:0,Re=le.isVirtual?1:0;return Ae!==Re?Ae-Re:S.name.localeCompare(le.name)}),ut=o.useCallback(S=>{E(le=>{if(le.some(me=>me.path===S.path))return le;const Y=[...le,S];return u!=null&&u.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${u.projectRoot}`,JSON.stringify(Y)),Y})},[u==null?void 0:u.projectRoot]),Mt=o.useCallback(S=>{E(le=>{const Y=le.filter(me=>me.path!==S);return u!=null&&u.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${u.projectRoot}`,JSON.stringify(Y)),Y})},[u==null?void 0:u.projectRoot]),Ft=Object.values((u==null?void 0:u.candidates)||{}).reduce((S,le)=>S+le.items.length,0),{isDark:zt}=St();return e.jsx(uo,{children:e.jsx(Fr,{children:e.jsxs("div",{className:`flex h-screen ${zt?"bg-[#1e1e1e] text-slate-200":"bg-slate-50 text-slate-900"} overflow-hidden font-sans`,children:[e.jsx(rl,{position:"top-center",toastOptions:{duration:5e3,style:{background:"none",padding:0,boxShadow:"none",border:"none"}},containerStyle:{top:24}}),e.jsx(br,{activeTab:n,navigateToTab:r,candidateCount:Ft,signalSuggestionCount:Se,currentUser:s.user!=="anonymous"?s.user:void 0,currentRole:s.role,permissionMode:s.mode,onLogout:void 0,collapsed:f,onToggleCollapse:()=>h(S=>!S)}),e.jsxs("main",{className:"flex-1 flex flex-col overflow-hidden relative",children:[e.jsx(_r,{searchQuery:x,setSearchQuery:i,setShowCreateModal:te,handleSyncSnippets:se,aiConfig:u==null?void 0:u.aiConfig,llmReady:Q,onOpenLlmConfig:()=>Ue(!0),onBeforeAiSwitch:He,onAiConfigChange:F,onSemanticSearchResults:S=>{B(S),n!=="recipes"&&r("recipes")}}),e.jsx("div",{className:`flex-1 ${n==="wiki"?"overflow-hidden":"overflow-y-auto p-4 xl:p-6 2xl:p-8"}`,children:y?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):n==="recipes"?e.jsx(Ur,{recipes:Oe,openRecipeEdit:C,handleDeleteRecipe:qe,onRefresh:F,idTitleMap:u==null?void 0:u.idTitleMap,currentPage:ye,onPageChange:Ne,pageSize:je,onPageSizeChange:S=>{v(S),Ne(1)}}):n==="guard"?e.jsx(jn,{onRefresh:F}):n==="skills"?e.jsx($n,{onRefresh:F,signalSuggestionCount:Se,onSuggestionCountChange:ne}):n==="candidates"?e.jsxs(e.Fragment,{children:[a.session&&e.jsx("div",{className:"mb-4",children:e.jsx(Un,{session:a.session,isAllDone:a.isAllDone,reviewState:a.reviewState,onDismiss:()=>a.resetSession()})}),e.jsx(an,{data:u,isShellTarget:us,isSilentTarget:lr,isPendingTarget:rr,handleDeleteCandidate:ze,onEditRecipe:C,onColdStart:Ie,isScanning:H,isBootstrapping:((st=a.session)==null?void 0:st.status)==="running",onRefresh:F,onAuditCandidate:(S,le)=>{var Ae,Re;const Y=(((Ae=S.content)==null?void 0:Ae.pattern)||"").trim(),me=!!Y&&(()=>{const Ee=Y.split(`
131
+ `).filter(Te=>Te.trim());return Ee.filter(Te=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Te)).length<=Ee.length*.3})();j([{...S,mode:me?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:S.difficulty||S.complexity||"intermediate",authority:((Re=S.stats)==null?void 0:Re.authority)||3,candidateId:S.id,candidateTargetName:le}]),r("spm")},onAuditAllInTarget:(S,le)=>{j(S.map(Y=>{var Re,Ee;const me=(((Re=Y.content)==null?void 0:Re.pattern)||"").trim(),Ae=!!me&&(()=>{const Fe=me.split(`
132
+ `).filter(Ke=>Ke.trim());return Fe.filter(Ke=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Ke)).length<=Fe.length*.3})();return{...Y,mode:Ae?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:Y.difficulty||Y.complexity||"intermediate",authority:((Ee=Y.stats)==null?void 0:Ee.authority)||3,candidateId:Y.id,candidateTargetName:le}})),r("spm")},handleDeleteAllInTarget:Ve})]}):n==="knowledge"?e.jsx(_n,{onRefresh:ue,idTitleMap:u==null?void 0:u.idTitleMap}):n==="depgraph"?e.jsx(yn,{}):n==="knowledgegraph"?e.jsx(Ln,{}):n==="spm"?e.jsx(xn,{targets:We,filteredTargets:Ge,selectedTargetName:Z,isScanning:H,scanProgress:I,scanFileList:$,scanResults:N,guardAudit:W,handleScanTarget:Ce,handleScanProject:Be,handleUpdateScanResult:Ye,handleSaveExtracted:J,handlePromoteToCandidate:ge,handleDeleteCandidate:ze,onEditRecipe:C,isShellTarget:us,recipes:(u==null?void 0:u.recipes)??[],isSavingRecipe:P,handleRefreshProject:ue,onAddCustomFolder:ut,onRemoveCustomFolder:Mt}):n==="wiki"?e.jsx(ao,{}):n==="help"?e.jsx(Yr,{}):e.jsx(wn,{})}),w&&e.jsx(ro,{editingRecipe:w,setEditingRecipe:T,handleSaveRecipe:Pe,closeRecipeEdit:b,isSavingRecipe:P}),ee&&e.jsx(no,{setShowCreateModal:te,createPath:de,setCreatePath:ve,handleCreateFromPath:D,handleCreateFromClipboard:V,isExtracting:fe}),K&&e.jsx(io,{searchQ:K.q,insertPath:K.path,onClose:()=>{xe(null),window.history.replaceState({},document.title,window.location.pathname)}}),we&&e.jsx(co,{onClose:()=>Ue(!1),onSaved:()=>{U(),F()}})]}),e.jsx(xo,{})]})})})},xo=()=>{const{isOpen:t}=ds();return t?e.jsx(zr,{}):null};nl.createRoot(document.getElementById("root")).render(e.jsx(Ct.StrictMode,{children:e.jsx(Ul,{children:e.jsx(ql,{children:e.jsx(po,{})})})}));