app.js 155 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077
  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. ${actionDescription ? `<span class="data-type-badge" style="background:#e0e7ff;color:#3730a3;font-weight:normal;margin-right:6px;">${actionDescription}</span>` : ''}
  2268. ${actionReasoning ? `<span style="color:var(--text-secondary);">${actionReasoning}</span>` : ''}
  2269. </div>
  2270. </div>`;
  2271. }
  2272. // Stage rendering removed per request
  2273. // Render effects
  2274. if (item.effects && Array.isArray(item.effects) && item.effects.length > 0) {
  2275. let effectsHtml = '';
  2276. item.effects.forEach(effectItem => {
  2277. if (typeof effectItem === 'string') {
  2278. effectsHtml += `<li style="margin-bottom: 4px;">${effectItem.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</li>`;
  2279. } else if (typeof effectItem === 'object' && effectItem !== null) {
  2280. const stmt = effectItem.statement ? effectItem.statement.replace(/</g, '&lt;').replace(/>/g, '&gt;') : 'Effect';
  2281. let detailsHtml = '';
  2282. const excludeKeys = ['statement'];
  2283. Object.entries(effectItem).forEach(([k, v]) => {
  2284. if (!excludeKeys.includes(k) && v !== null && v !== undefined && v !== '' && (!Array.isArray(v) || v.length > 0)) {
  2285. let valStr = '';
  2286. if (Array.isArray(v)) {
  2287. 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>`;
  2288. } else if (typeof v === 'object') {
  2289. valStr = JSON.stringify(v);
  2290. } else {
  2291. valStr = String(v).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2292. }
  2293. if (Array.isArray(v)) {
  2294. detailsHtml += `<div style="margin-top: 6px; font-size: 0.9em;">
  2295. <div style="color: var(--text-muted); font-weight: 500; margin-bottom: 2px; text-transform: capitalize;">${k.replace(/_/g, ' ')}:</div>
  2296. <div style="color: var(--text-main);">${valStr}</div>
  2297. </div>`;
  2298. } else {
  2299. detailsHtml += `<div style="margin-top: 4px; font-size: 0.9em;">
  2300. <span style="color: var(--text-muted); font-weight: 500; text-transform: capitalize;">${k.replace(/_/g, ' ')}:</span>
  2301. <span style="color: var(--text-main);">${valStr}</span>
  2302. </div>`;
  2303. }
  2304. }
  2305. });
  2306. effectsHtml += `<li style="list-style: none; margin-bottom: 8px; margin-left: -20px;">
  2307. <details style="background: rgba(0,0,0,0.02); border: 1px solid rgba(0,0,0,0.06); border-radius: 6px; padding: 6px 10px;">
  2308. <summary style="cursor: pointer; font-weight: 500; color: var(--accent-primary); outline: none;">
  2309. ${stmt}
  2310. </summary>
  2311. <div style="padding-top: 8px; margin-top: 6px; border-top: 1px dashed rgba(0,0,0,0.1);">
  2312. ${detailsHtml}
  2313. </div>
  2314. </details>
  2315. </li>`;
  2316. }
  2317. });
  2318. html += `<div class="structured-row">
  2319. <div class="structured-label">effects</div>
  2320. <div class="structured-value">
  2321. <ul class="effects-list">
  2322. ${effectsHtml}
  2323. </ul>
  2324. </div>
  2325. </div>`;
  2326. }
  2327. // Render confidence fields
  2328. const formatDate = (ts) => {
  2329. if (!ts) return '-';
  2330. if (typeof ts === 'string' && ts.includes('-')) return ts;
  2331. const num = Number(ts);
  2332. if (isNaN(num) || num <= 0) return '-';
  2333. const d = new Date(num > 10000000000 ? num : num * 1000);
  2334. 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')}`;
  2335. };
  2336. html += `<div class="structured-row">
  2337. <div class="structured-label" style="display:flex; align-items:center; gap:4px;">
  2338. 置信度
  2339. </div>
  2340. <div class="structured-value" style="display: flex; flex-wrap: wrap; gap: 8px; font-size: 0.85em;">
  2341. <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;">
  2342. <span style="color: var(--text-muted);">Maturity:</span>
  2343. <span style="font-weight: 500; color: var(--text-main);">${String((item.maturity || (parentItem && parentItem.maturity)) || '-').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</span>
  2344. </div>
  2345. <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;">
  2346. <span style="color: var(--text-muted);">Validation:</span>
  2347. <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>
  2348. </div>
  2349. <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;">
  2350. <span style="color: var(--text-muted);">Published:</span>
  2351. <span style="font-weight: 500; color: var(--text-main);">${formatDate(item.published_at || (parentItem && parentItem.published_at))}</span>
  2352. </div>
  2353. <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;">
  2354. <span style="color: var(--text-muted);">Last Verified:</span>
  2355. <span style="font-weight: 500; color: var(--text-main);">${formatDate(item.last_verified_at || (parentItem && parentItem.last_verified_at))}</span>
  2356. </div>
  2357. <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;">
  2358. <span style="color: var(--text-muted);">Created:</span>
  2359. <span style="font-weight: 500; color: var(--text-main);">${formatDate(item.created_at || (parentItem && parentItem.created_at))}</span>
  2360. </div>
  2361. <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;">
  2362. <span style="color: var(--text-muted);">Updated:</span>
  2363. <span style="font-weight: 500; color: var(--text-main);">${formatDate(item.updated_at || (parentItem && parentItem.updated_at))}</span>
  2364. </div>
  2365. </div>
  2366. </div>`;
  2367. // Render feedback if available
  2368. const feedbackVal = item.feedback || (parentItem && parentItem.feedback);
  2369. if (feedbackVal) {
  2370. let feedbackHtml = '';
  2371. if (typeof feedbackVal === 'object' && feedbackVal !== null) {
  2372. Object.entries(feedbackVal).forEach(([k, v]) => {
  2373. if (v !== null && v !== undefined && String(v).trim() !== '') {
  2374. 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;">
  2375. <span style="color: var(--text-muted);">${k}:</span>
  2376. <span style="font-weight: 500; color: var(--text-main);">${v}</span>
  2377. </div>`;
  2378. }
  2379. });
  2380. if (feedbackHtml !== '') {
  2381. feedbackHtml = `<div style="display: flex; flex-wrap: wrap; gap: 8px; font-size: 0.85em;">${feedbackHtml}</div>`;
  2382. }
  2383. } else if (typeof feedbackVal === 'string' && feedbackVal.trim() !== '') {
  2384. 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>`;
  2385. }
  2386. if (feedbackHtml !== '') {
  2387. html += `<div class="structured-row">
  2388. <div class="structured-label">feedback</div>
  2389. <div class="structured-value" style="display: flex; align-items: center;">
  2390. ${feedbackHtml}
  2391. </div>
  2392. </div>`;
  2393. }
  2394. }
  2395. // Render body
  2396. if (item.body && typeof item.body === 'string') {
  2397. html += `<div class="structured-row">
  2398. <div class="structured-label">body</div>
  2399. <div class="structured-value">${item.body.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</div>
  2400. </div>`;
  2401. }
  2402. // Helper for inputs/outputs (Moved up so it can be used by steps)
  2403. const renderDataObjList = (list) => {
  2404. const isValid = (v) => v !== null && v !== undefined && String(v).toLowerCase() !== 'null' && String(v).toLowerCase() !== 'none' && String(v).trim() !== '';
  2405. return list.map(io => {
  2406. const desc = isValid(io.description) ? io.description.replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
  2407. const mod = isValid(io.modality) ? io.modality : '';
  2408. const relation = isValid(io.relation) ? io.relation.replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
  2409. let content = '';
  2410. if (mod) {
  2411. 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>`;
  2412. }
  2413. if (desc) {
  2414. content += desc;
  2415. }
  2416. let extraHtml = '';
  2417. if (relation) {
  2418. extraHtml = `<div style="font-size: 0.85em; color: #94a3b8; margin-top: 2px; font-weight: normal;">↳ relation: ${relation}</div>`;
  2419. }
  2420. if (!content) {
  2421. const keys = Object.keys(io);
  2422. if (keys.length === 1 && typeof io[keys[0]] === 'string') {
  2423. content = `<span class="data-type-badge">${keys[0]}</span><span class="io-desc" style="margin-left:6px;">${io[keys[0]]}</span>`;
  2424. } else {
  2425. content = `<span class="data-type-badge">未知</span>`;
  2426. }
  2427. }
  2428. return `<div style="margin-bottom: 6px; color: var(--text-main); font-weight: bold; line-height: 1.5; word-wrap: break-word;">${content}${extraHtml}</div>`;
  2429. }).join('');
  2430. };
  2431. // Render steps array specially
  2432. if (item.steps && Array.isArray(item.steps)) {
  2433. const allCapabilities = (parentItem && parentItem.capability) || [];
  2434. const escapeHtml = (s) => String(s).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2435. const minWidth = 1250;
  2436. const renderAction = (src) => {
  2437. if (!src) return '-';
  2438. if (src.action && src.action.description) {
  2439. const description = escapeHtml(src.action.description);
  2440. const reasoning = src.action.reasoning ? escapeHtml(src.action.reasoning) : '';
  2441. return `<span class="data-type-badge" style="background:#e0e7ff;color:#3730a3;font-weight:normal;margin-right:6px;margin-bottom:2px;display:inline-block;">${description}</span>${reasoning ? `<div style="font-size:0.85em;color:#64748b;margin-top:4px;">${reasoning}</div>` : ''}`;
  2442. }
  2443. if (src.method) return escapeHtml(src.method);
  2444. if (src.description) return escapeHtml(src.description);
  2445. return '-';
  2446. };
  2447. const renderTools = (tools) => {
  2448. if (!tools || !Array.isArray(tools) || tools.length === 0) return '-';
  2449. return tools.map(t => `<span class="structured-badge tool-badge" style="display:inline-block; margin:2px;">${escapeHtml(t)}</span>`).join('');
  2450. };
  2451. const renderEffects = (effects) => {
  2452. if (!effects || !Array.isArray(effects) || effects.length === 0) return '-';
  2453. 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>`;
  2454. return `<div style="display:flex; flex-direction:column; gap:8px;">${effects.map(effect => {
  2455. if (typeof effect === 'string') {
  2456. 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>`;
  2457. }
  2458. if (typeof effect !== 'object' || effect === null) return '';
  2459. const statement = effect.statement ? escapeHtml(effect.statement) : '效果';
  2460. const criteria = effect.criteria ? escapeHtml(effect.criteria) : '';
  2461. const judgeMethod = effect.judge_method ? escapeHtml(effect.judge_method) : '';
  2462. const negativeExamples = Array.isArray(effect.negative_examples) && effect.negative_examples.length > 0
  2463. ? `<div style="display:flex; flex-direction:column; gap:4px; flex:1;">` +
  2464. 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('') +
  2465. `</div>`
  2466. : '';
  2467. return `<div class="effect-item">
  2468. <div class="effect-content" style="font-size: 0.95em; line-height: 1.6;">
  2469. <div style="font-weight: 600; margin-bottom: 6px; color: #0f172a; font-size: 1.05em;">${statement}</div>
  2470. ${criteria ? `<div style="margin-bottom: 4px; display: flex; align-items: flex-start;">${renderKeyTag('判断标准')}<span style="flex:1; color: #334155;">${criteria}</span></div>` : ''}
  2471. ${judgeMethod ? `<div style="margin-bottom: 4px; display: flex; align-items: flex-start;">${renderKeyTag('评判方式')}<span style="flex:1; color: #334155;">${judgeMethod}</span></div>` : ''}
  2472. ${negativeExamples ? `<div style="display: flex; align-items: flex-start;">${renderKeyTag('负面示例')}${negativeExamples}</div>` : ''}
  2473. </div>
  2474. </div>`;
  2475. }).join('')}</div>`;
  2476. };
  2477. const getStepCapabilities = (step) => {
  2478. if (!step || !step.step_id) return [];
  2479. return allCapabilities.filter(capability => {
  2480. const refStepId = capability.workflow_step_ref && capability.workflow_step_ref.step_id;
  2481. return refStepId === step.step_id || (
  2482. capability.capability_id && (
  2483. capability.capability_id === `c_${step.step_id}` ||
  2484. capability.capability_id.startsWith(`c_${step.step_id}_`)
  2485. )
  2486. );
  2487. });
  2488. };
  2489. const matchedCapabilities = new Set();
  2490. const renderCapabilityColumns = (capability) => {
  2491. const applyTo = capability && (capability.apply_to_draft || capability.apply_to_grounding || capability.apply_to);
  2492. const suggestApplyTo = capability && capability.apply_to_draft ? null : capability && capability.suggest_apply_to;
  2493. return `
  2494. <td class="capability-cell" style="font-family: monospace;">
  2495. <span class="row-expand-icon">▶</span>
  2496. ${capability && capability.capability_id ? `<span style="display:inline-block; color:#94a3b8; font-size:0.85em; font-weight:400;">${escapeHtml(capability.capability_id)}</span>` : '-'}
  2497. </td>
  2498. <td class="capability-cell">${capability && capability.inputs && capability.inputs.length > 0 ? renderDataObjList(capability.inputs) : '-'}</td>
  2499. <td class="capability-cell">${renderAction(capability)}</td>
  2500. <td class="capability-cell">${capability && capability.outputs && capability.outputs.length > 0 ? renderDataObjList(capability.outputs) : '-'}</td>
  2501. <td class="capability-cell"><div class="capability-clamp">${capability ? renderEffects(capability.effects) : '-'}</div></td>
  2502. <td class="capability-cell" style="font-size:0.9em;"><div class="capability-clamp">${applyTo ? renderApplyToVal(applyTo, suggestApplyTo) : '-'}</div></td>
  2503. <td class="capability-cell"><div class="capability-clamp">${capability ? renderTools(capability.tools) : '-'}</div></td>
  2504. <td class="capability-cell"><div class="capability-clamp capability-text">${capability && capability.body ? escapeHtml(capability.body) : '-'}</div></td>
  2505. `;
  2506. };
  2507. html += `<div class="structured-row">
  2508. <div class="structured-label">steps</div>
  2509. <div class="structured-value" style="width: 100%; overflow-x: auto; padding-bottom: 8px;">
  2510. <style>
  2511. .steps-table tbody tr { cursor: pointer; transition: background 0.2s; }
  2512. .steps-table tbody tr:hover { background: rgba(0,0,0,0.02) !important; }
  2513. .steps-table td { border-bottom: 1px solid rgba(0,0,0,0.05); }
  2514. .steps-table .step-merged-cell { background: #fbfdff; border-right: 1px dashed rgba(0,0,0,0.08); }
  2515. .steps-table .capability-cell { padding: 12px 10px; vertical-align: top; line-height: 1.5; color: var(--text-main); }
  2516. .steps-table .capability-clamp { max-height: 72px; overflow: hidden; position: relative; }
  2517. .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; }
  2518. .steps-table tr.capability-expanded .capability-clamp { max-height: none; overflow: visible; }
  2519. .steps-table tr.capability-expanded .capability-clamp::after { display: none; }
  2520. .steps-table .row-expand-icon { display: inline-block; margin-right: 6px; color: var(--text-muted); font-size: 0.8em; transition: transform 0.2s; }
  2521. .steps-table tr.capability-expanded .row-expand-icon { transform: rotate(90deg); }
  2522. .steps-table .capability-text { white-space: pre-wrap; word-break: break-word; }
  2523. .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; }
  2524. .steps-table .effect-item:last-child { margin-bottom:0; padding-bottom:0; border-bottom:0; }
  2525. .steps-table .effect-content { min-width:0; flex:1; }
  2526. .steps-table .effect-statement { color:var(--text-main); font-weight:600; }
  2527. .steps-table .effect-criteria { margin-top:4px; color:var(--text-secondary); font-size:0.9em; line-height:1.45; }
  2528. .steps-table .effect-meta { margin-top:6px; display:flex; flex-wrap:wrap; gap:4px; }
  2529. .steps-table .effect-method { background:#e0e7ff; color:#3730a3; font-weight:normal; margin-right:6px; margin-bottom:2px; display:inline-block; transform:translateY(-1px); }
  2530. .steps-table .effect-negative { background:#f8fafc; color:#64748b; border:1px solid #cbd5e1; border-radius:999px; padding:1px 7px; font-size:0.78em; }
  2531. </style>
  2532. <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);">
  2533. <thead>
  2534. <tr style="background: rgba(0,0,0,0.03); border-bottom: 2px solid rgba(0,0,0,0.1); text-align: left;">
  2535. <th style="padding: 12px 10px; width: 60px;">序号</th>
  2536. <th style="padding: 12px 10px; width: 90px;">阶段</th>
  2537. <th style="padding: 12px 8px; width: 90px;"></th>
  2538. <th style="padding: 12px 10px; width: 180px;">输入</th>
  2539. <th style="padding: 12px 10px; width: 140px;">动作</th>
  2540. <th style="padding: 12px 10px; width: 180px;">输出</th>
  2541. <th style="padding: 12px 10px; width: 360px;">效果</th>
  2542. <th style="padding: 12px 10px; width: 260px;">作用域</th>
  2543. <th style="padding: 12px 10px; width: 130px;">工具</th>
  2544. <th style="padding: 12px 10px; width: 300px;">做法</th>
  2545. </tr>
  2546. </thead>
  2547. <tbody>`;
  2548. item.steps.forEach((step, stepIdx) => {
  2549. const stepCapabilities = getStepCapabilities(step);
  2550. stepCapabilities.forEach(capability => matchedCapabilities.add(capability));
  2551. const capabilitiesToRender = stepCapabilities.length > 0 ? stepCapabilities : [null];
  2552. const rowspan = capabilitiesToRender.length;
  2553. capabilitiesToRender.forEach((capability, capabilityIdx) => {
  2554. html += `
  2555. <tr style="vertical-align: top;" onclick="this.classList.toggle('capability-expanded')">
  2556. ${capabilityIdx === 0 ? `
  2557. <td class="step-merged-cell" rowspan="${rowspan}" style="padding: 14px 10px; font-weight: 600; color: var(--text-muted); text-align: center;">
  2558. ${step.order || stepIdx + 1}
  2559. </td>
  2560. <td class="step-merged-cell" rowspan="${rowspan}" style="padding: 14px 10px;">
  2561. ${step.phase ? `<span class="structured-badge" style="background:#f1f5f9; color:#475569; font-weight: 500;">${escapeHtml(step.phase)}</span>` : '-'}
  2562. </td>` : ''}
  2563. ${renderCapabilityColumns(capability)}
  2564. </tr>
  2565. `;
  2566. });
  2567. });
  2568. allCapabilities.filter(capability => !matchedCapabilities.has(capability)).forEach(capability => {
  2569. html += `
  2570. <tr style="vertical-align: top;" onclick="this.classList.toggle('capability-expanded')">
  2571. <td class="step-merged-cell" style="padding: 14px 10px; font-weight: 600; color: var(--text-muted); text-align: center;">-</td>
  2572. <td class="step-merged-cell" style="padding: 14px 10px;">
  2573. <span class="structured-badge" style="background:#f8fafc; color:#64748b; font-weight: 500;">独立能力</span>
  2574. </td>
  2575. ${renderCapabilityColumns(capability)}
  2576. </tr>
  2577. `;
  2578. });
  2579. html += `</tbody></table></div></div>`;
  2580. }
  2581. // Render inputs
  2582. if (item.inputs && Array.isArray(item.inputs) && item.inputs.length > 0) {
  2583. html += `<div class="structured-row">
  2584. <div class="structured-label">inputs</div>
  2585. <div class="structured-value" style="display:flex; flex-direction:column; gap:6px;">
  2586. ${renderDataObjList(item.inputs)}
  2587. </div>
  2588. </div>`;
  2589. } else if (item.inputs && typeof item.inputs === 'object' && Object.keys(item.inputs).length > 0 && !Array.isArray(item.inputs)) {
  2590. // Fallback for old schema
  2591. html += `<div class="structured-row"><div class="structured-label">inputs</div><div class="structured-value" style="display:flex; flex-direction:column; gap:6px;">`;
  2592. Object.entries(item.inputs).forEach(([k, v]) => {
  2593. html += `<div class="io-item"><span class="data-type-badge">${k}</span><span class="io-desc">${v}</span></div>`;
  2594. });
  2595. html += `</div></div>`;
  2596. }
  2597. // Render outputs
  2598. if (item.outputs && Array.isArray(item.outputs) && item.outputs.length > 0) {
  2599. html += `<div class="structured-row">
  2600. <div class="structured-label">outputs</div>
  2601. <div class="structured-value" style="display:flex; flex-direction:column; gap:6px;">
  2602. ${renderDataObjList(item.outputs)}
  2603. </div>
  2604. </div>`;
  2605. } else if (item.outputs && typeof item.outputs === 'object' && Object.keys(item.outputs).length > 0 && !Array.isArray(item.outputs)) {
  2606. // Fallback for old schema
  2607. html += `<div class="structured-row"><div class="structured-label">outputs</div><div class="structured-value" style="display:flex; flex-direction:column; gap:6px;">`;
  2608. Object.entries(item.outputs).forEach(([k, v]) => {
  2609. html += `<div class="io-item"><span class="data-type-badge">${k}</span><span class="io-desc">${v}</span></div>`;
  2610. });
  2611. html += `</div></div>`;
  2612. }
  2613. // Render tools (for non-step items like capabilities)
  2614. if (item.tools && Array.isArray(item.tools) && item.tools.length > 0) {
  2615. html += `<div class="structured-row">
  2616. <div class="structured-label">tools</div>
  2617. <div class="structured-value">
  2618. ${item.tools.map(t => `<span class="structured-badge tool-badge">${t}</span>`).join('')}
  2619. </div>
  2620. </div>`;
  2621. }
  2622. // Dynamic fallback for any other unhandled keys
  2623. const handledKeys = [
  2624. 'method', 'name', 'action', 'unstructured_what', 'apply_to_grounding', 'apply_to_draft', 'apply_to',
  2625. 'suggest_apply_to', 'stage', 'effects', 'body', 'steps', 'inputs', 'outputs', 'tools'
  2626. ];
  2627. Object.keys(item).forEach(k => {
  2628. if (!handledKeys.includes(k)) {
  2629. let v = item[k];
  2630. if (v === null || v === undefined || v === '') return;
  2631. let displayHtml = '';
  2632. if (typeof v === 'object') {
  2633. if (Array.isArray(v)) {
  2634. if (v.length === 0) return;
  2635. if (typeof v[0] === 'object') {
  2636. 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>`;
  2637. } else {
  2638. displayHtml = v.map(vi => `<span class="structured-badge">${String(vi).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</span>`).join('');
  2639. }
  2640. } else {
  2641. if (Object.keys(v).length === 0) return;
  2642. 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>`;
  2643. }
  2644. } else {
  2645. displayHtml = String(v).replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2646. }
  2647. html += `<div class="structured-row">
  2648. <div class="structured-label">${k}</div>
  2649. <div class="structured-value">${displayHtml}</div>
  2650. </div>`;
  2651. }
  2652. });
  2653. html += `</div>`;
  2654. });
  2655. return html;
  2656. };
  2657. window.triggerSingleCaseRerun = async function (step, caseIndex) {
  2658. if (typeof currentSelectedIndex === 'undefined' || currentSelectedIndex === null) {
  2659. alert("请先选择一个需求项目!");
  2660. return;
  2661. }
  2662. const confirmMsg = `确定要针对当前 Case 单独重跑 [${step}] 步骤吗?\n注意:这会覆盖现有的提取结果!`;
  2663. if (!confirm(confirmMsg)) return;
  2664. try {
  2665. const payload = {
  2666. use_claude_sdk: false, // Default
  2667. only_step: step,
  2668. case_index: caseIndex
  2669. };
  2670. // Use global Claude SDK checkbox if it's checked in the UI
  2671. const cbClaudeSdk = document.getElementById('check-claude-sdk');
  2672. if (cbClaudeSdk) {
  2673. payload.use_claude_sdk = cbClaudeSdk.checked;
  2674. }
  2675. const res = await fetch(`/api/pipeline/run/${currentSelectedIndex}`, {
  2676. method: 'POST',
  2677. headers: { 'Content-Type': 'application/json' },
  2678. body: JSON.stringify(payload)
  2679. });
  2680. if (res.ok) {
  2681. alert(`✅ 单Case重跑已触发 (${step})!请在 Pipeline 终端查看进度。`);
  2682. // Show the logs modal instead of non-existent logs tab
  2683. const btnViewLogs = document.getElementById('btn-view-logs');
  2684. if (btnViewLogs) {
  2685. btnViewLogs.click();
  2686. }
  2687. const modalCaseDetail = document.getElementById('case-detail-modal');
  2688. if (modalCaseDetail) modalCaseDetail.classList.add('hidden');
  2689. } else {
  2690. const err = await res.json();
  2691. alert(`启动重跑失败: ${err.detail || JSON.stringify(err)}`);
  2692. }
  2693. } catch (e) {
  2694. console.error("Error triggering single case rerun:", e);
  2695. alert(`发生错误: ${e.message}`);
  2696. }
  2697. };
  2698. window.toggleCaseFilter = async function (caseId, isRestore) {
  2699. if (currentSelectedIndex === null) return;
  2700. const reqIndex = currentSelectedIndex;
  2701. let reason = "manual_delete";
  2702. if (!isRestore) {
  2703. reason = prompt("请输入移除原因 (默认: manual_delete):", "manual_delete");
  2704. if (reason === null) return; // Cancelled
  2705. if (!reason.trim()) reason = "manual_delete";
  2706. }
  2707. try {
  2708. const action = isRestore ? 'restore' : 'filter';
  2709. const res = await fetch(`/api/requirements/${reqIndex}/cases/${action}`, {
  2710. method: 'POST',
  2711. headers: { 'Content-Type': 'application/json' },
  2712. body: JSON.stringify({ case_id: caseId, reason: reason })
  2713. });
  2714. if (!res.ok) {
  2715. const err = await res.json();
  2716. alert('操作失败: ' + (err.detail || '未知错误'));
  2717. return;
  2718. }
  2719. // Close modal and refresh data
  2720. document.getElementById('case-detail-modal').classList.add('hidden');
  2721. document.getElementById('btn-refresh-data').click();
  2722. } catch (e) {
  2723. console.error(e);
  2724. alert('操作失败');
  2725. }
  2726. };
  2727. init();