stratagate-dsh 0.3.51 → 0.3.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -318,11 +318,11 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
318
318
  `).concat(renderTarget.picking?`if(outColor.a == 0.0) discard;
319
319
  else outColor = vIndex;`:"",`
320
320
  }
321
- `),program=createProgram(gl,vertexShaderSource,fragmentShaderSource);program.aPosition=gl.getAttribLocation(program,"aPosition"),program.aIndex=gl.getAttribLocation(program,"aIndex"),program.aVertType=gl.getAttribLocation(program,"aVertType"),program.aTransform=gl.getAttribLocation(program,"aTransform"),program.aAtlasId=gl.getAttribLocation(program,"aAtlasId"),program.aTex=gl.getAttribLocation(program,"aTex"),program.aPointAPointB=gl.getAttribLocation(program,"aPointAPointB"),program.aPointCPointD=gl.getAttribLocation(program,"aPointCPointD"),program.aLineWidth=gl.getAttribLocation(program,"aLineWidth"),program.aColor=gl.getAttribLocation(program,"aColor"),program.aCornerRadius=gl.getAttribLocation(program,"aCornerRadius"),program.aBorderColor=gl.getAttribLocation(program,"aBorderColor"),program.uPanZoomMatrix=gl.getUniformLocation(program,"uPanZoomMatrix"),program.uAtlasSize=gl.getUniformLocation(program,"uAtlasSize"),program.uBGColor=gl.getUniformLocation(program,"uBGColor"),program.uZoom=gl.getUniformLocation(program,"uZoom"),program.uTextures=[];for(var i2=0;i2<this.batchManager.getMaxAtlasesPerBatch();i2++)program.uTextures.push(gl.getUniformLocation(program,"uTexture".concat(i2)));return program}},{key:"_createVAO",value:function(){var unitSquare=[0,0,1,0,1,1,0,0,1,1,0,1];this.vertexCount=unitSquare.length/2;var n=this.maxInstances,gl=this.gl,program=this.program,vao=gl.createVertexArray();return gl.bindVertexArray(vao),createBufferStaticDraw(gl,"vec2",program.aPosition,unitSquare),this.transformBuffer=create3x3MatrixBufferDynamicDraw(gl,n,program.aTransform),this.indexBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aIndex),this.vertTypeBuffer=createBufferDynamicDraw(gl,n,"int",program.aVertType),this.atlasIdBuffer=createBufferDynamicDraw(gl,n,"int",program.aAtlasId),this.texBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aTex),this.pointAPointBBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aPointAPointB),this.pointCPointDBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aPointCPointD),this.lineWidthBuffer=createBufferDynamicDraw(gl,n,"vec2",program.aLineWidth),this.colorBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aColor),this.cornerRadiusBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aCornerRadius),this.borderColorBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aBorderColor),gl.bindVertexArray(null),vao}},{key:"buffers",get:function(){var _this=this;return this._buffers||(this._buffers=Object.keys(this).filter(function(k){return endsWith(k,"Buffer")}).map(function(k){return _this[k]})),this._buffers}},{key:"startFrame",value:function(panZoomMatrix){var renderTarget=arguments.length>1&&arguments[1]!==void 0?arguments[1]:RENDER_TARGET.SCREEN;this.panZoomMatrix=panZoomMatrix,this.renderTarget=renderTarget,this.batchDebugInfo=[],this.wrappedCount=0,this.simpleCount=0,this.startBatch()}},{key:"startBatch",value:function(){this.instanceCount=0,this.batchManager.startBatch()}},{key:"endFrame",value:function(){this.endBatch()}},{key:"_isVisible",value:function(ele,opts){return ele.visible()?opts&&opts.isVisible?opts.isVisible(ele):!0:!1}},{key:"drawTexture",value:function(ele,eleIndex,type){var atlasManager=this.atlasManager,batchManager=this.batchManager,opts=atlasManager.getRenderTypeOpts(type);if(this._isVisible(ele,opts)&&!(ele.isEdge()&&!this._isValidEdge(ele))){if(this.renderTarget.picking&&opts.getTexPickingMode){var mode=opts.getTexPickingMode(ele);if(mode===TEX_PICKING_MODE.IGNORE)return;if(mode==TEX_PICKING_MODE.USE_BB){this.drawPickingRectangle(ele,eleIndex,type);return}}var atlasInfoArray=atlasManager.getAtlasInfo(ele,type),_iterator=_createForOfIteratorHelper(atlasInfoArray),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var atlasInfo=_step.value,atlas=atlasInfo.atlas,tex1=atlasInfo.tex1,tex2=atlasInfo.tex2;batchManager.canAddToCurrentBatch(atlas)||this.endBatch();for(var atlasIndex=batchManager.getAtlasIndexForBatch(atlas),_i=0,_arr=[[tex1,!0],[tex2,!1]];_i<_arr.length;_i++){var _arr$_i=_slicedToArray(_arr[_i],2),tex=_arr$_i[0],first2=_arr$_i[1];if(tex.w!=0){var instance2=this.instanceCount;this.vertTypeBuffer.getView(instance2)[0]=TEXTURE;var indexView=this.indexBuffer.getView(instance2);indexToVec4(eleIndex,indexView);var atlasIdView=this.atlasIdBuffer.getView(instance2);atlasIdView[0]=atlasIndex;var texView=this.texBuffer.getView(instance2);texView[0]=tex.x,texView[1]=tex.y,texView[2]=tex.w,texView[3]=tex.h;var matrixView=this.transformBuffer.getMatrixView(instance2);this.setTransformMatrix(ele,matrixView,opts,atlasInfo,first2),this.instanceCount++,first2||this.wrappedCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}}}catch(err){_iterator.e(err)}finally{_iterator.f()}}}},{key:"setTransformMatrix",value:function(ele,matrix,opts,atlasInfo){var first2=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,padding=0;if(opts.shapeProps&&opts.shapeProps.padding&&(padding=ele.pstyle(opts.shapeProps.padding).pfValue),atlasInfo){var bb=atlasInfo.bb,tex1=atlasInfo.tex1,tex2=atlasInfo.tex2,ratio=tex1.w/(tex1.w+tex2.w);first2||(ratio=1-ratio);var adjBB=this._getAdjustedBB(bb,padding,first2,ratio);this._applyTransformMatrix(matrix,adjBB,opts,ele)}else{var _bb=opts.getBoundingBox(ele),_adjBB=this._getAdjustedBB(_bb,padding,!0,1);this._applyTransformMatrix(matrix,_adjBB,opts,ele)}}},{key:"_applyTransformMatrix",value:function(matrix,adjBB,opts,ele){var x2,y2;identity2(matrix);var theta=opts.getRotation?opts.getRotation(ele):0;if(theta!==0){var _opts$getRotationPoin=opts.getRotationPoint(ele),sx=_opts$getRotationPoin.x,sy=_opts$getRotationPoin.y;translate(matrix,matrix,[sx,sy]),rotate(matrix,matrix,theta);var offset=opts.getRotationOffset(ele);x2=offset.x+(adjBB.xOffset||0),y2=offset.y+(adjBB.yOffset||0)}else x2=adjBB.x1,y2=adjBB.y1;translate(matrix,matrix,[x2,y2]),scale(matrix,matrix,[adjBB.w,adjBB.h])}},{key:"_getAdjustedBB",value:function(bb,padding,first2,ratio){var x1=bb.x1,y1=bb.y1,w=bb.w,h=bb.h,yOffset=bb.yOffset;padding&&(x1-=padding,y1-=padding,w+=2*padding,h+=2*padding);var xOffset=0,adjW=w*ratio;return first2&&ratio<1?w=adjW:!first2&&ratio<1&&(xOffset=w-adjW,x1+=xOffset,w=adjW),{x1,y1,w,h,xOffset,yOffset}}},{key:"drawPickingRectangle",value:function(ele,eleIndex,type){var opts=this.atlasManager.getRenderTypeOpts(type),instance2=this.instanceCount;this.vertTypeBuffer.getView(instance2)[0]=RECTANGLE;var indexView=this.indexBuffer.getView(instance2);indexToVec4(eleIndex,indexView);var colorView=this.colorBuffer.getView(instance2);toWebGLColor([0,0,0],1,colorView);var matrixView=this.transformBuffer.getMatrixView(instance2);this.setTransformMatrix(ele,matrixView,opts),this.simpleCount++,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}},{key:"drawNode",value:function(node,eleIndex,type){var opts=this.simpleShapeOptions.get(type);if(this._isVisible(node,opts)){var props=opts.shapeProps,vertType=this._getVertTypeForShape(node,props.shape);if(vertType===void 0||opts.isSimple&&!opts.isSimple(node,this.renderTarget)){this.drawTexture(node,eleIndex,type);return}var instance2=this.instanceCount;if(this.vertTypeBuffer.getView(instance2)[0]=vertType,vertType===ROUND_RECTANGLE||vertType===BOTTOM_ROUND_RECTANGLE){var bb=opts.getBoundingBox(node),radius2=this._getCornerRadius(node,props.radius,bb),radiusView=this.cornerRadiusBuffer.getView(instance2);radiusView[0]=radius2,radiusView[1]=radius2,radiusView[2]=radius2,radiusView[3]=radius2,vertType===BOTTOM_ROUND_RECTANGLE&&(radiusView[0]=0,radiusView[2]=0)}var indexView=this.indexBuffer.getView(instance2);indexToVec4(eleIndex,indexView);var opacity=this.renderTarget.picking?1:type==="node-body"?node.effectiveOpacity():1,bgOpacity=this.renderTarget.picking?1:node.pstyle(props.opacity).value*opacity,color=node.pstyle(props.color).value,colorView=this.colorBuffer.getView(instance2);toWebGLColor(color,bgOpacity,colorView);var lineWidthView=this.lineWidthBuffer.getView(instance2);if(lineWidthView[0]=0,lineWidthView[1]=0,props.border){var borderWidth=node.pstyle("border-width").value;if(borderWidth>0){var borderColor=node.pstyle("border-color").value,borderOpacity=opacity*node.pstyle("border-opacity").value,borderColorView=this.borderColorBuffer.getView(instance2);toWebGLColor(borderColor,borderOpacity,borderColorView);var borderPos=node.pstyle("border-position").value;if(borderPos==="inside")lineWidthView[0]=0,lineWidthView[1]=-borderWidth;else if(borderPos==="outside")lineWidthView[0]=borderWidth,lineWidthView[1]=0;else{var halfWidth=borderWidth/2;lineWidthView[0]=halfWidth,lineWidthView[1]=-halfWidth}}}var matrixView=this.transformBuffer.getMatrixView(instance2);this.setTransformMatrix(node,matrixView,opts),this.simpleCount++,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}},{key:"_getVertTypeForShape",value:function(node,shapeProp){var shape=node.pstyle(shapeProp).value;switch(shape){case"rectangle":return RECTANGLE;case"ellipse":return ELLIPSE;case"roundrectangle":case"round-rectangle":return ROUND_RECTANGLE;case"bottom-round-rectangle":return BOTTOM_ROUND_RECTANGLE;default:return}}},{key:"_getCornerRadius",value:function(node,radiusProp,_ref2){var w=_ref2.w,h=_ref2.h;if(node.pstyle(radiusProp).value==="auto")return getRoundRectangleRadius(w,h);var radius2=node.pstyle(radiusProp).pfValue,halfWidth=w/2,halfHeight=h/2;return Math.min(radius2,halfHeight,halfWidth)}},{key:"drawEdgeArrow",value:function(edge,eleIndex,prefix){if(edge.visible()){var rs=edge._private.rscratch,x2,y2,angle2;if(prefix==="source"?(x2=rs.arrowStartX,y2=rs.arrowStartY,angle2=rs.srcArrowAngle):(x2=rs.arrowEndX,y2=rs.arrowEndY,angle2=rs.tgtArrowAngle),!(isNaN(x2)||x2==null||isNaN(y2)||y2==null||isNaN(angle2)||angle2==null)){var arrowShape=edge.pstyle(prefix+"-arrow-shape").value;if(arrowShape!=="none"){var color=edge.pstyle(prefix+"-arrow-color").value,baseOpacity=edge.pstyle("opacity").value,lineOpacity=edge.pstyle("line-opacity").value,opacity=baseOpacity*lineOpacity,lineWidth=edge.pstyle("width").pfValue,scale$1=edge.pstyle("arrow-scale").value,size3=this.r.getArrowWidth(lineWidth,scale$1),instance2=this.instanceCount,transform7=this.transformBuffer.getMatrixView(instance2);identity2(transform7),translate(transform7,transform7,[x2,y2]),scale(transform7,transform7,[size3,size3]),rotate(transform7,transform7,angle2),this.vertTypeBuffer.getView(instance2)[0]=EDGE_ARROW;var indexView=this.indexBuffer.getView(instance2);indexToVec4(eleIndex,indexView);var colorView=this.colorBuffer.getView(instance2);toWebGLColor(color,opacity,colorView),this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}}}},{key:"drawEdgeLine",value:function(edge,eleIndex){if(edge.visible()){var points=this._getEdgePoints(edge);if(points){var baseOpacity=edge.pstyle("opacity").value,lineOpacity=edge.pstyle("line-opacity").value,width2=edge.pstyle("width").pfValue,color=edge.pstyle("line-color").value,opacity=baseOpacity*lineOpacity;if(points.length/2+this.instanceCount>this.maxInstances&&this.endBatch(),points.length==4){var instance2=this.instanceCount;this.vertTypeBuffer.getView(instance2)[0]=EDGE_STRAIGHT;var indexView=this.indexBuffer.getView(instance2);indexToVec4(eleIndex,indexView);var colorView=this.colorBuffer.getView(instance2);toWebGLColor(color,opacity,colorView);var lineWidthBuffer=this.lineWidthBuffer.getView(instance2);lineWidthBuffer[0]=width2;var sourceTargetView=this.pointAPointBBuffer.getView(instance2);sourceTargetView[0]=points[0],sourceTargetView[1]=points[1],sourceTargetView[2]=points[2],sourceTargetView[3]=points[3],this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}else for(var i2=0;i2<points.length-2;i2+=2){var _instance=this.instanceCount;this.vertTypeBuffer.getView(_instance)[0]=EDGE_CURVE_SEGMENT;var _indexView=this.indexBuffer.getView(_instance);indexToVec4(eleIndex,_indexView);var _colorView=this.colorBuffer.getView(_instance);toWebGLColor(color,opacity,_colorView);var _lineWidthBuffer=this.lineWidthBuffer.getView(_instance);_lineWidthBuffer[0]=width2;var pAx=points[i2-2],pAy=points[i2-1],pBx=points[i2],pBy=points[i2+1],pCx=points[i2+2],pCy=points[i2+3],pDx=points[i2+4],pDy=points[i2+5];i2==0&&(pAx=2*pBx-pCx+.001,pAy=2*pBy-pCy+.001),i2==points.length-4&&(pDx=2*pCx-pBx+.001,pDy=2*pCy-pBy+.001);var pointABView=this.pointAPointBBuffer.getView(_instance);pointABView[0]=pAx,pointABView[1]=pAy,pointABView[2]=pBx,pointABView[3]=pBy;var pointCDView=this.pointCPointDBuffer.getView(_instance);pointCDView[0]=pCx,pointCDView[1]=pCy,pointCDView[2]=pDx,pointCDView[3]=pDy,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}}}},{key:"_isValidEdge",value:function(edge){var rs=edge._private.rscratch;return!(rs.badLine||rs.allpts==null||isNaN(rs.allpts[0]))}},{key:"_getEdgePoints",value:function(edge){var rs=edge._private.rscratch;if(this._isValidEdge(edge)){var controlPoints3=rs.allpts;if(controlPoints3.length==4)return controlPoints3;var numSegments=this._getNumSegments(edge);return this._getCurveSegmentPoints(controlPoints3,numSegments)}}},{key:"_getNumSegments",value:function(edge){var numSegments=15;return Math.min(Math.max(numSegments,5),this.maxInstances)}},{key:"_getCurveSegmentPoints",value:function(controlPoints3,segments){if(controlPoints3.length==4)return controlPoints3;for(var curvePoints=Array((segments+1)*2),i2=0;i2<=segments;i2++)if(i2==0)curvePoints[0]=controlPoints3[0],curvePoints[1]=controlPoints3[1];else if(i2==segments)curvePoints[i2*2]=controlPoints3[controlPoints3.length-2],curvePoints[i2*2+1]=controlPoints3[controlPoints3.length-1];else{var t=i2/segments;this._setCurvePoint(controlPoints3,t,curvePoints,i2*2)}return curvePoints}},{key:"_setCurvePoint",value:function(points,t,curvePoints,cpi){if(points.length<=2)curvePoints[cpi]=points[0],curvePoints[cpi+1]=points[1];else{for(var newpoints=Array(points.length-2),i2=0;i2<newpoints.length;i2+=2){var x2=(1-t)*points[i2]+t*points[i2+2],y2=(1-t)*points[i2+1]+t*points[i2+3];newpoints[i2]=x2,newpoints[i2+1]=y2}return this._setCurvePoint(newpoints,t,curvePoints,cpi)}}},{key:"endBatch",value:function(){var gl=this.gl,vao=this.vao,vertexCount=this.vertexCount,count=this.instanceCount;if(count!==0){var program=this.renderTarget.picking?this.pickingProgram:this.program;gl.useProgram(program),gl.bindVertexArray(vao);var _iterator2=_createForOfIteratorHelper(this.buffers),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var buffer=_step2.value;buffer.bufferSubData(count)}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}for(var atlases=this.batchManager.getAtlases(),i2=0;i2<atlases.length;i2++)atlases[i2].bufferIfNeeded(gl);for(var _i2=0;_i2<atlases.length;_i2++)gl.activeTexture(gl.TEXTURE0+_i2),gl.bindTexture(gl.TEXTURE_2D,atlases[_i2].texture),gl.uniform1i(program.uTextures[_i2],_i2);gl.uniform1f(program.uZoom,getEffectiveZoom(this.r)),gl.uniformMatrix3fv(program.uPanZoomMatrix,!1,this.panZoomMatrix),gl.uniform1i(program.uAtlasSize,this.batchManager.getAtlasSize());var webglBgColor=toWebGLColor(this.bgColor,1);gl.uniform4fv(program.uBGColor,webglBgColor),gl.drawArraysInstanced(gl.TRIANGLES,0,vertexCount,count),gl.bindVertexArray(null),gl.bindTexture(gl.TEXTURE_2D,null),this.debug&&this.batchDebugInfo.push({count,atlasCount:atlases.length}),this.startBatch()}}},{key:"getDebugInfo",value:function(){var atlasInfo=this.atlasManager.getDebugInfo(),totalAtlases=atlasInfo.reduce(function(count,info){return count+info.atlasCount},0),batchInfo=this.batchDebugInfo,totalInstances=batchInfo.reduce(function(count,info){return count+info.count},0);return{atlasInfo,totalAtlases,wrappedCount:this.wrappedCount,simpleCount:this.simpleCount,batchCount:batchInfo.length,batchInfo,totalInstances}}}])})(),CRp$4={};CRp$4.initWebgl=function(opts,fns){var r=this,gl=r.data.contexts[r.WEBGL];opts.bgColor=getBGColor(r),opts.webglTexSize=Math.min(opts.webglTexSize,gl.getParameter(gl.MAX_TEXTURE_SIZE)),opts.webglTexRows=Math.min(opts.webglTexRows,54),opts.webglTexRowsNodes=Math.min(opts.webglTexRowsNodes,54),opts.webglBatchSize=Math.min(opts.webglBatchSize,16384),opts.webglTexPerBatch=Math.min(opts.webglTexPerBatch,gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS)),r.webglDebug=opts.webglDebug,r.webglDebugShowAtlases=opts.webglDebugShowAtlases,r.pickingFrameBuffer=createPickingFrameBuffer(gl),r.pickingFrameBuffer.needsDraw=!0,r.drawing=new ElementDrawingWebGL(r,gl,opts);var getLabelRotation3=function(prop){return function(ele){return r.getTextAngle(ele,prop)}},isLabelVisible=function(prop){return function(ele){var label=ele.pstyle(prop);return label&&label.value}},isLayerVisible=function(prefix){return function(node){return node.pstyle("".concat(prefix,"-opacity")).value>0}},getTexPickingMode=function(ele){var enabled=ele.pstyle("text-events").strValue==="yes";return enabled?TEX_PICKING_MODE.USE_BB:TEX_PICKING_MODE.IGNORE},getBBForSimpleShape=function(node){var _node$position=node.position(),x2=_node$position.x,y2=_node$position.y,w=node.outerWidth(),h=node.outerHeight();return{w,h,x1:x2-w/2,y1:y2-h/2}};r.drawing.addAtlasCollection("node",{texRows:opts.webglTexRowsNodes}),r.drawing.addAtlasCollection("label",{texRows:opts.webglTexRows}),r.drawing.addTextureAtlasRenderType("node-body",{collection:"node",getKey:fns.getStyleKey,getBoundingBox:fns.getElementBox,drawElement:fns.drawElement}),r.drawing.addSimpleShapeRenderType("node-body",{getBoundingBox:getBBForSimpleShape,isSimple:isSimpleShape,shapeProps:{shape:"shape",color:"background-color",opacity:"background-opacity",radius:"corner-radius",border:!0}}),r.drawing.addSimpleShapeRenderType("node-overlay",{getBoundingBox:getBBForSimpleShape,isVisible:isLayerVisible("overlay"),shapeProps:{shape:"overlay-shape",color:"overlay-color",opacity:"overlay-opacity",padding:"overlay-padding",radius:"overlay-corner-radius"}}),r.drawing.addSimpleShapeRenderType("node-underlay",{getBoundingBox:getBBForSimpleShape,isVisible:isLayerVisible("underlay"),shapeProps:{shape:"underlay-shape",color:"underlay-color",opacity:"underlay-opacity",padding:"underlay-padding",radius:"underlay-corner-radius"}}),r.drawing.addTextureAtlasRenderType("label",{collection:"label",getTexPickingMode,getKey:getStyleKeysForLabel(fns.getLabelKey,null),getBoundingBox:getBoundingBoxForLabel(fns.getLabelBox,null),drawClipped:!0,drawElement:fns.drawLabel,getRotation:getLabelRotation3(null),getRotationPoint:fns.getLabelRotationPoint,getRotationOffset:fns.getLabelRotationOffset,isVisible:isLabelVisible("label")}),r.drawing.addTextureAtlasRenderType("edge-source-label",{collection:"label",getTexPickingMode,getKey:getStyleKeysForLabel(fns.getSourceLabelKey,"source"),getBoundingBox:getBoundingBoxForLabel(fns.getSourceLabelBox,"source"),drawClipped:!0,drawElement:fns.drawSourceLabel,getRotation:getLabelRotation3("source"),getRotationPoint:fns.getSourceLabelRotationPoint,getRotationOffset:fns.getSourceLabelRotationOffset,isVisible:isLabelVisible("source-label")}),r.drawing.addTextureAtlasRenderType("edge-target-label",{collection:"label",getTexPickingMode,getKey:getStyleKeysForLabel(fns.getTargetLabelKey,"target"),getBoundingBox:getBoundingBoxForLabel(fns.getTargetLabelBox,"target"),drawClipped:!0,drawElement:fns.drawTargetLabel,getRotation:getLabelRotation3("target"),getRotationPoint:fns.getTargetLabelRotationPoint,getRotationOffset:fns.getTargetLabelRotationOffset,isVisible:isLabelVisible("target-label")});var setGCFlag=debounce(function(){console.log("garbage collect flag set"),r.data.gc=!0},1e4);r.onUpdateEleCalcs(function(willDraw,eles){var gcNeeded=!1;eles&&eles.length>0&&(gcNeeded|=r.drawing.invalidate(eles)),gcNeeded&&setGCFlag()}),overrideCanvasRendererFunctions(r)};function getBGColor(r){var container2=r.cy.container(),cssColor=container2&&container2.style&&container2.style.backgroundColor||"white";return color2tuple(cssColor)}function getLabelLines(ele,prefix){var rs=ele._private.rscratch;return getPrefixedProperty(rs,"labelWrapCachedLines",prefix)||[]}var getStyleKeysForLabel=function(getKey3,prefix){return function(ele){var key=getKey3(ele),lines=getLabelLines(ele,prefix);return lines.length>1?lines.map(function(line,index){return"".concat(key,"_").concat(index)}):key}},getBoundingBoxForLabel=function(getBoundingBox,prefix){return function(ele,styleKey){var bb=getBoundingBox(ele);if(typeof styleKey=="string"){var ui=styleKey.indexOf("_");if(ui>0){var lineIndex=Number(styleKey.substring(ui+1)),lines=getLabelLines(ele,prefix),h=bb.h/lines.length,yOffset=h*lineIndex,y1=bb.y1+yOffset;return{x1:bb.x1,w:bb.w,y1,h,yOffset}}}return bb}};function overrideCanvasRendererFunctions(r){{var renderCanvas=r.render;r.render=function(options2){options2=options2||{};var cy=r.cy;r.webgl&&(cy.zoom()>maxZoom$1?(clearWebgl(r),renderCanvas.call(r,options2)):(clearCanvas(r),renderWebgl(r,options2,RENDER_TARGET.SCREEN)))}}{var baseFunc=r.matchCanvasSize;r.matchCanvasSize=function(container2){baseFunc.call(r,container2),r.pickingFrameBuffer.setFramebufferAttachmentSizes(r.canvasWidth,r.canvasHeight),r.pickingFrameBuffer.needsDraw=!0}}r.findNearestElements=function(x2,y2,interactiveElementsOnly,isTouch){return findNearestElementsWebgl(r,x2,y2)};{var _baseFunc=r.invalidateCachedZSortedEles;r.invalidateCachedZSortedEles=function(){_baseFunc.call(r),r.pickingFrameBuffer.needsDraw=!0}}{var _baseFunc2=r.notify;r.notify=function(eventName,eles){_baseFunc2.call(r,eventName,eles),eventName==="viewport"||eventName==="bounds"?r.pickingFrameBuffer.needsDraw=!0:eventName==="background"&&r.drawing.invalidate(eles,{type:"node-body"})}}}function clearWebgl(r){var gl=r.data.contexts[r.WEBGL];gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT)}function clearCanvas(r){var clear=function(context){context.save(),context.setTransform(1,0,0,1,0,0),context.clearRect(0,0,r.canvasWidth,r.canvasHeight),context.restore()};clear(r.data.contexts[r.NODE]),clear(r.data.contexts[r.DRAG])}function createPanZoomMatrix(r){var width2=r.canvasWidth,height2=r.canvasHeight,_util$getEffectivePan=getEffectivePanZoom(r),pan2=_util$getEffectivePan.pan,zoom2=_util$getEffectivePan.zoom,transform7=create();translate(transform7,transform7,[pan2.x,pan2.y]),scale(transform7,transform7,[zoom2,zoom2]);var projection$1=create();projection(projection$1,width2,height2);var product=create();return multiply(product,projection$1,transform7),product}function setContextTransform(r,context){var width2=r.canvasWidth,height2=r.canvasHeight,_util$getEffectivePan2=getEffectivePanZoom(r),pan2=_util$getEffectivePan2.pan,zoom2=_util$getEffectivePan2.zoom;context.setTransform(1,0,0,1,0,0),context.clearRect(0,0,width2,height2),context.translate(pan2.x,pan2.y),context.scale(zoom2,zoom2)}function drawSelectionRectangle(r,options2){r.drawSelectionRectangle(options2,function(context){return setContextTransform(r,context)})}function drawAxes(r){var context=r.data.contexts[r.NODE];context.save(),setContextTransform(r,context),context.strokeStyle="rgba(0, 0, 0, 0.3)",context.beginPath(),context.moveTo(-1e3,0),context.lineTo(1e3,0),context.stroke(),context.beginPath(),context.moveTo(0,-1e3),context.lineTo(0,1e3),context.stroke(),context.restore()}function drawAtlases(r){var draw=function(drawing,name,row){for(var collection4=drawing.atlasManager.getAtlasCollection(name),context=r.data.contexts[r.NODE],atlases=collection4.atlases,_i=0;_i<atlases.length;_i++){var atlas=atlases[_i],canvas=atlas.canvas;if(canvas){var w=canvas.width,h=canvas.height,x2=w*_i,y2=canvas.height*row,scale2=.4;context.save(),context.scale(scale2,scale2),context.drawImage(canvas,x2,y2),context.strokeStyle="black",context.rect(x2,y2,w,h),context.stroke(),context.restore()}}},i2=0;draw(r.drawing,"node",i2++),draw(r.drawing,"label",i2++)}function getPickingIndexes(r,mX1,mY1,mX2,mY2){var x2,y2,w,h,_util$getEffectivePan3=getEffectivePanZoom(r),pan2=_util$getEffectivePan3.pan,zoom2=_util$getEffectivePan3.zoom;{var _util$modelToRendered=modelToRenderedPosition2(r,pan2,zoom2,mX1,mY1),_util$modelToRendered2=_slicedToArray(_util$modelToRendered,2),cX1=_util$modelToRendered2[0],cY1=_util$modelToRendered2[1],t=6;x2=cX1-t/2,y2=cY1-t/2,w=t,h=t}if(w===0||h===0)return[];var gl=r.data.contexts[r.WEBGL];gl.bindFramebuffer(gl.FRAMEBUFFER,r.pickingFrameBuffer),r.pickingFrameBuffer.needsDraw&&(gl.viewport(0,0,gl.canvas.width,gl.canvas.height),renderWebgl(r,null,RENDER_TARGET.PICKING),r.pickingFrameBuffer.needsDraw=!1);var n=w*h,data4=new Uint8Array(n*4);gl.readPixels(x2,y2,w,h,gl.RGBA,gl.UNSIGNED_BYTE,data4),gl.bindFramebuffer(gl.FRAMEBUFFER,null);for(var indexes=new Set,i2=0;i2<n;i2++){var pixel=data4.slice(i2*4,i2*4+4),index=vec4ToIndex(pixel)-1;index>=0&&indexes.add(index)}return indexes}function findNearestElementsWebgl(r,x2,y2){var indexes=getPickingIndexes(r,x2,y2),eles=r.getCachedZSortedEles(),node,edge,_iterator=_createForOfIteratorHelper(indexes),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var index=_step.value,ele=eles[index];if(!node&&ele.isNode()&&(node=ele),!edge&&ele.isEdge()&&(edge=ele),node&&edge)break}}catch(err){_iterator.e(err)}finally{_iterator.f()}return[node,edge].filter(Boolean)}function drawEle(r,index,ele){var drawing=r.drawing;index+=1,ele.isNode()?(drawing.drawNode(ele,index,"node-underlay"),drawing.drawNode(ele,index,"node-body"),drawing.drawTexture(ele,index,"label"),drawing.drawNode(ele,index,"node-overlay")):(drawing.drawEdgeLine(ele,index),drawing.drawEdgeArrow(ele,index,"source"),drawing.drawEdgeArrow(ele,index,"target"),drawing.drawTexture(ele,index,"label"),drawing.drawTexture(ele,index,"edge-source-label"),drawing.drawTexture(ele,index,"edge-target-label"))}function renderWebgl(r,options2,renderTarget){var start;r.webglDebug&&(start=performance.now());var drawing=r.drawing,eleCount=0;if(renderTarget.screen&&r.data.canvasNeedsRedraw[r.SELECT_BOX]&&drawSelectionRectangle(r,options2),r.data.canvasNeedsRedraw[r.NODE]||renderTarget.picking){var gl=r.data.contexts[r.WEBGL];renderTarget.screen?(gl.clearColor(0,0,0,0),gl.enable(gl.BLEND),gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA)):gl.disable(gl.BLEND),gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT),gl.viewport(0,0,gl.canvas.width,gl.canvas.height);var panZoomMatrix=createPanZoomMatrix(r),eles=r.getCachedZSortedEles();if(eleCount=eles.length,drawing.startFrame(panZoomMatrix,renderTarget),renderTarget.screen){for(var i2=0;i2<eles.nondrag.length;i2++)drawEle(r,i2,eles.nondrag[i2]);for(var _i2=0;_i2<eles.drag.length;_i2++)drawEle(r,_i2,eles.drag[_i2])}else if(renderTarget.picking)for(var _i3=0;_i3<eles.length;_i3++)drawEle(r,_i3,eles[_i3]);drawing.endFrame(),renderTarget.screen&&r.webglDebugShowAtlases&&(drawAxes(r),drawAtlases(r)),r.data.canvasNeedsRedraw[r.NODE]=!1,r.data.canvasNeedsRedraw[r.DRAG]=!1}if(r.webglDebug){var end=performance.now(),compact=!1,time2=Math.ceil(end-start),debugInfo=drawing.getDebugInfo(),report=["".concat(eleCount," elements"),"".concat(debugInfo.totalInstances," instances"),"".concat(debugInfo.batchCount," batches"),"".concat(debugInfo.totalAtlases," atlases"),"".concat(debugInfo.wrappedCount," wrapped textures"),"".concat(debugInfo.simpleCount," simple shapes")].join(", ");if(compact)console.log("WebGL (".concat(renderTarget.name,") - time ").concat(time2,"ms, ").concat(report));else{console.log("WebGL (".concat(renderTarget.name,") - frame time ").concat(time2,"ms")),console.log("Totals:"),console.log(" ".concat(report)),console.log("Texture Atlases Used:");var atlasInfo=debugInfo.atlasInfo,_iterator2=_createForOfIteratorHelper(atlasInfo),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var info=_step2.value;console.log(" ".concat(info.type,": ").concat(info.keyCount," keys, ").concat(info.atlasCount," atlases"))}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}console.log("")}}r.data.gc&&(console.log("Garbage Collect!"),r.data.gc=!1,drawing.gc())}var CRp$3={};CRp$3.drawPolygonPath=function(context,x2,y2,width2,height2,points){var halfW=width2/2,halfH=height2/2;context.beginPath&&context.beginPath(),context.moveTo(x2+halfW*points[0],y2+halfH*points[1]);for(var i2=1;i2<points.length/2;i2++)context.lineTo(x2+halfW*points[i2*2],y2+halfH*points[i2*2+1]);context.closePath()};CRp$3.drawRoundPolygonPath=function(context,x2,y2,width2,height2,points,corners){corners.forEach(function(corner){return drawPreparedRoundCorner(context,corner)}),context.closePath()};CRp$3.drawRoundRectanglePath=function(context,x2,y2,width2,height2,radius2){var halfWidth=width2/2,halfHeight=height2/2,cornerRadius=radius2==="auto"?getRoundRectangleRadius(width2,height2):Math.min(radius2,halfHeight,halfWidth);context.beginPath&&context.beginPath(),context.moveTo(x2,y2-halfHeight),context.arcTo(x2+halfWidth,y2-halfHeight,x2+halfWidth,y2,cornerRadius),context.arcTo(x2+halfWidth,y2+halfHeight,x2,y2+halfHeight,cornerRadius),context.arcTo(x2-halfWidth,y2+halfHeight,x2-halfWidth,y2,cornerRadius),context.arcTo(x2-halfWidth,y2-halfHeight,x2,y2-halfHeight,cornerRadius),context.lineTo(x2,y2-halfHeight),context.closePath()};CRp$3.drawBottomRoundRectanglePath=function(context,x2,y2,width2,height2,radius2){var halfWidth=width2/2,halfHeight=height2/2,cornerRadius=radius2==="auto"?getRoundRectangleRadius(width2,height2):radius2;context.beginPath&&context.beginPath(),context.moveTo(x2,y2-halfHeight),context.lineTo(x2+halfWidth,y2-halfHeight),context.lineTo(x2+halfWidth,y2),context.arcTo(x2+halfWidth,y2+halfHeight,x2,y2+halfHeight,cornerRadius),context.arcTo(x2-halfWidth,y2+halfHeight,x2-halfWidth,y2,cornerRadius),context.lineTo(x2-halfWidth,y2-halfHeight),context.lineTo(x2,y2-halfHeight),context.closePath()};CRp$3.drawCutRectanglePath=function(context,x2,y2,width2,height2,points,corners){var halfWidth=width2/2,halfHeight=height2/2,cornerLength=corners==="auto"?getCutRectangleCornerLength():corners;context.beginPath&&context.beginPath(),context.moveTo(x2-halfWidth+cornerLength,y2-halfHeight),context.lineTo(x2+halfWidth-cornerLength,y2-halfHeight),context.lineTo(x2+halfWidth,y2-halfHeight+cornerLength),context.lineTo(x2+halfWidth,y2+halfHeight-cornerLength),context.lineTo(x2+halfWidth-cornerLength,y2+halfHeight),context.lineTo(x2-halfWidth+cornerLength,y2+halfHeight),context.lineTo(x2-halfWidth,y2+halfHeight-cornerLength),context.lineTo(x2-halfWidth,y2-halfHeight+cornerLength),context.closePath()};CRp$3.drawBarrelPath=function(context,x2,y2,width2,height2){var halfWidth=width2/2,halfHeight=height2/2,xBegin=x2-halfWidth,xEnd=x2+halfWidth,yBegin=y2-halfHeight,yEnd=y2+halfHeight,barrelCurveConstants=getBarrelCurveConstants(width2,height2),wOffset=barrelCurveConstants.widthOffset,hOffset=barrelCurveConstants.heightOffset,ctrlPtXOffset=barrelCurveConstants.ctrlPtOffsetPct*wOffset;context.beginPath&&context.beginPath(),context.moveTo(xBegin,yBegin+hOffset),context.lineTo(xBegin,yEnd-hOffset),context.quadraticCurveTo(xBegin+ctrlPtXOffset,yEnd,xBegin+wOffset,yEnd),context.lineTo(xEnd-wOffset,yEnd),context.quadraticCurveTo(xEnd-ctrlPtXOffset,yEnd,xEnd,yEnd-hOffset),context.lineTo(xEnd,yBegin+hOffset),context.quadraticCurveTo(xEnd-ctrlPtXOffset,yBegin,xEnd-wOffset,yBegin),context.lineTo(xBegin+wOffset,yBegin),context.quadraticCurveTo(xBegin+ctrlPtXOffset,yBegin,xBegin,yBegin+hOffset),context.closePath()};var sin0=Math.sin(0),cos0=Math.cos(0),sin={},cos={},ellipseStepSize=Math.PI/40;for(i=0*Math.PI;i<2*Math.PI;i+=ellipseStepSize)sin[i]=Math.sin(i),cos[i]=Math.cos(i);var i;CRp$3.drawEllipsePath=function(context,centerX,centerY,width2,height2){if(context.beginPath&&context.beginPath(),context.ellipse)context.ellipse(centerX,centerY,width2/2,height2/2,0,0,2*Math.PI);else for(var xPos,yPos,rw=width2/2,rh=height2/2,i2=0*Math.PI;i2<2*Math.PI;i2+=ellipseStepSize)xPos=centerX-rw*sin[i2]*sin0+rw*cos[i2]*cos0,yPos=centerY+rh*cos[i2]*sin0+rh*sin[i2]*cos0,i2===0?context.moveTo(xPos,yPos):context.lineTo(xPos,yPos);context.closePath()};var CRp$2={};CRp$2.createBuffer=function(w,h){var buffer=document.createElement("canvas");return buffer.width=w,buffer.height=h,[buffer,buffer.getContext("2d")]};CRp$2.bufferCanvasImage=function(options2){var cy=this.cy,eles=cy.mutableElements(),bb=eles.boundingBox(),ctrRect=this.findContainerClientCoords(),width2=options2.full?Math.ceil(bb.w):ctrRect[2],height2=options2.full?Math.ceil(bb.h):ctrRect[3],specdMaxDims=number$1(options2.maxWidth)||number$1(options2.maxHeight),pxRatio=this.getPixelRatio(),scale2=1;if(options2.scale!==void 0)width2*=options2.scale,height2*=options2.scale,scale2=options2.scale;else if(specdMaxDims){var maxScaleW=1/0,maxScaleH=1/0;number$1(options2.maxWidth)&&(maxScaleW=scale2*options2.maxWidth/width2),number$1(options2.maxHeight)&&(maxScaleH=scale2*options2.maxHeight/height2),scale2=Math.min(maxScaleW,maxScaleH),width2*=scale2,height2*=scale2}specdMaxDims||(width2*=pxRatio,height2*=pxRatio,scale2*=pxRatio);var buffCanvas=document.createElement("canvas");buffCanvas.width=width2,buffCanvas.height=height2,buffCanvas.style.width=width2+"px",buffCanvas.style.height=height2+"px";var buffCxt=buffCanvas.getContext("2d");if(width2>0&&height2>0){buffCxt.clearRect(0,0,width2,height2),buffCxt.globalCompositeOperation="source-over";var zsortedEles=this.getCachedZSortedEles();if(options2.full)buffCxt.translate(-bb.x1*scale2,-bb.y1*scale2),buffCxt.scale(scale2,scale2),this.drawElements(buffCxt,zsortedEles),buffCxt.scale(1/scale2,1/scale2),buffCxt.translate(bb.x1*scale2,bb.y1*scale2);else{var pan2=cy.pan(),translation={x:pan2.x*scale2,y:pan2.y*scale2};scale2*=cy.zoom(),buffCxt.translate(translation.x,translation.y),buffCxt.scale(scale2,scale2),this.drawElements(buffCxt,zsortedEles),buffCxt.scale(1/scale2,1/scale2),buffCxt.translate(-translation.x,-translation.y)}options2.bg&&(buffCxt.globalCompositeOperation="destination-over",buffCxt.fillStyle=options2.bg,buffCxt.rect(0,0,width2,height2),buffCxt.fill())}return buffCanvas};function b64ToBlob(b64,mimeType){for(var bytes=atob(b64),buff=new ArrayBuffer(bytes.length),buffUint8=new Uint8Array(buff),i2=0;i2<bytes.length;i2++)buffUint8[i2]=bytes.charCodeAt(i2);return new Blob([buff],{type:mimeType})}function b64UriToB64(b64uri){var i2=b64uri.indexOf(",");return b64uri.substr(i2+1)}function output(options2,canvas,mimeType){var getB64Uri=function(){return canvas.toDataURL(mimeType,options2.quality)};switch(options2.output){case"blob-promise":return new Promise$1(function(resolve2,reject2){try{canvas.toBlob(function(blob){blob!=null?resolve2(blob):reject2(new Error("`canvas.toBlob()` sent a null value in its callback"))},mimeType,options2.quality)}catch(err){reject2(err)}});case"blob":return b64ToBlob(b64UriToB64(getB64Uri()),mimeType);case"base64":return b64UriToB64(getB64Uri());default:return getB64Uri()}}CRp$2.png=function(options2){return output(options2,this.bufferCanvasImage(options2),"image/png")};CRp$2.jpg=function(options2){return output(options2,this.bufferCanvasImage(options2),"image/jpeg")};var CRp$1={};CRp$1.nodeShapeImpl=function(name,context,centerX,centerY,width2,height2,points,corners){switch(name){case"ellipse":return this.drawEllipsePath(context,centerX,centerY,width2,height2);case"polygon":return this.drawPolygonPath(context,centerX,centerY,width2,height2,points);case"round-polygon":return this.drawRoundPolygonPath(context,centerX,centerY,width2,height2,points,corners);case"roundrectangle":case"round-rectangle":return this.drawRoundRectanglePath(context,centerX,centerY,width2,height2,corners);case"cutrectangle":case"cut-rectangle":return this.drawCutRectanglePath(context,centerX,centerY,width2,height2,points,corners);case"bottomroundrectangle":case"bottom-round-rectangle":return this.drawBottomRoundRectanglePath(context,centerX,centerY,width2,height2,corners);case"barrel":return this.drawBarrelPath(context,centerX,centerY,width2,height2)}};var CR=CanvasRenderer,CRp=CanvasRenderer.prototype;CRp.CANVAS_LAYERS=3;CRp.SELECT_BOX=0;CRp.DRAG=1;CRp.NODE=2;CRp.WEBGL=3;CRp.CANVAS_TYPES=["2d","2d","2d","webgl2"];CRp.BUFFER_COUNT=3;CRp.TEXTURE_BUFFER=0;CRp.MOTIONBLUR_BUFFER_NODE=1;CRp.MOTIONBLUR_BUFFER_DRAG=2;function CanvasRenderer(options2){var r=this,containerWindow=r.cy.window(),document2=containerWindow.document;options2.webgl&&(CRp.CANVAS_LAYERS=r.CANVAS_LAYERS=4,console.log("webgl rendering enabled")),r.data={canvases:new Array(CRp.CANVAS_LAYERS),contexts:new Array(CRp.CANVAS_LAYERS),canvasNeedsRedraw:new Array(CRp.CANVAS_LAYERS),bufferCanvases:new Array(CRp.BUFFER_COUNT),bufferContexts:new Array(CRp.CANVAS_LAYERS)};var tapHlOffAttr="-webkit-tap-highlight-color",tapHlOffStyle="rgba(0,0,0,0)";r.data.canvasContainer=document2.createElement("div");var containerStyle=r.data.canvasContainer.style;r.data.canvasContainer.style[tapHlOffAttr]=tapHlOffStyle,containerStyle.position="relative",containerStyle.zIndex="0",containerStyle.overflow="hidden";var container2=options2.cy.container();container2.appendChild(r.data.canvasContainer),container2.style[tapHlOffAttr]=tapHlOffStyle;var styleMap={"-webkit-user-select":"none","-moz-user-select":"-moz-none","user-select":"none","-webkit-tap-highlight-color":"rgba(0,0,0,0)","outline-style":"none"};ms()&&(styleMap["-ms-touch-action"]="none",styleMap["touch-action"]="none");for(var i2=0;i2<CRp.CANVAS_LAYERS;i2++){var canvas=r.data.canvases[i2]=document2.createElement("canvas"),type=CRp.CANVAS_TYPES[i2];r.data.contexts[i2]=canvas.getContext(type),r.data.contexts[i2]||error("Could not create canvas of type "+type),Object.keys(styleMap).forEach(function(k){canvas.style[k]=styleMap[k]}),canvas.style.position="absolute",canvas.setAttribute("data-id","layer"+i2),canvas.style.zIndex=String(CRp.CANVAS_LAYERS-i2),r.data.canvasContainer.appendChild(canvas),r.data.canvasNeedsRedraw[i2]=!1}r.data.topCanvas=r.data.canvases[0],r.data.canvases[CRp.NODE].setAttribute("data-id","layer"+CRp.NODE+"-node"),r.data.canvases[CRp.SELECT_BOX].setAttribute("data-id","layer"+CRp.SELECT_BOX+"-selectbox"),r.data.canvases[CRp.DRAG].setAttribute("data-id","layer"+CRp.DRAG+"-drag"),r.data.canvases[CRp.WEBGL]&&r.data.canvases[CRp.WEBGL].setAttribute("data-id","layer"+CRp.WEBGL+"-webgl");for(var i2=0;i2<CRp.BUFFER_COUNT;i2++)r.data.bufferCanvases[i2]=document2.createElement("canvas"),r.data.bufferContexts[i2]=r.data.bufferCanvases[i2].getContext("2d"),r.data.bufferCanvases[i2].style.position="absolute",r.data.bufferCanvases[i2].setAttribute("data-id","buffer"+i2),r.data.bufferCanvases[i2].style.zIndex=String(-i2-1),r.data.bufferCanvases[i2].style.visibility="hidden";r.pathsEnabled=!0;var emptyBb=makeBoundingBox(),getBoxCenter=function(bb){return{x:(bb.x1+bb.x2)/2,y:(bb.y1+bb.y2)/2}},getCenterOffset=function(bb){return{x:-bb.w/2,y:-bb.h/2}},backgroundTimestampHasChanged=function(ele){var _p=ele[0]._private,same2=_p.oldBackgroundTimestamp===_p.backgroundTimestamp;return!same2},getStyleKey=function(ele){return ele[0]._private.nodeKey},getLabelKey=function(ele){return ele[0]._private.labelStyleKey},getSourceLabelKey=function(ele){return ele[0]._private.sourceLabelStyleKey},getTargetLabelKey=function(ele){return ele[0]._private.targetLabelStyleKey},drawElement=function(context,ele,bb,scaledLabelShown,useEleOpacity){return r.drawElement(context,ele,bb,!1,!1,useEleOpacity)},drawLabel=function(context,ele,bb,scaledLabelShown,useEleOpacity){return r.drawElementText(context,ele,bb,scaledLabelShown,"main",useEleOpacity)},drawSourceLabel=function(context,ele,bb,scaledLabelShown,useEleOpacity){return r.drawElementText(context,ele,bb,scaledLabelShown,"source",useEleOpacity)},drawTargetLabel=function(context,ele,bb,scaledLabelShown,useEleOpacity){return r.drawElementText(context,ele,bb,scaledLabelShown,"target",useEleOpacity)},getElementBox=function(ele){return ele.boundingBox(),ele[0]._private.bodyBounds},getLabelBox=function(ele){return ele.boundingBox(),ele[0]._private.labelBounds.main||emptyBb},getSourceLabelBox=function(ele){return ele.boundingBox(),ele[0]._private.labelBounds.source||emptyBb},getTargetLabelBox=function(ele){return ele.boundingBox(),ele[0]._private.labelBounds.target||emptyBb},isLabelVisibleAtScale=function(ele,scaledLabelShown){return scaledLabelShown},getElementRotationPoint=function(ele){return getBoxCenter(getElementBox(ele))},addTextMargin=function(prefix,pt,ele){var pre=prefix?prefix+"-":"";return{x:pt.x+ele.pstyle(pre+"text-margin-x").pfValue,y:pt.y+ele.pstyle(pre+"text-margin-y").pfValue}},getRsPt=function(ele,x2,y2){var rs=ele[0]._private.rscratch;return{x:rs[x2],y:rs[y2]}},getLabelRotationPoint=function(ele){return addTextMargin("",getRsPt(ele,"labelX","labelY"),ele)},getSourceLabelRotationPoint=function(ele){return addTextMargin("source",getRsPt(ele,"sourceLabelX","sourceLabelY"),ele)},getTargetLabelRotationPoint=function(ele){return addTextMargin("target",getRsPt(ele,"targetLabelX","targetLabelY"),ele)},getElementRotationOffset=function(ele){return getCenterOffset(getElementBox(ele))},getSourceLabelRotationOffset=function(ele){return getCenterOffset(getSourceLabelBox(ele))},getTargetLabelRotationOffset=function(ele){return getCenterOffset(getTargetLabelBox(ele))},getLabelRotationOffset=function(ele){var bb=getLabelBox(ele),p2=getCenterOffset(getLabelBox(ele));if(ele.isNode()){switch(labelHalign(ele.pstyle("text-halign").value)){case"left":p2.x=-bb.w-(bb.leftPad||0);break;case"right":p2.x=-(bb.rightPad||0);break}switch(labelValign(ele.pstyle("text-valign").value)){case"top":p2.y=-bb.h-(bb.topPad||0);break;case"bottom":p2.y=-(bb.botPad||0);break}}return p2},eleTxrCache=r.data.eleTxrCache=new ElementTextureCache(r,{getKey:getStyleKey,doesEleInvalidateKey:backgroundTimestampHasChanged,drawElement,getBoundingBox:getElementBox,getRotationPoint:getElementRotationPoint,getRotationOffset:getElementRotationOffset,allowEdgeTxrCaching:!1,allowParentTxrCaching:!1}),lblTxrCache=r.data.lblTxrCache=new ElementTextureCache(r,{getKey:getLabelKey,drawElement:drawLabel,getBoundingBox:getLabelBox,getRotationPoint:getLabelRotationPoint,getRotationOffset:getLabelRotationOffset,isVisible:isLabelVisibleAtScale}),slbTxrCache=r.data.slbTxrCache=new ElementTextureCache(r,{getKey:getSourceLabelKey,drawElement:drawSourceLabel,getBoundingBox:getSourceLabelBox,getRotationPoint:getSourceLabelRotationPoint,getRotationOffset:getSourceLabelRotationOffset,isVisible:isLabelVisibleAtScale}),tlbTxrCache=r.data.tlbTxrCache=new ElementTextureCache(r,{getKey:getTargetLabelKey,drawElement:drawTargetLabel,getBoundingBox:getTargetLabelBox,getRotationPoint:getTargetLabelRotationPoint,getRotationOffset:getTargetLabelRotationOffset,isVisible:isLabelVisibleAtScale}),lyrTxrCache=r.data.lyrTxrCache=new LayeredTextureCache(r);r.onUpdateEleCalcs(function(willDraw,eles){eleTxrCache.invalidateElements(eles),lblTxrCache.invalidateElements(eles),slbTxrCache.invalidateElements(eles),tlbTxrCache.invalidateElements(eles),lyrTxrCache.invalidateElements(eles);for(var _i=0;_i<eles.length;_i++){var _p=eles[_i]._private;_p.oldBackgroundTimestamp=_p.backgroundTimestamp}});var refineInLayers=function(reqs){for(var i3=0;i3<reqs.length;i3++)lyrTxrCache.enqueueElementRefinement(reqs[i3].ele)};eleTxrCache.onDequeue(refineInLayers),lblTxrCache.onDequeue(refineInLayers),slbTxrCache.onDequeue(refineInLayers),tlbTxrCache.onDequeue(refineInLayers),options2.webgl&&r.initWebgl(options2,{getStyleKey,getLabelKey,getSourceLabelKey,getTargetLabelKey,drawElement,drawLabel,drawSourceLabel,drawTargetLabel,getElementBox,getLabelBox,getSourceLabelBox,getTargetLabelBox,getElementRotationPoint,getElementRotationOffset,getLabelRotationPoint,getSourceLabelRotationPoint,getTargetLabelRotationPoint,getLabelRotationOffset,getSourceLabelRotationOffset,getTargetLabelRotationOffset})}CRp.redrawHint=function(group2,bool){var r=this;switch(group2){case"eles":r.data.canvasNeedsRedraw[CRp.NODE]=bool;break;case"drag":r.data.canvasNeedsRedraw[CRp.DRAG]=bool;break;case"select":r.data.canvasNeedsRedraw[CRp.SELECT_BOX]=bool;break;case"gc":r.data.gc=!0;break}};var pathsImpld=typeof Path2D<"u";CRp.path2dEnabled=function(on3){if(on3===void 0)return this.pathsEnabled;this.pathsEnabled=!!on3};CRp.usePaths=function(){return pathsImpld&&this.pathsEnabled};CRp.setImgSmoothing=function(context,bool){context.imageSmoothingEnabled!=null?context.imageSmoothingEnabled=bool:(context.webkitImageSmoothingEnabled=bool,context.mozImageSmoothingEnabled=bool,context.msImageSmoothingEnabled=bool)};CRp.getImgSmoothing=function(context){return context.imageSmoothingEnabled!=null?context.imageSmoothingEnabled:context.webkitImageSmoothingEnabled||context.mozImageSmoothingEnabled||context.msImageSmoothingEnabled};CRp.makeOffscreenCanvas=function(width2,height2){var canvas;if((typeof OffscreenCanvas>"u"?"undefined":_typeof(OffscreenCanvas))!=="undefined")canvas=new OffscreenCanvas(width2,height2);else{var containerWindow=this.cy.window(),document2=containerWindow.document;canvas=document2.createElement("canvas"),canvas.width=width2,canvas.height=height2}return canvas};[CRp$b,CRp$a,CRp$9,CRp$8,CRp$7,CRp$6,CRp$5,CRp$4,CRp$3,CRp$2,CRp$1].forEach(function(props){extend(CRp,props)});var renderer2=[{name:"null",impl:NullRenderer},{name:"base",impl:BR},{name:"canvas",impl:CR}],incExts=[{type:"layout",extensions:layout3},{type:"renderer",extensions:renderer2}],extensions={},modules={};function setExtension(type,name,registrant){var ext=registrant,overrideErr=function(field){warn("Can not register `"+name+"` for `"+type+"` since `"+field+"` already exists in the prototype and can not be overridden")};if(type==="core"){if(Core.prototype[name])return overrideErr(name);Core.prototype[name]=registrant}else if(type==="collection"){if(Collection.prototype[name])return overrideErr(name);Collection.prototype[name]=registrant}else if(type==="layout"){for(var Layout2=function(options2){this.options=options2,registrant.call(this,options2),plainObject(this._private)||(this._private={}),this._private.cy=options2.cy,this._private.listeners=[],this.createEmitter()},layoutProto=Layout2.prototype=Object.create(registrant.prototype),optLayoutFns=[],i2=0;i2<optLayoutFns.length;i2++){var fnName=optLayoutFns[i2];layoutProto[fnName]=layoutProto[fnName]||function(){return this}}layoutProto.start&&!layoutProto.run?layoutProto.run=function(){return this.start(),this}:!layoutProto.start&&layoutProto.run&&(layoutProto.start=function(){return this.run(),this});var regStop=registrant.prototype.stop;layoutProto.stop=function(){var opts=this.options;if(opts&&opts.animate){var anis=this.animations;if(anis)for(var _i=0;_i<anis.length;_i++)anis[_i].stop()}return regStop?regStop.call(this):this.emit("layoutstop"),this},layoutProto.destroy||(layoutProto.destroy=function(){return this}),layoutProto.cy=function(){return this._private.cy};var getCy=function(layout4){return layout4._private.cy},emitterOpts={addEventFields:function(layout4,evt){evt.layout=layout4,evt.cy=getCy(layout4),evt.target=layout4},bubble:function(){return!0},parent:function(layout4){return getCy(layout4)}};extend(layoutProto,{createEmitter:function(){return this._private.emitter=new Emitter(emitterOpts,this),this},emitter:function(){return this._private.emitter},on:function(evt,cb){return this.emitter().on(evt,cb),this},one:function(evt,cb){return this.emitter().one(evt,cb),this},once:function(evt,cb){return this.emitter().one(evt,cb),this},removeListener:function(evt,cb){return this.emitter().removeListener(evt,cb),this},removeAllListeners:function(){return this.emitter().removeAllListeners(),this},emit:function(evt,params){return this.emitter().emit(evt,params),this}}),define2.eventAliasesOn(layoutProto),ext=Layout2}else if(type==="renderer"&&name!=="null"&&name!=="base"){var BaseRenderer3=getExtension("renderer","base"),bProto=BaseRenderer3.prototype,RegistrantRenderer=registrant,rProto=registrant.prototype,Renderer=function(){BaseRenderer3.apply(this,arguments),RegistrantRenderer.apply(this,arguments)},proto=Renderer.prototype;for(var pName in bProto){var pVal=bProto[pName],existsInR=rProto[pName]!=null;if(existsInR)return overrideErr(pName);proto[pName]=pVal}for(var _pName in rProto)proto[_pName]=rProto[_pName];bProto.clientFunctions.forEach(function(name2){proto[name2]=proto[name2]||function(){error("Renderer does not implement `renderer."+name2+"()` on its prototype")}}),ext=Renderer}else if(type==="__proto__"||type==="constructor"||type==="prototype")return error(type+" is an illegal type to be registered, possibly lead to prototype pollutions");return setMap({map:extensions,keys:[type,name],value:ext})}function getExtension(type,name){return getMap({map:extensions,keys:[type,name]})}function setModule(type,name,moduleType,moduleName,registrant){return setMap({map:modules,keys:[type,name,moduleType,moduleName],value:registrant})}function getModule(type,name,moduleType,moduleName){return getMap({map:modules,keys:[type,name,moduleType,moduleName]})}var extension=function(){if(arguments.length===2)return getExtension.apply(null,arguments);if(arguments.length===3)return setExtension.apply(null,arguments);if(arguments.length===4)return getModule.apply(null,arguments);if(arguments.length===5)return setModule.apply(null,arguments);error("Invalid extension access syntax")};Core.prototype.extension=extension;incExts.forEach(function(group2){group2.extensions.forEach(function(ext){setExtension(group2.type,ext.name,ext.impl)})});var _Stylesheet=function(){if(!(this instanceof _Stylesheet))return new _Stylesheet;this.length=0},sheetfn=_Stylesheet.prototype;sheetfn.instanceString=function(){return"stylesheet"};sheetfn.selector=function(selector){var i2=this.length++;return this[i2]={selector,properties:[]},this};sheetfn.css=function(name,value){var i2=this.length-1;if(string(name))this[i2].properties.push({name,value});else if(plainObject(name))for(var map2=name,propNames=Object.keys(map2),j=0;j<propNames.length;j++){var key=propNames[j],mapVal=map2[key];if(mapVal!=null){var prop=_Style.properties[key]||_Style.properties[dash2camel(key)];if(prop!=null){var _name=prop.name,_value=mapVal;this[i2].properties.push({name:_name,value:_value})}}}return this};sheetfn.style=sheetfn.css;sheetfn.generateStyle=function(cy){var style3=new _Style(cy);return this.appendToStyle(style3)};sheetfn.appendToStyle=function(style3){for(var i2=0;i2<this.length;i2++){var context=this[i2],selector=context.selector,props=context.properties;style3.selector(selector);for(var j=0;j<props.length;j++){var prop=props[j];style3.css(prop.name,prop.value)}}return style3};var version="3.34.1",cytoscape2=function(options2){if(options2===void 0&&(options2={}),plainObject(options2))return new Core(options2);if(string(options2))return extension.apply(extension,arguments)};cytoscape2.use=function(ext){var args=Array.prototype.slice.call(arguments,1);return args.unshift(cytoscape2),ext.apply(null,args),this};cytoscape2.warnings=function(bool){return warnings(bool)};cytoscape2.version=version;cytoscape2.stylesheet=cytoscape2.Stylesheet=_Stylesheet;var import_cytoscape_fcose=__toESM(require_cytoscape_fcose());cytoscape2.use(import_cytoscape_fcose.default);globalThis.__StrataGateGraphLibraries={cytoscape:cytoscape2};globalThis.__STRATAGATE_GITHUB_STARS__=116;window.__ModuleLoader__.load({id:"stratagate-dsh",factory:require2=>{let module={exports:{}},exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});let React=require2("react"),h=React.createElement,cytoscape4=globalThis.__StrataGateGraphLibraries?.cytoscape,AGENT_FEEDBACK_ENABLED=!0,GITHUB_FEEDBACK_ENABLED=!0,FEEDBACK_EMAIL="jiahongcheng61@gmail.com",EMAIL_BODY_HINT=`\u8BF7\u5728\u4E0B\u65B9\u7C98\u8D34 StrataGate \u53CD\u9988\u62A5\u544A\uFF0C\u68C0\u67E5\u540E\u53D1\u9001\u3002\u4E5F\u53EF\u4EE5\u624B\u52A8\u9644\u52A0\u5DF2\u4E0B\u8F7D\u7684\u8BCA\u65AD\u6587\u4EF6\u3002\r
321
+ `),program=createProgram(gl,vertexShaderSource,fragmentShaderSource);program.aPosition=gl.getAttribLocation(program,"aPosition"),program.aIndex=gl.getAttribLocation(program,"aIndex"),program.aVertType=gl.getAttribLocation(program,"aVertType"),program.aTransform=gl.getAttribLocation(program,"aTransform"),program.aAtlasId=gl.getAttribLocation(program,"aAtlasId"),program.aTex=gl.getAttribLocation(program,"aTex"),program.aPointAPointB=gl.getAttribLocation(program,"aPointAPointB"),program.aPointCPointD=gl.getAttribLocation(program,"aPointCPointD"),program.aLineWidth=gl.getAttribLocation(program,"aLineWidth"),program.aColor=gl.getAttribLocation(program,"aColor"),program.aCornerRadius=gl.getAttribLocation(program,"aCornerRadius"),program.aBorderColor=gl.getAttribLocation(program,"aBorderColor"),program.uPanZoomMatrix=gl.getUniformLocation(program,"uPanZoomMatrix"),program.uAtlasSize=gl.getUniformLocation(program,"uAtlasSize"),program.uBGColor=gl.getUniformLocation(program,"uBGColor"),program.uZoom=gl.getUniformLocation(program,"uZoom"),program.uTextures=[];for(var i2=0;i2<this.batchManager.getMaxAtlasesPerBatch();i2++)program.uTextures.push(gl.getUniformLocation(program,"uTexture".concat(i2)));return program}},{key:"_createVAO",value:function(){var unitSquare=[0,0,1,0,1,1,0,0,1,1,0,1];this.vertexCount=unitSquare.length/2;var n=this.maxInstances,gl=this.gl,program=this.program,vao=gl.createVertexArray();return gl.bindVertexArray(vao),createBufferStaticDraw(gl,"vec2",program.aPosition,unitSquare),this.transformBuffer=create3x3MatrixBufferDynamicDraw(gl,n,program.aTransform),this.indexBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aIndex),this.vertTypeBuffer=createBufferDynamicDraw(gl,n,"int",program.aVertType),this.atlasIdBuffer=createBufferDynamicDraw(gl,n,"int",program.aAtlasId),this.texBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aTex),this.pointAPointBBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aPointAPointB),this.pointCPointDBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aPointCPointD),this.lineWidthBuffer=createBufferDynamicDraw(gl,n,"vec2",program.aLineWidth),this.colorBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aColor),this.cornerRadiusBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aCornerRadius),this.borderColorBuffer=createBufferDynamicDraw(gl,n,"vec4",program.aBorderColor),gl.bindVertexArray(null),vao}},{key:"buffers",get:function(){var _this=this;return this._buffers||(this._buffers=Object.keys(this).filter(function(k){return endsWith(k,"Buffer")}).map(function(k){return _this[k]})),this._buffers}},{key:"startFrame",value:function(panZoomMatrix){var renderTarget=arguments.length>1&&arguments[1]!==void 0?arguments[1]:RENDER_TARGET.SCREEN;this.panZoomMatrix=panZoomMatrix,this.renderTarget=renderTarget,this.batchDebugInfo=[],this.wrappedCount=0,this.simpleCount=0,this.startBatch()}},{key:"startBatch",value:function(){this.instanceCount=0,this.batchManager.startBatch()}},{key:"endFrame",value:function(){this.endBatch()}},{key:"_isVisible",value:function(ele,opts){return ele.visible()?opts&&opts.isVisible?opts.isVisible(ele):!0:!1}},{key:"drawTexture",value:function(ele,eleIndex,type){var atlasManager=this.atlasManager,batchManager=this.batchManager,opts=atlasManager.getRenderTypeOpts(type);if(this._isVisible(ele,opts)&&!(ele.isEdge()&&!this._isValidEdge(ele))){if(this.renderTarget.picking&&opts.getTexPickingMode){var mode=opts.getTexPickingMode(ele);if(mode===TEX_PICKING_MODE.IGNORE)return;if(mode==TEX_PICKING_MODE.USE_BB){this.drawPickingRectangle(ele,eleIndex,type);return}}var atlasInfoArray=atlasManager.getAtlasInfo(ele,type),_iterator=_createForOfIteratorHelper(atlasInfoArray),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var atlasInfo=_step.value,atlas=atlasInfo.atlas,tex1=atlasInfo.tex1,tex2=atlasInfo.tex2;batchManager.canAddToCurrentBatch(atlas)||this.endBatch();for(var atlasIndex=batchManager.getAtlasIndexForBatch(atlas),_i=0,_arr=[[tex1,!0],[tex2,!1]];_i<_arr.length;_i++){var _arr$_i=_slicedToArray(_arr[_i],2),tex=_arr$_i[0],first2=_arr$_i[1];if(tex.w!=0){var instance2=this.instanceCount;this.vertTypeBuffer.getView(instance2)[0]=TEXTURE;var indexView=this.indexBuffer.getView(instance2);indexToVec4(eleIndex,indexView);var atlasIdView=this.atlasIdBuffer.getView(instance2);atlasIdView[0]=atlasIndex;var texView=this.texBuffer.getView(instance2);texView[0]=tex.x,texView[1]=tex.y,texView[2]=tex.w,texView[3]=tex.h;var matrixView=this.transformBuffer.getMatrixView(instance2);this.setTransformMatrix(ele,matrixView,opts,atlasInfo,first2),this.instanceCount++,first2||this.wrappedCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}}}catch(err){_iterator.e(err)}finally{_iterator.f()}}}},{key:"setTransformMatrix",value:function(ele,matrix,opts,atlasInfo){var first2=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,padding=0;if(opts.shapeProps&&opts.shapeProps.padding&&(padding=ele.pstyle(opts.shapeProps.padding).pfValue),atlasInfo){var bb=atlasInfo.bb,tex1=atlasInfo.tex1,tex2=atlasInfo.tex2,ratio=tex1.w/(tex1.w+tex2.w);first2||(ratio=1-ratio);var adjBB=this._getAdjustedBB(bb,padding,first2,ratio);this._applyTransformMatrix(matrix,adjBB,opts,ele)}else{var _bb=opts.getBoundingBox(ele),_adjBB=this._getAdjustedBB(_bb,padding,!0,1);this._applyTransformMatrix(matrix,_adjBB,opts,ele)}}},{key:"_applyTransformMatrix",value:function(matrix,adjBB,opts,ele){var x2,y2;identity2(matrix);var theta=opts.getRotation?opts.getRotation(ele):0;if(theta!==0){var _opts$getRotationPoin=opts.getRotationPoint(ele),sx=_opts$getRotationPoin.x,sy=_opts$getRotationPoin.y;translate(matrix,matrix,[sx,sy]),rotate(matrix,matrix,theta);var offset=opts.getRotationOffset(ele);x2=offset.x+(adjBB.xOffset||0),y2=offset.y+(adjBB.yOffset||0)}else x2=adjBB.x1,y2=adjBB.y1;translate(matrix,matrix,[x2,y2]),scale(matrix,matrix,[adjBB.w,adjBB.h])}},{key:"_getAdjustedBB",value:function(bb,padding,first2,ratio){var x1=bb.x1,y1=bb.y1,w=bb.w,h=bb.h,yOffset=bb.yOffset;padding&&(x1-=padding,y1-=padding,w+=2*padding,h+=2*padding);var xOffset=0,adjW=w*ratio;return first2&&ratio<1?w=adjW:!first2&&ratio<1&&(xOffset=w-adjW,x1+=xOffset,w=adjW),{x1,y1,w,h,xOffset,yOffset}}},{key:"drawPickingRectangle",value:function(ele,eleIndex,type){var opts=this.atlasManager.getRenderTypeOpts(type),instance2=this.instanceCount;this.vertTypeBuffer.getView(instance2)[0]=RECTANGLE;var indexView=this.indexBuffer.getView(instance2);indexToVec4(eleIndex,indexView);var colorView=this.colorBuffer.getView(instance2);toWebGLColor([0,0,0],1,colorView);var matrixView=this.transformBuffer.getMatrixView(instance2);this.setTransformMatrix(ele,matrixView,opts),this.simpleCount++,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}},{key:"drawNode",value:function(node,eleIndex,type){var opts=this.simpleShapeOptions.get(type);if(this._isVisible(node,opts)){var props=opts.shapeProps,vertType=this._getVertTypeForShape(node,props.shape);if(vertType===void 0||opts.isSimple&&!opts.isSimple(node,this.renderTarget)){this.drawTexture(node,eleIndex,type);return}var instance2=this.instanceCount;if(this.vertTypeBuffer.getView(instance2)[0]=vertType,vertType===ROUND_RECTANGLE||vertType===BOTTOM_ROUND_RECTANGLE){var bb=opts.getBoundingBox(node),radius2=this._getCornerRadius(node,props.radius,bb),radiusView=this.cornerRadiusBuffer.getView(instance2);radiusView[0]=radius2,radiusView[1]=radius2,radiusView[2]=radius2,radiusView[3]=radius2,vertType===BOTTOM_ROUND_RECTANGLE&&(radiusView[0]=0,radiusView[2]=0)}var indexView=this.indexBuffer.getView(instance2);indexToVec4(eleIndex,indexView);var opacity=this.renderTarget.picking?1:type==="node-body"?node.effectiveOpacity():1,bgOpacity=this.renderTarget.picking?1:node.pstyle(props.opacity).value*opacity,color=node.pstyle(props.color).value,colorView=this.colorBuffer.getView(instance2);toWebGLColor(color,bgOpacity,colorView);var lineWidthView=this.lineWidthBuffer.getView(instance2);if(lineWidthView[0]=0,lineWidthView[1]=0,props.border){var borderWidth=node.pstyle("border-width").value;if(borderWidth>0){var borderColor=node.pstyle("border-color").value,borderOpacity=opacity*node.pstyle("border-opacity").value,borderColorView=this.borderColorBuffer.getView(instance2);toWebGLColor(borderColor,borderOpacity,borderColorView);var borderPos=node.pstyle("border-position").value;if(borderPos==="inside")lineWidthView[0]=0,lineWidthView[1]=-borderWidth;else if(borderPos==="outside")lineWidthView[0]=borderWidth,lineWidthView[1]=0;else{var halfWidth=borderWidth/2;lineWidthView[0]=halfWidth,lineWidthView[1]=-halfWidth}}}var matrixView=this.transformBuffer.getMatrixView(instance2);this.setTransformMatrix(node,matrixView,opts),this.simpleCount++,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}},{key:"_getVertTypeForShape",value:function(node,shapeProp){var shape=node.pstyle(shapeProp).value;switch(shape){case"rectangle":return RECTANGLE;case"ellipse":return ELLIPSE;case"roundrectangle":case"round-rectangle":return ROUND_RECTANGLE;case"bottom-round-rectangle":return BOTTOM_ROUND_RECTANGLE;default:return}}},{key:"_getCornerRadius",value:function(node,radiusProp,_ref2){var w=_ref2.w,h=_ref2.h;if(node.pstyle(radiusProp).value==="auto")return getRoundRectangleRadius(w,h);var radius2=node.pstyle(radiusProp).pfValue,halfWidth=w/2,halfHeight=h/2;return Math.min(radius2,halfHeight,halfWidth)}},{key:"drawEdgeArrow",value:function(edge,eleIndex,prefix){if(edge.visible()){var rs=edge._private.rscratch,x2,y2,angle2;if(prefix==="source"?(x2=rs.arrowStartX,y2=rs.arrowStartY,angle2=rs.srcArrowAngle):(x2=rs.arrowEndX,y2=rs.arrowEndY,angle2=rs.tgtArrowAngle),!(isNaN(x2)||x2==null||isNaN(y2)||y2==null||isNaN(angle2)||angle2==null)){var arrowShape=edge.pstyle(prefix+"-arrow-shape").value;if(arrowShape!=="none"){var color=edge.pstyle(prefix+"-arrow-color").value,baseOpacity=edge.pstyle("opacity").value,lineOpacity=edge.pstyle("line-opacity").value,opacity=baseOpacity*lineOpacity,lineWidth=edge.pstyle("width").pfValue,scale$1=edge.pstyle("arrow-scale").value,size3=this.r.getArrowWidth(lineWidth,scale$1),instance2=this.instanceCount,transform7=this.transformBuffer.getMatrixView(instance2);identity2(transform7),translate(transform7,transform7,[x2,y2]),scale(transform7,transform7,[size3,size3]),rotate(transform7,transform7,angle2),this.vertTypeBuffer.getView(instance2)[0]=EDGE_ARROW;var indexView=this.indexBuffer.getView(instance2);indexToVec4(eleIndex,indexView);var colorView=this.colorBuffer.getView(instance2);toWebGLColor(color,opacity,colorView),this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}}}},{key:"drawEdgeLine",value:function(edge,eleIndex){if(edge.visible()){var points=this._getEdgePoints(edge);if(points){var baseOpacity=edge.pstyle("opacity").value,lineOpacity=edge.pstyle("line-opacity").value,width2=edge.pstyle("width").pfValue,color=edge.pstyle("line-color").value,opacity=baseOpacity*lineOpacity;if(points.length/2+this.instanceCount>this.maxInstances&&this.endBatch(),points.length==4){var instance2=this.instanceCount;this.vertTypeBuffer.getView(instance2)[0]=EDGE_STRAIGHT;var indexView=this.indexBuffer.getView(instance2);indexToVec4(eleIndex,indexView);var colorView=this.colorBuffer.getView(instance2);toWebGLColor(color,opacity,colorView);var lineWidthBuffer=this.lineWidthBuffer.getView(instance2);lineWidthBuffer[0]=width2;var sourceTargetView=this.pointAPointBBuffer.getView(instance2);sourceTargetView[0]=points[0],sourceTargetView[1]=points[1],sourceTargetView[2]=points[2],sourceTargetView[3]=points[3],this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}else for(var i2=0;i2<points.length-2;i2+=2){var _instance=this.instanceCount;this.vertTypeBuffer.getView(_instance)[0]=EDGE_CURVE_SEGMENT;var _indexView=this.indexBuffer.getView(_instance);indexToVec4(eleIndex,_indexView);var _colorView=this.colorBuffer.getView(_instance);toWebGLColor(color,opacity,_colorView);var _lineWidthBuffer=this.lineWidthBuffer.getView(_instance);_lineWidthBuffer[0]=width2;var pAx=points[i2-2],pAy=points[i2-1],pBx=points[i2],pBy=points[i2+1],pCx=points[i2+2],pCy=points[i2+3],pDx=points[i2+4],pDy=points[i2+5];i2==0&&(pAx=2*pBx-pCx+.001,pAy=2*pBy-pCy+.001),i2==points.length-4&&(pDx=2*pCx-pBx+.001,pDy=2*pCy-pBy+.001);var pointABView=this.pointAPointBBuffer.getView(_instance);pointABView[0]=pAx,pointABView[1]=pAy,pointABView[2]=pBx,pointABView[3]=pBy;var pointCDView=this.pointCPointDBuffer.getView(_instance);pointCDView[0]=pCx,pointCDView[1]=pCy,pointCDView[2]=pDx,pointCDView[3]=pDy,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}}}},{key:"_isValidEdge",value:function(edge){var rs=edge._private.rscratch;return!(rs.badLine||rs.allpts==null||isNaN(rs.allpts[0]))}},{key:"_getEdgePoints",value:function(edge){var rs=edge._private.rscratch;if(this._isValidEdge(edge)){var controlPoints3=rs.allpts;if(controlPoints3.length==4)return controlPoints3;var numSegments=this._getNumSegments(edge);return this._getCurveSegmentPoints(controlPoints3,numSegments)}}},{key:"_getNumSegments",value:function(edge){var numSegments=15;return Math.min(Math.max(numSegments,5),this.maxInstances)}},{key:"_getCurveSegmentPoints",value:function(controlPoints3,segments){if(controlPoints3.length==4)return controlPoints3;for(var curvePoints=Array((segments+1)*2),i2=0;i2<=segments;i2++)if(i2==0)curvePoints[0]=controlPoints3[0],curvePoints[1]=controlPoints3[1];else if(i2==segments)curvePoints[i2*2]=controlPoints3[controlPoints3.length-2],curvePoints[i2*2+1]=controlPoints3[controlPoints3.length-1];else{var t=i2/segments;this._setCurvePoint(controlPoints3,t,curvePoints,i2*2)}return curvePoints}},{key:"_setCurvePoint",value:function(points,t,curvePoints,cpi){if(points.length<=2)curvePoints[cpi]=points[0],curvePoints[cpi+1]=points[1];else{for(var newpoints=Array(points.length-2),i2=0;i2<newpoints.length;i2+=2){var x2=(1-t)*points[i2]+t*points[i2+2],y2=(1-t)*points[i2+1]+t*points[i2+3];newpoints[i2]=x2,newpoints[i2+1]=y2}return this._setCurvePoint(newpoints,t,curvePoints,cpi)}}},{key:"endBatch",value:function(){var gl=this.gl,vao=this.vao,vertexCount=this.vertexCount,count=this.instanceCount;if(count!==0){var program=this.renderTarget.picking?this.pickingProgram:this.program;gl.useProgram(program),gl.bindVertexArray(vao);var _iterator2=_createForOfIteratorHelper(this.buffers),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var buffer=_step2.value;buffer.bufferSubData(count)}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}for(var atlases=this.batchManager.getAtlases(),i2=0;i2<atlases.length;i2++)atlases[i2].bufferIfNeeded(gl);for(var _i2=0;_i2<atlases.length;_i2++)gl.activeTexture(gl.TEXTURE0+_i2),gl.bindTexture(gl.TEXTURE_2D,atlases[_i2].texture),gl.uniform1i(program.uTextures[_i2],_i2);gl.uniform1f(program.uZoom,getEffectiveZoom(this.r)),gl.uniformMatrix3fv(program.uPanZoomMatrix,!1,this.panZoomMatrix),gl.uniform1i(program.uAtlasSize,this.batchManager.getAtlasSize());var webglBgColor=toWebGLColor(this.bgColor,1);gl.uniform4fv(program.uBGColor,webglBgColor),gl.drawArraysInstanced(gl.TRIANGLES,0,vertexCount,count),gl.bindVertexArray(null),gl.bindTexture(gl.TEXTURE_2D,null),this.debug&&this.batchDebugInfo.push({count,atlasCount:atlases.length}),this.startBatch()}}},{key:"getDebugInfo",value:function(){var atlasInfo=this.atlasManager.getDebugInfo(),totalAtlases=atlasInfo.reduce(function(count,info){return count+info.atlasCount},0),batchInfo=this.batchDebugInfo,totalInstances=batchInfo.reduce(function(count,info){return count+info.count},0);return{atlasInfo,totalAtlases,wrappedCount:this.wrappedCount,simpleCount:this.simpleCount,batchCount:batchInfo.length,batchInfo,totalInstances}}}])})(),CRp$4={};CRp$4.initWebgl=function(opts,fns){var r=this,gl=r.data.contexts[r.WEBGL];opts.bgColor=getBGColor(r),opts.webglTexSize=Math.min(opts.webglTexSize,gl.getParameter(gl.MAX_TEXTURE_SIZE)),opts.webglTexRows=Math.min(opts.webglTexRows,54),opts.webglTexRowsNodes=Math.min(opts.webglTexRowsNodes,54),opts.webglBatchSize=Math.min(opts.webglBatchSize,16384),opts.webglTexPerBatch=Math.min(opts.webglTexPerBatch,gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS)),r.webglDebug=opts.webglDebug,r.webglDebugShowAtlases=opts.webglDebugShowAtlases,r.pickingFrameBuffer=createPickingFrameBuffer(gl),r.pickingFrameBuffer.needsDraw=!0,r.drawing=new ElementDrawingWebGL(r,gl,opts);var getLabelRotation3=function(prop){return function(ele){return r.getTextAngle(ele,prop)}},isLabelVisible=function(prop){return function(ele){var label=ele.pstyle(prop);return label&&label.value}},isLayerVisible=function(prefix){return function(node){return node.pstyle("".concat(prefix,"-opacity")).value>0}},getTexPickingMode=function(ele){var enabled=ele.pstyle("text-events").strValue==="yes";return enabled?TEX_PICKING_MODE.USE_BB:TEX_PICKING_MODE.IGNORE},getBBForSimpleShape=function(node){var _node$position=node.position(),x2=_node$position.x,y2=_node$position.y,w=node.outerWidth(),h=node.outerHeight();return{w,h,x1:x2-w/2,y1:y2-h/2}};r.drawing.addAtlasCollection("node",{texRows:opts.webglTexRowsNodes}),r.drawing.addAtlasCollection("label",{texRows:opts.webglTexRows}),r.drawing.addTextureAtlasRenderType("node-body",{collection:"node",getKey:fns.getStyleKey,getBoundingBox:fns.getElementBox,drawElement:fns.drawElement}),r.drawing.addSimpleShapeRenderType("node-body",{getBoundingBox:getBBForSimpleShape,isSimple:isSimpleShape,shapeProps:{shape:"shape",color:"background-color",opacity:"background-opacity",radius:"corner-radius",border:!0}}),r.drawing.addSimpleShapeRenderType("node-overlay",{getBoundingBox:getBBForSimpleShape,isVisible:isLayerVisible("overlay"),shapeProps:{shape:"overlay-shape",color:"overlay-color",opacity:"overlay-opacity",padding:"overlay-padding",radius:"overlay-corner-radius"}}),r.drawing.addSimpleShapeRenderType("node-underlay",{getBoundingBox:getBBForSimpleShape,isVisible:isLayerVisible("underlay"),shapeProps:{shape:"underlay-shape",color:"underlay-color",opacity:"underlay-opacity",padding:"underlay-padding",radius:"underlay-corner-radius"}}),r.drawing.addTextureAtlasRenderType("label",{collection:"label",getTexPickingMode,getKey:getStyleKeysForLabel(fns.getLabelKey,null),getBoundingBox:getBoundingBoxForLabel(fns.getLabelBox,null),drawClipped:!0,drawElement:fns.drawLabel,getRotation:getLabelRotation3(null),getRotationPoint:fns.getLabelRotationPoint,getRotationOffset:fns.getLabelRotationOffset,isVisible:isLabelVisible("label")}),r.drawing.addTextureAtlasRenderType("edge-source-label",{collection:"label",getTexPickingMode,getKey:getStyleKeysForLabel(fns.getSourceLabelKey,"source"),getBoundingBox:getBoundingBoxForLabel(fns.getSourceLabelBox,"source"),drawClipped:!0,drawElement:fns.drawSourceLabel,getRotation:getLabelRotation3("source"),getRotationPoint:fns.getSourceLabelRotationPoint,getRotationOffset:fns.getSourceLabelRotationOffset,isVisible:isLabelVisible("source-label")}),r.drawing.addTextureAtlasRenderType("edge-target-label",{collection:"label",getTexPickingMode,getKey:getStyleKeysForLabel(fns.getTargetLabelKey,"target"),getBoundingBox:getBoundingBoxForLabel(fns.getTargetLabelBox,"target"),drawClipped:!0,drawElement:fns.drawTargetLabel,getRotation:getLabelRotation3("target"),getRotationPoint:fns.getTargetLabelRotationPoint,getRotationOffset:fns.getTargetLabelRotationOffset,isVisible:isLabelVisible("target-label")});var setGCFlag=debounce(function(){console.log("garbage collect flag set"),r.data.gc=!0},1e4);r.onUpdateEleCalcs(function(willDraw,eles){var gcNeeded=!1;eles&&eles.length>0&&(gcNeeded|=r.drawing.invalidate(eles)),gcNeeded&&setGCFlag()}),overrideCanvasRendererFunctions(r)};function getBGColor(r){var container2=r.cy.container(),cssColor=container2&&container2.style&&container2.style.backgroundColor||"white";return color2tuple(cssColor)}function getLabelLines(ele,prefix){var rs=ele._private.rscratch;return getPrefixedProperty(rs,"labelWrapCachedLines",prefix)||[]}var getStyleKeysForLabel=function(getKey3,prefix){return function(ele){var key=getKey3(ele),lines=getLabelLines(ele,prefix);return lines.length>1?lines.map(function(line,index){return"".concat(key,"_").concat(index)}):key}},getBoundingBoxForLabel=function(getBoundingBox,prefix){return function(ele,styleKey){var bb=getBoundingBox(ele);if(typeof styleKey=="string"){var ui=styleKey.indexOf("_");if(ui>0){var lineIndex=Number(styleKey.substring(ui+1)),lines=getLabelLines(ele,prefix),h=bb.h/lines.length,yOffset=h*lineIndex,y1=bb.y1+yOffset;return{x1:bb.x1,w:bb.w,y1,h,yOffset}}}return bb}};function overrideCanvasRendererFunctions(r){{var renderCanvas=r.render;r.render=function(options2){options2=options2||{};var cy=r.cy;r.webgl&&(cy.zoom()>maxZoom$1?(clearWebgl(r),renderCanvas.call(r,options2)):(clearCanvas(r),renderWebgl(r,options2,RENDER_TARGET.SCREEN)))}}{var baseFunc=r.matchCanvasSize;r.matchCanvasSize=function(container2){baseFunc.call(r,container2),r.pickingFrameBuffer.setFramebufferAttachmentSizes(r.canvasWidth,r.canvasHeight),r.pickingFrameBuffer.needsDraw=!0}}r.findNearestElements=function(x2,y2,interactiveElementsOnly,isTouch){return findNearestElementsWebgl(r,x2,y2)};{var _baseFunc=r.invalidateCachedZSortedEles;r.invalidateCachedZSortedEles=function(){_baseFunc.call(r),r.pickingFrameBuffer.needsDraw=!0}}{var _baseFunc2=r.notify;r.notify=function(eventName,eles){_baseFunc2.call(r,eventName,eles),eventName==="viewport"||eventName==="bounds"?r.pickingFrameBuffer.needsDraw=!0:eventName==="background"&&r.drawing.invalidate(eles,{type:"node-body"})}}}function clearWebgl(r){var gl=r.data.contexts[r.WEBGL];gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT)}function clearCanvas(r){var clear=function(context){context.save(),context.setTransform(1,0,0,1,0,0),context.clearRect(0,0,r.canvasWidth,r.canvasHeight),context.restore()};clear(r.data.contexts[r.NODE]),clear(r.data.contexts[r.DRAG])}function createPanZoomMatrix(r){var width2=r.canvasWidth,height2=r.canvasHeight,_util$getEffectivePan=getEffectivePanZoom(r),pan2=_util$getEffectivePan.pan,zoom2=_util$getEffectivePan.zoom,transform7=create();translate(transform7,transform7,[pan2.x,pan2.y]),scale(transform7,transform7,[zoom2,zoom2]);var projection$1=create();projection(projection$1,width2,height2);var product=create();return multiply(product,projection$1,transform7),product}function setContextTransform(r,context){var width2=r.canvasWidth,height2=r.canvasHeight,_util$getEffectivePan2=getEffectivePanZoom(r),pan2=_util$getEffectivePan2.pan,zoom2=_util$getEffectivePan2.zoom;context.setTransform(1,0,0,1,0,0),context.clearRect(0,0,width2,height2),context.translate(pan2.x,pan2.y),context.scale(zoom2,zoom2)}function drawSelectionRectangle(r,options2){r.drawSelectionRectangle(options2,function(context){return setContextTransform(r,context)})}function drawAxes(r){var context=r.data.contexts[r.NODE];context.save(),setContextTransform(r,context),context.strokeStyle="rgba(0, 0, 0, 0.3)",context.beginPath(),context.moveTo(-1e3,0),context.lineTo(1e3,0),context.stroke(),context.beginPath(),context.moveTo(0,-1e3),context.lineTo(0,1e3),context.stroke(),context.restore()}function drawAtlases(r){var draw=function(drawing,name,row){for(var collection4=drawing.atlasManager.getAtlasCollection(name),context=r.data.contexts[r.NODE],atlases=collection4.atlases,_i=0;_i<atlases.length;_i++){var atlas=atlases[_i],canvas=atlas.canvas;if(canvas){var w=canvas.width,h=canvas.height,x2=w*_i,y2=canvas.height*row,scale2=.4;context.save(),context.scale(scale2,scale2),context.drawImage(canvas,x2,y2),context.strokeStyle="black",context.rect(x2,y2,w,h),context.stroke(),context.restore()}}},i2=0;draw(r.drawing,"node",i2++),draw(r.drawing,"label",i2++)}function getPickingIndexes(r,mX1,mY1,mX2,mY2){var x2,y2,w,h,_util$getEffectivePan3=getEffectivePanZoom(r),pan2=_util$getEffectivePan3.pan,zoom2=_util$getEffectivePan3.zoom;{var _util$modelToRendered=modelToRenderedPosition2(r,pan2,zoom2,mX1,mY1),_util$modelToRendered2=_slicedToArray(_util$modelToRendered,2),cX1=_util$modelToRendered2[0],cY1=_util$modelToRendered2[1],t=6;x2=cX1-t/2,y2=cY1-t/2,w=t,h=t}if(w===0||h===0)return[];var gl=r.data.contexts[r.WEBGL];gl.bindFramebuffer(gl.FRAMEBUFFER,r.pickingFrameBuffer),r.pickingFrameBuffer.needsDraw&&(gl.viewport(0,0,gl.canvas.width,gl.canvas.height),renderWebgl(r,null,RENDER_TARGET.PICKING),r.pickingFrameBuffer.needsDraw=!1);var n=w*h,data4=new Uint8Array(n*4);gl.readPixels(x2,y2,w,h,gl.RGBA,gl.UNSIGNED_BYTE,data4),gl.bindFramebuffer(gl.FRAMEBUFFER,null);for(var indexes=new Set,i2=0;i2<n;i2++){var pixel=data4.slice(i2*4,i2*4+4),index=vec4ToIndex(pixel)-1;index>=0&&indexes.add(index)}return indexes}function findNearestElementsWebgl(r,x2,y2){var indexes=getPickingIndexes(r,x2,y2),eles=r.getCachedZSortedEles(),node,edge,_iterator=_createForOfIteratorHelper(indexes),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var index=_step.value,ele=eles[index];if(!node&&ele.isNode()&&(node=ele),!edge&&ele.isEdge()&&(edge=ele),node&&edge)break}}catch(err){_iterator.e(err)}finally{_iterator.f()}return[node,edge].filter(Boolean)}function drawEle(r,index,ele){var drawing=r.drawing;index+=1,ele.isNode()?(drawing.drawNode(ele,index,"node-underlay"),drawing.drawNode(ele,index,"node-body"),drawing.drawTexture(ele,index,"label"),drawing.drawNode(ele,index,"node-overlay")):(drawing.drawEdgeLine(ele,index),drawing.drawEdgeArrow(ele,index,"source"),drawing.drawEdgeArrow(ele,index,"target"),drawing.drawTexture(ele,index,"label"),drawing.drawTexture(ele,index,"edge-source-label"),drawing.drawTexture(ele,index,"edge-target-label"))}function renderWebgl(r,options2,renderTarget){var start;r.webglDebug&&(start=performance.now());var drawing=r.drawing,eleCount=0;if(renderTarget.screen&&r.data.canvasNeedsRedraw[r.SELECT_BOX]&&drawSelectionRectangle(r,options2),r.data.canvasNeedsRedraw[r.NODE]||renderTarget.picking){var gl=r.data.contexts[r.WEBGL];renderTarget.screen?(gl.clearColor(0,0,0,0),gl.enable(gl.BLEND),gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA)):gl.disable(gl.BLEND),gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT),gl.viewport(0,0,gl.canvas.width,gl.canvas.height);var panZoomMatrix=createPanZoomMatrix(r),eles=r.getCachedZSortedEles();if(eleCount=eles.length,drawing.startFrame(panZoomMatrix,renderTarget),renderTarget.screen){for(var i2=0;i2<eles.nondrag.length;i2++)drawEle(r,i2,eles.nondrag[i2]);for(var _i2=0;_i2<eles.drag.length;_i2++)drawEle(r,_i2,eles.drag[_i2])}else if(renderTarget.picking)for(var _i3=0;_i3<eles.length;_i3++)drawEle(r,_i3,eles[_i3]);drawing.endFrame(),renderTarget.screen&&r.webglDebugShowAtlases&&(drawAxes(r),drawAtlases(r)),r.data.canvasNeedsRedraw[r.NODE]=!1,r.data.canvasNeedsRedraw[r.DRAG]=!1}if(r.webglDebug){var end=performance.now(),compact=!1,time2=Math.ceil(end-start),debugInfo=drawing.getDebugInfo(),report=["".concat(eleCount," elements"),"".concat(debugInfo.totalInstances," instances"),"".concat(debugInfo.batchCount," batches"),"".concat(debugInfo.totalAtlases," atlases"),"".concat(debugInfo.wrappedCount," wrapped textures"),"".concat(debugInfo.simpleCount," simple shapes")].join(", ");if(compact)console.log("WebGL (".concat(renderTarget.name,") - time ").concat(time2,"ms, ").concat(report));else{console.log("WebGL (".concat(renderTarget.name,") - frame time ").concat(time2,"ms")),console.log("Totals:"),console.log(" ".concat(report)),console.log("Texture Atlases Used:");var atlasInfo=debugInfo.atlasInfo,_iterator2=_createForOfIteratorHelper(atlasInfo),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var info=_step2.value;console.log(" ".concat(info.type,": ").concat(info.keyCount," keys, ").concat(info.atlasCount," atlases"))}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}console.log("")}}r.data.gc&&(console.log("Garbage Collect!"),r.data.gc=!1,drawing.gc())}var CRp$3={};CRp$3.drawPolygonPath=function(context,x2,y2,width2,height2,points){var halfW=width2/2,halfH=height2/2;context.beginPath&&context.beginPath(),context.moveTo(x2+halfW*points[0],y2+halfH*points[1]);for(var i2=1;i2<points.length/2;i2++)context.lineTo(x2+halfW*points[i2*2],y2+halfH*points[i2*2+1]);context.closePath()};CRp$3.drawRoundPolygonPath=function(context,x2,y2,width2,height2,points,corners){corners.forEach(function(corner){return drawPreparedRoundCorner(context,corner)}),context.closePath()};CRp$3.drawRoundRectanglePath=function(context,x2,y2,width2,height2,radius2){var halfWidth=width2/2,halfHeight=height2/2,cornerRadius=radius2==="auto"?getRoundRectangleRadius(width2,height2):Math.min(radius2,halfHeight,halfWidth);context.beginPath&&context.beginPath(),context.moveTo(x2,y2-halfHeight),context.arcTo(x2+halfWidth,y2-halfHeight,x2+halfWidth,y2,cornerRadius),context.arcTo(x2+halfWidth,y2+halfHeight,x2,y2+halfHeight,cornerRadius),context.arcTo(x2-halfWidth,y2+halfHeight,x2-halfWidth,y2,cornerRadius),context.arcTo(x2-halfWidth,y2-halfHeight,x2,y2-halfHeight,cornerRadius),context.lineTo(x2,y2-halfHeight),context.closePath()};CRp$3.drawBottomRoundRectanglePath=function(context,x2,y2,width2,height2,radius2){var halfWidth=width2/2,halfHeight=height2/2,cornerRadius=radius2==="auto"?getRoundRectangleRadius(width2,height2):radius2;context.beginPath&&context.beginPath(),context.moveTo(x2,y2-halfHeight),context.lineTo(x2+halfWidth,y2-halfHeight),context.lineTo(x2+halfWidth,y2),context.arcTo(x2+halfWidth,y2+halfHeight,x2,y2+halfHeight,cornerRadius),context.arcTo(x2-halfWidth,y2+halfHeight,x2-halfWidth,y2,cornerRadius),context.lineTo(x2-halfWidth,y2-halfHeight),context.lineTo(x2,y2-halfHeight),context.closePath()};CRp$3.drawCutRectanglePath=function(context,x2,y2,width2,height2,points,corners){var halfWidth=width2/2,halfHeight=height2/2,cornerLength=corners==="auto"?getCutRectangleCornerLength():corners;context.beginPath&&context.beginPath(),context.moveTo(x2-halfWidth+cornerLength,y2-halfHeight),context.lineTo(x2+halfWidth-cornerLength,y2-halfHeight),context.lineTo(x2+halfWidth,y2-halfHeight+cornerLength),context.lineTo(x2+halfWidth,y2+halfHeight-cornerLength),context.lineTo(x2+halfWidth-cornerLength,y2+halfHeight),context.lineTo(x2-halfWidth+cornerLength,y2+halfHeight),context.lineTo(x2-halfWidth,y2+halfHeight-cornerLength),context.lineTo(x2-halfWidth,y2-halfHeight+cornerLength),context.closePath()};CRp$3.drawBarrelPath=function(context,x2,y2,width2,height2){var halfWidth=width2/2,halfHeight=height2/2,xBegin=x2-halfWidth,xEnd=x2+halfWidth,yBegin=y2-halfHeight,yEnd=y2+halfHeight,barrelCurveConstants=getBarrelCurveConstants(width2,height2),wOffset=barrelCurveConstants.widthOffset,hOffset=barrelCurveConstants.heightOffset,ctrlPtXOffset=barrelCurveConstants.ctrlPtOffsetPct*wOffset;context.beginPath&&context.beginPath(),context.moveTo(xBegin,yBegin+hOffset),context.lineTo(xBegin,yEnd-hOffset),context.quadraticCurveTo(xBegin+ctrlPtXOffset,yEnd,xBegin+wOffset,yEnd),context.lineTo(xEnd-wOffset,yEnd),context.quadraticCurveTo(xEnd-ctrlPtXOffset,yEnd,xEnd,yEnd-hOffset),context.lineTo(xEnd,yBegin+hOffset),context.quadraticCurveTo(xEnd-ctrlPtXOffset,yBegin,xEnd-wOffset,yBegin),context.lineTo(xBegin+wOffset,yBegin),context.quadraticCurveTo(xBegin+ctrlPtXOffset,yBegin,xBegin,yBegin+hOffset),context.closePath()};var sin0=Math.sin(0),cos0=Math.cos(0),sin={},cos={},ellipseStepSize=Math.PI/40;for(i=0*Math.PI;i<2*Math.PI;i+=ellipseStepSize)sin[i]=Math.sin(i),cos[i]=Math.cos(i);var i;CRp$3.drawEllipsePath=function(context,centerX,centerY,width2,height2){if(context.beginPath&&context.beginPath(),context.ellipse)context.ellipse(centerX,centerY,width2/2,height2/2,0,0,2*Math.PI);else for(var xPos,yPos,rw=width2/2,rh=height2/2,i2=0*Math.PI;i2<2*Math.PI;i2+=ellipseStepSize)xPos=centerX-rw*sin[i2]*sin0+rw*cos[i2]*cos0,yPos=centerY+rh*cos[i2]*sin0+rh*sin[i2]*cos0,i2===0?context.moveTo(xPos,yPos):context.lineTo(xPos,yPos);context.closePath()};var CRp$2={};CRp$2.createBuffer=function(w,h){var buffer=document.createElement("canvas");return buffer.width=w,buffer.height=h,[buffer,buffer.getContext("2d")]};CRp$2.bufferCanvasImage=function(options2){var cy=this.cy,eles=cy.mutableElements(),bb=eles.boundingBox(),ctrRect=this.findContainerClientCoords(),width2=options2.full?Math.ceil(bb.w):ctrRect[2],height2=options2.full?Math.ceil(bb.h):ctrRect[3],specdMaxDims=number$1(options2.maxWidth)||number$1(options2.maxHeight),pxRatio=this.getPixelRatio(),scale2=1;if(options2.scale!==void 0)width2*=options2.scale,height2*=options2.scale,scale2=options2.scale;else if(specdMaxDims){var maxScaleW=1/0,maxScaleH=1/0;number$1(options2.maxWidth)&&(maxScaleW=scale2*options2.maxWidth/width2),number$1(options2.maxHeight)&&(maxScaleH=scale2*options2.maxHeight/height2),scale2=Math.min(maxScaleW,maxScaleH),width2*=scale2,height2*=scale2}specdMaxDims||(width2*=pxRatio,height2*=pxRatio,scale2*=pxRatio);var buffCanvas=document.createElement("canvas");buffCanvas.width=width2,buffCanvas.height=height2,buffCanvas.style.width=width2+"px",buffCanvas.style.height=height2+"px";var buffCxt=buffCanvas.getContext("2d");if(width2>0&&height2>0){buffCxt.clearRect(0,0,width2,height2),buffCxt.globalCompositeOperation="source-over";var zsortedEles=this.getCachedZSortedEles();if(options2.full)buffCxt.translate(-bb.x1*scale2,-bb.y1*scale2),buffCxt.scale(scale2,scale2),this.drawElements(buffCxt,zsortedEles),buffCxt.scale(1/scale2,1/scale2),buffCxt.translate(bb.x1*scale2,bb.y1*scale2);else{var pan2=cy.pan(),translation={x:pan2.x*scale2,y:pan2.y*scale2};scale2*=cy.zoom(),buffCxt.translate(translation.x,translation.y),buffCxt.scale(scale2,scale2),this.drawElements(buffCxt,zsortedEles),buffCxt.scale(1/scale2,1/scale2),buffCxt.translate(-translation.x,-translation.y)}options2.bg&&(buffCxt.globalCompositeOperation="destination-over",buffCxt.fillStyle=options2.bg,buffCxt.rect(0,0,width2,height2),buffCxt.fill())}return buffCanvas};function b64ToBlob(b64,mimeType){for(var bytes=atob(b64),buff=new ArrayBuffer(bytes.length),buffUint8=new Uint8Array(buff),i2=0;i2<bytes.length;i2++)buffUint8[i2]=bytes.charCodeAt(i2);return new Blob([buff],{type:mimeType})}function b64UriToB64(b64uri){var i2=b64uri.indexOf(",");return b64uri.substr(i2+1)}function output(options2,canvas,mimeType){var getB64Uri=function(){return canvas.toDataURL(mimeType,options2.quality)};switch(options2.output){case"blob-promise":return new Promise$1(function(resolve2,reject2){try{canvas.toBlob(function(blob){blob!=null?resolve2(blob):reject2(new Error("`canvas.toBlob()` sent a null value in its callback"))},mimeType,options2.quality)}catch(err){reject2(err)}});case"blob":return b64ToBlob(b64UriToB64(getB64Uri()),mimeType);case"base64":return b64UriToB64(getB64Uri());default:return getB64Uri()}}CRp$2.png=function(options2){return output(options2,this.bufferCanvasImage(options2),"image/png")};CRp$2.jpg=function(options2){return output(options2,this.bufferCanvasImage(options2),"image/jpeg")};var CRp$1={};CRp$1.nodeShapeImpl=function(name,context,centerX,centerY,width2,height2,points,corners){switch(name){case"ellipse":return this.drawEllipsePath(context,centerX,centerY,width2,height2);case"polygon":return this.drawPolygonPath(context,centerX,centerY,width2,height2,points);case"round-polygon":return this.drawRoundPolygonPath(context,centerX,centerY,width2,height2,points,corners);case"roundrectangle":case"round-rectangle":return this.drawRoundRectanglePath(context,centerX,centerY,width2,height2,corners);case"cutrectangle":case"cut-rectangle":return this.drawCutRectanglePath(context,centerX,centerY,width2,height2,points,corners);case"bottomroundrectangle":case"bottom-round-rectangle":return this.drawBottomRoundRectanglePath(context,centerX,centerY,width2,height2,corners);case"barrel":return this.drawBarrelPath(context,centerX,centerY,width2,height2)}};var CR=CanvasRenderer,CRp=CanvasRenderer.prototype;CRp.CANVAS_LAYERS=3;CRp.SELECT_BOX=0;CRp.DRAG=1;CRp.NODE=2;CRp.WEBGL=3;CRp.CANVAS_TYPES=["2d","2d","2d","webgl2"];CRp.BUFFER_COUNT=3;CRp.TEXTURE_BUFFER=0;CRp.MOTIONBLUR_BUFFER_NODE=1;CRp.MOTIONBLUR_BUFFER_DRAG=2;function CanvasRenderer(options2){var r=this,containerWindow=r.cy.window(),document2=containerWindow.document;options2.webgl&&(CRp.CANVAS_LAYERS=r.CANVAS_LAYERS=4,console.log("webgl rendering enabled")),r.data={canvases:new Array(CRp.CANVAS_LAYERS),contexts:new Array(CRp.CANVAS_LAYERS),canvasNeedsRedraw:new Array(CRp.CANVAS_LAYERS),bufferCanvases:new Array(CRp.BUFFER_COUNT),bufferContexts:new Array(CRp.CANVAS_LAYERS)};var tapHlOffAttr="-webkit-tap-highlight-color",tapHlOffStyle="rgba(0,0,0,0)";r.data.canvasContainer=document2.createElement("div");var containerStyle=r.data.canvasContainer.style;r.data.canvasContainer.style[tapHlOffAttr]=tapHlOffStyle,containerStyle.position="relative",containerStyle.zIndex="0",containerStyle.overflow="hidden";var container2=options2.cy.container();container2.appendChild(r.data.canvasContainer),container2.style[tapHlOffAttr]=tapHlOffStyle;var styleMap={"-webkit-user-select":"none","-moz-user-select":"-moz-none","user-select":"none","-webkit-tap-highlight-color":"rgba(0,0,0,0)","outline-style":"none"};ms()&&(styleMap["-ms-touch-action"]="none",styleMap["touch-action"]="none");for(var i2=0;i2<CRp.CANVAS_LAYERS;i2++){var canvas=r.data.canvases[i2]=document2.createElement("canvas"),type=CRp.CANVAS_TYPES[i2];r.data.contexts[i2]=canvas.getContext(type),r.data.contexts[i2]||error("Could not create canvas of type "+type),Object.keys(styleMap).forEach(function(k){canvas.style[k]=styleMap[k]}),canvas.style.position="absolute",canvas.setAttribute("data-id","layer"+i2),canvas.style.zIndex=String(CRp.CANVAS_LAYERS-i2),r.data.canvasContainer.appendChild(canvas),r.data.canvasNeedsRedraw[i2]=!1}r.data.topCanvas=r.data.canvases[0],r.data.canvases[CRp.NODE].setAttribute("data-id","layer"+CRp.NODE+"-node"),r.data.canvases[CRp.SELECT_BOX].setAttribute("data-id","layer"+CRp.SELECT_BOX+"-selectbox"),r.data.canvases[CRp.DRAG].setAttribute("data-id","layer"+CRp.DRAG+"-drag"),r.data.canvases[CRp.WEBGL]&&r.data.canvases[CRp.WEBGL].setAttribute("data-id","layer"+CRp.WEBGL+"-webgl");for(var i2=0;i2<CRp.BUFFER_COUNT;i2++)r.data.bufferCanvases[i2]=document2.createElement("canvas"),r.data.bufferContexts[i2]=r.data.bufferCanvases[i2].getContext("2d"),r.data.bufferCanvases[i2].style.position="absolute",r.data.bufferCanvases[i2].setAttribute("data-id","buffer"+i2),r.data.bufferCanvases[i2].style.zIndex=String(-i2-1),r.data.bufferCanvases[i2].style.visibility="hidden";r.pathsEnabled=!0;var emptyBb=makeBoundingBox(),getBoxCenter=function(bb){return{x:(bb.x1+bb.x2)/2,y:(bb.y1+bb.y2)/2}},getCenterOffset=function(bb){return{x:-bb.w/2,y:-bb.h/2}},backgroundTimestampHasChanged=function(ele){var _p=ele[0]._private,same2=_p.oldBackgroundTimestamp===_p.backgroundTimestamp;return!same2},getStyleKey=function(ele){return ele[0]._private.nodeKey},getLabelKey=function(ele){return ele[0]._private.labelStyleKey},getSourceLabelKey=function(ele){return ele[0]._private.sourceLabelStyleKey},getTargetLabelKey=function(ele){return ele[0]._private.targetLabelStyleKey},drawElement=function(context,ele,bb,scaledLabelShown,useEleOpacity){return r.drawElement(context,ele,bb,!1,!1,useEleOpacity)},drawLabel=function(context,ele,bb,scaledLabelShown,useEleOpacity){return r.drawElementText(context,ele,bb,scaledLabelShown,"main",useEleOpacity)},drawSourceLabel=function(context,ele,bb,scaledLabelShown,useEleOpacity){return r.drawElementText(context,ele,bb,scaledLabelShown,"source",useEleOpacity)},drawTargetLabel=function(context,ele,bb,scaledLabelShown,useEleOpacity){return r.drawElementText(context,ele,bb,scaledLabelShown,"target",useEleOpacity)},getElementBox=function(ele){return ele.boundingBox(),ele[0]._private.bodyBounds},getLabelBox=function(ele){return ele.boundingBox(),ele[0]._private.labelBounds.main||emptyBb},getSourceLabelBox=function(ele){return ele.boundingBox(),ele[0]._private.labelBounds.source||emptyBb},getTargetLabelBox=function(ele){return ele.boundingBox(),ele[0]._private.labelBounds.target||emptyBb},isLabelVisibleAtScale=function(ele,scaledLabelShown){return scaledLabelShown},getElementRotationPoint=function(ele){return getBoxCenter(getElementBox(ele))},addTextMargin=function(prefix,pt,ele){var pre=prefix?prefix+"-":"";return{x:pt.x+ele.pstyle(pre+"text-margin-x").pfValue,y:pt.y+ele.pstyle(pre+"text-margin-y").pfValue}},getRsPt=function(ele,x2,y2){var rs=ele[0]._private.rscratch;return{x:rs[x2],y:rs[y2]}},getLabelRotationPoint=function(ele){return addTextMargin("",getRsPt(ele,"labelX","labelY"),ele)},getSourceLabelRotationPoint=function(ele){return addTextMargin("source",getRsPt(ele,"sourceLabelX","sourceLabelY"),ele)},getTargetLabelRotationPoint=function(ele){return addTextMargin("target",getRsPt(ele,"targetLabelX","targetLabelY"),ele)},getElementRotationOffset=function(ele){return getCenterOffset(getElementBox(ele))},getSourceLabelRotationOffset=function(ele){return getCenterOffset(getSourceLabelBox(ele))},getTargetLabelRotationOffset=function(ele){return getCenterOffset(getTargetLabelBox(ele))},getLabelRotationOffset=function(ele){var bb=getLabelBox(ele),p2=getCenterOffset(getLabelBox(ele));if(ele.isNode()){switch(labelHalign(ele.pstyle("text-halign").value)){case"left":p2.x=-bb.w-(bb.leftPad||0);break;case"right":p2.x=-(bb.rightPad||0);break}switch(labelValign(ele.pstyle("text-valign").value)){case"top":p2.y=-bb.h-(bb.topPad||0);break;case"bottom":p2.y=-(bb.botPad||0);break}}return p2},eleTxrCache=r.data.eleTxrCache=new ElementTextureCache(r,{getKey:getStyleKey,doesEleInvalidateKey:backgroundTimestampHasChanged,drawElement,getBoundingBox:getElementBox,getRotationPoint:getElementRotationPoint,getRotationOffset:getElementRotationOffset,allowEdgeTxrCaching:!1,allowParentTxrCaching:!1}),lblTxrCache=r.data.lblTxrCache=new ElementTextureCache(r,{getKey:getLabelKey,drawElement:drawLabel,getBoundingBox:getLabelBox,getRotationPoint:getLabelRotationPoint,getRotationOffset:getLabelRotationOffset,isVisible:isLabelVisibleAtScale}),slbTxrCache=r.data.slbTxrCache=new ElementTextureCache(r,{getKey:getSourceLabelKey,drawElement:drawSourceLabel,getBoundingBox:getSourceLabelBox,getRotationPoint:getSourceLabelRotationPoint,getRotationOffset:getSourceLabelRotationOffset,isVisible:isLabelVisibleAtScale}),tlbTxrCache=r.data.tlbTxrCache=new ElementTextureCache(r,{getKey:getTargetLabelKey,drawElement:drawTargetLabel,getBoundingBox:getTargetLabelBox,getRotationPoint:getTargetLabelRotationPoint,getRotationOffset:getTargetLabelRotationOffset,isVisible:isLabelVisibleAtScale}),lyrTxrCache=r.data.lyrTxrCache=new LayeredTextureCache(r);r.onUpdateEleCalcs(function(willDraw,eles){eleTxrCache.invalidateElements(eles),lblTxrCache.invalidateElements(eles),slbTxrCache.invalidateElements(eles),tlbTxrCache.invalidateElements(eles),lyrTxrCache.invalidateElements(eles);for(var _i=0;_i<eles.length;_i++){var _p=eles[_i]._private;_p.oldBackgroundTimestamp=_p.backgroundTimestamp}});var refineInLayers=function(reqs){for(var i3=0;i3<reqs.length;i3++)lyrTxrCache.enqueueElementRefinement(reqs[i3].ele)};eleTxrCache.onDequeue(refineInLayers),lblTxrCache.onDequeue(refineInLayers),slbTxrCache.onDequeue(refineInLayers),tlbTxrCache.onDequeue(refineInLayers),options2.webgl&&r.initWebgl(options2,{getStyleKey,getLabelKey,getSourceLabelKey,getTargetLabelKey,drawElement,drawLabel,drawSourceLabel,drawTargetLabel,getElementBox,getLabelBox,getSourceLabelBox,getTargetLabelBox,getElementRotationPoint,getElementRotationOffset,getLabelRotationPoint,getSourceLabelRotationPoint,getTargetLabelRotationPoint,getLabelRotationOffset,getSourceLabelRotationOffset,getTargetLabelRotationOffset})}CRp.redrawHint=function(group2,bool){var r=this;switch(group2){case"eles":r.data.canvasNeedsRedraw[CRp.NODE]=bool;break;case"drag":r.data.canvasNeedsRedraw[CRp.DRAG]=bool;break;case"select":r.data.canvasNeedsRedraw[CRp.SELECT_BOX]=bool;break;case"gc":r.data.gc=!0;break}};var pathsImpld=typeof Path2D<"u";CRp.path2dEnabled=function(on3){if(on3===void 0)return this.pathsEnabled;this.pathsEnabled=!!on3};CRp.usePaths=function(){return pathsImpld&&this.pathsEnabled};CRp.setImgSmoothing=function(context,bool){context.imageSmoothingEnabled!=null?context.imageSmoothingEnabled=bool:(context.webkitImageSmoothingEnabled=bool,context.mozImageSmoothingEnabled=bool,context.msImageSmoothingEnabled=bool)};CRp.getImgSmoothing=function(context){return context.imageSmoothingEnabled!=null?context.imageSmoothingEnabled:context.webkitImageSmoothingEnabled||context.mozImageSmoothingEnabled||context.msImageSmoothingEnabled};CRp.makeOffscreenCanvas=function(width2,height2){var canvas;if((typeof OffscreenCanvas>"u"?"undefined":_typeof(OffscreenCanvas))!=="undefined")canvas=new OffscreenCanvas(width2,height2);else{var containerWindow=this.cy.window(),document2=containerWindow.document;canvas=document2.createElement("canvas"),canvas.width=width2,canvas.height=height2}return canvas};[CRp$b,CRp$a,CRp$9,CRp$8,CRp$7,CRp$6,CRp$5,CRp$4,CRp$3,CRp$2,CRp$1].forEach(function(props){extend(CRp,props)});var renderer2=[{name:"null",impl:NullRenderer},{name:"base",impl:BR},{name:"canvas",impl:CR}],incExts=[{type:"layout",extensions:layout3},{type:"renderer",extensions:renderer2}],extensions={},modules={};function setExtension(type,name,registrant){var ext=registrant,overrideErr=function(field){warn("Can not register `"+name+"` for `"+type+"` since `"+field+"` already exists in the prototype and can not be overridden")};if(type==="core"){if(Core.prototype[name])return overrideErr(name);Core.prototype[name]=registrant}else if(type==="collection"){if(Collection.prototype[name])return overrideErr(name);Collection.prototype[name]=registrant}else if(type==="layout"){for(var Layout2=function(options2){this.options=options2,registrant.call(this,options2),plainObject(this._private)||(this._private={}),this._private.cy=options2.cy,this._private.listeners=[],this.createEmitter()},layoutProto=Layout2.prototype=Object.create(registrant.prototype),optLayoutFns=[],i2=0;i2<optLayoutFns.length;i2++){var fnName=optLayoutFns[i2];layoutProto[fnName]=layoutProto[fnName]||function(){return this}}layoutProto.start&&!layoutProto.run?layoutProto.run=function(){return this.start(),this}:!layoutProto.start&&layoutProto.run&&(layoutProto.start=function(){return this.run(),this});var regStop=registrant.prototype.stop;layoutProto.stop=function(){var opts=this.options;if(opts&&opts.animate){var anis=this.animations;if(anis)for(var _i=0;_i<anis.length;_i++)anis[_i].stop()}return regStop?regStop.call(this):this.emit("layoutstop"),this},layoutProto.destroy||(layoutProto.destroy=function(){return this}),layoutProto.cy=function(){return this._private.cy};var getCy=function(layout4){return layout4._private.cy},emitterOpts={addEventFields:function(layout4,evt){evt.layout=layout4,evt.cy=getCy(layout4),evt.target=layout4},bubble:function(){return!0},parent:function(layout4){return getCy(layout4)}};extend(layoutProto,{createEmitter:function(){return this._private.emitter=new Emitter(emitterOpts,this),this},emitter:function(){return this._private.emitter},on:function(evt,cb){return this.emitter().on(evt,cb),this},one:function(evt,cb){return this.emitter().one(evt,cb),this},once:function(evt,cb){return this.emitter().one(evt,cb),this},removeListener:function(evt,cb){return this.emitter().removeListener(evt,cb),this},removeAllListeners:function(){return this.emitter().removeAllListeners(),this},emit:function(evt,params){return this.emitter().emit(evt,params),this}}),define2.eventAliasesOn(layoutProto),ext=Layout2}else if(type==="renderer"&&name!=="null"&&name!=="base"){var BaseRenderer3=getExtension("renderer","base"),bProto=BaseRenderer3.prototype,RegistrantRenderer=registrant,rProto=registrant.prototype,Renderer=function(){BaseRenderer3.apply(this,arguments),RegistrantRenderer.apply(this,arguments)},proto=Renderer.prototype;for(var pName in bProto){var pVal=bProto[pName],existsInR=rProto[pName]!=null;if(existsInR)return overrideErr(pName);proto[pName]=pVal}for(var _pName in rProto)proto[_pName]=rProto[_pName];bProto.clientFunctions.forEach(function(name2){proto[name2]=proto[name2]||function(){error("Renderer does not implement `renderer."+name2+"()` on its prototype")}}),ext=Renderer}else if(type==="__proto__"||type==="constructor"||type==="prototype")return error(type+" is an illegal type to be registered, possibly lead to prototype pollutions");return setMap({map:extensions,keys:[type,name],value:ext})}function getExtension(type,name){return getMap({map:extensions,keys:[type,name]})}function setModule(type,name,moduleType,moduleName,registrant){return setMap({map:modules,keys:[type,name,moduleType,moduleName],value:registrant})}function getModule(type,name,moduleType,moduleName){return getMap({map:modules,keys:[type,name,moduleType,moduleName]})}var extension=function(){if(arguments.length===2)return getExtension.apply(null,arguments);if(arguments.length===3)return setExtension.apply(null,arguments);if(arguments.length===4)return getModule.apply(null,arguments);if(arguments.length===5)return setModule.apply(null,arguments);error("Invalid extension access syntax")};Core.prototype.extension=extension;incExts.forEach(function(group2){group2.extensions.forEach(function(ext){setExtension(group2.type,ext.name,ext.impl)})});var _Stylesheet=function(){if(!(this instanceof _Stylesheet))return new _Stylesheet;this.length=0},sheetfn=_Stylesheet.prototype;sheetfn.instanceString=function(){return"stylesheet"};sheetfn.selector=function(selector){var i2=this.length++;return this[i2]={selector,properties:[]},this};sheetfn.css=function(name,value){var i2=this.length-1;if(string(name))this[i2].properties.push({name,value});else if(plainObject(name))for(var map2=name,propNames=Object.keys(map2),j=0;j<propNames.length;j++){var key=propNames[j],mapVal=map2[key];if(mapVal!=null){var prop=_Style.properties[key]||_Style.properties[dash2camel(key)];if(prop!=null){var _name=prop.name,_value=mapVal;this[i2].properties.push({name:_name,value:_value})}}}return this};sheetfn.style=sheetfn.css;sheetfn.generateStyle=function(cy){var style3=new _Style(cy);return this.appendToStyle(style3)};sheetfn.appendToStyle=function(style3){for(var i2=0;i2<this.length;i2++){var context=this[i2],selector=context.selector,props=context.properties;style3.selector(selector);for(var j=0;j<props.length;j++){var prop=props[j];style3.css(prop.name,prop.value)}}return style3};var version="3.34.1",cytoscape2=function(options2){if(options2===void 0&&(options2={}),plainObject(options2))return new Core(options2);if(string(options2))return extension.apply(extension,arguments)};cytoscape2.use=function(ext){var args=Array.prototype.slice.call(arguments,1);return args.unshift(cytoscape2),ext.apply(null,args),this};cytoscape2.warnings=function(bool){return warnings(bool)};cytoscape2.version=version;cytoscape2.stylesheet=cytoscape2.Stylesheet=_Stylesheet;var import_cytoscape_fcose=__toESM(require_cytoscape_fcose());cytoscape2.use(import_cytoscape_fcose.default);globalThis.__StrataGateGraphLibraries={cytoscape:cytoscape2};globalThis.__STRATAGATE_GITHUB_STARS__=119;window.__ModuleLoader__.load({id:"stratagate-dsh",factory:require2=>{let module={exports:{}},exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});let React=require2("react"),h=React.createElement,cytoscape4=globalThis.__StrataGateGraphLibraries?.cytoscape,AGENT_FEEDBACK_ENABLED=!0,GITHUB_FEEDBACK_ENABLED=!0,FEEDBACK_EMAIL="jiahongcheng61@gmail.com",EMAIL_BODY_HINT=`\u8BF7\u5728\u4E0B\u65B9\u7C98\u8D34 StrataGate \u53CD\u9988\u62A5\u544A\uFF0C\u68C0\u67E5\u540E\u53D1\u9001\u3002\u4E5F\u53EF\u4EE5\u624B\u52A8\u9644\u52A0\u5DF2\u4E0B\u8F7D\u7684\u8BCA\u65AD\u6587\u4EF6\u3002\r
322
322
  \r
323
323
  `,STAR_REPOSITORY_URL="https://github.com/diqierjia/StrataGate-AgentMemory",ISSUE_URL=STAR_REPOSITORY_URL+"/issues/new",DISCUSSION_URL=STAR_REPOSITORY_URL+"/discussions/categories/q-a",FEEDBACK_AI_PROMPT="\u8BF7\u6839\u636E\u5F53\u524D\u4F1A\u8BDD\u4E2D StrataGate \u63D2\u4EF6\u7684\u6545\u969C\u3001\u4F7F\u7528\u7591\u95EE\u6216\u6539\u8FDB\u5EFA\u8BAE\u6574\u7406\u53CD\u9988\u3002\u53EA\u7528\u5DF2\u77E5\u4E8B\u5B9E\uFF0C\u4E0D\u8981\u731C\u6D4B\uFF0C\u672A\u77E5\u7559\u7A7A\uFF0C\u53BB\u9664\u51ED\u636E\u3002\u8C03\u7528 feedback_prepare \u4FDD\u5B58\u672C\u5730\u8349\u7A3F\uFF1B\u65B0\u95EE\u9898\u4F20 new_draft=true\u3002\u8BCA\u65AD\u7531\u7A0B\u5E8F\u81EA\u52A8\u8865\u5145\u3002\u7ED9\u6211\u201C\u6253\u5F00\u53CD\u9988\u8349\u7A3F\u201D\u7684\u94FE\u63A5\uFF0C\u6211\u4F1A\u68C0\u67E5\u540E\u624B\u52A8\u53D1\u90AE\u4EF6\u3002",FEEDBACK_SETTINGS_ID="stratagate-memory",FEEDBACK_VIEW_ID="feedback",MEMORY_PANEL_ID="stratagate-memory",SIDEBAR_PROMPT_STORAGE_KEY="stratagate-dsh.sidebar-prompt.v1",SIDEBAR_PROMPT_STYLES=".sg-sidebar-panel-icon{display:block;flex-shrink:0}.sg-sidebar-placement-prompt{display:inline-flex;align-items:center;gap:8px;flex-wrap:wrap;max-width:100%;font-size:11px;line-height:1.5;color:var(--sg-muted)}.sg-sidebar-placement-text{min-width:0}.sg-memory .sg-sidebar-placement-action{padding:0;border:0;background:transparent;color:var(--sg-accent);font-size:11px;line-height:1.5;cursor:pointer;white-space:nowrap}.sg-sidebar-placement-action:hover{text-decoration:underline}.sg-memory .sg-sidebar-placement-close{display:inline-grid;place-items:center;width:20px;height:20px;flex:none;padding:0;border:0;border-radius:4px;background:transparent;color:var(--sg-muted);font-size:15px;line-height:1;cursor:pointer}.sg-sidebar-placement-close:hover{background:var(--sg-soft);color:var(--sg-text)}",pendingFeedbackNavigation=null,feedbackNavigationListeners=new Set;function setFeedbackNavigation(state){pendingFeedbackNavigation=state;for(let listener of feedbackNavigationListeners)listener(state);feedbackNavigationListeners.size&&(pendingFeedbackNavigation=null)}function FeedbackSettingsPage(props){let[navigationState,setNavigationState]=React.useState(()=>pendingFeedbackNavigation);return React.useEffect(()=>(feedbackNavigationListeners.add(setNavigationState),pendingFeedbackNavigation&&setNavigationState(pendingFeedbackNavigation),pendingFeedbackNavigation=null,()=>feedbackNavigationListeners.delete(setNavigationState)),[]),h(MemoryPage,{...props,navigationState:navigationState||props.navigationState})}let ISSUE_BODY_HINT=`> \u8BF7\u5728\u4E0B\u65B9\u7C98\u8D34 StrataGate \u53CD\u9988\u62A5\u544A\uFF08Ctrl+V / \u2318V\uFF09\uFF0C\u68C0\u67E5\u540E\u63D0\u4EA4\u3002\u82E5\u65E0\u6CD5\u7C98\u8D34\uFF0C\u8BF7\u8FD4\u56DE StrataGate \u624B\u52A8\u590D\u5236\u62A5\u544A\u3002
324
324
 
325
- `,STRATAGATE_CLIENT_VERSION="0.3.51",MEMORY_CITATIONS_KIND="stratagate-memory-citations",MEMORY_RETRIEVAL_TOOLS=new Set(["memory_search_events","memory_search_graph","memory_expand_graph_node","memory_search_elements","memory_search_raw","memory_get_blocks","memory_expand_block","memory_expand_event","memory_expand_element"]);function readFeedbackDeepLink(locationRef=window.location){let params=new URLSearchParams(String(locationRef?.search||""));if(params.get("settings")!==FEEDBACK_SETTINGS_ID||params.get("stratagateView")!==FEEDBACK_VIEW_ID)return null;let namespace=String(params.get("namespace")||"").trim();return namespace?{namespace}:null}function readFeedbackNavigationState(state){if(!state||state.view!==FEEDBACK_VIEW_ID)return null;let namespace=String(state.namespace||"").trim();return namespace?{namespace}:null}function readNewFeedbackNavigationState(previousState,state){return state===previousState?null:readFeedbackNavigationState(state)}function readGraphNodeNavigationState(state){if(!state||state.view!=="graph-node")return null;let namespace=String(state.namespace||"").trim(),nodeId=String(state.nodeId||"").trim();return namespace&&nodeId?{namespace,nodeId}:null}function readGraphNodeDeepLink(locationRef=window.location){let params=new URLSearchParams(String(locationRef?.search||""));if(params.get("settings")!==FEEDBACK_SETTINGS_ID||params.get("stratagateView")!=="graph-node")return null;let namespace=String(params.get("namespace")||"").trim(),nodeId=String(params.get("nodeId")||"").trim();return namespace&&nodeId?{namespace,nodeId}:null}function consumeFeedbackDeepLink(locationRef=window.location,historyRef=window.history){let params=new URLSearchParams(String(locationRef?.search||""));params.delete("settings"),params.delete("stratagateView"),params.delete("namespace");let search=params.toString(),next2=String(locationRef?.pathname||"/")+(search?"?"+search:"")+String(locationRef?.hash||"");return historyRef?.replaceState?.(historyRef.state,"",next2),next2}function consumeGraphNodeDeepLink(locationRef=window.location,historyRef=window.history){let params=new URLSearchParams(String(locationRef?.search||""));params.delete("settings"),params.delete("stratagateView"),params.delete("namespace"),params.delete("nodeId");let search=params.toString(),next2=String(locationRef?.pathname||"/")+(search?"?"+search:"")+String(locationRef?.hash||"");return historyRef?.replaceState?.(historyRef.state,"",next2),next2}function isDesktopFeedbackSurface(locationRef){try{let url=new URL(String(locationRef?.href||""));return url.protocol==="dsh-app:"&&url.hostname==="app"}catch{return!1}}function desktopFeedbackOrigin(value){try{let url=new URL(String(value||""));return url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)&&!url.username&&!url.password&&url.pathname==="/"&&!url.search&&!url.hash?url.origin:""}catch{return""}}function feedbackAnchorTarget(target,locationRef){let anchor=target?.closest?.("a[href]")||target?.parentElement?.closest?.("a[href]");if(!anchor)return null;let url;try{url=new URL(String(anchor.getAttribute?.("href")||""),String(locationRef?.href||""))}catch{return null}return!readFeedbackDeepLink(url)||url.pathname!=="/"||url.username||url.password?null:{anchor,url}}function feedbackLinkTarget(target,locationRef=window.location,desktopHostOrigin=""){let match2=feedbackAnchorTarget(target,locationRef);return match2&&(match2.url.origin===String(locationRef?.origin||"")||isDesktopFeedbackSurface(locationRef)&&desktopFeedbackOrigin(desktopHostOrigin)===match2.url.origin)?match2:null}function navigateToFeedback(ctx,targetUrl,locationRef=window.location,allowHttpFallback=!0){let feedback=readFeedbackDeepLink(targetUrl);if(!feedback)return"ignored";let navigation=ctx?.get?.("settingsNavigation");if(typeof navigation?.openSection=="function")return navigation.openSection(FEEDBACK_SETTINGS_ID,{view:FEEDBACK_VIEW_ID,namespace:feedback.namespace}),"host";let shell=ctx?.get?.("slots")?.entries?.("sidebar.settings")?.find(entry=>typeof entry.store?.create=="function")?.store.create();return typeof shell?.actions?.openSection=="function"?(setFeedbackNavigation({view:FEEDBACK_VIEW_ID,namespace:feedback.namespace}),shell.actions.openSection(FEEDBACK_SETTINGS_ID),"host"):(allowHttpFallback&&locationRef.assign(targetUrl.href),"http")}function navigateToGraphNode(ctx,namespace,nodeId,locationRef=window.location,allowHttpFallback=!0){let targetNamespace=String(namespace||"").trim(),targetNodeId=String(nodeId||"").trim();if(!targetNamespace||!targetNodeId)return Promise.resolve(!1);let navigation=ctx?.get?.("settingsNavigation");if(typeof navigation?.openSection!="function"){if(!allowHttpFallback||typeof locationRef?.assign!="function")return Promise.resolve(!1);try{let targetUrl=new URL(String(locationRef.href||""));return targetUrl.searchParams.set("settings",FEEDBACK_SETTINGS_ID),targetUrl.searchParams.set("stratagateView","graph-node"),targetUrl.searchParams.set("namespace",targetNamespace),targetUrl.searchParams.set("nodeId",targetNodeId),locationRef.assign(targetUrl.href),Promise.resolve(!0)}catch{return Promise.resolve(!1)}}try{return Promise.resolve(navigation.openSection(FEEDBACK_SETTINGS_ID,{view:"graph-node",namespace:targetNamespace,nodeId:targetNodeId})).then(result=>result!==!1,()=>!1)}catch{return Promise.resolve(!1)}}function installFeedbackLinkNavigation(ctx,documentRef=document,locationRef=window.location){let desktop=isDesktopFeedbackSurface(locationRef),active=!0,desktopHostOrigin="",bootPending=desktop&&typeof window.dshDesktopBoot?.ready=="function",replayingAnchor=null,bootReady=bootPending?Promise.resolve().then(()=>window.dshDesktopBoot.ready()).then(boot=>{active&&(desktopHostOrigin=desktopFeedbackOrigin(boot?.streamBaseUrl))}).catch(()=>{}).finally(()=>{bootPending=!1}):Promise.resolve(),takeClick=event3=>{event3.preventDefault(),event3.stopPropagation()},onClick=event3=>{if(event3.defaultPrevented||typeof event3.button=="number"&&event3.button!==0||event3.metaKey||event3.ctrlKey||event3.shiftKey||event3.altKey)return;let candidate=feedbackAnchorTarget(event3.target,locationRef);if(!candidate||candidate.anchor===replayingAnchor)return;let match2=feedbackLinkTarget(event3.target,locationRef,desktopHostOrigin);match2?(takeClick(event3),navigateToFeedback(ctx,match2.url,locationRef,!desktop)):bootPending&&desktopFeedbackOrigin(candidate.url.origin)&&(takeClick(event3),bootReady.then(()=>{if(active)if(candidate.url.origin===desktopHostOrigin)navigateToFeedback(ctx,candidate.url,locationRef,!1);else{replayingAnchor=candidate.anchor;try{candidate.anchor.click()}finally{replayingAnchor=null}}}))};return documentRef.addEventListener("click",onClick,!0),()=>{active=!1,documentRef.removeEventListener("click",onClick,!0)}}function exactInteractiveControl(labels,documentRef){let selector='button,[role="button"],[role="tab"],a',matches33=element3=>{let values=[element3.getAttribute?.("aria-label"),element3.getAttribute?.("title"),element3.textContent].map(value=>String(value||"").trim());return labels.some(label=>values.includes(label))},visible=element3=>!element3.hidden&&element3.getAttribute?.("aria-hidden")!=="true"&&(typeof element3.getClientRects!="function"||element3.getClientRects().length>0),direct=Array.from(documentRef.querySelectorAll(selector)).find(element3=>visible(element3)&&matches33(element3));if(direct)return direct;for(let element3 of Array.from(documentRef.querySelectorAll("*"))){if(String(element3.textContent||"").trim()!==labels[0])continue;let control=element3.closest?.(selector)||element3;if(visible(control)&&typeof control.click=="function")return control}return null}function openLegacyFeedbackDeepLink(documentRef=document){let observer=null,timer=null,settingsClicked=!1,sectionClicked=!1,cleanup=()=>{observer?.disconnect?.(),timer!==null&&window.clearTimeout(timer)},attempt=()=>{if(documentRef.querySelector('[data-testid="stratagate-memory-ui"]')){cleanup();return}if(!sectionClicked){let section=exactInteractiveControl(["StrataGate-AgentMemory"],documentRef);if(section){sectionClicked=!0,section.click();return}}if(!settingsClicked){let settings=exactInteractiveControl(["\u8BBE\u7F6E","Settings"],documentRef);settings&&(settingsClicked=!0,settings.click())}},Observer=window.MutationObserver||globalThis.MutationObserver;return typeof Observer=="function"&&(observer=new Observer(attempt),observer.observe(documentRef.documentElement||documentRef.body,{childList:!0,subtree:!0})),timer=window.setTimeout(cleanup,12e3),attempt(),cleanup}function openFeedbackDeepLink(ctx,documentRef=document,locationRef=window.location,historyRef=window.history){if(!readFeedbackDeepLink(locationRef))return()=>{};if(navigateToFeedback(ctx,locationRef,locationRef,!1)==="host")return consumeFeedbackDeepLink(locationRef,historyRef),()=>{};let legacyCleanup=()=>{},timer=window.setTimeout(()=>{legacyCleanup=openLegacyFeedbackDeepLink(documentRef)},250);return ctx?.inject?.(["settingsNavigation"],scope=>{navigateToFeedback(scope,locationRef,locationRef,!1)==="host"&&(window.clearTimeout(timer),legacyCleanup(),consumeFeedbackDeepLink(locationRef,historyRef))}),()=>{window.clearTimeout(timer),legacyCleanup()}}function openGraphNodeDeepLink(ctx,documentRef=document,locationRef=window.location,historyRef=window.history){let graphLink=readGraphNodeDeepLink(locationRef);if(!graphLink)return()=>{};if(typeof ctx?.get?.("settingsNavigation")?.openSection=="function")return navigateToGraphNode(ctx,graphLink.namespace,graphLink.nodeId,locationRef,!1).then(opened=>{opened&&consumeGraphNodeDeepLink(locationRef,historyRef)}),()=>{};let legacyCleanup=()=>{},timer=window.setTimeout(()=>{legacyCleanup=openLegacyFeedbackDeepLink(documentRef)},250);return ctx?.inject?.(["settingsNavigation"],scope=>{navigateToGraphNode(scope,graphLink.namespace,graphLink.nodeId,locationRef,!1).then(opened=>{opened&&(window.clearTimeout(timer),legacyCleanup(),consumeGraphNodeDeepLink(locationRef,historyRef))})}),()=>{window.clearTimeout(timer),legacyCleanup()}}let eventDetailCss=`
325
+ `,STRATAGATE_CLIENT_VERSION="0.3.53",MEMORY_CITATIONS_KIND="stratagate-memory-citations",MEMORY_RETRIEVAL_TOOLS=new Set(["memory_search_events","memory_search_graph","memory_expand_graph_node","memory_search_elements","memory_search_raw","memory_get_blocks","memory_expand_block","memory_expand_event","memory_expand_element"]);function readFeedbackDeepLink(locationRef=window.location){let params=new URLSearchParams(String(locationRef?.search||""));if(params.get("settings")!==FEEDBACK_SETTINGS_ID||params.get("stratagateView")!==FEEDBACK_VIEW_ID)return null;let namespace=String(params.get("namespace")||"").trim();return namespace?{namespace}:null}function readFeedbackNavigationState(state){if(!state||state.view!==FEEDBACK_VIEW_ID)return null;let namespace=String(state.namespace||"").trim();return namespace?{namespace}:null}function readNewFeedbackNavigationState(previousState,state){return state===previousState?null:readFeedbackNavigationState(state)}function readGraphNodeNavigationState(state){if(!state||state.view!=="graph-node")return null;let namespace=String(state.namespace||"").trim(),nodeId=String(state.nodeId||"").trim();return namespace&&nodeId?{namespace,nodeId}:null}function readGraphNodeDeepLink(locationRef=window.location){let params=new URLSearchParams(String(locationRef?.search||""));if(params.get("settings")!==FEEDBACK_SETTINGS_ID||params.get("stratagateView")!=="graph-node")return null;let namespace=String(params.get("namespace")||"").trim(),nodeId=String(params.get("nodeId")||"").trim();return namespace&&nodeId?{namespace,nodeId}:null}function consumeFeedbackDeepLink(locationRef=window.location,historyRef=window.history){let params=new URLSearchParams(String(locationRef?.search||""));params.delete("settings"),params.delete("stratagateView"),params.delete("namespace");let search=params.toString(),next2=String(locationRef?.pathname||"/")+(search?"?"+search:"")+String(locationRef?.hash||"");return historyRef?.replaceState?.(historyRef.state,"",next2),next2}function consumeGraphNodeDeepLink(locationRef=window.location,historyRef=window.history){let params=new URLSearchParams(String(locationRef?.search||""));params.delete("settings"),params.delete("stratagateView"),params.delete("namespace"),params.delete("nodeId");let search=params.toString(),next2=String(locationRef?.pathname||"/")+(search?"?"+search:"")+String(locationRef?.hash||"");return historyRef?.replaceState?.(historyRef.state,"",next2),next2}function isDesktopFeedbackSurface(locationRef){try{let url=new URL(String(locationRef?.href||""));return url.protocol==="dsh-app:"&&url.hostname==="app"}catch{return!1}}function desktopFeedbackOrigin(value){try{let url=new URL(String(value||""));return url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)&&!url.username&&!url.password&&url.pathname==="/"&&!url.search&&!url.hash?url.origin:""}catch{return""}}function feedbackAnchorTarget(target,locationRef){let anchor=target?.closest?.("a[href]")||target?.parentElement?.closest?.("a[href]");if(!anchor)return null;let url;try{url=new URL(String(anchor.getAttribute?.("href")||""),String(locationRef?.href||""))}catch{return null}return!readFeedbackDeepLink(url)||url.pathname!=="/"||url.username||url.password?null:{anchor,url}}function feedbackLinkTarget(target,locationRef=window.location,desktopHostOrigin=""){let match2=feedbackAnchorTarget(target,locationRef);return match2&&(match2.url.origin===String(locationRef?.origin||"")||isDesktopFeedbackSurface(locationRef)&&desktopFeedbackOrigin(desktopHostOrigin)===match2.url.origin)?match2:null}function navigateToFeedback(ctx,targetUrl,locationRef=window.location,allowHttpFallback=!0){let feedback=readFeedbackDeepLink(targetUrl);if(!feedback)return"ignored";let navigation=ctx?.get?.("settingsNavigation");if(typeof navigation?.openSection=="function")return navigation.openSection(FEEDBACK_SETTINGS_ID,{view:FEEDBACK_VIEW_ID,namespace:feedback.namespace}),"host";let shell=ctx?.get?.("slots")?.entries?.("sidebar.settings")?.find(entry=>typeof entry.store?.create=="function")?.store.create();return typeof shell?.actions?.openSection=="function"?(setFeedbackNavigation({view:FEEDBACK_VIEW_ID,namespace:feedback.namespace}),shell.actions.openSection(FEEDBACK_SETTINGS_ID),"host"):(allowHttpFallback&&locationRef.assign(targetUrl.href),"http")}function navigateToGraphNode(ctx,namespace,nodeId,locationRef=window.location,allowHttpFallback=!0){let targetNamespace=String(namespace||"").trim(),targetNodeId=String(nodeId||"").trim();if(!targetNamespace||!targetNodeId)return Promise.resolve(!1);let navigation=ctx?.get?.("settingsNavigation");if(typeof navigation?.openSection!="function"){if(!allowHttpFallback||typeof locationRef?.assign!="function")return Promise.resolve(!1);try{let targetUrl=new URL(String(locationRef.href||""));return targetUrl.searchParams.set("settings",FEEDBACK_SETTINGS_ID),targetUrl.searchParams.set("stratagateView","graph-node"),targetUrl.searchParams.set("namespace",targetNamespace),targetUrl.searchParams.set("nodeId",targetNodeId),locationRef.assign(targetUrl.href),Promise.resolve(!0)}catch{return Promise.resolve(!1)}}try{return Promise.resolve(navigation.openSection(FEEDBACK_SETTINGS_ID,{view:"graph-node",namespace:targetNamespace,nodeId:targetNodeId})).then(result=>result!==!1,()=>!1)}catch{return Promise.resolve(!1)}}function installFeedbackLinkNavigation(ctx,documentRef=document,locationRef=window.location){let desktop=isDesktopFeedbackSurface(locationRef),active=!0,desktopHostOrigin="",bootPending=desktop&&typeof window.dshDesktopBoot?.ready=="function",replayingAnchor=null,bootReady=bootPending?Promise.resolve().then(()=>window.dshDesktopBoot.ready()).then(boot=>{active&&(desktopHostOrigin=desktopFeedbackOrigin(boot?.streamBaseUrl))}).catch(()=>{}).finally(()=>{bootPending=!1}):Promise.resolve(),takeClick=event3=>{event3.preventDefault(),event3.stopPropagation()},onClick=event3=>{if(event3.defaultPrevented||typeof event3.button=="number"&&event3.button!==0||event3.metaKey||event3.ctrlKey||event3.shiftKey||event3.altKey)return;let candidate=feedbackAnchorTarget(event3.target,locationRef);if(!candidate||candidate.anchor===replayingAnchor)return;let match2=feedbackLinkTarget(event3.target,locationRef,desktopHostOrigin);match2?(takeClick(event3),navigateToFeedback(ctx,match2.url,locationRef,!desktop)):bootPending&&desktopFeedbackOrigin(candidate.url.origin)&&(takeClick(event3),bootReady.then(()=>{if(active)if(candidate.url.origin===desktopHostOrigin)navigateToFeedback(ctx,candidate.url,locationRef,!1);else{replayingAnchor=candidate.anchor;try{candidate.anchor.click()}finally{replayingAnchor=null}}}))};return documentRef.addEventListener("click",onClick,!0),()=>{active=!1,documentRef.removeEventListener("click",onClick,!0)}}function exactInteractiveControl(labels,documentRef){let selector='button,[role="button"],[role="tab"],a',matches33=element3=>{let values=[element3.getAttribute?.("aria-label"),element3.getAttribute?.("title"),element3.textContent].map(value=>String(value||"").trim());return labels.some(label=>values.includes(label))},visible=element3=>!element3.hidden&&element3.getAttribute?.("aria-hidden")!=="true"&&(typeof element3.getClientRects!="function"||element3.getClientRects().length>0),direct=Array.from(documentRef.querySelectorAll(selector)).find(element3=>visible(element3)&&matches33(element3));if(direct)return direct;for(let element3 of Array.from(documentRef.querySelectorAll("*"))){if(String(element3.textContent||"").trim()!==labels[0])continue;let control=element3.closest?.(selector)||element3;if(visible(control)&&typeof control.click=="function")return control}return null}function openLegacyFeedbackDeepLink(documentRef=document){let observer=null,timer=null,settingsClicked=!1,sectionClicked=!1,cleanup=()=>{observer?.disconnect?.(),timer!==null&&window.clearTimeout(timer)},attempt=()=>{if(documentRef.querySelector('[data-testid="stratagate-memory-ui"]')){cleanup();return}if(!sectionClicked){let section=exactInteractiveControl(["StrataGate-AgentMemory"],documentRef);if(section){sectionClicked=!0,section.click();return}}if(!settingsClicked){let settings=exactInteractiveControl(["\u8BBE\u7F6E","Settings"],documentRef);settings&&(settingsClicked=!0,settings.click())}},Observer=window.MutationObserver||globalThis.MutationObserver;return typeof Observer=="function"&&(observer=new Observer(attempt),observer.observe(documentRef.documentElement||documentRef.body,{childList:!0,subtree:!0})),timer=window.setTimeout(cleanup,12e3),attempt(),cleanup}function openFeedbackDeepLink(ctx,documentRef=document,locationRef=window.location,historyRef=window.history){if(!readFeedbackDeepLink(locationRef))return()=>{};if(navigateToFeedback(ctx,locationRef,locationRef,!1)==="host")return consumeFeedbackDeepLink(locationRef,historyRef),()=>{};let legacyCleanup=()=>{},timer=window.setTimeout(()=>{legacyCleanup=openLegacyFeedbackDeepLink(documentRef)},250);return ctx?.inject?.(["settingsNavigation"],scope=>{navigateToFeedback(scope,locationRef,locationRef,!1)==="host"&&(window.clearTimeout(timer),legacyCleanup(),consumeFeedbackDeepLink(locationRef,historyRef))}),()=>{window.clearTimeout(timer),legacyCleanup()}}function openGraphNodeDeepLink(ctx,documentRef=document,locationRef=window.location,historyRef=window.history){let graphLink=readGraphNodeDeepLink(locationRef);if(!graphLink)return()=>{};if(typeof ctx?.get?.("settingsNavigation")?.openSection=="function")return navigateToGraphNode(ctx,graphLink.namespace,graphLink.nodeId,locationRef,!1).then(opened=>{opened&&consumeGraphNodeDeepLink(locationRef,historyRef)}),()=>{};let legacyCleanup=()=>{},timer=window.setTimeout(()=>{legacyCleanup=openLegacyFeedbackDeepLink(documentRef)},250);return ctx?.inject?.(["settingsNavigation"],scope=>{navigateToGraphNode(scope,graphLink.namespace,graphLink.nodeId,locationRef,!1).then(opened=>{opened&&(window.clearTimeout(timer),legacyCleanup(),consumeGraphNodeDeepLink(locationRef,historyRef))})}),()=>{window.clearTimeout(timer),legacyCleanup()}}let eventDetailCss=`
326
326
  .sg-event-metadata{display:flex;align-items:center;gap:7px 16px;flex-wrap:wrap;margin-top:8px;color:var(--sg-muted);font-size:12px;line-height:1.45}.sg-event-metadata-item{display:inline-flex;align-items:center;gap:5px;min-width:0}.sg-event-metadata b{color:var(--sg-muted);font-weight:620}.sg-event-participants{display:inline-flex;align-items:center;gap:5px;flex-wrap:wrap}.sg-event-metadata .sg-entity-pill{padding:2px 7px}.sg-entity-pill-static{cursor:default;opacity:.82}.sg-entity-pill-static:hover{transform:none!important;background:transparent!important}.sg-event-section{display:grid;gap:9px;padding:17px 0;border-bottom:1px solid var(--sg-border)}.sg-event-section-title{margin:0;color:var(--sg-text);font-size:14px;font-weight:730}.sg-event-memory-copy{max-width:65ch;margin:0;color:var(--sg-text);font-size:14px;line-height:1.72;white-space:pre-wrap;overflow-wrap:anywhere;text-wrap:pretty}.sg-event-weight-section{gap:0}
327
327
  .sg-weight-header{display:flex;align-items:baseline;justify-content:space-between;gap:12px;margin-bottom:9px}.sg-weight-header .sg-section-title,.sg-long-detail .sg-weight-header h3{margin:0}.sg-weight-metrics{display:grid!important;grid-template-columns:1fr!important;gap:0!important;margin:0 0 13px!important}.sg-weight-metric{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:14px;min-width:0;padding:7px 2px!important;border-bottom:1px solid color-mix(in srgb,var(--sg-border) 72%,transparent);border-radius:0!important;background:transparent!important}.sg-weight-metric:last-child{border-bottom:0}.sg-weight-metric>span:first-child{color:var(--sg-muted);font-size:12px}.sg-weight-metric strong{margin:0!important;color:var(--sg-text);font-size:15px!important;font-weight:740;font-variant-numeric:tabular-nums;white-space:nowrap}.sg-weight-value{display:inline-flex!important;align-items:center;justify-content:flex-end;gap:6px;color:var(--sg-text)!important}
328
328
  .sg-info-disclosure{position:relative;display:inline-flex}.sg-info-trigger{display:grid;place-items:center;width:19px;height:19px;padding:0;border:0;border-radius:50%;background:transparent;color:var(--sg-muted);font-size:13px;line-height:1;cursor:pointer}.sg-info-trigger:hover,.sg-info-trigger[aria-expanded="true"]{background:var(--sg-soft);color:var(--sg-text)}.sg-info-popover{position:absolute;right:0;top:calc(100% + 7px);z-index:20;width:min(320px,calc(100vw - 40px));padding:13px 14px;border:1px solid color-mix(in srgb,var(--sg-accent) 20%,var(--sg-border));border-radius:9px;background:var(--sg-page);color:var(--sg-text);box-shadow:0 14px 36px color-mix(in srgb,var(--sg-text) 18%,transparent);font-size:12px;line-height:1.58;text-align:left}.sg-info-title{display:block;margin-bottom:7px;font-size:13px}.sg-info-popover p{margin:0;color:var(--sg-muted)}.sg-info-popover p+p{margin-top:7px}.sg-adoption-history{display:grid;gap:10px;margin:0;padding:0;list-style:none;counter-reset:history}.sg-adoption-history li{display:grid;gap:1px;padding-bottom:9px;border-bottom:1px solid var(--sg-border)}.sg-adoption-history li:last-child{padding-bottom:0;border-bottom:0}.sg-adoption-history time,.sg-adoption-history span{color:var(--sg-muted)}.sg-floor-table{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:4px 14px;margin:10px 0 0;padding-top:9px;border-top:1px solid var(--sg-border)}.sg-floor-table dt,.sg-floor-table dd{margin:0;color:var(--sg-muted)}.sg-floor-table .current{color:var(--sg-accent);font-weight:720}
@@ -704,59 +704,195 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
704
704
  .sg-memory .sg-tab.active:after{left:2px;right:2px}
705
705
  }
706
706
 
707
- /* \u603B\u89C8\uFF1A\u5927\u6570\u5B57 + \u7CBE\u7B80\u8BB0\u5FC6\u67F1 + \u957F\u671F\u8BB0\u5FC6\u70ED\u529B\u683C */
708
- .sg-ov{display:grid;gap:22px;min-width:0}
709
- .sg-ov-top{display:grid;grid-template-columns:minmax(180px,240px) minmax(0,1fr);gap:36px;align-items:start}
710
- .sg-ov-big{display:flex;align-items:flex-end;gap:8px}
711
- .sg-ov-big b{font:400 76px/0.9 var(--sg-serif);letter-spacing:-.03em}
712
- .sg-ov-big .sg-used svg{width:30px;height:24px;margin-bottom:12px}
713
- .sg-ov-stat p{margin:12px 0 0;color:var(--sg-muted);font-size:13px;line-height:1.6}
714
- .sg-ov-empty{color:var(--sg-muted)}
707
+ /* Share the approved top bar across views; keep page-body styling local. */
708
+ .sg-memory-panel{container:sg-memory-host / inline-size}
709
+ .sg-memory.sg-unified-top{
710
+ --sg-top-sans:"Noto Sans SC","Microsoft YaHei","PingFang SC",sans-serif;
711
+ --sg-top-serif:"Noto Serif SC","Times New Roman",serif;
712
+ --sg-overview-unit:clamp(.48px,.05733945cqi,1px);
713
+ --sg-overview-gutter:clamp(16px,2.6087cqi,48px);
714
+ max-width:1920px;padding:calc(30 * var(--sg-overview-unit)) var(--sg-overview-gutter) calc(32 * var(--sg-overview-unit));
715
+ }
716
+ .sg-memory.sg-overview-page{
717
+ --sg-sans:var(--sg-top-sans);--sg-serif:var(--sg-top-serif);
718
+ --sg-ink:color-mix(in srgb,#3d3c38 88%,var(--sg-text));
719
+ --sg-moss:#607f4e;--sg-water:#426f9b;--sg-sand:#a98431;
720
+ font-family:var(--sg-sans);
721
+ }
722
+ .sg-unified-top .sg-header-row-primary,.sg-unified-top .sg-tabs{
723
+ --sg-serif:var(--sg-top-serif);
724
+ --sg-ink:color-mix(in srgb,#3d3c38 88%,var(--sg-text));
725
+ --sg-moss:#607f4e;--sg-water:#426f9b;--sg-sand:#a98431;
726
+ font-family:var(--sg-top-sans);
727
+ }
728
+ .sg-page-body{display:contents}
729
+ .sg-memory.sg-unified-top:not(.sg-overview-page){padding-bottom:0}
730
+ .sg-unified-top:not(.sg-overview-page) .sg-page-body{
731
+ display:block;container:sg-memory / inline-size;box-sizing:border-box;
732
+ --sg-body-gutter:clamp(16px,2.7523cqi,48px);
733
+ width:min(1200px,calc(100% + 2 * var(--sg-body-gutter)));
734
+ margin-inline:calc((100% - min(1200px,calc(100% + 2 * var(--sg-body-gutter)))) / 2);
735
+ padding:max(6px,calc(62 * var(--sg-overview-unit) - 24px)) 20px 36px;
736
+ }
737
+ .sg-unified-top.sg-settings-page .sg-page-body{container-name:sg-settings}
738
+ @media (max-width:560px){.sg-unified-top:not(.sg-overview-page) .sg-page-body{padding-inline:12px;padding-bottom:26px}}
739
+ .sg-unified-top .sg-header{padding:calc(6 * var(--sg-overview-unit)) 0 0}
740
+ .sg-unified-top .sg-header-row{padding:0}
741
+ .sg-unified-top .sg-brand{gap:calc(20 * var(--sg-overview-unit))}
742
+ .sg-unified-top .sg-logo{width:calc(46 * var(--sg-overview-unit));height:calc(46 * var(--sg-overview-unit))}
743
+ .sg-unified-top .sg-brand-title{gap:calc(16 * var(--sg-overview-unit));flex-wrap:nowrap}
744
+ .sg-unified-top .sg-brand-name{font-family:var(--sg-serif);font-size:calc(34 * var(--sg-overview-unit));font-weight:600}
745
+ .sg-unified-top .sg-brand-version{font-size:calc(24 * var(--sg-overview-unit));font-weight:400}
746
+ .sg-unified-top .sg-header-usage{gap:calc(16 * var(--sg-overview-unit));font-size:calc(20 * var(--sg-overview-unit))}
747
+ .sg-unified-top .sg-header-end{gap:calc(16 * var(--sg-overview-unit))}
748
+ .sg-unified-top .sg-project{min-height:calc(56 * var(--sg-overview-unit));min-width:calc(210 * var(--sg-overview-unit));padding:0 calc(14 * var(--sg-overview-unit));gap:calc(12 * var(--sg-overview-unit));font-size:calc(24 * var(--sg-overview-unit));border-radius:calc(10 * var(--sg-overview-unit))}
749
+ .sg-unified-top .sg-project-label{display:none}
750
+ .sg-unified-top .sg-project-select{flex:1;width:auto;max-width:20ch;font-size:calc(24 * var(--sg-overview-unit));font-weight:400}
751
+ .sg-unified-top .sg-ghstar{height:calc(56 * var(--sg-overview-unit));min-width:calc(220 * var(--sg-overview-unit));font-size:calc(24 * var(--sg-overview-unit));border-radius:calc(10 * var(--sg-overview-unit));color:color-mix(in srgb,var(--sg-text) 45%,var(--sg-muted))}
752
+ .sg-unified-top .sg-ghstar:hover{color:var(--sg-text)}
753
+ .sg-unified-top .sg-ghstar-label,.sg-unified-top .sg-ghstar-count{padding:0 calc(18 * var(--sg-overview-unit))}
754
+ .sg-unified-top .sg-ghstar-label{flex:1;justify-content:center;gap:calc(12 * var(--sg-overview-unit))}
755
+ .sg-unified-top .sg-ghstar-icon{width:calc(27 * var(--sg-overview-unit));height:calc(27 * var(--sg-overview-unit))}
756
+ .sg-unified-top .sg-ghstar-count{min-width:calc(82 * var(--sg-overview-unit));justify-content:center;font-family:inherit}
757
+ .sg-unified-top .sg-tabs{gap:calc(24 * var(--sg-overview-unit));margin:calc(22 * var(--sg-overview-unit)) calc(-1 * var(--sg-overview-gutter)) 0;padding:0 var(--sg-overview-gutter)}
758
+ .sg-unified-top .sg-tab{gap:calc(12 * var(--sg-overview-unit));padding:calc(14 * var(--sg-overview-unit)) calc(14 * var(--sg-overview-unit)) calc(20 * var(--sg-overview-unit));font-size:calc(26 * var(--sg-overview-unit));color:color-mix(in srgb,var(--sg-text) 35%,var(--sg-muted))}
759
+ .sg-unified-top .sg-tab.active{color:var(--sg-text)}
760
+ .sg-unified-top .sg-tab-swatch{width:calc(17 * var(--sg-overview-unit));height:calc(17 * var(--sg-overview-unit));border-radius:3px}
761
+ /* Native control/readability floors need less surrounding space as the
762
+ panel narrows; retain the original spacing at the reference width. */
763
+ .sg-overview-page .sg-view{padding-top:max(6px,calc(62 * var(--sg-overview-unit) - 24px))}
764
+ .sg-overview-page .sg-footer{margin:max(12px,calc(50 * var(--sg-overview-unit) - 11px)) calc(-1 * var(--sg-overview-gutter)) 0;padding:calc(26 * var(--sg-overview-unit)) var(--sg-overview-gutter) 0;font-size:calc(23 * var(--sg-overview-unit));flex-wrap:wrap}
765
+ .sg-overview-page .sg-footer-links{display:inline-flex;align-items:center;gap:calc(8 * var(--sg-overview-unit));flex-wrap:wrap}
766
+ .sg-overview-page .sg-footer a{color:inherit;text-decoration:none}
767
+ .sg-overview-page .sg-footer a:hover{text-decoration:underline}
768
+ .sg-ov{--sg-bar-width:calc(168 * var(--sg-overview-unit));display:grid;gap:calc(55 * var(--sg-overview-unit));min-width:0}
769
+ .sg-ov-top{display:grid;grid-template-columns:minmax(0,25%) minmax(0,1fr);gap:calc(44 * var(--sg-overview-unit));align-items:start}
770
+ .sg-ov-big{display:flex;align-items:flex-end;gap:calc(14 * var(--sg-overview-unit));min-width:0}
771
+ .sg-ov-big b{font:400 calc(144 * var(--sg-overview-unit))/.925 "Times New Roman",var(--sg-serif);letter-spacing:0}
772
+ .sg-ov-speech{display:block;width:calc(54 * var(--sg-overview-unit));height:calc(48 * var(--sg-overview-unit));flex:none;color:var(--sg-text)}
773
+ .sg-ov-big .sg-ov-speech{margin-bottom:calc(6 * var(--sg-overview-unit))}
774
+ .sg-ov-summary{margin:calc(32 * var(--sg-overview-unit)) 0 0;color:color-mix(in srgb,var(--sg-text) 35%,var(--sg-muted));font-size:calc(24 * var(--sg-overview-unit));line-height:1.6;text-wrap:pretty}
775
+ .sg-memory .sg-ov-status{display:inline-flex;align-items:center;gap:calc(14 * var(--sg-overview-unit));max-width:100%;margin:calc(22 * var(--sg-overview-unit)) 0 0;padding:0;border:0;background:none;color:var(--sg-muted);font-size:calc(24 * var(--sg-overview-unit));line-height:1.5;text-align:left;cursor:pointer}
776
+ .sg-ov-status:hover{color:var(--sg-text)}
777
+ .sg-runtime-dot{display:inline-block;flex:none;width:13px;height:13px;border-radius:50%;background:var(--sg-muted)}
778
+ .sg-unified-top .sg-runtime-dot{width:calc(13 * var(--sg-overview-unit));height:calc(13 * var(--sg-overview-unit))}
779
+ .sg-runtime-dot[data-state="ok"]{background:#2d8b57}
780
+ .sg-runtime-dot[data-state="processing"],.sg-runtime-dot[data-state="warning"]{background:#a98431}
781
+ .sg-runtime-dot[data-state="failed"]{background:var(--sg-danger)}
782
+ .sg-project .sg-runtime-dot{width:12px;height:12px}
783
+ .sg-unified-top .sg-project .sg-runtime-dot{width:calc(12 * var(--sg-overview-unit));height:calc(12 * var(--sg-overview-unit))}
784
+ .sg-pillar-group{min-width:0}
785
+ .sg-pillar-cap{display:flex;flex-direction:column;align-items:center;gap:calc(10 * var(--sg-overview-unit));width:var(--sg-bar-width);height:calc(92 * var(--sg-overview-unit));padding-top:calc(6 * var(--sg-overview-unit))}
786
+ .sg-pillar-cap:after{content:"";flex:none;width:3px;height:calc(20 * var(--sg-overview-unit));background:var(--sg-text)}
715
787
  .sg-pillar{display:grid;gap:0}
716
- .sg-pillar-row{display:grid;grid-template-columns:72px minmax(0,1fr) auto minmax(108px,auto) minmax(132px,auto);column-gap:12px;align-items:center;width:100%;min-height:46px;padding:0;border:0;border-bottom:1px solid var(--sg-hair);border-radius:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
717
- .sg-pillar-row:hover{background:color-mix(in srgb,var(--sg-soft) 65%,transparent)}
718
- .sg-pillar-row:focus-visible{outline:2px solid var(--sg-accent);outline-offset:-2px;border-radius:6px}
719
- .sg-pillar-tail{display:contents}
720
- .sg-pillar-bar{width:72px;height:34px;border-radius:3px;background:var(--sg-ink);animation:sg-r6-rise .45s both}
721
- .sg-pillar-bar.moss{background:var(--sg-moss)}
722
- .sg-pillar-bar.water{background:var(--sg-water)}
723
- .sg-pillar-bar.sand{background:var(--sg-sand)}
724
- .sg-pillar-bar.lib{height:42px;background:color-mix(in srgb,var(--sg-moss) 12%,transparent);box-shadow:inset 0 0 0 1.5px var(--sg-moss)}
725
- .sg-pillar-gap{height:0;margin:8px 0 8px 84px;border-top:1px dashed var(--sg-border)}
726
- .sg-pillar-name,.sg-pillar-use,.sg-pillar-val,.sg-pillar-when{display:flex;align-items:center;min-width:0;min-height:40px}
727
- .sg-pillar-name b{font-size:14px;font-weight:600;white-space:nowrap}
728
- .sg-pillar-use{justify-content:flex-end}
729
- .sg-pillar-use:empty{visibility:hidden}
730
- .sg-pillar-val{justify-content:flex-end;gap:6px;color:var(--sg-muted);font-size:12px;white-space:nowrap}
731
- .sg-pillar-val b{font:400 22px/1 var(--sg-serif);color:var(--sg-text)}
732
- .sg-pillar-when{justify-content:flex-end;padding-left:14px;color:var(--sg-muted);font-size:12px;white-space:nowrap}
733
- .sg-pillar-key{display:flex;gap:16px;flex-wrap:wrap;margin-top:12px;color:var(--sg-muted);font-size:12px}
734
- .sg-pillar-key span{display:inline-flex;align-items:center;gap:6px}
735
- .sg-heat{padding-top:16px;border-top:1px solid var(--sg-hair)}
736
- .sg-heat-head{display:flex;justify-content:space-between;gap:12px;margin-bottom:10px;color:var(--sg-muted);font-size:12px}
737
- .sg-heat-head span:first-child{display:inline-flex;align-items:center;gap:6px;color:var(--sg-text);font-weight:600}
738
- .sg-heat-grid{display:grid;grid-template-columns:repeat(28,minmax(0,1fr));gap:4px}
739
- .sg-heat-grid i{aspect-ratio:1;border-radius:3px;background:var(--sg-sheet);box-shadow:inset 0 0 0 1px var(--sg-hair)}
740
- .sg-heat-scale{display:flex;justify-content:space-between;margin-top:6px;color:var(--sg-muted);font:11px var(--sg-mono)}
741
- @container sg-memory (max-width:520px){
742
- .sg-ov-top{grid-template-columns:minmax(0,1fr);gap:18px}
743
- .sg-ov-big b{font-size:58px}
744
- .sg-pillar-row{grid-template-columns:44px minmax(0,1fr) auto;column-gap:10px;row-gap:2px;align-items:center;padding:7px 0 8px}
745
- .sg-pillar-bar{width:44px;height:28px}
746
- .sg-pillar-name,.sg-pillar-val,.sg-pillar-when{min-height:0}
747
- .sg-pillar-name{grid-column:2;grid-row:1}
748
- .sg-pillar-name b{white-space:nowrap}
749
- .sg-pillar-use{display:none}
750
- .sg-pillar-tail{grid-column:3;grid-row:1;display:flex;align-items:center;justify-content:flex-end;gap:8px;min-width:0}
751
- .sg-pillar-tail .sg-pillar-use{display:flex;min-height:0}
752
- .sg-pillar-val{white-space:nowrap}
753
- .sg-pillar-when{grid-column:2 / -1;grid-row:2;justify-content:flex-start;padding-left:0;font-size:11.5px;white-space:normal}
754
- .sg-pillar-gap{margin:6px 0;margin-left:0}
755
- .sg-heat-grid{grid-template-columns:repeat(14,minmax(0,1fr))}
788
+ .sg-memory .sg-pillar-row{display:grid;grid-template-columns:var(--sg-bar-width) minmax(0,1fr) auto;column-gap:calc(28 * var(--sg-overview-unit));align-items:center;width:100%;min-height:0;padding:0;border:0;border-radius:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer;position:relative}
789
+ .sg-pillar-row:after{content:"";position:absolute;left:var(--sg-bar-width);right:0;bottom:0;border-bottom:1px solid var(--sg-hair);pointer-events:none}
790
+ .sg-memory .sg-pillar-row:hover{background:color-mix(in srgb,var(--sg-soft) 65%,transparent)}
791
+ .sg-pillar-row:focus-visible{outline:2px solid var(--sg-accent);outline-offset:3px}
792
+ .sg-pillar-tail{display:flex;align-items:center;justify-content:flex-end;gap:calc(66 * var(--sg-overview-unit));min-width:0}
793
+ .sg-pillar-bar{display:block;width:100%;height:calc(86 * var(--sg-overview-unit));margin:0 0 calc(6 * var(--sg-overview-unit));border-radius:3px 3px 0 0;background:var(--sg-ink)}
794
+ .sg-pillar-bar.moss{height:calc(66 * var(--sg-overview-unit));background:var(--sg-moss)}
795
+ .sg-pillar-bar.water{height:calc(94 * var(--sg-overview-unit));background:var(--sg-water)}
796
+ .sg-pillar-bar.sand{height:calc(78 * var(--sg-overview-unit));background:var(--sg-sand)}
797
+ .sg-pillar-bar.lib{height:calc(124 * var(--sg-overview-unit));margin:0;border:2px dashed var(--sg-moss);border-radius:3px;background:color-mix(in srgb,var(--sg-moss) 12%,var(--sg-page))}
798
+ .sg-pillar-gap{height:0;margin:calc(16 * var(--sg-overview-unit)) 0 calc(16 * var(--sg-overview-unit)) calc(var(--sg-bar-width) + calc(24 * var(--sg-overview-unit)));border-top:1px dashed var(--sg-border)}
799
+ .sg-pillar-name,.sg-pillar-use,.sg-pillar-val{display:flex;align-items:center;min-width:0}
800
+ .sg-pillar-name b{font-size:calc(28 * var(--sg-overview-unit));font-weight:600;white-space:nowrap}
801
+ .sg-pillar-use:empty{display:none}
802
+ .sg-ov .sg-used{gap:calc(6 * var(--sg-overview-unit));font-family:inherit;font-size:calc(24 * var(--sg-overview-unit));line-height:1.2}
803
+ .sg-ov .sg-used svg{width:calc(23 * var(--sg-overview-unit));height:calc(20 * var(--sg-overview-unit))}
804
+ .sg-pillar-val{justify-content:flex-end;gap:calc(10 * var(--sg-overview-unit));min-width:calc(178 * var(--sg-overview-unit));color:var(--sg-muted);font-size:calc(23 * var(--sg-overview-unit));white-space:nowrap}
805
+ .sg-pillar-val b{font:400 calc(40 * var(--sg-overview-unit))/1 var(--sg-serif);color:var(--sg-text)}
806
+ .sg-pillar-key{display:flex;gap:calc(40 * var(--sg-overview-unit));flex-wrap:wrap;margin-top:calc(30 * var(--sg-overview-unit));color:var(--sg-muted);font-size:calc(23 * var(--sg-overview-unit))}
807
+ .sg-pillar-key>span{display:inline-flex;align-items:center;gap:calc(10 * var(--sg-overview-unit))}
808
+ .sg-pillar-key .sg-sw{width:calc(19 * var(--sg-overview-unit));height:calc(19 * var(--sg-overview-unit));border-radius:3px;background:var(--sg-ink)}
809
+ .sg-pillar-key .sg-sw.lib{border:2px dashed currentColor;background:transparent;box-shadow:none}
810
+ .sg-heat{padding-top:calc(32 * var(--sg-overview-unit));border-top:1px solid var(--sg-hair)}
811
+ .sg-heat-head{display:flex;justify-content:space-between;gap:calc(16 * var(--sg-overview-unit));margin-bottom:calc(22 * var(--sg-overview-unit));color:var(--sg-muted);font-size:calc(23 * var(--sg-overview-unit))}
812
+ .sg-heat-head>span:first-child{display:inline-flex;align-items:center;gap:calc(12 * var(--sg-overview-unit));color:var(--sg-text);font-weight:600}
813
+ .sg-heat-grid{display:grid;grid-template-columns:repeat(28,minmax(0,1fr));gap:calc(8 * var(--sg-overview-unit))}
814
+ .sg-heat-grid i{aspect-ratio:1;border-radius:calc(5 * var(--sg-overview-unit));background:var(--sg-sheet);box-shadow:inset 0 0 0 1px var(--sg-hair)}
815
+ .sg-heat-scale{display:flex;justify-content:space-between;margin-top:calc(10 * var(--sg-overview-unit));color:var(--sg-muted);font-size:calc(21 * var(--sg-overview-unit))}
816
+ /* Keep small text readable without restoring the reference's large
817
+ desktop minimums inside a host sidebar or a scaled application. */
818
+ @container (min-width:721px){
819
+ .sg-unified-top .sg-header-row-primary{min-height:0}
820
+ .sg-unified-top .sg-brand-name{font-size:max(18px,calc(34 * var(--sg-overview-unit)))}
821
+ .sg-unified-top .sg-brand-version{font-size:max(12px,calc(24 * var(--sg-overview-unit)))}
822
+ .sg-unified-top .sg-project{min-height:max(32px,calc(56 * var(--sg-overview-unit)));min-width:max(120px,calc(210 * var(--sg-overview-unit)))}
823
+ .sg-unified-top .sg-project,.sg-unified-top .sg-project-select{font-size:max(13px,calc(24 * var(--sg-overview-unit)))}
824
+ .sg-unified-top .sg-ghstar{height:max(32px,calc(56 * var(--sg-overview-unit)));min-width:max(126px,calc(220 * var(--sg-overview-unit)));font-size:max(13px,calc(24 * var(--sg-overview-unit)))}
825
+ .sg-unified-top .sg-tab{font-size:max(14px,calc(26 * var(--sg-overview-unit)))}
826
+ .sg-ov-summary{font-size:max(12px,calc(24 * var(--sg-overview-unit)))}
827
+ .sg-memory .sg-ov-status{font-size:max(12px,calc(24 * var(--sg-overview-unit)))}
828
+ .sg-pillar-name b{font-size:max(14px,calc(28 * var(--sg-overview-unit)))}
829
+ .sg-pillar-val{font-size:max(12px,calc(23 * var(--sg-overview-unit)))}
830
+ .sg-pillar-key,.sg-ov .sg-used,.sg-heat-head,.sg-overview-page .sg-footer{font-size:max(12px,calc(23 * var(--sg-overview-unit)))}
831
+ .sg-heat-scale{font-size:max(11px,calc(21 * var(--sg-overview-unit)))}
832
+ }
833
+ @container (min-width:721px) and (max-width:820px){
834
+ .sg-ov-top{grid-template-columns:minmax(220px,28%) minmax(0,1fr)}
835
+ }
836
+ @container (max-width:720px){
837
+ .sg-unified-top .sg-runtime-dot{width:10px;height:10px}
838
+ .sg-unified-top .sg-project .sg-runtime-dot{width:9px;height:9px}
839
+ .sg-unified-top .sg-brand{gap:10px}
840
+ .sg-unified-top .sg-logo{width:34px;height:34px}
841
+ .sg-unified-top .sg-brand-title{gap:4px 10px}
842
+ .sg-unified-top .sg-brand-name{font-size:24px}
843
+ .sg-unified-top .sg-brand-version{font-size:12px}
844
+ .sg-unified-top .sg-header-row-primary{flex-wrap:wrap;gap:16px}
845
+ .sg-unified-top .sg-header-usage{gap:10px}
846
+ .sg-unified-top .sg-project{min-width:0;padding:0 9px;gap:8px}
847
+ .sg-unified-top .sg-project,.sg-unified-top .sg-project-select{font-size:14px;min-height:34px}
848
+ .sg-unified-top .sg-header-end{gap:10px}
849
+ .sg-unified-top .sg-ghstar{height:34px;min-width:0;font-size:14px}
850
+ .sg-unified-top .sg-ghstar-label,.sg-unified-top .sg-ghstar-count{padding:0 9px}
851
+ .sg-unified-top .sg-ghstar-label{gap:6px}
852
+ .sg-unified-top .sg-ghstar-count{min-width:0}
853
+ .sg-unified-top .sg-ghstar-icon{width:17px;height:17px}
854
+ .sg-unified-top .sg-tabs{gap:8px;margin-top:20px}
855
+ .sg-unified-top .sg-tab{flex:0 0 auto;gap:6px;padding:12px 6px;font-size:14px}
856
+ .sg-unified-top .sg-tab-swatch{width:11px;height:11px}
857
+ .sg-overview-page .sg-view{padding-top:28px}
858
+ .sg-ov{--sg-bar-width:72px;gap:30px}
859
+ .sg-ov-top{grid-template-columns:minmax(0,1fr);gap:24px}
860
+ .sg-ov-big b{font-size:88px}
861
+ .sg-ov-big .sg-ov-speech{width:38px;height:34px}
862
+ .sg-ov-summary{margin-top:16px;font-size:16px}
863
+ .sg-memory .sg-ov-status{margin-top:18px;gap:10px;font-size:16px}
864
+ .sg-pillar-cap{height:66px;gap:6px}
865
+ .sg-pillar-cap .sg-ov-speech{width:38px;height:34px}
866
+ .sg-pillar-cap:after{height:14px;width:2px}
867
+ .sg-memory .sg-pillar-row{column-gap:14px}
868
+ .sg-pillar-bar{height:56px;margin-bottom:4px}
869
+ .sg-pillar-bar.moss{height:44px}.sg-pillar-bar.water{height:60px}.sg-pillar-bar.sand{height:52px}.sg-pillar-bar.lib{height:80px}
870
+ .sg-pillar-name b{font-size:18px}
871
+ .sg-pillar-tail{gap:12px}
872
+ .sg-pillar-val{gap:5px;min-width:0;font-size:14px}
873
+ .sg-pillar-val b{font-size:28px}
874
+ .sg-ov .sg-used{font-size:14px;gap:4px}
875
+ .sg-ov .sg-used svg{width:16px;height:14px}
876
+ .sg-pillar-gap{margin:12px 0 12px calc(var(--sg-bar-width) + 14px)}
877
+ .sg-pillar-key{gap:20px;margin-top:20px;font-size:14px}
878
+ .sg-pillar-key>span{gap:7px}.sg-pillar-key .sg-sw{width:13px;height:13px}
879
+ .sg-heat{padding-top:22px}.sg-heat-head{margin-bottom:14px;font-size:14px}
880
+ .sg-heat-grid{grid-template-columns:repeat(14,minmax(0,1fr));gap:5px}
756
881
  .sg-heat-grid i:nth-child(-n+14){display:none}
757
882
  .sg-heat-scale span:first-child{font-size:0}
758
- .sg-heat-scale span:first-child:before{content:'2 \u5468\u524D';font-size:11px}
759
- }
883
+ .sg-heat-scale span:first-child:before{content:'2 \u5468\u524D';font-size:13px}
884
+ .sg-overview-page .sg-footer{font-size:13px;margin-top:30px;padding-top:20px}
885
+ }
886
+ @container (max-width:380px){
887
+ .sg-unified-top .sg-tabs{gap:4px}
888
+ .sg-unified-top .sg-tab{flex:0 0 auto;gap:4px;padding-inline:2px;font-size:12px}
889
+ .sg-unified-top .sg-tab-swatch{width:9px;height:9px}
890
+ .sg-ov{--sg-bar-width:52px}
891
+ .sg-memory .sg-pillar-row{column-gap:10px}
892
+ .sg-pillar-name b{font-size:16px}
893
+ .sg-pillar-tail{gap:8px}
894
+ .sg-pillar-val{font-size:12px;gap:4px}.sg-pillar-val b{font-size:25px}
895
+ .sg-heat-head{gap:8px;font-size:12px}.sg-heat-head>span:first-child{gap:6px}
760
896
  }
761
897
 
762
898
  /* \u5E38\u9A7B\u753B\u50CF\uFF1A\u5206\u7EC4\u5217\u8868\uFF0C\u4E00\u884C\u5C31\u662F\u4E00\u9879 */
@@ -1220,4 +1356,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1220
1356
  @container(max-width:600px){.sg-dup-options{grid-template-columns:1fr}.sg-dup-option{padding:12px}.sg-dup-draft-heading{flex-wrap:wrap}}
1221
1357
  @media(prefers-reduced-motion:reduce){.sg-dup-draft-skeleton span{animation:none}}
1222
1358
  @container(max-width:420px){.sg-dup-comparison,.sg-dup-methods{grid-template-columns:1fr}.sg-dup-heading h2{font-size:21px}.sg-dup-card-body{padding:13px}.sg-dup-actions>div{width:100%;justify-content:space-between}.sg-dup-button.primary{flex:1}.sg-dup-preview{padding:13px}}
1223
- `;function DuplicateIcon({kind="cards",size:size3=17}){let paths={cards:"M7 3H3v14h10v-4M7 3v10h10V3H7Z",check:"m4 10 4 4 8-8",info:"M10 9v5m0-8v.2M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0Z",back:"m12 5-5 5 5 5",next:"m8 5 5 5-5 5",merge:"M4 3v3c0 3 6 3 6 6v5m6-14v3c0 3-6 3-6 6m-3 2 3 3 3-3"};return h("svg",{width:size3,height:size3,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},h("path",{d:paths[kind]||paths.cards}))}function DuplicateEvidence({namespace,card,hideSummary=!1}){let[result,setResult]=React.useState(null),[error3,setError]=React.useState(""),[attempt,setAttempt]=React.useState(0);return React.useEffect(()=>{let active=!0;return setResult(null),setError(""),api2("sources",{namespace,eventId:card.id}).then(value=>{active&&setResult(value)}).catch(reason=>{active&&setError(String(reason.message||reason))}),()=>{active=!1}},[namespace,card.id,attempt]),h("section",{className:"sg-dup-source","aria-label":"\u5B8C\u6574\u8BB0\u5FC6\u4E0E\u6765\u6E90"},h("h4",null,hideSummary?"\u539F\u59CB\u6765\u6E90":"\u5B8C\u6574\u8BB0\u5FC6\u4E0E\u6765\u6E90"),hideSummary?null:h("p",{className:"sg-dup-summary"},card.summary),error3?h("div",{role:"alert"},error3,h("button",{type:"button",className:"sg-dup-button",onClick:()=>setAttempt(value=>value+1)},"\u91CD\u8BD5\u8BFB\u53D6\u6765\u6E90")):result?result.messages?.length?h("div",{className:"sg-citation-messages"},result.messages.map(message=>h("div",{key:message.id,className:"sg-citation-message"},h("span",{className:"sg-citation-message-role"},(message.role||"Recorded")+(message.createdAt?" \xB7 "+exactTime(message.createdAt):"")),String(message.content||"")))):h("p",null,"\u5F53\u524D\u6CA1\u6709\u53EF\u663E\u793A\u7684\u539F\u59CB\u6765\u6E90\u6D88\u606F\u3002"):h("p",{role:"status"},"\u6B63\u5728\u8BFB\u53D6\u6765\u6E90\u2026"))}function DuplicateCard({card,letter,selected,onSelect,unavailable,disabled,namespace,fullContent=!1,selectionMade=!1}){let[expanded,setExpanded]=React.useState(!1),[showSource,setShowSource]=React.useState(!1),sourcePosition=React.useRef(null);(React.useLayoutEffect||React.useEffect)(()=>{if(showSource||!sourcePosition.current)return;let{trigger,ancestors,top,left}=sourcePosition.current;trigger?.focus?.({preventScroll:!0});for(let saved of ancestors)saved.node.scrollTop=saved.top,saved.node.scrollLeft=saved.left;window.scrollTo?.(left,top),sourcePosition.current=null},[showSource]);let toggleSource=event3=>{if(!showSource){let ancestors=[];for(let node=event3.currentTarget.parentElement;node;node=node.parentElement)node.scrollHeight>node.clientHeight&&ancestors.push({node,top:node.scrollTop,left:node.scrollLeft});sourcePosition.current={trigger:event3.currentTarget,ancestors,top:window.scrollY||0,left:window.scrollX||0}}setShowSource(value=>!value)};if(!card)return h("article",{className:"sg-dup-card"},h("div",{className:"sg-dup-card-body"},h("h3",null,"\u8BB0\u5FC6 "+letter),h("p",null,"\u539F\u5361\u5DF2\u4E0D\u53EF\u7528")));let status={active:"\u5F53\u524D\u6709\u6548",superseded:"\u5DF2\u88AB\u66FF\u4EE3",archived:"\u5DF2\u5F52\u6863",forgotten:"\u5DF2\u9057\u5FD8"},criticality={routine:"\u4E00\u822C\u8BB0\u5FC6",preference:"\u504F\u597D",identity:"\u4E2A\u4EBA\u7ECF\u5386",safety:"\u91CD\u8981\u7EA6\u675F"},scope={user:"\u4E2A\u4EBA",project:"\u9879\u76EE",session:"\u672C\u6B21\u4F1A\u8BDD"},temporal=card.temporal||{},date=temporal.happenedStart||temporal.originalText;return h("article",{className:"sg-dup-card"+(selected?" selected":"")+(card.status==="archived"?" archived":"")},h("label",{className:"sg-dup-choice"},onSelect?h("input",{id:"sg-retain-"+card.id,type:"radio",name:"duplicate-retained",checked:selected,disabled:disabled||!!unavailable,onChange:onSelect,"aria-label":"\u53EA\u4FDD\u7559 "+letter+"\uFF1A"+card.title}):h("span",{className:"sg-dup-letter"},letter),h("span",null,onSelect?"\u53EA\u4FDD\u7559 "+letter:"\u8BB0\u5FC6 "+letter),h("em",null,status[card.status]||"")),h(onSelect?"label":"div",{className:"sg-dup-card-body",htmlFor:onSelect?"sg-retain-"+card.id:void 0},h("h3",null,card.title),h("div",{className:"sg-dup-meta"},date?h("span",null,date):null,h("span",null,criticality[card.criticality]||"\u4E00\u822C\u8BB0\u5FC6"),h("span",null,scope[card.scope]||card.scope||"\u4E2A\u4EBA"),card.weight?.pinned?h("span",null,"\u5DF2\u7F6E\u9876"):null),h("p",{className:"sg-dup-summary"+(!expanded&&!fullContent?" collapsed":"")},card.summary),!fullContent&&card.summary?.length>160?h("button",{type:"button",className:"sg-dup-expand",onClick:()=>setExpanded(!expanded),"aria-expanded":expanded},expanded?"\u6536\u8D77\u5168\u6587":"\u5C55\u5F00\u5168\u6587"):null,h("dl",{className:"sg-dup-evidence"},card.quotes?.length?h(React.Fragment,null,h("dt",null,"\u5F15\u8BED"),h("dd",null,card.quotes.map(quote=>h("blockquote",{key:quote},quote)))):null,temporal.participants?.length?h(React.Fragment,null,h("dt",null,"\u53C2\u4E0E\u8005"),h("dd",null,temporal.participants.join("\u3001"))):null,card.tags?.length?h(React.Fragment,null,h("dt",null,"\u6807\u7B7E"),h("dd",null,card.tags.join(" \xB7 "))):null)),fullContent&&onSelect&&!unavailable?null:h("div",{className:"sg-dup-card-footer"},fullContent&&onSelect?null:h("button",{type:"button",className:"sg-dup-button","aria-expanded":showSource,onClick:toggleSource},showSource?"\u6536\u8D77\u6765\u6E90\uFF0C\u8FD4\u56DE\u5BF9\u6BD4":"\u67E5\u770B "+(card.sourceMessageIds?.length||0)+" \u6761\u6765\u6E90\u4E0E\u5B8C\u6574\u8BB0\u5FC6"),unavailable?h("small",null,unavailable):null),fullContent&&onSelect?h("p",{className:"sg-dup-selection-result"},selectionMade?selected?"\u786E\u8BA4\u540E\u4FDD\u7559\u8FD9\u5F20":"\u786E\u8BA4\u540E\u5C06\u8FD9\u5F20\u5F52\u6863 \xB7 \u539F\u6587\u548C\u6765\u6E90\u4ECD\u4FDD\u7559":"\u70B9\u51FB\u4FDD\u7559\u8FD9\u5F20\u8BB0\u5FC6"):null,showSource||fullContent&&onSelect?h(React.Fragment,null,h(DuplicateEvidence,{namespace,card,hideSummary:fullContent}),showSource?h("button",{type:"button",className:"sg-dup-button text",onClick:toggleSource},"\u6536\u8D77\u6765\u6E90\uFF0C\u8FD4\u56DE\u5BF9\u6BD4"):null):null)}function DuplicatePair({item,busy,namespace,onResolve,onPrepareDraft,onTakeOver,draftState,onDraftState}){let[selectedId,setSelectedId]=React.useState(draftState?.selectedId||""),[mode,setMode]=React.useState(draftState?.mode||""),[draft,setDraft]=React.useState(draftState?.draft||item.draft||{title:"",summary:""}),[draftError,setDraftError]=React.useState(""),[draftBusy,setDraftBusy]=React.useState(!1),[dirty,setDirty]=React.useState(!!draftState?.dirty),[regenerate,setRegenerate]=React.useState(!1),[saveError,setSaveError]=React.useState(""),[draftOrigin,setDraftOrigin]=React.useState(draftState?.draftOrigin||(item.draft?"AI \u5408\u5E76\u7A3F \xB7 \u8BF7\u6838\u5BF9":"\u624B\u52A8\u586B\u5199\u5408\u5E76\u7A3F")),stageHeading=React.useRef(null);React.useEffect(()=>{onDraftState?.({selectedId,mode,draft,draftOrigin,dirty})},[selectedId,mode,draft,draftOrigin,dirty]),React.useEffect(()=>{mode&&(stageHeading.current?.focus({preventScroll:!0}),stageHeading.current?.scrollIntoView({block:"nearest"}))},[mode]);let archived=item.outcome==="merged"||item.outcome==="selected",retained=item.outcome==="kept"&&(item.aiResolved||item.userReviewed),done=archived||retained,awaitingAI=item.outcome==="pending",selected=selectedId===item.leftId?item.left:selectedId===item.rightId?item.right:null,letter=selectedId===item.leftId?"A":"B",mergeId=item.recommendedKeepId||(item.choices?.right?.canMerge?item.rightId:item.leftId),mergeCard=mergeId===item.leftId?item.left:item.right,selection=item.choices?.[selectedId===item.leftId?"left":"right"],draftValid=!!(draft.title.trim()&&draft.summary.trim()),generateDraft=async(force=!1)=>{if(dirty&&!force){setRegenerate(!0);return}setRegenerate(!1),setDraftBusy(!0),setDraftError("");try{let result2=await onPrepareDraft(item,force);if(!result2?.draft)throw new Error("AI \u5C1A\u672A\u751F\u6210\u5B8C\u6574\u7A3F\uFF0C\u4F60\u53EF\u4EE5\u624B\u52A8\u586B\u5199\u6216\u7A0D\u540E\u91CD\u8BD5\u3002");setDraft(result2.draft),setDirty(!1),setDraftOrigin("AI \u5408\u5E76\u7A3F \xB7 \u8BF7\u6838\u5BF9")}catch(reason){setDraftError(String(reason.message||reason).replace(/\s*[((]duplicates[))]$/,""))}finally{setDraftBusy(!1)}},start=value=>{setMode(value),setSaveError(""),value==="select"&&setSelectedId(""),value==="merge"&&!draft.title&&!draft.summary&&onPrepareDraft&&generateDraft()},save=async()=>{setSaveError("");try{await onResolve(mode==="both"?"keep":mode,item,mode==="select"?selectedId:mode==="merge"?mergeId:void 0,mode==="merge"?draft:void 0)}catch(reason){setSaveError("\u4F60\u7684\u9009\u62E9\u548C\u7F16\u8F91\u5DF2\u4FDD\u7559\u3002"+String(reason.message||reason).replace(/\s*[((]duplicates[))]$/,""))}},cards=(selectable=!1,originals=!1)=>h("div",{className:"sg-dup-comparison",role:selectable?"radiogroup":void 0,"aria-label":selectable?"\u9009\u62E9\u8981\u4FDD\u7559\u7684\u8BB0\u5FC6":"\u53CC\u65B9\u5B8C\u6574\u8BB0\u5FC6"},[originals&&item.originalLeft||item.left,originals&&item.originalRight||item.right].map((card,i2)=>h(DuplicateCard,{key:card?.id||i2,card,letter:i2?"B":"A",namespace,fullContent:!0,selected:selectable&&selectedId===card?.id,selectionMade:!!selectedId,onSelect:selectable?()=>{setSelectedId(i2?item.rightId:item.leftId),setSaveError("")}:null,disabled:busy||draftBusy,unavailable:selectable?item.choices?.[i2?"right":"left"]?.selectBlockedReason:""}))),back=()=>{setMode(""),setSaveError(""),setRegenerate(!1)},result=done&&item.keepId===item.leftId?item.left:item.right,consequences=h("section",{className:"sg-dup-consequences"},h("h3",null,"\u786E\u8BA4\u540E\u4F1A\u53D1\u751F\u4EC0\u4E48"),h("dl",{className:"sg-dup-result"},h("dt",null,"\u65E5\u5E38\u68C0\u7D22"),h("dd",null,mode==="merge"?"\u663E\u793A\u4E0A\u9762\u7684\u5B8C\u6574\u5408\u5E76\u7A3F\u3002":mode==="both"?"\u4E24\u5F20\u8BB0\u5FC6\u5206\u522B\u4FDD\u7559\uFF0C\u5185\u5BB9\u548C\u6765\u6E90\u4E0D\u53D8\u3002":"\u53EA\u663E\u793A\u8BB0\u5FC6 "+letter+" \xB7 "+(selected?.title||"")),h("dt",null,"\u539F\u59CB\u8BB0\u5F55"),h("dd",null,mode==="merge"?"\u53CC\u65B9\u5904\u7406\u524D\u7684\u5185\u5BB9\u3001\u6765\u6E90\u548C\u5386\u53F2\u5173\u8054\u4FDD\u7559\uFF0C\u53EF\u5728\u5DF2\u5904\u7406\u8BB0\u5F55\u4E2D\u6838\u5BF9\u3002":mode==="both"?"\u53CC\u65B9\u539F\u5361\u5747\u4FDD\u7559\u3002":"\u8BB0\u5FC6 "+(letter==="A"?"B":"A")+" \u8F6C\u5165\u5386\u53F2\uFF1B\u72EC\u6709\u5185\u5BB9\u4E0D\u4F1A\u5408\u5165\u6240\u9009\u5361\uFF0C\u539F\u6587\u548C\u6765\u6E90\u4ECD\u4FDD\u7559\u3002"),mode==="merge"&&mergeCard?.temporal?.happenedStart?h(React.Fragment,null,h("dt",null,"\u65E5\u671F"),h("dd",null,"\u68C0\u7D22\u65E5\u671F\u6CBF\u7528 "+mergeCard.temporal.happenedStart+"\uFF1B\u8BF7\u6838\u5BF9\u6B63\u6587\u4E2D\u7684\u539F\u5B89\u6392\u3001\u540E\u7EED\u53D8\u5316\u4E0E\u5F53\u524D\u4E8B\u5B9E\u3002")):null,h("dt",null,"\u540E\u7EED\u8C03\u6574"),h("dd",null,"\u53EF\u5728\u201C\u5DF2\u5904\u7406\u201D\u67E5\u770B\u7ED3\u679C\uFF1B\u6CA1\u6709\u540E\u7EED\u51B2\u7A81\u65F6\u53EF\u64A4\u9500\u3002")));return h("section",{className:"sg-dup-pair","aria-label":"\u8BB0\u5FC6\u5BF9\u6BD4\u4E0E\u5904\u7406","aria-busy":busy||draftBusy},h("nav",{className:"sg-dup-steps","aria-label":"\u5904\u7406\u6B65\u9AA4"},["\u5BF9\u6BD4\u8BB0\u5FC6","\u6838\u5BF9\u7ED3\u679C","\u5B8C\u6210"].map((label,i2)=>h("span",{key:label,"aria-current":(done?2:mode?1:0)===i2?"step":void 0},i2+1+" "+label))),done?h(React.Fragment,null,h("h3",{className:"sg-dup-stage-title"},archived?item.outcome==="merged"?"\u5DF2\u6574\u7406\u6210\u4E00\u5F20\u5B8C\u6574\u8BB0\u5FC6":"\u5DF2\u4FDD\u7559\u8BB0\u5FC6 "+(item.keepId===item.leftId?"A":"B"):"\u5DF2\u5206\u522B\u4FDD\u7559\u4E24\u5F20\u8BB0\u5FC6"),h("p",{className:"sg-dup-reason"},item.aiResolved?"\u7531 AI \u81EA\u52A8\u5904\u7406 \xB7 "+item.reason:item.reason),archived?h(React.Fragment,null,h("div",{className:"sg-dup-result-card"},h("small",null,"\u4ECA\u540E\u4F7F\u7528\u7684\u8BB0\u5FC6"),h("h3",null,result?.title),h("p",{className:"sg-dup-summary"},result?.summary)),h("details",null,h("summary",null,item.originalLeft&&item.originalRight?"\u67E5\u770B\u5904\u7406\u524D\u7684\u4E24\u5F20\u8BB0\u5FC6\u4E0E\u6765\u6E90":"\u67E5\u770B\u4E24\u5F20\u8BB0\u5FC6\u4E0E\u6765\u6E90\uFF08\u6309\u5F53\u524D\u8BB0\u5F55\uFF09"),cards(!1,!0))):cards(),h("div",{className:"sg-dup-actions"},h("p",null,"\u64A4\u9500\u524D\u4F1A\u68C0\u67E5\u540E\u7EED\u53D8\u5316\uFF0C\u907F\u514D\u8986\u76D6\u65B0\u6570\u636E\u3002"),item.undoId?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onResolve("undo",item).catch(()=>{})},"\u64A4\u9500\u672C\u6B21\u5904\u7406"):retained?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onTakeOver?.(item)},"\u91CD\u65B0\u5904\u7406\u8FD9\u7EC4"):h("p",null,"\u6B64\u8BB0\u5F55\u521B\u5EFA\u4E8E\u652F\u6301\u64A4\u9500\u4E4B\u524D\u3002"))):awaitingAI?h(React.Fragment,null,h("div",{className:"sg-dup-reason"},h("strong",null,"AI \u4F1A\u5148\u5224\u65AD\u8FD9\u7EC4\u8BB0\u5FC6"),h("p",null,"\u5224\u65AD\u660E\u786E\u7684\u81EA\u52A8\u5904\u7406\u5E76\u7559\u4E0B\u8BB0\u5F55\uFF1B\u4E0D\u786E\u5B9A\u6216\u5904\u7406\u5931\u8D25\u7684\uFF0C\u624D\u4F1A\u8FDB\u5165\u201C\u9700\u8981\u4F60\u5224\u65AD\u201D\u3002\u4E24\u5F20\u539F\u5361\u76EE\u524D\u5747\u4FDD\u7559\u3002"),h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onTakeOver(item)},"\u6211\u6765\u5904\u7406\u8FD9\u7EC4")),cards()):mode?h(React.Fragment,null,h("button",{type:"button",className:"sg-dup-button text sg-dup-back",disabled:busy||draftBusy,onClick:back},h(DuplicateIcon,{kind:"back",size:14}),"\u8FD4\u56DE\u5BF9\u6BD4"),h("div",{className:"sg-dup-stage-heading"},h("h3",{ref:stageHeading,tabIndex:-1},mode==="merge"?"\u628A\u53CC\u65B9\u4FE1\u606F\u6574\u7406\u6210\u4E00\u5F20\u8BB0\u5FC6":mode==="select"?"\u53EA\u4FDD\u7559\u54EA\u5F20\u8BB0\u5FC6\uFF1F":"\u5206\u522B\u4FDD\u7559\u8FD9\u4E24\u5F20\u8BB0\u5FC6"),h("p",null,mode==="merge"?"\u53CC\u65B9\u6709\u6548\u4FE1\u606F\u4F1A\u6574\u7406\u8FDB\u5B8C\u6574\u7A3F\uFF0C\u4FDD\u5B58\u524D\u4F60\u53EF\u4EE5\u4FEE\u6539\u6807\u9898\u548C\u6B63\u6587\u3002":mode==="select"?"\u4E24\u5F20\u5B8C\u6574\u5185\u5BB9\u90FD\u5728\u4E0B\u65B9\uFF0C\u70B9\u51FB\u8981\u4FDD\u7559\u7684\u5361\u7247\u3002\u53E6\u4E00\u5F20\u8F6C\u5165\u5386\u53F2\uFF0C\u5185\u5BB9\u4E0D\u4F1A\u81EA\u52A8\u5408\u5E76\u3002":"\u9002\u7528\u4E8E\u4E0D\u540C\u4E8B\u4EF6\u3001\u524D\u540E\u8FDB\u5C55\uFF0C\u6216\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u7684\u60C5\u51B5\u3002")),mode==="merge"?h(React.Fragment,null,item.historyNotice||item.mergeWarning?h("p",{className:"sg-dup-reason"},item.historyNotice||item.mergeWarning):null,!item.canMerge&&item.mergeBlockedReason?h("p",{className:"sg-dup-notice error",role:"note"},item.mergeBlockedReason," \u4ECD\u53EF\u5728\u4E0B\u65B9\u6574\u7406\u8349\u7A3F\uFF0C\u539F\u5361\u4E0D\u4F1A\u81EA\u52A8\u6539\u52A8\u3002"):null,h("div",{className:"sg-dup-editor"},h("div",{className:"sg-dup-draft-heading"},h("strong",null,draftBusy?"AI \u6B63\u5728\u6574\u7406\u5408\u5E76\u7A3F\u2026":draftOrigin),h("button",{type:"button",className:"sg-dup-button",disabled:busy||draftBusy,onClick:()=>generateDraft(!dirty)},"\u91CD\u65B0\u8BA9 AI \u6574\u7406")),regenerate?h("div",{className:"sg-dup-reason"},"\u91CD\u65B0\u751F\u6210\u4F1A\u66FF\u6362\u4F60\u5F53\u524D\u7F16\u8F91\u7684\u6807\u9898\u548C\u6B63\u6587\u3002",h("div",{className:"sg-dup-actions"},h("button",{type:"button",className:"sg-dup-button",onClick:()=>setRegenerate(!1)},"\u4FDD\u7559\u5F53\u524D\u7F16\u8F91"),h("button",{type:"button",className:"sg-dup-button",onClick:()=>generateDraft(!0)},"\u66FF\u6362\u4E3A\u65B0\u7A3F"))):null,draftError?h("p",{role:"alert",className:"sg-dup-notice error"},draftError," \u539F\u5361\u672A\u6539\u52A8\uFF0C\u53EF\u76F4\u63A5\u586B\u5199\u4E0B\u65B9\u5B8C\u6574\u8BB0\u5FC6\u3002"):null,draftBusy?h("div",{className:"sg-dup-draft-skeleton",role:"status","aria-label":"\u6B63\u5728\u751F\u6210\u5408\u5E76\u7A3F"},[1,2,3,4].map(i2=>h("span",{key:i2}))):h(React.Fragment,null,h("label",null,"\u5408\u5E76\u540E\u7684\u6807\u9898",h("input",{type:"text","aria-label":"\u5408\u5E76\u540E\u7684\u6807\u9898",value:draft.title,maxLength:200,disabled:busy,onChange:event3=>{setDraft({...draft,title:event3.target.value}),setDirty(!0),setDraftOrigin("\u4F60\u5DF2\u7F16\u8F91")}})),h("label",null,"\u5408\u5E76\u540E\u7684\u5B8C\u6574\u6B63\u6587",h("textarea",{"aria-label":"\u5408\u5E76\u540E\u7684\u5B8C\u6574\u6B63\u6587",value:draft.summary,maxLength:12e3,rows:8,disabled:busy,placeholder:"\u5199\u51FA\u4F60\u5E0C\u671B\u4ECA\u540E\u8BB0\u4F4F\u7684\u5B8C\u6574\u5185\u5BB9\uFF0C\u4FDD\u7559\u65F6\u95F4\u3001\u6761\u4EF6\u548C\u4E0D\u786E\u5B9A\u6027\u3002",onChange:event3=>{setDraft({...draft,summary:event3.target.value}),setDirty(!0),setDraftOrigin("\u4F60\u5DF2\u7F16\u8F91")}})),h("p",{className:"sg-dup-constraint"},draftValid?"\u5C06\u6309\u6B64\u5168\u6587\u4FDD\u5B58\uFF0C\u539F\u59CB\u8BC1\u636E\u53E6\u884C\u4FDD\u7559\u3002":"\u8BF7\u586B\u5199\u5B8C\u6574\u6807\u9898\u548C\u6B63\u6587\u540E\u518D\u4FDD\u5B58\u3002"))),h("details",null,h("summary",null,"\u5C55\u5F00\u53CC\u65B9\u539F\u5361\uFF0C\u6838\u5BF9\u5408\u5E76\u7A3F"),cards())):cards(mode==="select"),mode==="select"&&selected?.status==="superseded"?h("p",{className:"sg-dup-reason",role:"note"},"\u4F60\u9009\u62E9\u7684\u662F\u5386\u53F2\u7248\u672C "+letter+"\u3002\u4FDD\u5B58\u540E\u5B83\u4F1A\u91CD\u65B0\u6210\u4E3A\u6709\u6548\u8BB0\u5FC6\uFF0C\u53E6\u4E00\u5F20\u7684\u65B0\u589E\u5185\u5BB9\u4E0D\u4F1A\u5408\u5165\uFF1B\u8BF7\u786E\u8BA4\u8FD9\u7B26\u5408\u4F60\u7684\u610F\u601D\u3002"):null,mode==="select"&&selected&&selection?.selectBlockedReason?h("p",{className:"sg-dup-notice error",role:"note"},selection.selectBlockedReason):null,mode!=="select"||selected?consequences:h("p",{className:"sg-dup-constraint"},"\u5C1A\u672A\u9009\u62E9\u3002\u8BF7\u5BF9\u6BD4\u4E0A\u65B9\u5B8C\u6574\u5185\u5BB9\uFF0C\u518D\u9009\u62E9\u4FDD\u7559 A \u6216 B\u3002"),saveError?h("p",{className:"sg-dup-notice error",role:"alert"},saveError):null,h("div",{className:"sg-dup-actions"},h("p",null,"\u53EA\u6709\u786E\u8BA4\u4FDD\u5B58\uFF0C\u624D\u4F1A\u66F4\u65B0\u8BB0\u5FC6\u3002"),h("div",null,h("button",{type:"button",className:"sg-dup-button",disabled:busy||draftBusy,onClick:back},"\u8FD4\u56DE\u5BF9\u6BD4"),h("button",{type:"button",className:"sg-dup-button primary",disabled:busy||draftBusy||mode==="merge"&&!draftValid||mode==="select"&&!selected,onClick:save},busy?"\u6B63\u5728\u4FDD\u5B58\u2026":saveError?"\u91CD\u8BD5\u4FDD\u5B58":mode==="merge"?"\u786E\u8BA4\u4FDD\u5B58\u5408\u5E76\u7A3F":mode==="both"?"\u786E\u8BA4\u4FDD\u7559\u4E24\u5F20":selected?"\u786E\u8BA4\u53EA\u4FDD\u7559 "+letter:"\u8BF7\u9009\u62E9 A \u6216 B")))):h(React.Fragment,null,h("p",{className:"sg-dup-reason"},h("strong",null,"\u4E3A\u4EC0\u4E48\u9700\u8981\u4F60\u5224\u65AD"),item.reason),cards(),h("h3",{className:"sg-dup-stage-title"},"\u4F60\u5E0C\u671B\u600E\u4E48\u5904\u7406\uFF1F"),h("div",{className:"sg-dup-options"},[["merge","\u5408\u5E76\u53CC\u65B9\u5185\u5BB9","AI \u6574\u7406\u5B8C\u6574\u7A3F\uFF0C\u4F60\u53EF\u4EE5\u7F16\u8F91\u540E\u518D\u786E\u8BA4\u3002"],["select","\u53EA\u4FDD\u7559\u4E00\u5F20","\u67E5\u770B\u5B8C\u6574\u5185\u5BB9\uFF0C\u9009\u62E9 A \u6216 B\uFF0C\u53E6\u4E00\u5F20\u8F6C\u5165\u5386\u53F2\u3002"],["both","\u4FDD\u7559\u4E24\u5F20","\u5206\u522B\u4FDD\u7559\uFF0C\u7ED3\u675F\u8FD9\u7EC4\u6574\u7406\u3002"]].map(([value,title,description])=>h("button",{key:value,type:"button",className:"sg-dup-option",disabled:busy||draftBusy,onClick:()=>start(value)},h(DuplicateIcon,{kind:value==="merge"?"merge":"cards"}),h("strong",null,title),h("span",null,description)))),h("p",{className:"sg-dup-constraint"},"\u9009\u62E9\u540E\u5148\u6838\u5BF9\u5904\u7406\u7ED3\u679C\uFF0C\u786E\u8BA4\u4FDD\u5B58\u524D\u4E0D\u4F1A\u6539\u52A8\u539F\u5361\u3002")))}function DuplicateReviewPage({namespace,repair,onBack,openEvent,refresh}){let[page,setPage]=React.useState({items:[],offset:0,limit:20,total:0}),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState(""),[notice,setNotice]=React.useState(""),[loading,setLoading]=React.useState(!0),[index,setIndex]=React.useState(0),[queue,setQueue]=React.useState("review"),[lastAction,setLastAction]=React.useState(null),draftCache=React.useRef(new Map),focusPair=React.useRef(null),committedRead=React.useRef(!1),readFailure=reason=>(committedRead.current?"\u5904\u7406\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u8BFB\u53D6\u7ED3\u679C\u5931\u8D25\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u7ED3\u679C\u3002":"")+String(reason.message||reason),requestId=React.useRef(0),load=(offset=0,targetQueue=queue,focus=focusPair.current)=>{let id2=++requestId.current;return setLoading(!0),api2("duplicates",{namespace,offset,limit:20,queue:targetQueue,...focus?{focusLeft:focus.leftId,focusRight:focus.rightId}:{}}).then(value=>{id2===requestId.current&&(setPage(value),setIndex(i2=>value.focusIndex??Math.min(i2,Math.max(0,value.items.length-1))),focusPair.current=null,committedRead.current=!1)}).finally(()=>{id2===requestId.current&&setLoading(!1)})};React.useEffect(()=>{let active=!0,id2=++requestId.current;setLoading(!0),setError("");let focus=focusPair.current;return api2("duplicates",{namespace,offset:page.namespace===namespace&&page.queue===queue?page.offset:0,limit:20,queue,...focus?{focusLeft:focus.leftId,focusRight:focus.rightId}:{}}).then(value=>{active&&id2===requestId.current&&(setPage(value),setIndex(i2=>value.focusIndex??(page.namespace===namespace&&page.queue===queue?Math.min(i2,Math.max(0,value.items.length-1)):0)),focusPair.current=null,committedRead.current=!1)}).catch(reason=>{active&&id2===requestId.current&&setError(readFailure(reason))}).finally(()=>{active&&id2===requestId.current&&setLoading(!1)}),()=>{active=!1}},[namespace,queue,JSON.stringify(repair)]);let pairInput=item=>item?{leftId:item.leftId,rightId:item.rightId,leftFingerprint:item.leftFingerprint,rightFingerprint:item.rightFingerprint,exact:item.exact,similarity:item.similarity}:void 0,takeOver=item=>(setBusy(!0),setError(""),api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"takeover",pair:pairInput(item)})}).then(()=>(focusPair.current=item,setQueue("review"),setNotice("\u5DF2\u7531\u4F60\u63A5\u7BA1\uFF0CAI \u4E0D\u518D\u81EA\u52A8\u5904\u7406\u8FD9\u7EC4\u3002"),refresh())).catch(reason=>setError(String(reason.message||reason))).finally(()=>setBusy(!1))),prepareDraft=(item,regenerate=!1)=>(setBusy(!0),api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"draft",pair:pairInput(item),regenerate})}).finally(()=>setBusy(!1))),control=(action,item,keepId,draft)=>{let committed=!1;setBusy(!0),setError(""),setNotice("");let pair=item?{leftId:item.leftId,rightId:item.rightId,leftFingerprint:item.leftFingerprint,rightFingerprint:item.rightFingerprint,exact:item.exact,similarity:item.similarity}:void 0;return api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action,pair,keepId,draft,undoId:action==="undo"?item?.undoId:void 0})}).then(result=>{if(committed=!0,committedRead.current=!0,action==="undo"){for(let key of draftCache.current.keys())key.startsWith(namespace+":"+item.leftId+":"+item.rightId+":")&&draftCache.current.delete(key);focusPair.current=item,setQueue("review")}return setLastAction(result.undoId?{...item,undoId:result.undoId}:null),["merge","select","keep"].includes(action)&&(focusPair.current=item,setQueue("history")),setNotice(action==="rescan"?"\u5DF2\u91CD\u65B0\u626B\u63CF\uFF0CAI \u4F1A\u5148\u5904\u7406\u5019\u9009\u3002":action==="undo"?"\u5DF2\u64A4\u9500\uFF0C\u6062\u590D\u4E86\u5904\u7406\u524D\u7684\u5185\u5BB9\u3001\u72B6\u6001\u548C\u5173\u8054\u3002":action==="merge"?"\u5DF2\u4FDD\u5B58\u5B8C\u6574\u5408\u5E76\u7A3F\uFF0C\u53CC\u65B9\u8BC1\u636E\u4E0E\u6765\u6E90\u5DF2\u4FDD\u7559\u3002":action==="select"?"\u5DF2\u4FDD\u7559\u6240\u9009\u8BB0\u5FC6\uFF0C\u53E6\u4E00\u5F20\u5DF2\u5F52\u6863\uFF0C\u5185\u5BB9\u672A\u6DF7\u5408\u3002":"\u5DF2\u786E\u8BA4\u4FDD\u7559\u4E24\u5F20\u3002"),refresh()}).then(()=>(action==="rescan"&&setIndex(0),action==="undo"?load(0,"review",item):["merge","select","keep"].includes(action)?load(0,"history",item):load(action==="rescan"?0:page.offset))).catch(reason=>{if(committed){setError("\u5904\u7406\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u8BFB\u53D6\u7ED3\u679C\u5931\u8D25\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u7ED3\u679C\u3002"+String(reason.message||reason));return}throw["merge","select","keep"].includes(action)||setError(String(reason.message||reason)),reason}).finally(()=>setBusy(!1))},navigate=direction=>{if(setError(""),setNotice(""),index+direction>=0&&index+direction<page.items.length){setIndex(index+direction);return}let id2=++requestId.current;setLoading(!0),api2("duplicates",{namespace,offset:Math.max(0,page.offset+direction*page.limit),limit:20,queue}).then(value=>{id2===requestId.current&&(setPage(value),setIndex(direction>0?0:Math.max(0,value.items.length-1)))}).catch(reason=>{id2===requestId.current&&setError(String(reason.message||reason))}).finally(()=>{id2===requestId.current&&setLoading(!1)})},current=page.items[Math.min(index,Math.max(0,page.items.length-1))],draftKey=current?namespace+":"+current.leftId+":"+current.rightId+":"+current.leftFingerprint+":"+current.rightFingerprint:"";return h(React.Fragment,null,h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-duplicates"},h("header",{className:"sg-dup-heading"},h("div",null,h("h2",null,"\u91CD\u590D\u8BB0\u5FC6\u6574\u7406"),h("p",null,"AI \u5148\u5224\u65AD\u5E76\u6574\u7406\u3002\u8FD9\u91CC\u53EA\u9700\u8981\u4F60\u5904\u7406\u62FF\u4E0D\u51C6\u7684\u8BB0\u5FC6\u3002")),h(DuplicateIcon,{size:25})),h("nav",{className:"sg-dup-queues","aria-label":"\u6574\u7406\u961F\u5217"},[["review","\u9700\u8981\u4F60\u5224\u65AD",repair?.needsReview||0],["ai","\u7B49\u5F85 AI",repair?.awaitingAI||0],["history","\u5DF2\u5904\u7406",(repair?.merged||0)+(repair?.selected||0)+(repair?.retained||0)-(repair?.needsReview||0)+(repair?.failed||0)]].map(([value,label,count])=>h("button",{key:value,type:"button",className:"sg-dup-button","aria-pressed":queue===value,disabled:busy,onClick:()=>{setQueue(value),setError(""),setIndex(0)}},label+" "+Math.max(0,count)))),error3?h("div",{role:"alert",className:"sg-dup-notice error"},error3,h("button",{type:"button",className:"sg-dup-button text",disabled:busy||loading,onClick:()=>{setError(""),load(page.offset).catch(reason=>setError(readFailure(reason)))}},"\u91CD\u65B0\u8BFB\u53D6")):null,notice?h("div",{role:"status",className:"sg-dup-notice","aria-live":"polite"},notice,lastAction?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>{control("undo",lastAction).catch(()=>{})}},"\u64A4\u9500\u672C\u6B21\u5904\u7406"):null):null,!error3&&(loading||page.namespace!==namespace||page.queue!==queue)?h("div",{className:"sg-dup-comparison",role:"status","aria-label":"\u6B63\u5728\u8BFB\u53D6\u91CD\u590D\u8BB0\u5FC6"},h("div",{className:"sg-dup-skeleton"}),h("div",{className:"sg-dup-skeleton"})):current&&page.namespace===namespace&&page.queue===queue?h(React.Fragment,null,h("nav",{className:"sg-dup-navigation","aria-label":"\u5207\u6362\u5019\u9009\u7EC4"},h("button",{type:"button",className:"sg-dup-button","aria-label":"\u4E0A\u4E00\u7EC4",disabled:busy||page.offset+index<=0,onClick:()=>navigate(-1)},h(DuplicateIcon,{kind:"back",size:14})),h("select",{value:index,disabled:busy,onChange:event3=>{setIndex(Number(event3.target.value)),setNotice("")},"aria-label":"\u5F53\u524D\u5019\u9009\u7EC4"},page.items.map((item,i2)=>h("option",{key:item.leftId+":"+item.rightId,value:i2},item.left?.title||item.right?.title||"\u539F\u5361\u5DF2\u4E0D\u53EF\u7528"))),h("span",{className:"sg-dup-count"},page.offset+index+1+" / "+page.total),h("button",{type:"button",className:"sg-dup-button","aria-label":"\u4E0B\u4E00\u7EC4",disabled:busy||page.offset+index+1>=page.total,onClick:()=>navigate(1)},h(DuplicateIcon,{kind:"next",size:14}))),h(DuplicatePair,{key:namespace+current.leftId+current.rightId+current.leftFingerprint+current.rightFingerprint+current.outcome+!!current.userReviewed,item:current,busy,namespace,onResolve:control,onPrepareDraft:prepareDraft,onTakeOver:takeOver,draftState:draftCache.current.get(draftKey),onDraftState:value=>{draftCache.current.set(draftKey,value),draftCache.current.size>50&&draftCache.current.delete(draftCache.current.keys().next().value)}})):error3?null:h("section",{className:"sg-dup-empty"},h(DuplicateIcon,{kind:"check",size:28}),h("strong",null,queue==="review"?"\u6682\u65F6\u6CA1\u6709\u9700\u8981\u4F60\u5224\u65AD\u7684\u8BB0\u5FC6":queue==="ai"?"\u6CA1\u6709\u7B49\u5F85 AI \u7684\u5019\u9009":"\u8FD8\u6CA1\u6709\u5904\u7406\u8BB0\u5F55"),h("p",null,queue==="review"?"AI \u80FD\u5904\u7406\u7684\u4F1A\u81EA\u52A8\u5B8C\u6210\u3002\u4F60\u53EF\u4EE5\u5728\u201C\u5DF2\u5904\u7406\u201D\u67E5\u770B\u7ED3\u679C\u3002":"\u626B\u63CF\u548C\u5904\u7406\u8FDB\u5EA6\u4F1A\u5728\u5BF9\u5E94\u961F\u5217\u4E2D\u663E\u793A\u3002")),h("details",{className:"sg-dup-tools"},h("summary",null,"\u91CD\u65B0\u68C0\u67E5\u8BB0\u5FC6\u5E93"),h("p",null,"\u6309\u5F53\u524D\u89C4\u5219\u91CD\u65B0\u626B\u63CF\u3002\u540E\u7EED\u5224\u65AD\u53EF\u80FD\u4F7F\u7528\u5F53\u524D\u6A21\u578B\uFF0C\u5DF2\u5B8C\u6210\u7684\u626B\u63CF\u4E0D\u4F1A\u5728\u6BCF\u6B21\u542F\u52A8\u65F6\u91CD\u590D\u6267\u884C\u3002"),h("button",{type:"button",className:"sg-dup-button",disabled:busy||loading,onClick:()=>{control("rescan").catch(()=>{})}},"\u91CD\u65B0\u626B\u63CF\u4E0E\u5224\u65AD"))))}function SystemPage({selected,blocks,onBack,backLabel="\u66F4\u591A",refresh,onDuplicates}){let processing=blocks.filter(block=>block.status==="processing").length,[refreshing,setRefreshing]=React.useState(!1),[feedback,setFeedback]=React.useState({kind:"",text:""}),repair=selected.duplicateRepair,checkStatus=()=>{let before=processingFingerprint(selected);return setRefreshing(!0),setFeedback({kind:"",text:"\u6B63\u5728\u8BFB\u53D6\u2026"}),refresh({propagateError:!0}).then(next2=>{let updated=next2?.overview?.namespaces?.find(item=>item.namespace===selected.namespace);setFeedback({kind:"done",text:updated&&processingFingerprint(updated)!==before?"\u72B6\u6001\u5DF2\u66F4\u65B0":"\u72B6\u6001\u6CA1\u6709\u53D8\u5316"})}).catch(reason=>{setFeedback({kind:"failed",text:"\u8BFB\u53D6\u5931\u8D25\uFF1A"+String(reason?.message||reason)})}).finally(()=>setRefreshing(!1))};return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u7CFB\u7EDF\u72B6\u6001"),h("p",null,"\u4EC5\u5728\u8FD9\u91CC\u5C55\u793A\u8BB0\u5FC6\u5904\u7406\u7684\u5DE5\u7A0B\u72B6\u6001")),h("div",{className:"sg-pipeline"},[["Block \u6570\u91CF",selected.blocks],["\u5F85\u5904\u7406\u4EFB\u52A1",processing],["\u5931\u8D25\u4EFB\u52A1",selected.failedJobs],["\u6700\u8FD1\u6574\u7406\u65F6\u95F4",formatTime(selected.lastActivityAt)],["Event \u63D0\u53D6",selected.failedJobDetails?.some(item=>item.kind==="event-extraction")?"\u6709\u5931\u8D25":"\u6B63\u5E38"],["\u56FE\u8C31\u6295\u5F71",selected.failedJobDetails?.some(item=>item.kind==="graph-projection")?"\u6709\u5931\u8D25":"\u6B63\u5E38"]].map(([label,value])=>h("div",{key:label,className:"sg-stage"},h("span",null,label),h("span",{className:"sg-stage-value "+(label==="\u5931\u8D25\u4EFB\u52A1"&&value?"failed":"waiting")},String(value))))),repair?h("p",{className:"sg-setting-note",role:"status"},"\u5386\u53F2\u91CD\u590D\u8BB0\u5FC6\u6574\u7406"+(repair.status==="completed"?"\u5DF2\u5B8C\u6210":"\u8FDB\u884C\u4E2D")+"\uFF1A\u5DF2\u626B\u63CF "+repair.scannedEvents+" \u5F20\u5361\uFF0C\u5F52\u6863\u91CD\u590D\u5361 "+repair.merged+" \u5F20\uFF1B\u5176\u4F59\u4FDD\u7559\u3002"+(repair.failed?" \u90E8\u5206\u5224\u65AD\u672A\u5B8C\u6210\uFF0C\u539F\u5361\u5DF2\u4FDD\u7559\u3002":"")):null,h("button",{type:"button",className:"sg-quiet-button",onClick:onDuplicates},"\u67E5\u770B\u91CD\u590D\u5019\u9009\u4E0E\u5904\u7406\u539F\u56E0"),h("button",{type:"button",className:"sg-quiet-button",disabled:refreshing,onClick:()=>{checkStatus()},style:{marginTop:"14px"}},refreshing?"\u21BB \u6B63\u5728\u8BFB\u53D6\u2026":"\u21BB \u91CD\u65B0\u68C0\u67E5"),feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null)}function AuditPage({audit,auditPage,namespace,onBack,backLabel="\u66F4\u591A"}){let pagedAudit=usePagedMemory({namespace,kind:"audit",initialItems:audit,initialPage:auditPage,fallbackLimit:100});return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u4F7F\u7528\u8BB0\u5F55"),h("p",null,"\u957F\u671F\u8BB0\u5FC6\u88AB\u4F7F\u7528\u7684\u65F6\u95F4\u4E0E\u6765\u6E90")),pagedAudit.items.length?pagedAudit.items.map(item=>{let value=item.audit||{};return h("details",{key:item.id,className:"sg-audit"},h("summary",null,h("strong",null,"\u4F7F\u7528\u4E86 "+((item.events||[]).length+(item.elements||[]).length)+" \u6761\u8BB0\u5FC6"),h("span",{className:"sg-muted"}," \xB7 "+formatTime(item.createdAt))),h("div",{className:"sg-audit-body"},h("div",null,(item.events||[]).map(event3=>event3.title).join("\u3001")||(item.elements||[]).map(element3=>element3.name).join("\u3001")||"\u65E7\u7248\u4F7F\u7528\u8BB0\u5F55"),h("div",{className:"sg-tech-row sg-audit-evidence"},h("span",{className:"sg-muted"},"\u6765\u6E90\u4F1A\u8BDD"),h("span",{className:"sg-code"},value.sessionId||"\u672A\u8BB0\u5F55")),value.turn!==void 0?h("div",{className:"sg-tech-row"},h("span",{className:"sg-muted"},"Turn"),h("span",null,value.turn)):null))}):h(Empty,{title:"\u8FD8\u6CA1\u6709\u4F7F\u7528\u8BB0\u5F55",copy:"AI \u5728\u56DE\u7B54\u4E2D\u91C7\u7528\u957F\u671F\u8BB0\u5FC6\u540E\u4F1A\u8BB0\u5F55\u5728\u8FD9\u91CC\u3002"}),h(Pagination,{page:pagedAudit.page,loading:pagedAudit.loading,error:pagedAudit.error,onOffset:pagedAudit.loadOffset}))}function RawPage({data:data4,selected,onBack,backLabel="\u66F4\u591A"}){let groups=[["Block raw",data4.blocks,data4.pagination?.blocks?.total],["Event raw",data4.events,data4.pagination?.events?.total],["Graph raw",data4.graph],["Usage raw",data4.audit,data4.pagination?.audit?.total],["\u6A21\u578B\u54CD\u5E94",selected.successfulModelResponses||[]]];return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u539F\u59CB\u6570\u636E"),h("p",null,"\u4F9B\u6392\u67E5\u95EE\u9898\u4F7F\u7528\u7684\u5185\u90E8\u5B57\u6BB5\u4E0E JSON")),groups.map(([label,value,total])=>h("details",{key:label,className:"sg-raw-group"},h("summary",null,label+" ("+(Array.isArray(value)&&Number(total)>value.length?"\u5DF2\u52A0\u8F7D "+value.length+" / \u5171 "+total:Array.isArray(value)?value.length:(value.nodes?.length||0)+(value.edges?.length||0))+")"),h("pre",{className:"sg-raw-json sg-code"},JSON.stringify(value,null,2)))))}let profileGroups=[["\u79F0\u547C\u4E0E\u8BED\u8A00",[["userPreferredName","\u600E\u4E48\u79F0\u547C\u4F60",100],["assistantPreferredName","\u52A9\u624B\u53EB\u4EC0\u4E48",100],["preferredLanguage","\u56DE\u7B54\u7528\u4EC0\u4E48\u8BED\u8A00",100],["reasoningLanguage","\u601D\u8003\u8FC7\u7A0B\u7528\u4EC0\u4E48\u8BED\u8A00",100]]],["\u5730\u70B9",[["defaultLocation","\u5E38\u9A7B\u5730\u5740",200],["currentCity","\u73B0\u5728\u5728\u54EA",100],["homeCity","\u5E38\u9A7B\u57CE\u5E02\uFF08\u539F\u6709\u5B57\u6BB5\uFF09",100]]],["\u600E\u4E48\u56DE\u7B54\u4F60",[["responsePreferences","\u56DE\u590D\u65B9\u5F0F",1e3],["standingInstructions","\u4E00\u76F4\u8981\u9075\u5B88\u7684\u8981\u6C42",1e3]]],["\u5173\u4E8E\u4F60",[["userBackground","\u80CC\u666F",1500],["longTermGoals","\u957F\u671F\u76EE\u6807",1e3]]],["\u5176\u4ED6",[["persistentNotes","\u5176\u4ED6\u8981\u4E00\u76F4\u8BB0\u4F4F\u7684",1200]]]],PROFILE_EMPTY_HINTS={userPreferredName:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5C0F\u7A0B",assistantPreferredName:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u6A59\u5B50",preferredLanguage:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E2D\u6587",reasoningLanguage:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E2D\u6587",responsePreferences:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5148\u7ED9\u7ED3\u8BBA\uFF0C\u518D\u5C55\u5F00",standingInstructions:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u6539\u4EE3\u7801\u524D\u5148\u8BF4\u65B9\u6848",defaultLocation:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5317\u4EAC\u5E02\u6D77\u6DC0\u533A",currentCity:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E0A\u6D77",homeCity:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u676D\u5DDE",userBackground:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u8F6F\u4EF6\u5DE5\u7A0B\u5E08\uFF0C\u719F\u6089 Python",longTermGoals:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4ECA\u5E74\u5B8C\u6210\u4E00\u7BC7\u8BBA\u6587",persistentNotes:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u9879\u76EE\u7EDF\u4E00\u4F7F\u7528 pnpm"},profileFieldNames=profileGroups.flatMap(([,fields])=>fields.map(([field])=>field)),PROFILE_LIMIT_DEFAULT=6e3,PROFILE_LIMIT_MIN=2e3,PROFILE_LIMIT_MAX=12e3,profileTotalLimit=value=>{let candidate=Number(value?._limits?.totalMaxLength);return Number.isSafeInteger(candidate)&&candidate>0?candidate:PROFILE_LIMIT_DEFAULT},profileTotalLength=value=>profileFieldNames.reduce((sum,field)=>sum+Array.from(value?.[field]||"").length,0),profileRightColumn=new Set(["\u600E\u4E48\u56DE\u7B54\u4F60","\u5173\u4E8E\u4F60","\u5176\u4ED6"]),formatCount=value=>Number(value||0).toLocaleString("en-US");function sameProfile(left,right){return profileFieldNames.every(field=>left?.[field]===right?.[field]&&left?._revisions?.[field]===right?._revisions?.[field])&&profileTotalLimit(left)===profileTotalLimit(right)}function ProfilePage(){let[profile,setProfile]=usePageMemoryState(profilePageMemory,"profile",null),[editing,updateEditing]=usePageMemoryState(profilePageMemory,"editing",null),setEditing=update2=>{let previous=profilePageMemory.get("editing"),next2=typeof update2=="function"?update2(previous):update2;next2?profileFieldDrafts.set(next2.field,next2):previous&&profileFieldDrafts.delete(previous.field),updateEditing(next2)},[saving,setSaving]=React.useState(!1),[syncStatus,setSyncStatus]=React.useState("\u66F4\u65B0\u4E2D\u2026"),[error3,setError]=React.useState(""),[conflicts,setConflicts]=usePageMemoryState(profilePageMemory,"conflicts",{}),conflict=!!conflicts[editing?.field],setConflict=(value,field=profilePageMemory.get("editing")?.field)=>{field&&setConflicts(current=>({...current,[field]:value}))},[saveResults,setSaveResults]=usePageMemoryState(profilePageMemory,"saveResults",{}),[reading,setReading]=React.useState(!1),session=React.useRef(0),action=React.useRef(null),actionTimeout=React.useRef(null),readController=React.useRef(null),savedTimers=React.useRef(new Map),requestVersion=React.useRef(0),refreshRef=React.useRef(null),clearSavedTimer=field=>{window.clearTimeout(savedTimers.current.get(field)),savedTimers.current.delete(field)},showSaved=submission=>{clearSavedTimer(submission.field),setSaveResults(current=>({...current,[submission.field]:{kind:"saved",submission,flash:!0}}));let timer=window.setTimeout(()=>{savedTimers.current.get(submission.field)===timer&&(savedTimers.current.delete(submission.field),setSaveResults(current=>current[submission.field]?.submission===submission?{...current,[submission.field]:{...current[submission.field],flash:!1}}:current))},2e3);savedTimers.current.set(submission.field,timer)};React.useEffect(()=>{let active=!0,timer=null,controller=null,stopRequest=()=>{controller&&controller.abort(),controller=null,readController.current=null},check=({valid:valid2=()=>!0,onResult}={})=>{if(!active||document.hidden)return;if(timer!==null&&window.clearTimeout(timer),timer=null,stopRequest(),action.current){timer=window.setTimeout(check,5e3);return}let version2=++requestVersion.current,requestController=new AbortController;return controller=requestController,readController.current=requestController,api2("profile",{},{method:"GET",signal:requestController.signal}).then(latest=>{if(!(!active||document.hidden||version2!==requestVersion.current||!valid2())){if(!profileFieldNames.every(field=>typeof latest?.[field]=="string")||!latest?._revisions)throw new Error("\u753B\u50CF\u8BFB\u53D6\u54CD\u5E94\u4E0D\u5B8C\u6574");setProfile(current=>sameProfile(current,latest)?current:latest),setSyncStatus("\u5DF2\u662F\u6700\u65B0"),setError(""),onResult?.(latest)}}).catch(reason=>{active&&version2===requestVersion.current&&valid2()&&reason?.name!=="AbortError"&&(setSyncStatus("\u8BFB\u53D6\u5931\u8D25"),setError(String(reason?.message||reason)))}).finally(()=>{controller===requestController&&(controller=null,readController.current=null),active&&!document.hidden&&version2===requestVersion.current&&(timer=window.setTimeout(check,5e3))})};refreshRef.current=check;let onVisibilityChange=()=>{timer!==null&&window.clearTimeout(timer),timer=null,document.hidden?(++requestVersion.current,stopRequest()):check()};return document.addEventListener("visibilitychange",onVisibilityChange),check(),()=>{let submission=action.current?.submission;submission&&!profilePageMemory.get("saveResults")?.[submission.field]&&setSaveResults(current=>({...current,[submission.field]:{kind:"unknown",submission}})),active=!1,++session.current,++requestVersion.current,refreshRef.current=null,timer!==null&&window.clearTimeout(timer),stopRequest(),action.current?.abort(),action.current=null,window.clearTimeout(actionTimeout.current),actionTimeout.current=null,savedTimers.current.forEach(id2=>window.clearTimeout(id2)),savedTimers.current.clear(),setSaveResults(current=>Object.fromEntries(Object.entries(current).map(([field,result])=>[field,result.kind==="saved"?{...result,flash:!1}:result]))),document.removeEventListener("visibilitychange",onVisibilityChange)}},[]);let resetEdit=field=>{++session.current,++requestVersion.current,readController.current?.abort(),setReading(!1),field&&(setConflict(!1,field),clearSavedTimer(field),setSaveResults(current=>{let next2={...current};return delete next2[field],next2})),refreshRef.current?.()},beginEdit=field=>{resetEdit(profileFieldDrafts.has(field)?void 0:field),setEditing(profileFieldDrafts.get(field)||{field,draft:profile[field]||"",baseValue:profile[field]||"",baseRevision:profile._revisions?.[field]||0})},reloadField=()=>{if(!editing||saving||reading)return;let id2=session.current;setReading(!0),refreshRef.current?.({valid:()=>session.current===id2,onResult:latest=>{setEditing(current=>current?{...current,draft:latest[current.field],baseValue:latest[current.field],baseRevision:latest._revisions[current.field]}:null),setConflict(!1),setSaveResults(current=>{let next2={...current};return delete next2[editing.field],next2})}})?.finally(()=>{session.current===id2&&setReading(!1)})},save=()=>{if(!editing||action.current||saving||reading||saveResults[editing.field]?.kind==="unknown")return;if(conflict||profile[editing.field]!==editing.baseValue||profile._revisions?.[editing.field]!==editing.baseRevision){setConflict(!0);return}let submission={...editing},id2=session.current,controller=new AbortController;controller.submission=submission,action.current=controller;let valid2=()=>session.current===id2&&action.current===controller;setSaving(!0),setSaveResults(current=>{let next2={...current};return delete next2[submission.field],next2}),++requestVersion.current,readController.current?.abort();let timeout=window.setTimeout(()=>controller.abort(),15e3);actionTimeout.current=timeout,api2("profile",{},{method:"PATCH",signal:controller.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({field:submission.field,value:submission.draft,expectedValue:submission.baseValue,expectedRevision:submission.baseRevision})}).then(result=>{if(valid2()){if(!profileFieldNames.every(field=>typeof result?.snapshot?.[field]=="string")||!Number.isSafeInteger(result.snapshot?._revisions?.[submission.field]))throw new Error("\u753B\u50CF\u4FDD\u5B58\u54CD\u5E94\u4E0D\u5B8C\u6574");setProfile(result.snapshot),setEditing(null),setConflict(!1,submission.field),showSaved(submission)}}).catch(reason=>{if(!valid2())return;let message=String(reason?.message||reason);if(reason?.status===409||message.includes("\u521A\u521A\u5728\u5176\u4ED6\u4F4D\u7F6E\u66F4\u65B0")){setConflict(!0);return}let unknown=!reason?.status||[408,502,504].includes(reason.status),invalid=[400,413,422].includes(reason?.status),maximum=profileGroups.flatMap(([,fields])=>fields).find(([field])=>field===submission.field)?.[2],detail=/Persistent Profile exceeds/.test(message)?"\u753B\u50CF\u603B\u5B57\u7B26\u6570\u4E0D\u80FD\u8D85\u8FC7 6000\uFF0C\u8BF7\u7F29\u77ED\u5185\u5BB9\u3002":/exceeds \d+ characters/.test(message)?"\u6B64\u5B57\u6BB5\u4E0D\u80FD\u8D85\u8FC7 "+maximum+" \u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED\u5185\u5BB9\u3002":message;setSaveResults(current=>({...current,[submission.field]:{kind:unknown?"unknown":invalid?"invalid":"failed",submission,detail}}))}).finally(()=>{window.clearTimeout(timeout),actionTimeout.current===timeout&&(actionTimeout.current=null),valid2()&&(action.current=null,setSaving(!1),refreshRef.current?.())})},checkSave=result=>{if(reading||action.current)return;let id2=session.current,{submission}=result;setReading(!0),refreshRef.current?.({valid:()=>session.current===id2,onResult:latest=>{latest[submission.field]===submission.draft&&Number.isSafeInteger(latest._revisions[submission.field])&&latest._revisions[submission.field]>submission.baseRevision&&(showSaved(submission),setEditing(current=>current?.field===submission.field?current.draft===submission.draft?null:{...current,baseValue:latest[submission.field],baseRevision:latest._revisions[submission.field]}:current),setConflict(!1,submission.field))}})?.finally(()=>{session.current===id2&&setReading(!1)})},total=profileTotalLength(profile),limit2=profileTotalLimit(profile);return h(React.Fragment,null,h("div",{className:"sg-pg-head"},h("h2",null,"\u5E38\u9A7B\u753B\u50CF"),h("span",{className:"sg-pg-tag"},h("i",{className:"sg-sw ink","aria-hidden":"true"}),"\u6BCF\u8F6E\u90FD\u5E26\u7ED9 AI \xB7 \u70B9\u4EFB\u610F\u4E00\u884C\u4FEE\u6539"),syncStatus==="\u8BFB\u53D6\u5931\u8D25"?h("span",{className:"sg-pg-end"},h("span",{className:"sg-profile-sync failed",role:"alert"},syncStatus)):null),error3?h("p",{className:"sg-profile-error",role:"alert"},error3):null,profile?h(React.Fragment,null,h("div",{className:"sg-cap-row"},h("div",{className:"sg-cap-bar",role:"img","aria-label":"\u5E38\u9A7B\u753B\u50CF\u5DF2\u7528 "+total+" \u5B57\uFF0C\u4E0A\u9650 "+formatCount(limit2)+" \u5B57"},h("i",{style:{width:Math.min(100,total/limit2*100)+"%"}})),h("span",{className:"sg-cap-num"},h("b",null,formatCount(total)),"/ "+formatCount(limit2)+" \u5B57")),h("div",{className:"sg-pf"},[["1",profileGroups.filter(([title])=>!profileRightColumn.has(title))],["2",profileGroups.filter(([title])=>profileRightColumn.has(title))]].map(([column,groups])=>h("div",{key:column,className:"sg-pf-col","data-pf-stack":column},groups.map(([title,fields])=>h("section",{key:title,className:"sg-profile-group","aria-label":title},h("h4",null,title),h("ul",null,fields.filter(([field])=>field!=="homeCity"||profile.homeCity||profileFieldDrafts.has(field)).map(([field,label,maximum])=>{let value=profile[field]||"",isEditing=editing?.field===field,changedElsewhere=isEditing&&(value!==editing.baseValue||profile._revisions?.[field]!==editing.baseRevision),draftLength=isEditing?Array.from(editing.draft).length:0,nextTotal=total-Array.from(value).length+draftLength,result=saveResults[field],savedReadError=result?.kind==="saved"&&!!error3,savedFeedback=result?.kind==="saved"&&result.flash?h("span",{className:"sg-profile-saved",role:"status"},isEditing&&editing.draft!==result.submission.draft?"\u4E0A\u6B21\u63D0\u4EA4\u5DF2\u4FDD\u5B58":"\u5DF2\u4FDD\u5B58"):null,editor=isEditing?h("div",{className:"sg-profile-editor"},field==="userPreferredName"||field==="assistantPreferredName"||field==="preferredLanguage"||field==="reasoningLanguage"||field==="defaultLocation"||field==="homeCity"||field==="currentCity"?h("input",{id:"sg-profile-"+field,"aria-label":label,autoFocus:!0,disabled:saving,value:editing.draft,onChange:event3=>setEditing(current=>({...current,draft:event3.target.value}))}):h("textarea",{id:"sg-profile-"+field,"aria-label":label,autoFocus:!0,disabled:saving,value:editing.draft,onChange:event3=>setEditing(current=>({...current,draft:event3.target.value}))}),changedElsewhere||conflict?h("p",{className:"sg-profile-conflict",role:"alert"},"\u8BE5\u9879\u521A\u521A\u5728\u5176\u4ED6\u4F4D\u7F6E\u66F4\u65B0\u3002",h("button",{type:"button",className:"sg-profile-action",disabled:saving||reading,onClick:reloadField},"\u653E\u5F03\u8349\u7A3F\u5E76\u8F7D\u5165\u6700\u65B0\u5185\u5BB9")):null,result&&["failed","invalid","unknown"].includes(result.kind)?h("div",{className:"sg-profile-save-feedback sg-profile-save-feedback-"+result.kind,role:result.kind==="unknown"?"status":"alert"},h("p",null,result.kind==="unknown"?"\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u662F\u5426\u5DF2\u4FDD\u5B58\uFF0C\u8F93\u5165\u5185\u5BB9\u5DF2\u4FDD\u7559\u3002":"\u4FEE\u6539\u672A\u4FDD\u5B58\uFF0C\u8F93\u5165\u5185\u5BB9\u5DF2\u4FDD\u7559\u3002"),result.kind==="unknown"?h("button",{type:"button",className:"sg-profile-action",disabled:reading,onClick:()=>checkSave(result)},reading?"\u68C0\u67E5\u4E2D\u2026":"\u68C0\u67E5\u4FDD\u5B58\u7ED3\u679C"):result.kind==="invalid"?h("p",null,result.detail):null):null,h("div",{className:"sg-profile-editor-foot"},h("span",{className:"sg-profile-count"},formatCount(draftLength)+" / "+formatCount(maximum),draftLength>maximum?"\uFF0C\u8BF7\u7F29\u77ED\u81F3 "+formatCount(maximum)+" \u4E2A\u5B57\u7B26\u4EE5\u5185\u3002":nextTotal>limit2?"\uFF0C\u753B\u50CF\u603B\u5B57\u7B26\u6570\u4E0D\u80FD\u8D85\u8FC7 "+formatCount(limit2)+"\u3002":"",savedFeedback),h("div",{className:"sg-profile-actions"},h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:()=>{resetEdit(field),setEditing(null)}},"\u53D6\u6D88\u7F16\u8F91"),h("button",{type:"button",className:"sg-save-button",disabled:saving||reading||result?.kind==="unknown"||draftLength>maximum||nextTotal>limit2||editing.draft===editing.baseValue||changedElsewhere||conflict,onClick:save},saving?"\u4FDD\u5B58\u4E2D\u2026":result?.kind==="failed"?"\u91CD\u65B0\u4FDD\u5B58":"\u4FDD\u5B58")))):null;return h("li",{key:field,className:"sg-profile-row",onClick:isEditing?void 0:()=>{saving||beginEdit(field)}},h("div",{className:"sg-profile-summary"+(isEditing?" editing":"")},h("div",{className:"sg-profile-label-cell"},h("span",{className:"sg-profile-label"},label),editor||h("span",{className:"sg-profile-content"},h("button",{type:"button",className:"sg-profile-value "+(value?"":"empty"),title:value||PROFILE_EMPTY_HINTS[field],"aria-label":label+(value?"\uFF0C\u70B9\u51FB\u7F16\u8F91":"\uFF0C\u672A\u586B\u5199\uFF0C\u70B9\u51FB\u586B\u5199"),disabled:saving,onClick:event3=>{event3?.stopPropagation?.(),beginEdit(field)}},profileFieldDrafts.has(field)?"\u7EE7\u7EED\u7F16\u8F91\u8349\u7A3F":value||"\u672A\u586B\u5199"),savedFeedback)),isEditing?null:h("span",{className:"sg-profile-chev","aria-hidden":"true"},"\u203A"),h("button",{type:"button",className:"sg-profile-action",onClick:event3=>{event3?.stopPropagation?.(),beginEdit(field)},disabled:saving,"aria-hidden":isEditing||void 0},!isEditing&&profileFieldDrafts.has(field)?"\u7EE7\u7EED\u7F16\u8F91":value?"\u7F16\u8F91":"\u6DFB\u52A0")),savedReadError?h("p",{className:"sg-profile-save-feedback",role:"status"},h("span",null,"\u4FEE\u6539\u5DF2\u4FDD\u5B58\uFF0C\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6700\u65B0\u5185\u5BB9\u3002"),h("button",{type:"button",className:"sg-profile-action",disabled:reading,onClick:()=>refreshRef.current?.()},"\u91CD\u65B0\u8BFB\u53D6")):null)})))))))):h("p",null,"\u6B63\u5728\u8BFB\u53D6\u5E38\u9A7B\u753B\u50CF\u2026"))}let GRAPH_EXPLANATION="\u7531\u4E8E\u77E5\u8BC6\u56FE\u8C31\u529F\u80FD\u4E0E\u4E8B\u4EF6\u8BB0\u5F55\u548C\u4E3B\u9898\u76EE\u5F55\u6709\u90E8\u5206\u91CD\u590D\uFF0C\u8FD8\u9700\u8981\u989D\u5916\u6D88\u8017token\u7EF4\u62A4\u5B9E\u4F53\u5173\u7CFB\uFF0C\u5C06\u4F1A\u9ED8\u8BA4\u5173\u95ED\u77E5\u8BC6\u56FE\u8C31\u529F\u80FD\uFF0C\u5DF2\u7ECF\u751F\u6210\u7684\u56FE\u8C31\u6570\u636E\u4F1A\u4FDD\u7559\u3002",GRAPH_USAGE_HINT="\u63D0\u793A\uFF1A\u5982\u9700\u4F7F\u7528\uFF0C\u53EF\u4EE5\u5728\u957F\u671F\u8BB0\u5FC6\u9875\u9762\u70B9\u51FB\u201C\uFF0B\u201D\uFF0C\u6253\u5F00\u77E5\u8BC6\u56FE\u8C31\uFF0C\u529F\u80FD\u53EF\u4EE5\u6B63\u5E38\u4F7F\u7528\u3002",GRAPH_CONTROL_STYLES=".sg-graph-no-reminder{display:inline-flex;align-items:center;min-height:30px;padding:5px 8px;border:1px solid var(--sg-border);border-radius:6px;background:var(--sg-surface);color:var(--sg-muted);cursor:pointer}.sg-graph-no-reminder:hover{border-color:var(--sg-accent);color:var(--sg-accent);background:var(--sg-soft)}.sg-graph-no-reminder:disabled{cursor:not-allowed;opacity:.5}.sg-graph-notice-toggle{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:9px 0;border-top:1px solid var(--sg-border);border-bottom:1px solid var(--sg-border)}.sg-graph-notice-toggle>span{font-size:13px;font-weight:650}.sg-graph-menu{position:relative;z-index:31;display:inline-flex;align-items:center}.sg-long-tabs .sg-graph-menu-trigger{display:grid;place-items:center;align-self:center;flex:none;box-sizing:border-box;width:32px;height:32px;min-width:32px;min-height:32px;padding:0;border:0;border-radius:999px;background:transparent;color:var(--sg-muted);font-size:22px;line-height:1;cursor:pointer}.sg-graph-menu-trigger svg{display:block;width:16px;height:16px;flex:none}.sg-graph-menu-trigger:hover,.sg-graph-menu-trigger[aria-expanded=true]{background:var(--sg-soft);color:var(--sg-accent)}.sg-graph-menu-popover{position:absolute;z-index:32;right:0;left:auto;top:calc(100% + 8px);width:min(300px,calc(100vw - 32px));padding:10px;border:1px solid var(--sg-border);border-radius:10px;background:var(--sg-page);box-shadow:var(--sg-shadow);text-align:left}.sg-graph-menu-title{display:block;padding:0 2px 8px;color:var(--sg-text);font-size:13px;font-weight:650;line-height:1.4}.sg-graph-open{display:block;width:100%;margin-top:8px;padding:6px 2px 2px;border:0;border-top:1px solid var(--sg-border);background:none;color:var(--sg-text);font-size:12.5px;text-align:left;cursor:pointer}.sg-graph-open:hover{color:var(--sg-accent)}.sg-graph-copy{display:block;min-width:0}.sg-graph-title-row{display:flex;align-items:center;gap:6px;min-width:0}.sg-graph-copy b{display:block;font-size:13.5px;font-weight:650;color:var(--sg-text)}.sg-graph-copy span{display:block;margin-top:2px;font-size:11.5px;line-height:1.45;color:var(--sg-muted)}.sg-graph-title-row .sg-info-disclosure{display:inline-flex;flex:none} .sg-graph-copy .sg-graph-title-row{display:flex}.sg-graph-title-row .sg-info-trigger{width:18px;height:18px;font-size:12px}.sg-graph-menu-popover .sg-storage-card{padding:0;border:0;background:transparent}.sg-graph-menu-popover .sg-setting-note{font-size:11px;line-height:1.5}.sg-graph-dialog-heading{display:flex;align-items:center;justify-content:space-between;gap:12px}.sg-graph-dialog-heading h3{margin:0}.sg-graph-dialog-control{display:flex;align-items:center;gap:7px;color:var(--sg-muted);font-size:12px}";function GraphControlPanel({state={},refresh,page=!1,onGraphHidden,onOpenGraph}){let shouldShowNotice=!page&&state.enabled!==!0&&state.noticeSeen!==!0,[notice,setNotice]=React.useState(shouldShowNotice),[preview,setPreview]=React.useState(null),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState(""),[hideExplanation,setHideExplanation]=React.useState(!1),dialogRef=React.useRef(null);React.useEffect(()=>{setNotice(!page&&state.enabled!==!0&&state.noticeSeen!==!0)},[page,state.enabled,state.noticeSeen]),React.useEffect(()=>{if(!notice&&!preview)return;let previous=document.activeElement;return dialogRef.current?.querySelector("button")?.focus(),()=>{previous?.isConnected&&previous.focus?.()}},[notice,preview]);let control=async(action,token)=>{setBusy(!0),setError("");try{let result=await api2("graph/control",{action,...token?{token}:{}},{method:"POST"});action==="preview"?result.pending>0?setPreview(result):(await api2("graph/control",{action:"enable",token:result.token},{method:"POST"}),await refresh?.()):(setPreview(null),action==="notice"&&(setNotice(!1),setHideExplanation(!0),onGraphHidden?.()),await refresh?.())}catch(reason){setError(String(reason?.message||reason))}finally{setBusy(!1)}},graphStatus=state.enabled===!0?state.paused?"\u5DF2\u6682\u505C\u66F4\u65B0\uFF0C\u53EF\u67E5\u770B\u65E7\u56FE\u8C31":"\u5DF2\u5F00\u542F":"\u9ED8\u8BA4\u5173\u95ED\uFF0C\u6253\u5F00\u540E\u53EF\u67E5\u770B\u5DF2\u6709\u56FE\u8C31",graphInfo=page?null:h(InfoPopover,{label:"\u77E5\u8BC6\u56FE\u8C31\u8BF4\u660E"},h("p",null,GRAPH_EXPLANATION),h("p",null,GRAPH_USAGE_HINT)),showExplanation=!hideExplanation&&(!page||state.noticeSeen!==!0);return h(React.Fragment,null,h("style",null,GRAPH_CONTROL_STYLES),h("aside",{className:"sg-storage-card sg-graph-control"+(page?" sg-graph-page-control":""),"aria-label":page?"\u77E5\u8BC6\u56FE\u8C31\u5F00\u5173":void 0},h("div",{className:"sg-stage"},h("span",{className:"sg-graph-copy"},h("span",{className:"sg-graph-title-row"},h("b",null,page?"\u663E\u793A\u77E5\u8BC6\u56FE\u8C31":"\u542F\u7528\u77E5\u8BC6\u56FE\u8C31"),graphInfo),page?h("span",null,graphStatus):null),h("span",{className:"sg-lambda-control sg-graph-toggle"},!page&&showExplanation?h("button",{type:"button",className:"sg-icon-button","aria-label":"\u4E0D\u518D\u63D0\u9192",title:"\u4E0D\u518D\u63D0\u9192",disabled:busy,onClick:()=>{control("notice")}},"\xD7"):null,h("button",{type:"button",role:"switch","aria-label":"\u663E\u793A\u77E5\u8BC6\u56FE\u8C31","aria-checked":state.enabled===!0,disabled:busy,className:"sg-setting-switch",onClick:()=>{control(state.enabled?"disable":"preview")}}))),page&&state.enabled===!0?h("button",{type:"button",className:"sg-graph-open",onClick:()=>onOpenGraph?.()},"\u6253\u5F00\u77E5\u8BC6\u56FE\u8C31 \u2192"):null,!page&&state.enabled?h("button",{type:"button",className:"sg-storage-button",disabled:busy,onClick:()=>{control(state.paused?"preview":"pause")}},state.paused?"\u7EDF\u8BA1\u5E76\u7EE7\u7EED\u56FE\u8C31\u4EFB\u52A1":"\u6682\u505C\u56FE\u8C31\u4EFB\u52A1"):null,error3?h("p",{role:"alert",className:"sg-error-note"},error3):null,notice||preview?h("div",{className:"sg-import-overlay"},h("section",{ref:dialogRef,role:"dialog","aria-modal":"true","aria-label":notice?"\u77E5\u8BC6\u56FE\u8C31\u9ED8\u8BA4\u5173\u95ED\u8BF4\u660E":"\u786E\u8BA4\u6062\u590D\u77E5\u8BC6\u56FE\u8C31",className:"sg-import-dialog",onKeyDown:event3=>{if(event3.key==="Escape"&&preview&&!notice&&!busy&&(event3.preventDefault(),setPreview(null)),event3.key==="Tab"){let buttons=[...dialogRef.current.querySelectorAll("button:not(:disabled)")];if(!buttons.length){event3.preventDefault();return}let first2=buttons[0],last2=buttons.at(-1);event3.shiftKey&&document.activeElement===first2?(event3.preventDefault(),last2.focus()):!event3.shiftKey&&document.activeElement===last2&&(event3.preventDefault(),first2.focus())}}},h("div",{className:"sg-graph-dialog-heading"},h("h3",null,notice?"\u77E5\u8BC6\u56FE\u8C31\u9ED8\u8BA4\u5173\u95ED":"\u786E\u8BA4\u6062\u590D\u77E5\u8BC6\u56FE\u8C31"),notice?h("span",{className:"sg-graph-dialog-control"},h("span",null,"\u5F00\u542F"),h("button",{type:"button",role:"switch","aria-label":"\u542F\u7528\u77E5\u8BC6\u56FE\u8C31","aria-checked":state.enabled===!0,disabled:busy,className:"sg-setting-switch",onClick:()=>{control("preview")}})):null),h("p",null,GRAPH_EXPLANATION),h("p",null,GRAPH_USAGE_HINT),preview&&!notice?h("p",null,"\u5F53\u524D\u6709 "+preview.pending+" \u6761\u5F85\u5904\u7406\u4E8B\u4EF6\uFF0C\u7EA6 "+preview.batches+" \u4E2A\u6279\u6B21\u3002\u786E\u8BA4\u540E\u4EC5\u8865\u5EFA\u8FD9\u4EFD\u6E05\u5355\uFF0C\u6CBF\u7528\u73B0\u6709\u79DF\u7EA6\u3001\u5E76\u53D1\u548C\u91CD\u8BD5\u9650\u989D\uFF1B\u53EF\u968F\u65F6\u6682\u505C\u3002"):null,notice&&!preview?h("button",{type:"button",className:"sg-graph-no-reminder",disabled:busy,onClick:()=>{control("notice")}},"\u6682\u65F6\u5173\u95ED"):!notice&&preview?h(React.Fragment,null,h("button",{type:"button",disabled:busy,onClick:()=>setPreview(null)},"\u53D6\u6D88"),h("button",{type:"button",disabled:busy,onClick:()=>{control("enable",preview.token)}},"\u786E\u8BA4\u5F00\u542F\u5E76\u5206\u6279\u5904\u7406")):null,!notice&&!preview?h("button",{type:"button",className:"sg-graph-no-reminder",disabled:busy,onClick:()=>{control("notice")}},"\u6682\u65F6\u5173\u95ED"):null)):null))}function GraphSettingsPanel({state={},refresh}){return h(GraphControlPanel,{state,refresh})}function DailyNotesSettings({usePluginSettings,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[saving,setSaving]=React.useState(!1),[error3,setError]=React.useState(""),localTimeZone=Intl.DateTimeFormat().resolvedOptions().timeZone,timeZone=settings?.value?.dailyNotesTimeZone||"",enabled=settings?.value?.dailyNotesEnabled!==!1,injectionDays=settings?.value?.dailyNotesInjectionDays??3,zones=[...new Set(["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Asia/Kolkata","Europe/London","Europe/Berlin","America/New_York","America/Los_Angeles","Australia/Sydney","UTC",timeZone].filter(Boolean))],save=async(setter,value)=>{setSaving(!0),setError("");try{(!setter||!await setter(value))&&setError("\u672A\u80FD\u4FDD\u5B58\u7B14\u8BB0\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u8BD5\u3002")}catch(reason){setError("\u4FDD\u5B58\u5931\u8D25\uFF1A"+String(reason.message||reason))}finally{setSaving(!1)}},disabled=settings?.writable!==!0||saving;return h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u77ED\u671F\u8BB0\u5FC6"),h("span",{className:"sg-display-setting-description"},"\u6BCF\u5929\u4E00\u4EFD\u5DE5\u4F5C\u7B14\u8BB0\u3002\u5173\u95ED\u540E\u4E0D\u518D\u5199\u5165\u548C\u6CE8\u5165\uFF0C\u5DF2\u6709\u7B14\u8BB0\u4FDD\u7559\u3002")),h("button",{type:"button",className:"sg-setting-switch",role:"switch","aria-label":"\u77ED\u671F\u8BB0\u5FC6","aria-checked":enabled,disabled:disabled||!setDailyEnabled,onClick:()=>{save(setDailyEnabled,!enabled)}})),h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570"),h("span",{className:"sg-display-setting-description"},"\u53D6\u6700\u8FD1\u6709\u7B14\u8BB0\u7684\u65E5\u671F\uFF0C\u9ED8\u8BA4 3 \u5929\u3002\u4FEE\u6539\u540E\u7528\u4E8E\u65B0\u4F1A\u8BDD\uFF1B\u5185\u5BB9\u4ECD\u53D7\u957F\u5EA6\u4E0A\u9650\u7EA6\u675F\u3002")),h("select",{className:"sg-effort-select","aria-label":"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570",value:injectionDays,disabled:disabled||!setDailyInjectionDays,onChange:event3=>{save(setDailyInjectionDays,Number(event3.target.value))}},Array.from({length:30},(_,i2)=>h("option",{key:i2+1,value:i2+1},i2+1+" \u5929")))),h("div",{className:"sg-stage"},h("span",null,"\u7B14\u8BB0\u65F6\u533A"),h("select",{className:"sg-effort-select",style:{maxWidth:"100%",minWidth:0},"aria-label":"\u7B14\u8BB0\u65F6\u533A",value:timeZone,disabled:disabled||!setDailyTimeZone,onChange:event3=>{save(setDailyTimeZone,event3.target.value)}},h("option",{value:""},"\u8DDF\u968F\u672C\u673A\uFF08"+localTimeZone+"\uFF09"),zones.map(zone=>h("option",{key:zone,value:zone},zone)))),error3?h("p",{className:"sg-storage-feedback failed",role:"alert"},error3):null)}function ProfileLimitSettings(){let[profile,setProfile]=React.useState(null),[loading,setLoading]=React.useState(!0),[loadError,setLoadError]=React.useState(""),[editing,setEditing]=React.useState(!1),[draft,setDraft]=React.useState(""),[saving,setSaving]=React.useState(!1),[error3,setError]=React.useState(""),total=profileTotalLength(profile),limit2=profileTotalLimit(profile);React.useEffect(()=>{let controller=new AbortController;return api2("profile",{},{method:"GET",signal:controller.signal}).then(value=>{controller.signal.aborted||setProfile(value),setLoadError("")}).catch(reason=>{controller.signal.aborted||setLoadError("\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u753B\u50CF\u7528\u91CF\uFF1A"+String(reason?.message||reason))}).finally(()=>{controller.signal.aborted||setLoading(!1)}),()=>controller.abort()},[]);let begin=()=>{loading||loadError||(setDraft(String(limit2)),setError(""),setEditing(!0))},cancel=()=>{saving||(setEditing(!1),setError(""))},save=async()=>{if(saving)return;let next2=Number(draft);if(!Number.isSafeInteger(next2)||next2<PROFILE_LIMIT_MIN||next2>PROFILE_LIMIT_MAX){setError("\u8BF7\u8F93\u5165 "+formatCount(PROFILE_LIMIT_MIN)+" \u5230 "+formatCount(PROFILE_LIMIT_MAX)+" \u4E4B\u95F4\u7684\u6574\u6570\u3002");return}if(next2<total){setError("\u4E0A\u9650\u4E0D\u80FD\u4F4E\u4E8E\u5F53\u524D\u5DF2\u7528\u7684 "+formatCount(total)+" \u5B57\u3002");return}if(next2===limit2){setEditing(!1);return}setSaving(!0),setError("");try{let result=await api2("settings",null,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileMaxLength:next2})}),saved=Number(result?.profileMaxLength);if(!Number.isSafeInteger(saved)||saved!==next2)throw new Error("\u4E0A\u9650\u4FDD\u5B58\u7ED3\u679C\u4E0D\u5B8C\u6574");setProfile(current=>current&&{...current,_limits:{...current._limits||{},totalMaxLength:next2}}),setEditing(!1)}catch(reason){setError("\u4E0A\u9650\u672A\u4FDD\u5B58\uFF1A"+String(reason?.message||reason))}finally{setSaving(!1)}};return h("div",{className:"sg-settings-panel sg-profile-limit","data-testid":"stratagate-profile-limit-settings"},h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u5E38\u9A7B\u753B\u50CF\u5B57\u6570\u4E0A\u9650"),h("span",{className:"sg-display-setting-description"},"\u9650\u5236\u6BCF\u8F6E\u5E26\u5165\u7684\u5E38\u9A7B\u753B\u50CF\u603B\u91CF\uFF0C\u4E0D\u80FD\u4F4E\u4E8E\u5F53\u524D\u5DF2\u5199\u5185\u5BB9\u3002")),h("span",{className:"sg-profile-limit-control"},loading?h("span",{className:"sg-setting-note"},"\u8BFB\u53D6\u4E2D\u2026"):h(React.Fragment,null,loadError?null:h("span",{className:"sg-profile-limit-value","aria-label":"\u5E38\u9A7B\u753B\u50CF\u5DF2\u7528 "+total+" \u5B57\uFF0C\u4E0A\u9650 "+formatCount(limit2)+" \u5B57"},formatCount(total)+" / "+formatCount(limit2)+" \u5B57"),!loadError&&!editing?h("button",{type:"button",className:"sg-cap-limit",onClick:begin},"\u8C03\u6574\u4E0A\u9650"):null))),editing?h("div",{className:"sg-cap-edit sg-profile-limit-edit"},h("input",{type:"number",inputMode:"numeric",min:PROFILE_LIMIT_MIN,max:PROFILE_LIMIT_MAX,step:100,"aria-label":"\u5E38\u9A7B\u753B\u50CF\u5B57\u6570\u4E0A\u9650",value:draft,disabled:saving,autoFocus:!0,onChange:event3=>setDraft(event3.target.value),onKeyDown:event3=>{event3.key==="Enter"?(event3.preventDefault(),save()):event3.key==="Escape"&&(event3.preventDefault(),cancel())}}),h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:cancel},"\u53D6\u6D88"),h("button",{type:"button",className:"sg-save-button",disabled:saving,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58")):null,loadError?h("p",{className:"sg-storage-feedback failed",role:"alert"},loadError):null,error3?h("p",{className:"sg-cap-error",role:"alert"},error3):null)}function MemoryModelSettings({usePluginSettings,setMemoryModel}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[catalog,setCatalog]=React.useState(null),[draft,setDraft]=React.useState(null),customDraft=React.useRef(null),[models,setModels]=React.useState([]),[loading,setLoading]=React.useState(!1),[catalogError,setCatalogError]=React.useState(""),[modelsError,setModelsError]=React.useState(""),[feedback,setFeedback]=React.useState({kind:"",text:""}),[saving,setSaving]=React.useState(!1),[revision,setRevision]=React.useState(0);React.useEffect(()=>{if(feedback.kind!=="done")return;let timer=window.setTimeout(()=>setFeedback({kind:"",text:""}),4500);return()=>window.clearTimeout(timer)},[feedback]);let saved=settings?.value?.memoryModel||catalog?.selection||{mode:"auto"},value=draft||saved,provider=value.mode==="custom"&&value.provider||"";React.useEffect(()=>{let active=!0;return settings?.value?.memoryModel?.mode==="auto"&&value.mode==="auto"?(setCatalog(null),setCatalogError(""),()=>{active=!1}):(setCatalogError(""),api2("models").then(result=>{active&&setCatalog(result)}).catch(reason=>{active&&setCatalogError(String(reason?.message||reason))}),()=>{active=!1})},[revision,settings?.value?.memoryModel?.mode,value.mode]),React.useEffect(()=>{let active=!0;return setModels([]),setModelsError(""),provider?(setLoading(!0),api2("models",{provider}).then(result=>{active&&setModels(result.models)}).catch(reason=>{active&&setModelsError(String(reason?.message||reason))}).finally(()=>{active&&setLoading(!1)}),()=>{active=!1}):(setLoading(!1),()=>{active=!1})},[provider,revision]);let providers=catalog?.providers||[],custom=value.mode==="custom";React.useEffect(()=>{if(!draft||!custom||provider||!providers[0])return;let next2={...value,provider:providers[0].id};customDraft.current=next2,setDraft(next2)},[providers,custom,provider,draft,value]);let valid2=!custom||providers.some(item=>item.id===provider)&&!!value.model?.trim(),changed=value.mode!==saved.mode||custom&&(value.provider!==saved.provider||value.model!==saved.model),editingDisabled=settings?.writable!==!0||!setMemoryModel||saving,disabled=editingDisabled,edit=next2=>{next2.mode==="custom"&&(customDraft.current=next2),setDraft(next2),setFeedback({kind:"",text:""})},save=async()=>{if(!(disabled||!valid2||!changed)){setSaving(!0),setFeedback({kind:"",text:""});try{if(!await setMemoryModel(value))throw new Error("\u5BBF\u4E3B\u672A\u786E\u8BA4\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002");setCatalog(current=>({...current,selection:value})),setDraft(null),setFeedback({kind:"done",text:"\u5DF2\u4FDD\u5B58\uFF0C\u5BF9\u540E\u7EED\u8BB0\u5FC6\u5904\u7406\u8C03\u7528\u751F\u6548\u3002\u6B63\u5728\u8FD0\u884C\u7684\u8C03\u7528\u7EE7\u7EED\u5B8C\u6210\u3002"})}catch(reason){setFeedback({kind:"failed",text:"\u672A\u80FD\u786E\u8BA4\u4FDD\u5B58\uFF1A"+String(reason?.message||reason)+" \u5F53\u524D\u9009\u62E9\u5DF2\u4FDD\u7559\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}finally{setSaving(!1)}}},savedProvider=providers.find(item=>item.id===saved.provider)?.name||saved.provider,savedModel=saved.provider===provider&&models.find(item=>item.id===saved.model)?.name||saved.model,pendingProvider=providers.find(item=>item.id===value.provider)?.name||value.provider,pendingModel=value.provider===provider&&models.find(item=>item.id===value.model)?.name||value.model,savedSummary=saved.mode==="custom"?savedProvider+" / "+savedModel:"\u8DDF\u968F\u804A\u5929\u6A21\u578B",pendingSummary=value.mode==="custom"?pendingProvider+" / "+pendingModel:"\u8DDF\u968F\u804A\u5929\u6A21\u578B";return h("div",{className:"sg-settings-panel sg-model-settings"},h("h4",{className:"sg-model-heading"},"\u8BB0\u5FC6\u5904\u7406\u6A21\u578B"),h("div",{className:"sg-model-modes",role:"radiogroup","aria-label":"\u8BB0\u5FC6\u5904\u7406\u6A21\u578B"},[{mode:"auto",title:"\u8DDF\u968F\u804A\u5929\u6A21\u578B"},{mode:"custom",title:"\u5355\u72EC\u6307\u5B9A\u6A21\u578B"}].map(item=>h("label",{key:item.mode,className:"sg-model-mode"+(value.mode===item.mode?" selected":"")},h("input",{type:"radio",name:"sg-memory-model-mode",value:item.mode,checked:value.mode===item.mode,disabled:editingDisabled,onChange:()=>edit(item.mode==="auto"?{mode:"auto"}:customDraft.current||(saved.mode==="custom"?saved:{mode:"custom",provider:providers[0]?.id||"",model:""}))}),h("span",{className:"sg-model-mode-copy"},h("span",{className:"sg-model-mode-title"},item.title))))),custom?h(React.Fragment,null,h("div",{className:"sg-model-fields"},h("label",{className:"sg-model-field"},"\u670D\u52A1\u5546",h("select",{className:"sg-effort-select","aria-label":"\u8BB0\u5FC6\u5904\u7406\u670D\u52A1\u5546",value:provider,disabled:editingDisabled||!catalog,onChange:event3=>edit({mode:"custom",provider:event3.target.value,model:""})},h("option",{value:""},"\u8BF7\u9009\u62E9\u670D\u52A1\u5546"),provider&&!providers.some(item=>item.id===provider)?h("option",{value:provider},provider+"\uFF08\u5F53\u524D\u4E0D\u53EF\u7528\uFF09"):null,providers.map(item=>h("option",{key:item.id,value:item.id},item.name||item.id)))),h("label",{className:"sg-model-field"},"\u6A21\u578B",h("select",{className:"sg-effort-select","aria-label":"\u8BB0\u5FC6\u5904\u7406\u5177\u4F53\u6A21\u578B",value:value.model||"",disabled:editingDisabled||!catalog||!provider||loading||!!modelsError,onChange:event3=>edit({...value,model:event3.target.value})},h("option",{value:""},loading?"\u6B63\u5728\u8BFB\u53D6\u6A21\u578B\u2026":"\u8BF7\u9009\u62E9\u6A21\u578B"),value.model&&!models.some(item=>item.id===value.model)?h("option",{value:value.model},value.model+"\uFF08\u672A\u5728\u5217\u8868\u4E2D\uFF09"):null,models.map(item=>h("option",{key:item.id,value:item.id},item.name||item.id))))),null):null,custom&&!catalog&&!catalogError?h("p",{className:"sg-status-feedback",role:"status"},"\u6B63\u5728\u8BFB\u53D6\u670D\u52A1\u5546\u2026"):null,settings&&settings.writable!==!0?h("p",{className:"sg-status-feedback"},"\u5F53\u524D\u914D\u7F6E\u4E3A\u53EA\u8BFB\u3002"):null,catalogError||modelsError?h("p",{className:"sg-status-feedback failed",role:"alert"},"\u8BFB\u53D6\u5931\u8D25\uFF1A"+(catalogError||modelsError)," ",h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:()=>setRevision(current=>current+1)},"\u91CD\u65B0\u8BFB\u53D6")):null,h("div",{className:"sg-model-save-row"},h("div",{className:"sg-model-saved"},h("span",{className:"sg-model-active-label"},"\u5F53\u524D\u751F\u6548"),h("strong",null,catalog||settings?.value?.memoryModel?savedSummary:"\u8DDF\u968F\u804A\u5929\u6A21\u578B"),changed?h("span",{className:"sg-model-pending"},"\u2192 "+pendingSummary):null),changed?h("button",{type:"button",className:"sg-save-button",disabled:editingDisabled||!valid2||custom&&!catalog,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58"):h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"})),feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null)}function RetrievalModelSettings({kind,settings,writable,onSaved}){let embedding=kind==="embedding",title=embedding?"\u5411\u91CF\u68C0\u7D22":"\u7ED3\u679C\u7CBE\u6392\uFF08Rerank\uFF09",prefix=embedding?"embedding":"rerank",urlKey=prefix+"Url",secretKey=prefix+"Key",modelKey=prefix+"Model",[saved,setSaved]=React.useState(settings||null),[draft,setDraft]=React.useState({}),[models,setModels]=React.useState([]),[listing,setListing]=React.useState(!1),[listFeedback,setListFeedback]=React.useState(""),[saving,setSaving]=React.useState(!1),[reading,setReading]=React.useState(!1),[feedback,setFeedback]=React.useState({kind:"",text:""}),lookup2=React.useRef(0);React.useEffect(()=>{settings&&setSaved(settings)},[settings]),React.useEffect(()=>()=>{lookup2.current+=1},[]),React.useEffect(()=>{if(feedback.kind!=="done")return;let timer=window.setTimeout(()=>setFeedback({kind:"",text:""}),4500);return()=>window.clearTimeout(timer)},[feedback]);let value=key=>draft[key]??saved?.[key]??"",url=String(value(urlKey)).trim().replace(/\/+$/,""),keyEdited=Object.hasOwn(draft,secretKey),keyConfigured=keyEdited?!!draft[secretKey].trim():saved?.[prefix+"KeyConfigured"]===!0,urlValid=!url;try{urlValid=["http:","https:"].includes(new URL(url).protocol)}catch{}let numericValid=!embedding||["vectorWeight","embeddingMinScore"].every(key=>{let raw=draft[key]??saved?.[key]??(key==="vectorWeight"?1:.3);return String(raw).trim()!==""&&Number.isFinite(Number(raw))&&Number(raw)>=0&&Number(raw)<=(key==="vectorWeight"?5:1)}),changed=Object.keys(draft).some(key=>key===secretKey||String(draft[key])!==String(saved?.[key]??"")),disabled=!saved||writable!==!0||saving||reading,edit=(key,next2)=>{setDraft(current=>({...current,[key]:next2})),setFeedback({kind:"",text:""}),(key===urlKey||key===secretKey)&&(lookup2.current+=1,setModels([]),setListing(!1),setListFeedback(""))},listModels=async()=>{if(disabled||listing||!url||!urlValid||!keyConfigured)return;let request=++lookup2.current;setListing(!0),setModels([]),setListFeedback("");try{let result=await api2("models",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind,url,...keyEdited?{key:draft[secretKey].trim()}:{}})});if(request!==lookup2.current)return;let ids=Array.isArray(result.models)?result.models.filter(id2=>typeof id2=="string"&&id2):[];setModels(ids),setListFeedback(ids.length?"\u5DF2\u8BFB\u53D6\u6A21\u578B\u5217\u8868\u3002\u8BF7\u9009\u62E9\u5BF9\u5E94\u7C7B\u578B\u7684\u6A21\u578B\uFF0C\u4E5F\u53EF\u624B\u52A8\u586B\u5199\u3002":"\u672A\u80FD\u8BFB\u53D6\u6A21\u578B\u5217\u8868\uFF0C\u53EF\u91CD\u8BD5\u6216\u624B\u52A8\u586B\u5199\u6A21\u578B\u540D\u79F0\u3002")}catch{request===lookup2.current&&setListFeedback("\u672A\u80FD\u8BFB\u53D6\u6A21\u578B\u5217\u8868\uFF0C\u53EF\u91CD\u8BD5\u6216\u624B\u52A8\u586B\u5199\u6A21\u578B\u540D\u79F0\u3002")}finally{request===lookup2.current&&setListing(!1)}},save=async()=>{if(disabled||!changed||!urlValid||!numericValid)return;let patch={};for(let key of Object.keys(draft))patch[key]=key==="vectorWeight"||key==="embeddingMinScore"?Number(draft[key]):key===urlKey?url:draft[key].trim();setSaving(!0),setFeedback({kind:"",text:""}),lookup2.current+=1,setListing(!1);try{let result=await api2("settings",null,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(patch)});if(!result.vectorSettings||typeof result.vectorSettings[prefix+"Ready"]!="boolean")throw new Error("Missing saved settings");setSaved(result.vectorSettings),setDraft({}),onSaved?.(result.vectorSettings),setFeedback({kind:"done",text:"\u914D\u7F6E\u5DF2\u4FDD\u5B58\u3002"})}catch{setFeedback({kind:"failed",text:"\u672A\u80FD\u786E\u8BA4\u4FDD\u5B58\uFF0C\u8F93\u5165\u5DF2\u4FDD\u7559\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u914D\u7F6E\u540E\u6838\u5BF9\uFF0C\u6216\u91CD\u8BD5\u4FDD\u5B58\u3002"})}finally{setSaving(!1)}},readSaved=async()=>{if(!(saving||reading)){setReading(!0);try{let result=await api2("overview");if(!result.vectorSettings||typeof result.vectorSettings[prefix+"Ready"]!="boolean")throw new Error("Missing saved settings");setSaved(result.vectorSettings),onSaved?.(result.vectorSettings),setFeedback({kind:"done",text:"\u5DF2\u91CD\u65B0\u8BFB\u53D6\u4FDD\u5B58\u7684\u914D\u7F6E\uFF1B\u672A\u4FDD\u5B58\u8F93\u5165\u5DF2\u4FDD\u7559\u3002"})}catch{setFeedback({kind:"failed",text:"\u672A\u80FD\u8BFB\u53D6\u4FDD\u5B58\u7684\u914D\u7F6E\uFF0C\u8F93\u5165\u5DF2\u4FDD\u7559\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}finally{setReading(!1)}}},ready4=saved?.[prefix+"Ready"]===!0,active=ready4&&(!embedding||Number(saved.vectorWeight)>0),status=saved?active?"\u5DF2\u914D\u7F6E \xB7 "+saved[modelKey]:ready4&&embedding?"\u5DF2\u505C\u7528\uFF08\u5411\u91CF\u68C0\u7D22\u5360\u6BD4\u4E3A 0\uFF09":saved[urlKey]?"\u914D\u7F6E\u672A\u5B8C\u6574\uFF0C\u6682\u672A\u542F\u7528":"\u672A\u542F\u7528":"\u5C1A\u672A\u8BFB\u53D6\u914D\u7F6E";return h("div",{className:"sg-settings-panel sg-model-settings sg-retrieval-settings","data-kind":kind},h("div",{className:"sg-model-heading-row"},h("h4",{className:"sg-model-heading"},title),h(InfoPopover,{label:title+"\u8BF4\u660E"},h("p",null,"\u586B\u5199\u5730\u5740\u3001\u5BC6\u94A5\u548C\u6A21\u578B\u540E\u542F\u7528\uFF1B\u6E05\u7A7A\u5730\u5740\u5E76\u4FDD\u5B58\u5373\u53EF\u505C\u7528\u3002\u542F\u7528\u4F1A\u4EA7\u751F\u670D\u52A1\u5546 API \u8D39\u7528\u3002"),h("p",null,embedding?"\u542F\u7528\u540E\uFF0C\u4E8B\u4EF6\u6807\u9898\u548C\u6458\u8981\u4F1A\u53D1\u9001\u7ED9\u5411\u91CF\u670D\u52A1\u5546\u3002":"\u542F\u7528\u540E\uFF0C\u68C0\u7D22\u95EE\u9898\u548C\u5019\u9009\u4E8B\u4EF6\u5185\u5BB9\u4F1A\u53D1\u9001\u7ED9\u7CBE\u6392\u670D\u52A1\u5546\u3002"),h("p",null,"\u586B\u5199 OpenAI \u517C\u5BB9\u63A5\u53E3\u57FA\u7840\u5730\u5740\uFF0C\u4E0D\u542B "+(embedding?"/embeddings":"/rerank")+"\u3002"),h("p",null,"\u4FDD\u5B58\u4E0D\u9A8C\u8BC1\u8FDE\u63A5\u3002"+(embedding?"\u5DF2\u6709\u4E8B\u4EF6\u7684\u5411\u91CF\u4F1A\u5728\u540E\u7EED\u68C0\u7D22\u65F6\u8865\u9F50\u3002":"")))),h("div",{className:"sg-retrieval-fields"},h("label",{className:"sg-model-field"},"API \u5730\u5740",h("input",{type:"url",value:value(urlKey),disabled,placeholder:"https://\u4F60\u7684\u670D\u52A1\u5730\u5740/v1","aria-label":title+" API \u5730\u5740",spellCheck:!1,onChange:event3=>edit(urlKey,event3.target.value)})),urlValid?null:h("p",{className:"sg-status-feedback failed",role:"alert"},"\u8BF7\u586B\u5199\u4EE5 http:// \u6216 https:// \u5F00\u5934\u7684\u6709\u6548\u5730\u5740\u3002"),h("label",{className:"sg-model-field"},"API Key",h("input",{type:"password",value:draft[secretKey]??"",disabled,placeholder:keyEdited&&!draft[secretKey]?"\u4FDD\u5B58\u540E\u6E05\u9664\u5BC6\u94A5":saved?.[prefix+"KeyConfigured"]?"\u5DF2\u4FDD\u5B58\u5BC6\u94A5\uFF0C\u672A\u4FEE\u6539\u65F6\u4FDD\u7559":"\u586B\u5199 API Key","aria-label":title+" API Key",autoComplete:"new-password",spellCheck:!1,onChange:event3=>edit(secretKey,event3.target.value)})),h("div",{className:"sg-retrieval-actions"},saved?.[prefix+"KeyConfigured"]?h("button",{type:"button",className:"sg-quiet-button",disabled,onClick:()=>edit(secretKey,"")},"\u6E05\u9664\u5DF2\u4FDD\u5B58\u5BC6\u94A5"):null,keyEdited?h("button",{type:"button",className:"sg-quiet-button",disabled,onClick:()=>{setDraft(current=>{let next2={...current};return delete next2[secretKey],next2}),lookup2.current+=1,setModels([]),setListing(!1),setListFeedback(""),setFeedback({kind:"",text:""})}},"\u64A4\u9500\u5BC6\u94A5\u4FEE\u6539"):null),keyEdited&&!draft[secretKey].trim()?h("p",{className:"sg-setting-note"},"\u4FDD\u5B58\u540E\u5C06\u6E05\u9664\u5BC6\u94A5\u5E76\u505C\u7528\u6B64\u529F\u80FD\u3002"):null,h("label",{className:"sg-model-field"},"\u6A21\u578B\u540D\u79F0",h("input",{type:"text",value:value(modelKey),disabled,list:"sg-"+kind+"-models",placeholder:"\u586B\u5199\u6A21\u578B\u540D\u79F0\u6216\u4ECE\u5217\u8868\u9009\u62E9","aria-label":title+"\u6A21\u578B\u540D\u79F0",autoComplete:"off",spellCheck:!1,onChange:event3=>edit(modelKey,event3.target.value)})),h("datalist",{id:"sg-"+kind+"-models"},models.map(id2=>h("option",{key:id2,value:id2}))),h("div",{className:"sg-retrieval-actions"},h("button",{type:"button",className:"sg-storage-button",disabled:disabled||listing||!url||!urlValid||!keyConfigured,onClick:()=>{listModels()}},listing?"\u6B63\u5728\u8BFB\u53D6\u2026":"\u8BFB\u53D6\u6A21\u578B\u5217\u8868")),listFeedback?h("p",{className:"sg-status-feedback",role:"status"},listFeedback):null),embedding?h("details",{className:"sg-retrieval-tuning"},h("summary",null,"\u68C0\u7D22\u53C2\u6570"),h("div",{className:"sg-model-fields"},h("label",{className:"sg-model-field"},"\u5411\u91CF\u68C0\u7D22\u5360\u6BD4",h("input",{type:"number",min:0,max:5,step:.1,value:draft.vectorWeight??saved?.vectorWeight??1,disabled,"aria-label":"\u5411\u91CF\u68C0\u7D22\u5360\u6BD4",onChange:event3=>edit("vectorWeight",event3.target.value)})),h("label",{className:"sg-model-field"},"\u6700\u4F4E\u76F8\u4F3C\u5EA6",h("input",{type:"number",min:0,max:1,step:.05,value:draft.embeddingMinScore??saved?.embeddingMinScore??.3,disabled,"aria-label":"\u6700\u4F4E\u76F8\u4F3C\u5EA6",onChange:event3=>edit("embeddingMinScore",event3.target.value)}))),h("p",{className:"sg-setting-note"},"\u5360\u6BD4 1 \u4E0E\u5173\u952E\u8BCD\u68C0\u7D22\u5E73\u6743\uFF1B0 \u505C\u7528\u3002\u6700\u4F4E\u76F8\u4F3C\u5EA6\u8303\u56F4 0\u20131\u3002"),numericValid?null:h("p",{className:"sg-status-feedback failed",role:"alert"},"\u5360\u6BD4\u9700\u4E3A 0\u20135 \u7684\u6570\u5B57\uFF0C\u6700\u4F4E\u76F8\u4F3C\u5EA6\u9700\u4E3A 0\u20131 \u7684\u6570\u5B57\u3002")):null,h("div",{className:"sg-model-save-row"},h("div",{className:"sg-model-saved"},h("span",{className:"sg-model-active-label"},"\u5F53\u524D\u751F\u6548"),h("strong",null,status)),changed?h("button",{type:"button",className:"sg-save-button",disabled:disabled||!urlValid||!numericValid,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58"):saved?h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"}):null),!saved||writable!==!0?h("p",{className:"sg-status-feedback"},saved?"\u5F53\u524D\u68C0\u7D22\u914D\u7F6E\u4E3A\u53EA\u8BFB\u3002":"\u68C0\u7D22\u914D\u7F6E\u5C1A\u672A\u8BFB\u53D6\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u3002"):null,feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null,!saved||feedback.kind==="failed"?h("button",{type:"button",className:"sg-quiet-button",disabled:saving||reading,onClick:()=>{readSaved()}},reading?"\u6B63\u5728\u8BFB\u53D6\u2026":"\u91CD\u65B0\u8BFB\u53D6\u914D\u7F6E"):null)}function SettingsPage({selected,graphSettings,vectorSettings,retrievalSettingsWritable,onRetrievalSettingsSaved,refresh,namespace,dataDirectory,onBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let[turnSize,setTurnSize]=React.useState(String(selected.blockTurnSize??6)),[lambda,setLambda]=React.useState(String(selected.blockDecayLambda??.3)),[agentWeight,setAgentWeight]=React.useState(String(selected.agentMemoryRetrievalWeight??1)),[directoryOpening,setDirectoryOpening]=React.useState(!1),[directoryFeedback,setDirectoryFeedback]=React.useState({kind:"",text:""});React.useEffect(()=>{setTurnSize(String(selected.blockTurnSize??6)),setLambda(String(selected.blockDecayLambda??.3)),setAgentWeight(String(selected.agentMemoryRetrievalWeight??1))},[selected.blockTurnSize,selected.blockDecayLambda,selected.agentMemoryRetrievalWeight]);let turnSizeValue=Number(turnSize),lambdaValue=Number(lambda),agentWeightValue=Number(agentWeight),changed=Number.isSafeInteger(turnSizeValue)&&turnSizeValue>=1&&lambda!==""&&Number.isFinite(lambdaValue)&&lambdaValue>=0&&agentWeight!==""&&Number.isFinite(agentWeightValue)&&agentWeightValue>=0&&agentWeightValue<=5&&(turnSizeValue!==selected.blockTurnSize||lambdaValue!==selected.blockDecayLambda||agentWeightValue!==(selected.agentMemoryRetrievalWeight??1)),suggestedLambda=Math.round((selected.blockDecayLambda??.3)*turnSizeValue/(selected.blockTurnSize||6)/.05)*.05,showSuggestion=Number.isSafeInteger(turnSizeValue)&&turnSizeValue>=1&&turnSizeValue!==selected.blockTurnSize,pluginSettings=usePluginSettings?usePluginSettings(state=>state):null,effortMode=pluginSettings?.value?.structuredReasoningEffort||"auto",effortOverridden=pluginSettings?.user?.structuredReasoningEffort!==void 0,settingsWritable=pluginSettings?.writable===!0,workspaceRows=[["Schema","v"+selected.schemaVersion],["\u5DE5\u4F5C\u533A",selected.workspaceName||"\u5F53\u524D\u5DE5\u4F5C\u533A"],["\u5185\u90E8\u7A7A\u95F4 ID",namespace],["\u5DF2\u5904\u7406\u8F6E\u6B21",selected.currentTurn]],runtimeDiagnostics=[["duplicates","\u21C4","\u91CD\u590D\u8BB0\u5FC6\u6574\u7406","\u67E5\u770B\u4FDD\u7559\u539F\u56E0\u3001\u5408\u5E76\u5019\u9009\u4E0E\u91CD\u65B0\u626B\u63CF"],["system","\u2713","\u7CFB\u7EDF\u72B6\u6001","\u5904\u7406\u6982\u89C8\u4E0E\u6700\u8FD1\u6574\u7406\u65F6\u95F4"],["audit","\u2197","\u4F7F\u7528\u8BB0\u5F55","\u957F\u671F\u8BB0\u5FC6\u4F55\u65F6\u88AB\u4F7F\u7528"],["status","\u21BB","\u540E\u53F0\u4EFB\u52A1","\u5904\u7406\u8FDB\u5EA6\u3001\u5931\u8D25\u4EFB\u52A1\u4E0E\u91CD\u8BD5"]],openDirectory=()=>{!dataDirectory||directoryOpening||(setDirectoryOpening(!0),setDirectoryFeedback({kind:"",text:""}),api2("storage/open-directory",{},{method:"POST"}).then(()=>setDirectoryFeedback({kind:"done",text:"\u5DF2\u5728\u6587\u4EF6\u7BA1\u7406\u5668\u4E2D\u6253\u5F00"})).catch(reason=>setDirectoryFeedback({kind:"failed",text:"\u6253\u5F00\u5931\u8D25\uFF1A"+String(reason?.message||reason)})).finally(()=>setDirectoryOpening(!1)))},copyDirectory=()=>{if(dataDirectory){if(setDirectoryFeedback({kind:"",text:""}),!navigator?.clipboard?.writeText){setDirectoryFeedback({kind:"failed",text:"\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236"});return}navigator.clipboard.writeText(dataDirectory).then(()=>setDirectoryFeedback({kind:"done",text:"\u8DEF\u5F84\u5DF2\u590D\u5236"})).catch(reason=>setDirectoryFeedback({kind:"failed",text:"\u590D\u5236\u5931\u8D25\uFF1A"+String(reason?.message||reason)}))}},menu=items=>h("div",{className:"sg-menu sg-settings-menu"},items.map(([id2,icon,title,subtitle])=>h("button",{key:id2,type:"button",className:"sg-menu-row",onClick:()=>setView({name:id2,back:{name:"settings"}})},h("span",{className:"sg-menu-icon","aria-hidden":"true"},icon),h("span",null,h("span",{className:"sg-menu-title"},title),h("br"),h("span",{className:"sg-menu-subtitle"},subtitle)),h("span",{className:"sg-chevron"},"\u203A")))),stepper=({value,onChange,min:min4,max:max5,step:step3,label,allowFloat})=>{let current=Number(value),delta=allowFloat?step3:1,bump=direction=>{if(!Number.isFinite(current))return;let next2=Math.min(max5,Math.max(min4,Number((current+direction*delta).toFixed(2))));onChange(String(next2))};return h("span",{className:"sg-stp sg-stp-wide"},h("button",{type:"button","aria-label":"\u51CF\u5C11"+label,disabled:!Number.isFinite(current)||current<=min4,onClick:()=>bump(-1)},"\u2212"),h("input",{className:"sg-number-input",type:"number",min:String(min4),max:max5===void 0?void 0:String(max5),step:String(step3),value,onChange:event3=>onChange(event3.target.value),"aria-label":label}),h("button",{type:"button","aria-label":"\u589E\u52A0"+label,disabled:!Number.isFinite(current)||max5===void 0||current>=max5,onClick:()=>bump(1)},"+"))},blockSettings=h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-stage"},h("span",null,"\u6BCF\u4E2A Block \u7684\u5BF9\u8BDD\u8F6E\u6570"),h("span",{className:"sg-lambda-control"},stepper({value:turnSize,onChange:setTurnSize,min:1,max:30,step:1,label:"\u6BCF\u4E2A Block \u7684\u5BF9\u8BDD\u8F6E\u6570"}),h("span",{className:"sg-stage-value waiting"},"\u8F6E"))),h("p",{className:"sg-setting-note"},"1 \u8F6E\u7B49\u4E8E\u4E00\u6B21\u63D0\u95EE\u548C\u5B8C\u6574\u56DE\u590D\uFF0C\u53EA\u5F71\u54CD\u540E\u7EED\u672A\u5C01\u5B58\u5185\u5BB9\u3002"),h("div",{className:"sg-stage"},h("span",null,"Block \u8870\u51CF\u7CFB\u6570 \u03BB"),h("span",{className:"sg-lambda-control"},stepper({value:lambda,onChange:setLambda,min:0,max:.4,step:.05,label:"Block \u8870\u51CF\u7CFB\u6570 \u03BB",allowFloat:!0}))),h("p",{className:"sg-setting-note"},"\u8D8A\u5C0F\u9057\u5FD8\u8D8A\u6162\uFF0Ctoken \u6D88\u8017\u8D8A\u591A\u3002"),showSuggestion?h("div",{className:"sg-setting-suggestion"},h("span",null,"\u5EFA\u8BAE \u03BB \u8C03\u6574\u4E3A "+suggestedLambda.toFixed(2)+"\u3002"),h("button",{type:"button",className:"sg-quiet-button",onClick:()=>setLambda(String(Number(suggestedLambda.toFixed(2))))},"\u91C7\u7528\u5EFA\u8BAE\u503C")):null,h("div",{className:"sg-stage"},h("span",null,"\u4E3B\u52A8\u8BB0\u5FC6\u68C0\u7D22\u5360\u6BD4"),h("span",{className:"sg-lambda-control"},stepper({value:agentWeight,onChange:setAgentWeight,min:0,max:5,step:.05,label:"\u4E3B\u52A8\u8BB0\u5FC6\u68C0\u7D22\u5360\u6BD4",allowFloat:!0}))),h("p",{className:"sg-setting-note"},"1 \u4E3A\u5E73\u6743\uFF0C0 \u4E0D\u5C55\u793A agent \u8BB0\u5F55\u3002"),changed?h("div",{className:"sg-dirty"},h("span",null,[turnSizeValue!==selected.blockTurnSize,lambdaValue!==selected.blockDecayLambda,agentWeightValue!==(selected.agentMemoryRetrievalWeight??1)].filter(Boolean).length+" \u9879\u672A\u4FDD\u5B58"),h("button",{type:"button",className:"sg-quiet-button",disabled:savingSettings,onClick:()=>{setTurnSize(String(selected.blockTurnSize??6)),setLambda(String(selected.blockDecayLambda??.3)),setAgentWeight(String(selected.agentMemoryRetrievalWeight??1))}},"\u653E\u5F03"),h("button",{type:"button",className:"sg-save-button",disabled:!changed||savingSettings,onClick:()=>{updateSettings({blockTurnSize:turnSizeValue,blockDecayLambda:lambdaValue,agentMemoryRetrievalWeight:agentWeightValue})}},savingSettings?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58")):h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"})),effortSettings=h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-stage"},h("span",null,"\u7ED3\u6784\u5316\u63A8\u7406\u6863\u4F4D"),h("span",{className:"sg-lambda-control"},h("select",{className:"sg-effort-select",value:effortMode,disabled:!settingsWritable,onChange:event3=>{setEffort&&setEffort(event3.target.value)},"aria-label":"\u7ED3\u6784\u5316\u63A8\u7406\u6863\u4F4D\u7B56\u7565"},h("option",{value:"auto"},"auto\uFF08\u81EA\u52A8\uFF09"),h("option",{value:"force-off"},"force-off\uFF08\u5F3A\u5236\u5173\u95ED\uFF09")),effortOverridden?h("button",{type:"button",className:"sg-effort-button",onClick:()=>{resetEffort&&resetEffort()}},"\u6062\u590D\u9ED8\u8BA4"):h("span",{className:"sg-stage-value waiting"},"\u9ED8\u8BA4"))),h("p",{className:"sg-setting-note"},"auto \u8DDF\u968F\u6A21\u578B\u80FD\u529B\uFF1Bforce-off \u4F18\u5148\u5173\u95ED\uFF0C\u4E0D\u652F\u6301\u65F6\u81EA\u52A8\u964D\u7EA7\u3002")),workspaceInfo=h("div",{className:"sg-settings-panel sg-pipeline"},workspaceRows.map(([label,value])=>h("div",{key:label,className:"sg-stage"},h("span",null,label),h("span",{className:label==="\u5185\u90E8\u7A7A\u95F4 ID"?"sg-stage-value sg-code":"sg-stage-value"},String(value)))));return h("div",{className:"sg-settings-shell"},h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-pg-head"},h("h2",null,"\u9AD8\u7EA7\u8BBE\u7F6E")),h("section",{className:"sg-settings-group sg-settings-install","aria-labelledby":"sg-memory-settings-title"},h("h3",{id:"sg-memory-settings-title",className:"sg-settings-group-title"},"\u5B89\u88C5\u7EA7\u8BBE\u7F6E"),h("div",{className:"sg-settings-columns"},h("div",{className:"sg-settings-column"},h(GraphSettingsPanel,{state:graphSettings,refresh}),h(ProfileLimitSettings),h(DailyNotesSettings,{usePluginSettings,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}),blockSettings),h("div",{className:"sg-settings-column"},h(RetrievalModelSettings,{kind:"embedding",settings:vectorSettings,writable:retrievalSettingsWritable,onSaved:onRetrievalSettingsSaved}),h(RetrievalModelSettings,{kind:"rerank",settings:vectorSettings,writable:retrievalSettingsWritable,onSaved:onRetrievalSettingsSaved})))),h("section",{className:"sg-settings-group","aria-labelledby":"sg-host-settings-title"},h("h3",{id:"sg-host-settings-title",className:"sg-settings-group-title"},"\u5BBF\u4E3B\u914D\u7F6E"),h("div",{className:"sg-settings-columns"},h("div",{className:"sg-settings-column"},h(MemoryModelSettings,{usePluginSettings,setMemoryModel})),h("div",{className:"sg-settings-column"},effortSettings))),h("section",{className:"sg-settings-group","aria-labelledby":"sg-workspace-settings-title"},h("h3",{id:"sg-workspace-settings-title",className:"sg-settings-group-title"},"\u5DE5\u4F5C\u533A\u4FE1\u606F"),workspaceInfo),h("section",{className:"sg-settings-group","aria-labelledby":"sg-storage-title"},h("h3",{id:"sg-storage-title",className:"sg-settings-group-title"},"\u6570\u636E\u4E0E\u5B58\u50A8"),h("div",{className:"sg-storage-card"},h("span",{className:"sg-storage-label"},"\u6570\u636E\u5B58\u50A8\u4F4D\u7F6E"),h("span",{className:"sg-storage-path",title:dataDirectory||void 0},dataDirectory||"\u5F53\u524D\u4F7F\u7528\u5185\u5B58\u5B58\u50A8\uFF0C\u6CA1\u6709\u672C\u5730\u6570\u636E\u76EE\u5F55"),h("div",{className:"sg-storage-actions"},h("button",{type:"button",className:"sg-storage-button",disabled:!dataDirectory||directoryOpening,onClick:openDirectory},directoryOpening?"\u6B63\u5728\u6253\u5F00\u2026":"\u6253\u5F00\u6587\u4EF6\u5939"),h("button",{type:"button",className:"sg-storage-button",disabled:!dataDirectory,onClick:copyDirectory},"\u590D\u5236\u8DEF\u5F84")),h("p",{className:"sg-storage-feedback "+directoryFeedback.kind,role:directoryFeedback.kind==="failed"?"alert":"status","aria-live":"polite"},directoryFeedback.text)),menu([["raw","{}","\u67E5\u770B\u539F\u59CB\u6570\u636E","Block\u3001Event\u3001Graph \u4E0E\u6A21\u578B\u54CD\u5E94"]])),h("section",{className:"sg-settings-group sg-settings-compact","aria-labelledby":"sg-diagnostics-title"},h("h3",{id:"sg-diagnostics-title",className:"sg-settings-group-title"},"\u8FD0\u884C\u4E0E\u8BCA\u65AD"),menu(runtimeDiagnostics)))}function overviewAbsolute(value){let date=new Date(value);return Number.isNaN(date.getTime())?"\u65F6\u95F4\u672A\u77E5":new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(date)}function overviewRelative(value){let time2=Date.parse(value||"");if(!Number.isFinite(time2))return"\u8FD8\u6CA1\u6709\u66F4\u65B0";let seconds=Math.round((Date.now()-time2)/1e3);if(seconds<60)return"\u521A\u521A";if(seconds<3600)return Math.floor(seconds/60)+" \u5206\u949F\u524D";if(seconds<86400)return Math.floor(seconds/3600)+" \u5C0F\u65F6\u524D";let days=Math.floor(seconds/86400);return days===1?"\u6628\u5929":days<30?days+" \u5929\u524D":overviewAbsolute(value)}function overviewCount(value){return Number(value||0).toLocaleString("en-US")}function OverviewPage({selected,loading,onOpenSection}){let stats=selected?.memoryOverview;if(loading&&!stats)return h(Loading);if(!stats)return h(Empty,{title:"\u8FD8\u6CA1\u6709\u53EF\u6C47\u603B\u7684\u8BB0\u5FC6",copy:"\u8FD9\u4E2A\u5DE5\u4F5C\u533A\u7684\u8BB0\u5FC6\u8BFB\u51FA\u6765\u4E4B\u540E\uFF0C\u4F1A\u663E\u793A\u5728\u8FD9\u91CC\u3002"});let layers=[{key:"profile",name:"\u5E38\u9A7B\u753B\u50CF",tone:"ink",section:"profile",value:stats.layers.profile?overviewCount(stats.layers.profile.characters):"\u2014",unit:"\u5B57",updatedAt:stats.layers.profile?.updatedAt},{key:"directory",name:"\u8BB0\u5FC6\u76EE\u5F55",tone:"moss",section:"long",value:stats.layers.directory?overviewCount(stats.layers.directory.chapters):"\u2014",unit:"\u7AE0",updatedAt:stats.layers.directory?.updatedAt},{key:"session",name:"\u4F1A\u8BDD\u8BB0\u5FC6",tone:"water",section:"short",value:overviewCount(stats.layers.session.blocks),unit:"\u5757",updatedAt:stats.layers.session.updatedAt},{key:"short",name:"\u77ED\u671F\u8BB0\u5FC6",tone:"sand",section:"daily",value:stats.layers.shortTerm?overviewCount(stats.layers.shortTerm.items):"\u2014",unit:"\u6761",updatedAt:stats.layers.shortTerm?.updatedAt},{key:"long",name:"\u957F\u671F\u8BB0\u5FC6",tone:"lib",section:"long",value:overviewCount(stats.layers.longTerm.events),unit:"\u4E2A\u4E8B\u4EF6",updatedAt:stats.layers.longTerm.updatedAt,answers:stats.layers.longTerm.answers}],heatmap=Array.isArray(stats.heatmap)?stats.heatmap:[],peak=Math.max(1,...heatmap.map(day=>Number(day.answers)||0));return h("section",{className:"sg-ov","data-testid":"stratagate-overview","aria-label":"\u8BB0\u5FC6\u603B\u89C8"},h("div",{className:"sg-ov-top"},h("div",{className:"sg-ov-stat"},h("div",{className:"sg-ov-big"},h("b",{className:"sg-mono","data-testid":"overview-answer-count"},overviewCount(stats.answeredLast7Days)),h(UsedMark,{title:"\u957F\u671F\u8BB0\u5FC6\u5E2E\u5230\u7684\u56DE\u7B54"})),stats.lastRecall?h("p",{"data-testid":"overview-last-recall"},"\u6700\u8FD1\u4E00\u6B21\uFF1A\u5E2E\u4F60\u60F3\u8D77\u4E86\u300C"+stats.lastRecall.title+"\u300D"):h("p",{className:"sg-ov-empty","data-testid":"overview-last-recall"},"\u6700\u8FD1\u8FD8\u6CA1\u6709\u957F\u671F\u8BB0\u5FC6\u88AB\u7528\u5230\u56DE\u7B54\u91CC")),h("div",{className:"sg-pillar","aria-label":"\u8BB0\u5FC6\u5206\u5C42"},layers.map((layer,index)=>{let when="\u6700\u8FD1\u66F4\u65B0\uFF1A"+overviewRelative(layer.updatedAt),countText=layer.value==="\u2014"?"\u6682\u65E0\u6570\u636E":layer.value+" "+layer.unit,summary=layer.name+" "+countText+"\uFF0C"+when,open=()=>{typeof onOpenSection=="function"&&onOpenSection(layer.section)};return h(React.Fragment,{key:layer.key},layer.key==="long"?h("div",{className:"sg-pillar-gap","aria-hidden":"true"}):null,h("button",{type:"button",className:"sg-pillar-row","data-testid":"overview-layer-"+layer.key,"aria-label":"\u6253\u5F00"+layer.name+"\uFF1A"+countText+"\uFF0C"+when,title:summary,onClick:open},h("span",{className:"sg-pillar-bar "+layer.tone,style:{animationDelay:index*60+"ms"},"aria-hidden":"true"}),h("span",{className:"sg-pillar-name"},h("b",null,layer.name)),h("span",{className:"sg-pillar-tail"},h("span",{className:"sg-pillar-use"},layer.key==="long"&&layer.answers>0?h(UsedMark,{count:layer.answers,title:"\u88AB\u56DE\u7B54\u7528\u5230 "+layer.answers+" \u6B21"}):null),h("span",{className:"sg-pillar-val"},h("b",{className:"sg-mono"},layer.value))),h("span",{className:"sg-pillar-when"},when)))})),h("div",{className:"sg-pillar-key"},h("span",null,h("i",{className:"sg-sw","aria-hidden":"true"}),"\u4E00\u76F4\u5E26\u7740"),h("span",null,h("i",{className:"sg-sw lib","aria-hidden":"true"}),"\u9700\u8981\u65F6\u53BB\u627E"),h("span",null,h(UsedMark),"\u88AB\u7528\u5230"))),h("div",{className:"sg-heat"},h("div",{className:"sg-heat-head"},h("span",null,h(UsedMark),"\u6BCF\u5929\u88AB\u56DE\u7B54\u7528\u5230\u51E0\u6B21"),h("span",null,"\u989C\u8272\u8D8A\u6DF1\u8D8A\u591A")),h("div",{className:"sg-heat-grid","aria-label":"\u6700\u8FD1 "+heatmap.length+" \u5929\u957F\u671F\u8BB0\u5FC6\u91C7\u7528"},heatmap.map(day=>{let answers=Number(day.answers)||0,ink=answers?Math.min(28+Math.round(answers/peak*62),90):0;return h("i",{key:day.day,title:day.day+" \xB7 "+answers+" \u6B21\u56DE\u7B54",style:answers?{background:"color-mix(in srgb, var(--sg-ink) "+ink+"%, var(--sg-sheet))",boxShadow:"none"}:void 0})})),h("div",{className:"sg-heat-scale"},h("span",null,heatmap.length>14?"4 \u5468\u524D":"2 \u5468\u524D"),h("span",null,"\u4ECA\u5929"))))}function MemoryPage({useWorkspaces,useSessions,navigationState,usePluginSettings,setMemoryModel,setEffort,resetEffort,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry,onOpenDreamingSession,onChooseSidebar,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let TAB_SWATCH={profile:"ink",short:"water",daily:"sand",long:"lib"},workspaceItems=useWorkspaces(state=>state.items),sessionById=useSessions(state=>state.byId||{}),[overview,setOverview]=React.useState({namespaces:[]}),[namespace,setNamespace]=React.useState(""),[workspaceTitles,setWorkspaceTitles]=React.useState({}),[workspaceSessionIds,setWorkspaceSessionIds]=React.useState({}),[conversationId,setConversationId]=React.useState(""),[section,setSection]=React.useState("overview"),[view,setView]=React.useState({name:"root"}),[graphFocusNodeId,setGraphFocusNodeId]=React.useState(""),consumeGraphFocus=React.useCallback(()=>setGraphFocusNodeId(""),[]),[data4,setData]=React.useState({events:[],graph:{nodes:[],edges:[],migration:null},blocks:[],openBlock:null,conversations:[],activeThreadId:null,audit:[],pagination:{events:{total:0,offset:0,limit:40},blocks:{total:0,offset:0,limit:40},audit:{total:0,offset:0,limit:100}}}),[query,setQuery]=React.useState(""),[source,setSource]=React.useState(null),[loading,setLoading]=React.useState(!0),[error3,setError]=React.useState(""),[recentError,setRecentError]=React.useState(""),[savingSettings,setSavingSettings]=React.useState(!1),[pollFast,setPollFast]=React.useState(!1),dashboardRequestRef=React.useRef(null),sourceRequestRef=React.useRef(null),namespaceRef=React.useRef(namespace);namespaceRef.current=namespace;let dashboardEtagsRef=React.useRef(new Map),loadedNamespaceRef=React.useRef(""),feedbackDeepLinkRef=React.useRef(readFeedbackNavigationState(navigationState)||readFeedbackDeepLink()),graphNodeNavigationRef=React.useRef(readGraphNodeNavigationState(navigationState)||readGraphNodeDeepLink()),feedbackNavigationStateRef=React.useRef(navigationState),namespaceNavigationRef=React.useRef(null),directoryScrollRef=React.useRef(null),reportError=reason=>{let message=String(reason?.message||reason);if(setError(message),setRecentError(message),namespace){let category=/timeout|timed out|超时/i.test(message)?"timeout":/fetch|network|网络/i.test(message)?"network":"request-failed";api2("diagnostics",{namespace,category},{method:"POST"}).catch(()=>{})}};React.useEffect(()=>{let active=!0;return Promise.all((workspaceItems||[]).map(async workspace=>({key:await workspaceProjectKey(workspace.path),title:String(workspace.title||"").trim(),sessionIds:Array.isArray(workspace.sessionIds)?workspace.sessionIds.map(String):[]}))).then(entries=>{active&&(setWorkspaceTitles(Object.fromEntries(entries.filter(({key,title})=>key&&title).map(({key,title})=>[key,title]))),setWorkspaceSessionIds(Object.fromEntries(entries.filter(({key})=>key).map(({key,sessionIds})=>[key,sessionIds]))))}),()=>{active=!1}},[workspaceItems]);let loadDashboard=React.useCallback((activeNamespace,options2={})=>{let background=options2.background===!0;if(background&&!options2.force&&dashboardRequestRef.current)return Promise.resolve(null);dashboardRequestRef.current?.abort();let controller=new AbortController;dashboardRequestRef.current=controller;let key=String(activeNamespace||"")+"\0"+String(options2.threadId||"");return background||setLoading(!0),background||setError(""),dashboardApi({...activeNamespace?{namespace:activeNamespace}:{},...options2.threadId?{threadId:options2.threadId}:{}},{etag:options2.force?"":dashboardEtagsRef.current.get(key),signal:controller.signal}).then(result=>{if(controller.signal.aborted||dashboardRequestRef.current!==controller||(result.etag&&dashboardEtagsRef.current.set(key,result.etag),result.notModified||!result.data))return null;let next2=result.data;return setOverview(next2.overview||{namespaces:[]}),setPollFast(next2.processing===!0),next2.namespace&&(loadedNamespaceRef.current=next2.namespace,setNamespace(current=>next2.overview?.namespaces?.some(item=>item.namespace===current)?current:next2.namespace)),next2.data&&(setData(next2.data),setConversationId(next2.data.activeThreadId||"")),setError(""),next2}).catch(reason=>{if(controller.signal.aborted||dashboardRequestRef.current!==controller)return null;if(reason?.name!=="AbortError"&&reportError(reason),options2.propagateError===!0&&reason?.name!=="AbortError")throw reason;return null}).finally(()=>{dashboardRequestRef.current===controller&&(dashboardRequestRef.current=null,setLoading(!1))})},[]);React.useEffect(()=>{let graphLink=graphNodeNavigationRef.current,feedbackLink=feedbackDeepLinkRef.current;return graphLink?(setSection("long"),setQuery(""),setView({name:"root"}),setSource(null),setGraphFocusNodeId(graphLink.nodeId),readGraphNodeDeepLink()&&consumeGraphNodeDeepLink()):feedbackLink&&(setSection("more"),setView({name:"support"}),setSource(null),readFeedbackDeepLink()&&consumeFeedbackDeepLink()),loadDashboard(graphLink?.namespace||feedbackLink?.namespace||""),()=>{dashboardRequestRef.current?.abort(),sourceRequestRef.current?.abort()}},[loadDashboard]),React.useEffect(()=>{let graphLink=navigationState!==feedbackNavigationStateRef.current?readGraphNodeNavigationState(navigationState):null,feedback=readNewFeedbackNavigationState(feedbackNavigationStateRef.current,navigationState);if(feedbackNavigationStateRef.current=navigationState,graphLink){setSection("long"),setView({name:"root"}),setSource(null),setGraphFocusNodeId(graphLink.nodeId),namespaceNavigationRef.current=namespace!==graphLink.namespace?{namespace:graphLink.namespace}:null,setNamespace(graphLink.namespace),namespace===graphLink.namespace&&loadDashboard(graphLink.namespace,{force:!0});return}feedback&&(setSection("more"),setView({name:"support"}),setSource(null),namespaceNavigationRef.current=namespace!==feedback.namespace?{namespace:feedback.namespace}:null,setNamespace(feedback.namespace),namespace===feedback.namespace&&loadDashboard(feedback.namespace,{force:!0}))},[navigationState,loadDashboard]),React.useEffect(()=>{if(!namespace)return;let navigated=namespaceNavigationRef.current?.namespace===namespace;namespaceNavigationRef.current=null,loadedNamespaceRef.current!==namespace&&(directoryScrollRef.current=null,setConversationId(""),navigated||setView({name:"root"}),setSource(null),setRecentError(""),setData({events:[],graph:{nodes:[],edges:[],migration:null},blocks:[],openBlock:null,conversations:[],activeThreadId:null,audit:[],pagination:{events:{total:0,offset:0,limit:40},blocks:{total:0,offset:0,limit:40},audit:{total:0,offset:0,limit:100}}}),loadDashboard(namespace,{force:!0}))},[namespace,loadDashboard]),React.useEffect(()=>{if(!namespace)return;let stopped=!1,timer=null,schedule=delay2=>{stopped||document.hidden||(timer=window.setTimeout(run,delay2))},run=()=>{stopped||document.hidden||loadDashboard(namespace,{background:!0,threadId:conversationId}).finally(()=>{schedule(pollFast?2500:3e4)})},onVisibilityChange=()=>{document.hidden?(timer!==null&&window.clearTimeout(timer),timer=null,dashboardRequestRef.current?.abort()):run()};return document.addEventListener("visibilitychange",onVisibilityChange),schedule(pollFast?2500:3e4),()=>{stopped=!0,timer!==null&&window.clearTimeout(timer),document.removeEventListener("visibilitychange",onVisibilityChange)}},[namespace,conversationId,pollFast,loadDashboard]);let selected=(overview.namespaces||[]).find(item=>item.namespace===namespace),project=projectName(selected||namespace,workspaceTitles),activeProjectKey=namespace.includes(":project:")?namespace.split(":project:").pop():"",hostSessionIds=workspaceSessionIds[activeProjectKey]||[],memoryConversations=new Map(data4.conversations.map(conversation=>[conversation.id,conversation])),conversations=[],seenConversations=new Set;for(let id2 of hostSessionIds){let session=sessionById[id2];if(session?.parentId)continue;let memory=memoryConversations.get(id2),dshTitle=String(session?.title||"").trim();conversations.push({...memory||{},id:id2,label:dshTitle||memory?.label||"\u5BF9\u8BDD "+id2.slice(0,8)}),seenConversations.add(id2)}for(let memory of data4.conversations)seenConversations.has(memory.id)||conversations.push(memory);conversations.sort((left,right)=>left.id==="__legacy__"?1:right.id==="__legacy__"?-1:0);let clearSource=()=>{sourceRequestRef.current?.abort(),sourceRequestRef.current=null,setSource(null)},goSection=next2=>{directoryScrollRef.current=null,setSection(next2),setView({name:"root"}),clearSource()},sourceParams=(kind,item)=>kind==="event"?{eventId:item.id}:kind==="element"?{elementId:item.id}:{blockId:item.id},loadSource=(kind,item)=>{clearSource();let controller=new AbortController;sourceRequestRef.current=controller;let requestedNamespace=namespace,requestedId=String(item?.id||"");api2("sources",{namespace,...sourceParams(kind,item)},{signal:controller.signal}).then(value=>{if(sourceRequestRef.current!==controller||controller.signal.aborted||namespaceRef.current!==requestedNamespace)return;let returnedId=value?.event?.id||value?.element?.id||value?.block?.id||value?.id,returnedIds=Array.isArray(value?.events)?value.events.map(entry=>String(entry?.id||"")):[];returnedId&&String(returnedId)!==requestedId||returnedIds.length&&!returnedIds.includes(requestedId)||setSource(value)}).catch(reason=>{reason?.name!=="AbortError"&&sourceRequestRef.current===controller&&reportError(reason)})},openWithSource=(kind,item)=>{setView(current=>({name:kind,item,back:current})),loadSource(kind,item)},openEvent=(event3,trigger)=>{if(trigger?.getAttribute?.("data-topic-event-id")){let ancestors=[];for(let node=trigger.parentElement;node;node=node.parentElement)node.scrollHeight>node.clientHeight&&ancestors.push({node,top:node.scrollTop,left:node.scrollLeft});directoryScrollRef.current={namespace,eventId:event3.id,trigger,ancestors,top:window.scrollY||0,left:window.scrollX||0}}openWithSource("event",data4.events.find(item=>item.id===event3.id)||event3)};(React.useLayoutEffect||React.useEffect)(()=>{let saved=directoryScrollRef.current,action=directoryScrollAction(saved,section,namespace,view.name);if(action!=="none"){if(action==="clear"){directoryScrollRef.current=null;return}if(action==="detail"){for(let{node}of saved.ancestors)node.scrollTop=0,node.scrollLeft=0;window.scrollTo?.(0,0)}else if(action==="restore"){(saved.trigger?.isConnected&&saved.trigger.getClientRects().length?saved.trigger:Array.from(document.querySelectorAll(".sg-topic-event[data-topic-event-id]")).find(node=>node.getAttribute("data-topic-event-id")===saved.eventId&&node.getClientRects().length))?.focus?.({preventScroll:!0});for(let{node,top,left}of saved.ancestors)node.scrollTop=top,node.scrollLeft=left;window.scrollTo?.(saved.left,saved.top),directoryScrollRef.current=null}}},[view.name,section,namespace]);let openGraphNode=nodeId=>{directoryScrollRef.current=null,setSection("long"),setQuery(""),setView({name:"root"}),clearSource(),setGraphFocusNodeId(nodeId)},goBack=()=>{let previous=view.back||{name:"root"};setView(previous),previous.item&&["event","block"].includes(previous.name)?loadSource(previous.name,previous.item):clearSource()},backLabel=view.back?.name==="duplicates"?"\u91CD\u590D\u8BB0\u5FC6\u6574\u7406":view.back?.name==="block"?"\u4F1A\u8BDD\u8BB0\u5FC6":view.back?.name==="event"?"\u957F\u671F\u8BB0\u5FC6":view.back?.name==="structure"?"\u8BB0\u5FC6\u7ED3\u6784":section==="short"?"\u4F1A\u8BDD\u8BB0\u5FC6":"\u957F\u671F\u8BB0\u5FC6",refresh=(options2={})=>loadDashboard(namespace,{threadId:conversationId,force:!0,...options2}),refreshDirectory=React.useCallback(()=>loadDashboard(namespace,{threadId:conversationId,background:!0,force:!0}),[namespace,conversationId,loadDashboard]),selectConversation=nextConversationId=>(setConversationId(nextConversationId),loadDashboard(namespace,{threadId:nextConversationId,force:!0})),updateSettings=values=>(setSavingSettings(!0),setError(""),api2("settings",values,{method:"PATCH"}).then(()=>loadDashboard(namespace,{threadId:conversationId,force:!0})).catch(reportError).finally(()=>setSavingSettings(!1))),onRetrievalSettingsSaved=vectorSettings=>setOverview(current=>({...current,vectorSettings})),moreBack=()=>setView({name:"root"}),content=null;return(section==="long"||view.name==="support")&&loadedNamespaceRef.current!==namespace||loading&&!selected?content=h(Loading):view.name==="settings"&&!selected?content=h(SettingsPage,{graphSettings:overview.graphSettings,vectorSettings:overview.vectorSettings,retrievalSettingsWritable:overview.settingsWritable,onRetrievalSettingsSaved,refresh,selected:{blockTurnSize:6,blockDecayLambda:.3,agentMemoryRetrievalWeight:1,currentTurn:0,schemaVersion:12},namespace,dataDirectory:overview.dataDirectory,onBack:moreBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}):section==="overview"&&view.name==="root"?content=h(OverviewPage,{key:namespace,selected,loading,onOpenSection:goSection}):section==="profile"&&view.name==="root"?content=h(ProfilePage):section==="daily"&&view.name==="root"?content=h(DailyNotesPage,{key:namespace,namespace,setDailyInjectionDays}):!selected&&section!=="more"?content=h(Empty,{title:"\u8FD8\u6CA1\u6709\u8BB0\u5FC6",copy:"\u5B8C\u6210\u4E00\u4E9B DSH \u5BF9\u8BDD\u540E\uFF0C\u4F1A\u8BDD\u8BB0\u5FC6\u548C\u957F\u671F\u8BB0\u5FC6\u4F1A\u51FA\u73B0\u5728\u8FD9\u91CC\u3002"}):view.name==="event"?content=h(EventDetail,{event:view.item,project,source,onBack:goBack,backLabel,onNode:openGraphNode}):view.name==="status"?content=h(ProcessingStatus,{key:namespace,overview:selected,blocks:data4.blocks,conversations,namespace,serverVersion:overview.pluginVersion,onBack:view.back?goBack:()=>setView({name:"root"}),backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u8FD4\u56DE",refresh}):view.name==="import"?content=h(ImportPage,{key:namespace,namespace,onBack:moreBack,refresh}):view.name==="structure"?content=h(StructurePage,{events:data4.events,eventPage:data4.pagination?.events,graph:data4.graph,openEvent,namespace,onBack:moreBack}):view.name==="duplicates"?content=h(DuplicateReviewPage,{namespace,repair:selected?.duplicateRepair,onBack:moreBack,openEvent,refresh}):view.name==="system"?content=h(SystemPage,{selected,blocks:data4.blocks,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A",refresh,onDuplicates:()=>setView({name:"duplicates"})}):view.name==="audit"?content=h(AuditPage,{audit:data4.audit,auditPage:data4.pagination?.audit,namespace,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A"}):view.name==="raw"?content=h(RawPage,{data:data4,selected,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A"}):view.name==="display"?content=h(DisplayPage,{onBack:moreBack,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry}):view.name==="settings"?content=h(SettingsPage,{selected,graphSettings:overview.graphSettings,vectorSettings:overview.vectorSettings,retrievalSettingsWritable:overview.settingsWritable,onRetrievalSettingsSaved,refresh,namespace,dataDirectory:overview.dataDirectory,onBack:moreBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}):view.name==="support"?content=h(SupportPage,{key:namespace,namespace,overview,selected,data:data4,recentError,onBack:moreBack}):content=h(React.Fragment,null,loading?h(Loading):section==="short"?h(ShortTermPage,{key:namespace+":"+conversationId,blockTurnSize:selected?.blockTurnSize||6,blocks:data4.blocks,blockPage:data4.pagination?.blocks,openBlock:data4.openBlock,conversations,activeThreadId:conversationId||data4.activeThreadId||"",namespace,onConversationChange:selectConversation,refresh}):section==="long"?null:h(MoreHome,{setView,selected,overview,namespace,dataDirectory:overview.dataDirectory,updateSettings,savingSettings,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry,setDailyEnabled,setDailyInjectionDays})),h("main",{className:"sg-memory"+(view.name==="duplicates"?" sg-memory-review":"")+(view.name==="settings"||view.name==="display"||section==="more"&&view.name==="root"?" sg-settings-page":""),"data-testid":"stratagate-memory-ui"},h("style",null,css+DUPLICATE_STYLES+DAILY_NOTES_CSS+R6_STYLES),h("header",{className:"sg-header"},h("div",{className:"sg-header-row sg-header-row-primary"},h(GITHUB_FEEDBACK_ENABLED?"a":"div",{className:"sg-brand",href:GITHUB_FEEDBACK_ENABLED?STAR_REPOSITORY_URL:void 0,target:GITHUB_FEEDBACK_ENABLED?"_blank":void 0,rel:GITHUB_FEEDBACK_ENABLED?"noopener noreferrer":void 0},h(StrataGateMark),h("span",{className:"sg-brand-copy"},h("span",{className:"sg-brand-title"},h("span",{className:"sg-brand-name"},"StrataGate"),overview.pluginVersion&&overview.pluginVersion!=="unknown"?h("span",{className:"sg-brand-version"},"v"+overview.pluginVersion):null),onChooseSidebar?h(SidebarPlacementPrompt,{onChooseSidebar,usePluginSettings}):null)),h("div",{className:"sg-header-end"},h("div",{className:"sg-project"},h("span",{className:"sg-project-label"},"\u5F53\u524D\u5DE5\u4F5C\u533A"),h("select",{className:"sg-project-select",value:namespace,onChange:event3=>setNamespace(event3.target.value),"aria-label":"\u5F53\u524D\u5DE5\u4F5C\u533A"},(overview.namespaces||[]).map(item=>h("option",{key:item.namespace,value:item.namespace},projectName(item,workspaceTitles))))),GITHUB_FEEDBACK_ENABLED?h(HeaderStarLink):null)),h("nav",{className:"sg-tabs","aria-label":"\u8BB0\u5FC6\u89C6\u56FE"},[["overview","\u603B\u89C8"],["profile","\u5E38\u9A7B\u753B\u50CF"],["short","\u4F1A\u8BDD\u8BB0\u5FC6"],["daily","\u77ED\u671F\u8BB0\u5FC6"],["long","\u957F\u671F\u8BB0\u5FC6"],["more","\u66F4\u591A"]].map(([id2,label])=>h("button",{key:id2,type:"button",className:"sg-tab "+(section===id2?"active":""),"aria-current":section===id2?"page":void 0,onClick:()=>goSection(id2)},TAB_SWATCH[id2]?h("i",{key:"sw",className:"sg-tab-swatch "+TAB_SWATCH[id2],"aria-hidden":"true"}):null,label))),error3?h("div",{className:"sg-error"},h("div",{className:"sg-error-title"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u5B8C\u6574\u8BB0\u5FC6"),h("div",null,"\u5DF2\u663E\u793A\u80FD\u591F\u8BFB\u53D6\u7684\u5185\u5BB9\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u52A0\u8F7D\u3002"),h("details",null,h("summary",null,"\u6280\u672F\u8BE6\u60C5"),h("div",{className:"sg-code"},error3))):null,view.name==="root"&&selected?.duplicateRepair?.needsReview>0?h("button",{type:"button",className:"sg-dup-entry",onClick:()=>setView({name:"duplicates"})},h(DuplicateIcon,{size:23}),h("span",null,h("strong",null,selected.duplicateRepair.needsReview+" \u7EC4\u76F8\u4F3C\u8BB0\u5FC6\uFF0C\u7B49\u4F60\u786E\u8BA4"),h("small",null,"\u5BF9\u6BD4\u5185\u5BB9\uFF0C\u9009\u62E9\u4FDD\u7559\u54EA\u5F20\u6216\u5408\u5E76\u53CC\u65B9\u8BC1\u636E")),h(DuplicateIcon,{kind:"next"})):null,h("section",{key:section,className:"sg-view","aria-label":"StrataGate \u8BB0\u5FC6\u5185\u5BB9"},section==="long"&&selected&&loadedNamespaceRef.current===namespace?h(React.Fragment,null,h("div",{key:"long-browser",hidden:view.name!=="root"},h(LongTermPage,{graphSettings:overview.graphSettings,extractionGap:selected?.longTermExtractionGap===!0,key:namespace,events:data4.events,eventPage:data4.pagination?.events,graph:data4.graph,project,query,setQuery,openEvent,namespace,focusNodeId:graphFocusNodeId,onFocusHandled:consumeGraphFocus,topicDirectory:data4.topicDirectory,onDirectoryChanged:refreshDirectory,onOpenDreamingSession,refresh,active:view.name==="root"})),view.name==="root"?null:content):content),h("footer",{className:"sg-footer"},h("span",null,"StrataGate-AgentMemory \xB7 MIT"),h("span",{className:"sg-footer-links"},h("a",{href:STAR_REPOSITORY_URL,target:"_blank",rel:"noopener noreferrer"},"GitHub \u4ED3\u5E93")," \xB7 ",h("a",{href:ISSUE_URL,target:"_blank",rel:"noopener noreferrer"},"\u63D0 Issue")," \xB7 ",h("a",{href:STAR_REPOSITORY_URL+"/releases",target:"_blank",rel:"noopener noreferrer"},"\u66F4\u65B0\u8BB0\u5F55")))))}function MemoryPanel(props){return h("div",{className:"sg-memory-panel",style:{flex:"1 1 0%",minHeight:0,width:"100%",overflowY:"auto",overflowX:"hidden"}},h(MemoryPage,props))}function readSidebarPromptState(){try{return String(globalThis.localStorage?.getItem(SIDEBAR_PROMPT_STORAGE_KEY)||"")}catch{return""}}function writeSidebarPromptState(value){try{globalThis.localStorage?.setItem(SIDEBAR_PROMPT_STORAGE_KEY,value)}catch{}}function StrataGatePanelIcon({size:size3=20}){return h("svg",{width:size3,height:size3,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,focusable:!1,className:"sg-sidebar-panel-icon",style:{display:"block",flexShrink:0}},h("path",{opacity:.28,strokeWidth:1.4,d:"M3 12V4a1 1 0 0 1 1-1h8"}),h("path",{opacity:.55,d:"M6 15V7a1 1 0 0 1 1-1h9"}),h("rect",{x:9,y:9,width:12,height:13,rx:1.8}),h("path",{d:"M12 13h6M12 17h4"}))}function SidebarPlacementPrompt({onChooseSidebar,usePluginSettings}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[visible,setVisible]=React.useState(()=>readSidebarPromptState()!=="dismissed"),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState("");if(!visible||settings?.value?.showSidebarEntry===!0||settings?.writable!==!0)return null;let dismiss=()=>{writeSidebarPromptState("dismissed"),setVisible(!1)},chooseSidebar=async()=>{setBusy(!0),setError("");try{if(!await onChooseSidebar?.()){setError("\u672A\u80FD\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002");return}writeSidebarPromptState("sidebar"),setVisible(!1)}catch{setError("\u672A\u80FD\u4FDD\u5B58\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002")}finally{setBusy(!1)}};return h(React.Fragment,null,h("style",null,SIDEBAR_PROMPT_STYLES),h("span",{className:"sg-sidebar-placement-prompt",role:"region","aria-label":"StrataGate \u4FA7\u680F\u5165\u53E3\u63D0\u793A"},h("span",{className:"sg-sidebar-placement-text"},"\u4ECE\u5DE6\u4FA7\u680F\u5FEB\u901F\u6253\u5F00\u8BB0\u5FC6"),h("button",{type:"button",className:"sg-sidebar-placement-action",disabled:busy,onClick:()=>{chooseSidebar()}},"\u653E\u5230\u5DE6\u4FA7\u680F"),h("button",{type:"button",className:"sg-sidebar-placement-close","aria-label":"\u5173\u95ED\u4FA7\u680F\u5165\u53E3\u63D0\u793A",title:"\u4E0D\u518D\u63D0\u9192",disabled:busy,onClick:dismiss},"\xD7"),error3?h("span",{role:"alert"},error3):null))}let disposeFeedbackLinkNavigation=null;function apply2(ctx){let slots=ctx.get("slots");if(!slots)return;let configForms=ctx.get("configForms"),settingsScope=ctx.get("settingsScope"),pluginSettingsScope=configForms?configForms.get("stratagate-memory"):settingsScope?settingsScope.bind({namespace:"stratagate-memory"}):null,setSidebarEntry=async visible=>{if(!pluginSettingsScope||!await pluginSettingsScope.set("showSidebarEntry",visible))return!1;if(!visible){let layout4=ctx.get("layout");layout4?.activePanelId===MEMORY_PANEL_ID&&layout4.selectPanel?.(null)}return!0},warnCitationFailure=(part,error3)=>{if(!(typeof console>"u"||typeof console.warn!="function"))try{console.warn("[StrataGate] "+part+" registration failed; memory settings remain available.",error3)}catch{}};slots.inject("settings.section",()=>slots.register({name:"settings.section",id:"stratagate-memory",order:32,label:()=>"StrataGate-AgentMemory",inject:()=>({hooks:{pluginSettings:pluginSettingsScope},setMemoryModel:pluginSettingsScope?selection=>pluginSettingsScope.set("memoryModel",selection):null,setEffort:pluginSettingsScope?mode=>pluginSettingsScope.set("structuredReasoningEffort",mode):null,setDailyEnabled:pluginSettingsScope?enabled=>pluginSettingsScope.set("dailyNotesEnabled",enabled):null,setDailyInjectionDays:pluginSettingsScope?days=>pluginSettingsScope.set("dailyNotesInjectionDays",days):null,setDailyTimeZone:pluginSettingsScope?zone=>zone?pluginSettingsScope.set("dailyNotesTimeZone",zone):pluginSettingsScope.unset("dailyNotesTimeZone"):null,resetEffort:pluginSettingsScope?()=>pluginSettingsScope.unset("structuredReasoningEffort"):null,setStrataGateStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showStrataGateStatus",visible):null,setShortTermStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showShortTermStatus",visible):null,setRetrievalStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showRetrievalStatus",visible):null,setSidebarEntry:pluginSettingsScope?setSidebarEntry:null})},props=>h(FeedbackSettingsPage,{...props,onChooseSidebar:async()=>{let layout4=ctx.get("layout");return typeof layout4?.selectPanel!="function"||!await setSidebarEntry(!0)?!1:(layout4.selectPanel(MEMORY_PANEL_ID),props.close?.(),!0)},onOpenDreamingSession:sessionId=>{let navigation=ctx.get("uiWorkspace");if(typeof navigation?.openSession!="function")throw new Error("\u5F53\u524D DSH \u672A\u63D0\u4F9B\u4F1A\u8BDD\u5BFC\u822A\uFF0C\u8BF7\u5347\u7EA7\u5BBF\u4E3B\u540E\u91CD\u8BD5");navigation.openSession(sessionId),props.close?.()}})));let memoryPanelInject=()=>({setMemoryModel:pluginSettingsScope?selection=>pluginSettingsScope.set("memoryModel",selection):null,...pluginSettingsScope?{hooks:{pluginSettings:pluginSettingsScope}}:{},setEffort:pluginSettingsScope?mode=>pluginSettingsScope.set("structuredReasoningEffort",mode):null,setDailyEnabled:pluginSettingsScope?enabled=>pluginSettingsScope.set("dailyNotesEnabled",enabled):null,setDailyInjectionDays:pluginSettingsScope?days=>pluginSettingsScope.set("dailyNotesInjectionDays",days):null,setDailyTimeZone:pluginSettingsScope?zone=>zone?pluginSettingsScope.set("dailyNotesTimeZone",zone):pluginSettingsScope.unset("dailyNotesTimeZone"):null,resetEffort:pluginSettingsScope?()=>pluginSettingsScope.unset("structuredReasoningEffort"):null,setStrataGateStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showStrataGateStatus",visible):null,setShortTermStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showShortTermStatus",visible):null,setRetrievalStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showRetrievalStatus",visible):null,setSidebarEntry:pluginSettingsScope?setSidebarEntry:null,onOpenDreamingSession:sessionId=>{let navigation=ctx.get("uiWorkspace");if(typeof navigation?.openSession!="function")throw new Error("\u5F53\u524D DSH \u672A\u63D0\u4F9B\u4F1A\u8BDD\u5BFC\u822A\uFF0C\u8BF7\u5347\u7EA7\u5BBF\u4E3B\u540E\u91CD\u8BD5");navigation.openSession(sessionId)}});try{slots.inject("main",()=>slots.register({name:"main",key:MEMORY_PANEL_ID,order:20,inject:memoryPanelInject},MemoryPanel)),slots.inject("sidebar.panellist",()=>{let removeEntry=null,syncSidebar=()=>{let snapshot=pluginSettingsScope?.getSnapshot?.();if(snapshot?.status==="loading")return;let visible=snapshot?.value?.showSidebarEntry===!0;visible&&!removeEntry?removeEntry=slots.register({name:"sidebar.panellist",id:MEMORY_PANEL_ID,order:20,label:()=>"StrataGate \u8BB0\u5FC6"},StrataGatePanelIcon)||(()=>{}):!visible&&removeEntry&&(removeEntry(),removeEntry=null)},unsubscribe=pluginSettingsScope?.subscribe?.(syncSidebar);return syncSidebar(),()=>{unsubscribe?.(),removeEntry?.(),removeEntry=null}})}catch(error3){warnCitationFailure("sidebar entry",error3)}try{let uiConversation=ctx.get("uiConversation");uiConversation&&(uiConversation.events.register(memoryCitationsDefinition),ensureCitationStyles(),slots.inject("conversation.chat.turnTail",()=>{try{return slots.register({name:"conversation.chat.turnTail",id:"stratagate-memory-citations",select:selectMemoryCitations,inject:()=>({...pluginSettingsScope?{hooks:{pluginSettings:pluginSettingsScope}}:{},onOpenGraphNode:(namespace,nodeId)=>navigateToGraphNode(ctx,namespace,nodeId)})},MemoryCitationTail)}catch(error3){return warnCitationFailure("chat turn tail",error3),()=>{}}}))}catch(error3){warnCitationFailure("chat citations",error3)}if(typeof document<"u"){disposeFeedbackLinkNavigation?.();let disposeLinkNavigation=installFeedbackLinkNavigation(ctx),disposeDeepLink=openFeedbackDeepLink(ctx),disposeGraphDeepLink=openGraphNodeDeepLink(ctx);disposeFeedbackLinkNavigation=()=>{disposeLinkNavigation(),disposeDeepLink(),disposeGraphDeepLink()}}}return exports.name="stratagate-dsh",exports.inject=["slots","uiConversation"],exports.apply=apply2,module.exports}});})();
1359
+ `;function DuplicateIcon({kind="cards",size:size3=17}){let paths={cards:"M7 3H3v14h10v-4M7 3v10h10V3H7Z",check:"m4 10 4 4 8-8",info:"M10 9v5m0-8v.2M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0Z",back:"m12 5-5 5 5 5",next:"m8 5 5 5-5 5",merge:"M4 3v3c0 3 6 3 6 6v5m6-14v3c0 3-6 3-6 6m-3 2 3 3 3-3"};return h("svg",{width:size3,height:size3,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},h("path",{d:paths[kind]||paths.cards}))}function DuplicateEvidence({namespace,card,hideSummary=!1}){let[result,setResult]=React.useState(null),[error3,setError]=React.useState(""),[attempt,setAttempt]=React.useState(0);return React.useEffect(()=>{let active=!0;return setResult(null),setError(""),api2("sources",{namespace,eventId:card.id}).then(value=>{active&&setResult(value)}).catch(reason=>{active&&setError(String(reason.message||reason))}),()=>{active=!1}},[namespace,card.id,attempt]),h("section",{className:"sg-dup-source","aria-label":"\u5B8C\u6574\u8BB0\u5FC6\u4E0E\u6765\u6E90"},h("h4",null,hideSummary?"\u539F\u59CB\u6765\u6E90":"\u5B8C\u6574\u8BB0\u5FC6\u4E0E\u6765\u6E90"),hideSummary?null:h("p",{className:"sg-dup-summary"},card.summary),error3?h("div",{role:"alert"},error3,h("button",{type:"button",className:"sg-dup-button",onClick:()=>setAttempt(value=>value+1)},"\u91CD\u8BD5\u8BFB\u53D6\u6765\u6E90")):result?result.messages?.length?h("div",{className:"sg-citation-messages"},result.messages.map(message=>h("div",{key:message.id,className:"sg-citation-message"},h("span",{className:"sg-citation-message-role"},(message.role||"Recorded")+(message.createdAt?" \xB7 "+exactTime(message.createdAt):"")),String(message.content||"")))):h("p",null,"\u5F53\u524D\u6CA1\u6709\u53EF\u663E\u793A\u7684\u539F\u59CB\u6765\u6E90\u6D88\u606F\u3002"):h("p",{role:"status"},"\u6B63\u5728\u8BFB\u53D6\u6765\u6E90\u2026"))}function DuplicateCard({card,letter,selected,onSelect,unavailable,disabled,namespace,fullContent=!1,selectionMade=!1}){let[expanded,setExpanded]=React.useState(!1),[showSource,setShowSource]=React.useState(!1),sourcePosition=React.useRef(null);(React.useLayoutEffect||React.useEffect)(()=>{if(showSource||!sourcePosition.current)return;let{trigger,ancestors,top,left}=sourcePosition.current;trigger?.focus?.({preventScroll:!0});for(let saved of ancestors)saved.node.scrollTop=saved.top,saved.node.scrollLeft=saved.left;window.scrollTo?.(left,top),sourcePosition.current=null},[showSource]);let toggleSource=event3=>{if(!showSource){let ancestors=[];for(let node=event3.currentTarget.parentElement;node;node=node.parentElement)node.scrollHeight>node.clientHeight&&ancestors.push({node,top:node.scrollTop,left:node.scrollLeft});sourcePosition.current={trigger:event3.currentTarget,ancestors,top:window.scrollY||0,left:window.scrollX||0}}setShowSource(value=>!value)};if(!card)return h("article",{className:"sg-dup-card"},h("div",{className:"sg-dup-card-body"},h("h3",null,"\u8BB0\u5FC6 "+letter),h("p",null,"\u539F\u5361\u5DF2\u4E0D\u53EF\u7528")));let status={active:"\u5F53\u524D\u6709\u6548",superseded:"\u5DF2\u88AB\u66FF\u4EE3",archived:"\u5DF2\u5F52\u6863",forgotten:"\u5DF2\u9057\u5FD8"},criticality={routine:"\u4E00\u822C\u8BB0\u5FC6",preference:"\u504F\u597D",identity:"\u4E2A\u4EBA\u7ECF\u5386",safety:"\u91CD\u8981\u7EA6\u675F"},scope={user:"\u4E2A\u4EBA",project:"\u9879\u76EE",session:"\u672C\u6B21\u4F1A\u8BDD"},temporal=card.temporal||{},date=temporal.happenedStart||temporal.originalText;return h("article",{className:"sg-dup-card"+(selected?" selected":"")+(card.status==="archived"?" archived":"")},h("label",{className:"sg-dup-choice"},onSelect?h("input",{id:"sg-retain-"+card.id,type:"radio",name:"duplicate-retained",checked:selected,disabled:disabled||!!unavailable,onChange:onSelect,"aria-label":"\u53EA\u4FDD\u7559 "+letter+"\uFF1A"+card.title}):h("span",{className:"sg-dup-letter"},letter),h("span",null,onSelect?"\u53EA\u4FDD\u7559 "+letter:"\u8BB0\u5FC6 "+letter),h("em",null,status[card.status]||"")),h(onSelect?"label":"div",{className:"sg-dup-card-body",htmlFor:onSelect?"sg-retain-"+card.id:void 0},h("h3",null,card.title),h("div",{className:"sg-dup-meta"},date?h("span",null,date):null,h("span",null,criticality[card.criticality]||"\u4E00\u822C\u8BB0\u5FC6"),h("span",null,scope[card.scope]||card.scope||"\u4E2A\u4EBA"),card.weight?.pinned?h("span",null,"\u5DF2\u7F6E\u9876"):null),h("p",{className:"sg-dup-summary"+(!expanded&&!fullContent?" collapsed":"")},card.summary),!fullContent&&card.summary?.length>160?h("button",{type:"button",className:"sg-dup-expand",onClick:()=>setExpanded(!expanded),"aria-expanded":expanded},expanded?"\u6536\u8D77\u5168\u6587":"\u5C55\u5F00\u5168\u6587"):null,h("dl",{className:"sg-dup-evidence"},card.quotes?.length?h(React.Fragment,null,h("dt",null,"\u5F15\u8BED"),h("dd",null,card.quotes.map(quote=>h("blockquote",{key:quote},quote)))):null,temporal.participants?.length?h(React.Fragment,null,h("dt",null,"\u53C2\u4E0E\u8005"),h("dd",null,temporal.participants.join("\u3001"))):null,card.tags?.length?h(React.Fragment,null,h("dt",null,"\u6807\u7B7E"),h("dd",null,card.tags.join(" \xB7 "))):null)),fullContent&&onSelect&&!unavailable?null:h("div",{className:"sg-dup-card-footer"},fullContent&&onSelect?null:h("button",{type:"button",className:"sg-dup-button","aria-expanded":showSource,onClick:toggleSource},showSource?"\u6536\u8D77\u6765\u6E90\uFF0C\u8FD4\u56DE\u5BF9\u6BD4":"\u67E5\u770B "+(card.sourceMessageIds?.length||0)+" \u6761\u6765\u6E90\u4E0E\u5B8C\u6574\u8BB0\u5FC6"),unavailable?h("small",null,unavailable):null),fullContent&&onSelect?h("p",{className:"sg-dup-selection-result"},selectionMade?selected?"\u786E\u8BA4\u540E\u4FDD\u7559\u8FD9\u5F20":"\u786E\u8BA4\u540E\u5C06\u8FD9\u5F20\u5F52\u6863 \xB7 \u539F\u6587\u548C\u6765\u6E90\u4ECD\u4FDD\u7559":"\u70B9\u51FB\u4FDD\u7559\u8FD9\u5F20\u8BB0\u5FC6"):null,showSource||fullContent&&onSelect?h(React.Fragment,null,h(DuplicateEvidence,{namespace,card,hideSummary:fullContent}),showSource?h("button",{type:"button",className:"sg-dup-button text",onClick:toggleSource},"\u6536\u8D77\u6765\u6E90\uFF0C\u8FD4\u56DE\u5BF9\u6BD4"):null):null)}function DuplicatePair({item,busy,namespace,onResolve,onPrepareDraft,onTakeOver,draftState,onDraftState}){let[selectedId,setSelectedId]=React.useState(draftState?.selectedId||""),[mode,setMode]=React.useState(draftState?.mode||""),[draft,setDraft]=React.useState(draftState?.draft||item.draft||{title:"",summary:""}),[draftError,setDraftError]=React.useState(""),[draftBusy,setDraftBusy]=React.useState(!1),[dirty,setDirty]=React.useState(!!draftState?.dirty),[regenerate,setRegenerate]=React.useState(!1),[saveError,setSaveError]=React.useState(""),[draftOrigin,setDraftOrigin]=React.useState(draftState?.draftOrigin||(item.draft?"AI \u5408\u5E76\u7A3F \xB7 \u8BF7\u6838\u5BF9":"\u624B\u52A8\u586B\u5199\u5408\u5E76\u7A3F")),stageHeading=React.useRef(null);React.useEffect(()=>{onDraftState?.({selectedId,mode,draft,draftOrigin,dirty})},[selectedId,mode,draft,draftOrigin,dirty]),React.useEffect(()=>{mode&&(stageHeading.current?.focus({preventScroll:!0}),stageHeading.current?.scrollIntoView({block:"nearest"}))},[mode]);let archived=item.outcome==="merged"||item.outcome==="selected",retained=item.outcome==="kept"&&(item.aiResolved||item.userReviewed),done=archived||retained,awaitingAI=item.outcome==="pending",selected=selectedId===item.leftId?item.left:selectedId===item.rightId?item.right:null,letter=selectedId===item.leftId?"A":"B",mergeId=item.recommendedKeepId||(item.choices?.right?.canMerge?item.rightId:item.leftId),mergeCard=mergeId===item.leftId?item.left:item.right,selection=item.choices?.[selectedId===item.leftId?"left":"right"],draftValid=!!(draft.title.trim()&&draft.summary.trim()),generateDraft=async(force=!1)=>{if(dirty&&!force){setRegenerate(!0);return}setRegenerate(!1),setDraftBusy(!0),setDraftError("");try{let result2=await onPrepareDraft(item,force);if(!result2?.draft)throw new Error("AI \u5C1A\u672A\u751F\u6210\u5B8C\u6574\u7A3F\uFF0C\u4F60\u53EF\u4EE5\u624B\u52A8\u586B\u5199\u6216\u7A0D\u540E\u91CD\u8BD5\u3002");setDraft(result2.draft),setDirty(!1),setDraftOrigin("AI \u5408\u5E76\u7A3F \xB7 \u8BF7\u6838\u5BF9")}catch(reason){setDraftError(String(reason.message||reason).replace(/\s*[((]duplicates[))]$/,""))}finally{setDraftBusy(!1)}},start=value=>{setMode(value),setSaveError(""),value==="select"&&setSelectedId(""),value==="merge"&&!draft.title&&!draft.summary&&onPrepareDraft&&generateDraft()},save=async()=>{setSaveError("");try{await onResolve(mode==="both"?"keep":mode,item,mode==="select"?selectedId:mode==="merge"?mergeId:void 0,mode==="merge"?draft:void 0)}catch(reason){setSaveError("\u4F60\u7684\u9009\u62E9\u548C\u7F16\u8F91\u5DF2\u4FDD\u7559\u3002"+String(reason.message||reason).replace(/\s*[((]duplicates[))]$/,""))}},cards=(selectable=!1,originals=!1)=>h("div",{className:"sg-dup-comparison",role:selectable?"radiogroup":void 0,"aria-label":selectable?"\u9009\u62E9\u8981\u4FDD\u7559\u7684\u8BB0\u5FC6":"\u53CC\u65B9\u5B8C\u6574\u8BB0\u5FC6"},[originals&&item.originalLeft||item.left,originals&&item.originalRight||item.right].map((card,i2)=>h(DuplicateCard,{key:card?.id||i2,card,letter:i2?"B":"A",namespace,fullContent:!0,selected:selectable&&selectedId===card?.id,selectionMade:!!selectedId,onSelect:selectable?()=>{setSelectedId(i2?item.rightId:item.leftId),setSaveError("")}:null,disabled:busy||draftBusy,unavailable:selectable?item.choices?.[i2?"right":"left"]?.selectBlockedReason:""}))),back=()=>{setMode(""),setSaveError(""),setRegenerate(!1)},result=done&&item.keepId===item.leftId?item.left:item.right,consequences=h("section",{className:"sg-dup-consequences"},h("h3",null,"\u786E\u8BA4\u540E\u4F1A\u53D1\u751F\u4EC0\u4E48"),h("dl",{className:"sg-dup-result"},h("dt",null,"\u65E5\u5E38\u68C0\u7D22"),h("dd",null,mode==="merge"?"\u663E\u793A\u4E0A\u9762\u7684\u5B8C\u6574\u5408\u5E76\u7A3F\u3002":mode==="both"?"\u4E24\u5F20\u8BB0\u5FC6\u5206\u522B\u4FDD\u7559\uFF0C\u5185\u5BB9\u548C\u6765\u6E90\u4E0D\u53D8\u3002":"\u53EA\u663E\u793A\u8BB0\u5FC6 "+letter+" \xB7 "+(selected?.title||"")),h("dt",null,"\u539F\u59CB\u8BB0\u5F55"),h("dd",null,mode==="merge"?"\u53CC\u65B9\u5904\u7406\u524D\u7684\u5185\u5BB9\u3001\u6765\u6E90\u548C\u5386\u53F2\u5173\u8054\u4FDD\u7559\uFF0C\u53EF\u5728\u5DF2\u5904\u7406\u8BB0\u5F55\u4E2D\u6838\u5BF9\u3002":mode==="both"?"\u53CC\u65B9\u539F\u5361\u5747\u4FDD\u7559\u3002":"\u8BB0\u5FC6 "+(letter==="A"?"B":"A")+" \u8F6C\u5165\u5386\u53F2\uFF1B\u72EC\u6709\u5185\u5BB9\u4E0D\u4F1A\u5408\u5165\u6240\u9009\u5361\uFF0C\u539F\u6587\u548C\u6765\u6E90\u4ECD\u4FDD\u7559\u3002"),mode==="merge"&&mergeCard?.temporal?.happenedStart?h(React.Fragment,null,h("dt",null,"\u65E5\u671F"),h("dd",null,"\u68C0\u7D22\u65E5\u671F\u6CBF\u7528 "+mergeCard.temporal.happenedStart+"\uFF1B\u8BF7\u6838\u5BF9\u6B63\u6587\u4E2D\u7684\u539F\u5B89\u6392\u3001\u540E\u7EED\u53D8\u5316\u4E0E\u5F53\u524D\u4E8B\u5B9E\u3002")):null,h("dt",null,"\u540E\u7EED\u8C03\u6574"),h("dd",null,"\u53EF\u5728\u201C\u5DF2\u5904\u7406\u201D\u67E5\u770B\u7ED3\u679C\uFF1B\u6CA1\u6709\u540E\u7EED\u51B2\u7A81\u65F6\u53EF\u64A4\u9500\u3002")));return h("section",{className:"sg-dup-pair","aria-label":"\u8BB0\u5FC6\u5BF9\u6BD4\u4E0E\u5904\u7406","aria-busy":busy||draftBusy},h("nav",{className:"sg-dup-steps","aria-label":"\u5904\u7406\u6B65\u9AA4"},["\u5BF9\u6BD4\u8BB0\u5FC6","\u6838\u5BF9\u7ED3\u679C","\u5B8C\u6210"].map((label,i2)=>h("span",{key:label,"aria-current":(done?2:mode?1:0)===i2?"step":void 0},i2+1+" "+label))),done?h(React.Fragment,null,h("h3",{className:"sg-dup-stage-title"},archived?item.outcome==="merged"?"\u5DF2\u6574\u7406\u6210\u4E00\u5F20\u5B8C\u6574\u8BB0\u5FC6":"\u5DF2\u4FDD\u7559\u8BB0\u5FC6 "+(item.keepId===item.leftId?"A":"B"):"\u5DF2\u5206\u522B\u4FDD\u7559\u4E24\u5F20\u8BB0\u5FC6"),h("p",{className:"sg-dup-reason"},item.aiResolved?"\u7531 AI \u81EA\u52A8\u5904\u7406 \xB7 "+item.reason:item.reason),archived?h(React.Fragment,null,h("div",{className:"sg-dup-result-card"},h("small",null,"\u4ECA\u540E\u4F7F\u7528\u7684\u8BB0\u5FC6"),h("h3",null,result?.title),h("p",{className:"sg-dup-summary"},result?.summary)),h("details",null,h("summary",null,item.originalLeft&&item.originalRight?"\u67E5\u770B\u5904\u7406\u524D\u7684\u4E24\u5F20\u8BB0\u5FC6\u4E0E\u6765\u6E90":"\u67E5\u770B\u4E24\u5F20\u8BB0\u5FC6\u4E0E\u6765\u6E90\uFF08\u6309\u5F53\u524D\u8BB0\u5F55\uFF09"),cards(!1,!0))):cards(),h("div",{className:"sg-dup-actions"},h("p",null,"\u64A4\u9500\u524D\u4F1A\u68C0\u67E5\u540E\u7EED\u53D8\u5316\uFF0C\u907F\u514D\u8986\u76D6\u65B0\u6570\u636E\u3002"),item.undoId?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onResolve("undo",item).catch(()=>{})},"\u64A4\u9500\u672C\u6B21\u5904\u7406"):retained?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onTakeOver?.(item)},"\u91CD\u65B0\u5904\u7406\u8FD9\u7EC4"):h("p",null,"\u6B64\u8BB0\u5F55\u521B\u5EFA\u4E8E\u652F\u6301\u64A4\u9500\u4E4B\u524D\u3002"))):awaitingAI?h(React.Fragment,null,h("div",{className:"sg-dup-reason"},h("strong",null,"AI \u4F1A\u5148\u5224\u65AD\u8FD9\u7EC4\u8BB0\u5FC6"),h("p",null,"\u5224\u65AD\u660E\u786E\u7684\u81EA\u52A8\u5904\u7406\u5E76\u7559\u4E0B\u8BB0\u5F55\uFF1B\u4E0D\u786E\u5B9A\u6216\u5904\u7406\u5931\u8D25\u7684\uFF0C\u624D\u4F1A\u8FDB\u5165\u201C\u9700\u8981\u4F60\u5224\u65AD\u201D\u3002\u4E24\u5F20\u539F\u5361\u76EE\u524D\u5747\u4FDD\u7559\u3002"),h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onTakeOver(item)},"\u6211\u6765\u5904\u7406\u8FD9\u7EC4")),cards()):mode?h(React.Fragment,null,h("button",{type:"button",className:"sg-dup-button text sg-dup-back",disabled:busy||draftBusy,onClick:back},h(DuplicateIcon,{kind:"back",size:14}),"\u8FD4\u56DE\u5BF9\u6BD4"),h("div",{className:"sg-dup-stage-heading"},h("h3",{ref:stageHeading,tabIndex:-1},mode==="merge"?"\u628A\u53CC\u65B9\u4FE1\u606F\u6574\u7406\u6210\u4E00\u5F20\u8BB0\u5FC6":mode==="select"?"\u53EA\u4FDD\u7559\u54EA\u5F20\u8BB0\u5FC6\uFF1F":"\u5206\u522B\u4FDD\u7559\u8FD9\u4E24\u5F20\u8BB0\u5FC6"),h("p",null,mode==="merge"?"\u53CC\u65B9\u6709\u6548\u4FE1\u606F\u4F1A\u6574\u7406\u8FDB\u5B8C\u6574\u7A3F\uFF0C\u4FDD\u5B58\u524D\u4F60\u53EF\u4EE5\u4FEE\u6539\u6807\u9898\u548C\u6B63\u6587\u3002":mode==="select"?"\u4E24\u5F20\u5B8C\u6574\u5185\u5BB9\u90FD\u5728\u4E0B\u65B9\uFF0C\u70B9\u51FB\u8981\u4FDD\u7559\u7684\u5361\u7247\u3002\u53E6\u4E00\u5F20\u8F6C\u5165\u5386\u53F2\uFF0C\u5185\u5BB9\u4E0D\u4F1A\u81EA\u52A8\u5408\u5E76\u3002":"\u9002\u7528\u4E8E\u4E0D\u540C\u4E8B\u4EF6\u3001\u524D\u540E\u8FDB\u5C55\uFF0C\u6216\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u7684\u60C5\u51B5\u3002")),mode==="merge"?h(React.Fragment,null,item.historyNotice||item.mergeWarning?h("p",{className:"sg-dup-reason"},item.historyNotice||item.mergeWarning):null,!item.canMerge&&item.mergeBlockedReason?h("p",{className:"sg-dup-notice error",role:"note"},item.mergeBlockedReason," \u4ECD\u53EF\u5728\u4E0B\u65B9\u6574\u7406\u8349\u7A3F\uFF0C\u539F\u5361\u4E0D\u4F1A\u81EA\u52A8\u6539\u52A8\u3002"):null,h("div",{className:"sg-dup-editor"},h("div",{className:"sg-dup-draft-heading"},h("strong",null,draftBusy?"AI \u6B63\u5728\u6574\u7406\u5408\u5E76\u7A3F\u2026":draftOrigin),h("button",{type:"button",className:"sg-dup-button",disabled:busy||draftBusy,onClick:()=>generateDraft(!dirty)},"\u91CD\u65B0\u8BA9 AI \u6574\u7406")),regenerate?h("div",{className:"sg-dup-reason"},"\u91CD\u65B0\u751F\u6210\u4F1A\u66FF\u6362\u4F60\u5F53\u524D\u7F16\u8F91\u7684\u6807\u9898\u548C\u6B63\u6587\u3002",h("div",{className:"sg-dup-actions"},h("button",{type:"button",className:"sg-dup-button",onClick:()=>setRegenerate(!1)},"\u4FDD\u7559\u5F53\u524D\u7F16\u8F91"),h("button",{type:"button",className:"sg-dup-button",onClick:()=>generateDraft(!0)},"\u66FF\u6362\u4E3A\u65B0\u7A3F"))):null,draftError?h("p",{role:"alert",className:"sg-dup-notice error"},draftError," \u539F\u5361\u672A\u6539\u52A8\uFF0C\u53EF\u76F4\u63A5\u586B\u5199\u4E0B\u65B9\u5B8C\u6574\u8BB0\u5FC6\u3002"):null,draftBusy?h("div",{className:"sg-dup-draft-skeleton",role:"status","aria-label":"\u6B63\u5728\u751F\u6210\u5408\u5E76\u7A3F"},[1,2,3,4].map(i2=>h("span",{key:i2}))):h(React.Fragment,null,h("label",null,"\u5408\u5E76\u540E\u7684\u6807\u9898",h("input",{type:"text","aria-label":"\u5408\u5E76\u540E\u7684\u6807\u9898",value:draft.title,maxLength:200,disabled:busy,onChange:event3=>{setDraft({...draft,title:event3.target.value}),setDirty(!0),setDraftOrigin("\u4F60\u5DF2\u7F16\u8F91")}})),h("label",null,"\u5408\u5E76\u540E\u7684\u5B8C\u6574\u6B63\u6587",h("textarea",{"aria-label":"\u5408\u5E76\u540E\u7684\u5B8C\u6574\u6B63\u6587",value:draft.summary,maxLength:12e3,rows:8,disabled:busy,placeholder:"\u5199\u51FA\u4F60\u5E0C\u671B\u4ECA\u540E\u8BB0\u4F4F\u7684\u5B8C\u6574\u5185\u5BB9\uFF0C\u4FDD\u7559\u65F6\u95F4\u3001\u6761\u4EF6\u548C\u4E0D\u786E\u5B9A\u6027\u3002",onChange:event3=>{setDraft({...draft,summary:event3.target.value}),setDirty(!0),setDraftOrigin("\u4F60\u5DF2\u7F16\u8F91")}})),h("p",{className:"sg-dup-constraint"},draftValid?"\u5C06\u6309\u6B64\u5168\u6587\u4FDD\u5B58\uFF0C\u539F\u59CB\u8BC1\u636E\u53E6\u884C\u4FDD\u7559\u3002":"\u8BF7\u586B\u5199\u5B8C\u6574\u6807\u9898\u548C\u6B63\u6587\u540E\u518D\u4FDD\u5B58\u3002"))),h("details",null,h("summary",null,"\u5C55\u5F00\u53CC\u65B9\u539F\u5361\uFF0C\u6838\u5BF9\u5408\u5E76\u7A3F"),cards())):cards(mode==="select"),mode==="select"&&selected?.status==="superseded"?h("p",{className:"sg-dup-reason",role:"note"},"\u4F60\u9009\u62E9\u7684\u662F\u5386\u53F2\u7248\u672C "+letter+"\u3002\u4FDD\u5B58\u540E\u5B83\u4F1A\u91CD\u65B0\u6210\u4E3A\u6709\u6548\u8BB0\u5FC6\uFF0C\u53E6\u4E00\u5F20\u7684\u65B0\u589E\u5185\u5BB9\u4E0D\u4F1A\u5408\u5165\uFF1B\u8BF7\u786E\u8BA4\u8FD9\u7B26\u5408\u4F60\u7684\u610F\u601D\u3002"):null,mode==="select"&&selected&&selection?.selectBlockedReason?h("p",{className:"sg-dup-notice error",role:"note"},selection.selectBlockedReason):null,mode!=="select"||selected?consequences:h("p",{className:"sg-dup-constraint"},"\u5C1A\u672A\u9009\u62E9\u3002\u8BF7\u5BF9\u6BD4\u4E0A\u65B9\u5B8C\u6574\u5185\u5BB9\uFF0C\u518D\u9009\u62E9\u4FDD\u7559 A \u6216 B\u3002"),saveError?h("p",{className:"sg-dup-notice error",role:"alert"},saveError):null,h("div",{className:"sg-dup-actions"},h("p",null,"\u53EA\u6709\u786E\u8BA4\u4FDD\u5B58\uFF0C\u624D\u4F1A\u66F4\u65B0\u8BB0\u5FC6\u3002"),h("div",null,h("button",{type:"button",className:"sg-dup-button",disabled:busy||draftBusy,onClick:back},"\u8FD4\u56DE\u5BF9\u6BD4"),h("button",{type:"button",className:"sg-dup-button primary",disabled:busy||draftBusy||mode==="merge"&&!draftValid||mode==="select"&&!selected,onClick:save},busy?"\u6B63\u5728\u4FDD\u5B58\u2026":saveError?"\u91CD\u8BD5\u4FDD\u5B58":mode==="merge"?"\u786E\u8BA4\u4FDD\u5B58\u5408\u5E76\u7A3F":mode==="both"?"\u786E\u8BA4\u4FDD\u7559\u4E24\u5F20":selected?"\u786E\u8BA4\u53EA\u4FDD\u7559 "+letter:"\u8BF7\u9009\u62E9 A \u6216 B")))):h(React.Fragment,null,h("p",{className:"sg-dup-reason"},h("strong",null,"\u4E3A\u4EC0\u4E48\u9700\u8981\u4F60\u5224\u65AD"),item.reason),cards(),h("h3",{className:"sg-dup-stage-title"},"\u4F60\u5E0C\u671B\u600E\u4E48\u5904\u7406\uFF1F"),h("div",{className:"sg-dup-options"},[["merge","\u5408\u5E76\u53CC\u65B9\u5185\u5BB9","AI \u6574\u7406\u5B8C\u6574\u7A3F\uFF0C\u4F60\u53EF\u4EE5\u7F16\u8F91\u540E\u518D\u786E\u8BA4\u3002"],["select","\u53EA\u4FDD\u7559\u4E00\u5F20","\u67E5\u770B\u5B8C\u6574\u5185\u5BB9\uFF0C\u9009\u62E9 A \u6216 B\uFF0C\u53E6\u4E00\u5F20\u8F6C\u5165\u5386\u53F2\u3002"],["both","\u4FDD\u7559\u4E24\u5F20","\u5206\u522B\u4FDD\u7559\uFF0C\u7ED3\u675F\u8FD9\u7EC4\u6574\u7406\u3002"]].map(([value,title,description])=>h("button",{key:value,type:"button",className:"sg-dup-option",disabled:busy||draftBusy,onClick:()=>start(value)},h(DuplicateIcon,{kind:value==="merge"?"merge":"cards"}),h("strong",null,title),h("span",null,description)))),h("p",{className:"sg-dup-constraint"},"\u9009\u62E9\u540E\u5148\u6838\u5BF9\u5904\u7406\u7ED3\u679C\uFF0C\u786E\u8BA4\u4FDD\u5B58\u524D\u4E0D\u4F1A\u6539\u52A8\u539F\u5361\u3002")))}function DuplicateReviewPage({namespace,repair,onBack,openEvent,refresh}){let[page,setPage]=React.useState({items:[],offset:0,limit:20,total:0}),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState(""),[notice,setNotice]=React.useState(""),[loading,setLoading]=React.useState(!0),[index,setIndex]=React.useState(0),[queue,setQueue]=React.useState("review"),[lastAction,setLastAction]=React.useState(null),draftCache=React.useRef(new Map),focusPair=React.useRef(null),committedRead=React.useRef(!1),readFailure=reason=>(committedRead.current?"\u5904\u7406\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u8BFB\u53D6\u7ED3\u679C\u5931\u8D25\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u7ED3\u679C\u3002":"")+String(reason.message||reason),requestId=React.useRef(0),load=(offset=0,targetQueue=queue,focus=focusPair.current)=>{let id2=++requestId.current;return setLoading(!0),api2("duplicates",{namespace,offset,limit:20,queue:targetQueue,...focus?{focusLeft:focus.leftId,focusRight:focus.rightId}:{}}).then(value=>{id2===requestId.current&&(setPage(value),setIndex(i2=>value.focusIndex??Math.min(i2,Math.max(0,value.items.length-1))),focusPair.current=null,committedRead.current=!1)}).finally(()=>{id2===requestId.current&&setLoading(!1)})};React.useEffect(()=>{let active=!0,id2=++requestId.current;setLoading(!0),setError("");let focus=focusPair.current;return api2("duplicates",{namespace,offset:page.namespace===namespace&&page.queue===queue?page.offset:0,limit:20,queue,...focus?{focusLeft:focus.leftId,focusRight:focus.rightId}:{}}).then(value=>{active&&id2===requestId.current&&(setPage(value),setIndex(i2=>value.focusIndex??(page.namespace===namespace&&page.queue===queue?Math.min(i2,Math.max(0,value.items.length-1)):0)),focusPair.current=null,committedRead.current=!1)}).catch(reason=>{active&&id2===requestId.current&&setError(readFailure(reason))}).finally(()=>{active&&id2===requestId.current&&setLoading(!1)}),()=>{active=!1}},[namespace,queue,JSON.stringify(repair)]);let pairInput=item=>item?{leftId:item.leftId,rightId:item.rightId,leftFingerprint:item.leftFingerprint,rightFingerprint:item.rightFingerprint,exact:item.exact,similarity:item.similarity}:void 0,takeOver=item=>(setBusy(!0),setError(""),api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"takeover",pair:pairInput(item)})}).then(()=>(focusPair.current=item,setQueue("review"),setNotice("\u5DF2\u7531\u4F60\u63A5\u7BA1\uFF0CAI \u4E0D\u518D\u81EA\u52A8\u5904\u7406\u8FD9\u7EC4\u3002"),refresh())).catch(reason=>setError(String(reason.message||reason))).finally(()=>setBusy(!1))),prepareDraft=(item,regenerate=!1)=>(setBusy(!0),api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"draft",pair:pairInput(item),regenerate})}).finally(()=>setBusy(!1))),control=(action,item,keepId,draft)=>{let committed=!1;setBusy(!0),setError(""),setNotice("");let pair=item?{leftId:item.leftId,rightId:item.rightId,leftFingerprint:item.leftFingerprint,rightFingerprint:item.rightFingerprint,exact:item.exact,similarity:item.similarity}:void 0;return api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action,pair,keepId,draft,undoId:action==="undo"?item?.undoId:void 0})}).then(result=>{if(committed=!0,committedRead.current=!0,action==="undo"){for(let key of draftCache.current.keys())key.startsWith(namespace+":"+item.leftId+":"+item.rightId+":")&&draftCache.current.delete(key);focusPair.current=item,setQueue("review")}return setLastAction(result.undoId?{...item,undoId:result.undoId}:null),["merge","select","keep"].includes(action)&&(focusPair.current=item,setQueue("history")),setNotice(action==="rescan"?"\u5DF2\u91CD\u65B0\u626B\u63CF\uFF0CAI \u4F1A\u5148\u5904\u7406\u5019\u9009\u3002":action==="undo"?"\u5DF2\u64A4\u9500\uFF0C\u6062\u590D\u4E86\u5904\u7406\u524D\u7684\u5185\u5BB9\u3001\u72B6\u6001\u548C\u5173\u8054\u3002":action==="merge"?"\u5DF2\u4FDD\u5B58\u5B8C\u6574\u5408\u5E76\u7A3F\uFF0C\u53CC\u65B9\u8BC1\u636E\u4E0E\u6765\u6E90\u5DF2\u4FDD\u7559\u3002":action==="select"?"\u5DF2\u4FDD\u7559\u6240\u9009\u8BB0\u5FC6\uFF0C\u53E6\u4E00\u5F20\u5DF2\u5F52\u6863\uFF0C\u5185\u5BB9\u672A\u6DF7\u5408\u3002":"\u5DF2\u786E\u8BA4\u4FDD\u7559\u4E24\u5F20\u3002"),refresh()}).then(()=>(action==="rescan"&&setIndex(0),action==="undo"?load(0,"review",item):["merge","select","keep"].includes(action)?load(0,"history",item):load(action==="rescan"?0:page.offset))).catch(reason=>{if(committed){setError("\u5904\u7406\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u8BFB\u53D6\u7ED3\u679C\u5931\u8D25\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u7ED3\u679C\u3002"+String(reason.message||reason));return}throw["merge","select","keep"].includes(action)||setError(String(reason.message||reason)),reason}).finally(()=>setBusy(!1))},navigate=direction=>{if(setError(""),setNotice(""),index+direction>=0&&index+direction<page.items.length){setIndex(index+direction);return}let id2=++requestId.current;setLoading(!0),api2("duplicates",{namespace,offset:Math.max(0,page.offset+direction*page.limit),limit:20,queue}).then(value=>{id2===requestId.current&&(setPage(value),setIndex(direction>0?0:Math.max(0,value.items.length-1)))}).catch(reason=>{id2===requestId.current&&setError(String(reason.message||reason))}).finally(()=>{id2===requestId.current&&setLoading(!1)})},current=page.items[Math.min(index,Math.max(0,page.items.length-1))],draftKey=current?namespace+":"+current.leftId+":"+current.rightId+":"+current.leftFingerprint+":"+current.rightFingerprint:"";return h(React.Fragment,null,h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-duplicates"},h("header",{className:"sg-dup-heading"},h("div",null,h("h2",null,"\u91CD\u590D\u8BB0\u5FC6\u6574\u7406"),h("p",null,"AI \u5148\u5224\u65AD\u5E76\u6574\u7406\u3002\u8FD9\u91CC\u53EA\u9700\u8981\u4F60\u5904\u7406\u62FF\u4E0D\u51C6\u7684\u8BB0\u5FC6\u3002")),h(DuplicateIcon,{size:25})),h("nav",{className:"sg-dup-queues","aria-label":"\u6574\u7406\u961F\u5217"},[["review","\u9700\u8981\u4F60\u5224\u65AD",repair?.needsReview||0],["ai","\u7B49\u5F85 AI",repair?.awaitingAI||0],["history","\u5DF2\u5904\u7406",(repair?.merged||0)+(repair?.selected||0)+(repair?.retained||0)-(repair?.needsReview||0)+(repair?.failed||0)]].map(([value,label,count])=>h("button",{key:value,type:"button",className:"sg-dup-button","aria-pressed":queue===value,disabled:busy,onClick:()=>{setQueue(value),setError(""),setIndex(0)}},label+" "+Math.max(0,count)))),error3?h("div",{role:"alert",className:"sg-dup-notice error"},error3,h("button",{type:"button",className:"sg-dup-button text",disabled:busy||loading,onClick:()=>{setError(""),load(page.offset).catch(reason=>setError(readFailure(reason)))}},"\u91CD\u65B0\u8BFB\u53D6")):null,notice?h("div",{role:"status",className:"sg-dup-notice","aria-live":"polite"},notice,lastAction?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>{control("undo",lastAction).catch(()=>{})}},"\u64A4\u9500\u672C\u6B21\u5904\u7406"):null):null,!error3&&(loading||page.namespace!==namespace||page.queue!==queue)?h("div",{className:"sg-dup-comparison",role:"status","aria-label":"\u6B63\u5728\u8BFB\u53D6\u91CD\u590D\u8BB0\u5FC6"},h("div",{className:"sg-dup-skeleton"}),h("div",{className:"sg-dup-skeleton"})):current&&page.namespace===namespace&&page.queue===queue?h(React.Fragment,null,h("nav",{className:"sg-dup-navigation","aria-label":"\u5207\u6362\u5019\u9009\u7EC4"},h("button",{type:"button",className:"sg-dup-button","aria-label":"\u4E0A\u4E00\u7EC4",disabled:busy||page.offset+index<=0,onClick:()=>navigate(-1)},h(DuplicateIcon,{kind:"back",size:14})),h("select",{value:index,disabled:busy,onChange:event3=>{setIndex(Number(event3.target.value)),setNotice("")},"aria-label":"\u5F53\u524D\u5019\u9009\u7EC4"},page.items.map((item,i2)=>h("option",{key:item.leftId+":"+item.rightId,value:i2},item.left?.title||item.right?.title||"\u539F\u5361\u5DF2\u4E0D\u53EF\u7528"))),h("span",{className:"sg-dup-count"},page.offset+index+1+" / "+page.total),h("button",{type:"button",className:"sg-dup-button","aria-label":"\u4E0B\u4E00\u7EC4",disabled:busy||page.offset+index+1>=page.total,onClick:()=>navigate(1)},h(DuplicateIcon,{kind:"next",size:14}))),h(DuplicatePair,{key:namespace+current.leftId+current.rightId+current.leftFingerprint+current.rightFingerprint+current.outcome+!!current.userReviewed,item:current,busy,namespace,onResolve:control,onPrepareDraft:prepareDraft,onTakeOver:takeOver,draftState:draftCache.current.get(draftKey),onDraftState:value=>{draftCache.current.set(draftKey,value),draftCache.current.size>50&&draftCache.current.delete(draftCache.current.keys().next().value)}})):error3?null:h("section",{className:"sg-dup-empty"},h(DuplicateIcon,{kind:"check",size:28}),h("strong",null,queue==="review"?"\u6682\u65F6\u6CA1\u6709\u9700\u8981\u4F60\u5224\u65AD\u7684\u8BB0\u5FC6":queue==="ai"?"\u6CA1\u6709\u7B49\u5F85 AI \u7684\u5019\u9009":"\u8FD8\u6CA1\u6709\u5904\u7406\u8BB0\u5F55"),h("p",null,queue==="review"?"AI \u80FD\u5904\u7406\u7684\u4F1A\u81EA\u52A8\u5B8C\u6210\u3002\u4F60\u53EF\u4EE5\u5728\u201C\u5DF2\u5904\u7406\u201D\u67E5\u770B\u7ED3\u679C\u3002":"\u626B\u63CF\u548C\u5904\u7406\u8FDB\u5EA6\u4F1A\u5728\u5BF9\u5E94\u961F\u5217\u4E2D\u663E\u793A\u3002")),h("details",{className:"sg-dup-tools"},h("summary",null,"\u91CD\u65B0\u68C0\u67E5\u8BB0\u5FC6\u5E93"),h("p",null,"\u6309\u5F53\u524D\u89C4\u5219\u91CD\u65B0\u626B\u63CF\u3002\u540E\u7EED\u5224\u65AD\u53EF\u80FD\u4F7F\u7528\u5F53\u524D\u6A21\u578B\uFF0C\u5DF2\u5B8C\u6210\u7684\u626B\u63CF\u4E0D\u4F1A\u5728\u6BCF\u6B21\u542F\u52A8\u65F6\u91CD\u590D\u6267\u884C\u3002"),h("button",{type:"button",className:"sg-dup-button",disabled:busy||loading,onClick:()=>{control("rescan").catch(()=>{})}},"\u91CD\u65B0\u626B\u63CF\u4E0E\u5224\u65AD"))))}function SystemPage({selected,blocks,onBack,backLabel="\u66F4\u591A",refresh,onDuplicates}){let processing=blocks.filter(block=>block.status==="processing").length,[refreshing,setRefreshing]=React.useState(!1),[feedback,setFeedback]=React.useState({kind:"",text:""}),repair=selected.duplicateRepair,checkStatus=()=>{let before=processingFingerprint(selected);return setRefreshing(!0),setFeedback({kind:"",text:"\u6B63\u5728\u8BFB\u53D6\u2026"}),refresh({propagateError:!0}).then(next2=>{let updated=next2?.overview?.namespaces?.find(item=>item.namespace===selected.namespace);setFeedback({kind:"done",text:updated&&processingFingerprint(updated)!==before?"\u72B6\u6001\u5DF2\u66F4\u65B0":"\u72B6\u6001\u6CA1\u6709\u53D8\u5316"})}).catch(reason=>{setFeedback({kind:"failed",text:"\u8BFB\u53D6\u5931\u8D25\uFF1A"+String(reason?.message||reason)})}).finally(()=>setRefreshing(!1))};return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u7CFB\u7EDF\u72B6\u6001"),h("p",null,"\u4EC5\u5728\u8FD9\u91CC\u5C55\u793A\u8BB0\u5FC6\u5904\u7406\u7684\u5DE5\u7A0B\u72B6\u6001")),h("div",{className:"sg-pipeline"},[["Block \u6570\u91CF",selected.blocks],["\u5F85\u5904\u7406\u4EFB\u52A1",processing],["\u5931\u8D25\u4EFB\u52A1",selected.failedJobs],["\u6700\u8FD1\u6574\u7406\u65F6\u95F4",formatTime(selected.lastActivityAt)],["Event \u63D0\u53D6",selected.failedJobDetails?.some(item=>item.kind==="event-extraction")?"\u6709\u5931\u8D25":"\u6B63\u5E38"],["\u56FE\u8C31\u6295\u5F71",selected.failedJobDetails?.some(item=>item.kind==="graph-projection")?"\u6709\u5931\u8D25":"\u6B63\u5E38"]].map(([label,value])=>h("div",{key:label,className:"sg-stage"},h("span",null,label),h("span",{className:"sg-stage-value "+(label==="\u5931\u8D25\u4EFB\u52A1"&&value?"failed":"waiting")},String(value))))),repair?h("p",{className:"sg-setting-note",role:"status"},"\u5386\u53F2\u91CD\u590D\u8BB0\u5FC6\u6574\u7406"+(repair.status==="completed"?"\u5DF2\u5B8C\u6210":"\u8FDB\u884C\u4E2D")+"\uFF1A\u5DF2\u626B\u63CF "+repair.scannedEvents+" \u5F20\u5361\uFF0C\u5F52\u6863\u91CD\u590D\u5361 "+repair.merged+" \u5F20\uFF1B\u5176\u4F59\u4FDD\u7559\u3002"+(repair.failed?" \u90E8\u5206\u5224\u65AD\u672A\u5B8C\u6210\uFF0C\u539F\u5361\u5DF2\u4FDD\u7559\u3002":"")):null,h("button",{type:"button",className:"sg-quiet-button",onClick:onDuplicates},"\u67E5\u770B\u91CD\u590D\u5019\u9009\u4E0E\u5904\u7406\u539F\u56E0"),h("button",{type:"button",className:"sg-quiet-button",disabled:refreshing,onClick:()=>{checkStatus()},style:{marginTop:"14px"}},refreshing?"\u21BB \u6B63\u5728\u8BFB\u53D6\u2026":"\u21BB \u91CD\u65B0\u68C0\u67E5"),feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null)}function AuditPage({audit,auditPage,namespace,onBack,backLabel="\u66F4\u591A"}){let pagedAudit=usePagedMemory({namespace,kind:"audit",initialItems:audit,initialPage:auditPage,fallbackLimit:100});return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u4F7F\u7528\u8BB0\u5F55"),h("p",null,"\u957F\u671F\u8BB0\u5FC6\u88AB\u4F7F\u7528\u7684\u65F6\u95F4\u4E0E\u6765\u6E90")),pagedAudit.items.length?pagedAudit.items.map(item=>{let value=item.audit||{};return h("details",{key:item.id,className:"sg-audit"},h("summary",null,h("strong",null,"\u4F7F\u7528\u4E86 "+((item.events||[]).length+(item.elements||[]).length)+" \u6761\u8BB0\u5FC6"),h("span",{className:"sg-muted"}," \xB7 "+formatTime(item.createdAt))),h("div",{className:"sg-audit-body"},h("div",null,(item.events||[]).map(event3=>event3.title).join("\u3001")||(item.elements||[]).map(element3=>element3.name).join("\u3001")||"\u65E7\u7248\u4F7F\u7528\u8BB0\u5F55"),h("div",{className:"sg-tech-row sg-audit-evidence"},h("span",{className:"sg-muted"},"\u6765\u6E90\u4F1A\u8BDD"),h("span",{className:"sg-code"},value.sessionId||"\u672A\u8BB0\u5F55")),value.turn!==void 0?h("div",{className:"sg-tech-row"},h("span",{className:"sg-muted"},"Turn"),h("span",null,value.turn)):null))}):h(Empty,{title:"\u8FD8\u6CA1\u6709\u4F7F\u7528\u8BB0\u5F55",copy:"AI \u5728\u56DE\u7B54\u4E2D\u91C7\u7528\u957F\u671F\u8BB0\u5FC6\u540E\u4F1A\u8BB0\u5F55\u5728\u8FD9\u91CC\u3002"}),h(Pagination,{page:pagedAudit.page,loading:pagedAudit.loading,error:pagedAudit.error,onOffset:pagedAudit.loadOffset}))}function RawPage({data:data4,selected,onBack,backLabel="\u66F4\u591A"}){let groups=[["Block raw",data4.blocks,data4.pagination?.blocks?.total],["Event raw",data4.events,data4.pagination?.events?.total],["Graph raw",data4.graph],["Usage raw",data4.audit,data4.pagination?.audit?.total],["\u6A21\u578B\u54CD\u5E94",selected.successfulModelResponses||[]]];return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u539F\u59CB\u6570\u636E"),h("p",null,"\u4F9B\u6392\u67E5\u95EE\u9898\u4F7F\u7528\u7684\u5185\u90E8\u5B57\u6BB5\u4E0E JSON")),groups.map(([label,value,total])=>h("details",{key:label,className:"sg-raw-group"},h("summary",null,label+" ("+(Array.isArray(value)&&Number(total)>value.length?"\u5DF2\u52A0\u8F7D "+value.length+" / \u5171 "+total:Array.isArray(value)?value.length:(value.nodes?.length||0)+(value.edges?.length||0))+")"),h("pre",{className:"sg-raw-json sg-code"},JSON.stringify(value,null,2)))))}let profileGroups=[["\u79F0\u547C\u4E0E\u8BED\u8A00",[["userPreferredName","\u600E\u4E48\u79F0\u547C\u4F60",100],["assistantPreferredName","\u52A9\u624B\u53EB\u4EC0\u4E48",100],["preferredLanguage","\u56DE\u7B54\u7528\u4EC0\u4E48\u8BED\u8A00",100],["reasoningLanguage","\u601D\u8003\u8FC7\u7A0B\u7528\u4EC0\u4E48\u8BED\u8A00",100]]],["\u5730\u70B9",[["defaultLocation","\u5E38\u9A7B\u5730\u5740",200],["currentCity","\u73B0\u5728\u5728\u54EA",100],["homeCity","\u5E38\u9A7B\u57CE\u5E02\uFF08\u539F\u6709\u5B57\u6BB5\uFF09",100]]],["\u600E\u4E48\u56DE\u7B54\u4F60",[["responsePreferences","\u56DE\u590D\u65B9\u5F0F",1e3],["standingInstructions","\u4E00\u76F4\u8981\u9075\u5B88\u7684\u8981\u6C42",1e3]]],["\u5173\u4E8E\u4F60",[["userBackground","\u80CC\u666F",1500],["longTermGoals","\u957F\u671F\u76EE\u6807",1e3]]],["\u5176\u4ED6",[["persistentNotes","\u5176\u4ED6\u8981\u4E00\u76F4\u8BB0\u4F4F\u7684",1200]]]],PROFILE_EMPTY_HINTS={userPreferredName:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5C0F\u7A0B",assistantPreferredName:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u6A59\u5B50",preferredLanguage:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E2D\u6587",reasoningLanguage:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E2D\u6587",responsePreferences:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5148\u7ED9\u7ED3\u8BBA\uFF0C\u518D\u5C55\u5F00",standingInstructions:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u6539\u4EE3\u7801\u524D\u5148\u8BF4\u65B9\u6848",defaultLocation:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5317\u4EAC\u5E02\u6D77\u6DC0\u533A",currentCity:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E0A\u6D77",homeCity:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u676D\u5DDE",userBackground:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u8F6F\u4EF6\u5DE5\u7A0B\u5E08\uFF0C\u719F\u6089 Python",longTermGoals:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4ECA\u5E74\u5B8C\u6210\u4E00\u7BC7\u8BBA\u6587",persistentNotes:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u9879\u76EE\u7EDF\u4E00\u4F7F\u7528 pnpm"},profileFieldNames=profileGroups.flatMap(([,fields])=>fields.map(([field])=>field)),PROFILE_LIMIT_DEFAULT=6e3,PROFILE_LIMIT_MIN=2e3,PROFILE_LIMIT_MAX=12e3,profileTotalLimit=value=>{let candidate=Number(value?._limits?.totalMaxLength);return Number.isSafeInteger(candidate)&&candidate>0?candidate:PROFILE_LIMIT_DEFAULT},profileTotalLength=value=>profileFieldNames.reduce((sum,field)=>sum+Array.from(value?.[field]||"").length,0),profileRightColumn=new Set(["\u600E\u4E48\u56DE\u7B54\u4F60","\u5173\u4E8E\u4F60","\u5176\u4ED6"]),formatCount=value=>Number(value||0).toLocaleString("en-US");function sameProfile(left,right){return profileFieldNames.every(field=>left?.[field]===right?.[field]&&left?._revisions?.[field]===right?._revisions?.[field])&&profileTotalLimit(left)===profileTotalLimit(right)}function ProfilePage(){let[profile,setProfile]=usePageMemoryState(profilePageMemory,"profile",null),[editing,updateEditing]=usePageMemoryState(profilePageMemory,"editing",null),setEditing=update2=>{let previous=profilePageMemory.get("editing"),next2=typeof update2=="function"?update2(previous):update2;next2?profileFieldDrafts.set(next2.field,next2):previous&&profileFieldDrafts.delete(previous.field),updateEditing(next2)},[saving,setSaving]=React.useState(!1),[syncStatus,setSyncStatus]=React.useState("\u66F4\u65B0\u4E2D\u2026"),[error3,setError]=React.useState(""),[conflicts,setConflicts]=usePageMemoryState(profilePageMemory,"conflicts",{}),conflict=!!conflicts[editing?.field],setConflict=(value,field=profilePageMemory.get("editing")?.field)=>{field&&setConflicts(current=>({...current,[field]:value}))},[saveResults,setSaveResults]=usePageMemoryState(profilePageMemory,"saveResults",{}),[reading,setReading]=React.useState(!1),session=React.useRef(0),action=React.useRef(null),actionTimeout=React.useRef(null),readController=React.useRef(null),savedTimers=React.useRef(new Map),requestVersion=React.useRef(0),refreshRef=React.useRef(null),clearSavedTimer=field=>{window.clearTimeout(savedTimers.current.get(field)),savedTimers.current.delete(field)},showSaved=submission=>{clearSavedTimer(submission.field),setSaveResults(current=>({...current,[submission.field]:{kind:"saved",submission,flash:!0}}));let timer=window.setTimeout(()=>{savedTimers.current.get(submission.field)===timer&&(savedTimers.current.delete(submission.field),setSaveResults(current=>current[submission.field]?.submission===submission?{...current,[submission.field]:{...current[submission.field],flash:!1}}:current))},2e3);savedTimers.current.set(submission.field,timer)};React.useEffect(()=>{let active=!0,timer=null,controller=null,stopRequest=()=>{controller&&controller.abort(),controller=null,readController.current=null},check=({valid:valid2=()=>!0,onResult}={})=>{if(!active||document.hidden)return;if(timer!==null&&window.clearTimeout(timer),timer=null,stopRequest(),action.current){timer=window.setTimeout(check,5e3);return}let version2=++requestVersion.current,requestController=new AbortController;return controller=requestController,readController.current=requestController,api2("profile",{},{method:"GET",signal:requestController.signal}).then(latest=>{if(!(!active||document.hidden||version2!==requestVersion.current||!valid2())){if(!profileFieldNames.every(field=>typeof latest?.[field]=="string")||!latest?._revisions)throw new Error("\u753B\u50CF\u8BFB\u53D6\u54CD\u5E94\u4E0D\u5B8C\u6574");setProfile(current=>sameProfile(current,latest)?current:latest),setSyncStatus("\u5DF2\u662F\u6700\u65B0"),setError(""),onResult?.(latest)}}).catch(reason=>{active&&version2===requestVersion.current&&valid2()&&reason?.name!=="AbortError"&&(setSyncStatus("\u8BFB\u53D6\u5931\u8D25"),setError(String(reason?.message||reason)))}).finally(()=>{controller===requestController&&(controller=null,readController.current=null),active&&!document.hidden&&version2===requestVersion.current&&(timer=window.setTimeout(check,5e3))})};refreshRef.current=check;let onVisibilityChange=()=>{timer!==null&&window.clearTimeout(timer),timer=null,document.hidden?(++requestVersion.current,stopRequest()):check()};return document.addEventListener("visibilitychange",onVisibilityChange),check(),()=>{let submission=action.current?.submission;submission&&!profilePageMemory.get("saveResults")?.[submission.field]&&setSaveResults(current=>({...current,[submission.field]:{kind:"unknown",submission}})),active=!1,++session.current,++requestVersion.current,refreshRef.current=null,timer!==null&&window.clearTimeout(timer),stopRequest(),action.current?.abort(),action.current=null,window.clearTimeout(actionTimeout.current),actionTimeout.current=null,savedTimers.current.forEach(id2=>window.clearTimeout(id2)),savedTimers.current.clear(),setSaveResults(current=>Object.fromEntries(Object.entries(current).map(([field,result])=>[field,result.kind==="saved"?{...result,flash:!1}:result]))),document.removeEventListener("visibilitychange",onVisibilityChange)}},[]);let resetEdit=field=>{++session.current,++requestVersion.current,readController.current?.abort(),setReading(!1),field&&(setConflict(!1,field),clearSavedTimer(field),setSaveResults(current=>{let next2={...current};return delete next2[field],next2})),refreshRef.current?.()},beginEdit=field=>{resetEdit(profileFieldDrafts.has(field)?void 0:field),setEditing(profileFieldDrafts.get(field)||{field,draft:profile[field]||"",baseValue:profile[field]||"",baseRevision:profile._revisions?.[field]||0})},reloadField=()=>{if(!editing||saving||reading)return;let id2=session.current;setReading(!0),refreshRef.current?.({valid:()=>session.current===id2,onResult:latest=>{setEditing(current=>current?{...current,draft:latest[current.field],baseValue:latest[current.field],baseRevision:latest._revisions[current.field]}:null),setConflict(!1),setSaveResults(current=>{let next2={...current};return delete next2[editing.field],next2})}})?.finally(()=>{session.current===id2&&setReading(!1)})},save=()=>{if(!editing||action.current||saving||reading||saveResults[editing.field]?.kind==="unknown")return;if(conflict||profile[editing.field]!==editing.baseValue||profile._revisions?.[editing.field]!==editing.baseRevision){setConflict(!0);return}let submission={...editing},id2=session.current,controller=new AbortController;controller.submission=submission,action.current=controller;let valid2=()=>session.current===id2&&action.current===controller;setSaving(!0),setSaveResults(current=>{let next2={...current};return delete next2[submission.field],next2}),++requestVersion.current,readController.current?.abort();let timeout=window.setTimeout(()=>controller.abort(),15e3);actionTimeout.current=timeout,api2("profile",{},{method:"PATCH",signal:controller.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({field:submission.field,value:submission.draft,expectedValue:submission.baseValue,expectedRevision:submission.baseRevision})}).then(result=>{if(valid2()){if(!profileFieldNames.every(field=>typeof result?.snapshot?.[field]=="string")||!Number.isSafeInteger(result.snapshot?._revisions?.[submission.field]))throw new Error("\u753B\u50CF\u4FDD\u5B58\u54CD\u5E94\u4E0D\u5B8C\u6574");setProfile(result.snapshot),setEditing(null),setConflict(!1,submission.field),showSaved(submission)}}).catch(reason=>{if(!valid2())return;let message=String(reason?.message||reason);if(reason?.status===409||message.includes("\u521A\u521A\u5728\u5176\u4ED6\u4F4D\u7F6E\u66F4\u65B0")){setConflict(!0);return}let unknown=!reason?.status||[408,502,504].includes(reason.status),invalid=[400,413,422].includes(reason?.status),maximum=profileGroups.flatMap(([,fields])=>fields).find(([field])=>field===submission.field)?.[2],detail=/Persistent Profile exceeds/.test(message)?"\u753B\u50CF\u603B\u5B57\u7B26\u6570\u4E0D\u80FD\u8D85\u8FC7 6000\uFF0C\u8BF7\u7F29\u77ED\u5185\u5BB9\u3002":/exceeds \d+ characters/.test(message)?"\u6B64\u5B57\u6BB5\u4E0D\u80FD\u8D85\u8FC7 "+maximum+" \u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED\u5185\u5BB9\u3002":message;setSaveResults(current=>({...current,[submission.field]:{kind:unknown?"unknown":invalid?"invalid":"failed",submission,detail}}))}).finally(()=>{window.clearTimeout(timeout),actionTimeout.current===timeout&&(actionTimeout.current=null),valid2()&&(action.current=null,setSaving(!1),refreshRef.current?.())})},checkSave=result=>{if(reading||action.current)return;let id2=session.current,{submission}=result;setReading(!0),refreshRef.current?.({valid:()=>session.current===id2,onResult:latest=>{latest[submission.field]===submission.draft&&Number.isSafeInteger(latest._revisions[submission.field])&&latest._revisions[submission.field]>submission.baseRevision&&(showSaved(submission),setEditing(current=>current?.field===submission.field?current.draft===submission.draft?null:{...current,baseValue:latest[submission.field],baseRevision:latest._revisions[submission.field]}:current),setConflict(!1,submission.field))}})?.finally(()=>{session.current===id2&&setReading(!1)})},total=profileTotalLength(profile),limit2=profileTotalLimit(profile);return h(React.Fragment,null,h("div",{className:"sg-pg-head"},h("h2",null,"\u5E38\u9A7B\u753B\u50CF"),h("span",{className:"sg-pg-tag"},h("i",{className:"sg-sw ink","aria-hidden":"true"}),"\u6BCF\u8F6E\u90FD\u5E26\u7ED9 AI \xB7 \u70B9\u4EFB\u610F\u4E00\u884C\u4FEE\u6539"),syncStatus==="\u8BFB\u53D6\u5931\u8D25"?h("span",{className:"sg-pg-end"},h("span",{className:"sg-profile-sync failed",role:"alert"},syncStatus)):null),error3?h("p",{className:"sg-profile-error",role:"alert"},error3):null,profile?h(React.Fragment,null,h("div",{className:"sg-cap-row"},h("div",{className:"sg-cap-bar",role:"img","aria-label":"\u5E38\u9A7B\u753B\u50CF\u5DF2\u7528 "+total+" \u5B57\uFF0C\u4E0A\u9650 "+formatCount(limit2)+" \u5B57"},h("i",{style:{width:Math.min(100,total/limit2*100)+"%"}})),h("span",{className:"sg-cap-num"},h("b",null,formatCount(total)),"/ "+formatCount(limit2)+" \u5B57")),h("div",{className:"sg-pf"},[["1",profileGroups.filter(([title])=>!profileRightColumn.has(title))],["2",profileGroups.filter(([title])=>profileRightColumn.has(title))]].map(([column,groups])=>h("div",{key:column,className:"sg-pf-col","data-pf-stack":column},groups.map(([title,fields])=>h("section",{key:title,className:"sg-profile-group","aria-label":title},h("h4",null,title),h("ul",null,fields.filter(([field])=>field!=="homeCity"||profile.homeCity||profileFieldDrafts.has(field)).map(([field,label,maximum])=>{let value=profile[field]||"",isEditing=editing?.field===field,changedElsewhere=isEditing&&(value!==editing.baseValue||profile._revisions?.[field]!==editing.baseRevision),draftLength=isEditing?Array.from(editing.draft).length:0,nextTotal=total-Array.from(value).length+draftLength,result=saveResults[field],savedReadError=result?.kind==="saved"&&!!error3,savedFeedback=result?.kind==="saved"&&result.flash?h("span",{className:"sg-profile-saved",role:"status"},isEditing&&editing.draft!==result.submission.draft?"\u4E0A\u6B21\u63D0\u4EA4\u5DF2\u4FDD\u5B58":"\u5DF2\u4FDD\u5B58"):null,editor=isEditing?h("div",{className:"sg-profile-editor"},field==="userPreferredName"||field==="assistantPreferredName"||field==="preferredLanguage"||field==="reasoningLanguage"||field==="defaultLocation"||field==="homeCity"||field==="currentCity"?h("input",{id:"sg-profile-"+field,"aria-label":label,autoFocus:!0,disabled:saving,value:editing.draft,onChange:event3=>setEditing(current=>({...current,draft:event3.target.value}))}):h("textarea",{id:"sg-profile-"+field,"aria-label":label,autoFocus:!0,disabled:saving,value:editing.draft,onChange:event3=>setEditing(current=>({...current,draft:event3.target.value}))}),changedElsewhere||conflict?h("p",{className:"sg-profile-conflict",role:"alert"},"\u8BE5\u9879\u521A\u521A\u5728\u5176\u4ED6\u4F4D\u7F6E\u66F4\u65B0\u3002",h("button",{type:"button",className:"sg-profile-action",disabled:saving||reading,onClick:reloadField},"\u653E\u5F03\u8349\u7A3F\u5E76\u8F7D\u5165\u6700\u65B0\u5185\u5BB9")):null,result&&["failed","invalid","unknown"].includes(result.kind)?h("div",{className:"sg-profile-save-feedback sg-profile-save-feedback-"+result.kind,role:result.kind==="unknown"?"status":"alert"},h("p",null,result.kind==="unknown"?"\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u662F\u5426\u5DF2\u4FDD\u5B58\uFF0C\u8F93\u5165\u5185\u5BB9\u5DF2\u4FDD\u7559\u3002":"\u4FEE\u6539\u672A\u4FDD\u5B58\uFF0C\u8F93\u5165\u5185\u5BB9\u5DF2\u4FDD\u7559\u3002"),result.kind==="unknown"?h("button",{type:"button",className:"sg-profile-action",disabled:reading,onClick:()=>checkSave(result)},reading?"\u68C0\u67E5\u4E2D\u2026":"\u68C0\u67E5\u4FDD\u5B58\u7ED3\u679C"):result.kind==="invalid"?h("p",null,result.detail):null):null,h("div",{className:"sg-profile-editor-foot"},h("span",{className:"sg-profile-count"},formatCount(draftLength)+" / "+formatCount(maximum),draftLength>maximum?"\uFF0C\u8BF7\u7F29\u77ED\u81F3 "+formatCount(maximum)+" \u4E2A\u5B57\u7B26\u4EE5\u5185\u3002":nextTotal>limit2?"\uFF0C\u753B\u50CF\u603B\u5B57\u7B26\u6570\u4E0D\u80FD\u8D85\u8FC7 "+formatCount(limit2)+"\u3002":"",savedFeedback),h("div",{className:"sg-profile-actions"},h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:()=>{resetEdit(field),setEditing(null)}},"\u53D6\u6D88\u7F16\u8F91"),h("button",{type:"button",className:"sg-save-button",disabled:saving||reading||result?.kind==="unknown"||draftLength>maximum||nextTotal>limit2||editing.draft===editing.baseValue||changedElsewhere||conflict,onClick:save},saving?"\u4FDD\u5B58\u4E2D\u2026":result?.kind==="failed"?"\u91CD\u65B0\u4FDD\u5B58":"\u4FDD\u5B58")))):null;return h("li",{key:field,className:"sg-profile-row",onClick:isEditing?void 0:()=>{saving||beginEdit(field)}},h("div",{className:"sg-profile-summary"+(isEditing?" editing":"")},h("div",{className:"sg-profile-label-cell"},h("span",{className:"sg-profile-label"},label),editor||h("span",{className:"sg-profile-content"},h("button",{type:"button",className:"sg-profile-value "+(value?"":"empty"),title:value||PROFILE_EMPTY_HINTS[field],"aria-label":label+(value?"\uFF0C\u70B9\u51FB\u7F16\u8F91":"\uFF0C\u672A\u586B\u5199\uFF0C\u70B9\u51FB\u586B\u5199"),disabled:saving,onClick:event3=>{event3?.stopPropagation?.(),beginEdit(field)}},profileFieldDrafts.has(field)?"\u7EE7\u7EED\u7F16\u8F91\u8349\u7A3F":value||"\u672A\u586B\u5199"),savedFeedback)),isEditing?null:h("span",{className:"sg-profile-chev","aria-hidden":"true"},"\u203A"),h("button",{type:"button",className:"sg-profile-action",onClick:event3=>{event3?.stopPropagation?.(),beginEdit(field)},disabled:saving,"aria-hidden":isEditing||void 0},!isEditing&&profileFieldDrafts.has(field)?"\u7EE7\u7EED\u7F16\u8F91":value?"\u7F16\u8F91":"\u6DFB\u52A0")),savedReadError?h("p",{className:"sg-profile-save-feedback",role:"status"},h("span",null,"\u4FEE\u6539\u5DF2\u4FDD\u5B58\uFF0C\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6700\u65B0\u5185\u5BB9\u3002"),h("button",{type:"button",className:"sg-profile-action",disabled:reading,onClick:()=>refreshRef.current?.()},"\u91CD\u65B0\u8BFB\u53D6")):null)})))))))):h("p",null,"\u6B63\u5728\u8BFB\u53D6\u5E38\u9A7B\u753B\u50CF\u2026"))}let GRAPH_EXPLANATION="\u7531\u4E8E\u77E5\u8BC6\u56FE\u8C31\u529F\u80FD\u4E0E\u4E8B\u4EF6\u8BB0\u5F55\u548C\u4E3B\u9898\u76EE\u5F55\u6709\u90E8\u5206\u91CD\u590D\uFF0C\u8FD8\u9700\u8981\u989D\u5916\u6D88\u8017token\u7EF4\u62A4\u5B9E\u4F53\u5173\u7CFB\uFF0C\u5C06\u4F1A\u9ED8\u8BA4\u5173\u95ED\u77E5\u8BC6\u56FE\u8C31\u529F\u80FD\uFF0C\u5DF2\u7ECF\u751F\u6210\u7684\u56FE\u8C31\u6570\u636E\u4F1A\u4FDD\u7559\u3002",GRAPH_USAGE_HINT="\u63D0\u793A\uFF1A\u5982\u9700\u4F7F\u7528\uFF0C\u53EF\u4EE5\u5728\u957F\u671F\u8BB0\u5FC6\u9875\u9762\u70B9\u51FB\u201C\uFF0B\u201D\uFF0C\u6253\u5F00\u77E5\u8BC6\u56FE\u8C31\uFF0C\u529F\u80FD\u53EF\u4EE5\u6B63\u5E38\u4F7F\u7528\u3002",GRAPH_CONTROL_STYLES=".sg-graph-no-reminder{display:inline-flex;align-items:center;min-height:30px;padding:5px 8px;border:1px solid var(--sg-border);border-radius:6px;background:var(--sg-surface);color:var(--sg-muted);cursor:pointer}.sg-graph-no-reminder:hover{border-color:var(--sg-accent);color:var(--sg-accent);background:var(--sg-soft)}.sg-graph-no-reminder:disabled{cursor:not-allowed;opacity:.5}.sg-graph-notice-toggle{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:9px 0;border-top:1px solid var(--sg-border);border-bottom:1px solid var(--sg-border)}.sg-graph-notice-toggle>span{font-size:13px;font-weight:650}.sg-graph-menu{position:relative;z-index:31;display:inline-flex;align-items:center}.sg-long-tabs .sg-graph-menu-trigger{display:grid;place-items:center;align-self:center;flex:none;box-sizing:border-box;width:32px;height:32px;min-width:32px;min-height:32px;padding:0;border:0;border-radius:999px;background:transparent;color:var(--sg-muted);font-size:22px;line-height:1;cursor:pointer}.sg-graph-menu-trigger svg{display:block;width:16px;height:16px;flex:none}.sg-graph-menu-trigger:hover,.sg-graph-menu-trigger[aria-expanded=true]{background:var(--sg-soft);color:var(--sg-accent)}.sg-graph-menu-popover{position:absolute;z-index:32;right:0;left:auto;top:calc(100% + 8px);width:min(300px,calc(100vw - 32px));padding:10px;border:1px solid var(--sg-border);border-radius:10px;background:var(--sg-page);box-shadow:var(--sg-shadow);text-align:left}.sg-graph-menu-title{display:block;padding:0 2px 8px;color:var(--sg-text);font-size:13px;font-weight:650;line-height:1.4}.sg-graph-open{display:block;width:100%;margin-top:8px;padding:6px 2px 2px;border:0;border-top:1px solid var(--sg-border);background:none;color:var(--sg-text);font-size:12.5px;text-align:left;cursor:pointer}.sg-graph-open:hover{color:var(--sg-accent)}.sg-graph-copy{display:block;min-width:0}.sg-graph-title-row{display:flex;align-items:center;gap:6px;min-width:0}.sg-graph-copy b{display:block;font-size:13.5px;font-weight:650;color:var(--sg-text)}.sg-graph-copy span{display:block;margin-top:2px;font-size:11.5px;line-height:1.45;color:var(--sg-muted)}.sg-graph-title-row .sg-info-disclosure{display:inline-flex;flex:none} .sg-graph-copy .sg-graph-title-row{display:flex}.sg-graph-title-row .sg-info-trigger{width:18px;height:18px;font-size:12px}.sg-graph-menu-popover .sg-storage-card{padding:0;border:0;background:transparent}.sg-graph-menu-popover .sg-setting-note{font-size:11px;line-height:1.5}.sg-graph-dialog-heading{display:flex;align-items:center;justify-content:space-between;gap:12px}.sg-graph-dialog-heading h3{margin:0}.sg-graph-dialog-control{display:flex;align-items:center;gap:7px;color:var(--sg-muted);font-size:12px}";function GraphControlPanel({state={},refresh,page=!1,onGraphHidden,onOpenGraph}){let shouldShowNotice=!page&&state.enabled!==!0&&state.noticeSeen!==!0,[notice,setNotice]=React.useState(shouldShowNotice),[preview,setPreview]=React.useState(null),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState(""),[hideExplanation,setHideExplanation]=React.useState(!1),dialogRef=React.useRef(null);React.useEffect(()=>{setNotice(!page&&state.enabled!==!0&&state.noticeSeen!==!0)},[page,state.enabled,state.noticeSeen]),React.useEffect(()=>{if(!notice&&!preview)return;let previous=document.activeElement;return dialogRef.current?.querySelector("button")?.focus(),()=>{previous?.isConnected&&previous.focus?.()}},[notice,preview]);let control=async(action,token)=>{setBusy(!0),setError("");try{let result=await api2("graph/control",{action,...token?{token}:{}},{method:"POST"});action==="preview"?result.pending>0?setPreview(result):(await api2("graph/control",{action:"enable",token:result.token},{method:"POST"}),await refresh?.()):(setPreview(null),action==="notice"&&(setNotice(!1),setHideExplanation(!0),onGraphHidden?.()),await refresh?.())}catch(reason){setError(String(reason?.message||reason))}finally{setBusy(!1)}},graphStatus=state.enabled===!0?state.paused?"\u5DF2\u6682\u505C\u66F4\u65B0\uFF0C\u53EF\u67E5\u770B\u65E7\u56FE\u8C31":"\u5DF2\u5F00\u542F":"\u9ED8\u8BA4\u5173\u95ED\uFF0C\u6253\u5F00\u540E\u53EF\u67E5\u770B\u5DF2\u6709\u56FE\u8C31",graphInfo=page?null:h(InfoPopover,{label:"\u77E5\u8BC6\u56FE\u8C31\u8BF4\u660E"},h("p",null,GRAPH_EXPLANATION),h("p",null,GRAPH_USAGE_HINT)),showExplanation=!hideExplanation&&(!page||state.noticeSeen!==!0);return h(React.Fragment,null,h("style",null,GRAPH_CONTROL_STYLES),h("aside",{className:"sg-storage-card sg-graph-control"+(page?" sg-graph-page-control":""),"aria-label":page?"\u77E5\u8BC6\u56FE\u8C31\u5F00\u5173":void 0},h("div",{className:"sg-stage"},h("span",{className:"sg-graph-copy"},h("span",{className:"sg-graph-title-row"},h("b",null,page?"\u663E\u793A\u77E5\u8BC6\u56FE\u8C31":"\u542F\u7528\u77E5\u8BC6\u56FE\u8C31"),graphInfo),page?h("span",null,graphStatus):null),h("span",{className:"sg-lambda-control sg-graph-toggle"},!page&&showExplanation?h("button",{type:"button",className:"sg-icon-button","aria-label":"\u4E0D\u518D\u63D0\u9192",title:"\u4E0D\u518D\u63D0\u9192",disabled:busy,onClick:()=>{control("notice")}},"\xD7"):null,h("button",{type:"button",role:"switch","aria-label":"\u663E\u793A\u77E5\u8BC6\u56FE\u8C31","aria-checked":state.enabled===!0,disabled:busy,className:"sg-setting-switch",onClick:()=>{control(state.enabled?"disable":"preview")}}))),page&&state.enabled===!0?h("button",{type:"button",className:"sg-graph-open",onClick:()=>onOpenGraph?.()},"\u6253\u5F00\u77E5\u8BC6\u56FE\u8C31 \u2192"):null,!page&&state.enabled?h("button",{type:"button",className:"sg-storage-button",disabled:busy,onClick:()=>{control(state.paused?"preview":"pause")}},state.paused?"\u7EDF\u8BA1\u5E76\u7EE7\u7EED\u56FE\u8C31\u4EFB\u52A1":"\u6682\u505C\u56FE\u8C31\u4EFB\u52A1"):null,error3?h("p",{role:"alert",className:"sg-error-note"},error3):null,notice||preview?h("div",{className:"sg-import-overlay"},h("section",{ref:dialogRef,role:"dialog","aria-modal":"true","aria-label":notice?"\u77E5\u8BC6\u56FE\u8C31\u9ED8\u8BA4\u5173\u95ED\u8BF4\u660E":"\u786E\u8BA4\u6062\u590D\u77E5\u8BC6\u56FE\u8C31",className:"sg-import-dialog",onKeyDown:event3=>{if(event3.key==="Escape"&&preview&&!notice&&!busy&&(event3.preventDefault(),setPreview(null)),event3.key==="Tab"){let buttons=[...dialogRef.current.querySelectorAll("button:not(:disabled)")];if(!buttons.length){event3.preventDefault();return}let first2=buttons[0],last2=buttons.at(-1);event3.shiftKey&&document.activeElement===first2?(event3.preventDefault(),last2.focus()):!event3.shiftKey&&document.activeElement===last2&&(event3.preventDefault(),first2.focus())}}},h("div",{className:"sg-graph-dialog-heading"},h("h3",null,notice?"\u77E5\u8BC6\u56FE\u8C31\u9ED8\u8BA4\u5173\u95ED":"\u786E\u8BA4\u6062\u590D\u77E5\u8BC6\u56FE\u8C31"),notice?h("span",{className:"sg-graph-dialog-control"},h("span",null,"\u5F00\u542F"),h("button",{type:"button",role:"switch","aria-label":"\u542F\u7528\u77E5\u8BC6\u56FE\u8C31","aria-checked":state.enabled===!0,disabled:busy,className:"sg-setting-switch",onClick:()=>{control("preview")}})):null),h("p",null,GRAPH_EXPLANATION),h("p",null,GRAPH_USAGE_HINT),preview&&!notice?h("p",null,"\u5F53\u524D\u6709 "+preview.pending+" \u6761\u5F85\u5904\u7406\u4E8B\u4EF6\uFF0C\u7EA6 "+preview.batches+" \u4E2A\u6279\u6B21\u3002\u786E\u8BA4\u540E\u4EC5\u8865\u5EFA\u8FD9\u4EFD\u6E05\u5355\uFF0C\u6CBF\u7528\u73B0\u6709\u79DF\u7EA6\u3001\u5E76\u53D1\u548C\u91CD\u8BD5\u9650\u989D\uFF1B\u53EF\u968F\u65F6\u6682\u505C\u3002"):null,notice&&!preview?h("button",{type:"button",className:"sg-graph-no-reminder",disabled:busy,onClick:()=>{control("notice")}},"\u6682\u65F6\u5173\u95ED"):!notice&&preview?h(React.Fragment,null,h("button",{type:"button",disabled:busy,onClick:()=>setPreview(null)},"\u53D6\u6D88"),h("button",{type:"button",disabled:busy,onClick:()=>{control("enable",preview.token)}},"\u786E\u8BA4\u5F00\u542F\u5E76\u5206\u6279\u5904\u7406")):null,!notice&&!preview?h("button",{type:"button",className:"sg-graph-no-reminder",disabled:busy,onClick:()=>{control("notice")}},"\u6682\u65F6\u5173\u95ED"):null)):null))}function GraphSettingsPanel({state={},refresh}){return h(GraphControlPanel,{state,refresh})}function DailyNotesSettings({usePluginSettings,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[saving,setSaving]=React.useState(!1),[error3,setError]=React.useState(""),localTimeZone=Intl.DateTimeFormat().resolvedOptions().timeZone,timeZone=settings?.value?.dailyNotesTimeZone||"",enabled=settings?.value?.dailyNotesEnabled!==!1,injectionDays=settings?.value?.dailyNotesInjectionDays??3,zones=[...new Set(["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Asia/Kolkata","Europe/London","Europe/Berlin","America/New_York","America/Los_Angeles","Australia/Sydney","UTC",timeZone].filter(Boolean))],save=async(setter,value)=>{setSaving(!0),setError("");try{(!setter||!await setter(value))&&setError("\u672A\u80FD\u4FDD\u5B58\u7B14\u8BB0\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u8BD5\u3002")}catch(reason){setError("\u4FDD\u5B58\u5931\u8D25\uFF1A"+String(reason.message||reason))}finally{setSaving(!1)}},disabled=settings?.writable!==!0||saving;return h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u77ED\u671F\u8BB0\u5FC6"),h("span",{className:"sg-display-setting-description"},"\u6BCF\u5929\u4E00\u4EFD\u5DE5\u4F5C\u7B14\u8BB0\u3002\u5173\u95ED\u540E\u4E0D\u518D\u5199\u5165\u548C\u6CE8\u5165\uFF0C\u5DF2\u6709\u7B14\u8BB0\u4FDD\u7559\u3002")),h("button",{type:"button",className:"sg-setting-switch",role:"switch","aria-label":"\u77ED\u671F\u8BB0\u5FC6","aria-checked":enabled,disabled:disabled||!setDailyEnabled,onClick:()=>{save(setDailyEnabled,!enabled)}})),h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570"),h("span",{className:"sg-display-setting-description"},"\u53D6\u6700\u8FD1\u6709\u7B14\u8BB0\u7684\u65E5\u671F\uFF0C\u9ED8\u8BA4 3 \u5929\u3002\u4FEE\u6539\u540E\u7528\u4E8E\u65B0\u4F1A\u8BDD\uFF1B\u5185\u5BB9\u4ECD\u53D7\u957F\u5EA6\u4E0A\u9650\u7EA6\u675F\u3002")),h("select",{className:"sg-effort-select","aria-label":"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570",value:injectionDays,disabled:disabled||!setDailyInjectionDays,onChange:event3=>{save(setDailyInjectionDays,Number(event3.target.value))}},Array.from({length:30},(_,i2)=>h("option",{key:i2+1,value:i2+1},i2+1+" \u5929")))),h("div",{className:"sg-stage"},h("span",null,"\u7B14\u8BB0\u65F6\u533A"),h("select",{className:"sg-effort-select",style:{maxWidth:"100%",minWidth:0},"aria-label":"\u7B14\u8BB0\u65F6\u533A",value:timeZone,disabled:disabled||!setDailyTimeZone,onChange:event3=>{save(setDailyTimeZone,event3.target.value)}},h("option",{value:""},"\u8DDF\u968F\u672C\u673A\uFF08"+localTimeZone+"\uFF09"),zones.map(zone=>h("option",{key:zone,value:zone},zone)))),error3?h("p",{className:"sg-storage-feedback failed",role:"alert"},error3):null)}function ProfileLimitSettings(){let[profile,setProfile]=React.useState(null),[loading,setLoading]=React.useState(!0),[loadError,setLoadError]=React.useState(""),[editing,setEditing]=React.useState(!1),[draft,setDraft]=React.useState(""),[saving,setSaving]=React.useState(!1),[error3,setError]=React.useState(""),total=profileTotalLength(profile),limit2=profileTotalLimit(profile);React.useEffect(()=>{let controller=new AbortController;return api2("profile",{},{method:"GET",signal:controller.signal}).then(value=>{controller.signal.aborted||setProfile(value),setLoadError("")}).catch(reason=>{controller.signal.aborted||setLoadError("\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u753B\u50CF\u7528\u91CF\uFF1A"+String(reason?.message||reason))}).finally(()=>{controller.signal.aborted||setLoading(!1)}),()=>controller.abort()},[]);let begin=()=>{loading||loadError||(setDraft(String(limit2)),setError(""),setEditing(!0))},cancel=()=>{saving||(setEditing(!1),setError(""))},save=async()=>{if(saving)return;let next2=Number(draft);if(!Number.isSafeInteger(next2)||next2<PROFILE_LIMIT_MIN||next2>PROFILE_LIMIT_MAX){setError("\u8BF7\u8F93\u5165 "+formatCount(PROFILE_LIMIT_MIN)+" \u5230 "+formatCount(PROFILE_LIMIT_MAX)+" \u4E4B\u95F4\u7684\u6574\u6570\u3002");return}if(next2<total){setError("\u4E0A\u9650\u4E0D\u80FD\u4F4E\u4E8E\u5F53\u524D\u5DF2\u7528\u7684 "+formatCount(total)+" \u5B57\u3002");return}if(next2===limit2){setEditing(!1);return}setSaving(!0),setError("");try{let result=await api2("settings",null,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileMaxLength:next2})}),saved=Number(result?.profileMaxLength);if(!Number.isSafeInteger(saved)||saved!==next2)throw new Error("\u4E0A\u9650\u4FDD\u5B58\u7ED3\u679C\u4E0D\u5B8C\u6574");setProfile(current=>current&&{...current,_limits:{...current._limits||{},totalMaxLength:next2}}),setEditing(!1)}catch(reason){setError("\u4E0A\u9650\u672A\u4FDD\u5B58\uFF1A"+String(reason?.message||reason))}finally{setSaving(!1)}};return h("div",{className:"sg-settings-panel sg-profile-limit","data-testid":"stratagate-profile-limit-settings"},h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u5E38\u9A7B\u753B\u50CF\u5B57\u6570\u4E0A\u9650"),h("span",{className:"sg-display-setting-description"},"\u9650\u5236\u6BCF\u8F6E\u5E26\u5165\u7684\u5E38\u9A7B\u753B\u50CF\u603B\u91CF\uFF0C\u4E0D\u80FD\u4F4E\u4E8E\u5F53\u524D\u5DF2\u5199\u5185\u5BB9\u3002")),h("span",{className:"sg-profile-limit-control"},loading?h("span",{className:"sg-setting-note"},"\u8BFB\u53D6\u4E2D\u2026"):h(React.Fragment,null,loadError?null:h("span",{className:"sg-profile-limit-value","aria-label":"\u5E38\u9A7B\u753B\u50CF\u5DF2\u7528 "+total+" \u5B57\uFF0C\u4E0A\u9650 "+formatCount(limit2)+" \u5B57"},formatCount(total)+" / "+formatCount(limit2)+" \u5B57"),!loadError&&!editing?h("button",{type:"button",className:"sg-cap-limit",onClick:begin},"\u8C03\u6574\u4E0A\u9650"):null))),editing?h("div",{className:"sg-cap-edit sg-profile-limit-edit"},h("input",{type:"number",inputMode:"numeric",min:PROFILE_LIMIT_MIN,max:PROFILE_LIMIT_MAX,step:100,"aria-label":"\u5E38\u9A7B\u753B\u50CF\u5B57\u6570\u4E0A\u9650",value:draft,disabled:saving,autoFocus:!0,onChange:event3=>setDraft(event3.target.value),onKeyDown:event3=>{event3.key==="Enter"?(event3.preventDefault(),save()):event3.key==="Escape"&&(event3.preventDefault(),cancel())}}),h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:cancel},"\u53D6\u6D88"),h("button",{type:"button",className:"sg-save-button",disabled:saving,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58")):null,loadError?h("p",{className:"sg-storage-feedback failed",role:"alert"},loadError):null,error3?h("p",{className:"sg-cap-error",role:"alert"},error3):null)}function MemoryModelSettings({usePluginSettings,setMemoryModel}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[catalog,setCatalog]=React.useState(null),[draft,setDraft]=React.useState(null),customDraft=React.useRef(null),[models,setModels]=React.useState([]),[loading,setLoading]=React.useState(!1),[catalogError,setCatalogError]=React.useState(""),[modelsError,setModelsError]=React.useState(""),[feedback,setFeedback]=React.useState({kind:"",text:""}),[saving,setSaving]=React.useState(!1),[revision,setRevision]=React.useState(0);React.useEffect(()=>{if(feedback.kind!=="done")return;let timer=window.setTimeout(()=>setFeedback({kind:"",text:""}),4500);return()=>window.clearTimeout(timer)},[feedback]);let saved=settings?.value?.memoryModel||catalog?.selection||{mode:"auto"},value=draft||saved,provider=value.mode==="custom"&&value.provider||"";React.useEffect(()=>{let active=!0;return settings?.value?.memoryModel?.mode==="auto"&&value.mode==="auto"?(setCatalog(null),setCatalogError(""),()=>{active=!1}):(setCatalogError(""),api2("models").then(result=>{active&&setCatalog(result)}).catch(reason=>{active&&setCatalogError(String(reason?.message||reason))}),()=>{active=!1})},[revision,settings?.value?.memoryModel?.mode,value.mode]),React.useEffect(()=>{let active=!0;return setModels([]),setModelsError(""),provider?(setLoading(!0),api2("models",{provider}).then(result=>{active&&setModels(result.models)}).catch(reason=>{active&&setModelsError(String(reason?.message||reason))}).finally(()=>{active&&setLoading(!1)}),()=>{active=!1}):(setLoading(!1),()=>{active=!1})},[provider,revision]);let providers=catalog?.providers||[],custom=value.mode==="custom";React.useEffect(()=>{if(!draft||!custom||provider||!providers[0])return;let next2={...value,provider:providers[0].id};customDraft.current=next2,setDraft(next2)},[providers,custom,provider,draft,value]);let valid2=!custom||providers.some(item=>item.id===provider)&&!!value.model?.trim(),changed=value.mode!==saved.mode||custom&&(value.provider!==saved.provider||value.model!==saved.model),editingDisabled=settings?.writable!==!0||!setMemoryModel||saving,disabled=editingDisabled,edit=next2=>{next2.mode==="custom"&&(customDraft.current=next2),setDraft(next2),setFeedback({kind:"",text:""})},save=async()=>{if(!(disabled||!valid2||!changed)){setSaving(!0),setFeedback({kind:"",text:""});try{if(!await setMemoryModel(value))throw new Error("\u5BBF\u4E3B\u672A\u786E\u8BA4\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002");setCatalog(current=>({...current,selection:value})),setDraft(null),setFeedback({kind:"done",text:"\u5DF2\u4FDD\u5B58\uFF0C\u5BF9\u540E\u7EED\u8BB0\u5FC6\u5904\u7406\u8C03\u7528\u751F\u6548\u3002\u6B63\u5728\u8FD0\u884C\u7684\u8C03\u7528\u7EE7\u7EED\u5B8C\u6210\u3002"})}catch(reason){setFeedback({kind:"failed",text:"\u672A\u80FD\u786E\u8BA4\u4FDD\u5B58\uFF1A"+String(reason?.message||reason)+" \u5F53\u524D\u9009\u62E9\u5DF2\u4FDD\u7559\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}finally{setSaving(!1)}}},savedProvider=providers.find(item=>item.id===saved.provider)?.name||saved.provider,savedModel=saved.provider===provider&&models.find(item=>item.id===saved.model)?.name||saved.model,pendingProvider=providers.find(item=>item.id===value.provider)?.name||value.provider,pendingModel=value.provider===provider&&models.find(item=>item.id===value.model)?.name||value.model,savedSummary=saved.mode==="custom"?savedProvider+" / "+savedModel:"\u8DDF\u968F\u804A\u5929\u6A21\u578B",pendingSummary=value.mode==="custom"?pendingProvider+" / "+pendingModel:"\u8DDF\u968F\u804A\u5929\u6A21\u578B";return h("div",{className:"sg-settings-panel sg-model-settings"},h("h4",{className:"sg-model-heading"},"\u8BB0\u5FC6\u5904\u7406\u6A21\u578B"),h("div",{className:"sg-model-modes",role:"radiogroup","aria-label":"\u8BB0\u5FC6\u5904\u7406\u6A21\u578B"},[{mode:"auto",title:"\u8DDF\u968F\u804A\u5929\u6A21\u578B"},{mode:"custom",title:"\u5355\u72EC\u6307\u5B9A\u6A21\u578B"}].map(item=>h("label",{key:item.mode,className:"sg-model-mode"+(value.mode===item.mode?" selected":"")},h("input",{type:"radio",name:"sg-memory-model-mode",value:item.mode,checked:value.mode===item.mode,disabled:editingDisabled,onChange:()=>edit(item.mode==="auto"?{mode:"auto"}:customDraft.current||(saved.mode==="custom"?saved:{mode:"custom",provider:providers[0]?.id||"",model:""}))}),h("span",{className:"sg-model-mode-copy"},h("span",{className:"sg-model-mode-title"},item.title))))),custom?h(React.Fragment,null,h("div",{className:"sg-model-fields"},h("label",{className:"sg-model-field"},"\u670D\u52A1\u5546",h("select",{className:"sg-effort-select","aria-label":"\u8BB0\u5FC6\u5904\u7406\u670D\u52A1\u5546",value:provider,disabled:editingDisabled||!catalog,onChange:event3=>edit({mode:"custom",provider:event3.target.value,model:""})},h("option",{value:""},"\u8BF7\u9009\u62E9\u670D\u52A1\u5546"),provider&&!providers.some(item=>item.id===provider)?h("option",{value:provider},provider+"\uFF08\u5F53\u524D\u4E0D\u53EF\u7528\uFF09"):null,providers.map(item=>h("option",{key:item.id,value:item.id},item.name||item.id)))),h("label",{className:"sg-model-field"},"\u6A21\u578B",h("select",{className:"sg-effort-select","aria-label":"\u8BB0\u5FC6\u5904\u7406\u5177\u4F53\u6A21\u578B",value:value.model||"",disabled:editingDisabled||!catalog||!provider||loading||!!modelsError,onChange:event3=>edit({...value,model:event3.target.value})},h("option",{value:""},loading?"\u6B63\u5728\u8BFB\u53D6\u6A21\u578B\u2026":"\u8BF7\u9009\u62E9\u6A21\u578B"),value.model&&!models.some(item=>item.id===value.model)?h("option",{value:value.model},value.model+"\uFF08\u672A\u5728\u5217\u8868\u4E2D\uFF09"):null,models.map(item=>h("option",{key:item.id,value:item.id},item.name||item.id))))),null):null,custom&&!catalog&&!catalogError?h("p",{className:"sg-status-feedback",role:"status"},"\u6B63\u5728\u8BFB\u53D6\u670D\u52A1\u5546\u2026"):null,settings&&settings.writable!==!0?h("p",{className:"sg-status-feedback"},"\u5F53\u524D\u914D\u7F6E\u4E3A\u53EA\u8BFB\u3002"):null,catalogError||modelsError?h("p",{className:"sg-status-feedback failed",role:"alert"},"\u8BFB\u53D6\u5931\u8D25\uFF1A"+(catalogError||modelsError)," ",h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:()=>setRevision(current=>current+1)},"\u91CD\u65B0\u8BFB\u53D6")):null,h("div",{className:"sg-model-save-row"},h("div",{className:"sg-model-saved"},h("span",{className:"sg-model-active-label"},"\u5F53\u524D\u751F\u6548"),h("strong",null,catalog||settings?.value?.memoryModel?savedSummary:"\u8DDF\u968F\u804A\u5929\u6A21\u578B"),changed?h("span",{className:"sg-model-pending"},"\u2192 "+pendingSummary):null),changed?h("button",{type:"button",className:"sg-save-button",disabled:editingDisabled||!valid2||custom&&!catalog,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58"):h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"})),feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null)}function RetrievalModelSettings({kind,settings,writable,onSaved}){let embedding=kind==="embedding",title=embedding?"\u5411\u91CF\u68C0\u7D22":"\u7ED3\u679C\u7CBE\u6392\uFF08Rerank\uFF09",prefix=embedding?"embedding":"rerank",urlKey=prefix+"Url",secretKey=prefix+"Key",modelKey=prefix+"Model",[saved,setSaved]=React.useState(settings||null),[draft,setDraft]=React.useState({}),[models,setModels]=React.useState([]),[listing,setListing]=React.useState(!1),[listFeedback,setListFeedback]=React.useState(""),[saving,setSaving]=React.useState(!1),[reading,setReading]=React.useState(!1),[feedback,setFeedback]=React.useState({kind:"",text:""}),lookup2=React.useRef(0);React.useEffect(()=>{settings&&setSaved(settings)},[settings]),React.useEffect(()=>()=>{lookup2.current+=1},[]),React.useEffect(()=>{if(feedback.kind!=="done")return;let timer=window.setTimeout(()=>setFeedback({kind:"",text:""}),4500);return()=>window.clearTimeout(timer)},[feedback]);let value=key=>draft[key]??saved?.[key]??"",url=String(value(urlKey)).trim().replace(/\/+$/,""),keyEdited=Object.hasOwn(draft,secretKey),keyConfigured=keyEdited?!!draft[secretKey].trim():saved?.[prefix+"KeyConfigured"]===!0,urlValid=!url;try{urlValid=["http:","https:"].includes(new URL(url).protocol)}catch{}let numericValid=!embedding||["vectorWeight","embeddingMinScore"].every(key=>{let raw=draft[key]??saved?.[key]??(key==="vectorWeight"?1:.3);return String(raw).trim()!==""&&Number.isFinite(Number(raw))&&Number(raw)>=0&&Number(raw)<=(key==="vectorWeight"?5:1)}),changed=Object.keys(draft).some(key=>key===secretKey||String(draft[key])!==String(saved?.[key]??"")),disabled=!saved||writable!==!0||saving||reading,edit=(key,next2)=>{setDraft(current=>({...current,[key]:next2})),setFeedback({kind:"",text:""}),(key===urlKey||key===secretKey)&&(lookup2.current+=1,setModels([]),setListing(!1),setListFeedback(""))},listModels=async()=>{if(disabled||listing||!url||!urlValid||!keyConfigured)return;let request=++lookup2.current;setListing(!0),setModels([]),setListFeedback("");try{let result=await api2("models",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind,url,...keyEdited?{key:draft[secretKey].trim()}:{}})});if(request!==lookup2.current)return;let ids=Array.isArray(result.models)?result.models.filter(id2=>typeof id2=="string"&&id2):[];setModels(ids),setListFeedback(ids.length?"\u5DF2\u8BFB\u53D6\u6A21\u578B\u5217\u8868\u3002\u8BF7\u9009\u62E9\u5BF9\u5E94\u7C7B\u578B\u7684\u6A21\u578B\uFF0C\u4E5F\u53EF\u624B\u52A8\u586B\u5199\u3002":"\u672A\u80FD\u8BFB\u53D6\u6A21\u578B\u5217\u8868\uFF0C\u53EF\u91CD\u8BD5\u6216\u624B\u52A8\u586B\u5199\u6A21\u578B\u540D\u79F0\u3002")}catch{request===lookup2.current&&setListFeedback("\u672A\u80FD\u8BFB\u53D6\u6A21\u578B\u5217\u8868\uFF0C\u53EF\u91CD\u8BD5\u6216\u624B\u52A8\u586B\u5199\u6A21\u578B\u540D\u79F0\u3002")}finally{request===lookup2.current&&setListing(!1)}},save=async()=>{if(disabled||!changed||!urlValid||!numericValid)return;let patch={};for(let key of Object.keys(draft))patch[key]=key==="vectorWeight"||key==="embeddingMinScore"?Number(draft[key]):key===urlKey?url:draft[key].trim();setSaving(!0),setFeedback({kind:"",text:""}),lookup2.current+=1,setListing(!1);try{let result=await api2("settings",null,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(patch)});if(!result.vectorSettings||typeof result.vectorSettings[prefix+"Ready"]!="boolean")throw new Error("Missing saved settings");setSaved(result.vectorSettings),setDraft({}),onSaved?.(result.vectorSettings),setFeedback({kind:"done",text:"\u914D\u7F6E\u5DF2\u4FDD\u5B58\u3002"})}catch{setFeedback({kind:"failed",text:"\u672A\u80FD\u786E\u8BA4\u4FDD\u5B58\uFF0C\u8F93\u5165\u5DF2\u4FDD\u7559\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u914D\u7F6E\u540E\u6838\u5BF9\uFF0C\u6216\u91CD\u8BD5\u4FDD\u5B58\u3002"})}finally{setSaving(!1)}},readSaved=async()=>{if(!(saving||reading)){setReading(!0);try{let result=await api2("overview");if(!result.vectorSettings||typeof result.vectorSettings[prefix+"Ready"]!="boolean")throw new Error("Missing saved settings");setSaved(result.vectorSettings),onSaved?.(result.vectorSettings),setFeedback({kind:"done",text:"\u5DF2\u91CD\u65B0\u8BFB\u53D6\u4FDD\u5B58\u7684\u914D\u7F6E\uFF1B\u672A\u4FDD\u5B58\u8F93\u5165\u5DF2\u4FDD\u7559\u3002"})}catch{setFeedback({kind:"failed",text:"\u672A\u80FD\u8BFB\u53D6\u4FDD\u5B58\u7684\u914D\u7F6E\uFF0C\u8F93\u5165\u5DF2\u4FDD\u7559\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}finally{setReading(!1)}}},ready4=saved?.[prefix+"Ready"]===!0,active=ready4&&(!embedding||Number(saved.vectorWeight)>0),status=saved?active?"\u5DF2\u914D\u7F6E \xB7 "+saved[modelKey]:ready4&&embedding?"\u5DF2\u505C\u7528\uFF08\u5411\u91CF\u68C0\u7D22\u5360\u6BD4\u4E3A 0\uFF09":saved[urlKey]?"\u914D\u7F6E\u672A\u5B8C\u6574\uFF0C\u6682\u672A\u542F\u7528":"\u672A\u542F\u7528":"\u5C1A\u672A\u8BFB\u53D6\u914D\u7F6E";return h("div",{className:"sg-settings-panel sg-model-settings sg-retrieval-settings","data-kind":kind},h("div",{className:"sg-model-heading-row"},h("h4",{className:"sg-model-heading"},title),h(InfoPopover,{label:title+"\u8BF4\u660E"},h("p",null,"\u586B\u5199\u5730\u5740\u3001\u5BC6\u94A5\u548C\u6A21\u578B\u540E\u542F\u7528\uFF1B\u6E05\u7A7A\u5730\u5740\u5E76\u4FDD\u5B58\u5373\u53EF\u505C\u7528\u3002\u542F\u7528\u4F1A\u4EA7\u751F\u670D\u52A1\u5546 API \u8D39\u7528\u3002"),h("p",null,embedding?"\u542F\u7528\u540E\uFF0C\u4E8B\u4EF6\u6807\u9898\u548C\u6458\u8981\u4F1A\u53D1\u9001\u7ED9\u5411\u91CF\u670D\u52A1\u5546\u3002":"\u542F\u7528\u540E\uFF0C\u68C0\u7D22\u95EE\u9898\u548C\u5019\u9009\u4E8B\u4EF6\u5185\u5BB9\u4F1A\u53D1\u9001\u7ED9\u7CBE\u6392\u670D\u52A1\u5546\u3002"),h("p",null,"\u586B\u5199 OpenAI \u517C\u5BB9\u63A5\u53E3\u57FA\u7840\u5730\u5740\uFF0C\u4E0D\u542B "+(embedding?"/embeddings":"/rerank")+"\u3002"),h("p",null,"\u4FDD\u5B58\u4E0D\u9A8C\u8BC1\u8FDE\u63A5\u3002"+(embedding?"\u5DF2\u6709\u4E8B\u4EF6\u7684\u5411\u91CF\u4F1A\u5728\u540E\u7EED\u68C0\u7D22\u65F6\u8865\u9F50\u3002":"")))),h("div",{className:"sg-retrieval-fields"},h("label",{className:"sg-model-field"},"API \u5730\u5740",h("input",{type:"url",value:value(urlKey),disabled,placeholder:"https://\u4F60\u7684\u670D\u52A1\u5730\u5740/v1","aria-label":title+" API \u5730\u5740",spellCheck:!1,onChange:event3=>edit(urlKey,event3.target.value)})),urlValid?null:h("p",{className:"sg-status-feedback failed",role:"alert"},"\u8BF7\u586B\u5199\u4EE5 http:// \u6216 https:// \u5F00\u5934\u7684\u6709\u6548\u5730\u5740\u3002"),h("label",{className:"sg-model-field"},"API Key",h("input",{type:"password",value:draft[secretKey]??"",disabled,placeholder:keyEdited&&!draft[secretKey]?"\u4FDD\u5B58\u540E\u6E05\u9664\u5BC6\u94A5":saved?.[prefix+"KeyConfigured"]?"\u5DF2\u4FDD\u5B58\u5BC6\u94A5\uFF0C\u672A\u4FEE\u6539\u65F6\u4FDD\u7559":"\u586B\u5199 API Key","aria-label":title+" API Key",autoComplete:"new-password",spellCheck:!1,onChange:event3=>edit(secretKey,event3.target.value)})),h("div",{className:"sg-retrieval-actions"},saved?.[prefix+"KeyConfigured"]?h("button",{type:"button",className:"sg-quiet-button",disabled,onClick:()=>edit(secretKey,"")},"\u6E05\u9664\u5DF2\u4FDD\u5B58\u5BC6\u94A5"):null,keyEdited?h("button",{type:"button",className:"sg-quiet-button",disabled,onClick:()=>{setDraft(current=>{let next2={...current};return delete next2[secretKey],next2}),lookup2.current+=1,setModels([]),setListing(!1),setListFeedback(""),setFeedback({kind:"",text:""})}},"\u64A4\u9500\u5BC6\u94A5\u4FEE\u6539"):null),keyEdited&&!draft[secretKey].trim()?h("p",{className:"sg-setting-note"},"\u4FDD\u5B58\u540E\u5C06\u6E05\u9664\u5BC6\u94A5\u5E76\u505C\u7528\u6B64\u529F\u80FD\u3002"):null,h("label",{className:"sg-model-field"},"\u6A21\u578B\u540D\u79F0",h("input",{type:"text",value:value(modelKey),disabled,list:"sg-"+kind+"-models",placeholder:"\u586B\u5199\u6A21\u578B\u540D\u79F0\u6216\u4ECE\u5217\u8868\u9009\u62E9","aria-label":title+"\u6A21\u578B\u540D\u79F0",autoComplete:"off",spellCheck:!1,onChange:event3=>edit(modelKey,event3.target.value)})),h("datalist",{id:"sg-"+kind+"-models"},models.map(id2=>h("option",{key:id2,value:id2}))),h("div",{className:"sg-retrieval-actions"},h("button",{type:"button",className:"sg-storage-button",disabled:disabled||listing||!url||!urlValid||!keyConfigured,onClick:()=>{listModels()}},listing?"\u6B63\u5728\u8BFB\u53D6\u2026":"\u8BFB\u53D6\u6A21\u578B\u5217\u8868")),listFeedback?h("p",{className:"sg-status-feedback",role:"status"},listFeedback):null),embedding?h("details",{className:"sg-retrieval-tuning"},h("summary",null,"\u68C0\u7D22\u53C2\u6570"),h("div",{className:"sg-model-fields"},h("label",{className:"sg-model-field"},"\u5411\u91CF\u68C0\u7D22\u5360\u6BD4",h("input",{type:"number",min:0,max:5,step:.1,value:draft.vectorWeight??saved?.vectorWeight??1,disabled,"aria-label":"\u5411\u91CF\u68C0\u7D22\u5360\u6BD4",onChange:event3=>edit("vectorWeight",event3.target.value)})),h("label",{className:"sg-model-field"},"\u6700\u4F4E\u76F8\u4F3C\u5EA6",h("input",{type:"number",min:0,max:1,step:.05,value:draft.embeddingMinScore??saved?.embeddingMinScore??.3,disabled,"aria-label":"\u6700\u4F4E\u76F8\u4F3C\u5EA6",onChange:event3=>edit("embeddingMinScore",event3.target.value)}))),h("p",{className:"sg-setting-note"},"\u5360\u6BD4 1 \u4E0E\u5173\u952E\u8BCD\u68C0\u7D22\u5E73\u6743\uFF1B0 \u505C\u7528\u3002\u6700\u4F4E\u76F8\u4F3C\u5EA6\u8303\u56F4 0\u20131\u3002"),numericValid?null:h("p",{className:"sg-status-feedback failed",role:"alert"},"\u5360\u6BD4\u9700\u4E3A 0\u20135 \u7684\u6570\u5B57\uFF0C\u6700\u4F4E\u76F8\u4F3C\u5EA6\u9700\u4E3A 0\u20131 \u7684\u6570\u5B57\u3002")):null,h("div",{className:"sg-model-save-row"},h("div",{className:"sg-model-saved"},h("span",{className:"sg-model-active-label"},"\u5F53\u524D\u751F\u6548"),h("strong",null,status)),changed?h("button",{type:"button",className:"sg-save-button",disabled:disabled||!urlValid||!numericValid,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58"):saved?h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"}):null),!saved||writable!==!0?h("p",{className:"sg-status-feedback"},saved?"\u5F53\u524D\u68C0\u7D22\u914D\u7F6E\u4E3A\u53EA\u8BFB\u3002":"\u68C0\u7D22\u914D\u7F6E\u5C1A\u672A\u8BFB\u53D6\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u3002"):null,feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null,!saved||feedback.kind==="failed"?h("button",{type:"button",className:"sg-quiet-button",disabled:saving||reading,onClick:()=>{readSaved()}},reading?"\u6B63\u5728\u8BFB\u53D6\u2026":"\u91CD\u65B0\u8BFB\u53D6\u914D\u7F6E"):null)}function SettingsPage({selected,graphSettings,vectorSettings,retrievalSettingsWritable,onRetrievalSettingsSaved,refresh,namespace,dataDirectory,onBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let[turnSize,setTurnSize]=React.useState(String(selected.blockTurnSize??6)),[lambda,setLambda]=React.useState(String(selected.blockDecayLambda??.3)),[agentWeight,setAgentWeight]=React.useState(String(selected.agentMemoryRetrievalWeight??1)),[directoryOpening,setDirectoryOpening]=React.useState(!1),[directoryFeedback,setDirectoryFeedback]=React.useState({kind:"",text:""});React.useEffect(()=>{setTurnSize(String(selected.blockTurnSize??6)),setLambda(String(selected.blockDecayLambda??.3)),setAgentWeight(String(selected.agentMemoryRetrievalWeight??1))},[selected.blockTurnSize,selected.blockDecayLambda,selected.agentMemoryRetrievalWeight]);let turnSizeValue=Number(turnSize),lambdaValue=Number(lambda),agentWeightValue=Number(agentWeight),changed=Number.isSafeInteger(turnSizeValue)&&turnSizeValue>=1&&lambda!==""&&Number.isFinite(lambdaValue)&&lambdaValue>=0&&agentWeight!==""&&Number.isFinite(agentWeightValue)&&agentWeightValue>=0&&agentWeightValue<=5&&(turnSizeValue!==selected.blockTurnSize||lambdaValue!==selected.blockDecayLambda||agentWeightValue!==(selected.agentMemoryRetrievalWeight??1)),suggestedLambda=Math.round((selected.blockDecayLambda??.3)*turnSizeValue/(selected.blockTurnSize||6)/.05)*.05,showSuggestion=Number.isSafeInteger(turnSizeValue)&&turnSizeValue>=1&&turnSizeValue!==selected.blockTurnSize,pluginSettings=usePluginSettings?usePluginSettings(state=>state):null,effortMode=pluginSettings?.value?.structuredReasoningEffort||"auto",effortOverridden=pluginSettings?.user?.structuredReasoningEffort!==void 0,settingsWritable=pluginSettings?.writable===!0,workspaceRows=[["Schema","v"+selected.schemaVersion],["\u5DE5\u4F5C\u533A",selected.workspaceName||"\u5F53\u524D\u5DE5\u4F5C\u533A"],["\u5185\u90E8\u7A7A\u95F4 ID",namespace],["\u5DF2\u5904\u7406\u8F6E\u6B21",selected.currentTurn]],runtimeDiagnostics=[["duplicates","\u21C4","\u91CD\u590D\u8BB0\u5FC6\u6574\u7406","\u67E5\u770B\u4FDD\u7559\u539F\u56E0\u3001\u5408\u5E76\u5019\u9009\u4E0E\u91CD\u65B0\u626B\u63CF"],["system","\u2713","\u7CFB\u7EDF\u72B6\u6001","\u5904\u7406\u6982\u89C8\u4E0E\u6700\u8FD1\u6574\u7406\u65F6\u95F4"],["audit","\u2197","\u4F7F\u7528\u8BB0\u5F55","\u957F\u671F\u8BB0\u5FC6\u4F55\u65F6\u88AB\u4F7F\u7528"],["status","\u21BB","\u540E\u53F0\u4EFB\u52A1","\u5904\u7406\u8FDB\u5EA6\u3001\u5931\u8D25\u4EFB\u52A1\u4E0E\u91CD\u8BD5"]],openDirectory=()=>{!dataDirectory||directoryOpening||(setDirectoryOpening(!0),setDirectoryFeedback({kind:"",text:""}),api2("storage/open-directory",{},{method:"POST"}).then(()=>setDirectoryFeedback({kind:"done",text:"\u5DF2\u5728\u6587\u4EF6\u7BA1\u7406\u5668\u4E2D\u6253\u5F00"})).catch(reason=>setDirectoryFeedback({kind:"failed",text:"\u6253\u5F00\u5931\u8D25\uFF1A"+String(reason?.message||reason)})).finally(()=>setDirectoryOpening(!1)))},copyDirectory=()=>{if(dataDirectory){if(setDirectoryFeedback({kind:"",text:""}),!navigator?.clipboard?.writeText){setDirectoryFeedback({kind:"failed",text:"\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236"});return}navigator.clipboard.writeText(dataDirectory).then(()=>setDirectoryFeedback({kind:"done",text:"\u8DEF\u5F84\u5DF2\u590D\u5236"})).catch(reason=>setDirectoryFeedback({kind:"failed",text:"\u590D\u5236\u5931\u8D25\uFF1A"+String(reason?.message||reason)}))}},menu=items=>h("div",{className:"sg-menu sg-settings-menu"},items.map(([id2,icon,title,subtitle])=>h("button",{key:id2,type:"button",className:"sg-menu-row",onClick:()=>setView({name:id2,back:{name:"settings"}})},h("span",{className:"sg-menu-icon","aria-hidden":"true"},icon),h("span",null,h("span",{className:"sg-menu-title"},title),h("br"),h("span",{className:"sg-menu-subtitle"},subtitle)),h("span",{className:"sg-chevron"},"\u203A")))),stepper=({value,onChange,min:min4,max:max5,step:step3,label,allowFloat})=>{let current=Number(value),delta=allowFloat?step3:1,bump=direction=>{if(!Number.isFinite(current))return;let next2=Math.min(max5,Math.max(min4,Number((current+direction*delta).toFixed(2))));onChange(String(next2))};return h("span",{className:"sg-stp sg-stp-wide"},h("button",{type:"button","aria-label":"\u51CF\u5C11"+label,disabled:!Number.isFinite(current)||current<=min4,onClick:()=>bump(-1)},"\u2212"),h("input",{className:"sg-number-input",type:"number",min:String(min4),max:max5===void 0?void 0:String(max5),step:String(step3),value,onChange:event3=>onChange(event3.target.value),"aria-label":label}),h("button",{type:"button","aria-label":"\u589E\u52A0"+label,disabled:!Number.isFinite(current)||max5===void 0||current>=max5,onClick:()=>bump(1)},"+"))},blockSettings=h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-stage"},h("span",null,"\u6BCF\u4E2A Block \u7684\u5BF9\u8BDD\u8F6E\u6570"),h("span",{className:"sg-lambda-control"},stepper({value:turnSize,onChange:setTurnSize,min:1,max:30,step:1,label:"\u6BCF\u4E2A Block \u7684\u5BF9\u8BDD\u8F6E\u6570"}),h("span",{className:"sg-stage-value waiting"},"\u8F6E"))),h("p",{className:"sg-setting-note"},"1 \u8F6E\u7B49\u4E8E\u4E00\u6B21\u63D0\u95EE\u548C\u5B8C\u6574\u56DE\u590D\uFF0C\u53EA\u5F71\u54CD\u540E\u7EED\u672A\u5C01\u5B58\u5185\u5BB9\u3002"),h("div",{className:"sg-stage"},h("span",null,"Block \u8870\u51CF\u7CFB\u6570 \u03BB"),h("span",{className:"sg-lambda-control"},stepper({value:lambda,onChange:setLambda,min:0,max:.4,step:.05,label:"Block \u8870\u51CF\u7CFB\u6570 \u03BB",allowFloat:!0}))),h("p",{className:"sg-setting-note"},"\u8D8A\u5C0F\u9057\u5FD8\u8D8A\u6162\uFF0Ctoken \u6D88\u8017\u8D8A\u591A\u3002"),showSuggestion?h("div",{className:"sg-setting-suggestion"},h("span",null,"\u5EFA\u8BAE \u03BB \u8C03\u6574\u4E3A "+suggestedLambda.toFixed(2)+"\u3002"),h("button",{type:"button",className:"sg-quiet-button",onClick:()=>setLambda(String(Number(suggestedLambda.toFixed(2))))},"\u91C7\u7528\u5EFA\u8BAE\u503C")):null,h("div",{className:"sg-stage"},h("span",null,"\u4E3B\u52A8\u8BB0\u5FC6\u68C0\u7D22\u5360\u6BD4"),h("span",{className:"sg-lambda-control"},stepper({value:agentWeight,onChange:setAgentWeight,min:0,max:5,step:.05,label:"\u4E3B\u52A8\u8BB0\u5FC6\u68C0\u7D22\u5360\u6BD4",allowFloat:!0}))),h("p",{className:"sg-setting-note"},"1 \u4E3A\u5E73\u6743\uFF0C0 \u4E0D\u5C55\u793A agent \u8BB0\u5F55\u3002"),changed?h("div",{className:"sg-dirty"},h("span",null,[turnSizeValue!==selected.blockTurnSize,lambdaValue!==selected.blockDecayLambda,agentWeightValue!==(selected.agentMemoryRetrievalWeight??1)].filter(Boolean).length+" \u9879\u672A\u4FDD\u5B58"),h("button",{type:"button",className:"sg-quiet-button",disabled:savingSettings,onClick:()=>{setTurnSize(String(selected.blockTurnSize??6)),setLambda(String(selected.blockDecayLambda??.3)),setAgentWeight(String(selected.agentMemoryRetrievalWeight??1))}},"\u653E\u5F03"),h("button",{type:"button",className:"sg-save-button",disabled:!changed||savingSettings,onClick:()=>{updateSettings({blockTurnSize:turnSizeValue,blockDecayLambda:lambdaValue,agentMemoryRetrievalWeight:agentWeightValue})}},savingSettings?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58")):h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"})),effortSettings=h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-stage"},h("span",null,"\u7ED3\u6784\u5316\u63A8\u7406\u6863\u4F4D"),h("span",{className:"sg-lambda-control"},h("select",{className:"sg-effort-select",value:effortMode,disabled:!settingsWritable,onChange:event3=>{setEffort&&setEffort(event3.target.value)},"aria-label":"\u7ED3\u6784\u5316\u63A8\u7406\u6863\u4F4D\u7B56\u7565"},h("option",{value:"auto"},"auto\uFF08\u81EA\u52A8\uFF09"),h("option",{value:"force-off"},"force-off\uFF08\u5F3A\u5236\u5173\u95ED\uFF09")),effortOverridden?h("button",{type:"button",className:"sg-effort-button",onClick:()=>{resetEffort&&resetEffort()}},"\u6062\u590D\u9ED8\u8BA4"):h("span",{className:"sg-stage-value waiting"},"\u9ED8\u8BA4"))),h("p",{className:"sg-setting-note"},"auto \u8DDF\u968F\u6A21\u578B\u80FD\u529B\uFF1Bforce-off \u4F18\u5148\u5173\u95ED\uFF0C\u4E0D\u652F\u6301\u65F6\u81EA\u52A8\u964D\u7EA7\u3002")),workspaceInfo=h("div",{className:"sg-settings-panel sg-pipeline"},workspaceRows.map(([label,value])=>h("div",{key:label,className:"sg-stage"},h("span",null,label),h("span",{className:label==="\u5185\u90E8\u7A7A\u95F4 ID"?"sg-stage-value sg-code":"sg-stage-value"},String(value)))));return h("div",{className:"sg-settings-shell"},h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-pg-head"},h("h2",null,"\u9AD8\u7EA7\u8BBE\u7F6E")),h("section",{className:"sg-settings-group sg-settings-install","aria-labelledby":"sg-memory-settings-title"},h("h3",{id:"sg-memory-settings-title",className:"sg-settings-group-title"},"\u5B89\u88C5\u7EA7\u8BBE\u7F6E"),h("div",{className:"sg-settings-columns"},h("div",{className:"sg-settings-column"},h(GraphSettingsPanel,{state:graphSettings,refresh}),h(ProfileLimitSettings),h(DailyNotesSettings,{usePluginSettings,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}),blockSettings),h("div",{className:"sg-settings-column"},h(RetrievalModelSettings,{kind:"embedding",settings:vectorSettings,writable:retrievalSettingsWritable,onSaved:onRetrievalSettingsSaved}),h(RetrievalModelSettings,{kind:"rerank",settings:vectorSettings,writable:retrievalSettingsWritable,onSaved:onRetrievalSettingsSaved})))),h("section",{className:"sg-settings-group","aria-labelledby":"sg-host-settings-title"},h("h3",{id:"sg-host-settings-title",className:"sg-settings-group-title"},"\u5BBF\u4E3B\u914D\u7F6E"),h("div",{className:"sg-settings-columns"},h("div",{className:"sg-settings-column"},h(MemoryModelSettings,{usePluginSettings,setMemoryModel})),h("div",{className:"sg-settings-column"},effortSettings))),h("section",{className:"sg-settings-group","aria-labelledby":"sg-workspace-settings-title"},h("h3",{id:"sg-workspace-settings-title",className:"sg-settings-group-title"},"\u5DE5\u4F5C\u533A\u4FE1\u606F"),workspaceInfo),h("section",{className:"sg-settings-group","aria-labelledby":"sg-storage-title"},h("h3",{id:"sg-storage-title",className:"sg-settings-group-title"},"\u6570\u636E\u4E0E\u5B58\u50A8"),h("div",{className:"sg-storage-card"},h("span",{className:"sg-storage-label"},"\u6570\u636E\u5B58\u50A8\u4F4D\u7F6E"),h("span",{className:"sg-storage-path",title:dataDirectory||void 0},dataDirectory||"\u5F53\u524D\u4F7F\u7528\u5185\u5B58\u5B58\u50A8\uFF0C\u6CA1\u6709\u672C\u5730\u6570\u636E\u76EE\u5F55"),h("div",{className:"sg-storage-actions"},h("button",{type:"button",className:"sg-storage-button",disabled:!dataDirectory||directoryOpening,onClick:openDirectory},directoryOpening?"\u6B63\u5728\u6253\u5F00\u2026":"\u6253\u5F00\u6587\u4EF6\u5939"),h("button",{type:"button",className:"sg-storage-button",disabled:!dataDirectory,onClick:copyDirectory},"\u590D\u5236\u8DEF\u5F84")),h("p",{className:"sg-storage-feedback "+directoryFeedback.kind,role:directoryFeedback.kind==="failed"?"alert":"status","aria-live":"polite"},directoryFeedback.text)),menu([["raw","{}","\u67E5\u770B\u539F\u59CB\u6570\u636E","Block\u3001Event\u3001Graph \u4E0E\u6A21\u578B\u54CD\u5E94"]])),h("section",{className:"sg-settings-group sg-settings-compact","aria-labelledby":"sg-diagnostics-title"},h("h3",{id:"sg-diagnostics-title",className:"sg-settings-group-title"},"\u8FD0\u884C\u4E0E\u8BCA\u65AD"),menu(runtimeDiagnostics)))}function overviewAbsolute(value){let date=new Date(value);return Number.isNaN(date.getTime())?"\u65F6\u95F4\u672A\u77E5":new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(date)}function overviewRelative(value){let time2=Date.parse(value||"");if(!Number.isFinite(time2))return"\u8FD8\u6CA1\u6709\u66F4\u65B0";let seconds=Math.round((Date.now()-time2)/1e3);if(seconds<60)return"\u521A\u521A";if(seconds<3600)return Math.floor(seconds/60)+" \u5206\u949F\u524D";if(seconds<86400)return Math.floor(seconds/3600)+" \u5C0F\u65F6\u524D";let days=Math.floor(seconds/86400);return days===1?"\u6628\u5929":days<30?days+" \u5929\u524D":overviewAbsolute(value)}function overviewCount(value){return Number(value||0).toLocaleString("en-US")}function OverviewSpeechMark(){return h("svg",{className:"sg-ov-speech",viewBox:"0 0 54 48",fill:"none",stroke:"currentColor",strokeWidth:3,"aria-hidden":"true",focusable:"false"},h("path",{d:"M7 3h40a4 4 0 0 1 4 4v24a4 4 0 0 1-4 4H23L10 45V35H7a4 4 0 0 1-4-4V7a4 4 0 0 1 4-4Z"}),h("path",{d:"M14 15h27M14 23h18"}))}function overviewRuntimeState(selected,loading,error3){if(error3)return{state:"warning",text:"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6700\u65B0\u72B6\u6001"};if(loading)return{state:"loading",text:"\u6B63\u5728\u8BFB\u53D6\u72B6\u6001"};if(!selected?.memoryOverview||!Number.isSafeInteger(selected.failedJobs)||selected.failedJobs<0||!Number.isSafeInteger(selected.processingJobs)||selected.processingJobs<0)return{state:"unknown",text:"\u72B6\u6001\u6682\u4E0D\u53EF\u7528"};if(selected.failedJobs>0)return{state:"failed",text:selected.failedJobs+" \u4E2A\u4EFB\u52A1\u9700\u8981\u5904\u7406"};let layers=selected.memoryOverview.layers;return selected.topicDirectoryReadError||!layers?.profile||!layers.directory||!layers.session||!layers.shortTerm||!layers.longTerm?{state:"warning",text:"\u90E8\u5206\u8BB0\u5FC6\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6"}:selected.processingJobs>0?{state:"processing",text:"\u6B63\u5728\u6574\u7406\u8BB0\u5FC6"}:{state:"ok",text:"\u8FD0\u884C\u6B63\u5E38"}}function OverviewPage({selected,loading,error:error3,onOpenSection,onOpenStatus}){let stats=selected?.memoryOverview;if(loading&&!stats)return h(Loading);if(!stats)return h(Empty,{title:"\u8FD8\u6CA1\u6709\u53EF\u6C47\u603B\u7684\u8BB0\u5FC6",copy:"\u8FD9\u4E2A\u5DE5\u4F5C\u533A\u7684\u8BB0\u5FC6\u8BFB\u51FA\u6765\u4E4B\u540E\uFF0C\u4F1A\u663E\u793A\u5728\u8FD9\u91CC\u3002"});let runtimeState=overviewRuntimeState(selected,loading,error3),layers=[{key:"profile",name:"\u5E38\u9A7B\u753B\u50CF",tone:"ink",section:"profile",value:stats.layers.profile?overviewCount(stats.layers.profile.characters):"\u2014",unit:"\u5B57",updatedAt:stats.layers.profile?.updatedAt},{key:"directory",name:"\u8BB0\u5FC6\u76EE\u5F55",tone:"moss",section:"long",value:stats.layers.directory?overviewCount(stats.layers.directory.chapters):"\u2014",unit:"\u7AE0",updatedAt:stats.layers.directory?.updatedAt},{key:"session",name:"\u4F1A\u8BDD\u8BB0\u5FC6",tone:"water",section:"short",value:overviewCount(stats.layers.session.blocks),unit:"\u5757",updatedAt:stats.layers.session.updatedAt},{key:"short",name:"\u77ED\u671F\u8BB0\u5FC6",tone:"sand",section:"daily",value:stats.layers.shortTerm?overviewCount(stats.layers.shortTerm.items):"\u2014",unit:"\u6761",updatedAt:stats.layers.shortTerm?.updatedAt},{key:"long",name:"\u957F\u671F\u8BB0\u5FC6",tone:"lib",section:"long",value:overviewCount(stats.layers.longTerm.events),unit:"\u4E2A\u4E8B\u4EF6",updatedAt:stats.layers.longTerm.updatedAt,answers:stats.layers.longTerm.answers}],heatmap=Array.isArray(stats.heatmap)?stats.heatmap:[],peak=Math.max(1,...heatmap.map(day=>Number(day.answers)||0));return h("section",{className:"sg-ov","data-testid":"stratagate-overview","aria-label":"\u8BB0\u5FC6\u603B\u89C8"},h("div",{className:"sg-ov-top"},h("div",{className:"sg-ov-stat"},h("div",{className:"sg-ov-big"},h("b",{className:"sg-mono","data-testid":"overview-answer-count"},overviewCount(stats.answeredLast7Days)),h(OverviewSpeechMark)),h("p",{className:"sg-ov-summary","data-testid":"overview-answer-summary"},"\u6700\u8FD1 7 \u5929\uFF0C\u957F\u671F\u8BB0\u5FC6\u5E2E\u5230 "+overviewCount(stats.answeredLast7Days)+" \u6B21\u56DE\u7B54"),h(typeof onOpenStatus=="function"?"button":"div",{type:typeof onOpenStatus=="function"?"button":void 0,className:"sg-ov-status","data-testid":"overview-runtime-status","data-state":runtimeState.state,onClick:onOpenStatus,title:typeof onOpenStatus=="function"?"\u67E5\u770B\u7CFB\u7EDF\u72B6\u6001":void 0},h("i",{className:"sg-runtime-dot","data-state":runtimeState.state,"aria-hidden":"true"}),h("span",null,runtimeState.text))),h("div",{className:"sg-pillar-group"},h("div",{className:"sg-pillar-cap","aria-hidden":"true"},h(OverviewSpeechMark)),h("div",{className:"sg-pillar","aria-label":"\u8BB0\u5FC6\u5206\u5C42"},layers.map(layer=>{let when="\u6700\u8FD1\u66F4\u65B0\uFF1A"+overviewRelative(layer.updatedAt),countText=layer.value==="\u2014"?"\u6682\u65E0\u6570\u636E":layer.value+" "+layer.unit,summary=layer.name+" "+countText+"\uFF0C"+when,open=()=>{typeof onOpenSection=="function"&&onOpenSection(layer.section)};return h(React.Fragment,{key:layer.key},layer.key==="long"?h("div",{className:"sg-pillar-gap","aria-hidden":"true"}):null,h("button",{type:"button",className:"sg-pillar-row","data-testid":"overview-layer-"+layer.key,"aria-label":"\u6253\u5F00"+layer.name+"\uFF1A"+countText+"\uFF0C"+when,title:summary,onClick:open},h("span",{className:"sg-pillar-bar "+layer.tone,"aria-hidden":"true"}),h("span",{className:"sg-pillar-name"},h("b",null,layer.name)),h("span",{className:"sg-pillar-tail"},h("span",{className:"sg-pillar-use"},layer.key==="long"&&layer.answers>0?h(UsedMark,{count:layer.answers,title:"\u88AB\u56DE\u7B54\u7528\u5230 "+layer.answers+" \u6B21"}):null),h("span",{className:"sg-pillar-val"},h("b",{className:"sg-mono"},layer.value),layer.value!=="\u2014"?h("span",{className:"sg-pillar-unit"},layer.unit):null))))})),h("div",{className:"sg-pillar-key"},h("span",null,h("i",{className:"sg-sw","aria-hidden":"true"}),"\u4E00\u76F4\u5E26\u7740"),h("span",null,h("i",{className:"sg-sw lib","aria-hidden":"true"}),"\u9700\u8981\u65F6\u53BB\u627E"),h("span",null,h(UsedMark),"\u88AB\u7528\u5230")))),h("div",{className:"sg-heat"},h("div",{className:"sg-heat-head"},h("span",null,h(UsedMark),"\u6BCF\u5929\u88AB\u56DE\u7B54\u7528\u5230\u51E0\u6B21"),h("span",null,"\u989C\u8272\u8D8A\u6DF1\u8D8A\u591A")),h("div",{className:"sg-heat-grid","aria-label":"\u6700\u8FD1 "+heatmap.length+" \u5929\u957F\u671F\u8BB0\u5FC6\u91C7\u7528"},heatmap.map(day=>{let answers=Number(day.answers)||0,ink=answers?Math.min(28+Math.round(answers/peak*62),90):0;return h("i",{key:day.day,title:day.day+" \xB7 "+answers+" \u6B21\u56DE\u7B54",style:answers?{background:"color-mix(in srgb, var(--sg-ink) "+ink+"%, var(--sg-sheet))",boxShadow:"none"}:void 0})})),h("div",{className:"sg-heat-scale"},h("span",null,heatmap.length>14?"4 \u5468\u524D":"2 \u5468\u524D"),h("span",null,"\u4ECA\u5929"))))}function MemoryPage({useWorkspaces,useSessions,navigationState,usePluginSettings,setMemoryModel,setEffort,resetEffort,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry,onOpenDreamingSession,onChooseSidebar,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let TAB_SWATCH={profile:"ink",short:"water",daily:"sand",long:"lib"},workspaceItems=useWorkspaces(state=>state.items),sessionById=useSessions(state=>state.byId||{}),[overview,setOverview]=React.useState({namespaces:[]}),[namespace,setNamespace]=React.useState(""),[workspaceTitles,setWorkspaceTitles]=React.useState({}),[workspaceSessionIds,setWorkspaceSessionIds]=React.useState({}),[conversationId,setConversationId]=React.useState(""),[section,setSection]=React.useState("overview"),[view,setView]=React.useState({name:"root"}),[graphFocusNodeId,setGraphFocusNodeId]=React.useState(""),consumeGraphFocus=React.useCallback(()=>setGraphFocusNodeId(""),[]),[data4,setData]=React.useState({events:[],graph:{nodes:[],edges:[],migration:null},blocks:[],openBlock:null,conversations:[],activeThreadId:null,audit:[],pagination:{events:{total:0,offset:0,limit:40},blocks:{total:0,offset:0,limit:40},audit:{total:0,offset:0,limit:100}}}),[query,setQuery]=React.useState(""),[source,setSource]=React.useState(null),[loading,setLoading]=React.useState(!0),[error3,setError]=React.useState(""),[recentError,setRecentError]=React.useState(""),[savingSettings,setSavingSettings]=React.useState(!1),[pollFast,setPollFast]=React.useState(!1),dashboardRequestRef=React.useRef(null),sourceRequestRef=React.useRef(null),namespaceRef=React.useRef(namespace);namespaceRef.current=namespace;let dashboardEtagsRef=React.useRef(new Map),loadedNamespaceRef=React.useRef(""),feedbackDeepLinkRef=React.useRef(readFeedbackNavigationState(navigationState)||readFeedbackDeepLink()),graphNodeNavigationRef=React.useRef(readGraphNodeNavigationState(navigationState)||readGraphNodeDeepLink()),feedbackNavigationStateRef=React.useRef(navigationState),namespaceNavigationRef=React.useRef(null),directoryScrollRef=React.useRef(null),reportError=reason=>{let message=String(reason?.message||reason);if(setError(message),setRecentError(message),namespace){let category=/timeout|timed out|超时/i.test(message)?"timeout":/fetch|network|网络/i.test(message)?"network":"request-failed";api2("diagnostics",{namespace,category},{method:"POST"}).catch(()=>{})}};React.useEffect(()=>{let active=!0;return Promise.all((workspaceItems||[]).map(async workspace=>({key:await workspaceProjectKey(workspace.path),title:String(workspace.title||"").trim(),sessionIds:Array.isArray(workspace.sessionIds)?workspace.sessionIds.map(String):[]}))).then(entries=>{active&&(setWorkspaceTitles(Object.fromEntries(entries.filter(({key,title})=>key&&title).map(({key,title})=>[key,title]))),setWorkspaceSessionIds(Object.fromEntries(entries.filter(({key})=>key).map(({key,sessionIds})=>[key,sessionIds]))))}),()=>{active=!1}},[workspaceItems]);let loadDashboard=React.useCallback((activeNamespace,options2={})=>{let background=options2.background===!0;if(background&&!options2.force&&dashboardRequestRef.current)return Promise.resolve(null);dashboardRequestRef.current?.abort();let controller=new AbortController;dashboardRequestRef.current=controller;let key=String(activeNamespace||"")+"\0"+String(options2.threadId||"");return background||setLoading(!0),background||setError(""),dashboardApi({...activeNamespace?{namespace:activeNamespace}:{},...options2.threadId?{threadId:options2.threadId}:{}},{etag:options2.force?"":dashboardEtagsRef.current.get(key),signal:controller.signal}).then(result=>{if(controller.signal.aborted||dashboardRequestRef.current!==controller||(result.etag&&dashboardEtagsRef.current.set(key,result.etag),result.notModified||!result.data))return null;let next2=result.data;return setOverview(next2.overview||{namespaces:[]}),setPollFast(next2.processing===!0),next2.namespace&&(loadedNamespaceRef.current=next2.namespace,setNamespace(current=>next2.overview?.namespaces?.some(item=>item.namespace===current)?current:next2.namespace)),next2.data&&(setData(next2.data),setConversationId(next2.data.activeThreadId||"")),setError(""),next2}).catch(reason=>{if(controller.signal.aborted||dashboardRequestRef.current!==controller)return null;if(reason?.name!=="AbortError"&&reportError(reason),options2.propagateError===!0&&reason?.name!=="AbortError")throw reason;return null}).finally(()=>{dashboardRequestRef.current===controller&&(dashboardRequestRef.current=null,setLoading(!1))})},[]);React.useEffect(()=>{let graphLink=graphNodeNavigationRef.current,feedbackLink=feedbackDeepLinkRef.current;return graphLink?(setSection("long"),setQuery(""),setView({name:"root"}),setSource(null),setGraphFocusNodeId(graphLink.nodeId),readGraphNodeDeepLink()&&consumeGraphNodeDeepLink()):feedbackLink&&(setSection("more"),setView({name:"support"}),setSource(null),readFeedbackDeepLink()&&consumeFeedbackDeepLink()),loadDashboard(graphLink?.namespace||feedbackLink?.namespace||""),()=>{dashboardRequestRef.current?.abort(),sourceRequestRef.current?.abort()}},[loadDashboard]),React.useEffect(()=>{let graphLink=navigationState!==feedbackNavigationStateRef.current?readGraphNodeNavigationState(navigationState):null,feedback=readNewFeedbackNavigationState(feedbackNavigationStateRef.current,navigationState);if(feedbackNavigationStateRef.current=navigationState,graphLink){setSection("long"),setView({name:"root"}),setSource(null),setGraphFocusNodeId(graphLink.nodeId),namespaceNavigationRef.current=namespace!==graphLink.namespace?{namespace:graphLink.namespace}:null,setNamespace(graphLink.namespace),namespace===graphLink.namespace&&loadDashboard(graphLink.namespace,{force:!0});return}feedback&&(setSection("more"),setView({name:"support"}),setSource(null),namespaceNavigationRef.current=namespace!==feedback.namespace?{namespace:feedback.namespace}:null,setNamespace(feedback.namespace),namespace===feedback.namespace&&loadDashboard(feedback.namespace,{force:!0}))},[navigationState,loadDashboard]),React.useEffect(()=>{if(!namespace)return;let navigated=namespaceNavigationRef.current?.namespace===namespace;namespaceNavigationRef.current=null,loadedNamespaceRef.current!==namespace&&(directoryScrollRef.current=null,setConversationId(""),navigated||setView({name:"root"}),setSource(null),setRecentError(""),setData({events:[],graph:{nodes:[],edges:[],migration:null},blocks:[],openBlock:null,conversations:[],activeThreadId:null,audit:[],pagination:{events:{total:0,offset:0,limit:40},blocks:{total:0,offset:0,limit:40},audit:{total:0,offset:0,limit:100}}}),loadDashboard(namespace,{force:!0}))},[namespace,loadDashboard]),React.useEffect(()=>{if(!namespace)return;let stopped=!1,timer=null,schedule=delay2=>{stopped||document.hidden||(timer=window.setTimeout(run,delay2))},run=()=>{stopped||document.hidden||loadDashboard(namespace,{background:!0,threadId:conversationId}).finally(()=>{schedule(pollFast?2500:3e4)})},onVisibilityChange=()=>{document.hidden?(timer!==null&&window.clearTimeout(timer),timer=null,dashboardRequestRef.current?.abort()):run()};return document.addEventListener("visibilitychange",onVisibilityChange),schedule(pollFast?2500:3e4),()=>{stopped=!0,timer!==null&&window.clearTimeout(timer),document.removeEventListener("visibilitychange",onVisibilityChange)}},[namespace,conversationId,pollFast,loadDashboard]);let selected=(overview.namespaces||[]).find(item=>item.namespace===namespace),runtimeState=overviewRuntimeState(selected,loading,error3),project=projectName(selected||namespace,workspaceTitles),activeProjectKey=namespace.includes(":project:")?namespace.split(":project:").pop():"",hostSessionIds=workspaceSessionIds[activeProjectKey]||[],memoryConversations=new Map(data4.conversations.map(conversation=>[conversation.id,conversation])),conversations=[],seenConversations=new Set;for(let id2 of hostSessionIds){let session=sessionById[id2];if(session?.parentId)continue;let memory=memoryConversations.get(id2),dshTitle=String(session?.title||"").trim();conversations.push({...memory||{},id:id2,label:dshTitle||memory?.label||"\u5BF9\u8BDD "+id2.slice(0,8)}),seenConversations.add(id2)}for(let memory of data4.conversations)seenConversations.has(memory.id)||conversations.push(memory);conversations.sort((left,right)=>left.id==="__legacy__"?1:right.id==="__legacy__"?-1:0);let clearSource=()=>{sourceRequestRef.current?.abort(),sourceRequestRef.current=null,setSource(null)},goSection=next2=>{directoryScrollRef.current=null,setSection(next2),setView({name:"root"}),clearSource()},sourceParams=(kind,item)=>kind==="event"?{eventId:item.id}:kind==="element"?{elementId:item.id}:{blockId:item.id},loadSource=(kind,item)=>{clearSource();let controller=new AbortController;sourceRequestRef.current=controller;let requestedNamespace=namespace,requestedId=String(item?.id||"");api2("sources",{namespace,...sourceParams(kind,item)},{signal:controller.signal}).then(value=>{if(sourceRequestRef.current!==controller||controller.signal.aborted||namespaceRef.current!==requestedNamespace)return;let returnedId=value?.event?.id||value?.element?.id||value?.block?.id||value?.id,returnedIds=Array.isArray(value?.events)?value.events.map(entry=>String(entry?.id||"")):[];returnedId&&String(returnedId)!==requestedId||returnedIds.length&&!returnedIds.includes(requestedId)||setSource(value)}).catch(reason=>{reason?.name!=="AbortError"&&sourceRequestRef.current===controller&&reportError(reason)})},openWithSource=(kind,item)=>{setView(current=>({name:kind,item,back:current})),loadSource(kind,item)},openEvent=(event3,trigger)=>{if(trigger?.getAttribute?.("data-topic-event-id")){let ancestors=[];for(let node=trigger.parentElement;node;node=node.parentElement)node.scrollHeight>node.clientHeight&&ancestors.push({node,top:node.scrollTop,left:node.scrollLeft});directoryScrollRef.current={namespace,eventId:event3.id,trigger,ancestors,top:window.scrollY||0,left:window.scrollX||0}}openWithSource("event",data4.events.find(item=>item.id===event3.id)||event3)};(React.useLayoutEffect||React.useEffect)(()=>{let saved=directoryScrollRef.current,action=directoryScrollAction(saved,section,namespace,view.name);if(action!=="none"){if(action==="clear"){directoryScrollRef.current=null;return}if(action==="detail"){for(let{node}of saved.ancestors)node.scrollTop=0,node.scrollLeft=0;window.scrollTo?.(0,0)}else if(action==="restore"){(saved.trigger?.isConnected&&saved.trigger.getClientRects().length?saved.trigger:Array.from(document.querySelectorAll(".sg-topic-event[data-topic-event-id]")).find(node=>node.getAttribute("data-topic-event-id")===saved.eventId&&node.getClientRects().length))?.focus?.({preventScroll:!0});for(let{node,top,left}of saved.ancestors)node.scrollTop=top,node.scrollLeft=left;window.scrollTo?.(saved.left,saved.top),directoryScrollRef.current=null}}},[view.name,section,namespace]);let openGraphNode=nodeId=>{directoryScrollRef.current=null,setSection("long"),setQuery(""),setView({name:"root"}),clearSource(),setGraphFocusNodeId(nodeId)},goBack=()=>{let previous=view.back||{name:"root"};setView(previous),previous.item&&["event","block"].includes(previous.name)?loadSource(previous.name,previous.item):clearSource()},backLabel=view.back?.name==="duplicates"?"\u91CD\u590D\u8BB0\u5FC6\u6574\u7406":view.back?.name==="block"?"\u4F1A\u8BDD\u8BB0\u5FC6":view.back?.name==="event"?"\u957F\u671F\u8BB0\u5FC6":view.back?.name==="structure"?"\u8BB0\u5FC6\u7ED3\u6784":section==="short"?"\u4F1A\u8BDD\u8BB0\u5FC6":"\u957F\u671F\u8BB0\u5FC6",refresh=(options2={})=>loadDashboard(namespace,{threadId:conversationId,force:!0,...options2}),refreshDirectory=React.useCallback(()=>loadDashboard(namespace,{threadId:conversationId,background:!0,force:!0}),[namespace,conversationId,loadDashboard]),selectConversation=nextConversationId=>(setConversationId(nextConversationId),loadDashboard(namespace,{threadId:nextConversationId,force:!0})),updateSettings=values=>(setSavingSettings(!0),setError(""),api2("settings",values,{method:"PATCH"}).then(()=>loadDashboard(namespace,{threadId:conversationId,force:!0})).catch(reportError).finally(()=>setSavingSettings(!1))),onRetrievalSettingsSaved=vectorSettings=>setOverview(current=>({...current,vectorSettings})),moreBack=()=>setView({name:"root"}),content=null;return(section==="long"||view.name==="support")&&loadedNamespaceRef.current!==namespace||loading&&!selected?content=h(Loading):view.name==="settings"&&!selected?content=h(SettingsPage,{graphSettings:overview.graphSettings,vectorSettings:overview.vectorSettings,retrievalSettingsWritable:overview.settingsWritable,onRetrievalSettingsSaved,refresh,selected:{blockTurnSize:6,blockDecayLambda:.3,agentMemoryRetrievalWeight:1,currentTurn:0,schemaVersion:12},namespace,dataDirectory:overview.dataDirectory,onBack:moreBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}):section==="overview"&&view.name==="root"?content=h(OverviewPage,{key:namespace,selected,loading,error:error3,onOpenSection:goSection,onOpenStatus:()=>setView({name:"status"})}):section==="profile"&&view.name==="root"?content=h(ProfilePage):section==="daily"&&view.name==="root"?content=h(DailyNotesPage,{key:namespace,namespace,setDailyInjectionDays}):!selected&&section!=="more"?content=h(Empty,{title:"\u8FD8\u6CA1\u6709\u8BB0\u5FC6",copy:"\u5B8C\u6210\u4E00\u4E9B DSH \u5BF9\u8BDD\u540E\uFF0C\u4F1A\u8BDD\u8BB0\u5FC6\u548C\u957F\u671F\u8BB0\u5FC6\u4F1A\u51FA\u73B0\u5728\u8FD9\u91CC\u3002"}):view.name==="event"?content=h(EventDetail,{event:view.item,project,source,onBack:goBack,backLabel,onNode:openGraphNode}):view.name==="status"?content=h(ProcessingStatus,{key:namespace,overview:selected,blocks:data4.blocks,conversations,namespace,serverVersion:overview.pluginVersion,onBack:view.back?goBack:()=>setView({name:"root"}),backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u8FD4\u56DE",refresh}):view.name==="import"?content=h(ImportPage,{key:namespace,namespace,onBack:moreBack,refresh}):view.name==="structure"?content=h(StructurePage,{events:data4.events,eventPage:data4.pagination?.events,graph:data4.graph,openEvent,namespace,onBack:moreBack}):view.name==="duplicates"?content=h(DuplicateReviewPage,{namespace,repair:selected?.duplicateRepair,onBack:moreBack,openEvent,refresh}):view.name==="system"?content=h(SystemPage,{selected,blocks:data4.blocks,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A",refresh,onDuplicates:()=>setView({name:"duplicates"})}):view.name==="audit"?content=h(AuditPage,{audit:data4.audit,auditPage:data4.pagination?.audit,namespace,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A"}):view.name==="raw"?content=h(RawPage,{data:data4,selected,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A"}):view.name==="display"?content=h(DisplayPage,{onBack:moreBack,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry}):view.name==="settings"?content=h(SettingsPage,{selected,graphSettings:overview.graphSettings,vectorSettings:overview.vectorSettings,retrievalSettingsWritable:overview.settingsWritable,onRetrievalSettingsSaved,refresh,namespace,dataDirectory:overview.dataDirectory,onBack:moreBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}):view.name==="support"?content=h(SupportPage,{key:namespace,namespace,overview,selected,data:data4,recentError,onBack:moreBack}):content=h(React.Fragment,null,loading?h(Loading):section==="short"?h(ShortTermPage,{key:namespace+":"+conversationId,blockTurnSize:selected?.blockTurnSize||6,blocks:data4.blocks,blockPage:data4.pagination?.blocks,openBlock:data4.openBlock,conversations,activeThreadId:conversationId||data4.activeThreadId||"",namespace,onConversationChange:selectConversation,refresh}):section==="long"?null:h(MoreHome,{setView,selected,overview,namespace,dataDirectory:overview.dataDirectory,updateSettings,savingSettings,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry,setDailyEnabled,setDailyInjectionDays})),h("main",{className:"sg-memory sg-unified-top"+(section==="overview"&&view.name==="root"?" sg-overview-page":"")+(view.name==="duplicates"?" sg-memory-review":"")+(view.name==="settings"||view.name==="display"||section==="more"&&view.name==="root"?" sg-settings-page":""),"data-testid":"stratagate-memory-ui"},h("style",null,css+DUPLICATE_STYLES+DAILY_NOTES_CSS+R6_STYLES),h("header",{className:"sg-header"},h("div",{className:"sg-header-row sg-header-row-primary"},h(GITHUB_FEEDBACK_ENABLED?"a":"div",{className:"sg-brand",href:GITHUB_FEEDBACK_ENABLED?STAR_REPOSITORY_URL:void 0,target:GITHUB_FEEDBACK_ENABLED?"_blank":void 0,rel:GITHUB_FEEDBACK_ENABLED?"noopener noreferrer":void 0},h(StrataGateMark),h("span",{className:"sg-brand-copy"},h("span",{className:"sg-brand-title"},h("span",{className:"sg-brand-name"},"StrataGate"),overview.pluginVersion&&overview.pluginVersion!=="unknown"?h("span",{className:"sg-brand-version"},"v"+overview.pluginVersion):null),onChooseSidebar?h(SidebarPlacementPrompt,{onChooseSidebar,usePluginSettings}):null)),h("div",{className:"sg-header-end"},h("div",{className:"sg-project"},h("i",{className:"sg-runtime-dot","data-testid":"overview-workspace-dot","data-state":runtimeState.state,role:"img","aria-label":runtimeState.text,title:runtimeState.text}),h("span",{className:"sg-project-label"},"\u5F53\u524D\u5DE5\u4F5C\u533A"),h("select",{className:"sg-project-select",value:namespace,onChange:event3=>setNamespace(event3.target.value),"aria-label":"\u5F53\u524D\u5DE5\u4F5C\u533A"},(overview.namespaces||[]).map(item=>h("option",{key:item.namespace,value:item.namespace},projectName(item,workspaceTitles))))),GITHUB_FEEDBACK_ENABLED?h(HeaderStarLink):null)),h("nav",{className:"sg-tabs","aria-label":"\u8BB0\u5FC6\u89C6\u56FE"},[["overview","\u603B\u89C8"],["profile","\u5E38\u9A7B\u753B\u50CF"],["short","\u4F1A\u8BDD\u8BB0\u5FC6"],["daily","\u77ED\u671F\u8BB0\u5FC6"],["long","\u957F\u671F\u8BB0\u5FC6"],["more","\u66F4\u591A"]].map(([id2,label])=>h("button",{key:id2,type:"button",className:"sg-tab "+(section===id2?"active":""),"aria-current":section===id2?"page":void 0,onClick:()=>goSection(id2)},TAB_SWATCH[id2]?h("i",{key:"sw",className:"sg-tab-swatch "+TAB_SWATCH[id2],"aria-hidden":"true"}):null,label))),h("div",{className:"sg-page-body"},error3?h("div",{className:"sg-error"},h("div",{className:"sg-error-title"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u5B8C\u6574\u8BB0\u5FC6"),h("div",null,"\u5DF2\u663E\u793A\u80FD\u591F\u8BFB\u53D6\u7684\u5185\u5BB9\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u52A0\u8F7D\u3002"),h("details",null,h("summary",null,"\u6280\u672F\u8BE6\u60C5"),h("div",{className:"sg-code"},error3))):null,view.name==="root"&&selected?.duplicateRepair?.needsReview>0?h("button",{type:"button",className:"sg-dup-entry",onClick:()=>setView({name:"duplicates"})},h(DuplicateIcon,{size:23}),h("span",null,h("strong",null,selected.duplicateRepair.needsReview+" \u7EC4\u76F8\u4F3C\u8BB0\u5FC6\uFF0C\u7B49\u4F60\u786E\u8BA4"),h("small",null,"\u5BF9\u6BD4\u5185\u5BB9\uFF0C\u9009\u62E9\u4FDD\u7559\u54EA\u5F20\u6216\u5408\u5E76\u53CC\u65B9\u8BC1\u636E")),h(DuplicateIcon,{kind:"next"})):null,h("section",{key:section,className:"sg-view","aria-label":"StrataGate \u8BB0\u5FC6\u5185\u5BB9"},section==="long"&&selected&&loadedNamespaceRef.current===namespace?h(React.Fragment,null,h("div",{key:"long-browser",hidden:view.name!=="root"},h(LongTermPage,{graphSettings:overview.graphSettings,extractionGap:selected?.longTermExtractionGap===!0,key:namespace,events:data4.events,eventPage:data4.pagination?.events,graph:data4.graph,project,query,setQuery,openEvent,namespace,focusNodeId:graphFocusNodeId,onFocusHandled:consumeGraphFocus,topicDirectory:data4.topicDirectory,onDirectoryChanged:refreshDirectory,onOpenDreamingSession,refresh,active:view.name==="root"})),view.name==="root"?null:content):content),h("footer",{className:"sg-footer"},h("span",null,"StrataGate-AgentMemory \xB7 MIT"),h("span",{className:"sg-footer-links"},h("a",{href:STAR_REPOSITORY_URL,target:"_blank",rel:"noopener noreferrer"},"GitHub \u4ED3\u5E93")," \xB7 ",h("a",{href:ISSUE_URL,target:"_blank",rel:"noopener noreferrer"},"\u63D0 Issue")," \xB7 ",h("a",{href:STAR_REPOSITORY_URL+"/releases",target:"_blank",rel:"noopener noreferrer"},"\u66F4\u65B0\u8BB0\u5F55"))))))}function MemoryPanel(props){return h("div",{className:"sg-memory-panel",style:{flex:"1 1 0%",minHeight:0,width:"100%",overflowY:"auto",overflowX:"hidden"}},h(MemoryPage,props))}function readSidebarPromptState(){try{return String(globalThis.localStorage?.getItem(SIDEBAR_PROMPT_STORAGE_KEY)||"")}catch{return""}}function writeSidebarPromptState(value){try{globalThis.localStorage?.setItem(SIDEBAR_PROMPT_STORAGE_KEY,value)}catch{}}function StrataGatePanelIcon({size:size3=20}){return h("svg",{width:size3,height:size3,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,focusable:!1,className:"sg-sidebar-panel-icon",style:{display:"block",flexShrink:0}},h("path",{opacity:.28,strokeWidth:1.4,d:"M3 12V4a1 1 0 0 1 1-1h8"}),h("path",{opacity:.55,d:"M6 15V7a1 1 0 0 1 1-1h9"}),h("rect",{x:9,y:9,width:12,height:13,rx:1.8}),h("path",{d:"M12 13h6M12 17h4"}))}function SidebarPlacementPrompt({onChooseSidebar,usePluginSettings}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[visible,setVisible]=React.useState(()=>readSidebarPromptState()!=="dismissed"),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState("");if(!visible||settings?.value?.showSidebarEntry===!0||settings?.writable!==!0)return null;let dismiss=()=>{writeSidebarPromptState("dismissed"),setVisible(!1)},chooseSidebar=async()=>{setBusy(!0),setError("");try{if(!await onChooseSidebar?.()){setError("\u672A\u80FD\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002");return}writeSidebarPromptState("sidebar"),setVisible(!1)}catch{setError("\u672A\u80FD\u4FDD\u5B58\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002")}finally{setBusy(!1)}};return h(React.Fragment,null,h("style",null,SIDEBAR_PROMPT_STYLES),h("span",{className:"sg-sidebar-placement-prompt",role:"region","aria-label":"StrataGate \u4FA7\u680F\u5165\u53E3\u63D0\u793A"},h("span",{className:"sg-sidebar-placement-text"},"\u4ECE\u5DE6\u4FA7\u680F\u5FEB\u901F\u6253\u5F00\u8BB0\u5FC6"),h("button",{type:"button",className:"sg-sidebar-placement-action",disabled:busy,onClick:()=>{chooseSidebar()}},"\u653E\u5230\u5DE6\u4FA7\u680F"),h("button",{type:"button",className:"sg-sidebar-placement-close","aria-label":"\u5173\u95ED\u4FA7\u680F\u5165\u53E3\u63D0\u793A",title:"\u4E0D\u518D\u63D0\u9192",disabled:busy,onClick:dismiss},"\xD7"),error3?h("span",{role:"alert"},error3):null))}let disposeFeedbackLinkNavigation=null;function apply2(ctx){let slots=ctx.get("slots");if(!slots)return;let configForms=ctx.get("configForms"),settingsScope=ctx.get("settingsScope"),pluginSettingsScope=configForms?configForms.get("stratagate-memory"):settingsScope?settingsScope.bind({namespace:"stratagate-memory"}):null,setSidebarEntry=async visible=>{if(!pluginSettingsScope||!await pluginSettingsScope.set("showSidebarEntry",visible))return!1;if(!visible){let layout4=ctx.get("layout");layout4?.activePanelId===MEMORY_PANEL_ID&&layout4.selectPanel?.(null)}return!0},warnCitationFailure=(part,error3)=>{if(!(typeof console>"u"||typeof console.warn!="function"))try{console.warn("[StrataGate] "+part+" registration failed; memory settings remain available.",error3)}catch{}};slots.inject("settings.section",()=>slots.register({name:"settings.section",id:"stratagate-memory",order:32,label:()=>"StrataGate-AgentMemory",inject:()=>({hooks:{pluginSettings:pluginSettingsScope},setMemoryModel:pluginSettingsScope?selection=>pluginSettingsScope.set("memoryModel",selection):null,setEffort:pluginSettingsScope?mode=>pluginSettingsScope.set("structuredReasoningEffort",mode):null,setDailyEnabled:pluginSettingsScope?enabled=>pluginSettingsScope.set("dailyNotesEnabled",enabled):null,setDailyInjectionDays:pluginSettingsScope?days=>pluginSettingsScope.set("dailyNotesInjectionDays",days):null,setDailyTimeZone:pluginSettingsScope?zone=>zone?pluginSettingsScope.set("dailyNotesTimeZone",zone):pluginSettingsScope.unset("dailyNotesTimeZone"):null,resetEffort:pluginSettingsScope?()=>pluginSettingsScope.unset("structuredReasoningEffort"):null,setStrataGateStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showStrataGateStatus",visible):null,setShortTermStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showShortTermStatus",visible):null,setRetrievalStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showRetrievalStatus",visible):null,setSidebarEntry:pluginSettingsScope?setSidebarEntry:null})},props=>h(FeedbackSettingsPage,{...props,onChooseSidebar:async()=>{let layout4=ctx.get("layout");return typeof layout4?.selectPanel!="function"||!await setSidebarEntry(!0)?!1:(layout4.selectPanel(MEMORY_PANEL_ID),props.close?.(),!0)},onOpenDreamingSession:sessionId=>{let navigation=ctx.get("uiWorkspace");if(typeof navigation?.openSession!="function")throw new Error("\u5F53\u524D DSH \u672A\u63D0\u4F9B\u4F1A\u8BDD\u5BFC\u822A\uFF0C\u8BF7\u5347\u7EA7\u5BBF\u4E3B\u540E\u91CD\u8BD5");navigation.openSession(sessionId),props.close?.()}})));let memoryPanelInject=()=>({setMemoryModel:pluginSettingsScope?selection=>pluginSettingsScope.set("memoryModel",selection):null,...pluginSettingsScope?{hooks:{pluginSettings:pluginSettingsScope}}:{},setEffort:pluginSettingsScope?mode=>pluginSettingsScope.set("structuredReasoningEffort",mode):null,setDailyEnabled:pluginSettingsScope?enabled=>pluginSettingsScope.set("dailyNotesEnabled",enabled):null,setDailyInjectionDays:pluginSettingsScope?days=>pluginSettingsScope.set("dailyNotesInjectionDays",days):null,setDailyTimeZone:pluginSettingsScope?zone=>zone?pluginSettingsScope.set("dailyNotesTimeZone",zone):pluginSettingsScope.unset("dailyNotesTimeZone"):null,resetEffort:pluginSettingsScope?()=>pluginSettingsScope.unset("structuredReasoningEffort"):null,setStrataGateStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showStrataGateStatus",visible):null,setShortTermStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showShortTermStatus",visible):null,setRetrievalStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showRetrievalStatus",visible):null,setSidebarEntry:pluginSettingsScope?setSidebarEntry:null,onOpenDreamingSession:sessionId=>{let navigation=ctx.get("uiWorkspace");if(typeof navigation?.openSession!="function")throw new Error("\u5F53\u524D DSH \u672A\u63D0\u4F9B\u4F1A\u8BDD\u5BFC\u822A\uFF0C\u8BF7\u5347\u7EA7\u5BBF\u4E3B\u540E\u91CD\u8BD5");navigation.openSession(sessionId)}});try{slots.inject("main",()=>slots.register({name:"main",key:MEMORY_PANEL_ID,order:20,inject:memoryPanelInject},MemoryPanel)),slots.inject("sidebar.panellist",()=>{let removeEntry=null,syncSidebar=()=>{let snapshot=pluginSettingsScope?.getSnapshot?.();if(snapshot?.status==="loading")return;let visible=snapshot?.value?.showSidebarEntry===!0;visible&&!removeEntry?removeEntry=slots.register({name:"sidebar.panellist",id:MEMORY_PANEL_ID,order:20,label:()=>"StrataGate \u8BB0\u5FC6"},StrataGatePanelIcon)||(()=>{}):!visible&&removeEntry&&(removeEntry(),removeEntry=null)},unsubscribe=pluginSettingsScope?.subscribe?.(syncSidebar);return syncSidebar(),()=>{unsubscribe?.(),removeEntry?.(),removeEntry=null}})}catch(error3){warnCitationFailure("sidebar entry",error3)}try{let uiConversation=ctx.get("uiConversation");uiConversation&&(uiConversation.events.register(memoryCitationsDefinition),ensureCitationStyles(),slots.inject("conversation.chat.turnTail",()=>{try{return slots.register({name:"conversation.chat.turnTail",id:"stratagate-memory-citations",select:selectMemoryCitations,inject:()=>({...pluginSettingsScope?{hooks:{pluginSettings:pluginSettingsScope}}:{},onOpenGraphNode:(namespace,nodeId)=>navigateToGraphNode(ctx,namespace,nodeId)})},MemoryCitationTail)}catch(error3){return warnCitationFailure("chat turn tail",error3),()=>{}}}))}catch(error3){warnCitationFailure("chat citations",error3)}if(typeof document<"u"){disposeFeedbackLinkNavigation?.();let disposeLinkNavigation=installFeedbackLinkNavigation(ctx),disposeDeepLink=openFeedbackDeepLink(ctx),disposeGraphDeepLink=openGraphNodeDeepLink(ctx);disposeFeedbackLinkNavigation=()=>{disposeLinkNavigation(),disposeDeepLink(),disposeGraphDeepLink()}}}return exports.name="stratagate-dsh",exports.inject=["slots","uiConversation"],exports.apply=apply2,module.exports}});})();