@xopcai/xopc 0.0.470 → 0.0.472
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/extensions/telegram/xopc.extension.json +1 -1
- package/dist/gateway/static/root/assets/{apps-page-CXKTWj1s.js → apps-page-BlDivdQ0.js} +1 -1
- package/dist/gateway/static/root/assets/{automations-page-DqrAOReO.js → automations-page-36Dx_eLZ.js} +1 -1
- package/dist/gateway/static/root/assets/{automations-workspace-BYmFhO8E.js → automations-workspace-BY3P8w5G.js} +4 -4
- package/dist/gateway/static/root/assets/capabilities-page-DWslQZCv.js +2 -0
- package/dist/gateway/static/root/assets/{capabilities-settings-panel-DfyND0IO.js → capabilities-settings-panel-Drpf_JGM.js} +2 -2
- package/dist/gateway/static/root/assets/{channels-DwUmMnA1.js → channels-CjDJ2Mmb.js} +1 -1
- package/dist/gateway/static/root/assets/chat-page-D_8adelp.js +72 -0
- package/dist/gateway/static/root/assets/{chat-terminal-dock-Dn7Cm1O4.js → chat-terminal-dock-1VI02yzQ.js} +1 -1
- package/dist/gateway/static/root/assets/{connectors-page-HHGB3r3Q.js → connectors-page-T7W-zTEK.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-debug-page-DIAyDA-a.js → extension-debug-page-DIU2PfhR.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-iframe-host-CCe4R7L7.js → extension-iframe-host-0xdd5xm5.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-message-router-BD0ZamBV.js → extension-message-router-CN1KAjhe.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-page-C09dlV3J.js → extension-page-BiAzQtvI.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-provider-BhluafoX.js → extension-provider-CYVVZ21G.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-settings-page-CB8KLYoG.js → extension-settings-page-B71tjY9p.js} +1 -1
- package/dist/gateway/static/root/assets/{home-page-8KwhWlYt.js → home-page-C79KZbb1.js} +3 -3
- package/dist/gateway/static/root/assets/index-55eQOJhF.css +1 -0
- package/dist/gateway/static/root/assets/{index-CQNwlXpQ.js → index-Jbmr3G0d.js} +8 -8
- package/dist/gateway/static/root/assets/{local-app-workbench-page-DmzgjJNj.js → local-app-workbench-page-TZ7JoORJ.js} +1 -1
- package/dist/gateway/static/root/assets/{note-detail-panel-DeFb2HEC.js → note-detail-panel-DFR9Fc16.js} +3 -3
- package/dist/gateway/static/root/assets/{notes-page-nvqpOeHp.js → notes-page-Y6jTwZhu.js} +1 -1
- package/dist/gateway/static/root/assets/{page-context-capture-button-Cn4zi3Mt.js → page-context-capture-button-zG-782MJ.js} +1 -1
- package/dist/gateway/static/root/assets/{personal-page-HFjWZacf.js → personal-page-CNAaIQe_.js} +1 -1
- package/dist/gateway/static/root/assets/{personal-profile-settings-CNI5Eor6.js → personal-profile-settings-OoFMAniP.js} +1 -1
- package/dist/gateway/static/root/assets/{personal-settings-panel-BcrpYRn9.js → personal-settings-panel-BVv8cYny.js} +1 -1
- package/dist/gateway/static/root/assets/{preview-runtime-RnBDP-Lq.js → preview-runtime-pJGZe5Jx.js} +1 -1
- package/dist/gateway/static/root/assets/{project-detail-page-Dr5_WPRB.js → project-detail-page-CdIhsx42.js} +1 -1
- package/dist/gateway/static/root/assets/{route-preload-D-pdVwIK.js → route-preload-DAyaQF0B.js} +2 -2
- package/dist/gateway/static/root/assets/{routine-panel-rjq-8nZ8.js → routine-panel-BsUWc1HR.js} +2 -2
- package/dist/gateway/static/root/assets/session-manager-DzSlogQc.js +22 -0
- package/dist/gateway/static/root/assets/{settings-page-bCW4rave.js → settings-page-C2DiHQf_.js} +1 -1
- package/dist/gateway/static/root/assets/{share-preview-page-nzWjWhqF.js → share-preview-page-DDd5iT5G.js} +1 -1
- package/dist/gateway/static/root/assets/{shares-settings-LB3SYKFS.js → shares-settings-Dmk9W8r9.js} +1 -1
- package/dist/gateway/static/root/assets/skills-page-DXYcUGzM.js +2 -0
- package/dist/gateway/static/root/assets/space-page-fq1NyJx5.js +2 -0
- package/dist/gateway/static/root/assets/{task-detail-page-gffrDRvW.js → task-detail-page-DE3BWEBP.js} +1 -1
- package/dist/gateway/static/root/assets/{task-header-title-DwtjUOBg.js → task-header-title-BTCuRQKx.js} +1 -1
- package/dist/gateway/static/root/assets/{task-result-evidence-Bmgta9z9.js → task-result-evidence-DCHcXh04.js} +1 -1
- package/dist/gateway/static/root/assets/{use-composer-attachments-sszsCdh5.js → use-composer-attachments-B6CKcx51.js} +1 -1
- package/dist/gateway/static/root/assets/{use-file-preview-expanded-D4b4fDeu.js → use-file-preview-expanded-1ZjXWaYM.js} +1 -1
- package/dist/gateway/static/root/assets/{use-personal-work-C-rw8XVO.js → use-personal-work-CwZNBF3F.js} +1 -1
- package/dist/gateway/static/root/assets/{use-realtime-voice-cugjs8cK.js → use-realtime-voice-D5-XzM7H.js} +1 -1
- package/dist/gateway/static/root/assets/{use-workspace-tree-Crfx5ctU.js → use-workspace-tree-DsuGqCMo.js} +1 -1
- package/dist/gateway/static/root/assets/{voice-settings-BzfNK5Jm.js → voice-settings-lJN2e9mQ.js} +1 -1
- package/dist/gateway/static/root/assets/{workspace-api-g-wCKoQU.js → workspace-api-CFPK3JR6.js} +2 -2
- package/dist/gateway/static/root/assets/{workspace-file-preview-dialog-DxaxVC3q.js → workspace-file-preview-dialog-35uL-ra3.js} +1 -1
- package/dist/gateway/static/root/index.html +17 -17
- package/dist/package.js +1 -1
- package/dist/src/agent/inbound/turn-dispatcher.d.ts +2 -0
- package/dist/src/agent/inbound/turn-dispatcher.js +3 -1
- package/dist/src/agent/service/process-direct-streaming.js +14 -0
- package/dist/src/agent/tools/video-draft-tool.js +1 -1
- package/dist/src/gateway/chat-stream/mapper.js +10 -4
- package/dist/src/gateway/hono/routes/sessions.js +5 -2
- package/dist/src/gateway/hono/routes/video-generation.js +6 -5
- package/dist/src/gateway/service/session-input-coordinator.d.ts +2 -1
- package/dist/src/gateway/service/session-input-coordinator.js +3 -1
- package/dist/src/music-generation/artifact.d.ts +1 -1
- package/dist/src/music-generation/artifact.js +5 -4
- package/dist/src/music-generation/provider.d.ts +1 -0
- package/dist/src/music-generation/providers.js +4 -1
- package/dist/src/music-generation/worker.js +1 -1
- package/dist/src/music-generation/xopc-cloud.js +22 -0
- package/dist/src/session/manager.d.ts +3 -1
- package/dist/src/session/manager.js +2 -2
- package/dist/src/session/store.d.ts +3 -1
- package/dist/src/session/store.js +2 -2
- package/dist/src/session/user-round-delete.d.ts +3 -1
- package/dist/src/session/user-round-delete.js +6 -4
- package/dist/src/storage/sqlite/session-turn-replace-repository.js +6 -1
- package/dist/src/video-generation/artifact.js +1 -1
- package/dist/src/video-generation/drafts.js +3 -3
- package/dist/src/video-generation/settings.d.ts +1 -0
- package/dist/src/video-generation/settings.js +23 -7
- package/package.json +1 -1
- package/dist/gateway/static/root/assets/capabilities-page-XgIRdqCb.js +0 -2
- package/dist/gateway/static/root/assets/chat-page-DfFXhDRv.js +0 -72
- package/dist/gateway/static/root/assets/index-CZUfwwLp.css +0 -1
- package/dist/gateway/static/root/assets/session-manager-BVS3zxRZ.js +0 -22
- package/dist/gateway/static/root/assets/skills-page-CfhEcU8L.js +0 -2
- package/dist/gateway/static/root/assets/space-page-BXyQdUvp.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t}from"./vendor-react-BOUWij0V.js";import{i as n,o as r,p as i,r as a}from"./locale-store-Cit_aHqC.js";import{a as o,r as s}from"./voice-CDlC6XMH.js";import{t as c}from"./session-manager-BVS3zxRZ.js";import{t as l}from"./middleware-Pd0e8Igk.js";import{t as u}from"./composer-notifications-B0IZsy8x.js";var d=e(t(),1),ee=i()(l(e=>({captions:!0,microphoneId:``,setCaptions:t=>e({captions:t}),setMicrophoneId:t=>e({microphoneId:t})}),{name:`xopc-voice-preferences`}));function te(){let e=ee.getState().microphoneId;return{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,...e?{deviceId:{exact:e}}:{}}}function ne(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=(e,n)=>{o||(o=!0,clearTimeout(l),t.removeEventListener(`abort`,c),e===void 0?i(n):a(e))},c=()=>s(t.reason??new DOMException(`Cancelled`,`AbortError`)),l=setTimeout(()=>s(new DOMException(`Voice startup timed out`,`TimeoutError`)),n);e.then(e=>{o?r?.(e):s(void 0,e)},e=>s(e)),t.addEventListener(`abort`,c,{once:!0}),t.aborted&&c()})}function re(e,t,n,r){let i=e.get(t);if(i&&(n<i.revision||i.final&&!r||n===i.revision&&(i.final||!r)))return!1;if(!e.has(t)&&e.size>=256){let t=e.keys().next().value;t!==void 0&&e.delete(t)}return e.set(t,{revision:n,final:r}),!0}var f=32,p=1481592883,ie=3,ae=1,oe=2,m=1,h=64*1024,g=new TextEncoder,_=new TextDecoder(`utf-8`,{fatal:!0});function se(e){let t=g.encode(e.id);if(!t.length||t.length>160||!Number.isInteger(e.connectionEpoch)||e.connectionEpoch<1||e.connectionEpoch>4294967295||!Number.isInteger(e.seq)||e.seq<1||e.seq>4294967295||!Number.isFinite(e.timestampMs)||e.timestampMs<0||e.durationMs!==20||e.flags<0||e.flags>3||!e.audio.length||e.audio.length%2||f+t.length+e.audio.length>h)throw Error(`Invalid voice media frame`);let n=new Uint8Array(f+t.length+e.audio.length),r=new DataView(n.buffer);return r.setUint32(0,p),r.setUint8(4,ie),r.setUint8(5,e.kind),r.setUint8(6,m),r.setUint8(7,e.flags),r.setUint32(8,e.connectionEpoch),r.setUint32(12,e.seq),r.setFloat64(16,e.timestampMs),r.setUint16(24,e.durationMs),r.setUint16(26,t.length),r.setUint32(28,e.audio.length),n.set(t,f),n.set(e.audio,f+t.length),n}function ce(e,t){if(e.length<=f||e.length>h)throw Error(`Invalid voice media frame`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(5),i=n.getUint32(8),a=n.getUint32(12),o=n.getFloat64(16),s=n.getUint16(24),c=n.getUint16(26),l=n.getUint32(28),u=f+c,d=n.getUint8(7);if(n.getUint32(0)!==p||n.getUint8(4)!==ie||r!==t||n.getUint8(6)!==m||d>3||!i||!a||!Number.isFinite(o)||o<0||s!==20||!c||c>160||!l||l%2||u+l!==e.length)throw Error(`Invalid voice media header`);return{kind:r,connectionEpoch:i,id:_.decode(e.subarray(f,u)),seq:a,timestampMs:o,durationMs:s,flags:d,audio:e.slice(u)}}function le(e){let t=ce(e,oe);return{connectionEpoch:t.connectionEpoch,responseId:t.id,seq:t.seq,mediaTimestampMs:t.timestampMs,durationMs:t.durationMs,audio:t.audio}}function ue(e){return se({kind:ae,connectionEpoch:e.connectionEpoch,id:e.utteranceId,seq:e.audioSeq,timestampMs:e.capturedAtMonotonicMs,durationMs:e.durationMs,flags:!!e.start|(e.end?2:0),audio:e.audio})}var de=class{session;eventSeq=0;audioSeq=0;ready=!1;closed=!1;cancelled=new Set;constructor(e){this.session=e}event(e){if(this.closed)throw Error(`Voice session closed`);if(e.sessionId!==this.session.sessionId||e.seq!==this.eventSeq+1)throw Error(`Invalid voice event sequence`);if(this.eventSeq=e.seq,e.type===`session.ready`){if(this.ready||e.payload.connectionEpoch!==this.session.connectionEpoch||e.payload.purpose!==this.session.purpose||e.payload.inputMode!==this.session.inputMode||e.payload.inputFormat.sampleRate!==this.session.inputFormat.sampleRate||e.payload.mode!==this.session.mode||e.payload.route.engine!==this.session.route.engine)throw Error(`Voice session mismatch`);this.ready=!0}e.type===`response.cancelled`&&this.cancel(e.payload.responseId),e.type===`session.closed`&&(this.ready=!1,this.closed=!0)}audio(e){if(!this.ready||e.connectionEpoch!==this.session.connectionEpoch||e.seq!==this.audioSeq+1)throw Error(`Invalid voice audio sequence`);return this.audioSeq=e.seq,!this.cancelled.has(e.responseId)}cancel(e){if(!this.cancelled.has(e)){if(this.cancelled.size>=1e4)throw Error(`Voice response limit exceeded`);this.cancelled.add(e)}}};function v(e,t){return{protocolVersion:3,messageId:crypto.randomUUID(),type:e,sentAt:Date.now(),payload:t}}function y(e){let t=new URL(n(e));return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.toString()}var fe=class e{socket;session;timingMetrics;receive;heartbeatId;inputRemainder=new Uint8Array;utteranceId=crypto.randomUUID();inputSeq=0;constructor(e,t,n=[]){this.socket=e,this.session=t,this.timingMetrics=n,this.receive=new de(t)}static async preflight(e){return e.purpose===`conversation`&&e.conversationId&&await new c().materialize(e.conversationId,`voice`),(await r(n(`/api/voice/realtime/preflight`),{method:`POST`,signal:e.signal,body:JSON.stringify({purpose:e.purpose,mode:e.mode,naturalBackend:e.naturalBackend,testHiggsVoice:e.testHiggsVoice,conversationId:e.conversationId,supportedProtocolVersions:[3],mediaPreferences:[`websocket-pcm`]})})).timingMetrics??[]}static async connect(t){t.signal?.throwIfAborted();let i=await r(n(`/api/voice/realtime/sessions`),{method:`POST`,signal:t.signal,body:JSON.stringify({purpose:t.purpose,...t.language?{language:t.language}:{},...t.purpose===`conversation`&&t.mode!==`natural`&&t.logicalCallId?{openingGreeting:{logicalCallId:t.logicalCallId,initiation:t.recovery?`recovery`:`user`,supportsOutputReady:!0}}:{},...t.mode?{mode:t.mode}:{},...t.naturalBackend?{naturalBackend:t.naturalBackend}:{},...t.testHiggsVoice?{testHiggsVoice:t.testHiggsVoice}:{},...t.conversationId?{conversationId:t.conversationId}:{},supportedProtocolVersions:[3],mediaPreferences:[`websocket-pcm`]})}),a=s.parse(i.payload);t.signal?.throwIfAborted();let c=new WebSocket(y(a.websocketPath));c.binaryType=`arraybuffer`;let l=new e(c,a,t.timingMetrics);return await new Promise((e,n)=>{let r=!1,i,s=e=>{r||(r=!0,i!==void 0&&window.clearTimeout(i),c.close(),n(e))};i=window.setTimeout(()=>s(Error(`Realtime voice connection timed out`)),15e3);let u=()=>{r?c.close():s(Error(`Realtime voice connection cancelled`))};if(t.signal?.addEventListener(`abort`,u,{once:!0}),c.addEventListener(`close`,()=>t.signal?.removeEventListener(`abort`,u),{once:!0}),t.signal?.aborted){u();return}c.onerror=()=>s(Error(`Realtime voice connection failed`)),c.onclose=e=>{r?t.onClose?.(e.reason):s(Error(e.reason||`Realtime voice connection closed`))},c.onopen=()=>{c.send(JSON.stringify(v(`session.start`,{sessionId:a.sessionId,ticket:a.ticket})))},c.onmessage=n=>{if(typeof n.data!=`string`){try{let e=le(new Uint8Array(n.data));l.receive.audio(e)&&t.onAudio?.(e.audio.slice().buffer,e.responseId)}catch{c.close(4400,`Invalid voice audio frame`)}return}try{let c=o(JSON.parse(n.data));if(l.receive.event(c),t.onEvent(c),c.type===`session.ready`&&!r){if(c.payload.connectionEpoch!==a.connectionEpoch||c.payload.mode!==a.mode)throw Error(`Voice session mismatch`);r=!0,window.clearTimeout(i),l.startHeartbeat(c.payload.heartbeatIntervalMs),e()}else c.type===`session.error`&&!c.payload.recoverable&&s(Error(c.payload.message))}catch(e){r?c.close(4400,`Invalid voice protocol frame`):s(e instanceof Error?e:Error(String(e)))}}}),l}outputReady(){this.session.openingGreeting?.accepted&&this.sendControl(`session.output_ready`,{connectionEpoch:this.session.connectionEpoch})}sendAudio(e){if(!e.byteLength||this.socket.readyState!==WebSocket.OPEN)return;let t=new Uint8Array(e),n=new Uint8Array(this.inputRemainder.byteLength+t.byteLength);n.set(this.inputRemainder),n.set(t,this.inputRemainder.byteLength);let r=0;for(;r+640<=n.byteLength;){let e=ue({connectionEpoch:this.session.connectionEpoch,utteranceId:this.utteranceId,audioSeq:++this.inputSeq,capturedAtMonotonicMs:performance.now(),durationMs:20,...this.inputSeq===1?{start:!0}:{},audio:n.slice(r,r+640)});this.socket.send(e.buffer),r+=640}this.inputRemainder=n.slice(r)}reportMetric(e,t,n){t===`speech_end_to_audio_scheduled`&&!this.timingMetrics.includes(t)||this.sendControl(`session.metric`,{responseId:e,metric:t,durationMs:Math.min(6e5,Math.max(0,n))})}setInputMuted(e){this.sendControl(`input.mute`,{muted:e}),this.inputRemainder=new Uint8Array,e||(this.utteranceId=crypto.randomUUID(),this.inputSeq=0)}commit(){this.sendControl(`input.commit`,{})}cancelResponse(e){this.sendControl(`response.stop_playback`,{responseId:e})}cancelTask(e){this.sendControl(`task.cancel`,{taskId:e})}acknowledgeAudio(e,t){this.sendControl(`response.audio.played`,{responseId:e,playedDurationMs:Math.floor(t/48)})}stop(e=`user_finished`){this.stopHeartbeat(),this.socket.readyState===WebSocket.OPEN?this.sendControl(`session.stop`,{reason:e}):this.socket.close()}sendControl(e,t){this.socket.readyState===WebSocket.OPEN&&(e===`response.stop_playback`&&`responseId`in t&&this.receive.cancel(t.responseId),this.socket.send(JSON.stringify(v(e,t))))}startHeartbeat(e){this.stopHeartbeat(),this.heartbeatId=window.setInterval(()=>this.sendControl(`session.ping`,{}),e),this.socket.addEventListener(`close`,()=>this.stopHeartbeat(),{once:!0})}stopHeartbeat(){this.heartbeatId!==void 0&&(window.clearInterval(this.heartbeatId),this.heartbeatId=void 0)}},b=1.7,pe=class{context=new AudioContext({sampleRate:24e3,latencyHint:`interactive`});output=this.context.createGain();ringbackOutput=this.context.createGain();limiter=this.context.createDynamicsCompressor();sources=new Set;ringbackSources=new Map;ringbackDelay=null;ringbackInterval=null;ringbackActive=!1;nextStartTime=0;hasStartedAudio=!1;confirmedSpeech=!1;tentativeDuckTimer;constructor(){this.output.gain.value=b,this.limiter.threshold.value=-6,this.limiter.knee.value=6,this.limiter.ratio.value=12,this.limiter.attack.value=.003,this.limiter.release.value=.12,this.output.connect(this.limiter),this.limiter.connect(this.context.destination),this.ringbackOutput.gain.value=0,this.ringbackOutput.connect(this.context.destination)}async start(){await this.context.resume()}get hasPendingAudio(){return this.sources.size>0}startRingback(){this.stopRingback(),this.context.state!==`closed`&&(this.ringbackActive=!0,this.ringbackDelay=setTimeout(()=>{this.ringbackDelay=null,!(!this.ringbackActive||this.context.state!==`running`)&&(this.ringbackOutput.gain.cancelScheduledValues(this.context.currentTime),this.ringbackOutput.gain.setValueAtTime(.14,this.context.currentTime),this.playRingbackPulse(),this.ringbackInterval=setInterval(()=>this.playRingbackPulse(),3e3))},500))}playRingbackPulse(){if(!this.ringbackActive||this.context.state!==`running`)return;let e=this.context.currentTime;for(let[t,n]of[392,494].entries()){let r=e+t*.4,i=this.context.createOscillator(),a=this.context.createGain();i.type=`sine`,i.frequency.value=n,a.gain.setValueAtTime(0,r),a.gain.linearRampToValueAtTime(.5,r+.04),a.gain.setValueAtTime(.5,r+.18),a.gain.linearRampToValueAtTime(0,r+.28),i.connect(a),a.connect(this.ringbackOutput),this.ringbackSources.set(i,a),i.onended=()=>{this.ringbackSources.delete(i),i.disconnect(),a.disconnect()},i.start(r),i.stop(r+.29)}}stopRingback(){if(this.ringbackActive=!1,this.ringbackDelay!==null&&clearTimeout(this.ringbackDelay),this.ringbackInterval!==null&&clearInterval(this.ringbackInterval),this.ringbackDelay=null,this.ringbackInterval=null,this.context.state!==`closed`){this.ringbackOutput.gain.cancelScheduledValues(this.context.currentTime),this.ringbackOutput.gain.setTargetAtTime(0,this.context.currentTime,.025);for(let[e,t]of this.ringbackSources){t.gain.cancelScheduledValues(this.context.currentTime),t.gain.setTargetAtTime(0,this.context.currentTime,.02);try{e.stop(this.context.currentTime+.12)}catch{}}}}enqueue(e,t,n=24e3){if(e.byteLength<2||this.context.state===`closed`)return;let r=new DataView(e),i=new Float32Array(Math.floor(e.byteLength/2));for(let e=0;e<i.length;e+=1)i[e]=r.getInt16(e*2,!0)/32768;let a=this.context.createBuffer(1,i.length,n);a.copyToChannel(i,0);let o=this.context.createBufferSource();o.buffer=a,o.connect(this.output);let s=this.hasStartedAudio?.015:.02,c=Math.max(this.context.currentTime+s,this.nextStartTime);return o.start(c),this.hasStartedAudio=!0,this.nextStartTime=c+a.duration,this.sources.add(o),o.onended=()=>{this.sources.delete(o)&&(o.disconnect(),t())},Math.max(0,c-this.context.currentTime)*1e3}duck(e){clearTimeout(this.tentativeDuckTimer),this.tentativeDuckTimer=void 0,this.confirmedSpeech=e,this.setOutputGain(e?.15:1)}duckForVoiceOnset(){this.confirmedSpeech||this.tentativeDuckTimer!==void 0||!this.hasPendingAudio||(this.setOutputGain(.55),this.tentativeDuckTimer=setTimeout(()=>{this.tentativeDuckTimer=void 0,this.setOutputGain(1)},280))}setOutputGain(e){this.context.state!==`closed`&&(this.output.gain.cancelScheduledValues(this.context.currentTime),this.output.gain.setTargetAtTime(b*e,this.context.currentTime,.015))}clear(){for(let e of this.sources){e.onended=null;try{e.stop()}catch{}e.disconnect()}this.sources.clear(),this.nextStartTime=this.context.currentTime,this.hasStartedAudio=!1,this.duck(!1)}async close(){this.stopRingback(),this.clear(),this.output.disconnect(),this.ringbackOutput.disconnect(),this.limiter.disconnect(),this.context.state!==`closed`&&await this.context.close();for(let[e,t]of this.ringbackSources)e.onended=null,e.disconnect(),t.disconnect();this.ringbackSources.clear()}},x=`/assets/pcm-capture-worklet-CpXsv44v.js`,S=16e3;function C(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.min(1,Math.sqrt(t/e.length))}function w(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function me(e,t,n=S){if(t===n)return e;let r=Math.max(1,Math.round(e.length*n/t)),i=new Float32Array(r),a=t/n;for(let t=0;t<r;t+=1){let n=t*a,r=Math.min(e.length-1,Math.floor(n)),o=Math.min(e.length-1,r+1),s=n-r;i[t]=e[r]*(1-s)+e[o]*s}return i}function he(e,t=S){let n=new ArrayBuffer(44+e.length*2),r=new DataView(n),i=(e,t)=>{for(let n=0;n<t.length;n+=1)r.setUint8(e+n,t.charCodeAt(n))};i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t+=1){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}return n}function T(e){let t=new ArrayBuffer(e.length*2),n=new DataView(t);for(let t=0;t<e.length;t+=1){let r=Math.max(-1,Math.min(1,e[t]));n.setInt16(t*2,r<0?r*32768:r*32767,!0)}return t}var ge=class{sourceRate;targetRate;pending=new Float32Array;position=0;constructor(e,t=S){if(this.sourceRate=e,this.targetRate=t,e<=0||t<=0)throw Error(`PCM sample rates must be positive`)}push(e){if(e.length===0)return new ArrayBuffer(0);let t=new Float32Array(this.pending.length+e.length);t.set(this.pending),t.set(e,this.pending.length);let n=this.sourceRate/this.targetRate,r=[];for(;this.position+1<t.length;){let e=Math.floor(this.position),i=this.position-e;r.push(t[e]*(1-i)+t[e+1]*i),this.position+=n}let i=Math.min(t.length-1,Math.floor(this.position));return this.pending=t.slice(i),this.position-=i,T(Float32Array.from(r))}flush(){if(this.pending.length===0)return new ArrayBuffer(0);let e=this.pending[Math.min(this.pending.length-1,Math.floor(this.position))];return this.pending=new Float32Array,this.position=0,T(Float32Array.of(e))}},_e=`xopc-pcm-capture`,E=1e3,D=1e4,ve=class e{context;source;node;mutedOutput;options;sampleRate;paused=!1;accepting=!0;processorFailed=!1;stopPromise;flushResolve;constructor(e,t,n,r,i){this.context=e,this.source=t,this.node=n,this.mutedOutput=r,this.options=i,this.sampleRate=e.sampleRate,this.node.port.onmessage=e=>{if(e.data.type===`flushed`){this.flushResolve?.();return}if(!this.accepting||this.paused)return;let t=new Float32Array(e.data.buffer);if(this.options.onSamples(t),this.options.onAudioLevel){let e=C(t);this.options.onAudioLevel({level:e,speaking:e>=(this.options.speechThreshold??.015)})}},this.node.onprocessorerror=()=>{this.processorFailed=!0,this.flushResolve?.()}}static async start(t,n){if(typeof AudioWorkletNode>`u`)throw Error(`PCM audio recording is not supported in this browser`);let r=new AudioContext,i,a,o=new Promise((e,t)=>{a=setTimeout(()=>{t(new DOMException(`PCM audio capture startup timed out`,`TimeoutError`))},D)});try{await Promise.race([r.audioWorklet.addModule(x),o]);let a=r.createMediaStreamSource(t),s=n.frameDurationMs===void 0?void 0:Math.round(r.sampleRate*n.frameDurationMs/1e3),c=new AudioWorkletNode(r,_e,{processorOptions:{frameSamples:s}}),l=r.createGain();return l.gain.value=0,i=new e(r,a,c,l,n),a.connect(c),c.connect(l),l.connect(r.destination),await Promise.race([r.resume(),o]),i}catch(e){throw i?i.cancel():r.close().catch(()=>void 0),e}finally{clearTimeout(a)}}pause(){this.paused=!0}resume(){this.paused=!1}stop(){return this.stopPromise??=this.finish(),this.stopPromise}cancel(){this.accepting&&(this.accepting=!1,this.flushResolve?.(),this.flushResolve=void 0,this.disconnect(),this.context.close().catch(()=>void 0))}async finish(){this.accepting&&(this.processorFailed||await this.flushWorklet(),this.flushResolve=void 0,this.accepting&&(this.accepting=!1,this.disconnect(),await this.context.close().catch(()=>void 0)))}flushWorklet(){return new Promise(e=>{let t=!1,n=()=>{t||(t=!0,globalThis.clearTimeout(r),e())},r=globalThis.setTimeout(n,E);this.flushResolve=n;try{this.node.port.postMessage(`flush`)}catch{n()}})}disconnect(){this.node.port.onmessage=null,this.node.onprocessorerror=null,this.source.disconnect(),this.node.disconnect(),this.mutedOutput.disconnect()}},ye=class e{capture;chunks;stopped=!1;constructor(e,t){this.capture=e,this.chunks=t}static async start(t,n={}){let r=[],i=await ve.start(t,{...n,onSamples:e=>r.push(e)});return new e(i,r)}async stop(){if(this.stopped)return new Blob([],{type:`audio/wav`});this.stopped=!0,await this.capture.stop();let e=me(w(this.chunks),this.capture.sampleRate);return new Blob([he(e)],{type:`audio/wav`})}cancel(){this.stopped||(this.stopped=!0,this.capture.cancel(),this.chunks.length=0)}};function O(e){return e.includes(`ogg`)?`ogg`:e.includes(`mp4`)||e.includes(`m4a`)?`m4a`:e.includes(`mpeg`)||e.includes(`mp3`)?`mp3`:e.includes(`wav`)?`wav`:`webm`}async function k(e,t,i,a){let o=e.type||t||`audio/webm`,s=e.type?e:new Blob([e],{type:o}),c=new FormData;c.append(`audio`,s,`recording.${O(o)}`),a&&c.append(`expectedProvider`,a);let l=await r(n(`/api/voice/transcriptions`),{method:`POST`,body:c,...i?{signal:i}:{}});if(!l.payload)throw Error(`Missing transcription payload`);return l.payload}async function be(e){let t=await r(n(`/api/status`),{signal:e});if(!t.voice?.dictation)throw Error(`Missing dictation status`);return t.voice.dictation}function A(){}typeof window<`u`&&(window.addEventListener(`voice-config-changed`,A),window.addEventListener(`config-reload`,A));var j=null;function xe(e){return j&&j!==e?!1:(j=e,!0)}function M(e){j===e&&(j=null)}function Se(e){if(!(e instanceof Error))return!1;let t=e.body,n=typeof t?.error==`object`?t.error.code:void 0;return n===`VOICE_DISABLED`||n===`PROVIDER_UNAVAILABLE`}function Ce(e){if(!Number.isFinite(e)||e<0)return`0:00`;let t=Math.floor(e%60);return`${Math.floor(e/60)}:${t.toString().padStart(2,`0`)}`}function we(e){return e===`requesting`||e===`connecting`||e===`starting`}async function Te(){if(!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return null}}function Ee(e){return e instanceof DOMException||e instanceof Error?e.name:``}function De(e,t){if(e===`permission`)return`permission`;if(e===`recorder`)return`recorder`;if(e===`session`)return`session`;let n=Ee(t);return n===`NotAllowedError`||n===`SecurityError`?`permission`:`device`}function Oe(e){let{disabled:t,chat:i,onTranscript:o}=e,[s,c]=(0,d.useState)(`idle`),[l,ee]=(0,d.useState)(!1),f=(0,d.useRef)(null),p=(0,d.useRef)(null),ie=(0,d.useRef)(void 0),[ae,oe]=(0,d.useState)(0),[m,h]=(0,d.useState)(0),[g,_]=(0,d.useState)(``),[se,ce]=(0,d.useState)(``),[le,ue]=(0,d.useState)(``),[de,v]=(0,d.useState)([]),[y,b]=(0,d.useState)(null),[x,S]=(0,d.useState)(`idle`),[C,w]=(0,d.useState)(null),[me,he]=(0,d.useState)(!1),T=(0,d.useRef)(!1),[_e,E]=(0,d.useState)(null),[D,O]=(0,d.useState)(null),[A,j]=(0,d.useState)(!1),[Oe,ke]=(0,d.useState)(null),N=(0,d.useRef)(void 0),P=(0,d.useRef)(null),[Ae,je]=(0,d.useState)(`dictation`),Me=(0,d.useRef)(Symbol(`voice-capture`)),F=(0,d.useRef)(`idle`),I=(0,d.useRef)(0),L=(0,d.useRef)(null),Ne=(0,d.useRef)(null),R=(0,d.useRef)(null),Pe=(0,d.useRef)(void 0),Fe=(0,d.useRef)(void 0),Ie=(0,d.useRef)(void 0),z=(0,d.useRef)(null),Le=(0,d.useRef)(null),Re=(0,d.useRef)(null),B=(0,d.useRef)(new Map),V=(0,d.useRef)(!1),ze=(0,d.useRef)(()=>{}),Be=(0,d.useRef)(new Map),H=(0,d.useRef)(null),U=(0,d.useRef)(new Set),[Ve,He]=(0,d.useState)([]),Ue=(0,d.useRef)(!1),W=(0,d.useRef)(null),We=(0,d.useRef)(!1),G=(0,d.useRef)(new Set),Ge=(0,d.useRef)(0),Ke=(0,d.useRef)(6e5),qe=(0,d.useRef)(null),K=(0,d.useRef)(null),Je=(0,d.useRef)(o);Je.current=o;let Ye=(0,d.useRef)(e.onTestAudioPlayed);Ye.current=e.onTestAudioPlayed;let q=(0,d.useCallback)(e=>{F.current=e,c(e)},[]),J=(0,d.useCallback)(()=>{qe.current!=null&&(clearInterval(qe.current),qe.current=null)},[]),Y=(0,d.useCallback)(()=>{Le.current?.getTracks().forEach(e=>e.stop()),Le.current=null},[]),X=(0,d.useCallback)(()=>{M(Me.current),I.current+=1,P.current?.abort(),P.current=null,J(),K.current!==null&&clearTimeout(K.current),K.current=null,z.current?.stopRingback(),Y(),f.current?.cancel(),f.current=null,p.current=null,ie.current=void 0,ee(!1),L.current?.cancel(),L.current=null,Ne.current=null,R.current=null;let e=z.current;z.current=null,e?.close(),Re.current=null,oe(0),h(0),_(``),ce(``),ue(``),S(`idle`),w(null),v([]),b(null),W.current=null,G.current.clear(),T.current=!1,he(!1),j(!1),Be.current.clear(),B.current.clear(),V.current=!1,H.current=null,U.current.clear(),He([])},[Y,J]),Z=(0,d.useCallback)(()=>{X(),q(`idle`)},[X,q]),Xe=(0,d.useCallback)(()=>{R.current?.stop(`user_finished`),Z(),E(null),O(null),ke(null)},[Z]),Q=(0,d.useCallback)(async e=>{if(V.current)return;V.current=!0;let t=I.current,a=e??[...B.current.values()].join(` `).trim();if(Y(),J(),L.current?.cancel(),L.current=null,q(`transcribing`),!a){u(`warning`,i.voiceTranscribeEmpty),Z();return}let o=a;try{let e=await r(n(`/api/voice/transcriptions/refine`),{method:`POST`,body:JSON.stringify({text:a}),signal:AbortSignal.any([P.current.signal,AbortSignal.timeout(15e3)])});e.payload.text.trim()&&(o=e.payload.text)}catch{if(t!==I.current)return;u(`warning`,i.voiceRefinementFailed)}t===I.current&&(Je.current(o),Z())},[Z,i.voiceRefinementFailed,i.voiceTranscribeEmpty,Y,J,q]),Ze=(0,d.useCallback)(async()=>{if(V.current)return;V.current=!0;let e=I.current;J(),q(`transcribing`);try{let t=f.current;if(!p.current&&t){let n=await t.stop();if(e!==I.current)return;p.current=n}if(f.current=null,Y(),e!==I.current)return;let n=p.current;if(!n)throw Error(i.voiceTranscribeEmpty);let r=await k(n,n.type,AbortSignal.any([P.current.signal,AbortSignal.timeout(9e4)]),ie.current);if(e!==I.current)return;V.current=!1,await Q(r.text.trim())}catch(t){if(e!==I.current)return;Y(),V.current=!1,E(t instanceof Error?t.message:i.voiceTranscribeFailed),O(`session`),q(`error`)}},[Q,i.voiceTranscribeEmpty,i.voiceTranscribeFailed,Y,J,q]),Qe=(0,d.useCallback)(e=>{ke(e);let t=F.current;if(!(t===`idle`||t===`error`||V.current)){if(!N.current){if(t===`transcribing`&&e===`input_committed`){Q();return}J(),Y(),L.current?.cancel(),L.current=null,R.current=null,E(i.voiceTranscribeFailed),q(`error`);return}Z()}},[Q,Z,i.voiceTranscribeFailed,Y,J,q]),$e=(0,d.useCallback)(()=>{J(),qe.current=setInterval(()=>{let e=Re.current;if(e===null)return;let t=performance.now()-e;if(oe(Math.max(0,t/1e3)),t>=Ke.current&&F.current===`recording`){if(!N.current){ze.current();return}ke(`session_limit`),R.current?.stop(`user_finished`),Z()}},200)},[Z,J]),$=(0,d.useCallback)(async(e,n,r,o,s=!1,c)=>{if(t||F.current!==`idle`||e===`conversation`&&!r&&!c)return;if(!xe(Me.current)){E(i.callCaptureBusy),e===`dictation`&&u(`error`,i.callCaptureBusy);return}N.current=r;let l=new AbortController;P.current=l,E(null),O(null),ke(null);let d=++I.current,p=()=>d===I.current;je(e),w(e===`conversation`?`preparing`:null),(!s||!Pe.current)&&(Pe.current=crypto.randomUUID()),Fe.current=n,Ie.current=o,ue(``),q(`connecting`);let ae=performance.now(),m=(e,t,n)=>ne(e,l.signal,t,n),g=`permission`;try{if(e===`conversation`){g=`recorder`;let e=new pe;if(z.current=e,await m(e.start(),1e4),!p()){e.close();return}}g=`session`;let t=e===`dictation`?await m(be(l.signal),2e4):null;if(!p())return;if(t?.mode===`unavailable`){let e=Error(i.voiceSttNotConfigured);throw Object.assign(e,{body:{error:{code:`PROVIDER_UNAVAILABLE`}}}),e}let d=t?.mode===`recorded`,ne=e===`conversation`?{mode:n,...o?{naturalBackend:o}:{},...c?{testHiggsVoice:c}:{},conversationId:r}:{},ae=d?[]:await m(fe.preflight({purpose:e,...ne,signal:l.signal}),2e4),se=!1;if(!p())return;g=`permission`;let le=window.electronAPI?.system,de=await m(Te(),5e3);if(!p()||!we(F.current))return;if(le&&de!==`granted`){q(`requesting`);let e=await m(le.requestMicrophone(),6e4);if(!p())return;let t=window.electronAPI?.platform===`darwin`&&e.status!==`granted`;if(e.status===`denied`||t)throw Error(`Microphone permission denied`)}else!le&&de!==`granted`&&q(`requesting`);if(!p()||!we(F.current))return;q(`starting`),window.dispatchEvent(new Event(`xopc-voice-recording-start`)),g=`media`;let y=await m(navigator.mediaDevices.getUserMedia({audio:te()}),15e3,e=>e.getTracks().forEach(e=>e.stop()));if(!p()||!we(F.current)){y.getTracks().forEach(e=>e.stop());return}if(Le.current=y,d){g=`recorder`;let e=await m(ye.start(y,{onAudioLevel:({level:e})=>{p()&&h(Math.min(1,e*8))}}),15e3,e=>e.cancel());if(!p()){e.cancel();return}f.current=e,ie.current=t.provider,ee(!0),Ke.current=6e5,Re.current=performance.now(),oe(0),q(`recording`),$e();return}e===`conversation`&&(w(`dialing`),z.current?.startRingback(),K.current=setTimeout(()=>{p()&&(z.current?.stopRingback(),w(`slow`),K.current=null)},12e3)),g=`session`,q(`connecting`),B.current.clear();let x=await m(fe.connect({timingMetrics:ae,logicalCallId:Pe.current,recovery:s,language:a(),purpose:e,signal:l.signal,...ne,onEvent:t=>{if(p()&&!((t.type===`input.transcript.delta`||t.type===`input.transcript.final`)&&!re(Be.current,t.payload.utteranceId,t.payload.revision,t.type===`input.transcript.final`))){if(t.type===`input.transcript.delta`&&_(t.payload.text),t.type===`input.transcript.final`){let n=t.payload.text.trim();_(``),ce(n),n&&e===`dictation`&&(B.current.set(t.payload.utteranceId,n),[...B.current.values()].join(` `).length>=2e4&&F.current===`recording`&&ze.current(),ce([...B.current.values()].join(` `)))}if(t.type===`input.speech_started`&&!T.current&&R.current?.session.bargeIn&&H.current&&We.current&&(G.current.size<32&&G.current.add(t.payload.utteranceId),z.current?.duck(!0)),t.type===`input.speech_stopped`&&(W.current=performance.now(),G.current.delete(t.payload.utteranceId)&&G.current.size===0&&z.current?.duck(!1)),t.type===`response.created`){if(H.current){H.current!==t.payload.responseId&&R.current?.cancelResponse(t.payload.responseId);return}H.current=t.payload.responseId,G.current.clear(),z.current?.duck(!1),Ue.current=!1,We.current=!1,Ge.current=0,ue(``),U.current.size||(v([]),b(null)),S(`thinking`)}if(t.type===`task.created`&&(U.current.add(t.payload.taskId),He([...U.current])),t.type===`task.activity`&&U.current.has(t.payload.taskId)){let e={toolCallId:t.payload.toolCallId,toolName:t.payload.toolName,status:t.payload.status};v(t=>[...t.filter(t=>t.toolCallId!==e.toolCallId),e].slice(-8))}if(t.type===`task.done`&&(U.current.delete(t.payload.taskId),He([...U.current]),U.current.size||v([])),t.type===`response.clarification`&&b(t.payload),t.type===`response.text.delta`&&H.current===t.payload.responseId&&(S(`speaking`),ue(e=>e+t.payload.delta)),t.type===`response.audio.started`&&H.current===t.payload.responseId&&S(`speaking`),t.type===`response.done`&&H.current===t.payload.responseId&&(Ue.current=!0,z.current?.hasPendingAudio||(H.current=null,S(`idle`))),t.type===`response.cancelled`&&H.current===t.payload.responseId&&(G.current.clear(),H.current=null,S(`idle`),z.current?.clear()),t.type===`session.error`&&t.payload.recoverable&&t.payload.code===`RESPONSE_FAILED`&&u(`warning`,i.voiceResponseFailed),t.type===`session.error`&&t.payload.recoverable&&t.payload.code===`INPUT_DROPPED`&&u(`warning`,i.voiceInputDropped),t.type===`session.error`&&!t.payload.recoverable){let n=t.payload.code===`PROVIDER_UNAVAILABLE`,r=t.payload.code===`CONTEXT_CHANGED`?i.voiceContextChanged:n?i.voiceSttNotConfigured:t.payload.message;E(r),O(`session`),j(n),e===`dictation`&&u(`error`,r,void 0,n?{href:`/settings/capabilities/models?configure=transcription`}:void 0),R.current?.stop(`surface_closed`),e===`conversation`?X():(J(),Y(),L.current?.cancel(),L.current=null,R.current=null),q(`error`)}}},onAudio:(e,t)=>{if(!p())return;let n=H.current;if(!n||t!==n)return;let r=!We.current,i=W.current;r&&(We.current=!0,W.current!==null&&R.current?.reportMetric(n,`speech_end_to_audio_received`,performance.now()-W.current),W.current=null);let a=z.current?.enqueue(e,()=>{H.current===n&&(Ge.current+=e.byteLength,R.current?.acknowledgeAudio(n,Ge.current),c&&!se&&new Int16Array(e).some(e=>Math.abs(e)>96)&&(se=!0,Ye.current?.()),Ue.current&&!z.current?.hasPendingAudio&&(H.current=null,S(`idle`)))});r&&i!==null&&a!==void 0&&R.current?.reportMetric(n,`speech_end_to_audio_scheduled`,performance.now()-i+a)},onClose:e=>{p()&&Qe(e)}}),2e4,e=>e.stop(`surface_closed`));if(!p()){x.stop(`surface_closed`);return}z.current?.stopRingback(),K.current!==null&&clearTimeout(K.current),K.current=null,R.current=x,Ke.current=x.session.limits.maxSessionMs,g=`recorder`,q(`starting`);let C,me=[],he=e===`conversation`&&y.getAudioTracks()[0]?.getSettings?.().echoCancellation===!0,_e=.005,D=0,k=0,A=!1,xe=0,M=await m(ve.start(y,{frameDurationMs:20,onSamples:e=>{if(!p()||T.current)return;if(!C){me.push(e);return}let t=(Ne.current??C).push(e);t&&x.sendAudio(t)},onAudioLevel:({level:e})=>{if(p()){if(T.current){D=k=0,A=!1;return}if(xe++%2==0&&h(Math.min(1,e*8)),!(!he||!x.session.bargeIn)){if(!H.current||!We.current||!z.current?.hasPendingAudio){e<.02&&(_e+=(e-_e)*.05),D=k=0,A=!1;return}e>=Math.max(.022,_e*3)?(k=0,!A&&++D>=3&&(A=!0,z.current.duckForVoiceOnset())):(D=0,++k>=6&&(A=!1))}}}}),15e3,e=>e.cancel());if(!p()||!we(F.current)){M.cancel(),x.stop(`surface_closed`),y.getTracks().forEach(e=>e.stop());return}if(L.current=M,e===`conversation`&&(await m(z.current.start(),1e4),!p()))return;x.outputReady(),C=new ge(M.sampleRate,x.session.inputFormat.sampleRate),Ne.current=C;for(let e of me)x.sendAudio(C.push(e));Re.current=performance.now(),oe(0),q(`recording`),w(null),$e()}catch(t){if(!p())return;let n=De(g,t);console.error(`[chat:voice] realtime capture start failed`,{stage:g,durationMs:Math.round(performance.now()-ae),kind:n,errorName:Ee(t),errorMessage:t instanceof Error?t.message:String(t)}),R.current?.stop(`surface_closed`),X(),q(n===`session`?`error`:`idle`);let r=n===`session`&&Se(t),a=Ee(t)===`TimeoutError`?g===`session`?i.voiceConnectionTimeout:i.voiceMicrophoneTimeout:n===`permission`?i.voiceMicDenied:n===`device`?i.voiceMicUnavailable:n===`recorder`?i.voiceRecorderFailed:r?i.voiceSttNotConfigured:t instanceof Error?t.message:i.voiceSttNotConfigured;E(a),O(n),j(r),e===`dictation`&&u(`error`,a,void 0,r?{href:`/settings/capabilities/models?configure=transcription`}:void 0)}},[t,Qe,i,X,$e,Y,J,q]),et=(0,d.useCallback)(()=>{if(N.current)return;if(f.current||p.current){Ze();return}if(F.current===`error`&&B.current.size){Q();return}if(F.current!==`recording`)return;q(`transcribing`),J(),Y();let e=L.current,t=I.current;L.current=null,e?.stop().then(()=>{if(t!==I.current)return;let e=Ne.current?.flush();e&&R.current?.sendAudio(e),R.current?.commit()}).catch(()=>{t===I.current&&(u(`error`,i.voiceTranscribeFailed),R.current?.stop(`surface_closed`),X(),q(`error`))})},[Q,Ze,i.voiceTranscribeFailed,X,Y,J,q]);ze.current=et,(0,d.useEffect)(()=>()=>{M(Me.current),I.current+=1,P.current?.abort(),f.current?.cancel(),p.current=null,L.current?.cancel(),R.current?.stop(`surface_closed`),z.current?.close(),K.current!==null&&clearTimeout(K.current),Y(),J()},[Y,J]);let tt=(0,d.useCallback)(()=>{if(F.current===`error`){if(p.current){Ze();return}X(),q(`idle`),$(Ae,Fe.current,N.current,Ie.current,!0)}},[$,Ze,Ae,X,q]),nt=(0,d.useCallback)(()=>$(`dictation`),[$]),rt=(0,d.useCallback)((e,t,n)=>$(`conversation`,t,e,n),[$]),it=(0,d.useCallback)(e=>$(`conversation`,`natural`,void 0,void 0,!1,e),[$]),at=(0,d.useCallback)(()=>{let e=performance.now(),t=H.current;z.current?.clear(),G.current.clear(),H.current=null,S(`idle`),t&&(R.current?.reportMetric(t,`local_stop`,performance.now()-e),R.current?.cancelResponse(t))},[]),ot=(0,d.useCallback)(()=>{let e=!T.current;T.current=e,e&&(G.current.clear(),z.current?.duck(!1)),Le.current?.getAudioTracks().forEach(t=>{t.enabled=!e});let t=L.current,n=R.current;t&&n&&(Ne.current=new ge(t.sampleRate,n.session.inputFormat.sampleRate)),n?.setInputMuted(e),_(``),h(0),z.current?.duck(!1),he(e)},[]);return{phase:s,voiceActive:s!==`idle`,recordedDictation:l,elapsedLabel:Ce(ae),audioLevel:m,partialTranscript:g,finalTranscript:se,responseText:le,activeTaskIds:Ve,cancelTask:e=>{U.current.has(e)&&R.current?.cancelTask(e)},activities:de,clarification:y,dismissClarification:e=>b(t=>t?.requestId===e?null:t),responsePhase:x,callConnectionStage:C,muted:me,error:_e,failureKind:D,settingsRequired:A,endedReason:Oe,mode:Ae,startVoiceInput:nt,startVoiceConversation:rt,startHiggsTest:it,interruptResponse:at,toggleMute:ot,cancelVoiceInput:Xe,confirmVoiceInput:et,retryVoiceInput:tt}}export{ve as a,he as c,fe as d,ee as f,be as i,me as l,xe as n,ge as o,te as p,M as r,C as s,Oe as t,pe as u};
|
|
1
|
+
import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t}from"./vendor-react-BOUWij0V.js";import{i as n,o as r,p as i,r as a}from"./locale-store-Cit_aHqC.js";import{a as o,r as s}from"./voice-CDlC6XMH.js";import{t as c}from"./session-manager-DzSlogQc.js";import{t as l}from"./middleware-Pd0e8Igk.js";import{t as u}from"./composer-notifications-B0IZsy8x.js";var d=e(t(),1),ee=i()(l(e=>({captions:!0,microphoneId:``,setCaptions:t=>e({captions:t}),setMicrophoneId:t=>e({microphoneId:t})}),{name:`xopc-voice-preferences`}));function te(){let e=ee.getState().microphoneId;return{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,...e?{deviceId:{exact:e}}:{}}}function ne(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=(e,n)=>{o||(o=!0,clearTimeout(l),t.removeEventListener(`abort`,c),e===void 0?i(n):a(e))},c=()=>s(t.reason??new DOMException(`Cancelled`,`AbortError`)),l=setTimeout(()=>s(new DOMException(`Voice startup timed out`,`TimeoutError`)),n);e.then(e=>{o?r?.(e):s(void 0,e)},e=>s(e)),t.addEventListener(`abort`,c,{once:!0}),t.aborted&&c()})}function re(e,t,n,r){let i=e.get(t);if(i&&(n<i.revision||i.final&&!r||n===i.revision&&(i.final||!r)))return!1;if(!e.has(t)&&e.size>=256){let t=e.keys().next().value;t!==void 0&&e.delete(t)}return e.set(t,{revision:n,final:r}),!0}var f=32,p=1481592883,ie=3,ae=1,oe=2,m=1,h=64*1024,g=new TextEncoder,_=new TextDecoder(`utf-8`,{fatal:!0});function se(e){let t=g.encode(e.id);if(!t.length||t.length>160||!Number.isInteger(e.connectionEpoch)||e.connectionEpoch<1||e.connectionEpoch>4294967295||!Number.isInteger(e.seq)||e.seq<1||e.seq>4294967295||!Number.isFinite(e.timestampMs)||e.timestampMs<0||e.durationMs!==20||e.flags<0||e.flags>3||!e.audio.length||e.audio.length%2||f+t.length+e.audio.length>h)throw Error(`Invalid voice media frame`);let n=new Uint8Array(f+t.length+e.audio.length),r=new DataView(n.buffer);return r.setUint32(0,p),r.setUint8(4,ie),r.setUint8(5,e.kind),r.setUint8(6,m),r.setUint8(7,e.flags),r.setUint32(8,e.connectionEpoch),r.setUint32(12,e.seq),r.setFloat64(16,e.timestampMs),r.setUint16(24,e.durationMs),r.setUint16(26,t.length),r.setUint32(28,e.audio.length),n.set(t,f),n.set(e.audio,f+t.length),n}function ce(e,t){if(e.length<=f||e.length>h)throw Error(`Invalid voice media frame`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(5),i=n.getUint32(8),a=n.getUint32(12),o=n.getFloat64(16),s=n.getUint16(24),c=n.getUint16(26),l=n.getUint32(28),u=f+c,d=n.getUint8(7);if(n.getUint32(0)!==p||n.getUint8(4)!==ie||r!==t||n.getUint8(6)!==m||d>3||!i||!a||!Number.isFinite(o)||o<0||s!==20||!c||c>160||!l||l%2||u+l!==e.length)throw Error(`Invalid voice media header`);return{kind:r,connectionEpoch:i,id:_.decode(e.subarray(f,u)),seq:a,timestampMs:o,durationMs:s,flags:d,audio:e.slice(u)}}function le(e){let t=ce(e,oe);return{connectionEpoch:t.connectionEpoch,responseId:t.id,seq:t.seq,mediaTimestampMs:t.timestampMs,durationMs:t.durationMs,audio:t.audio}}function ue(e){return se({kind:ae,connectionEpoch:e.connectionEpoch,id:e.utteranceId,seq:e.audioSeq,timestampMs:e.capturedAtMonotonicMs,durationMs:e.durationMs,flags:!!e.start|(e.end?2:0),audio:e.audio})}var de=class{session;eventSeq=0;audioSeq=0;ready=!1;closed=!1;cancelled=new Set;constructor(e){this.session=e}event(e){if(this.closed)throw Error(`Voice session closed`);if(e.sessionId!==this.session.sessionId||e.seq!==this.eventSeq+1)throw Error(`Invalid voice event sequence`);if(this.eventSeq=e.seq,e.type===`session.ready`){if(this.ready||e.payload.connectionEpoch!==this.session.connectionEpoch||e.payload.purpose!==this.session.purpose||e.payload.inputMode!==this.session.inputMode||e.payload.inputFormat.sampleRate!==this.session.inputFormat.sampleRate||e.payload.mode!==this.session.mode||e.payload.route.engine!==this.session.route.engine)throw Error(`Voice session mismatch`);this.ready=!0}e.type===`response.cancelled`&&this.cancel(e.payload.responseId),e.type===`session.closed`&&(this.ready=!1,this.closed=!0)}audio(e){if(!this.ready||e.connectionEpoch!==this.session.connectionEpoch||e.seq!==this.audioSeq+1)throw Error(`Invalid voice audio sequence`);return this.audioSeq=e.seq,!this.cancelled.has(e.responseId)}cancel(e){if(!this.cancelled.has(e)){if(this.cancelled.size>=1e4)throw Error(`Voice response limit exceeded`);this.cancelled.add(e)}}};function v(e,t){return{protocolVersion:3,messageId:crypto.randomUUID(),type:e,sentAt:Date.now(),payload:t}}function y(e){let t=new URL(n(e));return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.toString()}var fe=class e{socket;session;timingMetrics;receive;heartbeatId;inputRemainder=new Uint8Array;utteranceId=crypto.randomUUID();inputSeq=0;constructor(e,t,n=[]){this.socket=e,this.session=t,this.timingMetrics=n,this.receive=new de(t)}static async preflight(e){return e.purpose===`conversation`&&e.conversationId&&await new c().materialize(e.conversationId,`voice`),(await r(n(`/api/voice/realtime/preflight`),{method:`POST`,signal:e.signal,body:JSON.stringify({purpose:e.purpose,mode:e.mode,naturalBackend:e.naturalBackend,testHiggsVoice:e.testHiggsVoice,conversationId:e.conversationId,supportedProtocolVersions:[3],mediaPreferences:[`websocket-pcm`]})})).timingMetrics??[]}static async connect(t){t.signal?.throwIfAborted();let i=await r(n(`/api/voice/realtime/sessions`),{method:`POST`,signal:t.signal,body:JSON.stringify({purpose:t.purpose,...t.language?{language:t.language}:{},...t.purpose===`conversation`&&t.mode!==`natural`&&t.logicalCallId?{openingGreeting:{logicalCallId:t.logicalCallId,initiation:t.recovery?`recovery`:`user`,supportsOutputReady:!0}}:{},...t.mode?{mode:t.mode}:{},...t.naturalBackend?{naturalBackend:t.naturalBackend}:{},...t.testHiggsVoice?{testHiggsVoice:t.testHiggsVoice}:{},...t.conversationId?{conversationId:t.conversationId}:{},supportedProtocolVersions:[3],mediaPreferences:[`websocket-pcm`]})}),a=s.parse(i.payload);t.signal?.throwIfAborted();let c=new WebSocket(y(a.websocketPath));c.binaryType=`arraybuffer`;let l=new e(c,a,t.timingMetrics);return await new Promise((e,n)=>{let r=!1,i,s=e=>{r||(r=!0,i!==void 0&&window.clearTimeout(i),c.close(),n(e))};i=window.setTimeout(()=>s(Error(`Realtime voice connection timed out`)),15e3);let u=()=>{r?c.close():s(Error(`Realtime voice connection cancelled`))};if(t.signal?.addEventListener(`abort`,u,{once:!0}),c.addEventListener(`close`,()=>t.signal?.removeEventListener(`abort`,u),{once:!0}),t.signal?.aborted){u();return}c.onerror=()=>s(Error(`Realtime voice connection failed`)),c.onclose=e=>{r?t.onClose?.(e.reason):s(Error(e.reason||`Realtime voice connection closed`))},c.onopen=()=>{c.send(JSON.stringify(v(`session.start`,{sessionId:a.sessionId,ticket:a.ticket})))},c.onmessage=n=>{if(typeof n.data!=`string`){try{let e=le(new Uint8Array(n.data));l.receive.audio(e)&&t.onAudio?.(e.audio.slice().buffer,e.responseId)}catch{c.close(4400,`Invalid voice audio frame`)}return}try{let c=o(JSON.parse(n.data));if(l.receive.event(c),t.onEvent(c),c.type===`session.ready`&&!r){if(c.payload.connectionEpoch!==a.connectionEpoch||c.payload.mode!==a.mode)throw Error(`Voice session mismatch`);r=!0,window.clearTimeout(i),l.startHeartbeat(c.payload.heartbeatIntervalMs),e()}else c.type===`session.error`&&!c.payload.recoverable&&s(Error(c.payload.message))}catch(e){r?c.close(4400,`Invalid voice protocol frame`):s(e instanceof Error?e:Error(String(e)))}}}),l}outputReady(){this.session.openingGreeting?.accepted&&this.sendControl(`session.output_ready`,{connectionEpoch:this.session.connectionEpoch})}sendAudio(e){if(!e.byteLength||this.socket.readyState!==WebSocket.OPEN)return;let t=new Uint8Array(e),n=new Uint8Array(this.inputRemainder.byteLength+t.byteLength);n.set(this.inputRemainder),n.set(t,this.inputRemainder.byteLength);let r=0;for(;r+640<=n.byteLength;){let e=ue({connectionEpoch:this.session.connectionEpoch,utteranceId:this.utteranceId,audioSeq:++this.inputSeq,capturedAtMonotonicMs:performance.now(),durationMs:20,...this.inputSeq===1?{start:!0}:{},audio:n.slice(r,r+640)});this.socket.send(e.buffer),r+=640}this.inputRemainder=n.slice(r)}reportMetric(e,t,n){t===`speech_end_to_audio_scheduled`&&!this.timingMetrics.includes(t)||this.sendControl(`session.metric`,{responseId:e,metric:t,durationMs:Math.min(6e5,Math.max(0,n))})}setInputMuted(e){this.sendControl(`input.mute`,{muted:e}),this.inputRemainder=new Uint8Array,e||(this.utteranceId=crypto.randomUUID(),this.inputSeq=0)}commit(){this.sendControl(`input.commit`,{})}cancelResponse(e){this.sendControl(`response.stop_playback`,{responseId:e})}cancelTask(e){this.sendControl(`task.cancel`,{taskId:e})}acknowledgeAudio(e,t){this.sendControl(`response.audio.played`,{responseId:e,playedDurationMs:Math.floor(t/48)})}stop(e=`user_finished`){this.stopHeartbeat(),this.socket.readyState===WebSocket.OPEN?this.sendControl(`session.stop`,{reason:e}):this.socket.close()}sendControl(e,t){this.socket.readyState===WebSocket.OPEN&&(e===`response.stop_playback`&&`responseId`in t&&this.receive.cancel(t.responseId),this.socket.send(JSON.stringify(v(e,t))))}startHeartbeat(e){this.stopHeartbeat(),this.heartbeatId=window.setInterval(()=>this.sendControl(`session.ping`,{}),e),this.socket.addEventListener(`close`,()=>this.stopHeartbeat(),{once:!0})}stopHeartbeat(){this.heartbeatId!==void 0&&(window.clearInterval(this.heartbeatId),this.heartbeatId=void 0)}},b=1.7,pe=class{context=new AudioContext({sampleRate:24e3,latencyHint:`interactive`});output=this.context.createGain();ringbackOutput=this.context.createGain();limiter=this.context.createDynamicsCompressor();sources=new Set;ringbackSources=new Map;ringbackDelay=null;ringbackInterval=null;ringbackActive=!1;nextStartTime=0;hasStartedAudio=!1;confirmedSpeech=!1;tentativeDuckTimer;constructor(){this.output.gain.value=b,this.limiter.threshold.value=-6,this.limiter.knee.value=6,this.limiter.ratio.value=12,this.limiter.attack.value=.003,this.limiter.release.value=.12,this.output.connect(this.limiter),this.limiter.connect(this.context.destination),this.ringbackOutput.gain.value=0,this.ringbackOutput.connect(this.context.destination)}async start(){await this.context.resume()}get hasPendingAudio(){return this.sources.size>0}startRingback(){this.stopRingback(),this.context.state!==`closed`&&(this.ringbackActive=!0,this.ringbackDelay=setTimeout(()=>{this.ringbackDelay=null,!(!this.ringbackActive||this.context.state!==`running`)&&(this.ringbackOutput.gain.cancelScheduledValues(this.context.currentTime),this.ringbackOutput.gain.setValueAtTime(.14,this.context.currentTime),this.playRingbackPulse(),this.ringbackInterval=setInterval(()=>this.playRingbackPulse(),3e3))},500))}playRingbackPulse(){if(!this.ringbackActive||this.context.state!==`running`)return;let e=this.context.currentTime;for(let[t,n]of[392,494].entries()){let r=e+t*.4,i=this.context.createOscillator(),a=this.context.createGain();i.type=`sine`,i.frequency.value=n,a.gain.setValueAtTime(0,r),a.gain.linearRampToValueAtTime(.5,r+.04),a.gain.setValueAtTime(.5,r+.18),a.gain.linearRampToValueAtTime(0,r+.28),i.connect(a),a.connect(this.ringbackOutput),this.ringbackSources.set(i,a),i.onended=()=>{this.ringbackSources.delete(i),i.disconnect(),a.disconnect()},i.start(r),i.stop(r+.29)}}stopRingback(){if(this.ringbackActive=!1,this.ringbackDelay!==null&&clearTimeout(this.ringbackDelay),this.ringbackInterval!==null&&clearInterval(this.ringbackInterval),this.ringbackDelay=null,this.ringbackInterval=null,this.context.state!==`closed`){this.ringbackOutput.gain.cancelScheduledValues(this.context.currentTime),this.ringbackOutput.gain.setTargetAtTime(0,this.context.currentTime,.025);for(let[e,t]of this.ringbackSources){t.gain.cancelScheduledValues(this.context.currentTime),t.gain.setTargetAtTime(0,this.context.currentTime,.02);try{e.stop(this.context.currentTime+.12)}catch{}}}}enqueue(e,t,n=24e3){if(e.byteLength<2||this.context.state===`closed`)return;let r=new DataView(e),i=new Float32Array(Math.floor(e.byteLength/2));for(let e=0;e<i.length;e+=1)i[e]=r.getInt16(e*2,!0)/32768;let a=this.context.createBuffer(1,i.length,n);a.copyToChannel(i,0);let o=this.context.createBufferSource();o.buffer=a,o.connect(this.output);let s=this.hasStartedAudio?.015:.02,c=Math.max(this.context.currentTime+s,this.nextStartTime);return o.start(c),this.hasStartedAudio=!0,this.nextStartTime=c+a.duration,this.sources.add(o),o.onended=()=>{this.sources.delete(o)&&(o.disconnect(),t())},Math.max(0,c-this.context.currentTime)*1e3}duck(e){clearTimeout(this.tentativeDuckTimer),this.tentativeDuckTimer=void 0,this.confirmedSpeech=e,this.setOutputGain(e?.15:1)}duckForVoiceOnset(){this.confirmedSpeech||this.tentativeDuckTimer!==void 0||!this.hasPendingAudio||(this.setOutputGain(.55),this.tentativeDuckTimer=setTimeout(()=>{this.tentativeDuckTimer=void 0,this.setOutputGain(1)},280))}setOutputGain(e){this.context.state!==`closed`&&(this.output.gain.cancelScheduledValues(this.context.currentTime),this.output.gain.setTargetAtTime(b*e,this.context.currentTime,.015))}clear(){for(let e of this.sources){e.onended=null;try{e.stop()}catch{}e.disconnect()}this.sources.clear(),this.nextStartTime=this.context.currentTime,this.hasStartedAudio=!1,this.duck(!1)}async close(){this.stopRingback(),this.clear(),this.output.disconnect(),this.ringbackOutput.disconnect(),this.limiter.disconnect(),this.context.state!==`closed`&&await this.context.close();for(let[e,t]of this.ringbackSources)e.onended=null,e.disconnect(),t.disconnect();this.ringbackSources.clear()}},x=`/assets/pcm-capture-worklet-CpXsv44v.js`,S=16e3;function C(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.min(1,Math.sqrt(t/e.length))}function w(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function me(e,t,n=S){if(t===n)return e;let r=Math.max(1,Math.round(e.length*n/t)),i=new Float32Array(r),a=t/n;for(let t=0;t<r;t+=1){let n=t*a,r=Math.min(e.length-1,Math.floor(n)),o=Math.min(e.length-1,r+1),s=n-r;i[t]=e[r]*(1-s)+e[o]*s}return i}function he(e,t=S){let n=new ArrayBuffer(44+e.length*2),r=new DataView(n),i=(e,t)=>{for(let n=0;n<t.length;n+=1)r.setUint8(e+n,t.charCodeAt(n))};i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t+=1){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}return n}function T(e){let t=new ArrayBuffer(e.length*2),n=new DataView(t);for(let t=0;t<e.length;t+=1){let r=Math.max(-1,Math.min(1,e[t]));n.setInt16(t*2,r<0?r*32768:r*32767,!0)}return t}var ge=class{sourceRate;targetRate;pending=new Float32Array;position=0;constructor(e,t=S){if(this.sourceRate=e,this.targetRate=t,e<=0||t<=0)throw Error(`PCM sample rates must be positive`)}push(e){if(e.length===0)return new ArrayBuffer(0);let t=new Float32Array(this.pending.length+e.length);t.set(this.pending),t.set(e,this.pending.length);let n=this.sourceRate/this.targetRate,r=[];for(;this.position+1<t.length;){let e=Math.floor(this.position),i=this.position-e;r.push(t[e]*(1-i)+t[e+1]*i),this.position+=n}let i=Math.min(t.length-1,Math.floor(this.position));return this.pending=t.slice(i),this.position-=i,T(Float32Array.from(r))}flush(){if(this.pending.length===0)return new ArrayBuffer(0);let e=this.pending[Math.min(this.pending.length-1,Math.floor(this.position))];return this.pending=new Float32Array,this.position=0,T(Float32Array.of(e))}},_e=`xopc-pcm-capture`,E=1e3,D=1e4,ve=class e{context;source;node;mutedOutput;options;sampleRate;paused=!1;accepting=!0;processorFailed=!1;stopPromise;flushResolve;constructor(e,t,n,r,i){this.context=e,this.source=t,this.node=n,this.mutedOutput=r,this.options=i,this.sampleRate=e.sampleRate,this.node.port.onmessage=e=>{if(e.data.type===`flushed`){this.flushResolve?.();return}if(!this.accepting||this.paused)return;let t=new Float32Array(e.data.buffer);if(this.options.onSamples(t),this.options.onAudioLevel){let e=C(t);this.options.onAudioLevel({level:e,speaking:e>=(this.options.speechThreshold??.015)})}},this.node.onprocessorerror=()=>{this.processorFailed=!0,this.flushResolve?.()}}static async start(t,n){if(typeof AudioWorkletNode>`u`)throw Error(`PCM audio recording is not supported in this browser`);let r=new AudioContext,i,a,o=new Promise((e,t)=>{a=setTimeout(()=>{t(new DOMException(`PCM audio capture startup timed out`,`TimeoutError`))},D)});try{await Promise.race([r.audioWorklet.addModule(x),o]);let a=r.createMediaStreamSource(t),s=n.frameDurationMs===void 0?void 0:Math.round(r.sampleRate*n.frameDurationMs/1e3),c=new AudioWorkletNode(r,_e,{processorOptions:{frameSamples:s}}),l=r.createGain();return l.gain.value=0,i=new e(r,a,c,l,n),a.connect(c),c.connect(l),l.connect(r.destination),await Promise.race([r.resume(),o]),i}catch(e){throw i?i.cancel():r.close().catch(()=>void 0),e}finally{clearTimeout(a)}}pause(){this.paused=!0}resume(){this.paused=!1}stop(){return this.stopPromise??=this.finish(),this.stopPromise}cancel(){this.accepting&&(this.accepting=!1,this.flushResolve?.(),this.flushResolve=void 0,this.disconnect(),this.context.close().catch(()=>void 0))}async finish(){this.accepting&&(this.processorFailed||await this.flushWorklet(),this.flushResolve=void 0,this.accepting&&(this.accepting=!1,this.disconnect(),await this.context.close().catch(()=>void 0)))}flushWorklet(){return new Promise(e=>{let t=!1,n=()=>{t||(t=!0,globalThis.clearTimeout(r),e())},r=globalThis.setTimeout(n,E);this.flushResolve=n;try{this.node.port.postMessage(`flush`)}catch{n()}})}disconnect(){this.node.port.onmessage=null,this.node.onprocessorerror=null,this.source.disconnect(),this.node.disconnect(),this.mutedOutput.disconnect()}},ye=class e{capture;chunks;stopped=!1;constructor(e,t){this.capture=e,this.chunks=t}static async start(t,n={}){let r=[],i=await ve.start(t,{...n,onSamples:e=>r.push(e)});return new e(i,r)}async stop(){if(this.stopped)return new Blob([],{type:`audio/wav`});this.stopped=!0,await this.capture.stop();let e=me(w(this.chunks),this.capture.sampleRate);return new Blob([he(e)],{type:`audio/wav`})}cancel(){this.stopped||(this.stopped=!0,this.capture.cancel(),this.chunks.length=0)}};function O(e){return e.includes(`ogg`)?`ogg`:e.includes(`mp4`)||e.includes(`m4a`)?`m4a`:e.includes(`mpeg`)||e.includes(`mp3`)?`mp3`:e.includes(`wav`)?`wav`:`webm`}async function k(e,t,i,a){let o=e.type||t||`audio/webm`,s=e.type?e:new Blob([e],{type:o}),c=new FormData;c.append(`audio`,s,`recording.${O(o)}`),a&&c.append(`expectedProvider`,a);let l=await r(n(`/api/voice/transcriptions`),{method:`POST`,body:c,...i?{signal:i}:{}});if(!l.payload)throw Error(`Missing transcription payload`);return l.payload}async function be(e){let t=await r(n(`/api/status`),{signal:e});if(!t.voice?.dictation)throw Error(`Missing dictation status`);return t.voice.dictation}function A(){}typeof window<`u`&&(window.addEventListener(`voice-config-changed`,A),window.addEventListener(`config-reload`,A));var j=null;function xe(e){return j&&j!==e?!1:(j=e,!0)}function M(e){j===e&&(j=null)}function Se(e){if(!(e instanceof Error))return!1;let t=e.body,n=typeof t?.error==`object`?t.error.code:void 0;return n===`VOICE_DISABLED`||n===`PROVIDER_UNAVAILABLE`}function Ce(e){if(!Number.isFinite(e)||e<0)return`0:00`;let t=Math.floor(e%60);return`${Math.floor(e/60)}:${t.toString().padStart(2,`0`)}`}function we(e){return e===`requesting`||e===`connecting`||e===`starting`}async function Te(){if(!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return null}}function Ee(e){return e instanceof DOMException||e instanceof Error?e.name:``}function De(e,t){if(e===`permission`)return`permission`;if(e===`recorder`)return`recorder`;if(e===`session`)return`session`;let n=Ee(t);return n===`NotAllowedError`||n===`SecurityError`?`permission`:`device`}function Oe(e){let{disabled:t,chat:i,onTranscript:o}=e,[s,c]=(0,d.useState)(`idle`),[l,ee]=(0,d.useState)(!1),f=(0,d.useRef)(null),p=(0,d.useRef)(null),ie=(0,d.useRef)(void 0),[ae,oe]=(0,d.useState)(0),[m,h]=(0,d.useState)(0),[g,_]=(0,d.useState)(``),[se,ce]=(0,d.useState)(``),[le,ue]=(0,d.useState)(``),[de,v]=(0,d.useState)([]),[y,b]=(0,d.useState)(null),[x,S]=(0,d.useState)(`idle`),[C,w]=(0,d.useState)(null),[me,he]=(0,d.useState)(!1),T=(0,d.useRef)(!1),[_e,E]=(0,d.useState)(null),[D,O]=(0,d.useState)(null),[A,j]=(0,d.useState)(!1),[Oe,ke]=(0,d.useState)(null),N=(0,d.useRef)(void 0),P=(0,d.useRef)(null),[Ae,je]=(0,d.useState)(`dictation`),Me=(0,d.useRef)(Symbol(`voice-capture`)),F=(0,d.useRef)(`idle`),I=(0,d.useRef)(0),L=(0,d.useRef)(null),Ne=(0,d.useRef)(null),R=(0,d.useRef)(null),Pe=(0,d.useRef)(void 0),Fe=(0,d.useRef)(void 0),Ie=(0,d.useRef)(void 0),z=(0,d.useRef)(null),Le=(0,d.useRef)(null),Re=(0,d.useRef)(null),B=(0,d.useRef)(new Map),V=(0,d.useRef)(!1),ze=(0,d.useRef)(()=>{}),Be=(0,d.useRef)(new Map),H=(0,d.useRef)(null),U=(0,d.useRef)(new Set),[Ve,He]=(0,d.useState)([]),Ue=(0,d.useRef)(!1),W=(0,d.useRef)(null),We=(0,d.useRef)(!1),G=(0,d.useRef)(new Set),Ge=(0,d.useRef)(0),Ke=(0,d.useRef)(6e5),qe=(0,d.useRef)(null),K=(0,d.useRef)(null),Je=(0,d.useRef)(o);Je.current=o;let Ye=(0,d.useRef)(e.onTestAudioPlayed);Ye.current=e.onTestAudioPlayed;let q=(0,d.useCallback)(e=>{F.current=e,c(e)},[]),J=(0,d.useCallback)(()=>{qe.current!=null&&(clearInterval(qe.current),qe.current=null)},[]),Y=(0,d.useCallback)(()=>{Le.current?.getTracks().forEach(e=>e.stop()),Le.current=null},[]),X=(0,d.useCallback)(()=>{M(Me.current),I.current+=1,P.current?.abort(),P.current=null,J(),K.current!==null&&clearTimeout(K.current),K.current=null,z.current?.stopRingback(),Y(),f.current?.cancel(),f.current=null,p.current=null,ie.current=void 0,ee(!1),L.current?.cancel(),L.current=null,Ne.current=null,R.current=null;let e=z.current;z.current=null,e?.close(),Re.current=null,oe(0),h(0),_(``),ce(``),ue(``),S(`idle`),w(null),v([]),b(null),W.current=null,G.current.clear(),T.current=!1,he(!1),j(!1),Be.current.clear(),B.current.clear(),V.current=!1,H.current=null,U.current.clear(),He([])},[Y,J]),Z=(0,d.useCallback)(()=>{X(),q(`idle`)},[X,q]),Xe=(0,d.useCallback)(()=>{R.current?.stop(`user_finished`),Z(),E(null),O(null),ke(null)},[Z]),Q=(0,d.useCallback)(async e=>{if(V.current)return;V.current=!0;let t=I.current,a=e??[...B.current.values()].join(` `).trim();if(Y(),J(),L.current?.cancel(),L.current=null,q(`transcribing`),!a){u(`warning`,i.voiceTranscribeEmpty),Z();return}let o=a;try{let e=await r(n(`/api/voice/transcriptions/refine`),{method:`POST`,body:JSON.stringify({text:a}),signal:AbortSignal.any([P.current.signal,AbortSignal.timeout(15e3)])});e.payload.text.trim()&&(o=e.payload.text)}catch{if(t!==I.current)return;u(`warning`,i.voiceRefinementFailed)}t===I.current&&(Je.current(o),Z())},[Z,i.voiceRefinementFailed,i.voiceTranscribeEmpty,Y,J,q]),Ze=(0,d.useCallback)(async()=>{if(V.current)return;V.current=!0;let e=I.current;J(),q(`transcribing`);try{let t=f.current;if(!p.current&&t){let n=await t.stop();if(e!==I.current)return;p.current=n}if(f.current=null,Y(),e!==I.current)return;let n=p.current;if(!n)throw Error(i.voiceTranscribeEmpty);let r=await k(n,n.type,AbortSignal.any([P.current.signal,AbortSignal.timeout(9e4)]),ie.current);if(e!==I.current)return;V.current=!1,await Q(r.text.trim())}catch(t){if(e!==I.current)return;Y(),V.current=!1,E(t instanceof Error?t.message:i.voiceTranscribeFailed),O(`session`),q(`error`)}},[Q,i.voiceTranscribeEmpty,i.voiceTranscribeFailed,Y,J,q]),Qe=(0,d.useCallback)(e=>{ke(e);let t=F.current;if(!(t===`idle`||t===`error`||V.current)){if(!N.current){if(t===`transcribing`&&e===`input_committed`){Q();return}J(),Y(),L.current?.cancel(),L.current=null,R.current=null,E(i.voiceTranscribeFailed),q(`error`);return}Z()}},[Q,Z,i.voiceTranscribeFailed,Y,J,q]),$e=(0,d.useCallback)(()=>{J(),qe.current=setInterval(()=>{let e=Re.current;if(e===null)return;let t=performance.now()-e;if(oe(Math.max(0,t/1e3)),t>=Ke.current&&F.current===`recording`){if(!N.current){ze.current();return}ke(`session_limit`),R.current?.stop(`user_finished`),Z()}},200)},[Z,J]),$=(0,d.useCallback)(async(e,n,r,o,s=!1,c)=>{if(t||F.current!==`idle`||e===`conversation`&&!r&&!c)return;if(!xe(Me.current)){E(i.callCaptureBusy),e===`dictation`&&u(`error`,i.callCaptureBusy);return}N.current=r;let l=new AbortController;P.current=l,E(null),O(null),ke(null);let d=++I.current,p=()=>d===I.current;je(e),w(e===`conversation`?`preparing`:null),(!s||!Pe.current)&&(Pe.current=crypto.randomUUID()),Fe.current=n,Ie.current=o,ue(``),q(`connecting`);let ae=performance.now(),m=(e,t,n)=>ne(e,l.signal,t,n),g=`permission`;try{if(e===`conversation`){g=`recorder`;let e=new pe;if(z.current=e,await m(e.start(),1e4),!p()){e.close();return}}g=`session`;let t=e===`dictation`?await m(be(l.signal),2e4):null;if(!p())return;if(t?.mode===`unavailable`){let e=Error(i.voiceSttNotConfigured);throw Object.assign(e,{body:{error:{code:`PROVIDER_UNAVAILABLE`}}}),e}let d=t?.mode===`recorded`,ne=e===`conversation`?{mode:n,...o?{naturalBackend:o}:{},...c?{testHiggsVoice:c}:{},conversationId:r}:{},ae=d?[]:await m(fe.preflight({purpose:e,...ne,signal:l.signal}),2e4),se=!1;if(!p())return;g=`permission`;let le=window.electronAPI?.system,de=await m(Te(),5e3);if(!p()||!we(F.current))return;if(le&&de!==`granted`){q(`requesting`);let e=await m(le.requestMicrophone(),6e4);if(!p())return;let t=window.electronAPI?.platform===`darwin`&&e.status!==`granted`;if(e.status===`denied`||t)throw Error(`Microphone permission denied`)}else!le&&de!==`granted`&&q(`requesting`);if(!p()||!we(F.current))return;q(`starting`),window.dispatchEvent(new Event(`xopc-voice-recording-start`)),g=`media`;let y=await m(navigator.mediaDevices.getUserMedia({audio:te()}),15e3,e=>e.getTracks().forEach(e=>e.stop()));if(!p()||!we(F.current)){y.getTracks().forEach(e=>e.stop());return}if(Le.current=y,d){g=`recorder`;let e=await m(ye.start(y,{onAudioLevel:({level:e})=>{p()&&h(Math.min(1,e*8))}}),15e3,e=>e.cancel());if(!p()){e.cancel();return}f.current=e,ie.current=t.provider,ee(!0),Ke.current=6e5,Re.current=performance.now(),oe(0),q(`recording`),$e();return}e===`conversation`&&(w(`dialing`),z.current?.startRingback(),K.current=setTimeout(()=>{p()&&(z.current?.stopRingback(),w(`slow`),K.current=null)},12e3)),g=`session`,q(`connecting`),B.current.clear();let x=await m(fe.connect({timingMetrics:ae,logicalCallId:Pe.current,recovery:s,language:a(),purpose:e,signal:l.signal,...ne,onEvent:t=>{if(p()&&!((t.type===`input.transcript.delta`||t.type===`input.transcript.final`)&&!re(Be.current,t.payload.utteranceId,t.payload.revision,t.type===`input.transcript.final`))){if(t.type===`input.transcript.delta`&&_(t.payload.text),t.type===`input.transcript.final`){let n=t.payload.text.trim();_(``),ce(n),n&&e===`dictation`&&(B.current.set(t.payload.utteranceId,n),[...B.current.values()].join(` `).length>=2e4&&F.current===`recording`&&ze.current(),ce([...B.current.values()].join(` `)))}if(t.type===`input.speech_started`&&!T.current&&R.current?.session.bargeIn&&H.current&&We.current&&(G.current.size<32&&G.current.add(t.payload.utteranceId),z.current?.duck(!0)),t.type===`input.speech_stopped`&&(W.current=performance.now(),G.current.delete(t.payload.utteranceId)&&G.current.size===0&&z.current?.duck(!1)),t.type===`response.created`){if(H.current){H.current!==t.payload.responseId&&R.current?.cancelResponse(t.payload.responseId);return}H.current=t.payload.responseId,G.current.clear(),z.current?.duck(!1),Ue.current=!1,We.current=!1,Ge.current=0,ue(``),U.current.size||(v([]),b(null)),S(`thinking`)}if(t.type===`task.created`&&(U.current.add(t.payload.taskId),He([...U.current])),t.type===`task.activity`&&U.current.has(t.payload.taskId)){let e={toolCallId:t.payload.toolCallId,toolName:t.payload.toolName,status:t.payload.status};v(t=>[...t.filter(t=>t.toolCallId!==e.toolCallId),e].slice(-8))}if(t.type===`task.done`&&(U.current.delete(t.payload.taskId),He([...U.current]),U.current.size||v([])),t.type===`response.clarification`&&b(t.payload),t.type===`response.text.delta`&&H.current===t.payload.responseId&&(S(`speaking`),ue(e=>e+t.payload.delta)),t.type===`response.audio.started`&&H.current===t.payload.responseId&&S(`speaking`),t.type===`response.done`&&H.current===t.payload.responseId&&(Ue.current=!0,z.current?.hasPendingAudio||(H.current=null,S(`idle`))),t.type===`response.cancelled`&&H.current===t.payload.responseId&&(G.current.clear(),H.current=null,S(`idle`),z.current?.clear()),t.type===`session.error`&&t.payload.recoverable&&t.payload.code===`RESPONSE_FAILED`&&u(`warning`,i.voiceResponseFailed),t.type===`session.error`&&t.payload.recoverable&&t.payload.code===`INPUT_DROPPED`&&u(`warning`,i.voiceInputDropped),t.type===`session.error`&&!t.payload.recoverable){let n=t.payload.code===`PROVIDER_UNAVAILABLE`,r=t.payload.code===`CONTEXT_CHANGED`?i.voiceContextChanged:n?i.voiceSttNotConfigured:t.payload.message;E(r),O(`session`),j(n),e===`dictation`&&u(`error`,r,void 0,n?{href:`/settings/capabilities/models?configure=transcription`}:void 0),R.current?.stop(`surface_closed`),e===`conversation`?X():(J(),Y(),L.current?.cancel(),L.current=null,R.current=null),q(`error`)}}},onAudio:(e,t)=>{if(!p())return;let n=H.current;if(!n||t!==n)return;let r=!We.current,i=W.current;r&&(We.current=!0,W.current!==null&&R.current?.reportMetric(n,`speech_end_to_audio_received`,performance.now()-W.current),W.current=null);let a=z.current?.enqueue(e,()=>{H.current===n&&(Ge.current+=e.byteLength,R.current?.acknowledgeAudio(n,Ge.current),c&&!se&&new Int16Array(e).some(e=>Math.abs(e)>96)&&(se=!0,Ye.current?.()),Ue.current&&!z.current?.hasPendingAudio&&(H.current=null,S(`idle`)))});r&&i!==null&&a!==void 0&&R.current?.reportMetric(n,`speech_end_to_audio_scheduled`,performance.now()-i+a)},onClose:e=>{p()&&Qe(e)}}),2e4,e=>e.stop(`surface_closed`));if(!p()){x.stop(`surface_closed`);return}z.current?.stopRingback(),K.current!==null&&clearTimeout(K.current),K.current=null,R.current=x,Ke.current=x.session.limits.maxSessionMs,g=`recorder`,q(`starting`);let C,me=[],he=e===`conversation`&&y.getAudioTracks()[0]?.getSettings?.().echoCancellation===!0,_e=.005,D=0,k=0,A=!1,xe=0,M=await m(ve.start(y,{frameDurationMs:20,onSamples:e=>{if(!p()||T.current)return;if(!C){me.push(e);return}let t=(Ne.current??C).push(e);t&&x.sendAudio(t)},onAudioLevel:({level:e})=>{if(p()){if(T.current){D=k=0,A=!1;return}if(xe++%2==0&&h(Math.min(1,e*8)),!(!he||!x.session.bargeIn)){if(!H.current||!We.current||!z.current?.hasPendingAudio){e<.02&&(_e+=(e-_e)*.05),D=k=0,A=!1;return}e>=Math.max(.022,_e*3)?(k=0,!A&&++D>=3&&(A=!0,z.current.duckForVoiceOnset())):(D=0,++k>=6&&(A=!1))}}}}),15e3,e=>e.cancel());if(!p()||!we(F.current)){M.cancel(),x.stop(`surface_closed`),y.getTracks().forEach(e=>e.stop());return}if(L.current=M,e===`conversation`&&(await m(z.current.start(),1e4),!p()))return;x.outputReady(),C=new ge(M.sampleRate,x.session.inputFormat.sampleRate),Ne.current=C;for(let e of me)x.sendAudio(C.push(e));Re.current=performance.now(),oe(0),q(`recording`),w(null),$e()}catch(t){if(!p())return;let n=De(g,t);console.error(`[chat:voice] realtime capture start failed`,{stage:g,durationMs:Math.round(performance.now()-ae),kind:n,errorName:Ee(t),errorMessage:t instanceof Error?t.message:String(t)}),R.current?.stop(`surface_closed`),X(),q(n===`session`?`error`:`idle`);let r=n===`session`&&Se(t),a=Ee(t)===`TimeoutError`?g===`session`?i.voiceConnectionTimeout:i.voiceMicrophoneTimeout:n===`permission`?i.voiceMicDenied:n===`device`?i.voiceMicUnavailable:n===`recorder`?i.voiceRecorderFailed:r?i.voiceSttNotConfigured:t instanceof Error?t.message:i.voiceSttNotConfigured;E(a),O(n),j(r),e===`dictation`&&u(`error`,a,void 0,r?{href:`/settings/capabilities/models?configure=transcription`}:void 0)}},[t,Qe,i,X,$e,Y,J,q]),et=(0,d.useCallback)(()=>{if(N.current)return;if(f.current||p.current){Ze();return}if(F.current===`error`&&B.current.size){Q();return}if(F.current!==`recording`)return;q(`transcribing`),J(),Y();let e=L.current,t=I.current;L.current=null,e?.stop().then(()=>{if(t!==I.current)return;let e=Ne.current?.flush();e&&R.current?.sendAudio(e),R.current?.commit()}).catch(()=>{t===I.current&&(u(`error`,i.voiceTranscribeFailed),R.current?.stop(`surface_closed`),X(),q(`error`))})},[Q,Ze,i.voiceTranscribeFailed,X,Y,J,q]);ze.current=et,(0,d.useEffect)(()=>()=>{M(Me.current),I.current+=1,P.current?.abort(),f.current?.cancel(),p.current=null,L.current?.cancel(),R.current?.stop(`surface_closed`),z.current?.close(),K.current!==null&&clearTimeout(K.current),Y(),J()},[Y,J]);let tt=(0,d.useCallback)(()=>{if(F.current===`error`){if(p.current){Ze();return}X(),q(`idle`),$(Ae,Fe.current,N.current,Ie.current,!0)}},[$,Ze,Ae,X,q]),nt=(0,d.useCallback)(()=>$(`dictation`),[$]),rt=(0,d.useCallback)((e,t,n)=>$(`conversation`,t,e,n),[$]),it=(0,d.useCallback)(e=>$(`conversation`,`natural`,void 0,void 0,!1,e),[$]),at=(0,d.useCallback)(()=>{let e=performance.now(),t=H.current;z.current?.clear(),G.current.clear(),H.current=null,S(`idle`),t&&(R.current?.reportMetric(t,`local_stop`,performance.now()-e),R.current?.cancelResponse(t))},[]),ot=(0,d.useCallback)(()=>{let e=!T.current;T.current=e,e&&(G.current.clear(),z.current?.duck(!1)),Le.current?.getAudioTracks().forEach(t=>{t.enabled=!e});let t=L.current,n=R.current;t&&n&&(Ne.current=new ge(t.sampleRate,n.session.inputFormat.sampleRate)),n?.setInputMuted(e),_(``),h(0),z.current?.duck(!1),he(e)},[]);return{phase:s,voiceActive:s!==`idle`,recordedDictation:l,elapsedLabel:Ce(ae),audioLevel:m,partialTranscript:g,finalTranscript:se,responseText:le,activeTaskIds:Ve,cancelTask:e=>{U.current.has(e)&&R.current?.cancelTask(e)},activities:de,clarification:y,dismissClarification:e=>b(t=>t?.requestId===e?null:t),responsePhase:x,callConnectionStage:C,muted:me,error:_e,failureKind:D,settingsRequired:A,endedReason:Oe,mode:Ae,startVoiceInput:nt,startVoiceConversation:rt,startHiggsTest:it,interruptResponse:at,toggleMute:ot,cancelVoiceInput:Xe,confirmVoiceInput:et,retryVoiceInput:tt}}export{ve as a,he as c,fe as d,ee as f,be as i,me as l,xe as n,ge as o,te as p,M as r,C as s,Oe as t,pe as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t}from"./vendor-react-BOUWij0V.js";import{i as n,o as r,s as i}from"./workspace-api-
|
|
1
|
+
import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t}from"./vendor-react-BOUWij0V.js";import{i as n,o as r,s as i}from"./workspace-api-CFPK3JR6.js";var a=e(t(),1);function o(e){return e.map(e=>({fileId:e.id,name:e.name,path:e.path,isDirectory:e.isDirectory,children:e.isDirectory?[]:void 0}))}function s(e,t,n){return e.map(e=>e.path===t?{...e,children:n}:e.isDirectory&&e.children?.length?{...e,children:s(e.children,t,n)}:e)}function c(e,t,c){let[l,u]=(0,a.useState)([]),[d,f]=(0,a.useState)(null),[p,m]=(0,a.useState)(!1),[h,g]=(0,a.useState)(null),_=(0,a.useRef)(new Set),v=e.trim(),y=t?.trim()??``,b=c?.trim()??``,x=b?``:y,S=!b&&!y?v:``,C=(0,a.useMemo)(()=>{if(b)return{projectId:b};if(x)return{conversationId:x};if(S)return{agentId:S}},[b,x,S]);return{tree:l,rootResource:d,loading:p,error:h,loadRoot:(0,a.useCallback)(async()=>{m(!0),g(null),_.current.clear();try{let[e,t]=await Promise.all([n(``,C),r(C)]);u(o(e.entries)),f(o([t])[0]??null),_.current.add(``)}catch(e){f(null),g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[C]),loadChildren:(0,a.useCallback)(async e=>{if(!_.current.has(e)){_.current.add(e);try{let t=o(await i(e,C));u(n=>s(n,e,t))}catch{_.current.delete(e)}}},[C]),refreshDirectory:(0,a.useCallback)(async e=>{let t=o(await i(e,C));u(e?n=>s(n,e,t):t),_.current.add(e)},[C]),reset:(0,a.useCallback)(()=>{u([]),f(null),g(null),_.current.clear()},[])}}export{c as t};
|
package/dist/gateway/static/root/assets/{voice-settings-BzfNK5Jm.js → voice-settings-lJN2e9mQ.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t,n,t as r}from"./vendor-react-BOUWij0V.js";import{m as i,t as a}from"./chunk-KS7C4IRE-CiwuuyV8.js";import{i as o,l as s,n as c,o as l}from"./locale-store-Cit_aHqC.js";import{t as u}from"./messages-DQveK9sk.js";import{n as d,r as f}from"./popover-select-CLsphyzA.js";import{t as p}from"./secret-input-DsjfQmDn.js";import{t as m}from"./loader-circle-CifKLtgG.js";import{t as h}from"./mic-CuUb7zc-.js";import{t as g}from"./play-kxZvpBg8.js";import{t as _}from"./square-DMK_fB-3.js";import{t as v}from"./volume-2-BSJhAY97.js";import{t as y}from"./cn-0WouolD0.js";import{t as b}from"./skeleton-DzdOeGYz.js";import{a as x,c as S,i as C,m as w,n as T,p as E,u as D}from"./schemas-CCWMleym.js";import{n as O}from"./voice-CDlC6XMH.js";import{i as k}from"./vendor-swr-CdRzEUwF.js";import{n as A,r as j}from"./gateway-config-swr-DVXDJNCI.js";import{t as M}from"./button-Cc4hUNTt.js";import{t as N}from"./open-capability-settings-DQsmJxI7.js";import{a as P,d as F,f as I,i as L,o as R,p as z,t as B,u as V}from"./use-realtime-voice-cugjs8cK.js";import{t as ee}from"./voice-call-context-BM2A4bLz.js";import{a as H,o as te,s as ne}from"./form-field-width-DJw_jULe.js";import{t as re}from"./secret-input-labels-B5Jl5HqK.js";import{n as U}from"./model-sort-_Tz8s_4N.js";import{r as W}from"./model-selector-Cg2kTsE7.js";import{n as G,s as K}from"./playback-coordinator-CWHIf0wr.js";import{t as ie}from"./settings-loading-skeleton-CAoOV17i.js";import{a as q,i as J}from"./capability-navigation-CZbCI5C2.js";import{t as ae}from"./number-input-El7Szeln.js";import{n as oe,t as se}from"./use-autosave-CvjQMyY8.js";import{a as ce,c as le,d as ue,f as de,g as fe,h as pe,i as Y,l as me,n as he,o as ge,p as _e,r as ve,t as ye,u as be}from"./voice-config-api-BLGbUq3v.js";import{t as xe}from"./voice-api-key-field-M7KB_Gl1.js";var Se=E({"zh-CN":w().min(1).optional(),en:w().min(1).optional()}),Ce=T([`transcription`,`transcription.stream`,`speech`,`speech.stream`,`conversation`]),we=E({protocolVersion:S(1),serviceVersion:D().int().positive(),modes:C(Ce),transport:S(`websocket-pcm`),inputFormat:E({encoding:S(`pcm_s16le`),sampleRate:S(16e3),channels:S(1)}),outputFormat:E({encoding:S(`pcm_s16le`),sampleRate:S(24e3),channels:S(1)}),turnDetection:C(S(`server_vad`)),bargeIn:x(),tools:x(),resumable:S(!1),voices:C(E({id:w().min(1),name:w(),displayNames:Se.optional(),languages:C(w()),gender:T([`female`,`male`]).optional(),style:w().optional(),description:w().optional(),modes:C(Ce).optional()})),defaultVoice:w().min(1).optional(),limits:E({maxFrameBytes:D().int().positive().max(65536),maxSessionSeconds:D().int().positive()})});function Te(e,t){return e.modes===void 0||e.modes.includes(t)}var Ee=E({mode:Ce,model:w().min(1).max(200),voice:w().min(1).max(200).optional()}),De=E({revision:w().min(1),catalogVersion:w().nullable(),selections:C(Ee),models:C(E({id:w(),name:w(),displayNames:Se.optional(),voice:we}))}),X=n(),Z=e(t(),1),Q=r();function Oe({disabled:e=!1,modes:t,onPendingChange:n}){let r=c(e=>e.language),i=r===`zh`,[a,s]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>(n?.(a),()=>n?.(!1)),[a,n]);let[u,p]=(0,Z.useState)(``),{data:m,mutate:h,error:g}=k(o(`/api/voice/catalog`),async e=>{let t=await l(e);return De.parse(t.payload)}),_=i?{transcription:`录音转文字`,"transcription.stream":`实时听写 / 语音助手输入`,speech:`消息朗读`,"speech.stream":`语音助手输出`,conversation:`自然语音对话`}:{transcription:`Recorded transcription`,"transcription.stream":`Live dictation / assistant input`,speech:`Message readout`,"speech.stream":`Assistant speech`,conversation:`Natural conversation`},v=async e=>{if(m){s(!0),p(``);try{let t=await l(o(e?`/api/voice/selection`:`/api/voice/catalog/refresh`),{method:e?`PUT`:`POST`,...e?{body:JSON.stringify({revision:m.revision,selection:e})}:{}});await h(De.parse(t.payload),!1),await A()}catch(e){p(e instanceof Error?e.message:String(e)),await h()}finally{s(!1)}}};return(0,Q.jsxs)(`section`,{className:`space-y-4 rounded-xl bg-surface-hover/20 p-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsx)(`h3`,{className:`font-medium`,children:i?`XOPC 托管语音模型`:`XOPC managed voice models`}),(0,Q.jsx)(M,{variant:`secondary`,disabled:a||e||!m,onClick:()=>void v(),children:i?`刷新目录`:`Refresh catalog`})]}),(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:i?`修改在下次调用生效。各设备共用此 Gateway 的配置。`:`Changes apply to the next call and are shared across devices.`}),u||g?(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm text-red-600`,children:u||String(g)}):null,m?(0,Q.jsx)(Q.Fragment,{children:t.map(t=>{let n=m.selections.find(e=>e.mode===t),o=m.models.filter(e=>e.voice.modes.includes(t)).sort(U),s=o.find(e=>e.id===n?.model),c=s?.voice.voices.filter(e=>Te(e,t))??[],l=n?.voice??c.find(e=>e.id===s?.voice.defaultVoice)?.id??c[0]?.id??``;return(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{className:`space-y-1 text-sm`,children:[(0,Q.jsx)(`span`,{children:_[t]}),(0,Q.jsxs)(d,{className:`w-full`,value:n?.model??``,disabled:a||e||!o.length,onChange:e=>void v({mode:t,model:e.target.value}),children:[(0,Q.jsx)(f,{value:``,disabled:!0,children:i?`选择模型`:`Choose model`}),n&&!s?(0,Q.jsxs)(f,{value:n.model,disabled:!0,children:[n.model,` · `,i?`不可用`:`Unavailable`]}):null,o.map(e=>(0,Q.jsx)(f,{value:e.id,children:W(e,r)},e.id))]}),o.length?null:(0,Q.jsx)(`span`,{className:`text-xs text-fg-muted`,children:i?`暂无可用模型`:`No available model`})]}),s&&c.length>0?(0,Q.jsxs)(`label`,{className:`space-y-1 text-sm`,children:[(0,Q.jsx)(`span`,{children:i?`音色`:`Voice`}),(0,Q.jsxs)(d,{className:`w-full`,value:l,disabled:a||e,onChange:e=>void v({mode:t,model:s.id,voice:e.target.value}),children:[n?.voice&&!c.some(e=>e.id===n.voice)?(0,Q.jsxs)(f,{value:n.voice,disabled:!0,children:[n.voice,` · `,i?`当前场景不可用`:`Unavailable for this mode`]}):null,c.map(e=>(0,Q.jsxs)(f,{value:e.id,children:[W(e,r),e.gender?` · ${i?e.gender===`female`?`女声`:`男声`:e.gender}`:``,e.style?` · ${e.style}`:``]},e.id))]}),c.find(e=>e.id===l)?.description?(0,Q.jsx)(`span`,{className:`block text-xs text-fg-muted`,children:c.find(e=>e.id===l)?.description}):null]}):null]},t)})}):(0,Q.jsx)(b,{className:`h-48 w-full`})]})}function ke({v:e}){let t=I(e=>e.microphoneId),n=I(e=>e.setMicrophoneId),[r,i]=(0,Z.useState)([]),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(!1),l=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{l.current=!0;let e=()=>{navigator.mediaDevices?.enumerateDevices().then(e=>{l.current&&i(e.filter(e=>e.kind===`audioinput`))}).catch(()=>{})};return e(),navigator.mediaDevices?.addEventListener(`devicechange`,e),()=>{l.current=!1,navigator.mediaDevices?.removeEventListener(`devicechange`,e)}},[]);let u=async()=>{c(!0),o(``);try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop());let e=await navigator.mediaDevices.enumerateDevices();l.current&&i(e.filter(e=>e.kind===`audioinput`))}catch(e){l.current&&o(e instanceof Error?e.message:String(e))}finally{l.current&&c(!1)}};return(0,Q.jsxs)(`section`,{className:`space-y-4 rounded-xl bg-surface-hover/20 p-4`,children:[(0,Q.jsxs)(`label`,{className:`block space-y-2 text-sm`,children:[(0,Q.jsx)(`span`,{children:e.experience.microphone}),(0,Q.jsxs)(d,{value:t,onChange:e=>n(e.target.value),children:[(0,Q.jsx)(f,{value:``,children:e.experience.systemDevice}),t&&!r.some(e=>e.deviceId===t)?(0,Q.jsx)(f,{value:t,children:e.experience.unavailable}):null,r.filter(e=>e.deviceId&&e.deviceId!=="default").map((t,n)=>(0,Q.jsx)(f,{value:t.deviceId,children:t.label||`${e.experience.microphone} ${n+1}`},t.deviceId))]})]}),(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:e.experience.deviceHint}),(0,Q.jsx)(M,{variant:`secondary`,disabled:s,onClick:()=>void u(),children:e.experience.refreshDevices}),a?(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm text-red-600`,children:a}):null]})}var Ae=(0,Z.createContext)(null);function je(e){let t=(0,X.c)(18),n,r;t[0]===e?(n=t[1],r=t[2]):({to:r,...n}=e,t[0]=e,t[1]=n,t[2]=r);let[o]=i(),s=(0,Z.useContext)(Ae),c,l;t[3]===r?(c=t[4],l=t[5]):(c=new URLSearchParams(r.split(`?`)[1]??``),l=J(c.get(`configure`)),t[3]=r,t[4]=c,t[5]=l);let u=l,d;t[6]!==s||t[7]!==n||t[8]!==c||t[9]!==u?(d=e=>{n.onClick?.(e),!e.defaultPrevented&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&e.button===0&&s&&u&&c.get(`tab`)===`services`&&(e.preventDefault(),s(u))},t[6]=s,t[7]=n,t[8]=c,t[9]=u,t[10]=d):d=t[10];let f;t[11]!==o||t[12]!==r?(f=q(r,o),t[11]=o,t[12]=r,t[13]=f):f=t[13];let p;return t[14]!==n||t[15]!==d||t[16]!==f?(p=(0,Q.jsx)(a,{...n,onClick:d,to:f}),t[14]=n,t[15]=d,t[16]=f,t[17]=p):p=t[17],p}function Me(e){let t=(0,X.c)(19),{zh:n}=e,{data:r,error:i,mutate:a}=k(`voice-dictation-route`,Ne),o,s;t[0]===a?(o=t[1],s=t[2]):(o=()=>{let e=()=>{a()};return window.addEventListener(`voice-config-changed`,e),window.addEventListener(`config-reload`,e),()=>{window.removeEventListener(`voice-config-changed`,e),window.removeEventListener(`config-reload`,e)}},s=[a],t[0]=a,t[1]=o,t[2]=s),(0,Z.useEffect)(o,s);let c=n?`同时用于聊天听写`:`Also used for chat dictation`,l;t[3]===c?l=t[4]:(l=(0,Q.jsx)(`h2`,{className:`font-medium text-fg`,children:c}),t[3]=c,t[4]=l);let u=n?`默认与录音识别共用模型。已有的独立听写设置会保留。`:`Dictation shares this recognition model. Existing separate dictation settings are preserved.`,d;t[5]===u?d=t[6]:(d=(0,Q.jsx)(`p`,{className:`text-fg-muted`,children:u}),t[5]=u,t[6]=d);let f;t[7]!==r||t[8]!==i||t[9]!==n?(f=!r&&!i?(0,Q.jsx)(b,{className:`h-5 w-64 max-w-full`}):(0,Q.jsx)(`p`,{role:i?`alert`:`status`,className:`text-fg-muted`,children:i?n?`暂时无法读取听写状态。`:`Dictation status could not be loaded.`:r?.mode===`recorded`?n?`当前使用 ${r.provider},点击完成后转为文字。`:`Using ${r.provider}. Choose Finish to transcribe.`:r?.mode===`streaming`?n?`当前使用流式识别${r.provider?` · ${r.provider}`:``}。`:`Using streaming recognition${r.provider?` · ${r.provider}`:``}.`:n?`听写未就绪,请检查识别模型或已有的流式配置。`:`Check the recognition model or existing streaming configuration.`}),t[7]=r,t[8]=i,t[9]=n,t[10]=f):f=t[10];let p;t[11]!==r?.mode||t[12]!==n?(p=r?.mode===`recorded`?null:(0,Q.jsx)(je,{className:`inline-block text-accent-fg hover:underline`,to:`/settings/capabilities/models?tab=services&configure=transcription`,children:n?`管理识别服务`:`Manage recognition services`}),t[11]=r?.mode,t[12]=n,t[13]=p):p=t[13];let m;return t[14]!==l||t[15]!==d||t[16]!==f||t[17]!==p?(m=(0,Q.jsxs)(`section`,{className:`space-y-2 rounded-xl border border-edge p-4 text-sm`,children:[l,d,f,p]}),t[14]=l,t[15]=d,t[16]=f,t[17]=p,t[18]=m):m=t[18],m}function Ne(){return L(AbortSignal.timeout(15e3))}function Pe({v:e,canListen:t,canSpeak:n,disabled:r,onVerified:i}){let a=e.setup,o=(0,Z.useContext)(ee)?.active??!1,[s,c]=(0,Z.useState)(`idle`),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(``),p=(0,Z.useRef)(`idle`),v=(0,Z.useRef)(null),y=(0,Z.useRef)(!1),b=e=>{p.current=e,c(e)},x=()=>{v.current?.(),v.current=null};(0,Z.useEffect)(()=>()=>v.current?.(),[]);async function S(e){x(),i?.({input:!1,output:!1}),y.current=!1,u(``),f(``),b(e?`connecting`:`playing`);let t=new AbortController,r,o,s,c,l=()=>{o?.cancel(),r?.getTracks().forEach(e=>e.stop()),s?.stop(`surface_closed`)},d=window.setTimeout(()=>m(a.timeout),6e4);v.current=()=>{t.abort(),window.clearTimeout(d),l(),c?.close()};function m(e){t.signal.aborted||(b(`error`),f(e),x())}async function h(){b(`playing`),l();try{let e=await ue(t.signal);if(t.signal.aborted)return;c?.enqueue(e,()=>{t.signal.aborted||(window.clearTimeout(d),b(`confirm`))})}catch(e){m(e instanceof Error?e.message:a.testFailed)}}try{if(n&&(c=new V,await c.start(),t.signal.throwIfAborted()),!e){await h();return}let d=window.electronAPI?.system;if(d){let e=await d.requestMicrophone();if(t.signal.throwIfAborted(),e.status===`denied`)throw Error(a.microphoneDenied)}if(r=await navigator.mediaDevices.getUserMedia({audio:z()}),t.signal.aborted){l();return}if(s=await F.connect({purpose:`dictation`,signal:t.signal,onEvent:e=>{t.signal.aborted||(e.type===`session.error`&&m(a.testFailed),p.current===`listening`&&(e.type===`input.transcript.delta`&&u(e.payload.text),e.type===`input.transcript.final`&&e.payload.text.trim()&&(u(e.payload.text.trim()),y.current=!0,n?h():(b(`passed`),i?.({input:!0,output:!1}),x()))))},onClose:()=>{(p.current===`listening`||p.current===`connecting`)&&m(a.testFailed)}}),t.signal.aborted){l();return}let f;if(o=await P.start(r,{onSamples:e=>{f&&!t.signal.aborted&&s?.sendAudio(f.push(e))}}),t.signal.aborted){l();return}f=new R(o.sampleRate,s.session.inputFormat.sampleRate),b(`listening`)}catch(e){if(t.signal.aborted){l();return}m(e instanceof Error?e.message:a.testFailed)}}let C=s===`connecting`||s===`listening`||s===`playing`;return(0,Q.jsxs)(`div`,{className:`space-y-3 rounded-xl bg-surface-base/45 p-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsxs)(M,{type:`button`,variant:`primary`,disabled:o||r||!t||C,onClick:()=>void S(!0),children:[C?(0,Q.jsx)(m,{className:`size-4 animate-spin`}):(0,Q.jsx)(h,{className:`size-4`}),n?a.test:a.testInput]}),(0,Q.jsxs)(M,{type:`button`,variant:`secondary`,disabled:o||r||!n||C,onClick:()=>void S(!1),children:[(0,Q.jsx)(g,{className:`size-4`}),e.tts.test.play]}),C?(0,Q.jsxs)(M,{type:`button`,variant:`ghost`,onClick:()=>{x(),b(`idle`)},children:[(0,Q.jsx)(_,{className:`size-4`}),e.tts.test.stop]}):null]}),(0,Q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,className:`space-y-2 text-xs text-fg-muted`,children:[s===`idle`?(0,Q.jsx)(`p`,{children:o?e.experience.endCallBeforeTest:r?a.saveBeforeTest:a.microphoneHint}):null,s===`connecting`?(0,Q.jsx)(`p`,{children:a.connecting}):null,s===`listening`?(0,Q.jsx)(`p`,{children:a.speakNow}):null,l?(0,Q.jsx)(`p`,{className:`rounded-lg bg-surface-base p-3 text-sm text-fg`,children:l}):null,s===`playing`?(0,Q.jsx)(`p`,{children:a.playing}):null,s===`confirm`?(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(`span`,{children:a.heardQuestion}),(0,Q.jsx)(M,{type:`button`,variant:`secondary`,onClick:()=>{x(),i?.({input:y.current,output:!0}),b(`passed`)},children:a.heard}),(0,Q.jsx)(M,{type:`button`,variant:`ghost`,onClick:()=>{x(),b(`error`),f(a.notHeard)},children:a.notHeardButton})]}):null,s===`passed`?(0,Q.jsx)(`p`,{children:y.current?n?a.passed:a.inputPassed:a.outputPassed}):null,s===`error`?(0,Q.jsx)(`p`,{role:`alert`,className:`text-red-600 dark:text-red-400`,children:d}):null]})]})}function Fe(e){let t=(0,X.c)(78),{section:n,v:r,form:i,pending:a,onChange:s}=e,l=c(Be),u=r.setup,p;t[0]===i?p=t[1]:(p=JSON.stringify(i),t[0]=i,t[1]=p);let m=p,h;t[2]===m?h=t[3]:(h={signature:m,input:!1,output:!1},t[2]=m,t[3]=h);let[g,_]=(0,Z.useState)(h);g.signature!==m&&_({signature:m,input:!1,output:!1});let v;t[4]!==a||t[5]!==m?(v=a?null:[`voice-realtime-status`,m],t[4]=a,t[5]=m,t[6]=v):v=t[6];let y;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(y={revalidateOnFocus:!0},t[7]=y):y=t[7];let{data:x,error:S,isLoading:C}=k(v,ve,y),w;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(w=o(`/api/voice/catalog`),t[8]=w):w=t[8];let{data:T}=k(w,ze),E=i.voice.realtime,D=E.tts,O=D?.provider??x?.tts?.provider,A=x?.tts?.model,j;t[9]!==A||t[10]!==O?(j=O&&A?[`realtime-voices`,O,A]:null,t[9]=A,t[10]=O,t[11]=j):j=t[11];let M;t[12]!==A||t[13]!==O?(M=()=>Y(O,A,`realtime`),t[12]=A,t[13]=O,t[14]=M):M=t[14];let N;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(N={revalidateOnFocus:!1},t[15]=N):N=t[15];let{data:P}=k(j,M,N),F;t[16]===P?F=t[17]:(F=P===void 0?[]:P,t[16]=P,t[17]=F);let I=F,L=I,R;t[18]===I?R=t[19]:(R=I.filter(Re),t[18]=I,t[19]=R);let z=R,B=E.defaultEngine===`omni`,V=B?E.omni?.voice??``:D?.voice??``,ee;t[20]!==T?.models||t[21]!==B||t[22]!==z||t[23]!==E.omni||t[24]!==L?(ee=B&&E.omni?.provider===`qwen-token-plan-cn`?[{id:E.omni.voice,name:E.omni.voice}]:B?E.omni?.provider===`xopc-cloud`?T?.models.find(e=>e.id===E.omni?.model)?.voice.voices.filter(Le)??[]:z.length?z:[`Cherry`,`Ethan`,`Serena`,`Chelsie`].map(Ie):L,t[20]=T?.models,t[21]=B,t[22]=z,t[23]=E.omni,t[24]=L,t[25]=ee):ee=t[25];let H=ee,ne=!!(x?.enabled&&x.stt),re=!!(x?.enabled&&x.tts),U;t[26]!==i||t[27]!==s||t[28]!==E?(U=e=>s({...i,voice:{...i.voice,realtime:{...E,...e}}}),t[26]=i,t[27]=s,t[28]=E,t[29]=U):U=t[29];let G=U,K;t[30]!==a||t[31]!==E.enabled||t[32]!==u.disabled||t[33]!==u.needsSetup||t[34]!==u.pending||t[35]!==u.unverified||t[36]!==u.verified||t[37]!==m||t[38]!==g.signature?(K=(e,t)=>E.enabled?a?u.pending:e?t&&g.signature===m?u.verified:u.unverified:u.needsSetup:u.disabled,t[30]=a,t[31]=E.enabled,t[32]=u.disabled,t[33]=u.needsSetup,t[34]=u.pending,t[35]=u.unverified,t[36]=u.verified,t[37]=m,t[38]=g.signature,t[39]=K):K=t[39];let ie=K,q;t[40]!==V||t[41]!==l||t[42]!==B||t[43]!==O||t[44]!==E.bargeIn||t[45]!==E.defaultEngine||t[46]!==E.enabled||t[47]!==E.omni||t[48]!==E.tts||t[49]!==u.bargeIn||t[50]!==u.defaultVoice||t[51]!==u.enable||t[52]!==u.voice||t[53]!==n||t[54]!==D||t[55]!==x?.tts||t[56]!==G||t[57]!==r.experience||t[58]!==r.realtime||t[59]!==H?(q=n===`listening`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`flex items-center justify-between gap-3 text-sm font-medium text-fg`,children:[(0,Q.jsx)(`span`,{children:u.enable}),(0,Q.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-checked":E.enabled,className:`ui-checkbox`,checked:E.enabled,onChange:e=>G({enabled:e.target.checked})})]}),(0,Q.jsxs)(`label`,{className:`block space-y-2 text-sm`,children:[(0,Q.jsx)(`span`,{children:r.experience.defaultMode}),(0,Q.jsxs)(d,{value:E.defaultEngine,className:te,onChange:e=>G({defaultEngine:e.target.value}),children:[(0,Q.jsx)(f,{value:`auto`,children:l===`zh`?`自动选择`:`Automatic`}),(0,Q.jsx)(f,{value:`agent`,children:r.experience.assistant}),(0,Q.jsx)(f,{value:`omni`,children:r.experience.natural})]})]}),(0,Q.jsxs)(`p`,{className:`text-xs text-fg-muted`,children:[E.defaultEngine===`agent`?r.experience.assistantHint:r.experience.naturalHint,` `,r.experience.nextCall]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Q.jsx)(`label`,{htmlFor:`realtime-voice`,className:`text-sm font-medium text-fg`,children:u.voice}),(0,Q.jsxs)(d,{id:`realtime-voice`,className:`${te} w-full sm:w-56`,value:V,disabled:B?!E.omni:!D&&!x?.tts,onChange:e=>{if(B&&E.omni){G({omni:{...E.omni,voice:e.target.value}});return}if(O===`alibaba`||O===`xopc-cloud`){let t={...E.tts,provider:O};e.target.value?t.voice=e.target.value:delete t.voice,G({tts:t})}},children:[B?null:(0,Q.jsx)(f,{value:``,children:u.defaultVoice}),V&&!H.some(e=>e.id===V)?(0,Q.jsx)(f,{value:V,children:V}):null,H.map(e=>(0,Q.jsxs)(f,{value:e.id,children:[W(e,l),`gender`in e&&e.gender?` · ${e.gender===`female`?`女声`:`男声`}`:``,`style`in e&&e.style?` · ${e.style}`:``]},e.id))]}),(()=>{let e=H.find(e=>e.id===V);return e&&`description`in e&&typeof e.description==`string`?(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:e.description}):null})()]}),(0,Q.jsxs)(`label`,{className:`flex items-center justify-between gap-4 text-sm text-fg`,children:[(0,Q.jsxs)(`span`,{children:[u.bargeIn,(0,Q.jsx)(`span`,{className:`mt-1 block text-xs text-fg-muted`,children:r.realtime.bargeInDescription})]}),(0,Q.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-checked":E.bargeIn,checked:E.bargeIn,className:`size-4 accent-accent`,onChange:e=>G({bargeIn:e.target.checked})})]})]}):null,t[40]=V,t[41]=l,t[42]=B,t[43]=O,t[44]=E.bargeIn,t[45]=E.defaultEngine,t[46]=E.enabled,t[47]=E.omni,t[48]=E.tts,t[49]=u.bargeIn,t[50]=u.defaultVoice,t[51]=u.enable,t[52]=u.voice,t[53]=n,t[54]=D,t[55]=x?.tts,t[56]=G,t[57]=r.experience,t[58]=r.realtime,t[59]=H,t[60]=q):q=t[60];let J;t[61]!==ne||t[62]!==re||t[63]!==S||t[64]!==C||t[65]!==a||t[66]!==n||t[67]!==m||t[68]!==x||t[69]!==ie||t[70]!==r||t[71]!==g.input||t[72]!==g.output?(J=n===`diagnostics`?(0,Q.jsxs)(Q.Fragment,{children:[C?(0,Q.jsx)(b,{className:`h-16 w-full`}):(0,Q.jsxs)(`div`,{className:`space-y-2 text-sm`,role:`status`,children:[(0,Q.jsxs)(`p`,{children:[r.experience.dictationReady,` · `,ie(ne,g.input)]}),(0,Q.jsxs)(`p`,{children:[r.experience.agentReady,` · `,ie(ne&&re,g.input&&g.output)]}),(0,Q.jsxs)(`p`,{children:[r.experience.omniReady,` · `,ie(!!(x?.enabled&&x.omni),!1)]})]}),(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:r.experience.configurationOnly}),(0,Q.jsx)(Pe,{v:r,canListen:ne,canSpeak:re,disabled:a||C||!!S,onVerified:e=>_({signature:m,...e})},`${m}:${JSON.stringify(x)}`)]}):null,t[61]=ne,t[62]=re,t[63]=S,t[64]=C,t[65]=a,t[66]=n,t[67]=m,t[68]=x,t[69]=ie,t[70]=r,t[71]=g.input,t[72]=g.output,t[73]=J):J=t[73];let ae;return t[74]!==u.service||t[75]!==q||t[76]!==J?(ae=(0,Q.jsxs)(`section`,{className:`space-y-5 rounded-xl bg-surface-hover/20 p-4 sm:p-5`,"aria-label":u.service,children:[q,J]}),t[74]=u.service,t[75]=q,t[76]=J,t[77]=ae):ae=t[77],ae}function Ie(e){return{id:e,name:e}}function Le(e){return Te(e,`conversation`)}function Re(e){return[`Cherry`,`Ethan`,`Serena`,`Chelsie`].includes(e.id)}async function ze(e){return De.parse((await l(e)).payload)}function Be(e){return e.language}function Ve(e){let t=(0,X.c)(19),{value:n,onChange:r}=e,i=c(He)===`zh`,a=i?`通话指令`:`Conversation instructions`,o;t[0]===a?o=t[1]:(o=(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium text-fg`,children:a}),t[0]=a,t[1]=o);let s=i?`通话会接续当前会话。可在这里调整语气与回答方式。`:`Calls continue the current conversation. Adjust tone and response style here.`,l;t[2]===s?l=t[3]:(l=(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:s}),t[2]=s,t[3]=l);let u=i?`通话指令`:`Conversation instructions`,d;t[4]===u?d=t[5]:(d=(0,Q.jsx)(`span`,{children:u}),t[4]=u,t[5]=d);let f;t[6]!==r||t[7]!==n?(f=e=>r({...n,instructions:e.target.value}),t[6]=r,t[7]=n,t[8]=f):f=t[8];let p;t[9]!==f||t[10]!==n.instructions?(p=(0,Q.jsx)(`textarea`,{className:`w-full rounded-lg border border-edge bg-surface-panel px-3 py-2 text-sm text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent`,rows:3,maxLength:8e3,value:n.instructions,onChange:f}),t[9]=f,t[10]=n.instructions,t[11]=p):p=t[11];let m;t[12]!==d||t[13]!==p?(m=(0,Q.jsxs)(`label`,{className:`block space-y-2 text-sm`,children:[d,p]}),t[12]=d,t[13]=p,t[14]=m):m=t[14];let h;return t[15]!==o||t[16]!==l||t[17]!==m?(h=(0,Q.jsxs)(`details`,{className:`space-y-3 rounded-xl bg-surface-hover/20 p-4`,children:[o,l,m]}),t[15]=o,t[16]=l,t[17]=m,t[18]=h):h=t[18],h}function He(e){return e.language}function Ue({disabled:e=!1}){let t=c(e=>e.language),n=t===`zh`,{data:r,error:i,mutate:s}=k(o(ye),he),[l,m]=(0,Z.useState)(``),[h,g]=(0,Z.useState)(0),_=(0,Z.useId)();(0,Z.useLayoutEffect)(()=>{g(e=>e+1)},[]);let[v,y]=(0,Z.useState)(),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(``),[T,E]=(0,Z.useState)(!1),D=B({disabled:e||x,chat:u(t).chat,onTranscript:()=>{},onTestAudioPlayed:()=>E(!0)}),j=D.phase!==`idle`&&D.phase!==`error`,P=v??r?.voice??`default`,F=r?.credentialSource===`global`;async function I(){try{return await _e()}catch(e){throw e instanceof Error&&`status`in e&&e.status===404?Error(n?`当前 Gateway 版本不支持查看密钥。请更新并重启 Gateway。`:`Update and restart the Gateway to view or copy the saved key.`):e}}async function L(e){if(!(x||j)){S(!0),w(``);try{await s(await pe(e),{revalidate:!1}),`apiKey`in e&&(m(``),g(e=>e+1),E(!1),D.cancelVoiceInput()),await A()}catch(e){w(e instanceof Error?e.message:String(e))}finally{S(!1)}}}return(0,Q.jsxs)(`section`,{className:`@container space-y-3 rounded-xl border border-edge bg-surface-panel p-4`,"aria-label":`Boson AI`,children:[(0,Q.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Boson AI · Higgs Realtime`}),!r&&!i?(0,Q.jsx)(b,{className:`h-24 w-full`}):null,i?(0,Q.jsxs)(`div`,{role:`alert`,className:`text-sm text-danger`,children:[n?`无法读取 Boson 设置。`:`Could not load Boson settings.`,(0,Q.jsx)(M,{variant:`ghost`,onClick:()=>void s(),children:n?`重试`:`Retry`})]}):null,r&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`fieldset`,{disabled:e||x||j,className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1`,children:[(0,Q.jsx)(`label`,{htmlFor:_,className:`text-sm font-medium text-fg`,children:`Boson API Key`}),(0,Q.jsx)(`p`,{role:`status`,className:`text-xs text-fg-muted`,children:r.credentialSource===`env`?n?`已从环境读取 BOSON_API_KEY`:`Using BOSON_API_KEY from the environment`:r.credentialSource?n?`已保存 API Key`:`API key saved`:n?`尚未连接`:`Connection needed`})]}),(0,Q.jsxs)(`div`,{className:`grid items-start gap-2 @min-[32rem]:grid-cols-[minmax(0,1fr)_auto]`,children:[(0,Q.jsx)(p,{id:_,value:l||(F?`••••••••••••`:``),onChange:e=>m(e.replace(/^•+/u,``)),autoComplete:`new-password`,inputClassName:`min-h-11`,labels:{show:n?`显示密钥`:`Show key`,hide:n?`隐藏密钥`:`Hide key`,copy:n?`复制密钥`:`Copy key`,copied:n?`已复制`:`Copied`},reveal:F?I:void 0,allowUnrevealedCopy:!0,loadFailedLabel:n?`无法查看已保存的密钥。`:`Could not load the saved key.`,notInConfigFile:n?`当前没有已保存的密钥。`:`There is no saved key.`},`${F}:${h}`),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(M,{className:`min-h-11`,variant:`secondary`,type:`button`,disabled:!l.trim(),onClick:()=>void L({apiKey:l}),children:x?n?`正在保存…`:`Saving…`:n?`保存密钥`:`Save key`}),F&&(0,Q.jsx)(M,{className:`min-h-11`,type:`button`,variant:`ghost`,onClick:()=>void L({apiKey:null}),children:n?`移除已保存密钥`:`Remove saved key`})]})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-1 text-sm`,children:[(0,Q.jsx)(`span`,{children:n?`Higgs 默认音色`:`Default Higgs voice`}),(0,Q.jsx)(d,{"aria-label":n?`Higgs 默认音色`:`Default Higgs voice`,value:P,onChange:e=>{y(e.target.value),E(!1),D.cancelVoiceInput()},children:O.map(e=>(0,Q.jsx)(f,{value:e,children:e==="default"?n?`模型默认`:`Model default`:e},e))})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(M,{type:`button`,variant:`secondary`,disabled:P===r.voice||!r.credentialSource,onClick:()=>void L({voice:P}),children:n?`保存音色`:`Save voice`}),(0,Q.jsx)(`span`,{className:`text-sm text-fg-muted`,children:r.defaultForNatural?n?`当前全局自然语音模型`:`Current global natural voice model`:n?`在上方选择全局自然语音模型`:`Choose the global natural voice model above`})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-2 border-t border-edge pt-3`,children:[(0,Q.jsx)(`p`,{className:`text-sm text-fg-muted`,children:n?`测试时请说一句中文,听到回复后可以插话。音频由 Boson 处理,测试内容仅在当前面板显示,可能产生用量。`:`Say a sentence and try interrupting the reply. Boson processes the audio. Test content stays in this panel and may incur usage.`}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[j?(0,Q.jsx)(M,{type:`button`,variant:`secondary`,onClick:D.cancelVoiceInput,children:n?`结束测试`:`End test`}):(0,Q.jsx)(M,{type:`button`,variant:`secondary`,disabled:e||x||!r.credentialSource,onClick:()=>{D.cancelVoiceInput(),E(!1),w(``),D.startHiggsTest(P)},children:n?`测试通话`:`Test call`}),r.credentialSource&&!e&&!x&&!j&&(0,Q.jsx)(a,{className:`px-2 text-sm text-accent-fg hover:underline`,to:`/personal`,onClick:N,children:n?`打开 Ada`:`Open Ada`})]}),j&&(0,Q.jsx)(`p`,{role:`status`,className:`text-sm text-fg-muted`,children:D.phase===`recording`?D.responsePhase===`speaking`?n?`正在播放,可以插话`:`Playing reply. You can interrupt.`:n?`麦克风已开启,请说话`:`Microphone on. Say something.`:n?`正在连接测试通话…`:`Connecting test call…`}),T&&(0,Q.jsx)(`p`,{role:`status`,className:`text-sm text-success`,children:n?`测试通过,已播放回复`:`Test passed. Reply played.`}),D.finalTranscript&&(0,Q.jsxs)(`p`,{className:`text-sm text-fg`,children:[n?`转写 · `:`Transcript · `,D.finalTranscript]}),D.responseText&&(0,Q.jsxs)(`p`,{className:`text-sm text-fg`,children:[n?`回复 · `:`Reply · `,D.responseText]})]})]}),(C||D.error)&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm text-danger`,children:C||D.error})]})}var We=H;function Ge(){return y(`w-full rounded-lg border border-edge bg-surface-panel px-3 py-2 text-sm text-fg`,`placeholder:text-fg-subtle`,ne,`dark:border-edge`)}function $(){return y(te,H)}function Ke(e){return!e||e<=0?``:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function qe(e,t){let n=window.atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return URL.createObjectURL(new Blob([r],{type:t}))}function Je(e,t){switch(e){case`xopc-cloud`:return t.setup.hosted;case`openai`:return t.stt.openai;case`alibaba`:return t.stt.alibaba;case`groq`:return`Groq`;default:return e}}function Ye(e,t){switch(e){case`xopc-cloud`:return t.setup.hosted;case`openai`:return t.tts.providerOpenai;case`alibaba`:return t.stt.alibaba;case`edge`:return t.tts.providerEdge;case`minimax`:return`MiniMax`;default:return e}}function Xe(e,t){switch(e){case`edge`:return t.tts.providerHints.edge;case`openai`:return t.tts.providerHints.openai;case`alibaba`:return t.tts.providerHints.alibaba;case`minimax`:return t.tts.providerHints.minimax;default:return t.tts.providerHints.generic}}function Ze(e){return{maskedHelp:e.apiKeyMaskedHelp,copy:e.apiKeyCopy,copied:e.apiKeyCopied,show:e.apiKeyShow,hide:e.apiKeyHide,notInConfigFile:e.apiKeyNotInConfigFile,loadFailed:e.apiKeyRevealFailed}}function Qe(e,t){let n=e[t.key];return typeof n==`string`||typeof n==`number`||typeof n==`boolean`?n:t.defaultValue===void 0?t.type!==`boolean`&&``:t.defaultValue}function $e(e,t){if(e.type===`boolean`)return!!t;if(e.type!==`number`)return t;let n=String(t).trim();if(!n)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function et(e,t){switch(t.type){case`reset`:return{form:null,baseline:null};case`sync`:{let e=structuredClone(t.value);return{form:e,baseline:structuredClone(e)}}case`update`:return{...e,form:t.updater(e.form)};case`saved`:{let n=structuredClone(t.value);return{form:e.form!==null&&JSON.stringify(e.form)!==JSON.stringify(t.value)?e.form:n,baseline:structuredClone(n)}}}}function tt(e){let t=(0,X.c)(10),[n,r]=(0,Z.useState)(0),i;t[0]!==e.capability||t[1]!==e.disabled?(i=e.capability===`conversation`&&(0,Q.jsx)(Ue,{disabled:e.disabled}),t[0]=e.capability,t[1]=e.disabled,t[2]=i):i=t[2];let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=()=>r(nt),t[3]=a):a=t[3];let o;t[4]!==n||t[5]!==e?(o=(0,Q.jsx)(rt,{...e,onReload:a},n),t[4]=n,t[5]=e,t[6]=o):o=t[6];let s;return t[7]!==i||t[8]!==o?(s=(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[i,o]}),t[7]=i,t[8]=o,t[9]=s):s=t[9],s}function nt(e){return e+1}function rt({capability:e,onPendingChange:t,disabled:n=!1,onReload:r}){let i=c(e=>e.language),a=u(i).voiceSettings,l=I(e=>e.captions),p=I(e=>e.setCaptions),m=!!s(e=>e.conversationId),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useReducer)(et,{form:null,baseline:null}),y=_.form,b=_.baseline,[x,S]=(0,Z.useState)(null),C=(0,Z.useRef)(!1),w=(0,Z.useRef)({}),T=(0,Z.useRef)(y);T.current=y;let E=(0,Z.useRef)({parsed:null,models:void 0}),{data:D,error:O,isLoading:A,mutate:N}=j(m),{data:P,error:F,isLoading:L,mutate:R}=k(m?o(`/api/voice/models`):null,ce,{revalidateOnFocus:!1}),{data:z,error:B,isLoading:V}=k(m?o(`/api/voice/providers`):null,ge,{revalidateOnFocus:!1}),{data:ee,error:H,isLoading:te}=k(m?o(`/api/voice/stt-providers`):null,le,{revalidateOnFocus:!1}),ne=(0,Z.useMemo)(()=>z?.providers??[],[z]),re=(0,Z.useMemo)(()=>ee?.providers??[],[ee]),U=(0,Z.useMemo)(()=>D?.payload?.config===void 0?null:me(D.payload.config),[D]),W=(0,Z.useMemo)(()=>!y||!b?!1:JSON.stringify(y)!==JSON.stringify(b),[y,b]);m?U!==null&&P!==void 0&&!C.current&&(E.current.parsed!==U||E.current.models!==P)&&(E.current={parsed:U,models:P},w.current=de(D?.payload?.config),v({type:`sync`,value:U}),S(P)):(E.current.parsed!==null||E.current.models!==void 0)&&(E.current={parsed:null,models:void 0},v({type:`reset`}),S(null),C.current=!1);let G=!!(m&&(U===null||P===void 0||z===void 0||ee===void 0)&&(A||L||V||te)),K=O instanceof Error?O.message:O?String(O):F instanceof Error?F.message:F?String(F):B instanceof Error?B.message:B?String(B):H instanceof Error?H.message:H?String(H):null,q=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>t?{...t,stt:{...t.stt,...e},...e.provider&&e.provider!==`xopc-cloud`?{voice:{...t.voice,realtime:{...t.voice.realtime,stt:void 0}}}:{}}:null})},[]),J=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>{if(!t)return null;let n=t.stt.fallback??{enabled:!1,order:[]};return{...t,stt:{...t.stt,fallback:{...n,...e}}}}})},[]),ae=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>t?{...t,voice:{...t.voice,input:{...t.voice.input,refinement:{...t.voice.input.refinement,...e}}}}:null})},[]),ue=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>t?{...t,voice:{...t.voice,languageMode:e,...e===`auto`?{language:i}:{}}}:null})},[i]),fe=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>t?{...t,voice:{...t.voice,realtime:{...t.voice.realtime,...e}}}:null})},[]),pe=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>t?{...t,tts:{...t.tts,...e}}:null})},[]),Y=se({value:y,dirty:W,onSave:(0,Z.useCallback)(async t=>{try{let n=await be(t,e,w.current[e]);w.current={...w.current,...n},v({type:`saved`,value:t}),C.current=!!(T.current&&JSON.stringify(T.current)!==JSON.stringify(t))}catch(e){throw Error(e instanceof Error?e.message:a.saveError)}},[a.saveError,e])});(0,Z.useEffect)(()=>{t?.(W||Y.status===`saving`||h)},[W,Y.status,h,t]),(0,Z.useEffect)(()=>()=>t?.(!1),[t]);let he=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:()=>e})},[]);if(!m)return(0,Q.jsx)(`div`,{className:`flex flex-col gap-3`,children:(0,Q.jsx)(`p`,{className:`text-sm text-fg-muted`,children:a.needToken})});if(G)return(0,Q.jsx)(ie,{rows:4});if(!y||x===null)return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,Q.jsx)(`p`,{className:`text-sm text-fg-muted`,children:K??a.loadError}),(0,Q.jsx)(M,{type:`button`,variant:`secondary`,onClick:()=>{N(),R()},children:a.retry})]});let _e=y.stt,ve=y.tts,ye=y.voice.input.refinement,xe=Ze(a);return(0,Q.jsxs)(`fieldset`,{disabled:n||h,className:`flex min-w-0 flex-col gap-4`,onBlurCapture:Y.error?void 0:Y.onBlurCapture,children:[(0,Q.jsx)(oe,{status:Y.status,error:Y.error}),Y.error?(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsx)(M,{variant:`secondary`,onClick:Y.retry,children:i===`zh`?`重试保存`:`Retry saving`}),(0,Q.jsx)(M,{variant:`ghost`,onClick:()=>{N().then(()=>r()).catch(()=>{})},children:i===`zh`?`重新加载(放弃未保存更改)`:`Reload and discard unsaved changes`})]}):null,e===`transcription`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Me,{zh:i===`zh`}),(0,Q.jsx)(ot,{managedModel:!0,v:a,apiKeyLabels:xe,stt:_e,models:x,sttProviders:re,updateStt:q,updateSttFallback:J}),(0,Q.jsx)(at,{v:a,voice:y.voice,updateLanguageMode:ue}),(0,Q.jsxs)(`details`,{"data-voice-section":`input-processing`,className:`rounded-xl bg-surface-hover/20 p-4`,children:[(0,Q.jsxs)(`summary`,{className:`cursor-pointer text-sm font-medium text-fg`,children:[a.experience.inputProcessing,` · `,ye.mode===`off`?a.stt.refinementOff:ye.mode===`punctuation`?a.stt.refinementPunctuation:ye.mode===`light`?a.stt.refinementLight:a.setup.advanced]}),(0,Q.jsxs)(`label`,{className:`mt-4 block space-y-2 text-sm`,children:[(0,Q.jsx)(`span`,{children:a.stt.refinement}),(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:a.stt.refinementDesc}),(0,Q.jsxs)(d,{className:$(),value:ye.mode,onChange:e=>ae({mode:e.target.value}),children:[(0,Q.jsx)(f,{value:`off`,children:a.stt.refinementOff}),(0,Q.jsx)(f,{value:`punctuation`,children:a.stt.refinementPunctuation}),(0,Q.jsx)(f,{value:`light`,children:a.stt.refinementLight}),ye.mode===`custom`?(0,Q.jsx)(f,{value:`custom`,children:a.setup.advanced}):null]})]})]}),_e.provider===`xopc-cloud`?(0,Q.jsxs)(`details`,{className:`rounded-xl border border-edge p-4`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:i===`zh`?`实时听写`:`Live dictation`}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Oe,{modes:[`transcription.stream`],disabled:W||Y.status===`saving`,onPendingChange:g})})]}):null]}):e===`speech`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(ct,{managedModel:!0,v:a,apiKeyLabels:xe,tts:ve,models:x,ttsProviders:ne,updateTts:pe}),(0,Q.jsx)(it,{v:a,tts:ve,updateTts:pe})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Fe,{section:`listening`,v:a,form:y,pending:W||Y.status===`saving`||!!Y.error,onChange:he}),y.voice.realtime.defaultEngine===`omni`&&y.voice.realtime.omni?(0,Q.jsx)(Ve,{value:y.voice.realtime.omni,onChange:e=>fe({omni:e})}):null,(0,Q.jsx)(`section`,{className:`rounded-xl bg-surface-hover/20 px-4 py-5 sm:px-5`,children:(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(12rem,18rem)] sm:items-center`,children:[(0,Q.jsx)(`div`,{className:`text-sm font-semibold text-fg`,children:a.experience.pace}),(0,Q.jsxs)(d,{className:$(),value:String(y.voice.realtime.silenceDurationMs),onChange:e=>fe({silenceDurationMs:Number(e.target.value)}),children:[(0,Q.jsx)(f,{value:`800`,children:a.experience.fast}),(0,Q.jsx)(f,{value:`1200`,children:a.experience.standard}),(0,Q.jsx)(f,{value:`2000`,children:a.experience.relaxed}),[800,1200,2e3].includes(y.voice.realtime.silenceDurationMs)?null:(0,Q.jsxs)(f,{value:String(y.voice.realtime.silenceDurationMs),children:[y.voice.realtime.silenceDurationMs,` ms`]})]})]})}),(0,Q.jsxs)(`label`,{className:`flex items-center justify-between text-sm`,children:[a.experience.captions,(0,Q.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-checked":l,className:`ui-checkbox`,checked:l,onChange:e=>p(e.target.checked)})]}),y.voice.realtime.defaultEngine===`agent`&&_e.provider===`xopc-cloud`?(0,Q.jsxs)(`details`,{className:`rounded-xl border border-edge p-4`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:i===`zh`?`语音助手输出`:`Assistant speech output`}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Oe,{modes:[`speech.stream`],disabled:W||Y.status===`saving`,onPendingChange:g})})]}):null,(0,Q.jsxs)(`details`,{className:`rounded-xl border border-edge p-4`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:i===`zh`?`麦克风、扬声器与诊断`:`Microphone, speakers and diagnostics`}),(0,Q.jsxs)(`div`,{className:`mt-4 space-y-4`,children:[(0,Q.jsx)(ke,{v:a}),(0,Q.jsx)(Fe,{section:`diagnostics`,v:a,form:y,pending:W||Y.status===`saving`||!!Y.error,onChange:he})]})]})]})]})}function it(e){let t=(0,X.c)(29),{v:n,tts:r,updateTts:i}=e,a;t[0]===n.setup.readout?a=t[1]:(a=(0,Q.jsx)(`span`,{className:`font-medium`,children:n.setup.readout}),t[0]=n.setup.readout,t[1]=a);let o=n.setup.readout,s;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(s=$(),t[2]=s):s=t[2];let c=r.enabled?r.trigger:`off`,l;t[3]===i?l=t[4]:(l=e=>i({enabled:e.target.value!==`off`,trigger:e.target.value}),t[3]=i,t[4]=l);let u;t[5]===n.tts.triggerOff?u=t[6]:(u=(0,Q.jsx)(f,{value:`off`,children:n.tts.triggerOff}),t[5]=n.tts.triggerOff,t[6]=u);let p;t[7]===n.tts.triggerInbound?p=t[8]:(p=(0,Q.jsx)(f,{value:`inbound`,children:n.tts.triggerInbound}),t[7]=n.tts.triggerInbound,t[8]=p);let m;t[9]===n.tts.triggerAlways?m=t[10]:(m=(0,Q.jsx)(f,{value:`always`,children:n.tts.triggerAlways}),t[9]=n.tts.triggerAlways,t[10]=m);let h;t[11]===n.tts.triggerTagged?h=t[12]:(h=(0,Q.jsx)(f,{value:`tagged`,children:n.tts.triggerTagged}),t[11]=n.tts.triggerTagged,t[12]=h);let g;t[13]!==c||t[14]!==l||t[15]!==u||t[16]!==p||t[17]!==m||t[18]!==h||t[19]!==n.setup.readout?(g=(0,Q.jsxs)(d,{"aria-label":o,className:s,value:c,onChange:l,children:[u,p,m,h]}),t[13]=c,t[14]=l,t[15]=u,t[16]=p,t[17]=m,t[18]=h,t[19]=n.setup.readout,t[20]=g):g=t[20];let _;t[21]!==a||t[22]!==g?(_=(0,Q.jsxs)(`label`,{className:`block space-y-2 text-sm`,children:[a,g]}),t[21]=a,t[22]=g,t[23]=_):_=t[23];let v;t[24]===n.setup.readoutHint?v=t[25]:(v=(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:n.setup.readoutHint}),t[24]=n.setup.readoutHint,t[25]=v);let y;return t[26]!==_||t[27]!==v?(y=(0,Q.jsxs)(`section`,{className:`space-y-2 rounded-xl bg-surface-hover/20 p-4 sm:p-5`,children:[_,v]}),t[26]=_,t[27]=v,t[28]=y):y=t[28],y}function at(e){let t=(0,X.c)(22),{v:n,voice:r,updateLanguageMode:i}=e,a;t[0]===n.language.title?a=t[1]:(a=(0,Q.jsx)(`div`,{className:`text-sm font-semibold text-fg`,children:n.language.title}),t[0]=n.language.title,t[1]=a);let o=r.languageMode===`auto`?n.language.autoDescription:n.language.manualDescription,s;t[2]===o?s=t[3]:(s=(0,Q.jsx)(`p`,{className:`mt-1 text-xs text-fg-muted`,children:o}),t[2]=o,t[3]=s);let c;t[4]!==a||t[5]!==s?(c=(0,Q.jsxs)(`div`,{children:[a,s]}),t[4]=a,t[5]=s,t[6]=c):c=t[6];let l;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(l=$(),t[7]=l):l=t[7];let u;t[8]===i?u=t[9]:(u=e=>i(e.target.value),t[8]=i,t[9]=u);let p;t[10]===n.language.auto?p=t[11]:(p=(0,Q.jsx)(f,{value:`auto`,children:n.language.auto}),t[10]=n.language.auto,t[11]=p);let m;t[12]===n.language.manual?m=t[13]:(m=(0,Q.jsx)(f,{value:`manual`,children:n.language.manual}),t[12]=n.language.manual,t[13]=m);let h;t[14]!==u||t[15]!==p||t[16]!==m||t[17]!==r.languageMode?(h=(0,Q.jsxs)(d,{className:l,value:r.languageMode,onChange:u,children:[p,m]}),t[14]=u,t[15]=p,t[16]=m,t[17]=r.languageMode,t[18]=h):h=t[18];let g;return t[19]!==c||t[20]!==h?(g=(0,Q.jsx)(`section`,{className:`rounded-xl bg-surface-hover/20 px-4 py-5 sm:px-5`,children:(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(12rem,18rem)] sm:items-center`,children:[c,h]})}),t[19]=c,t[20]=h,t[21]=g):g=t[21],g}function ot(e){let t=(0,X.c)(65),{v:n,apiKeyLabels:r,stt:i,models:a,sttProviders:o,updateStt:s,updateSttFallback:c,managedModel:l}=e,u=l!==void 0&&l,p;if(t[0]!==o){let e=new Set;p=[];for(let t of o)e.has(t.id)||(e.add(t.id),p.push(t));t[0]=o,t[1]=p}else p=t[1];let m=p,g,_,v,b;if(t[2]!==a||t[3]!==m||t[4]!==i.provider||t[5]!==i.providers){g=m.find(e=>e.id===i.provider);let e;t[10]!==i.provider||t[11]!==i.providers?(e=i.providers?.[i.provider]??{},t[10]=i.provider,t[11]=i.providers,t[12]=e):e=t[12],v=e,_=a?.stt?.[i.provider]?.length?a.stt[i.provider]:g?.models??[],b=g?.fields.find(st),t[2]=a,t[3]=m,t[4]=i.provider,t[5]=i.providers,t[6]=g,t[7]=_,t[8]=v,t[9]=b}else g=t[6],_=t[7],v=t[8],b=t[9];let x=b,S=typeof v.model==`string`?v.model:void 0,C=S??(typeof x?.defaultValue==`string`?x.defaultValue:_[0]?.id),w;t[13]!==i.provider||t[14]!==i.providers||t[15]!==s?(w=e=>{s({providers:{...i.providers??{},[i.provider]:{...i.providers?.[i.provider]??{},...e}}})},t[13]=i.provider,t[14]=i.providers,t[15]=s,t[16]=w):w=t[16];let T=w,E,D;t[17]!==S||t[18]!==C||t[19]!==u||t[20]!==x||t[21]!==T?(E=()=>{!u&&x&&C&&S!==C&&T({model:C})},D=[u,S,C,x,T],t[17]=S,t[18]=C,t[19]=u,t[20]=x,t[21]=T,t[22]=E,t[23]=D):(E=t[22],D=t[23]),(0,Z.useEffect)(E,D);let O;t[24]===Symbol.for(`react.memo_cache_sentinel`)?(O=(0,Q.jsx)(h,{"aria-hidden":`true`,className:`size-4 text-accent`,strokeWidth:1.75}),t[24]=O):O=t[24];let k;t[25]===n.stt.title?k=t[26]:(k=(0,Q.jsxs)(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-fg`,children:[O,n.stt.title]}),t[25]=n.stt.title,t[26]=k);let A;t[27]===n.stt.enable?A=t[28]:(A=(0,Q.jsx)(`span`,{children:n.stt.enable}),t[27]=n.stt.enable,t[28]=A);let j;t[29]===s?j=t[30]:(j=e=>s({enabled:e.target.checked}),t[29]=s,t[30]=j);let M;t[31]!==i.enabled||t[32]!==j?(M=(0,Q.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-checked":i.enabled,className:`ui-checkbox`,checked:i.enabled,onChange:j}),t[31]=i.enabled,t[32]=j,t[33]=M):M=t[33];let N;t[34]!==M||t[35]!==A?(N=(0,Q.jsxs)(`label`,{className:`flex min-h-10 items-center gap-2 text-xs text-fg-muted`,children:[A,M]}),t[34]=M,t[35]=A,t[36]=N):N=t[36];let P;t[37]!==N||t[38]!==k?(P=(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[k,N]}),t[37]=N,t[38]=k,t[39]=P):P=t[39];let F;t[40]===n.stt.description?F=t[41]:(F=(0,Q.jsx)(`p`,{className:`mt-1 text-xs text-fg-muted`,children:n.stt.description}),t[40]=n.stt.description,t[41]=F);let I;t[42]!==P||t[43]!==F?(I=(0,Q.jsxs)(`div`,{className:`mb-4`,children:[P,F]}),t[42]=P,t[43]=F,t[44]=I):I=t[44];let L;t[45]!==g?.fields||t[46]!==r||t[47]!==C||t[48]!==u||t[49]!==_||t[50]!==m||t[51]!==v||t[52]!==i.enabled||t[53]!==i.fallback?.enabled||t[54]!==i.provider||t[55]!==T||t[56]!==s||t[57]!==c||t[58]!==n?(L=i.enabled?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[u?null:(0,Q.jsxs)(`div`,{className:y(`flex flex-col gap-1.5`,We),children:[(0,Q.jsx)(gt,{children:n.stt.provider}),(0,Q.jsx)(d,{"aria-label":n.stt.provider,className:$(),value:i.provider,onChange:e=>s({provider:e.target.value}),children:m.map(e=>(0,Q.jsxs)(f,{value:e.id,children:[Je(e.id,n),e.configured?``:` *`]},e.id))})]}),(0,Q.jsx)(lt,{managedModel:u,kind:`stt`,providerId:i.provider,fields:g?.fields??[],providerSlice:v,models:_,currentModel:C,apiKeyLabels:r,onPatch:T})]}),i.provider===`alibaba`?(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:n.setup.keyHint}):null,(0,Q.jsxs)(`details`,{className:`rounded-lg border border-edge p-3`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium text-fg`,children:n.stt.fallback}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded-xl bg-surface-hover/50 px-3 py-2.5 dark:bg-surface-hover/35`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`text-sm font-medium text-fg`,children:n.stt.fallback}),(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:n.stt.fallbackDesc})]}),(0,Q.jsx)(`input`,{type:`checkbox`,className:`ui-checkbox`,checked:i.fallback?.enabled??!1,onChange:e=>c({enabled:e.target.checked})})]})]})]}):null,t[45]=g?.fields,t[46]=r,t[47]=C,t[48]=u,t[49]=_,t[50]=m,t[51]=v,t[52]=i.enabled,t[53]=i.fallback?.enabled,t[54]=i.provider,t[55]=T,t[56]=s,t[57]=c,t[58]=n,t[59]=L):L=t[59];let R;t[60]===L?R=t[61]:(R=(0,Q.jsx)(`div`,{className:`space-y-4`,children:L}),t[60]=L,t[61]=R);let z;return t[62]!==I||t[63]!==R?(z=(0,Q.jsxs)(`section`,{className:`rounded-xl bg-surface-hover/20 px-4 py-5 sm:px-5`,children:[I,R]}),t[62]=I,t[63]=R,t[64]=z):z=t[64],z}function st(e){return e.key===`model`}function ct({v:e,apiKeyLabels:t,tts:n,models:r,ttsProviders:i,updateTts:a,managedModel:o=!1}){let[s,c]=(0,Z.useState)(e.tts.test.sampleText),[l,u]=(0,Z.useState)({status:`idle`}),p=(0,Z.useRef)(null),h=(0,Z.useRef)(null),b=(0,Z.useRef)(null),x=(0,Z.useCallback)(()=>{b.current&&(K(b.current),b.current.abort()),b.current=null,p.current?.pause(),p.current=null,h.current&&=(URL.revokeObjectURL(h.current),null)},[]),S=(0,Z.useMemo)(()=>{let e=new Set,t=[];for(let n of i)e.has(n.id)||(e.add(n.id),t.push(n));return t},[i]),C=S.find(e=>e.id===n.provider),w=n.providers?.[n.provider]??{},T=r?.tts?.[n.provider]?.length?r.tts[n.provider]:C?.models??[],E=C?.fields.find(e=>e.key===`model`),D=C?.fields.find(e=>e.key===`voice`),O=typeof w.model==`string`?w.model:void 0,A=O??(typeof E?.defaultValue==`string`?E.defaultValue:T[0]?.id),j=T.find(e=>e.id===A),N=r?.ttsVoices?.[n.provider]?.length?r.ttsVoices[n.provider]:C?.voices??[],{data:P=[]}=k(A?`voice:tts:${n.provider}:${A}`:null,()=>Y(n.provider,A??``),{revalidateOnFocus:!1}),F=P.length>0?P:N,I=typeof w.voice==`string`?w.voice:void 0,L=I??F.find(e=>e.id===j?.tts?.defaultVoice)?.id??(typeof D?.defaultValue==`string`?D.defaultValue:F[0]?.id),R=(C?.fields??[]).filter(e=>(e.key!==`speed`||j?.tts?.speed!==!1)&&(e.key!==`instructions`||j?.tts?.instructions!==!1)),z=(0,Z.useCallback)(e=>{a({providers:{...n.providers??{},[n.provider]:{...n.providers?.[n.provider]??{},...e}}})},[n.provider,n.providers,a]);(0,Z.useEffect)(()=>{if(o)return;let e={};E&&A&&O!==A&&(e.model=A),D&&L&&I!==L&&(e.voice=L),Object.keys(e).length>0&&z(e)},[o,O,I,A,L,E,z,D]),(0,Z.useEffect)(()=>()=>x(),[x]);let B=(0,Z.useCallback)(e=>{a({provider:e}),u({status:`idle`})},[a]),V=(0,Z.useCallback)(async()=>{let t=s.trim();if(!t){u({status:`error`,message:e.tts.test.emptyText});return}x();let r=new AbortController;b.current=r,G(r,()=>{x(),u({status:`idle`})}),u({status:`loading`});try{let i=await fe({text:t,provider:n.provider,providerConfig:w,...A?{model:A}:{},...L?{voice:L}:{}},r.signal);if(r.signal.aborted)return;let a=qe(i.audio,i.mimeType);h.current=a;let o=new Audio(a);p.current=o;let s=[i.provider,i.format,i.latencyMs===void 0?void 0:`${i.latencyMs}ms`,Ke(i.audioSize)].filter(Boolean).join(` · `);o.addEventListener(`ended`,()=>{K(r),r.signal.aborted||u({status:`done`,summary:s})},{once:!0}),o.addEventListener(`error`,()=>{K(r),r.signal.aborted||u({status:`error`,message:e.tts.test.playFailed})},{once:!0}),await o.play(),r.signal.aborted||u({status:`playing`,summary:s})}catch(e){if(r.signal.aborted)return;x(),u({status:`error`,message:e instanceof Error?e.message:String(e)})}},[A,L,w,x,s,n.provider,e.tts.test.emptyText,e.tts.test.playFailed]);return(0,Q.jsxs)(`section`,{className:`rounded-xl bg-surface-hover/20 px-4 py-5 sm:px-5`,children:[(0,Q.jsxs)(`div`,{className:`mb-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-fg`,children:[(0,Q.jsx)(v,{className:`size-4 text-accent`,strokeWidth:1.75}),e.tts.title]}),(0,Q.jsx)(`p`,{className:`mt-1 text-xs text-fg-muted`,children:e.tts.description})]}),(0,Q.jsx)(`div`,{className:`space-y-4`,children:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:o?null:(0,Q.jsxs)(`div`,{className:y(`flex flex-col gap-1.5`,We),children:[(0,Q.jsx)(gt,{children:e.tts.provider}),(0,Q.jsx)(d,{"aria-label":e.tts.provider,className:$(),value:n.provider,onChange:e=>B(e.target.value),children:S.map(t=>(0,Q.jsx)(f,{value:t.id,children:Ye(t.id,e)},t.id))}),(0,Q.jsxs)(`p`,{className:`text-xs text-fg-subtle`,children:[C?.configured?e.tts.configured:C?.diagnostics.requiresApiKey?`${e.tts.needsKey} · ${C.diagnostics.envKeys?.join(`, `)??e.stt.apiKey}`:e.tts.noKeyNeeded,` · `,C?.description??Xe(n.provider,e)]})]})}),(0,Q.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:(0,Q.jsx)(lt,{managedModel:o,kind:`tts`,providerId:n.provider,fields:R,providerSlice:w,models:T,voices:F,currentModel:A,currentVoice:L,apiKeyLabels:t,onPatch:z,resetVoiceOnModelChange:!0})}),(0,Q.jsxs)(`details`,{className:`rounded-xl bg-surface-panel/80 p-3`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium text-fg`,children:e.tts.test.title}),(0,Q.jsxs)(`div`,{className:`mt-3`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`p`,{className:`mt-1 text-xs text-fg-muted`,children:e.tts.test.description})}),(0,Q.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Q.jsxs)(M,{type:`button`,variant:`primary`,onClick:()=>void V(),disabled:l.status===`loading`,className:`h-9`,children:[l.status===`loading`?(0,Q.jsx)(m,{className:`size-4 animate-spin`}):(0,Q.jsx)(g,{className:`size-4`}),l.status===`loading`?e.tts.test.generating:e.tts.test.play]}),(0,Q.jsxs)(M,{type:`button`,variant:`secondary`,onClick:()=>{x(),u(e=>e.status===`playing`?{status:`done`,summary:e.summary}:{status:`idle`})},disabled:l.status!==`playing`,className:`h-9`,children:[(0,Q.jsx)(_,{className:`size-4`}),e.tts.test.stop]})]})]}),(0,Q.jsxs)(`details`,{className:`mt-3`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-xs text-fg-muted`,children:e.setup.sampleText}),(0,Q.jsx)(`textarea`,{className:y(Ge(),`mt-3 min-h-20 resize-y`),value:s,onChange:e=>c(e.target.value),maxLength:1e3})]}),(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center justify-between gap-2 text-xs`,children:[(0,Q.jsxs)(`span`,{className:`text-fg-subtle`,children:[s.length,`/1000`]}),l.status===`playing`||l.status===`done`?(0,Q.jsxs)(`span`,{className:`text-emerald-700 dark:text-emerald-200`,children:[l.status===`playing`?e.tts.test.playing:e.tts.test.ready,` · `,l.summary]}):null,l.status===`error`?(0,Q.jsx)(`span`,{className:`text-red-600 dark:text-red-400`,children:l.message}):null]})]})]})]})})]})}function lt(e){let t=(0,X.c)(48),{kind:n,providerId:r,fields:i,providerSlice:a,models:o,voices:s,currentModel:l,currentVoice:p,apiKeyLabels:m,onPatch:h,resetVoiceOnModelChange:g,managedModel:_}=e,v;t[0]===s?v=t[1]:(v=s===void 0?[]:s,t[0]=s,t[1]=v);let b=v,x=g!==void 0&&g,S=_!==void 0&&_,C=c(pt),w;t[2]===C?w=t[3]:(w=u(C),t[2]=C,t[3]=w);let T=w.voiceSettings,E=S,D=ft,O=dt,k,A,j;if(t[4]!==m||t[5]!==l||t[6]!==p||t[7]!==i||t[8]!==n||t[9]!==C||t[10]!==S||t[11]!==o||t[12]!==h||t[13]!==r||t[14]!==a||t[15]!==x||t[16]!==E||t[17]!==T||t[18]!==b){let e;t[22]===E?e=t[23]:(e=e=>!E||e.key!==`model`&&!O(e),t[22]=E,t[23]=e);let s=i.filter(e),c;t[24]===Symbol.for(`react.memo_cache_sentinel`)?(c=e=>!D(e),t[24]=c):c=t[24];let u=s.filter(c),g;t[25]!==m||t[26]!==l||t[27]!==p||t[28]!==n||t[29]!==C||t[30]!==S||t[31]!==o||t[32]!==h||t[33]!==r||t[34]!==a||t[35]!==x||t[36]!==T||t[37]!==b?(g=e=>e.map(e=>S&&e.key===`model`?null:e.key===`apiKey`?(0,Q.jsxs)(`div`,{className:y(`flex flex-col gap-1.5`,We),children:[(0,Q.jsx)(gt,{htmlFor:`voice-${n}-${r}-api-key`,children:T.stt.apiKey}),(0,Q.jsx)(xe,{kind:n,providerId:r,fieldId:`voice-${n}-${r}-api-key`,value:typeof a.apiKey==`string`?a.apiKey:``,onChange:e=>h({apiKey:e}),labels:m,placeholder:e.placeholder}),e.description?(0,Q.jsx)(`p`,{className:`text-xs text-fg-subtle`,children:e.description}):null]},e.key):e.key===`model`&&o.length>0?(0,Q.jsxs)(`div`,{className:y(`flex flex-col gap-1.5`,We),children:[(0,Q.jsx)(gt,{htmlFor:`voice-${n}-${r}-model`,children:T.stt.model}),(0,Q.jsx)(d,{id:`voice-${n}-${r}-model`,className:$(),value:l??``,onChange:e=>h({model:e.target.value,...x?{voice:void 0}:{}}),children:[...o].sort(U).map(ut)})]},e.key):e.key===`voice`&&b.length>0?(0,Q.jsxs)(`div`,{className:y(`flex flex-col gap-1.5`,We),children:[(0,Q.jsx)(gt,{htmlFor:`voice-${n}-${r}-voice`,children:T.tts.voice}),(0,Q.jsxs)(d,{id:`voice-${n}-${r}-voice`,className:$(),value:p??``,onChange:e=>h({voice:e.target.value}),children:[p&&!b.some(e=>e.id===p)?(0,Q.jsxs)(f,{value:p,children:[p,` · unavailable`]}):null,b.map(e=>(0,Q.jsxs)(f,{value:e.id,children:[W(e,C),e.gender?` · ${e.gender===`female`?`女声`:`男声`}`:``,e.style?` · ${e.style}`:``]},e.id))]}),b.find(e=>e.id===p)?.description?(0,Q.jsx)(`p`,{className:`text-xs text-fg-subtle`,children:b.find(e=>e.id===p)?.description}):null]},e.key):(0,Q.jsx)(mt,{fieldId:`voice-${n}-${r}-${e.key}`,field:e,value:Qe(a,e),onChange:t=>h({[e.key]:t}),className:e.type===`textarea`?`sm:col-span-2`:We},e.key)),t[25]=m,t[26]=l,t[27]=p,t[28]=n,t[29]=C,t[30]=S,t[31]=o,t[32]=h,t[33]=r,t[34]=a,t[35]=x,t[36]=T,t[37]=b,t[38]=g):g=t[38];let _=g;t[39]!==i||t[40]!==n||t[41]!==C||t[42]!==E?(k=E&&i.some(O)?(0,Q.jsx)(je,{className:`text-sm text-accent-fg hover:underline`,to:`/settings/capabilities/models?tab=services&configure=${n===`stt`?`transcription`:`speech`}`,children:C===`zh`?`管理服务连接`:`Manage service connection`}):null,t[39]=i,t[40]=n,t[41]=C,t[42]=E,t[43]=k):k=t[43],A=_(s.filter(D)),j=u.length?(0,Q.jsxs)(`details`,{className:`rounded-lg border border-edge p-3 sm:col-span-2`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium text-fg`,children:T.experience.providerOptions}),(0,Q.jsx)(`div`,{className:`mt-3 grid gap-3 sm:grid-cols-2`,children:_(u)})]}):null,t[4]=m,t[5]=l,t[6]=p,t[7]=i,t[8]=n,t[9]=C,t[10]=S,t[11]=o,t[12]=h,t[13]=r,t[14]=a,t[15]=x,t[16]=E,t[17]=T,t[18]=b,t[19]=k,t[20]=A,t[21]=j}else k=t[19],A=t[20],j=t[21];let M;return t[44]!==k||t[45]!==A||t[46]!==j?(M=(0,Q.jsxs)(Q.Fragment,{children:[k,A,j]}),t[44]=k,t[45]=A,t[46]=j,t[47]=M):M=t[47],M}function ut(e){return(0,Q.jsx)(f,{value:e.id,children:e.name},e.id)}function dt(e){return e.secret||e.type===`password`||[`apiKey`,`baseUrl`,`region`,`groupId`].includes(e.key)}function ft(e){return e.required||[`apiKey`,`model`,`voice`].includes(e.key)}function pt(e){return e.language}function mt(e){let t=(0,X.c)(37),{fieldId:n,field:r,value:i,onChange:a,className:o}=e,s=n??`voice-schema-field-${r.key}`,c=r.description;if(r.type===`boolean`){let e;t[0]===o?e=t[1]:(e=y(`flex items-center justify-between gap-3 rounded-xl bg-surface-hover/50 px-3 py-2.5 dark:bg-surface-hover/35`,o),t[0]=o,t[1]=e);let n;t[2]===r.label?n=t[3]:(n=(0,Q.jsx)(`span`,{className:`block text-sm font-medium text-fg`,children:r.label}),t[2]=r.label,t[3]=n);let s;t[4]===c?s=t[5]:(s=c?(0,Q.jsx)(`span`,{className:`mt-1 block text-xs text-fg-subtle`,children:c}):null,t[4]=c,t[5]=s);let l;t[6]!==n||t[7]!==s?(l=(0,Q.jsxs)(`span`,{children:[n,s]}),t[6]=n,t[7]=s,t[8]=l):l=t[8];let u=!!i,d;t[9]!==r||t[10]!==a?(d=e=>a($e(r,e.target.checked)),t[9]=r,t[10]=a,t[11]=d):d=t[11];let f;t[12]!==u||t[13]!==d?(f=(0,Q.jsx)(`input`,{type:`checkbox`,className:`ui-checkbox`,checked:u,onChange:d}),t[12]=u,t[13]=d,t[14]=f):f=t[14];let p;return t[15]!==e||t[16]!==l||t[17]!==f?(p=(0,Q.jsxs)(`label`,{className:e,children:[l,f]}),t[15]=e,t[16]=l,t[17]=f,t[18]=p):p=t[18],p}let l=typeof i==`boolean`?``:String(i),u;t[19]===o?u=t[20]:(u=y(`flex flex-col gap-1.5`,o),t[19]=o,t[20]=u);let f;t[21]!==r.label||t[22]!==s?(f=(0,Q.jsx)(gt,{htmlFor:s,children:r.label}),t[21]=r.label,t[22]=s,t[23]=f):f=t[23];let m;t[24]!==o||t[25]!==r||t[26]!==l||t[27]!==s||t[28]!==a?(m=r.type===`select`?(0,Q.jsx)(d,{id:s,className:$(),value:l,required:r.required,onChange:e=>a($e(r,e.target.value)),children:(r.options??[]).map(ht)}):r.type===`textarea`?(0,Q.jsx)(`textarea`,{id:s,className:y(Ge(),`min-h-24 resize-y`),value:l,required:r.required,placeholder:r.placeholder,onChange:e=>a($e(r,e.target.value))}):r.type===`password`?(0,Q.jsx)(p,{id:s,className:o,value:l,onChange:e=>a($e(r,e)),placeholder:r.placeholder,labels:re}):r.type===`number`?(0,Q.jsx)(ae,{id:s,className:Ge(),autoComplete:r.secret?`new-password`:`off`,spellCheck:!1,value:l,required:r.required,allowEmpty:!r.required,placeholder:r.placeholder,min:r.min,max:r.max,step:r.step,onChange:e=>a($e(r,e.target.value))}):(0,Q.jsx)(`input`,{id:s,className:Ge(),type:`text`,autoComplete:r.secret?`new-password`:`off`,spellCheck:!1,value:l,required:r.required,placeholder:r.placeholder,min:r.min,max:r.max,step:r.step,onChange:e=>a($e(r,e.target.value))}),t[24]=o,t[25]=r,t[26]=l,t[27]=s,t[28]=a,t[29]=m):m=t[29];let h;t[30]===c?h=t[31]:(h=c?(0,Q.jsx)(`p`,{className:`text-xs text-fg-subtle`,children:c}):null,t[30]=c,t[31]=h);let g;return t[32]!==u||t[33]!==f||t[34]!==m||t[35]!==h?(g=(0,Q.jsxs)(`div`,{className:u,children:[f,m,h]}),t[32]=u,t[33]=f,t[34]=m,t[35]=h,t[36]=g):g=t[36],g}function ht(e){return(0,Q.jsx)(f,{value:e.id,children:e.name},e.id)}function gt(e){let t=(0,X.c)(3),{children:n,htmlFor:r}=e,i;return t[0]!==n||t[1]!==r?(i=r?(0,Q.jsx)(`label`,{htmlFor:r,className:`text-sm font-medium text-fg`,children:n}):(0,Q.jsx)(`div`,{className:`text-sm font-medium text-fg`,children:n}),t[0]=n,t[1]=r,t[2]=i):i=t[2],i}export{Ae as n,tt as t};
|
|
1
|
+
import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t,n,t as r}from"./vendor-react-BOUWij0V.js";import{m as i,t as a}from"./chunk-KS7C4IRE-CiwuuyV8.js";import{i as o,l as s,n as c,o as l}from"./locale-store-Cit_aHqC.js";import{t as u}from"./messages-DQveK9sk.js";import{n as d,r as f}from"./popover-select-CLsphyzA.js";import{t as p}from"./secret-input-DsjfQmDn.js";import{t as m}from"./loader-circle-CifKLtgG.js";import{t as h}from"./mic-CuUb7zc-.js";import{t as g}from"./play-kxZvpBg8.js";import{t as _}from"./square-DMK_fB-3.js";import{t as v}from"./volume-2-BSJhAY97.js";import{t as y}from"./cn-0WouolD0.js";import{t as b}from"./skeleton-DzdOeGYz.js";import{a as x,c as S,i as C,m as w,n as T,p as E,u as D}from"./schemas-CCWMleym.js";import{n as O}from"./voice-CDlC6XMH.js";import{i as k}from"./vendor-swr-CdRzEUwF.js";import{n as A,r as j}from"./gateway-config-swr-DVXDJNCI.js";import{t as M}from"./button-Cc4hUNTt.js";import{t as N}from"./open-capability-settings-DQsmJxI7.js";import{a as P,d as F,f as I,i as L,o as R,p as z,t as B,u as V}from"./use-realtime-voice-D5-XzM7H.js";import{t as ee}from"./voice-call-context-BM2A4bLz.js";import{a as H,o as te,s as ne}from"./form-field-width-DJw_jULe.js";import{t as re}from"./secret-input-labels-B5Jl5HqK.js";import{n as U}from"./model-sort-_Tz8s_4N.js";import{r as W}from"./model-selector-Cg2kTsE7.js";import{n as G,s as K}from"./playback-coordinator-CWHIf0wr.js";import{t as ie}from"./settings-loading-skeleton-CAoOV17i.js";import{a as q,i as J}from"./capability-navigation-CZbCI5C2.js";import{t as ae}from"./number-input-El7Szeln.js";import{n as oe,t as se}from"./use-autosave-CvjQMyY8.js";import{a as ce,c as le,d as ue,f as de,g as fe,h as pe,i as Y,l as me,n as he,o as ge,p as _e,r as ve,t as ye,u as be}from"./voice-config-api-BLGbUq3v.js";import{t as xe}from"./voice-api-key-field-M7KB_Gl1.js";var Se=E({"zh-CN":w().min(1).optional(),en:w().min(1).optional()}),Ce=T([`transcription`,`transcription.stream`,`speech`,`speech.stream`,`conversation`]),we=E({protocolVersion:S(1),serviceVersion:D().int().positive(),modes:C(Ce),transport:S(`websocket-pcm`),inputFormat:E({encoding:S(`pcm_s16le`),sampleRate:S(16e3),channels:S(1)}),outputFormat:E({encoding:S(`pcm_s16le`),sampleRate:S(24e3),channels:S(1)}),turnDetection:C(S(`server_vad`)),bargeIn:x(),tools:x(),resumable:S(!1),voices:C(E({id:w().min(1),name:w(),displayNames:Se.optional(),languages:C(w()),gender:T([`female`,`male`]).optional(),style:w().optional(),description:w().optional(),modes:C(Ce).optional()})),defaultVoice:w().min(1).optional(),limits:E({maxFrameBytes:D().int().positive().max(65536),maxSessionSeconds:D().int().positive()})});function Te(e,t){return e.modes===void 0||e.modes.includes(t)}var Ee=E({mode:Ce,model:w().min(1).max(200),voice:w().min(1).max(200).optional()}),De=E({revision:w().min(1),catalogVersion:w().nullable(),selections:C(Ee),models:C(E({id:w(),name:w(),displayNames:Se.optional(),voice:we}))}),X=n(),Z=e(t(),1),Q=r();function Oe({disabled:e=!1,modes:t,onPendingChange:n}){let r=c(e=>e.language),i=r===`zh`,[a,s]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>(n?.(a),()=>n?.(!1)),[a,n]);let[u,p]=(0,Z.useState)(``),{data:m,mutate:h,error:g}=k(o(`/api/voice/catalog`),async e=>{let t=await l(e);return De.parse(t.payload)}),_=i?{transcription:`录音转文字`,"transcription.stream":`实时听写 / 语音助手输入`,speech:`消息朗读`,"speech.stream":`语音助手输出`,conversation:`自然语音对话`}:{transcription:`Recorded transcription`,"transcription.stream":`Live dictation / assistant input`,speech:`Message readout`,"speech.stream":`Assistant speech`,conversation:`Natural conversation`},v=async e=>{if(m){s(!0),p(``);try{let t=await l(o(e?`/api/voice/selection`:`/api/voice/catalog/refresh`),{method:e?`PUT`:`POST`,...e?{body:JSON.stringify({revision:m.revision,selection:e})}:{}});await h(De.parse(t.payload),!1),await A()}catch(e){p(e instanceof Error?e.message:String(e)),await h()}finally{s(!1)}}};return(0,Q.jsxs)(`section`,{className:`space-y-4 rounded-xl bg-surface-hover/20 p-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsx)(`h3`,{className:`font-medium`,children:i?`XOPC 托管语音模型`:`XOPC managed voice models`}),(0,Q.jsx)(M,{variant:`secondary`,disabled:a||e||!m,onClick:()=>void v(),children:i?`刷新目录`:`Refresh catalog`})]}),(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:i?`修改在下次调用生效。各设备共用此 Gateway 的配置。`:`Changes apply to the next call and are shared across devices.`}),u||g?(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm text-red-600`,children:u||String(g)}):null,m?(0,Q.jsx)(Q.Fragment,{children:t.map(t=>{let n=m.selections.find(e=>e.mode===t),o=m.models.filter(e=>e.voice.modes.includes(t)).sort(U),s=o.find(e=>e.id===n?.model),c=s?.voice.voices.filter(e=>Te(e,t))??[],l=n?.voice??c.find(e=>e.id===s?.voice.defaultVoice)?.id??c[0]?.id??``;return(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{className:`space-y-1 text-sm`,children:[(0,Q.jsx)(`span`,{children:_[t]}),(0,Q.jsxs)(d,{className:`w-full`,value:n?.model??``,disabled:a||e||!o.length,onChange:e=>void v({mode:t,model:e.target.value}),children:[(0,Q.jsx)(f,{value:``,disabled:!0,children:i?`选择模型`:`Choose model`}),n&&!s?(0,Q.jsxs)(f,{value:n.model,disabled:!0,children:[n.model,` · `,i?`不可用`:`Unavailable`]}):null,o.map(e=>(0,Q.jsx)(f,{value:e.id,children:W(e,r)},e.id))]}),o.length?null:(0,Q.jsx)(`span`,{className:`text-xs text-fg-muted`,children:i?`暂无可用模型`:`No available model`})]}),s&&c.length>0?(0,Q.jsxs)(`label`,{className:`space-y-1 text-sm`,children:[(0,Q.jsx)(`span`,{children:i?`音色`:`Voice`}),(0,Q.jsxs)(d,{className:`w-full`,value:l,disabled:a||e,onChange:e=>void v({mode:t,model:s.id,voice:e.target.value}),children:[n?.voice&&!c.some(e=>e.id===n.voice)?(0,Q.jsxs)(f,{value:n.voice,disabled:!0,children:[n.voice,` · `,i?`当前场景不可用`:`Unavailable for this mode`]}):null,c.map(e=>(0,Q.jsxs)(f,{value:e.id,children:[W(e,r),e.gender?` · ${i?e.gender===`female`?`女声`:`男声`:e.gender}`:``,e.style?` · ${e.style}`:``]},e.id))]}),c.find(e=>e.id===l)?.description?(0,Q.jsx)(`span`,{className:`block text-xs text-fg-muted`,children:c.find(e=>e.id===l)?.description}):null]}):null]},t)})}):(0,Q.jsx)(b,{className:`h-48 w-full`})]})}function ke({v:e}){let t=I(e=>e.microphoneId),n=I(e=>e.setMicrophoneId),[r,i]=(0,Z.useState)([]),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(!1),l=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{l.current=!0;let e=()=>{navigator.mediaDevices?.enumerateDevices().then(e=>{l.current&&i(e.filter(e=>e.kind===`audioinput`))}).catch(()=>{})};return e(),navigator.mediaDevices?.addEventListener(`devicechange`,e),()=>{l.current=!1,navigator.mediaDevices?.removeEventListener(`devicechange`,e)}},[]);let u=async()=>{c(!0),o(``);try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop());let e=await navigator.mediaDevices.enumerateDevices();l.current&&i(e.filter(e=>e.kind===`audioinput`))}catch(e){l.current&&o(e instanceof Error?e.message:String(e))}finally{l.current&&c(!1)}};return(0,Q.jsxs)(`section`,{className:`space-y-4 rounded-xl bg-surface-hover/20 p-4`,children:[(0,Q.jsxs)(`label`,{className:`block space-y-2 text-sm`,children:[(0,Q.jsx)(`span`,{children:e.experience.microphone}),(0,Q.jsxs)(d,{value:t,onChange:e=>n(e.target.value),children:[(0,Q.jsx)(f,{value:``,children:e.experience.systemDevice}),t&&!r.some(e=>e.deviceId===t)?(0,Q.jsx)(f,{value:t,children:e.experience.unavailable}):null,r.filter(e=>e.deviceId&&e.deviceId!=="default").map((t,n)=>(0,Q.jsx)(f,{value:t.deviceId,children:t.label||`${e.experience.microphone} ${n+1}`},t.deviceId))]})]}),(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:e.experience.deviceHint}),(0,Q.jsx)(M,{variant:`secondary`,disabled:s,onClick:()=>void u(),children:e.experience.refreshDevices}),a?(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm text-red-600`,children:a}):null]})}var Ae=(0,Z.createContext)(null);function je(e){let t=(0,X.c)(18),n,r;t[0]===e?(n=t[1],r=t[2]):({to:r,...n}=e,t[0]=e,t[1]=n,t[2]=r);let[o]=i(),s=(0,Z.useContext)(Ae),c,l;t[3]===r?(c=t[4],l=t[5]):(c=new URLSearchParams(r.split(`?`)[1]??``),l=J(c.get(`configure`)),t[3]=r,t[4]=c,t[5]=l);let u=l,d;t[6]!==s||t[7]!==n||t[8]!==c||t[9]!==u?(d=e=>{n.onClick?.(e),!e.defaultPrevented&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&e.button===0&&s&&u&&c.get(`tab`)===`services`&&(e.preventDefault(),s(u))},t[6]=s,t[7]=n,t[8]=c,t[9]=u,t[10]=d):d=t[10];let f;t[11]!==o||t[12]!==r?(f=q(r,o),t[11]=o,t[12]=r,t[13]=f):f=t[13];let p;return t[14]!==n||t[15]!==d||t[16]!==f?(p=(0,Q.jsx)(a,{...n,onClick:d,to:f}),t[14]=n,t[15]=d,t[16]=f,t[17]=p):p=t[17],p}function Me(e){let t=(0,X.c)(19),{zh:n}=e,{data:r,error:i,mutate:a}=k(`voice-dictation-route`,Ne),o,s;t[0]===a?(o=t[1],s=t[2]):(o=()=>{let e=()=>{a()};return window.addEventListener(`voice-config-changed`,e),window.addEventListener(`config-reload`,e),()=>{window.removeEventListener(`voice-config-changed`,e),window.removeEventListener(`config-reload`,e)}},s=[a],t[0]=a,t[1]=o,t[2]=s),(0,Z.useEffect)(o,s);let c=n?`同时用于聊天听写`:`Also used for chat dictation`,l;t[3]===c?l=t[4]:(l=(0,Q.jsx)(`h2`,{className:`font-medium text-fg`,children:c}),t[3]=c,t[4]=l);let u=n?`默认与录音识别共用模型。已有的独立听写设置会保留。`:`Dictation shares this recognition model. Existing separate dictation settings are preserved.`,d;t[5]===u?d=t[6]:(d=(0,Q.jsx)(`p`,{className:`text-fg-muted`,children:u}),t[5]=u,t[6]=d);let f;t[7]!==r||t[8]!==i||t[9]!==n?(f=!r&&!i?(0,Q.jsx)(b,{className:`h-5 w-64 max-w-full`}):(0,Q.jsx)(`p`,{role:i?`alert`:`status`,className:`text-fg-muted`,children:i?n?`暂时无法读取听写状态。`:`Dictation status could not be loaded.`:r?.mode===`recorded`?n?`当前使用 ${r.provider},点击完成后转为文字。`:`Using ${r.provider}. Choose Finish to transcribe.`:r?.mode===`streaming`?n?`当前使用流式识别${r.provider?` · ${r.provider}`:``}。`:`Using streaming recognition${r.provider?` · ${r.provider}`:``}.`:n?`听写未就绪,请检查识别模型或已有的流式配置。`:`Check the recognition model or existing streaming configuration.`}),t[7]=r,t[8]=i,t[9]=n,t[10]=f):f=t[10];let p;t[11]!==r?.mode||t[12]!==n?(p=r?.mode===`recorded`?null:(0,Q.jsx)(je,{className:`inline-block text-accent-fg hover:underline`,to:`/settings/capabilities/models?tab=services&configure=transcription`,children:n?`管理识别服务`:`Manage recognition services`}),t[11]=r?.mode,t[12]=n,t[13]=p):p=t[13];let m;return t[14]!==l||t[15]!==d||t[16]!==f||t[17]!==p?(m=(0,Q.jsxs)(`section`,{className:`space-y-2 rounded-xl border border-edge p-4 text-sm`,children:[l,d,f,p]}),t[14]=l,t[15]=d,t[16]=f,t[17]=p,t[18]=m):m=t[18],m}function Ne(){return L(AbortSignal.timeout(15e3))}function Pe({v:e,canListen:t,canSpeak:n,disabled:r,onVerified:i}){let a=e.setup,o=(0,Z.useContext)(ee)?.active??!1,[s,c]=(0,Z.useState)(`idle`),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(``),p=(0,Z.useRef)(`idle`),v=(0,Z.useRef)(null),y=(0,Z.useRef)(!1),b=e=>{p.current=e,c(e)},x=()=>{v.current?.(),v.current=null};(0,Z.useEffect)(()=>()=>v.current?.(),[]);async function S(e){x(),i?.({input:!1,output:!1}),y.current=!1,u(``),f(``),b(e?`connecting`:`playing`);let t=new AbortController,r,o,s,c,l=()=>{o?.cancel(),r?.getTracks().forEach(e=>e.stop()),s?.stop(`surface_closed`)},d=window.setTimeout(()=>m(a.timeout),6e4);v.current=()=>{t.abort(),window.clearTimeout(d),l(),c?.close()};function m(e){t.signal.aborted||(b(`error`),f(e),x())}async function h(){b(`playing`),l();try{let e=await ue(t.signal);if(t.signal.aborted)return;c?.enqueue(e,()=>{t.signal.aborted||(window.clearTimeout(d),b(`confirm`))})}catch(e){m(e instanceof Error?e.message:a.testFailed)}}try{if(n&&(c=new V,await c.start(),t.signal.throwIfAborted()),!e){await h();return}let d=window.electronAPI?.system;if(d){let e=await d.requestMicrophone();if(t.signal.throwIfAborted(),e.status===`denied`)throw Error(a.microphoneDenied)}if(r=await navigator.mediaDevices.getUserMedia({audio:z()}),t.signal.aborted){l();return}if(s=await F.connect({purpose:`dictation`,signal:t.signal,onEvent:e=>{t.signal.aborted||(e.type===`session.error`&&m(a.testFailed),p.current===`listening`&&(e.type===`input.transcript.delta`&&u(e.payload.text),e.type===`input.transcript.final`&&e.payload.text.trim()&&(u(e.payload.text.trim()),y.current=!0,n?h():(b(`passed`),i?.({input:!0,output:!1}),x()))))},onClose:()=>{(p.current===`listening`||p.current===`connecting`)&&m(a.testFailed)}}),t.signal.aborted){l();return}let f;if(o=await P.start(r,{onSamples:e=>{f&&!t.signal.aborted&&s?.sendAudio(f.push(e))}}),t.signal.aborted){l();return}f=new R(o.sampleRate,s.session.inputFormat.sampleRate),b(`listening`)}catch(e){if(t.signal.aborted){l();return}m(e instanceof Error?e.message:a.testFailed)}}let C=s===`connecting`||s===`listening`||s===`playing`;return(0,Q.jsxs)(`div`,{className:`space-y-3 rounded-xl bg-surface-base/45 p-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsxs)(M,{type:`button`,variant:`primary`,disabled:o||r||!t||C,onClick:()=>void S(!0),children:[C?(0,Q.jsx)(m,{className:`size-4 animate-spin`}):(0,Q.jsx)(h,{className:`size-4`}),n?a.test:a.testInput]}),(0,Q.jsxs)(M,{type:`button`,variant:`secondary`,disabled:o||r||!n||C,onClick:()=>void S(!1),children:[(0,Q.jsx)(g,{className:`size-4`}),e.tts.test.play]}),C?(0,Q.jsxs)(M,{type:`button`,variant:`ghost`,onClick:()=>{x(),b(`idle`)},children:[(0,Q.jsx)(_,{className:`size-4`}),e.tts.test.stop]}):null]}),(0,Q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,className:`space-y-2 text-xs text-fg-muted`,children:[s===`idle`?(0,Q.jsx)(`p`,{children:o?e.experience.endCallBeforeTest:r?a.saveBeforeTest:a.microphoneHint}):null,s===`connecting`?(0,Q.jsx)(`p`,{children:a.connecting}):null,s===`listening`?(0,Q.jsx)(`p`,{children:a.speakNow}):null,l?(0,Q.jsx)(`p`,{className:`rounded-lg bg-surface-base p-3 text-sm text-fg`,children:l}):null,s===`playing`?(0,Q.jsx)(`p`,{children:a.playing}):null,s===`confirm`?(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(`span`,{children:a.heardQuestion}),(0,Q.jsx)(M,{type:`button`,variant:`secondary`,onClick:()=>{x(),i?.({input:y.current,output:!0}),b(`passed`)},children:a.heard}),(0,Q.jsx)(M,{type:`button`,variant:`ghost`,onClick:()=>{x(),b(`error`),f(a.notHeard)},children:a.notHeardButton})]}):null,s===`passed`?(0,Q.jsx)(`p`,{children:y.current?n?a.passed:a.inputPassed:a.outputPassed}):null,s===`error`?(0,Q.jsx)(`p`,{role:`alert`,className:`text-red-600 dark:text-red-400`,children:d}):null]})]})}function Fe(e){let t=(0,X.c)(78),{section:n,v:r,form:i,pending:a,onChange:s}=e,l=c(Be),u=r.setup,p;t[0]===i?p=t[1]:(p=JSON.stringify(i),t[0]=i,t[1]=p);let m=p,h;t[2]===m?h=t[3]:(h={signature:m,input:!1,output:!1},t[2]=m,t[3]=h);let[g,_]=(0,Z.useState)(h);g.signature!==m&&_({signature:m,input:!1,output:!1});let v;t[4]!==a||t[5]!==m?(v=a?null:[`voice-realtime-status`,m],t[4]=a,t[5]=m,t[6]=v):v=t[6];let y;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(y={revalidateOnFocus:!0},t[7]=y):y=t[7];let{data:x,error:S,isLoading:C}=k(v,ve,y),w;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(w=o(`/api/voice/catalog`),t[8]=w):w=t[8];let{data:T}=k(w,ze),E=i.voice.realtime,D=E.tts,O=D?.provider??x?.tts?.provider,A=x?.tts?.model,j;t[9]!==A||t[10]!==O?(j=O&&A?[`realtime-voices`,O,A]:null,t[9]=A,t[10]=O,t[11]=j):j=t[11];let M;t[12]!==A||t[13]!==O?(M=()=>Y(O,A,`realtime`),t[12]=A,t[13]=O,t[14]=M):M=t[14];let N;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(N={revalidateOnFocus:!1},t[15]=N):N=t[15];let{data:P}=k(j,M,N),F;t[16]===P?F=t[17]:(F=P===void 0?[]:P,t[16]=P,t[17]=F);let I=F,L=I,R;t[18]===I?R=t[19]:(R=I.filter(Re),t[18]=I,t[19]=R);let z=R,B=E.defaultEngine===`omni`,V=B?E.omni?.voice??``:D?.voice??``,ee;t[20]!==T?.models||t[21]!==B||t[22]!==z||t[23]!==E.omni||t[24]!==L?(ee=B&&E.omni?.provider===`qwen-token-plan-cn`?[{id:E.omni.voice,name:E.omni.voice}]:B?E.omni?.provider===`xopc-cloud`?T?.models.find(e=>e.id===E.omni?.model)?.voice.voices.filter(Le)??[]:z.length?z:[`Cherry`,`Ethan`,`Serena`,`Chelsie`].map(Ie):L,t[20]=T?.models,t[21]=B,t[22]=z,t[23]=E.omni,t[24]=L,t[25]=ee):ee=t[25];let H=ee,ne=!!(x?.enabled&&x.stt),re=!!(x?.enabled&&x.tts),U;t[26]!==i||t[27]!==s||t[28]!==E?(U=e=>s({...i,voice:{...i.voice,realtime:{...E,...e}}}),t[26]=i,t[27]=s,t[28]=E,t[29]=U):U=t[29];let G=U,K;t[30]!==a||t[31]!==E.enabled||t[32]!==u.disabled||t[33]!==u.needsSetup||t[34]!==u.pending||t[35]!==u.unverified||t[36]!==u.verified||t[37]!==m||t[38]!==g.signature?(K=(e,t)=>E.enabled?a?u.pending:e?t&&g.signature===m?u.verified:u.unverified:u.needsSetup:u.disabled,t[30]=a,t[31]=E.enabled,t[32]=u.disabled,t[33]=u.needsSetup,t[34]=u.pending,t[35]=u.unverified,t[36]=u.verified,t[37]=m,t[38]=g.signature,t[39]=K):K=t[39];let ie=K,q;t[40]!==V||t[41]!==l||t[42]!==B||t[43]!==O||t[44]!==E.bargeIn||t[45]!==E.defaultEngine||t[46]!==E.enabled||t[47]!==E.omni||t[48]!==E.tts||t[49]!==u.bargeIn||t[50]!==u.defaultVoice||t[51]!==u.enable||t[52]!==u.voice||t[53]!==n||t[54]!==D||t[55]!==x?.tts||t[56]!==G||t[57]!==r.experience||t[58]!==r.realtime||t[59]!==H?(q=n===`listening`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`flex items-center justify-between gap-3 text-sm font-medium text-fg`,children:[(0,Q.jsx)(`span`,{children:u.enable}),(0,Q.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-checked":E.enabled,className:`ui-checkbox`,checked:E.enabled,onChange:e=>G({enabled:e.target.checked})})]}),(0,Q.jsxs)(`label`,{className:`block space-y-2 text-sm`,children:[(0,Q.jsx)(`span`,{children:r.experience.defaultMode}),(0,Q.jsxs)(d,{value:E.defaultEngine,className:te,onChange:e=>G({defaultEngine:e.target.value}),children:[(0,Q.jsx)(f,{value:`auto`,children:l===`zh`?`自动选择`:`Automatic`}),(0,Q.jsx)(f,{value:`agent`,children:r.experience.assistant}),(0,Q.jsx)(f,{value:`omni`,children:r.experience.natural})]})]}),(0,Q.jsxs)(`p`,{className:`text-xs text-fg-muted`,children:[E.defaultEngine===`agent`?r.experience.assistantHint:r.experience.naturalHint,` `,r.experience.nextCall]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Q.jsx)(`label`,{htmlFor:`realtime-voice`,className:`text-sm font-medium text-fg`,children:u.voice}),(0,Q.jsxs)(d,{id:`realtime-voice`,className:`${te} w-full sm:w-56`,value:V,disabled:B?!E.omni:!D&&!x?.tts,onChange:e=>{if(B&&E.omni){G({omni:{...E.omni,voice:e.target.value}});return}if(O===`alibaba`||O===`xopc-cloud`){let t={...E.tts,provider:O};e.target.value?t.voice=e.target.value:delete t.voice,G({tts:t})}},children:[B?null:(0,Q.jsx)(f,{value:``,children:u.defaultVoice}),V&&!H.some(e=>e.id===V)?(0,Q.jsx)(f,{value:V,children:V}):null,H.map(e=>(0,Q.jsxs)(f,{value:e.id,children:[W(e,l),`gender`in e&&e.gender?` · ${e.gender===`female`?`女声`:`男声`}`:``,`style`in e&&e.style?` · ${e.style}`:``]},e.id))]}),(()=>{let e=H.find(e=>e.id===V);return e&&`description`in e&&typeof e.description==`string`?(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:e.description}):null})()]}),(0,Q.jsxs)(`label`,{className:`flex items-center justify-between gap-4 text-sm text-fg`,children:[(0,Q.jsxs)(`span`,{children:[u.bargeIn,(0,Q.jsx)(`span`,{className:`mt-1 block text-xs text-fg-muted`,children:r.realtime.bargeInDescription})]}),(0,Q.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-checked":E.bargeIn,checked:E.bargeIn,className:`size-4 accent-accent`,onChange:e=>G({bargeIn:e.target.checked})})]})]}):null,t[40]=V,t[41]=l,t[42]=B,t[43]=O,t[44]=E.bargeIn,t[45]=E.defaultEngine,t[46]=E.enabled,t[47]=E.omni,t[48]=E.tts,t[49]=u.bargeIn,t[50]=u.defaultVoice,t[51]=u.enable,t[52]=u.voice,t[53]=n,t[54]=D,t[55]=x?.tts,t[56]=G,t[57]=r.experience,t[58]=r.realtime,t[59]=H,t[60]=q):q=t[60];let J;t[61]!==ne||t[62]!==re||t[63]!==S||t[64]!==C||t[65]!==a||t[66]!==n||t[67]!==m||t[68]!==x||t[69]!==ie||t[70]!==r||t[71]!==g.input||t[72]!==g.output?(J=n===`diagnostics`?(0,Q.jsxs)(Q.Fragment,{children:[C?(0,Q.jsx)(b,{className:`h-16 w-full`}):(0,Q.jsxs)(`div`,{className:`space-y-2 text-sm`,role:`status`,children:[(0,Q.jsxs)(`p`,{children:[r.experience.dictationReady,` · `,ie(ne,g.input)]}),(0,Q.jsxs)(`p`,{children:[r.experience.agentReady,` · `,ie(ne&&re,g.input&&g.output)]}),(0,Q.jsxs)(`p`,{children:[r.experience.omniReady,` · `,ie(!!(x?.enabled&&x.omni),!1)]})]}),(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:r.experience.configurationOnly}),(0,Q.jsx)(Pe,{v:r,canListen:ne,canSpeak:re,disabled:a||C||!!S,onVerified:e=>_({signature:m,...e})},`${m}:${JSON.stringify(x)}`)]}):null,t[61]=ne,t[62]=re,t[63]=S,t[64]=C,t[65]=a,t[66]=n,t[67]=m,t[68]=x,t[69]=ie,t[70]=r,t[71]=g.input,t[72]=g.output,t[73]=J):J=t[73];let ae;return t[74]!==u.service||t[75]!==q||t[76]!==J?(ae=(0,Q.jsxs)(`section`,{className:`space-y-5 rounded-xl bg-surface-hover/20 p-4 sm:p-5`,"aria-label":u.service,children:[q,J]}),t[74]=u.service,t[75]=q,t[76]=J,t[77]=ae):ae=t[77],ae}function Ie(e){return{id:e,name:e}}function Le(e){return Te(e,`conversation`)}function Re(e){return[`Cherry`,`Ethan`,`Serena`,`Chelsie`].includes(e.id)}async function ze(e){return De.parse((await l(e)).payload)}function Be(e){return e.language}function Ve(e){let t=(0,X.c)(19),{value:n,onChange:r}=e,i=c(He)===`zh`,a=i?`通话指令`:`Conversation instructions`,o;t[0]===a?o=t[1]:(o=(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium text-fg`,children:a}),t[0]=a,t[1]=o);let s=i?`通话会接续当前会话。可在这里调整语气与回答方式。`:`Calls continue the current conversation. Adjust tone and response style here.`,l;t[2]===s?l=t[3]:(l=(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:s}),t[2]=s,t[3]=l);let u=i?`通话指令`:`Conversation instructions`,d;t[4]===u?d=t[5]:(d=(0,Q.jsx)(`span`,{children:u}),t[4]=u,t[5]=d);let f;t[6]!==r||t[7]!==n?(f=e=>r({...n,instructions:e.target.value}),t[6]=r,t[7]=n,t[8]=f):f=t[8];let p;t[9]!==f||t[10]!==n.instructions?(p=(0,Q.jsx)(`textarea`,{className:`w-full rounded-lg border border-edge bg-surface-panel px-3 py-2 text-sm text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent`,rows:3,maxLength:8e3,value:n.instructions,onChange:f}),t[9]=f,t[10]=n.instructions,t[11]=p):p=t[11];let m;t[12]!==d||t[13]!==p?(m=(0,Q.jsxs)(`label`,{className:`block space-y-2 text-sm`,children:[d,p]}),t[12]=d,t[13]=p,t[14]=m):m=t[14];let h;return t[15]!==o||t[16]!==l||t[17]!==m?(h=(0,Q.jsxs)(`details`,{className:`space-y-3 rounded-xl bg-surface-hover/20 p-4`,children:[o,l,m]}),t[15]=o,t[16]=l,t[17]=m,t[18]=h):h=t[18],h}function He(e){return e.language}function Ue({disabled:e=!1}){let t=c(e=>e.language),n=t===`zh`,{data:r,error:i,mutate:s}=k(o(ye),he),[l,m]=(0,Z.useState)(``),[h,g]=(0,Z.useState)(0),_=(0,Z.useId)();(0,Z.useLayoutEffect)(()=>{g(e=>e+1)},[]);let[v,y]=(0,Z.useState)(),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(``),[T,E]=(0,Z.useState)(!1),D=B({disabled:e||x,chat:u(t).chat,onTranscript:()=>{},onTestAudioPlayed:()=>E(!0)}),j=D.phase!==`idle`&&D.phase!==`error`,P=v??r?.voice??`default`,F=r?.credentialSource===`global`;async function I(){try{return await _e()}catch(e){throw e instanceof Error&&`status`in e&&e.status===404?Error(n?`当前 Gateway 版本不支持查看密钥。请更新并重启 Gateway。`:`Update and restart the Gateway to view or copy the saved key.`):e}}async function L(e){if(!(x||j)){S(!0),w(``);try{await s(await pe(e),{revalidate:!1}),`apiKey`in e&&(m(``),g(e=>e+1),E(!1),D.cancelVoiceInput()),await A()}catch(e){w(e instanceof Error?e.message:String(e))}finally{S(!1)}}}return(0,Q.jsxs)(`section`,{className:`@container space-y-3 rounded-xl border border-edge bg-surface-panel p-4`,"aria-label":`Boson AI`,children:[(0,Q.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Boson AI · Higgs Realtime`}),!r&&!i?(0,Q.jsx)(b,{className:`h-24 w-full`}):null,i?(0,Q.jsxs)(`div`,{role:`alert`,className:`text-sm text-danger`,children:[n?`无法读取 Boson 设置。`:`Could not load Boson settings.`,(0,Q.jsx)(M,{variant:`ghost`,onClick:()=>void s(),children:n?`重试`:`Retry`})]}):null,r&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`fieldset`,{disabled:e||x||j,className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1`,children:[(0,Q.jsx)(`label`,{htmlFor:_,className:`text-sm font-medium text-fg`,children:`Boson API Key`}),(0,Q.jsx)(`p`,{role:`status`,className:`text-xs text-fg-muted`,children:r.credentialSource===`env`?n?`已从环境读取 BOSON_API_KEY`:`Using BOSON_API_KEY from the environment`:r.credentialSource?n?`已保存 API Key`:`API key saved`:n?`尚未连接`:`Connection needed`})]}),(0,Q.jsxs)(`div`,{className:`grid items-start gap-2 @min-[32rem]:grid-cols-[minmax(0,1fr)_auto]`,children:[(0,Q.jsx)(p,{id:_,value:l||(F?`••••••••••••`:``),onChange:e=>m(e.replace(/^•+/u,``)),autoComplete:`new-password`,inputClassName:`min-h-11`,labels:{show:n?`显示密钥`:`Show key`,hide:n?`隐藏密钥`:`Hide key`,copy:n?`复制密钥`:`Copy key`,copied:n?`已复制`:`Copied`},reveal:F?I:void 0,allowUnrevealedCopy:!0,loadFailedLabel:n?`无法查看已保存的密钥。`:`Could not load the saved key.`,notInConfigFile:n?`当前没有已保存的密钥。`:`There is no saved key.`},`${F}:${h}`),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(M,{className:`min-h-11`,variant:`secondary`,type:`button`,disabled:!l.trim(),onClick:()=>void L({apiKey:l}),children:x?n?`正在保存…`:`Saving…`:n?`保存密钥`:`Save key`}),F&&(0,Q.jsx)(M,{className:`min-h-11`,type:`button`,variant:`ghost`,onClick:()=>void L({apiKey:null}),children:n?`移除已保存密钥`:`Remove saved key`})]})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-1 text-sm`,children:[(0,Q.jsx)(`span`,{children:n?`Higgs 默认音色`:`Default Higgs voice`}),(0,Q.jsx)(d,{"aria-label":n?`Higgs 默认音色`:`Default Higgs voice`,value:P,onChange:e=>{y(e.target.value),E(!1),D.cancelVoiceInput()},children:O.map(e=>(0,Q.jsx)(f,{value:e,children:e==="default"?n?`模型默认`:`Model default`:e},e))})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(M,{type:`button`,variant:`secondary`,disabled:P===r.voice||!r.credentialSource,onClick:()=>void L({voice:P}),children:n?`保存音色`:`Save voice`}),(0,Q.jsx)(`span`,{className:`text-sm text-fg-muted`,children:r.defaultForNatural?n?`当前全局自然语音模型`:`Current global natural voice model`:n?`在上方选择全局自然语音模型`:`Choose the global natural voice model above`})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-2 border-t border-edge pt-3`,children:[(0,Q.jsx)(`p`,{className:`text-sm text-fg-muted`,children:n?`测试时请说一句中文,听到回复后可以插话。音频由 Boson 处理,测试内容仅在当前面板显示,可能产生用量。`:`Say a sentence and try interrupting the reply. Boson processes the audio. Test content stays in this panel and may incur usage.`}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[j?(0,Q.jsx)(M,{type:`button`,variant:`secondary`,onClick:D.cancelVoiceInput,children:n?`结束测试`:`End test`}):(0,Q.jsx)(M,{type:`button`,variant:`secondary`,disabled:e||x||!r.credentialSource,onClick:()=>{D.cancelVoiceInput(),E(!1),w(``),D.startHiggsTest(P)},children:n?`测试通话`:`Test call`}),r.credentialSource&&!e&&!x&&!j&&(0,Q.jsx)(a,{className:`px-2 text-sm text-accent-fg hover:underline`,to:`/personal`,onClick:N,children:n?`打开 Ada`:`Open Ada`})]}),j&&(0,Q.jsx)(`p`,{role:`status`,className:`text-sm text-fg-muted`,children:D.phase===`recording`?D.responsePhase===`speaking`?n?`正在播放,可以插话`:`Playing reply. You can interrupt.`:n?`麦克风已开启,请说话`:`Microphone on. Say something.`:n?`正在连接测试通话…`:`Connecting test call…`}),T&&(0,Q.jsx)(`p`,{role:`status`,className:`text-sm text-success`,children:n?`测试通过,已播放回复`:`Test passed. Reply played.`}),D.finalTranscript&&(0,Q.jsxs)(`p`,{className:`text-sm text-fg`,children:[n?`转写 · `:`Transcript · `,D.finalTranscript]}),D.responseText&&(0,Q.jsxs)(`p`,{className:`text-sm text-fg`,children:[n?`回复 · `:`Reply · `,D.responseText]})]})]}),(C||D.error)&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm text-danger`,children:C||D.error})]})}var We=H;function Ge(){return y(`w-full rounded-lg border border-edge bg-surface-panel px-3 py-2 text-sm text-fg`,`placeholder:text-fg-subtle`,ne,`dark:border-edge`)}function $(){return y(te,H)}function Ke(e){return!e||e<=0?``:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function qe(e,t){let n=window.atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return URL.createObjectURL(new Blob([r],{type:t}))}function Je(e,t){switch(e){case`xopc-cloud`:return t.setup.hosted;case`openai`:return t.stt.openai;case`alibaba`:return t.stt.alibaba;case`groq`:return`Groq`;default:return e}}function Ye(e,t){switch(e){case`xopc-cloud`:return t.setup.hosted;case`openai`:return t.tts.providerOpenai;case`alibaba`:return t.stt.alibaba;case`edge`:return t.tts.providerEdge;case`minimax`:return`MiniMax`;default:return e}}function Xe(e,t){switch(e){case`edge`:return t.tts.providerHints.edge;case`openai`:return t.tts.providerHints.openai;case`alibaba`:return t.tts.providerHints.alibaba;case`minimax`:return t.tts.providerHints.minimax;default:return t.tts.providerHints.generic}}function Ze(e){return{maskedHelp:e.apiKeyMaskedHelp,copy:e.apiKeyCopy,copied:e.apiKeyCopied,show:e.apiKeyShow,hide:e.apiKeyHide,notInConfigFile:e.apiKeyNotInConfigFile,loadFailed:e.apiKeyRevealFailed}}function Qe(e,t){let n=e[t.key];return typeof n==`string`||typeof n==`number`||typeof n==`boolean`?n:t.defaultValue===void 0?t.type!==`boolean`&&``:t.defaultValue}function $e(e,t){if(e.type===`boolean`)return!!t;if(e.type!==`number`)return t;let n=String(t).trim();if(!n)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function et(e,t){switch(t.type){case`reset`:return{form:null,baseline:null};case`sync`:{let e=structuredClone(t.value);return{form:e,baseline:structuredClone(e)}}case`update`:return{...e,form:t.updater(e.form)};case`saved`:{let n=structuredClone(t.value);return{form:e.form!==null&&JSON.stringify(e.form)!==JSON.stringify(t.value)?e.form:n,baseline:structuredClone(n)}}}}function tt(e){let t=(0,X.c)(10),[n,r]=(0,Z.useState)(0),i;t[0]!==e.capability||t[1]!==e.disabled?(i=e.capability===`conversation`&&(0,Q.jsx)(Ue,{disabled:e.disabled}),t[0]=e.capability,t[1]=e.disabled,t[2]=i):i=t[2];let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=()=>r(nt),t[3]=a):a=t[3];let o;t[4]!==n||t[5]!==e?(o=(0,Q.jsx)(rt,{...e,onReload:a},n),t[4]=n,t[5]=e,t[6]=o):o=t[6];let s;return t[7]!==i||t[8]!==o?(s=(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[i,o]}),t[7]=i,t[8]=o,t[9]=s):s=t[9],s}function nt(e){return e+1}function rt({capability:e,onPendingChange:t,disabled:n=!1,onReload:r}){let i=c(e=>e.language),a=u(i).voiceSettings,l=I(e=>e.captions),p=I(e=>e.setCaptions),m=!!s(e=>e.conversationId),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useReducer)(et,{form:null,baseline:null}),y=_.form,b=_.baseline,[x,S]=(0,Z.useState)(null),C=(0,Z.useRef)(!1),w=(0,Z.useRef)({}),T=(0,Z.useRef)(y);T.current=y;let E=(0,Z.useRef)({parsed:null,models:void 0}),{data:D,error:O,isLoading:A,mutate:N}=j(m),{data:P,error:F,isLoading:L,mutate:R}=k(m?o(`/api/voice/models`):null,ce,{revalidateOnFocus:!1}),{data:z,error:B,isLoading:V}=k(m?o(`/api/voice/providers`):null,ge,{revalidateOnFocus:!1}),{data:ee,error:H,isLoading:te}=k(m?o(`/api/voice/stt-providers`):null,le,{revalidateOnFocus:!1}),ne=(0,Z.useMemo)(()=>z?.providers??[],[z]),re=(0,Z.useMemo)(()=>ee?.providers??[],[ee]),U=(0,Z.useMemo)(()=>D?.payload?.config===void 0?null:me(D.payload.config),[D]),W=(0,Z.useMemo)(()=>!y||!b?!1:JSON.stringify(y)!==JSON.stringify(b),[y,b]);m?U!==null&&P!==void 0&&!C.current&&(E.current.parsed!==U||E.current.models!==P)&&(E.current={parsed:U,models:P},w.current=de(D?.payload?.config),v({type:`sync`,value:U}),S(P)):(E.current.parsed!==null||E.current.models!==void 0)&&(E.current={parsed:null,models:void 0},v({type:`reset`}),S(null),C.current=!1);let G=!!(m&&(U===null||P===void 0||z===void 0||ee===void 0)&&(A||L||V||te)),K=O instanceof Error?O.message:O?String(O):F instanceof Error?F.message:F?String(F):B instanceof Error?B.message:B?String(B):H instanceof Error?H.message:H?String(H):null,q=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>t?{...t,stt:{...t.stt,...e},...e.provider&&e.provider!==`xopc-cloud`?{voice:{...t.voice,realtime:{...t.voice.realtime,stt:void 0}}}:{}}:null})},[]),J=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>{if(!t)return null;let n=t.stt.fallback??{enabled:!1,order:[]};return{...t,stt:{...t.stt,fallback:{...n,...e}}}}})},[]),ae=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>t?{...t,voice:{...t.voice,input:{...t.voice.input,refinement:{...t.voice.input.refinement,...e}}}}:null})},[]),ue=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>t?{...t,voice:{...t.voice,languageMode:e,...e===`auto`?{language:i}:{}}}:null})},[i]),fe=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>t?{...t,voice:{...t.voice,realtime:{...t.voice.realtime,...e}}}:null})},[]),pe=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:t=>t?{...t,tts:{...t.tts,...e}}:null})},[]),Y=se({value:y,dirty:W,onSave:(0,Z.useCallback)(async t=>{try{let n=await be(t,e,w.current[e]);w.current={...w.current,...n},v({type:`saved`,value:t}),C.current=!!(T.current&&JSON.stringify(T.current)!==JSON.stringify(t))}catch(e){throw Error(e instanceof Error?e.message:a.saveError)}},[a.saveError,e])});(0,Z.useEffect)(()=>{t?.(W||Y.status===`saving`||h)},[W,Y.status,h,t]),(0,Z.useEffect)(()=>()=>t?.(!1),[t]);let he=(0,Z.useCallback)(e=>{C.current=!0,v({type:`update`,updater:()=>e})},[]);if(!m)return(0,Q.jsx)(`div`,{className:`flex flex-col gap-3`,children:(0,Q.jsx)(`p`,{className:`text-sm text-fg-muted`,children:a.needToken})});if(G)return(0,Q.jsx)(ie,{rows:4});if(!y||x===null)return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,Q.jsx)(`p`,{className:`text-sm text-fg-muted`,children:K??a.loadError}),(0,Q.jsx)(M,{type:`button`,variant:`secondary`,onClick:()=>{N(),R()},children:a.retry})]});let _e=y.stt,ve=y.tts,ye=y.voice.input.refinement,xe=Ze(a);return(0,Q.jsxs)(`fieldset`,{disabled:n||h,className:`flex min-w-0 flex-col gap-4`,onBlurCapture:Y.error?void 0:Y.onBlurCapture,children:[(0,Q.jsx)(oe,{status:Y.status,error:Y.error}),Y.error?(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsx)(M,{variant:`secondary`,onClick:Y.retry,children:i===`zh`?`重试保存`:`Retry saving`}),(0,Q.jsx)(M,{variant:`ghost`,onClick:()=>{N().then(()=>r()).catch(()=>{})},children:i===`zh`?`重新加载(放弃未保存更改)`:`Reload and discard unsaved changes`})]}):null,e===`transcription`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Me,{zh:i===`zh`}),(0,Q.jsx)(ot,{managedModel:!0,v:a,apiKeyLabels:xe,stt:_e,models:x,sttProviders:re,updateStt:q,updateSttFallback:J}),(0,Q.jsx)(at,{v:a,voice:y.voice,updateLanguageMode:ue}),(0,Q.jsxs)(`details`,{"data-voice-section":`input-processing`,className:`rounded-xl bg-surface-hover/20 p-4`,children:[(0,Q.jsxs)(`summary`,{className:`cursor-pointer text-sm font-medium text-fg`,children:[a.experience.inputProcessing,` · `,ye.mode===`off`?a.stt.refinementOff:ye.mode===`punctuation`?a.stt.refinementPunctuation:ye.mode===`light`?a.stt.refinementLight:a.setup.advanced]}),(0,Q.jsxs)(`label`,{className:`mt-4 block space-y-2 text-sm`,children:[(0,Q.jsx)(`span`,{children:a.stt.refinement}),(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:a.stt.refinementDesc}),(0,Q.jsxs)(d,{className:$(),value:ye.mode,onChange:e=>ae({mode:e.target.value}),children:[(0,Q.jsx)(f,{value:`off`,children:a.stt.refinementOff}),(0,Q.jsx)(f,{value:`punctuation`,children:a.stt.refinementPunctuation}),(0,Q.jsx)(f,{value:`light`,children:a.stt.refinementLight}),ye.mode===`custom`?(0,Q.jsx)(f,{value:`custom`,children:a.setup.advanced}):null]})]})]}),_e.provider===`xopc-cloud`?(0,Q.jsxs)(`details`,{className:`rounded-xl border border-edge p-4`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:i===`zh`?`实时听写`:`Live dictation`}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Oe,{modes:[`transcription.stream`],disabled:W||Y.status===`saving`,onPendingChange:g})})]}):null]}):e===`speech`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(ct,{managedModel:!0,v:a,apiKeyLabels:xe,tts:ve,models:x,ttsProviders:ne,updateTts:pe}),(0,Q.jsx)(it,{v:a,tts:ve,updateTts:pe})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Fe,{section:`listening`,v:a,form:y,pending:W||Y.status===`saving`||!!Y.error,onChange:he}),y.voice.realtime.defaultEngine===`omni`&&y.voice.realtime.omni?(0,Q.jsx)(Ve,{value:y.voice.realtime.omni,onChange:e=>fe({omni:e})}):null,(0,Q.jsx)(`section`,{className:`rounded-xl bg-surface-hover/20 px-4 py-5 sm:px-5`,children:(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(12rem,18rem)] sm:items-center`,children:[(0,Q.jsx)(`div`,{className:`text-sm font-semibold text-fg`,children:a.experience.pace}),(0,Q.jsxs)(d,{className:$(),value:String(y.voice.realtime.silenceDurationMs),onChange:e=>fe({silenceDurationMs:Number(e.target.value)}),children:[(0,Q.jsx)(f,{value:`800`,children:a.experience.fast}),(0,Q.jsx)(f,{value:`1200`,children:a.experience.standard}),(0,Q.jsx)(f,{value:`2000`,children:a.experience.relaxed}),[800,1200,2e3].includes(y.voice.realtime.silenceDurationMs)?null:(0,Q.jsxs)(f,{value:String(y.voice.realtime.silenceDurationMs),children:[y.voice.realtime.silenceDurationMs,` ms`]})]})]})}),(0,Q.jsxs)(`label`,{className:`flex items-center justify-between text-sm`,children:[a.experience.captions,(0,Q.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-checked":l,className:`ui-checkbox`,checked:l,onChange:e=>p(e.target.checked)})]}),y.voice.realtime.defaultEngine===`agent`&&_e.provider===`xopc-cloud`?(0,Q.jsxs)(`details`,{className:`rounded-xl border border-edge p-4`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:i===`zh`?`语音助手输出`:`Assistant speech output`}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Oe,{modes:[`speech.stream`],disabled:W||Y.status===`saving`,onPendingChange:g})})]}):null,(0,Q.jsxs)(`details`,{className:`rounded-xl border border-edge p-4`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:i===`zh`?`麦克风、扬声器与诊断`:`Microphone, speakers and diagnostics`}),(0,Q.jsxs)(`div`,{className:`mt-4 space-y-4`,children:[(0,Q.jsx)(ke,{v:a}),(0,Q.jsx)(Fe,{section:`diagnostics`,v:a,form:y,pending:W||Y.status===`saving`||!!Y.error,onChange:he})]})]})]})]})}function it(e){let t=(0,X.c)(29),{v:n,tts:r,updateTts:i}=e,a;t[0]===n.setup.readout?a=t[1]:(a=(0,Q.jsx)(`span`,{className:`font-medium`,children:n.setup.readout}),t[0]=n.setup.readout,t[1]=a);let o=n.setup.readout,s;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(s=$(),t[2]=s):s=t[2];let c=r.enabled?r.trigger:`off`,l;t[3]===i?l=t[4]:(l=e=>i({enabled:e.target.value!==`off`,trigger:e.target.value}),t[3]=i,t[4]=l);let u;t[5]===n.tts.triggerOff?u=t[6]:(u=(0,Q.jsx)(f,{value:`off`,children:n.tts.triggerOff}),t[5]=n.tts.triggerOff,t[6]=u);let p;t[7]===n.tts.triggerInbound?p=t[8]:(p=(0,Q.jsx)(f,{value:`inbound`,children:n.tts.triggerInbound}),t[7]=n.tts.triggerInbound,t[8]=p);let m;t[9]===n.tts.triggerAlways?m=t[10]:(m=(0,Q.jsx)(f,{value:`always`,children:n.tts.triggerAlways}),t[9]=n.tts.triggerAlways,t[10]=m);let h;t[11]===n.tts.triggerTagged?h=t[12]:(h=(0,Q.jsx)(f,{value:`tagged`,children:n.tts.triggerTagged}),t[11]=n.tts.triggerTagged,t[12]=h);let g;t[13]!==c||t[14]!==l||t[15]!==u||t[16]!==p||t[17]!==m||t[18]!==h||t[19]!==n.setup.readout?(g=(0,Q.jsxs)(d,{"aria-label":o,className:s,value:c,onChange:l,children:[u,p,m,h]}),t[13]=c,t[14]=l,t[15]=u,t[16]=p,t[17]=m,t[18]=h,t[19]=n.setup.readout,t[20]=g):g=t[20];let _;t[21]!==a||t[22]!==g?(_=(0,Q.jsxs)(`label`,{className:`block space-y-2 text-sm`,children:[a,g]}),t[21]=a,t[22]=g,t[23]=_):_=t[23];let v;t[24]===n.setup.readoutHint?v=t[25]:(v=(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:n.setup.readoutHint}),t[24]=n.setup.readoutHint,t[25]=v);let y;return t[26]!==_||t[27]!==v?(y=(0,Q.jsxs)(`section`,{className:`space-y-2 rounded-xl bg-surface-hover/20 p-4 sm:p-5`,children:[_,v]}),t[26]=_,t[27]=v,t[28]=y):y=t[28],y}function at(e){let t=(0,X.c)(22),{v:n,voice:r,updateLanguageMode:i}=e,a;t[0]===n.language.title?a=t[1]:(a=(0,Q.jsx)(`div`,{className:`text-sm font-semibold text-fg`,children:n.language.title}),t[0]=n.language.title,t[1]=a);let o=r.languageMode===`auto`?n.language.autoDescription:n.language.manualDescription,s;t[2]===o?s=t[3]:(s=(0,Q.jsx)(`p`,{className:`mt-1 text-xs text-fg-muted`,children:o}),t[2]=o,t[3]=s);let c;t[4]!==a||t[5]!==s?(c=(0,Q.jsxs)(`div`,{children:[a,s]}),t[4]=a,t[5]=s,t[6]=c):c=t[6];let l;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(l=$(),t[7]=l):l=t[7];let u;t[8]===i?u=t[9]:(u=e=>i(e.target.value),t[8]=i,t[9]=u);let p;t[10]===n.language.auto?p=t[11]:(p=(0,Q.jsx)(f,{value:`auto`,children:n.language.auto}),t[10]=n.language.auto,t[11]=p);let m;t[12]===n.language.manual?m=t[13]:(m=(0,Q.jsx)(f,{value:`manual`,children:n.language.manual}),t[12]=n.language.manual,t[13]=m);let h;t[14]!==u||t[15]!==p||t[16]!==m||t[17]!==r.languageMode?(h=(0,Q.jsxs)(d,{className:l,value:r.languageMode,onChange:u,children:[p,m]}),t[14]=u,t[15]=p,t[16]=m,t[17]=r.languageMode,t[18]=h):h=t[18];let g;return t[19]!==c||t[20]!==h?(g=(0,Q.jsx)(`section`,{className:`rounded-xl bg-surface-hover/20 px-4 py-5 sm:px-5`,children:(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(12rem,18rem)] sm:items-center`,children:[c,h]})}),t[19]=c,t[20]=h,t[21]=g):g=t[21],g}function ot(e){let t=(0,X.c)(65),{v:n,apiKeyLabels:r,stt:i,models:a,sttProviders:o,updateStt:s,updateSttFallback:c,managedModel:l}=e,u=l!==void 0&&l,p;if(t[0]!==o){let e=new Set;p=[];for(let t of o)e.has(t.id)||(e.add(t.id),p.push(t));t[0]=o,t[1]=p}else p=t[1];let m=p,g,_,v,b;if(t[2]!==a||t[3]!==m||t[4]!==i.provider||t[5]!==i.providers){g=m.find(e=>e.id===i.provider);let e;t[10]!==i.provider||t[11]!==i.providers?(e=i.providers?.[i.provider]??{},t[10]=i.provider,t[11]=i.providers,t[12]=e):e=t[12],v=e,_=a?.stt?.[i.provider]?.length?a.stt[i.provider]:g?.models??[],b=g?.fields.find(st),t[2]=a,t[3]=m,t[4]=i.provider,t[5]=i.providers,t[6]=g,t[7]=_,t[8]=v,t[9]=b}else g=t[6],_=t[7],v=t[8],b=t[9];let x=b,S=typeof v.model==`string`?v.model:void 0,C=S??(typeof x?.defaultValue==`string`?x.defaultValue:_[0]?.id),w;t[13]!==i.provider||t[14]!==i.providers||t[15]!==s?(w=e=>{s({providers:{...i.providers??{},[i.provider]:{...i.providers?.[i.provider]??{},...e}}})},t[13]=i.provider,t[14]=i.providers,t[15]=s,t[16]=w):w=t[16];let T=w,E,D;t[17]!==S||t[18]!==C||t[19]!==u||t[20]!==x||t[21]!==T?(E=()=>{!u&&x&&C&&S!==C&&T({model:C})},D=[u,S,C,x,T],t[17]=S,t[18]=C,t[19]=u,t[20]=x,t[21]=T,t[22]=E,t[23]=D):(E=t[22],D=t[23]),(0,Z.useEffect)(E,D);let O;t[24]===Symbol.for(`react.memo_cache_sentinel`)?(O=(0,Q.jsx)(h,{"aria-hidden":`true`,className:`size-4 text-accent`,strokeWidth:1.75}),t[24]=O):O=t[24];let k;t[25]===n.stt.title?k=t[26]:(k=(0,Q.jsxs)(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-fg`,children:[O,n.stt.title]}),t[25]=n.stt.title,t[26]=k);let A;t[27]===n.stt.enable?A=t[28]:(A=(0,Q.jsx)(`span`,{children:n.stt.enable}),t[27]=n.stt.enable,t[28]=A);let j;t[29]===s?j=t[30]:(j=e=>s({enabled:e.target.checked}),t[29]=s,t[30]=j);let M;t[31]!==i.enabled||t[32]!==j?(M=(0,Q.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-checked":i.enabled,className:`ui-checkbox`,checked:i.enabled,onChange:j}),t[31]=i.enabled,t[32]=j,t[33]=M):M=t[33];let N;t[34]!==M||t[35]!==A?(N=(0,Q.jsxs)(`label`,{className:`flex min-h-10 items-center gap-2 text-xs text-fg-muted`,children:[A,M]}),t[34]=M,t[35]=A,t[36]=N):N=t[36];let P;t[37]!==N||t[38]!==k?(P=(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[k,N]}),t[37]=N,t[38]=k,t[39]=P):P=t[39];let F;t[40]===n.stt.description?F=t[41]:(F=(0,Q.jsx)(`p`,{className:`mt-1 text-xs text-fg-muted`,children:n.stt.description}),t[40]=n.stt.description,t[41]=F);let I;t[42]!==P||t[43]!==F?(I=(0,Q.jsxs)(`div`,{className:`mb-4`,children:[P,F]}),t[42]=P,t[43]=F,t[44]=I):I=t[44];let L;t[45]!==g?.fields||t[46]!==r||t[47]!==C||t[48]!==u||t[49]!==_||t[50]!==m||t[51]!==v||t[52]!==i.enabled||t[53]!==i.fallback?.enabled||t[54]!==i.provider||t[55]!==T||t[56]!==s||t[57]!==c||t[58]!==n?(L=i.enabled?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[u?null:(0,Q.jsxs)(`div`,{className:y(`flex flex-col gap-1.5`,We),children:[(0,Q.jsx)(gt,{children:n.stt.provider}),(0,Q.jsx)(d,{"aria-label":n.stt.provider,className:$(),value:i.provider,onChange:e=>s({provider:e.target.value}),children:m.map(e=>(0,Q.jsxs)(f,{value:e.id,children:[Je(e.id,n),e.configured?``:` *`]},e.id))})]}),(0,Q.jsx)(lt,{managedModel:u,kind:`stt`,providerId:i.provider,fields:g?.fields??[],providerSlice:v,models:_,currentModel:C,apiKeyLabels:r,onPatch:T})]}),i.provider===`alibaba`?(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:n.setup.keyHint}):null,(0,Q.jsxs)(`details`,{className:`rounded-lg border border-edge p-3`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium text-fg`,children:n.stt.fallback}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded-xl bg-surface-hover/50 px-3 py-2.5 dark:bg-surface-hover/35`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`text-sm font-medium text-fg`,children:n.stt.fallback}),(0,Q.jsx)(`p`,{className:`text-xs text-fg-muted`,children:n.stt.fallbackDesc})]}),(0,Q.jsx)(`input`,{type:`checkbox`,className:`ui-checkbox`,checked:i.fallback?.enabled??!1,onChange:e=>c({enabled:e.target.checked})})]})]})]}):null,t[45]=g?.fields,t[46]=r,t[47]=C,t[48]=u,t[49]=_,t[50]=m,t[51]=v,t[52]=i.enabled,t[53]=i.fallback?.enabled,t[54]=i.provider,t[55]=T,t[56]=s,t[57]=c,t[58]=n,t[59]=L):L=t[59];let R;t[60]===L?R=t[61]:(R=(0,Q.jsx)(`div`,{className:`space-y-4`,children:L}),t[60]=L,t[61]=R);let z;return t[62]!==I||t[63]!==R?(z=(0,Q.jsxs)(`section`,{className:`rounded-xl bg-surface-hover/20 px-4 py-5 sm:px-5`,children:[I,R]}),t[62]=I,t[63]=R,t[64]=z):z=t[64],z}function st(e){return e.key===`model`}function ct({v:e,apiKeyLabels:t,tts:n,models:r,ttsProviders:i,updateTts:a,managedModel:o=!1}){let[s,c]=(0,Z.useState)(e.tts.test.sampleText),[l,u]=(0,Z.useState)({status:`idle`}),p=(0,Z.useRef)(null),h=(0,Z.useRef)(null),b=(0,Z.useRef)(null),x=(0,Z.useCallback)(()=>{b.current&&(K(b.current),b.current.abort()),b.current=null,p.current?.pause(),p.current=null,h.current&&=(URL.revokeObjectURL(h.current),null)},[]),S=(0,Z.useMemo)(()=>{let e=new Set,t=[];for(let n of i)e.has(n.id)||(e.add(n.id),t.push(n));return t},[i]),C=S.find(e=>e.id===n.provider),w=n.providers?.[n.provider]??{},T=r?.tts?.[n.provider]?.length?r.tts[n.provider]:C?.models??[],E=C?.fields.find(e=>e.key===`model`),D=C?.fields.find(e=>e.key===`voice`),O=typeof w.model==`string`?w.model:void 0,A=O??(typeof E?.defaultValue==`string`?E.defaultValue:T[0]?.id),j=T.find(e=>e.id===A),N=r?.ttsVoices?.[n.provider]?.length?r.ttsVoices[n.provider]:C?.voices??[],{data:P=[]}=k(A?`voice:tts:${n.provider}:${A}`:null,()=>Y(n.provider,A??``),{revalidateOnFocus:!1}),F=P.length>0?P:N,I=typeof w.voice==`string`?w.voice:void 0,L=I??F.find(e=>e.id===j?.tts?.defaultVoice)?.id??(typeof D?.defaultValue==`string`?D.defaultValue:F[0]?.id),R=(C?.fields??[]).filter(e=>(e.key!==`speed`||j?.tts?.speed!==!1)&&(e.key!==`instructions`||j?.tts?.instructions!==!1)),z=(0,Z.useCallback)(e=>{a({providers:{...n.providers??{},[n.provider]:{...n.providers?.[n.provider]??{},...e}}})},[n.provider,n.providers,a]);(0,Z.useEffect)(()=>{if(o)return;let e={};E&&A&&O!==A&&(e.model=A),D&&L&&I!==L&&(e.voice=L),Object.keys(e).length>0&&z(e)},[o,O,I,A,L,E,z,D]),(0,Z.useEffect)(()=>()=>x(),[x]);let B=(0,Z.useCallback)(e=>{a({provider:e}),u({status:`idle`})},[a]),V=(0,Z.useCallback)(async()=>{let t=s.trim();if(!t){u({status:`error`,message:e.tts.test.emptyText});return}x();let r=new AbortController;b.current=r,G(r,()=>{x(),u({status:`idle`})}),u({status:`loading`});try{let i=await fe({text:t,provider:n.provider,providerConfig:w,...A?{model:A}:{},...L?{voice:L}:{}},r.signal);if(r.signal.aborted)return;let a=qe(i.audio,i.mimeType);h.current=a;let o=new Audio(a);p.current=o;let s=[i.provider,i.format,i.latencyMs===void 0?void 0:`${i.latencyMs}ms`,Ke(i.audioSize)].filter(Boolean).join(` · `);o.addEventListener(`ended`,()=>{K(r),r.signal.aborted||u({status:`done`,summary:s})},{once:!0}),o.addEventListener(`error`,()=>{K(r),r.signal.aborted||u({status:`error`,message:e.tts.test.playFailed})},{once:!0}),await o.play(),r.signal.aborted||u({status:`playing`,summary:s})}catch(e){if(r.signal.aborted)return;x(),u({status:`error`,message:e instanceof Error?e.message:String(e)})}},[A,L,w,x,s,n.provider,e.tts.test.emptyText,e.tts.test.playFailed]);return(0,Q.jsxs)(`section`,{className:`rounded-xl bg-surface-hover/20 px-4 py-5 sm:px-5`,children:[(0,Q.jsxs)(`div`,{className:`mb-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-fg`,children:[(0,Q.jsx)(v,{className:`size-4 text-accent`,strokeWidth:1.75}),e.tts.title]}),(0,Q.jsx)(`p`,{className:`mt-1 text-xs text-fg-muted`,children:e.tts.description})]}),(0,Q.jsx)(`div`,{className:`space-y-4`,children:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:o?null:(0,Q.jsxs)(`div`,{className:y(`flex flex-col gap-1.5`,We),children:[(0,Q.jsx)(gt,{children:e.tts.provider}),(0,Q.jsx)(d,{"aria-label":e.tts.provider,className:$(),value:n.provider,onChange:e=>B(e.target.value),children:S.map(t=>(0,Q.jsx)(f,{value:t.id,children:Ye(t.id,e)},t.id))}),(0,Q.jsxs)(`p`,{className:`text-xs text-fg-subtle`,children:[C?.configured?e.tts.configured:C?.diagnostics.requiresApiKey?`${e.tts.needsKey} · ${C.diagnostics.envKeys?.join(`, `)??e.stt.apiKey}`:e.tts.noKeyNeeded,` · `,C?.description??Xe(n.provider,e)]})]})}),(0,Q.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:(0,Q.jsx)(lt,{managedModel:o,kind:`tts`,providerId:n.provider,fields:R,providerSlice:w,models:T,voices:F,currentModel:A,currentVoice:L,apiKeyLabels:t,onPatch:z,resetVoiceOnModelChange:!0})}),(0,Q.jsxs)(`details`,{className:`rounded-xl bg-surface-panel/80 p-3`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium text-fg`,children:e.tts.test.title}),(0,Q.jsxs)(`div`,{className:`mt-3`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`p`,{className:`mt-1 text-xs text-fg-muted`,children:e.tts.test.description})}),(0,Q.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Q.jsxs)(M,{type:`button`,variant:`primary`,onClick:()=>void V(),disabled:l.status===`loading`,className:`h-9`,children:[l.status===`loading`?(0,Q.jsx)(m,{className:`size-4 animate-spin`}):(0,Q.jsx)(g,{className:`size-4`}),l.status===`loading`?e.tts.test.generating:e.tts.test.play]}),(0,Q.jsxs)(M,{type:`button`,variant:`secondary`,onClick:()=>{x(),u(e=>e.status===`playing`?{status:`done`,summary:e.summary}:{status:`idle`})},disabled:l.status!==`playing`,className:`h-9`,children:[(0,Q.jsx)(_,{className:`size-4`}),e.tts.test.stop]})]})]}),(0,Q.jsxs)(`details`,{className:`mt-3`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-xs text-fg-muted`,children:e.setup.sampleText}),(0,Q.jsx)(`textarea`,{className:y(Ge(),`mt-3 min-h-20 resize-y`),value:s,onChange:e=>c(e.target.value),maxLength:1e3})]}),(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center justify-between gap-2 text-xs`,children:[(0,Q.jsxs)(`span`,{className:`text-fg-subtle`,children:[s.length,`/1000`]}),l.status===`playing`||l.status===`done`?(0,Q.jsxs)(`span`,{className:`text-emerald-700 dark:text-emerald-200`,children:[l.status===`playing`?e.tts.test.playing:e.tts.test.ready,` · `,l.summary]}):null,l.status===`error`?(0,Q.jsx)(`span`,{className:`text-red-600 dark:text-red-400`,children:l.message}):null]})]})]})]})})]})}function lt(e){let t=(0,X.c)(48),{kind:n,providerId:r,fields:i,providerSlice:a,models:o,voices:s,currentModel:l,currentVoice:p,apiKeyLabels:m,onPatch:h,resetVoiceOnModelChange:g,managedModel:_}=e,v;t[0]===s?v=t[1]:(v=s===void 0?[]:s,t[0]=s,t[1]=v);let b=v,x=g!==void 0&&g,S=_!==void 0&&_,C=c(pt),w;t[2]===C?w=t[3]:(w=u(C),t[2]=C,t[3]=w);let T=w.voiceSettings,E=S,D=ft,O=dt,k,A,j;if(t[4]!==m||t[5]!==l||t[6]!==p||t[7]!==i||t[8]!==n||t[9]!==C||t[10]!==S||t[11]!==o||t[12]!==h||t[13]!==r||t[14]!==a||t[15]!==x||t[16]!==E||t[17]!==T||t[18]!==b){let e;t[22]===E?e=t[23]:(e=e=>!E||e.key!==`model`&&!O(e),t[22]=E,t[23]=e);let s=i.filter(e),c;t[24]===Symbol.for(`react.memo_cache_sentinel`)?(c=e=>!D(e),t[24]=c):c=t[24];let u=s.filter(c),g;t[25]!==m||t[26]!==l||t[27]!==p||t[28]!==n||t[29]!==C||t[30]!==S||t[31]!==o||t[32]!==h||t[33]!==r||t[34]!==a||t[35]!==x||t[36]!==T||t[37]!==b?(g=e=>e.map(e=>S&&e.key===`model`?null:e.key===`apiKey`?(0,Q.jsxs)(`div`,{className:y(`flex flex-col gap-1.5`,We),children:[(0,Q.jsx)(gt,{htmlFor:`voice-${n}-${r}-api-key`,children:T.stt.apiKey}),(0,Q.jsx)(xe,{kind:n,providerId:r,fieldId:`voice-${n}-${r}-api-key`,value:typeof a.apiKey==`string`?a.apiKey:``,onChange:e=>h({apiKey:e}),labels:m,placeholder:e.placeholder}),e.description?(0,Q.jsx)(`p`,{className:`text-xs text-fg-subtle`,children:e.description}):null]},e.key):e.key===`model`&&o.length>0?(0,Q.jsxs)(`div`,{className:y(`flex flex-col gap-1.5`,We),children:[(0,Q.jsx)(gt,{htmlFor:`voice-${n}-${r}-model`,children:T.stt.model}),(0,Q.jsx)(d,{id:`voice-${n}-${r}-model`,className:$(),value:l??``,onChange:e=>h({model:e.target.value,...x?{voice:void 0}:{}}),children:[...o].sort(U).map(ut)})]},e.key):e.key===`voice`&&b.length>0?(0,Q.jsxs)(`div`,{className:y(`flex flex-col gap-1.5`,We),children:[(0,Q.jsx)(gt,{htmlFor:`voice-${n}-${r}-voice`,children:T.tts.voice}),(0,Q.jsxs)(d,{id:`voice-${n}-${r}-voice`,className:$(),value:p??``,onChange:e=>h({voice:e.target.value}),children:[p&&!b.some(e=>e.id===p)?(0,Q.jsxs)(f,{value:p,children:[p,` · unavailable`]}):null,b.map(e=>(0,Q.jsxs)(f,{value:e.id,children:[W(e,C),e.gender?` · ${e.gender===`female`?`女声`:`男声`}`:``,e.style?` · ${e.style}`:``]},e.id))]}),b.find(e=>e.id===p)?.description?(0,Q.jsx)(`p`,{className:`text-xs text-fg-subtle`,children:b.find(e=>e.id===p)?.description}):null]},e.key):(0,Q.jsx)(mt,{fieldId:`voice-${n}-${r}-${e.key}`,field:e,value:Qe(a,e),onChange:t=>h({[e.key]:t}),className:e.type===`textarea`?`sm:col-span-2`:We},e.key)),t[25]=m,t[26]=l,t[27]=p,t[28]=n,t[29]=C,t[30]=S,t[31]=o,t[32]=h,t[33]=r,t[34]=a,t[35]=x,t[36]=T,t[37]=b,t[38]=g):g=t[38];let _=g;t[39]!==i||t[40]!==n||t[41]!==C||t[42]!==E?(k=E&&i.some(O)?(0,Q.jsx)(je,{className:`text-sm text-accent-fg hover:underline`,to:`/settings/capabilities/models?tab=services&configure=${n===`stt`?`transcription`:`speech`}`,children:C===`zh`?`管理服务连接`:`Manage service connection`}):null,t[39]=i,t[40]=n,t[41]=C,t[42]=E,t[43]=k):k=t[43],A=_(s.filter(D)),j=u.length?(0,Q.jsxs)(`details`,{className:`rounded-lg border border-edge p-3 sm:col-span-2`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium text-fg`,children:T.experience.providerOptions}),(0,Q.jsx)(`div`,{className:`mt-3 grid gap-3 sm:grid-cols-2`,children:_(u)})]}):null,t[4]=m,t[5]=l,t[6]=p,t[7]=i,t[8]=n,t[9]=C,t[10]=S,t[11]=o,t[12]=h,t[13]=r,t[14]=a,t[15]=x,t[16]=E,t[17]=T,t[18]=b,t[19]=k,t[20]=A,t[21]=j}else k=t[19],A=t[20],j=t[21];let M;return t[44]!==k||t[45]!==A||t[46]!==j?(M=(0,Q.jsxs)(Q.Fragment,{children:[k,A,j]}),t[44]=k,t[45]=A,t[46]=j,t[47]=M):M=t[47],M}function ut(e){return(0,Q.jsx)(f,{value:e.id,children:e.name},e.id)}function dt(e){return e.secret||e.type===`password`||[`apiKey`,`baseUrl`,`region`,`groupId`].includes(e.key)}function ft(e){return e.required||[`apiKey`,`model`,`voice`].includes(e.key)}function pt(e){return e.language}function mt(e){let t=(0,X.c)(37),{fieldId:n,field:r,value:i,onChange:a,className:o}=e,s=n??`voice-schema-field-${r.key}`,c=r.description;if(r.type===`boolean`){let e;t[0]===o?e=t[1]:(e=y(`flex items-center justify-between gap-3 rounded-xl bg-surface-hover/50 px-3 py-2.5 dark:bg-surface-hover/35`,o),t[0]=o,t[1]=e);let n;t[2]===r.label?n=t[3]:(n=(0,Q.jsx)(`span`,{className:`block text-sm font-medium text-fg`,children:r.label}),t[2]=r.label,t[3]=n);let s;t[4]===c?s=t[5]:(s=c?(0,Q.jsx)(`span`,{className:`mt-1 block text-xs text-fg-subtle`,children:c}):null,t[4]=c,t[5]=s);let l;t[6]!==n||t[7]!==s?(l=(0,Q.jsxs)(`span`,{children:[n,s]}),t[6]=n,t[7]=s,t[8]=l):l=t[8];let u=!!i,d;t[9]!==r||t[10]!==a?(d=e=>a($e(r,e.target.checked)),t[9]=r,t[10]=a,t[11]=d):d=t[11];let f;t[12]!==u||t[13]!==d?(f=(0,Q.jsx)(`input`,{type:`checkbox`,className:`ui-checkbox`,checked:u,onChange:d}),t[12]=u,t[13]=d,t[14]=f):f=t[14];let p;return t[15]!==e||t[16]!==l||t[17]!==f?(p=(0,Q.jsxs)(`label`,{className:e,children:[l,f]}),t[15]=e,t[16]=l,t[17]=f,t[18]=p):p=t[18],p}let l=typeof i==`boolean`?``:String(i),u;t[19]===o?u=t[20]:(u=y(`flex flex-col gap-1.5`,o),t[19]=o,t[20]=u);let f;t[21]!==r.label||t[22]!==s?(f=(0,Q.jsx)(gt,{htmlFor:s,children:r.label}),t[21]=r.label,t[22]=s,t[23]=f):f=t[23];let m;t[24]!==o||t[25]!==r||t[26]!==l||t[27]!==s||t[28]!==a?(m=r.type===`select`?(0,Q.jsx)(d,{id:s,className:$(),value:l,required:r.required,onChange:e=>a($e(r,e.target.value)),children:(r.options??[]).map(ht)}):r.type===`textarea`?(0,Q.jsx)(`textarea`,{id:s,className:y(Ge(),`min-h-24 resize-y`),value:l,required:r.required,placeholder:r.placeholder,onChange:e=>a($e(r,e.target.value))}):r.type===`password`?(0,Q.jsx)(p,{id:s,className:o,value:l,onChange:e=>a($e(r,e)),placeholder:r.placeholder,labels:re}):r.type===`number`?(0,Q.jsx)(ae,{id:s,className:Ge(),autoComplete:r.secret?`new-password`:`off`,spellCheck:!1,value:l,required:r.required,allowEmpty:!r.required,placeholder:r.placeholder,min:r.min,max:r.max,step:r.step,onChange:e=>a($e(r,e.target.value))}):(0,Q.jsx)(`input`,{id:s,className:Ge(),type:`text`,autoComplete:r.secret?`new-password`:`off`,spellCheck:!1,value:l,required:r.required,placeholder:r.placeholder,min:r.min,max:r.max,step:r.step,onChange:e=>a($e(r,e.target.value))}),t[24]=o,t[25]=r,t[26]=l,t[27]=s,t[28]=a,t[29]=m):m=t[29];let h;t[30]===c?h=t[31]:(h=c?(0,Q.jsx)(`p`,{className:`text-xs text-fg-subtle`,children:c}):null,t[30]=c,t[31]=h);let g;return t[32]!==u||t[33]!==f||t[34]!==m||t[35]!==h?(g=(0,Q.jsxs)(`div`,{className:u,children:[f,m,h]}),t[32]=u,t[33]=f,t[34]=m,t[35]=h,t[36]=g):g=t[36],g}function ht(e){return(0,Q.jsx)(f,{value:e.id,children:e.name},e.id)}function gt(e){let t=(0,X.c)(3),{children:n,htmlFor:r}=e,i;return t[0]!==n||t[1]!==r?(i=r?(0,Q.jsx)(`label`,{htmlFor:r,className:`text-sm font-medium text-fg`,children:n}):(0,Q.jsx)(`div`,{className:`text-sm font-medium text-fg`,children:n}),t[0]=n,t[1]=r,t[2]=i):i=t[2],i}export{Ae as n,tt as t};
|
package/dist/gateway/static/root/assets/{workspace-api-g-wCKoQU.js → workspace-api-CFPK3JR6.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/session-manager-
|
|
2
|
-
import{t as e}from"./preload-helper-Czpn1I53.js";import{a as t,i as n}from"./locale-store-Cit_aHqC.js";import{i as r,n as i,r as a,t as o}from"./files-BNL4kkSB.js";async function s(e){let t=await e.json().catch(()=>null);return Error(t?.error?.message??`HTTP ${e.status}`)}async function c(e,r){let i=await t(n(e),r);if(!i.ok)throw await s(i);return i.json()}async function l(t){if(!t?.projectId&&t?.conversationId){let{SessionManager:n}=await e(async()=>{let{SessionManager:e}=await import(`./session-manager-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/session-manager-DzSlogQc.js","assets/rolldown-runtime-aKtaBQYM.js","assets/diagnostics-Bo0Z42P_.js","assets/locale-store-Cit_aHqC.js","assets/vendor-react-BOUWij0V.js","assets/messages-DQveK9sk.js","assets/schemas-CCWMleym.js","assets/turn-outcome-BSbEJx8h.js","assets/product-delivery-4gEqUIsK.js","assets/session-api-CkOliupg.js","assets/gateway-startup-retry-2jU7zCyx.js","assets/local-session-drafts-CgAuYyKi.js","assets/tool-activity-BtJkgjFf.js","assets/attachment-utils-core-BPYdUI6y.js","assets/gateway-realtime-BnwNxbyc.js","assets/gateway-realtime-store-BpnGXAhi.js","assets/registry-api-BEnvt9-6.js","assets/preload-helper-Czpn1I53.js","assets/agents-admin-api-BL8lN8gP.js","assets/gateway-config-swr-DVXDJNCI.js","assets/vendor-swr-CdRzEUwF.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-Czpn1I53.js";import{a as t,i as n}from"./locale-store-Cit_aHqC.js";import{i as r,n as i,r as a,t as o}from"./files-BNL4kkSB.js";async function s(e){let t=await e.json().catch(()=>null);return Error(t?.error?.message??`HTTP ${e.status}`)}async function c(e,r){let i=await t(n(e),r);if(!i.ok)throw await s(i);return i.json()}async function l(t){if(!t?.projectId&&t?.conversationId){let{SessionManager:n}=await e(async()=>{let{SessionManager:e}=await import(`./session-manager-DzSlogQc.js`).then(e=>e.n);return{SessionManager:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]));await new n().materialize(t.conversationId,`session_resources`)}let n=t?.projectId?{kind:`project`,id:t.projectId}:t?.conversationId?{kind:`session`,id:t.conversationId}:t?.agentId?{kind:`agent`,id:t.agentId}:null;if(n){let e=await c(`/api/files/contexts/${n.kind}/${encodeURIComponent(n.id)}`);return r.parse(e.space)}let i=await c(`/api/files/default-space`);return r.parse(i.space)}function u(e){return{id:e.id,name:e.name,path:e.relativePath,isDirectory:e.kind===`directory`,mimeType:e.mimeType,revision:e.revision}}async function d(e,t){let n=await l(t),r=await c(`/api/files/resolve`,{method:`POST`,body:JSON.stringify({spaceId:n.id,path:e,taskRunId:t?.taskRunId})});return i.parse(r.resource)}async function f(e,t){return d(e,t)}async function p(e=``,t){let n=await l(t),r=new URLSearchParams;return e&&r.set(`path`,e),{entries:a.parse(await c(`/api/files/spaces/${encodeURIComponent(n.id)}/children${r.size?`?${r}`:``}`)).items.map(u)}}async function m(e=``,t){return(await p(e,t)).entries}async function h(e){let t=await l(e);return u(o.parse(await c(`/api/files/spaces/${encodeURIComponent(t.id)}/root`)).resource)}async function g(e,t,n=50){let r=await l(t),i=new URLSearchParams({q:e.trim(),limit:String(n),spaceId:r.id});return a.parse(await c(`/api/files/search?${i}`)).items.map(u)}async function _(e,r,i){if(i){let r=await t(n(`/api/files/${encodeURIComponent(i.id)}/content`)),a=r.headers.get(`ETag`);if(r.ok&&a)return{content:await r.text(),path:e,mtimeMs:i.mtimeMs,revision:a,fileId:i.id};if(!r.ok&&r.status!==404)throw await s(r)}let a=await d(e,r),o=await t(n(`/api/files/${encodeURIComponent(a.id)}/content`));if(!o.ok)throw await s(o);return{content:await o.text(),path:a.relativePath,mtimeMs:a.modifiedAt,revision:o.headers.get(`ETag`)??a.revision,fileId:a.id}}async function v(e,t){let n;try{n=await l(t)}catch{return null}try{let r=await c(`/api/files/resolve`,{method:`POST`,body:JSON.stringify({spaceId:n.id,path:e,taskRunId:t?.taskRunId})}),a=i.parse(r.resource);return{absolutePath:r.absolutePath,fileId:a.id,inputPath:e,displayName:a.name,scope:r.absolutePath?`external`:`workspace`,locationKind:r.absolutePath?`host`:`workspace`,exists:!0,isDirectory:a.kind===`directory`,workspaceRelativePath:a.relativePath,capabilities:a.capabilities.filter(e=>e===`preview`||e===`edit`),mtimeMs:a.modifiedAt}}catch{try{return(await c(`/api/files/resolve-reference`,{method:`POST`,body:JSON.stringify({spaceId:n.id,path:e,conversationId:t?.conversationId})})).reference}catch{return null}}}async function y(e,t,n){return await c(`/api/files/references/${encodeURIComponent(e)}/action`,{method:`POST`,body:JSON.stringify({action:t,conversationId:n?.conversationId})})}async function b(e,r){let i=await d(e,r),a=await t(n(`/api/files/${encodeURIComponent(i.id)}/content`),{headers:{Accept:`*/*`}});if(!a.ok)throw await s(a);return a.blob()}async function x(e,t,n,r){let a=await d(e,n),o=await c(`/api/files/${encodeURIComponent(a.id)}/content`,{method:`PUT`,body:JSON.stringify({content:t,revision:r??a.revision})}),s=i.parse(o.resource);return{path:s.relativePath,mtimeMs:s.modifiedAt,revision:s.revision}}async function S(e,r=``,i){let a=await l(i),c=new FormData;c.set(`directory`,r),c.set(`file`,e);let d=await t(n(`/api/files/spaces/${encodeURIComponent(a.id)}/upload`),{method:`POST`,body:c});if(!d.ok)throw await s(d);return u(o.parse(await d.json()).resource)}async function C(e){let r=await t(n(`/api/files/${encodeURIComponent(e)}`),{method:`DELETE`});if(!r.ok)throw await s(r)}function w(e,t){let n=new Blob([t],{type:`text/plain;charset=utf-8`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=e,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}function T(e,t,n){let r=new Blob([t],{type:n}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}export{b as a,_ as c,f as d,g as f,p as i,y as l,x as m,T as n,h as o,S as p,w as r,m as s,C as t,v as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,n as t}from"./rolldown-runtime-aKtaBQYM.js";import{a as n,t as r}from"./vendor-react-BOUWij0V.js";import{n as i}from"./locale-store-Cit_aHqC.js";import{t as a}from"./messages-DQveK9sk.js";import{n as ee,t as o}from"./use-file-preview-expanded-
|
|
1
|
+
import{i as e,n as t}from"./rolldown-runtime-aKtaBQYM.js";import{a as n,t as r}from"./vendor-react-BOUWij0V.js";import{n as i}from"./locale-store-Cit_aHqC.js";import{t as a}from"./messages-DQveK9sk.js";import{n as ee,t as o}from"./use-file-preview-expanded-1ZjXWaYM.js";import{c as s,h as c,l,s as u}from"./preview-runtime-pJGZe5Jx.js";import{n as d}from"./share-link-dialog-BxFk4-4u.js";import{t as f}from"./cn-0WouolD0.js";import{t as p}from"./skeleton-DzdOeGYz.js";import{r as m}from"./right-workspace-store-NXMrEuwH.js";import{t as h}from"./copy-to-clipboard-HOJ79TWv.js";import{t as g}from"./composer-notifications-B0IZsy8x.js";import{i as _}from"./theme-store-C1MxmBg7.js";import{n as v}from"./electron-env-DHOGevH3.js";import{a as y,t as b}from"./file-preview-surface-CeFFZo3a.js";var x=e(n(),1);async function S(e,t){try{let n=await e();return n&&`ok`in n&&n.code===`CANCELED`?!1:n&&(`ok`in n?n.ok:n.success)?!0:(g(`warning`,n?.error||t,void 0,{duration:4e3}),!1)}catch{return g(`warning`,t,void 0,{duration:4e3}),!1}}var C=new Map;function w(e,t){return C.set(e,t),()=>{C.get(e)===t&&C.delete(e)}}async function T(e){return await C.get(e)?.()??!0}var E=t({WorkspaceFilePreviewPanel:()=>A}),D=r(),O=new Intl.DateTimeFormat(`zh-CN`,{dateStyle:`medium`,timeStyle:`short`}),k=new Intl.DateTimeFormat(`en`,{dateStyle:`medium`,timeStyle:`short`});function te(e,t){return(t===`zh`?O:k).format(new Date(e))}function A({filePath:e,tabId:t,showEmbeddedClose:n=!1,active:r=!0,onClose:C,targetLine:T,resultRevision:E,resolvedFile:O,projectId:k,conversationId:A,agentId:j}){let M=i(e=>e.language),N=a(M),P=_(e=>e.resolved),F=l({filePath:e,projectId:k,conversationId:A,agentId:j,resolvedFile:O,initialEditMode:t?u(t).sourceEditMode:!1}),{dialogOpen:I,loading:L,result:R,error:z,pendingParams:B,createShareLink:V,confirmShareLink:H,handleOpenChange:U}=y(),[W,G]=(0,x.useState)(!1),[K,q]=(0,x.useState)(!1),{expanded:J,setExpanded:Y}=o(!!e,I);(0,x.useEffect)(()=>{t&&s(t,{sourceEditMode:F.sourceEditMode})},[F.sourceEditMode,t]),(0,x.useEffect)(()=>{if(t)return w(t,F.flushSource)},[F.flushSource,t]),(0,x.useEffect)(()=>{t&&F.fileResourceId&&m.getState().resolveFileIdentity(t,F.fileResourceId)},[F.fileResourceId,t]),(0,x.useEffect)(()=>{t&&m.getState().setFileStatus(t,F.saveStatus===`error`?`error`:F.dirty?`dirty`:null)},[F.dirty,F.saveStatus,t]),(0,x.useEffect)(()=>{let e=()=>{document.visibilityState!==`hidden`&&F.checkForUpdates()};return window.addEventListener(`focus`,e),window.addEventListener(`workspace-refresh-files`,e),window.addEventListener(`agent-run-ended`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`workspace-refresh-files`,e),window.removeEventListener(`agent-run-ended`,e),document.removeEventListener(`visibilitychange`,e)}},[F.checkForUpdates]);let X=e?c(e):``,Z=[`text`,`markdown`,`code`,`html`].includes(F.descriptor.type),ne=(0,x.useCallback)(async()=>{if(e){if(await h(e)){G(!0),g(`success`,N.workspace.pathCopied,void 0,{duration:2500}),window.setTimeout(()=>G(!1),2e3);return}g(`warning`,N.clipboard.copyFailed,void 0,{duration:4e3})}},[e,N.clipboard.copyFailed,N.workspace.pathCopied]),Q=(0,x.useCallback)(()=>{F.fileResourceId&&V({fileId:F.fileResourceId,fileName:X})},[V,X,F.fileResourceId]),$=(0,x.useCallback)(async()=>{await S(()=>F.onOpenWithSystemApp(),N.chat.attachmentPreviewOpenLocalFailed)},[N.chat.attachmentPreviewOpenLocalFailed,F.onOpenWithSystemApp]),re=(0,x.useCallback)(async()=>{let e;return await S(async()=>{let t=await F.onChooseOpenWithApp();return t?.ok&&(e=t.app),t},N.workspace.openFileFailed),e},[N.workspace.openFileFailed,F.onChooseOpenWithApp]),ie=(0,x.useCallback)(async e=>{await S(()=>F.onOpenWithRecentApp(e),N.workspace.openFileFailed)},[N.workspace.openFileFailed,F.onOpenWithRecentApp]),ae=(0,x.useCallback)(async()=>{await S(()=>F.onRevealInFolder(),N.workspace.revealFileFailed)},[N.workspace.revealFileFailed,F.onRevealInFolder]),oe=(0,x.useCallback)(()=>{Y(!1),C()},[C]),se=!!(e&&!F.loading&&!F.loadError),ce={onDownload:()=>void F.onDownload(),canDownload:F.canDownload,onOpenWithSystemApp:()=>void $(),canOpenWithSystemApp:F.canOpenWithSystemApp,onChooseOpenWithApp:()=>void F.onChooseOpenWithApp(),canChooseOpenWithApp:F.canChooseOpenWithApp};return!e||!r?null:(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(b,{expanded:J,children:(0,D.jsx)(ee,{header:{subtitle:(0,D.jsxs)(D.Fragment,{children:[!F.loading&&F.mtimeMs!=null?(0,D.jsxs)(`p`,{suppressHydrationWarning:!0,className:`min-w-0 truncate`,title:new Date(F.mtimeMs).toISOString(),children:[N.workspace.lastModified,`: `,te(F.mtimeMs,M),T?` · Line ${T}`:``]}):null,F.externalChange?(0,D.jsx)(`span`,{role:`status`,className:`text-fg-muted`,children:M===`zh`?`文件已更新,请先处理当前编辑`:`File changed; review your current edits`}):null,E?(0,D.jsxs)(`span`,{className:`shrink-0`,"data-result-revision":!0,children:[M===`zh`?`成果版本`:`Result version`,` `,E]}):null,F.loading?(0,D.jsx)(p,{className:`h-3.5 w-32`}):null,Z&&F.sourceEditMode&&F.saveStatus!==`idle`?(0,D.jsx)(`span`,{className:f(`shrink-0`,F.saveStatus===`error`&&`text-red-600 dark:text-red-400`),children:F.saveStatus===`saving`?N.workspace.saving:F.saveStatus===`error`?N.workspace.saveFailed:N.workspace.saved}):null]}),expanded:J,onRefresh:F.refresh,onRetrySave:F.saveStatus===`error`?()=>void F.flushSource():void 0,onToggleExpanded:se?()=>Y(e=>!e):void 0,hideClose:!!t&&!n,hideExpand:!!t,onClose:oe,edit:Z?{active:F.sourceEditMode,onToggle:()=>F.setSourceEditMode(e=>!e)}:void 0,wordWrap:Z&&F.sourceEditMode?{active:K,onToggle:()=>q(e=>!e)}:void 0,share:{onClick:Q,loading:L,disabled:!F.fileResourceId||F.loading||!!F.loadError},openWithSystemApp:F.canOpenWithSystemApp||v()&&window.electronAPI?.shell?.openFileResource?{onClick:()=>void $(),disabled:F.loading||!F.canOpenWithSystemApp}:void 0,chooseApp:F.canChooseOpenWithApp?{onClick:re}:void 0,recommendedApps:F.recommendedOpenWithApps,recentApps:F.recentOpenWithApps,onOpenWithApp:e=>void ie(e),onRevealInFolder:F.canRevealInFolder?()=>void ae():void 0,copyPath:{copied:W,onClick:()=>void ne()}},chat:{createFile:F.createAttachmentFile,projectId:k,conversationId:A,agentId:j,disabled:F.saveStatus===`saving`},language:M,resolvedTheme:P,descriptor:t?{...F.descriptor,id:t}:F.descriptor,loading:F.loading,loadError:F.loadError,textContent:F.textContent,binaryBuffer:F.binaryBuffer,fileResourceId:F.fileResourceId,mtimeMs:F.mtimeMs,targetLine:T,extractedText:F.extractedText,extractedTextTruncated:F.extractedTextTruncated,workspaceEditing:{sourceEditMode:F.sourceEditMode,onSourceChange:e=>{t&&m.getState().keepFileOpen(t),F.onSourceChange(e)},sourceWordWrap:K,isDark:P===`dark`},actions:ce})}),(0,D.jsx)(d,{open:I,onOpenChange:U,loading:L,error:z,result:R,pendingParams:B,onConfirm:e=>void H(e)})]})}export{S as i,E as n,T as r,A as t};
|