PageSourceSearch

https://paper2gal.com/assets/PaperResearchRoom-BERhtVXp.js

js paper2gal.com collected 2026-10-09 22:39:49 UTC 58,118 bytes, 3 lines download raw bytes

1import{r as b,j as r}from"./react-vendor-CHQL15iE.js";import{L as tt}from"./index.esm-DEYnJgQB.js";import rt from"./BlackboardMarkdown-Cizre-1w.js";import{a8 as at,a9 as se,aa as st,ab as Fe,ac as nt,ad as it,l as ot,ae as Ue,E as re,m as lt,u as ct,af as dt}from"./main-Dck1T9BT.js";import{r as ut}from"./renderLatex-D6ZnkI2b.js";import{ae as pt,o as ht,V as ft,ad as Te,v as mt,_ as Me,B as De,A as Oe,X as pe,a7 as bt,J as te,b9 as xt,aM as gt,aT as wt}from"./lucide-BFLOpGdB.js";import"./katex-math-BxKHCrdI.js";import"./markdown-W-rE_H7s.js";import"./pdfjs-ji3DqnKJ.js";const J=t=>t?`${t.ownerId}\0${t.sessionId}\0${t.epoch}`:"",W={status:"empty",identity:null,revision:0,presentation:null,metadataMissing:!1,latestTurn:null,material:null,selectedSectionId:"",messages:[],boardContent:"",images:[],turn:null,error:null,offline:!1,positionSaveError:null,metadataStatus:"idle",metadataError:null,emptyReason:"no_identity"},qe=/^p2g-document-image:\/\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/\d+$/iu,Be=2e4,X=(t,n)=>t instanceof Error&&t.message.trim()?t.message:n,Le=(t,n)=>J(t)===J(n),Ve=(t,n)=>{if(!t||typeof t!="object")return!1;const i=t;return typeof i.materialId=="string"&&i.materialId===n.materialId&&typeof i.runId=="string"&&typeof i.index=="number"&&Number.isSafeInteger(i.index)&&i.index>0&&typeof i.fileOrdinal=="number"&&Number.isSafeInteger(i.fileOrdinal)&&n.files.some(e=>e.fileOrdinal===i.fileOrdinal)&&typeof i.reference=="string"&&qe.test(i.reference)&&typeof i.type=="string"&&(i.type==="actual_image"||i.type==="data_chart"||i.type==="architecture_diagram")&&typeof i.description=="string"&&typeof i.url=="string"&&i.url.trim().length>0},me=(t,n,i)=>{if(!t||typeof t!="object")throw new Error("研究历史消息格式无效");const e=t;if(e.role!=="user"&&e.role!=="assistant"||typeof e.id!="string"||!e.id.trim()||i.has(e.id)||typeof e.text!="string"||!e.text.trim())throw new Error("研究历史消息格式无效");i.add(e.id);const d=e.role==="assistant"&&Array.isArray(e.citations)?e.citations.map(c=>nt(c,n)).filter(c=>c!==null):[],l=e.role==="assistant"?it(e.text,d,n):[];return{id:e.id,role:e.role,text:e.text,...l.length>0?{citations:l}:{},...typeof e.createdAt=="string"?{createdAt:e.createdAt}:{}}},ze=(t,n)=>{if(t.ownerId!==n.ownerId||t.sessionId!==n.sessionId||!Number.isSafeInteger(t.revision)||t.revision<0)throw new Error("研究会话身份校验失败");const i=st(t.material);if(!i)throw new Error("研究材料校验失败");if(!Array.isArray(t.messages))throw new Error("研究历史校验失败");const e=new Set,d=t.messages.map(C=>me(C,i,e)),l=Array.isArray(t.images)?t.images.filter(C=>Ve(C,i)):[];if(t.images&&l.length!==t.images.length)throw new Error("研究图片授权校验失败");if(typeof t.boardContent=="string"&&t.boardContent.length>Be)throw new Error("研究黑板内容过长");let c;const y=t.metadataMissing===!0||t.presentation==null;try{c=t.presentation==null?se(i):Fe(t.presentation,{material:i})}catch{throw new Error("研究元数据校验失败")}const R=t.latestTurn===void 0?void 0:t.latestTurn===null?null:{operationId:t.latestTurn.operationId,boardContent:t.latestTurn.boardContent,imageReferences:[...new Set(t.latestTurn.imageReferences)]};return{...t,latestTurn:R,metadataMissing:y,presentation:c,material:i,messages:d,images:l,boardContent:typeof t.boardContent=="string"?t.boardContent:""}},he=(t,n,i)=>{if(!t||t.operationId!==i)throw new Error("研究操作身份校验失败");const e=new Set,d=me(t.userMessage,n,e),l=me(t.assistantMessage,n,e);if(d.role!=="user"||l.role!=="assistant")throw new Error("研究回答角色校验失败");let c=t.session;if((c==null?void 0:c.presentation)!==void 0)try{c={...c,presentation:c.presentation==null?se(n):Fe(c.presentation,{material:n})}}catch{throw new Error("研究元数据校验失败")}return{operationId:i,userMessage:d,assistantMessage:l,...typeof t.boardContent=="string"?{boardContent:t.boardContent}:{},...Number.isSafeInteger(t.revision)?{revision:t.revision}:{},...Array.isArray(t.imageReferences)?{imageReferences:[...new Set(t.imageReferences)]}:{},...c?{session:c}:{}}},vt=()=>{var t,n;return((n=(t=globalThis.crypto)==null?void 0:t.randomUUID)==null?void 0:n.call(t))??`research-turn-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`};function yt({gateway:t,createOperationId:n=vt,characterConfiguration:i}){let e=W,d=null,l=0,c=null,y=!1,R=i,C=null,S=null;const _=new Set,O=()=>_.forEach(s=>s()),E=s=>{y||(e=s,O())},A=(s,m)=>!y&&m===l&&Le(d,s),z=(s,m)=>({...s,signal:m}),f=()=>(c==null||c.abort(),c=new AbortController,c),j=s=>{if(Le(d,s)&&e.status!=="empty")return;if(l+=1,c==null||c.abort(),C==null||C.abort(),S==null||S.abort(),c=null,C=null,S=null,d=s,!s){E({...W});return}const m=l,x=f();E({...W,status:"loading",identity:s,emptyReason:null}),t.loadSession(z(s,x.signal)).then(g=>{var N;if(!A(s,m))return;if(!g){E({...W,identity:s,emptyReason:"no_session",error:"当前没有可恢复的研究会话。"});return}const h=ze(g,s),p=h.selectedSectionId&&h.material.outline.some(w=>w.id===h.selectedSectionId)?h.selectedSectionId:((N=h.material.outline[0])==null?void 0:N.id)??"";E({status:"ready",identity:s,revision:h.revision,presentation:h.presentation??se(h.material),metadataMissing:h.metadataMissing===!0,latestTurn:h.latestTurn??null,material:h.material,selectedSectionId:p,messages:h.messages,boardContent:h.boardContent??"",images:h.images??[],turn:null,error:null,offline:h.offline===!0,positionSaveError:null,metadataStatus:"idle",metadataError:null,emptyReason:null})}).catch(g=>{!A(s,m)||x.signal.aborted||E({...W,status:"error",identity:s,error:X(g,"研究会话加载失败。"),emptyReason:null})})},T=async()=>{var g;if(!d)return!1;const s=d,m=l,x=new AbortController;S==null||S.abort(),S=x;try{const h=await t.loadSession(z(s,x.signal));if(!h||!A(s,m))return!1;const p=ze(h,s);if(p.revision<e.revision)return!1;const N=p.selectedSectionId&&p.material.outline.some(w=>w.id===p.selectedSectionId)?p.selectedSectionId:((g=p.material.outline[0])==null?void 0:g.id)??"";return E({...e,status:"ready",revision:p.revision,presentation:p.presentation??se(p.material),metadataMissing:p.metadataMissing===!0,latestTurn:p.latestTurn??null,material:p.material,selectedSectionId:N,messages:p.messages,boardContent:p.boardContent??"",images:p.images??[],offline:p.offline===!0,metadataStatus:"idle",metadataError:null,error:null,emptyReason:null}),!0}catch{return!1}finally{S===x&&(S=null)}},M=async s=>{if(e.status!=="ready"||e.offline||!d||!e.presentation||e.metadataMissing&&(!s.character||!s.background)||typeof t.updateMetadata!="function")return!1;const m=d,x=l,g=e.revision;S==null||S.abort();const h=new AbortController;S=h,E({...e,metadataStatus:"saving",metadataError:null});try{const p=await t.updateMetadata({...z(m,h.signal),expectedRevision:g,patch:s}
1);return!A(m,x)||h.signal.aborted?!1:p.revision<e.revision||p.revision!==g+1?(E({...e,metadataStatus:"conflict",metadataError:"研究会话版本已变化。"}),!1):(E({...e,revision:p.revision,presentation:p.presentation,metadataMissing:!1,metadataStatus:"idle",metadataError:null}),!0)}catch(p){return!A(m,x)||h.signal.aborted?!1:(p==null?void 0:p.code)==="RESEARCH_SESSION_STALE_REVISION"?(E({...e,metadataStatus:"conflict",metadataError:X(p,"研究会话版本已变化。")}),await T(),!1):(E({...e,metadataStatus:"error",metadataError:X(p,"研究元数据保存失败。")}),!1)}finally{S===h&&(S=null)}},I=s=>{if(e.status!=="ready"||e.offline||!e.material||!d)return;const m=e.material.outline.find(N=>N.id===s);if(!m)return;const x=d,g=l,h=e.revision;C==null||C.abort(),C=new AbortController;const p=C;E({...e,selectedSectionId:m.id,positionSaveError:null}),t.updatePosition({...z(x,p.signal),expectedRevision:h,selectedSectionId:m.id}).then(N=>{!A(x,g)||p.signal.aborted||C!==p||N.revision<e.revision||E({...e,revision:N.revision,selectedSectionId:m.id,positionSaveError:null})}).catch(N=>{!A(x,g)||p.signal.aborted||C!==p||E({...e,selectedSectionId:m.id,positionSaveError:X(N,"章节位置未保存,可继续阅读。")})})},H=async(s,m,x,g)=>{var w;if(!((w=s.imageReferences)!=null&&w.length))return{images:[]};const h=s.imageReferences.filter(k=>typeof k=="string"&&qe.test(k));if(h.length!==s.imageReferences.length)return{images:[],error:"回答包含无效图片引用,已移除。"};const p=await Promise.all(h.map(async k=>{try{const P=await t.resolveImage({...z(m,g.signal),reference:k});return!P||!e.material||P.reference!==k||!Ve(P,e.material)?null:P}catch{return null}}));if(!A(m,x))return{images:[]};const N=p.filter(k=>k!==null);return N.length===h.length?{images:N}:{images:N,error:"部分材料图片当前不可用,正文回答仍已保留。"}},a=(s,m,x,g,h)=>{if(!A(g,h)||!e.material)return!1;if(typeof s.boardContent=="string"&&s.boardContent.length>Be)throw new Error("研究黑板内容过长");const p=new Set(e.messages.map(k=>k.id)),N=[...e.messages];for(const k of[s.userMessage,s.assistantMessage])p.has(k.id)||(p.add(k.id),N.push(k));const w=new Map(e.images.map(k=>[k.reference,k]));for(const k of m)w.set(k.reference,k);return E({...e,status:"ready",revision:Number.isSafeInteger(s.revision)?s.revision:e.revision+1,messages:N,boardContent:s.boardContent??e.boardContent,latestTurn:{operationId:s.operationId,boardContent:s.boardContent??"",imageReferences:[...new Set(s.imageReferences??[])]},images:[...w.values()],turn:null,error:x??null,positionSaveError:null}),!0},v=async s=>{if(!d||!e.material||e.offline)return!1;const m=d,x=l,g=f();E({...e,turn:{...s,phase:"saving",error:void 0}});try{const h=await t.saveTurn({...z(m,g.signal),operationId:s.operationId});if(!A(m,x)||!e.material)return!1;if(h.status==="pending")return E({...e,turn:{...s,phase:"unsaved",error:"回答已生成,保存仍在服务端处理中。"}}),!1;if(h.status!==void 0&&h.status!=="completed"||!("userMessage"in h)||!("assistantMessage"in h))return E({...e,turn:{...s,phase:"failed",error:"回答保存失败,请使用相同操作重试。"}}),!1;const p=he(h,e.material,s.operationId),N=await H(p,m,x,g);return a(p,N.images,N.error,m,x)}catch(h){return A(m,x)&&E({...e,turn:{...s,phase:"unsaved",error:X(h,"回答保存失败,请使用相同操作重试。")}}),!1}},$=async(s,m)=>{var N;if(e.status!=="ready"||e.metadataMissing||e.offline||e.turn&&(e.turn.operationId!==m||e.turn.phase!=="failed")||!d||!e.material)return!1;const x=d,g=l,h=f(),p=((N=e.turn)==null?void 0:N.characterConfiguration)??(e.presentation?{characterReference:e.presentation.character.reference,outputLanguage:e.presentation.outputLanguage,narrativeStyle:e.presentation.narrativeStyle,...e.presentation.playerAddress?{playerAddressOverride:e.presentation.playerAddress}:{}}:R);E({...e,turn:{operationId:m,question:s,phase:"pending",images:[],characterConfiguration:p},error:null});try{const w=await t.ask({...z(x,h.signal),operationId:m,question:s,...e.selectedSectionId?{selectedSection:e.selectedSectionId}:{},...p?{characterConfiguration:p}:{}});if(!A(x,g)||!e.material)return!1;
1if(w.status==="pending"&&w.pendingReason!=="save")return E({...e,turn:{...e.turn,phase:"failed",images:[],error:"回答仍在服务端处理中,可使用相同操作重试。"}}),!1;if(w.status==="pending"&&w.pendingReason==="save"){const F=await t.saveTurn({...z(x,h.signal),operationId:m});if(!A(x,g)||!e.material)return!1;if(F.status==="pending")return E({...e,turn:{...e.turn,phase:"unsaved",images:[],error:"回答已生成,保存仍在服务端处理中。"}}),!1;if(F.status!==void 0&&F.status!=="completed"||!("userMessage"in F)||!("assistantMessage"in F))return E({...e,turn:{...e.turn,phase:"failed",images:[],error:"回答保存失败,请使用相同操作重试。"}}),!1;const Y=he(F,e.material,m),U=await H(Y,x,g,h);return a(Y,U.images,U.error,x,g)}if(w.status==="quota"||w.status==="capacity"){const F=w.status==="quota"?{kind:"quota",code:w.code,count:w.count,limit:w.limit}:{kind:"capacity",code:w.code,reason:w.reason};return E({...e,turn:{...e.turn,phase:"failed",images:[],error:w.status==="quota"?"研究问答次数已达上限。":"研究会话容量已达上限。",failure:F}}),!1}if(w.status!==void 0&&w.status!=="completed"||!("userMessage"in w)||!("assistantMessage"in w))return!1;const k=he(w,e.material,m),P=await H(k,x,g,h);return A(x,g)?a(k,P.images,P.error,x,g):!1}catch(w){return A(x,g)&&E({...e,turn:{...e.turn,phase:"failed",images:[],error:X(w,"提问失败,可使用相同操作重试。")}}),!1}};return{getState:()=>e,subscribe:s=>(_.add(s),()=>_.delete(s)),setIdentity:j,setCharacterConfiguration:s=>{R=s},selectSection:I,updateMetadata:M,refresh:T,submit:async s=>{const m=s.trim();return!m||e.status!=="ready"||e.metadataMissing||e.offline||e.turn||!d?!1:$(m,n())},retry:async()=>{const s=e.turn;return!s||!d?!1:s.phase==="unsaved"?v(s):s.phase!=="failed"?!1:$(s.question,s.operationId)},dispose:()=>{y=!0,l+=1,c==null||c.abort(),C==null||C.abort(),S==null||S.abort(),_.clear()}}}function Rt({identity:t,gateway:n,createOperationId:i,characterConfiguration:e}){const d=b.useRef(null);d.current||(d.current=yt({gateway:n,createOperationId:i,characterConfiguration:e}));const l=d.current,[,c]=b.useState(0);return b.useEffect(()=>l.subscribe(()=>c(y=>y+1)),[l]),b.useEffect(()=>{l.setCharacterConfiguration(e)},[l,e]),b.useEffect(()=>{l.setIdentity(t)},[l,t?J(t):""]),b.useEffect(()=>()=>l.setIdentity(null),[l]),{...l.getState(),selectSection:l.selectSection,updateMetadata:l.updateMetadata,refresh:l.refresh,submit:l.submit,retry:l.retry}}const Et=t=>t.material?at(t.material,t.selectedSectionId):null,$e={zh:{roomTitle:"自由研究室",waitingForSession:"等待已授权的研究会话。",loading:"正在恢复研究会话…",noSession:"当前没有可恢复的研究会话。请先完成材料准备。",loadFailed:"研究会话加载失败。",exit:"退出研究室",chapters:"章节",source:"原文",fullText:"全文",board:"独立黑板",questionPlaceholder:"围绕材料提问,按 Enter 发送…",send:"发送",thinking:"正在整理材料回答…",saving:"正在保存回答…",unsaved:"回答已显示,但尚未保存。离开前请重试保存。",failed:"提问失败。",retry:"重试",leaveRisk:"当前回答尚未保存,离开会丢失它。",leave:"仍然离开",stay:"留下",noChapters:"没有可导航的章节。",noSource:"该章节暂无可显示原文。",unavailableImage:"材料图片当前不可用。",user:"ä½ ",assistant:"研究助手",positionNotSaved:"章节位置尚未保存。",offlineReadOnly:"当前为离线只读模式,无法提问或保存新位置。",citation:"原文引用",quotaDetail:(t,n)=>Number.isFinite(t)&&Number.isFinite(n)?`今日额度已用 ${t}/${n}。`:"今日研究问答额度已达上限。",capacityDetail:t=>t?`会话容量已达上限(${t})。`:"研究会话容量已达上限。",paperResearchOutline:"论文目录",paperResearchSource:"论文原文",paperResearchPlaceholder:"继续追问论文内容,按 Enter 发送…",paperResearchThinking:"正在查找原文并整理回答…",paperResearchAskFailed:"提问失败,请稍后重试。",paperResearchExit:"返回主页面",paperResearchYou:"ä½ ",paperResearchPartner:"搭档",paperResearchSourceEmpty:"该章节没有可显示的原文ã€
1‚",paperResearchSourceTruncated:"[章节较长,已截断预览]",paperResearchContinuousHint:"连续问答会自动保存;用量以个人中心显示的额度与记录为准。",paperResearchMetadataMissing:"此历史会话没有保存角色设置,请显式确认角色与背景后再开始提问。",paperResearchMetadataResolve:"确认当前选择",paperResearchHistory:"对话历史",paperResearchVoiceUnavailable:"当前设备不支持语音输入。",paperResearchImageExpand:"点击全屏查看",paperResearchImageCollapse:"点击恢复"},en:{roomTitle:"Research Room",waitingForSession:"Waiting for an authorized research session.",loading:"Restoring research session…",noSession:"No resumable research session is available. Prepare the material first.",loadFailed:"The research session could not be loaded.",exit:"Exit research room",chapters:"Chapters",source:"Source",fullText:"Full text",board:"Separate board",questionPlaceholder:"Ask about the material. Press Enter to send…",send:"Send",thinking:"Preparing a grounded answer…",saving:"Saving answer…",unsaved:"The answer is shown but not saved. Retry before leaving.",failed:"The question failed.",retry:"Retry",leaveRisk:"The current answer is not saved and will be lost if you leave.",leave:"Leave anyway",stay:"Stay",noChapters:"No navigable chapters.",noSource:"No source text is available for this chapter.",unavailableImage:"This material image is unavailable.",user:"You",assistant:"Research assistant",positionNotSaved:"The chapter position was not saved.",offlineReadOnly:"Offline read-only mode: asking and saving a new position are disabled.",citation:"Source citation",quotaDetail:(t,n)=>Number.isFinite(t)&&Number.isFinite(n)?`Daily research quota reached (${t}/${n}).`:"Daily research question quota reached.",capacityDetail:t=>t?`Session capacity reached (${t}).`:"Research session capacity reached.",paperResearchOutline:"Paper Outline",paperResearchSource:"Source Text",paperResearchPlaceholder:"Ask a follow-up about the paper. Press Enter to send…",paperResearchThinking:"Finding the source and preparing an answer…",paperResearchAskFailed:"Could not answer. Please try again.",paperResearchExit:"Return to Home",paperResearchYou:"You",paperResearchPartner:"Partner",paperResearchSourceEmpty:"No source text is available for this section.",paperResearchSourceTruncated:"[This section is long; the preview has been truncated.]",paperResearchContinuousHint:"Follow-up questions are saved automatically. Check your profile for available allowance and usage records.",paperResearchMetadataMissing:"This legacy session has no saved persona settings. Explicitly confirm a character and background before asking.",paperResearchMetadataResolve:"Confirm selection",paperResearchHistory:"Dialogue History",paperResearchVoiceUnavailable:"Voice input is not supported on this device.",paperResearchImageExpand:"Click to view fullscreen",paperResearchImageCollapse:"Click to restore"},ja:{roomTitle:"リサーチルーム",waitingForSession:"認証済みの研究セッションを待っています。",loading:"研究セッションを復元中…",noSession:"復元できる研究セッションがありません。先に資料を準備してください。",loadFailed:"研究セッションを読み込めませんでした。",exit:"研究室を退出",chapters:"ç« ",source:"原文",fullText:"全文",board:"独立ボード",questionPlaceholder:"資料について質問。Enter で送信…",send:"送信",thinking:"資料に基づく回答を整理中…",saving:"回答を保存中…",unsaved:"回答は表示されていますが未保存です。退出前に再試行してください。",failed:"質問に失敗しました。",retry:"再試行",leaveRisk:"未保存の回答は退出すると失われます。",leave:"退出する",stay:"とどまる",noChapters:"移動できる章がありません。",noSource:"この章の原文はありません。",unavailableImage:"この資料画像は利用できません。",user:"あなた",assistant:"研究アシスタント",positionNotSaved:"章の位置を保存できませんでした。",offlineReadOnly:"オフラインの読み取り専用モードです。質問と新しい位置の保存は無効です。",citation:"原文引用",quotaDetail:(t,n)=>Number.isFinite(t)&&Number.isFinite(n)?`本日の質問上限です(${t}/${n})。`:"本日の研究質問上限です。",capacityDetail:t=>t?`セッション容量の上限です(${t})。`:"研究セッション容量の上限です。",paperResearchOutline:"論文目次",paperResearchSource:"原文",paperResearchPlaceholder:"論文について続けて質問します。Enter で送信…",paperResearchThinking:"原文を探して回答を整理しています…",paperResearchAskFailed:"回答でã
1ã¾ã›ã‚“でした。もう一度お試しください。",paperResearchExit:"ホームへ戻る",paperResearchYou:"あなた",paperResearchPartner:"パートナー",paperResearchSourceEmpty:"この節には表示できる原文がありません。",paperResearchSourceTruncated:"[節が長いため、プレビューを省略しました]",paperResearchContinuousHint:"質問は自動保存されます。利用枠と履歴はプロフィールで確認できます。",paperResearchMetadataMissing:"この旧セッションにはキャラクター設定がありません。質問前にキャラクターと背景を明示的に確認してください。",paperResearchMetadataResolve:"選択を確認",paperResearchHistory:"会話履歴",paperResearchVoiceUnavailable:"この端末は音声入力に対応していません。",paperResearchImageExpand:"クリックで全画面表示",paperResearchImageCollapse:"クリックで戻る"},ru:{roomTitle:"Исследовательская комната",waitingForSession:"Ожидание авторизованной исследовательской сессии.",loading:"Восстановление исследовательской сессии…",noSession:"Нет доступной сессии для восстановления. Сначала подготовьте материалы.",loadFailed:"Не удалось загрузить исследовательскую сессию.",exit:"Выйти из комнаты",chapters:"Главы",source:"Источник",fullText:"Полный текст",board:"Отдельная доска",questionPlaceholder:"Задайте вопрос о материале. Enter — отправить…",send:"Отправить",thinking:"Подготовка ответа по источнику…",saving:"Сохранение ответа…",unsaved:"Ответ показан, но не сохранён. Повторите попытку перед выходом.",failed:"Не удалось выполнить вопрос.",retry:"Повторить",leaveRisk:"Несохранённый ответ будет потерян при выходе.",leave:"Выйти",stay:"Остаться",noChapters:"Нет доступных глав.",noSource:"Для этой главы нет исходного текста.",unavailableImage:"Изображение материала недоступно.",user:"Вы",assistant:"Исследовательский помощник",positionNotSaved:"Позиция главы не сохранена.",offlineReadOnly:"Автономный режим только для чтения: вопросы и сохранение новой позиции отключены.",citation:"Цитата источника",quotaDetail:(t,n)=>Number.isFinite(t)&&Number.isFinite(n)?`Достигнут дневной лимит вопросов (${t}/${n}).`:"Достигнут дневной лимит исследовательских вопросов.",capacityDetail:t=>t?`Достигнут лимит сессии (${t}).`:"Достигнут лимит исследовательской сессии.",paperResearchOutline:"Структура статьи",paperResearchSource:"Исходный текст",paperResearchPlaceholder:"Задайте следующий вопрос. Enter — отправить…",paperResearchThinking:"Ищем исходный ф
1рагмент и готовим ответ…",paperResearchAskFailed:"Не удалось ответить. Попробуйте ещё раз.",paperResearchExit:"На главную",paperResearchYou:"Вы",paperResearchPartner:"Партнёр",paperResearchSourceEmpty:"Для этого раздела нет доступного текста.",paperResearchSourceTruncated:"[Раздел длинный; предпросмотр сокращён]",paperResearchContinuousHint:"Вопросы сохраняются автоматически. Доступный лимит и историю использования можно посмотреть в профиле.",paperResearchMetadataMissing:"В этой старой сессии нет настроек персонажа. Перед вопросом явно подтвердите персонажа и фон.",paperResearchMetadataResolve:"Подтвердить выбор",paperResearchHistory:"История диалога",paperResearchVoiceUnavailable:"Голосовой ввод не поддерживается на этом устройстве.",paperResearchImageExpand:"Нажмите, чтобы открыть на весь экран",paperResearchImageCollapse:"Нажмите, чтобы восстановить"}},St=(t="zh")=>$e[t]??$e.zh;async function ae(t,n,i={}){const e=localStorage.getItem("p2g_token");if(!e)throw new Error("RESEARCH_AUDIO_LOGIN");const d=new Headers(i.headers);d.set("Authorization",`Bearer ${e}`);const l=await ot(t,{...i,headers:d,signal:n,cache:"no-store"});if(!l.ok){const c=await l.json().catch(()=>null),y=["DAILY_POINTS_EXCEEDED","RESEARCH_RECORDING_INVALID"].includes(c==null?void 0:c.code)?c.code:l.status===403?"RESEARCH_VOICE_QUOTA":l.status===429?"RESEARCH_AUDIO_BUSY":"RESEARCH_AUDIO_FAILED";throw new Error(y)}return l}const kt=t=>new Promise((n,i)=>{const e=()=>{clearTimeout(d),i(new DOMException("Aborted","AbortError"))},d=setTimeout(()=>{t.removeEventListener("abort",e),n()},1500);t.aborted?e():t.addEventListener("abort",e,{once:!0})});async function jt(t,n,i,e){const d=`/api/research/sessions/${encodeURIComponent(t)}/voice`,l=await ae(d,e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageId:n,chunkIndex:i})}),{jobId:c}=await l.json();if(typeof c!="string"||!/^[0-9a-f-]{36}$/iu.test(c))throw new Error("RESEARCH_AUDIO_FAILED");const y=Date.now()+600*1e3;for(;Date.now()<y;){const R=await(await ae(`/api/tts/jobs/${c}`,e)).json();if(R.state==="done")return(await ae(`${d}/${c}/audio`,e)).blob();if(R.state==="failed")throw new Error("RESEARCH_AUDIO_FAILED");await kt(e)}throw new Error("RESEARCH_AUDIO_FAILED")}async function It(t,n,i){if(!n.size||n.size>2*1024*1024)throw new Error("RESEARCH_RECORDING_INVALID");const e=new FormData;e.append("audio",n,"question.audio");const d=await ae(`/api/research/sessions/${encodeURIComponent(t)}/transcribe`,i,{method:"POST",headers:{"Idempotency-Key":crypto.randomUUID()},body:e}),{text:l}=await d.json();if(typeof l!="string"||!l.trim())throw new Error("RESEARCH_AUDIO_FAILED");return l.slice(0,2e3)}function Nt(t){const n=Ue(String(t||"")).replace(/!\[[^\]]*\]\([^)]*\)|<img\b[^>]*>/giu,"").replace(/\[([^\]]+)\]\([^)]*\)/gu,"$1").replace(/https?:\/\/\S+|\[(?:引用|来源|citation|source)\s*\d+\]/giu,"").replace(/[`#*_]/gu,"").replace(/\s+/gu," ").trim(),i=[];for(let e=0;e<n.length;){let d=Math.min(n.length,e+70);if(d<n.length){let c=1/0;const y=d;for(let R=e+34;R<y;R++)/[。!?!?;;,,、::\s]/u.test(n[R])&&Math.abs(R+1-e-50)<c&&(c=Math.abs(R+1-e-50),d=R+1);c===1/0&&(d=e+50),/[\uD800-\uDBFF]/u.test(n[d-1])&&d--}const l=n.slice(e,d).trim();l&&i.push(l),e=d}return i}function Ct(t={},n="",i=null,e=Math.random()){const d=new Set,l=Object.values(re).filter(y=>{const R=t[y]||t[y.toLowerCase()]||(y===re.NEUTRAL?n:"");return!R||d.has(R)?!1:(d.add(R),!0)}),c=l.length>1?l.filter(y=>y!==i):l;return c[Math.floor(Math.max(0,Math.min(.999999,e))*c.length)]||re.NEUTRAL}function _t({scope:t,sessionId:n,message:i,locked:e,expressions:d,avatarUrl:l,volume:c,muted:y,onStateChange:R}){const[C,S]=b.useState(!1),[_,O]=b.useState(!1),[E,A]=b.useState(""),[z,f]=b.useState(""),j=b.useRef(null),T=b.useRef({expressions:d,avatarUrl:l,volume:c,muted:y,onStateChange:R});T.current={expressions:d,avatarUrl:l,volume:c,muted:y,onStateChange:R};const M=b.useRef(void 0),I=b.useCallback(()=>{var v,$,o;const a=j.current;j.current=null,a==null||a.controller.abort(),(v=a==null?void 0:a.audio)==null||v.pause(),a!=null&&a.url&&URL.revokeObjectURL(a.url),(o=($=T.current).onStateChange)==null||o.call($,{audio:null,emotion:re.NEUTRAL}),O(!1),A("")},[]),H=b.useCallback(async a=>{var o,V;if(I(),!n||e)return;const v={controller:new AbortController,audio:void 0,url:void 0};j.current=v,O(!0),f("");let $=null;try{const s=Nt(a.text),m=g=>
1jt(n,a.id,g,v.controller.signal).then(h=>({blob:h,error:null}),h=>({blob:null,error:h}));let x=s.length?m(0):null;for(let g=0;g<s.length;g++){const h=await x;if(h.error)throw h.error;if(j.current!==v)return;x=g+1<s.length?m(g+1):null,v.url=URL.createObjectURL(h.blob);const p=new Audio(v.url);v.audio=p,p.volume=Math.max(0,Math.min(1,T.current.volume)),p.muted=T.current.muted,$=Ct(T.current.expressions,T.current.avatarUrl,$),A(s[g]),(V=(o=T.current).onStateChange)==null||V.call(o,{audio:p,emotion:$}),await new Promise((N,w)=>{const k=()=>{p.onended=null,p.onerror=null,v.controller.signal.removeEventListener("abort",P)},P=()=>{k(),w(new DOMException("Aborted","AbortError"))};p.onended=()=>{k(),N()},p.onerror=()=>{k(),w(new Error("RESEARCH_AUDIO_FAILED"))},v.controller.signal.addEventListener("abort",P,{once:!0}),p.play().catch(()=>{k(),w(new Error("RESEARCH_AUDIO_PLAYBACK"))})}),URL.revokeObjectURL(v.url),v.url=void 0,v.audio=void 0}}catch(s){!v.controller.signal.aborted&&j.current===v&&f(s instanceof Error?s.message:"RESEARCH_AUDIO_FAILED")}finally{j.current===v&&I()}},[n,e,I]);return b.useEffect(()=>(S(!1),f(""),M.current=void 0,I),[t,I]),b.useEffect(()=>{if(e)return;const a=M.current;M.current=(i==null?void 0:i.id)||"",a!==void 0&&i&&a!==i.id&&C&&H(i)},[i,C,e,H]),b.useEffect(()=>{e&&I()},[e,I]),b.useEffect(()=>{var a;(a=j.current)!=null&&a.audio&&(j.current.audio.volume=Math.max(0,Math.min(1,c)),j.current.audio.muted=y)},[c,y]),{enabled:C,busy:_,subtitle:E,error:z,stop:I,replay:()=>i&&H(i),toggle:()=>{I(),f(""),S(a=>!a)}}}function At({scope:t,sessionId:n,disabled:i,onTranscript:e,onStart:d}){var z;const[l,c]=b.useState("idle"),[y,R]=b.useState(""),C=typeof navigator<"u"&&!!((z=navigator.mediaDevices)!=null&&z.getUserMedia)&&typeof MediaRecorder<"u",S=b.useRef({disabled:i,onTranscript:e,onStart:d});S.current={disabled:i,onTranscript:e,onStart:d};const _=b.useRef(null),O=b.useCallback(()=>{var j;const f=_.current;_.current=null,f==null||f.controller.abort(),clearTimeout(f==null?void 0:f.timer),f!=null&&f.recorder&&(f.recorder.ondataavailable=null,f.recorder.onstop=null,f.recorder.onerror=null,f.recorder.state!=="inactive"&&f.recorder.stop()),(j=f==null?void 0:f.stream)==null||j.getTracks().forEach(T=>T.stop()),c("idle")},[]),E=b.useCallback(()=>{var j;const f=_.current;((j=f==null?void 0:f.recorder)==null?void 0:j.state)==="recording"?f.recorder.stop():f&&!f.recorder&&O()},[O]),A=b.useCallback(async()=>{if(!C||!n||S.current.disabled||_.current)return;const f={controller:new AbortController,recorder:void 0,stream:void 0,timer:void 0};_.current=f,R(""),c("starting"),S.current.onStart();try{const j=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,channelCount:1}});if(_.current!==f){j.getTracks().forEach(a=>a.stop());return}f.stream=j;const T=["audio/webm;codecs=opus","audio/mp4","audio/ogg;codecs=opus"].find(a=>MediaRecorder.isTypeSupported(a)),M=new MediaRecorder(j,{...T?{mimeType:T}:{},audioBitsPerSecond:64e3});f.recorder=M;const I=[];let H=0;M.ondataavailable=a=>{if(H+=a.data.size,H>2*1024*1024){R("RESEARCH_RECORDING_INVALID"),O();return}a.data.size&&I.push(a.data)},M.onerror=()=>{R("RESEARCH_RECORDING_FAILED"),O()},M.onstop=async()=>{if(clearTimeout(f.timer),j.getTracks().forEach(a=>a.stop()),_.current===f){c("transcribing");try{const a=await It(n,new Blob(I,{type:M.mimeType}),f.controller.signal);_.current===f&&!S.current.disabled&&await S.current.onTranscript(a)}catch(a){!f.controller.signal.aborted&&_.current===f&&R(a instanceof Error?a.message:"RESEARCH_RECORDING_FAILED")}finally{_.current===f&&O()}}},M.start(250),c("recording"),f.timer=setTimeout(E,6e4)}catch(j){_.current===f&&(R(j instanceof Error&&["NotAllowedError","SecurityError"].includes(j.name)?"RESEARCH_RECORDING_PERMISSION":"RESEARCH_RECORDING_FAILED"),O())}},[C,n,O,E]);return b.useEffect(()=>(R(""),O),[t,O]),b.useEffect(()=>{let f=!1;const j=I=>{I.code!=="Space"||I.repeat||I.ctrlKey||I.altKey||I.metaKey||I.target instanceof Element&&I.target.closest('input,textarea,button,select,[contenteditable="true"],[role="dialog"]')||S.current.disabled||_.current||(I.preventDefault(),f=!0,A())},T=()=>{f&&(f=!1,E())},M=I=>{I.code==="Space"&&T()};return window.addEventListener("keydown",j),window.addEventListener("keyup",M),window.addEventListener("blur",T),()=>{window.removeEventListener("keydown",j),window.removeEventListener("keyup",M),window.removeEventListener("blur",T)}},[A,E]),{supported:C,phase:l,error:y,cancel:O,toggle:()=>_.current?E():void A()}}const Pe={zh:{voice:"回复配音",replay:"重播回复",record:"录音提
1问",stop:"结束录音",starting:"正在开启麦克风…",recording:"正在录音",transcribing:"正在识别语音…",unavailable:"该角色未配置语音",unsupported:"当前设备不支持录音",failed:"语音处理失败,请稍后重试。",quota:"语音额度已用完或暂无语音权限。",busy:"语音服务繁忙,请稍后重试。",permission:"无法访问麦克风,请检查浏览器权限。",invalid:"录音不能超过 60 秒或 2 MB。",playback:"无法播放语音,请点击重播。"},en:{voice:"Reply audio",replay:"Replay reply",record:"Voice question",stop:"Stop recording",starting:"Opening microphone…",recording:"Recording",transcribing:"Transcribing…",unavailable:"This character has no voice",unsupported:"Recording is unavailable on this device",failed:"Audio processing failed. Please try again.",quota:"Voice quota or access is unavailable.",busy:"Audio service is busy. Please try again.",permission:"Microphone access failed. Check browser permissions.",invalid:"Recordings must be within 60 seconds and 2 MB.",playback:"Audio could not play. Select replay."},ja:{voice:"返答の音声",replay:"返答を再生",record:"音声で質問",stop:"録音を終了",starting:"マイクを起動中…",recording:"録音中",transcribing:"音声を認識中…",unavailable:"このキャラクターに音声がありません",unsupported:"この端末は録音に対応していません",failed:"音声の処理に失敗しました。再試行してください。",quota:"音声の利用枠または権限がありません。",busy:"音声サービスが混雑しています。",permission:"マイクの権限を確認してください。",invalid:"録音は60秒、2 MB以内にしてください。",playback:"音声を再生できません。再生ボタンを押してください。"},ru:{voice:"Озвучка ответа",replay:"Повторить ответ",record:"Голосовой вопрос",stop:"Завершить запись",starting:"Включение микрофона…",recording:"Запись",transcribing:"Распознавание…",unavailable:"У персонажа нет голоса",unsupported:"Запись недоступна на этом устройстве",failed:"Не удалось обработать звук. Повторите попытку.",quota:"Озвучка недоступна или лимит исчерпан.",busy:"Сервис занят. Повторите попытку позже.",permission:"Проверьте разрешение на доступ к микрофону.",invalid:"Запись должна быть не длиннее 60 секунд и не больше 2 МБ.",playback:"Не удалось воспроизвести звук. Нажмите повтор."}};function Tt(t){const n=Pe[t]||Pe.en;return{...n,error:i=>i==="DAILY_POINTS_EXCEEDED"?lt(i,t):i==="RESEARCH_VOICE_QUOTA"?n.quota:i==="RESEARCH_AUDIO_BUSY"?n.busy:i==="RESEARCH_RECORDING_PERMISSION"?n.permission:i==="RESEARCH_RECORDING_INVALID"?n.invalid:i==="RESEARCH_AUDIO_PLAYBACK"?n.playback:n.failed}}const He=3e4,Mt={position:"absolute",top:"50%",left:"50%",width:"calc(100% + 20px)",height:"calc(100% + 20px)",pointerEvents:"none"},fe=({mouseContainer:t})=>r.jsx(tt,{displacementScale:78,blurAmount:.05,saturation:155,aberrationIntensity:4,elasticity:.12,cornerRadius:24,padding:"0",mode:"prominent",mouseContainer:t,className:"paper-research-liquid-layer",style:Mt,children:r.jsx("span",{"aria-hidden":"true",className:"block h-full w-full"})}),Dt=(t,n)=>{const i=new Map(n.map(l=>[l.reference,l])),e=dt(t);let d=t;for(const l of[...e].sort((c,y)=>y.startOffset-c.startOffset)){const c=i.get(l.url);if(!c){d=`${d.slice(0,l.startOffset)}${d.slice(l.endOffset)}`;continue}const y=l.alt.replace(/[\\\]]/gu,"\\\\$&");d=`${d.slice(0,l.startOffset)}![${y}](<${c.url}>)${d.slice(l.endOffset)}`}return d};function Bt({identity:t,gateway:n,characterConfiguration:i,language:e="zh",preparation:d=null,preparationActive:l=!1,preparationTerminal:c=!1,preparationUncertain:y=!1,preparationError:R=null,preparationCancelling:C=!1,characterAvailable:S=!0,voiceAvailable:_=!1,characterExpressions:O,characterAvatarUrl:E,voiceVolume:A=1,muted:z=!1,onVoiceStateChange:f,metadataMissing:j=!1,onResolveMissingMetadata:T,onMetadataResolved:M,onPresentationResolved:I,onExit:H}){var ye,Re,Ee,Se,ke,je,Ie,Ne,Ce,_e,Ae;const a=St(e),v=Tt(e),$=ct(),o=Rt({identity:t,gateway:n,characterConfiguration:i}),V=Et(o);b.useEffect(()=>{o.presentation&&(I==null||I(o.presentation))},[I,o.presentation]);const s=b.useRef(null),m=b.useRef(null),[x,g]=b.useState(null),[h,p]=b.useState(!1),[N,w]=b.useState(!1),[k,P]=b.useState(!1),[F,Y]=b.useState(""),[U,Z]=b.useState(null),[be,xe]=b.useState(!1),ne=((ye=o.turn)==null?void 0:ye.phase)==="pending"||((Re=o.turn)==null?void 0:Re.phase)==="saving",q=b.useMemo(()=>[...o.messages].reverse().find(u=>u.role==="assistant"),[o.messages]),ie=b.useMemo(()=>
1{if(!o.latestTurn)return[];const u=new Set(o.latestTurn.imageReferences);return o.images.filter(B=>u.has(B.reference)).slice(0,4)},[o.images,o.latestTurn]),ge=((Se=(Ee=o.presentation)==null?void 0:Ee.character.name)==null?void 0:Se.trim())||a.paperResearchPartner,ee=V==null?void 0:V.section,oe=ee?V.text:o.material&&o.material.outline.length===0?o.material.fullText:"",Ge=oe.length>He?`${oe.slice(0,He)}
2
3${a.paperResearchSourceTruncated}`:oe,Ye=(ee==null?void 0:ee.title)??(o.material&&o.material.outline.length===0?a.fullText:a.paperResearchSourceEmpty),le=((ke=o.turn)==null?void 0:ke.phase)==="unsaved",Q=l&&!c,ce=y?e==="zh"?"研究准备状态暂时不确定,仍可安全取消。":e==="ja"?"研究準備の状態を確認できません。安全にキャンセルできます。":e==="ru"?"Состояние подготовки неизвестно. Отмену всё ещё можно выполнить безопасно.":"Preparation status is uncertain. You can still cancel safely.":R||(Q?e==="zh"?"正在准备研究材料…":e==="ja"?"研究資料を準備中…":e==="ru"?"Подготовка исследовательских материалов…":"Preparing research material…":o.status==="loading"?a.loading:o.status==="error"?o.error||a.loadFailed:o.status==="empty"&&t?o.error||a.noSession:t?null:a.waitingForSession),Ke=R?"research-preparation-error":Q||y||d?"research-preparation-status":t?o.status==="error"?"research-error":o.status==="empty"?"research-no-session":"research-loading":"research-empty",Xe=Q||y||o.status==="loading",Qe=!!R||o.status==="error",de=j||o.metadataMissing,We=de?a.paperResearchMetadataMissing:S?R||(Q||y?ce:a.paperResearchContinuousHint):e==="zh"?"当前角色不可用,无法提问。":"The saved character is unavailable; questions are disabled.",G=o.offline||de||!t||Q||o.status!=="ready"||!S,D=_t({scope:J(t)||"",sessionId:t==null?void 0:t.sessionId,message:q,locked:G||!_,expressions:O,avatarUrl:E,volume:A,muted:z,onStateChange:f}),L=At({scope:J(t)||"",sessionId:t==null?void 0:t.sessionId,disabled:!!o.turn||G||k||N||h||be,onStart:D.stop,onTranscript:async u=>{Y(u),await o.submit(u)&&Y("")}}),K=L.phase!=="idle",ue=!!o.turn||G||K;b.useEffect(()=>{G&&L.cancel()},[G,L.cancel]);const we=o.turn&&(o.turn.phase==="failed"||o.turn.phase==="unsaved")?o.turn.phase==="unsaved"?a.unsaved:((je=o.turn.failure)==null?void 0:je.kind)==="quota"?o.turn.failure.code==="DAILY_POINTS_EXCEEDED"?v.error("DAILY_POINTS_EXCEEDED"):a.quotaDetail(o.turn.failure.count,o.turn.failure.limit):((Ie=o.turn.failure)==null?void 0:Ie.kind)==="capacity"?a.capacityDetail(o.turn.failure.reason):`${a.failed} ${o.turn.error??""}`:null;b.useEffect(()=>{if(!le)return;const u=B=>{B.preventDefault(),B.returnValue=a.leaveRisk};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[le,a.leaveRisk]),b.useEffect(()=>Z(null),[q==null?void 0:q.id]),b.useEffect(()=>{if(!U)return;const u=B=>{B.key==="Escape"&&Z(null)};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[U]),b.useEffect(()=>{if(!k)return;const u=setTimeout(()=>{m.current&&(m.current.scrollTop=m.current.scrollHeight)},50);return()=>clearTimeout(u)},[k]);const Je=()=>{if(le){xe(!0);return}D.stop(),L.cancel(),H()},Ze=u=>{g(null),w(!0),o.selectSection(u)},et=u=>{g(u),w(!0),o.selectSection(u.sectionId)},ve=async()=>{const u=F.trim();if(!u||ue)return;D.stop(),await o.submit(u)&&Y("")};return r.jsxs("div",{ref:s,"data-testid":"paper-research-scene",className:"pointer-events-none absolute inset-0 z-40 overflow-hidden text-slate-700",children:[r.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-black/25 via-transparent to-black/35"}),r.jsxs("header",{className:"pointer-events-auto absolute inset-x-0 top-0 z-30 flex items-center justify-between gap-3 p-3 md:p-5",children:[r.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[r.jsx("button",{type:"button",onClick:Je,disabled:C,"aria-busy":C||void 0,className:"rounded-full border border-white/30 bg-black/25 p-2.5 text-white shadow-lg backdrop-blur-md transition hover:bg-white hover:text-pink-600",title:a.paperResearchExit,children:r.jsx(pt,{size:20})}),r.jsxs("div",{className:"min-w-0 rounded-2xl border border-white/25 bg-black/25 px-3 py-2 text-white shadow-lg backdrop-blur-md",children:[r.jsx("div",{className:"max-w-[45vw] truncate text-xs font-black md:max-w-[55vw] md:text-sm",children:((Ne=o.presentation)==null?void 0:Ne.title)||a.roomTitle}),r.jsx("div",{className:"hidden truncate text-[10px] text-white/70 sm:block",children:We})]})]}),r.jsxs("div",{className:"flex shrink-0 gap-2",children:[r.jsxs("button",{"data-testid":"paper-research-voice-toggle",type:"button",disabled:G||!_,onClick:D.toggle,"aria-pressed":D.enabled,title:_?v.voice:v.unavailable,"aria-label":_?v.voice:v.unavailable,className:`flex items-center gap-2 rounded-full border px-3 py-2 text-xs font-black shadow-lg backdrop-blur-md transition disabled:opacity-50 ${D.enabled?"border-pink-300 bg-pink-500 text-white":"border-white/30 bg-black/25 text-white hover:bg-white hover:text-pink-600"}`,children:[D.enabled?r.jsx(ht,{size:16}):r.jsx(ft,{size:16}),r.jsx("span",{className:"hidden sm:inline",children:v.voice})]}),D.enabled&&q&&r.jsx("button",{type:"button","data-testid":"paper-research-voice-replay",onClick:()=>D.busy?D.stop():void D.replay(),disabled:G||K,title:D.busy?v.stop:v.replay,"aria-label":D.busy?v.stop:v.replay,className:"rounded-full border border-white/30 bg-black/25 p-2.5 text-white shadow-lg backdrop-blur-md disabled:opacity-50",children:D.busy?r.jsx(Te,{size:16}):r.jsx(mt,{size:16})}),r.jsxs("button",{"data-testid":"paper-research-history",type:"button",onClick:()=>P(!0),className:"flex items-center gap-2 rounded-full border border-white/30 bg-black/25 px-3 py-2 text-xs font-black text-white shadow-lg backdrop-blur-md transition hover:bg-white hover:text-pink-600",children:[r.jsx(Me,{size:16}),r.jsx("span",{className:"hidden sm:inline",children:a.paperResearchHistory})]}),r.jsxs("button",{"data-testid":"paper-research-outline-toggle",type:"button",onClick:()=>p(u=>!u),className:`flex items-center gap-2 rounded-full border px-3 py-2 text-xs font-black shadow-lg backdrop-blur-md transition ${h?"border-pink-300 bg-pink-500 text-white":"border-white/30 bg-black/25 text-white hover:bg-white hover:text-pink-600"}`,children:[r.jsx(De,{size:16}),r.jsx("span",{className:"hidden sm:inline",children:a.paperResearchOutline})]}),r.jsxs("button",{type:"button",onClick:()=>w(u=>!u),className:`flex items-center gap-2 rounded-full border px-3 py-2 text-xs font-black shadow-lg backdrop-blur-md transition ${N?"border-pink-300 bg-pink-500 text-white":"border-white/30 bg-black/25 text-white hover:bg-white hover:text-pink-600"}`,children:[r.jsx(Oe,{size:16}),r.jsx("span",{className:"hidden sm:inline",children:a.paperResearchSource})]})]})]}),h&&r.jsxs("aside",{"data-testid":"paper-research-outline",className:"paper-research-liquid-host pointer-events-auto absolute bottom-[25vh] left-3 top-16 z-30 flex w-[min(82vw,280px)] flex-col p-3 text-white md:bottom-[24vh] md:left-5 md:top-20",children:[r.jsx(fe,{mouseContainer:s}),r.jsxs("div",{className:"relative z-10 mb-2 flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 text-xs font-black",children:[r.jsx(De,{size:15}),a.paperResearchOutline]}),r.jsx("button",{type:"button",onClick:()=>p(!1),className:"rounded-full p-1 text-white/70 transition hover:bg-white/15 hover:text-white",children:r.jsx(pe,{size:15})})]}),r.jsx("nav",{className:"relative z-10 min-h-0 flex-1 space-y-1 overflow-y-auto pr-1 custom-scrollbar",children:(((Ce=o.material)==null?void 0:Ce.outline)??[]).map(u=>r.jsx("button",{type:"button",onClick:()=>Ze(u.id),"aria-current":o.selectedSectionId===u.id?"true":void 0,className:`w-full rounded-xl px-3 py-2 text-left text-xs font-bold transition ${o.selectedSectionId===u.id?"bg-pink-500 text-white":"text-white/80 hover:bg-white/15 hover:text-white"}`,style:{paddingLeft:`${12+Math.max(0,u.level-1)*9}px`},children:u.title},u.id))})]}),N&&r.jsxs("aside",{"data-testid":"paper-research-source-panel",className:"paper-research-liquid-host pointer-events-auto absolute bottom-[25vh] right-3 top-16 z-30 flex w-[min(88vw,390px)] flex-col p-3 text-white md:bottom-[24vh] md:right-5 md:top-20",children:[r.jsx(fe,{mouseContainer:s}),r.jsxs("div",{className:"relative z-10 mb-2 flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 text-xs font-black text-pink-300",children:[r.jsx(Oe,{size:15}),a.paperResearchSource]}),r.jsx("div",{className:"mt-1 truncate text-[11px] font-bold text-white/65",children:Ye})]}),r.jsx("button",{type:"button",onClick:()=>w(!1),className:"rounded-full p-1 text-white/60 transition hover:bg-white/15 hover:text-white",children:r.jsx(pe,{size:16})})]}),r.jsxs("div",{className:"relative z-10 min-h-0 flex-1 overflow-y-auto rounded-xl border border-white/10 bg-black/20 p-3 text-xs leading-6 text-white/75 custom-scrollbar",children:[x&&r.jsxs("blockquote",{className:"mb-3 rounded-xl border-l-4 border-pink-400 bg-pink-500/15 p-3 text-[11px] leading-5 text-white/80",children:[r.jsxs("div",{className:"mb-1 font-black text-pink-300",children:["[",x.id,"] ",x.sectionTitle]}),r.jsx("div",{className:"whitespace-pre-wrap",children:x.quote})]}),r.jsx("div",{className:"whitespace-pre-wrap",children:Ge||a.paperResearchSourceEmpty})]})]}),ie.length>0&&r.jsx("section",{"data-testid":"paper-research-image-stage",className:"pointer-events-auto absolute bottom-[51vh] right-4 top-[12vh] z-10 flex w-[min(44vw,760px)] items-center justify-end md:right-8",children:r.jsx("div",{className:`grid max-h-full w-full gap-3 overflow-y-auto pr-1 custom-scrollbar ${ie.length>1?"grid-cols-2":"grid-cols-1"}`,children:ie.map(u=>r.jsxs("figure",{className:"min-h-0 overflow-hidden rounded-2xl border border-white/30 bg-black/45 p-2 shadow-2xl backdrop-blur-sm",children:[r.jsxs("button",{type:"button",onClick:()=>Z(u),className:"group relative block w-full cursor-zoom-in overflow-hidden rounded-xl",title:a.paperResearchImageExpand,"aria-label":a.paperResearchImageExpand,children:[r.jsx("img",{src:u.url,alt:u.description||u.reference,className:"max-h-[30vh] w-full object-contain transition duration-200 group-hover:scale-[1.03] group-hover:brightness-110",draggable:!1}),r.jsx("span",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition group-hover:bg-black/20 group-hover:opacity-100",children:r.jsxs("span",{className:"flex items-center gap-2 rounded-full bg-black/65 px-3 py-1.5 text-xs font-black text-white backdrop-blur-sm",children:[r.jsx(bt,{size:15}),a.paperResearchImageExpand]})})]}),u.description&&r.jsx("figcaption",{className:"mt-1 line-clamp-2 text-center text-[11px] font-bold text-white/85",children:u.description})]},u.reference))})}),U&&r.jsxs("button",{"data-testid":"paper-research-image-fullscreen",type:"button",onClick:()=>Z(null),className:"pointer-events-auto absolute inset-0 z-[70] flex cursor-zoom-out flex-col items-center justify-center gap-3 bg-black/85 p-4 backdrop-blur-md",title:a.paperResearchImageCollapse,"aria-label":a.paperResearchImageCollapse,children:[r.jsx("div",{className:"flex min-h-0 w-full flex-1 items-center justify-center",children:r.jsx("img",{src:U.url,alt:U.description||U.reference,className:"h-full w-full object-contain drop-shadow-2xl",draggable:!1})}),U.description&&r.jsx("span",{className:"max-w-5xl text-center text-sm font-bold text-white/90 [text-shadow:0_2px_8px_rgba(0,0,0,1)]",children:U.description})]}),r.jsxs("main",{className:"absolute inset-x-0 bottom-0 z-20 flex max-h-[50vh] flex-col items-center px-2 pb-2 sm:px-5 sm:pb-3 md:px-10 md:pb-5",children:[r.jsx("div",{"data-testid":"paper-research-current-response","data-phase":(_e=o.turn)==null?void 0:_e.phase,className:"pointer-events-auto mb-3 min-h-0 w-[92%] max-w-5xl text-white sm:w-[82%]",children:r.jsxs("div",{className:"max-h-[24vh] overflow-y-auto px-4 py-2 custom-scrollbar md:px-6",children:[ce&&r.jsxs("div",{"data-testid":Ke,className:`flex items-center justify-center gap-2 text-center text-sm font-bold [text-shadow:0_2px_8px_rgba(0,0,0,0.9)] md:text-base ${Qe?"text-red-300":""}`,children:[Xe&&r.jsx(te,{size:16,className:"animate-spin text-pink-300"}),r.jsx("span",{children:ce})]}),de&&r.jsxs("p",{"data-testid":"research-metadata-missing",role:"status",className:"mt-1 text-center text-[11px] font-bold text-amber-200 [text-shadow:0_2px_8px_rgba(0,0,0,0.9)]",children:[a.paperResearchMetadataMissing,T&&!o.offline&&r.jsx("button",{type:"button","data-testid":"research-metadata-resolve",onClick:async()=>{const u=await T();u&&await o.updateMetadata(u)&&o.presentation&&(M==null||M({...o.presentation,...u}))},className:"ml-2 underline underline-offset-2",children:a.paperResearchMetadataResolve})]}),o.offline&&r.jsx("p",{"data-testid":"research-offline",className:"mt-1 text-center text-[11px] font-bold text-amber-200 [text-shadow:0_2px_8px_rgba(0,0,0,0.9)]",children:a.offlineReadOnly}),o.positionSaveError&&r.jsx("p",{className:"mt-1 text-center text-[11px] font-bold text-amber-200 [text-shadow:0_2px_8px_rgba(0,0,0,0.9)]",children:a.positionNotSaved}),ne&&r.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm font-bold [text-shadow:0_2px_8px_rgba(0,0,0,0.9)] md:text-base",children:[r.jsx(te,{size:16,className:"animate-spin text-pink-300"}),a.paperResearchThinking]}),!ne&&q&&r.jsxs("article",{className:"min-w-0",children:[r.jsx("div",{className:"mb-1.5 text-center text-sm font-black text-pink-200 [text-shadow:0_2px_8px_rgba(0,0,0,0.9)] md:text-base",children:ge}),r.jsx(rt,{content:Ue(Dt(q.text,o.images)),className:"h-auto text-sm !leading-relaxed [text-shadow:0_2px_8px_rgba(0,0,0,0.95)] md:text-base [&_h1]:!text-white [&_h2]:!text-white [&_h3]:!text-white [&_p]:!text-white [&_li]:!text-white [&_.katex]:!text-white [&_.katex-display]:!text-white"}),!!((Ae=q.citations)!=null&&Ae.length)&&r.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:q.citations.map(u=>r.jsxs("button",{type:"button",onClick:()=>et(u),className:"flex items-center gap-1 rounded-full border border-white/25 bg-white/10 px-2 py-1 text-[10px] font-black text-white transition hover:border-pink-300 hover:bg-pink-500/80",children:[r.jsx(xt,{size:10}),"[",u.id,"] ",a.paperResearchSource]},`${q.id}-${u.id}`))})]})]})}),r.jsxs("div",{"data-testid":"paper-research-dialogue",className:"paper-research-liquid-host pointer-events-auto relative flex w-[92%] max-w-5xl sm:w-[82%]",children:[r.jsx(fe,{mouseContainer:s}),r.jsxs("div",{"data-testid":"paper-research-input",className:"relative z-10 flex min-w-0 flex-1 flex-col justify-center px-3 py-2 md:px-5",children:[r.jsx("textarea",{value:F,onChange:u=>Y(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&!u.nativeEvent.isComposing&&(u.preventDefault(),ve())},rows:1,maxLength:2e3,disabled:ue,placeholder:a.paperResearchPlaceholder,className:"max-h-24 min-h-[30px] w-full resize-none bg-transparent py-1 text-sm font-medium leading-6 text-white outline-none placeholder:text-white/60 disabled:opacity-60 md:text-base"}),(D.subtitle||K||D.error||L.error)&&r.jsxs("div",{"data-testid":"paper-research-audio-status",role:"status",className:"max-h-16 overflow-y-auto text-xs leading-5 text-white/90",children:[K?v[L.phase]:D.subtitle,(L.error||D.error)&&r.jsx("span",{className:"block text-red-200",children:v.error(L.error||D.error)})]}),we&&r.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold text-red-300",children:[r.jsx("span",{children:we}),r.jsx("button",{type:"button",onClick:()=>void o.retry(),className:"flex items-center gap-1 rounded-full border border-white/25 bg-white/10 px-2 py-1 text-[10px] font-black text-white transition hover:border-pink-300 hover:bg-pink-500/80",children:a.retry})]})]}),r.jsx("button",{"data-testid":"paper-research-record",type:"button",disabled:!L.supported||G||!!o.turn||L.phase==="transcribing",onClick:L.toggle,"aria-pressed":L.phase==="recording",title:L.supported?K?v.stop:v.record:v.unsupported,"aria-label":L.supported?K?v.stop:v.record:v.unsupported,className:"relative z-10 flex w-12 shrink-0 items-center justify-center border-l borde
3r-white/35 text-white transition disabled:cursor-not-allowed disabled:bg-white/20 disabled:text-white/45 bg-white/10 hover:bg-white/25",children:L.phase==="transcribing"||L.phase==="starting"?r.jsx(te,{size:18,className:"animate-spin"}):L.phase==="recording"?r.jsx(Te,{size:18,className:"text-red-300"}):r.jsx(gt,{size:18})}),r.jsxs("button",{"data-testid":"paper-research-send",type:"button",onClick:()=>void ve(),disabled:!F.trim()||ue,className:"relative z-10 flex min-w-[88px] shrink-0 items-center justify-center gap-2 border-l border-white/50 bg-pink-500/75 px-4 text-xs font-black text-white shadow-[0_0_18px_rgba(236,72,153,0.25)] transition hover:bg-pink-400/85 disabled:cursor-not-allowed disabled:bg-white/70 disabled:text-slate-500 disabled:shadow-none md:min-w-[128px] md:px-6 md:text-sm",children:[ne?r.jsx(te,{size:16,className:"animate-spin"}):r.jsx(wt,{size:16}),r.jsx("span",{children:a.send})]})]})]}),k&&r.jsx("div",{"data-testid":"paper-research-history-drawer",className:"pointer-events-auto absolute inset-0 z-[100] bg-black/40 flex items-center justify-center animate-fade-in font-sans",onClick:()=>P(!1),children:r.jsxs("div",{className:"bg-white/95 backdrop-blur-xl border-white ring-blue-100 rounded-2xl w-full shadow-[0_20px_60px_rgba(0,0,0,0.3)] flex flex-col overflow-hidden border-solid max-w-4xl h-[80vh]",onClick:u=>u.stopPropagation(),children:[r.jsxs("div",{className:`${$?"p-3":"p-5 md:p-6"} border-gray-100 bg-blue-50/50 border-b flex justify-between items-center`,children:[r.jsxs("h3",{className:`${$?"text-base":"text-xl md:text-2xl"} text-brand-darkBlue font-black flex items-center gap-2 min-w-0`,children:[r.jsx(Me,{className:"w-6 h-6"}),r.jsx("span",{children:a.paperResearchHistory})]}),r.jsx("button",{type:"button",onClick:()=>P(!1),className:"text-slate-400 hover:bg-red-50 hover:text-red-500 rounded-full shrink-0 flex items-center justify-center transition-colors w-11 h-11",children:r.jsx(pe,{size:24})})]}),r.jsx("div",{ref:m,className:`flex-1 overflow-y-auto space-y-4 md:space-y-5 custom-scrollbar ${$?"p-3":"p-6 md:p-8"}`,children:o.messages.map((u,B)=>r.jsxs("div",{className:`flex flex-col ${B===o.messages.length-1?"opacity-100":"opacity-80 hover:opacity-100"} transition-opacity`,children:[r.jsx("div",{className:"flex items-center gap-3 mb-2",children:r.jsx("span",{className:`font-bold inline-flex items-center justify-center shadow-sm tracking-wide ${$?"text-xs":"text-xs md:text-sm"} px-3 py-1 rounded-full ${u.role==="user"?"bg-slate-700 text-white":"bg-gray-200 text-gray-600"}`,children:u.role==="user"?a.paperResearchYou:ge})}),r.jsx("div",{className:`${$?"text-sm":"text-base md:text-lg"} text-slate-700 border-gray-200 bg-white/50 leading-relaxed border-l-4 pl-4 pr-3 py-2 rounded-r-lg`,children:ut(u.text)})]},u.id))})]})}),be&&r.jsx("div",{role:"dialog","aria-modal":"true",className:"pointer-events-auto absolute inset-0 z-[110] flex items-center justify-center bg-black/70 p-4",children:r.jsxs("div",{className:"max-w-md rounded-2xl border border-white/10 bg-slate-950/90 p-5 shadow-xl backdrop-blur",children:[r.jsx("p",{className:"mb-4 text-sm text-white",children:a.leaveRisk}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{type:"button",className:"rounded-lg border border-white/15 bg-white/10 px-3 py-2 text-sm font-semibold text-white transition hover:bg-white/20 focus:outline-none focus:ring-2 focus:ring-cyan-300",onClick:()=>xe(!1),children:a.stay}),r.jsx("button",{type:"button",className:"rounded-lg border border-rose-300/40 bg-rose-400/20 px-3 py-2 text-sm font-semibold text-white transition hover:bg-rose-400/30 focus:outline-none focus:ring-2 focus:ring-rose-300",onClick:H,children:a.leave})]})]})})]})}export{Bt as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.