1"use strict";(self.webpackChunkknowledge_base_saas=self.webpackChunkknowledge_base_saas||[]).push([[1062],{1062(e,t,n){n.r(t),n.d(t,{default:()=>ye});var i=n(89379),s=n(5544),r=n(65043),o=n(47874),a=n(14939),c=n(41680),l=n(37719),d=n(84669),u=n(7365),g=n(65727),p=n(10629),m=n(14459),h=n(72313),y=n(61064),f=n(35746),x=n(92339),A=n(34528),w=n(37322),v=n(59395),E=n(66630),b=n(67898),C=n(52395),k=n(96822),S=n(48749),I=n(96060),_=n(20715),R=n(65584),T=n(29285),N=n(43677),D=n(38937),P=n(75381),j=n(40614),U=n(88693),O=n(15003);const L=(0,C.getFunctions)(k.yA,"us-central1"),G=(0,C.httpsCallable)(L,"createRealtimeSession");class M{constructor(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"marin",s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,r=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null;this.onTranscription=e,this.onResponse=t,this.onError=n,this.onResponseDelta=s,this.onUserSpeaking=r,this.onAISpeaking=o,this.voice=i,this.peerConnection=null,this.audioStream=null,this.dataChannel=null,this.isConnected=!1,this.isConnecting=!1,this.isListening=!1,this.isSpeaking=!1,this.sessionId=null,this.currentTranscription="",this.audioElement=null,this.audioMonitorInterval=null,this.receivedFinalTranscript=!1,this.accumulatedResponse="",this.systemPromptSent=!1,this.pendingUserMessage=null,this.pendingResponseCreation=!1,this.sessionUpdateConfirmed=!1,this.currentSystemPrompt=null,this.pendingUserMessage=null,this.sessionUpdateConfirmed=!1,this.audioContext=null,this.analyser=null,this.microphone=null,this.audioLevelInterval=null,this.isUserSpeaking=!1,this.speakingThreshold=.02,this.aiAudioMonitorInterval=null,this.isAIActuallySpeaking=!1,this.lastAIAudioTime=0,this.audioAnalyser=null,this.audioDataArray=null,this.audioStreamSource=null,this.hasActiveResponse=!1,this.isInterrupted=!1,this.waitForAudioTimeout=null,this.waitForAudioInterval=null,this.waitForAudioSafetyTimeout=null}async connect(){if(this.isConnected||this.isConnecting)(0,_.gg)("Already connected or connecting");else{this.isConnecting=!0;try{var e;(0,_.gg)("Requesting microphone access..."),this.audioStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:24e3}}),(0,_.gg)("\u2705 Microphone access granted"),this.setupAudioLevelMonitoring();const t=(0,b.xI)();if(!t.currentUser)throw new Error("User must be authenticated");(0,_.gg)("User authenticated:",t.currentUser.email),(0,_.gg)("Getting ephemeral token from server...");const n=await G({model:"gpt-4o-realtime-preview-2024-12-17",voice:this.voice});if(null===(e=n.data)||void 0===e||!e.clientSecret)throw new Error("Failed to get ephemeral token");const i=n.data.clientSecret;if((0,_.gg)("\u2705 Ephemeral token received"),!this.audioStream)throw new Error("Audio stream not available");this.peerConnection=new RTCPeerConnection;const s=this.audioStream.getTracks();if(!s||0===s.length)throw new Error("No audio tracks available in stream");s.forEach(e=>{e.enabled=!1,this.peerConnection.addTrack(e,this.audioStream)});let r=!1;this.peerConnection.ontrack=e=>{(0,_.gg)("Received audio track from OpenAI"),r&&this.audioElement&&this.audioElement.srcObject?(0,_.gg)("Audio track already set up, ignoring duplicate track event"):(r=!0,this.audioElement&&this.audioElement.srcObject?((0,_.gg)("Updating existing audio element with new stream"),this.audioElement.srcObject=e.streams[0]):this.setupAudioStream(e.streams[0]))},this.peerConnection.onconnectionstatechange=()=>{(0,_.gg)("Connection state:",this.peerConnection.connectionState),"connected"===this.peerConnection.connectionState?(this.isConnected=!0,this.isConnecting=!1):"disconnected"!==this.peerConnection.connectionState&&"failed"!==this.peerConnection.connectionState||(this.isConnected=!1,this.isConnecting=!1,this.onError&&this.onError(new Error("WebRTC connection lost")))},this.setupDataChannel();const o=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(o),(0,_.gg)("Sending SDP offer directly to OpenAI...");const a=await fetch("https://api.openai.com/v1/realtime",{method:"POST",body:o.sdp,headers:{Authorization:"Bearer ".concat(i),"Content-Type":"application/sdp"}});if(!a.ok){const e=await a.text();throw new Error("OpenAI SDP error: ".concat(e))}const c=await a.text();(0,_.gg)("\u2705 Received SDP answer, length:",c.length),await this.peerConnection.setRemoteDescription({type:"answer",sdp:c}),(0,_.gg)("\u2705 WebRTC connection established"),this.isConnected=!0,this.isConnecting=!1}catch(t){throw console.error("Error establishing WebRTC connection:",t),this.isConnecting=!1,this.onError&&this.onError(t),t}}}
1setupDataChannel(){this.dataChannel=this.peerConnection.createDataChannel("oai-events",{ordered:!0}),this.dataChannel.onmessage=e=>{try{const t=JSON.parse(e.data);this.handleDataChannelMessage(t)}catch(t){console.error("Error parsing data channel message:",t)}},this.dataChannel.onopen=()=>{(0,_.gg)("\u2705 Data channel opened")},this.dataChannel.onerror=e=>{console.error("Data channel error:",e),this.onError&&this.onError(new Error("Data channel error"))},this.peerConnection.ondatachannel=e=>{const t=e.channel;"oai-events"===t.label&&((0,_.gg)("Received oai-events data channel from OpenAI"),t.onmessage=e=>{try{const t=JSON.parse(e.data);this.handleDataChannelMessage(t)}catch(t){console.error("Error parsing data channel message:",t)}})}}handleDataChannelMessage(e){var t,n,i,s,r,o,a,c,l,d,u,g,p,m;switch((0,_.gg)("Data channel message:",e.type),e.type){case"session.created":(0,_.gg)("\u2705 Session created:",null===(t=e.session)||void 0===t?void 0:t.id),this.sessionId=null===(n=e.session)||void 0===n?void 0:n.id,this.configureSessionForWorkspaceContext(),this.currentSystemPrompt&&this.dataChannel&&"open"===this.dataChannel.readyState&&((0,_.gg)("\ud83d\udd04 Session ready, applying stored system prompt..."),this.updateSessionInstructions(this.currentSystemPrompt));break;case"session.updated":if((0,_.gg)("\u2705 Session updated"),this.sessionUpdateConfirmed=!0,this.pendingResponseCreation)(0,_.gg)("\u2705 Session instructions updated, creating response..."),this.pendingResponseCreation=!1,setTimeout(()=>{this.createResponse()},100);else if(this.pendingUserMessage){(0,_.gg)("\u2705 Session instructions updated, sending pending user message");const e=this.pendingUserMessage;this.pendingUserMessage=null,setTimeout(()=>{this.sendUserMessage(e)},100)}else(0,_.gg)("\u2705 Session configuration updated (turn_detection, etc.)");break;case"conversation.item.created":if((0,_.gg)("\ud83d\udcdd Conversation item created:",null===(i=e.item)||void 0===i?void 0:i.type),"message"===(null===(s=e.item)||void 0===s?void 0:s.type)&&"user"===(null===(r=e.item)||void 0===r?void 0:r.role)){var h,y,f;(0,_.gg)("\u2705 User message item created, item ID:",null===(h=e.item)||void 0===h?void 0:h.id),this.lastUserMessageItemId=null===(y=e.item)||void 0===y?void 0:y.id;const t=null===(f=e.item)||void 0===f?void 0:f.content;if(t&&Array.isArray(t)){const e=t.find(e=>"input_audio"===e.type);if(e&&e.transcript){if((0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 Found transcription in item:",e.transcript),this.onTranscription&&e.transcript.trim()){(0,_.gg)("\ud83d\udcde Calling onTranscription with transcript from item");try{this.onTranscription(e.transcript)}catch(w){console.error("\u274c Error in onTranscription callback:",w)}}}else{(0,_.gg)("\u23f3 Transcription not yet available, waiting for transcription events...");let e=0;const t=10,n=setInterval(()=>{if(e++,this.currentTranscription&&this.currentTranscription.trim()){if((0,_.gg)("\u23f0 Fallback: Using accumulated transcription:",this.currentTranscription),this.onTranscription)try{this.onTranscription(this.currentTranscription),this.currentTranscription="",clearInterval(n)}catch(w){console.error("\u274c Error in onTranscription callback:",w)}}else e>=t&&(console.warn("\u23f0 Timeout: No transcription received after 5 seconds"),clearInterval(n))},500)}}}break;case"conversation.item.updated":if((0,_.gg)("\ud83d\udcdd\ud83d\udcdd\ud83d\udcdd Conversation item updated - FULL MESSAGE:",JSON.stringify(e,null,2)),(0,_.gg)("\ud83d\udcdd Conversation item updated:",null===(o=e.item)||void 0===o?void 0:o.id),"message"===(null===(a=e.item)||void 0===a?void 0:a.type)&&"user"===(null===(c=e.item)||void 0===c?void 0:c.role)){var x;const t=null===(x=e.item)||void 0===x?void 0:x.content;if(t&&Array.isArray(t)){const e=t.find(e=>"input_audio"===e.type);if(e&&e.transcript&&((0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 Found transcription in updated item:",e.transcript),this.onTranscription&&e.transcript.trim())){(0,_.gg)("\ud83d\udcde Calling onTranscription with transcript from updated item");try{this.onTranscription(e.transcript)}catch(w){console.error("\u274c Error in onTranscription callback:",w)}}}}break;case"conversation.item.input_audio_transcription.delta":(0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 Transcription delta received:",e.delta),(0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 Full delta message:",JSON.stringify(e,null,2)),e.delta&&this.isListening&&(this.currentTranscription||(this.currentTranscription=""),this.currentTranscription+=e.delta,(0,_.gg)("Transcription delta:",e.delta,"Total:",this.currentTranscription),(0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 Accumulated transcription so far:",this.currentTranscription));break;case"conversation.item.input_audio_transcription.completed":(0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 Transcription completed event received!"),(0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 Full message:",JSON.stringify(e,null,2)),(0,_.gg)("\u2705 Transcription completed event received");let v=e.transcript||(null===(l=e.item)||void 0===l?void 0:l.transcript)||(null!==(d=e.item)&&void 0!==d&&d.content&&Array.isArray(e.item.content)?null===(u=e.item.content.find(e=>e.transcript))||void 0===u?void 0:u.transcript:null);if(v){if((0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 Transcript text:",v),(0,_.gg)("\u2705 Transcription completed:",v),(0,_.gg)("\u2705 Transcription callback available:",!!this.onTranscription),this.onTranscription){(0,_.gg)("\ud83d\udcde Calling onTranscription callback with:",v),(0,_.gg)("\ud83d\udcde Calling onTranscription callback with:",v);try{this.onTranscription(v)}catch(w){console.error("\u274c Error in onTranscription callback:",w)}}else console.error("\u274c onTranscription callback is not set!");this.currentTranscription=""}else console.warn("\u26a0\ufe0f Transcription completed but no transcript found in message"),console.warn("\u26a0\ufe0f Full message:",JSON.stringify(e,null,2)),(0,_.gg)("\u26a0\ufe0f Transcription completed but no transcript in message"),(0,_.gg)("\u26a0\ufe0f Full message:",JSON.stringify(e,null,2));break;case"response.created":(0,_.gg)("\u2705 Response created:",null===(g=e.response)||void 0===g?void 0:g.id),this.hasActiveResponse=!0,this.isInterrupted=!1;break;case"response.audio_transcript.delta":e.delta&&(this.receivedFinalTranscript=!1,this.accumulatedResponse||(this.accumulatedResponse=""),this.accumulatedResponse+=e.delta,this.onResponseDelta&&this.onResponseDelta(this.accumulatedResponse)),this.isSpeaking||this.isInterrupted||((0,_.gg)("\ud83c\udfb5 Audio response started"),this.isSpeaking=!0);break;case"response.audio_transcript.done":this.receivedFinalTranscript=!0,this.accumulatedResponse="",e.transcript&&this.onResponse&&this.onResponse(e.transcript);break;case"response.audio.done":(0,_.gg)("\u2705 Audio response completed"),this.waitForAudioToFinish();break;case"response.done":if(this.hasActiveResponse=!1,null!==(p=e.response)&&void 0!==p&&p.output&&!this.receivedFinalTranscript){var A;
1const t=null===(A=e.response.output.find(e=>"text"===e.type))||void 0===A?void 0:A.text;t&&this.onResponse&&this.onResponse(t)}this.receivedFinalTranscript=!1,this.waitForAudioToFinish();break;case"rate_limits.updated":(0,_.gg)("Rate limits updated:",e.rate_limit);break;case"error":const E=(null===(m=e.error)||void 0===m?void 0:m.message)||"";E.includes("no active response")||E.includes("Cancellation failed")||E.includes("active response")?(0,_.gg)("\u2139\ufe0f Non-critical API error (race condition or cancellation):",E):(console.error("Realtime API error:",e),this.onError&&this.onError(new Error(E||"Unknown error")));break;case"input_audio_buffer.speech_started":(0,_.gg)("\ud83c\udfa4 Speech started");break;case"input_audio_buffer.speech_stopped":(0,_.gg)("\ud83c\udfa4 Speech stopped");break;case"input_audio_buffer.committed":(0,_.gg)("\ud83c\udfa4 Audio buffer committed");break;default:(0,_.gg)("Unhandled message type:",e.type),e.type&&!e.type.includes("rate_limits")&&(0,_.gg)("Unhandled message:",JSON.stringify(e,null,2))}}setupAudioStream(e){try{this.audioElement||(this.audioElement=new Audio,this.audioElement.autoplay=!0,this.audioElement.onerror=e=>{console.error("Audio playback error:",e),this.isSpeaking=!1},this.audioMonitorInterval=null),this.audioElement.srcObject=e;try{this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioStreamSource||(this.audioStreamSource=this.audioContext.createMediaStreamSource(e),this.audioAnalyser=this.audioContext.createAnalyser(),this.audioAnalyser.fftSize=256,this.audioAnalyser.smoothingTimeConstant=.8,this.audioStreamSource.connect(this.audioAnalyser),this.audioDataArray=new Uint8Array(this.audioAnalyser.frequencyBinCount),(0,_.gg)("\u2705 Audio analyser node setup complete"))}catch(t){console.error("Error setting up audio analyser:",t)}this.startAIAudioMonitoring();const n=this.audioElement.play();void 0!==n&&n.then(()=>{(0,_.gg)("\u2705 Audio stream connected and playing")}).catch(e=>{console.error("Error playing audio:",e),"NotAllowedError"===e.name&&(0,_.gg)("\u26a0\ufe0f Autoplay blocked, user interaction required")})}catch(t){console.error("Error setting up audio playback:",t)}}playAudioStream(e){this.setupAudioStream(e)}startListening(){if(!this.isConnected)throw new Error("Not connected. Call connect() first.");this.isListening=!0}stopListening(){this.isListening=!1,this.audioStream&&this.audioStream.getAudioTracks().forEach(e=>{e.enabled=!1}),this.stopAudioLevelMonitoring(),this.currentTranscription="",(0,_.gg)("\u23f8\ufe0f Listening stopped - audio tracks disabled")}resumeListening(){this.audioStream&&this.audioStream.getAudioTracks().forEach(e=>{e.enabled=!0}),this.isListening=!0,this.startAudioLevelMonitoring()}setupAudioLevelMonitoring(){if(this.audioStream)try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.analyser.smoothingTimeConstant=.8,this.microphone=this.audioContext.createMediaStreamSource(this.audioStream),this.microphone.connect(this.analyser),(0,_.gg)("\u2705 Audio level monitoring setup complete")}catch(e){console.error("Error setting up audio level monitoring:",e)}}startAudioLevelMonitoring(){if(!this.analyser||this.audioLevelInterval)return;const e=new Uint8Array(this.analyser.frequencyBinCount);this.audioLevelInterval=setInterval(()=>{if(!this.analyser||!this.isListening)return void(this.isUserSpeaking&&(this.isUserSpeaking=!1,this.onUserSpeaking&&this.onUserSpeaking(!1)));this.analyser.getByteTimeDomainData(e);let t=0;for(let s=0;s<e.length;s++){const n=(e[s]-128)/128;t+=n*n}const n=Math.sqrt(t/e.length),i=this.isUserSpeaking;this.isUserSpeaking=n>this.speakingThreshold,this.isUserSpeaking!==i&&this.onUserSpeaking&&this.onUserSpeaking(this.isUserSpeaking)},100)}stopAudioLevelMonitoring(){this.audioLevelInterval&&(clearInterval(this.audioLevelInterval),this.audioLevelInterval=null),this.isUserSpeaking=!1,this.onUserSpeaking&&this.onUserSpeaking(!1)}startAIAudioMonitoring(){this.aiAudioMonitorInterval||(this.aiAudioMonitorInterval=setInterval(()=>{if(!this.audioElement)return void(this.isAIActuallySpeaking&&(this.isAIActuallySpeaking=!1,this.onAISpeaking&&this.onAISpeaking(!1)));const e=this.isAudioActuallyPlaying();let t=!1;if(void 0!==this.audioElement.currentTime){const n=this.audioElement.currentTime;n>this.lastAIAudioTime+.01?(t=!0,this.lastAIAudioTime=n):n===this.lastAIAudioTime&&n>0&&e&&(t=!0)}const n=this.isAIActuallySpeaking,i=this.audioElement.readyState>=2;this.isAIActuallySpeaking=this.isSpeaking&&(e&&i||t&&i||this.audioElement.currentTime>0&&e),this.isAIActuallySpeaking!==n&&this.onAISpeaking&&this.onAISpeaking(this.isAIActuallySpeaking)},100))}stopAIAudioMonitoring(){this.aiAudioMonitorInterval&&(clearInterval(this.aiAudioMonitorInterval),this.aiAudioMonitorInterval=null),this.isAIActuallySpeaking=!1,this.lastAIAudioTime=0,this.onAISpeaking&&this.onAISpeaking(!1)}interruptSpeaking(){if((0,_.gg)("\ud83d\uded1 Interrupting AI speech"),this.isInterrupted=!0,this.clearWaitForAudioTimers(),this.audioElement&&(this.audioElement.pause(),this.audioElement.currentTime=0),this.isSpeaking=!1,this.isAIActuallySpeaking=!1,this.hasActiveResponse=!1,this.onAISpeaking&&this.onAISpeaking(!1),this.accumulatedResponse="",this.dataChannel&&"open"===this.dataChannel.readyState)try{const e={type:"response.cancel"};this.dataChannel.send(JSON.stringify(e)),(0,_.gg)("\u2705 Sent response.cancel to API (may fail if response already completed)")}catch(e){(0,_.gg)("\u26a0\ufe0f Could not cancel server response
1(already completed):",e.message)}this.isConnected&&!this.isListening&&this.resumeListening()}configureSessionForWorkspaceContext(){if(!this.dataChannel||"open"!==this.dataChannel.readyState)return void(0,_.gg)("\u26a0\ufe0f Data channel not open, cannot configure session");this.dataChannel.send(JSON.stringify({type:"session.update",session:{turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:500,create_response:!1},input_audio_transcription:{model:"whisper-1",language:"en"}}})),(0,_.gg)("\u2705 Configured session to disable auto-responses - transcriptions will be intercepted")}updateSessionInstructions(e){if(!e||0===e.trim().length)return void console.warn("Empty instructions provided, skipping session update");if(this.currentSystemPrompt=e,!this.dataChannel||"open"!==this.dataChannel.readyState)return void(0,_.gg)("\u26a0\ufe0f Data channel not open yet, storing instructions for later");if(!this.sessionId)return void(0,_.gg)("\u26a0\ufe0f Session not created yet, storing instructions for when session is ready");const t={type:"session.update",session:{instructions:e}};this.dataChannel.send(JSON.stringify(t)),(0,_.gg)("\u2705 Sent session.update with workspace context instructions"),(0,_.gg)("\ud83d\udcdd Instructions length:",e.length),(0,_.gg)("\ud83d\udcdd Instructions preview:",e.substring(0,300)+"...")}createResponseWithContext(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if(this.dataChannel&&"open"===this.dataChannel.readyState){if(this.receivedFinalTranscript=!1,this.accumulatedResponse="",e)return(0,_.gg)("\ud83d\udd04 Updating session instructions with workspace context before creating response..."),this.sessionUpdateConfirmed=!1,this.pendingResponseCreation=!0,this.updateSessionInstructions(e),this.systemPromptSent=!0,void setTimeout(()=>{this.pendingResponseCreation&&!this.sessionUpdateConfirmed&&((0,_.gg)("\u26a0\ufe0f Session update confirmation timeout, creating response anyway"),this.pendingResponseCreation=!1,this.createResponse())},1e3);this.createResponse()}else console.warn("Data channel not open, cannot create response")}cancelActiveResponseThen(e){if(this.hasActiveResponse){(0,_.gg)("\u26a0\ufe0f Active response detected, cancelling before creating new one");try{this.dataChannel.send(JSON.stringify({type:"response.cancel"}))}catch(t){(0,_.gg)("\u26a0\ufe0f Could not send response.cancel:",t.message)}this.hasActiveResponse=!1,setTimeout(e,200)}else e()}createResponse(){if(!this.dataChannel||"open"!==this.dataChannel.readyState)return void console.warn("Data channel not open, cannot create response");this.cancelActiveResponseThen(()=>{(0,_.gg)("\ud83d\udce4 Creating response from Realtime API");this.dataChannel.send(JSON.stringify({type:"response.create",response:{modalities:["text","audio"]}})),(0,_.gg)("\u2705 Response creation requested")})}sendTextMessage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(this.dataChannel&&"open"===this.dataChannel.readyState){if(this.receivedFinalTranscript=!1,this.accumulatedResponse="",t)return(0,_.gg)("\ud83d\udd04 Updating session instructions with workspace context..."),this.sessionUpdateConfirmed=!1,this.pendingUserMessage=e,this.updateSessionInstructions(t),this.systemPromptSent=!0,void setTimeout(()=>{if(this.pendingUserMessage&&!this.sessionUpdateConfirmed){(0,_.gg)("\u26a0\ufe0f Session update confirmation timeout, sending message anyway");const e=this.pendingUserMessage;this.pendingUserMessage=null,this.sendUserMessage(e)}},1e3);this.sendUserMessage(e)}else console.warn("Data channel not open, cannot send text message")}sendUserMessage(e){if(!this.dataChannel||"open"!==this.dataChannel.readyState)return void console.warn("Data channel not open, cannot send user message");this.cancelActiveResponseThen(()=>{(0,_.gg)("\ud83d\udce4 Sending user message to Realtime API:",e);const t={type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:e}]}};this.dataChannel.send(JSON.stringify(t));this.dataChannel.send(JSON.stringify({type:"response.create",response:{modalities:["text","audio"]}})),(0,_.gg)("\u2705 Requested response from Realtime API")})}getCurrentTranscription(){return this.currentTranscription||""}handleTranscription(e){this.onTranscription&&this.onTranscription(e)}handleResponse(e){this.onResponse&&this.onResponse(e)}clearWaitForAudioTimers(){this.waitForAudioTimeout&&(clearTimeout(this.waitForAudioTimeout),this.waitForAudioTimeout=null),this.waitForAudioInterval&&(clearInterval(this.waitForAudioInterval),this.waitForAudioInterval=null),this.waitForAudioSafetyTimeout&&(clearTimeout(this.waitForAudioSafetyTimeout),this.waitForAudioSafetyTimeout=null)}
1waitForAudioToFinish(){if(!this.isSpeaking)return;this.clearWaitForAudioTimers(),(0,_.gg)("\ud83c\udfb5 Waiting for audio to finish playing...");let e=Date.now(),t=0,n=0;this.waitForAudioTimeout=setTimeout(()=>{this.isSpeaking&&(this.audioElement&&(t=this.audioElement.currentTime||0),this.waitForAudioInterval=setInterval(()=>{if(!this.isSpeaking)return void this.clearWaitForAudioTimers();const i=this.isAudioActuallyPlaying();if(this.audioElement&&void 0!==this.audioElement.currentTime){const e=this.audioElement.currentTime;e>t&&(t=e)}if(i)e=Date.now(),n=0;else{n++;const t=Date.now()-e;(0,_.gg)("\ud83c\udfb5 Audio check ".concat(n,"/").concat(10,": not playing (").concat(t,"ms since last active)")),n>=10&&t>2e3&&((0,_.gg)("\ud83c\udfb5 Audio finished, resetting speaking state"),this.isSpeaking=!1,this.clearWaitForAudioTimers(),this.isConnected&&!this.isListening&&((0,_.gg)("\ud83c\udfa4 Automatically resuming listening after AI response"),this.resumeListening()))}},300))},500),this.waitForAudioSafetyTimeout=setTimeout(()=>{this.isSpeaking&&((0,_.gg)("\u26a0\ufe0f Audio check timeout (30s), resetting speaking state"),this.isSpeaking=!1,this.isConnected&&!this.isListening&&((0,_.gg)("\ud83c\udfa4 Automatically resuming listening after timeout"),this.resumeListening())),this.clearWaitForAudioTimers()},3e4)}isAudioActuallyPlaying(){if(!this.audioElement)return!1;const e=!this.audioElement.paused&&!this.audioElement.ended&&this.audioElement.currentTime>0&&this.audioElement.readyState>=2;if(this.audioAnalyser&&this.audioDataArray)try{this.audioAnalyser.getByteFrequencyData(this.audioDataArray);const t=this.audioDataArray.reduce((e,t)=>e+t,0)/this.audioDataArray.length;return e&&t>10}catch(t){console.error("Error reading audio data:",t)}if(this.audioElement.srcObject){const t=this.audioElement.srcObject.getAudioTracks().some(e=>"live"===e.readyState);return e&&t}return e}disconnect(){if(this.stopAudioLevelMonitoring(),this.stopAIAudioMonitoring(),this.audioStreamSource){try{this.audioStreamSource.disconnect()}catch(e){console.error("Error disconnecting audio stream source:",e)}this.audioStreamSource=null}this.audioAnalyser=null,this.audioDataArray=null,this.audioContext&&"closed"!==this.audioContext.state&&this.audioContext.close().catch(e=>{console.error("Error closing audio context:",e)}),this.isListening=!1,this.isSpeaking=!1,this.isConnecting=!1,this.audioMonitorInterval&&(clearInterval(this.audioMonitorInterval),this.audioMonitorInterval=null),this.audioElement&&(this.audioElement.pause(),this.audioElement.srcObject=null,this.audioElement=null),this.dataChannel&&(this.dataChannel.close(),this.dataChannel=null),this.audioStream&&(this.audioStream.getTracks().forEach(e=>{e.stop()}),this.audioStream=null),this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null),this.clearWaitForAudioTimers(),this.isConnected=!1,this.sessionId=null,this.currentTranscription="",this.systemPromptSent=!1,this.pendingUserMessage=null,this.pendingResponseCreation=!1,this.sessionUpdateConfirmed=!1,this.currentSystemPrompt=null,this.hasActiveResponse=!1,this.isInterrupted=!1}}var F=n(55472),V=n(70579);const B=e=>{let t=e.workspace,n=e.chatId,o=e.onMessage,a=e.workspaceDocuments,c=void 0===a?[]:a,l=e.onControlsReady,d=e.activeDocumentId,u=void 0===d?null:d;const g=(0,r.useState)(!1),m=(0,s.A)(g,2),h=m[0],y=m[1],f=(0,r.useState)(!1),x=(0,s.A)(f,2),A=x[0],w=x[1],v=(0,r.useState)(!1),b=(0,s.A)(v,2),S=b[0],I=b[1],R=(0,r.useState)(!1),T=(0,s.A)(R,2),L=T[0],G=T[1],B=(0,r.useState)(!1),W=(0,s.A)(B,2),H=W[0],q=W[1],z=(0,r.useState)(!1),J=(0,s.A)(z,2),K=J[0],Y=J[1],Q=(0,r.useState)(!1),$=(0,s.A)(Q,2),Z=$[0],X=$[1],ee=(0,r.useState)(null),te=(0,s.A)(ee,2),ne=te[0],ie=te[1],se=(0,r.useState)(""),re=(0,s.A)(se,2),oe=(re[0],re[1]),ae=(0,r.useState)(""),ce=(0,s.A)(ae,2),le=ce[0],de=ce[1],ue=(0,r.useState)(""),ge=(0,s.A)(ue,2),pe=ge[0],me=ge[1],he=(0,r.useState)(""),ye=(0,s.A)(he,2),fe=(ye[0],ye[1]),xe=(0,r.useState)("marin"),Ae=(0,s.A)(xe,2),we=Ae[0],ve=Ae[1],Ee=(0,r.useState)(!1),be=(0,s.A)(Ee,2),Ce=be[0],ke=be[1],Se=(0,r.useState)(""),Ie=(0,s.A)(Se,2),_e=Ie[0],Re=Ie[1],Te=(0,r.useState)(!1),Ne=(0,s.A)(Te,2),De=Ne[0],Pe=Ne[1],je=[{value:"alloy",label:"Alloy"},{value:"ash",label:"Ash"},{value:"ballad",label:"Ballad"},{value:"coral",label:"Coral"},{value:"echo",label:"Echo"},{value:"sage",label:"Sage"},{value:"shimmer",label:"Shimmer"},{value:"verse",label:"Verse"},{value:"marin",label:"Marin (Recommended)"},{value:"cedar",label:"Cedar (Recommended)"}],Ue=(0,r.useRef)(null),Oe=(0,r.useRef)(o),Le=(0,r.useRef)([]),Ge=(0,r.useRef)([]),Me=(0,r.useRef)(""),Fe=(0,r.useRef)(null),Ve=(0,r.useRef)(null),Be=(0,r.useRef)(!1),We=(0,r.useRef)(!1),He=(0,r.useRef)(null),qe=(0,C.httpsCallable)(k.Cn,"sendAgentMessageWithRAG"),ze=(0,C.httpsCallable)(k.Cn,"indexWorkspaceForChat",{timeout:3e5}),Je=(0,C.httpsCallable)(k.Cn,"getWorkspaceContext");(0,r.useEffect)(()=>{Oe.current=o},[o]),(0,r.useEffect)(()=>{(async()=>
1{if(null!==t&&void 0!==t&&t.id)try{const e=(0,F.doc)(k.db,"workspaces",t.id),n=await(0,F.getDoc)(e);if(n.exists()){const e=n.data();Re(e.voicePersonality||e.voiceTone||""),e.selectedVoice&&ve(e.selectedVoice)}}catch(ne){console.error("Error loading voice personality:",ne)}})()},[null===t||void 0===t?void 0:t.id]);const Ke=(0,r.useCallback)(async e=>{(0,_.gg)("\ud83d\udd04 Voice Mode: Starting indexing...");try{const n=(e||c).filter(e=>!e.decryptionFailed&&!e.processingError),i=[],s=new Map;n.forEach(e=>{const t=e.content||e.extractedContent||e.text||e.textContent||"",n=t.length,r=e.title||"Untitled",o=t.substring(0,200).trim(),a="".concat(r,"|").concat(n,"|").concat(o);s.has(a)||(s.set(a,e),i.push(e))});const r={workspaceId:t.id,forceReindex:!0,documents:i.map(e=>{let t="";return t=e.textContent&&e.textContent.trim()?e.textContent:e.content&&e.content.trim()?e.content:e.extractedContent&&e.extractedContent.trim()?e.extractedContent:e.text&&e.text.trim()?e.text:e.editorHtml&&e.editorHtml.trim()?e.editorHtml:"Document: ".concat(e.title," (no content available)"),{id:e.id,title:e.title,content:t,type:e.type||"document",isEncrypted:e.isEncrypted||!1,wasDecrypted:e.isEncrypted&&!e.decryptionFailed,fileType:e.fileType||"",fileName:e.fileName||"",viewerMode:e.viewerMode||""}})},o=(await ze(r)).data;return(0,_.gg)("\u2705 Voice Mode: Indexing complete:",o),o.documentsProcessed>0}catch(n){return console.error("\ud83d\udd25 Voice Mode: Indexing failed:",n),!1}},[t,c,ze]),Ye=(0,r.useCallback)(async e=>{if((0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 handleTranscription CALLED with text:",e),(0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 isProcessing:",L),(0,_.gg)("\ud83c\udfa4\ud83c\udfa4\ud83c\udfa4 text trimmed:",null===e||void 0===e?void 0:e.trim()),(0,_.gg)("\ud83c\udfa4 handleTranscription called with text:",e),(0,_.gg)("\ud83c\udfa4 isProcessing:",L),(0,_.gg)("\ud83c\udfa4 text trimmed:",null===e||void 0===e?void 0:e.trim()),!e||!e.trim())return(0,_.gg)("\u26a0\ufe0f handleTranscription: Empty text, returning"),void(0,_.gg)("\u26a0\ufe0f handleTranscription: Empty text, returning");if(L)return(0,_.gg)("\u26a0\ufe0f handleTranscription: Already processing, returning"),void(0,_.gg)("\u26a0\ufe0f handleTranscription: Already processing, returning");(0,_.gg)("\u2705 handleTranscription: Starting processing..."),(0,_.gg)("\u2705 handleTranscription: Starting processing..."),Le.current=[],Ge.current=[],G(!0),I(!1),ie(null);try{(0,_.gg)("\ud83d\udd0d Voice Mode: Transcription received:",e),(0,_.gg)("\ud83d\udd0d Voice Mode: Starting workspace context retrieval..."),(0,_.gg)("\ud83d\udd0d Voice Mode: Transcription received:",e),(0,_.gg)("\ud83d\udd0d Voice Mode: Starting workspace context retrieval..."),o&&o({role:"user",content:e,timestamp:new Date});let g=null;try{(0,_.gg)("\ud83d\udd0d Voice Mode: Getting workspace context..."),(0,_.gg)("\ud83d\udd0d Voice Mode: Workspace ID:",t.id),(0,_.gg)("\ud83d\udd0d Voice Mode: Message:",e);const n=await Je({workspaceId:t.id,message:e,voicePersonality:_e||t.voicePersonality||t.voiceTone||null});if((0,_.gg)("\ud83d\udd0d Voice Mode: Context response received:",n),n&&n.data){(0,_.gg)("\ud83d\udd0d Voice Mode: Response data:",n.data);const e=n.data.pdfSources;Le.current=Array.isArray(e)?e:[];const t=n.data.viewerDocuments;Ge.current=Array.isArray(t)?t:[],n.data.systemPrompt?(g=n.data.systemPrompt,(0,_.gg)("\u2705 Voice Mode: Workspace context retrieved successfully!"),(0,_.gg)("\u2705 Voice Mode: Chunks found:",n.data.chunksFound),(0,_.gg)("\u2705 Voice Mode: Documents referenced:",n.data.documentsReferenced),(0,_.gg)("\u2705 Voice Mode: Context length:",g.length)):(0,_.gg)("\u26a0\ufe0f Voice Mode: No systemPrompt in response data")}else(0,_.gg)("\u26a0\ufe0f Voice Mode: No data in context response")}catch(l){var s,r,a;(0,_.gg)("\u274c Voice Mode: Error getting workspace context:",l),(0,_.gg)("\u274c Voice Mode: Error message:",l.message),(0,_.gg)("\u274c Voice Mode: Error code:",l.code),(0,_.gg)("\u274c Voice Mode: Full error:",JSON.stringify(l,null,2));if(((null===(s=l.message)||void 0===s?void 0:s.includes("not found"))||(null===(r=l.message)||void 0===r?void 0:r.includes("collection"))||(null===(a=l.message)||void 0===a?void 0:a.includes("Not Found"))||"functions/internal"===l.code||"not-found"===l.code)&&c.length>0){(0,_.gg)("\ud83d\udd04 Voice Mode: Collection not found, attempting automatic indexing..."),o&&o({role:"assistant",content:"Setting up your workspace knowledge base. This will just take a moment...",timestamp:new Date});if(await Ke()){(0,_.gg)("\u2705 Voice Mode: Indexing complete, retrying context request...");try{const n=await Je({workspaceId:t.id,message:e});if(n.data&&n.data.systemPrompt){g=n.data.systemPrompt;const e=n.data.pdfSources;Le.current=Array.isArray(e)?e:[];const t=n.data.viewerDocuments;Ge.current=Array.isArray(t)?t:[]}}catch(d){(0,_.gg)("\u26a0\ufe0f Voice Mode: Failed to get context after indexing:",d)}}else(0,_.gg)("\u26a0\ufe0f Voice Mode: Indexing failed, continuing without workspace context")}else(0,_.gg)("\u26a0\ufe0f Voice Mode: Failed to get workspace context:",l),(0,_.gg)("\u26a0\ufe0f Voice Mode: Error details:",{message:l.message,code:l.code,stack:l.stack}),o&&o({role:"assistant",content:"I encountered an issue accessing your workspace knowledge base. I'll try to answer using general knowledge, but for workspace-specific information, please use the text chat.",timestamp:new Date})}if(g||(Le.current=[],Ge.current=[]),g?(0,_.gg)("\u2705 Voice Mode: Workspace context is available and will be used"):((0,_.gg)("\u274c Voice Mode: NO workspace context available - responses will use general knowledge"),(0,_.gg)("\u274c Voice Mode: This is why you're getting general information instead of workspace-specific answers")),de(""),me(""),Me.current="",!Ue.current||!h)throw new Error("Realtime API not connected");g?((0,_.gg)("\u2705 Voice Mode: Creating response with workspace context"),(0,_.gg)("\u2705 Voice Mode: Creating response with workspace context"),(0,_.gg)("\ud83d\udcdd Workspace context length:",g.length),(0,_.gg)("\ud83d\udcdd Workspace context preview:",g.substring(0,200)+"..."),Ue.current.createResponseWithContext(g)):((0,_.gg)("\u26a0\ufe0f Voice Mode: No workspace context - creating response without context"),(0,_.gg)("\u26a0\ufe0f Voice Mode: No workspace context available - creating response without context"),(0,_.gg)("\u26a0\ufe0f This may result in general knowledge responses instead of workspace-specific answers"),Ue.current.createResponseWithContext());const p=(0,i.A)({workspaceId:t.id,chatId:n||"voice_chat_".concat(Date.now()),message:e,provider:"openai",ragAudience:"internal",isInternalSetup:!0},u?{documentId:u}:{});qe(p).catch(e=>{(0,_.gg)("\u26a0\ufe0f Voice Mode: RAG logging failed (non-critical):",e)})}catch(ne){console.error("Error processing transcription:",ne),ie("Error: ".concat(ne.message)),G(!1),o&&o({role:"assistant",content:"I encountered an error: ".concat(ne.message,". Please try again."),timestamp:new Date})}},[t,n,o,qe,Je,L,h,c,Ke,_e,u]);(0,r.useEffect)(()=>{Ve.current=Ye},[Ye]),(0,r.useEffect)(()=>{He.current&&(pe||le)&&(He.current.scrollTop=He.current.scrollHeight)},[pe,le]);const Qe=(0,r.useCallback)(async()=>
1{if(We.current)(0,_.gg)("Connection already in progress, skipping");else if(Ue.current)if(Ue.current.isConnected||Ue.current.isConnecting)(0,_.gg)("Already connected or connecting, skipping");else{We.current=!0,w(!0);try{ie(null),await Ue.current.connect(),y(!0),(0,_.gg)("Connected to Realtime API via WebRTC")}catch(ne){We.current=!1,w(!1),console.error("Failed to connect to Realtime API:",ne);let t="Failed to connect: ".concat(ne.message);ne.message.includes("permission")||"NotAllowedError"===ne.name||"PermissionDeniedError"===ne.name?t='Microphone permission denied. Please click "Allow" when prompted, or enable microphone access in your browser settings and refresh the page.':ne.message.includes("getUserMedia")||"NotFoundError"===ne.name?t="Could not access microphone. Please check your browser settings and ensure a microphone is connected.":ne.message.includes("timeout")?t="Connection timeout. Please check your network connection and try again.":(ne.message.includes("NotReadableError")||"NotReadableError"===ne.name)&&(t="Microphone is being used by another application. Please close other apps using the microphone and try again."),ie(t),y(!1)}finally{We.current=!1,w(!1)}}else(0,_.gg)("No service available for connection")},[]);(0,r.useEffect)(()=>{if(Ue.current){(0,_.gg)("Cleaning up existing service (voice may have changed)");const e=Ue.current;Ue.current=null;try{e.disconnect()}catch(ne){console.error("Error disconnecting old service:",ne)}Be.current=!1,We.current=!1,y(!1)}if(Be.current)return void(0,_.gg)("Service initialization already in progress, skipping");Be.current=!0,Me.current="",(0,_.gg)("Creating new RealtimeWebRTCService instance with voice:",we);const e=new M(e=>{if((0,_.gg)("\ud83c\udfa4 RealtimeWebRTCService: Final transcription received:",e),(0,_.gg)("\ud83c\udfa4 handleTranscriptionRef.current available:",!!Ve.current),oe(e),fe(""),e&&e.trim())if(Ve.current){(0,_.gg)("\ud83d\udcde Calling handleTranscriptionRef.current with:",e);try{Ve.current(e)}catch(ne){console.error("\u274c Error calling handleTranscription:",ne)}}else console.error("\u274c handleTranscriptionRef.current is not set!");else(0,_.gg)("\u26a0\ufe0f Transcription is empty, not calling handleTranscription")},e=>{(0,_.gg)("Final response text received:",e),Me.current=e,de(e),me(""),G(!1)},e=>{console.error("Realtime API error:",e),ie(e.message),I(!1),G(!1),q(!1)},we,e=>{me(e),G(!1)},e=>{Y(e)},e=>{X(e)});return Ue.current=e,Be.current=!1,()=>{(0,_.gg)("Cleaning up RealtimeWebRTCService"),Be.current=!1,We.current=!1,et()}},[Qe,we]);const $e=()=>{I(!1),Ue.current&&Ue.current.stopListening()},Ze=()=>{S?$e():(async()=>{try{if((0,_.gg)("\ud83c\udfa4 startListening called"),ie(null),oe(""),fe(""),Ue.current&&Ue.current.isConnected||((0,_.gg)("\u26a0\ufe0f Not connected, connecting..."),await Qe()),!Ue.current||!Ue.current.isConnected)throw(0,_.gg)("\u274c Not connected, cannot start listening"),new Error("Not connected. Please wait for connection to establish.");(0,_.gg)("\u2705 Starting to listen..."),Ue.current.resumeListening(),I(!0),(0,_.gg)("\u2705 Listening started, waiting for user input..."),Fe.current=setInterval(()=>{if(Ue.current&&Ue.current.isListening){const e=Ue.current.getCurrentTranscription();e&&fe(e)}},100),(0,_.gg)("\u2705 Started listening")}catch(ne){console.error("Error starting listening:",ne),ie(ne.message),I(!1),Fe.current&&(clearInterval(Fe.current),Fe.current=null)}})()},Xe=()=>{(0,_.gg)("\ud83d\uded1 User interrupted AI speech"),Ue.current&&(Ue.current.interruptSpeaking(),q(!1),X(!1),me(""),de(""))},et=()=>{if((0,_.gg)("Starting cleanup..."),$e(),Fe.current&&(clearInterval(Fe.current),Fe.current=null),Ue.current){try{Ue.current.disconnect()}catch(ne){console.error("Error during service disconnect:",ne)}Ue.current=null}Be.current=!1,We.current=!1,y(!1),w(!1),(0,_.gg)("Cleanup complete")};return(0,r.useEffect)(()=>{let e=H,t=!1,n=null;const s=setInterval(()=>{if(Ue.current){const s=Ue.current.isSpeaking;if(s&&Ue.current.audioElement){const e=Ue.current.audioElement;!e.paused&&!e.ended&&e.currentTime>
10?n&&(clearTimeout(n),n=null):n||(n=setTimeout(()=>{Ue.current&&Ue.current.isSpeaking&&((0,_.gg)("\u26a0\ufe0f Audio stuck in speaking state (10s timeout), resetting..."),Ue.current.isSpeaking=!1,q(!1)),n=null},1e4))}if(s!==e){if(e=s,q(s),!s&&!t&&Me.current&&Oe.current){const e=Me.current.trim();if(e){(0,_.gg)("Sending complete response to chat:",e);const n=Le.current,s=Ge.current,r={};Array.isArray(n)&&n.length>0&&(r.pdfSources=n),Array.isArray(s)&&s.length>0&&(r.viewerDocuments=s);const o=Object.keys(r).length>0?{ragInfo:r}:{};Oe.current((0,i.A)({role:"assistant",content:e,timestamp:new Date},o)),Me.current="",de(""),t=!0}}s&&(t=!1,G(!1))}const r=Ue.current.isListening;r!==S&&(I(r),(0,_.gg)("\ud83d\udd04 Synced listening state from service:",r))}},100);return()=>{clearInterval(s),n&&clearTimeout(n)}},[H,S]),(0,r.useEffect)(()=>{l&&l({selectedVoice:we,setSelectedVoice:ve,isListening:S,isSpeaking:H,isProcessing:L,error:ne,isConnected:h,showPersonalityModal:()=>ke(!0),availableVoices:je})},[we,S,H,L,ne,h,l]),(0,r.useEffect)(()=>{const e=e=>{"Escape"===e.key&&H&&Xe()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[H,Xe]),(0,r.useEffect)(()=>{if(!ne)return;const e=setTimeout(()=>ie(null),5e3);return()=>clearTimeout(e)},[ne]),(0,r.useEffect)(()=>{if(!L)return;const e=setTimeout(()=>G(!1),15e3);return()=>clearTimeout(e)},[L]),!A||h||ne?(0,V.jsxs)("div",{className:"h-full flex flex-col bg-white",children:[(0,V.jsxs)("div",{className:"flex-1 flex flex-col items-center justify-center p-8",children:[(0,V.jsxs)("div",{className:"mb-8 relative w-32 h-32 mx-auto",children:[(S||H)&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)("div",{className:"absolute inset-0 rounded-full animate-ping opacity-75 transition-colors duration-200 ".concat(H?"bg-green-100":"bg-blue-100")}),(0,V.jsx)("div",{className:"absolute inset-0 rounded-full animate-pulse transition-colors duration-200 ".concat(H?"bg-green-200":"bg-blue-200")})]}),(0,V.jsx)("div",{className:"relative flex items-center justify-center w-32 h-32 rounded-full transition-all duration-200 ".concat(H?"bg-green-500 scale-105":S?"bg-blue-500 scale-105":L?"bg-blue-400 scale-100":"bg-gray-100 scale-100"),children:L?(0,V.jsx)(E.y$,{size:"lg",className:"!w-16 !h-16 text-white transition-opacity duration-200"}):null!==t&&void 0!==t&&t.emoji?(0,V.jsx)("span",{className:"text-6xl",children:t.emoji}):H?(0,V.jsx)(N.A,{className:"w-16 h-16 text-white transition-opacity duration-200 ".concat(Z?"animate-pulsate":"")}):(0,V.jsx)(p.A,{className:"w-16 h-16 transition-all duration-200 ".concat(S?"text-white":"text-gray-400"," ").concat(K?"animate-pulsate":"")})})]}),(0,V.jsx)("div",{className:"text-center mb-8",children:H?(0,V.jsxs)("div",{className:"space-y-1",children:[(0,V.jsx)("p",{className:"text-lg font-medium text-green-600 transition-opacity duration-200",children:"Speaking..."}),(0,V.jsx)("p",{className:"text-xs text-gray-400",children:"Press Esc or click button to interrupt"})]}):L?null:S?(0,V.jsx)("p",{className:"text-lg font-medium text-blue-600 transition-opacity duration-200",children:"Listening..."}):null}),(0,V.jsx)("div",{className:"flex gap-4",children:H?(0,V.jsx)("button",{onClick:Xe,className:"px-8 py-4 rounded-full font-medium text-white bg-red-500 hover:bg-red-600 transition-all shadow-lg",children:(0,V.jsxs)("div",{className:"flex items-center",children:[(0,V.jsx)(D.A,{className:"w-5 h-5 mr-2"}),"Stop"]})}):S?(0,V.jsx)("button",{type:"button",onClick:Ze,disabled:A||L,className:"px-8 py-4 rounded-full font-medium text-white bg-red-500 hover:bg-red-600 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:(0,V.jsxs)("div",{className:"flex items-center",children:[(0,V.jsx)(P.A,{className:"w-5 h-5 mr-2"}),"End Chat"]})}):(0,V.jsx)(O.A,{type:"button",onClick:Ze,disabled:A||L,loading:A,leadingIcon:(0,V.jsx)(p.A,{className:"w-5 h-5"}),size:"lg",className:"rounded-full px-8 py-4 font-medium transition-all shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",children:A?"Connecting...":"Begin voice mode"})}),ne&&(0,V.jsx)("div",{className:"mt-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-800",children:ne})]}),Ce&&(0,V.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50",children:(0,V.jsxs)("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col",children:[(0,V.jsxs)("div",{className:"flex items-center justify-between p-6 border-b border-gray-200",children:[(0,V.jsxs)("div",{children:[(0,V.jsx)("h3",{className:"text-lg font-semibold text-gray-900",children:"Voice Personality Settings"}),(0,V.jsx)("p",{className:"text-sm text-gray-500 mt-1",children:"Customize how your voice assistant speaks and behaves"})]}),(0,V.jsx)("button",{onClick:()=>ke(!1),className:"text-gray-400 hover:text-gray-600 transition-colors",children:(0,V.jsx)(j.A,{className:"w-5 h-5"})})]}),(0,V.jsx)("div",{className:"flex-1 overflow-y-auto p-6",children:(0,V.jsxs)("div",{className:"space-y-4",children:[(0,V.jsxs)("div",{children:[(0,V.jsx)("label",{htmlFor:"voice-select-modal",className:"block text-sm font-medium text-gray-700 mb-2",children:"Voice"}),(0,V.jsx)("select",{id:"voice-select-modal",value:we,onChange:e=>{const t=e.target.value;ve(t)},disabled:S||H||L,className:"w-full px-3 py-2 text-sm border border-gray-300 rounded-md bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50 disabled:cursor-not-allowed",children:je.map(e=>(0,V.jsx)("option",{value:e.value,children:e.label},e.value))}),(0,V.jsx)("p",{className:"mt-1 text-xs text-gray-500",children:"Choose the voice for your AI assistant"})]}),(0,V.jsxs)("div",{children:[(0,V.jsx)("label",{htmlFor:"personality-input",className:"block text-sm font-medium text-gray-700 mb-2",children:"Personality Instructions"}),(0,V.jsx)("textarea",{id:"personality-input",value:_e,onChange:e=>Re(e.target.value),placeholder:"Example: You are a friendly and enthusiastic McDonald's employee. Speak with energy and positivity. Use phrases like 'I'm lov
1in' it!' and 'Can I help you with that?' Be warm, helpful, and maintain the upbeat energy of a fast-food restaurant worker.",className:"w-full h-64 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm"}),(0,V.jsx)("p",{className:"mt-2 text-xs text-gray-500",children:"Describe the personality, tone, and speaking style you want. The AI will maintain this character while still using your workspace documents for accurate answers."})]}),(0,V.jsxs)("div",{className:"bg-gray-50 rounded-lg p-4",children:[(0,V.jsx)("h4",{className:"text-sm font-medium text-gray-900 mb-3",children:"Quick Examples:"}),(0,V.jsxs)("div",{className:"space-y-2",children:[(0,V.jsxs)("button",{onClick:()=>Re('You are a friendly and enthusiastic McDonald\'s employee. \n- Speak with energy and positivity\n- Use phrases like "I\'m lovin\' it!", "Can I help you with that?", "Absolutely!"\n- Be warm, helpful, and maintain the upbeat energy of a fast-food restaurant worker\n- Keep responses concise and friendly\n- Show excitement about helping customers\n- Use casual, approachable language'),className:"text-left w-full px-3 py-2 text-xs bg-white border border-gray-200 rounded hover:bg-blue-50 hover:border-blue-300 transition-colors",children:[(0,V.jsx)("span",{className:"font-medium",children:"McDonald's Employee"})," - Friendly and enthusiastic"]}),(0,V.jsxs)("button",{onClick:()=>Re('You are Ronald McDonald, the iconic McDonald\'s mascot. \n- Speak with playful enthusiasm and childlike wonder\n- Use phrases like "That\'s fantastic!", "Wow!", "You\'re awesome!"\n- Be cheerful, optimistic, and fun-loving\n- Use simple, clear language that\'s friendly to all ages\n- Show genuine excitement about helping\n- Occasionally use light humor and positive exclamations\n- Maintain the character\'s signature upbeat personality'),className:"text-left w-full px-3 py-2 text-xs bg-white border border-gray-200 rounded hover:bg-blue-50 hover:border-blue-300 transition-colors",children:[(0,V.jsx)("span",{className:"font-medium",children:"Mascot Character"})," - Playful and fun-loving"]}),(0,V.jsxs)("button",{onClick:()=>Re("You are a professional business assistant.\n- Speak in a clear, confident, and professional tone\n- Use proper business language and terminology\n- Be concise and direct while remaining courteous\n- Maintain a helpful and knowledgeable demeanor\n- Structure responses clearly with key points\n- Use formal but approachable language"),className:"text-left w-full px-3 py-2 text-xs bg-white border border-gray-200 rounded hover:bg-blue-50 hover:border-blue-300 transition-colors",children:[(0,V.jsx)("span",{className:"font-medium",children:"Professional Assistant"})," - Clear and confident"]}),(0,V.jsxs)("button",{onClick:()=>Re(""),className:"text-left w-full px-3 py-2 text-xs bg-white border border-gray-200 rounded hover:bg-gray-50 transition-colors text-gray-500",children:[(0,V.jsx)("span",{className:"font-medium",children:"Clear"})," - Remove personality (default behavior)"]})]})]})]})}),(0,V.jsxs)("div",{className:"flex items-center justify-end gap-3 p-6 border-t border-gray-200",children:[(0,V.jsx)("button",{onClick:()=>ke(!1),className:"px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-md transition-colors",children:"Cancel"}),(0,V.jsx)(O.A,{type:"button",onClick:async()=>{if(null!==t&&void 0!==t&&t.id){Pe(!0);try{const e=(0,F.doc)(k.db,"workspaces",t.id);await(0,F.mZ)(e,{voicePersonality:_e.trim()||null,selectedVoice:we}),(0,_.gg)("\u2705 Voice personality saved successfully"),ke(!1),o&&o({role:"assistant",content:_e.trim()?"Voice personality updated! It will be applied to your next conversation.":"Voice personality removed. Default behavior restored.",timestamp:new Date})}catch(ne){console.error("Error saving voice personality:",ne),ie("Failed to save personality: ".concat(ne.message))}finally{Pe(!1)}}},loading:De,disabled:De,leadingIcon:(0,V.jsx)(U.A,{className:"w-4 h-4"}),size:"md",className:"px-4 py-2 text-sm rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:De?"Saving...":"Save Personality"})]})]})})]}):(0,V.jsx)("div",{className:"flex items-center justify-center h-full",children:(0,V.jsxs)("div",{className:"text-center",children:[(0,V.jsx)(E.y$,{size:"md",className:"mx-auto mb-4 text-blue-600"}),(0,V.jsx)("p",{className:"text-gray-600",children:"Connecting to voice mode..."})]})})};var W=n(86353),H=n(36401),q=n(38288),z=n(56790),J=n(67126),K=n(45580),Y=n(80813);const Q="us-central1",$="aiknowledgebase-7427e";const Z=new Set(["chat","create_document","open_blank","open_document","update_current_document","update_workspace_document","start_timer","cancel"]),X={prompt:"",documentTitle:"",documentIdGuess:"",updateInstruction:"",taskName:"",workspaceName:""};async function ee(e){const t="string"===typeof e.userText?e.userText.trim():"",n={intent:"chat",confidence:0,params:(0,i.A)((0,i.A)({},X),{},{prompt:t})};if(!t)return n;const s=k.j2.currentUser;if(!s)return n;const r=Array.isArray(e.workspaceDocIndex)?e.workspaceDocIndex.filter(e=>e&&e.id&&e.title).slice(0,50).map(e=>({id:String(e.id).slice(0,128),title:String(e.title).trim().slice(0,300)})):[],o=Array.isArray(e.orgWorkspaceIndex)?e.orgWorkspaceIndex.filter(e=>e&&e.id&&e.name).slice(0,50).map(e=>({id:String(e.id).slice(0,128),name:String(e.name).trim().slice(0,300)})):[];let a;try{a=await s.getIdToken()}catch(l){return n}const c=function(){const e={NODE_ENV:"production",PUBLIC_URL:".",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0,REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_NAME:"Gary Riger",REACT_APP_VERCEL_GIT_PROVIDER:"github",REACT_APP_VERCEL_PROJECT_ID:"prj_A5c8ZMv75ibxQVceA3I7GjPny9oD",REACT_APP_VERCEL_GIT_PULL_REQUEST_ID:"",REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG:'{"analytics":{"scriptSrc":"8f81e36d25c71756/script.
1js","viewEndpoint":"8f81e36d25c71756/view","eventEndpoint":"8f81e36d25c71756/event","sessionEndpoint":"8f81e36d25c71756/session"},"speedInsights":{"scriptSrc":"1e9f61cb490e195d/script.js","endpoint":"1e9f61cb490e195d/vitals"}}',REACT_APP_VERCEL_BRANCH_URL:"based-git-main-trybased.vercel.app",REACT_APP_VERCEL_GIT_COMMIT_MESSAGE:"Merge pull request #72 from grigerny/cursor/fix-doc-path-route-92cd\n\nfix: /doc/:id white screen \u2014 redirect to /?doc=",REACT_APP_VERCEL_DEPLOYMENT_ID:"dpl_AGjsSaVrRaABU1cBfdrSwYgrbTnK",REACT_APP_VERCEL_GIT_REPO_SLUG:"knowledge-base-saas",REACT_APP_VERCEL_TARGET_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_SHA:"3652b2969ded46d64de91ec6acc78f22cc8c6ae4",REACT_APP_VERCEL_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_REF:"main",REACT_APP_VERCEL_URL:"based-hwwo5zpxx-trybased.vercel.app",REACT_APP_VERCEL_PROJECT_PRODUCTION_URL:"www.trybased.com",REACT_APP_VERCEL_GIT_PREVIOUS_SHA:"",REACT_APP_VERCEL_GIT_REPO_ID:"980833582",REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_LOGIN:"grigerny",REACT_APP_VERCEL_GIT_REPO_OWNER:"grigerny"}.REACT_APP_CLASSIFY_AGENT_INTENT_URL;if(e&&"string"===typeof e&&e.startsWith("http"))return e.replace(/\/$/,"");if("true"==={NODE_ENV:"production",PUBLIC_URL:".",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0,REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_NAME:"Gary Riger",REACT_APP_VERCEL_GIT_PROVIDER:"github",REACT_APP_VERCEL_PROJECT_ID:"prj_A5c8ZMv75ibxQVceA3I7GjPny9oD",REACT_APP_VERCEL_GIT_PULL_REQUEST_ID:"",REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG:'{"analytics":{"scriptSrc":"8f81e36d25c71756/script.js","viewEndpoint":"8f81e36d25c71756/view","eventEndpoint":"8f81e36d25c71756/event","sessionEndpoint":"8f81e36d25c71756/session"},"speedInsights":{"scriptSrc":"1e9f61cb490e195d/script.js","endpoint":"1e9f61cb490e195d/vitals"}}',REACT_APP_VERCEL_BRANCH_URL:"based-git-main-trybased.vercel.app",REACT_APP_VERCEL_GIT_COMMIT_MESSAGE:"Merge pull request #72 from grigerny/cursor/fix-doc-path-route-92cd\n\nfix: /doc/:id white screen \u2014 redirect to /?doc=",REACT_APP_VERCEL_DEPLOYMENT_ID:"dpl_AGjsSaVrRaABU1cBfdrSwYgrbTnK",REACT_APP_VERCEL_GIT_REPO_SLUG:"knowledge-base-saas",REACT_APP_VERCEL_TARGET_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_SHA:"3652b2969ded46d64de91ec6acc78f22cc8c6ae4",REACT_APP_VERCEL_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_REF:"main",REACT_APP_VERCEL_URL:"based-hwwo5zpxx-trybased.vercel.app",REACT_APP_VERCEL_PROJECT_PRODUCTION_URL:"www.trybased.com",REACT_APP_VERCEL_GIT_PREVIOUS_SHA:"",REACT_APP_VERCEL_GIT_REPO_ID:"980833582",REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_LOGIN:"grigerny",REACT_APP_VERCEL_GIT_REPO_OWNER:"grigerny"}.REACT_APP_CONNECT_FUNCTIONS_EMULATOR||"true"==={NODE_ENV:"production",PUBLIC_URL:".",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0,REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_NAME:"Gary Riger",REACT_APP_VERCEL_GIT_PROVIDER:"github",REACT_APP_VERCEL_PROJECT_ID:"prj_A5c8ZMv75ibxQVceA3I7GjPny9oD",REACT_APP_VERCEL_GIT_PULL_REQUEST_ID:"",REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG:'{"analytics":{"scriptSrc":"8f81e36d25c71756/script.js","viewEndpoint":"8f81e36d25c71756/view","eventEndpoint":"8f81e36d25c71756/event","sessionEndpoint":"8f81e36d25c71756/session"},"speedInsights":{"scriptSrc":"1e9f61cb490e195d/script.js","endpoint":"1e9f61cb490e195d/vitals"}}',REACT_APP_VERCEL_BRANCH_URL:"based-git-main-trybased.vercel.app",REACT_APP_VERCEL_GIT_COMMIT_MESSAGE:"Merge pull request #72 from grigerny/cursor/fix-doc-path-route-92cd\n\nfix: /doc/:id white screen \u2014 redirect to /?doc=",REACT_APP_VERCEL_DEPLOYMENT_ID:"dpl_AGjsSaVrRaABU1cBfdrSwYgrbTnK",REACT_APP_VERCEL_GIT_REPO_SLUG:"knowledge-base-saas",REACT_APP_VERCEL_TARGET_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_SHA:"3652b2969ded46d64de91ec6acc78f22cc8c6ae4",REACT_APP_VERCEL_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_REF:"main",REACT_APP_VERCEL_URL:"based-hwwo5zpxx-trybased.vercel.app",REACT_APP_VERCEL_PROJECT_PRODUCTION_URL:"www.trybased.com",REACT_APP_VERCEL_GIT_PREVIOUS_SHA:"",REACT_APP_VERCEL_GIT_REPO_ID:"980833582",REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_LOGIN:"grigerny",REACT_APP_VERCEL_GIT_REPO_OWNER:"grigerny"}.REACT_APP_USE_FIREBASE_EMULATORS)return"http://127.0.0.1:".concat({NODE_ENV:"production",PUBLIC_URL:".",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0,REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_NAME:"Gary Riger",REACT_APP_VERCEL_GIT_PROVIDER:"github",REACT_APP_VERCEL_PROJECT_ID:"prj_A5c8ZMv75ibxQVceA3I7GjPny9oD",REACT_APP_VERCEL_GIT_PULL_REQUEST_ID:"",REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG:'{"analytics":{"scriptSrc":"8f81e36d25c71756/script.
1js","viewEndpoint":"8f81e36d25c71756/view","eventEndpoint":"8f81e36d25c71756/event","sessionEndpoint":"8f81e36d25c71756/session"},"speedInsights":{"scriptSrc":"1e9f61cb490e195d/script.js","endpoint":"1e9f61cb490e195d/vitals"}}',REACT_APP_VERCEL_BRANCH_URL:"based-git-main-trybased.vercel.app",REACT_APP_VERCEL_GIT_COMMIT_MESSAGE:"Merge pull request #72 from grigerny/cursor/fix-doc-path-route-92cd\n\nfix: /doc/:id white screen \u2014 redirect to /?doc=",REACT_APP_VERCEL_DEPLOYMENT_ID:"dpl_AGjsSaVrRaABU1cBfdrSwYgrbTnK",REACT_APP_VERCEL_GIT_REPO_SLUG:"knowledge-base-saas",REACT_APP_VERCEL_TARGET_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_SHA:"3652b2969ded46d64de91ec6acc78f22cc8c6ae4",REACT_APP_VERCEL_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_REF:"main",REACT_APP_VERCEL_URL:"based-hwwo5zpxx-trybased.vercel.app",REACT_APP_VERCEL_PROJECT_PRODUCTION_URL:"www.trybased.com",REACT_APP_VERCEL_GIT_PREVIOUS_SHA:"",REACT_APP_VERCEL_GIT_REPO_ID:"980833582",REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_LOGIN:"grigerny",REACT_APP_VERCEL_GIT_REPO_OWNER:"grigerny"}.REACT_APP_FUNCTIONS_EMULATOR_PORT||"5001","/").concat($,"/").concat(Q,"/classifyAgentIntent");return"https://".concat(Q,"-").concat($,".cloudfunctions.net/classifyAgentIntent")}();try{const i=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:"Bearer ".concat(a)},body:JSON.stringify({userText:t.slice(0,2e3),hasCurrentDocument:!0===e.hasCurrentDocument,workspaceDocIndex:r,orgWorkspaceIndex:o})});if(!i.ok)return n;const s=await i.json();let l="string"===typeof(null===s||void 0===s?void 0:s.intent)?s.intent.trim():"chat";Z.has(l)||(l="chat");const d="number"===typeof(null===s||void 0===s?void 0:s.confidence)&&Number.isFinite(s.confidence)?Math.max(0,Math.min(1,s.confidence)):.5,u=null!==s&&void 0!==s&&s.params&&"object"===typeof s.params?s.params:{},g={prompt:"string"===typeof u.prompt?u.prompt.trim():t,documentTitle:"string"===typeof u.documentTitle?u.documentTitle.trim():"",documentIdGuess:"string"===typeof u.documentIdGuess?u.documentIdGuess.trim():"",updateInstruction:"string"===typeof u.updateInstruction?u.updateInstruction.trim():"",taskName:"string"===typeof u.taskName?u.taskName.trim():"",workspaceName:"string"===typeof u.workspaceName?u.workspaceName.trim():""};return g.prompt||(g.prompt=t),{intent:l,confidence:d,params:g}}catch(d){return console.warn("classifyAgentIntent:",d),n}}var te=n(97976),ne=n(86836);const ie=/\b(add|remove|delete|update|edit|change|fix|replace|insert|include|rewrite|shorten|expand|format|convert|turn|make|transform|reformat)\b/i,se=/^(what|why|how|when|where|who|is|are|does|do|did|can you explain|tell me about|summarize|describe)\b/i;function re(e){const t=String(e||"").trim();return t?ne.AA.test(t)?t:se.test(t)&&!ie.test(t)?null:ie.test(t)?t:null:null}var oe=n(35417);const ae="kbFabPendingTimerPick",ce=/^(?:please\s+)?(?:can you\s+)?(?:start|begin|track|time|log)\s+(?:a\s+)?timer\s+(?:for|on)\s+(.+)/i,le=/^(?:please\s+)?(?:can you\s+)?(?:start|begin|track|time|log)\s+(?:a\s+)?timer\s+(?:for|on)\s+(.+?)\s+in\s+(?:the\s+)?(.+?)\s+workspace\s*$/i,de=/^(?:please\s+)?(?:can you\s+)?(?:start|begin|track|time|log)\s+(?:a\s+)?timer\s+(?:for|on)\s+(.+?)\s+in\s+(?:the\s+)?(.+)\s*$/i;function ue(e){const t=String(e||"").trim();if(!t)return null;const n=t.match(le);if(n)return{taskName:n[1].trim(),workspaceName:n[2].trim()};const i=t.match(de);if(i&&!/workspace$/i.test(i[2]))return{taskName:i[1].trim(),documentTitle:i[2].trim()};const s=t.match(ce);if(s)return{taskName:s[1].trim()};if(/\b(start|begin|track|log)\b.*\btimer\b/i.test(t)&&/\b(for|on)\b/i.test(t)){const e=t.replace(/^(please\s+|can you\s+)/i,"").trim().match(/\b(?:for|on)\s+(.+)/i);if(e)return{taskName:e[1].trim()}}return null}function ge(e){try{sessionStorage.setItem(ae,JSON.stringify(e))}catch(t){}}const pe=new Set(["timer","time","work","this work","task","untitled task","start timer","start a timer","begin timer","track time","log time"]);function me(e){const t=String(e||"").trim().toLowerCase();return!t||(!!pe.has(t)||!!/^(start|begin|track|log)\s+(a\s+)?timer\b/i.test(t))}function he(e){return me(e)?"your work":String(e||"").trim()}const ye=e=>{var t,n,N;let D=e.workspace,P=e.onAgentReady,j=e.filteredDocuments,U=void 0===j?null:j,O=e.userProfile,L=void 0===O?null:O,G=e.activeDocumentId,M=void 0===G?null:G,F=e.compact,Q=void 0!==F&&F,$=e.initialAssistantMessage,Z=void 0===$?null:$,X=e.onInitialAssistantMessageConsumed,ne=void 0===X?null:X,ie=e.onRequestClose,se=void 0===ie?null:ie;const ce=(0,r.useState)(!1),le=(0,s.A)(ce,2),de=le[0],pe=le[1],ye=(0,r.useState)(!1),fe=(0,s.A)(ye,2),xe=fe[0],Ae=fe[1],we=(0,r.useState)(null),ve=(0,s.A)(we,2),Ee=ve[0],be=ve[1],Ce=(0,r.useState)([]),ke=(0,s.A)(Ce,2),Se=ke[0],Ie=ke[1],_e=(0,r.useState)(""),Re=(0,s.A)(_e,2),Te=Re[0],Ne=Re[1],De=(0,r.useState)(null),Pe=(0,s.A)(De,2),je=Pe[0],Ue=Pe[1],Oe=(0,r.useState)(null),Le=(0,s.A)(Oe,2),Ge=Le[0],Me=Le[1],Fe=(0,r.useState)(!1),Ve=(0,s.A)(Fe,2),Be=Ve[0],We=Ve[1],He=(0,r.useState)(null),qe=(0,s.A)(He,2),ze=(qe[0],qe[1]),Je=(0,r.useState)(!0),Ke=(0,s.A)(Je,2),Ye=(Ke[0],Ke[1],(0,r.useState)([])),Qe=(0,s.A)(Ye,2),$e=Qe[0],Ze=Qe[1],Xe=(0,r.useState)([]),et=(0,s.A)(Xe,2),tt=et[0],nt=et[1],it=(0,r.useState)(null),st=(0,s.A)(it,2),rt=st[0],ot=st[1],at=(0,r.useState)(!1),ct=(0,s.A)(at,2),lt=ct[0],dt=ct[1],ut=(0,r.useState)(null),gt=(0,s.A)(ut,2),pt=(gt[0],gt[1]),mt=(0,r.useState)(!1),ht=(0,s.A)(mt,2),yt=ht[0],ft=ht[1],xt=(0,r.useState)([]),At=(0,s.A)(xt,2),wt=At[0],vt=At[1],Et=(0,r.useState)({}),bt=(0,s.A)(Et,2),Ct=bt[0],kt=bt[1],St=(0,r.useState)(!1),It=(0,s.A)(St,2),_t=It[0],Rt=It[1],Tt=(0,r.useState)(""),Nt=(0,s.A)(Tt,2),Dt=Nt[0],Pt=Nt[1],jt=(0,r.useState)(!1),Ut=(0,s.A)(jt,2),Ot=Ut[0],Lt=Ut[1],Gt=(0,r.useState)(!1),Mt=(0,s.A)(Gt,2),Ft=Mt[0],Vt=Mt[1],Bt=(0,r.useState)(null),Wt=(0,s.A)(Bt,2),Ht=Wt[0],qt=Wt[1],zt
1=(0,r.useState)(null),Jt=(0,s.A)(zt,2),Kt=Jt[0],Yt=Jt[1],Qt=(0,r.useRef)(null);(0,r.useEffect)(()=>{Qt.current=Kt},[Kt]);const $t=(0,o.Zp)(),Zt=(0,Y.V)(),Xt=Zt.requestKbAction,en=Zt.workspaceList,tn=(0,b.xI)(),nn=(0,r.useRef)(null),sn=(0,r.useRef)(null),rn=(0,r.useRef)(!1),on=(0,r.useRef)(Z),an=(0,r.useRef)(ne);(0,r.useEffect)(()=>{if(rn.current&&!Be){const e=sn.current;e&&!e.disabled&&e.focus()}rn.current=Be},[Be]),on.current=Z,an.current=ne;const cn=(null===D||void 0===D?void 0:D.emoji)||null,ln=(0,r.useCallback)(()=>{var e;const t=((null===L||void 0===L?void 0:L.firstName)||"").toString().replace(/['"]/g,"").trim();if(t)return t;const n=((null===tn||void 0===tn||null===(e=tn.currentUser)||void 0===e?void 0:e.displayName)||"").toString().replace(/['"]/g,"").trim();return n&&n.split(/\s+/)[0]||""},[null===L||void 0===L?void 0:L.firstName,null===tn||void 0===tn||null===(t=tn.currentUser)||void 0===t?void 0:t.displayName]),dn=(null===(n=(null===L||void 0===L?void 0:L.profileImageUrl)||(null===tn||void 0===tn||null===(N=tn.currentUser)||void 0===N?void 0:N.photoURL)||"")||void 0===n?void 0:n.toString().trim())||"",un=yt?"":dn;(0,r.useEffect)(()=>{ft(!1)},[dn]);const gn=(0,C.httpsCallable)(k.Cn,"createWorkspaceAgent"),pn=(0,C.httpsCallable)(k.Cn,"createAgentChatSession"),mn=(0,C.httpsCallable)(k.Cn,"sendAgentMessageWithRAG"),hn=(0,C.httpsCallable)(k.Cn,"sendAgentMessage"),yn=(0,C.httpsCallable)(k.Cn,"indexWorkspaceForChat",{timeout:3e5});(0,C.httpsCallable)(k.Cn,"getAgentChatHistory");(0,r.useEffect)(()=>{D&&((0,_.gg)("\ud83d\udd04 Workspace changed, resetting WorkspaceAgent state for:",D.id),pe(!1),Ae(!1),be(null),Ie([]),Ne(""),Ue(null),Me(null),We(!1),ze(null),Ze([]),ot(null),dt(!1),pt(null),ft(!1),vt([]),kt({}),Rt(!1),Pt(""),nt([]),Lt(!1),Yt(null))},[null===D||void 0===D?void 0:D.id]);const fn=async()=>{const e=tn.currentUser;if(!e)throw new Error("User not authenticated");return await e.getIdToken()},xn=async function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;(0,_.gg)("\ud83d\udcc4 PROCESS DEBUG: Starting to process document: ".concat(e.title,", isEncrypted: ").concat(e.isEncrypted,", encryptionMethod: ").concat(e.encryptionMethod));let o=(0,i.A)({},e);if(o.isEncrypted&&t){const l=e.id;kt(e=>(0,i.A)((0,i.A)({},e),{},{[l]:{status:"decrypting",progress:0}})),null===r||void 0===r||r("Reading secured document\u2026");try{var a;(0,_.gg)("\ud83d\udd10 PROCESS DEBUG: Decrypting document: ".concat(e.title," (method: ").concat(e.encryptionMethod,")"));let s=null,c="";if((0,_.gg)("\ud83d\udd0d ENCRYPTION DEBUG for ".concat(e.title,":"),{encryptionMethod:e.encryptionMethod,hasUserEncryptedResult:!!e.userEncryptedResult,userEncryptedLength:(null===(a=e.userEncryptedResult)||void 0===a?void 0:a.length)||0,hasWorkspaceEncryptedResults:!!e.workspaceEncryptedResults,availableWorkspaceIds:e.workspaceEncryptedResults?Object.keys(e.workspaceEncryptedResults):[],requestedWorkspaceId:n,documentWorkspaceId:e.workspaceId}),kt(e=>(0,i.A)((0,i.A)({},e),{},{[l]:{status:"decrypting",progress:25}})),"dual"===e.encryptionMethod||"workspace"===e.encryptionMethod){let i=null;if(e.workspaceEncryptedResults){const t=Object.keys(e.workspaceEncryptedResults);n&&t.includes(n)?i=n:e.workspaceId&&t.includes(e.workspaceId)?i=e.workspaceId:t.includes("Default")?i="Default":t.length>0&&(i=t[0],console.warn("\u26a0\ufe0f Using first available workspace ID: ".concat(i," for document: ").concat(e.title))),(0,_.gg)("\ud83d\udd0d WORKSPACE ID RESOLUTION:",{requested:n,documentWorkspaceId:e.workspaceId,availableIds:t,selectedId:i})}if(i&&e.workspaceEncryptedResults){(0,_.gg)("\ud83d\udd10 PROCESS DEBUG: Trying workspace decryption for ".concat(e.title," (workspace: ").concat(i,")")),null===r||void 0===r||r("Decrypting with workspace key\u2026");try{s=await(0,I._r)(e.workspaceEncryptedResults,i),s?(c="workspace-".concat(i),(0,_.gg)("\u2705 PROCESS DEBUG: Workspace decryption succeeded for ".concat(e.title," with workspace ").concat(i))):(0,_.gg)("\u274c PROCESS DEBUG: Workspace decryption returned null for ".concat(e.title," with workspace ").concat(i))}catch(d){console.error("\u274c PROCESS DEBUG: Workspace decryption threw error for ".concat(e.title,":"),d)}}if(!s&&"dual"===e.encryptionMethod&&e.userEncryptedResult){(0,_.gg)("\ud83d\udd04 PROCESS DEBUG: Trying user encryption as fallback for ".concat(e.title)),null===r||void 0===r||r("Trying personal key\u2026");try{const n=await(0,I.k5)(t.uid);n?(s=await(0,I.PV)(e.userEncryptedResult,n),s?(c="user-fallback",(0,_.gg)("\u2705 PROCESS DEBUG: User fallback decryption succeeded for ".concat(e.title))):(0,_.gg)("\u274c PROCESS DEBUG: User fallback decryption returned null for ".concat(e.title))):(0,_.gg)("\u274c PROCESS DEBUG: Could not derive user key for ".concat(e.title))}catch(u){console.error("\u274c PROCESS DEBUG: User fallback decryption failed for ".concat(e.title,":"),u)}}}else if(e.userEncryptedResult){(0,_.gg)("\ud83d\udd10 PROCESS DEBUG: Using user decryption (default) for ".concat(e.title)),null===r||void 0===r||r("Decrypting with personal key\u2026");try{const n=await(0,I.k5)(t.uid);n&&(s=await(0,I.PV)(e.userEncryptedResult,n),s&&(c="user",(0,_.gg)("\u2705 PROCESS DEBUG: User decryption succeeded for ".concat(e.title))))}catch(u){console.error("\u274c PROCESS DEBUG: User decryption failed for ".concat(e.title,":"),u)}}if(!s){const t={encryptionMethod:e.encryptionMethod,availableUserEncryption:!!e.userEncryptedResult,availableWorksp
1aceIds:e.workspaceEncryptedResults?Object.keys(e.workspaceEncryptedResults):[],requestedWorkspaceId:n,attemptedMethods:[]};throw e.workspaceEncryptedResults&&t.attemptedMethods.push("workspace"),e.userEncryptedResult&&"dual"===e.encryptionMethod&&t.attemptedMethods.push("user-fallback"),e.userEncryptedResult&&!e.encryptionMethod&&t.attemptedMethods.push("user"),new Error("All decryption methods failed. Details: ".concat(JSON.stringify(t)))}kt(e=>(0,i.A)((0,i.A)({},e),{},{[l]:{status:"decrypting",progress:75}})),(0,_.gg)("\ud83d\udd10 PROCESS DEBUG: Decryption successful, parsing JSON..."),(0,_.gg)("\ud83d\udd10 PROCESS DEBUG: Decrypted text preview:",s.substring(0,200)),null===r||void 0===r||r("Unpacking document\u2026");const g=JSON.parse(s);(0,_.gg)("\ud83d\udd10 PROCESS DEBUG: Parsed object keys:",Object.keys(g)),o=(0,i.A)((0,i.A)((0,i.A)({},o),g),{},{id:e.id,isEncrypted:!0,encryptionSource:c,content:g.textContent||g.content||g.editorHtml,extractedContent:g.textContent||g.extractedContent,text:g.textContent||g.text,title:g.title||e.title}),(0,_.gg)("\u2705 PROCESS DEBUG: Document decrypted successfully: ".concat(e.title," (source: ").concat(c,")")),kt(e=>(0,i.A)((0,i.A)({},e),{},{[l]:{status:"success",progress:100}}))}catch(Ee){var c;console.error("\u274c PROCESS DEBUG: Failed to decrypt document ".concat(e.title,":"),Ee),console.error("\u274c PROCESS DEBUG: Available encryption data:",{hasUserEncrypted:!!e.userEncryptedResult,hasWorkspaceEncrypted:!!e.workspaceEncryptedResults,workspaceKeys:e.workspaceEncryptedResults?Object.keys(e.workspaceEncryptedResults):[],encryptionMethod:e.encryptionMethod,requestedWorkspaceId:n,documentWorkspaceId:e.workspaceId,userEncryptedDataLength:(null===(c=e.userEncryptedResult)||void 0===c?void 0:c.length)||0,workspaceEncryptedDataLengths:e.workspaceEncryptedResults?Object.entries(e.workspaceEncryptedResults).map(e=>{let t=(0,s.A)(e,2),n=t[0],i=t[1];return"".concat(n,": ").concat(null===i||void 0===i?void 0:i.length)}):[]}),kt(e=>(0,i.A)((0,i.A)({},e),{},{[l]:{status:"error",progress:0,error:Ee.message}})),o=(0,i.A)((0,i.A)({},o),{},{title:e.title,content:"[Encrypted Document: ".concat(e.title,"] - Unable to decrypt. Error: ").concat(Ee.message),isEncrypted:!0,decryptionFailed:!0,decryptionError:Ee.message})}}else(0,_.gg)("\ud83d\udcc4 PROCESS DEBUG: Non-encrypted document ".concat(e.title)),e.textContent&&"[Encrypted Content]"!==e.textContent?o.content=e.textContent:e.content?o.content=e.content:e.extractedContent&&(o.content=e.extractedContent);const l=o.content||"";return(0,_.gg)("\ud83d\udcc4 PROCESS DEBUG: Final result for ".concat(e.title,":"),{hasContent:l.length>0,contentLength:l.length,encryptionSource:o.encryptionSource,decryptionFailed:o.decryptionFailed}),o},An=async e=>{const t=tn.currentUser;if(!t)return(0,_.gg)("\u274c LOAD DEBUG: No authenticated user for document loading"),[];try{Rt(!0);const n=e=>{Pt(e),(0,_.gg)("\ud83d\udcce Based AI init: ".concat(e));try{"undefined"!==typeof console&&console.info&&console.info("[Based AI]",e)}catch(t){}};if((0,_.gg)("\ud83d\udcda LOAD DEBUG: Starting document load for workspace ".concat(e,"...")),(0,_.gg)("\ud83d\udcda LOAD DEBUG: Current user:",{uid:t.uid,email:t.email}),(0,_.gg)("\ud83d\udcda LOAD DEBUG: filteredDocuments prop:",{exists:!!U,isArray:Array.isArray(U),length:(null===U||void 0===U?void 0:U.length)||0,sample:(null===U||void 0===U?void 0:U.slice(0,5).map(e=>({id:e.id,title:e.title||e.fileName})))||"N/A"}),U&&Array.isArray(U)&&U.length>0){(0,_.gg)("\ud83d\udcda LOAD DEBUG: \u2705 Using filtered documents from parent (grid view): ".concat(U.length," documents")),(0,_.gg)("\ud83d\udcda LOAD DEBUG: Filtered document IDs:",U.map(e=>e.id)),(0,_.gg)("\ud83d\udcda LOAD DEBUG: Filtered document titles:",U.map(e=>e.title||e.fileName||"Untitled"));const s=U;n("Reading ".concat(s.length," document").concat(1===s.length?"":"s"," from your current view\u2026"));const r=[];for(let c=0;c<s.length;c++){const o=s[c];try{const i=(0,W.Od)(o)||o.title||o.fileName||"Untitled",a=i.length>72?"".concat(i.slice(0,69),"\u2026"):i,l=o.isEncrypted?"Decrypting":"Loading";n("".concat(l,' "').concat(a,'" (').concat(c+1," of ").concat(s.length,")"));const d=await xn(o,t,e,e=>{n("".concat(l,' "').concat(a,'" (').concat(c+1," of ").concat(s.length,") \u2014 ").concat(e))});r.push(d)}catch(Ee){console.error("\u274c LOAD DEBUG: Failed to process document ".concat(o.title,":"),Ee);const t=(0,i.A)((0,i.A)({},o),{},{content:"[Error processing document: ".concat(o.title,"] - ").concat(Ee.message),processingError:!0});r.push(t)}}Ze(r);const o=r.filter(e=>e.isEncrypted);vt(o);const a=Array.from(new Map(r.map(e=>[e.id,e])).values());return nt(a),(0,_.gg)("\ud83d\udcca Document deduplication by ID: ".concat(r.length," processed \u2192 ").concat(a.length," unique")),(0,_.gg)("\ud83d\udccb AI ASSISTANT - Using filtered documents from grid view: ".concat(a.length," documents")),(0,_.gg)("\ud83d\udccb AI ASSISTANT - Document IDs:",a.map(e=>e.id)),(0,_.gg)("\ud83d\udccb AI ASSISTANT - Document titles:",a.map(e=>e.title||e.fileName||"Untitled")),Rt(!1),r}null===U||void 0===U?(0,_.gg)("\u26a0\ufe0f LOAD DEBUG: filteredDocuments prop is null/undefined - falling back to Firestore query"):Array.isArray(U)&&0===U.length&&(0,_.gg)("\u26a0\ufe0f LOAD DEBUG: filteredDocuments prop is empty array - falling back to Firestore query"),(0,_.gg)("\ud83d\udcda LOAD DEBUG: \u26a0\ufe0f Calling getDocumentsByWorkspaceId(".concat(e,") - NOT using filtered documents from grid view")),n("Fetching document list from your workspace\u2026");const s=await(0,S._R)(e);if((0,_.gg)("\ud83d\udcda LOAD DEBUG: Raw result from getDocumentsByWorkspaceId:",s),(0,_.gg)("\ud83d\udcda LOAD DEBUG: Type of documents:",typeof s),(0,_.gg)("\ud83d\udcda LOAD DEBUG: Is array:",Array.isArray(s)),(0,_.gg)("\ud83d\udcda LOAD DEBUG: Length:",null===s||void 0===s?void 0:s.length),!s||!Array.isArray(s))return console.error("\u274c LOAD DEBUG: getDocumentsByWorkspaceId returned invali
1d data:",s),[];if(0===s.length)return console.error("\u274c LOAD DEBUG: getDocumentsByWorkspaceId returned empty array for workspace ".concat(e)),console.error("\u274c LOAD DEBUG: This means either:"),console.error(" 1. No documents exist for this workspace ID"),console.error(" 2. The workspace ID is incorrect"),console.error(" 3. There's a permission/auth issue"),console.error(" 4. The getDocumentsByWorkspaceId function has a bug"),[];(0,_.gg)("\ud83d\udcda LOAD DEBUG: Retrieved ".concat(s.length," raw documents:"),s.map((e,t)=>({index:t,id:e.id,title:e.title,isEncrypted:e.isEncrypted,hasContent:!!(e.content||e.extractedContent||e.text),contentFields:Object.keys(e).filter(e=>["content","extractedContent","text","summary","originalText"].includes(e)),contentLengths:{content:(e.content||"").length,extractedContent:(e.extractedContent||"").length,text:(e.text||"").length,summary:(e.summary||"").length,originalText:(e.originalText||"").length},allKeys:Object.keys(e)})));const r=s.filter(e=>e.isEncrypted),o=s.filter(e=>!e.isEncrypted);(0,_.gg)("\ud83d\udd10 LOAD DEBUG: Found ".concat(r.length," encrypted documents:"),r.map(e=>({id:e.id,title:e.title}))),(0,_.gg)("\ud83d\udcc4 LOAD DEBUG: Found ".concat(o.length," non-encrypted documents:"),o.map(e=>({id:e.id,title:e.title}))),vt(r),n("Preparing ".concat(s.length," document").concat(1===s.length?"":"s"," (").concat(r.length," secured)\u2026"));const a=[];for(let u=0;u<s.length;u++){const r=s[u],o=(0,W.Od)(r)||r.title||r.fileName||"Untitled",c=o.length>72?"".concat(o.slice(0,69),"\u2026"):o,l=r.isEncrypted?"Decrypting":"Loading";n("".concat(l,' "').concat(c,'" (').concat(u+1," of ").concat(s.length,")")),(0,_.gg)("\ud83d\udd04 LOAD DEBUG: Processing document ".concat(u+1,"/").concat(s.length,": ").concat(r.title," (ID: ").concat(r.id,")")),(0,_.gg)("\ud83d\udd04 LOAD DEBUG: Document ".concat(r.title," details:"),{isEncrypted:r.isEncrypted,hasEncryptedResult:!!r.userEncryptedResult,hasContent:!!r.content,hasExtractedContent:!!r.extractedContent,hasText:!!r.text,contentPreview:(r.content||r.extractedContent||r.text||"").substring(0,200)});try{const i=await xn(r,t,e,e=>{n("".concat(l,' "').concat(c,'" (').concat(u+1," of ").concat(s.length,") \u2014 ").concat(e))});(0,_.gg)("\u2705 LOAD DEBUG: Successfully processed document ".concat(r.title,":"),{title:i.title,hasContent:!!(i.content||i.extractedContent||i.text),contentLength:(i.content||i.extractedContent||i.text||"").length,contentPreview:(i.content||i.extractedContent||i.text||"").substring(0,200),decryptionFailed:i.decryptionFailed,processingError:i.processingError}),a.push(i)}catch(Ee){console.error("\u274c LOAD DEBUG: Failed to process document ".concat(r.title,":"),Ee);const t=(0,i.A)((0,i.A)({},r),{},{content:"[Error processing document: ".concat(r.title,"] - ").concat(Ee.message),processingError:!0});(0,_.gg)("\u26a0\ufe0f LOAD DEBUG: Adding error document:",t),a.push(t)}}(0,_.gg)("\u2705 LOAD DEBUG: Final processed documents summary:",a.map((e,t)=>({index:t,title:e.title,id:e.id,hasContent:!!(e.content||e.extractedContent||e.text),contentLength:(e.content||e.extractedContent||e.text||"").length,isAccessible:!e.decryptionFailed&&!e.processingError,decryptionFailed:e.decryptionFailed,processingError:e.processingError,isEncrypted:e.isEncrypted,contentPreview:(e.content||e.extractedContent||e.text||"").substring(0,100)})));const c=a.filter(e=>!e.decryptionFailed&&!e.processingError);(0,_.gg)("\ud83d\udcca LOAD DEBUG: Final stats:",{totalRetrieved:s.length,totalProcessed:a.length,accessibleDocuments:c.length,failedDecryption:a.filter(e=>e.decryptionFailed).length,processingErrors:a.filter(e=>e.processingError).length}),0===c.length&&(console.error("\ud83d\udd25 LOAD DEBUG: ZERO ACCESSIBLE DOCUMENTS! This explains why indexing returns 0."),console.error("\ud83d\udd25 LOAD DEBUG: Check the content of your documents in the database."),console.error("\ud83d\udd25 LOAD DEBUG: All documents either failed decryption or processing.")),Ze(a);const l=Array.from(new Map(a.map(e=>[e.id,e])).values());nt(l),(0,_.gg)("\ud83d\udcca Document deduplication by ID: ".concat(a.length," processed \u2192 ").concat(l.length," unique"));const d=l.map(e=>e.id);return(0,_.gg)("\ud83d\udccb AI ASSISTANT - Deduplicated document IDs:",d),(0,_.gg)("\ud83d\udccb AI ASSISTANT - Deduplicated document titles:",l.map(e=>e.title||"Untitled")),a}catch(Ee){return console.error("\u274c LOAD DEBUG: Error in loadWorkspaceDocuments:",Ee),console.error("\u274c LOAD DEBUG: Error stack:",Ee.stack),Ze([]),[]}finally{Rt(!1)}},wn=e=>{if(!e)return 0;if("function"===typeof e.toMillis)return e.toMillis();if("number"===typeof e.seconds)return 1e3*e.seconds;if(e instanceof Date)return e.getTime();if("number"===typeof e)return e;if("string"===typeof e){const t=Date.parse(e);return Number.isFinite(t)?t:0}return 0},vn=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).force,n=void 0!==t&&t;
1(0,_.gg)("\ud83d\udd04 DEBUG: Starting indexing with detailed logging...");const i=e||$e,s=(i||[]).filter(e=>!e.decryptionFailed&&!e.processingError),r=n?s:s.filter(e=>!(e=>{if(!e)return!1;if("ready"!==e.workspaceSearchIndexStatus)return!1;const t=wn(e.workspaceSearchIndexAt);return!!t&&t>=wn(e.updatedAt||e.uploadedAt)})(e));if(0===r.length&&s.length>0){(0,_.gg)("\u2705 Index already fresh for all ".concat(s.length," accessible doc(s); skipping reindex call"));const e="\u2705 Search index up to date (".concat(s.length," document").concat(1===s.length?"":"s",")");return ot(e),Pt(""),!0}dt(!0);const o=(i||[]).some(e=>e.decryptionFailed),a=r.length,c=s.length,l=o?"Indexing for search (".concat(a," of ").concat(c," need refresh; some documents could not be unlocked)\u2026"):a===c?"Indexing ".concat(a," document").concat(1===a?"":"s"," for search\u2026"):"Refreshing search index for ".concat(a," updated document").concat(1===a?"":"s","\u2026");ot(l),Pt(l);try{(0,_.gg)("\ud83d\udcda DEBUG: About to index workspace:",D.id),(0,_.gg)("\ud83d\udcda DEBUG: Documents source:",e?"passed directly":"from state");const t=Array.from(new Map(r.map(e=>[e.id,e])).values());(0,_.gg)("\ud83d\udcca Stale set: ".concat(r.length," stale (of ").concat(s.length," accessible) \u2192 ").concat(t.length," unique to send")),(0,_.gg)("\ud83e\udd16 AI ASSISTANT - Documents being indexed: ".concat(t.length," unique documents"));const n=t.map(e=>({id:e.id,title:e.title||"Untitled",contentLength:(e.content||e.extractedContent||e.text||e.textContent||"").length}));(0,_.gg)("\ud83d\udccb AI ASSISTANT - Document list:",n),(0,_.gg)("\ud83d\udd0d CRITICAL DEBUG: About to send these documents to Cloud Function:"),t.forEach((e,t)=>{const n=e.content||e.extractedContent||e.text||e.textContent||"";(0,_.gg)("\ud83d\udcc4 Doc ".concat(t+1,":"),{id:e.id,title:e.title,contentSource:e.content?"content":e.extractedContent?"extractedContent":e.text?"text":e.textContent?"textContent":"NONE",contentLength:n.length,contentPreview:n.substring(0,200),isEncrypted:e.isEncrypted,wasDecrypted:e.isEncrypted&&!e.decryptionFailed,availableFields:{content:(e.content||"").length,extractedContent:(e.extractedContent||"").length,text:(e.text||"").length,textContent:(e.textContent||"").length,editorHtml:(e.editorHtml||"").length}})});const o={workspaceId:D.id,forceReindex:!0,documents:t.map(e=>{let t="";return e.textContent&&e.textContent.trim()?t=e.textContent:e.content&&e.content.trim()?t=e.content:e.extractedContent&&e.extractedContent.trim()?t=e.extractedContent:e.text&&e.text.trim()?t=e.text:e.editorHtml&&e.editorHtml.trim()?t=e.editorHtml:(console.error("\ud83d\udd25 No content found for document: ".concat(e.title)),t="Document: ".concat(e.title," (no content available)")),{id:e.id,title:e.title,content:t,type:e.type||"document",isEncrypted:e.isEncrypted||!1,wasDecrypted:e.isEncrypted&&!e.decryptionFailed,fileType:e.fileType||"",fileName:e.fileName||"",viewerMode:e.viewerMode||""}}),debugInfo:{totalDocuments:(i||[]).length,accessibleDocuments:s.length,staleDocuments:r.length,uniqueDocuments:t.length,duplicatesRemoved:r.length-t.length,encryptedDocuments:(i||[]).filter(e=>e.isEncrypted).length,failedDecryptions:(i||[]).filter(e=>e.decryptionFailed).length,documentTitles:t.map(e=>e.title)}};(0,_.gg)("\ud83d\ude80 DEBUG: Final payload being sent to indexWorkspaceForChat:",{workspaceId:o.workspaceId,documentsCount:o.documents.length,documentsDetail:o.documents.map(e=>({title:e.title,contentLength:e.content.length,contentPreview:e.content.substring(0,100)}))});const a=await yn(o);(0,_.gg)("\u2705 DEBUG: Raw indexing result:",a),(0,_.gg)("\u2705 DEBUG: Indexing data:",a.data);const c=a.data;0===c.documentsProcessed&&(console.error("\ud83d\udd25 DEBUG: ZERO DOCUMENTS PROCESSED!"),console.error("\ud83d\udd25 DEBUG: This means your Cloud Function indexWorkspaceForChat is not processing the documents correctly."),console.error("\ud83d\udd25 DEBUG: Check your Cloud Function logs to see what it received vs what it processed."),console.error("\ud83d\udd25 DEBUG: The documents we sent had content lengths:",o.documents.map(e=>"".concat(e.title,": ").concat(e.content.length," chars"))));const l=c.documentsProcessed>0?"\u2705 Indexed ".concat(c.documentsProcessed," documents with ").concat(c.totalChunks," chunks"):"\u274c Indexing failed - no documents were processed";return ot(l),Pt(l),c.documentsProcessed>0}catch(d){console.error("\ud83d\udd25 DEBUG: Indexing failed completely:",d);const e="\u274c Indexing failed: ".concat(d.message);return ot(e),Pt(e),!1}finally{dt(!1)}},En=(0,r.useCallback)(async()=>
1{if(!D)return void(0,_.gg)("No workspace selected");if(de||xe)return void(0,_.gg)("\ud83d\udd04 Agent already initialized or loading, skipping...");Ae(!0),be(null),Pt("Checking workspace documents\u2026");let e=0;if(Array.isArray(U))e=U.length;else try{const t=await(0,S._R)(D.id);e=Array.isArray(t)?t.length:0}catch(r){(0,_.gg)("\u26a0\ufe0f Failed to check document count:",r),e=0}if(0===e)return(0,_.gg)("\ud83d\udced No documents in workspace, skipping agent initialization"),Ae(!1),Lt(!0),be(null),void Pt("");Lt(!1);let t=null;try{Pt("Creating workspace AI assistant\u2026");await fn();(0,_.gg)("\ud83d\ude80 Initializing RAG-enabled agent with encryption support for workspace:",D.id),(0,_.gg)("\ud83d\ude80 filteredDocuments prop at initialization:",{exists:!!U,isArray:Array.isArray(U),length:(null===U||void 0===U?void 0:U.length)||0});try{const e=await gn({workspaceId:D.id,provider:"openai"});(0,_.gg)("\u2705 RAG Agent created:",e.data),t=e.data,Ue(t)}catch(o){var n;if("permission-denied"===o.code||null!==(n=o.message)&&void 0!==n&&n.includes("access"))return console.warn("\u26a0\ufe0f User does not have access to workspace for agent:",D.id,o.message),(0,_.gg)("\u26a0\ufe0f Skipping agent initialization - no workspace access"),be("You do not have access to create an agent for this workspace."),Ae(!1),void Pt("");throw o}try{Pt("Starting secure chat session\u2026");const e=await pn({workspaceId:D.id,provider:"openai"});(0,_.gg)("\u2705 Chat session created:",e.data);const t=e.data.chatId;Me(t)}catch(a){console.error("Failed to create chat session on init:",a),Me("rag_chat_".concat(Date.now()))}(0,_.gg)("\ud83d\udcda TIMING FIX: Starting document loading..."),Pt("Loading and decrypting workspace documents\u2026");const e=await An(D.id);(0,_.gg)("\ud83d\udcda TIMING FIX: Document loading completed, got:",e.length,"documents");const c=Array.from(new Map(e.map(e=>[e.id,e])).values()),l=c.length;(0,_.gg)("\ud83d\udcca Deduplication by ID: ".concat(e.length," loaded \u2192 ").concat(l," unique documents")),(0,_.gg)("\ud83e\udd16 AI ASSISTANT - Final document count: ".concat(l));const d=c.map(e=>({id:e.id,title:e.title||"Untitled",contentLength:(e.content||e.extractedContent||e.text||e.textContent||"").length}));(0,_.gg)("\ud83d\udccb AI ASSISTANT - Final document list:",d),(0,_.gg)("\ud83d\udccb AI ASSISTANT - Final document IDs:",c.map(e=>e.id)),(0,_.gg)("\ud83d\udcda TIMING FIX: Triggering background freshness check / indexing..."),vn(e).catch(e=>
1{console.error("\u26a0\ufe0f Background indexing failed:",e)}),pe(!0);const u=c.filter(e=>e.decryptionFailed).length,g=ln(),p=g?"Hi ".concat(g,"!"):"Hello!";let m="".concat(p," I'm your ").concat(D.name," assistant.");u>0?m+=" Note: ".concat(u," document").concat(1===u?"":"s"," couldn't be accessed for search and won't be included in answers."):l>0&&(m+=" I've indexed your documents and I'm ready to help."),m+=" How can I help you today?";const h="string"===typeof on.current?on.current.trim():"",y={id:Date.now(),role:"assistant",content:m,timestamp:new Date,ragInfo:null};if(h){Ie([{id:Date.now()-1,role:"assistant",content:h,timestamp:new Date,ragInfo:null},y]);try{var s;null===(s=an.current)||void 0===s||s.call(an)}catch(r){(0,_.gg)("onInitialAssistantMessageConsumed error",r)}}else Ie([y]);P&&t&&P((0,i.A)((0,i.A)({},t),{},{documentsCount:l}))}catch(c){console.error("\ud83d\udd25 Failed to initialize RAG agent:",c),be(c.message)}finally{Ae(!1),Pt("")}},[null===D||void 0===D?void 0:D.id,de,xe,U,ln]);(0,r.useEffect)(()=>{if(D&&!de&&!xe){if((0,_.gg)("\ud83d\udd04 Workspace effect triggered, initializing agent..."),(0,_.gg)("\ud83d\udd04 filteredDocuments at effect time:",{exists:!!U,isArray:Array.isArray(U),length:(null===U||void 0===U?void 0:U.length)||0}),null===U||void 0===U){(0,_.gg)("\u23f3 filteredDocuments not available yet, waiting 100ms...");const e=setTimeout(()=>{En()},100);return()=>clearTimeout(e)}En()}},[null===D||void 0===D?void 0:D.id,de,xe,U,En]);const bn=(0,r.useCallback)(async e=>{const t="string"===typeof e?e:"";if(t)try{await navigator.clipboard.writeText(t);const e=(0,A.UD)({documentTitle:null===D||void 0===D?void 0:D.name,contextLabel:"Assistant reply",excerpt:t});x.Ay.custom(t=>(0,V.jsxs)("div",{className:"rounded-lg bg-white px-3 py-2.5 shadow-lg border border-gray-200 max-w-sm",children:[(0,V.jsx)("p",{className:"text-sm font-medium text-gray-900",children:"Copied to clipboard"}),(0,V.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:"Continue in another assistant"}),(0,V.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,V.jsxs)("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-md border border-gray-200 bg-gray-50 px-2 py-1.5 text-xs font-medium text-gray-800 hover:bg-gray-100",onClick:()=>{(0,A._J)(e),x.Ay.dismiss(t.id)},children:[(0,V.jsx)(w.A,{size:16}),"ChatGPT"]}),(0,V.jsxs)("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-md border border-gray-200 bg-gray-50 px-2 py-1.5 text-xs font-medium text-gray-800 hover:bg-gray-100",onClick:()=>{(0,A.Vw)(e),x.Ay.dismiss(t.id)},children:[(0,V.jsx)(v.A,{size:16}),"Claude"]})]})]}),{duration:8e3})}catch(n){x.Ay.error("Could not copy to clipboard")}else x.Ay.error("Nothing to copy")},[null===D||void 0===D?void 0:D.name]),Cn=(0,r.useCallback)(e=>{const t=String(e||"").trim();t&&Ie(e=>[...e,{id:Date.now()+Math.floor(1e4*Math.random()),role:"assistant",content:t,timestamp:new Date,ragInfo:null}])},[]),kn=(0,r.useCallback)(async(e,t)=>{const n=await Xt({type:e,payload:t});if(null===n||void 0===n||!n.deferred)return n;try{"createWithAI"===e?(sessionStorage.setItem("kbFabPendingAction",JSON.stringify({type:"createWithAI",payload:{form:t.form,clarificationPairs:t.clarificationPairs||null}})),$t({pathname:"/",search:"?fabPendingAction=1"},{replace:!0})):"openBlank"===e?$t({pathname:"/",search:"?fabOpenBlank=1"},{replace:!0}):"openDocumentById"===e?$t({pathname:"/",search:"?fabOpenDocId=".concat(encodeURIComponent(String(t.id)))},{replace:!0}):"updateWithAIForDocument"===e?(sessionStorage.setItem("kbFabUpdatePrompt",String(t.userPrompt||"")),$t({pathname:"/",search:"?fabUpdateDocId=".concat(encodeURIComponent(String(t.id)))},{replace:!0})):"updateWithAIForCurrent"===e?(sessionStorage.setItem("kbFabPendingAction",JSON.stringify({type:"updateWithAIForCurrent",payload:{userPrompt:String(t.userPrompt||"")}})),$t({pathname:"/",search:"?fabPendingAction=1"},{replace:!0})):"switchWorkspace"===e?(ge({taskName:String(t.taskName||""),workspaceId:String(t.workspaceId||""),step:"pick_doc"}),$t({pathname:"/",search:"?fabSwitchWorkspaceId=".concat(encodeURIComponent(String(t.workspaceId)))},{replace:!0})):"startTimerOnDocument"===e?(sessionStorage.setItem("kbFabPendingAction",JSON.stringify({type:"startTimerOnDocument",payload:{id:String(t.id||""),taskName:String(t.taskName||""),forceSwitchTimer:!0===t.forceSwitchTimer}})),$t({pathname:"/",search:"?fabStartTimerDocId=".concat(encodeURIComponent(String(t.id)))},{replace:!0})):"openBlankThenStartTimer"===e&&(sessionStorage.setItem("kbFabPendingAction",JSON.stringify({type:"openBlankThenStartTimer",payload:{taskName:String(t.taskName||""),forceSwitchTimer:!0===t.forceSwitchTimer}})),$t({pathname:"/",search:"?fabOpenBlankThenStartTimer=1"},{replace:!0}))}catch(i){console.warn("dispatchKbOrDefer",i)}return x.Ay.success("Opening your workspace\u2026"),null===se||void 0===se||se(),n},[$t,se,Xt]);function Sn(e,t){const n=String(e||"").toLowerCase().trim(),i=String(t||"").toLowerCase().trim();if(!i||!n)return 0;if(n===i)return 200;if(n.includes(i))return 100+Math.min(i.length,40);const s=i.split(/[^a-z0-9]+/).filter(e=>e.length>1);let r=0;for(const o of s)n.includes(o)&&(r+=Math.min(o.length,12));return r}function In(){return $e.filter(e=>!e.decryptionFailed)}function _n(e,t){var n;const i=In(),s=null!=t?String(t).trim():"";if(s&&/^[a-zA-Z0-9_-]{8,}$/.test(s)){const e=i.find(e=>String(e.id)===s);if(e)return{matches:[{id:e.id,title:(0,W.Od)(e,"Untitled")}],ambiguous:!1}}const r=String(e||"").trim();if(!r)return{matches:[],ambiguous:!1};const o=i.map(e=>{const t=(0,W.Od)(e,"Untitled");return{id:e.id,title:t,score:Sn(t,r)}}).filter(e=>e.score>0).sort((e,t)=>
1t.score-e.score),a=(null===(n=o[0])||void 0===n?void 0:n.score)||0;if(!a)return{matches:[],ambiguous:!1};const c=o.filter(e=>e.score===a);return 1===c.length?{matches:c,ambiguous:!1}:{matches:c.slice(0,8),ambiguous:!0}}function Rn(e){return function(e,t){var n;const i=Array.isArray(e)?e:[],s=String(t||"").toLowerCase().trim();if(!s)return{matches:[],ambiguous:!1};const r=i.map(e=>{const t=String(e.name||"").trim(),n=t.toLowerCase();let i=0;if(n===s)i=200;else if(n.includes(s))i=100+Math.min(s.length,40);else for(const r of s.split(/[^a-z0-9]+/).filter(e=>e.length>1))n.includes(r)&&(i+=Math.min(r.length,12));return{id:e.id,name:t||"Untitled",score:i}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score),o=(null===(n=r[0])||void 0===n?void 0:n.score)||0;if(!o)return{matches:[],ambiguous:!1};const a=r.filter(e=>e.score===o);return 1===a.length?{matches:a,ambiguous:!1}:{matches:a.slice(0,8),ambiguous:!0}}(en,e)}function Tn(e){const t=In().slice(0,11).map(e=>({id:e.id,title:(0,W.Od)(e,"Untitled")})),n=t.map((e,t)=>"".concat(t+1,". **").concat(e.title,"**"));n.push("".concat(t.length+1,". **Create new document**")),Yt({kind:"start_timer_pick_doc",taskName:String(e||"").trim(),options:t,createNewIndex:t.length+1}),Cn("Which document should I track **".concat(he(e),"** in? Reply with a number, or say **cancel**:\n\n").concat(n.join("\n")))}function Nn(e){let t=e.docId,n=void 0===t?"":t,i=e.createNew,s=void 0!==i&&i;Yt({kind:"start_timer_task_name",docId:null!=n?String(n):"",createNew:!!s}),Cn("What should I track this timer for? Reply with a short task name (for example, **review PR#177**), or say **cancel**.")}async function Dn(e,t,n){t?await Un(null,n,async(e,t)=>{await jn(e,t)}):await Un(e,n,async(t,n)=>{await Pn(e,t,n)})}async function Pn(e,t){let n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).forceSwitchTimer,i=void 0!==n&&n;const s=String(t||"").trim()||"Untitled Task";await kn("startTimerOnDocument",{id:e,taskName:s,forceSwitchTimer:i}),Cn("Starting timer for **".concat(s,"**\u2026"))}async function jn(e){let t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).forceSwitchTimer,n=void 0!==t&&t;const i=String(e||"").trim()||"Untitled Task";await kn("openBlankThenStartTimer",{taskName:i,forceSwitchTimer:n}),Cn("Creating a document and starting timer for **".concat(i,"**\u2026"))}async function Un(e,t,n){const i=String(t||"").trim()||"Untitled Task",s=function(e){const t=(0,oe.qG)();if(!t||!["running","paused"].includes(t.state))return{conflict:!1,sameDoc:!1,persisted:null};const n=null!=e?String(e).trim():"",i=n&&String(t.docId)===n;return{conflict:!i,sameDoc:i,persisted:t}}(e),r=s.conflict,o=s.sameDoc,a=s.persisted;if(o&&a)await n(i,{forceSwitchTimer:!1});else{if(r&&a){const t=a.taskName||"another task";return Yt({kind:"start_timer_conflict",taskName:i,targetDocId:null!=e?String(e):"",startMode:e?"document":"new"}),void Cn("You already have a timer running for **".concat(t,"**. Reply **switch** to move timing to this task (the other timer will stop without saving), or **cancel**."))}await n(i,{forceSwitchTimer:!1})}}async function On(e,t){const n=e&&"object"===typeof e?e:{};let i=String(n.taskName||"").trim();const s=String(n.documentTitle||"").trim(),r=String(n.documentIdGuess||"").trim(),o=String(n.workspaceName||"").trim();if(!i){const e=ue(t);i=(null===e||void 0===e?void 0:e.taskName)||t}if(i){if(o){const e=Rn(o),t=e.matches,n=e.ambiguous;if(!t.length)return void Cn("I couldn't find a workspace named **".concat(o,"**."));if(n){const e=t.map((e,t)=>"".concat(t+1,". **").concat(e.name,"**"));return Yt({kind:"disambiguate_pick",options:t.map(e=>({id:e.id,title:e.name})),follow:"switch_workspace_timer",taskName:i}),void Cn("Which workspace? Reply with a number, or say **cancel**:\n\n".concat(e.join("\n")))}const s=t[0];if(String(s.id)!==String(null===D||void 0===D?void 0:D.id))return ge({taskName:i,workspaceId:String(s.id),step:"pick_doc"}),await kn("switchWorkspace",{workspaceId:String(s.id),taskName:i}),void Cn("Switching to **".concat(s.name,"** \u2014 then I'll ask which document to track **").concat(i,"** in."))}if(M&&!s&&!r)return me(i)?void Nn({docId:M,createNew:!1}):void await Un(M,i,async(e,t)=>{await Pn(M,e,t)});if(s||r){const e=_n(s||i,r),t=e.matches,n=e.ambiguous;if(!t.length)return void Cn("I couldn't find a workspace document that matches that name.");if(n){const e=t.map((e,t)=>"".concat(t+1,". **").concat(e.title,"**"));return Yt({kind:"disambiguate_pick",options:t.map(e=>({id:e.id,title:e.title})),follow:"start_timer",taskName:i}),void Cn("Which document should I track **".concat(he(i),"** in? Reply with a number, or say **cancel**:\n\n").concat(e.join("\n")))}return me(i)?void Nn({docId:t[0].id,createNew:!1}):void await Un(t[0].id,i,async(e,n)=>{await Pn(t[0].id,e,n)})}!function(e){const t=(null===D||void 0===D?void 0:D.name)||"this workspace";0!==(en||[]).filter(e=>{var t;return null!=(null===e||void 0===e?void 0:e.id)&&String(e.id)!==String(null!==(t=null===D||void 0===D?void 0:D.id)&&void 0!==t?t:"")}).length?(Yt({kind:"start_timer_pick_workspace",step:"current_or_other",taskName:String(e||"").trim(),currentWorkspaceId:null!=(null===D||void 0===D?void 0:D.id)?String(D.id):"",currentWorkspaceName:t}),Cn("Where should I track **".concat(he(e),"**?\n\n1. **").concat(t,"** (current workspace)\n2. **Another workspace**\n\nReply with **1** or **2**, or say **cancel**."))):Tn(e)}(i)}else Cn('Tell me what work to time \u2014 for example, "start timer for roofing estimate".')}function Ln(e){return"string"===typeof e?e:(null===e||void 0===e?void 0:e.question)||""}async function Gn(e){const t=Qt.current;if(!t||!t.kind)return;const n=String(e||"").trim().toLowerCase();if("cancel"===n)return Yt(null),void Cn("Okay \u2014 cancelled.");
1if("create_document"===t.kind&&"clarify"===t.step){const s=Array.isArray(t.clarifyQuestions)?t.clarifyQuestions:[],r="number"===typeof t.clarifyIndex?t.clarifyIndex:0;if(!s[r])return void Yt(null);const o="skip"===n?"":String(e||"").trim(),a=(0,i.A)((0,i.A)({},t.clarifyAnswers||{}),{},{[r]:o});if(r+1<s.length)return Yt((0,i.A)((0,i.A)({},t),{},{clarifyAnswers:a,clarifyIndex:r+1})),void Cn(Ln(s[r+1]));const c=s.map((e,t)=>{var n;return{question:Ln(e),answer:String(null!==(n=a[t])&&void 0!==n?n:"").trim()}}),l=t.formDraft||{};return Yt(null),await kn("createWithAI",{form:l,clarificationPairs:c}),void Cn("Opening your draft in the editor\u2026")}if("disambiguate_pick"===t.kind){const n=Array.isArray(t.options)?t.options:[],i=parseInt(String(e||"").trim(),10);if(!Number.isFinite(i)||i<1||i>n.length)return void Cn("Reply with a number **1\u2013".concat(n.length,"**, or say **cancel**."));const s=n[i-1],r=t.follow,o=t.updateInstruction||"";if(Yt(null),"open"===r)await kn("openDocumentById",{id:s.id}),Cn("Opening **".concat(s.title,"**."));else if("update"===r)await kn("updateWithAIForDocument",{id:s.id,userPrompt:o}),Cn("Updating **".concat(s.title,"**\u2026"));else if("start_timer"===r){const e=t.taskName||"";me(e)?Nn({docId:s.id,createNew:!1}):await Un(s.id,e,async(e,t)=>{await Pn(s.id,e,t)})}else if("switch_workspace_timer"===r){const e=t.taskName||"";String(s.id)!==String(null===D||void 0===D?void 0:D.id)?(ge({taskName:e,workspaceId:String(s.id),step:"pick_doc"}),await kn("switchWorkspace",{workspaceId:String(s.id),taskName:e}),Cn("Switching to **".concat(s.title,"** \u2014 then I'll ask which document to track **").concat(e,"** in."))):Tn(e)}return}if("start_timer_pick_workspace"===t.kind){const n=t.taskName||"";if("current_or_other"===t.step){const i=parseInt(String(e||"").trim(),10);return 1===i?(Yt(null),void Tn(n)):2===i?void function(e,t){const n=(en||[]).filter(e=>null!=(null===e||void 0===e?void 0:e.id)&&String(e.id)!==String(null!==t&&void 0!==t?t:"")).slice(0,12).map(e=>({id:String(e.id),name:String(e.name||"Untitled").trim()}));if(!n.length)return Cn("You don't have any other workspaces \u2014 I'll use the current one."),void Tn(e);const i=n.map((e,t)=>"".concat(t+1,". **").concat(e.name,"**"));Yt({kind:"start_timer_pick_workspace",step:"pick_other_workspace",taskName:String(e||"").trim(),options:n,currentWorkspaceId:null!=t?String(t):""}),Cn("Which workspace should I use? Reply with a number, or say **cancel**:\n\n".concat(i.join("\n")))}(n,t.currentWorkspaceId):void Cn("Reply **1** for the current workspace, **2** for another, or say **cancel**.")}if("pick_other_workspace"===t.step){const i=Array.isArray(t.options)?t.options:[],s=parseInt(String(e||"").trim(),10);if(!Number.isFinite(s)||s<1||s>i.length)return void Cn("Reply with a number **1\u2013".concat(i.length,"**, or say **cancel**."));const r=i[s-1];if(Yt(null),String(r.id)===String(null===D||void 0===D?void 0:D.id))return void Tn(n);ge({taskName:n,workspaceId:String(r.id),step:"pick_doc"}),await kn("switchWorkspace",{workspaceId:String(r.id),taskName:n}),Cn("Switching to **".concat(r.name,"** \u2014 then I'll ask which document to track **").concat(n,"** in."))}return}if("start_timer_pick_doc"===t.kind){const n=Array.isArray(t.options)?t.options:[],i="number"===typeof t.createNewIndex?t.createNewIndex:n.length+1,s=i,r=parseInt(String(e||"").trim(),10);if(!Number.isFinite(r)||r<1||r>s)return void Cn("Reply with a number **1\u2013".concat(s,"**, or say **cancel**."));const o=t.taskName||"";if(Yt(null),r===i)me(o)?Nn({createNew:!0}):await Dn(null,!0,o);else{const e=n[r-1];if(null===e||void 0===e||!e.id)return void Cn("That option is not available. Try again.");me(o)?Nn({docId:e.id,createNew:!1}):await Dn(e.id,!1,o)}return}if("start_timer_task_name"===t.kind){const n=String(e||"").trim();if(!n)return void Cn("Tell me what to track \u2014 a short task name is enough.");const i=t.docId||"",s=!!t.createNew;return Yt(null),void await Dn(i,s,n)}if("start_timer_conflict"!==t.kind);else if("switch"===n){(0,oe.HG)(null);const e=t.taskName||"",n=t.targetDocId||"",i=t.startMode||"document";Yt(null),"new"!==i&&n?await Pn(n,e,{forceSwitchTimer:!0}):await jn(e,{forceSwitchTimer:!0})}else Cn("Reply **switch** to move the timer, or **cancel**.")}async function Mn(e,t,n){const i=t&&"object"===typeof t?t:{}
1,s=String(i.prompt||n||"").trim(),r=String(i.documentTitle||"").trim(),o=String(i.documentIdGuess||"").trim(),a=String(i.updateInstruction||s||"").trim();if("open_blank"===e)return await kn("openBlank",{}),void Cn("Opening a new blank document.");if("open_document"===e){const e=_n(r||s,o),t=e.matches,n=e.ambiguous;if(!t.length)return void Cn("I couldn't find a workspace document that matches that name.");if(n){const e=t.map((e,t)=>"".concat(t+1,". **").concat(e.title,"**"));return Yt({kind:"disambiguate_pick",options:t.map(e=>({id:e.id,title:e.title})),follow:"open"}),void Cn("I found more than one match. Reply with a number, or say **cancel**:\n\n".concat(e.join("\n")))}return await kn("openDocumentById",{id:t[0].id}),void Cn("Opening **".concat(t[0].title,"**."))}if("update_current_document"===e)return M?(await kn("updateWithAIForCurrent",{userPrompt:a}),void Cn("Updating this document\u2026")):void Cn("Open a document first, or tell me which document to update by name.");if("update_workspace_document"===e){const e=_n(r||s,o),t=e.matches,n=e.ambiguous;if(!t.length)return void Cn("I couldn't find a workspace document that matches that name.");if(n){const e=t.map((e,t)=>"".concat(t+1,". **").concat(e.title,"**"));return Yt({kind:"disambiguate_pick",options:t.map(e=>({id:e.id,title:e.title})),follow:"update",updateInstruction:a}),void Cn("Which document should I update? Reply with a number, or say **cancel**:\n\n".concat(e.join("\n")))}return await kn("updateWithAIForDocument",{id:t[0].id,userPrompt:a}),void Cn("Updating **".concat(t[0].title,"**\u2026"))}if("create_document"===e){const e=s||n;if(!e)return void Cn("Tell me what kind of document you need.");const t={userPrompt:e,documentType:"auto",tone:"professional",useCompanyInfo:!0,useWorkspaceDocuments:!0,askClarification:!1};Cn("Got it \u2014 checking a few details that help avoid placeholders\u2026");try{const n=await(0,te.Ln)({userPrompt:e,documentType:"auto",companyContext:"",workspaceId:(null===D||void 0===D?void 0:D.id)||null}),i=n.status,s=n.questions;"need_info"===i&&Array.isArray(s)&&s.length?(Yt({kind:"create_document",step:"clarify",formDraft:t,clarifyQuestions:s,clarifyIndex:0,clarifyAnswers:{}}),Cn("**".concat(Ln(s[0]),"**\n\nAnswer here in chat. Say **skip** to leave a placeholder, or **cancel** to stop."))):(await kn("createWithAI",{form:t,clarificationPairs:null}),Cn("Opening your draft in the editor\u2026"))}catch(c){console.error("FAB gather details:",c),Cn("Could not prepare follow-up questions \u2014 starting the draft anyway."),await kn("createWithAI",{form:t,clarificationPairs:null})}return}"start_timer"===e&&await On(i,n)}(0,r.useEffect)(()=>{if(!Q||null===D||void 0===D||!D.id||!de)return;const e=function(){try{const e=sessionStorage.getItem(ae);return e?JSON.parse(e):null}catch(e){return null}}();if(!e||"pick_doc"!==e.step)return;if(String(e.workspaceId)!==String(D.id))return;!function(){try{sessionStorage.removeItem(ae)}catch(e){}}();const t=e.taskName||"",n=setTimeout(()=>{Tn(t)},500);return()=>clearTimeout(n)},[Q,null===D||void 0===D?void 0:D.id,de]);const Fn=async()=>{if(!Te.trim()||!je||Be)return;const e=Te.trim();Ne(""),We(!0),be(null);const t={id:Date.now(),role:"user",content:e,timestamp:new Date};if(Qt.current){Ie(e=>[...e,t]);try{await Gn(e)}catch(r){console.error("FAB pending intent:",r),Ie(e=>[...e,{id:Date.now()+2,role:"assistant",content:(null===r||void 0===r?void 0:r.message)||"Something went wrong. Try again.",timestamp:new Date,ragInfo:null}])}finally{We(!1)}return}if(Ie(e=>[...e,t]),Q)try{const t=$e.filter(e=>!e.decryptionFailed).slice(0,50).map(e=>({id:String(e.id),title:(0,W.Od)(e,"Untitled")}));if(M){const t=re(e);if(t)return await Mn("update_current_document",{updateInstruction:t,prompt:e},e),void We(!1)}else if(re(e))return Cn("Open the document you want to change in the editor first, then ask me again from Based AI."),void We(!1);const n=ue(e);if(n)return await Mn("start_timer",{taskName:n.taskName,documentTitle:n.documentTitle||"",workspaceName:n.workspaceName||"",prompt:e},e),void We(!1);const i=(en||[]).slice(0,50).map(e=>({id:String(e.id),name:String(e.name||"Untitled").trim()})),s=await ee({userText:e,hasCurrentDocument:!!M,workspaceDocIndex:t,orgWorkspaceIndex:i}),r=s.intent,o=s.params;if("cancel"===r)return Cn("Nothing to cancel right now."),void We(!1);if(r&&"chat"!==r)return await Mn(r,o,e),void We(!1)}catch(r){(0,_.gg)("classifyAgentIntent",r)}let n=null,s=Ge;try{const e=await fn();
1if((0,_.gg)("\ud83d\udd0d RAG DEBUG: Starting message send process with encryption support"),(0,_.gg)("\ud83d\udd0d RAG DEBUG: Auth token obtained:",!!e),(0,_.gg)("\ud83d\udd0d RAG DEBUG: Workspace info:",{id:D.id,name:D.name,type:typeof D.id}),!s){(0,_.gg)("\ud83d\udd0d RAG DEBUG: No chat ID, creating new session...");try{const e=await pn({workspaceId:D.id,provider:"openai"});(0,_.gg)("\ud83d\udd0d RAG DEBUG: Session creation result:",e),s=e.data.chatId,Me(s)}catch(o){(0,_.gg)("\ud83d\udd0d RAG DEBUG: Session creation failed:",o),s="rag_chat_".concat(Date.now()),Me(s),(0,_.gg)("\ud83d\udd0d RAG DEBUG: Using fallback chat ID:",s)}}const r="workspace_".concat(D.id);(0,_.gg)("\ud83d\udd0d RAG DEBUG: Expected Qdrant collection name:",r);const a=Se.slice(-10).map(e=>({role:e.role,content:e.content})),c=$e.filter(e=>!e.decryptionFailed);n=(0,H.Ww)({workspaceId:D.id,chatId:s,message:t.content,surface:q.qN.INTERNAL_AGENT,ragAudience:"internal",conversationHistory:a,documents:c,format:"callable",extras:(0,i.A)({isInternalSetup:!0,encryptionContext:{totalDocuments:$e.length,encryptedDocuments:wt.length,accessibleDocuments:c.length}},M?{documentId:M}:{})}),(0,_.gg)("\ud83d\udd0d RAG DEBUG: Request payload with encryption context:",{workspaceId:D.id,chatId:s,messageLength:t.content.length,provider:"openai",encryptionContext:n.encryptionContext}),(0,_.gg)("\ud83d\udd0d RAG DEBUG: About to call sendAgentMessageWithRAG function");const l=await mn(n);(0,_.gg)("\ud83d\udd0d RAG DEBUG: Raw response received:",l);const d=l.data;(0,_.gg)("\u2705 RAG response processed:",d);let u="";u=d.content?d.content:d.message?d.message:d.response?d.response:d.answer?d.answer:"I received your message but had trouble generating a response. Please try rephrasing your question.";const g={id:Date.now()+1,role:"assistant",content:u,timestamp:new Date,ragInfo:d.ragContext||null};Ie(e=>[...e,g]),d.ragContext&&ze(d.ragContext)}catch(a){console.error("\ud83d\udd25 RAG DEBUG: Complete error object:",a);let e="";if(a.message.includes("not-found")||a.message.includes("Not found")||a.message.includes("not_found")||a.message.includes("does not exist")||a.message.includes("Please index first")||"functions/not-found"===a.code){console.error("\ud83d\udd25 RAG DEBUG: Collection not found error detected"),(0,_.gg)("\ud83d\udd04 RAG DEBUG: Attempting automatic indexing...");const t={id:Date.now()+1,role:"assistant",content:'I notice this is the first time referencing "'.concat(D.name,'". Let me quickly index your documents. This will take a moment...'),timestamp:new Date,ragInfo:null};Ie(e=>[...e,t]);try{if(await vn()){(0,_.gg)("\ud83d\udd04 RAG DEBUG: Indexing complete, retrying original message...");try{const e=(await mn(n)).data;(0,_.gg)("\u2705 RAG retry successful:",e);let t="";t=e.content?e.content:e.message?e.message:e.response?e.response:e.answer?e.answer:"OK! All set up now. Please ask your question again.";const i={id:Date.now()+2,role:"assistant",content:t,timestamp:new Date,ragInfo:e.ragContext||null};return Ie(e=>[...e,i]),void(e.ragContext&&ze(e.ragContext))}catch(c){console.error("\ud83d\udd25 RAG DEBUG: Retry after indexing failed:",c),e="RAG search was set up, but I encountered an issue processing your question. Please try asking again: ".concat(c.message)}}else e="I tried to set up RAG search for your workspace, but the indexing process failed. Please check that your workspace has accessible documents and try again."}catch(l){console.error("\ud83d\udd25 RAG DEBUG: Indexing process failed:",l),e="I tried to automatically set up RAG search, but encountered an error during indexing: ".concat(l.message)}}else if(a.message.includes("permission-denied"))e="I am not authorized to respond. Please check my configuration.";else if(a.message.includes("quota")||a.message.includes("billing"))e="OpenAI API quota exceeded. Please check your billing settings.";else if(a.message.includes("rate limit"))e="Too many requests. Please wait a moment and try again.";else{(0,_.gg)("\ud83d\udd04 RAG failed, trying fallback with document context (including decrypted)...");try{const e=$e.filter(e=>!e.decryptionFailed).map((e,t)=>{(0,_.gg)("\ud83d\udd0d Processing Document ".concat(t+1,": ").concat(e.title," (encrypted: ").concat(e.isEncrypted,")"));let n="",i="none";return e.extractedContent?(n=e.extractedContent,i="extractedContent"):e.content?(n=e.content,i="content"):e.text?(n=e.text,i="text"):e.summary&&e.originalText?(n="Summary: ".concat(e.summary,"\n\nOriginal Text: ").concat(e.originalText),i="summary + originalText"):e.summary?(n=e.summary,i="summary only"):e.originalText&&(n=e.originalText,i="originalText"),e.keyPoints&&Array.isArray(e.keyPoints)&&(n+="\n\nKey Points:\n"+e.keyPoints.map(e=>"\u2022 ".concat(e)).join("\n"),i+=" + keyPoints"),{title:e.title,content:n,type:e.type||"document",isEncrypted:e.isEncrypted||!1,wasDecrypted:e.isEncrypted&&!e.decryptionFailed}}),n=$e.filter(e=>e.decryptionFailed).length,i=Se.slice(-10).map(e=>({role:e.role,content:e.content})),r={workspaceId:D.id,chatId:s,message:t.content,conversationHistory:i,provider:"openai",context:{documents:e,workspaceName:D.name,encryptionInfo:{totalDocuments:$e.length,accessibleDocuments:e.length,excludedDocuments:n,encryptedAndAccessible:e.filter(e=>e.wasDecrypted).length}}};(0,_.gg)("\ud83d\udd04 Trying fallback with document context (with encryption info)...");const o=(await hn(r)).data;let a="";a=o.content?o.content:o.message?o.message:o.response?o.response:o.answer?o.answer:"I was able to access your documents directly and provide this response.";let c="*Note: RAG search is currently unavailable, but I searched through your ".concat(e.length," accessible workspace documents directly.*");n>0&&(c="*Note: RAG search is currently unavailable, but I searched through your ".concat(e.length," accessible documents directly. ").concat(n," document").concat(1===n?"":"s"," couldn't be accessed for search.*"));const l={id:Date.now()+1,role:"assistant",content:"".concat(a,"\n\n").concat(c),timestamp:new Date,ragInfo:null};return void Ie(e=>[...e,l])}catch(d){console.error("\ud83d\udd25 Fallback also failed:",d),e="Sorry, I encountered an error with both RAG search and document fallback: ".concat(a.message)}}const i={id:Date.now()+3,role:"assistant",content:e,timestamp:new Date,ragInfo:null};Ie(e=>[...e,i])}finally{We(!1)}},Vn=(0,r.useCallback)(e=>{Ie(t=>[...t,(0,i.A)({id:Date.now()},e)])},[]);(0,r.useEffect)(()=>{var e;null===(e=nn.current)||void 0===e||e.scrollIntoView({behavior:"smooth"})},[Se,Be]);const Bn=Dt||(lt?rt||"Indexing documents for search\u2026":_t?"Decrypting and loading workspace files\u2026":"Processing documents and handling encryption\u2026");return D?Ot?(0,V.jsx)("div",{className:"flex items-center justify-center h-full bg-gray-50",children:(0,V.jsxs)("div",{className:"text-center",children:[(0,V.jsx)(c.A,{className:"w-12 h-12 text-gray-400 mx-auto mb-3"}),(0,V.jsx)("h3",{className:"text-lg font-semibold text-gray-800",children:"No Documents Yet"}),(0,V.jsx)("p",{className:"text-gray-600 mt-1 max-w-xs mx-auto",children:"Please add documents to this workspace before using the AI assistant."}),(0,V.jsx)("button",{onClick:()=>{Lt(!1),En()},className:"mt-4 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 text-sm",children:"Check Again"})]})}):xe?(0,V.jsx)("div",{className:"flex items-center justify-center h-full bg-gray-50",children:(0,V.jsxs)("div",{className:"text-center",children:[(0,V.jsx)(E.y$,{size:"md",className:"mx-auto mb-4 text-blue-600"}),(0,V.jsxs)("p",{className:"text-gray-600",children:["Initializing ",D.name," agent..."]}),(0,V.jsx)("p",{className:"text-sm text-gray-500 mt-2 max-w-md mx-auto px-3 break-words",children:Bn})]})}):Ee?(0,V.jsx)("div",{className:"bg-red-50 border border-red-200 rounded-lg p-6",children:(0,V.jsxs)("div",{className:"flex items-center",children:[(0,V.jsx)(l.A,{className:"w-6 h-6 text-red-600 mr-3"}),(0,V.jsxs)("div",{children:[(0,V.jsx)("h3",{className:"text-red-800 font-medium",children:"Failed to initialize RAG agent"}),(0,V.jsx)("p",{className:"text-red-600 text-sm mt-1",children:Ee}),(0,V.jsx)("button",{onClick:En,className:"mt-3 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 text-sm",children:"Try Again"})]})]})}):de?Ft?(0,V.jsxs)("div",{className:"h-full flex flex-col bg-white relative",children:[Q?(0,V.jsxs)("div",{className:"flex items-center justify-end gap-2 px-3 py-2 border-b border-gray-200 bg-white shrink-0 z-10",children:[(0,V.jsx)("button",{type:"button",onClick:()=>Vt(!1),className:"px-2.5 py-1 text-xs font-medium text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors",title:"Switch to text mode",children:(0,V.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,V.jsx)(d.A,{className:"w-3.5 h-3.5"}),"Text"]})}),Ht&&(0,V.jsx)("button",{type:"button",onClick:Ht.showPersonalityModal,disabled:Ht.isListening||Ht.isSpeaking||Ht.isProcessing,className:"p-1.5 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Voice settings",children:(0,V.jsx)(u.A,{className:"w-4 h-4"})})]}):(0,V.jsxs)("div",{className:"flex items-center justify-between px-4 py-3 border-b border-gray-200 bg-white z-10",children:[(0,V.jsx)("div",{className:"flex items-center gap-4",children:(()=>{const e=tt.length>0?tt.filter(e=>e.isEncrypted&&!e.decryptionFailed).length:wt.length;return e>0&&(0,V.jsxs)("div",{className:"text-xs text-gray-500 flex items-center gap-1.5",children:[(0,V.jsx)(g.A,{className:"w-3 h-3"}),(0,V.jsxs)("span",{children:[e," encrypted"]})]})})()}),(0,V.jsxs)("div",{className:"flex items-center gap-3",children:[(0,V.jsx)("button",{type:"button",onClick:()=>Vt(!1),className:"px-2.5 py-1 text-xs font-medium text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors",title:"Switch to text mode",children:(0,V.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,V.jsx)(d.A,{className:"w-3.5 h-3.5"}),"Text"]})}),Ht&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)("button",{type:"button",onClick:Ht.showPersonalityModal,disabled:Ht.isListening||Ht.isSpeaking||Ht.isProcessing,className:"p-1.5 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Voice settings",children:(0,V.jsx)(u.A,{className:"w-4 h-4"})}),Ht.isConnected&&(0,V.jsxs)("div",{className:"flex items-center text-xs text-gray-500",children:[(0,V.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full mr-1.5"}),"Connected"]}),Ht.error&&(0,V.jsxs)("div",{className:"flex items-center text-red-600 text-xs",children:[(0,V.jsx)(l.A,{className:"w-3 h-3 mr-1"}),(0,V.jsx)("span",{children:Ht.error})]})]})]})]}),(0,V.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,V.jsx)(B,{workspace:D,chatId:Ge,onMessage:Vn,workspaceDocuments:$e,onControlsReady:qt,activeDocumentId:M})})]}):(0,V.jsxs)("div",{className:"h-full flex flex-col bg-white relative",children:[!Q&&(0,V.jsxs)("div",{className:"flex items-center justify-between px-4 py-3 border-b border-gray-200 bg-white z-10",children:[(0,V.jsxs)("div",{className:"flex items-center gap-4",children:[(()=>{const e=tt.length>0?tt.filter(e=>e.isEncrypted&&!e.decryptionFailed).length:wt.length;return e>0&&(0,V.jsxs)("div",{className:"text-xs text-gray-500 flex items-center gap-1.5",children:[(0,V.jsx)(g.A,{className:"w-3 h-3"}),(0,V.jsxs)("span",{children:[e," encrypted"]})]})})(),(0,V.jsx)("button",{type:"button",onClick:async()=>{try{(0,_.gg)("\ud83d\udd04 Reindex button clicked"),(0,_.gg)("\ud83d\udd0d Current workspaceDocuments state:",{type:typeof $e,isArray:Array.isArray($e),length:null===$e||void 0===$e?void 0:$e.length}),(0,_.gg)("\ud83d\udcda Reloading documents before reindexing...");const e=await An(D.id);await vn(e)}catch(Ee){console.error("\ud83d\udd25 Reindex failed:",Ee),ot("\u274c Reindex failed: ".concat(Ee.message))}},disabled:lt,className:"px-2.5 py-1 text-xs font-medium bg-gray-100 hover:bg-gray-200 border border-gray-300 rounded-md text-gray-700 transition-colors disabled:opacity-50",children:lt?(0,V.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,V.jsx)(E.y$,{size:"sm"}),"Reindexing..."]}):"Reindex"}),(0,V.jsx)("button",{type:"button",onClick:()=>Vt(!0),className:"px-2.5 py-1 text-xs font-medium text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors",title:"Switch to voice mode",children:(0,V.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,V.jsx)(p.A,{className:"w-3.5 h-3.5"}),"Voice"]})})]}),(0,V.jsxs)("div",{className:"flex items-center space-x-3",children:[lt&&(0,V.jsxs)("div",{className:"flex items-center text-sm text-blue-600",children:[(0,V.jsx)(E.y$,{size:"sm",className:"mr-2"}),(0,V.jsx)("span",{children:"Setting up RAG..."})]}),_t&&(0,V.jsxs)("div",{className:"flex items-center text-sm text-blue-600",children:[(0,V.jsx)(g.A,{className:"w-4 h-4 animate-pulse mr-2"}),(0,V.jsx)("span",{children:"Decrypting..."})]}),(0,V.jsxs)("div",{className:"flex items-center",children:[(0,V.jsx)("div",{className:"w-2 h-2 rounded-full ".concat(de?"bg-green-500":"bg-yellow-500")}),(0,V.jsx)("span",{className:"ml-2 text-xs text-gray-500",children:de?"Ready":"Initializing"})]})]})]}),(0,V.jsx)("div",{className:"flex-1 overflow-y-auto",children:(0,V.jsxs)("div",{className:"p-4 space-y-4",children:[Se.map(e=>{var t,n,i,s;return(0,V.jsx)("div",{className:"flex ".concat("user"===e.role?"justify-end":"justify-start"),children:(0,V.jsxs)("div",{className:"flex max-w-xs lg:max-w-md ".concat("user"===e.role?"flex-row-reverse":"flex-row"),children:[(0,V.jsx)("div",{className:"flex-shrink-0 ".concat("user"===e.role?"ml-2":"mr-2"),children:"user"===e.role?un?(0,V.jsx)("div",{className:"w-6 h-6 rounded-full overflow-hidden flex-shrink-0",children:(0,V.jsx)("img",{src:un,alt:"Your profile",className:"w-full h-full object-cover",crossOrigin:"anonymous",onError:()=>ft(!0)},un)}):(0,V.jsx)(m.A,{className:"w-6 h-6 text-gray-600","aria-label":"User"}):cn?(0,V.jsx)("div",{className:"w-6 h-6 rounded-full bg-blue-50 flex items-center justify-center text-[15px] leading-none select-none","aria-label":"Workspace assistant",title:"Workspace assistant",children:cn}):(0,V.jsx)(a.A,{className:"w-6 h-6 text-blue-600","aria-label":"Workspace assistant"})}),(0,V.jsxs)("div",{className:"space-y-2",children:[(0,V.jsxs)("div",{className:"px-4 py-2 rounded-lg ".concat("user"===e.role?"bg-blue-600 text-white":"bg-gray-100 text-gray-800"),children:[(0,V.jsx)("div",{className:"text-sm [&_li]:whitespace-normal ".concat("user"===e.role?"whitespace-pre-wrap":""),children:(0,V.jsx)(R.oz,{remarkPlugins:[T.A],components:{a:t=>{let n=t.href,i=t.children;return(0,V.jsx)("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"underline hover:opacity-80 transition-opacity ".concat("user"===e.role?"text-blue-100 hover:text-white":"text-blue-600 hover:text-blue-800"),children:i})},p:e=>{let t=e.children;return(0,V.jsx)("p",{className:"mb-2 last:mb-0",children:t})},ol:e=>{let t=e.children;return(0,V.jsx)("ol",{className:"list-decimal list-outside pl-5 mt-0 mb-1 space-y-0.5",children:t})},ul:e=>{let t=e.children;return(0,V.jsx)("ul",{className:"list-disc list-outside pl-5 mt-0 mb-1 space-y-0.5",children:t})},li:e=>{let t=e.children;return(0,V.jsx)("li",{className:"my-0.5",children:t})}},children:"assistant"===e.role?(0,z.r)((0,J.M4)(e.content,Array.isArray(null===(t=e.ragInfo)||void 0===t?void 0:t.viewerDocuments)?e.ragInfo.viewerDocuments:[],{})):e.content})}),"assistant"===e.role?(0,V.jsxs)("div",{className:"flex items-center justify-between gap-2 mt-1",children:[(0,V.jsx)("p",{className:"text-xs text-gray-500",children:e.timestamp.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}),(0,V.jsx)("button",{type:"button",onClick:()=>bn(e.content),className:"rounded p-1 text-gray-500 hover:bg-gray-200 hover:text-gray-700 shrink-0",title:"Copy reply","aria-label":"Copy assistant reply",children:(0,V.jsx)(h.A,{className:"w-3.5 h-3.5"})})]}):(0,V.jsx)("p",{className:"text-xs mt-1 ".concat("user"===e.role?"text-blue-200":"text-gray-500"),children:e.timestamp.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})})]}),"assistant"===e.role&&(null!==(n=null===(i=e.ragInfo)||void 0===i||null===(s=i.pdfSources)||void 0
1===s?void 0:s.length)&&void 0!==n?n:0)>0&&(0,V.jsx)(K.E,{pdfSources:e.ragInfo.pdfSources}),"assistant"===e.role&&e.ragInfo&&(0,V.jsxs)("div",{className:"text-xs text-gray-500 bg-gray-50 rounded p-2 border",children:[(0,V.jsxs)("div",{className:"flex items-center mb-1",children:[cn?(0,V.jsx)("span",{className:"mr-1 leading-none","aria-hidden":"true",children:cn}):(0,V.jsx)(a.A,{className:"w-3 h-3 mr-1","aria-hidden":"true"}),(0,V.jsx)("span",{className:"font-medium",children:"RAG Search Results"}),e.ragInfo.encryptionInfo&&(0,V.jsx)(g.A,{className:"w-3 h-3 ml-2 text-blue-500"})]}),e.ragInfo.chunksFound>0&&(0,V.jsxs)("div",{children:["Found ",e.ragInfo.chunksFound," relevant chunks from"," ",e.ragInfo.documentsReferenced.length," documents"]}),e.ragInfo.documentsReferenced.length>0&&(0,V.jsxs)("div",{className:"mt-1",children:[(0,V.jsx)("strong",{children:"Sources:"})," ",e.ragInfo.documentsReferenced.join(", ")]}),e.ragInfo.averageScore&&(0,V.jsxs)("div",{className:"mt-1",children:[(0,V.jsx)("strong",{children:"Avg. Relevance:"})," ",(100*e.ragInfo.averageScore).toFixed(1),"%"]}),e.ragInfo.encryptionInfo&&(0,V.jsxs)("div",{className:"mt-2 pt-2 border-t border-gray-200",children:[(0,V.jsxs)("div",{className:"flex items-center text-blue-600 mb-1",children:[(0,V.jsx)(y.A,{className:"w-3 h-3 mr-1"}),(0,V.jsx)("span",{className:"font-medium",children:"Encryption Status"})]}),e.ragInfo.encryptionInfo.encryptedProcessed>0&&(0,V.jsxs)("div",{children:["\u2705 ",e.ragInfo.encryptionInfo.encryptedProcessed," encrypted documents processed"]}),e.ragInfo.encryptionInfo.encryptionFailed>0&&(0,V.jsxs)("div",{className:"text-yellow-600",children:["\u26a0\ufe0f ",e.ragInfo.encryptionInfo.encryptionFailed," encrypted documents inaccessible"]}),e.ragInfo.encryptionInfo.excludedDocuments>0&&(0,V.jsxs)("div",{className:"text-yellow-600",children:["\u26a0\ufe0f ",e.ragInfo.encryptionInfo.excludedDocuments," documents excluded (encryption key unavailable)"]})]})]})]})]})},e.id)}),Be&&!lt&&(0,V.jsx)("div",{className:"flex justify-start",children:(0,V.jsxs)("div",{className:"flex max-w-xs lg:max-w-md flex-row",children:[(0,V.jsx)("div",{className:"flex-shrink-0 mr-2",children:cn?(0,V.jsx)("div",{className:"w-6 h-6 rounded-full bg-blue-50 flex items-center justify-center text-[15px] leading-none select-none","aria-label":"Workspace assistant",title:"Workspace assistant",children:cn}):(0,V.jsx)(a.A,{className:"w-6 h-6 text-blue-600","aria-label":"Workspace assistant"})}),(0,V.jsx)("div",{className:"px-4 py-3 rounded-lg bg-gray-100 text-gray-800",role:"status","aria-label":"Assistant is typing",children:(0,V.jsxs)("div",{className:"kb-typing-indicator",children:[(0,V.jsx)("span",{className:"kb-typing-dot",style:{animationDelay:"0ms"}}),(0,V.jsx)("span",{className:"kb-typing-dot",style:{animationDelay:"150ms"}}),(0,V.jsx)("span",{className:"kb-typing-dot",style:{animationDelay:"300ms"}})]})})]})}),(0,V.jsx)("div",{ref:nn})]})}),(0,V.jsxs)("div",{className:"border-t border-gray-200 bg-white p-4 shadow-lg",children:[(0,V.jsxs)("div",{className:"flex space-x-2",children:[(0,V.jsx)("input",{ref:sn,type:"text",value:Te,onChange:e=>Ne(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),Fn())},placeholder:"Ask about ".concat(D.name,"..."),className:"flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent",disabled:Be}),(0,V.jsx)("button",{onClick:Fn,disabled:!Te.trim()||Be,className:"px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50",children:(0,V.jsx)(f.A,{className:"w-4 h-4"})})]}),(wt.length>0||Object.keys(Ct).some(e=>"error"===Ct[e].status))&&(0,V.jsx)("div",{className:"mt-2 flex items-center justify-between text-xs text-gray-500",children:(0,V.jsx)("div",{className:"flex items-center"})})]})]}):(0,V.jsx)("div",{className:"flex items-center justify-center h-full bg-gray-50",children:(0,V.jsxs)("div",{className:"text-center",children:[(0,V.jsx)(E.y$,{size:"md",className:"mx-auto mb-4 text-blue-600"}),(0,V.jsxs)("p",{className:"text-gray-600",children:["Initializing ",D.name," agent..."]}),(0,V.jsx)("p",{className:"text-sm text-gray-500 mt-2 max-w-md mx-auto px-3 break-words",children:Bn})]})}):(0,V.jsx)("div",{className:"bg-white border border-gray-200 rounded-lg shadow-sm p-6",children:(0,V.jsxs)("div",{className:"text-center mb-6",children:[(0,V.jsx)(a.A,{className:"w-12 h-12 text-blue-600 mx-auto mb-3"}),(0,V.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Select a Workspace"}),(0,V.jsx)("p",{className:"text-gray-600",children:"Choose a workspace to create a RAG-powered AI assistant with encryption support"})]})})}},34528(e,t,n){n.d(t,{UD:()=>r,Vw:()=>a,_J:()=>
1o});const i=12e3;function s(e,t){return null==e||"string"!==typeof e?"":e.length<=t?e:"".concat(e.slice(0,Math.max(0,t-24)),"\n\n[\u2026truncated]")}function r(e){let t=e.documentTitle,n=e.contextLabel,r=e.excerpt;const o="string"===typeof t?t.trim():"",a=o?"Document: ".concat(o,"\n\n"):"",c="Context (".concat(n,"):\n\n").concat(r);return s("".concat(a).concat(c),i)}function o(e){const t=s(e,i),n="https://chatgpt.com/?q=".concat(encodeURIComponent(t));window.open(n,"_blank","noopener,noreferrer")}function a(e){const t=s(e,i),n="https://claude.ai/new?q=".concat(encodeURIComponent(t));window.open(n,"_blank","noopener,noreferrer")}}}]); 2//# sourceMappingURL=1062.81c179e2.chunk.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.