import {n,p as p$1}from'./chunk-BKZZV17h.js';import {J,c as tS,a5 as fh,cI as p,gK as Jc,gL as ld,as as t,aH as $t,j as Re$1,aM as AD,a7 as si,b3 as w,ef as T,d5 as Aa,cN as g,gM as qe,L as w$1,bZ as J$1,gN as D$,aK as Le,m as ot,aN as r4,ac as Dr,bd as K,a9 as zt,gO as wa,aA as o$1,el as d,w as wo,d6 as Do,bW as JT,bu as dy,bv as Vy,bw as y_,bx as v_}from'./main-WUGO6e7n.js';var ie,Re,ne=J(()=>{tS();fh();p();Jc();ld();n();t();$t();Re$1();AD();si();w();T();tS();Aa();ie=["messagesContainer"],Re=(()=>{class S extends g{get isTyping(){return this.isSending&&!this.isStreaming}get canSend(){return !this.isDisabled&&!this.isSending&&this.pendingReads===0&&(!!this.inputText.trim()||this.pendingFiles.length>0)}get providerLabel(){if(!this.aiConfig||this.aiConfig.aiProvider===qe.None)return "";let e=p$1(this.aiConfig.aiProvider);return this.aiConfig.aiModel?`${e} \xB7 ${this.aiConfig.aiModel}`:e}constructor(e){super(),this.httpClient=e,this.messages=[],this.inputText="",this.isSending=!1,this.isStreaming=!1,this.isDragging=!1,this.pendingFiles=[],this.pendingReads=0,this.fileError=null,this.fileErrorParam=null,this.connectionId="",this.aiConfig=null,this.isDisabled=!1,this.MAX_FILE_SIZE=200*1024,this.MAX_FILES=5,this.MAX_TOTAL_PAYLOAD_SIZE=1024*1024,this.autoScrollBottomThresholdPx=80,this.isPinnedToBottom=!0,this.readBatchId=0,this._thinkState="none",this._thinkBuffer="",this._sseBuffer="",this.streamNgZone=w$1(J$1),this.changeDetectorRef=w$1(D$),this.oauthService=w$1(Le),this.authService=w$1(ot),this.serverInfoService=w$1(r4),this.currentUserService=w$1(Dr),this.errorService=w$1(K),this.activeStreamRequest=null,this.renderSyncScheduled=!1,this.streamRequestId=0;}sendMessage(){let e=this.inputText.trim();if(!e&&!this.pendingFiles.length||this.isSending)return;let t=[...this.pendingFiles];this.messages.push({role:"user",content:e,files:t.length?t:void 0}),this.scrollToBottom(!0),this.inputText="",this.pendingFiles=[],this.readBatchId++,this.fileError=null,this.fileErrorParam=null,this.isSending=!0,this.isStreaming=!1;let s=this.messages.filter(r=>r.role==="user"||r.role==="assistant").map(r=>({role:r.role,content:r.role==="user"?this.buildMessageContent(r):r.content}));if(s.reduce((r,f)=>r+f.content.length,0)>this.MAX_TOTAL_PAYLOAD_SIZE){this.messages.push({role:"error",content:"lblAIAssistantPayloadTooLarge"}),this.isSending=!1,this.scrollToBottom(!0);return}let i=++this.streamRequestId,o=null,n=!1,u=!1;this._sseBuffer="";let d=new Set,m=new Set,h=r=>{let{content:f,error:c,toolCalls:I,toolResults:v}=r;if(c){n=!0,o&&(this.messages=this.messages.filter(l=>l!==o),o=null),this.messages.push({role:"error",content:c}),this.isSending=!1,this.isStreaming=!1,this.scrollToBottom(!0),this.scheduleViewSync();return}if(!n){for(let l of I)d.has(l.callId)||this.messages.some(p=>p.role==="tool"&&p.toolCallId===l.callId)||(d.add(l.callId),this.messages.push({role:"tool",content:"",toolCallId:l.callId,toolName:l.toolName,toolStatus:"pending"}));I.length&&o&&this.moveMessageToEnd(o);for(let l of v){if(l.callId&&m.has(l.callId))continue;l.callId&&m.add(l.callId);let p=this.messages.find(R=>R.role==="tool"&&R.toolCallId===l.callId);p?(p.toolStatus="done",p.toolResult=l.result):this.messages.push({role:"tool",content:"",toolCallId:l.callId,toolName:l.toolName,toolStatus:"done",toolResult:l.result});}v.length&&o&&this.moveMessageToEnd(o),(I.length||v.length)&&(this.scrollToBottom(),this.scheduleViewSync()),r.confirmationPayload&&(this.messages.push({role:"confirmation",content:"",confirmationPayload:r.confirmationPayload}),o&&this.moveMessageToEnd(o),this.scrollToBottom(),this.scheduleViewSync()),f&&(o||(o={role:"assistant",content:""},this.messages.push(o),this.isStreaming=!0,this._thinkState="none"),o.content+=this.processThinkChunk(f),this.scrollToBottom(),this.scheduleViewSync());}};this.startStreamRequest(i,{connectionId:this.connectionId||null,chatHistory:s},r=>{this.streamNgZone.run(()=>{i===this.streamRequestId&&h(this.parseSseChunk(r));});},()=>{this.streamNgZone.run(()=>{i!==this.streamRequestId||n||u||(this._sseBuffer.trim()&&h(this.parseSseChunk(`

`)),u||(u=!0,this.onResponseComplete(o),this.scheduleViewSync()));});},r=>{this.streamNgZone.run(()=>{i===this.streamRequestId&&(this.onSendError(r),this.isSending=!1,this.isStreaming=!1,this.scrollToBottom(!0),this.scheduleViewSync());});});}onKeyDown(e){e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.sendMessage());}onMessagesScroll(){this.isPinnedToBottom=this.isContainerPinnedToBottom();}clearChat(){this.streamRequestId++,this.activeStreamRequest&&(this.activeStreamRequest.abort(),this.activeStreamRequest=null),this.messages=[],this.inputText="",this.pendingFiles=[],this.pendingReads=0,this.fileError=null,this.fileErrorParam=null,this.isSending=!1,this.isStreaming=!1,this._thinkState="none",this._thinkBuffer="",this._sseBuffer="",this.isPinnedToBottom=!0;}ngOnDestroy(){this.activeStreamRequest&&(this.activeStreamRequest.abort(),this.activeStreamRequest=null),super.ngOnDestroy();}addFiles(e){this.fileError=null;let t=this.MAX_FILES-this.pendingFiles.length;if(t<=0){this.fileError="lblAIAssistantTooManyFiles",this.fileErrorParam=this.MAX_FILES;return}let s=!1,a=this.readBatchId;Array.from(e).slice(0,t).forEach(i=>{if(i.size>this.MAX_FILE_SIZE){s=!0;return}this.pendingReads++;let o=new FileReader;o.onload=n=>{if(this.pendingReads--,a!==this.readBatchId)return;let u=n.target?.result;if(!u?.trim()){this.fileError="lblAIAssistantEmptyFile";return}this.pendingFiles.push({name:i.name,content:u,size:i.size});},o.onerror=()=>{this.pendingReads--,this.fileError="lblAIAssistantFileReadError";},o.readAsText(i);}),s&&(this.fileError="lblAIAssistantFileTooLarge",this.fileErrorParam=this.MAX_FILE_SIZE/1024);}removeFile(e){this.readBatchId++,this.pendingFiles.splice(e,1),this.fileError=null,this.fileErrorParam=null;}onFileInputChange(e){let t=e.target;t.files?.length&&this.addFiles(t.files),t.value="";}onDragOver(e){e.preventDefault(),this.isDragging=!0;}onDragLeave(e){e.currentTarget.contains(e.relatedTarget)||(this.isDragging=!1);}onDrop(e){e.preventDefault(),this.isDragging=!1;let t=e.dataTransfer?.files;t?.length&&this.addFiles(t);}loadAiConfig(){this.loadGlobalAiConfig();}onResponseComplete(e){let t=this.messages[this.messages.length-1];if(e?.content)e.content=e.content.replace(/\n{3,}/g,`

`).trim();else {if(t?.role==="confirmation"||t?.role==="tool"&&t.toolStatus==="done"){this.isSending=!1,this.isStreaming=!1;return}e&&(this.messages=this.messages.filter(s=>s!==e)),this.messages.push({role:"error",content:"lblAIAssistantEmptyResponse"});}this.isSending=!1,this.isStreaming=!1,this.scrollToBottom(!0);}onSendError(e){this.messages.push({role:"error",content:this.extractErrorMessage(e)});}scrollToBottom(e=!1){let t=e||this.isPinnedToBottom;setTimeout(()=>{t&&this.messagesContainer&&(this.messagesContainer.nativeElement.scrollTop=this.messagesContainer.nativeElement.scrollHeight,this.isPinnedToBottom=!0);},100);}isContainerPinnedToBottom(){if(!this.messagesContainer)return !0;let{scrollTop:e,clientHeight:t,scrollHeight:s}=this.messagesContainer.nativeElement;return e+t>=s-this.autoScrollBottomThresholdPx}moveMessageToEnd(e){let t=this.messages.indexOf(e);t===-1||t===this.messages.length-1||(this.messages.splice(t,1),this.messages.push(e));}extractErrorMessage(e){if(e&&typeof e=="object"){let t=e;if(t.error&&typeof t.error=="object"){let s=t.error;if(typeof s.message=="string")return s.message}if(typeof t.message=="string")return t.message}return "lblAIAssistantError"}buildMessageContent(e){let t=e.files?.filter(a=>!!a.content?.trim());if(!t?.length)return e.content;let s=t.map(a=>`<file name="${a.name}">
${a.content}
</file>`).join(`

`);return e.content?`${s}

${e.content}`:s}loadGlobalAiConfig(){let e=this.connectionId?`api/ai/configuration?connectionId=${encodeURIComponent(this.connectionId)}`:"api/ai/configuration";this.httpClient.get(e).pipe(zt(1)).subscribe({next:t=>{let s=t?.data;s&&!s.isEnabled?(this.isDisabled=!0,this.aiConfig=null):s&&s.provider!==qe.None?(this.isDisabled=!1,this.aiConfig=new wa({aiProvider:s.provider,aiModel:s.model,aiApiKey:""})):(this.isDisabled=!1,this.aiConfig=null);},error:()=>{this.aiConfig=null;}});}processThinkChunk(e){e=this._thinkBuffer+e,this._thinkBuffer="";let t="",s=0,a=e.toLowerCase();for(;s<e.length;)if(this._thinkState==="inside"){let i=a.indexOf("</think>",s);if(i===-1)return this._thinkBuffer=this._extractPartialTag(e.slice(s),"</think>"),t;this._thinkState="none",s=i+8;}else {let i=a.indexOf("<think>",s);if(i===-1){let o=e.slice(s),n=this._extractPartialTag(o,"<think>");return t+=o.slice(0,o.length-n.length),this._thinkBuffer=n,t}t+=e.slice(s,i),this._thinkState="inside",s=i+7;}return t}_extractPartialTag(e,t){let s=e.toLowerCase(),a=t.toLowerCase();for(let i=Math.min(t.length-1,e.length);i>=1;i--)if(a.startsWith(s.slice(s.length-i)))return e.slice(e.length-i);return ""}parseSseChunk(e){let t="",s,a=[],i=[],o,n=(this._sseBuffer+e).replace(/\r\n/g,`
`).replace(/\r/g,`
`),u=n.split(`

`),d=n.endsWith(`

`);this._sseBuffer=d?"":u.pop()??"";for(let m of u.filter(h=>h.trim())){let h=m.split(`
`),r=h.find(c=>c.startsWith("event: "))?.slice(7),f=h.filter(c=>c.startsWith("data: ")).map(c=>c.slice(6)).join(`
`);if(r==="error")s=f;else if(r==="tool_call")try{a.push(JSON.parse(f));}catch(c){}else if(r==="tool_result")try{i.push(JSON.parse(f));}catch(c){}else if(r==="confirmation_required")try{o=JSON.parse(f);}catch(c){}else t+=f;}return {content:t,error:s,toolCalls:a,toolResults:i,confirmationPayload:o}}startStreamRequest(e,t,s,a,i,o=!0){this.activeStreamRequest&&(this.activeStreamRequest.abort(),this.activeStreamRequest=null);let n=new XMLHttpRequest;this.activeStreamRequest=n;let u=0,d=null;n.open("POST",`${o$1.dvlsUrl}api/ai/chat/stream`,!0),n.setRequestHeader("Content-Type","application/json"),n.setRequestHeader("Accept","text/event-stream");let m=this.oauthService.getAccessToken();m&&n.setRequestHeader("Authorization",`Bearer ${m}`),n.withCredentials=o$1.production,n.onreadystatechange=()=>{n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&n.status>=400&&(d=n.status);},n.onprogress=()=>{if(e!==this.streamRequestId||d!==null)return;let h=n.responseText??"",r=h.slice(u);u=h.length,r&&s(r);},n.onerror=()=>{e===this.streamRequestId&&(this.activeStreamRequest=null,i("lblAIAssistantRequestFailed"));},n.onloadend=()=>{if(e!==this.streamRequestId)return;let h=d??n.status,r=n.responseText??"",f=n.getAllResponseHeaders().toLowerCase();if(this.activeStreamRequest=null,h>=200&&h<400){let c=r.slice(u);c&&s(c),a();return}if(h===401){if(!o||!this.oauthService.getAccessToken()){this.authService.logout(),i("lblAIAssistantRequestFailed");return}this.oauthService.refreshToken().then(()=>{e===this.streamRequestId&&this.startStreamRequest(e,t,s,a,i,!1);}).catch(()=>{this.authService.logout(),i("lblAIAssistantRequestFailed");});return}h===403&&f.includes("application/json")&&this.tryHandleLimitedMode(r)||h!==0&&i("lblAIAssistantRequestFailed");},n.send(JSON.stringify(t));}tryHandleLimitedMode(e){try{let t=JSON.parse(e);return t?.limitExceeded?(this.errorService.pushError(new d({fatal:!1,message:t.message,messageDetail:t.errorMessage})),this.serverInfoService.update(),this.currentUserService.refreshAccessInformations(),this.isSending=!1,this.isStreaming=!1,this.scheduleViewSync(),!0):!1}catch(t){return !1}}scheduleViewSync(){this.renderSyncScheduled||(this.renderSyncScheduled=!0,requestAnimationFrame(()=>{this.renderSyncScheduled=!1,this.streamNgZone.run(()=>{this.changeDetectorRef.detectChanges();});}));}static{this.\u0275fac=function(t){return new(t||S)(wo(Do))};}static{this.\u0275dir=JT({type:S,viewQuery:function(t,s){if(t&1&&Vy(ie,5),t&2){let a;y_(a=v_())&&(s.messagesContainer=a.first);}},features:[dy]});}}return S})();});export{Re as R,ne as n};