app.js 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105
  1. let requirements = [];
  2. let currentSelectedIndex = null;
  3. let activeRuns = {};
  4. let statusInterval = null;
  5. let currentAvailablePlatforms = ['xhs', 'youtube', 'bili', 'x'];
  6. let currentPromptName = null;
  7. const modalPrompts = document.getElementById('prompts-modal');
  8. const elPromptList = document.getElementById('prompt-list');
  9. const elPromptTextarea = document.getElementById('prompt-textarea');
  10. const elSchemaTextarea = document.getElementById('schema-textarea');
  11. const elPromptStatus = document.getElementById('prompt-save-status');
  12. // DOM Elements
  13. const elReqSelector = document.getElementById('req-selector');
  14. const elStatsContainer = document.getElementById('stats-container');
  15. const elMainContent = document.getElementById('main-content');
  16. const elEmptyState = document.getElementById('empty-state');
  17. const elDetailView = document.getElementById('detail-view');
  18. const elStatusBanner = document.getElementById('status-banner');
  19. const elStatusText = document.getElementById('status-text');
  20. // Form logic
  21. const selectForcePhase = document.getElementById('select-force-phase');
  22. const groupPlatforms = document.getElementById('group-platforms');
  23. if (selectForcePhase && groupPlatforms) {
  24. selectForcePhase.addEventListener('change', (e) => {
  25. const val = e.target.value;
  26. if (val.startsWith('phase2') || val === 'phase3') {
  27. groupPlatforms.style.display = 'none';
  28. } else {
  29. groupPlatforms.style.display = 'block';
  30. }
  31. });
  32. }
  33. const jsonStrategy = document.getElementById('json-strategy');
  34. const jsonBlueprint = document.getElementById('json-blueprint');
  35. const jsonSource = document.getElementById('json-source');
  36. const jsonRaw = document.getElementById('json-raw');
  37. // Modals
  38. const modalRun = document.getElementById('run-modal');
  39. const modalLogs = document.getElementById('logs-modal');
  40. const terminalLogs = document.getElementById('terminal-logs');
  41. const PIPELINE_STEPS = [
  42. { id: 'research', label: '1.1 分布式爬取' },
  43. { id: 'source', label: '1.5 提取数据源' },
  44. { id: 'generate-case', label: '1.6 生成 case.json' },
  45. { id: 'workflow-extract', label: '1.6 提取' },
  46. { id: 'apply-grounding', label: '1.7 场景映射' },
  47. { id: 'process-cluster', label: '2.1.1 工序聚类' },
  48. { id: 'process-score', label: '2.1.2 工序打分' },
  49. { id: 'capability-extract', label: '2.2.1 能力提取' },
  50. { id: 'capability-enrich', label: '2.2.2 能力丰富化' },
  51. { id: 'strategy', label: '3.0 策略组装' }
  52. ];
  53. let chainStartNode = null;
  54. let chainEndNode = null;
  55. let currentPipelineStatus = {};
  56. // Initialize
  57. async function init() {
  58. await fetchRequirements();
  59. setupEventListeners();
  60. startStatusPolling();
  61. }
  62. // Fetch Data
  63. async function fetchRequirements() {
  64. try {
  65. const res = await fetch('/api/requirements');
  66. requirements = await res.json();
  67. requirements.sort((a, b) => b.index - a.index);
  68. renderTaskList(requirements);
  69. updateStats();
  70. } catch (e) {
  71. console.error("Failed to fetch requirements", e);
  72. elReqSelector.innerHTML = '<option value="">加载数据失败。请检查后端是否运行。</option>';
  73. }
  74. }
  75. function renderJSON(obj) {
  76. if (obj === null) return `<span class="json-null">null</span>`;
  77. if (typeof obj === 'number') return `<span class="json-number">${obj}</span>`;
  78. if (typeof obj === 'boolean') return `<span class="json-boolean">${obj}</span>`;
  79. if (typeof obj === 'string') {
  80. const escaped = obj.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  81. return `<span class="json-string">"${escaped}"</span>`;
  82. }
  83. if (Array.isArray(obj)) {
  84. if (obj.length === 0) return '[]';
  85. let html = '<div class="json-array">[<div class="json-children">';
  86. obj.forEach((val, i) => {
  87. html += `<div class="json-item">${renderJSON(val)}${i < obj.length - 1 ? ',' : ''}</div>`;
  88. });
  89. html += '</div>]</div>';
  90. return html;
  91. }
  92. if (typeof obj === 'object') {
  93. const keys = Object.keys(obj);
  94. if (keys.length === 0) return '{}';
  95. let html = '<div class="json-object">{<div class="json-children">';
  96. keys.forEach((k, i) => {
  97. html += `<div class="json-prop"><span class="json-key">"${k}"</span>: ${renderJSON(obj[k])}${i < keys.length - 1 ? ',' : ''}</div>`;
  98. });
  99. html += '</div>}</div>';
  100. return html;
  101. }
  102. return String(obj);
  103. }
  104. function renderDataOrRaw(dataObj, renderFunc) {
  105. if (!dataObj) return '<p style="color:var(--text-muted)">无可用数据</p>';
  106. let safeRaw = "";
  107. if (dataObj.error) {
  108. safeRaw = dataObj.raw_content ? dataObj.raw_content.replace(/</g, "&lt;").replace(/>/g, "&gt;") : "文件为空。";
  109. return `<div style="padding:1rem; background:rgba(239, 68, 68, 0.1); border:1px solid var(--danger); border-radius:8px;">
  110. <h3 style="color:var(--danger); margin-bottom:0.5rem">⚠️ JSON 解析失败</h3>
  111. <pre style="white-space: pre-wrap; font-family: monospace; font-size: 0.85rem; color: var(--text-muted); overflow-x: auto">${safeRaw}</pre>
  112. </div>`;
  113. } else {
  114. safeRaw = JSON.stringify(dataObj, null, 2).replace(/</g, "&lt;").replace(/>/g, "&gt;");
  115. }
  116. // Check global toggle state
  117. const isRaw = document.getElementById('global-json-toggle') && document.getElementById('global-json-toggle').checked;
  118. return `
  119. <div class="data-view-container">
  120. <div class="data-view-ui" style="${isRaw ? 'display:none;' : ''}">
  121. ${renderFunc(dataObj)}
  122. </div>
  123. <div class="data-view-raw" style="${isRaw ? '' : 'display:none;'}">
  124. <div style="padding:1rem; background:rgba(0, 0, 0, 0.05); border:1px solid rgba(0, 0, 0, 0.1); border-radius:8px;">
  125. <h3 style="color:var(--text-muted); margin-bottom:0.5rem">📝 JSON 原文</h3>
  126. <pre style="white-space: pre-wrap; font-family: monospace; font-size: 0.85rem; color: var(--text-muted); overflow-x: auto">${safeRaw}</pre>
  127. </div>
  128. </div>
  129. </div>`;
  130. }
  131. function renderRawCases(rawCasesObj) {
  132. if (!rawCasesObj || Object.keys(rawCasesObj).length === 0) return '无原始案例数据';
  133. const reqId = requirements[currentSelectedIndex]?.id || "001";
  134. // Build maps
  135. const sourceMap = {};
  136. const sourceData = rawCasesObj['source'];
  137. const sourceList = sourceData ? (Array.isArray(sourceData) ? sourceData : sourceData.sources) : null;
  138. if (sourceList) {
  139. sourceList.forEach(s => {
  140. const sId = s.case_id || (s._raw && s._raw.case_id);
  141. const sUrl = s.source_url || s.url;
  142. if (sId) sourceMap[sId] = s;
  143. if (sUrl) sourceMap[sUrl] = s;
  144. });
  145. }
  146. const detailMap = {};
  147. const detailMapByUrl = {};
  148. // Cache context for modal
  149. window._currentRawCasesContext = {
  150. rawCasesObj, sourceMap, detailMap, detailMapByUrl, reqId
  151. };
  152. let totalStatsHtml = '';
  153. const detailedCaseObj = rawCasesObj['case'] || rawCasesObj['case_detailed'];
  154. if (detailedCaseObj) {
  155. const cd = detailedCaseObj;
  156. let uniqueCases = new Set();
  157. let calcWorkflow = 0;
  158. let calcCapabilities = 0;
  159. if (cd.cases) {
  160. cd.cases.forEach(c => {
  161. const cId = c.case_id || (c._raw && c._raw.case_id);
  162. const cUrl = c.source_url || c.url;
  163. const uniqueKey = cId || cUrl || Math.random().toString();
  164. uniqueCases.add(uniqueKey);
  165. if (c.workflow) calcWorkflow++;
  166. if (c.capability && c.capability.length > 0) calcCapabilities++;
  167. if (cId) {
  168. if (c.workflow) detailMap[cId] = { ...detailMap[cId], workflow: c.workflow };
  169. if (c.capability) detailMap[cId] = { ...detailMap[cId], capability: c.capability };
  170. }
  171. if (cUrl) {
  172. if (c.workflow) detailMapByUrl[cUrl] = { ...detailMapByUrl[cUrl], workflow: c.workflow };
  173. if (c.capability) detailMapByUrl[cUrl] = { ...detailMapByUrl[cUrl], capability: c.capability };
  174. }
  175. });
  176. }
  177. const displayTotal = uniqueCases.size > 0 ? uniqueCases.size : (cd.total !== undefined ? cd.total : 0);
  178. const displayWorkflowSuccess = calcWorkflow > 0 ? calcWorkflow : (cd.workflow_success !== undefined && cd.workflow_success !== null ? cd.workflow_success : (cd.success !== undefined && cd.success !== null ? cd.success : 0));
  179. const displayCapabilitiesSuccess = calcCapabilities > 0 ? calcCapabilities : (cd.capabilities_success !== undefined && cd.capabilities_success !== null ? cd.capabilities_success : 0);
  180. if (cd.total !== undefined || uniqueCases.size > 0) {
  181. totalStatsHtml = `<div style="display:flex; gap:1rem; margin-bottom:1rem; padding:0.5rem 1rem; background:rgba(0, 0, 0, 0.03); border-radius:8px; align-items:center;">
  182. <div style="flex:1; text-align:center; display:flex; flex-direction:column; gap:2px;">
  183. <span style="font-size:1.3rem; color:var(--text-main); font-weight:bold; line-height:1;">${displayTotal}</span>
  184. <span style="color:var(--text-muted); font-size:0.75rem;">未被过滤的帖子总数</span>
  185. </div>
  186. <div style="flex:1; text-align:center; display:flex; flex-direction:column; gap:2px;">
  187. <span style="font-size:1.3rem; color:var(--success); font-weight:bold; line-height:1;">${displayWorkflowSuccess}</span>
  188. <span style="color:var(--text-muted); font-size:0.75rem;">工序提取成功数</span>
  189. </div>
  190. <div style="flex:1; text-align:center; display:flex; flex-direction:column; gap:2px;">
  191. <span style="font-size:1.3rem; color:var(--accent-primary); font-weight:bold; line-height:1;">${displayCapabilitiesSuccess}</span>
  192. <span style="color:var(--text-muted); font-size:0.75rem;">能力提取成功数</span>
  193. </div>
  194. </div>`;
  195. }
  196. }
  197. let filteredStatsHtml = '';
  198. if (rawCasesObj['filtered_cases']) {
  199. const fObj = rawCasesObj['filtered_cases'];
  200. let totalFiltered = 0;
  201. if (fObj.total !== undefined) totalFiltered = fObj.total;
  202. else if (fObj.cases) totalFiltered = fObj.cases.length;
  203. else if (fObj.sources) totalFiltered = fObj.sources.length;
  204. else if (fObj.by_reason) {
  205. Object.values(fObj.by_reason).forEach(r => {
  206. if (r.sources) totalFiltered += r.sources.length;
  207. else if (r.cases) totalFiltered += r.cases.length;
  208. });
  209. } else if (Array.isArray(fObj)) totalFiltered = fObj.length;
  210. filteredStatsHtml = `<div style="display:flex; gap:1rem; margin-bottom:1rem; padding:0.5rem 1rem; background:rgba(0, 0, 0, 0.03); border-radius:8px; align-items:center;">
  211. <div style="flex:1; text-align:center; display:flex; flex-direction:column; gap:2px;">
  212. <span style="font-size:1.3rem; color:var(--text-main); font-weight:bold; line-height:1;">${totalFiltered}</span>
  213. <span style="color:var(--text-muted); font-size:0.75rem;">被过滤的帖子数</span>
  214. </div>
  215. </div>`;
  216. }
  217. const allPlatforms = Object.keys(rawCasesObj).filter(p => p !== 'source' && p !== 'case_detailed' && p !== 'case' && p !== 'images');
  218. const channelPlatforms = allPlatforms.filter(p => p !== 'filtered_cases' && p !== 'source_ex');
  219. const hasFiltered = allPlatforms.includes('filtered_cases');
  220. const hasExternal = allPlatforms.includes('source_ex');
  221. let html = '';
  222. html += `<div class="sub-tabs">`;
  223. html += `<button class="sub-tab-btn active" onclick="selectSubTab('total')">TOTAL</button>`;
  224. if (hasFiltered) html += `<button class="sub-tab-btn" onclick="selectSubTab('filtered_cases')">FILTERED</button>`;
  225. if (hasExternal) html += `<button class="sub-tab-btn" onclick="selectSubTab('source_ex')">EXTERNAL</button>`;
  226. html += `<button class="sub-tab-btn" id="btn-upload-source-ex" style="background-color: var(--primary); margin-left: auto;">+ 上传 source_ex</button>`;
  227. html += `<input type="file" id="input-upload-source-ex" accept=".json" style="display:none;">`;
  228. html += `</div><div class="sub-tab-contents">`;
  229. const renderPaneContent = (pList, paneType) => {
  230. let paneHtml = '';
  231. if (paneType === 'total' && typeof totalStatsHtml !== 'undefined' && totalStatsHtml) {
  232. paneHtml += totalStatsHtml;
  233. } else if (paneType === 'filtered_cases' && typeof filteredStatsHtml !== 'undefined' && filteredStatsHtml) {
  234. paneHtml += filteredStatsHtml;
  235. }
  236. let totalCases = 0;
  237. let seenIds = new Set();
  238. let groupedHtml = {};
  239. const getGroupKey = (c, p) => (p === 'filtered_cases' && c.filter_reason) ? `🚫 过滤原因: ${c.filter_reason}` : 'default';
  240. let allCases = [];
  241. pList.forEach(p => {
  242. if (!rawCasesObj[p]) return;
  243. if (rawCasesObj[p].error) {
  244. const safeRaw = rawCasesObj[p].raw_content ? rawCasesObj[p].raw_content.replace(/</g, "&lt;").replace(/>/g, "&gt;") : "文件为空。";
  245. paneHtml += `<div style="padding:1rem; background:rgba(239, 68, 68, 0.1); border:1px solid var(--danger); border-radius:8px; margin-bottom:1rem;">
  246. <h3 style="color:var(--danger); margin-bottom:0.5rem">⚠️ ${p} JSON 解析失败</h3>
  247. <pre style="white-space: pre-wrap; font-family: monospace; font-size: 0.85rem; color: var(--text-muted); overflow-x: auto">${safeRaw}</pre>
  248. </div>`;
  249. return;
  250. }
  251. if (rawCasesObj[p].reason && p !== 'filtered_cases') {
  252. paneHtml += `<div style="padding:0.5rem 1rem; background:rgba(239, 68, 68, 0.1); border:1px solid var(--danger); border-radius:6px; margin-bottom:1rem; color:var(--danger); font-size:0.9rem;">🛑 ${p} 提示: ${rawCasesObj[p].reason}</div>`;
  253. }
  254. let cases = [];
  255. if (Array.isArray(rawCasesObj[p])) {
  256. cases = rawCasesObj[p];
  257. } else if (rawCasesObj[p].cases) {
  258. cases = rawCasesObj[p].cases;
  259. } else if (rawCasesObj[p].sources) {
  260. cases = rawCasesObj[p].sources;
  261. } else if (rawCasesObj[p].by_reason) {
  262. Object.entries(rawCasesObj[p].by_reason).forEach(([reasonKey, reasonObj]) => {
  263. if (reasonObj.sources && Array.isArray(reasonObj.sources)) {
  264. reasonObj.sources.forEach(src => {
  265. if (!src.filter_reason) src.filter_reason = reasonKey;
  266. cases.push(src);
  267. });
  268. }
  269. });
  270. }
  271. if (cases.length > 0) {
  272. if (!rawCasesObj['source'] && p !== 'source_ex' && p !== 'filtered_cases' && p !== 'source') {
  273. paneHtml += `<div style="padding:1rem; background:rgba(0, 0, 0, 0.05); border:1px solid rgba(0, 0, 0, 0.1); border-radius:8px; margin-bottom:1rem;">
  274. <h3 style="color:var(--text-main); margin-bottom:0.5rem">📝 ${p} 原始爬取数据 (未进行 1.5 数据源提取)</h3>
  275. <div style="font-family: monospace; font-size: 0.85rem; overflow-x: auto">${renderJSON(rawCasesObj[p])}</div>
  276. </div>`;
  277. return;
  278. }
  279. cases.forEach((c, idx) => {
  280. allCases.push({ c: c, p: p, originalIdx: idx });
  281. });
  282. }
  283. });
  284. allCases.sort((aObj, bObj) => {
  285. const getScore = (item) => {
  286. const iId = item.case_id || (item._raw && item._raw.case_id) || (item.post && item.post.channel_content_id);
  287. const iUrl = item.source_url || item.url || (item.post && item.post.link);
  288. const mapped = sourceMap[iId] || sourceMap[iUrl] || (item._raw && sourceMap[item._raw.case_id]) || item;
  289. return mapped.evaluation && mapped.evaluation.quality ? (mapped.evaluation.quality.overall_score || 0) : 0;
  290. };
  291. return getScore(bObj.c) - getScore(aObj.c);
  292. });
  293. allCases.forEach(itemObj => {
  294. const c = itemObj.c;
  295. const p = itemObj.p;
  296. const idx = itemObj.originalIdx;
  297. totalCases++;
  298. const cId = c.case_id || (c._raw && c._raw.case_id) || (c.post && c.post.channel_content_id) || `temp_${p}_${idx}`;
  299. const cUrl = c.source_url || c.url || (c.post && c.post.link) || '';
  300. const groupKey = getGroupKey(c, p);
  301. if (!groupedHtml[groupKey]) groupedHtml[groupKey] = '';
  302. if (cId || cUrl || c.post) {
  303. const mappedS = sourceMap[cId] || sourceMap[cUrl] || (c._raw && sourceMap[c._raw.case_id]);
  304. if (p !== 'filtered_cases' && p !== 'source' && p !== 'source_ex' && !mappedS) return;
  305. if (cId && seenIds.has(cId)) return;
  306. if (cId) seenIds.add(cId);
  307. const s = mappedS || c;
  308. const post = s.post || s || {};
  309. const images = post.images || [];
  310. const xImages = post.image_url_list || [];
  311. const ytThumbnails = post.thumbnails && post.thumbnails.length > 0 ? [post.thumbnails[post.thumbnails.length - 1].url] : [];
  312. const allImages = [...images, ...xImages.map(img => img.image_url), ...ytThumbnails].filter(Boolean);
  313. const coverImgUrl = allImages.length > 0 ? `/output/${reqId}/raw_cases/images/${cId}/00.jpg` : '';
  314. const fallbackImgUrl = allImages.length > 0 ? allImages[0] : '';
  315. const title = post.title || c.title || post.desc || (post.body_text ? post.body_text.substring(0, 30) + '...' : '') || cId || '无标题';
  316. const author = post.channel_account_name || s.author || '-';
  317. const likes = post.like_count !== undefined ? post.like_count : (post.likes !== undefined ? post.likes : '-');
  318. const snippetStr = (post.body_text || post.body || '').substring(0, 100);
  319. const snippetHtml = snippetStr ? `<div class="masonry-card-snippet">${snippetStr.replace(/</g, "&lt;").replace(/>/g, "&gt;")}...</div>` : '';
  320. const platBadge = p.startsWith('case_') ? `<span class="tag" style="position:absolute; top:8px; left:8px; background:rgba(0,0,0,0.6); color:#fff; padding:2px 6px; border-radius:4px; font-size:0.7em; z-index:2; backdrop-filter: blur(4px); border: 1px solid rgba(255,255,255,0.2);">${p.replace('case_', '').toUpperCase()}</span>` : '';
  321. const score = s.evaluation && s.evaluation.quality ? s.evaluation.quality.overall_score : null;
  322. let scoreBadge = '';
  323. if (score !== null && score !== undefined) {
  324. let color = score >= 80 ? '#10b981' : (score >= 60 ? '#f59e0b' : '#ef4444');
  325. scoreBadge = `<div style="position:absolute; top:8px; right:8px; background:rgba(0,0,0,0.7); color:${color}; font-weight:bold; padding:2px 8px; border-radius:12px; font-size:0.8em; z-index:2; backdrop-filter: blur(4px); border: 1px solid rgba(255,255,255,0.2);">⭐️ ${score}</div>`;
  326. }
  327. let actionBtn = '';
  328. if (p === 'source_ex') {
  329. const isImported = !!sourceMap[cId] || !!sourceMap[cUrl];
  330. if (isImported) {
  331. actionBtn = `<button disabled style="position:absolute; top:8px; right:8px; background:#10b981; color:#fff; border:none; padding:4px 8px; border-radius:4px; font-size:0.7em; z-index:3; cursor:not-allowed; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">✅ 已导入</button>`;
  332. } else {
  333. actionBtn = `<button onclick="importExternalCase(event, '${cId}')" style="position:absolute; top:8px; right:8px; background:var(--accent-primary); color:#fff; border:none; padding:4px 8px; border-radius:4px; font-size:0.7em; z-index:3; cursor:pointer; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">📥 导入 Source</button>`;
  334. }
  335. }
  336. groupedHtml[groupKey] += `<div class="masonry-card" style="position:relative;" onclick="openCaseDetail('${p}', ${idx})">
  337. ${platBadge}
  338. ${scoreBadge}
  339. ${actionBtn}
  340. ${allImages.length > 0 ? `<img class="cover-img" src="${coverImgUrl}" onerror="this.onerror=null; this.src='${fallbackImgUrl}';">` : ''}
  341. <div class="masonry-card-info">
  342. <div class="masonry-card-title">${title}</div>
  343. ${allImages.length === 0 ? snippetHtml : ''}
  344. <div class="masonry-card-stats">
  345. <div class="masonry-card-author">👤 ${author}</div>
  346. <div class="masonry-card-likes">❤️ ${likes}</div>
  347. </div>
  348. </div>
  349. </div>`;
  350. } else {
  351. groupedHtml[groupKey] += `<div class="masonry-card" style="padding:12px; font-family:monospace; font-size:0.8em;" onclick="openCaseDetail('${p}', ${idx})">
  352. 📝 旧版格式 / 解析失败<br>点击查看详情
  353. </div>`;
  354. }
  355. });
  356. if (totalCases === 0 && pList.length > 0 && !paneHtml.includes('解析失败') && !paneHtml.includes('未进行')) {
  357. paneHtml += `<div style="padding:1rem; color:var(--text-muted); text-align:center;">暂无数据</div>`;
  358. } else {
  359. Object.entries(groupedHtml).forEach(([groupName, gHtml]) => {
  360. if (gHtml) {
  361. if (groupName !== 'default') {
  362. paneHtml += `<h3 style="margin-top: 1rem; margin-bottom: 0.5rem; font-size: 1.1rem; color: var(--text-main); border-left: 4px solid var(--accent-primary); padding-left: 8px;">${groupName}</h3>`;
  363. }
  364. paneHtml += `<div class="masonry-grid">${gHtml}</div>`;
  365. }
  366. });
  367. }
  368. return paneHtml;
  369. };
  370. html += `<div id="sub-tab-total" class="sub-tab-pane">${renderPaneContent([...channelPlatforms, 'source'], 'total')}</div>`;
  371. if (hasFiltered) html += `<div id="sub-tab-filtered_cases" class="sub-tab-pane hidden">${renderPaneContent(['filtered_cases'], 'filtered_cases')}</div>`;
  372. if (hasExternal) {
  373. html += `<div id="sub-tab-source_ex" class="sub-tab-pane hidden">`;
  374. html += `<div style="margin-bottom: 1rem; text-align: right;"><button onclick="importAllExternalCases()" class="btn btn-primary btn-small">📥 全部导入 Source</button></div>`;
  375. html += renderPaneContent(['source_ex'], 'source_ex');
  376. html += `</div>`;
  377. }
  378. html += `</div>`;
  379. return html;
  380. }
  381. window.importExternalCase = async function (e, caseId) {
  382. e.stopPropagation();
  383. if (!confirm('确定要将该外部数据导入到 source 吗?')) return;
  384. try {
  385. const res = await fetch(`/api/requirements/${currentSelectedIndex}/import_source_ex`, {
  386. method: 'POST',
  387. headers: { 'Content-Type': 'application/json' },
  388. body: JSON.stringify({ case_id: caseId })
  389. });
  390. const data = await res.json();
  391. if (data.status === 'success') {
  392. fetchRequirementData(currentSelectedIndex); // Refresh data
  393. } else {
  394. alert('导入失败: ' + (data.detail || data.message || JSON.stringify(data)));
  395. }
  396. } catch (err) {
  397. alert('导入出错: ' + err);
  398. }
  399. };
  400. window.importAllExternalCases = async function () {
  401. if (!confirm('确定要将所有外部数据全部导入到 source 吗?')) return;
  402. try {
  403. const res = await fetch(`/api/requirements/${currentSelectedIndex}/import_all_source_ex`, {
  404. method: 'POST'
  405. });
  406. const data = await res.json();
  407. if (data.status === 'success') {
  408. alert(`成功导入 ${data.count} 条数据!`);
  409. fetchRequirementData(currentSelectedIndex); // Refresh data
  410. } else {
  411. alert('全部导入失败: ' + (data.detail || data.message || JSON.stringify(data)));
  412. }
  413. } catch (err) {
  414. alert('导入出错: ' + err);
  415. }
  416. };
  417. function selectSubTab(tabName) {
  418. document.querySelectorAll('#json-raw .sub-tab-btn').forEach(btn => {
  419. btn.classList.remove('active');
  420. });
  421. const activeBtn = document.querySelector(`#json-raw .sub-tab-btn[data-target="sub-tab-${tabName}"]`);
  422. if (activeBtn) activeBtn.classList.add('active');
  423. document.querySelectorAll('#json-raw .sub-tab-pane').forEach(pane => {
  424. pane.classList.add('hidden');
  425. });
  426. document.getElementById(`sub-tab-${tabName}`).classList.remove('hidden');
  427. }
  428. window.deleteClusterItems = async function (indices) {
  429. if (currentSelectedIndex === null) return;
  430. const data = window.dataCache[currentSelectedIndex]?.cluster;
  431. if (!data) return;
  432. let newData = Array.isArray(data) ? [...data] : { ...data };
  433. let count = 0;
  434. // Sort indices descending to avoid shifting issues if it's an array
  435. indices.sort((a, b) => b - a);
  436. if (Array.isArray(newData)) {
  437. indices.forEach(i => { newData.splice(i, 1); count++; });
  438. } else {
  439. const keys = Object.keys(newData);
  440. indices.forEach(i => { delete newData[keys[i]]; count++; });
  441. }
  442. if (!confirm(`确定要删除选中的 ${count} 个项目吗?`)) return;
  443. try {
  444. const res = await fetch(`/api/requirements/${currentSelectedIndex}/save_cluster`, {
  445. method: 'POST',
  446. body: JSON.stringify(newData),
  447. headers: { 'Content-Type': 'application/json' }
  448. });
  449. if (res.ok) {
  450. fetchRequirementData(currentSelectedIndex);
  451. } else {
  452. alert('删除失败');
  453. }
  454. } catch (e) {
  455. console.error(e);
  456. alert('删除失败');
  457. }
  458. };
  459. window.deleteSingleCluster = function (idx) {
  460. deleteClusterItems([idx]);
  461. };
  462. window.deleteSelectedClusters = function () {
  463. const checkboxes = document.querySelectorAll('.cluster-checkbox:checked');
  464. const indices = Array.from(checkboxes).map(cb => parseInt(cb.dataset.idx));
  465. if (indices.length === 0) {
  466. alert('请先选择要删除的项目');
  467. return;
  468. }
  469. deleteClusterItems(indices);
  470. };
  471. window.clearAllClusters = async function () {
  472. if (currentSelectedIndex === null) return;
  473. if (!confirm('确定要清空全部聚类结果吗?')) return;
  474. try {
  475. const res = await fetch(`/api/requirements/${currentSelectedIndex}/save_cluster`, {
  476. method: 'POST',
  477. body: JSON.stringify(Array.isArray(window.dataCache[currentSelectedIndex]?.cluster) ? [] : {}),
  478. headers: { 'Content-Type': 'application/json' }
  479. });
  480. if (res.ok) {
  481. fetchRequirementData(currentSelectedIndex);
  482. } else {
  483. alert('清空失败');
  484. }
  485. } catch (e) {
  486. console.error(e);
  487. alert('清空失败');
  488. }
  489. };
  490. function renderClusterDeletable(clusterData) {
  491. if (!clusterData || (Array.isArray(clusterData) && clusterData.length === 0) || (typeof clusterData === 'object' && Object.keys(clusterData).length === 0)) {
  492. return `<div style="color:var(--text-muted); padding:2rem; text-align:center;">暂无聚类结果数据,请导入 JSON 文件</div>`;
  493. }
  494. let html = `<div style="margin-bottom: 1rem; display: flex; justify-content: space-between; align-items: center;">
  495. <button class="btn btn-danger btn-small" onclick="deleteSelectedClusters()" style="background-color: var(--danger); border-color: var(--danger); color: white;">🗑️ 删除选中项</button>
  496. <button class="btn btn-secondary btn-small" onclick="clearAllClusters()">🧹 清空全部</button>
  497. </div>`;
  498. html += `<div style="display:flex; flex-direction:column; gap:1rem;">`;
  499. const items = Array.isArray(clusterData) ? clusterData : Object.entries(clusterData).map(([k, v]) => ({ key: k, value: v }));
  500. items.forEach((item, idx) => {
  501. const displayData = Array.isArray(clusterData) ? item : item.value;
  502. const displayKey = Array.isArray(clusterData) ? `导入记录 #${idx + 1}` : `Key: ${item.key}`;
  503. html += `<div style="background: rgba(0,0,0,0.02); border: 1px solid var(--border-glass); border-radius: 8px; padding: 1rem;">
  504. <div style="display:flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; border-bottom: 1px solid rgba(0,0,0,0.05); padding-bottom: 0.5rem;">
  505. <label style="display:flex; align-items:center; gap:8px; cursor:pointer; font-weight:bold; color:var(--text-main);">
  506. <input type="checkbox" class="cluster-checkbox" data-idx="${idx}" style="cursor:pointer; width:16px; height:16px;">
  507. ${displayKey}
  508. </label>
  509. <button class="btn btn-secondary btn-small" onclick="deleteSingleCluster(${idx})" style="color:var(--danger); border-color:rgba(239, 68, 68, 0.2); background:rgba(239, 68, 68, 0.05);">❌ 删除此项</button>
  510. </div>
  511. <div style="background: #1e1e1e; color: #d4d4d4; padding: 1rem; border-radius: 6px; font-family: monospace; font-size: 0.85rem; overflow-x: auto; max-height: 400px;">
  512. ${renderJSON(displayData)}
  513. </div>
  514. </div>`;
  515. });
  516. html += `</div>`;
  517. return html;
  518. }
  519. window.selectGenericSubTab = function (prefix, targetId) {
  520. const parentContainer = document.getElementById(`container-${prefix}`);
  521. if (!parentContainer) return;
  522. parentContainer.querySelectorAll('.sub-tab-btn').forEach(btn => {
  523. btn.classList.remove('active');
  524. });
  525. const activeBtn = parentContainer.querySelector(`[data-target="${targetId}"]`);
  526. if (activeBtn) activeBtn.classList.add('active');
  527. parentContainer.querySelectorAll('.sub-tab-pane').forEach(pane => {
  528. pane.classList.add('hidden');
  529. });
  530. const activePane = document.getElementById(targetId);
  531. if (activePane) activePane.classList.remove('hidden');
  532. };
  533. function renderWithSubTabs(dataMain, dataTemp, renderFn, tabPrefix) {
  534. if (!dataTemp || Object.keys(dataTemp).length === 0) {
  535. return renderDataOrRaw(dataMain, renderFn);
  536. }
  537. const mainHtml = renderDataOrRaw(dataMain, renderFn);
  538. const tempHtml = renderDataOrRaw(dataTemp, renderFn);
  539. return `<div id="container-${tabPrefix}">
  540. <div class="sub-tabs">
  541. <button class="sub-tab-btn active" data-target="sub-tab-${tabPrefix}-main" onclick="selectGenericSubTab('${tabPrefix}', 'sub-tab-${tabPrefix}-main')">最终版本</button>
  542. <button class="sub-tab-btn" data-target="sub-tab-${tabPrefix}-temp" onclick="selectGenericSubTab('${tabPrefix}', 'sub-tab-${tabPrefix}-temp')">中间过程 (Temp)</button>
  543. </div>
  544. <div class="sub-tab-contents">
  545. <div id="sub-tab-${tabPrefix}-main" class="sub-tab-pane">
  546. ${mainHtml}
  547. </div>
  548. <div id="sub-tab-${tabPrefix}-temp" class="sub-tab-pane hidden">
  549. ${tempHtml}
  550. </div>
  551. </div>
  552. </div>`;
  553. }
  554. function renderCaseTags(caseRefs) {
  555. if (!caseRefs || caseRefs.length === 0) return '';
  556. let html = `<div class="tags-container" style="gap:0.8rem; flex-wrap:wrap; margin-top: 0.5rem;">`;
  557. caseRefs.forEach(ref => {
  558. let caseId = null;
  559. let title = ref;
  560. const matchNew = ref.match(/^([a-z]+)_([^\s::]+)(?:[::\s]+(.*))?/);
  561. if (matchNew && matchNew[1] !== 'case') {
  562. caseId = `${matchNew[1]}_${matchNew[2]}`;
  563. title = matchNew[3] || ref;
  564. } else {
  565. const matchA = ref.match(/^case_([a-z]+)_([a-zA-Z0-9]+)(?:[::\s]+(.*))?/);
  566. if (matchA) {
  567. caseId = `${matchA[1]}-case_${matchA[2]}`;
  568. title = matchA[3] || ref;
  569. } else {
  570. const matchB = ref.match(/^([a-z]+)[\/\s](case_[a-zA-Z0-9]+)(?:[::\s]+(.*))?/);
  571. if (matchB) {
  572. caseId = `${matchB[1]}-${matchB[2]}`;
  573. title = matchB[3] || ref;
  574. } else {
  575. const matchC = ref.match(/^case_([a-zA-Z0-9]+)_([a-z]+)(?:[::\s]+(.*))?/);
  576. if (matchC) {
  577. caseId = `${matchC[2]}-case_${matchC[1]}`;
  578. title = matchC[3] || ref;
  579. }
  580. }
  581. }
  582. }
  583. if (caseId) {
  584. html += `<a href="#" onclick="jumpToCase('${caseId}'); return false;" class="badge-emoji primary" style="text-decoration:none; white-space:normal; text-align:left; line-height:1.4">
  585. <strong>🔍 ${caseId.replace('-', ' ')}</strong><br>
  586. <span style="font-size:0.75rem">${title.substring(0, 40) + (title.length > 40 ? '...' : '')}</span>
  587. </a>`;
  588. } else {
  589. html += `<span class="badge-emoji" style="white-space:normal; text-align:left; line-height:1.4; font-size:0.75rem">${ref}</span>`;
  590. }
  591. });
  592. html += `</div>`;
  593. return html;
  594. }
  595. function renderCapabilities(capsObj) {
  596. if (!capsObj || (!capsObj.extracted_capabilities && !capsObj.capabilities)) {
  597. return `<div class="data-card" style="border-color: var(--warning)"><div class="card-header"><div class="card-title">⚠️ 未知或非标准格式 (Capabilities)</div></div><div class="card-body" style="font-family: monospace; font-size: 0.85rem; overflow-x: auto;">${renderJSON(capsObj)}</div></div>`;
  598. }
  599. const caps = capsObj.capabilities || capsObj.extracted_capabilities;
  600. if (caps.length === 0) return '<p>未提取到能力。</p>';
  601. let html = ``;
  602. caps.forEach(cap => {
  603. if (!cap.name && !cap.能力名称 && !cap.description && !cap.能力描述 && !cap.id) {
  604. html += `<div class="data-card"><div class="card-header"><div class="card-title">⚠️ 非标准能力项</div></div><div class="card-body" style="font-family: monospace; font-size: 0.85rem; overflow-x: auto;">${renderJSON(cap)}</div></div>`;
  605. return;
  606. }
  607. const isNew = cap.is_new ? '<span class="badge-emoji success">✨ 新能力</span>' : '';
  608. html += `<div class="data-card">
  609. <div class="card-header">
  610. <div class="card-title">⚡ [${cap.id || 'N/A'}] ${cap.name || cap.能力名称 || '未命名'}</div>
  611. ${isNew}
  612. </div>
  613. <div class="card-body">
  614. <p>${cap.description || cap.能力描述 || ''}</p>`;
  615. if (cap.enriched_details) {
  616. const ed = cap.enriched_details;
  617. if (ed.execution_process) {
  618. html += `<div class="card-section"><div class="section-title">🚀 执行流程</div><p style="white-space:pre-wrap;">${ed.execution_process}</p></div>`;
  619. }
  620. if (ed.core_parameters) {
  621. html += `<div class="card-section"><div class="section-title">⚙️ 核心参数</div><p style="white-space:pre-wrap;">${ed.core_parameters}</p></div>`;
  622. }
  623. if (ed.effects) {
  624. html += `<div class="card-section"><div class="section-title">✨ 影响效果</div><p style="white-space:pre-wrap;">${ed.effects}</p></div>`;
  625. }
  626. if (ed.visual_notes) {
  627. html += `<div class="card-section"><div class="section-title">🖼️ 视觉备注</div><p style="white-space:pre-wrap;">${ed.visual_notes}</p></div>`;
  628. }
  629. } else {
  630. html += `<div class="card-section"><div class="section-title">✨ 影响 (Effects)</div><ul>`;
  631. if (cap.effects) cap.effects.forEach(eff => html += `<li>${eff}</li>`);
  632. html += `</ul></div>`;
  633. if (cap.implements && Object.keys(cap.implements).length > 0) {
  634. html += `<div class="card-section"><div class="section-title">🛠️ 实现工具 (Tools)</div><div class="tags-container">`;
  635. for (const [tool, args] of Object.entries(cap.implements)) {
  636. html += `<span class="badge-emoji primary" title="${args}">🔧 ${tool}</span>`;
  637. }
  638. html += `</div></div>`;
  639. }
  640. }
  641. if (cap.case_references && cap.case_references.length > 0) {
  642. html += `<div class="card-section"><div class="section-title">📌 来源案例</div>${renderCaseTags(cap.case_references)}</div>`;
  643. }
  644. html += `</div></div>`;
  645. });
  646. return html;
  647. }
  648. function renderBlueprint(bpObj) {
  649. if (!bpObj || (!bpObj.blueprints && !bpObj.clusters)) {
  650. return `<div class="data-card" style="border-color: var(--warning)"><div class="card-header"><div class="card-title">⚠️ 未知或非标准格式 (Blueprint)</div></div><div class="card-body" style="font-family: monospace; font-size: 0.85rem; overflow-x: auto;">${renderJSON(bpObj)}</div></div>`;
  651. }
  652. let html = ``;
  653. // New process.json format
  654. if (bpObj.clusters) {
  655. html += `<div style="margin-bottom: 1.5rem; padding: 1rem; background: rgba(0,0,0,0.2); border-radius: 8px;">
  656. <h3 style="color:var(--text-main); margin-bottom:0.8rem">🎯 需求</h3>
  657. <p style="color:var(--text-muted)">${bpObj.requirement || ''}</p>
  658. </div>`;
  659. bpObj.clusters.forEach(c => {
  660. if (!c.cluster_id && !c.cluster_name && !c.工序步骤) {
  661. html += `<div class="data-card"><div class="card-header"><div class="card-title">⚠️ 非标准聚类项</div></div><div class="card-body" style="font-family: monospace; font-size: 0.85rem; overflow-x: auto;">${renderJSON(c)}</div></div>`;
  662. return;
  663. }
  664. const score = c.score || 0;
  665. const deg = score * 360;
  666. const scoreClass = score >= 0.8 ? '' : (score >= 0.5 ? 'medium' : 'low');
  667. html += `<div class="data-card">
  668. <div class="card-header">
  669. <div class="card-title">🧩 [${c.cluster_id || 'N/A'}] ${c.cluster_name || '未命名'}</div>
  670. </div>
  671. <div class="card-body">
  672. <div class="score-container" style="margin-bottom:1rem">
  673. <div class="score-circle ${scoreClass}" style="--score-deg: ${deg}deg"><span>${Math.round(score * 100)}%</span></div>
  674. <div class="score-text"><strong>匹配度得分</strong></div>
  675. </div>
  676. <div class="card-section"><div class="section-title">🧠 解释 (Explanation)</div>
  677. <p>${c.explanation || ''}</p></div>
  678. <div class="card-section"><div class="section-title">📍 工序步骤</div><div class="phase-list">`;
  679. if (c.工序步骤) c.工序步骤.forEach(step => {
  680. html += `<div class="phase-item">
  681. <div class="phase-title">步骤 ${step.步骤序号}</div>
  682. <div>${step.步骤描述 || ''}</div>
  683. </div>`;
  684. });
  685. html += `</div></div>`;
  686. if (c.关联案例 && c.关联案例.length > 0) {
  687. html += `<div class="card-section"><div class="section-title">📌 关联案例</div>${renderCaseTags(c.关联案例)}</div>`;
  688. }
  689. html += `</div></div>`;
  690. });
  691. return html;
  692. }
  693. // Old blueprint format
  694. if (bpObj.distilled_cases && bpObj.distilled_cases.length > 0) {
  695. html += `<div style="margin-bottom: 1.5rem; padding: 1rem; background: rgba(0,0,0,0.2); border-radius: 8px;">
  696. <h3 style="color:var(--text-main); margin-bottom:0.8rem">📚 蓝图来源案例</h3>
  697. <div class="tags-container" style="gap:0.8rem">`;
  698. bpObj.distilled_cases.forEach(c => {
  699. let targetId = c.id;
  700. const matchA = targetId.match(/^case_([a-z]+)_(\d+)/);
  701. if (matchA) {
  702. targetId = `${matchA[1]}-case_${matchA[2]}`;
  703. } else {
  704. const matchB = targetId.match(/^([a-z]+)[\/\s](case_\d+)/);
  705. if (matchB) {
  706. targetId = `${matchB[1]}-${matchB[2]}`;
  707. } else {
  708. const matchC = targetId.match(/^case_(\d+)_([a-z]+)/);
  709. if (matchC) targetId = `${matchC[2]}-case_${matchC[1]}`;
  710. }
  711. }
  712. html += `<a href="#" onclick="jumpToCase('${targetId}'); return false;" class="badge-emoji primary" style="text-decoration:none; white-space:normal; text-align:left; line-height:1.4">
  713. <strong>🔍 ${c.id}</strong><br>
  714. <span style="font-size:0.75rem">${c.title ? c.title.substring(0, 40) + (c.title.length > 40 ? '...' : '') : 'View Source'}</span>
  715. </a>`;
  716. });
  717. html += `</div></div>`;
  718. }
  719. if (bpObj.blueprints) bpObj.blueprints.forEach(bp => {
  720. if (!bp.name && !bp.phases) {
  721. html += `<div class="data-card"><div class="card-header"><div class="card-title">⚠️ 非标准蓝图项</div></div><div class="card-body" style="font-family: monospace; font-size: 0.85rem; overflow-x: auto;">${renderJSON(bp)}</div></div>`;
  722. return;
  723. }
  724. html += `<div class="data-card">
  725. <div class="card-header">
  726. <div class="card-title">🗺️ ${bp.name || '未命名'}</div>
  727. </div>
  728. <div class="card-body">
  729. <div class="card-section"><div class="section-title">🧠 推理逻辑 (Reasoning)</div>
  730. <p>${bp.reasoning || ''}</p></div>
  731. <div class="card-section"><div class="section-title">📍 阶段 (Phases)</div><div class="phase-list">`;
  732. if (bp.phases) bp.phases.forEach(ph => {
  733. html += `<div class="phase-item">
  734. <div class="phase-title">${ph.phase || ''}</div>
  735. <div>${ph.description || ''}</div>
  736. </div>`;
  737. });
  738. html += `</div></div></div>`;
  739. });
  740. return html;
  741. }
  742. function renderStrategy(stratObj) {
  743. if (!stratObj || (!stratObj.strategies && !stratObj.workflow)) {
  744. return `<div class="data-card" style="border-color: var(--warning)"><div class="card-header"><div class="card-title">⚠️ 未知或非标准格式 (Strategy)</div></div><div class="card-body" style="font-family: monospace; font-size: 0.85rem; overflow-x: auto;">${renderJSON(stratObj)}</div></div>`;
  745. }
  746. let html = `<div style="margin-bottom: 1.5rem; padding: 1rem; background: rgba(0,0,0,0.2); border-radius: 8px;">
  747. <h3 style="color:var(--text-main); margin-bottom:0.5rem">🎯 需求描述</h3>
  748. <p style="color:var(--text-muted)">${stratObj.requirement || ''}</p>
  749. </div>`;
  750. // New Workflow Format
  751. if (stratObj.workflow) {
  752. stratObj.workflow.forEach(strat => {
  753. if (!strat.cluster_id && !strat.cluster_name && !strat.steps) {
  754. html += `<div class="data-card"><div class="card-header"><div class="card-title">⚠️ 非标准工作流项</div></div><div class="card-body" style="font-family: monospace; font-size: 0.85rem; overflow-x: auto;">${renderJSON(strat)}</div></div>`;
  755. return;
  756. }
  757. const score = strat.score || 0;
  758. const deg = score * 360;
  759. const scoreClass = score >= 0.8 ? '' : (score >= 0.5 ? 'medium' : 'low');
  760. let scoreHtml = `<div class="score-container">
  761. <div class="score-circle ${scoreClass}" style="--score-deg: ${deg}deg"><span>${Math.round(score * 100)}%</span></div>
  762. <div class="score-text"><strong>匹配得分</strong><br>${strat.explanation || ''}</div>
  763. </div>`;
  764. html += `<div class="data-card">
  765. <div class="card-header">
  766. <div class="card-title">🎯 [${strat.cluster_id}] ${strat.cluster_name || '未命名'}</div>
  767. </div>
  768. <div class="card-body">
  769. ${scoreHtml}
  770. ${(strat.关联案例 && strat.关联案例.length > 0) ? `<div class="card-section" style="margin-bottom: 1rem;"><div class="section-title">📌 关联案例</div>${renderCaseTags(strat.关联案例)}</div>` : ''}
  771. <div class="card-section"><div class="section-title">🧱 工作流步骤</div><div class="phase-list">`;
  772. if (strat.steps) strat.steps.forEach(step => {
  773. html += `<div class="phase-item">
  774. <div class="phase-title">步骤 ${step.步骤序号}</div>
  775. <div style="margin-bottom:0.5rem">${step.步骤描述}</div>
  776. <div class="tags-container">`;
  777. if (step.capabilities) {
  778. step.capabilities.forEach(cap => {
  779. html += `<div style="margin-top: 0.5rem; padding: 0.5rem; background: rgba(0, 0, 0, 0.05); border-radius: 4px; width: 100%;">
  780. <div style="font-weight: bold; margin-bottom: 0.3rem;">⚡ [${cap.id}] ${cap.name}</div>
  781. <div style="font-size: 0.8rem; color: var(--text-muted);">${cap.description}</div>
  782. ${(cap.case_references && cap.case_references.length > 0) ? `<div style="margin-top: 0.5rem;">${renderCaseTags(cap.case_references)}</div>` : ''}
  783. </div>`;
  784. });
  785. }
  786. html += `</div></div>`;
  787. });
  788. html += `</div></div></div></div>`;
  789. });
  790. return html;
  791. }
  792. if (stratObj.strategies) {
  793. stratObj.strategies.sort((a, b) => (b.is_selected === true) - (a.is_selected === true));
  794. stratObj.strategies.forEach(strat => {
  795. if (!strat.name && !strat.workflow_outline) {
  796. html += `<div class="data-card"><div class="card-header"><div class="card-title">⚠️ 非标准策略项</div></div><div class="card-body" style="font-family: monospace; font-size: 0.85rem; overflow-x: auto;">${renderJSON(strat)}</div></div>`;
  797. return;
  798. }
  799. const isSelected = strat.is_selected;
  800. const icon = isSelected ? '🎯' : '🥈';
  801. const badge = isSelected ? '<span class="badge-emoji success">⭐ 被选中的策略</span>' : '<span class="badge-emoji warning">备选策略</span>';
  802. let scoreHtml = '';
  803. if (strat.coverage_score !== undefined) {
  804. const score = strat.coverage_score;
  805. const deg = score * 360;
  806. const scoreClass = score >= 0.8 ? '' : (score >= 0.5 ? 'medium' : 'low');
  807. scoreHtml = `<div class="score-container">
  808. <div class="score-circle ${scoreClass}" style="--score-deg: ${deg}deg"><span>${Math.round(score * 100)}%</span></div>
  809. <div class="score-text"><strong>覆盖率得分</strong><br>${strat.coverage_explanation || ''}</div>
  810. </div>`;
  811. }
  812. html += `<div class="data-card" style="${isSelected ? 'border-color: var(--accent-primary); box-shadow: 0 0 15px rgba(59,130,246,0.1);' : ''}">
  813. <div class="card-header">
  814. <div class="card-title">${icon} ${strat.name || '未命名'}</div>
  815. ${badge}
  816. </div>
  817. <div class="card-body">
  818. ${scoreHtml}
  819. <div class="tags-container" style="margin-bottom:1rem">
  820. <span class="badge-emoji">📥 来源: ${strat.source || 'N/A'}</span>
  821. </div>`;
  822. if (strat.reasoning) html += `<div class="card-section"><div class="section-title">🧠 推理逻辑 (Reasoning)</div><p>${strat.reasoning}</p></div>`;
  823. if (strat.why_not) html += `<div class="card-section"><div class="section-title">❌ 为何未被选中</div><p>${strat.why_not}</p></div>`;
  824. if (strat.workflow_outline && strat.workflow_outline.length > 0) {
  825. html += `<div class="card-section"><div class="section-title">🧱 工作流大纲</div><div class="phase-list">`;
  826. strat.workflow_outline.forEach(wo => {
  827. html += `<div class="phase-item">
  828. <div class="phase-title">${wo.phase}</div>
  829. <div style="margin-bottom:0.5rem">${wo.description}</div>
  830. <div class="tags-container">`;
  831. if (wo.capabilities) {
  832. wo.capabilities.forEach(cap => html += `<span class="badge-emoji primary">⚡ ${cap.name}</span>`);
  833. }
  834. html += `</div></div>`;
  835. });
  836. html += `</div></div>`;
  837. }
  838. html += `</div></div>`;
  839. });
  840. }
  841. if (stratObj.uncovered_requirements && stratObj.uncovered_requirements.length > 0) {
  842. html += `<div class="data-card" style="border-color: var(--danger)">
  843. <div class="card-header"><div class="card-title">⚠️ Uncovered Requirements</div></div>
  844. <div class="card-body"><ul>`;
  845. stratObj.uncovered_requirements.forEach(req => html += `<li>${req}</li>`);
  846. html += `</ul></div></div>`;
  847. }
  848. return html;
  849. }
  850. window.selectSubTab = function (p) {
  851. document.querySelectorAll('.sub-tab-btn').forEach(b => {
  852. b.classList.remove('active');
  853. if (b.textContent === p.replace('case_', '').toUpperCase()) b.classList.add('active');
  854. });
  855. document.querySelectorAll('.sub-tab-pane').forEach(pane => pane.classList.add('hidden'));
  856. const target = document.getElementById('sub-tab-' + p);
  857. if (target) target.classList.remove('hidden');
  858. };
  859. window.jumpToCase = function (caseId) {
  860. // Switch to raw tab
  861. document.querySelector('.tab-btn-pill[data-target="tab-raw"]').click();
  862. // Find the case card
  863. const targetCard = document.getElementById('case-card-' + caseId);
  864. if (targetCard) {
  865. // Find which sub-tab pane it's inside
  866. const pane = targetCard.closest('.sub-tab-pane');
  867. if (pane) {
  868. const platformId = pane.id.replace('sub-tab-', '');
  869. selectSubTab(platformId);
  870. }
  871. // Scroll into view
  872. targetCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
  873. // Add highlight
  874. targetCard.classList.remove('highlight-pulse');
  875. void targetCard.offsetWidth; // Trigger reflow
  876. targetCard.classList.add('highlight-pulse');
  877. } else {
  878. alert("Case not found in raw cases data.");
  879. }
  880. };
  881. async function fetchPromptsList() {
  882. try {
  883. const res = await fetch('/api/prompts');
  884. let list = await res.json();
  885. // Handle DAG nodes
  886. document.querySelectorAll('.prompt-node').forEach(node => {
  887. const p = node.dataset.prompt;
  888. if (list.includes(p)) {
  889. node.onclick = () => selectPrompt(p, node);
  890. // Remove from list so it doesn't appear in "other"
  891. list = list.filter(item => item !== p);
  892. } else {
  893. node.style.opacity = 0.5; // gray out if not found
  894. node.style.cursor = 'not-allowed';
  895. }
  896. });
  897. const elOtherPromptsList = document.getElementById('other-prompts-list');
  898. if (elOtherPromptsList) {
  899. elOtherPromptsList.innerHTML = '';
  900. list.forEach((p) => {
  901. const div = document.createElement('div');
  902. div.className = 'prompt-tab';
  903. div.textContent = p;
  904. div.onclick = () => selectPrompt(p, div);
  905. elOtherPromptsList.appendChild(div);
  906. });
  907. }
  908. // Select the first prompt by default (maybe researcher.prompt)
  909. const firstNode = document.querySelector('.prompt-node[data-prompt="researcher.prompt"]');
  910. if (firstNode) {
  911. selectPrompt('researcher.prompt', firstNode);
  912. }
  913. } catch (e) {
  914. console.error("Failed to load prompts", e);
  915. }
  916. }
  917. async function selectPrompt(name, tabEl) {
  918. currentPromptName = name;
  919. document.querySelectorAll('.prompt-tab').forEach(el => el.classList.remove('active'));
  920. document.querySelectorAll('.prompt-node').forEach(el => el.classList.remove('active'));
  921. if (tabEl) tabEl.classList.add('active');
  922. elPromptTextarea.value = 'Loading...';
  923. elPromptTextarea.disabled = true;
  924. if (elSchemaTextarea) {
  925. elSchemaTextarea.value = 'Loading...';
  926. elSchemaTextarea.disabled = true;
  927. }
  928. try {
  929. const res = await fetch(`/api/prompts/${name}`);
  930. const data = await res.json();
  931. elPromptTextarea.value = data.content || '';
  932. if (elSchemaTextarea) {
  933. elSchemaTextarea.value = data.schema_content || '';
  934. }
  935. } catch (e) {
  936. elPromptTextarea.value = 'Error loading prompt.';
  937. if (elSchemaTextarea) elSchemaTextarea.value = '';
  938. }
  939. elPromptTextarea.disabled = false;
  940. if (elSchemaTextarea) elSchemaTextarea.disabled = false;
  941. elPromptStatus.textContent = '';
  942. }
  943. function renderAggregatedPerCaseData(cases, type) {
  944. if (!cases || !Array.isArray(cases) || cases.length === 0) {
  945. return '<div style="color:var(--text-muted); padding: 1rem; text-align: center;">暂无案例数据</div>';
  946. }
  947. let sidebarHtml = `<div class="case-sidebar" style="width: 56px; flex-shrink: 0; position: sticky; top: 0; align-self: flex-start; height: calc(100vh - 100px); overflow-y: auto; background: #fff;">`;
  948. sidebarHtml += `<div class="sidebar-nav-list" style="padding: 6px;">`;
  949. let contentHtml = `<div class="case-content-area" style="flex: 1; min-width: 0; padding-left: 1.25rem; padding-right: 2rem; border-left: 1px solid #f1f3f4; margin-left: -1px;">`;
  950. let hasData = false;
  951. let displayIndex = 1;
  952. // Sort cases by score
  953. const sortedCases = [...cases].sort((a, b) => {
  954. const aId = a.case_id || (a._raw && a._raw.case_id);
  955. const bId = b.case_id || (b._raw && b._raw.case_id);
  956. const sourceMap = window._currentRawCasesContext ? window._currentRawCasesContext.sourceMap || {} : {};
  957. const aMapped = sourceMap[aId] || {};
  958. const bMapped = sourceMap[bId] || {};
  959. const aScore = aMapped.evaluation && aMapped.evaluation.quality ? (aMapped.evaluation.quality.overall_score || 0) : 0;
  960. const bScore = bMapped.evaluation && bMapped.evaluation.quality ? (bMapped.evaluation.quality.overall_score || 0) : 0;
  961. return bScore - aScore;
  962. });
  963. sortedCases.forEach((c, idx) => {
  964. const cId = c.case_id || (c._raw && c._raw.case_id) || `temp_${idx}`;
  965. const sourceMap = window._currentRawCasesContext ? window._currentRawCasesContext.sourceMap || {} : {};
  966. const mappedS = sourceMap[cId] || {};
  967. const postObj = mappedS.post || c.post || c || {};
  968. const title = postObj.title || c.title || postObj.desc || (postObj.body_text ? postObj.body_text.substring(0, 30) + '...' : '') || cId || `案例 ${idx + 1}`;
  969. hasData = true; // Always render if there is a case, so the user can click Rerun.
  970. let items = null;
  971. if (type === 'workflow') {
  972. items = c.workflow ? [c.workflow] : null;
  973. } else if (type === 'capabilities') {
  974. items = c.capability && Array.isArray(c.capability) ? c.capability : null;
  975. }
  976. const targetId = `case-${type}-${idx}`;
  977. const navIndex = displayIndex++;
  978. let publishStrHtml = '';
  979. if (c.published_at) {
  980. const dateObj = new Date(c.published_at);
  981. const dateStr = isNaN(dateObj.getTime()) ? c.published_at : dateObj.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
  982. publishStrHtml = `<span style="font-size: 0.75em; font-weight: normal; color: #94a3b8; background: #f1f5f9; border: 1px solid #e2e8f0; padding: 2px 8px; border-radius: 12px; margin-left: 8px;">发布于: ${dateStr}</span>`;
  983. }
  984. const score = mappedS.evaluation && mappedS.evaluation.quality ? mappedS.evaluation.quality.overall_score : null;
  985. let scoreBadge = '';
  986. if (score !== null && score !== undefined) {
  987. let color = score >= 80 ? '#10b981' : (score >= 60 ? '#f59e0b' : '#ef4444');
  988. scoreBadge = `<span style="font-size: 0.85em; font-weight: bold; color: #fff; background: ${color}; padding: 2px 8px; border-radius: 12px; margin-left: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">⭐️ ${score}</span>`;
  989. }
  990. const typeLabel = type === 'workflow' ? '工序' : '能力';
  991. // Add to sidebar
  992. sidebarHtml += `<div class="sidebar-nav-item" title="${title.replace(/"/g, '&quot;')}" style="min-height: 34px; padding: 0; margin-bottom: 6px; display:flex; align-items:center; justify-content:center; font-family: monospace; font-weight: 700; color:#64748b;" onclick="
  993. document.querySelectorAll('.sidebar-nav-item').forEach(el => el.classList.remove('active'));
  994. this.classList.add('active');
  995. document.getElementById('${targetId}').scrollIntoView({behavior: 'smooth'})
  996. ">
  997. ${navIndex}
  998. </div>`;
  999. contentHtml += `<div id="${targetId}" class="case-section" style="margin-bottom: 3.5rem; padding-top: 1rem;">`;
  1000. const stepName = 'workflow-extract';
  1001. const caseIndexToPass = c.index || (idx + 1);
  1002. const btnHtml = `<button class="btn btn-secondary" style="font-size: 0.85em; padding: 0.4rem 0.8rem; border-radius: 4px;" onclick="event.stopPropagation(); triggerSingleCaseRerun('${stepName}', ${caseIndexToPass})">🔄 重跑${typeLabel}</button>`;
  1003. contentHtml += `<div style="display: flex; align-items: center; justify-content: space-between; background: rgba(0,0,0,0.02); border-radius: 8px; padding-right: 1rem; cursor: pointer; margin-bottom: 1.2rem;" onclick="const content = this.nextElementSibling; content.classList.toggle('hidden'); this.querySelector('.case-arrow').textContent = content.classList.contains('hidden') ? '▶' : '▼';">`;
  1004. contentHtml += `<h3 style="margin: 0; padding: 1rem; color: var(--text-main); font-size: 1.2rem; display: flex; align-items: center; gap: 10px; user-select: none; flex: 1;">`;
  1005. contentHtml += `<span class="case-arrow" style="font-size: 0.8em; color: var(--text-muted); width: 16px; display: inline-block;">▶</span>`;
  1006. contentHtml += `<span style="color: #64748b; font-size: 1.1rem; font-weight: bold; font-family: monospace;">#${idx + 1}</span>`;
  1007. contentHtml += `<span>${title.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</span>${scoreBadge}${publishStrHtml}</h3>`;
  1008. contentHtml += btnHtml;
  1009. contentHtml += `</div>`;
  1010. // Collapsible Post Info
  1011. const post = mappedS.post || c.post || c || {};
  1012. const images = post.images || [];
  1013. const xImages = post.image_url_list || [];
  1014. const ytThumbnails = post.thumbnails && post.thumbnails.length > 0 ? [post.thumbnails[post.thumbnails.length - 1].url] : [];
  1015. const allImages = [...images, ...xImages.map(img => img.image_url), ...ytThumbnails].filter(Boolean);
  1016. const bodyText = post.body_text || post.body || post.desc || '';
  1017. let mediaHtml = '';
  1018. if (allImages.length > 0) {
  1019. mediaHtml = `<div style="display:flex; gap:8px; overflow-x:auto; margin-bottom: 1rem; padding-bottom: 8px;">`;
  1020. allImages.forEach((img, i) => {
  1021. const coverImgUrl = `/output/${window._currentRawCasesContext.reqId}/raw_cases/images/${cId}/${i.toString().padStart(2, '0')}.jpg`;
  1022. mediaHtml += `<img src="${coverImgUrl}" onerror="this.onerror=null; this.src='${img}';" style="height: 150px; border-radius: 6px; object-fit: cover; flex-shrink: 0;">`;
  1023. });
  1024. mediaHtml += `</div>`;
  1025. }
  1026. contentHtml += `<div class="case-post-info hidden" style="padding: 1.5rem; background: #f8fafc; border-radius: 8px; margin-bottom: 1.5rem; border: 1px solid #e2e8f0;">
  1027. ${mediaHtml}
  1028. <div style="font-size: 0.95em; color: #334155; white-space: pre-wrap; line-height: 1.6; word-break: break-all;">${bodyText.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</div>
  1029. </div>`;
  1030. // Always Expanded Structured Data
  1031. contentHtml += window.renderStructuredData(items, type, c);
  1032. // Add JSON toggle at the bottom of the case section
  1033. const caseJsonStr = JSON.stringify(c, null, 2).replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  1034. contentHtml += `<div style="margin-top: 1.5rem; border-top: 1px dashed rgba(0,0,0,0.1); padding-top: 1rem;">
  1035. <div style="font-size: 0.8rem; color: var(--text-muted); cursor: pointer; display: flex; align-items: center; gap: 4px;" onclick="const content = this.nextElementSibling; content.classList.toggle('hidden'); this.querySelector('.arrow').textContent = content.classList.contains('hidden') ? '▶' : '▼';">
  1036. <span class="arrow">▶</span> 查看 raw JSON
  1037. </div>
  1038. <div class="json-container hidden" style="margin-top: 0.8rem;"><pre style="background: #1e1e1e; color: #d4d4d4; padding: 1rem; border-radius: 6px; font-size: 0.8rem; overflow-x: auto; max-height: 400px; margin: 0;"><code>${caseJsonStr}</code></pre></div>
  1039. </div>`;
  1040. contentHtml += `</div>`;
  1041. });
  1042. sidebarHtml += `</div></div>`;
  1043. contentHtml += `</div>`;
  1044. if (!hasData) {
  1045. return `<div style="color:var(--text-muted); padding: 1rem; text-align: center;">当前需求的所有案例均无提取的${type === 'workflow' ? '工序' : '能力'}</div>`;
  1046. }
  1047. return `<div style="display: flex; align-items: stretch; position: relative;">${sidebarHtml}${contentHtml}</div>`;
  1048. }
  1049. async function fetchRequirementData(index) {
  1050. try {
  1051. const res = await fetch(`/api/requirements/${index}/data`);
  1052. const data = await res.json();
  1053. window.dataCache = window.dataCache || {};
  1054. window.dataCache[index] = data;
  1055. let rawCasesClone = null;
  1056. let casesList = [];
  1057. if (data.raw_cases) {
  1058. rawCasesClone = { ...data.raw_cases };
  1059. const detailedCaseObj = data.raw_cases['case'] || data.raw_cases['case_detailed'];
  1060. if (detailedCaseObj && detailedCaseObj.cases) {
  1061. casesList = detailedCaseObj.cases;
  1062. }
  1063. }
  1064. if (jsonStrategy) jsonStrategy.innerHTML = ''; // Tab removed
  1065. jsonRaw.innerHTML = renderDataOrRaw(rawCasesClone, renderRawCases);
  1066. const clusterData = window.dataCache[index].cluster;
  1067. const oldActiveWorkflowTab = jsonBlueprint.querySelector('.sub-tab-btn.active')?.dataset?.target || 'sub-tab-workflow-cases';
  1068. const workflowCasesHtml = renderAggregatedPerCaseData(casesList, 'workflow');
  1069. let bpHtml = `<div id="container-workflow">`;
  1070. bpHtml += `<div class="sub-tabs-container" style="margin-bottom: 1rem; border-bottom: 1px solid var(--border-glass); padding-bottom: 8px; display: flex; gap: 8px;">`;
  1071. bpHtml += `<button class="sub-tab-btn ${oldActiveWorkflowTab === 'sub-tab-workflow-cases' ? 'active' : ''}" data-target="sub-tab-workflow-cases" onclick="selectGenericSubTab('workflow', 'sub-tab-workflow-cases')">📊 案例解析页</button>`;
  1072. bpHtml += `<button class="sub-tab-btn ${oldActiveWorkflowTab === 'sub-tab-workflow-cluster' ? 'active' : ''}" data-target="sub-tab-workflow-cluster" onclick="selectGenericSubTab('workflow', 'sub-tab-workflow-cluster')">🧩 聚类结果 (Cluster)</button>`;
  1073. bpHtml += `</div>`;
  1074. bpHtml += `<div id="sub-tab-workflow-cases" class="sub-tab-pane ${oldActiveWorkflowTab === 'sub-tab-workflow-cases' ? '' : 'hidden'}">${workflowCasesHtml}</div>`;
  1075. bpHtml += `<div id="sub-tab-workflow-cluster" class="sub-tab-pane ${oldActiveWorkflowTab === 'sub-tab-workflow-cluster' ? '' : 'hidden'}">
  1076. <div style="margin-bottom: 1.5rem; padding: 1.2rem; background: rgba(0,0,0,0.02); border-radius: 8px; display: flex; justify-content: space-between; align-items: center; border: 1px dashed rgba(0,0,0,0.1);">
  1077. <span style="color: var(--text-muted); font-size: 0.9em;">导入本地生成的 JSON (如 process.json 等) 将保存为 cluster.json 并支持单项删除与多选清除。</span>
  1078. <div>
  1079. <input type="file" id="input-upload-cluster" accept=".json" style="display:none;">
  1080. <button class="btn btn-primary btn-small" onclick="document.getElementById('input-upload-cluster').click()">📥 导入 JSON</button>
  1081. </div>
  1082. </div>
  1083. <div id="cluster-preview-content">${renderClusterDeletable(clusterData)}</div>
  1084. </div>`;
  1085. bpHtml += `</div>`;
  1086. jsonBlueprint.innerHTML = bpHtml;
  1087. const clusterFileInput = document.getElementById('input-upload-cluster');
  1088. if (clusterFileInput) {
  1089. clusterFileInput.onchange = async (e) => {
  1090. const file = e.target.files[0];
  1091. if (!file) return;
  1092. const formData = new FormData();
  1093. formData.append('file', file);
  1094. try {
  1095. const res = await fetch(`/api/requirements/${index}/upload_cluster`, {
  1096. method: 'POST',
  1097. body: formData
  1098. });
  1099. if (res.ok) {
  1100. fetchRequirementData(index);
  1101. } else {
  1102. alert('上传失败');
  1103. }
  1104. } catch (err) {
  1105. console.error(err);
  1106. alert('上传出错');
  1107. }
  1108. };
  1109. }
  1110. const btnUpload = document.getElementById('btn-upload-source-ex');
  1111. const fileInput = document.getElementById('input-upload-source-ex');
  1112. if (btnUpload && fileInput) {
  1113. btnUpload.onclick = () => fileInput.click();
  1114. fileInput.onchange = async (e) => {
  1115. const file = e.target.files[0];
  1116. if (!file) return;
  1117. const formData = new FormData();
  1118. formData.append('file', file);
  1119. try {
  1120. const res = await fetch(`/api/requirements/${index}/upload_source_ex`, {
  1121. method: 'POST',
  1122. body: formData
  1123. });
  1124. if (res.ok) {
  1125. alert('上传成功!');
  1126. fetchRequirementData(index);
  1127. } else {
  1128. alert('上传失败');
  1129. }
  1130. } catch (err) {
  1131. console.error(err);
  1132. alert('上传出错');
  1133. }
  1134. };
  1135. }
  1136. if (rawCasesClone && Object.keys(rawCasesClone).length > 0) {
  1137. currentAvailablePlatforms = Object.keys(rawCasesClone)
  1138. .filter(p => p.startsWith('case_') && p !== 'case_detailed' && p !== 'case')
  1139. .map(p => p.replace('case_', ''));
  1140. if (currentAvailablePlatforms.length === 0) {
  1141. currentAvailablePlatforms = ['xhs', 'youtube', 'bili', 'x'];
  1142. }
  1143. } else {
  1144. currentAvailablePlatforms = ['xhs', 'youtube', 'bili', 'x'];
  1145. }
  1146. } catch (e) {
  1147. console.error("Failed to fetch data", e);
  1148. }
  1149. }
  1150. async function pollStatus() {
  1151. try {
  1152. const res = await fetch('/api/pipeline/status');
  1153. const statusData = await res.json();
  1154. let needsListUpdate = false;
  1155. // Check if any status changed
  1156. for (const [idxStr, runInfo] of Object.entries(statusData)) {
  1157. const idx = parseInt(idxStr);
  1158. if (!activeRuns[idx] || activeRuns[idx].status !== runInfo.status) {
  1159. needsListUpdate = true;
  1160. }
  1161. activeRuns[idx] = runInfo;
  1162. // Update logs if modal is open for this index
  1163. if (currentSelectedIndex === idx && !modalLogs.classList.contains('hidden')) {
  1164. terminalLogs.textContent = runInfo.logs.join('');
  1165. terminalLogs.scrollTop = terminalLogs.scrollHeight;
  1166. }
  1167. // Update detail view banner if this is the selected one
  1168. if (currentSelectedIndex === idx) {
  1169. updateDetailBannerStatus(runInfo.status);
  1170. }
  1171. }
  1172. if (needsListUpdate) {
  1173. // update in requirements array
  1174. requirements.forEach(req => {
  1175. if (activeRuns[req.index]) {
  1176. req.status = activeRuns[req.index].status;
  1177. }
  1178. });
  1179. renderTaskList(requirements);
  1180. updateStats();
  1181. }
  1182. } catch (e) {
  1183. console.error("Failed to poll status", e);
  1184. }
  1185. }
  1186. function startStatusPolling() {
  1187. if (statusInterval) clearInterval(statusInterval);
  1188. statusInterval = setInterval(pollStatus, 2000);
  1189. }
  1190. // Render
  1191. function renderTaskList(list) {
  1192. elReqSelector.innerHTML = '<option value="">-- 选择一个需求 --</option>';
  1193. list.forEach(req => {
  1194. const option = document.createElement('option');
  1195. option.value = req.index;
  1196. let statusMarker = '';
  1197. if (req.status === 'running') statusMarker = '🚀';
  1198. else if (req.status === 'completed') statusMarker = '✅';
  1199. else if (req.status === 'partial') statusMarker = '⚠️';
  1200. else if (req.status === 'failed') statusMarker = '❌';
  1201. else statusMarker = '⏳';
  1202. option.textContent = `${statusMarker} [#${req.id}] ${req.requirement} (Cases: ${req.raw_cases_count})`;
  1203. if (currentSelectedIndex === req.index) {
  1204. option.selected = true;
  1205. }
  1206. elReqSelector.appendChild(option);
  1207. });
  1208. }
  1209. function updateStats() {
  1210. const total = requirements.length;
  1211. const completed = requirements.filter(r => r.status === 'completed').length;
  1212. const running = requirements.filter(r => r.status === 'running').length;
  1213. elStatsContainer.innerHTML = `
  1214. <span>Total: ${total}</span>
  1215. <span style="color:var(--success)">Done: ${completed}</span>
  1216. ${running > 0 ? `<span style="color:var(--accent-primary)">Running: ${running}</span>` : ''}
  1217. `;
  1218. }
  1219. function selectRequirement(index) {
  1220. currentSelectedIndex = index;
  1221. const req = requirements.find(r => r.index === index);
  1222. if (!req) return;
  1223. // Sync dropdown if called from somewhere else
  1224. if (elReqSelector.value != index) {
  1225. elReqSelector.value = index;
  1226. }
  1227. // Update Detail UI
  1228. elEmptyState.classList.add('hidden');
  1229. elDetailView.classList.remove('hidden');
  1230. updateDetailBannerStatus(activeRuns[index] ? activeRuns[index].status : req.status);
  1231. // Fetch data
  1232. if (jsonStrategy) jsonStrategy.textContent = 'Loading...';
  1233. if (jsonBlueprint) jsonBlueprint.textContent = 'Loading...';
  1234. if (jsonRaw) jsonRaw.textContent = 'Loading...';
  1235. fetchRequirementData(index);
  1236. }
  1237. function updateDetailBannerStatus(status) {
  1238. const btnStop = document.getElementById('btn-stop-pipeline');
  1239. if (status === 'running') {
  1240. elStatusBanner.classList.remove('hidden');
  1241. elStatusBanner.style.background = 'rgba(59, 130, 246, 0.1)';
  1242. elStatusText.textContent = 'Pipeline is currently running...';
  1243. elStatusBanner.querySelector('.status-indicator').style.display = 'block';
  1244. elStatusBanner.querySelector('.status-indicator').style.background = 'var(--accent-primary)';
  1245. if (btnStop) btnStop.style.display = 'inline-block';
  1246. } else if (status === 'failed') {
  1247. elStatusBanner.classList.remove('hidden');
  1248. elStatusBanner.style.background = 'rgba(239, 68, 68, 0.1)';
  1249. elStatusText.textContent = 'Pipeline run failed.';
  1250. elStatusBanner.querySelector('.status-indicator').style.display = 'block';
  1251. elStatusBanner.querySelector('.status-indicator').style.background = 'var(--danger)';
  1252. if (btnStop) btnStop.style.display = 'none';
  1253. } else {
  1254. elStatusBanner.classList.add('hidden');
  1255. if (btnStop) btnStop.style.display = 'none';
  1256. }
  1257. }
  1258. // Actions
  1259. async function triggerRun() {
  1260. if (currentSelectedIndex === null) return;
  1261. const checkSdk = document.getElementById('check-claude-sdk').checked;
  1262. const mode = document.getElementById('select-force-phase').value;
  1263. const platforms = document.getElementById('input-platforms').value;
  1264. let only_step = null;
  1265. let start_from = null;
  1266. let end_at = null;
  1267. let restart_mode = null;
  1268. let phase = null;
  1269. if (mode === "custom_range") {
  1270. if (!chainStartNode) {
  1271. alert('请在下方链条中选择至少一个节点作为起点。');
  1272. return;
  1273. }
  1274. if (chainStartNode === chainEndNode || !chainEndNode) {
  1275. only_step = chainStartNode.replace(/-1$/, '');
  1276. } else {
  1277. start_from = chainStartNode.replace(/-1$/, '');
  1278. end_at = chainEndNode.replace(/-1$/, '');
  1279. }
  1280. } else if (mode.startsWith("step_")) {
  1281. const stepMap = {
  1282. "step_1.1": "research",
  1283. "step_1.5": "source",
  1284. "step_1.6": "generate-case",
  1285. "step_1.6_extract": "workflow-extract",
  1286. "step_1.7": "apply-grounding",
  1287. "step_2.1.1": "process-cluster",
  1288. "step_2.1.2": "process-score",
  1289. "step_2.2.1": "capability-extract",
  1290. "step_2.2.2": "capability-enrich",
  1291. "step_3.0": "strategy"
  1292. };
  1293. only_step = stepMap[mode];
  1294. if (mode === "step_1.1") {
  1295. restart_mode = "single_platforms"; // triggers backend's platform specific clearing
  1296. }
  1297. } else if (mode.startsWith("phase")) {
  1298. if (mode === "phase1") {
  1299. phase = 1;
  1300. } else if (mode === "phase2") {
  1301. phase = 2;
  1302. } else if (mode === "phase3") {
  1303. phase = 3;
  1304. }
  1305. } else {
  1306. restart_mode = "smart";
  1307. }
  1308. const groupPlatforms = document.getElementById('group-platforms');
  1309. const platformsToSend = groupPlatforms && groupPlatforms.style.display !== 'none' ? platforms : "";
  1310. const requestData = {
  1311. platforms: platformsToSend,
  1312. use_claude_sdk: checkSdk,
  1313. restart_mode: restart_mode,
  1314. phase: phase,
  1315. only_step: only_step,
  1316. start_from: start_from,
  1317. end_at: end_at
  1318. };
  1319. modalRun.classList.add('hidden');
  1320. // Optimistic UI update
  1321. const req = requirements.find(r => r.index === currentSelectedIndex);
  1322. if (req) req.status = 'running';
  1323. activeRuns[currentSelectedIndex] = { status: 'running', logs: ['Initializing request...'] };
  1324. renderTaskList(requirements);
  1325. updateDetailBannerStatus('running');
  1326. try {
  1327. const res = await fetch(`/api/pipeline/run/${currentSelectedIndex}`, {
  1328. method: 'POST',
  1329. headers: { 'Content-Type': 'application/json' },
  1330. body: JSON.stringify(requestData)
  1331. });
  1332. if (!res.ok) {
  1333. const err = await res.json();
  1334. alert("Error: " + err.detail);
  1335. }
  1336. } catch (e) {
  1337. console.error("Run failed", e);
  1338. alert("Failed to trigger run");
  1339. }
  1340. }
  1341. // Event Listeners
  1342. function setupEventListeners() {
  1343. // Global JSON Toggle
  1344. const globalJsonToggle = document.getElementById('global-json-toggle');
  1345. if (globalJsonToggle) {
  1346. globalJsonToggle.addEventListener('change', (e) => {
  1347. const isRaw = e.target.checked;
  1348. document.querySelectorAll('.data-view-ui').forEach(el => el.style.display = isRaw ? 'none' : '');
  1349. document.querySelectorAll('.data-view-raw').forEach(el => el.style.display = isRaw ? '' : 'none');
  1350. });
  1351. }
  1352. // Dropdown change
  1353. elReqSelector.addEventListener('change', (e) => {
  1354. const val = e.target.value;
  1355. if (val) {
  1356. selectRequirement(parseInt(val));
  1357. } else {
  1358. currentSelectedIndex = null;
  1359. elEmptyState.classList.remove('hidden');
  1360. elDetailView.classList.add('hidden');
  1361. }
  1362. });
  1363. // Refresh Data without changing page position
  1364. const btnRefresh = document.getElementById('btn-refresh-data');
  1365. if (btnRefresh) {
  1366. btnRefresh.addEventListener('click', async () => {
  1367. if (currentSelectedIndex === null) {
  1368. alert("请先选择一个需求项目!");
  1369. return;
  1370. }
  1371. const oldText = btnRefresh.innerHTML;
  1372. btnRefresh.innerHTML = '🔄 刷新中...';
  1373. btnRefresh.disabled = true;
  1374. const modalCaseDetail = document.getElementById('case-detail-modal');
  1375. const isModalOpen = modalCaseDetail && !modalCaseDetail.classList.contains('hidden');
  1376. const activeSidebarItem = document.querySelector('.modal-sidebar-item.active');
  1377. const activeCaseIdx = activeSidebarItem ? parseInt(activeSidebarItem.id.replace('sidebar-item-', '')) : null;
  1378. try {
  1379. await fetchRequirementData(currentSelectedIndex);
  1380. if (isModalOpen && activeCaseIdx !== null && typeof window.renderSingleCaseDetail === 'function') {
  1381. window.renderSingleCaseDetail(activeCaseIdx);
  1382. }
  1383. } catch (e) {
  1384. console.error("Failed to refresh data", e);
  1385. } finally {
  1386. btnRefresh.innerHTML = oldText;
  1387. btnRefresh.disabled = false;
  1388. }
  1389. });
  1390. }
  1391. // Tabs
  1392. document.querySelectorAll('.tab-btn-pill').forEach(btn => {
  1393. btn.addEventListener('click', () => {
  1394. document.querySelectorAll('.tab-btn-pill').forEach(b => b.classList.remove('active'));
  1395. document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
  1396. btn.classList.add('active');
  1397. document.getElementById(btn.dataset.target).classList.add('active');
  1398. });
  1399. });
  1400. // Modals
  1401. document.getElementById('btn-open-run-modal').addEventListener('click', async () => {
  1402. if (currentSelectedIndex !== null) {
  1403. modalRun.classList.remove('hidden');
  1404. const selectForcePhase = document.getElementById('select-force-phase');
  1405. if (selectForcePhase) selectForcePhase.dispatchEvent(new Event('change'));
  1406. const inputPlatforms = document.getElementById('input-platforms');
  1407. if (inputPlatforms && currentAvailablePlatforms && currentAvailablePlatforms.length > 0) {
  1408. inputPlatforms.value = currentAvailablePlatforms.join(',');
  1409. }
  1410. // Fetch status and render chain
  1411. await fetchAndRenderPipelineChain(currentSelectedIndex);
  1412. }
  1413. });
  1414. document.getElementById('btn-close-modal').addEventListener('click', () => {
  1415. modalRun.classList.add('hidden');
  1416. });
  1417. document.getElementById('btn-cancel-run').addEventListener('click', () => {
  1418. modalRun.classList.add('hidden');
  1419. });
  1420. const selectForcePhase = document.getElementById('select-force-phase');
  1421. const groupPlatforms = document.getElementById('group-platforms');
  1422. const chainContainer = document.getElementById('pipeline-chain-container');
  1423. if (selectForcePhase && groupPlatforms) {
  1424. selectForcePhase.addEventListener('change', (e) => {
  1425. const val = e.target.value;
  1426. if (['smart', 'phase1', 'step_1.1'].includes(val) || (val === 'custom_range' && chainStartNode === 'research')) {
  1427. groupPlatforms.style.display = 'block';
  1428. } else {
  1429. groupPlatforms.style.display = 'none';
  1430. }
  1431. if (val === 'custom_range') {
  1432. chainContainer.classList.remove('hidden');
  1433. } else {
  1434. chainContainer.classList.add('hidden');
  1435. }
  1436. });
  1437. }
  1438. document.getElementById('btn-reset-chain').addEventListener('click', () => {
  1439. chainStartNode = null;
  1440. chainEndNode = null;
  1441. renderPipelineChain();
  1442. });
  1443. // Add Requirement Modal Events
  1444. const modalAddReq = document.getElementById('add-req-modal');
  1445. const inputAddReq = document.getElementById('input-new-req');
  1446. document.getElementById('btn-add-req').addEventListener('click', () => {
  1447. inputAddReq.value = "";
  1448. modalAddReq.classList.remove('hidden');
  1449. });
  1450. document.getElementById('btn-close-add-req').addEventListener('click', () => {
  1451. modalAddReq.classList.add('hidden');
  1452. });
  1453. document.getElementById('btn-cancel-add-req').addEventListener('click', () => {
  1454. modalAddReq.classList.add('hidden');
  1455. });
  1456. document.getElementById('btn-submit-add-req').addEventListener('click', async () => {
  1457. const val = inputAddReq.value.trim();
  1458. if (!val) {
  1459. alert('需求内容不能为空');
  1460. return;
  1461. }
  1462. try {
  1463. const res = await fetch(`/api/requirements`, {
  1464. method: 'POST',
  1465. headers: { 'Content-Type': 'application/json' },
  1466. body: JSON.stringify({ requirement: val })
  1467. });
  1468. if (res.ok) {
  1469. modalAddReq.classList.add('hidden');
  1470. await fetchRequirements();
  1471. } else {
  1472. alert('添加失败');
  1473. }
  1474. } catch (e) {
  1475. console.error(e);
  1476. alert('网络错误');
  1477. }
  1478. });
  1479. const modalEditReq = document.getElementById('edit-req-modal');
  1480. const inputEditReq = document.getElementById('edit-req-textarea');
  1481. document.getElementById('btn-edit-req').addEventListener('click', () => {
  1482. if (currentSelectedIndex !== null) {
  1483. const req = requirements.find(r => r.index === currentSelectedIndex);
  1484. if (req) {
  1485. inputEditReq.value = req.requirement;
  1486. modalEditReq.classList.remove('hidden');
  1487. }
  1488. }
  1489. });
  1490. const closeEditReq = () => modalEditReq.classList.add('hidden');
  1491. document.getElementById('btn-close-edit-req').addEventListener('click', closeEditReq);
  1492. document.getElementById('btn-cancel-edit-req').addEventListener('click', closeEditReq);
  1493. const saveRequirementText = async (runAfter) => {
  1494. if (currentSelectedIndex === null) return;
  1495. const newText = inputEditReq.value.trim();
  1496. if (!newText) {
  1497. alert('需求文本不能为空');
  1498. return;
  1499. }
  1500. try {
  1501. const res = await fetch(`/api/requirements/${currentSelectedIndex}`, {
  1502. method: 'PUT',
  1503. headers: { 'Content-Type': 'application/json' },
  1504. body: JSON.stringify({ requirement: newText })
  1505. });
  1506. if (!res.ok) {
  1507. const err = await res.json();
  1508. alert('保存失败: ' + (err.detail || '未知错误'));
  1509. return;
  1510. }
  1511. // Update locally
  1512. const req = requirements.find(r => r.index === currentSelectedIndex);
  1513. if (req) {
  1514. req.requirement = newText;
  1515. renderTaskList(requirements);
  1516. }
  1517. closeEditReq();
  1518. if (runAfter) {
  1519. document.getElementById('btn-open-run-modal').click();
  1520. }
  1521. } catch (e) {
  1522. console.error(e);
  1523. alert('保存请求失败');
  1524. }
  1525. };
  1526. document.getElementById('btn-save-edit-req').addEventListener('click', () => saveRequirementText(false));
  1527. document.getElementById('btn-save-run-edit-req').addEventListener('click', () => saveRequirementText(true));
  1528. document.getElementById('btn-confirm-run').addEventListener('click', triggerRun);
  1529. document.getElementById('btn-view-logs').addEventListener('click', () => {
  1530. modalLogs.classList.remove('hidden');
  1531. if (activeRuns[currentSelectedIndex]) {
  1532. terminalLogs.textContent = activeRuns[currentSelectedIndex].logs.join('');
  1533. terminalLogs.scrollTop = terminalLogs.scrollHeight;
  1534. } else {
  1535. terminalLogs.textContent = 'No logs available.';
  1536. }
  1537. });
  1538. const btnStop = document.getElementById('btn-stop-pipeline');
  1539. if (btnStop) {
  1540. btnStop.addEventListener('click', async () => {
  1541. if (currentSelectedIndex === null) return;
  1542. if (!confirm('Are you sure you want to stop the running pipeline?')) return;
  1543. try {
  1544. const res = await fetch(`/api/pipeline/stop/${currentSelectedIndex}`, { method: 'POST' });
  1545. if (!res.ok) {
  1546. const err = await res.json();
  1547. alert("Error stopping pipeline: " + err.detail);
  1548. }
  1549. } catch (e) {
  1550. console.error("Failed to stop pipeline", e);
  1551. alert("Failed to stop pipeline");
  1552. }
  1553. });
  1554. }
  1555. document.getElementById('btn-close-logs').addEventListener('click', () => {
  1556. modalLogs.classList.add('hidden');
  1557. });
  1558. const btnOpenPrompts = document.getElementById('btn-open-prompts');
  1559. if (btnOpenPrompts) {
  1560. btnOpenPrompts.addEventListener('click', () => {
  1561. modalPrompts.classList.remove('hidden');
  1562. fetchPromptsList();
  1563. });
  1564. }
  1565. const btnClosePrompts = document.getElementById('btn-close-prompts');
  1566. if (btnClosePrompts) {
  1567. btnClosePrompts.addEventListener('click', () => {
  1568. modalPrompts.classList.add('hidden');
  1569. });
  1570. }
  1571. const btnSavePrompt = document.getElementById('btn-save-prompt');
  1572. if (btnSavePrompt) {
  1573. btnSavePrompt.addEventListener('click', async () => {
  1574. if (!currentPromptName) return;
  1575. elPromptStatus.textContent = 'Saving...';
  1576. elPromptStatus.style.color = 'var(--text-muted)';
  1577. try {
  1578. const reqBody = { content: elPromptTextarea.value };
  1579. if (elSchemaTextarea) reqBody.schema_content = elSchemaTextarea.value;
  1580. const res = await fetch(`/api/prompts/${currentPromptName}`, {
  1581. method: 'POST',
  1582. headers: { 'Content-Type': 'application/json' },
  1583. body: JSON.stringify(reqBody)
  1584. });
  1585. if (res.ok) {
  1586. elPromptStatus.textContent = 'Saved!';
  1587. elPromptStatus.style.color = 'var(--success)';
  1588. setTimeout(() => elPromptStatus.textContent = '', 2000);
  1589. } else {
  1590. const errData = await res.json();
  1591. throw new Error(errData.detail || "Failed to save");
  1592. }
  1593. } catch (e) {
  1594. elPromptStatus.textContent = e.message || 'Save failed';
  1595. elPromptStatus.style.color = 'var(--danger)';
  1596. }
  1597. });
  1598. }
  1599. const btnUpdateSchema = document.getElementById('update-schema-btn');
  1600. if (btnUpdateSchema) {
  1601. btnUpdateSchema.addEventListener('click', async () => {
  1602. if (!currentPromptName) return;
  1603. const originalText = btnUpdateSchema.innerHTML;
  1604. btnUpdateSchema.innerHTML = '<span style="font-size: 1.1em;">⏳</span> 更新中...';
  1605. btnUpdateSchema.disabled = true;
  1606. try {
  1607. // First save the prompt so the backend reads the latest content
  1608. const reqBody = { content: elPromptTextarea.value };
  1609. if (elSchemaTextarea) reqBody.schema_content = elSchemaTextarea.value;
  1610. let res = await fetch(`/api/prompts/${currentPromptName}`, {
  1611. method: 'POST',
  1612. headers: { 'Content-Type': 'application/json' },
  1613. body: JSON.stringify(reqBody)
  1614. });
  1615. if (!res.ok) {
  1616. const errData = await res.json();
  1617. throw new Error(errData.detail || "保存 Prompt 失败");
  1618. }
  1619. // Then call the schema update API
  1620. res = await fetch(`/api/prompts/${currentPromptName}/update_schema`, {
  1621. method: 'POST'
  1622. });
  1623. if (res.ok) {
  1624. const data = await res.json();
  1625. if (elSchemaTextarea && data.schema_content) {
  1626. elSchemaTextarea.value = data.schema_content;
  1627. }
  1628. btnUpdateSchema.innerHTML = '<span style="font-size: 1.1em;">✅</span> 更新成功';
  1629. setTimeout(() => {
  1630. btnUpdateSchema.innerHTML = originalText;
  1631. btnUpdateSchema.disabled = false;
  1632. }, 2000);
  1633. } else {
  1634. const errData = await res.json();
  1635. throw new Error(errData.detail || "更新 Schema 失败");
  1636. }
  1637. } catch (e) {
  1638. alert(e.message || '更新失败');
  1639. btnUpdateSchema.innerHTML = '<span style="font-size: 1.1em;">❌</span> 失败';
  1640. setTimeout(() => {
  1641. btnUpdateSchema.innerHTML = originalText;
  1642. btnUpdateSchema.disabled = false;
  1643. }, 2000);
  1644. }
  1645. });
  1646. }
  1647. }
  1648. // Boot
  1649. // ----------------------------------------------------
  1650. // Pipeline Chain Visualization Logic
  1651. // ----------------------------------------------------
  1652. async function fetchAndRenderPipelineChain(index) {
  1653. try {
  1654. const res = await fetch(`/api/requirements/${index}/pipeline-status`);
  1655. if (res.ok) {
  1656. currentPipelineStatus = await res.json();
  1657. } else {
  1658. currentPipelineStatus = {};
  1659. }
  1660. } catch (e) {
  1661. console.error("Failed to fetch pipeline status", e);
  1662. currentPipelineStatus = {};
  1663. }
  1664. chainStartNode = null;
  1665. chainEndNode = null;
  1666. renderPipelineChain();
  1667. }
  1668. function bindPipelineChainEvents() {
  1669. PIPELINE_STEPS.forEach((step) => {
  1670. const node = document.getElementById('node-' + step.id);
  1671. if (!node) return;
  1672. node.addEventListener('click', () => {
  1673. if (!chainStartNode) {
  1674. chainStartNode = step.id;
  1675. } else if (!chainEndNode) {
  1676. if (chainStartNode === step.id) {
  1677. chainEndNode = step.id; // Double click = single step mode
  1678. } else {
  1679. chainEndNode = step.id;
  1680. }
  1681. } else {
  1682. chainStartNode = step.id; // Reset and start new
  1683. chainEndNode = null;
  1684. }
  1685. renderPipelineChain();
  1686. // Toggle platforms group if research is selected
  1687. const groupPlatforms = document.getElementById('group-platforms');
  1688. if (groupPlatforms && document.getElementById('select-force-phase').value === 'custom_range') {
  1689. const startIndex = PIPELINE_STEPS.findIndex(s => s.id === chainStartNode);
  1690. const endIndex = chainEndNode ? PIPELINE_STEPS.findIndex(s => s.id === chainEndNode) : startIndex;
  1691. const finalStart = Math.min(startIndex, endIndex);
  1692. const finalEnd = Math.max(startIndex, endIndex);
  1693. if (finalStart === 0) { // 'research' is index 0
  1694. groupPlatforms.style.display = 'block';
  1695. } else {
  1696. groupPlatforms.style.display = 'none';
  1697. }
  1698. }
  1699. });
  1700. });
  1701. }
  1702. function renderPipelineChain() {
  1703. if (chainStartNode && chainEndNode) {
  1704. const startIndex = PIPELINE_STEPS.findIndex(s => s.id === chainStartNode);
  1705. const endIndex = PIPELINE_STEPS.findIndex(s => s.id === chainEndNode);
  1706. if (endIndex < startIndex) {
  1707. const tempId = chainStartNode;
  1708. chainStartNode = chainEndNode;
  1709. chainEndNode = tempId;
  1710. }
  1711. }
  1712. const LINEAR_PREFIX = ["research", "source", "generate-case", "workflow-extract", "apply-grounding"];
  1713. const BRANCH_21 = ["process-cluster", "process-score"];
  1714. const BRANCH_22 = ["capability-extract", "capability-enrich"];
  1715. const STRATEGY = "strategy";
  1716. let activeSteps = new Set();
  1717. if (chainStartNode && !chainEndNode) {
  1718. activeSteps.add(chainStartNode);
  1719. } else if (chainStartNode && chainEndNode) {
  1720. const start = chainStartNode;
  1721. const end = chainEndNode;
  1722. const start_in_linear = LINEAR_PREFIX.includes(start);
  1723. const start_in_21 = BRANCH_21.includes(start);
  1724. const start_in_22 = BRANCH_22.includes(start);
  1725. const end_in_linear = LINEAR_PREFIX.includes(end);
  1726. const end_in_21 = BRANCH_21.includes(end);
  1727. const end_in_22 = BRANCH_22.includes(end);
  1728. const end_is_strategy = end === STRATEGY;
  1729. // 1. Linear Prefix
  1730. LINEAR_PREFIX.forEach(s => {
  1731. const s_idx = LINEAR_PREFIX.indexOf(s);
  1732. const start_idx = LINEAR_PREFIX.indexOf(start);
  1733. if (start_idx >= 0 && s_idx >= start_idx) {
  1734. if (end_in_linear) {
  1735. if (s_idx <= LINEAR_PREFIX.indexOf(end)) activeSteps.add(s);
  1736. } else {
  1737. activeSteps.add(s);
  1738. }
  1739. }
  1740. });
  1741. // 2. Branches
  1742. if (end_is_strategy || (!end_in_21 && !end_in_22 && !end_in_linear)) {
  1743. if (!start_in_21 && !start_in_22) {
  1744. BRANCH_21.forEach(s => activeSteps.add(s));
  1745. BRANCH_22.forEach(s => activeSteps.add(s));
  1746. } else if (start_in_21) {
  1747. const idx = BRANCH_21.indexOf(start);
  1748. BRANCH_21.slice(idx).forEach(s => activeSteps.add(s));
  1749. BRANCH_22.forEach(s => activeSteps.add(s));
  1750. } else if (start_in_22) {
  1751. const idx = BRANCH_22.indexOf(start);
  1752. BRANCH_22.slice(idx).forEach(s => activeSteps.add(s));
  1753. BRANCH_21.forEach(s => activeSteps.add(s));
  1754. }
  1755. } else if (end_in_21) {
  1756. const end_idx = BRANCH_21.indexOf(end);
  1757. const start_idx = start_in_21 ? BRANCH_21.indexOf(start) : 0;
  1758. BRANCH_21.slice(start_idx, end_idx + 1).forEach(s => activeSteps.add(s));
  1759. } else if (end_in_22) {
  1760. const end_idx = BRANCH_22.indexOf(end);
  1761. const start_idx = start_in_22 ? BRANCH_22.indexOf(start) : 0;
  1762. BRANCH_22.slice(start_idx, end_idx + 1).forEach(s => activeSteps.add(s));
  1763. }
  1764. // 3. Strategy
  1765. if (end_is_strategy) {
  1766. activeSteps.add("strategy");
  1767. }
  1768. }
  1769. PIPELINE_STEPS.forEach((step) => {
  1770. const node = document.getElementById('node-' + step.id);
  1771. if (!node) return;
  1772. node.className = 'chain-node';
  1773. if (currentPipelineStatus[step.id]) {
  1774. node.classList.add('completed');
  1775. } else {
  1776. node.classList.add('missing');
  1777. }
  1778. if (activeSteps.has(step.id)) {
  1779. if ((chainStartNode && !chainEndNode) || step.id === chainStartNode || step.id === chainEndNode) {
  1780. node.classList.add('selected');
  1781. } else {
  1782. node.classList.add('selected-range');
  1783. }
  1784. }
  1785. });
  1786. }
  1787. bindPipelineChainEvents();
  1788. // Case Detail Modal Listeners
  1789. const btnCloseCaseDetail = document.getElementById('btn-close-case-detail');
  1790. const modalCaseDetail = document.getElementById('case-detail-modal');
  1791. if (btnCloseCaseDetail && modalCaseDetail) {
  1792. btnCloseCaseDetail.addEventListener('click', () => {
  1793. modalCaseDetail.classList.add('hidden');
  1794. });
  1795. // Close on escape
  1796. document.addEventListener('keydown', (e) => {
  1797. if (e.key === 'Escape' && !modalCaseDetail.classList.contains('hidden')) {
  1798. modalCaseDetail.classList.add('hidden');
  1799. }
  1800. });
  1801. // Close on click outside
  1802. modalCaseDetail.addEventListener('click', (e) => {
  1803. if (e.target === modalCaseDetail) {
  1804. modalCaseDetail.classList.add('hidden');
  1805. }
  1806. });
  1807. }
  1808. window.openCaseDetail = function (p, initialIdx) {
  1809. if (!window._currentRawCasesContext) return;
  1810. const ctx = window._currentRawCasesContext;
  1811. // Determine the list of platforms to aggregate.
  1812. let platformsToAggregate = [p];
  1813. if (p !== 'filtered_cases' && p !== 'source_ex') {
  1814. const crawlerPlatforms = Object.keys(ctx.rawCasesObj).filter(k => k !== 'source' && k !== 'case_detailed' && k !== 'case' && k !== 'images' && k !== 'filtered_cases' && k !== 'source_ex');
  1815. platformsToAggregate = [...crawlerPlatforms, 'source'];
  1816. }
  1817. let casesList = [];
  1818. let globalInitialIdx = 0;
  1819. const seenIds = new Set();
  1820. platformsToAggregate.forEach(plat => {
  1821. if (!ctx.rawCasesObj[plat]) return;
  1822. let platCases = [];
  1823. if (Array.isArray(ctx.rawCasesObj[plat])) {
  1824. platCases = ctx.rawCasesObj[plat];
  1825. } else if (ctx.rawCasesObj[plat].cases) {
  1826. platCases = ctx.rawCasesObj[plat].cases;
  1827. } else if (ctx.rawCasesObj[plat].sources) {
  1828. platCases = ctx.rawCasesObj[plat].sources;
  1829. } else if (ctx.rawCasesObj[plat].by_reason) {
  1830. Object.entries(ctx.rawCasesObj[plat].by_reason).forEach(([reasonKey, reasonObj]) => {
  1831. if (reasonObj.sources && Array.isArray(reasonObj.sources)) {
  1832. reasonObj.sources.forEach(src => {
  1833. if (!src.filter_reason) src.filter_reason = reasonKey;
  1834. platCases.push(src);
  1835. });
  1836. }
  1837. });
  1838. }
  1839. platCases.forEach((c, idx) => {
  1840. const cId = c.case_id || (c._raw && c._raw.case_id) || (c.post && c.post.channel_content_id) || `temp_${plat}_${idx}`;
  1841. const cUrl = c.source_url || c.url || (c.post && c.post.link) || '';
  1842. const mappedS = ctx.sourceMap[cId] || ctx.sourceMap[cUrl] || (c._raw && ctx.sourceMap[c._raw.case_id]);
  1843. if (plat !== 'filtered_cases' && plat !== 'source' && plat !== 'source_ex' && !mappedS) return;
  1844. if (seenIds.has(cId)) return;
  1845. seenIds.add(cId);
  1846. const augmentedC = { ...c, _actualPlatform: plat };
  1847. if (plat === p && idx === initialIdx) {
  1848. globalInitialIdx = casesList.length;
  1849. }
  1850. casesList.push(augmentedC);
  1851. });
  1852. });
  1853. window._currentModalCases = casesList;
  1854. window._currentModalPlatform = p;
  1855. window._currentModalContext = ctx;
  1856. window._currentModalIdx = globalInitialIdx;
  1857. // Build Sidebar
  1858. let sidebarHtml = '<div class="modal-sidebar">';
  1859. casesList.forEach((c, idx) => {
  1860. const cId = c.case_id || (c._raw && c._raw.case_id) || (c.post && c.post.channel_content_id) || `temp_${idx}`;
  1861. const cUrl = c.source_url || c.url || (c.post && c.post.link) || '';
  1862. const mappedS = ctx.sourceMap[cId] || ctx.sourceMap[cUrl] || (c._raw && ctx.sourceMap[c._raw.case_id]);
  1863. const s = mappedS || c;
  1864. const post = s.post || s || {};
  1865. const title = post.title || c.title || '无标题';
  1866. let metaHtml = '';
  1867. const wf = ctx.detailMap[cId] || (cUrl ? ctx.detailMapByUrl[cUrl] : null) || c;
  1868. if (wf && wf.workflow && wf.workflow.steps) metaHtml += `<span>工序 ${wf.workflow.steps.length}</span>`;
  1869. if (wf && wf.capability) metaHtml += `<span>能力 ${wf.capability.length}</span>`;
  1870. if (!metaHtml) metaHtml = '<span>无提取</span>';
  1871. sidebarHtml += `<div class="modal-sidebar-item ${idx === globalInitialIdx ? 'active' : ''}" id="sidebar-item-${idx}" onclick="window.renderSingleCaseDetail(${idx})">
  1872. <div class="sidebar-item-index">${idx + 1}.</div>
  1873. <div class="sidebar-item-content">
  1874. <div class="sidebar-item-title">${title}</div>
  1875. <div class="sidebar-item-meta">${metaHtml}</div>
  1876. </div>
  1877. </div>`;
  1878. });
  1879. sidebarHtml += '</div>';
  1880. // Build Main Content Skeleton
  1881. const mainHtml = `
  1882. <div class="modal-main-content">
  1883. <div id="modal-main-header" style="padding: 1.5rem 1.5rem 0 1.5rem; flex-shrink: 0;"></div>
  1884. <div class="modal-main-scrollable" id="modal-main-scrollable"></div>
  1885. </div>
  1886. `;
  1887. document.getElementById('case-detail-modal-body').innerHTML = sidebarHtml + mainHtml;
  1888. // Render the selected case
  1889. window.renderSingleCaseDetail(globalInitialIdx);
  1890. document.getElementById('case-detail-modal').classList.remove('hidden');
  1891. // Scroll sidebar to active item
  1892. setTimeout(() => {
  1893. const activeItem = document.getElementById(`sidebar-item-${globalInitialIdx}`);
  1894. if (activeItem) activeItem.scrollIntoView({ block: 'nearest' });
  1895. }, 10);
  1896. };
  1897. window.renderSingleCaseDetail = function (idx) {
  1898. window._currentModalIdx = idx;
  1899. const ctx = window._currentModalContext;
  1900. const c = window._currentModalCases[idx];
  1901. if (!c) return;
  1902. // Update Sidebar Active State
  1903. document.querySelectorAll('.modal-sidebar-item').forEach(el => el.classList.remove('active'));
  1904. const activeEl = document.getElementById(`sidebar-item-${idx}`);
  1905. if (activeEl) activeEl.classList.add('active');
  1906. const p = c._actualPlatform || window._currentModalPlatform;
  1907. const platCode = p.replace('case_', '');
  1908. const cId = c.case_id || (c._raw && c._raw.case_id) || (c.post && c.post.channel_content_id) || `temp_${idx}`;
  1909. const cUrl = c.source_url || c.url || (c.post && c.post.link) || '';
  1910. const mappedS = ctx.sourceMap[cId] || ctx.sourceMap[cUrl] || (c._raw && ctx.sourceMap[c._raw.case_id]);
  1911. const s = mappedS || c;
  1912. const post = s.post || s || {};
  1913. const platformName = s.platform || (s._raw && s._raw.platform) || platCode;
  1914. const title = post.title || c.title || '无标题';
  1915. const workflowUrl = s.source_url || s.url || cUrl;
  1916. const publishedTime = post.publish_timestamp || post.published_at || '-';
  1917. const likeCount = post.like_count !== undefined ? post.like_count : (post.likes !== undefined ? post.likes : '-');
  1918. const collectCount = post.collect_count !== undefined ? post.collect_count : (post.collects !== undefined ? post.collects : '-');
  1919. const commentCount = post.comment_count !== undefined ? post.comment_count : (post.comments !== undefined ? post.comments : '-');
  1920. const shareCount = post.share_count !== undefined ? post.share_count : (post.shares !== undefined ? post.shares : '-');
  1921. const isFiltered = (c._actualPlatform === 'filtered_cases');
  1922. let filterActionHtml = '';
  1923. if (isFiltered) {
  1924. filterActionHtml = `<button onclick="window.toggleCaseFilter('${cId}', true)" style="padding: 6px 12px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 0.9em; font-weight: bold; margin-left: auto;">↩️ 恢复至总库</button>`;
  1925. } else {
  1926. filterActionHtml = `<button onclick="window.toggleCaseFilter('${cId}', false)" style="padding: 6px 12px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 0.9em; font-weight: bold; margin-left: auto;">🗑️ 移至被过滤</button>`;
  1927. }
  1928. const headerHtml = `
  1929. <div style="display:flex; justify-content: space-between; align-items: flex-start; gap: 1rem;">
  1930. <h2 style="margin: 0 0 0.5rem 0; font-size: 1.4em; color: var(--text-main); flex: 1;">${title}</h2>
  1931. ${filterActionHtml}
  1932. </div>
  1933. <div style="display: flex; gap: 12px; margin-bottom: 0.8rem;">
  1934. ${workflowUrl ? `<a href="${workflowUrl}" target="_blank" style="color: var(--accent-primary); text-decoration: none; font-size: 0.9em;">原文 ↗</a>` : ''}
  1935. <span style="color: var(--text-muted); font-size: 0.9em;">平台: ${platformName}</span>
  1936. </div>
  1937. <div style="display: flex; gap: 10px; margin-bottom: 1rem; flex-wrap: wrap;">
  1938. <div style="display: flex; flex-direction: column; background: rgba(0,0,0,0.02); border: 1px solid rgba(0,0,0,0.06); padding: 4px 10px; border-radius: 6px;">
  1939. <span style="font-size: 0.7em; color: var(--text-muted); text-transform: uppercase;">Published</span>
  1940. <span style="font-size: 0.9rem; font-weight: 500; color: var(--text-main);">${publishedTime}</span>
  1941. </div>
  1942. <div style="display: flex; flex-direction: column; background: rgba(0,0,0,0.02); border: 1px solid rgba(0,0,0,0.06); padding: 4px 10px; border-radius: 6px;">
  1943. <span style="font-size: 0.7em; color: var(--text-muted); text-transform: uppercase;">Likes</span>
  1944. <span style="font-size: 0.9rem; font-weight: 500; color: var(--text-main);">${likeCount}</span>
  1945. </div>
  1946. <div style="display: flex; flex-direction: column; background: rgba(0,0,0,0.02); border: 1px solid rgba(0,0,0,0.06); padding: 4px 10px; border-radius: 6px;">
  1947. <span style="font-size: 0.7em; color: var(--text-muted); text-transform: uppercase;">Collects</span>
  1948. <span style="font-size: 0.9rem; font-weight: 500; color: var(--text-main);">${collectCount}</span>
  1949. </div>
  1950. <div style="display: flex; flex-direction: column; background: rgba(0,0,0,0.02); border: 1px solid rgba(0,0,0,0.06); padding: 4px 10px; border-radius: 6px;">
  1951. <span style="font-size: 0.7em; color: var(--text-muted); text-transform: uppercase;">Comments</span>
  1952. <span style="font-size: 0.9rem; font-weight: 500; color: var(--text-main);">${commentCount}</span>
  1953. </div>
  1954. <div style="display: flex; flex-direction: column; background: rgba(0,0,0,0.02); border: 1px solid rgba(0,0,0,0.06); padding: 4px 10px; border-radius: 6px;">
  1955. <span style="font-size: 0.7em; color: var(--text-muted); text-transform: uppercase;">Shares</span>
  1956. <span style="font-size: 0.9rem; font-weight: 500; color: var(--text-main);">${shareCount}</span>
  1957. </div>
  1958. </div>
  1959. `;
  1960. document.getElementById('modal-main-header').innerHTML = headerHtml;
  1961. // Media & Body
  1962. let mediaHtml = '';
  1963. const images = post.images || [];
  1964. const xImages = post.image_url_list || [];
  1965. const ytThumbnails = post.thumbnails && post.thumbnails.length > 0 ? [post.thumbnails[post.thumbnails.length - 1].url] : [];
  1966. const allImages = [...images, ...xImages.map(img => img.image_url), ...ytThumbnails].filter(Boolean);
  1967. if (allImages.length > 0) {
  1968. mediaHtml += `<div class="image-gallery" style="margin-bottom: 1rem;">`;
  1969. allImages.forEach((imgUrl, imgIdx) => {
  1970. const localPath = `/output/${ctx.reqId}/raw_cases/images/${cId}/${String(imgIdx).padStart(2, '0')}.jpg`;
  1971. mediaHtml += `<div class="image-item" style="cursor:pointer" onclick="window.open(this.querySelector('img').src, '_blank')">
  1972. <img src="${localPath}" onerror="this.onerror=null; this.src='${imgUrl}';">
  1973. </div>`;
  1974. });
  1975. mediaHtml += `</div>`;
  1976. }
  1977. const videos = post.videos || [];
  1978. const xVideos = post.video_url_list || [];
  1979. const allVideos = [...videos, ...xVideos.map(vid => vid.video_url)].filter(Boolean);
  1980. if (allVideos.length > 0) {
  1981. mediaHtml += `<div style="display:flex; flex-wrap:wrap; gap:8px; margin-bottom: 1rem;">`;
  1982. allVideos.forEach(vidUrl => {
  1983. mediaHtml += `<video controls src="${vidUrl}" style="height: 200px; border-radius: 6px; border: 1px solid rgba(0, 0, 0, 0.1);"></video>`;
  1984. });
  1985. mediaHtml += `</div>`;
  1986. }
  1987. const bodyText = post.body_text || post.body || '';
  1988. // Source Panel
  1989. let mainScrollableHtml = `
  1990. <div class="source-panel open" id="source-panel">
  1991. <div class="source-panel-header" onclick="document.getElementById('source-panel').classList.toggle('open')">
  1992. <span>原始内容 / SOURCE POSTS</span>
  1993. <span style="font-size: 0.8em; color: var(--text-muted);">点击展开/折叠</span>
  1994. </div>
  1995. <div class="source-panel-body">
  1996. ${mediaHtml}
  1997. ${bodyText ? `<div style="font-size:0.9rem; line-height:1.6; color:var(--text-main); white-space: pre-wrap;">${bodyText}</div>` : '<div style="color:var(--text-muted)">无正文</div>'}
  1998. </div>
  1999. </div>
  2000. `;
  2001. // Evaluation Panel
  2002. if (s.evaluation && Object.keys(s.evaluation).length > 0) {
  2003. const renderEvalNode = (node, indent = 0) => {
  2004. let html = '';
  2005. if (typeof node === 'object' && node !== null) {
  2006. Object.entries(node).forEach(([k, v]) => {
  2007. html += `<div style="display: flex; flex-direction: column; padding-left: ${indent}px; margin-bottom: 8px;">
  2008. <span style="color: var(--text-muted); font-size: 0.85rem; font-weight: bold; text-transform: uppercase;">${k.replace(/_/g, ' ')}</span>`;
  2009. if (typeof v === 'object' && v !== null) {
  2010. html += `<div style="margin-top: 4px; border-left: 2px solid rgba(0,0,0,0.1); padding-left: 8px;">${renderEvalNode(v, 0)}</div>`;
  2011. } else {
  2012. const valColor = typeof v === 'number' ? '#3b82f6' : 'var(--text-main)';
  2013. html += `<span style="font-weight: 500; font-size: 0.95rem; color: ${valColor}; margin-top: 2px;">${String(v).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</span>`;
  2014. }
  2015. html += `</div>`;
  2016. });
  2017. }
  2018. return html;
  2019. };
  2020. mainScrollableHtml += `
  2021. <div class="case-section" style="margin-top: 1rem;">
  2022. <div style="background: rgba(0,0,0,0.02); border: 1px solid rgba(0,0,0,0.05); border-radius: 8px; padding: 1rem;">
  2023. <h3 style="margin: 0 0 1rem 0; color: var(--text-main); font-size: 1.1rem; display: flex; align-items: center; gap: 10px;">
  2024. <span style="color: #10b981;">📊</span> 质量评估 (Evaluation)
  2025. </h3>
  2026. <div style="display: flex; flex-direction: column; gap: 4px;">
  2027. ${renderEvalNode(s.evaluation)}
  2028. </div>
  2029. </div>
  2030. </div>`;
  2031. }
  2032. // Extracted Data
  2033. const wf = ctx.detailMap[cId] || (workflowUrl ? ctx.detailMapByUrl[workflowUrl] : null) || c;
  2034. const detailedCaseObj = ctx.rawCasesObj['case'] || ctx.rawCasesObj['case_detailed'];
  2035. const caseJsonCases = (detailedCaseObj && detailedCaseObj.cases) || [];
  2036. const realCaseIndex = caseJsonCases.findIndex(jc =>
  2037. (jc.case_id === cId) ||
  2038. (jc._raw && jc._raw.case_id === cId) ||
  2039. (jc.post && jc.post.channel_content_id === cId)
  2040. );
  2041. const caseIndexToPass = realCaseIndex >= 0 ? (caseJsonCases[realCaseIndex].index || (realCaseIndex + 1)) : -1;
  2042. const btnWorkflowHtml = caseIndexToPass !== -1 ? `<button class="btn btn-secondary" style="font-size: 0.8em; padding: 0.3rem 0.6rem; border-radius: 4px;" onclick="event.stopPropagation(); triggerSingleCaseRerun('workflow-extract', ${caseIndexToPass})">🔄 重跑工序</button>` : '';
  2043. const btnCapabilityHtml = caseIndexToPass !== -1 ? `<button class="btn btn-secondary" style="font-size: 0.8em; padding: 0.3rem 0.6rem; border-radius: 4px;" onclick="event.stopPropagation(); triggerSingleCaseRerun('workflow-extract', ${caseIndexToPass})">🔄 重跑能力</button>` : '';
  2044. mainScrollableHtml += `
  2045. <div class="case-section" style="margin-top: 2rem;">
  2046. <div style="display: flex; align-items: center; justify-content: space-between; background: rgba(0,0,0,0.02); border-radius: 8px; padding-right: 1rem; cursor: pointer;" onclick="const content = this.nextElementSibling; content.classList.toggle('hidden'); this.querySelector('.case-arrow').textContent = content.classList.contains('hidden') ? '▶' : '▼';">
  2047. <h3 style="margin: 0; padding: 1rem; color: var(--text-main); font-size: 1.1rem; display: flex; align-items: center; gap: 10px; user-select: none;">
  2048. <span class="case-arrow" style="font-size: 0.8em; color: var(--text-muted); width: 16px; display: inline-block;">▶</span>
  2049. <span style="color: var(--accent-primary);">⚡</span> 提取的工序 (Strategy)
  2050. </h3>
  2051. ${btnWorkflowHtml}
  2052. </div>
  2053. <div class="hidden" style="padding-top: 1.2rem;">
  2054. ${window.renderStructuredData(wf && wf.workflow ? [wf.workflow] : null, 'workflow', wf)}
  2055. </div>
  2056. </div>
  2057. <div class="case-section" style="margin-top: 1rem; margin-bottom: 2rem;">
  2058. <div style="display: flex; align-items: center; justify-content: space-between; background: rgba(0,0,0,0.02); border-radius: 8px; padding-right: 1rem; cursor: pointer;" onclick="const content = this.nextElementSibling; content.classList.toggle('hidden'); this.querySelector('.case-arrow').textContent = content.classList.contains('hidden') ? '▶' : '▼';">
  2059. <h3 style="margin: 0; padding: 1rem; color: var(--text-main); font-size: 1.1rem; display: flex; align-items: center; gap: 10px; user-select: none;">
  2060. <span class="case-arrow" style="font-size: 0.8em; color: var(--text-muted); width: 16px; display: inline-block;">▶</span>
  2061. <span style="color: var(--accent-secondary);">✨</span> 提取的能力 (Capability)
  2062. </h3>
  2063. ${btnCapabilityHtml}
  2064. </div>
  2065. <div class="hidden" style="padding-top: 1.2rem;">
  2066. ${window.renderStructuredData(wf && wf.capability ? wf.capability : null, 'capabilities', wf)}
  2067. </div>
  2068. </div>
  2069. `;
  2070. document.getElementById('modal-main-scrollable').innerHTML = mainScrollableHtml;
  2071. };
  2072. window.switchDetailTab = function (tabId) {
  2073. document.querySelectorAll('.detail-tab-btn').forEach(btn => btn.classList.remove('active'));
  2074. document.querySelectorAll('.detail-tab-content').forEach(content => content.style.display = 'none');
  2075. document.getElementById(`tab-btn-${tabId}`).classList.add('active');
  2076. document.getElementById(`tab-content-${tabId}`).style.display = 'block';
  2077. };
  2078. window.renderStructuredData = function (items, type, parentItem = null) {
  2079. if (!items || items.length === 0) {
  2080. return `<div style="color:var(--text-muted); padding: 1rem;">暂无${type === 'workflow' ? '工序' : '能力'}数据</div>`;
  2081. }
  2082. const formatIOs = (ios) => {
  2083. if (!ios || !Array.isArray(ios) || ios.length === 0) return '';
  2084. const escapeHtml = (s) => String(s).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2085. return ios.map(io => {
  2086. const desc = escapeHtml(io.description || io.role || '未知');
  2087. const mod = escapeHtml(io.modality || '未知');
  2088. return `${desc}[${mod}]`;
  2089. }).join(' + ');
  2090. };
  2091. const buildFullTitle = (inputs, outputs, actionStr, fallbackTitle) => {
  2092. const escapeHtml = (s) => String(s).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2093. const inStr = formatIOs(inputs) || '无';
  2094. const outStr = formatIOs(outputs) || '无';
  2095. let parts = [];
  2096. parts.push(inStr);
  2097. if (actionStr) parts.push(`<strong>${escapeHtml(actionStr)}</strong>`);
  2098. parts.push(outStr);
  2099. return parts.join(' ➔ ');
  2100. };
  2101. let html = '';
  2102. items.forEach((item, idx) => {
  2103. let title = '';
  2104. const hasValidIO = (arr) => Array.isArray(arr) && arr.length > 0 && (arr[0].role || arr[0].description);
  2105. if (hasValidIO(item.inputs) || hasValidIO(item.outputs) || (item.steps && item.steps.length > 0)) {
  2106. let actionStr = '';
  2107. if (item.action && item.action.description) {
  2108. actionStr = item.action.description;
  2109. } else if (item.method && !item.method.includes('[')) {
  2110. actionStr = item.method;
  2111. } else if (item.steps && Array.isArray(item.steps)) {
  2112. const hasAnyValidIO = item.steps.some(s => hasValidIO(s.inputs) || hasValidIO(s.outputs) || s.body);
  2113. if (hasAnyValidIO) {
  2114. actionStr = item.steps.map(s => {
  2115. if (s.action && s.action.description) {
  2116. return s.action.description;
  2117. }
  2118. if (s.body) return s.body.length > 20 ? s.body.substring(0, 20) + '...' : s.body;
  2119. if (s.method) return s.method;
  2120. if (s.phase) return s.phase;
  2121. return '未知';
  2122. }).join(' ➔ ');
  2123. } else {
  2124. actionStr = item.method || item.name || type === 'workflow' ? '工作流' : `节点 ${idx + 1}`;
  2125. }
  2126. }
  2127. if (hasValidIO(item.inputs) || hasValidIO(item.outputs)) {
  2128. title = buildFullTitle(item.inputs, item.outputs, actionStr, item.method || item.name || `节点 ${idx + 1}`);
  2129. } else {
  2130. title = String(actionStr).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2131. }
  2132. } else {
  2133. const escapeHtml = (s) => String(s).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2134. title = escapeHtml(item.method || item.name || '');
  2135. if (!title && item.action && item.action.description) {
  2136. title = escapeHtml(item.action.description);
  2137. }
  2138. if (!title && item.body) {
  2139. const actText = item.body.length > 50 ? item.body.substring(0, 50) + '...' : item.body;
  2140. title = escapeHtml(actText);
  2141. }
  2142. if (!title) {
  2143. title = escapeHtml(type === 'workflow' ? '工作流' : `节点 ${idx + 1}`);
  2144. }
  2145. }
  2146. // Tree node tags (from apply_to keys) or unstructured_what fallback
  2147. const getApplyToField = (it) => {
  2148. if (it.apply_to_grounding) return { key: 'apply_to_grounding', val: it.apply_to_grounding, suggest: it.suggest_apply_to };
  2149. if (it.apply_to_draft) return { key: 'apply_to_draft', val: it.apply_to_draft, suggest: null };
  2150. if (it.apply_to) return { key: 'apply_to', val: it.apply_to, suggest: it.suggest_apply_to };
  2151. return null;
  2152. };
  2153. const applyToData = getApplyToField(item);
  2154. let treeNodeTags = '';
  2155. if (applyToData && typeof applyToData.val === 'object') {
  2156. const allLeafs = [];
  2157. Object.values(applyToData.val).forEach(v => {
  2158. if (Array.isArray(v)) {
  2159. v.forEach(pathObj => {
  2160. let leaf = '';
  2161. if (typeof pathObj === 'object' && pathObj !== null) {
  2162. if (pathObj.element) leaf = pathObj.element;
  2163. else if (pathObj.category_path || pathObj.path) {
  2164. leaf = (pathObj.category_path || pathObj.path).split('/').pop();
  2165. }
  2166. } else {
  2167. leaf = String(pathObj).split('/').pop();
  2168. }
  2169. if (leaf) allLeafs.push(leaf);
  2170. });
  2171. }
  2172. });
  2173. const uniqueLeafs = [...new Set(allLeafs)];
  2174. const badgeStyle = 'background: #f8fafc; color: #475569; border: 1px solid #cbd5e1; border-radius: 12px; padding: 2px 10px; font-size: 0.85em; font-weight: normal; margin-right: 6px; display: inline-block; white-space: nowrap;';
  2175. treeNodeTags = uniqueLeafs.map(leaf => `<span class="unstruct-badge" style="${badgeStyle}">${leaf.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</span>`).join('');
  2176. } else if (item.unstructured_what && Array.isArray(item.unstructured_what)) {
  2177. const badgeStyle = 'background: #f8fafc; color: #475569; border: 1px solid #cbd5e1; border-radius: 12px; padding: 2px 10px; font-size: 0.85em; font-weight: normal; margin-right: 6px; display: inline-block; white-space: nowrap;';
  2178. treeNodeTags = item.unstructured_what.map(t => `<span class="unstruct-badge" style="${badgeStyle}">${String(t).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</span>`).join('');
  2179. }
  2180. html += `<div class="structured-card">
  2181. <div class="structured-card-title-row" style="display:flex; align-items:center; flex-wrap:wrap; gap: 8px; margin-bottom: 1rem;">
  2182. <div class="structured-card-title" style="margin:0;">${title}</div>
  2183. ${treeNodeTags}
  2184. </div>
  2185. `;
  2186. const renderApplyToVal = (valObj, suggestApplyTo = null) => {
  2187. if (!valObj || typeof valObj !== 'object') return '-';
  2188. const escapeApplyToText = (s) => String(s).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2189. const renderPathParts = (pathValue, highlight = false) => {
  2190. const pathStr = String(pathValue || '').trim();
  2191. if (!pathStr) return '';
  2192. const parts = pathStr.split('/');
  2193. const leaf = parts.pop();
  2194. const prefix = parts.length > 0 ? parts.join('/') + '/' : '';
  2195. const leafStyle = highlight
  2196. ? 'background:#eff6ff; color:#2563eb; border:1px solid #bfdbfe;'
  2197. : '';
  2198. return `
  2199. ${prefix ? `<span class="apply-to-path-prefix">${escapeApplyToText(prefix)}</span>` : ''}
  2200. <span class="apply-to-path-leaf" style="${leafStyle}">${escapeApplyToText(leaf)}</span>
  2201. `;
  2202. };
  2203. let res = '<div style="display:flex; flex-direction:column; gap:6px;">';
  2204. let hasRows = false;
  2205. Object.entries(valObj).forEach(([k, v]) => {
  2206. if (Array.isArray(v) && v.length > 0) {
  2207. hasRows = true;
  2208. res += `<div class="apply-to-subrow">
  2209. <span class="apply-to-key-badge" style="background: rgba(0,0,0,0.05); color: #475569;">${escapeApplyToText(k)}</span>
  2210. <div class="apply-to-values" style="display:flex; flex-wrap:wrap; gap:4px;">`;
  2211. v.forEach(pathObj => {
  2212. let pathStr = '';
  2213. let elementStr = '';
  2214. if (typeof pathObj === 'object' && pathObj !== null) {
  2215. pathStr = pathObj.category_path || pathObj.path || '';
  2216. elementStr = pathObj.element || '';
  2217. } else {
  2218. pathStr = String(pathObj);
  2219. }
  2220. let tooltipHtml = '';
  2221. if (typeof pathObj === 'object' && pathObj !== null && pathObj.rationale) {
  2222. tooltipHtml = `
  2223. <div class="apply-to-tooltip">
  2224. ${pathObj.category_id ? `<span class="tooltip-id">id: ${pathObj.category_id}</span>` : ''}
  2225. <span class="tooltip-rationale">${escapeApplyToText(pathObj.rationale)}</span>
  2226. </div>
  2227. `;
  2228. }
  2229. let htmlParts = '';
  2230. if (pathStr && elementStr) {
  2231. htmlParts = `<span class="apply-to-path-prefix">${escapeApplyToText(pathStr)}</span><span class="apply-to-path-leaf" style="margin-left: 4px;">${escapeApplyToText(elementStr)}</span>`;
  2232. } else if (pathStr) {
  2233. htmlParts = renderPathParts(pathStr);
  2234. }
  2235. if (htmlParts) {
  2236. res += `<span class="apply-to-path-item has-tooltip">${htmlParts}${tooltipHtml}</span>`;
  2237. }
  2238. });
  2239. res += `</div></div>`;
  2240. }
  2241. });
  2242. if (typeof suggestApplyTo === 'string' && suggestApplyTo.trim()) {
  2243. hasRows = true;
  2244. res += `<div class="apply-to-subrow">
  2245. <span class="apply-to-key-badge" style="background:#eff6ff; color:#2563eb; border-color:#bfdbfe;">最优</span>
  2246. <div class="apply-to-values" style="display:flex; flex-wrap:wrap; gap:4px;">
  2247. <span class="apply-to-path-item" style="border: 2px dashed #94a3b8; background: transparent;">${renderPathParts(suggestApplyTo, true)}</span>
  2248. </div>
  2249. </div>`;
  2250. }
  2251. res += `</div>`;
  2252. return hasRows ? res : '-';
  2253. };
  2254. // Render apply_to / apply_to_grounding at workflow level (if it exists)
  2255. if (applyToData && typeof applyToData.val === 'object' && Object.keys(applyToData.val).length > 0) {
  2256. html += `<div class="structured-row">
  2257. <div class="structured-label">${applyToData.key}</div>
  2258. <div class="structured-value">${renderApplyToVal(applyToData.val, applyToData.suggest)}</div>
  2259. </div>`;
  2260. }
  2261. if (item.action && typeof item.action === 'object' && (item.action.description || item.action.reasoning)) {
  2262. const actionDescription = item.action.description ? String(item.action.description).replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
  2263. const actionReasoning = item.action.reasoning ? String(item.action.reasoning).replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
  2264. html += `<div class="structured-row">
  2265. <div class="structured-label">action</div>
  2266. <div class="structured-value">
  2267. <style>
  2268. .action-description-tooltip:hover .action-reasoning-popover { display:block !important; }
  2269. </style>
  2270. ${actionDescription ? `<span class="action-description-tooltip" style="position:relative; display:inline-block;">
  2271. <span class="data-type-badge" style="background:#e0e7ff;color:#3730a3;font-weight:normal;margin-right:6px;">${actionDescription}</span>
  2272. ${actionReasoning ? `<span class="action-reasoning-popover" style="display:none; position:absolute; left:0; top:calc(100% + 6px); z-index:50; width:300px; max-width:60vw; padding:8px 10px; border-radius:8px; background:#0f172a; color:#f8fafc; box-shadow:0 10px 25px rgba(15,23,42,0.18); font-size:0.86em; line-height:1.5; white-space:normal; font-weight:400;">${actionReasoning}</span>` : ''}
  2273. </span>` : ''}
  2274. </div>
  2275. </div>`;
  2276. }
  2277. // Stage rendering removed per request
  2278. // Render effects
  2279. if (item.effects && Array.isArray(item.effects) && item.effects.length > 0) {
  2280. let effectsHtml = '';
  2281. item.effects.forEach(effectItem => {
  2282. if (typeof effectItem === 'string') {
  2283. effectsHtml += `<li style="margin-bottom: 4px;">${effectItem.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</li>`;
  2284. } else if (typeof effectItem === 'object' && effectItem !== null) {
  2285. const stmt = effectItem.statement ? effectItem.statement.replace(/</g, '&lt;').replace(/>/g, '&gt;') : 'Effect';
  2286. let detailsHtml = '';
  2287. const excludeKeys = ['statement'];
  2288. Object.entries(effectItem).forEach(([k, v]) => {
  2289. if (!excludeKeys.includes(k) && v !== null && v !== undefined && v !== '' && (!Array.isArray(v) || v.length > 0)) {
  2290. let valStr = '';
  2291. if (Array.isArray(v)) {
  2292. valStr = `<ul style="margin: 2px 0 0 20px; padding: 0;">` + v.map(vi => `<li>${String(vi).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</li>`).join('') + `</ul>`;
  2293. } else if (typeof v === 'object') {
  2294. valStr = JSON.stringify(v);
  2295. } else {
  2296. valStr = String(v).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2297. }
  2298. if (Array.isArray(v)) {
  2299. detailsHtml += `<div style="margin-top: 6px; font-size: 0.9em;">
  2300. <div style="color: var(--text-muted); font-weight: 500; margin-bottom: 2px; text-transform: capitalize;">${k.replace(/_/g, ' ')}:</div>
  2301. <div style="color: var(--text-main);">${valStr}</div>
  2302. </div>`;
  2303. } else {
  2304. detailsHtml += `<div style="margin-top: 4px; font-size: 0.9em;">
  2305. <span style="color: var(--text-muted); font-weight: 500; text-transform: capitalize;">${k.replace(/_/g, ' ')}:</span>
  2306. <span style="color: var(--text-main);">${valStr}</span>
  2307. </div>`;
  2308. }
  2309. }
  2310. });
  2311. effectsHtml += `<li style="list-style: none; margin-bottom: 8px; margin-left: -20px;">
  2312. <details style="background: rgba(0,0,0,0.02); border: 1px solid rgba(0,0,0,0.06); border-radius: 6px; padding: 6px 10px;">
  2313. <summary style="cursor: pointer; font-weight: 500; color: var(--accent-primary); outline: none;">
  2314. ${stmt}
  2315. </summary>
  2316. <div style="padding-top: 8px; margin-top: 6px; border-top: 1px dashed rgba(0,0,0,0.1);">
  2317. ${detailsHtml}
  2318. </div>
  2319. </details>
  2320. </li>`;
  2321. }
  2322. });
  2323. html += `<div class="structured-row">
  2324. <div class="structured-label">effects</div>
  2325. <div class="structured-value">
  2326. <ul class="effects-list">
  2327. ${effectsHtml}
  2328. </ul>
  2329. </div>
  2330. </div>`;
  2331. }
  2332. // Render confidence fields
  2333. const formatDate = (ts) => {
  2334. if (!ts) return '-';
  2335. if (typeof ts === 'string' && ts.includes('-')) return ts;
  2336. const num = Number(ts);
  2337. if (isNaN(num) || num <= 0) return '-';
  2338. const d = new Date(num > 10000000000 ? num : num * 1000);
  2339. return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
  2340. };
  2341. html += `<div class="structured-row">
  2342. <div class="structured-label" style="display:flex; align-items:center; gap:4px;">
  2343. 置信度
  2344. </div>
  2345. <div class="structured-value" style="display: flex; flex-wrap: wrap; gap: 8px; font-size: 0.85em;">
  2346. <div style="background: rgba(0,0,0,0.03); border: 1px solid rgba(0,0,0,0.06); padding: 4px 8px; border-radius: 6px; display:flex; gap: 6px;">
  2347. <span style="color: var(--text-muted);">Maturity:</span>
  2348. <span style="font-weight: 500; color: var(--text-main);">${String((item.maturity || (parentItem && parentItem.maturity)) || '-').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</span>
  2349. </div>
  2350. <div style="background: rgba(0,0,0,0.03); border: 1px solid rgba(0,0,0,0.06); padding: 4px 8px; border-radius: 6px; display:flex; gap: 6px;">
  2351. <span style="color: var(--text-muted);">Validation:</span>
  2352. <span style="font-weight: 500; color: var(--text-main);">${(item.validation_count !== undefined && item.validation_count !== null) ? String(item.validation_count).replace(/</g, '&lt;').replace(/>/g, '&gt;') : (parentItem && parentItem.validation_count !== undefined && parentItem.validation_count !== null) ? String(parentItem.validation_count).replace(/</g, '&lt;').replace(/>/g, '&gt;') : '-'}</span>
  2353. </div>
  2354. <div style="background: rgba(0,0,0,0.03); border: 1px solid rgba(0,0,0,0.06); padding: 4px 8px; border-radius: 6px; display:flex; gap: 6px;">
  2355. <span style="color: var(--text-muted);">Published:</span>
  2356. <span style="font-weight: 500; color: var(--text-main);">${formatDate(item.published_at || (parentItem && parentItem.published_at))}</span>
  2357. </div>
  2358. <div style="background: rgba(0,0,0,0.03); border: 1px solid rgba(0,0,0,0.06); padding: 4px 8px; border-radius: 6px; display:flex; gap: 6px;">
  2359. <span style="color: var(--text-muted);">Last Verified:</span>
  2360. <span style="font-weight: 500; color: var(--text-main);">${formatDate(item.last_verified_at || (parentItem && parentItem.last_verified_at))}</span>
  2361. </div>
  2362. <div style="background: rgba(0,0,0,0.03); border: 1px solid rgba(0,0,0,0.06); padding: 4px 8px; border-radius: 6px; display:flex; gap: 6px;">
  2363. <span style="color: var(--text-muted);">Created:</span>
  2364. <span style="font-weight: 500; color: var(--text-main);">${formatDate(item.created_at || (parentItem && parentItem.created_at))}</span>
  2365. </div>
  2366. <div style="background: rgba(0,0,0,0.03); border: 1px solid rgba(0,0,0,0.06); padding: 4px 8px; border-radius: 6px; display:flex; gap: 6px;">
  2367. <span style="color: var(--text-muted);">Updated:</span>
  2368. <span style="font-weight: 500; color: var(--text-main);">${formatDate(item.updated_at || (parentItem && parentItem.updated_at))}</span>
  2369. </div>
  2370. </div>
  2371. </div>`;
  2372. // Render feedback if available
  2373. const feedbackVal = item.feedback || (parentItem && parentItem.feedback);
  2374. if (feedbackVal) {
  2375. let feedbackHtml = '';
  2376. if (typeof feedbackVal === 'object' && feedbackVal !== null) {
  2377. Object.entries(feedbackVal).forEach(([k, v]) => {
  2378. if (v !== null && v !== undefined && String(v).trim() !== '') {
  2379. feedbackHtml += `<div style="background: rgba(0,0,0,0.03); border: 1px solid rgba(0,0,0,0.06); padding: 4px 8px; border-radius: 6px; display:flex; gap: 6px;">
  2380. <span style="color: var(--text-muted);">${k}:</span>
  2381. <span style="font-weight: 500; color: var(--text-main);">${v}</span>
  2382. </div>`;
  2383. }
  2384. });
  2385. if (feedbackHtml !== '') {
  2386. feedbackHtml = `<div style="display: flex; flex-wrap: wrap; gap: 8px; font-size: 0.85em;">${feedbackHtml}</div>`;
  2387. }
  2388. } else if (typeof feedbackVal === 'string' && feedbackVal.trim() !== '') {
  2389. feedbackHtml = `<div style="color: var(--text-main); font-size: 0.95em; line-height: 1.5; white-space: pre-wrap; padding-top: 2px;">${String(feedbackVal).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</div>`;
  2390. }
  2391. if (feedbackHtml !== '') {
  2392. html += `<div class="structured-row">
  2393. <div class="structured-label">feedback</div>
  2394. <div class="structured-value" style="display: flex; align-items: center;">
  2395. ${feedbackHtml}
  2396. </div>
  2397. </div>`;
  2398. }
  2399. }
  2400. // Render body
  2401. if (item.body && typeof item.body === 'string') {
  2402. html += `<div class="structured-row">
  2403. <div class="structured-label">body</div>
  2404. <div class="structured-value">${item.body.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</div>
  2405. </div>`;
  2406. }
  2407. // Helper for inputs/outputs (Moved up so it can be used by steps)
  2408. const renderDataObjList = (list) => {
  2409. const isValid = (v) => v !== null && v !== undefined && String(v).toLowerCase() !== 'null' && String(v).toLowerCase() !== 'none' && String(v).trim() !== '';
  2410. return list.map(io => {
  2411. const desc = isValid(io.description) ? io.description.replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
  2412. const mod = isValid(io.modality) ? io.modality : '';
  2413. const relation = isValid(io.relation) ? io.relation.replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
  2414. let content = '';
  2415. if (mod) {
  2416. content += `<span class="data-type-badge" style="background:#e0e7ff;color:#3730a3;font-weight:normal;margin-right:6px;margin-bottom:2px;display:inline-block;">${mod}</span>`;
  2417. }
  2418. if (desc) {
  2419. content += desc;
  2420. }
  2421. let extraHtml = '';
  2422. if (relation) {
  2423. extraHtml = `<div style="font-size: 0.85em; color: #94a3b8; margin-top: 2px; font-weight: normal;">↳ relation: ${relation}</div>`;
  2424. }
  2425. if (!content) {
  2426. const keys = Object.keys(io);
  2427. if (keys.length === 1 && typeof io[keys[0]] === 'string') {
  2428. content = `<span class="data-type-badge">${keys[0]}</span><span class="io-desc" style="margin-left:6px;">${io[keys[0]]}</span>`;
  2429. } else {
  2430. content = `<span class="data-type-badge">未知</span>`;
  2431. }
  2432. }
  2433. return `<div style="margin-bottom: 6px; color: var(--text-main); font-weight: bold; line-height: 1.5; word-wrap: break-word;">${content}${extraHtml}</div>`;
  2434. }).join('');
  2435. };
  2436. // Render steps array specially
  2437. if (item.steps && Array.isArray(item.steps)) {
  2438. const allCapabilities = (parentItem && parentItem.capability) || [];
  2439. const escapeHtml = (s) => String(s).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2440. const minWidth = 1250;
  2441. const renderAction = (src) => {
  2442. if (!src) return '-';
  2443. if (src.action && src.action.description) {
  2444. const description = escapeHtml(src.action.description);
  2445. const reasoning = src.action.reasoning ? escapeHtml(src.action.reasoning) : '';
  2446. return `<span class="action-description-tooltip">
  2447. <span class="data-type-badge" style="background:#e0e7ff;color:#3730a3;font-weight:normal;margin-right:6px;margin-bottom:2px;display:inline-block;">${description}</span>
  2448. ${reasoning ? `<span class="action-reasoning-popover">${reasoning}</span>` : ''}
  2449. </span>`;
  2450. }
  2451. if (src.method) return escapeHtml(src.method);
  2452. if (src.description) return escapeHtml(src.description);
  2453. return '-';
  2454. };
  2455. const renderTools = (tools) => {
  2456. if (!tools || !Array.isArray(tools) || tools.length === 0) return '-';
  2457. return tools.map(t => `<span class="structured-badge tool-badge" style="display:inline-block; margin:2px;">${escapeHtml(t)}</span>`).join('');
  2458. };
  2459. const renderEffects = (effects) => {
  2460. if (!effects || !Array.isArray(effects) || effects.length === 0) return '-';
  2461. const renderKeyTag = (keyText) => `<span style="display:inline-block; padding: 2px 6px; background: #f1f5f9; color: #475569; border-radius: 4px; font-size: 0.85em; font-weight: 500; margin-right: 6px; border: 1px solid #e2e8f0; vertical-align: middle; white-space: nowrap;">${keyText}</span>`;
  2462. return `<div style="display:flex; flex-direction:column; gap:8px;">${effects.map(effect => {
  2463. if (typeof effect === 'string') {
  2464. return `<div class="effect-item"><div style="margin-bottom: 2px; display: flex; align-items: flex-start; line-height: 1.6;">${renderKeyTag('效果')}<span style="flex:1;">${escapeHtml(effect)}</span></div></div>`;
  2465. }
  2466. if (typeof effect !== 'object' || effect === null) return '';
  2467. const statement = effect.statement ? escapeHtml(effect.statement) : '效果';
  2468. const criteria = effect.criteria ? escapeHtml(effect.criteria) : '';
  2469. const judgeMethod = effect.judge_method ? escapeHtml(effect.judge_method) : '';
  2470. const negativeExamples = Array.isArray(effect.negative_examples) && effect.negative_examples.length > 0
  2471. ? `<div style="display:flex; flex-direction:column; gap:4px; flex:1;">` +
  2472. effect.negative_examples.map(ex => `<span style="background: #f8fafc; color: #64748b; padding: 2px 8px; border-radius: 4px; font-size: 0.9em; border: 1px solid #cbd5e1; display: inline-block; word-break: break-word;">${escapeHtml(ex)}</span>`).join('') +
  2473. `</div>`
  2474. : '';
  2475. return `<div class="effect-item">
  2476. <div class="effect-content" style="font-size: 0.95em; line-height: 1.6;">
  2477. <div style="font-weight: 600; margin-bottom: 6px; color: #0f172a; font-size: 1.05em;">${statement}</div>
  2478. ${criteria ? `<div style="margin-bottom: 4px; display: flex; align-items: flex-start;">${renderKeyTag('判断标准')}<span style="flex:1; color: #334155;">${criteria}</span></div>` : ''}
  2479. ${judgeMethod ? `<div style="margin-bottom: 4px; display: flex; align-items: flex-start;">${renderKeyTag('评判方式')}<span style="flex:1; color: #334155;">${judgeMethod}</span></div>` : ''}
  2480. ${negativeExamples ? `<div style="display: flex; align-items: flex-start;">${renderKeyTag('负面示例')}${negativeExamples}</div>` : ''}
  2481. </div>
  2482. </div>`;
  2483. }).join('')}</div>`;
  2484. };
  2485. const getStepCapabilities = (step) => {
  2486. if (!step || !step.step_id) return [];
  2487. return allCapabilities.filter(capability => {
  2488. const refStepId = capability.workflow_step_ref && capability.workflow_step_ref.step_id;
  2489. return refStepId === step.step_id || (
  2490. capability.capability_id && (
  2491. capability.capability_id === `c_${step.step_id}` ||
  2492. capability.capability_id.startsWith(`c_${step.step_id}_`)
  2493. )
  2494. );
  2495. });
  2496. };
  2497. const matchedCapabilities = new Set();
  2498. const renderCapabilityColumns = (capability) => {
  2499. const applyTo = capability && (capability.apply_to_draft || capability.apply_to_grounding || capability.apply_to);
  2500. const suggestApplyTo = capability && capability.apply_to_draft ? null : capability && capability.suggest_apply_to;
  2501. return `
  2502. <td class="capability-cell" style="font-family: monospace;">
  2503. <span class="row-expand-icon">▶</span>
  2504. ${capability && capability.capability_id ? `<span style="display:inline-block; color:#94a3b8; font-size:0.85em; font-weight:400;">${escapeHtml(capability.capability_id)}</span>` : '-'}
  2505. </td>
  2506. <td class="capability-cell">${capability && capability.inputs && capability.inputs.length > 0 ? renderDataObjList(capability.inputs) : '-'}</td>
  2507. <td class="capability-cell">${renderAction(capability)}</td>
  2508. <td class="capability-cell">${capability && capability.outputs && capability.outputs.length > 0 ? renderDataObjList(capability.outputs) : '-'}</td>
  2509. <td class="capability-cell" style="font-size:0.9em;"><div class="capability-clamp">${applyTo ? renderApplyToVal(applyTo, suggestApplyTo) : '-'}</div></td>
  2510. <td class="capability-cell"><div class="capability-clamp capability-text">${capability && capability.body ? escapeHtml(capability.body) : '-'}</div></td>
  2511. <td class="capability-cell"><div class="capability-clamp">${capability ? renderEffects(capability.effects) : '-'}</div></td>
  2512. <td class="capability-cell"><div class="capability-clamp">${capability ? renderTools(capability.tools) : '-'}</div></td>
  2513. `;
  2514. };
  2515. html += `<div class="structured-row">
  2516. <div class="structured-label">steps</div>
  2517. <div class="structured-value" style="width: 100%; overflow-x: auto; padding-bottom: 8px;">
  2518. <style>
  2519. .steps-table tbody tr { cursor: pointer; transition: background 0.2s; }
  2520. .steps-table tbody tr:hover { background: rgba(0,0,0,0.02) !important; }
  2521. .steps-table td { border-bottom: 1px solid rgba(0,0,0,0.05); }
  2522. .steps-table .step-merged-cell { background: #fbfdff; border-right: 1px dashed rgba(0,0,0,0.08); }
  2523. .steps-table .capability-cell { padding: 12px 10px; vertical-align: top; line-height: 1.5; color: var(--text-main); }
  2524. .steps-table .capability-clamp { max-height: 72px; overflow: hidden; position: relative; }
  2525. .steps-table .capability-clamp::after { content: ""; position: absolute; left: 0; right: 0; bottom: 0; height: 24px; background: linear-gradient(to bottom, rgba(255,255,255,0), white); pointer-events: none; }
  2526. .steps-table tr.capability-expanded .capability-clamp { max-height: none; overflow: visible; }
  2527. .steps-table tr.capability-expanded .capability-clamp::after { display: none; }
  2528. .steps-table .row-expand-icon { display: inline-block; margin-right: 6px; color: var(--text-muted); font-size: 0.8em; transition: transform 0.2s; }
  2529. .steps-table tr.capability-expanded .row-expand-icon { transform: rotate(90deg); }
  2530. .steps-table .capability-text { white-space: pre-wrap; word-break: break-word; }
  2531. .steps-table .action-description-tooltip { position: relative; display: inline-block; max-width: 100%; }
  2532. .steps-table .action-reasoning-popover {
  2533. display: none;
  2534. position: absolute;
  2535. left: 0;
  2536. top: calc(100% + 6px);
  2537. z-index: 50;
  2538. width: 300px;
  2539. max-width: 60vw;
  2540. padding: 8px 10px;
  2541. border-radius: 8px;
  2542. background: #0f172a;
  2543. color: #f8fafc;
  2544. box-shadow: 0 10px 25px rgba(15,23,42,0.18);
  2545. font-size: 0.86em;
  2546. line-height: 1.5;
  2547. white-space: normal;
  2548. font-weight: 400;
  2549. }
  2550. .steps-table .action-description-tooltip:hover .action-reasoning-popover { display: block; }
  2551. .steps-table .effect-item { padding-bottom:8px; margin-bottom:8px; border-bottom:1px dashed rgba(0,0,0,0.08); color:var(--text-main); line-height:1.5; }
  2552. .steps-table .effect-item:last-child { margin-bottom:0; padding-bottom:0; border-bottom:0; }
  2553. .steps-table .effect-content { min-width:0; flex:1; }
  2554. .steps-table .effect-statement { color:var(--text-main); font-weight:600; }
  2555. .steps-table .effect-criteria { margin-top:4px; color:var(--text-secondary); font-size:0.9em; line-height:1.45; }
  2556. .steps-table .effect-meta { margin-top:6px; display:flex; flex-wrap:wrap; gap:4px; }
  2557. .steps-table .effect-method { background:#e0e7ff; color:#3730a3; font-weight:normal; margin-right:6px; margin-bottom:2px; display:inline-block; transform:translateY(-1px); }
  2558. .steps-table .effect-negative { background:#f8fafc; color:#64748b; border:1px solid #cbd5e1; border-radius:999px; padding:1px 7px; font-size:0.78em; }
  2559. </style>
  2560. <table class="steps-table" style="width: 100%; min-width: ${minWidth + 220}px; border-collapse: collapse; margin-top: 8px; font-size: 0.9em; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">
  2561. <thead>
  2562. <tr style="background: rgba(0,0,0,0.03); border-bottom: 2px solid rgba(0,0,0,0.1); text-align: left;">
  2563. <th style="padding: 12px 10px; width: 60px;">序号</th>
  2564. <th style="padding: 12px 10px; width: 90px;">阶段</th>
  2565. <th style="padding: 12px 8px; width: 90px;"></th>
  2566. <th style="padding: 12px 10px; width: 180px;">输入</th>
  2567. <th style="padding: 12px 10px; width: 140px;">动作</th>
  2568. <th style="padding: 12px 10px; width: 180px;">输出</th>
  2569. <th style="padding: 12px 10px; width: 260px;">作用域</th>
  2570. <th style="padding: 12px 10px; width: 300px;">做法</th>
  2571. <th style="padding: 12px 10px; width: 360px;">效果</th>
  2572. <th style="padding: 12px 10px; width: 130px;">工具</th>
  2573. </tr>
  2574. </thead>
  2575. <tbody>`;
  2576. item.steps.forEach((step, stepIdx) => {
  2577. const stepCapabilities = getStepCapabilities(step);
  2578. stepCapabilities.forEach(capability => matchedCapabilities.add(capability));
  2579. const capabilitiesToRender = stepCapabilities.length > 0 ? stepCapabilities : [null];
  2580. const rowspan = capabilitiesToRender.length;
  2581. capabilitiesToRender.forEach((capability, capabilityIdx) => {
  2582. html += `
  2583. <tr style="vertical-align: top;" onclick="this.classList.toggle('capability-expanded')">
  2584. ${capabilityIdx === 0 ? `
  2585. <td class="step-merged-cell" rowspan="${rowspan}" style="padding: 14px 10px; font-weight: 600; color: var(--text-muted); text-align: center;">
  2586. ${step.order || stepIdx + 1}
  2587. </td>
  2588. <td class="step-merged-cell" rowspan="${rowspan}" style="padding: 14px 10px;">
  2589. ${step.phase ? `<span class="structured-badge" style="background:#f1f5f9; color:#475569; font-weight: 500;">${escapeHtml(step.phase)}</span>` : '-'}
  2590. </td>` : ''}
  2591. ${renderCapabilityColumns(capability)}
  2592. </tr>
  2593. `;
  2594. });
  2595. });
  2596. allCapabilities.filter(capability => !matchedCapabilities.has(capability)).forEach(capability => {
  2597. html += `
  2598. <tr style="vertical-align: top;" onclick="this.classList.toggle('capability-expanded')">
  2599. <td class="step-merged-cell" style="padding: 14px 10px; font-weight: 600; color: var(--text-muted); text-align: center;">-</td>
  2600. <td class="step-merged-cell" style="padding: 14px 10px;">
  2601. <span class="structured-badge" style="background:#f8fafc; color:#64748b; font-weight: 500;">独立能力</span>
  2602. </td>
  2603. ${renderCapabilityColumns(capability)}
  2604. </tr>
  2605. `;
  2606. });
  2607. html += `</tbody></table></div></div>`;
  2608. }
  2609. // Render inputs
  2610. if (item.inputs && Array.isArray(item.inputs) && item.inputs.length > 0) {
  2611. html += `<div class="structured-row">
  2612. <div class="structured-label">inputs</div>
  2613. <div class="structured-value" style="display:flex; flex-direction:column; gap:6px;">
  2614. ${renderDataObjList(item.inputs)}
  2615. </div>
  2616. </div>`;
  2617. } else if (item.inputs && typeof item.inputs === 'object' && Object.keys(item.inputs).length > 0 && !Array.isArray(item.inputs)) {
  2618. // Fallback for old schema
  2619. html += `<div class="structured-row"><div class="structured-label">inputs</div><div class="structured-value" style="display:flex; flex-direction:column; gap:6px;">`;
  2620. Object.entries(item.inputs).forEach(([k, v]) => {
  2621. html += `<div class="io-item"><span class="data-type-badge">${k}</span><span class="io-desc">${v}</span></div>`;
  2622. });
  2623. html += `</div></div>`;
  2624. }
  2625. // Render outputs
  2626. if (item.outputs && Array.isArray(item.outputs) && item.outputs.length > 0) {
  2627. html += `<div class="structured-row">
  2628. <div class="structured-label">outputs</div>
  2629. <div class="structured-value" style="display:flex; flex-direction:column; gap:6px;">
  2630. ${renderDataObjList(item.outputs)}
  2631. </div>
  2632. </div>`;
  2633. } else if (item.outputs && typeof item.outputs === 'object' && Object.keys(item.outputs).length > 0 && !Array.isArray(item.outputs)) {
  2634. // Fallback for old schema
  2635. html += `<div class="structured-row"><div class="structured-label">outputs</div><div class="structured-value" style="display:flex; flex-direction:column; gap:6px;">`;
  2636. Object.entries(item.outputs).forEach(([k, v]) => {
  2637. html += `<div class="io-item"><span class="data-type-badge">${k}</span><span class="io-desc">${v}</span></div>`;
  2638. });
  2639. html += `</div></div>`;
  2640. }
  2641. // Render tools (for non-step items like capabilities)
  2642. if (item.tools && Array.isArray(item.tools) && item.tools.length > 0) {
  2643. html += `<div class="structured-row">
  2644. <div class="structured-label">tools</div>
  2645. <div class="structured-value">
  2646. ${item.tools.map(t => `<span class="structured-badge tool-badge">${t}</span>`).join('')}
  2647. </div>
  2648. </div>`;
  2649. }
  2650. // Dynamic fallback for any other unhandled keys
  2651. const handledKeys = [
  2652. 'method', 'name', 'action', 'unstructured_what', 'apply_to_grounding', 'apply_to_draft', 'apply_to',
  2653. 'suggest_apply_to', 'stage', 'effects', 'body', 'steps', 'inputs', 'outputs', 'tools'
  2654. ];
  2655. Object.keys(item).forEach(k => {
  2656. if (!handledKeys.includes(k)) {
  2657. let v = item[k];
  2658. if (v === null || v === undefined || v === '') return;
  2659. let displayHtml = '';
  2660. if (typeof v === 'object') {
  2661. if (Array.isArray(v)) {
  2662. if (v.length === 0) return;
  2663. if (typeof v[0] === 'object') {
  2664. displayHtml = `<pre style="margin:0; background:rgba(0,0,0,0.03); padding:8px; border-radius:4px; font-size:0.85em; overflow-x:auto;">${JSON.stringify(v, null, 2).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>`;
  2665. } else {
  2666. displayHtml = v.map(vi => `<span class="structured-badge">${String(vi).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</span>`).join('');
  2667. }
  2668. } else {
  2669. if (Object.keys(v).length === 0) return;
  2670. displayHtml = `<pre style="margin:0; background:rgba(0,0,0,0.03); padding:8px; border-radius:4px; font-size:0.85em; overflow-x:auto;">${JSON.stringify(v, null, 2).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>`;
  2671. }
  2672. } else {
  2673. displayHtml = String(v).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2674. }
  2675. html += `<div class="structured-row">
  2676. <div class="structured-label">${k}</div>
  2677. <div class="structured-value">${displayHtml}</div>
  2678. </div>`;
  2679. }
  2680. });
  2681. html += `</div>`;
  2682. });
  2683. return html;
  2684. };
  2685. window.triggerSingleCaseRerun = async function (step, caseIndex) {
  2686. if (typeof currentSelectedIndex === 'undefined' || currentSelectedIndex === null) {
  2687. alert("请先选择一个需求项目!");
  2688. return;
  2689. }
  2690. const confirmMsg = `确定要针对当前 Case 单独重跑 [${step}] 步骤吗?\n注意:这会覆盖现有的提取结果!`;
  2691. if (!confirm(confirmMsg)) return;
  2692. try {
  2693. const payload = {
  2694. use_claude_sdk: false, // Default
  2695. only_step: step,
  2696. case_index: caseIndex
  2697. };
  2698. // Use global Claude SDK checkbox if it's checked in the UI
  2699. const cbClaudeSdk = document.getElementById('check-claude-sdk');
  2700. if (cbClaudeSdk) {
  2701. payload.use_claude_sdk = cbClaudeSdk.checked;
  2702. }
  2703. const res = await fetch(`/api/pipeline/run/${currentSelectedIndex}`, {
  2704. method: 'POST',
  2705. headers: { 'Content-Type': 'application/json' },
  2706. body: JSON.stringify(payload)
  2707. });
  2708. if (res.ok) {
  2709. alert(`✅ 单Case重跑已触发 (${step})!请在 Pipeline 终端查看进度。`);
  2710. // Show the logs modal instead of non-existent logs tab
  2711. const btnViewLogs = document.getElementById('btn-view-logs');
  2712. if (btnViewLogs) {
  2713. btnViewLogs.click();
  2714. }
  2715. const modalCaseDetail = document.getElementById('case-detail-modal');
  2716. if (modalCaseDetail) modalCaseDetail.classList.add('hidden');
  2717. } else {
  2718. const err = await res.json();
  2719. alert(`启动重跑失败: ${err.detail || JSON.stringify(err)}`);
  2720. }
  2721. } catch (e) {
  2722. console.error("Error triggering single case rerun:", e);
  2723. alert(`发生错误: ${e.message}`);
  2724. }
  2725. };
  2726. window.toggleCaseFilter = async function (caseId, isRestore) {
  2727. if (currentSelectedIndex === null) return;
  2728. const reqIndex = currentSelectedIndex;
  2729. let reason = "manual_delete";
  2730. if (!isRestore) {
  2731. reason = prompt("请输入移除原因 (默认: manual_delete):", "manual_delete");
  2732. if (reason === null) return; // Cancelled
  2733. if (!reason.trim()) reason = "manual_delete";
  2734. }
  2735. try {
  2736. const action = isRestore ? 'restore' : 'filter';
  2737. const res = await fetch(`/api/requirements/${reqIndex}/cases/${action}`, {
  2738. method: 'POST',
  2739. headers: { 'Content-Type': 'application/json' },
  2740. body: JSON.stringify({ case_id: caseId, reason: reason })
  2741. });
  2742. if (!res.ok) {
  2743. const err = await res.json();
  2744. alert('操作失败: ' + (err.detail || '未知错误'));
  2745. return;
  2746. }
  2747. // Close modal and refresh data
  2748. document.getElementById('case-detail-modal').classList.add('hidden');
  2749. document.getElementById('btn-refresh-data').click();
  2750. } catch (e) {
  2751. console.error(e);
  2752. alert('操作失败');
  2753. }
  2754. };
  2755. init();