@jetcrab/pi-desk 1.1.30-dev → 1.1.31
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/package.json +1 -1
- package/temp/build/pi-desk/release/.next/BUILD_ID +1 -1
- package/temp/build/pi-desk/release/.next/build-manifest.json +2 -2
- package/temp/build/pi-desk/release/.next/prerender-manifest.json +3 -3
- package/temp/build/pi-desk/release/.next/required-server-files.js +3 -3
- package/temp/build/pi-desk/release/.next/required-server-files.json +3 -3
- package/temp/build/pi-desk/release/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_global-error.html +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_global-error.rsc +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/api/health/route.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/page.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/project-preview/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/middleware-build-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/pages/500.html +1 -1
- package/temp/build/pi-desk/release/.next/server/server-reference-manifest.json +1 -1
- package/temp/build/pi-desk/release/.next/static/chunks/app/{page-978906de76a8dcfe.js → page-c27bac30ceaea98b.js} +1 -1
- package/temp/build/pi-desk/release/.next/trace-build +1 -1
- /package/temp/build/pi-desk/release/.next/static/{ErYBfYXAir5b-6rlacGvL → n_zNpuntCtgSLQXHItXgr}/_buildManifest.js +0 -0
- /package/temp/build/pi-desk/release/.next/static/{ErYBfYXAir5b-6rlacGvL → n_zNpuntCtgSLQXHItXgr}/_ssgManifest.js +0 -0
|
@@ -151,7 +151,7 @@ textarea.pi-desk-ui-control{min-height:13rem;resize:vertical;font-family:ui-mono
|
|
|
151
151
|
@container (max-width:28rem){.pi-desk-ui-action-row-mobile-stack{align-items:flex-start;flex-direction:column}.pi-desk-ui-key-value{grid-template-columns:minmax(0,1fr)}.pi-desk-ui-key-value-action{justify-self:start}}
|
|
152
152
|
`;function ex(...e){return e.filter(Boolean).join(" ")}function eb({className:e,children:t,...s}){return(0,n.jsxs)("div",{...s,"data-pi-desk-ui-root":"",className:ex("pi-desk-ui-root",e),children:[(0,n.jsx)("style",{href:"pi-desk-ui",precedence:"pi-desk-ui",children:ef}),t]})}function ev({className:e,...t}){return(0,n.jsx)("input",{...t,type:"checkbox",className:ex("pi-desk-ui-checkbox",e)})}r.Component;var ew=s(84942);let ey=[{key:"all",label:"policyAll"},{key:"allow",label:"policyAllow"},{key:"deny",label:"policyDeny"},{key:"none",label:"policyNone"}];function ek({label:e,rule:t,options:s,disabled:i,onChange:a}){let{t:l}=(0,b.Bd)("capabilityModes"),[o,c]=(0,r.useState)(()=>void 0!==t.allow?0===t.allow.length?"none":"allow":t.deny?.length?"deny":"all"),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(160),[v,w]=(0,r.useState)(()=>[...new Set([...t.allow??[],...t.deny??[]])]),y="deny"===o||"all"===o||"allow"===o&&d?"deny":"allow",k=t[y]??[],j=new Set(k),N=(0,r.useMemo)(()=>{let e=new Map(s.map(e=>[e.value,e]));for(let s of[...v,...t.allow??[],...t.deny??[]])e.has(s)||e.set(s,{value:s});return[...e.values()].sort((e,t)=>e.value.localeCompare(t.value))},[v,s,t.allow,t.deny]),S=m.trim(),E=N.filter(e=>(!h||!!j.has(e.value))&&(!S||`${e.value} ${e.label??""} ${e.description??""}`.toLowerCase().includes(S.toLowerCase())||S.includes("*")&&(0,ew.RC)({allow:[S]},e.value))),M=E.slice(0,f),z=S.length>0&&S.length<=256&&!j.has(S);function A(e){"all"===o&&e.length>0&&c("deny"),"none"===o&&e.length>0&&c("allow"),a({...t,[y]:e})}function $(e,t){A(t?[...new Set([...k,e])]:k.filter(t=>t!==e))}function R(){z&&!i&&(w(e=>[...new Set([...e,S])]),$(S,!0),p(""))}return(0,n.jsxs)(eb,{className:"flex min-h-0 flex-1 flex-col","aria-label":l("ruleEditor",{name:e}),children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 border-b px-4 py-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("div",{className:"flex flex-wrap gap-1",role:"group","aria-label":l("ruleMode",{name:e}),children:ey.map(e=>(0,n.jsxs)(I.$,{size:"sm",variant:o===e.key?"secondary":"ghost","aria-pressed":o===e.key,disabled:i,onClick:()=>{var s;c(s=e.key),u(!1),g(!1),"all"===s?a({}):"none"===s?a({allow:[]}):"deny"===s?a({deny:t.deny??[]}):a({allow:t.allow??[],...t.deny?.length?{deny:t.deny}:{}})},children:[o===e.key&&(0,n.jsx)(ep.A,{className:"size-3.5"}),l(e.label)]},e.key))}),"allow"===o&&(0,n.jsxs)(I.$,{size:"sm",variant:d?"secondary":"ghost",disabled:i,"aria-pressed":d,onClick:()=>{u(!d),g(!1)},children:[l("exclusions"),t.deny?.length?` \xb7 ${t.deny.length}`:""]})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,n.jsx)(eh.A,{className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{"aria-label":l("ruleSearch"),placeholder:l("ruleSearchPlaceholder"),maxLength:256,className:"pl-9 pr-9",value:m,disabled:i,onChange:e=>{p(e.target.value),x(160)},onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),R())}}),m&&(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost","aria-label":l("clearSearch"),className:"absolute right-0.5 top-1/2 -translate-y-1/2",onClick:()=>p(""),children:(0,n.jsx)(V.A,{className:"size-3.5"})})]}),(0,n.jsxs)(I.$,{size:"sm",variant:h?"secondary":"ghost","aria-pressed":h,onClick:()=>g(!h),children:[(0,n.jsx)(eg.A,{className:"size-4"}),(0,n.jsx)("span",{className:"hidden @min-[420px]:inline",children:l("selectedOnly")}),(0,n.jsx)("span",{className:"@min-[420px]:hidden",children:l("selectedShort")})]})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:[l("allow"===y?"allowRules":"excludeRules")," \xb7"," ",l("selectedCount",{count:k.length})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1",children:[(0,n.jsx)(I.$,{size:"sm",variant:"ghost",disabled:i||0===M.length,onClick:()=>A([...new Set([...k,...M.map(e=>e.value)])]),children:l("selectVisible")}),k.length>0&&(0,n.jsx)(I.$,{size:"sm",variant:"ghost",disabled:i,onClick:()=>A([]),children:l("clearSelected")})]})]})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain p-3",children:[z&&(0,n.jsxs)(I.$,{variant:"outline",disabled:i,className:"mb-3 h-auto min-h-9 max-w-full justify-start",onClick:R,children:[(0,n.jsx)(U.A,{className:"size-4 shrink-0"}),l("addRule")," ",(0,n.jsx)("span",{className:"min-w-0 truncate font-mono",children:S})]}),(0,n.jsx)("div",{className:"grid min-w-0 grid-cols-1 gap-1 @min-[620px]:grid-cols-2",children:M.map(e=>{let t=j.has(e.value);return(0,n.jsxs)("label",{className:(0,C.cn)("flex min-h-9 min-w-0 cursor-pointer items-start gap-3 rounded-lg px-3 py-2 transition-colors hover:bg-muted",t&&"bg-accent text-accent-foreground",i&&"pointer-events-none opacity-50"),children:[(0,n.jsx)(ev,{checked:t,disabled:i,"aria-label":l("allow"===y?"allowValue":"excludeValue",{name:e.value}),className:"mt-1 shrink-0",onChange:t=>$(e.value,t.target.checked)}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block break-all text-sm font-medium",children:e.label??e.value}),e.label&&e.label!==e.value&&(0,n.jsx)("span",{className:"block break-all font-mono text-xs text-muted-foreground",children:e.value}),e.description?(0,n.jsxs)("details",{className:"mt-0.5 text-xs leading-5 text-muted-foreground",onClick:e=>e.stopPropagation(),children:[(0,n.jsx)("summary",{className:"line-clamp-1 cursor-pointer list-none",children:e.description}),(0,n.jsx)("span",{className:"block whitespace-pre-wrap break-words pt-1 text-sm",children:e.description})]}):e.value.includes("*")?(0,n.jsx)("span",{className:"block text-xs text-muted-foreground",children:l("pattern")}):null]})]},e.value)})}),0===M.length&&(0,n.jsx)("p",{className:"px-3 py-6 text-sm text-muted-foreground",children:S?l("noMatches"):h?l("noSelection"):l("enterPattern")}),E.length>M.length&&(0,n.jsx)(I.$,{variant:"ghost",className:"mt-3",onClick:()=>x(e=>e+160),children:l("moreRules",{count:E.length-M.length})})]})]})}function ej({modeKey:e,mode:t,catalog:s,disabled:i,onChange:a}){var l;let{t:o}=(0,b.Bd)("capabilityModes"),c=(0,r.useMemo)(()=>(function(e,t,s){let n=[{key:"tools",label:s,options:e?.tools??[],target:{kind:"tools"}},{key:"skills",label:"Skills",options:e?.skills??[],target:{kind:"skills"}}];for(let s of new Set([...Object.keys(e?.plugins??{}),...Object.keys(t.plugins??{})])){let r=e?.plugins[s]??{};for(let e of new Set([...Object.keys(r),...Object.keys(t.plugins?.[s]??{})]))n.push({key:`plugin:${s}:${e}`,label:r[e]?.label??`${s} / ${e}`,options:r[e]?.options??[],target:{kind:"plugin",pluginName:s,group:e}})}return n})(s,t,o("groupTools")),[s,t,o]),[d,u]=(0,r.useState)("tools"),m=c.find(e=>e.key===d)??c[0];return(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col",children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-3",children:(0,n.jsxs)("label",{className:"flex max-w-xl flex-wrap items-center gap-2 text-sm font-medium",children:[(0,n.jsx)("span",{children:o("modeName")}),(0,n.jsx)(em.p,{"aria-label":o("modeName"),value:t.name,maxLength:64,disabled:i,className:"min-w-40 flex-1",onChange:e=>a({...t,name:e.target.value})})]})}),(0,n.jsx)("div",{className:"flex shrink-0 flex-wrap gap-1 border-b px-4 py-2",role:"tablist","aria-label":o("category"),children:c.map(e=>(0,n.jsx)(I.$,{variant:e.key===m.key?"secondary":"ghost",size:"sm",role:"tab","aria-selected":e.key===m.key,onClick:()=>u(e.key),children:e.label},e.key))}),(0,n.jsx)(ek,{label:m.label,rule:"plugin"===(l=m.target).kind?t.plugins?.[l.pluginName]?.[l.group]??{}:t[l.kind]??{},options:m.options,disabled:i,onChange:e=>a(function(e,t,s){let n={...void 0===s.allow?{}:{allow:[...new Set(s.allow)]},...s.deny?.length?{deny:[...new Set(s.deny)]}:{}},r=0===Object.keys(n).length;if("plugin"!==t.kind){let s={...e};return r?delete s[t.kind]:s[t.kind]=n,s}let i={...e.plugins?.[t.pluginName]};r?delete i[t.group]:i[t.group]=n;let a={...e.plugins};Object.keys(i).length?a[t.pluginName]=i:delete a[t.pluginName];let l={...e};return Object.keys(a).length?l.plugins=a:delete l.plugins,l}(t,m.target,e))},`${e}:${m.key}`)]})}var eN=s(5464);function eI({open:e,deleteName:t,saving:s,error:r,onCancel:i,onDelete:a,onLeave:l}){let{t:o}=(0,b.Bd)("capabilityModes");return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||s||i()},children:(0,n.jsxs)(eN.hA,{className:"z-[150]",showCloseButton:!s,children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:o(t?"deleteConfirm":"saveConfirm")}),(0,n.jsx)(eN.uX,{children:t?o("deleteDescription",{name:t}):o("unsavedDescription")})]}),r&&(0,n.jsx)("p",{role:"alert",className:"px-4 pb-3 text-sm text-destructive",children:r}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{variant:"outline",disabled:s,onClick:i,children:o("cancel")}),t?(0,n.jsx)(I.$,{variant:"destructive",onClick:a,children:o("delete")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{variant:"ghost",disabled:s,onClick:()=>l("discard"),children:o("discard")}),(0,n.jsx)(I.$,{disabled:s,onClick:()=>l("save"),children:o(s?"saving":"saveContinue")})]})]})]})})}function eS({modeNames:e,onBeforeLeaveChange:t}){let{t:s}=(0,b.Bd)("capabilityModes"),{clientId:i}=(0,ei.gM)(),a=(0,X.G)(),l=function(e){let{t}=(0,b.Bd)("capabilityModes"),[s,n]=(0,r.useState)(null),[i,a]=(0,r.useState)({}),[l,o]=(0,r.useState)(null),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(null),[x,v]=(0,r.useState)(!1),w=(0,r.useRef)(null),y=(0,r.useRef)(null),k=null!==s&&JSON.stringify(s)!==JSON.stringify(i);(0,r.useEffect)(()=>{let e=new AbortController;return y.current=e,()=>{e.abort(),w.current?.(!1),w.current=null}},[]);let j=(0,r.useCallback)(async(r=!1)=>{if(null!==s&&!r)return i;m(!0),f(null);try{let t=await e.get(y.current?.signal);if(y.current?.signal.aborted)return null;return o(t.catalog),null!==s&&k||(n(t.modes),a(structuredClone(t.modes))),null!==s&&k?i:t.modes}catch(e){return y.current?.signal.aborted||f(e instanceof Error?e.message:t("catalogFailed")),null}finally{y.current?.signal.aborted||m(!1)}},[e,k,i,s,t]),N=(0,r.useCallback)(async e=>{if(null===e)return void d(null);let t=await j();t&&Object.hasOwn(t,e)&&d(e)},[j]),I=(0,r.useCallback)(async(e=!1)=>{let s=await j();if(!s)return;let n=e&&c?s[c]:void 0,r=crypto.randomUUID(),i=function(e,t){let s=new Set(Object.values(e).map(e=>e.name));if(!s.has(t))return t;let n=2;for(;s.has(`${t} ${n}`);)n+=1;return`${t} ${n}`}(s,n?t("copySuffix",{name:n.name}):t("newMode"));a({...s,[r]:{...n?structuredClone(n):{},name:i}}),d(r)},[j,c,t]),S=(0,r.useCallback)(e=>{c&&a(t=>({...t,[c]:e}))},[c]),C=(0,r.useCallback)(()=>{c&&(a(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==c))),d(null))},[c]),E=(0,r.useCallback)(async()=>{if(!k)return!0;h(!0),f(null);try{let t=await e.replace(i,y.current?.signal);if(y.current?.signal.aborted)return!1;return n(t),a(structuredClone(t)),!0}catch(e){return y.current?.signal.aborted||f(e instanceof Error?e.message:t("saveFailed")),!1}finally{y.current?.signal.aborted||h(!1)}},[e,k,i,t]),M=(0,r.useCallback)(()=>k?(v(!0),new Promise(e=>{w.current=e})):Promise.resolve(!0),[k]);return{draft:i,saved:s,catalog:l,selected:c,loading:u,saving:p,error:g,dirty:k,leaveOpen:x,beforeLeave:M,decideLeave:(0,r.useCallback)(async e=>{("save"!==e||await E())&&(v(!1),w.current?.("cancel"!==e),w.current=null)},[E]),load:j,select:N,add:I,update:S,remove:C,save:E}}((0,r.useMemo)(()=>(function(e){async function t(t,s,n,r){return eu(e,t,s,n,{signal:r,fallbackMessage:(0,ed.B)({msg:"能力模式请求失败",i18n:{key:"errors:capabilityFailed"}})})}return{get:e=>t("/api/capability-modes/get",{},el,e),async replace(e,s){let n=eo.safeParse({modes:e});if(!n.success)throw Error((0,ed.B)({msg:"请检查模式规则",i18n:{key:"errors:capabilityRuleInvalid"}}));return await t("/api/capability-modes/replace",n.data,ec,s),n.data.modes}}})(i),[i])),[o,c]=(0,r.useState)(null),{beforeLeave:d}=l;(0,r.useEffect)(()=>(t(d),()=>t(null)),[d,t]);let u=null===l.saved?e:(0,er.HE)(l.draft),m=l.selected?l.draft[l.selected]:void 0,p=l.loading||l.saving,h=async()=>{await l.save()&&a.success(s("saved"))},g=(0,n.jsxs)(I.$,{size:"sm",disabled:!l.dirty||p,onClick:()=>void h(),children:[l.saving?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(Z.A,{className:"size-4"}),l.saving?s("saving"):s("saveModes")]});return(0,n.jsxs)("section",{"aria-label":s("settings"),className:"flex h-full min-h-0 flex-col bg-background",children:[(0,n.jsxs)("header",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-b px-4 py-3",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"shrink-0 text-sm font-medium",children:s("editMode")}),(0,n.jsxs)(ea.l6,{value:l.selected??"",disabled:p,onValueChange:e=>{"string"==typeof e&&l.select(e||null)},children:[(0,n.jsx)(ea.bq,{"aria-label":s("selectMode"),className:"w-40 sm:w-48",children:(0,n.jsx)(ea.yv,{children:l.selected?u[l.selected]||s("unnamedMode"):s("allDefault")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[140]",children:[(0,n.jsx)(ea.eb,{value:"",children:s("allDefault")}),Object.entries(u).map(([e,t])=>(0,n.jsx)(ea.eb,{value:e,children:t||s("unnamedMode")},e))]})]})]}),(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,n.jsxs)(I.$,{size:"sm",variant:"ghost",disabled:p,onClick:()=>void l.add(),children:[(0,n.jsx)(U.A,{className:"size-4"}),s("addMode")]}),m&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost","aria-label":s("copyMode"),title:s("copyTitle"),disabled:p,onClick:()=>void l.add(!0),children:(0,n.jsx)(ee.A,{className:"size-4"})}),(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost","aria-label":s("deleteMode"),title:s("deleteTitle"),disabled:p,onClick:()=>c(m.name||s("unnamedMode")),children:(0,n.jsx)(et.A,{className:"size-4"})})]}),l.catalog&&(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost","aria-label":s("refreshCatalog"),title:s("refreshCatalog"),disabled:p,onClick:()=>void l.load(!0),children:(0,n.jsx)(es.A,{className:"size-4"})}),(0,n.jsx)("span",{className:"ml-1 hidden sm:inline-flex",children:g})]})]}),l.error&&(0,n.jsxs)("div",{role:"alert",className:"shrink-0 border-b px-4 py-3 text-sm text-destructive",children:[l.error,(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:()=>void l.load(!0),children:s("retryRead")})]}),l.loading&&(0,n.jsxs)("div",{role:"status",className:"flex shrink-0 items-center gap-2 border-b px-4 py-3 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),s("loadingCatalog")]}),m&&l.selected?(0,n.jsx)(ej,{modeKey:l.selected,mode:m,catalog:l.catalog,disabled:l.saving,onChange:l.update}):(0,n.jsxs)("div",{className:"flex items-start gap-3 p-6",children:[(0,n.jsx)(en.A,{className:"mt-0.5 size-6 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:"text-sm font-semibold",children:s("allEnabled")}),(0,n.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:s("allDescription")})]})]}),(0,n.jsxs)("footer",{className:"mt-auto flex shrink-0 items-center justify-between gap-3 border-t px-4 py-3 pb-[max(.75rem,env(safe-area-inset-bottom))] text-xs text-muted-foreground sm:py-2",children:[(0,n.jsx)("span",{role:"status",children:l.dirty?s("unsaved"):s("allIsDefault")}),(0,n.jsx)("span",{className:"sm:hidden",children:g})]}),(0,n.jsx)(eI,{open:l.leaveOpen||null!==o,deleteName:o,saving:l.saving,error:l.leaveOpen?l.error:null,onCancel:()=>{null!==o?c(null):l.decideLeave("cancel")},onDelete:()=>{l.remove(),c(null)},onLeave:e=>void l.decideLeave(e)})]})}var eC=s(87372),eE=s(79566),eM=s(13344),ez=s(54359),eA=s(24022),e$=s(77483),eR=s(95526),eP=s(66584),eD=s(76085),eT=s(58619),eO=s(90695),eL=s(6609);let eF={plugin:eC.A,server:eE.A,rocket:eM.A,settings:ez.A,panel:eA.A,message:e$.A,terminal:w.A,file:eR.A,folder:eP.A,bot:eD.A,wrench:eT.A,database:eO.A,globe:eL.A},eB=new Map;function eq({icon:e,className:t}){if(e?.type==="svg"){let s=function(e){if(eB.has(e))return eB.get(e)??null;let t=e.trim(),s=t.length>16384||!/^<svg[\s>]/i.test(t)||!/<\/svg>$/i.test(t)||/<\s*(script|foreignObject|iframe|object|embed|link|style)\b/i.test(t)||/\son[a-z]+\s*=/i.test(t)||/(javascript:|data:text\/html|https?:\/\/)/i.test(t)?null:t;return eB.set(e,s),s}(e.content);if(s)return(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("block [&>svg]:size-full",t),dangerouslySetInnerHTML:{__html:s}})}let s=e?.type==="builtin"?eF[e.name]:eC.A;return(0,n.jsx)(s,{"aria-hidden":"true",className:t})}var e_=s(94173),eW=s(90434),eY=s(86758),eV=s(81649);function eU({error:e,children:t}){let{t:s}=(0,b.Bd)("common"),r=e.message.trim().split(/\r?\n/)[0]||s("unknownError");return(0,n.jsxs)("div",{className:"mt-1 min-w-0",children:[(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:r}),(0,n.jsxs)(eV.Nt,{defaultOpen:!1,children:[(0,n.jsxs)(eV.R6,{className:"group mt-1 inline-flex min-h-8 cursor-pointer items-center gap-2 rounded-md text-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eY.A,{"aria-hidden":"true",className:"size-4 shrink-0 transition-transform group-aria-expanded:rotate-180 motion-reduce:transition-none"}),s("errorDetails")]}),(0,n.jsx)(eV.Ke,{className:"h-[var(--collapsible-panel-height)] overflow-hidden transition-[height,opacity] duration-200 ease-out data-starting-style:h-0 data-starting-style:opacity-0 data-ending-style:h-0 data-ending-style:opacity-0 motion-reduce:transition-none",children:(0,n.jsxs)("div",{className:"space-y-3 pt-2",children:[(0,n.jsx)("pre",{className:"max-h-[min(20rem,45dvh)] overflow-auto rounded-md bg-background p-3 font-mono text-sm leading-relaxed whitespace-pre-wrap [overflow-wrap:anywhere]",children:e.stack||e.message}),t]})})]})]})}function eK({pluginName:e,kind:t,contributionName:s,target:i,targetKey:a,className:l,layout:o="fill"}){let{t:c}=(0,b.Bd)("pluginManagement"),d=(0,Q.t4)();(0,Q.So)();let u=d.getEntryState(e),m="ready"===u.status?u.runtime:u.status,p="failed"===u.status?u.error:null,h=(0,r.useRef)(null),g=(0,r.useRef)(i),f=a??i,x="session-header-item"===i.kind?i.presentation:void 0,[w,y]=(0,r.useState)(0),[k,j]=(0,r.useState)({status:"loading"});(0,r.useEffect)(()=>{g.current=i},[i]),(0,r.useEffect)(()=>{let n=h.current;if(!n)return;let r=new AbortController,i=!0,a=null;if("ready"!==u.status)return queueMicrotask(()=>{i&&j(p?{status:"error",error:p}:{status:"loading"})}),()=>{i=!1,r.abort()};let l=Promise.resolve().then(()=>i?((a=document.createElement("div")).className="intrinsic"===o?"inline-block min-h-0 min-w-0 align-top":"inline"===o?"min-w-0 w-full":"h-full min-h-0 w-full min-w-0",n.append(a),d.mountContribution({pluginName:e,kind:t,contributionName:s,container:a,target:g.current,signal:r.signal})):null);return queueMicrotask(()=>{i&&j({status:"loading"})}),l.then(e=>{i&&e&&j({status:"ready"})},e=>{i&&j({status:"error",error:e instanceof Error?e:Error(String(e))})}),()=>{i=!1,r.abort(),a?.remove(),l.then(async n=>{if(n)try{await n()}catch(n){console.error("[Pi Desk][PluginHost] Contribution disposer 执行失败",{pluginName:e,kind:t,contributionName:s,errorName:n instanceof Error?n.name:"UnknownError",message:n instanceof Error?n.message:String(n)})}},()=>void 0)}},[w,s,m,u.status,p,t,o,f,e,d]);let N=()=>{if("failed"===u.status){j({status:"loading"}),d.retryEntry(e).catch(t=>{"failed"===d.getEntryState(e).status&&j({status:"error",error:t instanceof Error?t:Error(String(t))})});return}"failed"!==d.getContributionLoadState(e,t,s,x).status?y(e=>e+1):(j({status:"loading"}),d.retryContribution(e,t,s,x).then(()=>{d.getEntryState(e)===u&&y(e=>e+1)},t=>{d.getEntryState(e)===u&&j({status:"error",error:t instanceof Error?t:Error(String(t))})}))},S="loading"===k.status?"h-[200px] w-[360px]":"error"===k.status?"w-[min(480px,calc(100dvw-3rem))]":"h-fit w-fit";return(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar relative min-h-0 min-w-0","intrinsic"===o?(0,C.cn)("max-h-[calc(100dvh-7rem)] max-w-[calc(100dvw-3rem)] overflow-auto max-sm:max-h-[calc(100dvh-5rem)] max-sm:max-w-[calc(100dvw-2rem)]",S):"inline"===o?"w-full":"h-full w-full",l),children:[(0,n.jsx)("div",{ref:h,"data-pi-desk-plugin":e,"data-pi-desk-kind":t,"data-pi-desk-contribution":s,className:(0,C.cn)("intrinsic"===o?"inline-block min-h-0 min-w-0 align-top":"inline"===o?"w-full min-w-0":"h-full min-h-0 w-full min-w-0","error"===k.status&&"hidden")}),"loading"===k.status&&"widget"!==t&&"session-header-item"!==t?(0,n.jsxs)("div",{role:"status",className:(0,C.cn)("flex items-center text-sm text-muted-foreground","inline"===o?"min-h-7 gap-1 py-1":"absolute inset-0 justify-center bg-popover p-6"),children:[(0,n.jsx)(v.A,{className:"mr-2 size-4 shrink-0 animate-spin"}),(0,n.jsx)("span",{className:"min-w-0 truncate",children:c("viewLoading")})]}):null,"error"===k.status&&"inline"===o?(0,n.jsx)("div",{role:"alert",className:"min-w-0",children:(0,n.jsxs)(eW.AM,{children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":c("viewFailed"),title:c("viewFailed"),className:"text-destructive"}),children:(0,n.jsx)(e_.A,{className:"size-4"})}),(0,n.jsxs)(eW.hl,{align:"start",finalFocus:!0,children:[(0,n.jsx)(eW.eO,{children:c("viewFailed")}),(0,n.jsx)(eU,{error:k.error,children:(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e," \xb7 ",t," \xb7 ",s]})}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",onClick:N,children:[(0,n.jsx)(es.A,{}),c("retry")]})]})]})}):"error"===k.status?(0,n.jsx)("div",{role:"alert",className:(0,C.cn)("flex items-center justify-center overflow-auto bg-background p-4","fill"===o&&"absolute inset-0"),children:(0,n.jsx)("div",{className:"w-full max-w-xl rounded-lg border border-destructive/35 bg-muted p-4",children:(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)(e_.A,{className:"mt-0.5 size-5 shrink-0 text-destructive"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"font-medium text-destructive",children:c("viewFailed")}),(0,n.jsx)(eU,{error:k.error,children:(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e," \xb7 ",t," \xb7 ",s]})}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:N,children:[(0,n.jsx)(es.A,{}),c("retry")]})]})]})})}):null]})}function eH({pluginName:e,descriptor:t,workSessions:s,preferredWorkId:i,onClose:a}){let{t:l}=(0,b.Bd)("pluginManagement"),o=(0,Q.t4)();(0,Q.So)();let c=o.getEntryState(e),[d]=(0,r.useState)(()=>{let e=s.find(e=>e.workId===i);return e?{source:{workId:e.workId,sessionId:e.sessionId,branchId:e.branchId},cwd:e.cwd}:null}),u=(0,r.useMemo)(()=>({kind:"application",initialContext:d,close:()=>{o.getEntryState(e)===c&&a()}}),[c,d,a,e,o]),m="host"===t.chrome;return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:(e,t)=>{e||"focus-out"===t.reason||a()},children:(0,n.jsxs)(eN.hA,{finalFocus:!1,showCloseButton:!1,className:(0,C.cn)("w-fit max-w-[calc(100dvw-2rem)] max-h-[calc(100dvh-2rem)]",!m&&"rounded-none border-0 bg-transparent shadow-none ring-0"),children:[m?(0,n.jsx)(eN.Hl,{className:"border-b px-4 py-3",children:(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground",children:(0,n.jsx)(eq,{icon:t.icon,className:"size-5"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{className:"break-words",children:t.title}),(0,n.jsx)(eN.uX,{className:"sr-only",children:e})]}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon","aria-label":l("closeNamedApplication",{name:t.title}),title:l("closeApplication"),onClick:a,className:"text-muted-foreground",children:(0,n.jsx)(V.A,{className:"size-4"})})]})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eN.YM,{className:"sr-only",children:t.title}),(0,n.jsx)(eN.uX,{className:"sr-only",children:e})]}),(0,n.jsx)("div",{className:"min-h-0 min-w-0 max-w-full overflow-hidden",children:(0,n.jsx)(eK,{pluginName:e,kind:"application",contributionName:t.contributionName,target:u,layout:"intrinsic"})})]})})}function eG({pluginName:e,descriptor:t,source:s,onClose:i}){let a=(0,r.useMemo)(()=>({kind:"composer-panel",source:s,close:i}),[i,s]);return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>!e&&i(),children:(0,n.jsxs)(eN.hA,{finalFocus:!1,className:"h-[min(720px,calc(100dvh-2rem))] max-w-4xl max-sm:h-[var(--pi-desk-content-height)] max-sm:max-h-[var(--pi-desk-content-height)] max-sm:w-full max-sm:max-w-none max-sm:rounded-none max-sm:border-0",children:[(0,n.jsx)(eN.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground",children:(0,n.jsx)(eq,{icon:t.icon,className:"size-5"})}),(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)(eN.YM,{className:"truncate",children:t.label}),(0,n.jsx)(eN.uX,{className:"sr-only",children:e})]})]})}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:(0,n.jsx)(eK,{pluginName:e,kind:"composer-panel",contributionName:t.contributionName,target:a,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})})]})})}var eJ=s(15265),eQ=s(5816),eX=s(31026),eZ=s(59095),e0=s(12720),e1=s(43016),e2=s(73392);function e5({className:e,orientation:t="horizontal",...s}){return(0,n.jsx)(eX.p,{"data-slot":"tabs","data-orientation":t,className:(0,C.cn)("group/tabs flex gap-2 data-horizontal:flex-col",e),...s})}let e3=(0,e2.F)("group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",{variants:{variant:{default:"bg-muted",line:"gap-1 bg-transparent"}},defaultVariants:{variant:"default"}});function e4({className:e,variant:t="default",...s}){return(0,n.jsx)(eZ.j,{"data-slot":"tabs-list","data-variant":t,className:(0,C.cn)(e3({variant:t}),e),...s})}function e6({className:e,...t}){return(0,n.jsx)(e0.M,{"data-slot":"tabs-trigger",className:(0,C.cn)("relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4","group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent","data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground","after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",e),...t})}function e8({className:e,...t}){return(0,n.jsx)(e1.R,{"data-slot":"tabs-content",className:(0,C.cn)("flex-1 text-sm outline-none",e),...t})}var e7=s(36670),e9=s(99084);let te=new Set(["bash","edit","find","grep","ls","read","write"]),tt="__pi_desk_unknown_schema_type__",ts={before_agent_start:{label:"eventAgentStart",description:"eventAgentStartDescription"},context:{label:"eventContext",description:"eventContextDescription"},input:{label:"eventInput",description:"eventInputDescription"},before_provider_request:{label:"eventProvider",description:"eventProviderDescription"},tool_call:{label:"eventToolCall",description:"eventToolCallDescription"},tool_result:{label:"eventToolResult",description:"eventToolResultDescription"},message_end:{label:"eventMessageEnd",description:"eventMessageEndDescription"},session_before_compact:{label:"eventBeforeCompact",description:"eventBeforeCompactDescription"}},tn={application:"contributionApplication","composer-panel":"contributionComposer","settings-page":"contributionSettings","message-view":"contributionMessage","session-sidebar-tab":"contributionSidebar",widget:"contributionWidget","session-header-item":"contributionSessionHeader"};function tr(e){let t=[];for(let s of e.extensions)for(let e of s.events){let n=ts[e.name];n&&t.push({name:e.name,count:e.count,path:s.path,label:n.label,description:n.description})}return t.sort((e,t)=>{let s=e.name.localeCompare(t.name);return 0===s?e.path.localeCompare(t.path):s})}function ti(e){return null===e||"object"!=typeof e||Array.isArray(e)?null:e}function ta({state:e}){let{t}=(0,b.Bd)("pluginManagement"),s=t("active"===e?"stateActive":"inactive"===e?"stateInactive":"stateShadowed");return(0,n.jsx)("span",{className:`rounded-md px-1.5 py-0.5 text-xs font-medium ${"active"===e?"bg-muted text-status-success":"inactive"===e?"bg-muted text-muted-foreground":"bg-muted text-status-warning"}`,children:s})}function tl({text:e,label:t}){let{t:s}=(0,b.Bd)("pluginManagement"),[i,a]=(0,r.useState)(!1);return(0,n.jsx)(I.$,{type:"button",size:"icon",variant:"ghost","aria-label":t,title:s(i?"copied":"copy"),onClick:()=>{(0,e9.x)(e).then(e=>{e&&a(!0)})},children:i?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})})}function to({title:e,text:t}){let{t:s}=(0,b.Bd)("pluginManagement");return(0,n.jsxs)("div",{className:"rounded-lg bg-muted",children:[(0,n.jsxs)("div",{className:"flex min-h-9 items-center justify-between gap-2 px-3",children:[(0,n.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:e}),(0,n.jsx)(tl,{text:t,label:s("copyNamed",{name:e})})]}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words px-3 py-3 font-mono text-sm leading-[1.6]",children:t})]})}function tc({title:e,description:t,children:s}){return(0,n.jsxs)(eV.Nt,{className:"border-t",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-8 w-full cursor-pointer items-center gap-2 py-2 text-left text-sm font-medium outline-none hover:text-muted-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:[(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),e]}),(0,n.jsx)(eV.Ke,{children:(0,n.jsxs)("div",{className:"space-y-3 pb-3",children:[t?(0,n.jsx)("p",{className:"text-sm leading-5 text-muted-foreground",children:t}):null,s]})})]})}function td({capabilities:e}){let{t}=(0,b.Bd)("pluginManagement"),s=tr(e);return 0===s.length?null:(0,n.jsx)(tc,{title:t("dynamicTitle"),description:t("dynamicDescription"),children:(0,n.jsx)("div",{className:"divide-y",children:s.map((e,s)=>(0,n.jsxs)("div",{className:"px-3 py-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"text-xs font-semibold",children:e.name}),e.count>1?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["\xd7",e.count]}):null,(0,n.jsx)("span",{className:"text-xs font-medium",children:t(e.label)})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:t(e.description)}),(0,n.jsx)("p",{className:"mt-1 truncate font-mono text-xs text-muted-foreground",title:e.path,children:e.path})]},`${e.path}:${e.name}:${s}`))})})}function tu({tool:e}){let{t}=(0,b.Bd)("pluginManagement"),s=function(e){var t;let s=ti(e.properties);if(!s)return[];let n=new Set(Array.isArray(t=e.required)?t.filter(e=>"string"==typeof e):[]);return Object.entries(s).map(([e,t])=>{let s=ti(t);return{name:e,required:n.has(e),type:function e(t){let s=ti(t);if(!s)return tt;let n=Array.isArray(s.enum)?s.enum.filter(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e):[];if(n.length>0)return n.map(String).join(" | ");if("string"==typeof s.type){if("array"!==s.type)return s.type;let t=e(s.items);return t===tt?"array":`${t}[]`}for(let t of["anyOf","oneOf"]){if(!Array.isArray(s[t]))continue;let n=s[t].map(e).filter(e=>e!==tt);if(n.length>0)return[...new Set(n)].join(" | ")}return tt}(t),description:"string"==typeof s?.description?s.description:null}})}(e.parameters);return(0,n.jsxs)("div",{className:"mt-4",children:[(0,n.jsxs)("p",{className:"text-sm font-medium",children:[t("arguments")," \xb7 ",s.length>0?s.length:t("none")]}),(0,n.jsxs)("div",{className:"py-3",children:[s.length>0?(0,n.jsx)("div",{className:"space-y-2",children:s.map(e=>(0,n.jsxs)("div",{className:"grid gap-1 text-sm sm:grid-cols-[minmax(8rem,0.8fr)_minmax(0,1.5fr)] sm:gap-3",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[(0,n.jsx)("code",{className:"font-semibold",children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(e.required?"required":"optional")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.type===tt?t("unknown"):e.type})]}),(0,n.jsx)("p",{className:"min-w-0 break-words leading-5 text-muted-foreground",children:e.description??"—"})]},e.name))}):(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("noArguments")}),(0,n.jsxs)(eV.Nt,{className:"mt-3",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-8 cursor-pointer items-center gap-2 text-sm text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),t("rawSchema")]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,children:(0,n.jsx)("pre",{className:"mt-2 whitespace-pre-wrap break-words rounded-lg bg-muted p-3 font-mono text-sm leading-[1.6]",children:JSON.stringify(e.parameters,null,2)})})]})]})]})}function tm({detail:e}){let{t}=(0,b.Bd)("pluginManagement");return 0===e.tools.length?null:(0,n.jsx)(tc,{title:t("toolCapabilities"),description:t("toolDescription"),children:(0,n.jsx)("div",{className:"space-y-2",children:e.tools.map((e,s)=>(0,n.jsxs)(eV.Nt,{className:"border-b py-3 last:border-b-0",children:[(0,n.jsxs)(eV.R6,{className:"group w-full cursor-pointer text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"mr-2 inline-block size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),(0,n.jsxs)("span",{className:"inline-flex min-w-0 flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"font-semibold",children:e.name}),e.label&&e.label!==e.name?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.label}):null,(0,n.jsx)(ta,{state:e.state}),te.has(e.name)&&"shadowed"!==e.state?(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs font-medium text-foreground",children:t("overridesBuiltin")}):null]}),(0,n.jsx)("span",{className:"mt-1.5 block break-words text-sm leading-5 text-muted-foreground",children:e.description||t("noDescription")})]}),(0,n.jsxs)(eV.Ke,{keepMounted:!0,children:[(0,n.jsx)(tu,{tool:e}),e.promptSnippet||e.promptGuidelines.length>0?(0,n.jsxs)("div",{className:"mt-3 space-y-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"text-xs font-medium",children:t("systemPrompts")}),"active"!==e.state?(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("inactivePrompt")}):null]}),e.promptSnippet?(0,n.jsx)(to,{title:"Available tools",text:e.promptSnippet}):null,e.promptGuidelines.length>0?(0,n.jsx)(to,{title:`Guidelines \xb7 ${e.promptGuidelines.length}`,text:e.promptGuidelines.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}):null]}):null]})]},`${e.name}:${s}`))})})}function tp({title:e,content:t,truncated:s}){let{t:r}=(0,b.Bd)("pluginManagement");return(0,n.jsxs)(eV.Nt,{className:"mt-3",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-8 w-full cursor-pointer items-center gap-2 py-2 text-left text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),e]}),(0,n.jsxs)(eV.Ke,{keepMounted:!0,className:"border-t",children:[(0,n.jsx)("div",{className:"flex justify-end px-2 pt-1",children:(0,n.jsx)(tl,{text:t,label:r("copyNamed",{name:e})})}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words rounded-lg bg-muted p-3 font-mono text-sm leading-[1.6]",children:t}),s?(0,n.jsx)("p",{className:"py-2 text-sm text-status-warning",children:r("truncated")}):null]})]})}function th({detail:e}){let{t}=(0,b.Bd)("pluginManagement");return 0===e.skills.length&&0===e.prompts.length?null:(0,n.jsx)(tc,{title:t("resourcesTitle"),description:t("resourcesDescription"),children:(0,n.jsxs)("div",{className:"space-y-2",children:[e.skills.map(e=>(0,n.jsxs)("article",{className:"border-b py-4 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"font-semibold",children:e.name}),(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:t(e.modelVisible?"skillModelVisible":"manualOnly")})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:e.description}),(0,n.jsx)("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:e.path}),e.modelVisible?(0,n.jsx)("div",{className:"mt-2",children:(0,n.jsx)(to,{title:t("skillMetadata"),text:`name: ${e.name}
|
|
153
153
|
description: ${e.description}
|
|
154
|
-
location: ${e.path}`})}):null,(0,n.jsx)(tp,{title:t("viewSkillContent"),content:e.content,truncated:e.truncated})]},e.path)),e.prompts.map(e=>(0,n.jsxs)("article",{className:"border-b py-4 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)("code",{className:"font-semibold",children:["/",e.name]}),(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:t("manualOnly")})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:e.description}),(0,n.jsx)("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:e.path}),(0,n.jsx)(tp,{title:t("viewPromptContent"),content:e.content,truncated:e.truncated})]},e.path))]})})}function tg({capabilities:e,browserContributions:t}){let{t:s}=(0,b.Bd)("pluginManagement"),r=e.extensions.some(e=>e.events.length>0||e.commands.length>0||e.shortcuts.length>0||e.flags.length>0||e.messageRenderers.length>0||e.entryRenderers.length>0),i=e.piDesk.methods.length>0||e.piDesk.browserEntries.length>0||e.piDesk.messageDeclarations.length>0||t.length>0,a=e.themes.length>0||e.providers.length>0;return r||i||a?(0,n.jsx)(tc,{title:s("otherCapabilities"),children:(0,n.jsxs)("div",{className:"space-y-2",children:[i?(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs",children:[(0,n.jsx)("p",{className:"font-semibold",children:"Pi Desk"}),(0,n.jsxs)("div",{className:"mt-2 space-y-1.5 text-muted-foreground",children:[e.piDesk.methods.map(e=>(0,n.jsxs)("p",{children:["Method:",(0,n.jsxs)("code",{children:[e.pluginName,"/",e.method]})]},`${e.pluginName}:${e.method}`)),t.map(e=>(0,n.jsxs)("p",{children:[s(tn[e.kind]),":","message-view"===e.kind?e.viewKey:"application"===e.kind?e.title:"widget"===e.kind||"session-header-item"===e.kind?e.contributionName:e.label]},`${e.kind}:${e.contributionName}`)),e.piDesk.messageDeclarations.map(e=>(0,n.jsxs)("p",{children:[s("messageDeclarations"),(0,n.jsxs)("code",{children:[e.pluginName,"/",e.declarationName]})]},`${e.pluginName}:${e.declarationName}`))]})]}):null,r?e.extensions.map(e=>(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs",children:[(0,n.jsx)("code",{className:"block break-all font-semibold",children:e.path}),e.commands.length>0?(0,n.jsxs)("p",{className:"mt-2 leading-5 text-muted-foreground",children:["Commands:",e.commands.map(e=>`/${e.name}`).join("、")]}):null,e.shortcuts.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Shortcuts:",e.shortcuts.map(e=>e.shortcut).join("、")]}):null,e.flags.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Flags:",e.flags.map(e=>`--${e.name}`).join("、")]}):null,e.events.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Events:",e.events.map(e=>e.name).join("、")]}):null]},e.path)):null,a?(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs text-muted-foreground",children:[e.themes.length>0?(0,n.jsxs)("p",{children:["Theme:",e.themes.map(e=>e.name).join("、")]}):null,e.providers.length>0?(0,n.jsxs)("p",{className:"mt-1",children:["Provider:",e.providers.map(e=>e.name).join("、")]}):null]}):null]})}):null}function tf({plugin:e,detail:t,detailLoading:s,detailError:r,browserContributions:i,onRetry:a}){let{t:l}=(0,b.Bd)("pluginManagement"),{locale:o}=(0,eQ.i)(),c=function(e,t,s){let n=[];e.tools.length>0&&n.push({label:s("tagTools",{count:e.tools.length}),tone:"neutral"});let r=e.tools.reduce((e,t)=>"active"!==t.state?e:e+ +!!t.promptSnippet+t.promptGuidelineCount,0)+e.skills.filter(e=>e.modelVisible).length;r>0&&n.push({label:s("tagFixed",{count:r}),tone:"prompt"});let i=tr(e).reduce((e,t)=>e+t.count,0);i>0&&n.push({label:s("tagDynamic",{count:i}),tone:"dynamic"});let a=e.tools.filter(e=>"shadowed"!==e.state&&te.has(e.name)).length;a>0&&n.push({label:s("tagOverride",{count:a}),tone:"override"});let l=e.prompts.length+e.skills.filter(e=>!e.modelVisible).length;l>0&&n.push({label:s("tagManual",{count:l}),tone:"neutral"});let o=t.length+e.piDesk.methods.length+e.piDesk.messageDeclarations.length;o>0&&n.push({label:`Pi Desk ${o}`,tone:"neutral"});let c=e.providers.length+e.themes.length+e.extensions.reduce((e,t)=>e+t.commands.length+t.shortcuts.length+t.flags.length,0);return c>0&&n.push({label:s("tagInteraction",{count:c}),tone:"neutral"}),0===n.length&&e.extensions.length>0&&n.push({label:`Extension ${e.extensions.length}`,tone:"neutral"}),n}(e.capabilities,i,l);return(0,n.jsxs)("div",{className:"space-y-3 text-sm","data-testid":"plugin-capability-detail",children:[(0,n.jsx)("p",{className:"break-all font-mono text-xs text-muted-foreground",children:e.source}),c.length>0?(0,n.jsx)("div",{className:"flex flex-wrap gap-2","aria-label":l("capabilityCategories"),children:c.map(e=>(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-0.5 text-xs text-muted-foreground",children:e.label},e.label))}):null,e.capabilities.error?(0,n.jsx)("p",{className:"whitespace-pre-wrap break-words text-sm leading-5 text-status-warning",children:l("incompleteCapabilities",{error:(0,eJ.fD)(e.capabilities.error,o)})}):null,s?(0,n.jsxs)("div",{className:"flex items-center gap-2 py-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),l("loadingFullDetails")]}):r?(0,n.jsxs)("div",{className:"flex items-start gap-2",role:"alert",children:[(0,n.jsx)("p",{className:"min-w-0 flex-1 break-words text-sm text-destructive",children:r}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",onClick:a,children:[(0,n.jsx)(es.A,{"data-icon":"inline-start"}),l("retry")]})]}):t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(tm,{detail:t}),(0,n.jsx)(th,{detail:t})]}):null,(0,n.jsx)(td,{capabilities:e.capabilities}),(0,n.jsx)(tg,{capabilities:e.capabilities,browserContributions:i})]})}var tx=s(76782),tb=s(44980);function tv({className:e,size:t="default",...s}){return(0,n.jsx)(tx.l,{"data-slot":"switch","data-size":t,className:(0,C.cn)("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",e),...s,children:(0,n.jsx)(tb.p,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"})})}function tw({plugin:e,displayName:t,browserError:s,disabled:r,pending:i,browserRetryPending:a,onAction:l}){let{t:o}=(0,b.Bd)("pluginManagement"),c=e.operation?.phase,d="disabled"!==e.status;return(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-3",children:[i?(0,n.jsxs)("span",{role:"status",className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:["waiting"!==c?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):null,o(c&&"failed"!==c?`phase_${c}`:"submitting")]}):e.updateAvailable&&"extension"!==e.kind&&"failed"!==c?(0,n.jsx)(I.$,{size:"sm",disabled:r,onClick:()=>l("update"),children:o("update")}):null,"failed"===c?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||i,onClick:()=>l("retry"),children:o("retry")}):"failed"===e.status?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||i,onClick:()=>l("reload"),children:o("reloadOne")}):s&&e.pluginName?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||a,onClick:()=>l("retry-browser"),children:o("retryView")}):null,(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(tv,{checked:d,"aria-label":o("togglePlugin",{name:t}),disabled:r||i,onCheckedChange:e=>l(e?"enable":"disable")}),o(d?"enabled":"disabled")]}),"extension"!==e.kind?(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive","aria-label":o("removeNamed",{name:t}),title:o("remove"),disabled:r||i,onClick:()=>l("remove"),children:(0,n.jsx)(et.A,{})}):null]})}function ty({plugin:e,requestError:t,browserError:s}){let{t:r}=(0,b.Bd)("pluginManagement"),{locale:i}=(0,eQ.i)(),a=e.operation?.phase,l=[t,"failed"===a?e.operation?.message:null,e.error?(0,eJ.fD)(e.error.message,i):null,s,e.updateError?r("itemCheckFailed",{error:e.updateError}):null].filter((e,t,s)=>!!e&&s.indexOf(e)===t);return l.length||"waiting"===a||"failed"===e.status?(0,n.jsxs)("div",{className:"space-y-1",children:[l.map(e=>(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive [overflow-wrap:anywhere]",children:e},e)),l.length||"failed"!==e.status?null:(0,n.jsx)("p",{className:"text-sm text-destructive",children:r("notLoaded")}),"waiting"===a&&e.operation?.message?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operation.message}):null]}):null}function tk(e){let t=e.startsWith("npm:")?e.slice(4):e,s=/^((?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*)(?:@([^\s/]+))?$/i.exec(t);return s?{name:s[1],...s[2]?{version:s[2]}:{}}:null}function tj(e){return e.source.startsWith("npm:")?tk(e.source)?.name??e.source:e.pluginName??("extension"===e.kind?e.source.replaceAll("\\","/").split("/").at(-1):null)??e.source}function tN(e){return`source:${tk(e)?.name??e}`}function tI(e){switch(e.kind){case"batch":return"add"===e.input.action?"batchInstall":"update"===e.input.action?"updateSelected":"del"===e.input.action?"removeSelected":"setChannel";case"add":return"actionAdd";case"update":return"actionUpdate";case"del":return"actionDelete";case"enable":return"enable";case"disable":return"disable";case"reload":return"normal"===e.mode?"restartNormal":"actionReload"}}let tS=a.Yj().trim().min(1).max(128).regex(/^[a-zA-Z][a-zA-Z0-9._-]*$/),tC=a.Yj().trim().url().max(2048).refine(e=>{let t=new URL(e);return["https:","http:"].includes(t.protocol)&&!t.username&&!t.password&&!t.search&&!t.hash},"插件源必须是 HTTP 或 HTTPS 仓库地址"),tE=a.gM("mode",[a.Ik({mode:a.eu("auto")}).strict(),a.Ik({mode:a.eu("local")}).strict(),a.Ik({mode:a.eu("official")}).strict(),a.Ik({mode:a.eu("domestic")}).strict(),a.Ik({mode:a.eu("custom"),registry:tC}).strict()]),tM=a.Ik({description:a.Yj().trim().min(1).max(4e3).optional(),readme:a.Yj().trim().min(1).max(1024).optional()});a.Ik({description:a.Yj().optional(),piDesk:a.Ik({i18n:a.g1(a.Yj().min(1).max(35),tM).optional()}).passthrough().optional()}).passthrough();let tz=a.Ik({downloadSource:tE,recommendedRegistry:tC}).strict(),tA=a.Ik({downloadSource:tE}).strict(),t$=a.Ik({query:a.Yj().trim().max(200).default(""),page:a.ai().int().min(1).max(100).default(1),kind:a.k5(["all","desk","pi"]).default("all"),registry:tC.optional()}).strict(),tR=a.Ik({name:a.Yj().trim().min(1).max(214).regex(/^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/i),version:a.Yj().trim().min(1).max(128).optional(),registry:tC.optional()}).strict(),tP=a.Ik({name:a.Yj(),description:eJ.qf.nullable(),version:a.Yj(),publisher:a.Yj().nullable(),kind:a.k5(["desk","pi","unknown"]),official:a.zM(),registry:tC}).strict(),tD=a.Ik({items:a.YO(tP),hasMore:a.zM()}).strict(),tT=tP.extend({versions:a.YO(a.Yj()),readme:eJ.qf.nullable(),homepage:a.Yj().nullable(),repository:a.Yj().nullable(),compatible:a.zM().nullable(),compatibilityNote:a.Yj().nullable()}).strict();function tO({id:e,mode:t,registry:s,recommendedRegistry:r,savedRegistry:i,loading:a,saving:l,error:o,override:c,onMode:d,onRegistry:u,onSave:m,onRetry:p}){let{t:h}=(0,b.Bd)("pluginManagement"),g="auto"===t?r:"official"===t?"https://registry.npmjs.org":"domestic"===t?"https://mirrors.cloud.tencent.com/npm":"custom"===t?i??s:null,f=[...c?[{value:"default",label:h("useDefaultSource")}]:[],...["local","auto","domestic","official","custom"].map(e=>({value:e,label:h(`download_${e}`)}))];return(0,n.jsxs)("div",{className:"min-w-0 space-y-3 text-sm",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:e,className:"font-medium",children:h(c?"installDownloadSource":"downloadSource")}),(0,n.jsxs)(ea.l6,{value:t,items:f,disabled:a,onValueChange:e=>{e&&!l&&d(e)},children:[(0,n.jsx)(ea.bq,{id:e,className:"max-w-full",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:f.map(e=>(0,n.jsx)(ea.eb,{value:e.value,disabled:l,children:e.label},e.value))})]}),l?(0,n.jsx)("span",{role:"status",className:"text-muted-foreground",children:h("saving")}):null]}),"custom"===t?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:`${e}-url`,className:"block",children:h("registryUrl")}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(em.p,{id:`${e}-url`,type:"url",value:s,placeholder:"https://registry.example.com",className:"min-w-0 flex-1 basis-48",disabled:l,onChange:e=>u(e.target.value)}),m?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:l,onClick:m,children:h("save")}):null]})]}):!c&&g?(0,n.jsx)("p",{className:"break-all text-xs text-muted-foreground",children:g}):null,o?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:o}),p?(0,n.jsx)(I.$,{variant:"outline",size:"sm",onClick:p,children:h("retry")}):null]}):null]})}var tL=s(3058),tF=s(97724),tB=s(48742);function tq({className:e,...t}){return(0,n.jsx)(tF.y,{"data-slot":"checkbox",className:(0,C.cn)("peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",e),...t,children:(0,n.jsx)(tB.P,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none [&>svg]:size-3.5",children:(0,n.jsx)(ep.A,{})})})}function t_(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=e.snapshot?.plugins??[],i=t=>e.requests.has(tN(t.source))||!!(t.operation&&"failed"!==t.operation.phase),a=r.filter(t=>("updates"!==e.statusFilter||!!t.updateAvailable)&&("disabled"!==e.statusFilter||"disabled"===t.status)&&("failed"!==e.statusFilter||!!("failed"===t.status||t.operation?.phase==="failed"||t.updateError||t.pluginName&&e.browserErrors.has(t.pluginName)))&&`${tj(t)} ${t.description?(0,eJ.fD)(t.description,s):""}`.toLocaleLowerCase().includes(e.filter.trim().toLocaleLowerCase())),l=a.filter(e=>"extension"!==e.kind),o=r.filter(t=>e.selected.has(tN(t.source))),c=r.filter(e=>!0===e.updateAvailable&&"extension"!==e.kind&&!i(e)),d=c.filter(t=>e.selected.has(tN(t.source))),u=o.filter(e=>!i(e)),m=l.length>0&&l.every(t=>e.selected.has(tN(t.source))),p=l.some(t=>e.selected.has(tN(t.source))),h=["all","updates","disabled","failed"].map(e=>({value:e,label:t(`statusFilter_${e}`)}));return(0,n.jsxs)("section",{"aria-label":t("installed"),className:"flex min-h-0 min-w-0 flex-col gap-3",children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 bg-popover pb-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(em.p,{"aria-label":t("filterInstalled"),value:e.filter,onChange:t=>e.onFilter(t.target.value),placeholder:t("filterInstalled"),className:"min-w-40 flex-1 basis-52"}),(0,n.jsxs)(ea.l6,{value:e.statusFilter,items:h,onValueChange:t=>{t&&e.onStatusFilter(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("filterStatus"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:h.map(e=>(0,n.jsx)(ea.eb,{value:e.value,children:e.label},e.value))})]}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading||e.disabled,onClick:e.onRefresh,children:t(e.loading?"checkingUpdates":"checkUpdates")}),c.length>0?(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||e.loading,onClick:e.onUpdateAll,children:t("updateAll",{count:c.length})}):null,r.some(e=>"extension"!==e.kind)?(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:()=>e.onBatchMode(!e.batchMode),children:t(e.batchMode?"finishSelection":"batchManage")}):null]}),e.batchMode?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 rounded-lg bg-muted px-3 py-2",children:[(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,n.jsxs)("span",{className:"relative flex size-4 items-center justify-center",children:[(0,n.jsx)(tq,{checked:m,indeterminate:p&&!m,className:"data-indeterminate:[&_svg]:hidden",disabled:!l.length,onCheckedChange:t=>e.onSelect(l.map(e=>tN(e.source)),t)}),p&&!m?(0,n.jsx)(tL.A,{"aria-hidden":!0,className:"pointer-events-none absolute size-3.5"}):null]}),t(e.filter||"all"!==e.statusFilter?"selectFiltered":"selectAll")]}),(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("selectedCount",{count:o.length})}),o.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled||e.loading||!d.length,onClick:e.onUpdateSelected,children:t("updateSelected")}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled||!u.length,onClick:e.onRemoveSelected,children:t("removeSelected")}),(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:()=>e.onSelect([...e.selected],!1),children:t("clearSelection")})]}):null]}):null,e.errors.list?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.errors.list}):null]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto",children:e.loading&&!e.snapshot?(0,n.jsx)("p",{role:"status",className:"py-6 text-sm text-muted-foreground",children:t("loading")}):a.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:a.map(r=>{let a=tj(r),l=tN(r.source),o=r.pluginName?e.browserErrors.get(r.pluginName)??null:null;return(0,n.jsx)("article",{"aria-label":a,className:`min-w-0 px-4 py-3 ${e.selected.has(l)&&e.batchMode?"bg-accent/40":""}`,children:(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[e.batchMode&&"extension"!==r.kind?(0,n.jsx)("div",{className:"flex min-h-8 shrink-0 items-center",children:(0,n.jsx)(tq,{checked:e.selected.has(l),"aria-label":t("selectPlugin",{name:a}),onCheckedChange:t=>e.onSelect([l],t)})}):null,(0,n.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-1 basis-64 flex-wrap items-center gap-x-2 gap-y-1",children:[(0,n.jsx)(I.$,{variant:"link",className:"h-auto min-h-8 min-w-0 max-w-full justify-start p-0 text-left text-sm font-semibold whitespace-normal no-underline hover:underline [overflow-wrap:anywhere]","aria-label":t("viewDetails",{name:a}),onClick:()=>e.onDetail(r.source),children:a}),r.version?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",r.version]}):null,r.updateAvailable?(0,n.jsx)("span",{className:"inline-flex rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:r.availableVersion?t("newVersion",{version:r.availableVersion}):t("updateAvailable")}):null,r.updateTag&&"latest"!==r.updateTag?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:"dev"===r.updateTag?t("channelDev"):r.updateTag}):null]}),(0,n.jsx)(tw,{plugin:r,displayName:a,browserError:o,disabled:e.disabled,pending:i(r),browserRetryPending:e.requests.has(`entry:${r.pluginName}`),onAction:t=>e.onAction(r,t)})]}),r.description?(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:(0,eJ.fD)(r.description,s)}):null,(0,n.jsx)(ty,{plugin:r,browserError:o,requestError:e.errors[l]??e.errors[`entry:${r.pluginName}`]})]})]})},l)})}):(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:t(e.filter||"all"!==e.statusFilter?"noMatches":"empty")})})]})}function tW(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=new Map(e.snapshot?.plugins.filter(e=>e.source.startsWith("npm:")).map(e=>[tk(e.source)?.name,e]));return(0,n.jsxs)("section",{className:"min-w-0 space-y-4","aria-label":t("searchPlugins"),children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:"plugin-catalog-query",className:"sr-only",children:t("searchPlugins")}),(0,n.jsx)(em.p,{id:"plugin-catalog-query",value:e.query,placeholder:t("searchPlaceholder"),className:"min-w-40 flex-1 basis-56",maxLength:200,onChange:t=>e.onQuery(t.target.value),onCompositionStart:e.onCompositionStart,onCompositionEnd:e.onCompositionEnd}),(0,n.jsxs)(ea.l6,{value:e.searchSource,items:[{value:"public",label:t("publicNpm")},{value:"custom",label:t("customSearchSource")}],onValueChange:t=>{t&&e.onSearchSource(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("searchSource"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"public",children:t("publicNpm")}),(0,n.jsx)(ea.eb,{value:"custom",children:t("customSearchSource")})]})]}),(0,n.jsxs)(ea.l6,{value:e.kind,items:["all","desk","pi"].map(e=>({value:e,label:t(`kind_${e}`)})),onValueChange:t=>{t&&e.onKind(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("pluginKind"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:["all","desk","pi"].map(e=>(0,n.jsx)(ea.eb,{value:e,children:t(`kind_${e}`)},e))})]}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:e.onDirectInstall,children:t("directInstall")}),"custom"===e.searchSource?(0,n.jsxs)("div",{className:"w-full space-y-1",children:[(0,n.jsx)("label",{htmlFor:"plugin-search-registry",className:"block text-sm",children:t("searchRegistryUrl")}),(0,n.jsx)(em.p,{id:"plugin-search-registry",type:"url",value:e.registry,onChange:t=>e.onRegistry(t.target.value),placeholder:"https://registry.example.com"})]}):null]}),e.error?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 text-sm text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:e.error}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:e.onRetry,children:t("retry")})]}):null,e.items.length?(0,n.jsx)("div",{className:"@container/catalog divide-y rounded-lg border bg-card",children:e.items.map(i=>{let a=r.get(i.name),l=tN(`npm:${i.name}`),o=a?.description??i.description,c=!!(a?.operation&&"failed"!==a.operation.phase),d=e.requests.has(l)||c||e.preparing.has(i.name),u=a&&(a.operation?.action!=="add"||"failed"!==a.operation.phase),m=e.installErrors[i.name]??e.errors[l]??(a?.error?(0,eJ.fD)(a.error.message,s):null);return(0,n.jsxs)("article",{"aria-label":i.name,className:"grid min-w-0 gap-x-4 gap-y-2 px-4 py-3 @xl/catalog:grid-cols-[minmax(0,1fr)_auto]",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(I.$,{variant:"link",className:"h-auto min-h-8 min-w-0 max-w-full p-0 text-left text-sm font-semibold whitespace-normal no-underline hover:underline [overflow-wrap:anywhere]",onClick:()=>e.onDetail(i),children:i.name}),(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",u&&a.version?a.version:i.version]}),u&&a.updateAvailable?(0,n.jsx)("span",{className:"rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:a.availableVersion?t("newVersion",{version:a.availableVersion}):t("updateAvailable")}):null,(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`kind_${i.kind}`)}),i.publisher?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:i.publisher}):null]}),(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:o?(0,eJ.fD)(o,s):t("noPluginDescription")})]}),(0,n.jsx)("div",{className:"flex min-h-8 items-center self-start @xl/catalog:justify-end",children:d?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:c?t(`phase_${a?.operation?.phase}`):e.preparing.has(i.name)?t("loadingPackage"):t("submitting")}):u?(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),a.updateAvailable?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onUpdate(a.source),children:t("update")}):null]}):(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onInstall(i),children:t("install")})}),m?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere] @xl/catalog:col-span-2",children:m}):null,a?.operation?.phase==="failed"&&a.operation.message?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere] @xl/catalog:col-span-2",children:a.operation.message}):null]},i.name)})}):null,e.loading?(0,n.jsx)("p",{role:"status",className:"py-4 text-sm text-muted-foreground",children:t("searching")}):e.error||!e.searched||e.items.length?null:(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:t("noSearchResults")}),e.hasMore?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onMore,children:t("loadMore")}):null]})}let tY=(0,e2.F)("flex w-fit items-stretch *:focus-visible:relative *:focus-visible:z-10 has-[>[data-slot=button-group]]:gap-2 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-lg [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1",{variants:{orientation:{horizontal:"*:data-slot:rounded-r-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-r-lg! [&>[data-slot]~[data-slot]]:rounded-l-none [&>[data-slot]~[data-slot]]:border-l-0",vertical:"flex-col *:data-slot:rounded-b-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-b-lg! [&>[data-slot]~[data-slot]]:rounded-t-none [&>[data-slot]~[data-slot]]:border-t-0"}},defaultVariants:{orientation:"horizontal"}});function tV({className:e,orientation:t,...s}){return(0,n.jsx)("div",{role:"group","data-slot":"button-group","data-orientation":t,className:(0,C.cn)(tY({orientation:t}),e),...s})}var tU=s(32892),tK=s(57445),tH=s(73028),tG=s(48318),tJ=s(93356),tQ=s(10508);let tX=({className:e,from:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("group flex w-full max-w-[95%] flex-col gap-2","user"===t?"is-user ml-auto justify-end":"is-assistant",e),...s}),tZ=({children:e,className:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("flex w-fit min-w-0 max-w-full flex-col gap-2 overflow-hidden text-base leading-[1.8]","group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground","group-[.is-assistant]:text-foreground",t),...s,children:e}),t0=({tooltip:e,children:t,label:s,variant:r="ghost",size:i="icon-sm",...a})=>{let l=(0,n.jsxs)(I.$,{size:i,type:"button",variant:r,...a,children:[t,(0,n.jsx)("span",{className:"sr-only",children:s||e})]});return e?(0,n.jsx)(tU.Bc,{children:(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:l}),(0,n.jsx)(tU.ZI,{children:(0,n.jsx)("p",{children:e})})]})}):l},t1={cjk:tK.h,code:tH.a,math:tG.D,mermaid:tJ.a},t2=(0,r.memo)(({className:e,...t})=>(0,n.jsx)(tQ.jH,{className:(0,C.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),plugins:t1,...t}),(e,t)=>e.children===t.children&&t.isAnimating===e.isAnimating);t2.displayName="MessageResponse";let t5=({className:e,children:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("mt-4 flex w-full items-center justify-between gap-4",e),...s,children:t});function t3({readme:e}){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),[i,a]=(0,r.useState)(null),l=e&&"string"!=typeof e?e.translations:{},o=Object.keys(l).filter(e=>/^(zh(?:-|$)|en(?:-|$))/.test(e)),c=i&&void 0!==l[i]?i:null,d=e?c?l[c]:(0,eJ.fD)(e,s):null;return(0,n.jsxs)("section",{className:"min-w-0 space-y-3","aria-label":t("readme"),children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:t("readme")}),o.length>0?(0,n.jsxs)("div",{className:"flex items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("readmeLanguage")}),(0,n.jsxs)(ea.l6,{value:c??"",onValueChange:e=>a(e||null),children:[(0,n.jsx)(ea.bq,{"aria-label":t("readmeLanguage"),children:(0,n.jsx)(ea.yv,{children:c?c.startsWith("zh")?"中文":"English":t("defaultLanguage")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"",children:t("defaultLanguage")}),o.map(e=>(0,n.jsx)(ea.eb,{value:e,children:e.startsWith("zh")?"中文":"English"},e))]})]})]}):null]}),d?(0,n.jsx)("div",{className:"min-w-0 overflow-x-auto text-base leading-relaxed [overflow-wrap:anywhere]",children:(0,n.jsx)(t2,{mode:"static",isAnimating:!1,skipHtml:!0,controls:!1,className:"min-w-0 [&_img]:max-w-full [&_pre]:overflow-x-auto",children:d})}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:t("noReadme")})]})}function t4({value:e,label:t,placeholder:s,disabled:r,onChange:i}){let{t:a}=(0,b.Bd)("pluginManagement"),l=[...s?[{value:"",label:s}]:[],{value:"latest",label:a("channelLatest")},{value:"dev",label:a("channelDev")},...e&&!["latest","dev"].includes(e)?[{value:e,label:e}]:[]];return(0,n.jsxs)(ea.l6,{value:e,items:l,onOpenChange:(e,t)=>{e&&r&&t.cancel()},onValueChange:e=>{null===e||r||i(e)},children:[(0,n.jsx)(ea.bq,{"aria-label":t,"aria-disabled":r,className:"max-w-full aria-disabled:opacity-50",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:l.map(e=>(0,n.jsx)(ea.eb,{value:e.value,disabled:r,children:e.label},e.value))})]})}function t6(e){if(!e)return null;try{let t=new URL(e);return["https:","http:"].includes(t.protocol)?t.href:null}catch{return null}}function t8(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=e.detail,i=e.installed&&e.installedVersion===r.version,a=t6(r.homepage),l=t6(r.repository),o=[...new Set([r.version,...r.versions])];return(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:["v",r.version]}),(0,n.jsx)("span",{children:t(`kind_${r.kind}`)}),r.publisher?(0,n.jsx)("span",{className:"[overflow-wrap:anywhere]",children:r.publisher}):null]}),r.description?(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:(0,eJ.fD)(r.description,s)}):null,!1===r.compatible?(0,n.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:[t("incompatible"),r.compatibilityNote?` \xb7 ${r.compatibilityNote}`:""]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[e.pending?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:e.operationMessage??t("submitting")}):i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),e.updateAvailable?(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled,onClick:e.onUpdate,children:t("update")}):null]}):(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||!1===r.compatible,onClick:e.onInstall,children:t(e.installed?"installVersion":"install")}),a?(0,n.jsx)("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"text-sm underline underline-offset-4",children:t("homepage")}):null,l?(0,n.jsx)("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"text-sm underline underline-offset-4",children:t("repository")}):null]}),e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.error}):null]}),(0,n.jsxs)(eV.Nt,{className:"rounded-lg border",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between px-3 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"space-y-3 px-3 pb-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(t4,{value:e.channel,label:t("installChannel"),placeholder:t("defaultChannel"),disabled:e.pending,onChange:e.onChannel}),(0,n.jsxs)(ea.l6,{value:r.version,items:o.map(e=>({value:e,label:e})),onOpenChange:(t,s)=>{t&&e.pending&&s.cancel()},onValueChange:t=>{t&&!e.pending&&e.onVersion(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("version"),"aria-disabled":e.pending,children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:o.map(t=>(0,n.jsx)(ea.eb,{value:t,disabled:e.pending,children:t},t))})]})]}),(0,n.jsx)(tO,{id:"plugin-detail-download",mode:e.downloadMode,registry:e.downloadRegistry,override:!0,saving:e.pending,onMode:e.onDownloadMode,onRegistry:e.onDownloadRegistry})]})})]}),(0,n.jsx)("div",{className:"border-t pt-4",children:(0,n.jsx)(t3,{readme:r.readme},`${r.name}@${r.version}`)})]})}var t7=s(68017);function t9(e){let{t}=(0,b.Bd)("pluginManagement");return(0,n.jsxs)("section",{"aria-label":t("directInstall"),className:"min-w-0 space-y-3 rounded-lg border bg-card p-4",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:t("directInstall")}),(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:e.onClose,children:t("close")})]}),(0,n.jsx)("label",{htmlFor:"plugin-direct-source",className:"block text-sm font-medium",children:t("source")}),(0,n.jsx)(t7.T,{id:"plugin-direct-source",value:e.source,placeholder:t("batchSourcePlaceholder"),rows:2,disabled:e.pending,onChange:t=>e.onSource(t.target.value)}),e.isNpm||e.multiple?(0,n.jsxs)(eV.Nt,{children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-8 items-center gap-2 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"space-y-3 pt-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(t4,{value:e.tag,label:t("installChannel"),placeholder:t("defaultChannel"),disabled:e.pending,onChange:e.onTag})]}),e.isNpm?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onRead,children:t(e.loading?"loadingPackage":"readPackage")}):null,e.detail?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.detail.name}),(0,n.jsxs)(ea.l6,{value:e.selectedVersion,onOpenChange:(t,s)=>{t&&(e.loading||e.pending)&&s.cancel()},items:[{value:"",label:t("automaticVersion")},...[...new Set([e.detail.version,...e.detail.versions])].map(e=>({value:e,label:e}))],onValueChange:t=>{null===t||e.loading||e.pending||e.onVersion(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("version"),"aria-disabled":e.loading||e.pending,className:"max-w-full",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"",disabled:e.loading||e.pending,children:t("automaticVersion")}),[...new Set([e.detail.version,...e.detail.versions])].map(t=>(0,n.jsx)(ea.eb,{value:t,disabled:e.loading||e.pending,children:t},t))]})]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t("targetVersion",{version:e.detail.version})})]}):null,(0,n.jsx)(tO,{id:"plugin-direct-download",mode:e.override,registry:e.registry,override:!0,saving:e.pending,onMode:e.onMode,onRegistry:e.onRegistry})]})})]}):null,e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm whitespace-pre-wrap text-destructive [overflow-wrap:anywhere]",children:e.error}):null,e.operationMessage?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operationMessage}):null,(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||e.loading||e.pending||!e.source.trim(),onClick:e.onInstall,children:t(e.pending?"installing":e.multiple?"batchInstall":"install")})]})}function se({confirmation:e,onClose:t,onConfirm:s}){let{t:r}=(0,b.Bd)("pluginManagement"),i=e?r(tI(e)):null,a=e?.kind==="del"||e?.kind==="batch"&&"del"===e.input.action,l=e?.kind==="add"||e?.kind==="batch"&&"add"===e.input.action;return(0,n.jsx)(eN.YV,{open:!!e,onOpenChange:e=>{e||t()},children:(0,n.jsxs)(eN.hA,{className:"z-[150] max-w-lg",backdropClassName:"z-[140]",children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:r("confirmAction",{action:i})}),(0,n.jsx)(eN.uX,{children:r(a?"removeDescription":l?"thirdPartyDescription":e?.kind==="reload"?"normal"===e.mode?"restartNormalDescription":"restartDescription":"confirmChange")})]}),(0,n.jsx)(eN._Y,{className:"min-h-0",children:(0,n.jsx)("div",{className:"min-w-0 p-4 pt-0",children:e?.kind==="batch"?(0,n.jsx)("ul",{className:"space-y-2 text-sm",children:("add"===e.input.action?e.input.items.map(e=>e.source):e.input.sources).map(e=>(0,n.jsx)("li",{className:"font-medium [overflow-wrap:anywhere]",children:e.startsWith("npm:")?tk(e)?.name??e:e},e))}):e?.kind==="add"?(0,n.jsxs)("dl",{className:"space-y-3 text-sm",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("packageName")}),(0,n.jsx)("dd",{className:"mt-1 font-medium [overflow-wrap:anywhere]",children:e.package?.name??e.input.source})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("version")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.package?.version??tk(e.input.source)?.version??r("fromSource")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("publisher")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.package?.publisher??r("unknownPublisher")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("source")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.input.registry??e.package?.registry??e.input.source})]})]}):e&&"reload"!==e.kind?(0,n.jsx)("p",{className:"text-sm font-medium [overflow-wrap:anywhere]",children:e.source.startsWith("npm:")?tk(e.source)?.name??e.source:e.source}):null})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:t,children:r("cancel")}),(0,n.jsx)(I.$,{size:"sm",variant:a?"destructive":"default",onClick:()=>{e&&s(e)},children:i})]})]})})}function st({basicMode:e=!1,snapshot:t,biz:s,onSnapshot:i,onRestartScheduled:a}){let{t:l}=(0,b.Bd)("pluginManagement"),{locale:o}=(0,eQ.i)(),[c,d]=(0,r.useState)("installed"),[u,m]=(0,r.useState)(""),[p,h]=(0,r.useState)("all"),[g,f]=(0,r.useState)(!1),[x,v]=(0,r.useState)(()=>new Set);(0,r.useEffect)(()=>{if(!t)return;let e=new Set(t.plugins.map(e=>tN(e.source)));[...x].some(t=>!e.has(t))&&queueMicrotask(()=>v(t=>new Set([...t].filter(t=>e.has(t)))))},[t,x]);let[w,y]=(0,r.useState)(""),[k,j]=(0,r.useState)(!1),N=function({basicMode:e=!1,biz:t,snapshot:s,onSnapshot:n,onRestartScheduled:i}){let{t:a}=(0,b.Bd)("pluginManagement"),l=(0,Q.t4)();(0,Q.So)();let[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(()=>new Set),m=(0,r.useRef)(new Set),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)({}),[x,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(null),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(null),S=(0,r.useRef)(0),C=(0,r.useRef)(0),E=(0,r.useRef)(!0),M=(e,t)=>{t?m.current.add(e):m.current.delete(e),E.current&&u(new Set(m.current))},z=(e,t)=>{E.current&&f(s=>{let n={...s};return t?n[e]=t:delete n[e],n})},A=e=>{let t=tN(e);return m.current.has(t)||!!s?.plugins.some(e=>tN(e.source)===t&&e.operation&&"failed"!==e.operation.phase)},$=async(e=!1)=>{let s=++C.current,r=await t.list(e);E.current&&s===C.current&&n(r)},R=async(e,t)=>{if(m.current.has("check"))return;let n=e??s?.plugins.filter(e=>"package"===e.kind&&(!t||e.updateTag===t)).map(e=>e.source)??[],r=n.filter(A),i=n.filter(e=>!A(e));if(r.forEach(e=>z(tN(e),a("sourceBusy"))),!i.length)return;let l=i.map(tN);M("check",!0),l.forEach(e=>M(e,!0)),c(!0),z("list",null);try{if(e||r.length)for(let e=0;e<i.length&&(await $({checkUpdates:!0,sources:i.slice(e,e+32),...t?{tag:t}:{}}),E.current);e+=32);else await $({checkUpdates:!0,...t?{tag:t}:{}})}catch(e){z("list",e instanceof Error?e.message:a("updateCheckFailed"))}finally{M("check",!1),l.forEach(e=>M(e,!1)),E.current&&c(!1)}};(0,r.useEffect)(()=>{E.current=!0;let s=!0,r=++C.current;return queueMicrotask(()=>{s&&(c(!0),t.list(!1).then(async i=>{if(!s||r!==C.current)return;n(i);let a=i.plugins.some(e=>"package"===e.kind&&/^(npm:|git:|https?:|git@)/.test(e.source)&&null===e.updateAvailable&&!e.updateError&&!e.operation);if(!e&&a){let e=await t.list(!0);s&&r===C.current&&n(e)}}).catch(e=>{s&&z("list",e instanceof Error?e.message:a("updateCheckFailed"))}).finally(()=>{s&&c(!1)}))}),()=>{s=!1,E.current=!1,S.current+=1,C.current+=1}},[t,n,a,e]);let P=async e=>{let s="add"===e.action?e.items.map(e=>e.source):e.sources,r=s.filter(e=>!A(e));if(s.filter(A).forEach(e=>z(tN(e),a("sourceBusy"))),!r.length)return;let i=r.map(tN);i.forEach(e=>{M(e,!0),z(e,null)}),h(null);let l=[...r];try{let s=await t.list(),r=Date.now()+9e5;for(;l.length;){let i=s.plugins.filter(e=>e.operation&&"failed"!==e.operation.phase),o="tag"===e.action?32:Math.max(0,32-i.length);if(!o){if(i.some(e=>e.operation?.phase==="waiting")||Date.now()>=r){l.forEach(e=>z(tN(e),a("batchWaiting")));break}await new Promise(e=>setTimeout(e,750)),s=await t.list(),E.current&&(C.current+=1,n(s));continue}let c=l.slice(0,o),d="add"===e.action?{...e,items:e.items.filter(e=>c.includes(e.source))}:{...e,sources:c},u=await t.batch(d);s=u.snapshot,E.current&&(C.current+=1,n(s)),u.results.forEach(e=>z(tN(e.source),e.error)),c.forEach(e=>M(tN(e),!1)),l=l.slice(c.length)}}catch(t){let e=t instanceof Error?t.message:a("batchFailed");l.forEach(t=>z(tN(t),e))}finally{i.forEach(e=>M(e,!1))}},D=async e=>{if("batch"===e.kind)return void await P(e.input);if("reload"!==e.kind&&A("add"===e.kind?e.input.source:e.source))return;let s="reload"===e.kind?"reload":tN("add"===e.kind?e.input.source:e.source);if(!m.current.has(s)){M(s,!0),h(null),z(s,null);try{let s="add"===e.kind?await t.add(e.input):"update"===e.kind?await t.update(e.source):"del"===e.kind?await t.del(e.source):"enable"===e.kind||"disable"===e.kind?await t.setEnabled(e.source,"enable"===e.kind):await t.reload(e.mode);if(!E.current)return;C.current+=1,n(s),"reload"===e.kind?i():await $()}catch(t){z(s,t instanceof Error?t.message:a("actionFailed",{action:a(tI(e))}))}finally{M(s,!1)}}},T=(e,t)=>{let s={kind:"add",input:e,package:t};t?.official===!0?D(s):h(s)},O=async e=>{let s=e?.[0]?tN(e[0]):"apply";if(!m.current.has(s)){M(s,!0),z(s,null);try{let s=await t.apply(e);E.current&&(C.current+=1,n(s),await $())}catch(e){z(s,e instanceof Error?e.message:a("actionFailed",{action:a("reloadOne")}))}finally{M(s,!1)}}},L=async(e,t)=>{if(!m.current.has(e)){M(e,!0),z(e,null);try{await t()}catch(t){z(e,t instanceof Error?t.message:a("retryFailed"))}finally{M(e,!1)}}},F=async e=>{let s=++S.current;j(!0),I(null);try{let n=await t.get(e);E.current&&s===S.current&&y(n)}catch(e){E.current&&s===S.current&&I(e instanceof Error?e.message:a("detailFailed"))}finally{E.current&&s===S.current&&j(!1)}};return{loading:o,requests:d,confirmation:p,setConfirmation:h,errors:g,detailSource:x,detail:w,detailLoading:k,detailError:N,pluginHost:l,refresh:R,executeBatch:P,execute:D,requestInstall:T,applyChanges:O,loadDetail:F,openDetail:e=>{v(e),y(null),F(e)},closeDetail:()=>{S.current+=1,v(null),y(null),I(null),j(!1)},handleControlAction:(e,t)=>{switch(t){case"reload":O([e.source]);break;case"update":D({kind:"update",source:e.source});break;case"remove":h({kind:"del",source:e.source});break;case"enable":case"disable":D({kind:t,source:e.source});break;case"retry-browser":e.pluginName&&L(`entry:${e.pluginName}`,()=>l.retryEntry(e.pluginName));break;case"retry":{let t=e.operation?.action;"apply"===t?O([e.source]):"add"===t?T({source:e.source}):t&&D({kind:t,source:e.source})}}},refreshEntries:()=>L("entries",()=>l.refreshEntries())}}({biz:s,snapshot:t,onSnapshot:i,onRestartScheduled:a,basicMode:e}),S=function(e,t){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(""),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)("all"),[d,u]=(0,r.useState)("public"),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)([]),[f,x]=(0,r.useState)(!1),[v,w]=(0,r.useState)(1),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(null),[I,S]=(0,r.useState)(!1),[C,E]=(0,r.useState)(null),[M,z]=(0,r.useState)(null),[A,$]=(0,r.useState)(!1),[R,P]=(0,r.useState)(null),[D,T]=(0,r.useState)(()=>new Set),[O,L]=(0,r.useState)({}),F=(0,r.useRef)(0),B=(0,r.useRef)(0),q=(0,r.useRef)(new Set),_=(0,r.useRef)(null),[W,Y]=(0,r.useState)(!1),[V,U]=(0,r.useState)("default"),[K,H]=(0,r.useState)(""),G=(0,r.useRef)(!0);(0,r.useEffect)(()=>(G.current=!0,()=>{G.current=!1,F.current+=1,B.current+=1}),[]);let J=(0,r.useCallback)(async(t,n)=>{k(!0),N(null);try{let s=await e.searchCatalog(t);if(!G.current||n!==F.current)return;g(e=>{let n=1===t.page?s.items:[...e,...s.items],r=e=>e.official?0:"desk"===e.kind?1:"pi"===e.kind?2:3;return[...new Map(n.map(e=>[e.name,e])).values()].sort((e,t)=>r(e)-r(t))}),w(t.page),x(s.hasMore),S(!0)}catch(e){G.current&&n===F.current&&N(e instanceof Error?e.message:s("searchFailed"))}finally{G.current&&n===F.current&&k(!1)}},[e,s]);(0,r.useEffect)(()=>{t&&queueMicrotask(()=>Y(!0))},[t]),(0,r.useEffect)(()=>{if(!W||a)return;let e=++F.current;_.current=null,queueMicrotask(()=>{G.current&&e===F.current&&(k(!0),N(null),x(!1))});let t=setTimeout(()=>{let t="custom"===d?tC.safeParse(m):null;if(t&&!t.success){_.current=null,g([]),x(!1),S(!1),N(s("invalidRegistry")),k(!1);return}let r={query:n.trim(),kind:o,page:1,...t?.success?{registry:t.data}:{}};_.current=r,g([]),x(!1),S(!1),J(r,e)},300);return()=>clearTimeout(t)},[n,o,d,m,a,J,W,s]);let Q=async(t,n=t.version)=>{let r=++B.current;$(!0),P(null),L(e=>{let s={...e};return delete s[t.name],s});try{let s=await e.getCatalog({name:t.name,registry:t.registry,version:n});G.current&&r===B.current&&z(s)}catch(e){G.current&&r===B.current&&P(e instanceof Error?e.message:s("detailFailed"))}finally{G.current&&r===B.current&&$(!1)}};return{query:n,setQuery:i,composing:a,beginComposition:()=>{F.current+=1,_.current=null,k(!1),l(!0)},endComposition:()=>l(!1),kind:o,setKind:c,searchSource:d,setSearchSource:u,registry:m,setRegistry:p,items:h,loading:y,error:j,searched:I,hasMore:f,loadMore:()=>{_.current&&!y&&f&&J({..._.current,page:v+1},F.current)},retry:()=>{if(a||y)return;let e="custom"===d?tC.safeParse(m):null;if(e&&!e.success)return void N(s("invalidRegistry"));let t={query:n.trim(),kind:o,page:1,...e?.success?{registry:e.data}:{}};_.current=t,g([]),J(t,++F.current)},selection:C,detail:M,detailLoading:A,detailError:R,openDetail:e=>{E(e),z(null),U("default"),H(""),Q(e)},closeDetail:()=>{B.current+=1,E(null),z(null),$(!1),P(null)},loadDetail:Q,prepareInstall:async(t,n)=>{if(!q.current.has(t.name)){q.current.add(t.name),T(new Set(q.current)),L(e=>{let s={...e};return delete s[t.name],s});try{let r=await e.getCatalog({name:t.name,version:t.version,registry:t.registry});if(!G.current)return;if(!1===r.compatible)return void L(e=>({...e,[t.name]:s("installIncompatible")}));n(r)}catch(e){G.current&&L(n=>({...n,[t.name]:e instanceof Error?e.message:s("detailFailed")}))}finally{q.current.delete(t.name),G.current&&T(new Set(q.current))}}},preparing:D,installErrors:O,downloadMode:V,setDownloadMode:U,downloadRegistry:K,setDownloadRegistry:H,installDetail:e=>{if(!M||A)return;if(!1===M.compatible)return void L(e=>({...e,[M.name]:s("installIncompatible")}));let t="default"===V?null:tE.safeParse("custom"===V?{mode:V,registry:K}:{mode:V});t&&!t.success?L(e=>({...e,[M.name]:s("invalidRegistry")})):(L(e=>{let t={...e};return delete t[M.name],t}),e({source:`npm:${M.name}@${M.version}`,registry:M.registry,...t?.success?{downloadSource:t.data}:{}},M))}}}(s,"search"===c),C=function(e,t){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(null),[a,l]=(0,r.useState)("auto"),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(!1),[h,g]=(0,r.useState)(null),f=(0,r.useRef)(!0),x=(0,r.useRef)(!1),v=(0,r.useRef)(0),w=(0,r.useRef)("load"),y=async()=>{let t=v.current;u(!0),g(null);try{let s=await e.getCatalogSettings();if(!f.current)return;t===v.current?(i(s),l(s.downloadSource.mode),"custom"===s.downloadSource.mode&&c(s.downloadSource.registry)):i(e=>e??s)}catch(e){w.current="load",f.current&&g(e instanceof Error?e.message:s("settingsFailed"))}finally{f.current&&u(!1)}};(0,r.useEffect)(()=>{f.current=!0;let e=!0;return queueMicrotask(()=>{e&&y()}),()=>{e=!1,f.current=!1}},[e]);let k=async(n=a)=>{if(x.current)return;let r=tE.safeParse("custom"===n?{mode:n,registry:o}:{mode:n});if(!r.success){w.current="save",g(s("invalidRegistry"));return}x.current=!0,p(!0),g(null);try{let s=await e.saveCatalogSettings(r.data);f.current&&(i(s),l(s.downloadSource.mode),t())}catch(e){w.current="save",f.current&&g(e instanceof Error?e.message:s("settingsFailed"))}finally{x.current=!1,f.current&&p(!1)}};return{settings:n,mode:a,registry:o,setRegistry:e=>{v.current+=1,c(e)},loading:d,saving:m,error:h,load:y,save:k,changeMode:e=>{v.current+=1,l(e),"custom"!==e&&k(e)},retry:()=>"save"===w.current?k():y()}}(s,()=>{e||N.refresh()}),E=function(e,t=[]){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(""),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(null),[v,w]=(0,r.useState)("default"),[y,k]=(0,r.useState)(""),j=(0,r.useRef)(0),N=(0,r.useRef)(!0),I=a.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),S=1===I.length?tk(I[0]):null;(0,r.useEffect)(()=>(N.current=!0,()=>{N.current=!1,j.current+=1}),[]);let C=()=>{j.current+=1,p(null),g(!1),x(null)},E=async n=>{let r;if(!S)return null;void 0!==n&&u(n||null);let i=t.find(e=>tk(e.source)?.name===S.name)?.updateTag,a=S.version??(o||i||"latest"),l=""===n?a:n??d??a;if("custom"===v){let e=tC.safeParse(y);if(!e.success)return x(s("invalidRegistry")),null;r=e.data}else"official"===v?r="https://registry.npmjs.org":"domestic"===v&&(r="https://registry.npmmirror.com");let c=++j.current;g(!0),p(null),x(null);try{let t=await e.getCatalog({...S,...l?{version:l}:{},...r?{registry:r}:{}});if(!N.current||c!==j.current)return null;return p(t),t}catch(e){return N.current&&c===j.current&&x(e instanceof Error?e.message:s("detailFailed")),null}finally{N.current&&c===j.current&&g(!1)}},M=async(e,t)=>{if(!I.length||h)return;x(null);let n="default"===v?null:tE.safeParse("custom"===v?{mode:v,registry:y}:{mode:v});if(n&&!n.success)return void x(s("invalidRegistry"));let r={...o?{tag:o}:{},...n?.success?{downloadSource:n.data}:{}};if(I.length>1){let e=I.map(tk);if(I.length>32||e.some(e=>!e))return void x(s(I.length>32?"batchLimit":"batchNpmOnly"));let n=new Map;return e.forEach(e=>{e&&n.set(e.name,{source:`npm:${e.name}${e.version?`@${e.version}`:""}`,...r})}),void t([...n.values()])}if(!S)return void e({source:I[0]});let i=m?Promise.resolve(m):E(d??void 0),a=j.current,l=await i;if(l&&N.current&&a===j.current){if(!1===l.compatible)return void x(s("installIncompatible"));e({source:`npm:${l.name}${d||S.version?`@${d??S.version}`:""}`,registry:l.registry,...r},l)}};return{open:n,setOpen:i,source:a,sources:I,tag:o,selectedVersion:d??"",setTag:e=>{C(),u(null),c(e)},changeSource:e=>{C(),u(null),l(e)},spec:S,detail:m,loading:h,error:f,override:v,setOverride:e=>{C(),w(e)},registry:y,setRegistry:e=>{C(),k(e)},loadDetail:E,install:M}}(s,t?.plugins),M=e||N.requests.has("reload"),z=new Map(N.pluginHost.getFailedEntries().map(e=>[e.pluginName,e.error.message])),$=N.pluginHost.getEntryListError(),R=t?.plugins.find(e=>e.source===N.detailSource),P=S.selection?t?.plugins.find(e=>e.source.startsWith("npm:")&&tk(e.source)?.name===S.selection?.name):void 0,D=S.selection?tN(`npm:${S.selection.name}`):"",T=tN(E.detail?`npm:${E.detail.name}`:E.spec?`npm:${E.spec.name}`:E.source.trim()),O=t?.plugins.find(e=>tN(e.source)===T),L=e=>{let s=t?.plugins.find(t=>tN(t.source)===tN(e));return N.requests.has(tN(e))||!!(s?.operation&&"failed"!==s.operation.phase)},F=L(`npm:${S.selection?.name??""}`),B=E.sources.some(L),q=E.sources.map(e=>{let s=tN(e),n=t?.plugins.find(e=>tN(e.source)===s),r=N.errors[s]??(n?.operation?.phase==="failed"?n.operation.message:null);return r?`${e}: ${r}`:null}).filter(Boolean).join("\n"),_=!!(N.detailSource||S.selection),W=(0,r.useRef)(null),Y=(0,r.useRef)(null);(0,r.useEffect)(()=>{_?W.current?.focus():Y.current?.isConnected&&(Y.current.focus(),Y.current=null)},[_]);let V=()=>{Y.current=document.activeElement instanceof HTMLElement?document.activeElement:null},U=e=>{let s=t?.plugins.find(t=>tk(t.source)?.name===e.name);return{...e,version:s?.updateTag??"latest"}},K=e=>t?.plugins.filter(t=>"extension"!==t.kind&&!0===t.updateAvailable&&!L(t.source)&&(!e||x.has(tN(t.source)))).map(e=>e.source)??[],H=e=>e?l(`phase_${e}`):null,G=()=>{d("installed"),E.setOpen(!0)};return(0,n.jsxs)("div",{className:"flex h-full min-h-0 min-w-0 flex-col",children:[(0,n.jsxs)("header",{className:"shrink-0 space-y-3 border-b p-4 sm:px-6",children:[_?(0,n.jsxs)(I.$,{ref:W,size:"sm",variant:"ghost",className:"-ml-2",onClick:()=>{N.closeDetail(),S.closeDetail()},children:[(0,n.jsx)(A.A,{}),l("backToList")]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h2",{className:"min-w-0 text-xl font-semibold [overflow-wrap:anywhere]",children:_?R?tj(R):S.selection?.name??l("details"):l("title")}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[_?null:(0,n.jsxs)(eW.AM,{children:[(0,n.jsxs)(eW.Wv,{render:(0,n.jsx)(I.$,{size:"sm",variant:"ghost"}),children:[l("downloadSource"),":",C.loading&&!C.settings?l("loading"):l(`download_${C.settings?.downloadSource.mode??C.mode}`),(0,n.jsx)(eY.A,{className:"size-4"})]}),(0,n.jsx)(eW.hl,{align:"end",positionerClassName:"z-[150]",className:"w-80 max-w-[calc(100vw-2rem)]",children:(0,n.jsx)(tO,{id:"plugin-default-download",mode:C.mode,registry:C.registry,savedRegistry:C.settings?.downloadSource.mode==="custom"?C.settings.downloadSource.registry:void 0,recommendedRegistry:C.settings?.recommendedRegistry,loading:C.loading,saving:C.saving,error:C.error,onMode:e=>{"default"!==e&&C.changeMode(e)},onRegistry:C.setRegistry,onSave:()=>void C.save(),onRetry:()=>void C.retry()})})]}),e||t?.restartRequired?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:N.requests.has("reload"),onClick:()=>N.setConfirmation({kind:"reload",mode:e?"normal":void 0}),children:l(e?"restartNormal":"restartApply")}):null]})]}),e?(0,n.jsx)("p",{role:"status",className:"rounded-lg bg-muted p-3 text-sm",children:l("basicModeNotice")}):null,t?.restartRequired?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("pendingRestart")}):null,t?.loadError||$?(0,n.jsxs)("div",{role:"alert",className:"max-h-32 space-y-1 overflow-y-auto text-sm text-destructive",children:[t?.loadError?(0,n.jsx)("p",{className:"[overflow-wrap:anywhere]",children:(0,eJ.fD)(t.loadError,o)}):null,$?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"min-w-0 [overflow-wrap:anywhere]",children:$}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:N.requests.has("entries"),onClick:()=>void N.refreshEntries(),children:l("retry")})]}):null]}):null,N.errors.reload||N.errors.entries?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:N.errors.reload??N.errors.entries}):null]}),(0,n.jsxs)(e5,{value:c,onValueChange:e=>d(String(e)),className:`min-h-0 flex-1 gap-0 ${_?"hidden":""}`,children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 pt-2 sm:px-6",children:(0,n.jsxs)(e4,{variant:"line","aria-label":l("title"),className:"h-9",children:[(0,n.jsxs)(e6,{value:"installed",className:"px-3",children:[l("installedTab"),t?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t.plugins.length}):null]}),(0,n.jsx)(e6,{value:"search",className:"px-3",children:l("searchPlugins")})]})}),(0,n.jsx)(e8,{value:"installed",keepMounted:!0,className:"flex min-h-0 flex-col overflow-hidden p-4 data-[hidden]:hidden sm:p-6",children:(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[E.open?(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar max-h-1/2 shrink-0 overflow-y-auto",children:(0,n.jsx)(t9,{source:E.source,isNpm:!!E.spec,multiple:E.sources.length>1,tag:E.tag,selectedVersion:E.selectedVersion,onTag:E.setTag,detail:E.detail,loading:E.loading,pending:B,disabled:M,error:E.error??(q||null),operationMessage:B?H(O?.operation?.phase)??l("submitting"):null,override:E.override,registry:E.registry,onSource:E.changeSource,onMode:E.setOverride,onRegistry:E.setRegistry,onRead:()=>void E.loadDetail(),onVersion:e=>void E.loadDetail(e),onInstall:()=>void E.install(N.requestInstall,e=>N.setConfirmation({kind:"batch",input:{action:"add",items:e}})),onClose:()=>E.setOpen(!1)})}):null,(0,n.jsx)(t_,{snapshot:t,loading:N.loading,filter:u,statusFilter:p,batchMode:g,selected:x,onStatusFilter:h,onBatchMode:e=>{f(e),e||v(new Set)},onSelect:(e,t)=>{v(s=>{let n=new Set(s);return e.forEach(e=>{t?n.add(e):n.delete(e)}),n})},onUpdateAll:()=>void N.executeBatch({action:"update",sources:K(!1)}),onUpdateSelected:()=>void N.executeBatch({action:"update",sources:K(!0)}),onRemoveSelected:()=>N.setConfirmation({kind:"batch",input:{action:"del",sources:t?.plugins.filter(e=>x.has(tN(e.source))&&!L(e.source)).map(e=>e.source)??[]}}),disabled:M,requests:N.requests,errors:N.errors,browserErrors:z,onFilter:m,onDetail:e=>{V(),S.closeDetail(),N.openDetail(e)},onAction:N.handleControlAction,onRefresh:()=>void N.refresh()}),t?.plugins.length||E.open?null:(0,n.jsx)(I.$,{size:"sm",variant:"outline",className:"shrink-0 self-start",disabled:M,onClick:G,children:l("directInstall")})]})}),(0,n.jsx)(e8,{value:"search",keepMounted:!0,className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto p-4 data-[hidden]:hidden sm:p-6",children:(0,n.jsx)(tW,{query:S.query,kind:S.kind,searchSource:S.searchSource,registry:S.registry,items:S.items,loading:S.loading,error:S.error,searched:S.searched,hasMore:S.hasMore,disabled:M,snapshot:t,requests:N.requests,preparing:S.preparing,errors:N.errors,installErrors:S.installErrors,onQuery:S.setQuery,onCompositionStart:S.beginComposition,onCompositionEnd:S.endComposition,onKind:S.setKind,onSearchSource:e=>{S.setSearchSource(e),"custom"!==e||S.registry||C.settings?.downloadSource.mode!=="custom"||S.setRegistry(C.settings.downloadSource.registry)},onRegistry:S.setRegistry,onDetail:e=>{V(),N.closeDetail(),y(""),j(!1),S.openDetail(U(e))},onInstall:e=>{S.prepareInstall(U(e),e=>N.requestInstall({source:`npm:${e.name}`,registry:e.registry},e))},onUpdate:e=>void N.execute({kind:"update",source:e}),onMore:S.loadMore,onRetry:S.retry,onDirectInstall:G})})]}),_?(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:R?(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[R.version?(0,n.jsxs)("span",{children:["v",R.version]}):null,R.updateAvailable?(0,n.jsx)("span",{className:"rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:R.availableVersion?l("newVersion",{version:R.availableVersion}):l("updateAvailable")}):null]}),(0,n.jsx)(tw,{plugin:R,displayName:tj(R),browserError:R.pluginName?z.get(R.pluginName)??null:null,disabled:M,pending:L(R.source),browserRetryPending:N.requests.has(`entry:${R.pluginName}`),onAction:e=>N.handleControlAction(R,e)})]}),R.description?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:(0,eJ.fD)(R.description,o)}):null,(0,n.jsx)(ty,{plugin:R,requestError:N.errors[tN(R.source)],browserError:R.pluginName?z.get(R.pluginName)??null:null})]}),(0,n.jsxs)(eV.Nt,{className:"rounded-lg border",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between px-3 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 px-3 pb-3",children:[R.source.startsWith("npm:")?(0,n.jsx)(t4,{value:R.updateTag??"latest",label:l("installChannel"),disabled:M||L(R.source),onChange:e=>void N.executeBatch({action:"tag",sources:[R.source],tag:e})}):null,(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:M||L(R.source)&&R.operation?.phase!=="waiting",onClick:()=>N.handleControlAction(R,"reload"),children:l("reloadOne")})]})})]}),N.detailLoading?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("loadingPackage")}):null,N.detail?.readme?(0,n.jsx)(t3,{readme:N.detail.readme},R.source):null,(0,n.jsxs)(eV.Nt,{className:"border-t pt-2",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l("capabilityDetails"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsx)(tf,{plugin:R,detail:N.detail,detailLoading:N.detailLoading,detailError:N.detailError,browserContributions:R.pluginName?N.pluginHost.getRegisteredBrowserDescriptors().find(e=>e.pluginName===R.pluginName)?.contributions??[]:[],onRetry:()=>void N.loadDetail(R.source)})})]}),N.detailError?(0,n.jsxs)("div",{role:"alert",className:"flex items-center gap-2 text-sm text-destructive",children:[(0,n.jsx)("span",{children:N.detailError}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:()=>void N.loadDetail(R.source),children:l("retry")})]}):null]}):S.selection?(0,n.jsxs)(n.Fragment,{children:[S.detailLoading?(0,n.jsx)("p",{role:"status",className:"mb-3 text-sm text-muted-foreground",children:l("loadingPackage")}):null,S.detailError?(0,n.jsxs)("div",{role:"alert",className:"mb-3 space-y-2 text-sm",children:[(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:S.detailError}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:()=>void S.loadDetail(S.selection),children:l("retry")})]}):null,S.detail?(0,n.jsx)(t8,{detail:S.detail,disabled:M||!!S.detailError,pending:F||S.detailLoading,installed:!!(P&&(P.operation?.action!=="add"||"failed"!==P.operation.phase)),installedVersion:P?.version??null,updateAvailable:!!P?.updateAvailable,error:S.installErrors[S.detail.name]??N.errors[D]??(P?.operation?.phase==="failed"?P.operation.message:null),operationMessage:S.detailLoading?l("loadingPackage"):H(P?.operation?.phase),channel:w,onChannel:e=>{y(e),j(!1),S.loadDetail(S.selection,e||P?.updateTag||"latest")},downloadMode:S.downloadMode,downloadRegistry:S.downloadRegistry,onDownloadMode:S.setDownloadMode,onDownloadRegistry:S.setDownloadRegistry,onVersion:e=>{j(!0),S.loadDetail(S.selection,e)},onInstall:()=>S.installDetail((e,t)=>N.requestInstall({...e,source:k?e.source:`npm:${t.name}`,...w?{tag:w}:{}},t)),onUpdate:()=>{P&&N.execute({kind:"update",source:P.source})}}):null]}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:l("pluginRemoved")})}):null,(0,n.jsx)(se,{confirmation:N.confirmation,onClose:()=>N.setConfirmation(null),onConfirm:e=>void N.execute(e)})]})}var ss=s(99739);let sn=a.Yj().trim().min(1).max(2048),sr=a.YO(sn).min(1).max(32),si=a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:eJ.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0)}).strict(),sa=a.Yj().trim().min(1).max(4096),sl=a.Yj().trim().min(1).max(256),so=a.Yj().max(32768),sc=a.Ik({name:sl,label:so,state:a.k5(["active","inactive","shadowed"]),description:so,promptSnippet:so.nullable(),promptGuidelineCount:a.ai().int().nonnegative(),promptGuidelinePreview:so.nullable()}).strict(),sd=a.Ik({name:sl,label:so,state:a.k5(["active","inactive","shadowed"]),description:so,parameters:ss.Dz,promptSnippet:so.nullable(),promptGuidelines:a.YO(so)}).strict(),su=a.Ik({path:sa,events:a.YO(a.Ik({name:sl,count:a.ai().int().positive()}).strict()),commands:a.YO(a.Ik({name:sl,description:so.nullable()}).strict()),shortcuts:a.YO(a.Ik({shortcut:sl,description:so.nullable()}).strict()),flags:a.YO(a.Ik({name:sl,type:a.k5(["boolean","string"]),description:so.nullable(),default:a.KC([a.zM(),a.Yj(),a.ch()])}).strict()),messageRenderers:a.YO(sl),entryRenderers:a.YO(sl)}).strict(),sm=a.Ik({name:sl,description:so,path:sa}).strict(),sp=sm.extend({modelVisible:a.zM()}).strict(),sh=sm.extend({content:a.Yj().max(65536),truncated:a.zM()}).strict(),sg=sh.extend({modelVisible:a.zM()}).strict(),sf=a.Ik({name:sl,path:sa}).strict(),sx=a.Ik({name:sl,kind:a.k5(["config","native"])}).strict(),sb=a.Ik({methods:a.YO(a.Ik({pluginName:sl,method:sl}).strict()),browserEntries:a.YO(a.Ik({pluginName:sl}).strict()),messageDeclarations:a.YO(a.Ik({pluginName:sl,declarationName:sl,priority:a.ai().int().safe()}).strict())}).strict(),sv=a.Ik({error:eJ.qf.refine(e=>"string"==typeof e?e.length<=32768:[e.default,...Object.values(e.translations)].every(e=>e.length<=32768)).nullable(),extensions:a.YO(su),tools:a.YO(sc),skills:a.YO(sp),prompts:a.YO(sm),themes:a.YO(sf),providers:a.YO(sx),piDesk:sb}).strict(),sw=a.Ik({action:a.k5(["add","update","del","apply","enable","disable"]),phase:a.k5(["queued","checking","applying","waiting","failed"]),message:a.Yj().max(4e3).nullable()}).strict(),sy=(0,l._G)({path:"plugins/management-update",bodySchema:a.Ik({}).strict()}),sk=a.Ik({source:sn,kind:a.k5(["package","extension"]).default("package"),operation:sw.nullable().default(null),pluginName:a.Yj().trim().min(1).nullable(),description:eJ.qf.nullable().default(null),version:a.Yj().trim().min(1).nullable(),updateAvailable:a.zM().nullable(),updateTag:tS.nullable().optional(),availableVersion:a.Yj().min(1).nullable().optional(),updateError:a.Yj().max(4e3).nullable().optional(),status:a.k5(["ready","available","disabled","failed"]),error:si.nullable(),capabilities:sv}).strict(),sj=a.Ik({source:sn,readme:eJ.qf.nullable().default(null),tools:a.YO(sd),skills:a.YO(sg),prompts:a.YO(sh)}).strict(),sN=a.Ik({plugins:a.YO(sk),restartRequired:a.zM(),loadError:eJ.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0).nullable()}).strict(),sI=a.Ik({sources:a.YO(sn).min(1).max(32).optional()}).strict(),sS=a.Ik({}).strict().extend({mode:a.k5(["normal","basic"]).optional()}).strict(),sC=a.Ik({checkUpdates:a.zM().optional(),sources:sr.optional(),tag:tS.optional()}).strict(),sE=a.Ik({source:sn}).strict(),sM=sE.extend({downloadSource:tE.optional(),registry:tC.optional(),tag:tS.optional()}).strict(),sz=a.gM("action",[a.Ik({action:a.eu("add"),items:a.YO(sM).min(1).max(32)}).strict(),a.Ik({action:a.eu("update"),sources:sr}).strict(),a.Ik({action:a.eu("del"),sources:sr}).strict(),a.Ik({action:a.eu("tag"),sources:sr,tag:tS}).strict()]),sA=a.Ik({snapshot:sN,results:a.YO(a.Ik({source:sn,error:a.Yj().max(4e3).nullable()}).strict()).max(32)}).strict(),s$=sE.extend({enabled:a.zM()}).strict();async function sR(e,t,s,n){return eu(e,t,s,n,{fallbackMessage:"插件管理请求失败"})}function sP({pluginName:e,descriptor:t,source:s,cwd:r,onPreviewFile:i,onRevealFile:a,onHeaderActionsChange:l}){let o=`${s.workId}\u0000${s.sessionId}\u0000${s.branchId}\u0000${r}`;return(0,n.jsx)(eK,{pluginName:e,kind:"session-sidebar-tab",contributionName:t.contributionName,target:{kind:"session-sidebar-tab",source:s,cwd:r,files:{preview:i,reveal:a},setHeaderActions:l},targetKey:o,layout:"fill"})}function sD({pluginName:e,descriptor:t,onClose:s,onBeforeLeaveChange:i}){let a=(0,Q.t4)();(0,Q.So)();let l=a.getEntryState(e),o="ready"===l.status?l.runtime:l.status;(0,r.useEffect)(()=>()=>{i(null)},[o,i]);let c=(0,r.useMemo)(()=>({kind:"settings-page",close:()=>{a.getEntryState(e)===l&&s()},setBeforeLeave:t=>{a.getEntryState(e)===l&&i(t)}}),[l,i,s,e,a]);return(0,n.jsx)(eK,{pluginName:e,kind:"settings-page",contributionName:t.contributionName,target:c,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})}function sT({source:e,placement:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,Q.So)(),a=(0,r.useMemo)(()=>({kind:"widget",source:e}),[e]),l=JSON.stringify([e.workId,e.sessionId,e.branchId]),o=i.flatMap(e=>e.contributions.flatMap(s=>"widget"===s.kind&&s.placement===t?[{pluginName:e.pluginName,descriptor:s}]:[]));return 0===o.length?null:(0,n.jsx)("div",{"data-testid":`plugin-widgets-${t}`,"aria-label":s("composer"),className:"min-w-0 w-full",children:o.map(({pluginName:e,descriptor:t})=>(0,n.jsx)(eK,{pluginName:e,kind:"widget",contributionName:t.contributionName,target:a,targetKey:l,layout:"inline"},`${e}:${t.contributionName}:${l}`))})}function sO({pluginName:e,contributionName:t,presentation:s,source:i,icon:a,label:l,onSelected:o}){let c=(0,Q.t4)();(0,Q.So)();let d=c.getEntryState(e),u=(0,X.G)(),{t:m}=(0,b.Bd)("workbench"),p=(0,r.useRef)(null),h=(0,r.useRef)(!1),[g,f]=(0,r.useState)(!1);(0,r.useLayoutEffect)(()=>{let e=new AbortController;return p.current=e,h.current=!1,queueMicrotask(()=>{e.signal.aborted||f(!1)}),()=>{e.abort(),p.current===e&&(p.current=null)}},[d,s,i]);let x=async()=>{let n=p.current;if(!n||n.signal.aborted||h.current)return;let r=()=>!n.signal.aborted&&c.getEntryState(e)===d;h.current=!0,f(!0);try{await c.invokeSessionHeaderAction({pluginName:e,contributionName:t,presentation:s,source:i,signal:n.signal}),r()&&o?.()}catch(a){if(!r())return;let n=a instanceof Error?a.message:m("operationFailed");console.error("[Pi Desk][PluginHost] 会话标题操作失败",{pluginName:e,contributionName:t,presentation:s,source:i,message:n}),u.error(n)}finally{r()&&(h.current=!1,f(!1))}};return(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm","aria-label":l,"aria-busy":g,disabled:g,"data-testid":"plugin-session-header-action","data-plugin-name":e,"data-contribution-name":t,"data-presentation":s,className:(0,C.cn)("overflow"===s&&"w-full justify-start whitespace-normal text-left"),onClick:()=>void x(),children:[(0,n.jsx)(eq,{icon:a,className:"size-4"}),(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:l})]})}function sL(e){return`${e.pluginName}:${e.descriptor.contributionName}`}function sF({item:e,source:t,presentation:s,onSelected:i,onContentChange:a}){let l=e.descriptor[s],o=(0,r.useMemo)(()=>({kind:"session-header-item",source:t,presentation:s}),[s,t]),c=JSON.stringify([t.workId,t.sessionId,t.branchId,s]),d=(0,r.useRef)(null),[u,m]=(0,r.useState)(!1);return((0,r.useLayoutEffect)(()=>{let t=d.current;if(!t)return;let s=new ResizeObserver(()=>{let s=t.getBoundingClientRect().height>0;m(s),a?.(e,s)});return s.observe(t),()=>s.disconnect()},[e,a,c]),"action"===l.type)?(0,n.jsx)(sO,{pluginName:e.pluginName,contributionName:e.descriptor.contributionName,presentation:s,source:t,icon:l.icon,label:l.label,onSelected:i}):(0,n.jsx)("div",{"data-testid":"plugin-session-header-custom","data-plugin-name":e.pluginName,"data-contribution-name":e.descriptor.contributionName,"data-presentation":s,className:(0,C.cn)("min-w-0 shrink-0","overflow"===s&&"w-full",!u&&"pointer-events-none invisible absolute"),"aria-hidden":!u,inert:!u,style:"inline"===s&&"custom"===e.descriptor.inline.type?{width:`${e.descriptor.inline.minWidthRem}rem`}:void 0,children:(0,n.jsx)("div",{ref:d,children:(0,n.jsx)(eK,{pluginName:e.pluginName,kind:"session-header-item",contributionName:e.descriptor.contributionName,target:o,targetKey:c,layout:"inline"})})})}function sB({source:e,title:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,Q.So)(),a=(0,r.useMemo)(()=>i.flatMap(e=>e.contributions.flatMap(t=>"session-header-item"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[i]),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(new Map),d=(0,r.useRef)(null),u=(0,r.useCallback)((e,t)=>{c.current.get(e)!==t&&(c.current.set(e,t),d.current?.())},[]),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),f=m?.items===a?m.count:a.length,x=m?.items===a?m.occupied:a.some(e=>"action"===e.descriptor.inline.type),v=a.slice(0,f),w=a.slice(f);return(0,r.useLayoutEffect)(()=>{for(let e of c.current.keys())a.includes(e)||c.current.delete(e);let e=l.current,t=o.current;if(!e||!t||0===a.length)return;let s=[...t.querySelectorAll("[data-header-item-width]")],n=t.querySelector("[data-header-title-width]"),r=t.querySelector("[data-header-more-width]"),i=t.querySelector("[data-header-gap-width]"),u=()=>{let t=i.getBoundingClientRect().width,l=e.getBoundingClientRect().width-n.getBoundingClientRect().width-t,o=s.map((e,t)=>"custom"!==a[t].descriptor.inline.type||c.current.get(a[t])?e.getBoundingClientRect().width:0),d=function(e,t,s,n){let r=e.filter(e=>e>0).length;if(e.reduce((e,t)=>e+t,0)+Math.max(0,r-1)*n<=t)return e.length;let i=s,a=0;for(let s of e){if(s>0){if(i+n+s>t)break;i+=n+s}a+=1}return a}(o,l,r.getBoundingClientRect().width,t),u=o.some(e=>e>0);d===a.length&&g(!1),p(e=>e?.items===a&&e.count===d&&e.occupied===u?e:{items:a,count:d,occupied:u})};d.current=u;let m=new ResizeObserver(u);for(let t of(m.observe(e),[...s,n,r,i]))m.observe(t);return u(),()=>{d.current=null,m.disconnect()}},[a]),(0,n.jsxs)("div",{ref:l,className:"relative flex min-w-0 flex-1 items-center","data-testid":"plugin-session-header",children:[(0,n.jsx)("div",{className:"min-w-[3rem] flex-1",children:t}),a.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:(0,C.cn)("flex shrink-0 items-center gap-1",x&&"ml-1"),"data-testid":"session-header-items",children:[v.map(t=>(0,n.jsx)(sF,{item:t,source:e,presentation:"inline",onContentChange:u},sL(t))),w.length>0?(0,n.jsxs)(eW.AM,{open:h,onOpenChange:g,children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":s("moreActions"),"data-testid":"session-header-more"}),children:(0,n.jsx)(K.A,{className:"size-4"})}),(0,n.jsxs)(eW.hl,{align:"end",finalFocus:!0,className:"pi-desk-chat-scrollbar max-h-[min(28rem,var(--available-height))] gap-1 overflow-auto p-1","data-testid":"session-header-overflow","aria-label":s("moreActions"),children:[(0,n.jsx)(eW.eO,{className:"sr-only",children:s("moreActions")}),h?w.map(t=>(0,n.jsx)(sF,{item:t,source:e,presentation:"overflow",onSelected:()=>g(!1)},sL(t))):null]})]}):null]}),(0,n.jsx)("div",{ref:o,"aria-hidden":"true",inert:!0,className:"pointer-events-none invisible absolute inset-0 overflow-hidden",children:(0,n.jsxs)("div",{className:"flex w-max items-center",children:[(0,n.jsx)("span",{"data-header-title-width":!0,className:"inline-block w-[3rem]"}),(0,n.jsx)("span",{"data-header-gap-width":!0,className:"inline-block w-1"}),(0,n.jsx)("span",{"data-header-more-width":!0,className:(0,I.r)({variant:"ghost",size:"icon-sm"}),children:(0,n.jsx)(K.A,{className:"size-4"})}),a.map(e=>"action"===e.descriptor.inline.type?(0,n.jsxs)("span",{"data-header-item-width":!0,className:(0,I.r)({variant:"ghost",size:"sm"}),children:[(0,n.jsx)(eq,{icon:e.descriptor.inline.icon,className:"size-4"}),(0,n.jsx)("span",{children:e.descriptor.inline.label})]},sL(e)):(0,n.jsx)("span",{"data-header-item-width":!0,className:"inline-block shrink-0",style:{width:`${e.descriptor.inline.minWidthRem}rem`}},sL(e)))]})})]}):null]})}var sq=s(10263),s_=s(11831),sW=s(79615),sY=s(24863),sV=s(10672);let sU="1.1.30-dev".trim()||"未知",sK="2026-10-28T23:14:15+08:00".trim()||null;var sH=s(42655),sG=s(55079),sJ=s(49667),sQ=s(61286),sX=s(33550),sZ=s(66453),s0=s(67765);let s1=a.Yj().min(1).max(s0.uV).refine(e=>!e.includes("\0")&&(e.startsWith("/")||e.startsWith("\\\\")||/^[a-zA-Z]:[\\/]/.test(e)),"必须是绝对路径"),s2=a.Ik({cwd:sZ.m4.nullable()}).strict(),s5=a.Ik({skillPath:s1,name:a.Yj().min(1),description:a.Yj(),packageSource:a.Yj().nullable()}).strict(),s3=a.Ik({skills:a.YO(s5),diagnostics:a.YO(a.Ik({path:a.Yj(),message:eJ.qf}).strict())}).strict(),s4=s2.extend({skillPath:s1}),s6=s4.extend({path:s0.rh}).strict(),s8=a.Ik({entries:a.YO(a.Ik({name:a.Yj().min(1),type:a.k5(["directory","file"])}).strict()).max(s0.xm),truncated:a.zM()}).strict(),s7=s4.extend({path:s0._g}).strict(),s9=a.gM("kind",[a.Ik({kind:a.eu("text"),content:a.Yj(),size:a.ai().int().nonnegative().max(s0.NL),readOnlyReason:eJ.qf.nullable()}).strict(),a.Ik({kind:a.eu("image"),mimeType:s0.CT,data:a.Yj(),size:a.ai().int().nonnegative()}).strict(),a.Ik({kind:a.eu("unsupported"),size:a.ai().int().nonnegative(),reason:a.Yj()}).strict()]),ne=s7.extend({content:a.Yj().max(s0.NL)}).strict(),nt=a.Ik({}).strict(),ns={path:"/api/skills/list",request:s2,response:s3},nn={path:"/api/skill-files/list",request:s6,response:s8},nr={path:"/api/skill-files/get",request:s7,response:s9},ni={path:"/api/skill-files/replace",request:ne,response:nt},na=a.Ik({code:a.ai(),msg:a.Yj(),data:a.L5(),i18n:sQ.N.optional()});async function nl(e,t,s,n){let r=await fetch(t.path,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(t.request.parse(s)),signal:n}),i=na.parse(await r.json());if(!r.ok||0!==i.code||null===i.data)throw Error(i.msg?(0,ed.B)(i):"Skills 请求失败");return t.response.parse(i.data)}function no(e){(0,sX.ZQ)({wrapLines:e})}async function nc(e){let t=e.skillPath.replaceAll("\\","/");await navigator.clipboard.writeText(t.slice(0,t.lastIndexOf("/")+1)+e.path)}var nd=s(46782);function nu(e){return(0,ed.B)({msg:nd.P["zh-CN"][e],i18n:{key:`skills:${e}`}})}function nm(e){return JSON.stringify(e)}function np(e){return JSON.stringify([e.cwd,e.skillPath,e.path])}function nh(e){return e.replace(/\r\n|\r/g,"\n")}function ng(e){return e?.file?.kind==="text"&&e.draft!==nh(e.file.content)}var nf=s(60794),nx=s(89757),nb=s(55628),nv=s(91182);function nw(e){let{t}=(0,b.Bd)("common"),{wrapLines:s}=(0,sX.TX)(),i=e.path,a=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(null),d=(0,r.useRef)(null),u=(0,r.useRef)(0),m=(0,r.useRef)(e),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{m.current=e}),(0,r.useEffect)(()=>{let e=!1,s=()=>void 0,n=()=>void 0;return(0,nv.cu)().then(r=>{if(e||!a.current)return;let i=m.current,o=r.editor.create(a.current,{model:null,theme:(0,nv.dC)(),automaticLayout:!0,readOnly:i.readOnly,domReadOnly:i.readOnly,wordWrap:(0,sX.E6)().wrapLines?"on":"off",wrappingIndent:"same",minimap:{enabled:!1},stickyScroll:{enabled:!1},scrollBeyondLastLine:!1,...(0,nv.R)(),lineNumbersMinChars:3,padding:{top:14,bottom:14},unicodeHighlight:{nonBasicASCII:!1},renderWhitespace:"selection",overviewRulerBorder:!1,ariaLabel:t("skillEditor")});l.current=o,o.addCommand(r.KeyMod.CtrlCmd|r.KeyCode.KeyS,()=>m.current.onSave()),s=(0,nv.Tr)(e=>r.editor.setTheme(e)),n=(0,nv.BK)(e=>o.updateOptions(e)),f(!0)}).catch(()=>{e||h(!0)}),()=>{e=!0,s(),n(),c.current?.dispose(),c.current=null,o.current?.dispose(),o.current=null,d.current=null,l.current?.dispose(),l.current=null}},[t]),(0,r.useEffect)(()=>{let e=!1,t=u.current+1;return u.current=t,(0,nv.cu)().then(s=>{if(e||t!==u.current||!l.current)return;let n=m.current,r=s.editor.createModel(n.content,(0,nv.ix)(n.path,n.size),(0,nv.B3)(s,n.path,"edit")),a=o.current;c.current?.dispose(),c.current=r.onDidChangeContent(()=>{m.current.onChange(r.getValue(s.editor.EndOfLinePreference.LF))}),o.current=r,d.current=i,l.current.setModel(r),a?.dispose()}),()=>{e=!0}},[i]),(0,r.useEffect)(()=>{let t=o.current;t&&d.current===e.path&&t.getValue().replace(/\r\n|\r/g,"\n")!==e.content&&t.setValue(e.content)},[e.content,e.path]),(0,r.useEffect)(()=>{l.current?.updateOptions({readOnly:e.readOnly,domReadOnly:e.readOnly,wordWrap:s?"on":"off"})},[e.readOnly,s]),(0,n.jsxs)("div",{"data-testid":"code-editor",className:"relative h-full min-h-0 w-full overflow-hidden bg-background",children:[(0,n.jsx)("div",{ref:a,className:"size-full"}),!g&&(0,n.jsx)("div",{role:"status",className:"absolute inset-0 flex items-center justify-center p-6 text-sm text-muted-foreground",children:p?t("editorFailed"):t("editorLoading")})]})}var ny=s(58840);function nk({file:e,path:t}){let{t:s}=(0,b.Bd)("skills"),i=(0,r.useMemo)(()=>[{src:`data:${e.mimeType};base64,${e.data}`,alt:t}],[e,t]);return(0,n.jsx)(ny.k,{mode:"inline",slides:i,className:"h-full w-full",ariaLabel:s("imagePreview")})}function nj(e){let{document:t,skill:s,dirty:r,loading:i,saving:a,opening:l}=e,{t:o}=(0,b.Bd)("skills"),{locale:c}=(0,eQ.i)();if(!t)return(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center",children:[(0,n.jsx)(nf.A,{className:"size-6 text-muted-foreground"}),(0,n.jsx)("h3",{className:"text-sm font-medium",children:o("chooseFile")}),(0,n.jsx)("p",{className:"max-w-xs text-sm leading-6 text-muted-foreground",children:o("chooseFileDescription")})]});let d=t.file,u=d?.kind==="text"?d.readOnlyReason:null;return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-14 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-2",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("p",{className:"truncate text-xs text-muted-foreground",title:s?.description,children:[s?.name??t.target.skillPath.split("/").at(-2),(0,n.jsx)("span",{className:"mx-1.5",children:"/"}),o(null===t.target.cwd?"global":"project"),` \xb7 ${o(s?.packageSource?"package":"local")}`]}),(0,n.jsx)("p",{className:"mt-1 truncate font-mono text-sm",title:t.target.path,children:t.target.path})]}),d?.kind==="text"&&(0,n.jsxs)("span",{role:"status","aria-label":o(a?"saving":l?"switchingFile":r?"unsavedChanges":u?"readOnlyFile":"fileSaved"),className:"hidden shrink-0 items-center gap-1 text-xs text-muted-foreground sm:flex",children:[a||l?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):r?(0,n.jsx)("span",{className:"size-1.5 rounded-full bg-status-warning"}):u?(0,n.jsx)(nx.A,{className:"size-3.5"}):(0,n.jsx)(ep.A,{className:"size-3.5"}),o(a?"saving":l?"switchingFile":r?"unsaved":u?"readOnly":"saved")]}),r&&(0,n.jsx)("span",{"aria-label":o("unsavedChanges"),className:"size-2 shrink-0 rounded-full bg-status-warning sm:hidden"}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon","aria-label":o("copySkillPath"),title:o("copyPath"),onClick:e.onCopy,children:(0,n.jsx)(ee.A,{className:"size-4"})}),(0,n.jsxs)(I.$,{"aria-label":o("saveSkill"),disabled:!r||!!u||i||a,onClick:e.onSave,children:[a?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(Z.A,{className:"size-4"}),o("save")]})]}),u&&(0,n.jsxs)("div",{role:"note",className:"flex shrink-0 items-start gap-2 border-b bg-muted px-4 py-2 text-sm leading-5 text-muted-foreground",children:[(0,n.jsx)(nx.A,{className:"mt-0.5 size-3.5 shrink-0"}),(0,n.jsx)("p",{children:(0,eJ.fD)(u,c)})]}),t.error&&(0,n.jsxs)("div",{role:"alert",className:"shrink-0 border-b bg-muted px-4 py-2 text-sm text-destructive",children:[t.error,!d&&(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:e.onReload,children:o("reload")})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:i&&!d?(0,n.jsxs)("div",{role:"status",className:"flex h-full items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),o("loadingFile")]}):d?.kind==="text"?(0,n.jsx)(nw,{path:t.target.skillPath.slice(0,t.target.skillPath.lastIndexOf("/")+1)+t.target.path,content:t.draft,size:d.size,readOnly:!!u||a||l,onChange:e.onChange,onSave:e.onSave}):d?.kind==="image"?(0,n.jsx)(nk,{file:d,path:t.target.path}):d?.kind==="unsupported"?(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-sm text-muted-foreground",children:[(0,n.jsx)(nf.A,{className:"mb-2 size-8"}),(0,n.jsx)("p",{children:d.reason}),(0,n.jsx)("p",{children:o("fileSize",{size:d.size.toLocaleString("en"===c?"en-US":"zh-CN")})})]}):null}),d?.kind==="text"&&(0,n.jsxs)("div",{className:"flex min-h-9 shrink-0 items-center justify-between gap-2 border-t px-3 py-1 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{className:"truncate",children:["UTF-8 \xb7 ",o(u?"readOnly":"saveShortcut")]}),(0,n.jsxs)(I.$,{variant:"ghost",size:"sm","aria-label":o("wrapLines"),"aria-pressed":e.wrapLines,onClick:e.onWrapLines,children:[(0,n.jsx)(nb.A,{className:"size-3.5"}),o("wrapLines")]})]})]})}function nN({open:e,saving:t,path:s,error:r,onDecide:i}){let{t:a}=(0,b.Bd)("skills");return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||t||i("cancel")},children:(0,n.jsxs)(eN.hA,{className:"z-[150]",showCloseButton:!t,children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:a("saveChangesTitle")}),(0,n.jsx)(eN.uX,{children:a("saveChangesDescription",{path:s??""})})]}),r&&(0,n.jsx)("p",{role:"alert",className:"px-4 pb-4 text-sm text-destructive",children:r}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{variant:"outline",disabled:t,onClick:()=>void i("cancel"),children:a("cancel")}),(0,n.jsx)(I.$,{variant:"ghost",disabled:t,onClick:()=>void i("discard"),children:a("discard")}),(0,n.jsx)(I.$,{disabled:t,onClick:()=>void i("save"),children:a(t?"savingChanges":"saveContinue")})]})]})})}var nI=s(19932),nS=s(43326),nC=s(17511);function nE(e,t){return!!(e&&e.cwd===t.cwd&&e.skillPath===t.skillPath&&e.path===t.path)}function nM({target:e,props:t,depth:s=0,skillName:i}){let{t:a}=(0,b.Bd)("skills"),l=t.directories[np(e)],{onLoadDirectory:o}=t;return((0,r.useEffect)(()=>{l||o(e)},[l,o,e]),l?.error)?(0,n.jsxs)("div",{className:"px-3 py-2 text-xs text-destructive",children:[l.error,(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:()=>void t.onLoadDirectory(e),children:a("retryFolder")})]}):l?.data?(0,n.jsxs)("div",{className:"relative ml-5 border-l border-border/70 py-1 pl-3",children:[l.data.entries.map(r=>{let l=e.path?`${e.path}/${r.name}`:r.name,o={...e,path:l};if("directory"===r.type)return(0,n.jsx)(nz,{target:o,props:t,depth:s,name:r.name,skillName:i},l);let c=nE(t.selected,o),d=nE(t.pending,o);return(0,n.jsxs)(I.$,{variant:"ghost","aria-label":a("skillFile",{path:`${i}/${l}`}),"aria-pressed":c,title:l,className:(0,C.cn)("min-h-9 w-full justify-start text-left font-normal text-muted-foreground",c&&"font-medium",d&&"bg-muted text-foreground"),onClick:()=>void t.onOpenFile(o),children:["SKILL.md"===r.name?(0,n.jsx)(nI.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(nf.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r.name}),d&&(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin"})]},l)}),0===l.data.entries.length&&(0,n.jsx)("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:a("emptyFolder")}),l.data.truncated&&(0,n.jsx)("p",{className:"px-3 py-2 text-sm text-status-warning",children:a("folderTruncated")})]}):(0,n.jsx)("p",{role:"status",className:"px-4 py-2 text-xs text-muted-foreground",children:a("loadingFolder")})}function nz({target:e,props:t,depth:s,name:i,skillName:a}){let{t:l}=(0,b.Bd)("skills"),[o,c]=(0,r.useState)(!1);return(0,n.jsxs)("div",{children:[(0,n.jsxs)(I.$,{variant:"ghost","aria-expanded":o,"aria-label":l("skillFolder",{path:`${a}/${e.path}`}),className:(0,C.cn)("min-h-9 w-full justify-start font-normal text-muted-foreground",o&&"bg-muted text-foreground"),onClick:()=>c(!o),children:[o?(0,n.jsx)(eY.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(e7.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)(eP.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:i})]}),o&&(0,n.jsx)("div",{className:s>3?"-ml-3":void 0,children:(0,n.jsx)(nM,{target:e,props:t,depth:s+1,skillName:a})})]})}function nA({cwd:e,skill:t,props:s}){let{t:i}=(0,b.Bd)("skills"),a=s.selected?.cwd===e&&s.selected.skillPath===t.skillPath,l=s.pending?.cwd===e&&s.pending.skillPath===t.skillPath,[o,c]=(0,r.useState)(null),d=o??a,u=async()=>{if(d)return void c(!1);let n=t.skillPath.replaceAll("\\","/").split("/").at(-1);await s.onOpenFile({cwd:e,skillPath:t.skillPath,path:n})&&c(!0)};return(0,n.jsxs)("div",{className:"py-0.5",children:[(0,n.jsxs)(I.$,{variant:"ghost","aria-label":i("skillName",{name:t.name}),"aria-expanded":d,title:`${t.description}
|
|
154
|
+
location: ${e.path}`})}):null,(0,n.jsx)(tp,{title:t("viewSkillContent"),content:e.content,truncated:e.truncated})]},e.path)),e.prompts.map(e=>(0,n.jsxs)("article",{className:"border-b py-4 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)("code",{className:"font-semibold",children:["/",e.name]}),(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:t("manualOnly")})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:e.description}),(0,n.jsx)("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:e.path}),(0,n.jsx)(tp,{title:t("viewPromptContent"),content:e.content,truncated:e.truncated})]},e.path))]})})}function tg({capabilities:e,browserContributions:t}){let{t:s}=(0,b.Bd)("pluginManagement"),r=e.extensions.some(e=>e.events.length>0||e.commands.length>0||e.shortcuts.length>0||e.flags.length>0||e.messageRenderers.length>0||e.entryRenderers.length>0),i=e.piDesk.methods.length>0||e.piDesk.browserEntries.length>0||e.piDesk.messageDeclarations.length>0||t.length>0,a=e.themes.length>0||e.providers.length>0;return r||i||a?(0,n.jsx)(tc,{title:s("otherCapabilities"),children:(0,n.jsxs)("div",{className:"space-y-2",children:[i?(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs",children:[(0,n.jsx)("p",{className:"font-semibold",children:"Pi Desk"}),(0,n.jsxs)("div",{className:"mt-2 space-y-1.5 text-muted-foreground",children:[e.piDesk.methods.map(e=>(0,n.jsxs)("p",{children:["Method:",(0,n.jsxs)("code",{children:[e.pluginName,"/",e.method]})]},`${e.pluginName}:${e.method}`)),t.map(e=>(0,n.jsxs)("p",{children:[s(tn[e.kind]),":","message-view"===e.kind?e.viewKey:"application"===e.kind?e.title:"widget"===e.kind||"session-header-item"===e.kind?e.contributionName:e.label]},`${e.kind}:${e.contributionName}`)),e.piDesk.messageDeclarations.map(e=>(0,n.jsxs)("p",{children:[s("messageDeclarations"),(0,n.jsxs)("code",{children:[e.pluginName,"/",e.declarationName]})]},`${e.pluginName}:${e.declarationName}`))]})]}):null,r?e.extensions.map(e=>(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs",children:[(0,n.jsx)("code",{className:"block break-all font-semibold",children:e.path}),e.commands.length>0?(0,n.jsxs)("p",{className:"mt-2 leading-5 text-muted-foreground",children:["Commands:",e.commands.map(e=>`/${e.name}`).join("、")]}):null,e.shortcuts.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Shortcuts:",e.shortcuts.map(e=>e.shortcut).join("、")]}):null,e.flags.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Flags:",e.flags.map(e=>`--${e.name}`).join("、")]}):null,e.events.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Events:",e.events.map(e=>e.name).join("、")]}):null]},e.path)):null,a?(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs text-muted-foreground",children:[e.themes.length>0?(0,n.jsxs)("p",{children:["Theme:",e.themes.map(e=>e.name).join("、")]}):null,e.providers.length>0?(0,n.jsxs)("p",{className:"mt-1",children:["Provider:",e.providers.map(e=>e.name).join("、")]}):null]}):null]})}):null}function tf({plugin:e,detail:t,detailLoading:s,detailError:r,browserContributions:i,onRetry:a}){let{t:l}=(0,b.Bd)("pluginManagement"),{locale:o}=(0,eQ.i)(),c=function(e,t,s){let n=[];e.tools.length>0&&n.push({label:s("tagTools",{count:e.tools.length}),tone:"neutral"});let r=e.tools.reduce((e,t)=>"active"!==t.state?e:e+ +!!t.promptSnippet+t.promptGuidelineCount,0)+e.skills.filter(e=>e.modelVisible).length;r>0&&n.push({label:s("tagFixed",{count:r}),tone:"prompt"});let i=tr(e).reduce((e,t)=>e+t.count,0);i>0&&n.push({label:s("tagDynamic",{count:i}),tone:"dynamic"});let a=e.tools.filter(e=>"shadowed"!==e.state&&te.has(e.name)).length;a>0&&n.push({label:s("tagOverride",{count:a}),tone:"override"});let l=e.prompts.length+e.skills.filter(e=>!e.modelVisible).length;l>0&&n.push({label:s("tagManual",{count:l}),tone:"neutral"});let o=t.length+e.piDesk.methods.length+e.piDesk.messageDeclarations.length;o>0&&n.push({label:`Pi Desk ${o}`,tone:"neutral"});let c=e.providers.length+e.themes.length+e.extensions.reduce((e,t)=>e+t.commands.length+t.shortcuts.length+t.flags.length,0);return c>0&&n.push({label:s("tagInteraction",{count:c}),tone:"neutral"}),0===n.length&&e.extensions.length>0&&n.push({label:`Extension ${e.extensions.length}`,tone:"neutral"}),n}(e.capabilities,i,l);return(0,n.jsxs)("div",{className:"space-y-3 text-sm","data-testid":"plugin-capability-detail",children:[(0,n.jsx)("p",{className:"break-all font-mono text-xs text-muted-foreground",children:e.source}),c.length>0?(0,n.jsx)("div",{className:"flex flex-wrap gap-2","aria-label":l("capabilityCategories"),children:c.map(e=>(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-0.5 text-xs text-muted-foreground",children:e.label},e.label))}):null,e.capabilities.error?(0,n.jsx)("p",{className:"whitespace-pre-wrap break-words text-sm leading-5 text-status-warning",children:l("incompleteCapabilities",{error:(0,eJ.fD)(e.capabilities.error,o)})}):null,s?(0,n.jsxs)("div",{className:"flex items-center gap-2 py-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),l("loadingFullDetails")]}):r?(0,n.jsxs)("div",{className:"flex items-start gap-2",role:"alert",children:[(0,n.jsx)("p",{className:"min-w-0 flex-1 break-words text-sm text-destructive",children:r}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",onClick:a,children:[(0,n.jsx)(es.A,{"data-icon":"inline-start"}),l("retry")]})]}):t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(tm,{detail:t}),(0,n.jsx)(th,{detail:t})]}):null,(0,n.jsx)(td,{capabilities:e.capabilities}),(0,n.jsx)(tg,{capabilities:e.capabilities,browserContributions:i})]})}var tx=s(76782),tb=s(44980);function tv({className:e,size:t="default",...s}){return(0,n.jsx)(tx.l,{"data-slot":"switch","data-size":t,className:(0,C.cn)("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",e),...s,children:(0,n.jsx)(tb.p,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"})})}function tw({plugin:e,displayName:t,browserError:s,disabled:r,pending:i,browserRetryPending:a,onAction:l}){let{t:o}=(0,b.Bd)("pluginManagement"),c=e.operation?.phase,d="disabled"!==e.status;return(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-3",children:[i?(0,n.jsxs)("span",{role:"status",className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:["waiting"!==c?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):null,o(c&&"failed"!==c?`phase_${c}`:"submitting")]}):e.updateAvailable&&"extension"!==e.kind&&"failed"!==c?(0,n.jsx)(I.$,{size:"sm",disabled:r,onClick:()=>l("update"),children:o("update")}):null,"failed"===c?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||i,onClick:()=>l("retry"),children:o("retry")}):"failed"===e.status?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||i,onClick:()=>l("reload"),children:o("reloadOne")}):s&&e.pluginName?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||a,onClick:()=>l("retry-browser"),children:o("retryView")}):null,(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(tv,{checked:d,"aria-label":o("togglePlugin",{name:t}),disabled:r||i,onCheckedChange:e=>l(e?"enable":"disable")}),o(d?"enabled":"disabled")]}),"extension"!==e.kind?(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive","aria-label":o("removeNamed",{name:t}),title:o("remove"),disabled:r||i,onClick:()=>l("remove"),children:(0,n.jsx)(et.A,{})}):null]})}function ty({plugin:e,requestError:t,browserError:s}){let{t:r}=(0,b.Bd)("pluginManagement"),{locale:i}=(0,eQ.i)(),a=e.operation?.phase,l=[t,"failed"===a?e.operation?.message:null,e.error?(0,eJ.fD)(e.error.message,i):null,s,e.updateError?r("itemCheckFailed",{error:e.updateError}):null].filter((e,t,s)=>!!e&&s.indexOf(e)===t);return l.length||"waiting"===a||"failed"===e.status?(0,n.jsxs)("div",{className:"space-y-1",children:[l.map(e=>(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive [overflow-wrap:anywhere]",children:e},e)),l.length||"failed"!==e.status?null:(0,n.jsx)("p",{className:"text-sm text-destructive",children:r("notLoaded")}),"waiting"===a&&e.operation?.message?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operation.message}):null]}):null}function tk(e){let t=e.startsWith("npm:")?e.slice(4):e,s=/^((?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*)(?:@([^\s/]+))?$/i.exec(t);return s?{name:s[1],...s[2]?{version:s[2]}:{}}:null}function tj(e){return e.source.startsWith("npm:")?tk(e.source)?.name??e.source:e.pluginName??("extension"===e.kind?e.source.replaceAll("\\","/").split("/").at(-1):null)??e.source}function tN(e){return`source:${tk(e)?.name??e}`}function tI(e){switch(e.kind){case"batch":return"add"===e.input.action?"batchInstall":"update"===e.input.action?"updateSelected":"del"===e.input.action?"removeSelected":"setChannel";case"add":return"actionAdd";case"update":return"actionUpdate";case"del":return"actionDelete";case"enable":return"enable";case"disable":return"disable";case"reload":return"normal"===e.mode?"restartNormal":"actionReload"}}let tS=a.Yj().trim().min(1).max(128).regex(/^[a-zA-Z][a-zA-Z0-9._-]*$/),tC=a.Yj().trim().url().max(2048).refine(e=>{let t=new URL(e);return["https:","http:"].includes(t.protocol)&&!t.username&&!t.password&&!t.search&&!t.hash},"插件源必须是 HTTP 或 HTTPS 仓库地址"),tE=a.gM("mode",[a.Ik({mode:a.eu("auto")}).strict(),a.Ik({mode:a.eu("local")}).strict(),a.Ik({mode:a.eu("official")}).strict(),a.Ik({mode:a.eu("domestic")}).strict(),a.Ik({mode:a.eu("custom"),registry:tC}).strict()]),tM=a.Ik({description:a.Yj().trim().min(1).max(4e3).optional(),readme:a.Yj().trim().min(1).max(1024).optional()});a.Ik({description:a.Yj().optional(),piDesk:a.Ik({i18n:a.g1(a.Yj().min(1).max(35),tM).optional()}).passthrough().optional()}).passthrough();let tz=a.Ik({downloadSource:tE,recommendedRegistry:tC}).strict(),tA=a.Ik({downloadSource:tE}).strict(),t$=a.Ik({query:a.Yj().trim().max(200).default(""),page:a.ai().int().min(1).max(100).default(1),kind:a.k5(["all","desk","pi"]).default("all"),registry:tC.optional()}).strict(),tR=a.Ik({name:a.Yj().trim().min(1).max(214).regex(/^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/i),version:a.Yj().trim().min(1).max(128).optional(),registry:tC.optional()}).strict(),tP=a.Ik({name:a.Yj(),description:eJ.qf.nullable(),version:a.Yj(),publisher:a.Yj().nullable(),kind:a.k5(["desk","pi","unknown"]),official:a.zM(),registry:tC}).strict(),tD=a.Ik({items:a.YO(tP),hasMore:a.zM()}).strict(),tT=tP.extend({versions:a.YO(a.Yj()),readme:eJ.qf.nullable(),homepage:a.Yj().nullable(),repository:a.Yj().nullable(),compatible:a.zM().nullable(),compatibilityNote:a.Yj().nullable()}).strict();function tO({id:e,mode:t,registry:s,recommendedRegistry:r,savedRegistry:i,loading:a,saving:l,error:o,override:c,onMode:d,onRegistry:u,onSave:m,onRetry:p}){let{t:h}=(0,b.Bd)("pluginManagement"),g="auto"===t?r:"official"===t?"https://registry.npmjs.org":"domestic"===t?"https://mirrors.cloud.tencent.com/npm":"custom"===t?i??s:null,f=[...c?[{value:"default",label:h("useDefaultSource")}]:[],...["local","auto","domestic","official","custom"].map(e=>({value:e,label:h(`download_${e}`)}))];return(0,n.jsxs)("div",{className:"min-w-0 space-y-3 text-sm",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:e,className:"font-medium",children:h(c?"installDownloadSource":"downloadSource")}),(0,n.jsxs)(ea.l6,{value:t,items:f,disabled:a,onValueChange:e=>{e&&!l&&d(e)},children:[(0,n.jsx)(ea.bq,{id:e,className:"max-w-full",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:f.map(e=>(0,n.jsx)(ea.eb,{value:e.value,disabled:l,children:e.label},e.value))})]}),l?(0,n.jsx)("span",{role:"status",className:"text-muted-foreground",children:h("saving")}):null]}),"custom"===t?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:`${e}-url`,className:"block",children:h("registryUrl")}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(em.p,{id:`${e}-url`,type:"url",value:s,placeholder:"https://registry.example.com",className:"min-w-0 flex-1 basis-48",disabled:l,onChange:e=>u(e.target.value)}),m?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:l,onClick:m,children:h("save")}):null]})]}):!c&&g?(0,n.jsx)("p",{className:"break-all text-xs text-muted-foreground",children:g}):null,o?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:o}),p?(0,n.jsx)(I.$,{variant:"outline",size:"sm",onClick:p,children:h("retry")}):null]}):null]})}var tL=s(3058),tF=s(97724),tB=s(48742);function tq({className:e,...t}){return(0,n.jsx)(tF.y,{"data-slot":"checkbox",className:(0,C.cn)("peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",e),...t,children:(0,n.jsx)(tB.P,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none [&>svg]:size-3.5",children:(0,n.jsx)(ep.A,{})})})}function t_(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=e.snapshot?.plugins??[],i=t=>e.requests.has(tN(t.source))||!!(t.operation&&"failed"!==t.operation.phase),a=r.filter(t=>("updates"!==e.statusFilter||!!t.updateAvailable)&&("disabled"!==e.statusFilter||"disabled"===t.status)&&("failed"!==e.statusFilter||!!("failed"===t.status||t.operation?.phase==="failed"||t.updateError||t.pluginName&&e.browserErrors.has(t.pluginName)))&&`${tj(t)} ${t.description?(0,eJ.fD)(t.description,s):""}`.toLocaleLowerCase().includes(e.filter.trim().toLocaleLowerCase())),l=a.filter(e=>"extension"!==e.kind),o=r.filter(t=>e.selected.has(tN(t.source))),c=r.filter(e=>!0===e.updateAvailable&&"extension"!==e.kind&&!i(e)),d=c.filter(t=>e.selected.has(tN(t.source))),u=o.filter(e=>!i(e)),m=l.length>0&&l.every(t=>e.selected.has(tN(t.source))),p=l.some(t=>e.selected.has(tN(t.source))),h=["all","updates","disabled","failed"].map(e=>({value:e,label:t(`statusFilter_${e}`)}));return(0,n.jsxs)("section",{"aria-label":t("installed"),className:"flex min-h-0 min-w-0 flex-col gap-3",children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 bg-popover pb-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(em.p,{"aria-label":t("filterInstalled"),value:e.filter,onChange:t=>e.onFilter(t.target.value),placeholder:t("filterInstalled"),className:"min-w-40 flex-1 basis-52"}),(0,n.jsxs)(ea.l6,{value:e.statusFilter,items:h,onValueChange:t=>{t&&e.onStatusFilter(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("filterStatus"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:h.map(e=>(0,n.jsx)(ea.eb,{value:e.value,children:e.label},e.value))})]}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading||e.disabled,onClick:e.onRefresh,children:t(e.loading?"checkingUpdates":"checkUpdates")}),c.length>0?(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||e.loading,onClick:e.onUpdateAll,children:t("updateAll",{count:c.length})}):null,r.some(e=>"extension"!==e.kind)?(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:()=>e.onBatchMode(!e.batchMode),children:t(e.batchMode?"finishSelection":"batchManage")}):null]}),e.batchMode?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 rounded-lg bg-muted px-3 py-2",children:[(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,n.jsxs)("span",{className:"relative flex size-4 items-center justify-center",children:[(0,n.jsx)(tq,{checked:m,indeterminate:p&&!m,className:"data-indeterminate:[&_svg]:hidden",disabled:!l.length,onCheckedChange:t=>e.onSelect(l.map(e=>tN(e.source)),t)}),p&&!m?(0,n.jsx)(tL.A,{"aria-hidden":!0,className:"pointer-events-none absolute size-3.5"}):null]}),t(e.filter||"all"!==e.statusFilter?"selectFiltered":"selectAll")]}),(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("selectedCount",{count:o.length})}),o.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled||e.loading||!d.length,onClick:e.onUpdateSelected,children:t("updateSelected")}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled||!u.length,onClick:e.onRemoveSelected,children:t("removeSelected")}),(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:()=>e.onSelect([...e.selected],!1),children:t("clearSelection")})]}):null]}):null,e.errors.list?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.errors.list}):null]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto",children:e.loading&&!e.snapshot?(0,n.jsx)("p",{role:"status",className:"py-6 text-sm text-muted-foreground",children:t("loading")}):a.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:a.map(r=>{let a=tj(r),l=tN(r.source),o=r.pluginName?e.browserErrors.get(r.pluginName)??null:null;return(0,n.jsx)("article",{"aria-label":a,className:`min-w-0 px-4 py-3 ${e.selected.has(l)&&e.batchMode?"bg-accent/40":""}`,children:(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[e.batchMode&&"extension"!==r.kind?(0,n.jsx)("div",{className:"flex min-h-8 shrink-0 items-center",children:(0,n.jsx)(tq,{checked:e.selected.has(l),"aria-label":t("selectPlugin",{name:a}),onCheckedChange:t=>e.onSelect([l],t)})}):null,(0,n.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-1 basis-64 flex-wrap items-center gap-x-2 gap-y-1",children:[(0,n.jsx)(I.$,{variant:"link",className:"h-auto min-h-8 min-w-0 max-w-full justify-start p-0 text-left text-sm font-semibold whitespace-normal no-underline hover:underline [overflow-wrap:anywhere]","aria-label":t("viewDetails",{name:a}),onClick:()=>e.onDetail(r.source),children:a}),r.version?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",r.version]}):null,r.updateAvailable?(0,n.jsx)("span",{className:"inline-flex rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:r.availableVersion?t("newVersion",{version:r.availableVersion}):t("updateAvailable")}):null,r.updateTag&&"latest"!==r.updateTag?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:"dev"===r.updateTag?t("channelDev"):r.updateTag}):null]}),(0,n.jsx)(tw,{plugin:r,displayName:a,browserError:o,disabled:e.disabled,pending:i(r),browserRetryPending:e.requests.has(`entry:${r.pluginName}`),onAction:t=>e.onAction(r,t)})]}),r.description?(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:(0,eJ.fD)(r.description,s)}):null,(0,n.jsx)(ty,{plugin:r,browserError:o,requestError:e.errors[l]??e.errors[`entry:${r.pluginName}`]})]})]})},l)})}):(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:t(e.filter||"all"!==e.statusFilter?"noMatches":"empty")})})]})}function tW(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=new Map(e.snapshot?.plugins.filter(e=>e.source.startsWith("npm:")).map(e=>[tk(e.source)?.name,e]));return(0,n.jsxs)("section",{className:"min-w-0 space-y-4","aria-label":t("searchPlugins"),children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:"plugin-catalog-query",className:"sr-only",children:t("searchPlugins")}),(0,n.jsx)(em.p,{id:"plugin-catalog-query",value:e.query,placeholder:t("searchPlaceholder"),className:"min-w-40 flex-1 basis-56",maxLength:200,onChange:t=>e.onQuery(t.target.value),onCompositionStart:e.onCompositionStart,onCompositionEnd:e.onCompositionEnd}),(0,n.jsxs)(ea.l6,{value:e.searchSource,items:[{value:"public",label:t("publicNpm")},{value:"custom",label:t("customSearchSource")}],onValueChange:t=>{t&&e.onSearchSource(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("searchSource"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"public",children:t("publicNpm")}),(0,n.jsx)(ea.eb,{value:"custom",children:t("customSearchSource")})]})]}),(0,n.jsxs)(ea.l6,{value:e.kind,items:["all","desk","pi"].map(e=>({value:e,label:t(`kind_${e}`)})),onValueChange:t=>{t&&e.onKind(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("pluginKind"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:["all","desk","pi"].map(e=>(0,n.jsx)(ea.eb,{value:e,children:t(`kind_${e}`)},e))})]}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:e.onDirectInstall,children:t("directInstall")}),"custom"===e.searchSource?(0,n.jsxs)("div",{className:"w-full space-y-1",children:[(0,n.jsx)("label",{htmlFor:"plugin-search-registry",className:"block text-sm",children:t("searchRegistryUrl")}),(0,n.jsx)(em.p,{id:"plugin-search-registry",type:"url",value:e.registry,onChange:t=>e.onRegistry(t.target.value),placeholder:"https://registry.example.com"})]}):null]}),e.error?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 text-sm text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:e.error}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:e.onRetry,children:t("retry")})]}):null,e.items.length?(0,n.jsx)("div",{className:"@container/catalog divide-y rounded-lg border bg-card",children:e.items.map(i=>{let a=r.get(i.name),l=tN(`npm:${i.name}`),o=a?.description??i.description,c=!!(a?.operation&&"failed"!==a.operation.phase),d=e.requests.has(l)||c||e.preparing.has(i.name),u=a&&(a.operation?.action!=="add"||"failed"!==a.operation.phase),m=e.installErrors[i.name]??e.errors[l]??(a?.error?(0,eJ.fD)(a.error.message,s):null);return(0,n.jsxs)("article",{"aria-label":i.name,className:"grid min-w-0 gap-x-4 gap-y-2 px-4 py-3 @xl/catalog:grid-cols-[minmax(0,1fr)_auto]",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(I.$,{variant:"link",className:"h-auto min-h-8 min-w-0 max-w-full p-0 text-left text-sm font-semibold whitespace-normal no-underline hover:underline [overflow-wrap:anywhere]",onClick:()=>e.onDetail(i),children:i.name}),(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",u&&a.version?a.version:i.version]}),u&&a.updateAvailable?(0,n.jsx)("span",{className:"rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:a.availableVersion?t("newVersion",{version:a.availableVersion}):t("updateAvailable")}):null,(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`kind_${i.kind}`)}),i.publisher?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:i.publisher}):null]}),(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:o?(0,eJ.fD)(o,s):t("noPluginDescription")})]}),(0,n.jsx)("div",{className:"flex min-h-8 items-center self-start @xl/catalog:justify-end",children:d?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:c?t(`phase_${a?.operation?.phase}`):e.preparing.has(i.name)?t("loadingPackage"):t("submitting")}):u?(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),a.updateAvailable?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onUpdate(a.source),children:t("update")}):null]}):(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onInstall(i),children:t("install")})}),m?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere] @xl/catalog:col-span-2",children:m}):null,a?.operation?.phase==="failed"&&a.operation.message?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere] @xl/catalog:col-span-2",children:a.operation.message}):null]},i.name)})}):null,e.loading?(0,n.jsx)("p",{role:"status",className:"py-4 text-sm text-muted-foreground",children:t("searching")}):e.error||!e.searched||e.items.length?null:(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:t("noSearchResults")}),e.hasMore?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onMore,children:t("loadMore")}):null]})}let tY=(0,e2.F)("flex w-fit items-stretch *:focus-visible:relative *:focus-visible:z-10 has-[>[data-slot=button-group]]:gap-2 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-lg [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1",{variants:{orientation:{horizontal:"*:data-slot:rounded-r-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-r-lg! [&>[data-slot]~[data-slot]]:rounded-l-none [&>[data-slot]~[data-slot]]:border-l-0",vertical:"flex-col *:data-slot:rounded-b-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-b-lg! [&>[data-slot]~[data-slot]]:rounded-t-none [&>[data-slot]~[data-slot]]:border-t-0"}},defaultVariants:{orientation:"horizontal"}});function tV({className:e,orientation:t,...s}){return(0,n.jsx)("div",{role:"group","data-slot":"button-group","data-orientation":t,className:(0,C.cn)(tY({orientation:t}),e),...s})}var tU=s(32892),tK=s(57445),tH=s(73028),tG=s(48318),tJ=s(93356),tQ=s(10508);let tX=({className:e,from:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("group flex w-full max-w-[95%] flex-col gap-2","user"===t?"is-user ml-auto justify-end":"is-assistant",e),...s}),tZ=({children:e,className:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("flex w-fit min-w-0 max-w-full flex-col gap-2 overflow-hidden text-base leading-[1.8]","group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground","group-[.is-assistant]:text-foreground",t),...s,children:e}),t0=({tooltip:e,children:t,label:s,variant:r="ghost",size:i="icon-sm",...a})=>{let l=(0,n.jsxs)(I.$,{size:i,type:"button",variant:r,...a,children:[t,(0,n.jsx)("span",{className:"sr-only",children:s||e})]});return e?(0,n.jsx)(tU.Bc,{children:(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:l}),(0,n.jsx)(tU.ZI,{children:(0,n.jsx)("p",{children:e})})]})}):l},t1={cjk:tK.h,code:tH.a,math:tG.D,mermaid:tJ.a},t2=(0,r.memo)(({className:e,...t})=>(0,n.jsx)(tQ.jH,{className:(0,C.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),plugins:t1,...t}),(e,t)=>e.children===t.children&&t.isAnimating===e.isAnimating);t2.displayName="MessageResponse";let t5=({className:e,children:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("mt-4 flex w-full items-center justify-between gap-4",e),...s,children:t});function t3({readme:e}){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),[i,a]=(0,r.useState)(null),l=e&&"string"!=typeof e?e.translations:{},o=Object.keys(l).filter(e=>/^(zh(?:-|$)|en(?:-|$))/.test(e)),c=i&&void 0!==l[i]?i:null,d=e?c?l[c]:(0,eJ.fD)(e,s):null;return(0,n.jsxs)("section",{className:"min-w-0 space-y-3","aria-label":t("readme"),children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:t("readme")}),o.length>0?(0,n.jsxs)("div",{className:"flex items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("readmeLanguage")}),(0,n.jsxs)(ea.l6,{value:c??"",onValueChange:e=>a(e||null),children:[(0,n.jsx)(ea.bq,{"aria-label":t("readmeLanguage"),children:(0,n.jsx)(ea.yv,{children:c?c.startsWith("zh")?"中文":"English":t("defaultLanguage")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"",children:t("defaultLanguage")}),o.map(e=>(0,n.jsx)(ea.eb,{value:e,children:e.startsWith("zh")?"中文":"English"},e))]})]})]}):null]}),d?(0,n.jsx)("div",{className:"min-w-0 overflow-x-auto text-base leading-relaxed [overflow-wrap:anywhere]",children:(0,n.jsx)(t2,{mode:"static",isAnimating:!1,skipHtml:!0,controls:!1,className:"min-w-0 [&_img]:max-w-full [&_pre]:overflow-x-auto",children:d})}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:t("noReadme")})]})}function t4({value:e,label:t,placeholder:s,disabled:r,onChange:i}){let{t:a}=(0,b.Bd)("pluginManagement"),l=[...s?[{value:"",label:s}]:[],{value:"latest",label:a("channelLatest")},{value:"dev",label:a("channelDev")},...e&&!["latest","dev"].includes(e)?[{value:e,label:e}]:[]];return(0,n.jsxs)(ea.l6,{value:e,items:l,onOpenChange:(e,t)=>{e&&r&&t.cancel()},onValueChange:e=>{null===e||r||i(e)},children:[(0,n.jsx)(ea.bq,{"aria-label":t,"aria-disabled":r,className:"max-w-full aria-disabled:opacity-50",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:l.map(e=>(0,n.jsx)(ea.eb,{value:e.value,disabled:r,children:e.label},e.value))})]})}function t6(e){if(!e)return null;try{let t=new URL(e);return["https:","http:"].includes(t.protocol)?t.href:null}catch{return null}}function t8(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=e.detail,i=e.installed&&e.installedVersion===r.version,a=t6(r.homepage),l=t6(r.repository),o=[...new Set([r.version,...r.versions])];return(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:["v",r.version]}),(0,n.jsx)("span",{children:t(`kind_${r.kind}`)}),r.publisher?(0,n.jsx)("span",{className:"[overflow-wrap:anywhere]",children:r.publisher}):null]}),r.description?(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:(0,eJ.fD)(r.description,s)}):null,!1===r.compatible?(0,n.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:[t("incompatible"),r.compatibilityNote?` \xb7 ${r.compatibilityNote}`:""]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[e.pending?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:e.operationMessage??t("submitting")}):i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),e.updateAvailable?(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled,onClick:e.onUpdate,children:t("update")}):null]}):(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||!1===r.compatible,onClick:e.onInstall,children:t(e.installed?"installVersion":"install")}),a?(0,n.jsx)("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"text-sm underline underline-offset-4",children:t("homepage")}):null,l?(0,n.jsx)("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"text-sm underline underline-offset-4",children:t("repository")}):null]}),e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.error}):null]}),(0,n.jsxs)(eV.Nt,{className:"rounded-lg border",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between px-3 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"space-y-3 px-3 pb-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(t4,{value:e.channel,label:t("installChannel"),placeholder:t("defaultChannel"),disabled:e.pending,onChange:e.onChannel}),(0,n.jsxs)(ea.l6,{value:r.version,items:o.map(e=>({value:e,label:e})),onOpenChange:(t,s)=>{t&&e.pending&&s.cancel()},onValueChange:t=>{t&&!e.pending&&e.onVersion(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("version"),"aria-disabled":e.pending,children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:o.map(t=>(0,n.jsx)(ea.eb,{value:t,disabled:e.pending,children:t},t))})]})]}),(0,n.jsx)(tO,{id:"plugin-detail-download",mode:e.downloadMode,registry:e.downloadRegistry,override:!0,saving:e.pending,onMode:e.onDownloadMode,onRegistry:e.onDownloadRegistry})]})})]}),(0,n.jsx)("div",{className:"border-t pt-4",children:(0,n.jsx)(t3,{readme:r.readme},`${r.name}@${r.version}`)})]})}var t7=s(68017);function t9(e){let{t}=(0,b.Bd)("pluginManagement");return(0,n.jsxs)("section",{"aria-label":t("directInstall"),className:"min-w-0 space-y-3 rounded-lg border bg-card p-4",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:t("directInstall")}),(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:e.onClose,children:t("close")})]}),(0,n.jsx)("label",{htmlFor:"plugin-direct-source",className:"block text-sm font-medium",children:t("source")}),(0,n.jsx)(t7.T,{id:"plugin-direct-source",value:e.source,placeholder:t("batchSourcePlaceholder"),rows:2,disabled:e.pending,onChange:t=>e.onSource(t.target.value)}),e.isNpm||e.multiple?(0,n.jsxs)(eV.Nt,{children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-8 items-center gap-2 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"space-y-3 pt-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(t4,{value:e.tag,label:t("installChannel"),placeholder:t("defaultChannel"),disabled:e.pending,onChange:e.onTag})]}),e.isNpm?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onRead,children:t(e.loading?"loadingPackage":"readPackage")}):null,e.detail?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.detail.name}),(0,n.jsxs)(ea.l6,{value:e.selectedVersion,onOpenChange:(t,s)=>{t&&(e.loading||e.pending)&&s.cancel()},items:[{value:"",label:t("automaticVersion")},...[...new Set([e.detail.version,...e.detail.versions])].map(e=>({value:e,label:e}))],onValueChange:t=>{null===t||e.loading||e.pending||e.onVersion(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("version"),"aria-disabled":e.loading||e.pending,className:"max-w-full",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"",disabled:e.loading||e.pending,children:t("automaticVersion")}),[...new Set([e.detail.version,...e.detail.versions])].map(t=>(0,n.jsx)(ea.eb,{value:t,disabled:e.loading||e.pending,children:t},t))]})]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t("targetVersion",{version:e.detail.version})})]}):null,(0,n.jsx)(tO,{id:"plugin-direct-download",mode:e.override,registry:e.registry,override:!0,saving:e.pending,onMode:e.onMode,onRegistry:e.onRegistry})]})})]}):null,e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm whitespace-pre-wrap text-destructive [overflow-wrap:anywhere]",children:e.error}):null,e.operationMessage?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operationMessage}):null,(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||e.loading||e.pending||!e.source.trim(),onClick:e.onInstall,children:t(e.pending?"installing":e.multiple?"batchInstall":"install")})]})}function se({confirmation:e,onClose:t,onConfirm:s}){let{t:r}=(0,b.Bd)("pluginManagement"),i=e?r(tI(e)):null,a=e?.kind==="del"||e?.kind==="batch"&&"del"===e.input.action,l=e?.kind==="add"||e?.kind==="batch"&&"add"===e.input.action;return(0,n.jsx)(eN.YV,{open:!!e,onOpenChange:e=>{e||t()},children:(0,n.jsxs)(eN.hA,{className:"z-[150] max-w-lg",backdropClassName:"z-[140]",children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:r("confirmAction",{action:i})}),(0,n.jsx)(eN.uX,{children:r(a?"removeDescription":l?"thirdPartyDescription":e?.kind==="reload"?"normal"===e.mode?"restartNormalDescription":"restartDescription":"confirmChange")})]}),(0,n.jsx)(eN._Y,{className:"min-h-0",children:(0,n.jsx)("div",{className:"min-w-0 p-4 pt-0",children:e?.kind==="batch"?(0,n.jsx)("ul",{className:"space-y-2 text-sm",children:("add"===e.input.action?e.input.items.map(e=>e.source):e.input.sources).map(e=>(0,n.jsx)("li",{className:"font-medium [overflow-wrap:anywhere]",children:e.startsWith("npm:")?tk(e)?.name??e:e},e))}):e?.kind==="add"?(0,n.jsxs)("dl",{className:"space-y-3 text-sm",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("packageName")}),(0,n.jsx)("dd",{className:"mt-1 font-medium [overflow-wrap:anywhere]",children:e.package?.name??e.input.source})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("version")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.package?.version??tk(e.input.source)?.version??r("fromSource")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("publisher")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.package?.publisher??r("unknownPublisher")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("source")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.input.registry??e.package?.registry??e.input.source})]})]}):e&&"reload"!==e.kind?(0,n.jsx)("p",{className:"text-sm font-medium [overflow-wrap:anywhere]",children:e.source.startsWith("npm:")?tk(e.source)?.name??e.source:e.source}):null})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:t,children:r("cancel")}),(0,n.jsx)(I.$,{size:"sm",variant:a?"destructive":"default",onClick:()=>{e&&s(e)},children:i})]})]})})}function st({basicMode:e=!1,snapshot:t,biz:s,onSnapshot:i,onRestartScheduled:a}){let{t:l}=(0,b.Bd)("pluginManagement"),{locale:o}=(0,eQ.i)(),[c,d]=(0,r.useState)("installed"),[u,m]=(0,r.useState)(""),[p,h]=(0,r.useState)("all"),[g,f]=(0,r.useState)(!1),[x,v]=(0,r.useState)(()=>new Set);(0,r.useEffect)(()=>{if(!t)return;let e=new Set(t.plugins.map(e=>tN(e.source)));[...x].some(t=>!e.has(t))&&queueMicrotask(()=>v(t=>new Set([...t].filter(t=>e.has(t)))))},[t,x]);let[w,y]=(0,r.useState)(""),[k,j]=(0,r.useState)(!1),N=function({basicMode:e=!1,biz:t,snapshot:s,onSnapshot:n,onRestartScheduled:i}){let{t:a}=(0,b.Bd)("pluginManagement"),l=(0,Q.t4)();(0,Q.So)();let[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(()=>new Set),m=(0,r.useRef)(new Set),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)({}),[x,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(null),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(null),S=(0,r.useRef)(0),C=(0,r.useRef)(0),E=(0,r.useRef)(!0),M=(e,t)=>{t?m.current.add(e):m.current.delete(e),E.current&&u(new Set(m.current))},z=(e,t)=>{E.current&&f(s=>{let n={...s};return t?n[e]=t:delete n[e],n})},A=e=>{let t=tN(e);return m.current.has(t)||!!s?.plugins.some(e=>tN(e.source)===t&&e.operation&&"failed"!==e.operation.phase)},$=async(e=!1)=>{let s=++C.current,r=await t.list(e);E.current&&s===C.current&&n(r)},R=async(e,t)=>{if(m.current.has("check"))return;let n=e??s?.plugins.filter(e=>"package"===e.kind&&(!t||e.updateTag===t)).map(e=>e.source)??[],r=n.filter(A),i=n.filter(e=>!A(e));if(r.forEach(e=>z(tN(e),a("sourceBusy"))),!i.length)return;let l=i.map(tN);M("check",!0),l.forEach(e=>M(e,!0)),c(!0),z("list",null);try{if(e||r.length)for(let e=0;e<i.length&&(await $({checkUpdates:!0,sources:i.slice(e,e+32),...t?{tag:t}:{}}),E.current);e+=32);else await $({checkUpdates:!0,...t?{tag:t}:{}})}catch(e){z("list",e instanceof Error?e.message:a("updateCheckFailed"))}finally{M("check",!1),l.forEach(e=>M(e,!1)),E.current&&c(!1)}};(0,r.useEffect)(()=>{E.current=!0;let s=!0,r=++C.current;return queueMicrotask(()=>{s&&(c(!0),t.list(!1).then(async i=>{if(!s||r!==C.current)return;n(i);let a=i.plugins.some(e=>"package"===e.kind&&/^(npm:|git:|https?:|git@)/.test(e.source)&&null===e.updateAvailable&&!e.updateError&&!e.operation);if(!e&&a){let e=await t.list(!0);s&&r===C.current&&n(e)}}).catch(e=>{s&&z("list",e instanceof Error?e.message:a("updateCheckFailed"))}).finally(()=>{s&&c(!1)}))}),()=>{s=!1,E.current=!1,S.current+=1,C.current+=1}},[t,n,a,e]);let P=async e=>{let s="add"===e.action?e.items.map(e=>e.source):e.sources,r=s.filter(e=>!A(e));if(s.filter(A).forEach(e=>z(tN(e),a("sourceBusy"))),!r.length)return;let i=r.map(tN);i.forEach(e=>{M(e,!0),z(e,null)}),h(null);let l=[...r];try{let s=await t.list(),r=Date.now()+9e5;for(;l.length;){let i=s.plugins.filter(e=>e.operation&&"failed"!==e.operation.phase),o="tag"===e.action?32:Math.max(0,32-i.length);if(!o){if(i.some(e=>e.operation?.phase==="waiting")||Date.now()>=r){l.forEach(e=>z(tN(e),a("batchWaiting")));break}await new Promise(e=>setTimeout(e,750)),s=await t.list(),E.current&&(C.current+=1,n(s));continue}let c=l.slice(0,o),d="add"===e.action?{...e,items:e.items.filter(e=>c.includes(e.source))}:{...e,sources:c},u=await t.batch(d);s=u.snapshot,E.current&&(C.current+=1,n(s)),u.results.forEach(e=>z(tN(e.source),e.error)),c.forEach(e=>M(tN(e),!1)),l=l.slice(c.length)}}catch(t){let e=t instanceof Error?t.message:a("batchFailed");l.forEach(t=>z(tN(t),e))}finally{i.forEach(e=>M(e,!1))}},D=async e=>{if("batch"===e.kind)return void await P(e.input);if("reload"!==e.kind&&A("add"===e.kind?e.input.source:e.source))return;let s="reload"===e.kind?"reload":tN("add"===e.kind?e.input.source:e.source);if(!m.current.has(s)){M(s,!0),h(null),z(s,null);try{let s="add"===e.kind?await t.add(e.input):"update"===e.kind?await t.update(e.source):"del"===e.kind?await t.del(e.source):"enable"===e.kind||"disable"===e.kind?await t.setEnabled(e.source,"enable"===e.kind):await t.reload(e.mode);if(!E.current)return;C.current+=1,n(s),"reload"===e.kind?i():await $()}catch(t){z(s,t instanceof Error?t.message:a("actionFailed",{action:a(tI(e))}))}finally{M(s,!1)}}},T=(e,t)=>{let s={kind:"add",input:e,package:t};t?.official===!0?D(s):h(s)},O=async e=>{let s=e?.[0]?tN(e[0]):"apply";if(!m.current.has(s)){M(s,!0),z(s,null);try{let s=await t.apply(e);E.current&&(C.current+=1,n(s),await $())}catch(e){z(s,e instanceof Error?e.message:a("actionFailed",{action:a("reloadOne")}))}finally{M(s,!1)}}},L=async(e,t)=>{if(!m.current.has(e)){M(e,!0),z(e,null);try{await t()}catch(t){z(e,t instanceof Error?t.message:a("retryFailed"))}finally{M(e,!1)}}},F=async e=>{let s=++S.current;j(!0),I(null);try{let n=await t.get(e);E.current&&s===S.current&&y(n)}catch(e){E.current&&s===S.current&&I(e instanceof Error?e.message:a("detailFailed"))}finally{E.current&&s===S.current&&j(!1)}};return{loading:o,requests:d,confirmation:p,setConfirmation:h,errors:g,detailSource:x,detail:w,detailLoading:k,detailError:N,pluginHost:l,refresh:R,executeBatch:P,execute:D,requestInstall:T,applyChanges:O,loadDetail:F,openDetail:e=>{v(e),y(null),F(e)},closeDetail:()=>{S.current+=1,v(null),y(null),I(null),j(!1)},handleControlAction:(e,t)=>{switch(t){case"reload":O([e.source]);break;case"update":D({kind:"update",source:e.source});break;case"remove":h({kind:"del",source:e.source});break;case"enable":case"disable":D({kind:t,source:e.source});break;case"retry-browser":e.pluginName&&L(`entry:${e.pluginName}`,()=>l.retryEntry(e.pluginName));break;case"retry":{let t=e.operation?.action;"apply"===t?O([e.source]):"add"===t?T({source:e.source}):t&&D({kind:t,source:e.source})}}},refreshEntries:()=>L("entries",()=>l.refreshEntries())}}({biz:s,snapshot:t,onSnapshot:i,onRestartScheduled:a,basicMode:e}),S=function(e,t){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(""),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)("all"),[d,u]=(0,r.useState)("public"),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)([]),[f,x]=(0,r.useState)(!1),[v,w]=(0,r.useState)(1),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(null),[I,S]=(0,r.useState)(!1),[C,E]=(0,r.useState)(null),[M,z]=(0,r.useState)(null),[A,$]=(0,r.useState)(!1),[R,P]=(0,r.useState)(null),[D,T]=(0,r.useState)(()=>new Set),[O,L]=(0,r.useState)({}),F=(0,r.useRef)(0),B=(0,r.useRef)(0),q=(0,r.useRef)(new Set),_=(0,r.useRef)(null),[W,Y]=(0,r.useState)(!1),[V,U]=(0,r.useState)("default"),[K,H]=(0,r.useState)(""),G=(0,r.useRef)(!0);(0,r.useEffect)(()=>(G.current=!0,()=>{G.current=!1,F.current+=1,B.current+=1}),[]);let J=(0,r.useCallback)(async(t,n)=>{k(!0),N(null);try{let s=await e.searchCatalog(t);if(!G.current||n!==F.current)return;g(e=>{let n=1===t.page?s.items:[...e,...s.items],r=e=>e.official?0:"desk"===e.kind?1:"pi"===e.kind?2:3;return[...new Map(n.map(e=>[e.name,e])).values()].sort((e,t)=>r(e)-r(t))}),w(t.page),x(s.hasMore),S(!0)}catch(e){G.current&&n===F.current&&N(e instanceof Error?e.message:s("searchFailed"))}finally{G.current&&n===F.current&&k(!1)}},[e,s]);(0,r.useEffect)(()=>{t&&queueMicrotask(()=>Y(!0))},[t]),(0,r.useEffect)(()=>{if(!W||a)return;let e=++F.current;_.current=null,queueMicrotask(()=>{G.current&&e===F.current&&(k(!0),N(null),x(!1))});let t=setTimeout(()=>{let t="custom"===d?tC.safeParse(m):null;if(t&&!t.success){_.current=null,g([]),x(!1),S(!1),N(s("invalidRegistry")),k(!1);return}let r={query:n.trim(),kind:o,page:1,...t?.success?{registry:t.data}:{}};_.current=r,g([]),x(!1),S(!1),J(r,e)},300);return()=>clearTimeout(t)},[n,o,d,m,a,J,W,s]);let Q=async(t,n=t.version)=>{let r=++B.current;$(!0),P(null),L(e=>{let s={...e};return delete s[t.name],s});try{let s=await e.getCatalog({name:t.name,registry:t.registry,version:n});G.current&&r===B.current&&z(s)}catch(e){G.current&&r===B.current&&P(e instanceof Error?e.message:s("detailFailed"))}finally{G.current&&r===B.current&&$(!1)}};return{query:n,setQuery:i,composing:a,beginComposition:()=>{F.current+=1,_.current=null,k(!1),l(!0)},endComposition:()=>l(!1),kind:o,setKind:c,searchSource:d,setSearchSource:u,registry:m,setRegistry:p,items:h,loading:y,error:j,searched:I,hasMore:f,loadMore:()=>{_.current&&!y&&f&&J({..._.current,page:v+1},F.current)},retry:()=>{if(a||y)return;let e="custom"===d?tC.safeParse(m):null;if(e&&!e.success)return void N(s("invalidRegistry"));let t={query:n.trim(),kind:o,page:1,...e?.success?{registry:e.data}:{}};_.current=t,g([]),J(t,++F.current)},selection:C,detail:M,detailLoading:A,detailError:R,openDetail:e=>{E(e),z(null),U("default"),H(""),Q(e)},closeDetail:()=>{B.current+=1,E(null),z(null),$(!1),P(null)},loadDetail:Q,prepareInstall:async(t,n)=>{if(!q.current.has(t.name)){q.current.add(t.name),T(new Set(q.current)),L(e=>{let s={...e};return delete s[t.name],s});try{let r=await e.getCatalog({name:t.name,version:t.version,registry:t.registry});if(!G.current)return;if(!1===r.compatible)return void L(e=>({...e,[t.name]:s("installIncompatible")}));n(r)}catch(e){G.current&&L(n=>({...n,[t.name]:e instanceof Error?e.message:s("detailFailed")}))}finally{q.current.delete(t.name),G.current&&T(new Set(q.current))}}},preparing:D,installErrors:O,downloadMode:V,setDownloadMode:U,downloadRegistry:K,setDownloadRegistry:H,installDetail:e=>{if(!M||A)return;if(!1===M.compatible)return void L(e=>({...e,[M.name]:s("installIncompatible")}));let t="default"===V?null:tE.safeParse("custom"===V?{mode:V,registry:K}:{mode:V});t&&!t.success?L(e=>({...e,[M.name]:s("invalidRegistry")})):(L(e=>{let t={...e};return delete t[M.name],t}),e({source:`npm:${M.name}@${M.version}`,registry:M.registry,...t?.success?{downloadSource:t.data}:{}},M))}}}(s,"search"===c),C=function(e,t){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(null),[a,l]=(0,r.useState)("auto"),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(!1),[h,g]=(0,r.useState)(null),f=(0,r.useRef)(!0),x=(0,r.useRef)(!1),v=(0,r.useRef)(0),w=(0,r.useRef)("load"),y=async()=>{let t=v.current;u(!0),g(null);try{let s=await e.getCatalogSettings();if(!f.current)return;t===v.current?(i(s),l(s.downloadSource.mode),"custom"===s.downloadSource.mode&&c(s.downloadSource.registry)):i(e=>e??s)}catch(e){w.current="load",f.current&&g(e instanceof Error?e.message:s("settingsFailed"))}finally{f.current&&u(!1)}};(0,r.useEffect)(()=>{f.current=!0;let e=!0;return queueMicrotask(()=>{e&&y()}),()=>{e=!1,f.current=!1}},[e]);let k=async(n=a)=>{if(x.current)return;let r=tE.safeParse("custom"===n?{mode:n,registry:o}:{mode:n});if(!r.success){w.current="save",g(s("invalidRegistry"));return}x.current=!0,p(!0),g(null);try{let s=await e.saveCatalogSettings(r.data);f.current&&(i(s),l(s.downloadSource.mode),t())}catch(e){w.current="save",f.current&&g(e instanceof Error?e.message:s("settingsFailed"))}finally{x.current=!1,f.current&&p(!1)}};return{settings:n,mode:a,registry:o,setRegistry:e=>{v.current+=1,c(e)},loading:d,saving:m,error:h,load:y,save:k,changeMode:e=>{v.current+=1,l(e),"custom"!==e&&k(e)},retry:()=>"save"===w.current?k():y()}}(s,()=>{e||N.refresh()}),E=function(e,t=[]){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(""),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(null),[v,w]=(0,r.useState)("default"),[y,k]=(0,r.useState)(""),j=(0,r.useRef)(0),N=(0,r.useRef)(!0),I=a.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),S=1===I.length?tk(I[0]):null;(0,r.useEffect)(()=>(N.current=!0,()=>{N.current=!1,j.current+=1}),[]);let C=()=>{j.current+=1,p(null),g(!1),x(null)},E=async n=>{let r;if(!S)return null;void 0!==n&&u(n||null);let i=t.find(e=>tk(e.source)?.name===S.name)?.updateTag,a=S.version??(o||i||"latest"),l=""===n?a:n??d??a;if("custom"===v){let e=tC.safeParse(y);if(!e.success)return x(s("invalidRegistry")),null;r=e.data}else"official"===v?r="https://registry.npmjs.org":"domestic"===v&&(r="https://registry.npmmirror.com");let c=++j.current;g(!0),p(null),x(null);try{let t=await e.getCatalog({...S,...l?{version:l}:{},...r?{registry:r}:{}});if(!N.current||c!==j.current)return null;return p(t),t}catch(e){return N.current&&c===j.current&&x(e instanceof Error?e.message:s("detailFailed")),null}finally{N.current&&c===j.current&&g(!1)}},M=async(e,t)=>{if(!I.length||h)return;x(null);let n="default"===v?null:tE.safeParse("custom"===v?{mode:v,registry:y}:{mode:v});if(n&&!n.success)return void x(s("invalidRegistry"));let r={...o?{tag:o}:{},...n?.success?{downloadSource:n.data}:{}};if(I.length>1){let e=I.map(tk);if(I.length>32||e.some(e=>!e))return void x(s(I.length>32?"batchLimit":"batchNpmOnly"));let n=new Map;return e.forEach(e=>{e&&n.set(e.name,{source:`npm:${e.name}${e.version?`@${e.version}`:""}`,...r})}),void t([...n.values()])}if(!S)return void e({source:I[0]});let i=m?Promise.resolve(m):E(d??void 0),a=j.current,l=await i;if(l&&N.current&&a===j.current){if(!1===l.compatible)return void x(s("installIncompatible"));e({source:`npm:${l.name}${d||S.version?`@${d??S.version}`:""}`,registry:l.registry,...r},l)}};return{open:n,setOpen:i,source:a,sources:I,tag:o,selectedVersion:d??"",setTag:e=>{C(),u(null),c(e)},changeSource:e=>{C(),u(null),l(e)},spec:S,detail:m,loading:h,error:f,override:v,setOverride:e=>{C(),w(e)},registry:y,setRegistry:e=>{C(),k(e)},loadDetail:E,install:M}}(s,t?.plugins),M=e||N.requests.has("reload"),z=new Map(N.pluginHost.getFailedEntries().map(e=>[e.pluginName,e.error.message])),$=N.pluginHost.getEntryListError(),R=t?.plugins.find(e=>e.source===N.detailSource),P=S.selection?t?.plugins.find(e=>e.source.startsWith("npm:")&&tk(e.source)?.name===S.selection?.name):void 0,D=S.selection?tN(`npm:${S.selection.name}`):"",T=tN(E.detail?`npm:${E.detail.name}`:E.spec?`npm:${E.spec.name}`:E.source.trim()),O=t?.plugins.find(e=>tN(e.source)===T),L=e=>{let s=t?.plugins.find(t=>tN(t.source)===tN(e));return N.requests.has(tN(e))||!!(s?.operation&&"failed"!==s.operation.phase)},F=L(`npm:${S.selection?.name??""}`),B=E.sources.some(L),q=E.sources.map(e=>{let s=tN(e),n=t?.plugins.find(e=>tN(e.source)===s),r=N.errors[s]??(n?.operation?.phase==="failed"?n.operation.message:null);return r?`${e}: ${r}`:null}).filter(Boolean).join("\n"),_=!!(N.detailSource||S.selection),W=(0,r.useRef)(null),Y=(0,r.useRef)(null);(0,r.useEffect)(()=>{_?W.current?.focus():Y.current?.isConnected&&(Y.current.focus(),Y.current=null)},[_]);let V=()=>{Y.current=document.activeElement instanceof HTMLElement?document.activeElement:null},U=e=>{let s=t?.plugins.find(t=>tk(t.source)?.name===e.name);return{...e,version:s?.updateTag??"latest"}},K=e=>t?.plugins.filter(t=>"extension"!==t.kind&&!0===t.updateAvailable&&!L(t.source)&&(!e||x.has(tN(t.source)))).map(e=>e.source)??[],H=e=>e?l(`phase_${e}`):null,G=()=>{d("installed"),E.setOpen(!0)};return(0,n.jsxs)("div",{className:"flex h-full min-h-0 min-w-0 flex-col",children:[(0,n.jsxs)("header",{className:"shrink-0 space-y-3 border-b p-4 sm:px-6",children:[_?(0,n.jsxs)(I.$,{ref:W,size:"sm",variant:"ghost",className:"-ml-2",onClick:()=>{N.closeDetail(),S.closeDetail()},children:[(0,n.jsx)(A.A,{}),l("backToList")]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h2",{className:"min-w-0 text-xl font-semibold [overflow-wrap:anywhere]",children:_?R?tj(R):S.selection?.name??l("details"):l("title")}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[_?null:(0,n.jsxs)(eW.AM,{children:[(0,n.jsxs)(eW.Wv,{render:(0,n.jsx)(I.$,{size:"sm",variant:"ghost"}),children:[l("downloadSource"),":",C.loading&&!C.settings?l("loading"):l(`download_${C.settings?.downloadSource.mode??C.mode}`),(0,n.jsx)(eY.A,{className:"size-4"})]}),(0,n.jsx)(eW.hl,{align:"end",positionerClassName:"z-[150]",className:"w-80 max-w-[calc(100vw-2rem)]",children:(0,n.jsx)(tO,{id:"plugin-default-download",mode:C.mode,registry:C.registry,savedRegistry:C.settings?.downloadSource.mode==="custom"?C.settings.downloadSource.registry:void 0,recommendedRegistry:C.settings?.recommendedRegistry,loading:C.loading,saving:C.saving,error:C.error,onMode:e=>{"default"!==e&&C.changeMode(e)},onRegistry:C.setRegistry,onSave:()=>void C.save(),onRetry:()=>void C.retry()})})]}),e||t?.restartRequired?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:N.requests.has("reload"),onClick:()=>N.setConfirmation({kind:"reload",mode:e?"normal":void 0}),children:l(e?"restartNormal":"restartApply")}):null]})]}),e?(0,n.jsx)("p",{role:"status",className:"rounded-lg bg-muted p-3 text-sm",children:l("basicModeNotice")}):null,t?.restartRequired?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("pendingRestart")}):null,t?.loadError||$?(0,n.jsxs)("div",{role:"alert",className:"max-h-32 space-y-1 overflow-y-auto text-sm text-destructive",children:[t?.loadError?(0,n.jsx)("p",{className:"[overflow-wrap:anywhere]",children:(0,eJ.fD)(t.loadError,o)}):null,$?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"min-w-0 [overflow-wrap:anywhere]",children:$}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:N.requests.has("entries"),onClick:()=>void N.refreshEntries(),children:l("retry")})]}):null]}):null,N.errors.reload||N.errors.entries?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:N.errors.reload??N.errors.entries}):null]}),(0,n.jsxs)(e5,{value:c,onValueChange:e=>d(String(e)),className:`min-h-0 flex-1 gap-0 ${_?"hidden":""}`,children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 pt-2 sm:px-6",children:(0,n.jsxs)(e4,{variant:"line","aria-label":l("title"),className:"h-9",children:[(0,n.jsxs)(e6,{value:"installed",className:"px-3",children:[l("installedTab"),t?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t.plugins.length}):null]}),(0,n.jsx)(e6,{value:"search",className:"px-3",children:l("searchPlugins")})]})}),(0,n.jsx)(e8,{value:"installed",keepMounted:!0,className:"flex min-h-0 flex-col overflow-hidden p-4 data-[hidden]:hidden sm:p-6",children:(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[E.open?(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar max-h-1/2 shrink-0 overflow-y-auto",children:(0,n.jsx)(t9,{source:E.source,isNpm:!!E.spec,multiple:E.sources.length>1,tag:E.tag,selectedVersion:E.selectedVersion,onTag:E.setTag,detail:E.detail,loading:E.loading,pending:B,disabled:M,error:E.error??(q||null),operationMessage:B?H(O?.operation?.phase)??l("submitting"):null,override:E.override,registry:E.registry,onSource:E.changeSource,onMode:E.setOverride,onRegistry:E.setRegistry,onRead:()=>void E.loadDetail(),onVersion:e=>void E.loadDetail(e),onInstall:()=>void E.install(N.requestInstall,e=>N.setConfirmation({kind:"batch",input:{action:"add",items:e}})),onClose:()=>E.setOpen(!1)})}):null,(0,n.jsx)(t_,{snapshot:t,loading:N.loading,filter:u,statusFilter:p,batchMode:g,selected:x,onStatusFilter:h,onBatchMode:e=>{f(e),e||v(new Set)},onSelect:(e,t)=>{v(s=>{let n=new Set(s);return e.forEach(e=>{t?n.add(e):n.delete(e)}),n})},onUpdateAll:()=>void N.executeBatch({action:"update",sources:K(!1)}),onUpdateSelected:()=>void N.executeBatch({action:"update",sources:K(!0)}),onRemoveSelected:()=>N.setConfirmation({kind:"batch",input:{action:"del",sources:t?.plugins.filter(e=>x.has(tN(e.source))&&!L(e.source)).map(e=>e.source)??[]}}),disabled:M,requests:N.requests,errors:N.errors,browserErrors:z,onFilter:m,onDetail:e=>{V(),S.closeDetail(),N.openDetail(e)},onAction:N.handleControlAction,onRefresh:()=>void N.refresh()}),t?.plugins.length||E.open?null:(0,n.jsx)(I.$,{size:"sm",variant:"outline",className:"shrink-0 self-start",disabled:M,onClick:G,children:l("directInstall")})]})}),(0,n.jsx)(e8,{value:"search",keepMounted:!0,className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto p-4 data-[hidden]:hidden sm:p-6",children:(0,n.jsx)(tW,{query:S.query,kind:S.kind,searchSource:S.searchSource,registry:S.registry,items:S.items,loading:S.loading,error:S.error,searched:S.searched,hasMore:S.hasMore,disabled:M,snapshot:t,requests:N.requests,preparing:S.preparing,errors:N.errors,installErrors:S.installErrors,onQuery:S.setQuery,onCompositionStart:S.beginComposition,onCompositionEnd:S.endComposition,onKind:S.setKind,onSearchSource:e=>{S.setSearchSource(e),"custom"!==e||S.registry||C.settings?.downloadSource.mode!=="custom"||S.setRegistry(C.settings.downloadSource.registry)},onRegistry:S.setRegistry,onDetail:e=>{V(),N.closeDetail(),y(""),j(!1),S.openDetail(U(e))},onInstall:e=>{S.prepareInstall(U(e),e=>N.requestInstall({source:`npm:${e.name}`,registry:e.registry},e))},onUpdate:e=>void N.execute({kind:"update",source:e}),onMore:S.loadMore,onRetry:S.retry,onDirectInstall:G})})]}),_?(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:R?(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[R.version?(0,n.jsxs)("span",{children:["v",R.version]}):null,R.updateAvailable?(0,n.jsx)("span",{className:"rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:R.availableVersion?l("newVersion",{version:R.availableVersion}):l("updateAvailable")}):null]}),(0,n.jsx)(tw,{plugin:R,displayName:tj(R),browserError:R.pluginName?z.get(R.pluginName)??null:null,disabled:M,pending:L(R.source),browserRetryPending:N.requests.has(`entry:${R.pluginName}`),onAction:e=>N.handleControlAction(R,e)})]}),R.description?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:(0,eJ.fD)(R.description,o)}):null,(0,n.jsx)(ty,{plugin:R,requestError:N.errors[tN(R.source)],browserError:R.pluginName?z.get(R.pluginName)??null:null})]}),(0,n.jsxs)(eV.Nt,{className:"rounded-lg border",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between px-3 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 px-3 pb-3",children:[R.source.startsWith("npm:")?(0,n.jsx)(t4,{value:R.updateTag??"latest",label:l("installChannel"),disabled:M||L(R.source),onChange:e=>void N.executeBatch({action:"tag",sources:[R.source],tag:e})}):null,(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:M||L(R.source)&&R.operation?.phase!=="waiting",onClick:()=>N.handleControlAction(R,"reload"),children:l("reloadOne")})]})})]}),N.detailLoading?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("loadingPackage")}):null,N.detail?.readme?(0,n.jsx)(t3,{readme:N.detail.readme},R.source):null,(0,n.jsxs)(eV.Nt,{className:"border-t pt-2",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l("capabilityDetails"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsx)(tf,{plugin:R,detail:N.detail,detailLoading:N.detailLoading,detailError:N.detailError,browserContributions:R.pluginName?N.pluginHost.getRegisteredBrowserDescriptors().find(e=>e.pluginName===R.pluginName)?.contributions??[]:[],onRetry:()=>void N.loadDetail(R.source)})})]}),N.detailError?(0,n.jsxs)("div",{role:"alert",className:"flex items-center gap-2 text-sm text-destructive",children:[(0,n.jsx)("span",{children:N.detailError}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:()=>void N.loadDetail(R.source),children:l("retry")})]}):null]}):S.selection?(0,n.jsxs)(n.Fragment,{children:[S.detailLoading?(0,n.jsx)("p",{role:"status",className:"mb-3 text-sm text-muted-foreground",children:l("loadingPackage")}):null,S.detailError?(0,n.jsxs)("div",{role:"alert",className:"mb-3 space-y-2 text-sm",children:[(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:S.detailError}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:()=>void S.loadDetail(S.selection),children:l("retry")})]}):null,S.detail?(0,n.jsx)(t8,{detail:S.detail,disabled:M||!!S.detailError,pending:F||S.detailLoading,installed:!!(P&&(P.operation?.action!=="add"||"failed"!==P.operation.phase)),installedVersion:P?.version??null,updateAvailable:!!P?.updateAvailable,error:S.installErrors[S.detail.name]??N.errors[D]??(P?.operation?.phase==="failed"?P.operation.message:null),operationMessage:S.detailLoading?l("loadingPackage"):H(P?.operation?.phase),channel:w,onChannel:e=>{y(e),j(!1),S.loadDetail(S.selection,e||P?.updateTag||"latest")},downloadMode:S.downloadMode,downloadRegistry:S.downloadRegistry,onDownloadMode:S.setDownloadMode,onDownloadRegistry:S.setDownloadRegistry,onVersion:e=>{j(!0),S.loadDetail(S.selection,e)},onInstall:()=>S.installDetail((e,t)=>N.requestInstall({...e,source:k?e.source:`npm:${t.name}`,...w?{tag:w}:{}},t)),onUpdate:()=>{P&&N.execute({kind:"update",source:P.source})}}):null]}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:l("pluginRemoved")})}):null,(0,n.jsx)(se,{confirmation:N.confirmation,onClose:()=>N.setConfirmation(null),onConfirm:e=>void N.execute(e)})]})}var ss=s(99739);let sn=a.Yj().trim().min(1).max(2048),sr=a.YO(sn).min(1).max(32),si=a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:eJ.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0)}).strict(),sa=a.Yj().trim().min(1).max(4096),sl=a.Yj().trim().min(1).max(256),so=a.Yj().max(32768),sc=a.Ik({name:sl,label:so,state:a.k5(["active","inactive","shadowed"]),description:so,promptSnippet:so.nullable(),promptGuidelineCount:a.ai().int().nonnegative(),promptGuidelinePreview:so.nullable()}).strict(),sd=a.Ik({name:sl,label:so,state:a.k5(["active","inactive","shadowed"]),description:so,parameters:ss.Dz,promptSnippet:so.nullable(),promptGuidelines:a.YO(so)}).strict(),su=a.Ik({path:sa,events:a.YO(a.Ik({name:sl,count:a.ai().int().positive()}).strict()),commands:a.YO(a.Ik({name:sl,description:so.nullable()}).strict()),shortcuts:a.YO(a.Ik({shortcut:sl,description:so.nullable()}).strict()),flags:a.YO(a.Ik({name:sl,type:a.k5(["boolean","string"]),description:so.nullable(),default:a.KC([a.zM(),a.Yj(),a.ch()])}).strict()),messageRenderers:a.YO(sl),entryRenderers:a.YO(sl)}).strict(),sm=a.Ik({name:sl,description:so,path:sa}).strict(),sp=sm.extend({modelVisible:a.zM()}).strict(),sh=sm.extend({content:a.Yj().max(65536),truncated:a.zM()}).strict(),sg=sh.extend({modelVisible:a.zM()}).strict(),sf=a.Ik({name:sl,path:sa}).strict(),sx=a.Ik({name:sl,kind:a.k5(["config","native"])}).strict(),sb=a.Ik({methods:a.YO(a.Ik({pluginName:sl,method:sl}).strict()),browserEntries:a.YO(a.Ik({pluginName:sl}).strict()),messageDeclarations:a.YO(a.Ik({pluginName:sl,declarationName:sl,priority:a.ai().int().safe()}).strict())}).strict(),sv=a.Ik({error:eJ.qf.refine(e=>"string"==typeof e?e.length<=32768:[e.default,...Object.values(e.translations)].every(e=>e.length<=32768)).nullable(),extensions:a.YO(su),tools:a.YO(sc),skills:a.YO(sp),prompts:a.YO(sm),themes:a.YO(sf),providers:a.YO(sx),piDesk:sb}).strict(),sw=a.Ik({action:a.k5(["add","update","del","apply","enable","disable"]),phase:a.k5(["queued","checking","applying","waiting","failed"]),message:a.Yj().max(4e3).nullable()}).strict(),sy=(0,l._G)({path:"plugins/management-update",bodySchema:a.Ik({}).strict()}),sk=a.Ik({source:sn,kind:a.k5(["package","extension"]).default("package"),operation:sw.nullable().default(null),pluginName:a.Yj().trim().min(1).nullable(),description:eJ.qf.nullable().default(null),version:a.Yj().trim().min(1).nullable(),updateAvailable:a.zM().nullable(),updateTag:tS.nullable().optional(),availableVersion:a.Yj().min(1).nullable().optional(),updateError:a.Yj().max(4e3).nullable().optional(),status:a.k5(["ready","available","disabled","failed"]),error:si.nullable(),capabilities:sv}).strict(),sj=a.Ik({source:sn,readme:eJ.qf.nullable().default(null),tools:a.YO(sd),skills:a.YO(sg),prompts:a.YO(sh)}).strict(),sN=a.Ik({plugins:a.YO(sk),restartRequired:a.zM(),loadError:eJ.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0).nullable()}).strict(),sI=a.Ik({sources:a.YO(sn).min(1).max(32).optional()}).strict(),sS=a.Ik({}).strict().extend({mode:a.k5(["normal","basic"]).optional()}).strict(),sC=a.Ik({checkUpdates:a.zM().optional(),sources:sr.optional(),tag:tS.optional()}).strict(),sE=a.Ik({source:sn}).strict(),sM=sE.extend({downloadSource:tE.optional(),registry:tC.optional(),tag:tS.optional()}).strict(),sz=a.gM("action",[a.Ik({action:a.eu("add"),items:a.YO(sM).min(1).max(32)}).strict(),a.Ik({action:a.eu("update"),sources:sr}).strict(),a.Ik({action:a.eu("del"),sources:sr}).strict(),a.Ik({action:a.eu("tag"),sources:sr,tag:tS}).strict()]),sA=a.Ik({snapshot:sN,results:a.YO(a.Ik({source:sn,error:a.Yj().max(4e3).nullable()}).strict()).max(32)}).strict(),s$=sE.extend({enabled:a.zM()}).strict();async function sR(e,t,s,n){return eu(e,t,s,n,{fallbackMessage:"插件管理请求失败"})}function sP({pluginName:e,descriptor:t,source:s,cwd:r,onPreviewFile:i,onRevealFile:a,onHeaderActionsChange:l}){let o=`${s.workId}\u0000${s.sessionId}\u0000${s.branchId}\u0000${r}`;return(0,n.jsx)(eK,{pluginName:e,kind:"session-sidebar-tab",contributionName:t.contributionName,target:{kind:"session-sidebar-tab",source:s,cwd:r,files:{preview:i,reveal:a},setHeaderActions:l},targetKey:o,layout:"fill"})}function sD({pluginName:e,descriptor:t,onClose:s,onBeforeLeaveChange:i}){let a=(0,Q.t4)();(0,Q.So)();let l=a.getEntryState(e),o="ready"===l.status?l.runtime:l.status;(0,r.useEffect)(()=>()=>{i(null)},[o,i]);let c=(0,r.useMemo)(()=>({kind:"settings-page",close:()=>{a.getEntryState(e)===l&&s()},setBeforeLeave:t=>{a.getEntryState(e)===l&&i(t)}}),[l,i,s,e,a]);return(0,n.jsx)(eK,{pluginName:e,kind:"settings-page",contributionName:t.contributionName,target:c,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})}function sT({source:e,placement:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,Q.So)(),a=(0,r.useMemo)(()=>({kind:"widget",source:e}),[e]),l=JSON.stringify([e.workId,e.sessionId,e.branchId]),o=i.flatMap(e=>e.contributions.flatMap(s=>"widget"===s.kind&&s.placement===t?[{pluginName:e.pluginName,descriptor:s}]:[]));return 0===o.length?null:(0,n.jsx)("div",{"data-testid":`plugin-widgets-${t}`,"aria-label":s("composer"),className:"min-w-0 w-full",children:o.map(({pluginName:e,descriptor:t})=>(0,n.jsx)(eK,{pluginName:e,kind:"widget",contributionName:t.contributionName,target:a,targetKey:l,layout:"inline"},`${e}:${t.contributionName}:${l}`))})}function sO({pluginName:e,contributionName:t,presentation:s,source:i,icon:a,label:l,onSelected:o}){let c=(0,Q.t4)();(0,Q.So)();let d=c.getEntryState(e),u=(0,X.G)(),{t:m}=(0,b.Bd)("workbench"),p=(0,r.useRef)(null),h=(0,r.useRef)(!1),[g,f]=(0,r.useState)(!1);(0,r.useLayoutEffect)(()=>{let e=new AbortController;return p.current=e,h.current=!1,queueMicrotask(()=>{e.signal.aborted||f(!1)}),()=>{e.abort(),p.current===e&&(p.current=null)}},[d,s,i]);let x=async()=>{let n=p.current;if(!n||n.signal.aborted||h.current)return;let r=()=>!n.signal.aborted&&c.getEntryState(e)===d;h.current=!0,f(!0);try{await c.invokeSessionHeaderAction({pluginName:e,contributionName:t,presentation:s,source:i,signal:n.signal}),r()&&o?.()}catch(a){if(!r())return;let n=a instanceof Error?a.message:m("operationFailed");console.error("[Pi Desk][PluginHost] 会话标题操作失败",{pluginName:e,contributionName:t,presentation:s,source:i,message:n}),u.error(n)}finally{r()&&(h.current=!1,f(!1))}};return(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm","aria-label":l,"aria-busy":g,disabled:g,"data-testid":"plugin-session-header-action","data-plugin-name":e,"data-contribution-name":t,"data-presentation":s,className:(0,C.cn)("overflow"===s&&"w-full justify-start whitespace-normal text-left"),onClick:()=>void x(),children:[(0,n.jsx)(eq,{icon:a,className:"size-4"}),(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:l})]})}function sL(e){return`${e.pluginName}:${e.descriptor.contributionName}`}function sF({item:e,source:t,presentation:s,onSelected:i,onContentChange:a}){let l=e.descriptor[s],o=(0,r.useMemo)(()=>({kind:"session-header-item",source:t,presentation:s}),[s,t]),c=JSON.stringify([t.workId,t.sessionId,t.branchId,s]),d=(0,r.useRef)(null),[u,m]=(0,r.useState)(!1);return((0,r.useLayoutEffect)(()=>{let t=d.current;if(!t)return;let s=new ResizeObserver(()=>{let s=t.getBoundingClientRect().height>0;m(s),a?.(e,s)});return s.observe(t),()=>s.disconnect()},[e,a,c]),"action"===l.type)?(0,n.jsx)(sO,{pluginName:e.pluginName,contributionName:e.descriptor.contributionName,presentation:s,source:t,icon:l.icon,label:l.label,onSelected:i}):(0,n.jsx)("div",{"data-testid":"plugin-session-header-custom","data-plugin-name":e.pluginName,"data-contribution-name":e.descriptor.contributionName,"data-presentation":s,className:(0,C.cn)("min-w-0 shrink-0","overflow"===s&&"w-full",!u&&"pointer-events-none invisible absolute"),"aria-hidden":!u,inert:!u,style:"inline"===s&&"custom"===e.descriptor.inline.type?{width:`${e.descriptor.inline.minWidthRem}rem`}:void 0,children:(0,n.jsx)("div",{ref:d,children:(0,n.jsx)(eK,{pluginName:e.pluginName,kind:"session-header-item",contributionName:e.descriptor.contributionName,target:o,targetKey:c,layout:"inline"})})})}function sB({source:e,title:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,Q.So)(),a=(0,r.useMemo)(()=>i.flatMap(e=>e.contributions.flatMap(t=>"session-header-item"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[i]),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(new Map),d=(0,r.useRef)(null),u=(0,r.useCallback)((e,t)=>{c.current.get(e)!==t&&(c.current.set(e,t),d.current?.())},[]),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),f=m?.items===a?m.count:a.length,x=m?.items===a?m.occupied:a.some(e=>"action"===e.descriptor.inline.type),v=a.slice(0,f),w=a.slice(f);return(0,r.useLayoutEffect)(()=>{for(let e of c.current.keys())a.includes(e)||c.current.delete(e);let e=l.current,t=o.current;if(!e||!t||0===a.length)return;let s=[...t.querySelectorAll("[data-header-item-width]")],n=t.querySelector("[data-header-title-width]"),r=t.querySelector("[data-header-more-width]"),i=t.querySelector("[data-header-gap-width]"),u=()=>{let t=i.getBoundingClientRect().width,l=e.getBoundingClientRect().width-n.getBoundingClientRect().width-t,o=s.map((e,t)=>"custom"!==a[t].descriptor.inline.type||c.current.get(a[t])?e.getBoundingClientRect().width:0),d=function(e,t,s,n){let r=e.filter(e=>e>0).length;if(e.reduce((e,t)=>e+t,0)+Math.max(0,r-1)*n<=t)return e.length;let i=s,a=0;for(let s of e){if(s>0){if(i+n+s>t)break;i+=n+s}a+=1}return a}(o,l,r.getBoundingClientRect().width,t),u=o.some(e=>e>0);d===a.length&&g(!1),p(e=>e?.items===a&&e.count===d&&e.occupied===u?e:{items:a,count:d,occupied:u})};d.current=u;let m=new ResizeObserver(u);for(let t of(m.observe(e),[...s,n,r,i]))m.observe(t);return u(),()=>{d.current=null,m.disconnect()}},[a]),(0,n.jsxs)("div",{ref:l,className:"relative flex min-w-0 flex-1 items-center","data-testid":"plugin-session-header",children:[(0,n.jsx)("div",{className:"min-w-[3rem] flex-1",children:t}),a.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:(0,C.cn)("flex shrink-0 items-center gap-1",x&&"ml-1"),"data-testid":"session-header-items",children:[v.map(t=>(0,n.jsx)(sF,{item:t,source:e,presentation:"inline",onContentChange:u},sL(t))),w.length>0?(0,n.jsxs)(eW.AM,{open:h,onOpenChange:g,children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":s("moreActions"),"data-testid":"session-header-more"}),children:(0,n.jsx)(K.A,{className:"size-4"})}),(0,n.jsxs)(eW.hl,{align:"end",finalFocus:!0,className:"pi-desk-chat-scrollbar max-h-[min(28rem,var(--available-height))] gap-1 overflow-auto p-1","data-testid":"session-header-overflow","aria-label":s("moreActions"),children:[(0,n.jsx)(eW.eO,{className:"sr-only",children:s("moreActions")}),h?w.map(t=>(0,n.jsx)(sF,{item:t,source:e,presentation:"overflow",onSelected:()=>g(!1)},sL(t))):null]})]}):null]}),(0,n.jsx)("div",{ref:o,"aria-hidden":"true",inert:!0,className:"pointer-events-none invisible absolute inset-0 overflow-hidden",children:(0,n.jsxs)("div",{className:"flex w-max items-center",children:[(0,n.jsx)("span",{"data-header-title-width":!0,className:"inline-block w-[3rem]"}),(0,n.jsx)("span",{"data-header-gap-width":!0,className:"inline-block w-1"}),(0,n.jsx)("span",{"data-header-more-width":!0,className:(0,I.r)({variant:"ghost",size:"icon-sm"}),children:(0,n.jsx)(K.A,{className:"size-4"})}),a.map(e=>"action"===e.descriptor.inline.type?(0,n.jsxs)("span",{"data-header-item-width":!0,className:(0,I.r)({variant:"ghost",size:"sm"}),children:[(0,n.jsx)(eq,{icon:e.descriptor.inline.icon,className:"size-4"}),(0,n.jsx)("span",{children:e.descriptor.inline.label})]},sL(e)):(0,n.jsx)("span",{"data-header-item-width":!0,className:"inline-block shrink-0",style:{width:`${e.descriptor.inline.minWidthRem}rem`}},sL(e)))]})})]}):null]})}var sq=s(10263),s_=s(11831),sW=s(79615),sY=s(24863),sV=s(10672);let sU="1.1.31".trim()||"未知",sK="2026-10-29T01:47:38+08:00".trim()||null;var sH=s(42655),sG=s(55079),sJ=s(49667),sQ=s(61286),sX=s(33550),sZ=s(66453),s0=s(67765);let s1=a.Yj().min(1).max(s0.uV).refine(e=>!e.includes("\0")&&(e.startsWith("/")||e.startsWith("\\\\")||/^[a-zA-Z]:[\\/]/.test(e)),"必须是绝对路径"),s2=a.Ik({cwd:sZ.m4.nullable()}).strict(),s5=a.Ik({skillPath:s1,name:a.Yj().min(1),description:a.Yj(),packageSource:a.Yj().nullable()}).strict(),s3=a.Ik({skills:a.YO(s5),diagnostics:a.YO(a.Ik({path:a.Yj(),message:eJ.qf}).strict())}).strict(),s4=s2.extend({skillPath:s1}),s6=s4.extend({path:s0.rh}).strict(),s8=a.Ik({entries:a.YO(a.Ik({name:a.Yj().min(1),type:a.k5(["directory","file"])}).strict()).max(s0.xm),truncated:a.zM()}).strict(),s7=s4.extend({path:s0._g}).strict(),s9=a.gM("kind",[a.Ik({kind:a.eu("text"),content:a.Yj(),size:a.ai().int().nonnegative().max(s0.NL),readOnlyReason:eJ.qf.nullable()}).strict(),a.Ik({kind:a.eu("image"),mimeType:s0.CT,data:a.Yj(),size:a.ai().int().nonnegative()}).strict(),a.Ik({kind:a.eu("unsupported"),size:a.ai().int().nonnegative(),reason:a.Yj()}).strict()]),ne=s7.extend({content:a.Yj().max(s0.NL)}).strict(),nt=a.Ik({}).strict(),ns={path:"/api/skills/list",request:s2,response:s3},nn={path:"/api/skill-files/list",request:s6,response:s8},nr={path:"/api/skill-files/get",request:s7,response:s9},ni={path:"/api/skill-files/replace",request:ne,response:nt},na=a.Ik({code:a.ai(),msg:a.Yj(),data:a.L5(),i18n:sQ.N.optional()});async function nl(e,t,s,n){let r=await fetch(t.path,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(t.request.parse(s)),signal:n}),i=na.parse(await r.json());if(!r.ok||0!==i.code||null===i.data)throw Error(i.msg?(0,ed.B)(i):"Skills 请求失败");return t.response.parse(i.data)}function no(e){(0,sX.ZQ)({wrapLines:e})}async function nc(e){let t=e.skillPath.replaceAll("\\","/");await navigator.clipboard.writeText(t.slice(0,t.lastIndexOf("/")+1)+e.path)}var nd=s(46782);function nu(e){return(0,ed.B)({msg:nd.P["zh-CN"][e],i18n:{key:`skills:${e}`}})}function nm(e){return JSON.stringify(e)}function np(e){return JSON.stringify([e.cwd,e.skillPath,e.path])}function nh(e){return e.replace(/\r\n|\r/g,"\n")}function ng(e){return e?.file?.kind==="text"&&e.draft!==nh(e.file.content)}var nf=s(60794),nx=s(89757),nb=s(55628),nv=s(91182);function nw(e){let{t}=(0,b.Bd)("common"),{wrapLines:s}=(0,sX.TX)(),i=e.path,a=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(null),d=(0,r.useRef)(null),u=(0,r.useRef)(0),m=(0,r.useRef)(e),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{m.current=e}),(0,r.useEffect)(()=>{let e=!1,s=()=>void 0,n=()=>void 0;return(0,nv.cu)().then(r=>{if(e||!a.current)return;let i=m.current,o=r.editor.create(a.current,{model:null,theme:(0,nv.dC)(),automaticLayout:!0,readOnly:i.readOnly,domReadOnly:i.readOnly,wordWrap:(0,sX.E6)().wrapLines?"on":"off",wrappingIndent:"same",minimap:{enabled:!1},stickyScroll:{enabled:!1},scrollBeyondLastLine:!1,...(0,nv.R)(),lineNumbersMinChars:3,padding:{top:14,bottom:14},unicodeHighlight:{nonBasicASCII:!1},renderWhitespace:"selection",overviewRulerBorder:!1,ariaLabel:t("skillEditor")});l.current=o,o.addCommand(r.KeyMod.CtrlCmd|r.KeyCode.KeyS,()=>m.current.onSave()),s=(0,nv.Tr)(e=>r.editor.setTheme(e)),n=(0,nv.BK)(e=>o.updateOptions(e)),f(!0)}).catch(()=>{e||h(!0)}),()=>{e=!0,s(),n(),c.current?.dispose(),c.current=null,o.current?.dispose(),o.current=null,d.current=null,l.current?.dispose(),l.current=null}},[t]),(0,r.useEffect)(()=>{let e=!1,t=u.current+1;return u.current=t,(0,nv.cu)().then(s=>{if(e||t!==u.current||!l.current)return;let n=m.current,r=s.editor.createModel(n.content,(0,nv.ix)(n.path,n.size),(0,nv.B3)(s,n.path,"edit")),a=o.current;c.current?.dispose(),c.current=r.onDidChangeContent(()=>{m.current.onChange(r.getValue(s.editor.EndOfLinePreference.LF))}),o.current=r,d.current=i,l.current.setModel(r),a?.dispose()}),()=>{e=!0}},[i]),(0,r.useEffect)(()=>{let t=o.current;t&&d.current===e.path&&t.getValue().replace(/\r\n|\r/g,"\n")!==e.content&&t.setValue(e.content)},[e.content,e.path]),(0,r.useEffect)(()=>{l.current?.updateOptions({readOnly:e.readOnly,domReadOnly:e.readOnly,wordWrap:s?"on":"off"})},[e.readOnly,s]),(0,n.jsxs)("div",{"data-testid":"code-editor",className:"relative h-full min-h-0 w-full overflow-hidden bg-background",children:[(0,n.jsx)("div",{ref:a,className:"size-full"}),!g&&(0,n.jsx)("div",{role:"status",className:"absolute inset-0 flex items-center justify-center p-6 text-sm text-muted-foreground",children:p?t("editorFailed"):t("editorLoading")})]})}var ny=s(58840);function nk({file:e,path:t}){let{t:s}=(0,b.Bd)("skills"),i=(0,r.useMemo)(()=>[{src:`data:${e.mimeType};base64,${e.data}`,alt:t}],[e,t]);return(0,n.jsx)(ny.k,{mode:"inline",slides:i,className:"h-full w-full",ariaLabel:s("imagePreview")})}function nj(e){let{document:t,skill:s,dirty:r,loading:i,saving:a,opening:l}=e,{t:o}=(0,b.Bd)("skills"),{locale:c}=(0,eQ.i)();if(!t)return(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center",children:[(0,n.jsx)(nf.A,{className:"size-6 text-muted-foreground"}),(0,n.jsx)("h3",{className:"text-sm font-medium",children:o("chooseFile")}),(0,n.jsx)("p",{className:"max-w-xs text-sm leading-6 text-muted-foreground",children:o("chooseFileDescription")})]});let d=t.file,u=d?.kind==="text"?d.readOnlyReason:null;return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-14 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-2",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("p",{className:"truncate text-xs text-muted-foreground",title:s?.description,children:[s?.name??t.target.skillPath.split("/").at(-2),(0,n.jsx)("span",{className:"mx-1.5",children:"/"}),o(null===t.target.cwd?"global":"project"),` \xb7 ${o(s?.packageSource?"package":"local")}`]}),(0,n.jsx)("p",{className:"mt-1 truncate font-mono text-sm",title:t.target.path,children:t.target.path})]}),d?.kind==="text"&&(0,n.jsxs)("span",{role:"status","aria-label":o(a?"saving":l?"switchingFile":r?"unsavedChanges":u?"readOnlyFile":"fileSaved"),className:"hidden shrink-0 items-center gap-1 text-xs text-muted-foreground sm:flex",children:[a||l?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):r?(0,n.jsx)("span",{className:"size-1.5 rounded-full bg-status-warning"}):u?(0,n.jsx)(nx.A,{className:"size-3.5"}):(0,n.jsx)(ep.A,{className:"size-3.5"}),o(a?"saving":l?"switchingFile":r?"unsaved":u?"readOnly":"saved")]}),r&&(0,n.jsx)("span",{"aria-label":o("unsavedChanges"),className:"size-2 shrink-0 rounded-full bg-status-warning sm:hidden"}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon","aria-label":o("copySkillPath"),title:o("copyPath"),onClick:e.onCopy,children:(0,n.jsx)(ee.A,{className:"size-4"})}),(0,n.jsxs)(I.$,{"aria-label":o("saveSkill"),disabled:!r||!!u||i||a,onClick:e.onSave,children:[a?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(Z.A,{className:"size-4"}),o("save")]})]}),u&&(0,n.jsxs)("div",{role:"note",className:"flex shrink-0 items-start gap-2 border-b bg-muted px-4 py-2 text-sm leading-5 text-muted-foreground",children:[(0,n.jsx)(nx.A,{className:"mt-0.5 size-3.5 shrink-0"}),(0,n.jsx)("p",{children:(0,eJ.fD)(u,c)})]}),t.error&&(0,n.jsxs)("div",{role:"alert",className:"shrink-0 border-b bg-muted px-4 py-2 text-sm text-destructive",children:[t.error,!d&&(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:e.onReload,children:o("reload")})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:i&&!d?(0,n.jsxs)("div",{role:"status",className:"flex h-full items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),o("loadingFile")]}):d?.kind==="text"?(0,n.jsx)(nw,{path:t.target.skillPath.slice(0,t.target.skillPath.lastIndexOf("/")+1)+t.target.path,content:t.draft,size:d.size,readOnly:!!u||a||l,onChange:e.onChange,onSave:e.onSave}):d?.kind==="image"?(0,n.jsx)(nk,{file:d,path:t.target.path}):d?.kind==="unsupported"?(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-sm text-muted-foreground",children:[(0,n.jsx)(nf.A,{className:"mb-2 size-8"}),(0,n.jsx)("p",{children:d.reason}),(0,n.jsx)("p",{children:o("fileSize",{size:d.size.toLocaleString("en"===c?"en-US":"zh-CN")})})]}):null}),d?.kind==="text"&&(0,n.jsxs)("div",{className:"flex min-h-9 shrink-0 items-center justify-between gap-2 border-t px-3 py-1 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{className:"truncate",children:["UTF-8 \xb7 ",o(u?"readOnly":"saveShortcut")]}),(0,n.jsxs)(I.$,{variant:"ghost",size:"sm","aria-label":o("wrapLines"),"aria-pressed":e.wrapLines,onClick:e.onWrapLines,children:[(0,n.jsx)(nb.A,{className:"size-3.5"}),o("wrapLines")]})]})]})}function nN({open:e,saving:t,path:s,error:r,onDecide:i}){let{t:a}=(0,b.Bd)("skills");return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||t||i("cancel")},children:(0,n.jsxs)(eN.hA,{className:"z-[150]",showCloseButton:!t,children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:a("saveChangesTitle")}),(0,n.jsx)(eN.uX,{children:a("saveChangesDescription",{path:s??""})})]}),r&&(0,n.jsx)("p",{role:"alert",className:"px-4 pb-4 text-sm text-destructive",children:r}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{variant:"outline",disabled:t,onClick:()=>void i("cancel"),children:a("cancel")}),(0,n.jsx)(I.$,{variant:"ghost",disabled:t,onClick:()=>void i("discard"),children:a("discard")}),(0,n.jsx)(I.$,{disabled:t,onClick:()=>void i("save"),children:a(t?"savingChanges":"saveContinue")})]})]})})}var nI=s(19932),nS=s(43326),nC=s(17511);function nE(e,t){return!!(e&&e.cwd===t.cwd&&e.skillPath===t.skillPath&&e.path===t.path)}function nM({target:e,props:t,depth:s=0,skillName:i}){let{t:a}=(0,b.Bd)("skills"),l=t.directories[np(e)],{onLoadDirectory:o}=t;return((0,r.useEffect)(()=>{l||o(e)},[l,o,e]),l?.error)?(0,n.jsxs)("div",{className:"px-3 py-2 text-xs text-destructive",children:[l.error,(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:()=>void t.onLoadDirectory(e),children:a("retryFolder")})]}):l?.data?(0,n.jsxs)("div",{className:"relative ml-5 border-l border-border/70 py-1 pl-3",children:[l.data.entries.map(r=>{let l=e.path?`${e.path}/${r.name}`:r.name,o={...e,path:l};if("directory"===r.type)return(0,n.jsx)(nz,{target:o,props:t,depth:s,name:r.name,skillName:i},l);let c=nE(t.selected,o),d=nE(t.pending,o);return(0,n.jsxs)(I.$,{variant:"ghost","aria-label":a("skillFile",{path:`${i}/${l}`}),"aria-pressed":c,title:l,className:(0,C.cn)("min-h-9 w-full justify-start text-left font-normal text-muted-foreground",c&&"font-medium",d&&"bg-muted text-foreground"),onClick:()=>void t.onOpenFile(o),children:["SKILL.md"===r.name?(0,n.jsx)(nI.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(nf.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r.name}),d&&(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin"})]},l)}),0===l.data.entries.length&&(0,n.jsx)("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:a("emptyFolder")}),l.data.truncated&&(0,n.jsx)("p",{className:"px-3 py-2 text-sm text-status-warning",children:a("folderTruncated")})]}):(0,n.jsx)("p",{role:"status",className:"px-4 py-2 text-xs text-muted-foreground",children:a("loadingFolder")})}function nz({target:e,props:t,depth:s,name:i,skillName:a}){let{t:l}=(0,b.Bd)("skills"),[o,c]=(0,r.useState)(!1);return(0,n.jsxs)("div",{children:[(0,n.jsxs)(I.$,{variant:"ghost","aria-expanded":o,"aria-label":l("skillFolder",{path:`${a}/${e.path}`}),className:(0,C.cn)("min-h-9 w-full justify-start font-normal text-muted-foreground",o&&"bg-muted text-foreground"),onClick:()=>c(!o),children:[o?(0,n.jsx)(eY.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(e7.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)(eP.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:i})]}),o&&(0,n.jsx)("div",{className:s>3?"-ml-3":void 0,children:(0,n.jsx)(nM,{target:e,props:t,depth:s+1,skillName:a})})]})}function nA({cwd:e,skill:t,props:s}){let{t:i}=(0,b.Bd)("skills"),a=s.selected?.cwd===e&&s.selected.skillPath===t.skillPath,l=s.pending?.cwd===e&&s.pending.skillPath===t.skillPath,[o,c]=(0,r.useState)(null),d=o??a,u=async()=>{if(d)return void c(!1);let n=t.skillPath.replaceAll("\\","/").split("/").at(-1);await s.onOpenFile({cwd:e,skillPath:t.skillPath,path:n})&&c(!0)};return(0,n.jsxs)("div",{className:"py-0.5",children:[(0,n.jsxs)(I.$,{variant:"ghost","aria-label":i("skillName",{name:t.name}),"aria-expanded":d,title:`${t.description}
|
|
155
155
|
${t.skillPath}`,className:(0,C.cn)("min-h-14 w-full justify-start whitespace-normal text-left",d&&"bg-accent hover:bg-accent",a&&"text-foreground"),onClick:()=>void u(),children:[d?(0,n.jsx)(eY.A,{className:"size-3.5 shrink-0 text-muted-foreground"}):(0,n.jsx)(e7.A,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",children:t.name}),t.description&&(0,n.jsx)("p",{className:"mt-0.5 truncate text-xs font-normal text-muted-foreground",children:t.description})]}),l?(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground"}):t.packageSource?(0,n.jsx)(nS.A,{"aria-label":i("packageSkill"),className:"size-3.5 shrink-0 text-muted-foreground"}):null]}),d&&(0,n.jsx)(nM,{target:{cwd:e,skillPath:t.skillPath,path:""},props:s,skillName:t.name})]})}function n$({cwd:e,name:t,props:s}){let{t:i}=(0,b.Bd)("skills"),{locale:a}=(0,eQ.i)(),l=s.selected?.cwd===e||s.pending?.cwd===e,[o,c]=(0,r.useState)(null),{onLoadScope:d}=s,u=s.scopes[nm(e)],m=s.query.trim().toLowerCase(),p=o??(null===e||s.focusedCwd===e||l),h=p||!!m;(0,r.useEffect)(()=>{h&&!u&&d(e)},[e,h,u,d]);let g=`${t} ${e??""}`.toLowerCase().includes(m),f=u?.data?.skills.filter(e=>!m||g||`${e.name} ${e.description}`.toLowerCase().includes(m))??[];if(m&&u?.data&&!f.length&&!g&&!u.error)return null;let x=null===e;return(0,n.jsxs)("section",{className:"mx-2 mt-2 min-w-0 border-b pb-2","aria-label":x?i("globalSkills"):i("projectSkills",{name:t}),children:[(0,n.jsxs)(I.$,{variant:"ghost",className:"min-h-14 w-full justify-start text-left","aria-label":i("skillsGroup",{name:x?i("global"):t}),"aria-expanded":h,onClick:()=>c(!p),children:[h?(0,n.jsx)(eY.A,{className:"size-4 shrink-0"}):(0,n.jsx)(e7.A,{className:"size-4 shrink-0"}),x?(0,n.jsx)(eL.A,{className:"size-4 shrink-0 text-primary"}):(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-semibold",children:x?i("globalSkills"):t}),e&&(0,n.jsx)("p",{title:e,className:"mt-1 truncate text-xs font-normal text-muted-foreground",children:e})]}),u?.loading?(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground"}):u?.data?(0,n.jsx)("span",{className:"text-xs tabular-nums text-muted-foreground",children:m?f.length:u.data.skills.length}):null]}),h&&(0,n.jsxs)("div",{className:"px-1 py-1",children:[u?.error&&(0,n.jsxs)("p",{className:"px-3 py-2 text-xs text-destructive",children:[u.error,(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:()=>void s.onLoadScope(e),children:i("retryGroup")})]}),f.map(t=>(0,n.jsx)(nA,{cwd:e,skill:t,props:s},t.skillPath)),u?.data&&0===f.length&&!u.error&&(0,n.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground",children:i(m?"noSkillMatches":"noSkills")}),!!u?.data?.diagnostics.length&&(0,n.jsxs)("details",{className:"mx-2 mb-1 mt-2 rounded-md bg-muted p-2 text-sm text-muted-foreground",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-status-warning",children:i("diagnostics",{count:u.data.diagnostics.length})}),(0,n.jsx)("div",{className:"mt-2 space-y-3",children:u.data.diagnostics.map((e,t)=>(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"break-words",children:(0,eJ.fD)(e.message,a)}),(0,n.jsx)("p",{className:"mt-1 break-all text-xs",children:e.path})]},`${e.path}:${t}`))})]})]})]})}function nR(e){let{t}=(0,b.Bd)("skills");return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsx)("div",{className:"shrink-0 border-b p-3",children:(0,n.jsxs)(nC.MG,{children:[(0,n.jsx)(nC.Sq,{children:(0,n.jsx)(eh.A,{className:"size-4"})}),(0,n.jsx)(nC.iV,{"aria-label":t("searchSkills"),value:e.query,onChange:t=>e.onQuery(t.target.value),placeholder:t("searchSkillsPlaceholder")})]})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain pb-4",children:[(0,n.jsx)(n$,{cwd:null,name:t("global"),props:e}),(0,n.jsxs)("div",{className:"flex items-center gap-2 px-4 pb-1 pt-5",children:[(0,n.jsx)("span",{className:"h-px flex-1 bg-border"}),(0,n.jsx)("p",{className:"shrink-0 text-xs font-medium text-muted-foreground",children:t("workspaceCount",{count:e.projects.length})}),(0,n.jsx)("span",{className:"h-px flex-1 bg-border"})]}),e.projects.map(t=>(0,n.jsx)(n$,{cwd:t.cwd,name:t.projectName,props:e},t.cwd)),0===e.projects.length&&(0,n.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground",children:t("workspaceEmpty")})]})]})}function nP({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{t:i}=(0,b.Bd)("skills"),{clientId:a}=(0,ei.gM)(),l=(0,X.G)(),o=(0,r.useMemo)(()=>({list:(e,t)=>nl(a,ns,e,t),listFiles:(e,t)=>nl(a,nn,e,t),getFile:(e,t)=>nl(a,nr,e,t),async replaceFile(e){await nl(a,ni,e)}}),[a]),c=function(e,t){let[s,n]=(0,r.useState)({}),[i,a]=(0,r.useState)({}),l=(0,r.useRef)(new Map),o=(0,r.useRef)(!0);(0,r.useEffect)(()=>{o.current=!0;let e=l.current;return()=>{for(let t of(o.current=!1,e.values()))t.abort();e.clear()}},[]);let c=(0,r.useCallback)(async t=>{let s=nm(t),r=`scope:${s}`;l.current.get(r)?.abort();let i=new AbortController;l.current.set(r,i),n(e=>({...e,[s]:{data:e[s]?.data??null,loading:!0,error:null}}));try{let r=await e.list({cwd:t},i.signal);!i.signal.aborted&&o.current&&n(e=>({...e,[s]:{data:r,loading:!1,error:null}}))}catch(e){!i.signal.aborted&&o.current&&n(t=>({...t,[s]:{data:t[s]?.data??null,loading:!1,error:e instanceof Error?e.message:nu("skillsReadFailed")}}))}finally{l.current.get(r)===i&&l.current.delete(r)}},[e]),d=(0,r.useCallback)(async t=>{let s=np(t),n=`directory:${s}`;l.current.get(n)?.abort();let r=new AbortController;l.current.set(n,r),a(e=>({...e,[s]:{data:e[s]?.data??null,loading:!0,error:null}}));try{let n=await e.listFiles(t,r.signal);!r.signal.aborted&&o.current&&a(e=>({...e,[s]:{data:n,loading:!1,error:null}}))}catch(e){!r.signal.aborted&&o.current&&a(t=>({...t,[s]:{data:null,loading:!1,error:e instanceof Error?e.message:nu("directoryReadFailed")}}))}finally{l.current.get(n)===r&&l.current.delete(n)}},[e]),u=JSON.stringify(t.map(e=>e.cwd));return(0,r.useEffect)(()=>{let e=new Set([nm(null),...JSON.parse(u).map(nm)]);for(let[t,s]of(n(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),a(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(nm(JSON.parse(t)[0]))))),l.current)){let n=t.startsWith("scope:")?t.slice(6):nm(JSON.parse(t.slice(10))[0]);e.has(n)||(s.abort(),l.current.delete(t))}},[u]),{scopes:s,directories:i,loadScope:c,loadDirectory:d}}(o,e),{loadScope:d}=c,u=function(e,t){let{wrapLines:s}=(0,sX.TX)(),[n,i]=(0,r.useState)(null),a=(0,r.useRef)(null),l=(0,r.useRef)(!0),[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(!1),h=(0,r.useRef)(null),g=(0,r.useRef)(!1),f=(0,r.useRef)(null),[x,b]=(0,r.useState)(!1),v=(0,r.useRef)(null),w=(0,r.useCallback)(e=>{l.current&&(a.current=e,i(e))},[]);(0,r.useEffect)(()=>(l.current=!0,()=>{l.current=!1,f.current?.abort(),v.current?.resolve(!1),v.current=null}),[]);let y=(0,r.useCallback)(()=>{if(h.current)return h.current;let s=a.current;if(!s||s.file?.kind!=="text"||s.file.readOnlyReason)return Promise.resolve(!1);if(!ng(s))return Promise.resolve(!0);p(!0);let n=(async()=>{try{await e.replaceFile({...s.target,content:s.draft});let n=a.current;return n?.file?.kind==="text"&&n.target===s.target&&w({...n,file:{...n.file,content:s.draft},error:null}),l.current&&t(s.target.cwd),!0}catch(t){let e=a.current;return e?.target===s.target&&w({...e,error:t instanceof Error?t.message:nu("saveFailed")}),!1}finally{h.current=null,l.current&&p(!1)}})();return h.current=n,n},[w,e,t]),k=(0,r.useCallback)(async()=>{let e;if(h.current&&await h.current,!l.current)return!1;if(!ng(a.current))return!0;if(v.current)return v.current.promise;let t=new Promise(t=>{e=t});return v.current={promise:t,resolve:e},b(!0),t},[]),j=(0,r.useCallback)(async e=>{if(!v.current||h.current||"save"===e&&(!await y()||ng(a.current)))return;if("discard"===e){let e=a.current;e?.file?.kind==="text"&&w({...e,draft:nh(e.file.content),error:null})}let t=v.current;v.current=null,b(!1),t?.resolve("cancel"!==e)},[w,y]),N=(0,r.useCallback)(async t=>{if(g.current)return!1;g.current=!0;try{if(!await k()||!l.current)return!1;f.current?.abort();let s=new AbortController;f.current=s,u(t),c(!0);try{let n=await e.getFile(t,s.signal);if(s.signal.aborted||!l.current)return!1;return w({target:t,file:n,draft:"text"===n.kind?nh(n.content):"",error:null}),!0}catch(e){if(!s.signal.aborted){let s=a.current,n=e instanceof Error?e.message:nu("fileReadFailed");w(s?{...s,error:n}:{target:t,file:null,draft:"",error:n})}return!1}finally{l.current&&(u(null),c(!1))}}finally{g.current=!1}},[w,k,e]),I=(0,r.useCallback)(e=>{let t=a.current;t?.file?.kind!=="text"||t.file.readOnlyReason||t.draft===e||w({...t,draft:e})},[w]),S=ng(n);return(0,r.useEffect)(()=>{if(!S)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[S]),{document:n,dirty:S,loading:o,openingTarget:d,saving:m,confirmOpen:x,wrapLines:s,setWrapLines:no,change:I,open:N,save:y,beforeLeave:k,decide:j}}(o,(0,r.useCallback)(e=>{d(e)},[d])),{document:m,open:p}=u,[h,g]=(0,r.useState)(""),[f,x]=(0,r.useState)(!1),[w,y]=(0,r.useState)(!0),k=(0,r.useRef)(!1),j=(0,r.useRef)(t);(0,r.useEffect)(()=>(s(u.beforeLeave),()=>s(null)),[u.beforeLeave,s]),(0,r.useEffect)(()=>{if(k.current||m)return;let e=c.scopes[nm(j.current)];if(!e||e.loading)return;let t=c.scopes[nm(null)],s=e.data?.skills[0];if(!s&&(!t||t.loading))return;let n=s??t?.data?.skills[0];k.current=!0,n&&p({cwd:s?j.current:null,skillPath:n.skillPath,path:n.skillPath.split("/").at(-1)})},[c.scopes,m,p]);let N=(0,r.useCallback)(async e=>{let t=await p(e);return t&&x(!1),t},[p]),S=async()=>{if(u.document)try{await nc(u.document.target),l.success(i("pathCopied"))}catch{l.error(i("copyFailed"))}},E=u.document?.target??null,M=E?c.scopes[nm(E.cwd)]?.data?.skills.find(e=>e.skillPath===E.skillPath)??null:null,z=Object.values(c.scopes).some(e=>e.loading)||Object.values(c.directories).some(e=>e.loading),A={projects:e,focusedCwd:t,query:h,onQuery:g,scopes:c.scopes,directories:c.directories,selected:E,pending:u.openingTarget,onLoadScope:c.loadScope,onLoadDirectory:c.loadDirectory,onOpenFile:N};return(0,n.jsxs)("section",{"aria-label":i("skillsManagement"),className:"flex h-full min-h-0 flex-col bg-background",children:[(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 border-b px-4 py-2",children:[(0,n.jsx)(I.$,{variant:"ghost",size:"icon",className:"lg:hidden","aria-label":i("openSkillsFolder"),onClick:()=>x(!0),children:(0,n.jsx)(sY.A,{className:"size-4"})}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon",className:"hidden lg:inline-flex","aria-label":i(w?"collapseSkillsFolder":"expandSkillsFolder"),onClick:()=>y(!w),children:w?(0,n.jsx)(sG.A,{className:"size-4"}):(0,n.jsx)(sJ.A,{className:"size-4"})}),(0,n.jsx)("h2",{className:"text-xl font-semibold",children:"Skills"}),(0,n.jsx)("div",{className:"flex-1"}),(0,n.jsxs)(I.$,{variant:"ghost",size:"sm",disabled:z,"aria-label":i("refreshSkillsFolder"),onClick:()=>{for(let e of Object.keys(c.scopes))c.loadScope(JSON.parse(e));for(let e of Object.keys(c.directories)){let[t,s,n]=JSON.parse(e);c.loadDirectory({cwd:t,skillPath:s,path:n})}},children:[z?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(es.A,{className:"size-3.5"}),i("refreshFolder")]})]}),(0,n.jsxs)("div",{className:"flex min-h-0 flex-1",children:[(0,n.jsx)("aside",{"aria-label":i("skillsProjectFolder"),className:(0,C.cn)("hidden w-64 shrink-0 border-r bg-sidebar xl:w-72",w&&"lg:block"),children:(0,n.jsx)(nR,{...A})}),(0,n.jsx)("main",{className:"min-h-0 min-w-0 flex-1",children:(0,n.jsx)(nj,{document:u.document,skill:M,dirty:u.dirty,loading:u.loading,saving:u.saving,opening:!!u.openingTarget,wrapLines:u.wrapLines,onWrapLines:()=>u.setWrapLines(!u.wrapLines),onChange:u.change,onSave:()=>void u.save(),onReload:()=>{E&&N(E)},onCopy:()=>void S()})})]}),(0,n.jsx)(eN.YV,{open:f,onOpenChange:x,children:(0,n.jsxs)(eN.hA,{className:"left-0 top-[var(--pi-desk-window-inset)] z-[130] h-[var(--pi-desk-content-height)] max-h-[var(--pi-desk-content-height)] w-[min(360px,calc(100dvw-2rem))] max-w-none translate-x-0 translate-y-0 rounded-l-none",finalFocus:!1,children:[(0,n.jsx)(eN.Hl,{className:"shrink-0 border-b px-4 py-3 pr-12",children:(0,n.jsx)(eN.YM,{children:i("skillsFolderTitle")})}),(0,n.jsx)("div",{className:"min-h-0 flex-1",children:(0,n.jsx)(nR,{...A})})]})}),(0,n.jsx)(nN,{open:u.confirmOpen,saving:u.saving,path:E?.path??null,error:u.document?.error??null,onDecide:u.decide})]})}var nD=s(75851),nT=s(17247),nO=s(4090),nL=s(19562);function nF(){let{t:e}=(0,b.Bd)("common"),[t,s]=(0,r.useState)(null),i=(0,r.useRef)(null),a=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{i.current?.(!1),i.current=null},[]);let l=e=>{let t=i.current;i.current=null,s(null),t?.(e)};return{confirm:e=>(i.current?.(!1),s(e),new Promise(e=>{i.current=e})),dialog:t?(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||l(!1)},children:(0,n.jsxs)(eN.hA,{initialFocus:a,className:"z-[130] max-w-[27.5rem]",children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:t.title}),(0,n.jsx)(eN.uX,{className:"break-words",children:t.description})]}),t.content?(0,n.jsx)(eN._Y,{className:"grid grid-rows-[minmax(0,1fr)]",children:t.content}):null,(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{ref:a,variant:"outline",onClick:()=>l(!1),children:e("cancel")}),(0,n.jsx)(I.$,{variant:t.confirmVariant??"destructive",onClick:()=>l(!0),children:t.confirmLabel??e("delete")})]})]})}):null}}var nB=s(33941);async function nq(e,t,s,n,r){let i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s),signal:r});401===i.status&&window.location.replace("/login");let a=await i.json();if(!i.ok||0!==a.code||null===a.data)throw Error(0===a.code?(0,ed.B)({msg:"登录保护设置处理失败",i18n:{key:"auth:settingsFailed"}}):(0,ed.B)(a));return n.parse(a.data)}async function n_(e){await nq(e,"/api/auth/logout",{},nB.Xm),window.location.replace("/login")}async function nW(e,t){let s=nB.uZ.safeParse(t);if(!s.success)throw Error((0,ed.B)({msg:"密码不符合要求,请按输入框下方的规则调整。",i18n:{key:"auth:settingsInvalid"}}));await nq(e,"/api/auth-settings/replace",s.data,nB.Kc),window.location.replace(null===t.password?"/":"/login")}function nY(){let{t:e}=(0,b.Bd)("auth"),t=function(){let{t:e}=(0,b.Bd)("auth"),{clientId:t}=(0,ei.gM)(),{confirm:s,dialog:n}=nF(),[i,a]=(0,r.useState)(null),[l,o]=(0,r.useState)(!0),[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)(0),[x,v]=(0,r.useState)(""),w=(0,r.useRef)(!1);(0,r.useEffect)(()=>{var s;let n=new AbortController;return(s=n.signal,nq(t,"/api/auth-settings/get",{},nB.G6,s)).then(e=>{n.signal.aborted||(a(e),o(!1))}).catch(t=>{n.signal.aborted||(h(t instanceof Error?t.message:e("settingsFailed")),o(!1))}),()=>n.abort()},[t,g,e]);let y=async()=>{if(!w.current&&i){w.current=!0,d(!0),h(null);try{await nW(t,{password:x})}catch(t){w.current=!1,d(!1),h(t instanceof Error?t.message:e("settingsFailed"))}}},k=async()=>{if(!w.current&&i){if(w.current=!0,!await s({title:e("disableTitle"),description:e("disableDescription"),confirmLabel:e("disable")})){w.current=!1;return}d(!0),h(null);try{await nW(t,{password:null})}catch(t){w.current=!1,d(!1),h(t instanceof Error?t.message:e("settingsFailed"))}}},j=async()=>{if(!w.current&&i?.enabled){w.current=!0,m(!0),h(null);try{await n_(t)}catch(t){w.current=!1,m(!1),h(t instanceof Error?t.message:e("logoutFailed"))}}};return{settings:i,loading:l,saving:c,signingOut:u,error:p,password:x,setPassword:v,save:y,generatePassword:()=>{if(!w.current)try{v(function(){for(;;){let e=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@"[e%64]).join("");if(/[A-Z]/.test(e)&&/[a-z]/.test(e)&&/[0-9]/.test(e)&&/[!@]/.test(e))return e}}()),h(null)}catch{h(e("generatePasswordFailed"))}},disable:k,logout:j,dialog:n,retry:()=>{o(!0),h(null),f(e=>e+1)}}}(),s=t.settings?.enabled??!1,i=t.saving||t.signingOut,a=s?en.A:nD.A;return(0,n.jsxs)("section",{"aria-labelledby":"auth-settings-title",className:"@container min-w-0 space-y-6",children:[(0,n.jsx)("h2",{id:"auth-settings-title",className:"text-xl font-semibold",children:e("settings:loginProtection")}),t.loading?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",role:"status",children:e("common:loading")}):t.settings?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 rounded-xl bg-muted p-4",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[(0,n.jsx)(a,{className:"size-5 shrink-0","aria-hidden":"true"}),(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:e("protection")}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e(s?"enabled":"disabled")})]})]}),s?(0,n.jsxs)(I.$,{type:"button",variant:"outline",className:"border-destructive/50 text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:i,"aria-busy":t.signingOut,onClick:()=>void t.logout(),children:[t.signingOut?(0,n.jsx)(v.A,{className:"motion-safe:animate-spin","aria-hidden":"true"}):(0,n.jsx)(nT.A,{"aria-hidden":"true"}),e(t.signingOut?"signingOut":"logout")]}):null]}),(0,n.jsxs)("form",{className:"grid gap-4 @min-[36rem]:grid-cols-[10rem_minmax(0,1fr)] @min-[36rem]:gap-6","aria-busy":i,onSubmit:e=>{e.preventDefault(),t.save()},children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:e(s?"changePassword":"setPassword")}),s?null:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("publicAccess")})]}),(0,n.jsxs)("div",{className:"min-w-0 max-w-[40rem] space-y-4",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("label",{className:"block text-sm font-medium",htmlFor:"auth-password",children:e(s?"newPassword":"password")}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:i,title:e("generatePasswordHint"),onClick:t.generatePassword,children:[(0,n.jsx)(nO.A,{"aria-hidden":"true"}),e("generatePassword")]})]}),(0,n.jsx)(nL.k,{id:"auth-password",name:"password",className:"[&::-ms-reveal]:hidden",autoComplete:"new-password",minLength:12,maxLength:64,required:!0,disabled:i,value:t.password,"aria-describedby":`auth-password-hint${t.error?" auth-settings-error":""}`,onChange:e=>t.setPassword(e.target.value)}),(0,n.jsx)("p",{id:"auth-password-hint",className:"text-sm text-muted-foreground",children:e("passwordHint")})]}),t.error?(0,n.jsx)("p",{id:"auth-settings-error",className:"text-sm text-destructive",role:"alert",children:t.error}):null,(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("saveEffect")}),(0,n.jsxs)(I.$,{type:"submit",disabled:i,children:[t.saving?(0,n.jsx)(v.A,{className:"motion-safe:animate-spin","aria-hidden":"true"}):null,e(t.saving?"saving":s?"saveAndSignIn":"enable")]})]})]}),s?(0,n.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4 border-t pt-4",children:[(0,n.jsxs)("details",{className:"group min-w-0 flex-1 text-sm",children:[(0,n.jsxs)("summary",{className:"flex min-h-8 w-fit cursor-pointer items-center gap-1 rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring",children:[(0,n.jsx)(e7.A,{className:"size-4 shrink-0 transition-transform group-open:rotate-90","aria-hidden":"true"}),e("recovery")]}),(0,n.jsxs)("div",{className:"mt-2 space-y-2",children:[(0,n.jsx)("p",{className:"text-muted-foreground",children:e("recoveryDescription")}),(0,n.jsx)("code",{className:"block break-all text-xs",children:t.settings.configPath})]})]}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"text-muted-foreground",disabled:i,onClick:()=>void t.disable(),children:e("disable")})]}):null]}):(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:t.error}),(0,n.jsx)(I.$,{variant:"outline",onClick:t.retry,children:e("common:retry")})]}),t.dialog]})}var nV=s(60471),nU=s(62851);let nK=Object.freeze({apply:(0,l.Vc)({path:"app-runtime/apply",inputSchema:nU.$C,outputSchema:nU.Pq}),update:(0,l._G)({path:"app-runtime/update",bodySchema:nU.YT})});var nH=s(48708);async function nG(e,t,s,n){let r=(0,nH.fx)();if(!r)return"cancelled";let i=e!==r.locale;if(i&&!window.confirm(t))return"cancelled";if(i&&n&&!await n())return"blocked";try{await s.request(nK.apply,{key:"settings",update:{region:{locale:e}}})}catch{return"save-failed"}return i&&window.location.reload(),"changed"}async function nJ(e,t){try{return await t.request(nK.apply,{key:"settings",update:{region:{timeZone:e}}}),!0}catch{return!1}}function nQ({canLeave:e}){let{t}=(0,b.Bd)("settings"),s=(0,eQ.i)(),{appSocket:i}=(0,ei.gM)(),[a,l]=(0,r.useState)(null),[o,c]=(0,r.useState)(()=>new Date);(0,r.useEffect)(()=>{let e=window.setInterval(()=>c(new Date),6e4);return()=>window.clearInterval(e)},[]);let d=(0,r.useMemo)(()=>[...["UTC",...Intl.supportedValuesOf("timeZone").filter(e=>"UTC"!==e)].map(e=>({value:e,label:e.replaceAll("_"," ")}))],[]),u=async s=>{l(null);let n=await nG(s,t("common:reloadConfirm"),i,e);"save-failed"===n&&l(t("common:localeError")),"blocked"===n&&l(t("common:reloadBlocked"))},m=async e=>{l(await nJ(e,i)?null:t("common:timeZoneError"))};return(0,n.jsxs)("section",{className:"@container min-w-0 space-y-6","aria-labelledby":"region-settings-title",children:[(0,n.jsx)("h2",{id:"region-settings-title",className:"text-xl font-semibold",children:t("region")}),(0,n.jsxs)("div",{className:"grid max-w-[40rem] gap-6 @min-[32rem]:grid-cols-2",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("label",{className:"block text-sm font-medium",htmlFor:"region-language",children:t("language")}),(0,n.jsxs)(ea.l6,{value:s.localePreference,onValueChange:e=>{("zh-CN"===e||"en"===e)&&u(e)},children:[(0,n.jsx)(ea.bq,{id:"region-language",className:"w-full",children:(0,n.jsx)(ea.yv,{children:"zh-CN"===s.localePreference?t("common:chinese"):"English"})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(ea.eb,{value:"zh-CN",children:t("common:chinese")}),(0,n.jsx)(ea.eb,{value:"en",children:"English"})]})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("currentLanguage",{locale:s.locale})}),s.pendingLocale&&(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("common:languagePending")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void u(s.localePreference),children:t("reloadLanguage")})]})]}),(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("span",{className:"block text-sm font-medium",children:t("timeZone")}),(0,n.jsx)(nV.b,{value:s.timeZonePreference,options:d,onChange:e=>void m(e),ariaLabel:t("timeZone"),searchPlaceholder:t("searchTimeZones"),emptyText:t("common:unavailable"),className:"w-full"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("currentTimeZone",{timeZone:s.timeZone})})]})]}),(0,n.jsxs)("div",{className:"space-y-1 rounded-xl bg-muted p-4",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("timeExample")}),(0,n.jsx)("p",{className:"text-sm font-medium tabular-nums",children:new Intl.DateTimeFormat("en"===s.locale?"en-US":"zh-CN",{timeZone:s.timeZone,year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(o)})]}),a&&(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:a})]})}var nX=s(90772),nZ=s(90164),n0=s(52871),n1=s(96646);function n2({label:e,value:t,options:s,onChange:r,layout:i="list",disabled:a=!1}){let l=s.some(e=>e.value===t);return(0,n.jsx)("div",{role:"radiogroup","aria-label":e,onKeyDown:e=>{if(a||e.nativeEvent.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=["ArrowRight","ArrowDown"].includes(e.key)?1:["ArrowLeft","ArrowUp"].includes(e.key)?-1:0;if(!n&&"Home"!==e.key&&"End"!==e.key)return;e.preventDefault();let i=Math.max(0,s.findIndex(e=>e.value===t)),l="Home"===e.key?0:"End"===e.key?s.length-1:(i+n+s.length)%s.length,o=s[l];o&&(r(o.value),e.currentTarget.querySelectorAll('[role="radio"]')[l]?.focus())},className:(0,C.cn)("segmented"===i?"inline-flex max-w-full flex-wrap gap-0.5 rounded-lg bg-muted p-0.5":"grid gap-2"),children:s.map((e,s)=>{let o=e.value===t,c=e.icon;return(0,n.jsxs)("button",{type:"button",role:"radio","aria-checked":o,tabIndex:o||!l&&0===s?0:-1,disabled:a,"data-testid":e.testId,onClick:()=>r(e.value),className:(0,C.cn)("flex min-w-0 cursor-pointer items-center gap-2 text-left text-sm leading-5 outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset","segmented"===i?"min-h-7 rounded-md px-2 py-0.5":"min-h-9 rounded-lg border border-transparent px-3 py-2",o?"segmented"===i?"bg-card text-card-foreground shadow-sm":"border-border bg-accent text-accent-foreground":"text-muted-foreground hover:bg-foreground/8 hover:text-foreground"),children:[c?(0,n.jsx)(c,{className:"size-4 shrink-0"}):null,(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block font-medium",children:e.label}),e.description?(0,n.jsx)("span",{className:"mt-1 block text-sm font-normal text-muted-foreground",children:e.description}):null]}),"list"===i?(0,n.jsx)(ep.A,{"aria-hidden":"true",className:(0,C.cn)("size-4 shrink-0",!o&&"invisible")}):null]},e.value)})})}var n5=s(74052),n3=s(38903),n4=s(90740),n6=s(67796),n8=s(8001),n7=s(46376),n9=s.n(n7);let re={code:{copy:!0,download:!1}};function rt({href:e,children:t,...s}){return delete s.node,(0,n.jsx)("a",{...s,href:e,target:"_blank",rel:"noopener noreferrer",children:t})}function rs({src:e,alt:t,className:s,onError:i,...a}){let{t:l}=(0,b.Bd)("conversation"),[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(!1),m=t||l("image"),p=(0,r.useMemo)(()=>"string"==typeof e&&e?[{src:e,alt:m}]:[],[m,e]);if(delete a.node,0===p.length)return null;if(d)return(0,n.jsx)("span",{className:n9().imageFallback,children:l("imageUnavailable")});let h=p[0].src;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",className:n9().imageTrigger,"aria-label":l("previewImage",{name:m}),onClick:()=>c(!0),children:[(0,n.jsx)("img",{...a,src:h,alt:m,"data-streamdown":"image",className:(0,C.cn)(n9().image,s),onError:e=>{u(!0),i?.(e)}}),(0,n.jsx)("span",{className:n9().imageAction,"aria-hidden":"true",children:(0,n.jsx)(q.A,{className:"size-4"})})]}),o?(0,n.jsx)(ny.k,{mode:"modal",open:!0,slides:p,ariaLabel:l("imagePreview"),onClose:()=>c(!1)}):null]})}function rn({className:e,isAnimating:t,components:s,...r}){let i=(0,X.G)(),{t:a}=(0,b.Bd)("conversation"),{locale:l}=(0,eQ.i)();return(0,n.jsx)("div",{className:"contents",onClickCapture:e=>{if("u">typeof navigator&&"function"==typeof navigator.clipboard?.writeText)return;let t=function(e){if(!(e instanceof Element))return null;let t=e.closest('[data-streamdown="code-block-copy-button"]');return t?t.closest('[data-streamdown="code-block"]')?.querySelector('[data-streamdown="code-block-body"]')?.textContent??null:null}(e.target);null!==t&&(e.preventDefault(),e.stopPropagation(),(0,e9.x)(t).then(e=>{e||i.error(a("codeCopyFailed"))}))},children:(0,n.jsx)(t2,{className:(0,C.cn)("space-y-0",n9().markdown,n8.om,e),controls:re,isAnimating:t,lineNumbers:!1,allowedTags:n8.IV,remarkPlugins:n8.XC,components:{...n8.e6,...s,a:rt,img:rs},...r,translations:"zh-CN"===l?n6.X:void 0})})}let rr=[{value:"system",label:"common:system",icon:nX.A},{value:"light",label:"themeLight",icon:nZ.A},{value:"dark",label:"themeDark",icon:n0.A}],ri=[{value:"compact",label:"sizeCompact"},{value:"standard",label:"sizeStandard"},{value:"large",label:"sizeLarge"}];function ra(){let{t:e}=(0,b.Bd)("settings"),t=(0,r.useSyncExternalStore)(n5.Cy,n5.Is,()=>n1.Pl),s=(0,r.useSyncExternalStore)(n4.wm,n4.Ev,()=>n3.Y8);return(0,n.jsxs)("section",{"aria-labelledby":"settings-appearance-title",className:"@container grid gap-6",children:[(0,n.jsx)("h2",{id:"settings-appearance-title",className:"text-xl font-semibold",children:e("appearance")}),(0,n.jsxs)("div",{className:"grid min-w-0 gap-6 @min-[40rem]:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-4",children:[(0,n.jsxs)("div",{className:"space-y-2 border-b pb-4",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("theme")}),(0,n.jsx)(n2,{label:e("theme"),layout:"segmented",value:t,options:rr.map(t=>({...t,label:e(t.label)})),onChange:n5.VS})]}),(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("displaySize")}),(0,n.jsx)(n2,{label:e("displaySize"),layout:"segmented",value:s,options:ri.map(t=>({...t,label:e(t.label)})),onChange:n4.$y})]})]}),(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("displayPreview")}),(0,n.jsx)("div",{"aria-label":e("displayPreview"),className:"min-w-0 rounded-xl bg-muted p-4",children:(0,n.jsx)(rn,{mode:"static",isAnimating:!1,children:e("displayPreviewContent")})})]})]})]})}var rl=s(50163),ro=s(93780),rc=s(88707),rd=s(31848),ru=s(71057),rm=s(20476);let rp="pi-super:new-work-session-behavior",rh="activate",rg=new Set,rf=rh,rx=!1;function rb(){if(!rx){rx=!0;try{var e;e=window.localStorage.getItem(rp),rf="none"===e||"activate"===e||"pin"===e?e:rh}catch{rf=rh}}}function rv(){return rb(),rf}function rw(e){if(rb(),rf!==e){rf=e;try{window.localStorage.setItem(rp,e)}catch{}for(let e of[...rg])e()}}function ry(e){return rg.add(e),()=>rg.delete(e)}let rk=[{value:"none",label:"behaviorNone",description:"behaviorNoneDescription",icon:rl.A,testId:"new-work-session-behavior-none"},{value:"activate",label:"behaviorActivate",description:"behaviorActivateDescription",icon:ro.A,testId:"new-work-session-behavior-activate"},{value:"pin",label:"behaviorPin",description:"behaviorPinDescription",icon:rc.A,testId:"new-work-session-behavior-pin"}],rj=[{value:"compressed",label:"imageCompressed",description:"imageCompressedDescription",icon:rd.A,testId:"image-preview-mode-compressed"},{value:"original",label:"imageOriginal",description:"imageOriginalDescription",icon:ru.A,testId:"image-preview-mode-original"}];function rN(){let{t:e}=(0,b.Bd)("settings"),t=(0,r.useSyncExternalStore)(ry,rv,rv),s=(0,r.useSyncExternalStore)(rm.ku,rm.Wq,rm.Wq);return(0,n.jsxs)("section",{"aria-labelledby":"settings-habits-title",className:"@container grid min-w-0 gap-6",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"settings-habits-title",className:"text-xl font-semibold",children:e("habits")}),(0,n.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:e("browserOnly")})]}),(0,n.jsxs)("div",{className:"grid min-w-0 gap-6 lg:@min-[40rem]:grid-cols-2",children:[(0,n.jsxs)("section",{className:"hidden min-w-0 lg:block","aria-labelledby":"new-session-behavior-title",children:[(0,n.jsx)("h3",{id:"new-session-behavior-title",className:"mb-3 text-sm font-semibold",children:e("newSessionBehavior")}),(0,n.jsx)(n2,{label:e("newSessionBehavior"),value:t,options:rk.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:rw}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:e("desktopOnlyBehavior")})]}),(0,n.jsxs)("section",{className:"min-w-0 lg:border-t lg:pt-4 lg:@min-[40rem]:border-t-0 lg:@min-[40rem]:border-l lg:@min-[40rem]:pt-0 lg:@min-[40rem]:pl-6","aria-labelledby":"image-preview-mode-title",children:[(0,n.jsx)("h3",{id:"image-preview-mode-title",className:"mb-3 text-sm font-semibold",children:e("imagePreviewMode")}),(0,n.jsx)(n2,{label:e("imagePreviewMode"),value:s,options:rj.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:rm.lU}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:e("imagePreviewApply")})]})]})]})}var rI=s(17339);let rS={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function rC({projectDefaults:e}){let{t}=(0,b.Bd)("settings");return(0,n.jsx)("ul",{className:"space-y-3 px-4 pb-4",children:e.map(({cwd:e,from:s,to:r})=>(0,n.jsxs)("li",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"break-all font-medium",children:e}),(0,n.jsxs)("p",{className:"break-all text-muted-foreground",children:[s.provider,"/",s.modelId," \xb7 ",t(rS[s.thinkingLevel]),(0,n.jsx)("span",{className:"mx-1.5",children:"→"}),(0,n.jsx)("span",{className:"text-foreground",children:r?(0,n.jsxs)(n.Fragment,{children:[r.provider,"/",r.modelId," \xb7 ",t(rS[r.thinkingLevel])]}):t("clearProjectDefault")})]})]},e))})}var rE=s(26357),rM=s(70698);let rz=a.Yj().trim().min(1).max(128),rA=a.Yj().trim().min(1).max(256),r$=a.Yj().trim().min(1).max(256),rR=a.Yj().trim().min(1).nullable(),rP=a.g1(a.Yj().trim().min(1),a.Yj()),rD=a.Yj().trim().min(1).max(128),rT=a.g1(a.Yj(),a.Pq()),rO=a.Ik({level:rE.$,providerValue:a.Yj().trim().min(1).nullable()}).strict(),rL=a.Ik({input:a.ai().nonnegative().finite(),output:a.ai().nonnegative().finite(),cacheRead:a.ai().nonnegative().finite(),cacheWrite:a.ai().nonnegative().finite()}).strict(),rF=a.Ik({supportsDeveloperRole:a.zM().nullable(),thinkingFormat:a.Yj().trim().min(1).max(128).nullable(),requiresReasoningContentOnAssistantMessages:a.zM().nullable()}).strict(),rB=a.Ik({modelId:rA,name:r$,api:rD.nullable(),baseUrl:rR,reasoning:a.zM(),thinkingLevels:a.YO(rO).min(1).max(7),input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),cost:rL.nullable(),headers:rP,compat:rF.nullable()}).strict().superRefine((e,t)=>{let s=new Set;for(let n of e.thinkingLevels)s.has(n.level)&&t.addIssue({code:"custom",message:`思考等级 ${n.level} 重复`}),s.add(n.level),("xhigh"===n.level||"max"===n.level)&&null===n.providerValue&&t.addIssue({code:"custom",message:`${n.level} 必须配置 Provider 映射`});e.reasoning||1===e.thinkingLevels.length&&s.has("off")||t.addIssue({code:"custom",message:"非推理模型只允许 off 思考等级"})}),rq=a.Ik({provider:rz,name:rR,baseUrl:rR,api:rD.nullable(),apiKey:a.Yj().nullable(),authHeader:a.zM().nullable(),headers:rP,models:a.YO(rB)}).strict().superRefine((e,t)=>{let s=new Set;for(let n of e.models)s.has(n.modelId)&&t.addIssue({code:"custom",message:`模型 ${n.modelId} 重复`}),s.add(n.modelId)}),r_=a.Ik({provider:rz,modelId:rA,thinkingLevel:rE.$,color:a.Yj().regex(/^#[0-9a-fA-F]{6}$/).nullable()}).strict(),rW=a.Ik({provider:rz,modelId:rA,name:r$,input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),thinkingLevels:a.YO(rE.$).min(1).max(7)}).strict(),rY=a.Ik({provider:rz,modelId:rA,thinkingLevel:rE.$}).strict(),rV=a.Ik({contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),cost:rL.partial().optional()}).strict(),rU=a.Ik({provider:rz,modelId:rA,overrides:rV}).strict(),rK=a.Ik({provider:rz,name:r$,loggedIn:a.zM(),subscription:a.zM(),models:a.YO(rB)}).strict();a.Ik({}).strict();let rH=a.Ik({providers:a.YO(rq),presets:a.YO(r_),models:a.YO(rW),nativeConfig:rT,accountModels:a.YO(rU),accounts:a.YO(rK)}).strict(),rG=a.Ik({provider:rz,modelId:rA}).strict(),rJ=a.Ik({from:rG,to:rG}).strict(),rQ=a.Ik({providers:a.YO(rq).optional(),presets:a.YO(r_).optional(),accountModels:a.YO(rU).optional(),modelReplacements:a.YO(rJ).optional()}).strict().refine(e=>void 0!==e.providers||void 0!==e.presets||void 0!==e.accountModels,{message:"请提交需要保存的模型配置"}),rX=a.KC([rQ,a.Ik({nativeConfig:rT}).strict()]),rZ=a.Ik({}).strict(),r0=a.Ik({projectDefaults:a.YO(a.Ik({cwd:sZ.m4,from:rY,to:rY.nullable()}).strict())}).strict(),r1=a.Ik({query:a.Yj().trim().max(256),refresh:a.zM(),page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive().max(100)}).strict()}).strict(),r2=a.Ik({reasoning:a.zM(),thinkingLevels:a.YO(rO).min(1).max(7),input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),cost:rL.nullable()}).strict(),r5=a.Ik({provider:rz,providerName:r$,modelId:rA,official:a.zM(),defaults:r2}).strict(),r3=a.Ik({referenceId:a.Yj().trim().min(1).max(512),name:r$,match:a.k5(["exact","similar"]).nullable(),sources:a.YO(r5).min(1)}).strict(),r4=a.Ik({updatedAt:rM.k,refreshResult:a.k5(["not-requested","updated","unchanged","partial","cached"]),page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive(),total:a.ai().int().nonnegative()}).strict(),models:a.YO(r3)}).strict();a.Ik({cwd:sZ.m4}).strict();let r6=a.Ik({cwd:sZ.m4,default:rY.nullable(),models:a.YO(rW)}).strict(),r8=a.Ik({cwd:sZ.m4,default:rY.nullable()}).strict(),r7=a.Ik({}).strict();var r9=s(29029);let ie="pi-desk:pi-directories",it="pi-desk:ignored-pi-directories",is="pi-desk:pi-directory-entries",ir=!1,ii=null,ia=null,il=!1,io=new Map;function ic(e){if(null===e)return"<root>";let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function id(e){try{return JSON.parse(window.localStorage.getItem(e)??"null")}catch{return null}}function iu(){ir||(ir=!0,ii=id(ie),ia=id(it))}function im(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function ip(e){iu(),ii=e,im(ie,e)}function ih(){if(il)return;il=!0;let e=id(is);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.entries;if(!(!t||"object"!=typeof t||Array.isArray(t)))for(let[e,s]of Object.entries(t))io.set(e,s)}function ig(e){return ih(),io.get(ic(e))??null}let ix="pi-desk:project-model-defaults",ib=!1,iv=new Map;function iw(e){let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function iy(){if(!ib){ib=!0;try{let e=JSON.parse(window.localStorage.getItem(ix)??"null");if(!e||"object"!=typeof e||Array.isArray(e))return;for(let[t,s]of Object.entries(e)){let e=r6.safeParse(s);e.success&&iv.set(t,e.data)}let t=!1;for(;iv.size>64;){let e=iv.keys().next().value;if(void 0===e)break;iv.delete(e),t=!0}t&&ik()}catch{iv.clear()}}}function ik(){try{window.localStorage.setItem(ix,JSON.stringify(Object.fromEntries(iv)))}catch{}}function ij(e){let t=r6.safeParse(e);if(!t.success)return;iy();let s=iw(t.data.cwd);for(iv.delete(s),iv.set(s,t.data);iv.size>64;){let e=iv.keys().next().value;if(void 0===e)break;iv.delete(e)}ik()}function iN(e){let t=rX.safeParse(e);if(!t.success){let e=t.error.issues[0]?.path.at(-1);if("modelId"===e)throw Error("请填写模型 ID 后再保存配置。");if("provider"===e)throw Error("请填写 Provider ID 后再保存配置。");throw Error("模型配置不完整或格式不正确,请检查必填字段和数值。")}return t.data}let iI=a.KC([a.k5(["appearance","region","habits","auth","models","mcp-settings","capability-modes","skills","plugins","about"]),a.Uy(["plugin:",a.Yj(),":",a.Yj()])]),iS=a.k5(["providers","presets","project-default"]),iC="pi-super:settings:section",iE="pi-super:settings:model-tab";function iM(e,t,s){try{let n=t.safeParse(window.localStorage.getItem(e));return n.success?n.data:s}catch{return s}}function iz(e,t){try{window.localStorage.setItem(e,t)}catch(e){console.warn("[Pi Desk][Settings] 保存设置导航位置失败,仅当前窗口生效",e)}}function iA({open:e,text:t,error:s,saving:r,dirty:i,onChange:a,onClose:l,onSave:o}){let{t:c}=(0,b.Bd)("settings");return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||l()},children:(0,n.jsxs)(eN.hA,{className:"max-w-[52rem]",initialFocus:!1,showCloseButton:!r,children:[(0,n.jsxs)(eN.Hl,{className:"border-b px-4 py-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:c("nativeConfig")}),(0,n.jsx)(eN.uX,{children:c("nativeConfigScope")})]}),(0,n.jsx)(eN._Y,{className:"max-h-[70dvh]",children:(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(t7.T,{"aria-label":c("nativeConfigEditor"),value:t,disabled:r,spellCheck:!1,autoCapitalize:"none",autoCorrect:"off",className:"min-h-[min(28rem,50dvh)] resize-y font-mono text-sm",onChange:e=>a(e.target.value)}),s?(0,n.jsx)("p",{role:"alert",className:"break-words text-sm text-destructive",children:s}):null]})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",disabled:r,onClick:l,children:c("cancel",{ns:"common"})}),(0,n.jsxs)(I.$,{type:"button",disabled:r||!i,onClick:o,children:[r?(0,n.jsx)(v.A,{className:"animate-spin"}):null,c(r?"savingModels":"saveNativeConfig")]})]})]})})}var i$=s(43209),iR=s(54346),iP=s(55289),iD=s(24121),iT=s(78844);let iO=[{value:"#3b82f6",label:"presetColorBlue"},{value:"#0891b2",label:"presetColorCyan"},{value:"#16a34a",label:"presetColorGreen"},{value:"#b7791f",label:"presetColorAmber"},{value:"#ea580c",label:"presetColorOrange"},{value:"#dc2626",label:"presetColorRed"},{value:"#db2777",label:"presetColorPink"},{value:"#8b5cf6",label:"presetColorPurple"}];function iL(e){return iO.map(({value:t})=>({value:t,count:e.filter(e=>e.color?.toLowerCase()===t).length})).reduce((e,t)=>t.count<e.count?t:e).value}let iF=["OpenAI Chat Completions","OpenAI Responses","Anthropic Messages","Google Generative AI","Mistral Conversations","Azure OpenAI Responses","OpenAI Codex Responses","Amazon Bedrock","Google Vertex AI","Pi Messages"],iB=["openai-completions","openai-responses","anthropic-messages","google-generative-ai","mistral-conversations","azure-openai-responses","openai-codex-responses","bedrock-converse-stream","google-vertex","pi-messages"].map((e,t)=>({value:e,label:iF[t]})),iq=["openai","openrouter","together","deepseek","zai","qwen","chat-template","qwen-chat-template","string-thinking","ant-ling","baseten"];function i_(e){return Object.entries(e).map(([e,t])=>`${e}: ${t}`).join("\n")}function iW({headers:e,onChange:t,placeholder:s}){let[i,a]=(0,r.useState)(null);return(0,n.jsx)(t7.T,{value:i??i_(e),onFocus:()=>a(i_(e)),onChange:e=>{let s=e.target.value;a(s),t(Object.fromEntries(s.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(":");return t>0?[e.slice(0,t).trim(),e.slice(t+1).trim()]:[e,""]})))},onBlur:()=>a(null),rows:4,placeholder:s,className:"font-mono"})}function iY(e){let t=Math.floor(e/1e3),s=e%1e3;return s?`${t}.${String(s).padStart(3,"0").replace(/0+$/,"")}`:String(t)}function iV(e){if(!/^\d+(?:\.\d{0,3})?$/.test(e))return null;let[t,s=""]=e.split("."),n=1e3*Number(t)+Number(s.padEnd(3,"0"));return Number.isSafeInteger(n)&&n>0?n:null}function iU({label:e,children:t,className:s}){return(0,n.jsxs)("label",{className:(0,C.cn)("grid gap-1 text-sm text-foreground",s),children:[(0,n.jsx)("span",{className:"font-medium",children:e}),t]})}let iK="__pi-desk_empty__";function iH({value:e,options:t,onChange:s,ariaLabel:r,placeholder:i,allowEmpty:a=!0,className:l}){let{t:o}=(0,b.Bd)("settings"),c=i??o("useDefault"),d=e||(a?iK:t[0]?.value??null),u=!!e&&!t.some(t=>t.value===e);return(0,n.jsxs)(ea.l6,{value:d,onValueChange:e=>s(e===iK||null===e?"":e),children:[(0,n.jsx)(ea.bq,{"aria-label":r,className:(0,C.cn)("w-full",l),children:(0,n.jsx)(ea.yv,{children:t.find(t=>t.value===e)?.label??(e||c)})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[a?(0,n.jsx)(ea.eb,{value:iK,children:c}):null,u?(0,n.jsx)(ea.eb,{value:e,children:e}):null,t.map(e=>(0,n.jsx)(ea.eb,{value:e.value,children:e.label},e.value))]})]})}function iG({value:e,onChange:t,ariaLabel:s}){let{t:r}=(0,b.Bd)("settings");return(0,n.jsx)(iH,{value:null===e?"":String(e),ariaLabel:s,options:[{value:"true",label:r("yes")},{value:"false",label:r("no")}],onChange:e=>t(""===e?null:"true"===e)})}let iJ={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function iQ(e,t){return JSON.stringify([e,t])}function iX(e,t){return JSON.stringify([e.provider,e.modelId,e.thinkingLevel,t])}function iZ(e){return e.map(e=>({value:iQ(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider}))}function i0(e,t){return(e?.thinkingLevels??[]).map(e=>({value:e,label:t(iJ[e])}))}function i1({id:e,preset:t,model:s,models:r,canMoveUp:i,canMoveDown:a,onChange:l,onDelete:o,onMoveUp:c,onMoveDown:d}){let{t:u}=(0,b.Bd)("settings"),{attributes:m,listeners:p,setActivatorNodeRef:h,setNodeRef:g,transform:f,transition:x,isDragging:v}=(0,iR.gl)({id:e}),w=f?`translate3d(${f.x}px, ${f.y}px, 0) scaleX(${f.scaleX??1}) scaleY(${f.scaleY??1})`:void 0,y=t.color?.toLowerCase()??"none",k=iO.find(e=>e.value===y),j=k?u(k.label):u(t.color?"presetColorCustom":"presetColorNone"),N=[{value:"none",color:null,label:u("presetColorNone")},...t.color&&!k?[{value:y,color:t.color,label:u("presetColorCustom")}]:[],...iO.map(e=>({value:e.value,color:e.value,label:u(e.label)}))];return(0,n.jsxs)("div",{ref:g,style:{transform:w,transition:x},className:(0,C.cn)("grid min-w-0 items-center gap-3 border-b bg-card py-3 @[48rem]/presets:grid-cols-[auto_minmax(0,1fr)_7.5rem_4rem_auto]",v&&"z-10 opacity-70 shadow-lg"),children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(I.$,{variant:"ghost",size:"icon-sm",ref:h,type:"button",title:u("presetDrag"),"aria-label":u("presetDrag"),className:"touch-none cursor-grab text-muted-foreground active:cursor-grabbing",...m,...p,children:(0,n.jsx)(iP.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(I.$,{variant:"ghost",size:"icon-sm",type:"button",title:u("presetMoveUp"),"aria-label":u("presetMoveUp"),disabled:!i,onClick:c,children:(0,n.jsx)(iD.A,{className:"size-4"})}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon-sm",type:"button",title:u("presetMoveDown"),"aria-label":u("presetMoveDown"),disabled:!a,onClick:d,children:(0,n.jsx)(eY.A,{className:"size-4"})})]})]}),(0,n.jsx)(iU,{label:u("modelsHeading"),children:(0,n.jsx)(nV.b,{value:iQ(t.provider,t.modelId),options:iZ(r),ariaLabel:u("presetModel"),searchPlaceholder:u("modelSearch"),onChange:e=>{let s=r.find(t=>iQ(t.provider,t.modelId)===e);s&&l({...t,provider:s.provider,modelId:s.modelId,thinkingLevel:s.thinkingLevels.includes(t.thinkingLevel)?t.thinkingLevel:s.thinkingLevels[0]})}})}),(0,n.jsx)(iU,{label:u("thinkingLevel"),children:(0,n.jsx)(iH,{value:t.thinkingLevel,options:i0(s,u),ariaLabel:u("presetThinking"),allowEmpty:!1,onChange:e=>l({...t,thinkingLevel:e})})}),(0,n.jsx)(iU,{label:u("presetColor"),children:(0,n.jsxs)(ea.l6,{value:y,onValueChange:e=>{null!==e&&l({...t,color:"none"===e?null:e})},children:[(0,n.jsx)(ea.bq,{"aria-label":u("presetColorLabel"),className:"w-16",children:(0,n.jsxs)(ea.yv,{children:[t.color?(0,n.jsx)("span",{"aria-hidden":"true",className:"size-4 shrink-0 rounded-full",style:{backgroundColor:t.color}}):(0,n.jsx)(iT.A,{"aria-hidden":"true",className:"size-4 text-muted-foreground"}),(0,n.jsx)("span",{className:"sr-only",children:j})]})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[120]",className:"w-40 min-w-40",align:"end",alignItemWithTrigger:!1,children:(0,n.jsx)(ea.s3,{className:"grid grid-cols-4 gap-1 p-2",children:N.map(e=>(0,n.jsx)(ea.eb,{value:e.value,label:e.label,"aria-label":e.label,className:"size-8 justify-center p-0 data-selected:bg-accent data-selected:ring-1 data-selected:ring-ring data-selected:ring-inset [&>span:first-child]:justify-center [&>span:last-child]:hidden",children:e.color?(0,n.jsx)("span",{"aria-hidden":"true",className:"size-4 shrink-0 self-center rounded-full",style:{backgroundColor:e.color}}):(0,n.jsx)(iT.A,{"aria-hidden":"true",className:"size-4 text-muted-foreground"})},e.value))})})]})}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm",title:u("presetDelete"),"aria-label":u("presetDelete"),onClick:o,children:(0,n.jsx)(et.A,{})})]})}function i2({presets:e,models:t,onChange:s}){let{t:i}=(0,b.Bd)("settings"),[a,l]=(0,r.useState)(()=>t[0]?iQ(t[0].provider,t[0].modelId):""),o=t.find(e=>iQ(e.provider,e.modelId)===a),[c,d]=(0,r.useState)(o?.thinkingLevels[0]??"off"),u=(0,i$.FR)((0,i$.MS)(i$.AN,{activationConstraint:{distance:6}}),(0,i$.MS)(i$.uN,{coordinateGetter:iR.JR})),m=(0,r.useMemo)(()=>e.map(iX),[e]);return(0,n.jsxs)("div",{className:"@container/presets space-y-4 p-4 sm:p-6",children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:i("presetDescription")}),(0,n.jsxs)("div",{className:"grid gap-3 border-b pb-4 @[32rem]/presets:grid-cols-[minmax(0,1fr)_7.5rem_auto]",children:[(0,n.jsx)(iU,{label:i("modelsHeading"),children:(0,n.jsx)(nV.b,{value:a,options:iZ(t),ariaLabel:i("presetModelNew"),searchPlaceholder:i("modelSearch"),disabled:0===t.length,onChange:e=>{l(e);let s=t.find(t=>iQ(t.provider,t.modelId)===e);s&&d(s.thinkingLevels[0])}})}),(0,n.jsx)(iU,{label:i("thinkingLevel"),children:(0,n.jsx)(iH,{value:c,options:i0(o,i),ariaLabel:i("presetThinkingNew"),allowEmpty:!1,onChange:e=>d(e)})}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",className:"self-end justify-self-start",onClick:function(){let n=t.find(e=>iQ(e.provider,e.modelId)===a);if(!n)return;let r=n.thinkingLevels.includes(c)?c:n.thinkingLevels[0];e.some(e=>e.provider===n.provider&&e.modelId===n.modelId&&e.thinkingLevel===r)||s([...e,{provider:n.provider,modelId:n.modelId,thinkingLevel:r,color:iL(e)}])},disabled:!o,children:[(0,n.jsx)(U.A,{})," ",i("presetAdd")]})]}),0===e.length?(0,n.jsx)("p",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:i("presetEmpty")}):(0,n.jsx)(i$.Mp,{sensors:u,collisionDetection:i$.fp,onDragEnd:function(t){if(!t.over||t.active.id===t.over.id)return;let n=m.indexOf(String(t.active.id)),r=m.indexOf(String(t.over.id));n>=0&&r>=0&&s((0,iR.be)(e,n,r))},children:(0,n.jsx)(iR.gB,{items:m,strategy:iR._G,children:(0,n.jsx)("div",{className:"space-y-2",children:e.map((r,i)=>{let a=t.find(e=>e.provider===r.provider&&e.modelId===r.modelId);return(0,n.jsx)(i1,{id:m[i],preset:r,model:a,models:t,canMoveUp:i>0,canMoveDown:i<e.length-1,onChange:t=>s(e.map((e,s)=>s===i?t:e)),onDelete:()=>s(e.filter((e,t)=>t!==i)),onMoveUp:()=>s((0,iR.be)(e,i,i-1)),onMoveDown:()=>s((0,iR.be)(e,i,i+1))},m[i])})})})})]})}var i5=s(72910),i3=s(61108),i4=s(46783),i6=s(89790);function i8(e){return 100*!!e.official+10*!!e.defaults.cost}let i7=[["off","thinkingOff"],["minimal","thinkingMinimal"],["low","thinkingLow"],["medium","thinkingMedium"],["high","thinkingHigh"],["xhigh","thinkingXhigh"],["max","thinkingMax"]],i9=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function ae(e){return{input:String(e.cost?.input??""),output:String(e.cost?.output??""),cacheRead:String(e.cost?.cacheRead??""),cacheWrite:String(e.cost?.cacheWrite??"")}}function at(e,t){return Object.values(e).some(e=>null===iV(e))||Object.values(t).some(e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e)))}function as({biz:e,provider:t,model:s,onChange:i,onInputState:a}){let{t:l}=(0,b.Bd)("settings"),o=(0,r.useId)(),[c,d]=(0,r.useState)({contextWindow:iY(s.contextWindow),maxTokens:iY(s.maxTokens)}),[u,m]=(0,r.useState)(()=>ae(s)),{searchText:p,setSearchText:h,catalogOpen:g,setCatalogOpen:f,loadingCatalog:x,candidates:w,visibleCandidates:y,showAllCandidates:k,setShowAllCandidates:j,selectedCandidateKey:N,setSelectedCandidateKey:S}=function(e,t){let{t:s}=(0,b.Bd)("settings"),n=(0,X.G)(),i=(0,r.useRef)(0),[a,l]=(0,r.useState)(t),[o,c]=(0,r.useState)([]),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(!1),v=(0,r.useMemo)(()=>{let e=new Map,t=o.filter(e=>"exact"===e.match);for(let s of t.length?t:o)for(let t of s.sources){let n=JSON.stringify([s.referenceId,t.modelId,t.defaults]),r=e.get(n);r?r.sources.push(t):e.set(n,{item:s,sources:[t]})}let s=a.trim().toLocaleLowerCase();return[...e.entries()].map(([e,t])=>{let s=[...t.sources].sort((e,t)=>i8(t)-i8(e)||e.providerName.localeCompare(t.providerName)),n=s[0];return{key:e,item:t.item,source:n,equivalentSourceCount:s.length,recommended:n.official}}).sort((e,t)=>("exact"===e.item.match?0:"similar"===e.item.match?1:2)-("exact"===t.item.match?0:"similar"===t.item.match?1:2)||Number(t.recommended)-Number(e.recommended)||Number(t.source.modelId.toLocaleLowerCase()===s)-Number(e.source.modelId.toLocaleLowerCase()===s)||e.source.providerName.localeCompare(t.source.providerName))},[o,a]);return(0,r.useEffect)(()=>{let t=++i.current;if(!d)return;let r=window.setTimeout(()=>{g(!0),e.listCatalog({query:a.trim(),refresh:!1,page:{index:1,size:10}}).then(e=>{i.current===t&&c(e.models)}).catch(e=>{i.current===t&&(c([]),n.error(e instanceof Error?e.message:s("catalogSearchFailed")))}).finally(()=>{i.current===t&&g(!1)})},250);return()=>{window.clearTimeout(r),i.current===t&&(i.current+=1)}},[e,d,a,n,s]),{searchText:a,setSearchText:l,catalogOpen:d,setCatalogOpen:e=>{u(e),e||g(!1)},loadingCatalog:h,candidates:v,visibleCandidates:f?v:v.slice(0,6),showAllCandidates:f,setShowAllCandidates:x,selectedCandidateKey:m,setSelectedCandidateKey:p}}(e,s.modelId),C=new Map(s.thinkingLevels.map(e=>[e.level,e])),E=iB.find(e=>e.value===t.api)?.label??t.api;function M(e){i({...s,...e})}return(0,n.jsxs)("div",{className:"@container/model-editor space-y-6",children:[(0,n.jsxs)("div",{className:"grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[(0,n.jsxs)("div",{className:"grid gap-1 text-sm @[32rem]/model-editor:col-span-2",children:[(0,n.jsx)("label",{htmlFor:o,className:"font-medium",children:l("modelId")}),(0,n.jsx)(i6.uB,{shouldFilter:!1,loop:!0,className:"h-auto w-full overflow-visible rounded-none bg-transparent p-0 [&_[data-slot=command-input-wrapper]]:p-0 [&_[data-slot=input-group-addon]]:hidden",onKeyDown:e=>{"Escape"===e.key&&g&&(e.preventDefault(),e.stopPropagation(),f(!1))},children:(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(i6.G7,{id:o,value:p,onValueChange:e=>{h(e),M({modelId:e}),S(null),j(!1),f(!0)},placeholder:l("modelIdSearch"),"aria-label":l("modelId"),"aria-autocomplete":"list",className:"pr-9"}),(0,n.jsxs)(eW.AM,{open:g,onOpenChange:e=>{f(e),e&&j(!1)},children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm",title:l("chooseModel"),"aria-label":l("chooseModel"),"aria-busy":x,className:"absolute top-0.5 right-0.5 z-10",children:x?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(i4.A,{})})}),(0,n.jsx)(eW.hl,{align:"end",sideOffset:4,initialFocus:!1,finalFocus:!1,positionerClassName:"z-[120]",className:"w-[min(32rem,calc(100vw-2rem))] gap-0 p-0",children:(0,n.jsx)(i6.oI,{className:"max-h-[min(24rem,var(--available-height))] p-1",children:x&&0===w.length?(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:l("matchingCatalog")}):0===w.length?(0,n.jsx)(i6.xL,{className:"py-6 text-sm",children:l("noCatalogMatches")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(i6.L$,{className:"p-0",children:y.map(e=>(0,n.jsx)(i6.h_,{value:e.key,"data-checked":N===e.key?"true":void 0,className:"px-3 py-2",onSelect:()=>(function(e){let{item:t,source:n}=e,r={...s,modelId:n.modelId,name:t.name,...n.defaults};i(r),d({contextWindow:iY(r.contextWindow),maxTokens:iY(r.maxTokens)}),m(ae(r)),a({dirty:!1,invalid:!1}),h(n.modelId),S(e.key),j(!1),f(!1)})(e),children:(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("span",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("span",{className:"break-all font-mono text-sm font-semibold",children:e.source.modelId}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.source.providerName})]}),(0,n.jsxs)("span",{className:"mt-1 block text-xs text-muted-foreground",children:[e.item.name," \xb7"," ",l("contextAndOutput",{context:`${iY(e.source.defaults.contextWindow)}K`,output:`${iY(e.source.defaults.maxTokens)}K`})]}),(0,n.jsx)("span",{className:"mt-1 block text-xs text-muted-foreground",children:e.source.defaults.cost?`${l("priceInput",{price:`$${e.source.defaults.cost.input}`})} \xb7 ${l("priceOutput",{price:`$${e.source.defaults.cost.output}`})}${l("perMillionTokens")}`:l("priceMissing")})]})},e.key))}),!k&&w.length>y.length?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:()=>j(!0),children:l("moreConfigurations",{count:w.length-y.length})}):null]})})})]})]})}),s.modelId.trim()?null:(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("modelIdRequired")})]}),(0,n.jsxs)(iU,{label:l("modelName"),className:"@[32rem]/model-editor:col-span-2",children:[(0,n.jsx)(em.p,{value:s.name,onChange:e=>M({name:e.target.value})}),s.name.trim()?null:(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("modelNameRequired")})]}),[["contextWindow","contextLength"],["maxTokens","maximumOutput"]].map(([e,t])=>{let s=null===iV(c[e]);return(0,n.jsxs)(iU,{label:l(t),children:[(0,n.jsxs)(nC.MG,{children:[(0,n.jsx)(nC.iV,{"aria-label":l(t),inputMode:"decimal",value:c[e],"aria-invalid":s,"aria-describedby":s?`${o}-${e}-error`:void 0,onChange:t=>{var s;let n,r,i;return s=t.target.value,d(n={...c,[e]:s}),a({dirty:r=at(n,u),invalid:r}),void(null!==(i=iV(s))&&M({[e]:i}))}}),(0,n.jsx)(nC.Sq,{align:"inline-end",children:"K"})]}),s?(0,n.jsx)("span",{id:`${o}-${e}-error`,role:"alert",className:"text-xs text-destructive",children:l("capacityInvalid")}):null]},e)})]}),(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:l("capabilities")}),(0,n.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2 text-sm",children:[s.input.map(e=>(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-1",children:l("text"===e?"textInput":"imageInput")},e)),s.reasoning?(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-1",children:l("supportsThinking")}):null]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("inputAndThinking")}),(0,n.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:[["text","image"].map(e=>{let t=s.input.includes(e);return(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline","aria-pressed":t,onClick:()=>{t&&1===s.input.length||M({input:t?s.input.filter(t=>t!==e):[...s.input,e]})},children:[t?(0,n.jsx)(ep.A,{}):null,l("text"===e?"textInput":"imageInput")]},e)}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline","aria-pressed":s.reasoning,onClick:()=>M({reasoning:!s.reasoning,thinkingLevels:s.reasoning?[{level:"off",providerValue:null}]:[{level:"high",providerValue:null}]}),children:[s.reasoning?(0,n.jsx)(ep.A,{}):null,l("supportsThinking")]})]}),s.reasoning?(0,n.jsxs)("details",{className:"mt-4 border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-medium",children:l("thinkingMapping")}),(0,n.jsx)("div",{className:"mt-2 grid max-w-[40rem] gap-x-4 @[32rem]/model-editor:grid-cols-2",children:i7.map(([e,t])=>{let r=C.get(e);return(0,n.jsxs)("div",{className:"grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-2 border-b py-2",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm","aria-pressed":!!r,className:"justify-start",onClick:()=>{let t=r?s.thinkingLevels.filter(t=>t.level!==e):[...s.thinkingLevels,{level:e,providerValue:"off"===e?null:e}];t.length&&M({thinkingLevels:t})},children:[r?(0,n.jsx)(ep.A,{}):null,l(t)]}),(0,n.jsx)(em.p,{"aria-label":l("providerMapping",{level:l(t)}),disabled:!r||"off"===e,value:"off"===e?l("noMapping"):r?.providerValue??"",placeholder:e,onChange:t=>M({thinkingLevels:s.thinkingLevels.map(s=>s.level===e?{...s,providerValue:t.target.value||null}:s)})})]},e)})})]}):null]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("price")}),(0,n.jsxs)("div",{className:"mt-3 grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[i9.map(([e,t])=>{let r=""!==u[e]&&(!Number.isFinite(Number(u[e]))||0>Number(u[e]));return(0,n.jsxs)(iU,{label:l(t),children:[(0,n.jsx)(em.p,{inputMode:"decimal",value:u[e],"aria-invalid":r,onChange:t=>(function(e,t){let n={...u,[e]:t};m(n);let r=at(c,n);if(a({dirty:r,invalid:r}),Object.values(n).every(e=>""===e))return void M({cost:null});let i=Number(t);Number.isFinite(i)&&!(i<0)&&M({cost:{input:s.cost?.input??0,output:s.cost?.output??0,cacheRead:s.cost?.cacheRead??0,cacheWrite:s.cost?.cacheWrite??0,[e]:i}})})(e,t.target.value)}),r?(0,n.jsx)("span",{role:"alert",className:"text-xs text-destructive",children:l("priceInvalid")}):null]},e)}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",className:"justify-self-start",onClick:()=>{let e={input:"",output:"",cacheRead:"",cacheWrite:""};m(e),a({dirty:!0,invalid:at(c,e)}),M({cost:null})},children:l("clearPrice")})]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("advancedCompatibility")}),(0,n.jsxs)("div",{className:"mt-3 grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[(0,n.jsx)(iU,{label:l("apiOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(iH,{value:s.api??"",ariaLabel:l("apiOverride"),options:iB,placeholder:E?l("inheritServiceValue",{value:E}):l("inheritService"),onChange:e=>M({api:e||null})})}),(0,n.jsx)(iU,{label:l("baseUrlOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(em.p,{value:s.baseUrl??"","aria-label":l("baseUrlOverride"),placeholder:t.baseUrl?l("inheritServiceValue",{value:t.baseUrl}):l("inheritService"),onChange:e=>M({baseUrl:e.target.value||null})})}),(0,n.jsx)(iU,{label:l("modelHeaders"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(iW,{headers:s.headers,onChange:e=>M({headers:e}),placeholder:l("headerPlaceholder")})}),(0,n.jsx)(iU,{label:l("developerRole"),children:(0,n.jsx)(iG,{value:s.compat?.supportsDeveloperRole??null,ariaLabel:l("developerRole"),onChange:e=>M({compat:{supportsDeveloperRole:e,thinkingFormat:s.compat?.thinkingFormat??null,requiresReasoningContentOnAssistantMessages:s.compat?.requiresReasoningContentOnAssistantMessages??null}})})}),(0,n.jsx)(iU,{label:"Thinking Format",children:(0,n.jsx)(iH,{value:s.compat?.thinkingFormat??"",ariaLabel:"Thinking Format",options:iq.map(e=>({value:e,label:e})),onChange:e=>M({compat:{supportsDeveloperRole:s.compat?.supportsDeveloperRole??null,thinkingFormat:e||null,requiresReasoningContentOnAssistantMessages:s.compat?.requiresReasoningContentOnAssistantMessages??null}})})}),(0,n.jsx)(iU,{label:l("replayReasoning"),children:(0,n.jsx)(iG,{value:s.compat?.requiresReasoningContentOnAssistantMessages??null,ariaLabel:l("replayReasoning"),onChange:e=>M({compat:{supportsDeveloperRole:s.compat?.supportsDeveloperRole??null,thinkingFormat:s.compat?.thinkingFormat??null,requiresReasoningContentOnAssistantMessages:e}})})})]})]})]})}var an=s(66153),ar=s(95929);function ai({className:e,disabled:t,id:s,...i}){let{t:a}=(0,b.Bd)("common"),[l,o]=r.useState(!1),c=a(l?"hideSecret":"revealSecret");return(0,n.jsxs)("div",{className:"relative min-w-0",children:[(0,n.jsx)(em.p,{...i,id:s,disabled:t,type:"text",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,className:(0,C.cn)("pr-9",!l&&"[-webkit-text-security:disc]",e)}),(0,n.jsx)("button",{type:"button",className:"absolute top-1/2 right-1 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50","aria-label":c,"aria-controls":s,"aria-pressed":l,title:c,disabled:t,onClick:()=>o(e=>!e),children:l?(0,n.jsx)(an.A,{className:"size-3.5"}):(0,n.jsx)(ar.A,{className:"size-3.5"})})]})}function aa({provider:e,existingIds:t,isNew:s,onApply:i,onDelete:a,onClose:l,onDirtyChange:o}){let{t:c}=(0,b.Bd)("settings"),{confirm:d,dialog:u}=nF(),[m,p]=(0,r.useState)(()=>structuredClone(e)),h=JSON.stringify(m)!==JSON.stringify(e),g=!m.provider.trim()||t.includes(m.provider.trim()),f=m.provider||c("providerUnnamed");function x(e){p(t=>({...t,...e}))}async function v(){(!h||await d({title:c("discardServiceTitle"),description:c("discardServiceDescription"),confirmLabel:c("discardModelConfirm")}))&&l()}async function w(){await d({title:c("providerDeleteTitle"),description:c("providerDeleteDescription",{name:f,count:e.models.length})})&&a()}return(0,r.useEffect)(()=>(o(h),()=>o(!1)),[h,o]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||v()},children:(0,n.jsxs)(eN.hA,{className:"max-w-[40rem]",initialFocus:!1,children:[(0,n.jsxs)(eN.Hl,{className:"border-b px-4 py-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:c("serviceConnection")}),(0,n.jsx)(eN.uX,{children:c("serviceDraftScope",{count:e.models.length})})]}),(0,n.jsx)(eN._Y,{className:"max-h-[65dvh]",children:(0,n.jsxs)("div",{className:"space-y-5 p-4",children:[(0,n.jsxs)(iU,{label:c("serviceId"),children:[(0,n.jsx)(em.p,{value:m.provider,"aria-label":c("serviceId"),autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:c("providerIdExample"),"aria-invalid":g,onChange:e=>x({provider:e.target.value})}),g?(0,n.jsx)("span",{role:"alert",className:"text-xs text-destructive",children:c("serviceIdInvalid")}):null]}),(0,n.jsx)(iU,{label:c("serviceAddress"),children:(0,n.jsx)(em.p,{value:m.baseUrl??"",placeholder:"https://api.example.com/v1",onChange:e=>x({baseUrl:e.target.value||null})})}),(0,n.jsx)(iU,{label:c("providerApiType"),children:(0,n.jsx)(iH,{value:m.api??"",ariaLabel:c("providerApiType"),options:iB,onChange:e=>x({api:e||null})})}),(0,n.jsx)(iU,{label:c("serviceKey"),children:(0,n.jsx)(ai,{value:m.apiKey??"",onChange:e=>x({apiKey:e.target.value||null})})}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:c("providerAdvanced")}),(0,n.jsxs)("div",{className:"mt-3 space-y-3",children:[(0,n.jsx)(iU,{label:c("providerAuthHeader"),children:(0,n.jsx)(iG,{value:m.authHeader,ariaLabel:c("providerAuthHeader"),onChange:e=>x({authHeader:e})})}),(0,n.jsx)(iU,{label:c("providerHeaders"),children:(0,n.jsx)(iW,{headers:m.headers,onChange:e=>x({headers:e}),placeholder:c("headerPlaceholder")})})]})]})]})}),(0,n.jsxs)(eN.vu,{children:[s?null:(0,n.jsxs)(I.$,{type:"button",variant:"ghost",className:"mr-auto text-destructive hover:text-destructive",onClick:w,children:[(0,n.jsx)(et.A,{}),c("providerDelete")]}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:l,children:c("cancel",{ns:"common"})}),(0,n.jsx)(I.$,{type:"button",disabled:g||!h&&!s,onClick:()=>i(m),children:c("applyServiceDraft")})]})]})}),u]})}let al=a.Ik({}).strict(),ao=a.Yj().trim().min(1).max(128),ac=a.Yj().max(32768),ad=a.Ik({url:ac,label:ac.optional()}).strict(),au=a.Ik({provider:ao,name:ac,loggedIn:a.zM(),conflict:a.Yj().nullable()}).strict(),am=a.Ik({id:a.Yj().uuid(),type:a.k5(["text","secret","select","manual_code"]),message:ac,placeholder:ac.optional(),options:a.YO(a.Ik({id:ac,label:ac,description:ac.optional()}).strict()).optional()}).strict(),ap=a.gM("type",[a.Ik({type:a.eu("auth_url"),url:ac,instructions:ac.optional()}).strict(),a.Ik({type:a.eu("device_code"),userCode:ac,verificationUri:ac}).strict(),a.Ik({type:a.eu("info"),message:ac,links:a.YO(ad).optional()}).strict(),a.Ik({type:a.eu("progress"),message:ac}).strict()]),ah=a.Ik({loginId:a.Yj().uuid(),provider:ao,status:a.k5(["running","completed","cancelled","error"]),notice:ap.nullable(),prompt:am.nullable(),message:a.Yj().nullable()}).strict(),ag=Object.freeze({list:(0,l.Vc)({path:"model-auth/list",inputSchema:al,outputSchema:a.Ik({providers:a.YO(au)}).strict()}),start:(0,l.Vc)({path:"model-auth/start",inputSchema:a.Ik({loginId:a.Yj().uuid(),provider:ao}).strict(),outputSchema:al}),respond:(0,l.Vc)({path:"model-auth/respond",inputSchema:a.Ik({loginId:a.Yj().uuid(),promptId:a.Yj().uuid(),value:ac}).strict(),outputSchema:al}),cancel:(0,l.Vc)({path:"model-auth/cancel",inputSchema:a.Ik({loginId:a.Yj().uuid()}).strict(),outputSchema:al}),logout:(0,l.Vc)({path:"model-auth/logout",inputSchema:a.Ik({provider:ao}).strict(),outputSchema:al}),state:(0,l._G)({path:"model-auth/state",bodySchema:ah})});function af(e){try{let t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}}function ax(e){let t=af(e);t&&window.open(t,"_blank","noopener,noreferrer")}async function ab(e){await navigator.clipboard.writeText(e)}function av({prompt:e,submitting:t,onRespond:s}){let{t:i}=(0,b.Bd)("settings"),[a,l]=(0,r.useState)(""),o="select"!==e.type||a.length>0;return(0,n.jsxs)("form",{className:"grid gap-3",onSubmit:n=>{n.preventDefault(),o&&!t&&s(e.id,a)},children:[(0,n.jsx)(iU,{label:e.message,children:"select"===e.type?(0,n.jsx)(iH,{value:a,ariaLabel:e.message,placeholder:e.placeholder??i("accountChooseOption"),options:(e.options??[]).map(e=>({value:e.id,label:e.description?`${e.label} — ${e.description}`:e.label})),onChange:l}):"secret"===e.type?(0,n.jsx)(ai,{value:a,placeholder:e.placeholder,disabled:t,onChange:e=>l(e.target.value)}):(0,n.jsx)(em.p,{value:a,placeholder:e.placeholder,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,disabled:t,onChange:e=>l(e.target.value)})}),(0,n.jsx)(I.$,{type:"submit",disabled:!o||t,className:"justify-self-end",children:i("accountContinue")})]})}function aw({notice:e,onCopy:t,onOpenUrl:s}){let{t:r}=(0,b.Bd)("settings"),i="auth_url"===e.type?[{url:e.url}]:"device_code"===e.type?[{url:e.verificationUri}]:"info"===e.type?e.links??[]:[];return(0,n.jsxs)("div",{className:"space-y-3",children:["auth_url"===e.type&&e.instructions?(0,n.jsx)("p",{className:"whitespace-pre-wrap text-sm",children:e.instructions}):null,"info"===e.type||"progress"===e.type?(0,n.jsx)("p",{className:"whitespace-pre-wrap text-sm",role:"status",children:e.message}):null,"device_code"===e.type?(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-lg border p-3",children:[(0,n.jsx)("span",{className:"text-sm",children:r("accountDeviceCode")}),(0,n.jsx)("code",{className:"select-all break-all text-lg font-semibold",children:e.userCode}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void t(e.userCode),children:r("accountCopyCode")})]}):null,i.map((e,i)=>af(e.url)?(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("p",{className:"break-all text-sm text-muted-foreground",children:e.url}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>s(e.url),children:e.label??r("accountOpenLink")}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>void t(e.url),children:r("accountCopyLink")})]})]},`${i}:${e.url}`):(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:r("accountInvalidLink")},i))]})}function ay({open:e,connected:t,providers:s,state:r,loading:i,submitting:a,error:l,onClose:o,onStart:c,onRespond:d,onCopy:u,onOpenUrl:m,onRetry:p}){let{t:h}=(0,b.Bd)("settings"),g=r?.status==="running";return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||o()},children:(0,n.jsxs)(eN.hA,{className:"max-w-lg",children:[(0,n.jsx)(eN.Hl,{className:"border-b p-4 pr-12",children:(0,n.jsx)(eN.YM,{children:r?s.find(e=>e.provider===r.provider)?.name??r.provider:h("accountLogin")})}),(0,n.jsx)(eN._Y,{className:"max-h-[65dvh]",children:(0,n.jsxs)("div",{className:"space-y-4 p-4",children:[l?(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive",children:l}):null,r?.message?(0,n.jsx)("p",{role:"error"===r.status?"alert":"status",className:"whitespace-pre-wrap text-sm",children:r.message}):null,r&&"cancelled"!==r.status&&"error"!==r.status?null:i?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:h("accountLoadingProviders")}):(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:h("accountChooseProvider")}),s.length?null:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:h("accountNoProviders")}),s.map(e=>(0,n.jsxs)("div",{className:"grid gap-1",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",className:"h-auto min-h-10 justify-between whitespace-normal text-left",disabled:!t||!!e.conflict,onClick:()=>void c(e.provider),children:[(0,n.jsx)("span",{children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.loggedIn?h("accountRelogin"):h("accountLogin")})]}),e.conflict?(0,n.jsx)("p",{className:"text-sm text-destructive",children:e.conflict}):null]},e.provider))]}),g&&r.notice?(0,n.jsx)(aw,{notice:r.notice,onCopy:u,onOpenUrl:m}):null,g&&r.prompt?(0,n.jsx)(av,{prompt:r.prompt,submitting:a||!t,onRespond:d},r.prompt.id):null,g&&!r.prompt?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:h("accountWaiting")}):null,r?.status==="completed"?(0,n.jsx)("p",{role:"status",className:"text-sm",children:h("accountLoggedIn")}):null]})}),(0,n.jsxs)(eN.vu,{children:[l&&!g?(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:i,onClick:p,children:h("retry",{ns:"common"})}):null,(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:o,children:h(g?"cancel":"close",{ns:"common"})})]})]})})}function ak({account:e,existingIds:t,onAdd:s,onClose:i}){let{t:a}=(0,b.Bd)("settings"),[l,o]=(0,r.useState)(""),[c,d]=(0,r.useState)([]),u=e.models.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(l.toLocaleLowerCase()));return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||i()},children:(0,n.jsxs)(eN.hA,{className:"max-w-xl",children:[(0,n.jsx)(eN.Hl,{className:"border-b p-4 pr-12",children:(0,n.jsx)(eN.YM,{children:a("modelAddToService",{name:e.name})})}),(0,n.jsx)("div",{className:"p-4 pb-2",children:(0,n.jsx)(em.p,{value:l,"aria-label":a("accountModelSearch"),placeholder:a("accountModelSearch"),onChange:e=>o(e.target.value)})}),(0,n.jsx)(eN._Y,{className:"max-h-[55dvh]",children:(0,n.jsxs)("div",{className:"space-y-1 px-4 pb-4",children:[u.map(e=>{let s=t.includes(e.modelId);return(0,n.jsxs)("label",{className:"flex min-h-14 cursor-pointer items-center gap-3 rounded-lg px-3 py-2 hover:bg-accent",children:[(0,n.jsx)("input",{type:"checkbox",className:"size-4 shrink-0 accent-primary",checked:s||c.includes(e.modelId),disabled:s,onChange:t=>d(s=>t.target.checked?[...s,e.modelId]:s.filter(t=>t!==e.modelId))}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block break-words text-sm font-medium",children:e.name}),(0,n.jsxs)("span",{className:"block break-all text-xs text-muted-foreground",children:[e.modelId," \xb7 ",iY(e.contextWindow)," K"]})]}),s?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:a("accountModelAdded")}):null]},e.modelId)}),u.length?null:(0,n.jsx)("p",{className:"py-6 text-center text-sm text-muted-foreground",children:a("accountNoModels")})]})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:i,children:a("accountAddLater")}),(0,n.jsx)(I.$,{type:"button",disabled:!c.length,onClick:()=>s(c),children:a("accountAddSelected",{count:c.length})})]})]})})}let aj=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function aN({model:e,account:t,overrides:s,onChange:i,onInputState:a}){let{t:l}=(0,b.Bd)("settings"),[o,c]=(0,r.useState)(()=>({contextWindow:void 0===s.contextWindow?"":iY(s.contextWindow),maxTokens:void 0===s.maxTokens?"":iY(s.maxTokens),...Object.fromEntries(aj.map(([e])=>[e,s.cost?.[e]===void 0?"":String(s.cost[e])]))})),d=e=>""!==e&&null===iV(e),u=e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e));function m(e,t){let n={...o,[e]:t};c(n);let r=d(n.contextWindow)||d(n.maxTokens)||aj.some(([e])=>u(n[e]));if(a({dirty:r,invalid:r}),"contextWindow"===e||"maxTokens"===e){if(d(t))return;let n={...s};""===t?delete n[e]:n[e]=iV(t),i(n)}else{if(aj.some(([e])=>u(n[e])))return;let e={...s};aj.every(([e])=>""===n[e])?delete e.cost:e.cost=Object.fromEntries(aj.filter(([e])=>""!==n[e]).map(([e])=>[e,Number(n[e])])),i(e)}}if(!e)return(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("accountModelUnavailable")});let p=e.cost?{...e.cost,...s.cost}:s.cost;return(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-6",children:[(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)("span",{children:l(t?.loggedIn?"accountLoggedIn":"accountLoggedOut")}),t?.subscription?(0,n.jsx)("span",{className:"rounded-md bg-muted px-2",children:l("accountSubscription")}):null]}),(0,n.jsxs)("dl",{className:"grid gap-4 sm:grid-cols-2",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("contextLength")}),(0,n.jsxs)("dd",{className:"mt-1 text-lg font-semibold",children:[iY(s.contextWindow??e.contextWindow)," K"]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("maximumOutput")}),(0,n.jsxs)("dd",{className:"mt-1 text-lg font-semibold",children:[iY(s.maxTokens??e.maxTokens)," K"]})]}),(0,n.jsxs)("div",{className:"sm:col-span-2",children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("capabilities")}),(0,n.jsx)("dd",{className:"mt-1 text-sm",children:[...e.input.map(e=>l("image"===e?"imageInput":"textInput")),...e.reasoning?[l("supportsThinking")]:[]].join(" \xb7 ")})]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("accountReferencePrice")}),(0,n.jsx)("div",{className:"mt-3 text-sm text-muted-foreground",children:p?aj.map(([e,t])=>(0,n.jsxs)("p",{children:[l(t),": ",void 0===p[e]?"—":`$${p[e]}`]},e)):l("priceMissing")})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("accountAdjustParameters")}),(0,n.jsxs)("div",{className:"mt-4 space-y-4",children:[(0,n.jsx)("div",{className:"grid gap-3 sm:grid-cols-2",children:["contextWindow","maxTokens"].map(t=>(0,n.jsxs)(iU,{label:`${l("contextWindow"===t?"contextLength":"maximumOutput")} (K)`,children:[(0,n.jsx)(em.p,{value:o[t],placeholder:iY(e[t]),inputMode:"decimal","aria-invalid":d(o[t]),onChange:e=>m(t,e.target.value)}),d(o[t])?(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("capacityInvalid")}):null]},t))}),(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-medium",children:l("price")}),(0,n.jsx)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:aj.map(([t,s])=>(0,n.jsxs)(iU,{label:l(s),children:[(0,n.jsx)(em.p,{value:o[t],inputMode:"decimal",placeholder:String(e.cost?.[t]??""),"aria-invalid":u(o[t]),onChange:e=>m(t,e.target.value)}),u(o[t])?(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("priceInvalid")}):null]},t))})]}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>{c({contextWindow:"",maxTokens:"",input:"",output:"",cacheRead:"",cacheWrite:""}),i({}),a({dirty:!1,invalid:!1})},children:l("accountRestoreDefaults")})]})]})]})}var aI=s(34506);function aS({name:e,hasAccount:t,loggedIn:s,hasCustom:i,onCustomSettings:a,onLogin:l,onLogout:o}){let{t:c}=(0,b.Bd)("settings"),[d,u]=(0,r.useState)(!1),m=(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":c("serviceSettingsNamed",{name:e}),onClick:t?void 0:a,children:(0,n.jsx)(aI.A,{})});function p(e){u(!1),e()}return t?(0,n.jsxs)(eW.AM,{open:d,onOpenChange:u,children:[(0,n.jsx)(eW.Wv,{render:m}),(0,n.jsxs)(eW.hl,{align:"end",positionerClassName:"z-[120]",className:"w-52 gap-1 p-1",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"justify-start",onClick:()=>p(l),children:c(s?"accountRelogin":"accountLogin")}),s?(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"justify-start text-destructive",onClick:()=>p(o),children:c("accountLogout")}):null,i?(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"justify-start",onClick:()=>p(a),children:c("accountCustomSettings")}):null]})]}):m}function aC({providerId:e,custom:t,account:s,accountModels:r,query:i,modelKeys:a,selectedCustomIndex:l,selectedAccountId:o,presets:c,onSelectCustom:d,onSelectAccount:u,onCustomSettings:m,onAddCustom:p,onAddAccount:h,onLogin:g,onLogout:f,onGroupRef:x,onRowRef:v}){let{t:w}=(0,b.Bd)("settings"),y=(t?e:s?.name)||e||w("providerUnnamed"),k=r.filter(e=>!t?.models.some(t=>t.modelId===e.modelId)),j=[...(t?.models??[]).map((e,t)=>({key:a[t],modelId:e.modelId,name:e.name,model:e,selected:l===t,select:()=>d(t)})),...k.map(t=>{let n=s?.models.find(e=>e.modelId===t.modelId);return{key:`account:${e}:${t.modelId}`,modelId:t.modelId,name:n?.name??t.modelId,model:n?{...n,...t.overrides}:void 0,selected:o===t.modelId,select:()=>u(t.modelId)}})],N=j.filter(t=>`${e} ${y} ${s?.name??""} ${t.name} ${t.modelId}`.toLocaleLowerCase().includes(i.toLocaleLowerCase()));if(i&&!N.length&&!`${e} ${y} ${s?.name??""}`.toLocaleLowerCase().includes(i.toLocaleLowerCase()))return null;let S=!!s||r.length>0;return(0,n.jsxs)("section",{ref:x,className:"mb-3",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-foreground",children:[(0,n.jsx)(eE.A,{"aria-hidden":"true",className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold",title:s?.name,children:y}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:j.length}),(0,n.jsx)(aS,{name:y,hasAccount:S,loggedIn:s?.loggedIn??!1,hasCustom:!!t,onCustomSettings:m,onLogin:g,onLogout:f})]}),(0,n.jsxs)("div",{className:"space-y-1",children:[N.map(t=>(0,n.jsxs)("button",{ref:e=>v(t.key,e),type:"button","aria-current":t.selected?"true":void 0,className:(0,C.cn)("flex min-h-14 w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",t.selected&&"bg-accent text-accent-foreground"),onClick:t.select,children:[(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",children:t.name||t.modelId||w("modelUnnamed")}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:t.model?`${iY(t.model.contextWindow)} K \xb7 ${w(t.model.input.includes("image")?"imageInput":"textInput")}`:w("accountModelUnavailableShort")})]}),c.some(s=>s.provider===e&&s.modelId===t.modelId)?(0,n.jsx)(i3.A,{className:"size-4 shrink-0 text-muted-foreground"}):null]},t.key)),S?(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",className:"mt-1 w-full border border-dashed border-input","aria-label":w("modelAddToService",{name:s?.name??y}),onClick:h,children:[(0,n.jsx)(U.A,{}),w("modelAdd")]}):null,t?(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",className:"mt-1 w-full border border-dashed border-input","aria-label":w("modelAddToService",{name:y}),onClick:p,children:[(0,n.jsx)(U.A,{}),S?w("accountCustomModel"):null]}):null]})]})}let aE={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function aM({biz:e,connectionReady:t,providers:s,accounts:i,accountModels:a,onAccountModelsChange:l,onRefreshAccounts:o,savedModels:c,savedProviders:d,presets:u,resetVersion:m,onChange:p,onPresetsChange:h,onInputState:g,onServiceDirtyChange:f}){let{t:x}=(0,b.Bd)("settings"),{confirm:v,dialog:w}=nF(),y=(0,X.G)(),[k,j]=(0,r.useState)(null),[N,S]=(0,r.useState)(null),[E,M]=(0,r.useState)(!1),[z,$]=(0,r.useState)(()=>new Set),R=function(e,t){let{appSocket:s}=(0,ei.gM)(),n=(0,r.useMemo)(()=>({list:async()=>(await s.request(ag.list,{})).providers,async start(e,t){await s.request(ag.start,{loginId:e,provider:t})},async respond(e,t,n){await s.request(ag.respond,{loginId:e,promptId:t,value:n})},async cancel(e){await s.request(ag.cancel,{loginId:e})},async logout(e){await s.request(ag.logout,{provider:e})},subscribe:e=>s.subscribe(ag.state,e)}),[s]),{t:i}=(0,b.Bd)("settings"),a=(0,X.G)(),[l,o]=(0,r.useState)(!1),[c,d]=(0,r.useState)([]),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(!1),[x,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(null),k=(0,r.useRef)(e),j=(0,r.useRef)(null),N=(0,r.useRef)(null),I=(0,r.useRef)(null),S=(0,r.useRef)(null),C=(0,r.useRef)(0),E=(0,r.useRef)(t);function M(){let e=j.current;j.current=null,N.current=null,I.current=null,S.current?.(),S.current=null,e?.status==="running"&&n.cancel(e.loginId).catch(e=>{console.warn("[Pi Desk][ModelAuth] 取消登录失败",{message:e instanceof Error?e.message:String(e)})})}function z(){C.current+=1,M(),o(!1)}async function A(){let e=j.current;if(!e||"completed"!==e.status||I.current)return;I.current=e.loginId,f(!0),y(null);let t=()=>j.current?.loginId===e.loginId;try{await E.current(e.provider,t),t()&&z()}catch(e){t()&&y(e instanceof Error?e.message:i("accountRefreshFailed"))}finally{t()&&(I.current=null,f(!1))}}async function $(e){if(!k.current)return void y(i("accountConnectionNotReady"));if(j.current?.status==="running")return;M();let t={loginId:crypto.randomUUID(),provider:e,status:"running",notice:null,prompt:null,message:null};j.current=t,m(t),y(null),v(null),S.current=n.subscribe(e=>{j.current?.loginId===e.loginId&&((j.current.prompt?.id!==e.prompt?.id||"running"!==e.status)&&(N.current=null,v(null)),j.current=e,m(e),y("error"!==e.status||e.message?null:i("accountLoginFailed")),"completed"===e.status&&A())});try{await n.start(t.loginId,e)}catch(e){if(j.current?.loginId!==t.loginId||"running"!==j.current.status)return;M(),m(null),y(e instanceof Error?e.message:i("accountLoginFailed"))}}async function R(e,t){let s=j.current;if(!k.current||!s||"running"!==s.status||s.prompt?.id!==e||N.current)return;let r={loginId:s.loginId,promptId:e};N.current=r,v(e),y(null);try{await n.respond(s.loginId,e,t)}catch(t){j.current?.loginId===s.loginId&&j.current.prompt?.id===e&&y(t instanceof Error?t.message:i("accountLoginFailed"))}finally{N.current===r&&(N.current=null,v(null))}}return(0,r.useEffect)(()=>{E.current=t},[t]),(0,r.useEffect)(()=>()=>{C.current+=1;let e=j.current;j.current=null,S.current?.(),e?.status==="running"&&n.cancel(e.loginId).catch(()=>void 0)},[n]),(0,r.useEffect)(()=>{k.current=e;let t=j.current;if(e||t?.status!=="running")return;j.current=null,N.current=null,S.current?.(),S.current=null,n.cancel(t.loginId).catch(()=>void 0);let s=C.current;queueMicrotask(()=>{C.current===s&&(m(null),v(null),y(i("accountDisconnected")))})},[e,n,i]),{open:l,providers:c,state:u,loading:p||g,submitting:null!==x&&x===u?.prompt?.id,error:w,show:function(e){if(z(),m(null),y(null),v(null),f(!1),o(!0),!k.current){h(!1),y(i("accountConnectionNotReady"));return}h(!0);let t=++C.current;n.list().then(s=>{C.current===t&&(d(s),e&&s.some(t=>t.provider===e&&!t.conflict)&&$(e))}).catch(e=>{C.current===t&&y(e instanceof Error?e.message:i("accountLoginFailed"))}).finally(()=>{C.current===t&&h(!1)})},close:z,start:$,respond:R,finish:A,async logout(e){if(!k.current)throw Error(i("accountConnectionNotReady"));await n.logout(e)},async copy(e){try{await ab(e),a.success(i("accountCopied"))}catch{a.error(i("accountCopyFailed"))}},openUrl:ax}}(t,async(e,t)=>{await o(),t()&&S(e)}),P=function(e,t,s,n){let[i,a]=(0,r.useState)(()=>{let t=e.findIndex(e=>e.models.length>0);return t<0?null:{providerIndex:t,modelIndex:0}}),[l,o]=(0,r.useState)(!1),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(()=>e.map((e,t)=>e.models.map((e,s)=>`${t}:${s}`))),p=(0,r.useRef)(0),h=(0,r.useRef)(new Map(e.flatMap((e,t)=>e.models.map((s,n)=>[`${t}:${n}`,{provider:e.provider,modelId:s.modelId}])))),[g,f]=(0,r.useState)({}),[x,b]=(0,r.useState)(null),[v,w]=(0,r.useState)(!1),y=(0,r.useRef)(e);function k(e){f(t=>Object.fromEntries(Object.entries(t).filter(([t])=>!e.includes(t))))}function j(e,s=u){let n=[];e.forEach((e,t)=>{e.models.forEach((r,i)=>{let a=h.current.get(s[t][i]),l={provider:e.provider.trim(),modelId:r.modelId.trim()};a&&(a.provider!==l.provider||a.modelId!==l.modelId)&&n.push({from:a,to:l})})}),t(e,n)}function N(){b(null),w(!1)}return(0,r.useEffect)(()=>{y.current=e},[e]),(0,r.useEffect)(()=>{queueMicrotask(()=>{let e=y.current;h.current=new Map(e.flatMap((e,t)=>e.models.map((s,n)=>[`${t}:${n}`,{provider:e.provider,modelId:s.modelId}]))),f({}),m(e.map((e,t)=>e.models.map((e,s)=>`${t}:${s}`))),a(t=>{if(t&&e[t.providerIndex]?.models[t.modelIndex])return t;let s=e.findIndex(e=>e.models.length);return s<0?null:{providerIndex:s,modelIndex:0}})})},[n]),(0,r.useEffect)(()=>{let e=Object.values(g);s({dirty:e.some(e=>e.dirty),invalid:e.some(e=>e.invalid)})},[g,s]),{selection:i,mobileDetail:l,query:c,setQuery:d,modelKeys:u,serviceIndex:x,newService:v,openService:e=>{b(e),w(null===e)},closeService:N,applyService:t=>{v?(j([...e,t],[...u,[]]),m(e=>[...e,[]])):j(e.map((e,s)=>s===x?t:e)),N()},deleteService:()=>{if(null===x)return;k(u[x]);let t=e.filter((e,t)=>t!==x);j(t,u.filter((e,t)=>t!==x)),m(e=>e.filter((e,t)=>t!==x)),a(e=>{if(!e||e.providerIndex===x){let e=t.findIndex(e=>e.models.length);return e<0?null:{providerIndex:e,modelIndex:0}}return e.providerIndex>x?{...e,providerIndex:e.providerIndex-1}:e}),o(!1),N()},addModel:t=>{let s=e[t],n=`new-${++p.current}`;j(e.map((e,s)=>s===t?{...e,models:[...e.models,{modelId:"",name:"",api:null,baseUrl:null,reasoning:!1,thinkingLevels:[{level:"off",providerValue:null}],input:["text"],contextWindow:128e3,maxTokens:16384,cost:null,headers:{},compat:null}]}:e),u.map((e,s)=>s===t?[...e,n]:e)),m(e=>e.map((e,s)=>s===t?[...e,n]:e)),a({providerIndex:t,modelIndex:s.models.length}),d(""),o(!0)},selectModel:(e,t)=>{a({providerIndex:e,modelIndex:t}),o(!0)},backToList:()=>{o(!1),d("")},updateModel:function(t,s,n){j(e.map((e,r)=>r===t?{...e,models:e.models.map((e,t)=>t===s?n:e)}:e))},deleteModel:(t,s)=>{k([u[t][s]]);let n=e.map((e,n)=>n===t?{...e,models:e.models.filter((e,t)=>t!==s)}:e);j(n,u.map((e,n)=>n===t?e.filter((e,t)=>t!==s):e)),m(e=>e.map((e,n)=>n===t?e.filter((e,t)=>t!==s):e)),a(e=>{if(!e||e.providerIndex!==t)return e;if(e.modelIndex===s){if(n[t].models.length)return{providerIndex:t,modelIndex:Math.min(s,n[t].models.length-1)};let e=n.findIndex(e=>e.models.length);return e<0?null:{providerIndex:e,modelIndex:0}}return e.modelIndex>s?{...e,modelIndex:e.modelIndex-1}:e}),o(!1)},updateInputState:(e,t)=>f(s=>({...s,[e]:t}))}}(s,p,g,m),{selection:D,mobileDetail:T,query:O,setQuery:L,modelKeys:F,serviceIndex:B,newService:q}=P,_=(0,r.useRef)(new Map),W=(0,r.useRef)(new Map),[Y,V]=(0,r.useState)(!1),[K,H]=(0,r.useState)("off"),G=a.find(e=>e.provider===k?.provider&&e.modelId===k?.modelId)??(s.some(e=>e.models.length)?void 0:a[0]),J=i.find(e=>e.provider===G?.provider),Q=J?.models.find(e=>e.modelId===G?.modelId),Z=!!G,ee=!Z&&D?s[D.providerIndex]:null,es=!Z&&D?ee?.models[D.modelIndex]:null,en=Z?E:T&&!!es,er=Z?Q?.name??G?.modelId:es?.name||es?.modelId||x("modelUnnamed"),ea=G?.provider||ee?.provider||x("providerUnnamed"),el=i.find(e=>e.provider===N),eo=[...new Set([...s.map(e=>e.provider),...i.map(e=>e.provider),...a.map(e=>e.provider)])],ec=e=>`account:${e.provider}:${e.modelId}`,ed=new Set(a.map(ec)),eu=new Set([...z].filter(e=>ed.has(e)));G&&eu.add(ec(G)),(eu.size!==z.size||G&&!z.has(ec(G)))&&$(eu);let[ep,eh]=(0,r.useState)(()=>new Set),eg=D?F[D.providerIndex]?.[D.modelIndex]:void 0,ef=new Set(F.flat()),ex=new Set([...ep].filter(e=>ef.has(e)));eg&&ex.add(eg),(ex.size!==ep.size||eg&&!ep.has(eg))&&eh(ex);let eb=Z?c.find(e=>e.provider===G?.provider&&e.modelId===G.modelId):ee&&es&&d.some(e=>e.provider===ee.provider&&e.models.some(e=>e.modelId===es.modelId))?c.find(e=>e.provider===ee.provider&&e.modelId===es.modelId):void 0;async function ev(){if(G){await v({title:x("accountRemoveTitle"),description:x("accountRemoveDescription",{name:er})})&&(l(a.filter(e=>e!==G)),P.updateInputState(ec(G),{dirty:!1,invalid:!1}),j(null),M(!1));return}D&&es&&await v({title:x("modelDeleteTitle"),description:x("modelDeleteDescription",{name:es.name||es.modelId||x("modelUnnamed")})})&&P.deleteModel(D.providerIndex,D.modelIndex)}async function ew(e){if(await v({title:x("accountLogoutTitle"),description:x("accountLogoutDescription",{name:i.find(t=>t.provider===e)?.name??e}),confirmLabel:x("accountLogout")}))try{await R.logout(e),await o()}catch(e){y.error(e instanceof Error?e.message:x("accountLogoutFailed"))}}return(0,n.jsxs)("section",{className:"@container/models h-full min-h-0 overflow-hidden bg-card",children:[(0,n.jsxs)("div",{className:"grid h-full min-h-0 grid-cols-1 @[48rem]/models:grid-cols-[15rem_minmax(0,1fr)]",children:[(0,n.jsxs)("aside",{"aria-label":x("providerList"),className:(0,C.cn)("min-h-0 min-w-0 flex-col bg-sidebar @[48rem]/models:flex @[48rem]/models:border-r",en?"hidden":"flex"),children:[(0,n.jsx)("div",{className:"shrink-0 p-3",children:(0,n.jsx)(em.p,{value:O,"aria-label":x("modelSearch"),placeholder:x("modelSearch"),onChange:e=>L(e.target.value)})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto px-2 pb-3",children:[eo.map(e=>{let t=s.findIndex(t=>t.provider===e);return(0,n.jsx)(aC,{providerId:e,custom:s[t],account:i.find(t=>t.provider===e),accountModels:a.filter(t=>t.provider===e),query:O,modelKeys:F[t]??[],selectedCustomIndex:Z||D?.providerIndex!==t?null:D.modelIndex,selectedAccountId:G?.provider===e?G.modelId:null,presets:u,onSelectCustom:e=>{j(null),P.selectModel(t,e)},onSelectAccount:t=>{j({provider:e,modelId:t}),M(!0),$(s=>new Set([...s,ec({provider:e,modelId:t})]))},onCustomSettings:()=>P.openService(t),onAddCustom:()=>{j(null),P.addModel(t)},onAddAccount:()=>{let t;return t=i.find(t=>t.provider===e),void(t?.loggedIn?S(e):R.show(e))},onLogin:()=>R.show(e),onLogout:()=>void ew(e),onGroupRef:e=>{t<0||(e?_.current.set(t,e):_.current.delete(t))},onRowRef:(e,t)=>{t?W.current.set(e,t):W.current.delete(e)}},e)}),eo.length?null:(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:x("providerEmpty")})]}),(0,n.jsxs)("div",{className:"flex shrink-0 gap-2 border-t p-3",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>P.openService(null),children:[(0,n.jsx)(U.A,{}),x("accountCustomApi")]}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>R.show(),children:[(0,n.jsx)(i5.A,{}),x("accountLogin")]})]})]}),(0,n.jsx)("section",{"aria-label":x("modelsHeading"),className:(0,C.cn)("min-h-0 min-w-0 flex-col @[48rem]/models:flex",en?"flex":"hidden"),children:Z||es&&D?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2 @[48rem]/models:hidden",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":x("backModelList"),onClick:function(){if(G){M(!1),window.requestAnimationFrame(()=>{let e=W.current.get(ec(G));e?.scrollIntoView({block:"nearest"}),e?.focus({preventScroll:!0})});return}P.backToList(),window.requestAnimationFrame(()=>{if(!D)return;let e=F[D.providerIndex]?.[D.modelIndex];_.current.get(D.providerIndex)?.scrollIntoView({block:"nearest"}),W.current.get(e)?.scrollIntoView({block:"nearest"}),W.current.get(e)?.focus({preventScroll:!0})})},children:(0,n.jsx)(A.A,{})}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",title:J?.name??ea,children:J?.name??ea}),(0,n.jsx)(aS,{name:ea,hasAccount:i.some(e=>e.provider===ea)||a.some(e=>e.provider===ea),loggedIn:i.find(e=>e.provider===ea)?.loggedIn??!1,hasCustom:s.some(e=>e.provider===ea),onCustomSettings:()=>P.openService(s.findIndex(e=>e.provider===ea)),onLogin:()=>R.show(ea),onLogout:()=>void ew(ea)})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 @[48rem]/models:p-6",children:[(0,n.jsxs)("div",{className:"mb-5 flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"min-w-0 break-all text-lg font-semibold",children:er}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:!eb,title:eb?void 0:x("saveBeforePreset"),onClick:()=>{H(eb?.thinkingLevels[0]??"off"),V(!0)},children:[(0,n.jsx)(i3.A,{}),x("addModelPreset")]}),(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm",className:"text-destructive hover:text-destructive","aria-label":Z?`${x("accountRemove")} ${er}`:x("modelDeleteNamed",{name:er}),onClick:ev,children:(0,n.jsx)(et.A,{})})}),(0,n.jsx)(tU.ZI,{children:x(Z?"accountRemove":"modelDelete")})]})]})]}),a.map(e=>{let t=ec(e);if(!eu.has(t))return null;let s=i.find(t=>t.provider===e.provider);return(0,n.jsx)("div",{hidden:!Z||G!==e,children:(0,n.jsx)(aN,{account:s,model:s?.models.find(t=>t.modelId===e.modelId),overrides:e.overrides,onChange:t=>l(a.map(s=>s===e?{...e,overrides:t}:s)),onInputState:e=>P.updateInputState(t,e)})},`${t}:${m}`)}),s.flatMap((t,s)=>t.models.map((r,i)=>{let a=!Z&&D?.providerIndex===s&&D.modelIndex===i,l=F[s]?.[i];return ex.has(l)?(0,n.jsx)("div",{hidden:!a,children:(0,n.jsx)(as,{biz:e,provider:t,model:r,onChange:e=>P.updateModel(s,i,e),onInputState:e=>P.updateInputState(l,e)})},`${l}:${m}`):null}))]})]}):(0,n.jsxs)("div",{className:"flex flex-col items-center gap-3 p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(eO.A,{className:"size-6"}),x("selectModelToEdit")]})})]}),(0,n.jsx)(ay,{open:R.open,connected:t,providers:R.providers,state:R.state,loading:R.loading,submitting:R.submitting,error:R.error,onClose:R.close,onStart:R.start,onRespond:R.respond,onCopy:R.copy,onOpenUrl:R.openUrl,onRetry:()=>R.state?.status==="completed"?void R.finish():R.show()}),el?(0,n.jsx)(ak,{account:el,existingIds:[...a.filter(e=>e.provider===el.provider).map(e=>e.modelId),...s.filter(e=>e.provider===el.provider).flatMap(e=>e.models.map(e=>e.modelId))],onAdd:function(e){if(!el)return;let t=e.filter(e=>!a.some(t=>t.provider===el.provider&&t.modelId===e)&&!s.some(t=>t.provider===el.provider&&t.models.some(t=>t.modelId===e))).map(e=>({provider:el.provider,modelId:e,overrides:{}}));l([...a,...t]),S(null)},onClose:()=>S(null)},el.provider):null,q||null!==B?(0,n.jsx)(aa,{provider:q?{provider:"",name:null,baseUrl:null,api:"openai-responses",apiKey:null,authHeader:null,headers:{},models:[]}:s[B],existingIds:s.filter((e,t)=>q||t!==B).map(e=>e.provider),isNew:q,onApply:P.applyService,onDelete:P.deleteService,onClose:P.closeService,onDirtyChange:f}):null,(0,n.jsx)(eN.YV,{open:Y,onOpenChange:V,children:(0,n.jsxs)(eN.hA,{children:[(0,n.jsx)(eN.Hl,{className:"border-b px-4 py-4 pr-12",children:(0,n.jsx)(eN.YM,{children:x("addModelPreset")})}),(0,n.jsx)(eN._Y,{children:(0,n.jsx)("div",{className:"p-4",children:(0,n.jsx)(iU,{label:x("thinkingLevel"),children:(0,n.jsx)(iH,{value:K,allowEmpty:!1,ariaLabel:x("presetThinkingNew"),options:(eb?.thinkingLevels??[]).map(e=>({value:e,label:x(aE[e])})),onChange:e=>H(e)})})})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:()=>V(!1),children:x("cancel",{ns:"common"})}),(0,n.jsx)(I.$,{type:"button",onClick:function(){eb&&(u.some(e=>e.provider===eb.provider&&e.modelId===eb.modelId&&e.thinkingLevel===K)||h([...u,{provider:eb.provider,modelId:eb.modelId,thinkingLevel:K,color:iL(u)}]),V(!1))},disabled:!eb,children:x("presetAdd")})]})]})}),w]})}let az={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function aA(e,t){return JSON.stringify([e,t])}function a$(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function aR({biz:e,presets:t,onDirtyChange:s}){let{t:i}=(0,b.Bd)("settings"),a=function(e,t){let{t:s}=(0,b.Bd)("settings"),n=(0,X.G)(),{confirm:i,dialog:a}=nF(),[l,o]=(0,r.useState)([]),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)([]),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)(!1),[x,v]=(0,r.useState)(!0),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(!1),[S,C]=(0,r.useState)(null),[E,M]=(0,r.useState)(null),[z,A]=(0,r.useState)(null),[$,R]=(0,r.useState)(0),[P,D]=(0,r.useState)(0),T=S===c&&null===z&&!w&&!k,O=(0,r.useRef)(!1),L=(0,r.useRef)(""),F=(0,r.useRef)(0),B=(0,r.useCallback)(e=>{O.current=e,t?.(e)},[t]);function q(e){m(e.models),f(null!==e.default),h(e.default??(e.models[0]?{provider:e.models[0].provider,modelId:e.models[0].modelId,thinkingLevel:e.models[0].thinkingLevels[0]}:null))}async function _(e){return!N&&(e===c||(!O.current||!!await i({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}))&&(F.current+=1,j(!0),d(e),!0))}async function W(){if(c&&T&&!w&&!k&&!N&&(!g||p)){I(!0);try{await e.replaceProjectDefault({cwd:c,default:g?p:null}),ij({cwd:c,default:g?p:null,models:u}),B(!1),n.success(g?s("projectDefaultSaved"):s("projectDefaultGlobalSaved"))}catch(e){n.error(e instanceof Error?e.message:s("projectDefaultSaveFailed"))}finally{I(!1)}}}return(0,r.useEffect)(()=>{let t=!1,n=r9.N$.safeParse((iu(),ii)),r=n.success?n.data.directories:null;return queueMicrotask(()=>{!t&&(M(null),v(!r),r&&(o(r),d(e=>e&&r.some(t=>t.cwd===e)?e:r[0]?.cwd??"")))}),(async()=>{try{let s=await e.listDirectories();if(t)return;o(s.directories),d(e=>e&&s.directories.some(t=>t.cwd===e)?e:s.directories[0]?.cwd??"")}catch(e){if(!t&&!r){let t=e instanceof Error?e.message:s("projectDirectoriesFailed");console.warn("[Pi Desk][ProjectModelDefault] 读取项目目录失败",{message:t}),M(t)}}finally{t||v(!1)}})(),()=>{t=!0}},[e,s,$]),(0,r.useEffect)(()=>{let t=!1,n=++F.current;function r(){return!t&&n===F.current}let i=L.current!==c;if(L.current=c,i&&B(!1),!c)return queueMicrotask(()=>{r()&&(m([]),h(null),f(!1),C(null),A(null),y(!1),j(!1))}),()=>{t=!0};let a=(iy(),iv.get(iw(c))??null);return queueMicrotask(()=>{r()&&(A(null),!O.current&&a&&(q(a),C(c)),y(!a&&!O.current),j(!!a||O.current))}),(async()=>{try{let t=await e.getProjectDefault(c);if(!r())return;O.current||q(t),C(c)}catch(e){if(r()){let t=e instanceof Error?e.message:s("projectDefaultFailed");console.warn("[Pi Desk][ProjectModelDefault] 读取项目模型配置失败",{cwd:c,message:t}),A(t)}}finally{r()&&(y(!1),j(!1))}})(),()=>{t=!0}},[e,c,s,B,P]),{directories:l,cwd:c,loadedCwd:S,models:u,selection:p,fixed:g,directoriesLoading:x,projectLoading:w,projectRefreshing:k,saving:N,projectReady:T,directoriesError:E,projectError:z,dialog:a,selectProject:_,changeFixed:function(e){T&&!N&&(B(!0),f(e))},selectModel:function(e){T&&!N&&(B(!0),h({provider:e.provider,modelId:e.modelId,thinkingLevel:e.thinkingLevels[0]}))},selectThinking:function(e){if(!T||N)return;let t=u.find(e=>e.provider===p?.provider&&e.modelId===p.modelId),s=t?.thinkingLevels.find(t=>t===e);p&&s&&(B(!0),h({...p,thinkingLevel:s}))},applyPreset:function(e){T&&!N&&(B(!0),h({provider:e.provider,modelId:e.modelId,thinkingLevel:e.thinkingLevel}))},retryDirectories:function(){R(e=>e+1)},retryProject:function(){F.current+=1,j(!0),D(e=>e+1)},save:W}}(e,s),[l,o]=(0,r.useState)(""),[c,d]=(0,r.useState)(!1),u=a.models.find(e=>e.provider===a.selection?.provider&&e.modelId===a.selection.modelId),m=t.filter(e=>a.models.some(t=>t.provider===e.provider&&t.modelId===e.modelId&&t.thinkingLevels.includes(e.thinkingLevel))),p=a.directories.filter(e=>e.cwd.toLocaleLowerCase().includes(l.trim().toLocaleLowerCase())),h=a.models.map(e=>({value:aA(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider})),g=!a.projectReady||a.saving,f=a.loadedCwd??a.cwd;async function x(e){await a.selectProject(e)&&d(!0)}return(0,n.jsxs)("section",{className:"@container/project-default h-full min-h-0 overflow-hidden bg-card",children:[(0,n.jsxs)("div",{className:"grid h-full min-h-0 grid-cols-1 @[48rem]/project-default:grid-cols-[18rem_minmax(0,1fr)]",children:[(0,n.jsxs)("aside",{"aria-label":i("projectList"),className:(0,C.cn)("min-h-0 min-w-0 flex-col bg-sidebar @[48rem]/project-default:flex @[48rem]/project-default:border-r",c&&a.cwd?"hidden":"flex"),children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 p-3",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:i("projectList")}),(0,n.jsx)(em.p,{value:l,"aria-label":i("projectSearch"),placeholder:i("projectSearch"),onChange:e=>o(e.target.value)})]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto px-2 pb-3",children:a.directoriesLoading&&0===a.directories.length?(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 px-3 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{"aria-hidden":"true",className:"size-4 animate-spin"}),i("projectLoading")]}):a.directoriesError?(0,n.jsxs)("div",{className:"space-y-3 px-3 py-6 text-sm",children:[(0,n.jsx)("p",{role:"alert",className:"break-words text-destructive",children:a.directoriesError}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:a.retryDirectories,children:i("retry",{ns:"common"})})]}):0===p.length?(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:i("projectEmpty")}):(0,n.jsx)("div",{className:"space-y-1",children:p.map(e=>{let t=e.cwd===a.cwd;return(0,n.jsx)(I.$,{type:"button",variant:"ghost","aria-current":t?"true":void 0,disabled:a.saving,className:(0,C.cn)("h-auto min-h-14 w-full items-start justify-start gap-2 whitespace-normal px-3 py-2 text-left",t&&"bg-accent text-accent-foreground ring-1 ring-border ring-inset"),onClick:()=>{x(e.cwd)},children:(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("span",{className:"flex items-start gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 break-all text-sm font-medium",children:a$(e.cwd)}),t?(0,n.jsx)(ep.A,{"aria-hidden":"true",className:"mt-0.5 size-4 shrink-0"}):null]}),(0,n.jsx)("span",{className:"mt-1 block break-all text-xs font-normal text-muted-foreground",children:e.cwd}),(0,n.jsx)("span",{className:"mt-1 block text-xs font-normal text-muted-foreground",children:i("projectSessionCount",{count:e.sessionCount})})]})},e.cwd)})})})]}),(0,n.jsx)("section",{"aria-label":i("projectDefaultSource"),className:(0,C.cn)("min-h-0 min-w-0 flex-col @[48rem]/project-default:flex",c&&a.cwd?"flex":"hidden"),children:a.cwd?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-2 @[48rem]/project-default:hidden",children:(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(!1),children:[(0,n.jsx)(A.A,{"aria-hidden":"true"}),i("backProjectList")]})}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 @[48rem]/project-default:p-6",children:(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-6",children:[(0,n.jsxs)("header",{className:"space-y-1",children:[(0,n.jsxs)("h3",{className:"flex items-center gap-2 text-lg font-semibold",children:[(0,n.jsx)("span",{className:"min-w-0 break-all",children:a$(f)}),(0,n.jsx)("span",{className:"inline-flex size-4 shrink-0",children:!a.projectReady&&!a.projectError&&(0,n.jsx)(v.A,{role:"status","aria-label":i("projectLoading"),className:"size-4 animate-spin text-muted-foreground"})})]}),(0,n.jsx)("p",{className:"break-all text-sm text-muted-foreground",children:f})]}),a.projectError?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("p",{role:"alert",className:"min-w-0 flex-1 break-words text-destructive",children:a.projectError}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:a.retryProject,disabled:a.projectLoading||a.projectRefreshing,children:i("retry",{ns:"common"})})]}):null,null!==a.loadedCwd?(0,n.jsxs)("fieldset",{disabled:g,className:"min-w-0 space-y-6",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:i("projectDefaultSource")}),(0,n.jsx)(n2,{label:i("projectDefaultSource"),value:a.fixed?"fixed":"global",layout:"segmented",disabled:g,options:[{value:"global",label:i("projectFollowGlobal")},{value:"fixed",label:i("projectFixed")}],onChange:e=>a.changeFixed("fixed"===e)})]}),a.fixed?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)(iU,{label:i("projectDefaultModel"),children:(0,n.jsx)(nV.b,{value:a.selection?aA(a.selection.provider,a.selection.modelId):"",options:h,ariaLabel:i("projectDefaultModel"),searchPlaceholder:i("modelSearch"),disabled:g||0===a.models.length,onChange:function(e){let t=a.models.find(t=>aA(t.provider,t.modelId)===e);t&&a.selectModel(t)}})}),(0,n.jsx)(iU,{label:i("thinkingLevel"),children:(0,n.jsx)(iH,{value:a.selection?.thinkingLevel??"",options:(u?.thinkingLevels??[]).map(e=>({value:e,label:i(az[e])})),ariaLabel:i("projectDefaultThinking"),allowEmpty:!1,onChange:a.selectThinking})}),m.length>0?(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:i("fromPreset")}),(0,n.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:m.map((e,t)=>{let s=a.models.find(t=>t.provider===e.provider&&t.modelId===e.modelId);return(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"xs",disabled:g,className:"h-auto min-h-7 max-w-full whitespace-normal text-left",onClick:()=>a.applyPreset(e),children:[(0,n.jsx)("span",{className:"size-2 shrink-0 rounded-full bg-current",style:e.color?{color:e.color}:void 0}),(0,n.jsxs)("span",{className:"min-w-0 break-all",children:[s?.name||e.modelId," \xb7"," ",i(az[e.thinkingLevel])]})]},`${e.provider}/${e.modelId}/${e.thinkingLevel}/${t}`)})})]}):null]}):null]}):null]})}),(0,n.jsx)("div",{className:"shrink-0 border-t px-4 py-3 @[48rem]/project-default:px-6",children:(0,n.jsxs)(I.$,{type:"button",onClick:a.save,disabled:!a.projectReady||g||a.fixed&&!a.selection,children:[a.saving?(0,n.jsx)(v.A,{"aria-hidden":"true",className:"animate-spin"}):(0,n.jsx)(Z.A,{"aria-hidden":"true"}),a.saving?i("savingModels"):i("saveProjectDefault")]})})]}):(0,n.jsxs)("div",{className:"flex items-center gap-2 p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(eP.A,{"aria-hidden":"true",className:"size-6 shrink-0"}),i("selectProjectToConfigure")]})})]}),a.dialog]})}let aP=[{value:"providers",label:"modelProviders"},{value:"presets",label:"modelPresets"},{value:"project-default",label:"projectDefault"}];function aD({loading:e,error:t,onRetry:s}){let{t:r}=(0,b.Bd)("settings");return(0,n.jsx)("div",{className:"flex min-h-72 flex-col items-center justify-center gap-3 p-5 text-sm text-muted-foreground",children:e?(0,n.jsxs)("span",{className:"flex items-center gap-2",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"})," ",r("loadingModels")]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{role:"alert",className:"rounded-lg bg-destructive/10 px-3 py-2 text-destructive",children:t??r("modelsUnavailable")}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:s,children:r("retry",{ns:"common"})})]})})}function aT({onBeforeLeaveChange:e,connectionReady:t=!1,initialTab:s}){let{t:i}=(0,b.Bd)("settings"),{locale:a,timeZone:l}=(0,eQ.i)(),[o,c]=(0,r.useState)(!1),{biz:d,tab:u,settings:m,providers:p,presets:h,accountModels:g,changeAccountModels:f,refreshAccounts:x,resetVersion:w,formDirty:y,formInvalid:k,serviceDirty:j,nativeOpen:N,nativeText:S,nativeError:E,nativeDirty:M,setNativeText:z,openNative:A,closeNative:$,saveNative:R,revertConfig:P,setInputState:D,setServiceDirty:T,loading:O,saving:L,refreshing:F,catalogUpdatedAt:B,loadError:q,dialog:_,setProjectDefaultDirty:W,changeProviders:Y,changePresets:V,selectTab:U,retry:H,refreshCatalog:G,saveConfig:J}=function(e,t){let{t:s}=(0,b.Bd)("settings"),{clientId:n}=(0,ei.gM)(),i=(0,X.G)(),{confirm:a,dialog:l}=nF(),o=(0,r.useMemo)(()=>{let e;return e=null,{parseNativeConfig(e){let t=JSON.parse(e);return rT.parse(t)},getSettings:()=>(e||(e=eu(n,"/api/model-settings/get",{},rH).finally(()=>{e=null})),e),previewSettings:e=>eu(n,"/api/model-settings/preview",iN(e),r0),async replaceSettings(e){await eu(n,"/api/model-settings/replace",iN(e),rZ)},listCatalog:e=>eu(n,"/api/model-catalog/list",r1.parse(e),r4),async listDirectories(){let e=await eu(n,"/api/pi/directories/list",{forceRefresh:!1},r9.N$);return ip(e),e},async getProjectDefault(e){let t=await eu(n,"/api/project-model-default/get",{cwd:e},r6);return ij(t),t},async replaceProjectDefault(e){await eu(n,"/api/project-model-default/replace",r8.parse(e),r7)}}},[n]),[c,d]=(0,r.useState)(()=>t??iM(iE,iS,"providers"));(0,r.useEffect)(()=>{iz(iE,c)},[c]);let[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)([]),[g,f]=(0,r.useState)([]),[x,v]=(0,r.useState)([]),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(!1),[S,C]=(0,r.useState)(!1),[E,M]=(0,r.useState)(!0),[z,A]=(0,r.useState)(!1),[$,R]=(0,r.useState)(!1),[P,D]=(0,r.useState)(null),[T,O]=(0,r.useState)(null),[L,F]=(0,r.useState)(0),[B,q]=(0,r.useState)(0),[_,W]=(0,r.useState)({dirty:!1,invalid:!1}),[Y,V]=(0,r.useState)(!1),[U,K]=(0,r.useState)(!1),[H,G]=(0,r.useState)(""),[J,Q]=(0,r.useState)(null),Z=(0,r.useRef)(!1),ee=(0,r.useRef)([]),et=u?JSON.stringify(u.nativeConfig,null,2):"",es=U&&H!==et,en=k||N||w||_.dirty,er=en||S||Y||es;(0,r.useEffect)(()=>(e(er?()=>!z&&a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}):null),()=>e(null)),[e,er,z,a,s]),(0,r.useEffect)(()=>{if(!er)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[er]);let ea=(0,r.useCallback)(e=>{ee.current=[],m(e),h(structuredClone(e.providers)),f(structuredClone(e.presets)),v(structuredClone(e.accountModels)),y(!1),j(!1),I(!1),W({dirty:!1,invalid:!1}),q(e=>e+1)},[]);async function el(){R(!0);try{let e=await o.listCatalog({query:"",refresh:!0,page:{index:1,size:1}});D(e.updatedAt),await ed(),i.success("cached"===e.refreshResult?s("catalogCached"):"partial"===e.refreshResult?s("catalogPartial"):"unchanged"===e.refreshResult?s("catalogUnchanged"):s("catalogUpdated"))}catch(e){i.error(e instanceof Error?e.message:s("catalogRefreshFailed"))}finally{R(!1)}}async function eo(e,t=0){let{projectDefaults:n}=await o.previewSettings(e);if(n.length>0){let e=[s("replaceProjectDefaultsDescription"),...t>0?[s("removeInvalidPresets",{count:t})]:[]].join(" ");return a({title:s("replaceProjectDefaultsTitle"),description:e,content:(0,r.createElement)(rC,{projectDefaults:n}),confirmLabel:s("confirmAndSaveModels"),confirmVariant:"default"})}return 0===t||a({title:s("removeInvalidPresetsTitle"),description:s("removeInvalidPresets",{count:t}),confirmLabel:s("removeAndSave")})}async function ec(){if(!Z.current&&!_.invalid&&!Y&&!U){if(!u||!en)return void i.success(s("modelsNoChanges"));Z.current=!0,A(!0);try{let e=new Set([...p.flatMap(e=>e.models.map(t=>`${e.provider}\u0000${t.modelId}`)),...x.map(e=>`${e.provider}\u0000${e.modelId}`)]),t=new Set([...u.providers.flatMap(e=>e.models.map(t=>`${e.provider}\u0000${t.modelId}`)),...u.accountModels.map(e=>`${e.provider}\u0000${e.modelId}`)]),n=g.filter(s=>{let n=`${s.provider}\u0000${s.modelId}`;return!t.has(n)||e.has(n)}),r=g.length-n.length,a={...k||_.dirty?{providers:p}:{},...w?{accountModels:x}:{},...N||r>0?{presets:n}:{},...ee.current.length?{modelReplacements:ee.current}:{}};if(!await eo(a,r))return;await o.replaceSettings(a),ea(await o.getSettings()),j(!1),I(!1),i.success(s("modelSaved"))}catch(e){i.error(e instanceof Error?e.message:s("modelSaveFailed"))}finally{Z.current=!1,A(!1)}}}async function ed(){let e=await o.getSettings();return m(t=>t?{...t,accounts:e.accounts,models:e.models,nativeConfig:e.nativeConfig}:e),e}async function em(){!u||Z.current||Y||await a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")})&&ea(u)}async function ep(){Z.current||(!es||await a({title:s("discardNativeTitle"),description:s("discardNativeDescription"),confirmLabel:s("discardModelConfirm")}))&&K(!1)}async function eh(){if(!Z.current&&U&&es){Z.current=!0,A(!0),Q(null);try{let e={nativeConfig:o.parseNativeConfig(H)};if(!await eo(e))return;await o.replaceSettings(e),ea(await o.getSettings()),K(!1),i.success(s("modelSaved"))}catch(t){let e=t instanceof Error?t.message:s("modelSaveFailed");console.warn("[Pi Desk][ModelSettings] 保存 Pi 配置失败",{message:e}),Q(e)}finally{Z.current=!1,A(!1)}}}return(0,r.useEffect)(()=>{let e=!1;return queueMicrotask(()=>{e||(M(!0),O(null))}),o.getSettings().then(t=>{e||ea(t)}).catch(t=>{if(e)return;let n=t instanceof Error?t.message:s("modelsLoadFailed");console.warn("[Pi Desk][ModelSettings] 读取模型配置失败",{message:n}),O(n)}).finally(()=>{e||M(!1)}),()=>{e=!0}},[o,s,L,ea]),{biz:o,tab:c,settings:u,providers:p,presets:g,accountModels:x,changeAccountModels:e=>{v(e),y(JSON.stringify(e)!==JSON.stringify(u?.accountModels))},refreshAccounts:ed,providersDirty:k,presetsDirty:N,loading:E,saving:z,refreshing:$,catalogUpdatedAt:P,loadError:T,resetVersion:B,formDirty:en,formInvalid:_.invalid,serviceDirty:Y,nativeOpen:U,nativeText:H,nativeError:J,nativeDirty:es,setNativeText:G,openNative:function(){if(u&&!Z.current){if(en||Y||S)return void i.error(s("nativeProtectDraft"));G(et),Q(null),K(!0)}},closeNative:ep,saveNative:eh,revertConfig:em,setInputState:W,setServiceDirty:V,dialog:l,setProjectDefaultDirty:C,changeProviders:(e,t)=>{ee.current=t,h(e),j(JSON.stringify(e)!==JSON.stringify(u?.providers))},changePresets:e=>{f(e),I(JSON.stringify(e)!==JSON.stringify(u?.presets))},selectTab:e=>{if(e!==c&&!Z.current){if("project-default"===c&&S)return void a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}).then(t=>{t&&(C(!1),d(e))});d(e)}},retry:()=>F(e=>e+1),refreshCatalog:el,saveConfig:ec}}(e,s);return(0,n.jsxs)("div",{className:"@container/model-settings flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center justify-between gap-2 border-b p-4",children:[(0,n.jsx)(n2,{label:i("models"),layout:"segmented",value:u,options:aP.map(e=>({...e,label:i(e.label)})),onChange:U}),(0,n.jsxs)("div",{className:"hidden gap-2 @[40rem]/model-settings:flex",children:[(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:!m||L,onClick:A,children:[(0,n.jsx)(rI.A,{}),i("nativeConfig")]}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",title:B?i("catalogUpdatedAt",{time:new Date(B).toLocaleString("en"===a?"en-US":"zh-CN",{timeZone:l,timeZoneName:"shortOffset",hourCycle:"h23"})}):i("catalogUnavailable"),onClick:G,disabled:F,children:[(0,n.jsx)(es.A,{className:(0,C.cn)(F&&"animate-spin")}),F?i("refreshingCatalog"):i("refreshCatalog")]})]}),(0,n.jsxs)(eW.AM,{open:o,onOpenChange:c,children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":i("modelMoreActions"),className:"shrink-0 @[40rem]/model-settings:hidden",children:(0,n.jsx)(K.A,{})})}),(0,n.jsxs)(eW.hl,{align:"end",positionerClassName:"z-[120]",className:"w-48 gap-1 p-1",children:[(0,n.jsxs)(I.$,{type:"button",variant:"ghost",className:"justify-start",disabled:!m||L,onClick:()=>{c(!1),A()},children:[(0,n.jsx)(rI.A,{}),i("nativeConfig")]}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",className:"justify-start",disabled:F,onClick:()=>{c(!1),G()},children:[(0,n.jsx)(es.A,{}),i("refreshCatalog")]})]})]})]}),(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar min-h-0 flex-1","presets"===u?"overflow-y-auto":"overflow-hidden"),children:["project-default"===u?(0,n.jsx)(aR,{biz:d,presets:m?.presets??[],onDirtyChange:W}):m?null:(0,n.jsx)(aD,{loading:O,error:q,onRetry:H}),m?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("fieldset",{disabled:L,className:(0,C.cn)("h-full min-h-0 min-w-0","providers"!==u&&"hidden"),children:(0,n.jsx)(aM,{biz:d,connectionReady:t,providers:p,accounts:m.accounts,accountModels:g,onAccountModelsChange:f,onRefreshAccounts:x,savedProviders:m.providers,savedModels:m.models,presets:h,resetVersion:w,onChange:Y,onPresetsChange:V,onInputState:D,onServiceDirtyChange:T})}),(0,n.jsx)("fieldset",{disabled:L,className:(0,C.cn)("min-w-0","presets"!==u&&"hidden"),children:(0,n.jsx)(i2,{presets:h,models:m.models,onChange:V})})]}):null]}),"project-default"!==u&&m?(0,n.jsxs)("footer",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-t bg-card px-4 py-3",children:[(0,n.jsx)("span",{className:(0,C.cn)("text-xs text-muted-foreground",k&&"text-destructive"),role:"status",children:k?i("fixModelInputs"):y?i("modelDraftPending"):i("modelDraftClean")}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:L||!y||j,onClick:P,children:i("revertModels")}),(0,n.jsxs)(I.$,{type:"button",size:"sm",onClick:J,disabled:L||!y||k||j,children:[L?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(Z.A,{}),L?i("savingModels"):i("saveModels")]})]})]}):null,(0,n.jsx)(iA,{open:N,text:S,error:E,saving:L,dirty:M,onChange:z,onClose:$,onSave:R}),_]})}function aO({render:e,input:t}){return e(t)}let aL=[{id:"appearance",label:"appearance",icon:sq.A},{id:"region",label:"region",icon:s_.A},{id:"habits",label:"habits",icon:sW.A},{id:"models",label:"models",icon:eD.A},{id:"mcp-settings",label:"mcpSettings",icon:eC.A},{id:"capability-modes",label:"capabilityModes",icon:eg.A},{id:"skills",label:"skills",icon:sY.A},{id:"plugins",label:"plugins",icon:eC.A},{id:"auth",label:"loginProtection",icon:en.A},{id:"about",label:"about",icon:sV.A}];function aF(e,t){return`plugin:${e}:${t}`}function aB(){let{t:e}=(0,b.Bd)("settings"),t=(0,eQ.i)();return(0,n.jsxs)("section",{"aria-labelledby":"settings-about-title",className:"min-w-0 space-y-6",children:[(0,n.jsx)("h2",{id:"settings-about-title",className:"text-xl font-semibold",children:e("about")}),(0,n.jsxs)("div",{className:"flex items-center gap-3 rounded-xl bg-muted p-4",children:[(0,n.jsx)(sH.V,{size:48,className:"shrink-0"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:"Pi Desk"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("webDescription")})]})]}),(0,n.jsxs)("dl",{className:"divide-y border-y text-sm",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:e("version")}),(0,n.jsxs)("dd",{className:"font-mono",children:["v",sU]})]}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:e("versionUpdated")}),(0,n.jsx)("dd",{className:"tabular-nums",children:function(e,t,s,n){if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:new Intl.DateTimeFormat(t,{timeZone:s,year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(r)}(sK,"en"===t.locale?"en-US":"zh-CN",t.timeZone,e("common:unavailable"))})]})]})]})}function aq({open:e,connectionReady:t=!1,initialModelTab:s,workSessions:i,focusedCwd:a,pluginAttention:l,renderPluginManagement:o,renderMcpSettings:c,renderCapabilityModesSettings:d,renderPluginSettingsPage:u,onOpenChange:m,onBeforeReload:p}){let{t:h}=(0,b.Bd)("settings"),g=(0,Q.So)(),f=(0,r.useMemo)(()=>{let e=new Map;for(let{cwd:t,projectName:s}of i){let n=t.replaceAll("\\","/").replace(/\/+$/,""),r=/^[a-zA-Z]:\//.test(n)||n.startsWith("//")?n.toLowerCase():n;e.has(r)||e.set(r,{cwd:t,projectName:s})}return[...e.values()]},[i]),x=(0,r.useMemo)(()=>g.flatMap(e=>e.contributions.flatMap(t=>"settings-page"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[g]),[v,w]=(0,r.useState)(()=>s?"models":iM(iC,iI,"appearance"));(0,r.useEffect)(()=>{e&&iz(iC,v)},[v,e]);let[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(!1),S=(0,r.useRef)(null),E=(0,r.useRef)(!1),M=x.find(e=>aF(e.pluginName,e.descriptor.contributionName)===v),z=v.startsWith("plugin:")&&!M?"appearance":v,A=aL.find(e=>e.id===z),$=A?.icon,R=(0,r.useCallback)(async e=>{if(!E.current){E.current=!0,N(!0);try{let t=S.current;if(t&&!await t())return;S.current=null,e()}finally{E.current=!1,N(!1)}}},[]),P=(0,r.useCallback)(()=>{R(()=>m(!1))},[m,R]),D=(0,r.useCallback)(e=>{S.current=e},[]),T=e=>{e!==z&&R(()=>w(e))};return(0,n.jsx)(eN.YV,{open:e,onOpenChange:(e,t)=>{e?m(!0):"focus-out"!==t.reason&&P()},children:(0,n.jsxs)(eN.hA,{className:"h-[min(48rem,calc(100dvh-2rem))] max-w-6xl max-sm:h-[var(--pi-desk-content-height)] max-sm:max-h-[var(--pi-desk-content-height)] max-sm:w-dvw max-sm:max-w-none max-sm:rounded-none max-sm:border-0",finalFocus:!1,showCloseButton:!j,children:[(0,n.jsx)(eN.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsx)(eN.YM,{children:h("title")})}),(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col sm:flex-row",children:[(0,n.jsx)("div",{className:"shrink-0 border-b bg-sidebar p-3 sm:hidden",children:(0,n.jsxs)(ea.l6,{value:z,disabled:j,onValueChange:e=>{if("string"!=typeof e)return;let t=aL.find(t=>t.id===e);if(t)return void T(t.id);let s=x.find(t=>aF(t.pluginName,t.descriptor.contributionName)===e);s&&T(aF(s.pluginName,s.descriptor.contributionName))},children:[(0,n.jsx)(ea.bq,{"aria-label":h("category"),className:"w-full",children:(0,n.jsx)(ea.yv,{children:M?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eq,{icon:M.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:M.descriptor.label})]}):A&&$?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)($,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:h(A.label)})]}):null})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",align:"start",children:[aL.map(e=>{let t=e.icon;return(0,n.jsxs)(ea.eb,{value:e.id,children:[(0,n.jsxs)("span",{className:"relative shrink-0",children:[(0,n.jsx)(t,{className:"size-4"}),"plugins"===e.id&&l?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute -right-1 -top-1 size-1.5 rounded-full","error"===l?"bg-destructive":"bg-primary")}):null]}),(0,n.jsx)("span",{children:h(e.label)})]},e.id)}),x.length>0?(0,n.jsxs)(ea.s3,{children:[(0,n.jsx)(ea.TR,{children:h("pluginSettings")}),x.map(e=>{let t=aF(e.pluginName,e.descriptor.contributionName);return(0,n.jsxs)(ea.eb,{value:t,children:[(0,n.jsx)(eq,{icon:e.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{children:e.descriptor.label})]},t)})]}):null]})]})}),(0,n.jsxs)("nav",{"aria-label":h("category"),className:"pi-desk-chat-scrollbar hidden w-48 shrink-0 space-y-4 overflow-auto border-r bg-sidebar p-3 sm:block",children:[(0,n.jsx)("div",{className:"grid grid-cols-1 gap-1",children:aL.map(e=>{let t=e.icon,s=e.id===z;return(0,n.jsxs)(I.$,{variant:"ghost",disabled:j,"aria-current":s?"page":void 0,"aria-label":`${h("category")}:${h(e.label)}`,onClick:()=>T(e.id),className:(0,C.cn)("min-w-0 justify-start",s?"bg-accent text-accent-foreground hover:bg-accent":"text-muted-foreground"),children:[(0,n.jsxs)("span",{className:"relative shrink-0",children:[(0,n.jsx)(t,{className:"size-4"}),"plugins"===e.id&&l?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute -right-1 -top-1 size-1.5 rounded-full","error"===l?"bg-destructive":"bg-primary")}):null]}),(0,n.jsx)("span",{className:"truncate",children:h(e.label)})]},e.id)})}),x.length>0?(0,n.jsxs)(eV.Nt,{open:y||!!M,onOpenChange:k,className:"mt-2 border-t pt-2",children:[(0,n.jsxs)(eV.R6,{type:"button","aria-label":h("pluginSettings"),className:"flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1 text-sm font-medium text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 text-left",children:h("pluginSettings")}),(0,n.jsx)("span",{className:"tabular-nums",children:x.length}),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-3.5 transition-transform",y||M?"rotate-180":null)})]}),(0,n.jsx)(eV.Ke,{children:(0,n.jsx)("div",{className:"mt-1 grid grid-cols-1 gap-1",children:x.map(e=>{let t=aF(e.pluginName,e.descriptor.contributionName),s=t===z;return(0,n.jsxs)(I.$,{variant:"ghost",disabled:j,"aria-current":s?"page":void 0,onClick:()=>T(t),className:(0,C.cn)("min-w-0 justify-start",s?"bg-accent text-accent-foreground hover:bg-accent":"text-muted-foreground"),children:[(0,n.jsx)(eq,{icon:e.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:e.descriptor.label})]},t)})})})]}):null]}),M?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:(0,n.jsx)(aO,{render:u,input:{pluginName:M.pluginName,descriptor:M.descriptor,onClose:P,onBeforeLeaveChange:D}})}):"skills"===z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(nP,{projects:f,focusedCwd:a,onBeforeLeaveChange:D})}):"mcp-settings"===z?(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(aO,{render:c,input:{onBeforeLeaveChange:D}})}):"capability-modes"===z?(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(aO,{render:d,input:{onBeforeLeaveChange:D}})}):"models"===z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(aT,{connectionReady:t,initialTab:s,onBeforeLeaveChange:D})}):"plugins"===z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:o()}):(0,n.jsx)(eN._Y,{className:"min-w-0 max-h-none",children:(0,n.jsx)("div",{className:"p-4 sm:p-6",children:"appearance"===z?(0,n.jsx)(ra,{}):"habits"===z?(0,n.jsx)(rN,{}):"auth"===z?e&&(0,n.jsx)(nY,{}):"region"===z?(0,n.jsx)(nQ,{canLeave:p}):(0,n.jsx)(aB,{})})})]})]})})}let a_=a.Ik({cwd:a.Yj().trim().min(1).nullable()}).strict(),aW=a.g1(a.Yj(),a.Pq()),aY=a.g1(a.Yj().min(1).max(128),aW),aV=a.Ik({local:aY,inherited:aY,projectTrusted:a.zM().nullable(),diagnostics:a.YO(a.Ik({name:a.Yj().nullable(),message:a.Yj()}).strict())}).strict();a_.extend({servers:aY}).strict(),a_.extend({name:a.Yj().min(1).max(128)}).strict();let aU=a.Ik({output:a.Yj()}).strict(),aK=a.Ik({}).strict(),aH=["command","args","url","type","description","enabled","exposure"];function aG(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&Object.values(e).every(e=>"string"==typeof e)}function aJ(e){return aG(e)?Object.entries(e).map(([e,t])=>({key:e,value:t})):[]}function aQ(e){return!("command"in e)&&!("url"in e)&&!("type"in e)}function aX(e,t){let s=t??{};return{originalName:e,name:e??"",transport:t&&aQ(t)?"inherit":"url"in s?"http":"stdio",command:"string"==typeof s.command?s.command:"",args:Array.isArray(s.args)?s.args.join("\n"):"",env:aJ(s.env),headers:aJ(s.headers),url:"string"==typeof s.url?s.url:"",description:"string"==typeof s.description?s.description:"",enabled:!1!==s.enabled,exposure:"string"==typeof s.exposure?s.exposure:"",advanced:JSON.stringify(Object.fromEntries(Object.entries(s).filter(([e,t])=>!aH.includes(e)&&!(["env","headers"].includes(e)&&aG(t)))),null,2)}}class aZ extends Error{constructor(e,t){super(t),this.field=e}}function a0(e){return"string"==typeof e.url?e.url:"string"==typeof e.command?e.command:"继承全局连接"}let a1={MCP:"MCP",服务列表:"Servers",配置服务:"Configure server",服务配置:"Server configuration",手动配置:"Configure manually","导入 JSON":"Import JSON",返回服务列表:"Back to servers",服务操作:"Server actions",恢复全局配置:"Restore global configuration",删除服务:"Delete server",继承全局:"Inherited from global",项目配置:"Project configuration","项目配置 \xb7 继承全局连接":"Project configuration \xb7 inherits global connection","连接参数沿用全局,仅保存本项目的启用和工具设置。":"Connection settings are inherited from global. Only enablement and tool settings are saved for this project.",环境变量:"Environment variables",请求头:"Request headers",名称:"Name",值:"Value",添加:"Add ",删除行:"Remove row",高级设置:"Advanced settings","其他配置(JSON)":"Other configuration (JSON)",保存并测试:"Save and test",连接测试结果:"Connection test result","正在测试连接…":"Testing connection…","已保存,正在测试连接…":"Saved. Testing connection…",连接测试通过:"Connection test passed",连接测试失败:"Connection test failed",查看详细输出:"View output","已保存,连接测试通过。":"Saved. Connection test passed.","已保存,连接测试失败。":"Saved. Connection test failed.","请填写名称,或删除空白行。":"Enter a name or remove the empty row.","名称不能重复。":"Names must be unique.","环境变量和请求头不能在表单与 JSON 中重复配置。":"Do not configure environment variables or request headers in both the form and JSON.","连接请求最多等待 10 秒;凭据命令可能延长检查时间。":"Connection requests wait up to 10 seconds; credential commands may extend the check.",配置范围:"Configuration scope",全局:"Global",当前项目:"Current project",手动添加:"Add manually","添加 JSON":"Add JSON","正在读取配置…":"Loading configuration…",重试:"Retry","添加第一个 MCP 服务":"Add your first MCP server","添加服务地址或本地程序。":"Add a server URL or a local program.",已启用:"Enabled",已停用:"Disabled",启用:"Enable",停用:"Disable",编辑:"Edit",为本项目配置:"Configure for this project",独立检查:"Check independently",删除:"Delete",来自全局:"Inherited from global",本项目:"This project",覆盖全局:"Overrides global","项目设置 \xb7 继承全局连接":"Project settings \xb7 inherits global connection",继承全局连接:"Inherit global connection","本项目尚未受信任,不能执行检查;仍可编辑和保存配置。":"This project is not trusted. Checking is disabled; editing and saving remain available.","配置启用不代表已连接。保存不会自动连接或重载会话。":"Enabled configuration does not mean connected. Saving does not connect or reload sessions.","正在检查…":"Checking…",检查输出:"Check output",检查完成:"Check completed",检查失败:"Check failed","检查连接已关闭,当前聊天会话状态未改变。":"The check connection is closed. Current chat session state is unchanged.",返回编辑:"Edit configuration",关闭结果:"Dismiss result",返回:"Back",添加服务:"Add server",编辑服务:"Edit server",保存范围:"Save scope",服务名称:"Server name",连接方式:"Transport",本地程序:"Local program","HTTP 地址":"HTTP URL",启动程序:"Command","参数(每行一个)":"Arguments (one per line)","服务说明(可选)":"Description (optional)",工具使用方式:"Tool exposure",沿用默认:"Use default",通过脚本调用:"Via scripts",按需发现:"On-demand discovery",直接使用:"Direct use",隐藏:"Hidden","高级配置(JSON)":"Advanced configuration (JSON)","继承全局连接,仅保存本项目启用与曝光设置,不复制全局凭据。":"Inherits the global connection. Only project enablement and exposure settings are saved; global credentials are not copied.","本项目的完整定义会整体替换同名全局配置。":"A complete project definition replaces the global configuration of the same name.","配置 JSON":"Configuration JSON","仅接受包含 mcpServers 的标准 JSON。":"Only standard JSON with mcpServers is accepted.",解析预览:"Preview",待保存服务:"Servers to save",新增:"New",替换已有配置:"Replace existing configuration","覆盖全局(仅本项目)":"Override global (this project only)",允许替换以上同名已有配置:"Allow replacing existing configuration with the same names","重新编辑 JSON":"Edit JSON again",取消:"Cancel",保存:"Save","保存中…":"Saving…","已保存。新会话使用新配置;已有会话需重载 Pi 配置。":"Saved. New sessions use the new configuration; existing sessions must reload Pi configuration.","放弃未保存的修改?":"Discard unsaved changes?","当前修改尚未保存。放弃后将保留已保存的配置。":"Your changes have not been saved. Discarding keeps the saved configuration.",放弃修改:"Discard changes",删除配置:"Delete configuration","删除本项目配置后,将恢复使用同名全局配置。":"Deleting this project configuration restores the global configuration of the same name.","此范围内的服务配置将被删除。":"The server configuration will be deleted from this scope.","请输入有效的 JSON。":"Enter valid JSON.","仅接受包含 mcpServers 的标准配置,不允许其他根级字段。":"Only a standard mcpServers object is accepted; other root fields are not allowed.","配置中至少需要一个服务。":"At least one server is required.","服务名称需要 1–128 个字符。":"Server names must contain 1–128 characters.","高级配置需要是 JSON 对象。":"Advanced configuration must be a JSON object.","连接、说明、启用和曝光字段请在上方表单中填写。":"Set connection, description, enablement and exposure in the fields above.","继承连接只允许启用、曝光和 toolExposure 设置。":"Inherited connections only allow enablement, exposure and toolExposure settings.","请输入启动程序。":"Enter a command.","请输入有效的 HTTP 或 HTTPS 地址。":"Enter a valid HTTP or HTTPS URL.","请明确勾选替换已有配置。":"Explicitly allow replacing existing configuration.","该名称已存在,请编辑已有服务或使用其他名称。":"This name already exists. Edit that server or choose another name.","请求失败,请重试。":"The request failed. Please retry."};function a2(){let{locale:e}=(0,eQ.i)();return t=>"en"===e?a1[t]??t:t}function a5(e){return e instanceof Error?e.message:"请求失败,请重试。"}var a3=s(60454),a4=s(93750),a6=s(13464);function a8({id:e,label:t,value:s,options:r,disabled:i,onChange:a}){return(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsx)("label",{id:`${e}-label`,htmlFor:e,className:"text-sm font-medium",children:t}),(0,n.jsxs)(ea.l6,{value:s,disabled:i,onValueChange:e=>{"string"==typeof e&&a(e)},children:[(0,n.jsx)(ea.bq,{id:e,"aria-labelledby":`${e}-label`,className:"w-full min-w-0 whitespace-normal [&_[data-slot=select-value]]:line-clamp-none [&_[data-slot=select-value]]:break-all",children:(0,n.jsx)(ea.yv,{children:r.find(e=>e.value===s)?.label??s})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[125]",align:"start",children:r.map(e=>(0,n.jsx)(ea.eb,{value:e.value,className:"[&_span]:whitespace-normal [&_span]:break-all",children:e.label},e.value))})]})]})}function a7({trigger:e,children:t}){return(0,n.jsxs)(H.rI,{children:[(0,n.jsx)(H.ty,{render:e}),(0,n.jsx)(H.dc,{children:(0,n.jsx)(a3.y,{sideOffset:4,align:"end",className:"z-[125] outline-none",children:(0,n.jsx)(a4._,{className:a6.hD,children:t})})})]})}function a9({message:e,id:t}){let s=a2();return e?(0,n.jsx)("p",{id:t,role:"alert",className:"break-words text-sm text-destructive",children:s(e)}):null}function le({rows:e,selectedName:t,pending:s,onSelect:r}){let i=a2();return(0,n.jsx)("ul",{"aria-label":i("服务列表"),className:"divide-y",children:e.map(e=>{let a="string"==typeof e.config.url?eL.A:w.A;return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button","aria-label":`${i("配置服务")} \xb7 ${e.name}`,"aria-current":t===e.name?"true":void 0,disabled:s,onClick:()=>r(e),className:(0,C.cn)("flex w-full min-w-0 cursor-pointer items-center gap-3 p-4 text-left outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-default",t===e.name&&"bg-accent"),children:[(0,n.jsx)(a,{"aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1 space-y-1",children:[(0,n.jsxs)("span",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,n.jsx)("span",{className:"min-w-0 break-all text-sm font-medium",children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:i(!1===e.config.enabled?"已停用":"已启用")})]}),(0,n.jsxs)("span",{className:"block text-xs text-muted-foreground",children:[i(e.source)," \xb7"," ",i("string"==typeof e.config.url?"HTTP 地址":"本地程序")]}),(0,n.jsx)("span",{className:"block truncate font-mono text-xs text-muted-foreground",children:a0(e.config)})]}),(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"})]})},e.name)})})}function lt({id:e,label:t,rows:s,disabled:r,error:i,onChange:a}){let l=a2();return(0,n.jsxs)("fieldset",{className:"min-w-0 space-y-2",disabled:r,children:[(0,n.jsx)("legend",{className:"text-sm font-medium",children:t}),s.length>0&&(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_2rem] gap-2 text-xs text-muted-foreground","aria-hidden":"true",children:[(0,n.jsx)("span",{children:l("名称")}),(0,n.jsx)("span",{children:l("值")})]}),s.map((o,c)=>(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_2rem] gap-2",children:[(0,n.jsx)(em.p,{"aria-label":`${t} \xb7 ${l("名称")} ${c+1}`,"aria-invalid":!!i,"aria-describedby":i?`${e}-error`:void 0,value:o.key,spellCheck:!1,className:"min-w-0 font-mono",onChange:e=>a(s.map((t,s)=>s===c?{...t,key:e.target.value}:t))}),(0,n.jsx)(em.p,{"aria-label":`${t} \xb7 ${l("值")} ${c+1}`,value:o.value,spellCheck:!1,autoComplete:"off",className:"min-w-0 font-mono",onChange:e=>a(s.map((t,s)=>s===c?{...t,value:e.target.value}:t))}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":`${l("删除行")} \xb7 ${t} ${c+1}`,disabled:r,onClick:()=>a(s.filter((e,t)=>t!==c)),children:(0,n.jsx)(et.A,{"aria-hidden":"true"})})]},c)),(0,n.jsx)(a9,{id:`${e}-error`,message:i}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>a([...s,{key:"",value:""}]),children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),l("添加"),t]})]})}var ls=s(27315);function ln({check:e,onRetry:t,onDismiss:s}){let r=a2(),i=e.loading?v.A:e.error?Y.A:ls.A;return(0,n.jsxs)("section",{"aria-label":r("连接测试结果"),"aria-busy":e.loading,className:"space-y-2 border-b pb-4",children:[(0,n.jsxs)("p",{role:"status",className:"flex items-center gap-2 text-sm font-medium",children:[(0,n.jsx)(i,{"aria-hidden":"true",className:`size-4 shrink-0 ${e.loading?"motion-safe:animate-spin":e.error?"text-destructive":""}`}),r(e.loading?"已保存,正在测试连接…":e.error?"已保存,连接测试失败。":"已保存,连接测试通过。")]}),(0,n.jsx)(a9,{message:e.error}),e.loading?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:r("连接请求最多等待 10 秒;凭据命令可能延长检查时间。")}):(0,n.jsxs)(n.Fragment,{children:[e.output&&(0,n.jsxs)("details",{className:"text-sm",children:[(0,n.jsx)("summary",{className:"w-fit cursor-pointer rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:r("查看详细输出")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap break-all rounded-lg bg-muted p-3 font-mono text-sm",children:e.output})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:r("检查连接已关闭,当前聊天会话状态未改变。")}),(0,n.jsxs)("div",{className:"flex gap-2",children:[e.error&&(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:t,children:r("重试")}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:s,children:r("关闭结果")})]})]})]})}function lr({editor:e,scopeLabel:t,project:s,projectTrusted:i,check:a,local:l,inherited:o,pending:c,saving:d,error:u,onDraft:m,onJson:p,onPreview:h,onOverwrite:g,onSave:f,onCancel:x,onRemove:b,onDismissCheck:v}){let w=a2(),y=(0,r.useId)(),k=(0,r.useRef)(null),[j,N]=(0,r.useState)(!1);(0,r.useEffect)(()=>{u&&k.current?.querySelector('[aria-invalid="true"]')?.focus()},[u]);let S=e=>`${y}-${e}`,C="manual"===e.kind?e.draft:null,E="json"===e.kind&&e.preview?Object.keys(e.preview).filter(e=>Object.hasOwn(l,e)):[],M="json"===e.kind?"导入 JSON":C?.originalName?"服务配置":"添加服务",z=C?.originalName,$=!!(z&&Object.hasOwn(l,z)),R=!!(s&&z&&Object.hasOwn(o,z)),P=(e,t,s)=>(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:S(e),className:"text-sm font-medium",children:w(t)}),s,(0,n.jsx)(a9,{id:S(`${e}-error`),message:u?.field===e?u.message:null})]}),D=(e,t)=>P(e,t,(0,n.jsx)(em.p,{id:S(e),value:C?.[e]??"",disabled:c||"name"===e&&!!C?.originalName,"aria-invalid":u?.field===e,"aria-describedby":u?.field===e?S(`${e}-error`):void 0,onChange:t=>m({[e]:t.target.value})}));return(0,n.jsxs)("form",{ref:k,"aria-label":w(M),className:"flex min-h-0 min-w-0 flex-1 flex-col",onSubmit:e=>{e.preventDefault(),f()},children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-1 border-b p-4 sm:px-6",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":w("返回服务列表"),disabled:c,onClick:x,children:(0,n.jsx)(A.A,{"aria-hidden":"true"})}),(0,n.jsx)("h3",{className:"min-w-0 flex-1 text-sm font-semibold",children:w(M)}),$&&z&&(0,n.jsx)(a7,{trigger:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":w("服务操作"),disabled:c,children:(0,n.jsx)(K.A,{"aria-hidden":"true"})}),children:(0,n.jsx)(H._2,{variant:R?"default":"destructive",onClick:()=>b(z),children:w(R?"恢复全局配置":"删除服务")})})]}),s&&(0,n.jsxs)("p",{className:"break-all text-xs text-muted-foreground",children:[w("保存范围"),":",t]})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:[C?(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-4",children:[a&&(0,n.jsx)(ln,{check:a,onRetry:()=>f(!0),onDismiss:v}),D("name","服务名称"),"inherit"===C.transport?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:w("继承全局连接")}),z&&o[z]&&(0,n.jsx)("p",{className:"break-all font-mono text-sm text-muted-foreground",children:a0(o[z])}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("连接参数沿用全局,仅保存本项目的启用和工具设置。")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a8,{id:S("transport"),label:w("连接方式"),value:C.transport,disabled:c,options:[{value:"stdio",label:w("本地程序")},{value:"http",label:w("HTTP 地址")}],onChange:e=>m({transport:"http"===e?"http":"stdio"})}),"stdio"===C.transport?(0,n.jsxs)(n.Fragment,{children:[D("command","启动程序"),P("args","参数(每行一个)",(0,n.jsx)(t7.T,{id:S("args"),className:"min-h-24 font-mono",value:C.args,disabled:c,onChange:e=>m({args:e.target.value})}))]}):D("url","HTTP 地址"),("stdio"===C.transport||u?.field==="env")&&(0,n.jsx)(lt,{id:S("env"),label:w("环境变量"),rows:C.env,disabled:c,error:u?.field==="env"?u.message:null,onChange:e=>m({env:e})}),("http"===C.transport||u?.field==="headers")&&(0,n.jsx)(lt,{id:S("headers"),label:w("请求头"),rows:C.headers,disabled:c,error:u?.field==="headers"?u.message:null,onChange:e=>m({headers:e})}),s&&(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("本项目的完整定义会整体替换同名全局配置。")})]}),(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",checked:C.enabled,disabled:c,onChange:e=>m({enabled:e.target.checked}),className:"size-4 shrink-0 accent-primary"}),w("已启用")]}),(0,n.jsxs)(eV.Nt,{open:j||u?.field==="advanced",onOpenChange:N,children:[(0,n.jsxs)(eV.R6,{type:"button",className:"group flex min-h-8 cursor-pointer items-center gap-2 rounded-lg px-2 text-sm font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eY.A,{"aria-hidden":"true",className:"size-4 transition-transform group-data-panel-open:rotate-180"}),w("高级设置")]}),(0,n.jsxs)(eV.Ke,{className:"space-y-3 pt-3",children:["inherit"!==C.transport&&D("description","服务说明(可选)"),(0,n.jsx)(a8,{id:S("exposure"),label:w("工具使用方式"),value:C.exposure,disabled:c,options:[{value:"",label:w("沿用默认")},{value:"codemode",label:w("通过脚本调用")},{value:"deferred",label:w("按需发现")},{value:"direct",label:w("直接使用")},{value:"hidden",label:w("隐藏")},...["","codemode","deferred","direct","hidden"].includes(C.exposure)?[]:[{value:C.exposure,label:C.exposure}]],onChange:e=>m({exposure:e})}),(0,n.jsx)("label",{htmlFor:S("advanced"),className:"block text-sm font-medium",children:w("其他配置(JSON)")}),(0,n.jsx)(t7.T,{id:S("advanced"),onFocus:()=>N(!0),value:C.advanced,disabled:c,className:"min-h-40 font-mono",spellCheck:!1,"aria-invalid":u?.field==="advanced","aria-describedby":u?.field==="advanced"?S("advanced-error"):void 0,onChange:e=>m({advanced:e.target.value})}),(0,n.jsx)(a9,{id:S("advanced-error"),message:u?.field==="advanced"?u.message:null})]})]})]}):"json"===e.kind?(0,n.jsxs)("div",{className:"space-y-3",children:[P("json","配置 JSON",(0,n.jsx)(t7.T,{id:S("json"),value:e.text,disabled:c,"aria-invalid":u?.field==="json","aria-describedby":u?.field==="json"?S("json-error"):void 0,spellCheck:!1,className:"min-h-48 font-mono",placeholder:'{ "mcpServers": { "docs": { "url": "https://example.com/mcp" } } }',onChange:e=>p(e.target.value)})),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("仅接受包含 mcpServers 的标准 JSON。")}),(0,n.jsx)(I.$,{type:"button",variant:"outline",onClick:h,disabled:c||!e.text.trim(),children:w("解析预览")}),e.preview&&(0,n.jsxs)("section",{"aria-label":w("待保存服务"),className:"space-y-3",children:[(0,n.jsx)("ul",{className:"divide-y border-y",children:Object.entries(e.preview).map(([e,t])=>(0,n.jsxs)("li",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 break-all font-medium",children:e}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(aQ(t)?"继承全局连接":"url"in t?"HTTP 地址":"本地程序")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(Object.hasOwn(l,e)?"替换已有配置":Object.hasOwn(o,e)?"覆盖全局(仅本项目)":"新增")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(!1===t.enabled?"已停用":"已启用")})]},e))}),E.length>0&&(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-start gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",checked:e.overwrite,disabled:c,className:"mt-1 size-4 shrink-0 accent-primary",onChange:e=>g(e.target.checked)}),(0,n.jsx)("span",{children:w("允许替换以上同名已有配置")})]})]})]}):null,(0,n.jsx)("div",{className:"mt-3",children:(0,n.jsx)(a9,{message:u?.field==="save"?u.message:null})})]}),(0,n.jsxs)("footer",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t bg-background px-4 py-3 sm:px-6",children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:c,onClick:x,children:w("取消")}),C&&(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:c||!C.enabled||!1===i,onClick:()=>f(!0),children:w("保存并测试")}),(0,n.jsx)(I.$,{type:"submit",disabled:c||"json"===e.kind&&(!e.preview||E.length>0&&!e.overwrite),children:w(a?.loading?"正在测试连接…":d?"保存中…":"保存")})]})]})}function li({pending:e,onAdd:t,onImport:s}){let r=a2();return(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-6",children:(0,n.jsx)("div",{className:"grid min-h-full grid-rows-[1fr_auto_2fr]",children:(0,n.jsxs)("div",{className:"row-start-2 flex flex-col items-center gap-6 text-center",children:[(0,n.jsxs)("div",{"aria-hidden":"true",className:"relative h-28 w-60 shrink-0 text-muted-foreground",children:[(0,n.jsxs)("svg",{viewBox:"0 0 240 112",fill:"none",className:"absolute inset-0 size-full text-muted-foreground/40",children:[(0,n.jsx)("path",{d:"M44 76H64Q76 76 76 64V60Q76 56 92 56M148 56H164Q180 56 180 44Q180 40 196 40M120 12V28",stroke:"currentColor"}),(0,n.jsx)("circle",{cx:"120",cy:"8",r:"3",className:"fill-background stroke-current"}),(0,n.jsx)("circle",{cx:"64",cy:"76",r:"2",className:"fill-muted-foreground"}),(0,n.jsx)("circle",{cx:"180",cy:"44",r:"2",className:"fill-muted-foreground"})]}),(0,n.jsx)("div",{className:"absolute top-14 left-1 flex size-10 items-center justify-center rounded-xl border bg-muted/50",children:(0,n.jsx)(w.A,{className:"size-4"})}),(0,n.jsx)("div",{className:"absolute top-7 left-[92px] flex size-14 items-center justify-center rounded-xl border bg-background text-foreground",children:(0,n.jsx)(eC.A,{className:"size-6"})}),(0,n.jsx)("div",{className:"absolute top-5 right-1 flex size-10 items-center justify-center rounded-xl border bg-muted/50",children:(0,n.jsx)(eL.A,{className:"size-4"})})]}),(0,n.jsx)("h3",{className:"text-lg font-semibold",children:r("添加第一个 MCP 服务")}),(0,n.jsxs)("div",{className:"flex flex-wrap justify-center gap-2",children:[(0,n.jsxs)(I.$,{disabled:e,onClick:t,children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),r("添加服务")]}),(0,n.jsx)(I.$,{variant:"outline",disabled:e,onClick:s,children:r("导入 JSON")})]})]})})})}function la({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{clientId:i}=(0,ei.gM)(),l=function(e,t){let s=a2(),n=(0,r.useMemo)(()=>({getMcp:(t,s)=>eu(e,"/api/mcp-settings/get",{cwd:t},aV,{signal:s}),replaceMcp:(t,s)=>eu(e,"/api/mcp-settings/replace",t,aK,{signal:s}),deleteMcp:(t,s,n)=>eu(e,"/api/mcp-settings/del",{cwd:t,name:s},aK,{signal:n}),checkMcp:(t,s,n)=>eu(e,"/api/mcp-check/get",{cwd:t,name:s},aU,{signal:n})}),[e]),{confirm:i,dialog:l}=nF(),[o,c]=(0,r.useState)(null),[d,u]=(0,r.useState)(null),m=d?.data??null,p=d?d.cwd:o,[h,g]=(0,r.useState)(null),[f,x]=(0,r.useState)(!0),[b,v]=(0,r.useState)(!1),[w,y]=(0,r.useState)(null),[k,j]=(0,r.useState)(null),[N,I]=(0,r.useState)(null),[S,C]=(0,r.useState)(null),E=(0,r.useRef)(null),M=(0,r.useRef)(0),z=(0,r.useRef)(0),A=(0,r.useRef)(i),$=(0,r.useRef)(s);(0,r.useEffect)(()=>{A.current=i,$.current=s},[i,s]);let R=null!==d&&d.cwd===o&&!f&&!w,P=R&&(h?.kind==="manual"&&JSON.stringify(h.draft)!==h.initial||h?.kind==="json"&&!!h.text),D=(0,r.useCallback)(()=>{g(null),j(null)},[]),T=(0,r.useCallback)(async()=>!(b||S?.loading)&&(!P||await A.current({title:$.current("放弃未保存的修改?"),description:$.current("当前修改尚未保存。放弃后将保留已保存的配置。"),confirmLabel:$.current("放弃修改")})),[P,b,S?.loading]);(0,r.useEffect)(()=>(t(T),()=>t(null)),[T,t]);let O=(0,r.useCallback)(async(e,t,s=!1)=>{x(!0),y(null);try{let r=await n.getMcp(o,e);if(e.aborted||M.current!==t)return!1;return u({cwd:o,data:r}),s&&g(null),!0}catch(s){return e.aborted||M.current!==t||(console.warn("[Pi Desk][MCP] 读取配置失败",{cwd:o,message:a5(s)}),y(a5(s))),!1}finally{e.aborted||M.current!==t||x(!1)}},[n,o]);(0,r.useEffect)(()=>{let e=new AbortController;E.current=e;let t=++M.current;return O(e.signal,t,!0),()=>e.abort()},[O]);let L=async e=>{await T()&&(D(),I(null),e())},F=async e=>{e!==o&&await T()&&(E.current?.abort(),j(null),I(null),C(null),y(null),x(!0),c(e))},B=(e,t)=>{let s=aX(e,t);j(null),I(null),C(null),g({kind:"manual",draft:s,initial:JSON.stringify(s)})},q=async(e,t)=>{let s=E.current?.signal;if(!s||!R||b||S?.loading)return!1;let n=M.current;v(!0),j(null),I(null);try{if(await e(s),s.aborted||M.current!==n)return!1;return t(),C(null),I("已保存。新会话使用新配置;已有会话需重载 Pi 配置。"),await O(s,n)}catch(e){return s.aborted||M.current!==n||j({field:e instanceof aZ?e.field:"save",message:a5(e)}),!1}finally{s.aborted||M.current!==n||v(!1)}},_=async(e=!1)=>{if(!(!h||!m||!R||b||S?.loading)&&(!e||"manual"===h.kind&&h.draft.enabled&&!1!==m.projectTrusted))try{let t="manual"===h.kind?function(e,t){let s,n=e.name.trim();if(!n||n.length>128)throw new aZ("name","服务名称需要 1–128 个字符。");try{s=aW.parse(JSON.parse(e.advanced))}catch{throw new aZ("advanced","高级配置需要是 JSON 对象。")}if(aH.some(e=>e in s))throw new aZ("advanced","连接、说明、启用和曝光字段请在上方表单中填写。");if("inherit"===e.transport&&Object.keys(s).some(e=>"toolExposure"!==e))throw new aZ("advanced","继承连接只允许启用、曝光和 toolExposure 设置。");let r={...s,enabled:e.enabled};if(e.exposure&&(r.exposure=e.exposure),"inherit"!==e.transport){for(let n of(e.description&&(r.description=e.description),["env","headers"]))if(e[n].length>0||aG(t?.[n])){if(n in s)throw new aZ("advanced","环境变量和请求头不能在表单与 JSON 中重复配置。");r[n]=function(e,t){let s=[],n=new Set;for(let r of e){if(!r.key.trim()&&!r.value)continue;if(!r.key.trim())throw new aZ(t,"请填写名称,或删除空白行。");let e=r.key.trim(),i="headers"===t?e.toLowerCase():e;if(n.has(i))throw new aZ(t,"名称不能重复。");n.add(i),s.push([e,r.value])}return Object.fromEntries(s)}(e[n],n)}}if("stdio"===e.transport){if(!e.command.trim())throw new aZ("command","请输入启动程序。");r.command=e.command.trim(),r.args=Array.isArray(t?.args)&&t.args.join("\n")===e.args?t.args:e.args?e.args.split(/\r?\n/):[],(t?.type!==void 0||!t||"url"in t)&&(r.type="stdio")}else if("http"===e.transport){try{let t=new URL(e.url.trim());if(!["https:","http:"].includes(t.protocol))throw Error()}catch{throw new aZ("url","请输入有效的 HTTP 或 HTTPS 地址。")}r.url=e.url.trim(),(t?.type!==void 0||!t||"command"in t)&&(r.type="http")}return{[n]:r}}(h.draft,h.draft.originalName?m.local[h.draft.originalName]:void 0):h.preview;if(!t)return;let s=Object.keys(t).filter(e=>Object.hasOwn(m.local,e));if("json"===h.kind&&s.length&&!h.overwrite)throw new aZ("json","请明确勾选替换已有配置。");if("manual"===h.kind&&s.some(e=>e!==h.draft.originalName))throw new aZ("name","该名称已存在,请编辑已有服务或使用其他名称。");if(await q(e=>n.replaceMcp({cwd:o,servers:t},e),()=>{if("json"===h.kind)g(null);else{let e=h.draft.name.trim(),s=aX(e,t[e]);g({kind:"manual",draft:s,initial:JSON.stringify(s)})}})&&e&&"manual"===h.kind){let e=await Y(h.draft.name.trim());E.current?.signal.aborted||I(e?"已保存,连接测试通过。":"已保存,连接测试失败。")}}catch(e){j({field:e instanceof aZ?e.field:"save",message:a5(e)})}},W=async e=>{if(!m||!R||b||!Object.hasOwn(m.local,e))return;let t=null!==o&&Object.hasOwn(m.inherited,e);await A.current({title:`${$.current(t?"恢复全局配置":"删除服务")} \xb7 ${e}`,description:$.current(t?"删除本项目配置后,将恢复使用同名全局配置。":"此范围内的服务配置将被删除。"),confirmLabel:$.current(t?"恢复全局配置":"删除服务")})&&await q(t=>n.deleteMcp(o,e,t),()=>g(null))},Y=async e=>{let t=E.current?.signal;if(!t||!m||!1===m.projectTrusted||S?.loading)return!1;let s=++z.current;C({name:e,loading:!0,output:null,error:null});try{let r=await n.checkMcp(o,e,t);return t.aborted||z.current!==s||C({name:e,loading:!1,output:r.output.slice(0,32768),error:null}),!0}catch(n){return t.aborted||z.current!==s||C({name:e,loading:!1,output:null,error:a5(n)}),!1}},V=m?[...new Set([...Object.keys(m.inherited),...Object.keys(m.local)])].map(e=>{let t=m.local[e],s=m.inherited[e],n=!!(t&&s&&aQ(t));return{name:e,config:n?{...s,...t}:t??s,local:t??null,source:null===p?"全局":t?n?"项目配置 \xb7 继承全局连接":"项目配置":"继承全局"}}):[];return{cwd:o,displayCwd:p,ready:R,mcp:m,editor:h,setEditor:g,loading:f,pending:b,loadError:w,error:k,notice:N,check:S,rows:V,dirty:P,dialog:l,retry:()=>{E.current&&O(E.current.signal,M.current,d?.cwd!==o)},navigate:L,setCwd:F,startManual:B,startInherited:(e,t)=>{B(e,{enabled:!1!==t.enabled})},updateDraft:e=>{g(t=>t?.kind==="manual"?{...t,draft:{...t.draft,...e}}:t),j(null),I(null),C(null)},updateJson:e=>{g({kind:"json",text:e,preview:null,overwrite:!1}),j(null)},previewJson:()=>{if(h?.kind==="json"&&m)try{let t=function(e){let t;try{t=JSON.parse(e)}catch{throw Error("请输入有效的 JSON。")}let s=a.Ik({mcpServers:aY}).strict().safeParse(t);if(!s.success)throw Error("仅接受包含 mcpServers 的标准配置,不允许其他根级字段。");if(0===Object.keys(s.data.mcpServers).length)throw Error("配置中至少需要一个服务。");return s.data.mcpServers}(h.text);var e=m.inherited;for(let[s,n]of Object.entries(t)){if(!s.trim()||s!==s.trim())throw new aZ("json","服务名称不能为空或带有首尾空格。");if(aQ(n)){if(null===o||!Object.hasOwn(e,s)||Object.keys(n).some(e=>!["enabled","exposure","toolExposure"].includes(e)))throw new aZ("json",`${s}:继承配置需要同名全局服务,且只允许启用和曝光设置。`)}else if("sse"===n.type)throw new aZ("json",`${s}:不支持 SSE,请使用 HTTP 连接。`);else if("string"!=typeof n.command&&"string"!=typeof n.url)throw new aZ("json",`${s}:请提供启动程序或服务地址。`)}g({...h,preview:t,overwrite:!1}),j(null)}catch(e){j({field:"json",message:a5(e)})}},saveEditor:_,remove:W,dismissCheck:()=>{C(null)},beforeLeave:T}}(i,s),o=a2(),c=(0,r.useId)(),d=(0,r.useMemo)(()=>{let s=new Map;for(let t of e){let e=t.cwd.replaceAll("\\","/").replace(/\/+$/,""),n=/^[a-zA-Z]:\//.test(e)||e.startsWith("//")?e.toLowerCase():e;s.has(n)||s.set(n,t)}return[...s.values()].sort((e,s)=>Number(s.cwd===t)-Number(e.cwd===t))},[e,t]),u=null===l.displayCwd?o("全局"):`${d.find(e=>e.cwd===l.displayCwd)?.projectName??o("当前项目")} \xb7 ${l.displayCwd}`,m=!!(l.editor&&l.mcp),p=l.pending||!!l.check?.loading,h=p||!l.ready,g=l.editor?.kind==="manual"?l.editor.draft.originalName:null,f=()=>{l.navigate(()=>l.startManual(null))},x=()=>{l.navigate(()=>l.setEditor({kind:"json",text:"",preview:null,overwrite:!1}))};return(0,n.jsxs)("section",{"aria-label":"MCP",className:"@container/mcp flex h-full min-h-0 min-w-0 flex-col",children:[l.dialog,(0,n.jsxs)("header",{className:"grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 border-b p-4 @min-[40rem]/mcp:grid-cols-[auto_minmax(0,1fr)_auto]",children:[(0,n.jsxs)("h2",{className:"flex items-center gap-2 text-xl font-semibold",children:["MCP",(0,n.jsx)("span",{className:"inline-flex size-4",children:l.loading&&(0,n.jsx)(v.A,{role:"status","aria-label":o("正在读取配置…"),className:"size-4 animate-spin text-muted-foreground"})})]}),(0,n.jsxs)("div",{className:"col-start-2 flex flex-wrap justify-end gap-2 @min-[40rem]/mcp:col-start-3 @min-[40rem]/mcp:self-end",children:[(0,n.jsxs)(I.$,{disabled:h,onClick:f,children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),o("添加服务")]}),(0,n.jsx)(I.$,{variant:"outline",disabled:h,onClick:x,children:o("导入 JSON")})]}),(0,n.jsx)("div",{className:"col-span-2 row-start-2 w-full @min-[40rem]/mcp:col-span-1 @min-[40rem]/mcp:col-start-2 @min-[40rem]/mcp:row-start-1 @min-[40rem]/mcp:max-w-80 @min-[40rem]/mcp:justify-self-end @min-[40rem]/mcp:[&_[data-slot=select-trigger]]:mb-0",children:(0,n.jsx)(a8,{id:`${c}-scope`,label:o("配置范围"),value:l.cwd??"",disabled:p,options:[{value:"",label:o("全局")},...d.map(e=>({value:e.cwd,label:`${e.projectName}${e.cwd===t?` \xb7 ${o("当前项目")}`:""}`}))],onChange:e=>{l.setCwd(e||null)}})})]}),l.notice&&!l.check&&(0,n.jsx)("p",{role:"status",className:"shrink-0 break-words border-b px-4 py-2 text-sm",children:o(l.notice)}),l.mcp?.projectTrusted===!1&&(0,n.jsx)("p",{className:"shrink-0 px-4 pt-3 text-sm text-muted-foreground",children:o("本项目尚未受信任,不能执行检查;仍可编辑和保存配置。")}),l.mcp&&l.mcp.diagnostics.length>0&&(0,n.jsx)("div",{className:"max-h-32 shrink-0 space-y-2 overflow-y-auto px-4 pt-3",children:l.mcp.diagnostics.map((e,t)=>(0,n.jsx)(a9,{message:`${e.name?`${e.name}:`:""}${e.message}`},t))}),l.loadError&&(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(a9,{message:l.loadError}),(0,n.jsx)(I.$,{variant:"outline",onClick:l.retry,disabled:l.loading,children:o("重试")})]}),l.loading&&!l.mcp?(0,n.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:o("正在读取配置…")}):l.mcp?(0,n.jsxs)("div",{"aria-busy":l.loading,className:"flex min-h-0 min-w-0 flex-1",children:[l.editor?.kind!=="json"&&l.rows.length>0&&(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar min-h-0 min-w-0 overflow-y-auto",m?"hidden @min-[48rem]/mcp:block @min-[48rem]/mcp:w-56 @min-[48rem]/mcp:shrink-0 @min-[48rem]/mcp:border-r":"flex-1"),children:[!m&&l.error&&(0,n.jsx)("div",{className:"p-4",children:(0,n.jsx)(a9,{message:l.error.message})}),(0,n.jsx)(le,{rows:l.rows,selectedName:g,pending:h,onSelect:e=>{g!==e.name&&l.navigate(()=>e.local?l.startManual(e.name,e.local):l.startInherited(e.name,e.config))}})]}),l.editor?(0,n.jsx)(lr,{editor:l.editor,scopeLabel:u,project:null!==l.displayCwd,projectTrusted:l.mcp.projectTrusted,local:l.mcp.local,inherited:l.mcp.inherited,pending:h,saving:l.pending,error:l.error,check:l.check?.name===g?l.check:null,onDraft:l.updateDraft,onJson:l.updateJson,onPreview:l.previewJson,onOverwrite:e=>l.setEditor(t=>t?.kind==="json"?{...t,overwrite:e}:t),onSave:e=>void l.saveEditor(e),onCancel:()=>void l.navigate(()=>l.setEditor(null)),onRemove:e=>void l.remove(e),onDismissCheck:l.dismissCheck},"manual"===l.editor.kind?g??"new":"json"):0===l.rows.length?(0,n.jsx)(li,{pending:h,onAdd:f,onImport:x}):null]}):null]})}var ll=s(267),lo=s(59605),lc=s(55438);let ld=a.Yj().trim().min(1).max(200),lu=a.Yj().trim().min(1).max(100).nullable(),lm=a.Yj().trim().min(1).max(100).nullable(),lp=a.Yj().trim().min(1).max(200),lh=a.Ik({label:a.Yj().trim().min(1).max(64),value:a.Yj().trim().min(1).max(500)}).strict(),lg=a.Yj().trim().min(1).max(300).nullable(),lf=a.k5(["running","completed","failed","stopped","interrupted"]),lx=a.Ik({taskId:ld,taskKind:lu,taskType:lm,title:lp,info:a.YO(lh).max(12),status:lf,activity:lg,startedAt:rM.k,endedAt:rM.k.nullable()}).strict().superRefine((e,t)=>{"running"===e.status&&null!==e.endedAt&&t.addIssue({code:"custom",message:"running task requires endedAt=null",path:["endedAt"]}),"running"!==e.status&&null===e.endedAt&&t.addIssue({code:"custom",message:"terminal task requires endedAt",path:["endedAt"]})}),lb=a.Ik({tasks:a.YO(lx)}).strict().superRefine((e,t)=>{let s=new Set;for(let[n,r]of e.tasks.entries())s.has(r.taskId)&&t.addIssue({code:"custom",message:"taskId values must be unique",path:["tasks",n,"taskId"]}),s.add(r.taskId)}),lv=a.Ik({kind:a.eu("text"),text:a.Yj(),truncated:a.zM()}).strict(),lw=lo.RX.extend({kind:a.eu("conversation"),truncated:a.zM()}).strict(),ly=a.KC([a.ch(),lv,lw]),lk=a.Ik({taskId:ld,canInterrupt:a.zM(),body:ly}).strict(),lj=lc.mv,lN=a.KC([a.Ik({type:a.eu("snapshot"),snapshot:lk}).strict(),a.Ik({type:a.eu("text_append"),text:a.Yj().min(1)}).strict(),a.Ik({type:a.eu("conversation_event"),event:lj}).strict(),a.Ik({type:a.eu("unavailable")}).strict()]);a.Ik({source:ll.R,taskId:ld,entryId:sZ.Rv}).strict().extend({imageIndex:a.ai().int().nonnegative()}).strict();let lI=a.Ik({source:ll.R,taskId:ld.nullable()}).strict(),lS=a.Ik({snapshot:lk.nullable()}).strict(),lC=a.Ik({source:ll.R,taskId:ld}).strict(),lE=a.Ik({}).strict(),lM=a.Ik({source:ll.R,taskId:ld,event:lN}).strict(),lz=Object.freeze({detailWatch:(0,l.Vc)({path:"task-center/detail-watch",inputSchema:lI,outputSchema:lS}),interrupt:(0,l.Vc)({path:"task-center/interrupt",inputSchema:lC,outputSchema:lE}),detailEvent:(0,l._G)({path:"task-center/detail-event",bodySchema:lM})});var lA=s(45811),l$=s(14510),lR=s(12019),lP=s(86075),lD=s(84571),lT=s(67011);let lO=({className:e,...t})=>(0,n.jsx)(lT.z,{className:(0,C.cn)("relative flex-1 overflow-y-hidden",e),initial:"smooth",resize:"smooth",role:"log",...t}),lL=({className:e,...t})=>(0,n.jsx)(lT.z.Content,{className:(0,C.cn)("flex flex-col gap-8 p-4",e),...t});var lF=s(47744),lB=s(30973),lq=s(14203),l_=s(26575),lW=s(11953);function lY({onOpenChange:e,...t}){let s=(0,r.useRef)(null);return(0,n.jsx)(lF.j,{"data-slot":"hover-card",...t,onOpenChange:(t,n)=>{if(e?.(t,n),n.isCanceled)return;if(t){s.current=n.trigger??null;return}let r=s.current;s.current=null,"escape-key"===n.reason&&r instanceof HTMLElement&&r.ownerDocument.activeElement===r&&r.blur()}})}function lV({...e}){return(0,n.jsx)(lB.Z,{"data-slot":"hover-card-trigger",...e})}function lU({className:e,side:t="bottom",sideOffset:s=4,align:r="center",alignOffset:i=4,...a}){return(0,n.jsx)(lq.D,{"data-slot":"hover-card-portal",children:(0,n.jsx)(l_.p,{align:r,alignOffset:i,side:t,sideOffset:s,className:"isolate z-50",children:(0,n.jsx)(lW.p,{"data-slot":"hover-card-content",className:(0,C.cn)("z-50 w-80 max-w-[calc(100vw-2rem)] origin-(--transform-origin) rounded-lg border border-border bg-popover p-3 text-sm text-popover-foreground shadow-md outline-hidden duration-100 motion-reduce:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...a})})})}let lK=({className:e,...t})=>(0,n.jsx)(nC.Sq,{align:"block-end",className:(0,C.cn)("justify-between gap-1",e),...t}),lH=({className:e,...t})=>(0,n.jsx)("div",{className:(0,C.cn)("flex min-w-0 items-center gap-1",e),...t}),lG=({variant:e="ghost",className:t,size:s,tooltip:i,...a})=>{let l=s??(r.Children.count(a.children)>1?"sm":"icon-sm"),o=(0,n.jsx)(nC.Ik,{className:(0,C.cn)(t),size:l,type:"button",variant:e,...a});if(!i)return o;let c="string"==typeof i?i:i.content,d="string"==typeof i?void 0:i.shortcut,u="string"==typeof i?"top":i.side??"top";return(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:o}),(0,n.jsxs)(tU.ZI,{side:u,children:[c,d&&(0,n.jsx)("span",{className:"ml-2 text-muted-foreground",children:d})]})]})},lJ=a.Ik({input:a.g1(a.Yj(),a.Pq())}).strict(),lQ=a.Ik({output:a.Yj()}).strict(),lX="pideskHelp",lZ=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,l0=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function l1(e){return/^[a-zA-Z0-9_./:@=+-]+$/.test(e)?e:JSON.stringify(e)}let l2=a.Ik({name:a.Yj(),scope:a.eu("global").optional(),source:a.Yj(),kind:a.k5(["package","extension"]),version:a.Yj().nullable(),status:a.k5(["ready","available","disabled","failed"]),updateTag:a.Yj().nullish(),availableVersion:a.Yj().nullish(),updateError:a.Yj().nullish(),operation:a.Ik({action:a.k5(["add","update","del","apply"]),phase:a.k5(["queued","checking","applying","waiting","failed"]),message:a.Yj().nullable()}).strict().nullish(),error:a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:eJ.qf}).strict().nullish()}).strict(),l5=a.Ik({plugins:a.YO(l2),restartRequired:a.zM(),loadError:eJ.qf.nullish()}).strict(),l3=l2.extend({detail:a.g1(a.Yj(),a.Pq())}).strict(),l4=a.Ik({version:a.Yj(),environment:a.k5(["development","production"]),mode:a.k5(["basic","normal"]),cwd:a.Yj(),agentDir:a.Yj(),docsDirectory:a.Yj()}).strict(),l6=null,l8=new WeakMap,l7=new WeakMap,l9=new WeakMap;function oe(e){switch(e.fixed.type){case"user":{let t=lo.lJ.safeParse(e.summary);return{summary:{type:"user",...t.success?t.data:{text:"",images:[]},hasDetail:!1},detail:void 0}}case"assistant":{let t="pi-desk/assistant"===e.fixed.viewKey?lo.Er.safeParse(e.summary):null,s=t?.success?t.data:{text:"",errorMessage:null},n="pi-desk/assistant"===e.fixed.viewKey?lo.Rh.safeParse(e.detail):null;return{summary:{type:"assistant",text:s.text,model:"model"in s?s.model:null,errorMessage:s.errorMessage,status:e.fixed.status,usage:e.fixed.usage,hasDetail:e.fixed.hasDetail},detail:n?.success?{type:"assistant",...n.data}:void 0}}case"tool":{let t={name:e.fixed.viewKey,reasoning:null,inputPreview:null,activity:null},s={status:e.fixed.status,usage:e.fixed.usage,hasDetail:e.fixed.hasDetail};switch(e.fixed.viewKey){case"pi-desk/codemode":{let n=lo.UT.safeParse(e.summary),r=n.success?n.data:t,i=lo.ny.safeParse(e.detail);return{summary:{type:"tool",kind:"codemode",...r,...s},detail:i.success?{type:"tool",kind:"codemode",...i.data}:void 0}}case"pi-desk/pidesk":{let n=lJ.safeParse(e.summary),r=n.success?n.data:{input:{}},i=lQ.safeParse(e.detail);return{summary:{type:"tool",kind:"pidesk",...t,...r,...s},detail:i.success?{type:"tool",kind:"pidesk",output:i.data.output}:void 0}}case"pi-desk/bash-tool":{let n=lo.Qi.safeParse(e.summary),r=n.success?n.data:{...t,timing:null},i=lo.Ok.safeParse(e.detail);return{summary:{type:"tool",kind:"bash",...r,...s},detail:i.success?{type:"tool",kind:"bash",output:i.data.output}:void 0}}case"pi-desk/read":{let n=lo.Gx.safeParse(e.summary),r=n.success?n.data:{...t,path:null},i=lo.Xj.safeParse(e.detail);return{summary:{type:"tool",kind:"read",...r,...s},detail:i.success?{type:"tool",kind:"read",content:i.data.content}:void 0}}case"pi-desk/edit":{let n=lo.aV.safeParse(e.summary),r=n.success?n.data:{...t,path:null},i=lo.Rk.safeParse(e.detail);return{summary:{type:"tool",kind:"edit",...r,...s},detail:i.success?{type:"tool",kind:"edit",contentKind:i.data.kind,content:i.data.content}:void 0}}case"pi-desk/write":{let n=lo.bN.safeParse(e.summary),r=n.success?n.data:{...t,path:null},i=lo.O_.safeParse(e.detail);return{summary:{type:"tool",kind:"write",...r,...s},detail:i.success?{type:"tool",kind:"write",contentKind:i.data.kind,content:i.data.content}:void 0}}default:{let n=lo.Px.safeParse(e.summary),r=n.success?n.data:t,i=lo.Ok.safeParse(e.detail);return{summary:{type:"tool",kind:"generic",...r,...s},detail:i.success?{type:"tool",kind:"generic",output:i.data.output}:void 0}}}}case"bash":{let t=lo.ai.safeParse(e.summary),s=t.success?t.data:{command:e.fixed.viewKey},n=lo.bG.safeParse(e.detail);return{summary:{type:"bash",command:s.command,status:e.fixed.status,hasDetail:e.fixed.hasDetail},detail:n.success?{type:"bash",...n.data}:void 0}}case"custom":{if("pi-desk/compaction"===e.fixed.viewKey){let t=lo.sL.safeParse(e.detail);return{summary:{type:"compaction",hasDetail:e.fixed.hasDetail},detail:t.success?{type:"compaction",...t.data}:void 0}}let t=lo.Rt.safeParse(e.summary);return{summary:{type:"custom",text:(t.success?t.data:{text:""}).text,hasDetail:!1},detail:void 0}}}}function ot(e){return e.temporary||"status"in e.summary&&"running"===e.summary.status}function os(e){return"assistant"===e.summary.type&&("error"===e.summary.status||!!e.summary.errorMessage||(e.detail?.type==="assistant"?e.detail.thinking.trim().length>0:e.summary.hasDetail))}function on(e,t,s){if("compaction"===s.summary.type){or(e,t),e.push({identity:s.identity,user:null,processItems:[],finalAssistant:null,compaction:s,running:ot(s),toolCount:0});return}"user"!==s.summary.type?t.body.push(s):(or(e,t),t.user=s)}function or(e,t){if(!t.user&&0===t.body.length)return;let s=t.user?.identity??t.body[0].identity;e.push(function(e,t,s){let n=function(e){for(let t=e.length-1;t>=0;t-=1){let s=e[t];if("custom"!==s.summary.type){if("assistant"!==s.summary.type)return -1;return s.summary.text.trim()||"pi-desk/assistant"!==s.viewKey?t:-1}}return -1}(s),r=n>=0?s[n]:null,i=[];for(let[e,t]of s.entries()){if(e!==n){("assistant"!==t.summary.type||"pi-desk/assistant"!==t.viewKey||t.summary.text.trim().length>0||os(t))&&i.push({message:t,hideAssistantText:!1});continue}os(t)&&i.push({message:t,hideAssistantText:!0})}return{identity:e,user:t,processItems:i,finalAssistant:r,compaction:null,running:s.some(ot),toolCount:s.filter(e=>"tool"===e.summary.type||"bash"===e.summary.type).length}}(s,t.user,t.body)),t.user=null,t.body=[]}function oi(e,t=!1){let s=function(e){let t=l9.get(e);if(t)return t;let s=[],n={user:null,body:[]},r=new Set,i=[],a=(e[0]?.location.index??0)>0;for(let t of e){if(r.has(t.location.entryId))continue;r.add(t.location.entryId);let e=function(e){let t=l8.get(e);if(t)return t;let s=oe(e),n={identity:`position:${e.location.index}`,position:e.location.index,viewKey:e.fixed.viewKey,snapshot:e,...s,temporary:!1,timestampMs:e.fixed.timestampMs,durable:e,tempId:null};return l8.set(e,n),n}(t);"compaction"===e.summary.type?(i=[],a=!1):"assistant"===t.fixed.type&&(i.push(e),"assistant"===e.summary.type&&null!==e.timestampMs&&(e.summary.text.trim()||"pi-desk/assistant"!==e.viewKey)&&(e={...e,usageCalls:i,usageIncomplete:a},i=[],a=!1)),on(s,n,e)}let l={turns:s,user:n.user,body:n.body};return l9.set(e,l),l}(e.messages),n=[...s.turns],r={user:s.user,body:[...s.body]};for(let[t,s]of e.temporaryMessages.entries())on(n,r,function(e,t){let s=l7.get(e);if(s?.position===t)return s.message;let n=oe(e),r={identity:`position:${t}`,position:t,viewKey:e.fixed.viewKey,snapshot:e,...n,temporary:!0,timestampMs:e.fixed.timestampMs,durable:null,tempId:e.location.tempId};return l7.set(e,{position:t,message:r}),r}(s,e.messages.length+t));or(n,r);let i=n.at(-1);return t&&i&&!i.compaction&&(i.running=!0),n}function oa(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}m`}function ol(e){return 0===e?"$0":e<1e-4?"<$0.0001":`$${e.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function oo(e,t=Date.now(),s="en",n="UTC"){let r=new Date(e),i=new Date(t),a=function(e,t){if(l6?.locale===e&&l6.timeZone===t)return l6;let s="en"===e?"en-US":"zh-CN";return l6={locale:e,timeZone:t,compactTime:new Intl.DateTimeFormat(s,{timeZone:t,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),compactDateTime:new Intl.DateTimeFormat(s,{timeZone:t,month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),fullDateTime:new Intl.DateTimeFormat(s,{timeZone:t,timeZoneName:"shortOffset",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}),dateKey:new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"})}}(s,n);return{compact:a.dateKey.format(r)===a.dateKey.format(i)?a.compactTime.format(r):a.compactDateTime.format(r),full:a.fullDateTime.format(r)}}function oc(e,t,s={}){if("1"!==new URLSearchParams(window.location.search).get("chatScrollDebug"))return;let n=om(t);console.info("[Pi Desk][ChatScroll]",e,{time:Math.round(10*performance.now())/10,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight,distanceFromBottom:t.scrollHeight-t.scrollTop-t.clientHeight,tailSpace:n?op(n):0,tailMinHeight:n?.style.minHeight||null,tailAnchor:n?.dataset.chatTailAnchor??null,...s})}function od(e,t,s){let n=Array.from(e.querySelectorAll(`[${t}]`));return void 0===s?n.at(-1)??null:n.find(e=>e.getAttribute(t)===s)??null}function ou(e){let t,s=(t=e.querySelectorAll("[data-chat-turn]")).item(t.length-1);return s?.hasAttribute("data-chat-logical-tail")?s:null}function om(e){return e.querySelector("[data-chat-tail-space]")}function op(e){let t=e.lastElementChild;return t instanceof HTMLElement?Math.max(0,e.getBoundingClientRect().bottom-t.getBoundingClientRect().bottom):0}function oh(e,t,s,n){let r=e.getBoundingClientRect(),i=e.scrollTop,a=Math.max(0,i+t.getBoundingClientRect().top-r.top-n),l=i+s.getBoundingClientRect().top-r.top;return{targetScrollTop:a,minHeight:Math.max(0,a+e.clientHeight-l-function(e){let t=e.parentElement;if(!t)return 0;let s=Number.parseFloat(getComputedStyle(t).paddingBottom);return Number.isFinite(s)?s:0}(s))}}function og(e){for(let t of e.querySelectorAll("[data-chat-tail-space]"))oc("tail:clear:start",e),t.style.removeProperty("min-height"),delete t.dataset.chatTailSpace,delete t.dataset.chatTailAnchor,delete t.dataset.chatTailOffset,oc("tail:clear:end",e)}function of(e){let t=om(e);if(!t)return;if(t!==ou(e))return void og(e);let s=t.dataset.chatTailAnchor,n=Number.parseFloat(t.dataset.chatTailOffset??"");if(!s||!Number.isFinite(n))return;let r=od(e,"data-chat-scroll-anchor",s);if(!r)return void og(e);let{minHeight:i}=oh(e,r,t,n),a=`${Math.ceil(i)}px`;t.style.minHeight!==a&&(oc("tail:refresh:start",e,{nextMinHeight:a}),t.style.minHeight=a,oc("tail:refresh:end",e,{nextMinHeight:a}))}function ox(e,t,s,n){oc("position:start",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n});let r=n?ou(e):null;if(r&&om(e)===r||og(e),!r){e.scrollTop=Math.max(0,e.scrollTop+t.getBoundingClientRect().top-e.getBoundingClientRect().top-s),oc("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n});return}let{targetScrollTop:i,minHeight:a}=oh(e,t,r,s),l=`${Math.ceil(a)}px`;r.style.minHeight!==l&&(r.style.minHeight=l),r.hasAttribute("data-chat-tail-space")||(r.dataset.chatTailSpace="");let o=t.dataset.chatScrollAnchor;r.dataset.chatTailAnchor!==o&&(o?r.dataset.chatTailAnchor=o:delete r.dataset.chatTailAnchor),r.dataset.chatTailOffset!==String(s)&&(r.dataset.chatTailOffset=String(s)),e.scrollTop=i,oc("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n,minHeight:a})}function ob({active:e=!0}){let{scrollRef:t,state:s}=(0,lT.B)();return(0,r.useEffect)(()=>{let n,r,i=t.current;if(!i||!e)return;let a=null,l=new Set,o=()=>{null===a&&(a=window.requestAnimationFrame(()=>{a=null,of(i)}))},c=new ResizeObserver(o),d=()=>{let e=new Set,t=om(i);if(t)for(let s of t.children)s instanceof HTMLElement&&e.add(s);for(let t of l)e.has(t)||c.unobserve(t);for(let t of e)l.has(t)||c.observe(t);l=e},u=new MutationObserver(()=>{d(),o()}),m=0,p=null,h=null,g=new ResizeObserver(([e])=>{if(!e)return;let{height:t,width:l}=e.contentRect,c=t-(n??t),d=l-(r??l);(n=t,r=l,c||d)?(oc("viewport:resize",i,{difference:c,widthDifference:d,isAtBottom:s.isAtBottom,escapedFromLock:s.escapedFromLock}),c&&(m=c,s.resizeDifference=c),null!==a&&(window.cancelAnimationFrame(a),a=null),of(i),s.isAtBottom&&(s.scrollTop=Math.max(0,s.calculatedTargetScrollTop)),oc("viewport:resize:positioned",i,{difference:c,widthDifference:d}),c&&(null!==p&&window.cancelAnimationFrame(p),null!==h&&window.clearTimeout(h),p=window.requestAnimationFrame(()=>{p=null,h=window.setTimeout(()=>{h=null,s.resizeDifference===c&&(s.resizeDifference=0),m=0},1)}))):o()});return u.observe(i,{attributes:!0,attributeFilter:["data-chat-tail-space","data-chat-logical-tail"],childList:!0,subtree:!0}),g.observe(i),d(),o(),()=>{null!==a&&window.cancelAnimationFrame(a),null!==p&&window.cancelAnimationFrame(p),null!==h&&window.clearTimeout(h),m&&s.resizeDifference===m&&(s.resizeDifference=0),u.disconnect(),c.disconnect(),g.disconnect()}},[e,t,s]),null}function ov(e){let t=[e.user,...e.processItems.map(e=>e.message),e.finalAssistant,e.compaction].filter(e=>null!==e),s=new Set;return t.filter(e=>!s.has(e.identity)&&(s.add(e.identity),!0))}function ow(e,t,s){let n=0;for(let r=t;r<s;r+=1)e[r]?.user&&(n+=1);return n}function oy(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,ow(e,0,s)),r=s,i=0,a=0,l=0;for(;r>0;){let t=e[r-1],s=ov(t).length,o=l<n;if(i>0&&!o&&(i>=30||a+s>200))break;r-=1,i+=1,a+=s,t.user&&(l+=1)}return r}function ok(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,ow(e,s,e.length)),r=s,i=0,a=0,l=0;for(;r<e.length;){let t=e[r],s=ov(t).length,o=l<n;if(i>0&&!o&&(i>=30||a+s>200))break;r+=1,i+=1,a+=s,t.user&&(l+=1)}return r}function oj(e){return{startIndex:oy(e,e.length),endIndex:e.length}}function oN(e,t){let s,n;if(0===e.length)return{startIndex:0,endIndex:0};if(!t)return oj(e);let r=(n=(s=t.lastIndexOf(":"))>0?t.slice(0,s):t,e.findIndex(e=>ov(e).some(e=>e.identity===n)));if(r<0)return oj(e);let i=Math.min(e.length,r+1+10);return{startIndex:oy(e,i),endIndex:i}}function oI({active:e=!0,turns:t,focusTurnIdentity:s,initialAnchor:i,children:a}){let{scrollRef:l}=(0,lT.B)(),[o,c]=(0,r.useState)(()=>({...oN(t,i),turnCount:t.length,focusTurnIdentity:s}));e||o.focusTurnIdentity===s||c({...o,focusTurnIdentity:s});let d=(0,r.useRef)(null),u=(0,r.useRef)(!1),m=(0,r.useMemo)(()=>{if(0===t.length)return{startIndex:0,endIndex:0};if(e&&o.focusTurnIdentity!==s)return oj(t);if(0===o.turnCount&&0===o.endIndex)return oN(t,i);let n=o.endIndex>=o.turnCount;return{startIndex:Math.min(o.startIndex,t.length),endIndex:n?t.length:Math.max(o.startIndex,Math.min(o.endIndex,t.length))}},[e,s,i,t,o]),p=(0,r.useCallback)(e=>{c({...e,turnCount:t.length,focusTurnIdentity:s})},[s,t.length]),h=(0,r.useCallback)(()=>{let e=l.current,t=e?.querySelector("[data-chat-turn]");e&&t?.dataset.chatTurn&&(d.current={turnIdentity:t.dataset.chatTurn,offset:t.getBoundingClientRect().top-e.getBoundingClientRect().top})},[l]),g=(0,r.useCallback)(()=>{if(m.startIndex<=0||u.current)return;let e=oy(t,m.startIndex);if(e>=m.startIndex)return;h();let s=l.current;s&&oc("window:expand-earlier",s,{previousStartIndex:m.startIndex,nextStartIndex:e}),u.current=!0,p({...m,startIndex:e})},[h,p,m,l,t]),f=(0,r.useCallback)(()=>{if(m.endIndex>=t.length||u.current)return;let e=ok(t,m.endIndex);e<=m.endIndex||(u.current=!0,p({...m,endIndex:e}))},[p,m,t]),x=(0,r.useCallback)(e=>{!Number.isSafeInteger(e)||e<0||e>=t.length||e>=m.startIndex&&e<m.endIndex||(e<m.startIndex?p({...m,startIndex:Math.min(e,oy(t,e+1))}):p({...m,endIndex:Math.max(e+1,ok(t,e))}))},[p,m,t]),b=(0,r.useCallback)(()=>{p(oj(t))},[p,t]);(0,r.useLayoutEffect)(()=>{var e;u.current=!1;let t=d.current;if(!t)return;let s=l.current,n=s?(e=t.turnIdentity,Array.from(s.querySelectorAll("[data-chat-turn]")).find(t=>t.dataset.chatTurn===e)??null):null;if(d.current=null,!s||!n)return;let r=n.getBoundingClientRect().top-s.getBoundingClientRect().top,i=r-t.offset;oc("window:anchor-correction:start",s,{turnIdentity:t.turnIdentity,previousOffset:t.offset,nextOffset:r,correction:i}),s.scrollTop+=i,oc("window:anchor-correction:end",s,{turnIdentity:t.turnIdentity,correction:i})},[m.endIndex,m.startIndex,l]),(0,r.useLayoutEffect)(()=>{let s=l.current;if(!s||!e)return;let n=null,r=()=>{(n=null,s.scrollTop<=24&&m.startIndex>0)?g():s.scrollHeight-s.scrollTop-s.clientHeight<=24&&m.endIndex<t.length&&f()},i=()=>{null===n&&(n=window.requestAnimationFrame(r))},a=e=>{e.deltaY<0&&s.scrollTop<=24?g():e.deltaY>0&&i()},o=()=>{s.scrollTop<=24?g():i()};return s.addEventListener("scroll",i,{passive:!0}),s.addEventListener("wheel",a,{passive:!0}),s.addEventListener("touchmove",o,{passive:!0}),()=>{s.removeEventListener("scroll",i),s.removeEventListener("wheel",a),s.removeEventListener("touchmove",o),null!==n&&window.cancelAnimationFrame(n)}},[e,m,g,f,l,t.length]);let v=(0,r.useMemo)(()=>t.slice(m.startIndex,m.endIndex),[m.endIndex,m.startIndex,t]),w=(0,r.useMemo)(()=>({...m,visibleTurns:v,containsTail:m.endIndex>=t.length,revealTurn:x,resetToTail:b}),[m,b,x,t.length,v]);return(0,n.jsx)(n.Fragment,{children:a(w)})}let oS={canMoveUp:!1,canMoveDown:!1,hasNextMessage:!1};function oC(e,t,s,n){let r=0,i=e.length;for(;r<i;){let a=Math.floor((r+i)/2),l=e[a].getBoundingClientRect().top-t;(n?l>=s:l>s)?i=a:r=a+1}return r}function oE(e){return e.user?`${e.user.identity}:user`:null}function oM(e,t,s){let n,r=Array.from(e.querySelectorAll("[data-chat-user-message]")),i=e.getBoundingClientRect().top+12,a=oC(r,i,-2,!0),l=oC(r,i,2,!1),o=s.find(e=>e>=t.startIndex&&e<t.endIndex),c=s.findLast(e=>e>=t.startIndex&&e<t.endIndex),d=0===a?s.findLast(e=>e<(o??t.startIndex))??null:null,u=l>=r.length?s.find(e=>e>(c??t.endIndex-1))??null:null,m=e.scrollHeight-e.scrollTop-e.clientHeight,p=(n=om(e))?op(n):0,h=t.containsTail&&m<=2;return oc("navigation:inspect",e,{containsTail:t.containsTail,tailSpacerHeight:p,atBottom:h,previousMessage:r[a-1]?.dataset.chatUserMessage??null,nextMessage:r[l]?.dataset.chatUserMessage??null,previousOutsideTurnIndex:d,nextOutsideTurnIndex:u}),{previousMessage:r[a-1]??null,nextMessage:r[l]??null,previousOutsideTurnIndex:d,nextOutsideTurnIndex:u,atBottom:h}}function oz({turns:e,window:t}){let{t:s}=(0,b.Bd)("conversation"),{scrollRef:i,scrollToBottom:a,stopScroll:l}=(0,lT.B)(),o=(0,r.useMemo)(()=>e.flatMap((e,t)=>e.user?[t]:[]),[e]),[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(oS),[p,h]=(0,r.useState)(null),g=(0,r.useRef)(null),f=(0,r.useRef)(!1),x=(0,r.useRef)(!1),v=(0,r.useRef)(null),w=(0,r.useRef)(null),y=(0,r.useRef)(!1),k=(0,r.useRef)(null),j=(0,r.useRef)(!1),N=(0,r.useRef)(!1),S=(0,r.useCallback)(e=>{var s;let n,r=(n=!(s=oM(e,t,o)).atBottom,{canMoveUp:null!==s.previousMessage||null!==s.previousOutsideTurnIndex,canMoveDown:n,hasNextMessage:n&&(null!==s.nextMessage||null!==s.nextOutsideTurnIndex)});y.current&&(r.canMoveDown=!1),m(e=>e.canMoveUp===r.canMoveUp&&e.canMoveDown===r.canMoveDown&&e.hasNextMessage===r.hasNextMessage?e:r)},[t,o]),C=(0,r.useCallback)(e=>{null===w.current&&(w.current=window.requestAnimationFrame(()=>{w.current=null,S(e)}))},[S]),E=(0,r.useCallback)(()=>{null!==v.current&&(window.clearTimeout(v.current),v.current=null)},[]),M=(0,r.useCallback)(()=>{E(),x.current||(v.current=window.setTimeout(()=>{v.current=null,f.current=!1,d(!1),null!==w.current&&(window.cancelAnimationFrame(w.current),w.current=null)},2e3))},[E]),z=(0,r.useCallback)(()=>{null!==g.current&&window.clearTimeout(g.current),g.current=null,h(e=>e?.visible?{...e,visible:!1}:e)},[]),A=(0,r.useCallback)(e=>{null!==g.current&&window.clearTimeout(g.current),h({index:e,visible:!0}),g.current=window.setTimeout(()=>{g.current=null,h(e=>e?.visible?{...e,visible:!1}:e)},2e3)},[]),P=(0,r.useCallback)(()=>{let e=i.current;e&&(f.current||m(oS),f.current=!0,d(!0),C(e),M())},[C,M,i]);(0,r.useLayoutEffect)(()=>{let e=i.current;if(!e)return;let s=k.current;if(s){let n=Array.from(e.querySelectorAll("[data-chat-scroll-anchor]")).find(e=>e.dataset.chatScrollAnchor===s.anchor);n&&(k.current=null,l(),ox(e,n,12,t.containsTail))}j.current&&t.containsTail&&(j.current=!1,og(e),Promise.resolve(a({animation:"instant"})).finally(()=>{y.current=!1,N.current&&f.current&&C(e)}))},[C,i,a,l,t.containsTail,t.endIndex,t.startIndex]),(0,r.useLayoutEffect)(()=>{let e=i.current;if(!e)return;N.current=!0;let t=()=>{z(),P()},s=()=>{f.current&&C(e)},n=t=>{t.target===e&&z()},r=e=>{["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(e.key)&&z()};return e.addEventListener("wheel",t,{passive:!0}),e.addEventListener("touchmove",t,{passive:!0}),e.addEventListener("pointerdown",n,{passive:!0}),e.addEventListener("keydown",r),e.addEventListener("scroll",s,{passive:!0}),()=>{e.removeEventListener("wheel",t),e.removeEventListener("touchmove",t),e.removeEventListener("pointerdown",n),e.removeEventListener("keydown",r),e.removeEventListener("scroll",s),null!==w.current&&(window.cancelAnimationFrame(w.current),w.current=null),N.current=!1}},[z,C,i,P]),(0,r.useLayoutEffect)(()=>()=>{E(),null!==g.current&&window.clearTimeout(g.current),y.current=!1,k.current=null,j.current=!1},[E]),(0,r.useLayoutEffect)(()=>{c&&(u.canMoveUp||u.canMoveDown)||(x.current=!1)},[u.canMoveDown,u.canMoveUp,c]);let D=(0,r.useCallback)((s,n)=>{let r=i.current;if(!r)return;P();let c=oM(r,t,o),d="up"===s?c.previousMessage:c.atBottom?null:c.nextMessage;if(d){let s=o.findIndex(t=>oE(e[t])===d.dataset.chatScrollAnchor);s>=0&&A(s+1),y.current=!1,l(),ox(r,d,12,t.containsTail)}else{let i="up"===s?c.previousOutsideTurnIndex:c.nextOutsideTurnIndex;if(null!==i){let s=oE(e[i]);s&&(A(o.indexOf(i)+1),y.current=!1,k.current={anchor:s},t.revealTurn(i))}else"down"===s&&(o.length>0&&A(o.length),n&&(n.disabled=!0),m(e=>e.canMoveDown?{...e,canMoveDown:!1}:e),c.atBottom||y.current||(oc("navigation:bottom:start",r,{containsTail:t.containsTail}),y.current=!0,og(r),t.containsTail?Promise.resolve(a({animation:"instant"})).finally(()=>{y.current=!1,N.current&&f.current&&C(r)}):(j.current=!0,t.resetToTail())))}C(r)},[C,i,a,P,A,l,e,t,o]),T=c&&(u.canMoveUp||u.canMoveDown),O=s(u.hasNextMessage?"nextUserMessage":"bottom");return(0,n.jsxs)(n.Fragment,{children:[p&&o.length>0?(0,n.jsxs)("div",{role:"status","aria-hidden":!p.visible,"aria-label":`${s("userNavigation")} ${p.index} / ${o.length}`,className:`pointer-events-none absolute top-1/2 left-3 z-10 -translate-y-1/2 rounded-lg border bg-background/95 px-2 py-2 shadow-sm transition-opacity duration-150 motion-reduce:transition-none sm:left-4 ${p.visible?"opacity-100":"opacity-0"}`,children:[(0,n.jsxs)("div",{className:"text-center text-sm font-medium tabular-nums",children:[p.index," / ",o.length]}),(0,n.jsx)("div",{className:"relative mx-auto mt-2 h-28 w-0.5 rounded-full bg-border",children:(0,n.jsx)("span",{className:"absolute left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground",style:{top:`${(p.index-1)/Math.max(1,o.length-1)*100}%`}})})]}):null,T?(0,n.jsxs)(tV,{orientation:"vertical",className:"absolute right-3 bottom-4 z-10 rounded-lg shadow-sm sm:right-4","aria-label":s("userNavigation"),onMouseEnter:()=>{x.current=!0,E()},onMouseLeave:()=>{x.current=!1,f.current&&M()},children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"icon",className:"size-10 bg-background/90 backdrop-blur dark:bg-background/90",disabled:!u.canMoveUp,"aria-label":s("previousUserMessage"),title:s("previousUserShort"),onClick:()=>D("up"),children:(0,n.jsx)($.A,{className:"size-4"})}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"icon",className:"size-10 bg-background/90 backdrop-blur dark:bg-background/90",disabled:!u.canMoveDown,"aria-label":O,title:O,onClick:e=>D("down",e.currentTarget),children:(0,n.jsx)(R.A,{className:"size-4"})})]}):null]})}let oA=(0,r.createContext)({basic:!1});function o$({basic:e,onRecover:t,children:s}){let i=(0,r.useMemo)(()=>({basic:e,recover:t}),[e,t]);return(0,n.jsx)(oA.Provider,{value:i,children:s})}function oR(e){return{location:e.snapshot.location,fixed:e.snapshot.fixed,summary:e.snapshot.summary,...void 0===e.snapshot.detail?{}:{detail:e.snapshot.detail}}}class oP{constructor(e,t){this.listeners=new Set,this.pending=null,this.requestEpoch=0,this.disposed=!1,this.basic=!1,this.message=e,this.snapshot=oR(e),this.loader=t,this.detailLoaded=void 0!==this.snapshot.detail||!this.snapshot.fixed.hasDetail}getSnapshot(){return this.snapshot}subscribe(e){if(this.disposed)throw Error("Message Handle has been disposed");return this.listeners.add(e),()=>{this.listeners.delete(e)}}loadDetail(){if(this.detailLoaded)return Promise.resolve(this.snapshot.detail??null);if(!this.snapshot.fixed.hasDetail)return Promise.resolve(null);if(!("entryId"in this.snapshot.location))return Promise.reject(Error("Temporary Message 不能读取 canonical Detail"));if(this.pending)return this.pending;let e=this.requestEpoch,t=this.loader(this.message).then(t=>(this.disposed||e!==this.requestEpoch||(this.detailLoaded=!0,this.snapshot={...this.snapshot,...null===t?{}:{detail:t}},this.notify()),t)).finally(()=>{this.pending===t&&(this.pending=null)});return this.pending=t,t}replace(e,t,s){if(this.disposed)return;let n=oR(e);if(this.snapshot===n)return;let r=this.basic!==s||void 0!==this.snapshot.detail&&void 0===n.detail||this.snapshot.fixed.viewKey!==n.fixed.viewKey||"entryId"in this.snapshot.location&&"entryId"in n.location&&this.snapshot.location.entryId!==n.location.entryId;this.basic=s,this.message=e,this.loader=t,this.snapshot=n,r?(this.requestEpoch+=1,this.pending=null,this.detailLoaded=void 0!==n.detail||!n.fixed.hasDetail):void 0===n.detail&&n.fixed.hasDetail||(this.detailLoaded=!0),this.notify()}dispose(){this.disposed||(this.disposed=!0,this.listeners.clear(),this.requestEpoch+=1,this.pending=null)}notify(){for(let e of[...this.listeners])e()}}function oD({message:e,pluginName:t,contributionName:s,phase:i,error:a,handle:l,fallback:o,onRetry:c}){let{t:d}=(0,b.Bd)("conversation"),[u,m]=(0,r.useState)(l.getSnapshot().detail),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(null),x=(0,r.useContext)(oA),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),N=a.name,S=a.message,C=a.stack;return(0,r.useEffect)(()=>{console.error("[Pi Desk][MessageView] 消息视图无法展示",{messageId:e.identity,viewKey:e.viewKey,pluginName:t,contributionName:s,phase:i,errorName:N,message:S,stack:C})},[e.identity,e.viewKey,t,s,i,N,S,C]),(0,n.jsxs)("div",{className:"space-y-2","data-message-id":e.identity,children:[o,(0,n.jsx)("div",{role:"alert",className:"rounded-lg border border-destructive/35 bg-muted/30 p-3 text-sm",children:(0,n.jsxs)("div",{className:"flex items-start gap-2",children:[(0,n.jsx)(e_.A,{className:"mt-0.5 size-4 shrink-0 text-destructive"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"font-medium text-destructive",children:d("viewFailed")}),"pi-desk/message-declaration-error"===e.viewKey&&"string"==typeof e.snapshot.summary.text&&e.snapshot.summary.text.length>0?(0,n.jsx)("p",{className:"mt-2 whitespace-pre-wrap break-words text-foreground",children:e.snapshot.summary.text}):null,(0,n.jsxs)(eU,{error:a,children:[(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[t??"Host"," \xb7 ",s??d("reservedView")," \xb7 ",e.viewKey," ","\xb7 ",i]}),(0,n.jsxs)("details",{className:"text-sm",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:d("publicSnapshot")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto rounded-md bg-background p-3 font-mono text-sm whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(l.getSnapshot(),null,2)})]}),!e.temporary&&e.snapshot.fixed.hasDetail&&void 0===u?(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:p,onClick:()=>{h(!0),f(null),l.loadDetail().then(m,e=>{f(e instanceof Error?e.message:d("detailFailed"))}).finally(()=>h(!1))},children:[p?(0,n.jsx)(v.A,{className:"animate-spin"}):null,d("loadDetail")]}):null,g?(0,n.jsx)("p",{className:"text-sm text-destructive [overflow-wrap:anywhere]",children:g}):null,u?(0,n.jsx)("pre",{className:"max-h-48 overflow-auto rounded-md bg-background p-3 font-mono text-sm whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(u,null,2)}):null]}),x.recover?(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",className:"mt-2 mr-2",disabled:w,onClick:()=>{y(!0),x.recover().catch(e=>f(e instanceof Error?e.message:String(e))).finally(()=>y(!1))},children:[w?(0,n.jsx)(v.A,{className:"animate-spin"}):null,d("useBasicPresentation")]}):null,c?(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",className:"mt-2",disabled:k,onClick:()=>{j(!0),f(null),Promise.resolve().then(c).catch(e=>f(e instanceof Error?e.message:String(e))).finally(()=>j(!1))},children:[k?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(es.A,{}),d("retry")]}):null]})]})})]})}function oT({message:e}){let{t}=(0,b.Bd)("conversation");return(0,n.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm","aria-busy":"true",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",role:"status",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),t("viewLoading")]}),(0,n.jsxs)("details",{className:"mt-2",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:t("messageContent")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(e.snapshot.summary,null,2)})]})]})}function oO({message:e,loadDetail:t,defaultView:s}){let{t:i}=(0,b.Bd)("conversation"),a=(0,Q.t4)();(0,Q.So)();let l=(0,r.useContext)(oA),o=(0,r.useRef)(null),c=(0,r.useRef)(null),d=(0,r.useRef)(null),[u,m]=(0,r.useState)({status:"loading"}),[p]=(0,r.useState)(()=>new oP(e,t)),[h,g]=(0,r.useState)(0),f=a.getMessageViewResolution(e.viewKey),x=a.areEntriesInitialized(),v=!f&&a.isRefreshingEntries(),w=f?.status==="winner"?`${e.viewKey}\u0000${f.pluginName}\u0000${f.descriptor.contributionName}\u0000${f.descriptor.priority}`:f?.status==="conflict"?`${e.viewKey}\u0000${f.candidates.map(e=>`${e.pluginName}:${e.descriptor.contributionName}`).join(",")}`:e.viewKey,y=f?.status==="winner"?f.pluginName:null,k=f?.status==="winner"?f.descriptor.contributionName:null,j=y?a.getEntryState(y):null,N=j?.status==="ready"?j.runtime:j?.status,I=e.viewKey.startsWith("pi-desk/")&&"pi-desk/message-declaration-error"!==e.viewKey,S=I&&null===f,C=(0,r.useMemo)(()=>({attempt:h,basic:l.basic,resolutionKey:w,winnerIdentity:N}),[h,l.basic,w,N]),E=(0,r.useMemo)(()=>({kind:"message-view",message:{getSnapshot:()=>p.getSnapshot(),subscribe:e=>d.current!==C?()=>void 0:p.subscribe(()=>{if(d.current===C&&y&&a.getEntryState(y)===j)try{e()}catch(e){m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"update",generation:C})}}),loadDetail:async()=>{if(d.current!==C)throw Error("Message View 已释放");let e=await p.loadDetail();if(d.current!==C)throw Error("Message View 已释放");return e}},reportError(e){d.current===C&&y&&a.getEntryState(y)===j&&m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"report-error",generation:C})}}),[p,C,a,j,y]);if((0,r.useLayoutEffect)(()=>(d.current=C,p.replace(e,t,l.basic),()=>{d.current===C&&(d.current=null)}),[p,t,e,l.basic,C]),(0,r.useEffect)(()=>{let e={};return c.current=e,()=>{c.current===e&&(c.current=null),queueMicrotask(()=>{null===c.current&&p.dispose()})}},[p]),(0,r.useEffect)(()=>{if(l.basic)return void queueMicrotask(()=>m({status:"loading"}));if(!x||S||"pi-desk/message-declaration-error"===e.viewKey||!y||!k||j?.status!=="ready")return;let t=o.current;if(!t)return;let s=new AbortController,n=!0,r=null;queueMicrotask(()=>{n&&m({status:"loading"})});let i=Promise.resolve().then(()=>n?(r=document.createElement("div"),t.append(r),a.mountContribution({pluginName:y,kind:"message-view",contributionName:k,container:r,target:E,signal:s.signal})):null);return i.then(e=>{n&&e&&a.getEntryState(y)===j&&m(e=>"error"===e.status&&e.generation===C?e:{status:"ready",generation:C})},e=>{n&&a.getEntryState(y)===j&&m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"mount",generation:C})}),()=>{n=!1,s.abort(),r?.remove(),i.then(async e=>{await e?.()},()=>void 0)}},[h,S,x,e.viewKey,C,y,k,j,a,E,l.basic]),l.basic)return(0,n.jsx)(n.Fragment,{children:s});if("pi-desk/message-declaration-error"===e.viewKey)return(0,n.jsx)(oD,{message:e,pluginName:"pi-desk",contributionName:"message-declaration-error",phase:"declaration",error:Error(i("declarationFailed")),handle:p});if(!x)return I?(0,n.jsx)(n.Fragment,{children:s}):(0,n.jsx)(oT,{message:e});if(f?.status==="conflict")return(0,n.jsx)(oD,{message:e,pluginName:null,contributionName:null,phase:"priority-conflict",error:Error(i("viewConflict")),handle:p,fallback:I?s:void 0});if(!f)return I?(0,n.jsx)(n.Fragment,{children:s}):v?(0,n.jsx)(oT,{message:e}):(0,n.jsx)(oD,{message:e,pluginName:null,contributionName:null,phase:"missing-view",error:Error(i("viewMissing",{viewKey:e.viewKey})),handle:p,onRetry:async()=>{await a.refreshEntries(),await Promise.all(a.getFailedEntries().map(({pluginName:e})=>a.retryEntry(e)))}});if("error"===u.status&&u.generation===C)return(0,n.jsx)(oD,{message:e,pluginName:f.pluginName,contributionName:f.descriptor.contributionName,phase:u.phase,error:u.error,handle:p,fallback:I?s:void 0,onRetry:()=>{let e=a.getContributionLoadState(f.pluginName,"message-view",f.descriptor.contributionName);(m({status:"loading"}),"failed"!==e.status)?g(e=>e+1):a.retryContribution(f.pluginName,"message-view",f.descriptor.contributionName).then(()=>g(e=>e+1),e=>{m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"load",generation:C})})}});let M="ready"===u.status&&u.generation===C;return(0,n.jsxs)("div",{className:"relative","data-message-id":e.identity,"aria-busy":!M,children:[M?null:I?s:(0,n.jsx)(oT,{message:e}),(0,n.jsx)("div",{ref:o,className:M?void 0:"pointer-events-none invisible absolute inset-x-0 top-0","data-pi-desk-plugin":f.pluginName,"data-pi-desk-kind":"message-view","data-pi-desk-contribution":f.descriptor.contributionName})]})}var oL=s(41934),oF=s(4795),oB=s(33353),oq=s(15948),o_=s(7010),oW=s(64572),oY=s(69272),oV=s(47125),oU=s(9922);let oK=new Map,oH=(0,r.memo)(({children:e,as:t="p",className:s,duration:i=2,spread:a=2})=>{let l,o=((l=oK.get(t))||(l=oU.PY1.create(t),oK.set(t,l)),l),c=(0,r.useMemo)(()=>(e?.length??0)*a,[e,a]);return(0,n.jsx)(o,{animate:{backgroundPosition:"0% center"},className:(0,C.cn)("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",s),initial:{backgroundPosition:"100% center"},style:{"--spread":`${c}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{duration:i,ease:"linear",repeat:1/0},children:e})}),oG=(0,r.createContext)(null),oJ=(0,r.memo)(({className:e,isStreaming:t=!1,open:s,defaultOpen:i,onOpenChange:a,duration:l,children:o,...c})=>{let d=i??t,u=!1===i,[m,p]=(0,oV.i)({defaultProp:d,onChange:a,prop:s}),[h,g]=(0,oV.i)({defaultProp:void 0,prop:l}),f=(0,r.useRef)(t),[x,b]=(0,r.useState)(!1),v=(0,r.useRef)(null);(0,r.useEffect)(()=>{t?(f.current=!0,null===v.current&&(v.current=Date.now())):null!==v.current&&(g(Math.ceil((Date.now()-v.current)/1e3)),v.current=null)},[t,g]),(0,r.useEffect)(()=>{!t||m||u||p(!0)},[t,m,p,u]),(0,r.useEffect)(()=>{if(f.current&&!t&&m&&!x){let e=setTimeout(()=>{p(!1),b(!0)},1e3);return()=>clearTimeout(e)}},[t,m,p,x]);let w=(0,r.useCallback)(e=>{p(e)},[p]),y=(0,r.useMemo)(()=>({duration:h,isOpen:m,isStreaming:t,setIsOpen:p}),[h,m,t,p]);return(0,n.jsx)(oG.Provider,{value:y,children:(0,n.jsx)(eV.Nt,{className:(0,C.cn)("not-prose mb-4",e),onOpenChange:w,open:m,...c,children:o})})}),oQ=(e,t)=>e||0===t?(0,n.jsx)(oH,{duration:1,children:"Thinking..."}):void 0===t?(0,n.jsx)("p",{children:"Thought for a few seconds"}):(0,n.jsxs)("p",{children:["Thought for ",t," seconds"]}),oX=(0,r.memo)(({className:e,children:t,getThinkingMessage:s=oQ,...i})=>{let{isStreaming:a,isOpen:l,duration:o}=(()=>{let e=(0,r.useContext)(oG);if(!e)throw Error("Reasoning components must be used within Reasoning");return e})();return(0,n.jsx)(eV.R6,{className:(0,C.cn)("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...i,children:t??(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oL.A,{className:"size-4"}),s(a,o),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-4 transition-transform",l?"rotate-180":"rotate-0")})]})})}),oZ={cjk:tK.h,code:tH.a,math:tG.D,mermaid:tJ.a},o0=(0,r.memo)(({className:e,children:t,...s})=>(0,n.jsx)(eV.Ke,{className:(0,C.cn)("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...s,children:(0,n.jsx)(tQ.jH,{plugins:oZ,children:t})}));oJ.displayName="Reasoning",oX.displayName="ReasoningTrigger",o0.displayName="ReasoningContent";var o1=s(52216),o2=s.n(o1);function o5({messages:e,incomplete:t,children:s}){let{t:i}=(0,b.Bd)("conversation"),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)(!1),d=(0,r.useRef)(null),u=(0,r.useRef)(!1);return(0,n.jsxs)(eW.AM,{open:a,onOpenChange:(e,t)=>{if(!e&&"trigger-press"===t.reason&&u.current){u.current=!1,t.cancel();return}e&&"trigger-hover"===t.reason&&o||!e&&"trigger-hover"===t.reason&&(!u.current||d.current?.contains(document.activeElement))?t.cancel():(e?u.current="trigger-hover"===t.reason:"trigger-hover"!==t.reason&&(u.current=!1,c(!0)),l(e))},children:[(0,n.jsx)(eW.Wv,{openOnHover:!o,delay:250,closeDelay:180,onPointerLeave:()=>c(!1),className:"min-w-0 cursor-pointer rounded-sm text-left text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:s}),(0,n.jsxs)(eW.hl,{ref:d,align:"start",side:"top",initialFocus:()=>!u.current,className:(0,C.cn)(o2().panel,"w-[30rem] gap-0 p-2"),children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b px-1 pb-1",children:[(0,n.jsx)(eW.eO,{className:"min-w-0 flex-1 text-xs font-medium text-muted-foreground",children:i(t?"calls.loadedTitle":"calls.title")}),(0,n.jsx)("button",{type:"button","aria-label":i("calls.close"),className:"flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{u.current=!1,c(!0),l(!1)},children:(0,n.jsx)(V.A,{className:"size-3.5"})})]}),a?(0,n.jsx)("div",{className:"min-h-0 overflow-y-auto overscroll-contain",children:(0,n.jsxs)("div",{className:o2().table,children:[(0,n.jsxs)("div",{className:(0,C.cn)(o2().row,"text-muted-foreground"),children:[(0,n.jsx)("span",{children:i("calls.model")}),(0,n.jsx)("span",{children:i("calls.input")}),(0,n.jsx)("span",{children:i("calls.output")}),(0,n.jsx)("span",{children:i("calls.cached")}),(0,n.jsx)("span",{children:i("calls.cost")})]}),e.map(e=>{let t=e.snapshot.fixed;if("assistant"!==t.type)return null;let s="assistant"===e.summary.type?e.summary.model:null,r=t.usage;return(0,n.jsxs)("div",{className:o2().row,children:[(0,n.jsxs)("span",{className:"flex min-w-0 items-center gap-1",children:[(0,n.jsxs)("span",{className:"min-w-0 truncate",title:s?`${s.modelId} \xb7 ${s.provider}`:void 0,children:[s?.modelId||i("calls.unknownModel"),s?.provider?(0,n.jsxs)("span",{className:"text-muted-foreground",children:[" \xb7 ",s.provider]}):null]}),"error"===t.status||"aborted"===t.status?(0,n.jsx)("span",{className:"shrink-0 text-destructive",children:i(`calls.${t.status}`)}):null]}),(0,n.jsx)("span",{children:oa(r.inputTokens)}),(0,n.jsx)("span",{children:oa(r.outputTokens)}),(0,n.jsx)("span",{children:oa(r.cacheReadTokens)}),(0,n.jsx)("span",{children:ol(r.costUsd)})]},e.durable.location.entryId)})]})}):null]})]})}function o3({nestedCalls:e}){let{t}=(0,b.Bd)("conversation");return(0,n.jsxs)("section",{className:"border-t px-3 py-3 text-sm",children:[(0,n.jsx)("h4",{className:"mb-2 font-medium",children:t(e.complete?"nestedCalls":"nestedCallsIncomplete")}),(0,n.jsx)("ol",{className:"max-h-[min(24rem,45dvh)] space-y-2 overflow-auto",children:e.calls.map((e,s)=>(0,n.jsxs)("li",{className:"border-b pb-2 last:border-0 last:pb-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,n.jsx)("span",{className:"text-xs tabular-nums text-muted-foreground",children:s+1}),(0,n.jsx)("span",{className:"min-w-0 break-words font-mono font-medium",children:e.name}),(0,n.jsx)("span",{className:"error"===e.status?"text-xs text-destructive":"text-xs text-muted-foreground",children:t(`nestedStatus.${e.status}`)}),void 0===e.durationMs?null:(0,n.jsxs)("span",{className:"ml-auto text-xs tabular-nums text-muted-foreground",children:[e.durationMs," ms"]})]}),e.arguments?(0,n.jsxs)("details",{className:"mt-1",children:[(0,n.jsx)("summary",{className:"min-h-7 cursor-pointer text-xs text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring",children:t("nestedArguments")}),(0,n.jsx)("pre",{className:"max-h-48 overflow-auto whitespace-pre-wrap break-words py-2 font-mono text-sm",children:JSON.stringify(e.arguments,null,2)})]}):null,void 0===e.argumentsBytes?null:(0,n.jsx)("p",{className:"mt-1 text-xs tabular-nums text-muted-foreground",children:t("nestedArgumentsBytes",{count:e.argumentsBytes})}),e.error?(0,n.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-destructive",children:e.error}):null]},s))})]})}function o4({plugin:e}){let{t}=(0,b.Bd)("conversation"),{locale:s}=(0,eQ.i)();return(0,n.jsxs)("div",{className:"min-w-0 space-y-1 py-2 first:pt-0 last:pb-0",role:"listitem",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.name}),(0,n.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:e.version??t("pidesk.unknownVersion")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`pidesk.status.${e.status}`)})]}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[t(`pidesk.kind.${e.kind}`)," \xb7 ",(0,n.jsx)("span",{className:"font-mono",children:e.source})]}),e.updateTag||e.availableVersion?(0,n.jsxs)("p",{className:"flex flex-wrap gap-x-3 text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e.updateTag?(0,n.jsx)("span",{children:t("pidesk.updateChannel",{tag:e.updateTag})}):null,e.availableVersion?(0,n.jsx)("span",{children:t("pidesk.targetVersion",{version:e.availableVersion})}):null]}):null,e.updateError?(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:e.updateError}):null,e.operation?(0,n.jsxs)("p",{className:"[overflow-wrap:anywhere]",children:[t(`pidesk.action.${e.operation.action}`)," \xb7 ",t(`pidesk.phase.${e.operation.phase}`),e.operation.message?` \xb7 ${e.operation.message}`:""]}):null,e.error?(0,n.jsxs)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:[t(`pidesk.errorPhase.${e.error.phase}`)," \xb7 ",(0,eJ.fD)(e.error.message,s)]}):null]})}function o6({result:e}){let{t}=(0,b.Bd)("conversation"),{locale:s}=(0,eQ.i)();return"info"===e.kind?(0,n.jsx)("dl",{className:"grid grid-cols-[max-content_minmax(0,1fr)] gap-x-4 gap-y-2",children:Object.entries(e.data).map(([e,s])=>(0,n.jsxs)("div",{className:"contents",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:t(`pidesk.info.${e}`)}),(0,n.jsx)("dd",{className:"min-w-0 [overflow-wrap:anywhere]",children:"environment"===e?t(`pidesk.environment.${s}`):"mode"===e?t(`pidesk.mode.${s}`):(0,n.jsx)("span",{className:"font-mono",children:s})})]},e))}):"plugin"===e.kind?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{role:"list",children:(0,n.jsx)(o4,{plugin:e.data})}),(0,n.jsx)("p",{className:"mt-3 mb-2 font-medium",children:t("pidesk.pluginDetail")}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono leading-relaxed",children:JSON.stringify(e.data.detail,null,2)})]}):(0,n.jsxs)(n.Fragment,{children:[e.data.restartRequired?(0,n.jsx)("p",{className:"mb-2",children:t("pidesk.restartRequired")}):null,e.data.loadError?(0,n.jsx)("p",{className:"mb-2 text-destructive [overflow-wrap:anywhere]",children:(0,eJ.fD)(e.data.loadError,s)}):null,e.data.plugins.length>0?(0,n.jsx)("div",{className:"divide-y divide-border",role:"list",children:e.data.plugins.map((e,t)=>(0,n.jsx)(o4,{plugin:e},`${e.source}:${t}`))}):(0,n.jsx)("p",{className:"text-muted-foreground",children:t("pidesk.noPlugins")})]})}function o8({identity:e,command:t,output:s,expandable:r,open:i,loading:a,error:l,onOpenChange:o,commandAction:c,outputAction:d}){let{t:u}=(0,b.Bd)("conversation"),m=t.label?[u(t.label),t.name,t.version].filter(Boolean).join(" \xb7 "):t.command,p=null===s?null:function(e,t){let s;if(!["pideskListPlugins","pideskShowPlugin","pideskInfo"].includes(e??""))return null;try{s=JSON.parse(t)}catch{return null}switch(e){case"pideskListPlugins":{let e=l5.safeParse(s);return e.success?{kind:"plugins",data:e.data}:null}case"pideskShowPlugin":{let e=l3.safeParse(s);return e.success?{kind:"plugin",data:e.data}:null}case"pideskInfo":{let e=l4.safeParse(s);return e.success?{kind:"info",data:e.data}:null}default:return null}}(t.label,s);return(0,n.jsxs)(eV.Nt,{open:r&&i,onOpenChange:o,className:"w-full min-w-0 overflow-hidden rounded-lg border border-border bg-card text-sm leading-relaxed","data-message-id":e,"data-chat-scroll-anchor":`${e}:tool`,children:[(0,n.jsxs)(eV.R6,{disabled:!r,"aria-label":r?u(i?"collapseTool":"expandTool",{name:m}):m,className:(0,C.cn)("flex min-h-9 w-full min-w-0 items-center gap-2 px-3 py-1.5 text-left",r&&"cursor-pointer hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"),children:[(0,n.jsx)(nX.A,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,n.jsx)("span",{className:(0,C.cn)("min-w-0 flex-1 truncate font-medium",!t.label&&"font-mono"),title:m,children:m}),r?(0,n.jsx)(eY.A,{className:(0,C.cn)("size-4 shrink-0 text-muted-foreground transition-transform",i&&"rotate-180"),"aria-hidden":"true"}):null]}),(0,n.jsx)(eV.Ke,{className:"h-[var(--collapsible-panel-height)] overflow-hidden transition-[height,opacity] duration-200 ease-out data-starting-style:h-0 data-starting-style:opacity-0 data-ending-style:h-0 data-ending-style:opacity-0 motion-reduce:transition-none",children:(0,n.jsxs)("div",{className:"border-t",children:[(0,n.jsxs)("section",{className:"border-b px-3 py-2","aria-label":u("pidesk.command"),children:[(0,n.jsxs)("div",{className:"mb-1 flex min-h-7 items-center justify-between gap-2",children:[(0,n.jsx)("h4",{className:"font-medium text-muted-foreground",children:u("pidesk.command")}),c]}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono leading-relaxed",children:t.command})]}),(0,n.jsxs)("section",{"aria-label":u("pidesk.output"),children:[(0,n.jsxs)("div",{className:"flex min-h-9 items-center justify-between gap-2 px-3 pt-2",children:[(0,n.jsx)("h4",{className:"font-medium text-muted-foreground",children:u("pidesk.output")}),d]}),(0,n.jsx)("div",{className:"max-h-[min(24rem,50dvh)] overflow-auto px-3 pt-1 pb-3",role:"region","aria-label":u("pidesk.output"),tabIndex:0,children:a?(0,n.jsx)("p",{className:"text-muted-foreground",children:u("loadingResult")}):l?(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:l}):s?p?(0,n.jsx)(o6,{result:p}):(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono leading-relaxed",children:s}):(0,n.jsx)("p",{className:"text-muted-foreground",children:u("pidesk.empty")})})]})]})})]})}var o7=s(43769),o9=s.n(o7);let ce="max-h-[min(20rem,45dvh)] overflow-auto [scrollbar-gutter:stable]",ct=(0,r.createContext)(()=>void 0),cs=(0,r.createContext)(null),cn=(0,r.createContext)(null),cr="h-[var(--collapsible-panel-height)] overflow-hidden transition-[height,opacity] duration-200 ease-out data-starting-style:h-0 data-starting-style:opacity-0 data-ending-style:h-0 data-ending-style:opacity-0 motion-reduce:transition-none";function ci({children:e}){let{isAtBottom:t,stopScroll:s}=(0,lT.B)(),i=(0,r.useRef)(t),a=(0,r.useRef)(s);(0,r.useLayoutEffect)(()=>{i.current=t,a.current=s},[t,s]);let l=(0,r.useCallback)(()=>{i.current&&a.current()},[]);return(0,n.jsx)(ct.Provider,{value:l,children:e})}function ca(e,t){let{t:s}=(0,b.Bd)("conversation"),[n,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(null),o=(0,r.useCallback)(async()=>{if(!e.temporary&&e.durable&&e.snapshot.fixed.hasDetail&&void 0===e.detail&&!n){i(!0),l(null);try{await t(e)}catch(e){l(e instanceof Error?e.message:s("detailFailed"))}finally{i(!1)}}},[n,e,t,s]);return{loading:n,error:a,load:o}}function cl(e,t){let[s,n]=(0,r.useState)(!1),i=(0,r.useContext)(ct),{loading:a,error:l,load:o}=ca(e,t),c=!e.temporary&&(e.summary.hasDetail||"tool"===e.summary.type&&!!e.summary.images?.length);return{open:s,expandable:c,loading:a,error:l,handleOpenChange:e=>{c&&(e&&(i(),o()),n(e))}}}function co({timestampMs:e}){let{locale:t,timeZone:s}=(0,eQ.i)(),r=oo(e,void 0,t,s);return(0,n.jsx)("time",{dateTime:new Date(e).toISOString(),title:r.full,className:"shrink-0",children:r.compact})}function cc({text:e,copyLabel:t,alwaysVisible:s=!1}){let{t:i}=(0,b.Bd)("conversation"),a=(0,X.G)(),[l,o]=(0,r.useState)(!1),c=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{null!==c.current&&window.clearTimeout(c.current)},[]);let d=(0,r.useCallback)(async()=>{let t=!1;try{t=await (0,e9.x)(e)}catch{t=!1}t?(o(!0),null!==c.current&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{c.current=null,o(!1)},1500)):a.error(i("messageCopyFailed"))},[e,a,i]);if(!e.trim())return null;let u=l?i("copied"):t??i("copyMessage");return(0,n.jsx)(t0,{tooltip:u,label:u,size:"icon-sm",className:(0,C.cn)(!s&&o9().messageCopyAction,"text-muted-foreground"),onClick:()=>void d(),children:l?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})})}function cd({usage:e,compactOnly:t=!1}){let{t:s}=(0,b.Bd)("conversation"),r=oa(e.inputTokens),i=oa(e.outputTokens),a=oa(e.cacheReadTokens),l=ol(e.costUsd),o=s("usage",{input:r,output:i,cached:a,cost:l}),c=`${r}/${i}/${a}/${l}`;return t?(0,n.jsx)("span",{className:"shrink-0 font-mono text-xs tabular-nums text-muted-foreground",title:o,"aria-label":o,children:c}):(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("span",{className:o9().usageLabeled,children:o}),(0,n.jsx)("span",{className:o9().usageCompact,children:c})]})}function cu({message:e}){if("assistant"!==e.summary.type||null===e.timestampMs)return null;let t="running"!==e.summary.status?e.summary.text:null;return(0,n.jsxs)(t5,{className:(0,C.cn)(o9().usageToolbar,"mt-1 flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground"),children:[e.usageCalls?.length?(0,n.jsx)(o5,{messages:e.usageCalls,incomplete:e.usageIncomplete??!1,children:(0,n.jsx)(cd,{usage:e.summary.usage})},e.durable.location.entryId):(0,n.jsx)(cd,{usage:e.summary.usage}),(0,n.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-1",children:[null===t?null:(0,n.jsx)(cc,{text:t}),null===e.timestampMs?null:(0,n.jsx)(co,{timestampMs:e.timestampMs})]})]})}function cm({message:e,onAcquireImage:t}){let{t:s}=(0,b.Bd)("conversation"),i="user"===e.summary.type||"tool"===e.summary.type?e.summary.images??[]:[],a=i.length,l=(0,r.useRef)(e);(0,r.useLayoutEffect)(()=>{l.current=e},[e]);let[o,c]=(0,r.useState)(()=>Array.from({length:a},()=>({status:"loading"}))),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(0);return(0,r.useLayoutEffect)(()=>{let e=!0,s=Array.from({length:a},()=>null);for(let n=0;n<a;n+=1){let r=t=>{e?(s[n]=t.release,c(e=>{let s=[...e];return s[n]={status:"ready",url:t.url},s})):t.release()},i=()=>{e&&c(e=>{let t=[...e];return t[n]={status:"error"},t})};try{let e=t(l.current,n);"then"in e?e.then(r).catch(i):r(e)}catch{i()}}return()=>{e=!1,s.forEach(e=>e?.())}},[a,e.identity,e.tempId,e.durable?.location.entryId,t,m]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"mb-2 grid grid-cols-2 gap-2 sm:grid-cols-3",children:i.map((e,t)=>{let r=o[t];return r?.status==="error"?(0,n.jsxs)("button",{type:"button",className:"flex aspect-square min-h-20 cursor-pointer flex-col items-center justify-center gap-2 rounded-md border bg-muted px-2 text-center text-xs text-muted-foreground hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{u(null),c(e=>e.map(e=>"error"===e.status?{status:"loading"}:e)),p(e=>e+1)},children:[(0,n.jsx)("span",{children:s("imageUnavailable")}),(0,n.jsx)("span",{className:"text-sm font-medium text-foreground",children:s("retry",{ns:"common"})})]},`${t}:${e.width}:${e.height}`):r?.status!=="ready"?(0,n.jsx)("div",{className:"grid aspect-square min-h-20 place-items-center rounded-md border bg-muted px-2 text-center text-xs text-muted-foreground",children:s("imageLoading")},`${t}:${e.width}:${e.height}`):(0,n.jsx)("button",{type:"button",className:"group block aspect-square w-full cursor-zoom-in overflow-hidden rounded-md border bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{let e,n;return e=[],n=-1,void(o.forEach((r,a)=>{if("ready"!==r.status)return;a===t&&(n=e.length);let l=i[a];e.push({src:r.url,alt:s("chatImage",{count:a+1}),width:l.width,height:l.height})}),n>=0&&u({slides:e,index:n}))},"aria-label":s("previewImageNumber",{count:t+1}),children:(0,n.jsx)("img",{src:r.url,alt:s("chatImage",{count:t+1}),className:"aspect-square size-full object-cover transition-transform duration-200 group-hover:scale-[1.02] motion-reduce:transition-none"})},`${t}:${e.width}:${e.height}`)})}),d?(0,n.jsx)(ny.k,{mode:"modal",open:!0,slides:d.slides,index:d.index,ariaLabel:s("chatImagePreview"),onClose:()=>u(null),onIndexChange:e=>u(t=>t?{...t,index:e}:t)}):null]})}function cp({text:e}){let{t}=(0,b.Bd)("conversation"),s=(0,r.useRef)(null),[i,a]=(0,r.useState)(!1),[l,o]=(0,r.useState)(null),c=(0,r.useContext)(ct);(0,r.useLayoutEffect)(()=>{let e=s.current;if(!e)return;let t=new ResizeObserver(([t])=>{if(!t||0===t.contentRect.height)return;let s=Number.parseFloat(getComputedStyle(e).lineHeight);o(t.contentRect.height>6*s+1)});return t.observe(e),()=>t.disconnect()},[]);let d=(0,r.useCallback)(()=>{i||c(),a(e=>!e)},[c,i]);return(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("div",{className:(0,C.cn)("relative",!i&&!1!==l&&o9().userTextCollapsed),children:[(0,n.jsx)("p",{ref:s,className:"whitespace-pre-wrap break-words",children:e}),l&&!i?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-secondary to-transparent","aria-hidden":"true"}):null]}),l?(0,n.jsxs)("button",{type:"button","aria-expanded":i,onClick:d,className:"-mb-1 ml-auto mt-1 flex min-h-7 cursor-pointer items-center gap-1 rounded-md px-1 text-xs font-medium text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t(i?"collapse":"expand"),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-3.5 transition-transform",i&&"rotate-180"),"aria-hidden":"true"})]}):null]})}function ch({message:e,onAcquireImage:t,onResend:s,resendDisabled:r}){let{t:i}=(0,b.Bd)("conversation");if("user"!==e.summary.type)throw Error("UserMessage requires a user summary");return(0,n.jsxs)(tX,{from:"user","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:user`,"data-chat-user-message":"",className:(0,C.cn)(o9().copyableMessage,"max-w-[92%] sm:max-w-[84%]"),children:[(0,n.jsxs)(tZ,{className:(0,C.cn)(o9().userText,"group-[.is-user]:px-3 group-[.is-user]:py-2"),children:[e.summary.images.length>0?(0,n.jsx)(cm,{message:e,onAcquireImage:t},`${e.tempId}:${e.durable?.location.entryId??"temporary"}`):null,e.summary.text?(0,n.jsx)(cp,{text:e.summary.text}):null]}),null===e.timestampMs?null:(0,n.jsxs)(t5,{className:"mt-0 justify-end gap-1 text-xs text-muted-foreground",children:[e.durable&&s?(0,n.jsx)(t0,{tooltip:i("resendMessage"),label:i("resendMessage"),size:"icon-sm",className:(0,C.cn)(o9().messageCopyAction,"text-muted-foreground"),disabled:r,onClick:()=>s(e.durable.location.entryId),children:(0,n.jsx)(lP.A,{className:"size-3.5"})}):null,(0,n.jsx)(cc,{text:e.summary.text}),(0,n.jsx)(co,{timestampMs:e.timestampMs})]})]})}function cg({message:e,text:t}){let s=e.temporary&&"assistant"===e.summary.type&&"running"===e.summary.status;return(0,n.jsxs)(tX,{from:"assistant","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:text`,className:(0,C.cn)(o9().copyableMessage,"max-w-full gap-1"),children:[(0,n.jsx)(tZ,{className:"w-full",children:(0,n.jsx)(rn,{isAnimating:s,mode:s?"streaming":"static",children:t})}),(0,n.jsx)(cu,{message:e})]})}function cf(){let{t:e}=(0,b.Bd)("conversation");return(0,n.jsxs)("div",{role:"status",className:(0,C.cn)(o9().detailText,"flex min-h-9 w-full items-center gap-2 py-1 text-muted-foreground"),children:[(0,n.jsx)(oL.A,{className:"size-4","aria-hidden":"true"}),(0,n.jsx)(oH,{as:"span",duration:1,children:e("thinking")})]})}function cx({content:e,streaming:t}){let{t:s}=(0,b.Bd)("conversation"),{scrollRef:r,contentRef:i}=(0,oW.q)({initial:!!t&&"instant",resize:"instant"}),a=e.length>5e3,l=e.slice(-5e3);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{ref:r,className:"max-h-56 overflow-y-auto pb-2 pr-2 [scrollbar-gutter:stable] sm:max-h-72",children:(0,n.jsx)("div",{ref:i,children:(0,n.jsx)(rn,{isAnimating:t,mode:t?"streaming":"static",children:l},a?e.length:void 0)})}),a?(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 pt-1",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:s("thinkingTruncated",{count:5e3})}),(0,n.jsx)(cc,{text:e,copyLabel:s("copyThinking"),alwaysVisible:!0})]}):null]})}function cb({message:e,detailLoad:t}){let{t:s}=(0,b.Bd)("conversation");if("assistant"!==e.summary.type)return null;let{loading:r,error:i,load:a}=t,l=void 0!==e.detail,o=e.detail?.type==="assistant"?e.detail:null,c=o?.thinking??"",d=c.trim().length>0,u=d&&e.temporary&&"running"===e.summary.status&&0===e.summary.text.trim().length;if(!(d||!l&&e.summary.hasDetail))return null;let m=c||(r?s("thinkingLoading"):i??s("thinkingUnavailable"));return(0,n.jsxs)(oJ,{className:"mb-0 w-full",isStreaming:u,onOpenChange:e=>{e&&a()},children:[(0,n.jsx)(oX,{className:(0,C.cn)(o9().detailText,"min-h-9 justify-start py-1"),getThinkingMessage:e=>e?(0,n.jsx)(oH,{as:"span",duration:1,children:s("thinking")}):(0,n.jsx)("span",{children:s("thinkingProcess")})}),(0,n.jsx)(eV.Ke,{className:(0,C.cn)(cr,"text-sm leading-6 text-muted-foreground outline-none"),children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)("div",{className:"border-l pl-4",children:(0,n.jsx)(cx,{content:m,streaming:u})})})})]})}function cv({message:e}){let{t}=(0,b.Bd)("conversation"),{locale:s}=(0,eQ.i)();if("assistant"!==e.summary.type)return null;let r=function(e,t){let s=e?.trim();if(!s)return null;switch(s.toLowerCase()){case"terminated":return n6.W[t].streamInterrupted;case"request timed out":case"request timed out.":return n6.W[t].requestTimedOut;default:return e}}(e.summary.errorMessage,s)??("error"===e.summary.status?t("modelFailed"):null);return r?(0,n.jsx)("pre",{className:(0,C.cn)(o9().toolOutput,"whitespace-pre-wrap break-words rounded-lg border border-destructive/40 bg-muted p-3 font-sans text-destructive"),children:r}):null}function cw({item:e,onLoadDetail:t}){let{message:s,hideAssistantText:r}=e,i=ca(s,t);if("assistant"!==s.summary.type)throw Error("AssistantProcessItem requires an assistant summary");return(0,n.jsxs)("div",{className:"space-y-2","data-message-id":s.identity,"data-chat-scroll-anchor":`${s.identity}:process`,children:[(0,n.jsx)(cb,{message:s,detailLoad:i}),r||!s.summary.text.trim()?null:(0,n.jsx)(cg,{message:s,text:s.summary.text}),(0,n.jsx)(cv,{message:s})]})}function cy({name:e,filePath:t,className:s}){let r=e.toLowerCase().split(".").at(-1)??e.toLowerCase(),i={className:s};switch(r){case"read":return t?(0,n.jsx)(oY.s,{path:t,...i}):(0,n.jsx)(nI.A,{...i});case"write":return(0,n.jsx)(oF.A,{...i});case"edit":return(0,n.jsx)(oB.A,{...i});case"bash":return(0,n.jsx)(w.A,{...i});case"grep":case"find":return(0,n.jsx)(eh.A,{...i});case"ls":return(0,n.jsx)(eP.A,{...i});case"agent":case"agent_resume":return(0,n.jsx)(eD.A,{...i});default:return(0,n.jsx)(eT.A,{...i})}}function ck(e){let t=e.replaceAll("\\","/");return"/"===t||/^[A-Za-z]:\/$/.test(t)?t:t.replace(/\/+$/,"")}function cj({status:e,timing:t}){let s=t&&"startedAtMs"in t?t.startedAtMs:null,i=t&&"durationMs"in t?t.durationMs:null,[a,l]=(0,r.useState)(()=>Date.now());(0,r.useEffect)(()=>{if("running"!==e||null===s)return;let t=window.setInterval(()=>l(Date.now()),1e3);return()=>window.clearInterval(t)},[s,e]);let o=i??(null===s?null:Math.max(0,a-s));return null===o?null:(0,n.jsx)(n.Fragment,{children:function(e){let t=Math.max(0,Math.floor(e/1e3)),s=t%60,n=Math.floor(t/60);if(0===n)return`${s}s`;let r=n%60,i=Math.floor(n/60);return 0===i?`${r}m ${s}s`:`${i}h ${r}m ${s}s`}(o)})}function cN({message:e,onLoadDetail:t,previewPath:s,onPreviewFile:i,renderDetail:a}){let{t:l}=(0,b.Bd)("conversation");if("tool"!==e.summary.type&&"bash"!==e.summary.type)throw Error("ToolCardShell requires a tool or bash summary");let o=(0,r.useContext)(cs),c=(0,r.useContext)(cn),d=!e.temporary&&"tool"===e.summary.type&&!!e.summary.images?.length,{open:u,expandable:m,loading:p,error:h,handleOpenChange:g}=cl(e,t),{name:f,reasoning:x,inputPreview:v,activity:w,usage:y}="tool"===e.summary.type?{name:e.summary.name,reasoning:e.summary.reasoning,inputPreview:e.summary.inputPreview,activity:e.summary.activity,usage:e.summary.usage}:{name:"bash",reasoning:null,inputPreview:e.summary.command,activity:null,usage:null},k="tool"===e.summary.type&&"bash"===e.summary.kind?e.summary:null,j="error"===e.summary.status,N=!e.temporary&&null!==s&&void 0!==i,I=s?function(e,t){let{compactPath:s,fullPath:n}=function(e,t){let s=ck(e);if(!t)return{compactPath:s,fullPath:s};let n=ck(t);if(!(s.startsWith("/")||/^[A-Za-z]:\//.test(s))){let e=s.replace(/^(?:\.\/)+/,""),t=n.endsWith("/")?n:`${n}/`;return{compactPath:e,fullPath:`${t}${e}`}}let r=n.endsWith("/")?n:`${n}/`,i=/^[A-Za-z]:\//.test(s)&&/^[A-Za-z]:\//.test(n),a=i?s.toLowerCase():s,l=i?r.toLowerCase():r;return a.startsWith(l)?{compactPath:s.slice(r.length),fullPath:s}:{compactPath:s,fullPath:s}}(e,t),r=s.match(/^[A-Za-z]:\//)?.[0]??null??(s.startsWith("/")?"/":""),i=s.slice(r.length).split("/").filter(Boolean),a=i.pop()??s,l=a.lastIndexOf("."),o=i.length>2?`…/${i.slice(-2).join("/")}`:`${r}${i.join("/")}`;return{fileStem:l>0?a.slice(0,l):a,fileExtension:l>0?a.slice(l):"",directory:o||null,fullPath:n}}(s,o):null;return(0,n.jsxs)(eV.Nt,{open:m&&u,onOpenChange:g,className:(0,C.cn)(o9().detailText,"w-full overflow-hidden rounded-lg border bg-muted/45 dark:bg-card",j?"border-destructive":"border-border"),"data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:tool`,children:[(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsxs)(eV.R6,{disabled:!m,className:(0,C.cn)("relative grid min-h-14 w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-2 px-3 py-1.5 text-left",m&&"cursor-pointer hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"),"aria-label":l(m?u?"collapseTool":"expandTool":"tool",{name:f}),children:[(0,n.jsx)(cy,{name:f,filePath:s,className:"col-start-1 row-start-1 size-4 text-muted-foreground"}),(0,n.jsxs)("span",{className:"col-start-2 row-start-1 flex min-h-7 min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"shrink-0 font-mono font-medium",children:f}),x?(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-foreground",children:x}):null,y?(0,n.jsx)(cd,{usage:y,compactOnly:!0}):null]}),(0,n.jsxs)("span",{className:"col-start-3 row-start-1 flex min-h-7 items-center justify-end gap-2",children:[N?(0,n.jsx)("span",{className:"size-7","aria-hidden":"true"}):null,m?(0,n.jsx)("span",{className:"flex size-7 items-center justify-center","aria-hidden":"true",children:(0,n.jsx)(eY.A,{"data-tool-disclosure":"",className:(0,C.cn)("size-4 text-muted-foreground transition-transform",u&&"rotate-180")})}):null]}),I?(0,n.jsxs)("span",{className:(0,C.cn)(o9().toolFilePath,"col-start-2 row-start-2 flex min-w-0 items-baseline overflow-hidden font-mono text-xs"),title:I.fullPath,children:[(0,n.jsxs)("span",{className:"flex min-w-0 max-w-full shrink-0 items-baseline text-foreground",children:[(0,n.jsx)("span",{className:"min-w-0 truncate",children:I.fileStem}),(0,n.jsx)("span",{className:"shrink-0",children:I.fileExtension})]}),I.directory?(0,n.jsxs)("span",{className:(0,C.cn)(o9().toolFileDirectory,"min-w-0 truncate text-muted-foreground"),children:["\xa0\xb7\xa0",I.directory]}):null]}):v?(0,n.jsx)("span",{className:"col-start-2 row-start-2 truncate font-mono text-xs text-muted-foreground",children:v}):null,k?.timing?(0,n.jsx)("span",{className:"col-start-3 row-start-2 text-right font-mono text-xs tabular-nums whitespace-nowrap text-muted-foreground",children:(0,n.jsx)(cj,{status:k.status,timing:k.timing})}):w?(0,n.jsx)("span",{className:"col-start-3 row-start-2 max-w-36 truncate text-right font-mono text-xs tabular-nums text-muted-foreground",title:w,children:w}):null]}),N?(0,n.jsx)("button",{type:"button",title:l("previewFile"),"aria-label":l("previewFilePath",{path:s}),onClick:()=>i(s),className:(0,C.cn)("absolute top-1.5 flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",m?"right-12":"right-3"),children:(0,n.jsx)(oq.A,{className:"size-4","aria-hidden":"true"})}):null]}),(0,n.jsx)(eV.Ke,{className:cr,children:(0,n.jsxs)("div",{className:"border-t",children:[I?(0,n.jsx)("p",{className:"border-b px-3 py-2 font-mono text-xs text-muted-foreground [overflow-wrap:anywhere]",children:I.fullPath}):null,u&&d&&c?(0,n.jsx)("div",{className:"px-3 pt-3",children:(0,n.jsx)(cm,{message:e,onAcquireImage:c})}):null,a({loading:p,error:h})]})})]})}function cI({children:e,destructive:t=!1}){return(0,n.jsx)("p",{className:(0,C.cn)(o9().detailText,"px-3 py-3",t?"text-destructive":"text-muted-foreground"),children:e})}function cS({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="bash"||e.detail?.type==="tool"&&("generic"===e.detail.kind||"bash"===e.detail.kind||"codemode"===e.detail.kind)?e.detail:null,a=i?.output??"";return t?(0,n.jsx)(cI,{children:r("loadingResult")}):s?(0,n.jsx)(cI,{destructive:!0,children:s}):a?(0,n.jsx)("pre",{role:"region","aria-label":r("toolOutput"),tabIndex:0,className:(0,C.cn)(ce,o9().toolOutput,"whitespace-pre-wrap break-words px-3 py-3 font-mono"),children:a}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(cI,{children:r("emptyResult")})}function cC({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="tool"&&"read"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(cI,{children:r("loadingRead")}):s?(0,n.jsx)(cI,{destructive:!0,children:s}):i?i.content?(0,n.jsx)("pre",{role:"region","aria-label":r("readContent"),tabIndex:0,className:(0,C.cn)(ce,o9().toolOutput,o9().toolCode,"px-3 py-3 font-mono"),children:i.content}):(0,n.jsx)(cI,{children:r("readEmpty")}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(cI,{children:r("readUnavailable")})}function cE({content:e}){let{t}=(0,b.Bd)("conversation");return(0,n.jsx)("div",{role:"region","aria-label":t("editDiff"),tabIndex:0,className:(0,C.cn)(ce,o9().toolOutput,"font-mono"),children:e.split("\n").map((e,t)=>{let s=e.startsWith("+")?"bg-emerald-500/10 text-emerald-800 dark:text-emerald-200":e.startsWith("-")?"bg-red-500/10 text-red-800 dark:text-red-200":e.trimEnd().endsWith("...")?"bg-muted/40 text-muted-foreground":"text-foreground";return(0,n.jsx)("span",{className:(0,C.cn)(o9().toolCode,o9().toolCodeLine,"block px-3",s),children:e||" "},t)})})}function cM({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="tool"&&"edit"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(cI,{children:r("loadingDiff")}):s?(0,n.jsx)(cI,{destructive:!0,children:s}):i?"diff"===i.contentKind?(0,n.jsx)(cE,{content:i.content}):(0,n.jsx)("pre",{role:"region","aria-label":r("editResult"),tabIndex:0,className:(0,C.cn)(ce,o9().toolOutput,"whitespace-pre-wrap break-words px-3 py-3 font-mono","tool"===e.summary.type&&"error"===e.summary.status&&"text-destructive"),children:i.content}):(0,n.jsx)(cI,{children:r("diffUnavailable")})}function cz({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="tool"&&"write"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(cI,{children:r("loadingWrite")}):s?(0,n.jsx)(cI,{destructive:!0,children:s}):i?"content"!==i.contentKind||i.content?(0,n.jsx)("pre",{role:"region","aria-label":r("content"===i.contentKind?"writeContent":"writeResult"),tabIndex:0,className:(0,C.cn)(ce,o9().toolOutput,"px-3 py-3 font-mono","content"===i.contentKind?o9().toolCode:"whitespace-pre-wrap break-words","output"===i.contentKind&&"tool"===e.summary.type&&"error"===e.summary.status&&"text-destructive"),children:i.content}):(0,n.jsx)(cI,{children:r("writeEmpty")}):(0,n.jsx)(cI,{children:r("writeUnavailable")})}function cA({message:e,onLoadDetail:t}){let{t:s}=(0,b.Bd)("conversation"),{open:r,expandable:i,loading:a,error:l,handleOpenChange:o}=cl(e,t);if("tool"!==e.summary.type||"pidesk"!==e.summary.kind)throw Error("PiDeskToolView requires a pidesk summary");let c=function(e){let t=e.args,s={command:0===Object.keys(e).length?"pidesk":`pidesk ${JSON.stringify(e)}`,label:null,name:null,version:null};if(1!==Object.keys(e).length||!Array.isArray(t)||t.length>32||!t.every(e=>"string"==typeof e))return s;s.command=["pidesk",...t.map(l1)].join(" ");let n=t.some(e=>/\s/.test(e))?"":t.join(" ");if(0===t.length||["--help","-h","plugins","session","plugins --help","plugins -h","session --help","session -h"].includes(n))return{...s,label:lX};if("--version"===n)return{...s,label:"pideskVersion"};if("info"===n)return{...s,label:"pideskInfo"};if("session reload"===n)return{...s,label:"pideskReload"};if(3===t.length&&["--help","-h"].includes(t[2])&&("plugins"===t[0]&&["list","show","install","remove"].includes(t[1])||"session"===t[0]&&"reload"===t[1]))return{...s,label:lX};let r=t[1];if("plugins"!==t[0]||!r||!["list","show","install","remove"].includes(r))return s;let i=null,a=[],l=null,o=null,c=!1;for(let e=2;e<t.length;e+=1){let n=t[e];if("--scope"===n&&null===i&&"global"===t[e+1])i=t[++e];else if("--version"===n&&"install"===r&&null===l&&l0.test(t[e+1]??""))l=t[++e];else if("--tag"===n&&["list","install"].includes(r)&&null===o&&(t[e+1]?.length??0)<=128&&/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(t[e+1]??""))o=t[++e];else if("--check-updates"!==n||"list"!==r||c)if(!("list"!==r&&("show"!==r||0===a.length)&&"node_modules"!==n&&lZ.test(n)))return s;else a.push(n);else c=!0}if(null!==o&&null!==l||"list"!==r&&(0===a.length||null===i))return s;let d=a.length>0?a.join("、"):null;switch(r){case"list":return{...s,label:"pideskListPlugins"};case"show":return{...s,label:"pideskShowPlugin",name:d};case"install":return{...s,label:"pideskInstallPlugin",name:d,version:l};case"remove":return{...s,label:"pideskRemovePlugin",name:d};default:return s}}(e.summary.input),d=e.detail?.type==="tool"&&"pidesk"===e.detail.kind?e.detail.output:null;return(0,n.jsx)(o8,{identity:e.identity,command:c,output:d,expandable:i,open:r,loading:a,error:l,onOpenChange:o,commandAction:(0,n.jsx)(cc,{text:c.command,copyLabel:s("pidesk.copyCommand"),alwaysVisible:!0}),outputAction:d?(0,n.jsx)(cc,{text:d,copyLabel:s("pidesk.copyOutput"),alwaysVisible:!0}):null})}function c$({message:e,onLoadDetail:t}){return(0,n.jsx)(cN,{message:e,onLoadDetail:t,previewPath:null,renderDetail:t=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cS,{message:e,...t}),e.detail?.type==="tool"&&"codemode"===e.detail.kind&&e.detail.nestedCalls?(0,n.jsx)(o3,{nestedCalls:e.detail.nestedCalls}):null]})})}function cR({message:e,onLoadDetail:t}){return(0,n.jsx)(c$,{message:e,onLoadDetail:t})}function cP({message:e,onLoadDetail:t,onPreviewFile:s}){if("tool"!==e.summary.type||"read"!==e.summary.kind)throw Error("ReadToolView requires a read summary");return(0,n.jsx)(cN,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(cC,{message:e,...t})})}function cD({message:e,onLoadDetail:t,onPreviewFile:s}){if("tool"!==e.summary.type||"edit"!==e.summary.kind)throw Error("EditToolView requires an edit summary");return(0,n.jsx)(cN,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(cM,{message:e,...t})})}function cT({message:e,onLoadDetail:t,onPreviewFile:s}){if("tool"!==e.summary.type||"write"!==e.summary.kind)throw Error("WriteToolView requires a write summary");return(0,n.jsx)(cN,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(cz,{message:e,...t})})}function cO({message:e}){let{t}=(0,b.Bd)("conversation");if("custom"!==e.summary.type)throw Error("CustomMessage requires a custom summary");return(0,n.jsx)("div",{"data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:custom`,className:(0,C.cn)(o9().toolOutput,"rounded-lg border-l-2 bg-muted px-3 py-2 text-muted-foreground"),children:e.summary.text||t("emptyMessage")})}function cL({message:e,onLoadDetail:t}){let{t:s}=(0,b.Bd)("conversation");if("compaction"!==e.summary.type)throw Error("CompactionMessage requires a compaction summary");let{open:r,expandable:i,loading:a,error:l,handleOpenChange:o}=cl(e,t),c=e.detail?.type==="compaction"?e.detail:null;return(0,n.jsxs)(eV.Nt,{open:i&&r,onOpenChange:o,className:"w-full py-1","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:compaction`,children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"h-px min-w-3 flex-1 bg-border/70","aria-hidden":"true"}),(0,n.jsxs)(eV.R6,{disabled:!i,"aria-label":i?`${s(r?"collapse":"expand")} ${s("compactionSummary")}`:s(e.temporary?"compactionRunning":"compactionComplete"),className:(0,C.cn)("inline-flex min-h-8 max-w-full items-center gap-2 rounded-full border border-border/70 bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground outline-none transition-colors",i?"hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring":"cursor-default"),children:[e.temporary?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin","aria-hidden":"true"}):(0,n.jsx)(o_.A,{className:"size-3.5","aria-hidden":"true"}),(0,n.jsx)("span",{children:s(e.temporary?"compactionRunning":"compactionComplete")}),i?(0,n.jsx)(eY.A,{className:(0,C.cn)("size-3.5 transition-transform",r&&"rotate-180"),"aria-hidden":"true"}):null]}),(0,n.jsx)("span",{className:"h-px min-w-3 flex-1 bg-border/70","aria-hidden":"true"})]}),(0,n.jsx)(eV.Ke,{className:cr,children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)("div",{className:"rounded-xl border border-border/70 bg-muted/20 px-3 py-3 sm:px-4",children:(0,n.jsx)("div",{role:"region","aria-label":s("compactionSummaryContent"),tabIndex:0,className:"max-h-80 overflow-y-auto pr-2 [scrollbar-gutter:stable]",children:a?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:s("compactionLoading")}):l?(0,n.jsx)("p",{className:"text-sm text-destructive",children:l}):c?.text?(0,n.jsx)(rn,{isAnimating:!1,mode:"static",children:c.text}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:s("compactionUnavailable")})})})})})]})}let cF=(0,r.memo)(function({item:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:r}){let i=(()=>{switch(e.message.summary.type){case"assistant":return(0,n.jsx)(cw,{item:e,onLoadDetail:t});case"tool":switch(e.message.summary.kind){case"pidesk":return(0,n.jsx)(cA,{message:e.message,onLoadDetail:t});case"read":return(0,n.jsx)(cP,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"edit":return(0,n.jsx)(cD,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"write":return(0,n.jsx)(cT,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"bash":case"codemode":case"generic":return(0,n.jsx)(c$,{message:e.message,onLoadDetail:t})}case"bash":return(0,n.jsx)(cR,{message:e.message,onLoadDetail:t});case"custom":return(0,n.jsx)(cO,{message:e.message});case"compaction":return(0,n.jsx)(cL,{message:e.message,onLoadDetail:t});case"user":return(0,n.jsx)(ch,{message:e.message,onAcquireImage:s})}})();return(0,n.jsx)(oO,{message:e.message,loadDetail:t,defaultView:i})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&e.onPreviewFile===t.onPreviewFile&&e.item.hideAssistantText===t.item.hideAssistantText&&c_(e.item.message,t.item.message));function cB({items:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i}){let{scrollRef:a}=(0,lT.B)(),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(e.length),d=(0,r.useRef)(null),[u,m]=(0,r.useState)(()=>Math.min(64,e.length)),p=Math.max(0,e.length-u),h=p>0,g=(0,r.useCallback)(()=>{if(!h)return;let t=a.current,s=l.current?.querySelector("[data-chat-process-item]");t&&s?.dataset.chatProcessItem&&(d.current={identity:s.dataset.chatProcessItem,offset:s.getBoundingClientRect().top-t.getBoundingClientRect().top}),m(t=>Math.min(e.length,t+64))},[h,e.length,a]);return(0,r.useLayoutEffect)(()=>{let t=c.current;c.current=e.length,u>=t&&u<e.length&&m(e.length)},[u,e.length]),(0,r.useLayoutEffect)(()=>{let e=d.current;if(!e)return;let t=a.current,s=Array.from(l.current?.querySelectorAll("[data-chat-process-item]")??[]).find(t=>t.dataset.chatProcessItem===e.identity);if(d.current=null,!t||!s)return;let n=s.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=n-e.offset},[p,a]),(0,r.useEffect)(()=>{let e=a.current,t=o.current;if(!e||!t||!h)return;let s=()=>{let s=e.getBoundingClientRect().top,n=t.getBoundingClientRect().top;return n>=s-96&&n<=s+96},n=e=>{e.deltaY<0&&s()&&g()},r=()=>{s()&&g()};return e.addEventListener("wheel",n,{passive:!0}),e.addEventListener("touchmove",r,{passive:!0}),()=>{e.removeEventListener("wheel",n),e.removeEventListener("touchmove",r)}},[h,g,a]),(0,n.jsxs)("div",{ref:l,children:[h?(0,n.jsx)("div",{ref:o,className:"h-px","data-chat-process-history":!0,"aria-hidden":"true"}):null,e.slice(p).map((r,a)=>{let l=p+a,o=e[l-1],c=o?.message.summary.type==="assistant"&&!o.hideAssistantText&&!!o.message.summary.text.trim();return(0,n.jsx)("div",{"data-chat-process-item":r.message.identity,className:l>0?c?"mt-5":"mt-2":void 0,children:(0,n.jsx)(cF,{item:r,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i})},r.message.identity)})]})}let cq=(0,r.memo)(function({turn:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i}){let{t:a}=(0,b.Bd)("conversation"),[l,o]=(0,r.useState)(!1),c=(0,r.useContext)(ct),d=(0,Q.t4)();(0,Q.So)();let u=e.processItems.filter(e=>!e.hideAssistantText||"pi-desk/assistant"===e.message.viewKey&&null===d.getMessageViewResolution(e.message.viewKey)),m=e.running||l,p=(0,r.useCallback)(t=>{e.running||(t&&c(),o(t))},[c,e.running]);return 0===u.length?null:(0,n.jsxs)(eV.Nt,{open:m,onOpenChange:p,className:"w-full",children:[(0,n.jsxs)(eV.R6,{className:(0,C.cn)(o9().detailText,"flex min-h-9 w-full cursor-pointer items-center gap-2 py-1 text-left text-muted-foreground hover:text-foreground"),children:[(0,n.jsxs)("span",{className:"flex-1",children:[a("processGroup"),e.toolCount>0?` \xb7 ${a("toolCalls",{count:e.toolCount})}`:""]}),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-4 transition-transform",m&&"rotate-180")})]}),(0,n.jsx)(eV.Ke,{className:cr,children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)(cB,{items:u,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i})})})]})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&e.onPreviewFile===t.onPreviewFile&&e.turn.running===t.turn.running&&e.turn.toolCount===t.turn.toolCount&&cW(e.turn.processItems,t.turn.processItems));function c_(e,t){return e===t||!!e&&!!t&&e.identity===t.identity&&(e.durable||t.durable?e.durable===t.durable&&e.usageIncomplete===t.usageIncomplete&&(e.usageCalls?.length??0)===(t.usageCalls?.length??0)&&(e.usageCalls??[]).every((e,s)=>e.durable===t.usageCalls?.[s]?.durable):e.tempId===t.tempId&&e.summary===t.summary&&e.detail===t.detail&&e.timestampMs===t.timestampMs)}function cW(e,t){return e===t||e.length===t.length&&e.every((e,s)=>{let n=t[s];return void 0!==n&&e.hideAssistantText===n.hideAssistantText&&c_(e.message,n.message)})}let cY=(0,r.memo)(function({message:e,onLoadDetail:t,onAcquireImage:s,onResend:r,resendDisabled:i}){return(0,n.jsx)(oO,{message:e,loadDetail:t,defaultView:(0,n.jsx)(ch,{message:e,onAcquireImage:s,onResend:r,resendDisabled:i})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&e.onResend===t.onResend&&e.resendDisabled===t.resendDisabled&&c_(e.message,t.message)),cV=(0,r.memo)(function({message:e,onLoadDetail:t}){return"assistant"!==e.summary.type?null:(0,n.jsx)(oO,{message:e,loadDetail:t,defaultView:(0,n.jsx)(cg,{message:e,text:e.summary.text})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&c_(e.message,t.message)),cU=(0,r.memo)(function({turn:e,cwd:t,logicalTail:s=!1,onLoadDetail:r,onAcquireImage:i,onPreviewFile:a,onResend:l,resendDisabled:o}){if(e.compaction)return(0,n.jsx)("section",{className:(0,C.cn)(!e.running&&"pi-desk-chat-turn-contained"),"data-chat-turn":e.identity,"data-chat-logical-tail":s?"":void 0,children:(0,n.jsx)(oO,{message:e.compaction,loadDetail:r,defaultView:(0,n.jsx)(cL,{message:e.compaction,onLoadDetail:r})})});let c=e.running&&0===e.processItems.length&&null===e.finalAssistant;return(0,n.jsxs)("section",{className:(0,C.cn)("space-y-3",!e.running&&"pi-desk-chat-turn-contained"),"data-chat-turn":e.identity,"data-chat-logical-tail":s?"":void 0,children:[e.user?(0,n.jsx)(cY,{message:e.user,onLoadDetail:r,onAcquireImage:i,onResend:l,resendDisabled:o}):null,(0,n.jsx)(cn.Provider,{value:i,children:(0,n.jsx)(cs.Provider,{value:t,children:(0,n.jsx)(cq,{turn:e,onLoadDetail:r,onAcquireImage:i,onPreviewFile:a})})}),c?(0,n.jsx)(cf,{}):null,e.finalAssistant?(0,n.jsx)(cV,{message:e.finalAssistant,onLoadDetail:r}):null]})},(e,t)=>{var s,n;return e.cwd===t.cwd&&e.logicalTail===t.logicalTail&&e.onResend===t.onResend&&e.resendDisabled===t.resendDisabled&&e.onAcquireImage===t.onAcquireImage&&e.onLoadDetail===t.onLoadDetail&&e.onPreviewFile===t.onPreviewFile&&((s=e.turn)===(n=t.turn)||s.identity===n.identity&&s.running===n.running&&s.toolCount===n.toolCount&&c_(s.user,n.user)&&c_(s.finalAssistant,n.finalAssistant)&&c_(s.compaction,n.compaction)&&cW(s.processItems,n.processItems))});cU.displayName="L3ConversationTurnView";let cK={running:"statusRunning",completed:"statusCompleted",failed:"statusFailed",stopped:"statusStopped",interrupted:"statusInterrupted"};function cH(e,t){return null!==e&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}function cG(e,t){let s=Math.max(0,Math.round(((e.endedAt??Date.now())-e.startedAt)/1e3));if(s<60)return t("seconds",s);let n=Math.floor(s/60);if(n<60)return t("minutes",n);let r=Math.floor(n/60);return`${t("hours",r)}${n%60?` ${t("minutes",n%60)}`:""}`}function cJ(e){return[e.taskKind,e.taskType].filter(e=>!!e).join(" / ")}function cQ(e){switch(e){case"running":return(0,n.jsx)(v.A,{className:"size-4 animate-spin text-foreground"});case"completed":return(0,n.jsx)(ls.A,{className:"size-4 text-status-success"});case"failed":return(0,n.jsx)(lA.A,{className:"size-4 text-destructive"});case"interrupted":return(0,n.jsx)(l$.A,{className:"size-4 text-status-warning"});case"stopped":return(0,n.jsx)(lR.A,{className:"size-4 text-muted-foreground"})}}function cX({info:e}){let{t}=(0,b.Bd)("taskCenter"),s=(0,X.G)(),[i,a]=(0,r.useState)(null);if(0===e.length)return null;let l=(e,n)=>{(0,e9.x)(e.value).then(r=>{r?a(n):s.error(t("copyFailed",{name:e.label}))})};return(0,n.jsx)("div",{"data-task-info-scroll":"",className:"max-h-32 overflow-y-auto pr-1 [scrollbar-gutter:stable]",children:(0,n.jsx)("dl",{className:"flex flex-wrap gap-2",children:e.map((e,s)=>{let r=`${e.label}:${s}:${e.value}`,a=i===r;return(0,n.jsxs)("div",{role:"button",tabIndex:0,"aria-label":t(a?"copied":"copy",{name:e.label}),title:a?t("copiedShort"):t("clickToCopy",{name:e.label}),className:(0,C.cn)("flex min-h-8 min-w-0 max-w-full cursor-pointer items-start gap-2 rounded-md px-2 py-1 text-sm outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",a&&"bg-muted"),onClick:()=>l(e,r),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),l(e,r))},children:[(0,n.jsx)("dt",{className:"shrink-0 pt-0.5 font-medium text-muted-foreground",children:e.label}),(0,n.jsx)("dd",{className:"min-w-0 flex-1 break-words text-foreground",children:e.value}),(0,n.jsx)("span",{className:"shrink-0 pt-0.5 text-muted-foreground","aria-hidden":"true",children:a?(0,n.jsx)(ep.A,{className:"size-3.5 text-status-success"}):(0,n.jsx)(ee.A,{className:"size-3.5"})})]},`${e.label}:${s}`)})})})}function cZ({snapshot:e,running:t,runtime:s,cwd:i}){let{t:a}=(0,b.Bd)("taskCenter"),l=(0,r.useMemo)(()=>oi(e,t),[t,e]),o=l.findLast(e=>null!==e.user)??null;return(0,n.jsx)(lO,{className:"h-full min-h-0",initial:"instant",resize:"instant","aria-label":a("conversationDetails"),children:(0,n.jsx)(oI,{turns:l,focusTurnIdentity:o?.identity??null,initialAnchor:null,children:e=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ob,{}),(0,n.jsx)(ci,{children:(0,n.jsxs)(lL,{scrollClassName:"pi-desk-chat-scrollbar",className:"mx-auto min-h-full w-full max-w-3xl gap-6 px-4 pt-3 pb-6 sm:px-6",children:[l.length>0?e.visibleTurns.map((t,r)=>{let a=e.startIndex+r;return(0,n.jsx)(cU,{turn:t,cwd:i,logicalTail:e.containsTail&&a===l.length-1,onLoadDetail:s.loadMessageDetail,onAcquireImage:s.acquireImage},t.identity)}):(0,n.jsx)("div",{className:"grid min-h-48 place-items-center text-sm text-muted-foreground",children:a("noMessages")}),(0,n.jsx)("div",{className:"h-4 shrink-0","aria-hidden":"true"})]})}),(0,n.jsx)(oz,{turns:l,window:e})]})})})}function c0({task:e,runtime:t,cwd:s}){let{t:i}=(0,b.Bd)("taskCenter"),a=(0,r.useSyncExternalStore)(t.subscribe,t.getState,t.getState),l=e?a.details[e.taskId]:void 0,[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),h=async()=>{if(!o)return void c(!0);u(!0),p(null);try{await t.interruptSelected(),c(!1)}catch(e){p(e instanceof Error?e.message:i("interruptFailed"))}finally{u(!1)}};if(!e)return(0,n.jsx)("div",{className:"grid h-full min-h-0 place-items-center px-6 text-center text-sm text-muted-foreground",children:i("selectTask")});let g=cJ(e);return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsx)("header",{className:"shrink-0 border-b px-4 py-3 lg:pr-16",children:(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-start gap-2",children:[(0,n.jsx)("span",{className:"mt-0.5 shrink-0",children:cQ(e.status)}),(0,n.jsx)("h3",{className:"min-w-0 break-words text-sm font-semibold",children:g?`${g} \xb7 ${e.title}`:e.title})]}),(0,n.jsxs)("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs",children:[(0,n.jsx)("span",{className:(0,C.cn)("rounded-md px-1.5 py-0.5 font-medium",function(e){switch(e){case"running":return"bg-muted text-foreground";case"completed":return"bg-muted text-status-success";case"failed":return"bg-muted text-destructive";case"interrupted":return"bg-muted text-status-warning";case"stopped":return"bg-muted text-muted-foreground"}}(e.status)),children:i(cK[e.status])}),(0,n.jsx)("span",{className:"text-muted-foreground",children:cG(e,(e,t)=>i(e,{count:t}))}),e.activity?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"text-muted-foreground/60",children:"\xb7"}),(0,n.jsx)("span",{className:"min-w-0 break-words text-muted-foreground",children:e.activity})]}):null]})]}),l?.canInterrupt?(0,n.jsxs)(I.$,{className:"shrink-0",type:"button",size:"sm",variant:o?"destructive":"outline",disabled:d,onClick:()=>void h(),children:[d?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(lR.A,{}),o?i("confirmInterrupt"):i("interrupt")]}):null]})}),m?(0,n.jsx)("p",{role:"alert",className:"shrink-0 border-b bg-muted px-4 py-2 text-sm text-destructive",children:m}):null,e.info.length>0?(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-2",children:(0,n.jsx)(cX,{info:e.info})}):null,(0,n.jsxs)("div",{className:"relative min-h-0 flex-1",children:[l?.body?.kind==="conversation"?(0,n.jsx)(cZ,{snapshot:l.body,running:"running"===e.status,runtime:t,cwd:s}):l?.body?.kind==="text"?(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("pre",{className:(0,C.cn)("whitespace-pre-wrap break-words font-mono text-sm leading-[1.6]"),children:l.body.text||i("waitingOutput")})}):l?(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("div",{className:"grid min-h-48 place-items-center px-2 text-center text-sm text-muted-foreground",children:i("noDetails")})}):(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("div",{className:"grid min-h-48 place-items-center px-2 text-center text-sm text-muted-foreground",children:a.error?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("p",{className:"text-destructive",children:a.error}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>t.selectTask(e.taskId),children:[(0,n.jsx)(lP.A,{}),i("retry")]})]}):(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),i("loadingDetail")]})})}),a.refreshing?(0,n.jsxs)("div",{className:"pointer-events-none absolute right-3 top-3 flex items-center gap-2 rounded-md border bg-popover px-2 py-1 text-xs text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-3 animate-spin"}),i("refreshing")]}):null]})]})}function c1({source:e,tasks:t,runtime:s,cwd:i}){let{t:a}=(0,b.Bd)("taskCenter"),{locale:l,timeZone:o}=(0,eQ.i)(),c=(0,r.useCallback)(()=>{let e=s.getState();return JSON.stringify([e.open,e.source?.workId??null,e.source?.sessionId??null,e.source?.branchId??null,e.selectedTaskId])},[s]);(0,r.useSyncExternalStore)(s.subscribe,c,c);let d=s.getState(),[u,m]=(0,r.useState)(!1),p=t.find(e=>e.taskId===d.selectedTaskId)??null;(0,r.useEffect)(()=>{d.open&&cH(d.source,e)&&s.reconcileTasks(e,t)},[s,e,d.open,d.source,t]);let h=u&&null!==d.selectedTaskId,g=d.open&&cH(d.source,e);return(0,n.jsx)(eN.YV,{open:g,onOpenChange:e=>{e||s.close()},children:(0,n.jsxs)(eN.hA,{"aria-label":a("title"),showCloseButton:!1,className:"h-[calc(100dvh-2rem)] max-w-[70rem] flex-row bg-background max-lg:h-[var(--pi-desk-content-height)] max-lg:max-h-[var(--pi-desk-content-height)] max-lg:w-dvw max-lg:max-w-none max-lg:rounded-none max-lg:border-0",children:[(0,n.jsxs)("div",{className:(0,C.cn)("flex min-w-0 flex-1 flex-col border-r bg-sidebar lg:max-w-80",h&&"hidden lg:flex"),children:[(0,n.jsxs)("header",{className:"flex min-h-14 items-center gap-3 border-b px-4 py-3",children:[(0,n.jsx)(lD.A,{className:"size-5 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{children:a("title")}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:a("recordCount",{count:t.length})})]}),(0,n.jsx)(I.$,{className:"lg:hidden",type:"button",variant:"ghost",size:"icon","aria-label":a("close"),onClick:()=>s.close(),children:(0,n.jsx)(V.A,{})})]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-2",children:t.length>0?(0,n.jsx)("div",{className:"space-y-1",children:t.map(e=>{let t=cJ(e),r=cG(e,(e,t)=>a(e,{count:t})),i=oo(e.startedAt,void 0,l,o);return(0,n.jsxs)("button",{type:"button","aria-current":e.taskId===d.selectedTaskId?"true":void 0,onClick:()=>{var t;return t=e.taskId,void(s.selectTask(t),m(!0))},className:(0,C.cn)("grid min-h-14 w-full cursor-pointer grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-x-2 rounded-lg px-3 py-3 text-left outline-none transition-colors hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",e.taskId===d.selectedTaskId&&"bg-accent text-accent-foreground hover:bg-accent"),children:[(0,n.jsx)("span",{className:"mt-0.5 shrink-0",children:cQ(e.status)}),(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsxs)("span",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-baseline gap-x-3",children:[(0,n.jsx)("span",{className:"truncate text-sm font-medium",children:e.title}),(0,n.jsxs)("span",{className:"whitespace-nowrap text-xs tabular-nums text-muted-foreground","aria-label":a("runningTime",{duration:r,time:i.full}),children:[r,(0,n.jsx)("span",{className:"mx-1 text-muted-foreground/50","aria-hidden":"true",children:"\xb7"}),(0,n.jsx)("time",{dateTime:new Date(e.startedAt).toISOString(),children:i.compact})]})]}),t?(0,n.jsx)("span",{className:"mt-1 block truncate text-xs text-muted-foreground",children:t}):null]}),(0,n.jsx)(e7.A,{className:"mt-1 size-4 shrink-0 text-muted-foreground lg:hidden"})]},e.taskId)})}):(0,n.jsx)("div",{className:"grid min-h-48 place-items-center text-sm text-muted-foreground",children:a("noTasks")})})]}),(0,n.jsx)("div",{className:(0,C.cn)("min-w-0 flex-1",!h&&"hidden lg:block"),children:(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-12 items-center gap-2 border-b bg-muted/10 px-3 lg:hidden",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":a("back"),onClick:()=>m(!1),children:(0,n.jsx)(A.A,{})}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-center text-xs text-muted-foreground",children:p?.title??a("detail")}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":a("close"),onClick:()=>s.close(),children:(0,n.jsx)(V.A,{})})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1",children:(0,n.jsx)(c0,{task:p,runtime:s,cwd:i},p?.taskId??"no-task")})]})}),(0,n.jsx)(I.$,{className:"absolute right-4 top-3 z-10 hidden lg:inline-flex",type:"button",variant:"ghost",size:"icon","aria-label":a("close"),onClick:()=>s.close(),children:(0,n.jsx)(V.A,{})})]})})}function c2({source:e,cwd:t,tasks:s,runtime:r,variant:i}){let{t:a}=(0,b.Bd)("taskCenter"),l=s.filter(e=>"running"===e.status),o=l[0],c=()=>{r.open(e,(s.find(e=>"running"===e.status)??s[0]??null)?.taskId??null)};return"footer"===i?s.length>0?(0,n.jsx)(lG,{tooltip:a("title"),"aria-label":a("open"),onClick:c,children:(0,n.jsx)(lD.A,{className:"size-4"})}):(0,n.jsx)(n.Fragment,{}):"menu"===i?(0,n.jsxs)(H._2,{onClick:c,children:[(0,n.jsx)(lD.A,{className:"size-4"}),a("title")]}):(0,n.jsxs)(n.Fragment,{children:[o?(0,n.jsxs)("button",{type:"button",className:"mb-2 flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-md border bg-muted px-2.5 text-left text-sm text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",onClick:c,"aria-label":`${a("open")}, ${a("runningCount",{count:l.length})}`,children:[(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin text-foreground"}),(0,n.jsx)("span",{className:"shrink-0 font-medium text-foreground",children:a("runningCount",{count:l.length})}),(0,n.jsxs)("span",{className:"min-w-0 flex-1 truncate",children:[o.title,o.activity?` \xb7 ${o.activity}`:""]}),(0,n.jsx)(e7.A,{className:"size-3.5 shrink-0"})]}):null,(0,n.jsx)(c1,{source:e,tasks:s,runtime:r,cwd:t})]})}function c5({source:e,cwd:t,pluginState:s,runtime:i,variant:a}){let l=(0,r.useMemo)(()=>{let e=lb.safeParse(s);return e.success?e.data.tasks:[]},[s]);return(0,n.jsx)(c2,{source:e,cwd:t,tasks:l,runtime:i,variant:a})}var c3=s(74577),c4=s(85232);function c6(e){return`${e.location.index}:${e.location.entryId}`}let c8={user:["viewKey","hasDetail"],assistant:["viewKey","status","hasDetail","usage"],tool:["viewKey","status","hasDetail","usage"],bash:["viewKey","status","hasDetail"],custom:["viewKey","hasDetail"]};function c7(e,t,s){if(!t)return e;let n={...e,...t};return"summary"===s?lo.Hf.parse(n):lo.D8.parse(n)}function c9(e,t){if(Array.isArray(e.parent)){if("number"!=typeof e.key)throw Error("Increment array key is invalid");e.parent[e.key]=t;return}if("string"!=typeof e.key)throw Error("Increment object key is invalid");e.parent[e.key]=t}function de(e,t,s){let n=structuredClone(e),r=function(e,t){if(0===t.length)throw Error("Increment cannot append to the message layer root");let s=e;for(let e of t.slice(0,-1)){if("number"==typeof e){if(!Array.isArray(s)||e>=s.length)throw Error(`Increment array path does not exist: ${e}`);s=s[e];continue}if(!s||"object"!=typeof s||Array.isArray(s))throw Error(`Increment object path does not exist: ${e}`);if(!Object.hasOwn(s,e))throw Error(`Increment object field does not exist: ${e}`);s=s[e]}let n=t.at(-1);if("number"==typeof n){if(!Array.isArray(s)||n>=s.length)throw Error(`Increment array target does not exist: ${n}`);return{parent:s,key:n,value:s[n]}}if(!s||"object"!=typeof s||Array.isArray(s))throw Error(`Increment object target does not exist: ${n}`);if(!Object.hasOwn(s,n))throw Error(`Increment target does not exist: ${n}`);return{parent:s,key:n,value:s[n]}}(n,t);if("string"==typeof s){if("string"!=typeof r.value)throw Error("Increment target is not a string");return c9(r,`${r.value}${s}`),lo.Hf.parse(n)}if(!Array.isArray(r.value))throw Error("Increment target is not an array");return c9(r,[...r.value,...s]),lo.Hf.parse(n)}function dt(e,t,s){let n=new Map(e.messages.filter(e=>void 0!==e.detail).map(e=>[c6(e),e]));return{messages:t.map(e=>{let t=n.get(c6(e));return e.fixed.hasDetail&&t&&t.fixed.type===e.fixed.type&&t.fixed.viewKey===e.fixed.viewKey&&void 0!==t.detail?lo.mj.parse({...e,detail:t.detail}):e}),temporaryMessages:[...s]}}function ds(e,t){if("message_start"===t.type){if(e.temporaryMessages.some(e=>e.location.tempId===t.snapshot.location.tempId))throw Error(`Temporary conversation message already exists: ${t.snapshot.location.tempId}`);return{...e,temporaryMessages:[...e.temporaryMessages,t.snapshot]}}let s=e.temporaryMessages.findIndex(e=>e.location.tempId===t.location.tempId);if(s<0)throw Error(`Temporary conversation message was not found: ${t.location.tempId}`);if("message_update"===t.type){let n=[...e.temporaryMessages];return n[s]=function(e,t){var s,n;if(e.location.tempId!==t.location.tempId)throw Error(`Conversation update tempId mismatch: ${t.location.tempId}`);let r=(s=e.fixed,(n=t.fixed)?(!function(e,t,s){let n=Object.keys(e).filter(e=>!t.includes(e));if(n.length>0)throw Error(`${s} patch contains fields invalid for the current message: ${n}`)}(n,c8[s.type],`${s.type} fixed`),lo.q5.parse({...s,...n})):s),i=c7(e.summary,t.summary,"summary"),a=e.detail;if(void 0!==t.detail||Object.keys(t.increments??{}).some(e=>"detail"===(0,c4.U)(e).root)){if(t.fixed?.hasDetail===!1)throw Error("Realtime detail cannot be updated while explicitly clearing hasDetail");r.hasDetail||(r=lo.q5.parse({...r,hasDetail:!0}))}for(let[e,s]of(t.detail&&(a=c7(a??{},t.detail,"detail")),Object.entries(t.increments??{}))){let t=(0,c4.U)(e);"summary"===t.root?i=de(i,t.segments,s):a=de(a??{},t.segments,s)}return r.hasDetail||(a=void 0),lo.s4.parse({location:e.location,fixed:r,summary:i,...void 0===a?{}:{detail:a}})}(n[s],t),{...e,temporaryMessages:n}}if("message_discard"===t.type)return{...e,temporaryMessages:e.temporaryMessages.filter(e=>e.location.tempId!==t.location.tempId)};if(t.durable.index!==e.messages.length)throw Error(`Conversation commit index is not continuous: expected ${e.messages.length}, received ${t.durable.index}`);if(e.messages.some(e=>e.location.entryId===t.durable.entryId))throw Error(`Conversation commit entryId already exists: ${t.durable.entryId}`);let{detail:n,fixed:r,...i}=e.temporaryMessages[s],a=lo.mj.parse({...i,location:t.durable,fixed:{...r,timestampMs:t.fixed.timestampMs},...r.hasDetail&&void 0!==n?{detail:n}:{}});return{messages:[...e.messages,a],temporaryMessages:e.temporaryMessages.filter(e=>e.location.tempId!==t.location.tempId)}}function dn(e,t){let s=e.messages.findIndex(e=>e.location.index===t.index&&e.location.entryId===t.entryId);if(s<0)throw Error(`Conversation detail target was not found: ${t.index}/${t.entryId}`);let n=e.messages[s];if(null!==t.detail&&!n.fixed.hasDetail)throw Error("Message without hasDetail cannot accept detail");let r=[...e.messages];return r[s]=lo.mj.parse({...n,...null===t.detail?{detail:void 0}:{detail:t.detail}}),{...e,messages:r}}function dr(e,t){return e.taskId!==t.taskId||e.body?.kind!=="conversation"||t.body?.kind!=="conversation"?t:lk.parse({...t,body:{kind:"conversation",truncated:t.body.truncated,...dt(e.body,t.body.messages,t.body.temporaryMessages)}})}var di=s(7237);function da(e){return(0,ed.B)({msg:c3.U["zh-CN"][e],i18n:{key:`taskCenter:${e}`}})}let dl=Object.freeze({open:!1,source:null,selectedTaskId:null,details:{},loading:!1,refreshing:!1,error:null});function dc(e,t){return e===t||null!==e&&null!==t&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}var dd=s(15381),du=s(94853);let dm=s0.rh,dp=s0.eC,dh=a.Ik({workId:dd.eW,cwd:dd.ik}).strict(),dg=dh.extend({path:dm}).strict(),df=dh.extend(s0.Nu.shape).strict(),dx=du.Ot.request.safeExtend({workId:dd.eW});du.Ot.response;let db=s0.p$,dv=dh.extend({path:dp,imagePreviewMode:db}).strict();var dw=s(46117),dy=s.n(dw);function dk({mobile:e,open:t,sidebar:s,children:i,onClose:a}){let{t:l}=(0,b.Bd)("workbench"),o=(0,E.fk)(),c=(0,r.useRef)(288);return((0,r.useLayoutEffect)(()=>{if(e)return;let s=requestAnimationFrame(()=>{o.current?.resize(t?c.current:0)});return()=>cancelAnimationFrame(s)},[e,t,o]),e)?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button","aria-label":l("closeSessionMenu"),"aria-hidden":!t,tabIndex:t?0:-1,onClick:a,className:(0,C.cn)(dy().backdrop,"fixed inset-0 z-40 bg-black/35",t?"opacity-100":"pointer-events-none opacity-0")}),(0,n.jsx)("div",{"data-testid":"mobile-work-session-drawer","data-open":t,"aria-hidden":!t||void 0,inert:!t||void 0,className:(0,C.cn)(dy().drawer,"fixed inset-y-0 left-0 z-50 flex w-[min(86vw,320px)] flex-col border-r bg-sidebar shadow-2xl",!t&&"pointer-events-none"),children:s}),(0,n.jsx)("div",{className:"flex min-h-0 min-w-0 flex-1",inert:t||void 0,children:i})]}):(0,n.jsxs)(S.HK,{orientation:"horizontal",disableCursor:!0,className:(0,C.cn)(dy().panelGroup,"pi-desk-workbench-resize-group min-h-0 min-w-0 flex-1"),onLayoutChanged:(e,s)=>{if(!s.isUserInteraction||!t)return;let n=o.current?.getSize().inPixels;void 0!==n&&(c.current=n)},children:[(0,n.jsx)(S.wV,{id:"work-session-sidebar",panelRef:o,defaultSize:288,minSize:224*!!t,maxSize:480*!!t,disabled:!t,"aria-hidden":!t||void 0,inert:!t||void 0,className:"flex h-full min-h-0 min-w-0 !overflow-hidden bg-sidebar",children:(0,n.jsx)("div",{className:"flex h-full w-full min-w-[224px] flex-col border-r",children:s})}),(0,n.jsx)(S.WM,{withHandle:!0,"aria-label":l("resizeSessionList"),"aria-hidden":!t||void 0,disabled:!t,className:(0,C.cn)("cursor-col-resize",!t&&"w-0 pointer-events-none opacity-0")}),(0,n.jsx)(S.wV,{id:"work-session-content",minSize:360,className:"flex h-full min-h-0 min-w-0 !overflow-hidden",children:i})]})}let dj=a.Ik({application:a.eu("Pi Desk"),status:a.eu("ready"),version:a.Yj().trim().min(1).nullable().default(null),boundaries:a.Ik({client:a.eu("isolated"),server:a.eu("isolated"),common:a.eu("shared")}),layers:a.PV([a.eu("L1 Entry"),a.eu("L2 Biz"),a.eu("L3 Modules"),a.eu("L4 Foundation")])});var dN=s(5011),dI=s(42515),dS=s(80077);dS.Gm.extend({query:a.Yj().trim().min(1).max(120)});let dC=a.Ik({sessions:a.YO(a.Ik({workId:dd.eW,matches:a.YO(dS.Jk).min(1).max(4)}).strict())}).strict();var dE=s(91399),dM=s(95826),dz=s(37975),dA=s(56592),d$=s(31343);function dR(e,t){return(0,ed.B)({msg:d$.R["zh-CN"][e],i18n:{key:`workbench:${e}`,...t?{params:t}:{}}})}function dP(e){let{workId:t,sessionId:s,branchId:n}=e.source;return JSON.stringify([t,s,n,e.cwd])}function dD(e,t,s){return`${dP(e)}\u0000${s}\u0000${t}`}class dT{peek(e,t,s){let n=this.images.get(dD(e,t,s));return!n||0===n.references&&Date.now()-n.unusedAt>=6e4?null:n.url}get(e,t,s){this.trim();let n=dD(e,t,s),r=this.images.get(n);return r?this.acquire(n,r):null}store(e,t,s,n){if(this.disposed||!this.validSources.has(dP(e)))throw Error("工作会话来源已变化");let r=dD(e,t,s),i=this.images.get(r);if(i)return this.acquire(r,i);let a={url:URL.createObjectURL(n),size:n.size,references:0,unusedAt:Date.now()};return this.images.set(r,a),this.acquire(r,a)}invalidate(e,t,s){this.remove(dD(e,t,s))}reconcileWorkSessions(e){for(let t of(this.validSources=new Set(e.map(e=>dP({source:e,cwd:e.cwd}))),this.images.keys()))this.validSources.has(t.split("\0")[0])||this.remove(t);this.trim()}dispose(){for(let e of(this.disposed=!0,this.images.keys()))this.remove(e);this.validSources.clear()}acquire(e,t){t.references+=1,this.images.delete(e),this.images.set(e,t),this.trim();let s=!1;return{url:t.url,release:()=>{s||(s=!0,t.references-=1,0===t.references&&(t.unusedAt=Date.now()),this.trim())}}}remove(e){let t=this.images.get(e);t&&(URL.revokeObjectURL(t.url),this.images.delete(e))}trim(){let e=Date.now(),t=[...this.images.values()].reduce((e,t)=>e+t.size,0);for(let[s,n]of this.images)!(n.references>0)&&(e-n.unusedAt<6e4&&t<=0x4000000&&this.images.size<=64||(this.remove(s),t-=n.size))}constructor(){this.images=new Map,this.validSources=new Set,this.disposed=!1}}class dO{constructor(e,t,s=()=>void 0){this.biz=e,this.gitBiz=t,this.onNotice=s,this.standaloneImages=new dT,this.listeners=new Set,this.workspaces=new Map,this.sources=new Map,this.previewDirectories=new Map,this.expandedWorkId=null,this.revision=0,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.getRevision=()=>this.revision}getWorkspace(e){let t=e?this.workspaces.get(e):null;return t?{...t.files.state,cwd:t.files.cwd,windowOpen:t.windowOpen,chatWidthPercent:t.chatWidthPercent,activePane:t.activePane}:null}getFileRuntime(e){return this.workspaceFor(e).files}getExpandedWorkId(){return this.expandedWorkId}getDirectories(e){return this.previewDirectories.get(e)?.directories??[]}getDirectory(e){let t=this.previewDirectories.get(e);if(!t)throw Error(dR("sourceChanged"));return t.selectedDirectory}applyPreviewDirectories(e,t){let s=this.sources.get(e.workId);if(!s||s.sessionId!==e.sessionId||s.branchId!==e.branchId)return;let n=this.previewDirectories.get(e.workId),r=new Map([[(0,dz.Yj)(s.cwd),s.cwd]]);for(let e of t.directories){let t=(0,dz.Yj)(e);r.has(t)||r.set(t,e)}let i=t.defaultDirectory?r.get((0,dz.Yj)(t.defaultDirectory))??null:null,a=(n.defaultDirectory?(0,dz.Yj)(n.defaultDirectory):null)!==(i?(0,dz.Yj)(i):null)?i??s.cwd:r.get((0,dz.Yj)(n.selectedDirectory))??s.cwd,l=[...r.values()];if(n.defaultDirectory===i&&n.selectedDirectory===a&&n.directories.length===l.length&&n.directories.every((e,t)=>e===l[t]))return;this.previewDirectories.set(e.workId,{directories:l,defaultDirectory:i,selectedDirectory:a});let o=this.workspaces.get(e.workId);if(o){for(let[e,t]of o.roots)r.has(e)||(t.unsubscribe(),t.files.dispose(),o.roots.delete(e));this.switchFiles(e.workId,o)}this.publish()}selectDirectory(e,t){let s=this.previewDirectories.get(e);if(!s)throw Error(dR("sourceChanged"));let n=s.directories.find(e=>(0,dz.Yj)(e)===(0,dz.Yj)(t));if(!n)throw Error(dR("sourceChanged"));if(s.selectedDirectory===n)return;s.selectedDirectory=n;let r=this.workspaces.get(e);r&&this.switchFiles(e,r),this.publish()}reconcileWorkSessions(e){this.standaloneImages.reconcileWorkSessions(e);let t=new Map(e.map(({workId:e,cwd:t,sessionId:s,branchId:n})=>[e,{workId:e,cwd:t,sessionId:s,branchId:n}])),s=!1;for(let[e,n]of this.sources){let r=t.get(e);if(r?.cwd===n.cwd&&r.sessionId===n.sessionId&&r.branchId===n.branchId)continue;let i=this.workspaces.get(e);i&&(this.disposeLayout(i),this.workspaces.delete(e)),this.previewDirectories.delete(e),s=!0,this.expandedWorkId===e&&(this.expandedWorkId=null)}for(let[e,s]of(this.sources.clear(),t))this.sources.set(e,s),this.previewDirectories.has(e)||this.previewDirectories.set(e,{directories:[s.cwd],defaultDirectory:null,selectedDirectory:s.cwd});s&&this.publish()}ensureRoot(e){return this.getFileRuntime(e).ensureRoot()}ensureDirectory(e,t){return this.getFileRuntime(e).ensureDirectory(t)}setExpandedPaths(e,t){this.getFileRuntime(e).setExpandedPaths(t)}setTreeScrollTop(e,t){this.workspaces.get(e)?.files.setTreeScrollTop(t)}refreshTree(e){this.getFileRuntime(e).refreshTree()}setSearchQuery(e,t){this.getFileRuntime(e).setSearchQuery(t)}search(e,t){return this.getFileRuntime(e).search(t)}openFile(e,t){let s=this.workspaceFor(e);s.windowOpen=!0,s.activePane="files",s.files.openFile(t)}async revealFile(e,t){await this.getFileRuntime(e).revealFile(t)}activateFile(e,t){this.workspaces.get(e)?.files.state.tabs.includes(t)&&this.openFile(e,t)}closeFile(e,t){this.closeTabs(e,t,"current")}closeTabs(e,t,s){this.workspaces.get(e)?.files.closeTabs(t,s)}hideWindow(e){let t=this.workspaces.get(e);t?.windowOpen&&(t.windowOpen=!1,t.activePane="chat",this.expandedWorkId===e&&(this.expandedWorkId=null),this.publish())}showWindow(e){let t=this.workspaceFor(e),{tabs:s,activeDiff:n,activePath:r}=t.files.state;(s.length||n||this.expandedWorkId===e)&&(t.windowOpen=!0,t.activePane="files",this.publish(),!n&&r&&t.files.ensureDocument(r))}setChatWidthPercent(e,t){let s=this.workspaces.get(e);!s||!Number.isFinite(t)||t<=0||t>=100||.001>Math.abs(s.chatWidthPercent-t)||(s.chatWidthPercent=t,this.publish())}setActivePane(e,t){let s=this.workspaces.get(e);s&&s.activePane!==t&&(s.activePane=t,this.publish())}expandWindow(e){this.expandedWorkId=e,this.showWindow(e)}collapseExpandedWindow(){if(!this.expandedWorkId)return;let e=this.workspaces.get(this.expandedWorkId);this.expandedWorkId=null,!e||e.files.state.tabs.length||e.files.state.activeDiff||(e.windowOpen=!1,e.activePane="chat"),this.publish()}reloadFile(e,t){this.workspaces.get(e)?.files.reloadFile(t)}openDiff(e,t,s){let n=this.workspaceFor(e);n.windowOpen=!0,n.activePane="files",n.files.openDiff(t,s)}closeDiff(e){this.closeTabs(e,null,"current")}reloadDiff(e){this.workspaces.get(e)?.files.reloadDiff()}setDiffViewMode(e,t){this.workspaces.get(e)?.files.setDiffViewMode(t)}setDiffWrapLines(e,t){this.workspaces.get(e)?.files.setDiffWrapLines(t)}setDiffCollapseUnchanged(e,t){this.workspaces.get(e)?.files.setDiffCollapseUnchanged(t)}handleGitBranchChanged(e,t){for(let s of this.workspaces.values())for(let n of s.roots.values())n.files.cwd===e&&n.files.handleGitBranchChanged(t)}saveEditorState(e,t,s){this.workspaces.get(e)?.files.saveEditorState(t,s)}setWrapLines(e,t,s){this.workspaces.get(e)?.files.setWrapLines(t,s)}setTextViewMode(e,t,s){this.workspaces.get(e)?.files.setTextViewMode(t,s)}dispose(){for(let e of(this.standaloneImages.dispose(),this.workspaces.values()))this.disposeLayout(e);this.workspaces.clear(),this.sources.clear(),this.previewDirectories.clear(),this.expandedWorkId=null,this.listeners.clear()}workspaceFor(e){if(!this.sources.get(e))throw Error(dR("sourceChanged"));let t=this.workspaces.get(e);if(t)return t;let s={files:this.createFiles(e,this.getDirectory(e)),roots:new Map,windowOpen:!1,chatWidthPercent:50,activePane:"files"};return this.attachRoot(e,s,s.files),this.workspaces.set(e,s),s}createFiles(e,t){let s={workId:e,cwd:t};return new dA.h(t,{list:(e,t)=>this.biz.list({...s,path:e},t),search:(e,t)=>this.biz.search({...s,...e},t),get:(e,t,n)=>this.biz.get({...s,path:e,imagePreviewMode:t},n),diff:(e,t,n)=>this.gitBiz.getDiff({...s,repositoryRoot:e,path:t},n)},{imagePreviewMode:rm.Wq,htmlPreview:!0,onNotice:this.onNotice,reveal:async(e,t)=>{await this.biz.reveal({...s,path:e,..."directory"===t?{targetType:t}:{}})}})}attachRoot(e,t,s){let n=s.subscribe(()=>{t.files===s&&(s.state.activePath||s.state.activeDiff||this.expandedWorkId===e||(t.windowOpen=!1,t.activePane="chat"),this.publish())});t.roots.set((0,dz.Yj)(s.cwd),{files:s,unsubscribe:n})}switchFiles(e,t){let s=this.getDirectory(e),n=(0,dz.Yj)(s);if((0,dz.Yj)(t.files.cwd)===n)return;let r=t.roots.get(n);if(!r){let i=this.createFiles(e,s);this.attachRoot(e,t,i),r=t.roots.get(n)}t.files=r.files,r.files.state.activePath||r.files.state.activeDiff||this.expandedWorkId===e||(t.windowOpen=!1,t.activePane="chat")}disposeLayout(e){for(let t of e.roots.values())t.unsubscribe(),t.files.dispose();e.roots.clear()}publish(){for(let e of(this.revision+=1,this.listeners))e()}}var dL=s(70657);function dF(e,t,s,n){t.reconcileWorkSessions(s,n,s.flatMap(({workId:t})=>e.getDirectories(t).map(e=>({workId:t,cwd:e}))))}var dB=s(90504),dq=s(46487),d_=s(97921),dW=s(36510);let dY='data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/%3E';function dV({target:e,paths:t,index:s,onIndexChange:i,biz:a,images:l}){let{t:o}=(0,b.Bd)("workbench"),[c,d]=(0,r.useState)({}),u=(0,r.useRef)(new Map),m=t[s],p=c[m],h=(0,rm.Wq)(),g=l.peek(e,m,h),f=p?.status==="ready"||!p&&null!==g;return(0,r.useLayoutEffect)(()=>{let e=u.current;return()=>{for(let t of e.values())t.release();e.clear()}},[]),(0,r.useLayoutEffect)(()=>{let t,s=u.current;if(p?.status==="error"||s.has(m))return;let n=l.get(e,m,h);if(n)return void s.set(m,n);let r=new AbortController;return(async()=>{try{let n=await a.get({workId:e.source.workId,cwd:e.cwd,path:m,imagePreviewMode:h},r.signal);if(r.signal.aborted)return;if("image"!==n.kind)throw Error(o("standaloneReadFailed"));t=l.store(e,m,h,(0,di.E)(n));let i=new Image;if(i.src=t.url,await i.decode(),r.signal.aborted)return;let c=t.url;s.set(m,t),d(e=>({...e,[m]:{status:"ready",objectUrl:c}}))}catch(n){if(t&&(t.release(),l.invalidate(e,m,h)),r.signal.aborted)return;let s=n instanceof Error?n.message:o("standaloneReadFailed");console.warn("[Pi Desk][StandaloneImageGallery] 读取图片失败",{workId:e.source.workId,path:m,error:s}),d(e=>({...e,[m]:{status:"error",message:s}}))}})(),()=>{r.abort(),s.get(m)!==t&&t?.release()}},[a,p,l,h,m,o,e]),(0,n.jsxs)("div",{className:"relative size-full","data-testid":"standalone-image-gallery",children:[(0,n.jsx)(ny.k,{mode:"inline",thumbnails:!1,slides:t.map(e=>{let t=c[e];return{src:t?.status==="ready"?t.objectUrl:e===m?g??dY:dY,alt:e}}),index:s,onIndexChange:i}),f?null:(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 z-[2] flex items-center justify-center p-6 pb-20",children:p?.status==="error"?(0,n.jsxs)("div",{className:"flex max-w-full flex-col items-center gap-3 rounded-lg bg-background/95 p-4 text-center",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:p.message}),(0,n.jsx)(I.$,{className:"pointer-events-auto",variant:"outline",onClick:()=>{l.invalidate(e,m,(0,rm.Wq)()),d(e=>{let t={...e};return delete t[m],t})},children:o("reloadFile")})]}):(0,n.jsxs)("div",{role:"status",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),o("loadingFile")]})})]})}function dU(e){return e.replaceAll("\\","/").split("/").at(-1)??e}function dK(e,t){return e instanceof Error?e.message:t}function dH({target:e,biz:t,images:s,mobile:i,onClose:a}){let{t:l}=(0,b.Bd)("workbench"),{t:o}=(0,b.Bd)("projectFiles"),c=(0,r.useRef)(null),[d,u]=(0,r.useState)({mode:"preview",scrollTop:0}),m=(0,r.useRef)(0),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)(0),[x,v]=(0,r.useState)(()=>{let t=e&&!e.imagePaths?s.peek(e,e.path,(0,rm.Wq)()):null;return t?{status:"image",objectUrl:t}:{status:"loading"}}),[w,y]=(0,r.useState)(()=>e?.imagePaths?e.imagePaths.indexOf(e.path):0);if((0,r.useLayoutEffect)(()=>{let n;if(!e||e.imagePaths)return;let r=new AbortController,i=!0,a=(0,rm.Wq)(),o=s.get(e,e.path,a);return o?o.release:(t.get({workId:e.source.workId,cwd:e.cwd,path:e.path,imagePreviewMode:a},r.signal).then(t=>{if(!i)return;if("text"===t.kind)return void v({status:"text",content:t.content,size:t.size});let r=s.store(e,e.path,a,(0,di.E)(t));n=r.release,v({status:"image",objectUrl:r.url})}).catch(t=>{i&&!r.signal.aborted&&(console.warn("[Pi Desk][PluginStandaloneFilePreview] 读取文件失败",{workId:e.source.workId,path:e.path,error:dK(t,l("standaloneReadFailed"))}),v({status:"error",message:dK(t,l("standaloneReadFailed"))}))}),()=>{i=!1,r.abort(),n?.()})},[t,s,g,e,l]),(0,r.useEffect)(()=>{if(!e)return;let t=e=>{e.source===c.current?.contentWindow&&"pi-desk:file-escape"===e.data&&a()};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[a,e]),!e)return null;let k=e.imagePaths?.[w]??e.path,j=(0,d_.g)(k);return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||a()},children:(0,n.jsxs)(eN.hA,{className:i?"inset-x-0 top-[var(--pi-desk-window-inset)] bottom-0 h-[var(--pi-desk-content-height)] max-h-none w-dvw max-w-none translate-x-0 translate-y-0 rounded-none border-0 ring-0":"h-[min(94dvh,1080px)] w-[min(96dvw,1600px)] max-w-none",children:[(0,n.jsx)(eN.YM,{className:"sr-only",children:dU(k)}),(0,n.jsxs)("section",{"data-testid":"plugin-standalone-file-preview",className:"flex size-full min-h-0 min-w-0 flex-col overflow-hidden bg-background","aria-label":l("standaloneViewer",{name:e.projectName}),children:[(0,n.jsxs)("header",{className:"flex min-h-14 shrink-0 items-center gap-3 border-b pl-3 pr-14 pt-[env(safe-area-inset-top)]",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-semibold",title:dU(k),children:dU(k)}),(0,n.jsxs)("p",{className:"truncate text-xs text-muted-foreground",title:`${e.projectName} \xb7 ${k}`,children:[e.projectName," \xb7 ",k]})]}),"markdown"===j&&"text"===x.status?(0,n.jsx)("div",{className:"flex shrink-0",role:"group","aria-label":o("markdownMode"),children:["preview","source"].map(e=>(0,n.jsx)(I.$,{size:"sm",variant:d.mode===e?"secondary":"ghost","aria-pressed":d.mode===e,onClick:()=>{d.mode!==e&&u({mode:e,scrollTop:m.current})},children:o("preview"===e?"previewMode":"sourceMode")},e))}):null]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden pb-[env(safe-area-inset-bottom)]",children:e.imagePaths?(0,n.jsx)(dV,{target:e,paths:e.imagePaths,index:w,onIndexChange:y,biz:t,images:s}):"loading"===x.status?(0,n.jsx)(dG,{}):"error"===x.status?(0,n.jsxs)("div",{className:"flex size-full flex-col items-center justify-center gap-3 p-6 text-center",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:x.message}),(0,n.jsx)(I.$,{variant:"outline",onClick:()=>{s.invalidate(e,e.path,(0,rm.Wq)()),v({status:"loading"}),f(e=>e+1)},children:l("reloadFile")})]}):"image"===x.status?(0,n.jsx)(ny.k,{mode:"inline",slides:[{src:x.objectUrl,alt:e.path}],ariaLabel:l("standaloneImage",{name:dU(e.path)})}):"markdown"===j&&"preview"===d.mode?(0,n.jsx)(dq.n,{content:x.content,label:o("markdownPreview",{name:k}),savedScrollTop:d.scrollTop,onScroll:e=>{m.current=e}}):"html"===j?(0,n.jsx)("iframe",{ref:c,className:"block size-full border-0 bg-white",sandbox:"allow-scripts",srcDoc:(0,dW.z)(x.content),title:l("standaloneHtml",{name:e.path})}):(0,n.jsx)(dB.e,{path:e.path,content:x.content,size:x.size,savedState:p,onSaveState:(e,t)=>h(t),onEscape:a})})]})]})})}function dG(){let{t:e}=(0,b.Bd)("workbench");return(0,n.jsxs)("div",{className:"flex size-full items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),e("loadingFile")]})}var dJ=s(3635),dQ=s(76812),dX=s.n(dQ);let dZ=(0,dJ.default)(()=>s.e(19991).then(s.bind(s,19991)).then(e=>e.L2FileWorkspaceView),{loadableGenerated:{webpack:()=>[19991]},ssr:!1});function d0({workSession:e,runtime:t,gitRuntime:s,mobile:i,onOpenGitBranches:a,onOpenSidebar:l,children:o}){let{t:c}=(0,b.Bd)("workbench");(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let d=(0,r.useRef)(null),u=(0,E.OG)(),m=(0,r.useRef)(null),p=(0,r.useRef)(null),h=(0,r.useRef)(null),g=(0,r.useRef)(null),f=(0,r.useRef)(null),[x,v]=(0,r.useState)(!1),{workId:w}=e,y=t.getWorkspace(w),k=y?.windowOpen===!0,j=`session-chat-pane-${w}`,N=`session-file-pane-${w}`,I=y?.chatWidthPercent??50,[M]=(0,r.useState)(()=>k?I:100),z=!!(y?.tabs.length||y?.activeDiff),A=x&&!i,$=A&&k,R=t.getExpandedWorkId()===w,P=k&&($||y?.activePane==="files"),D=!P||$;(0,r.useLayoutEffect)(()=>{let e=d.current;if(!e)return;let t=new ResizeObserver(([e])=>{v((e?.contentRect.width??0)>=880)});return t.observe(e),()=>t.disconnect()},[]),(0,r.useLayoutEffect)(()=>{if(!A)return;let e=requestAnimationFrame(()=>{u.current?.setLayout({[j]:k?I:100,[N]:k?100-I:0})});return()=>cancelAnimationFrame(e)},[j,I,N,k,u,A]);let T=e=>{f.current=e};(0,r.useLayoutEffect)(()=>{let e=f.current;if(e&&("chat"===e?D:P)){let t,s;f.current=null,t="chat"===e?m.current:p.current,s="chat"===e?h.current:g.current,s?.isConnected&&t?.contains(s)&&!s.closest("[inert]")?s.focus({preventScroll:!0}):t?.querySelector("chat"===e?'textarea, [data-testid="session-files-entry"]':'[data-testid="file-workspace"]')?.focus({preventScroll:!0})}},[D,P,y?.activePane]);let O=()=>{if(!z)return;let e=t.getWorkspace(w)?.activePane==="files"?"chat":"files";T(e),"files"===e?t.showWindow(w):t.setActivePane(w,"chat")};return(0,n.jsx)("div",{ref:d,"data-testid":"session-file-layout","data-file-layout":$?"split":"single",className:"relative size-full min-h-0 min-w-0 overflow-hidden",onKeyDownCapture:e=>{"Tab"!==e.key||!e.ctrlKey||e.altKey||e.metaKey||e.repeat||e.nativeEvent.isComposing||!z||e.target instanceof Element&&e.target.closest('[role="menu"], [data-slot="app-dialog-content"]')||(e.preventDefault(),e.stopPropagation(),O())},children:(0,n.jsxs)(S.HK,{groupRef:u,className:(0,C.cn)("pi-desk-workbench-resize-group relative size-full min-h-0 min-w-0",A?[dy().panelGroup,dX().wide]:dX().single),orientation:"horizontal",disabled:!$,resizeTargetMinimumSize:{fine:8,coarse:20},onLayoutChanged:(e,s)=>{if(!$||!s.isUserInteraction)return;let n=e[j];void 0!==n&&t.setChatWidthPercent(w,n)},children:[(0,n.jsx)(S.wV,{id:j,"data-pane":"chat",defaultSize:`${M}%`,minSize:320*!!$,"aria-hidden":!D||void 0,inert:!D||void 0,className:"flex min-h-0 min-w-0 !overflow-hidden",children:(0,n.jsx)("div",{ref:m,className:"size-full min-h-0 min-w-0",onPointerDownCapture:()=>t.setActivePane(w,"chat"),onFocusCapture:e=>{h.current=e.target,t.setActivePane(w,"chat")},children:o(D)})}),(0,n.jsx)(S.WM,{id:`session-file-divider-${w}`,"aria-label":c("resizeChatFile"),"aria-hidden":!$||void 0,disabled:!$,disableDoubleClick:!0,className:(0,C.cn)("z-10 w-px cursor-col-resize bg-transparent aria-disabled:cursor-default",!$&&"hidden")}),(0,n.jsx)(S.wV,{id:N,"data-pane":"files",defaultSize:`${100-M}%`,minSize:320*!!$,maxSize:A&&!k?0:void 0,"aria-hidden":!P||void 0,inert:!P||void 0,className:"flex min-h-0 min-w-0 !overflow-hidden",children:(0,n.jsx)("div",{ref:p,className:"size-full min-h-0 min-w-0 overflow-hidden",onPointerDownCapture:()=>t.setActivePane(w,"files"),onFocusCapture:e=>{g.current=e.target,t.setActivePane(w,"files")},children:z&&!R?(0,n.jsx)(dZ,{workSession:e,runtime:t,gitRuntime:s,mobile:i,presentation:A?"split":"single",onOpenGitBranches:a,onOpenSidebar:l,onHide:()=>{T("chat"),t.hideWindow(w)},onExpand:()=>t.expandWindow(w),onSwitchPane:O},`${e.sessionId}:${e.branchId}`):null})})]})})}function d1({workSessions:e,runtime:t,gitRuntime:s,mobile:i,onOpenGitBranches:a,onOpenSidebar:l,onOpenTerminal:o}){let{t:c}=(0,b.Bd)("workbench");(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let d=e.find(e=>e.workId===t.getExpandedWorkId());if(!d)return null;let u=()=>{i?t.hideWindow(d.workId):t.collapseExpandedWindow()},m=()=>{let e=document.querySelector(`[data-work-id="${CSS.escape(d.workId)}"] textarea`);e&&(t.hideWindow(d.workId),requestAnimationFrame(()=>e.focus({preventScroll:!0})))};return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||u()},children:(0,n.jsxs)(eN.hA,{showCloseButton:!1,onKeyDownCapture:e=>{"Tab"!==e.key||!e.ctrlKey||e.altKey||e.metaKey||e.repeat||e.nativeEvent.isComposing||e.target instanceof Element&&e.target.closest('[role="menu"]')||(e.preventDefault(),e.stopPropagation(),m())},className:i?"inset-x-0 top-[var(--pi-desk-window-inset)] bottom-0 h-[var(--pi-desk-content-height)] max-h-none w-dvw max-w-none translate-x-0 translate-y-0 rounded-none border-0 ring-0":"h-[min(94dvh,1080px)] w-[min(96dvw,1600px)] max-w-none",finalFocus:()=>{let e=document.querySelector(`[data-work-id="${CSS.escape(d.workId)}"]`);return e?.querySelector("[data-file-expand-trigger]")??e?.querySelector('[data-testid="session-files-entry"]')??!1},children:[(0,n.jsx)(eN.YM,{className:"sr-only",children:c("fileViewer",{name:d.projectName})}),(0,n.jsx)(dZ,{workSession:d,runtime:t,gitRuntime:s,mobile:i,presentation:i?"single":"expanded",onOpenGitBranches:a,onOpenSidebar:()=>{t.collapseExpandedWindow(),l(d.workId)},onSwitchPane:m,onOpenTerminal:o,onHide:()=>t.hideWindow(d.workId),onExpand:u},`${d.workId}:${d.sessionId}:${d.branchId}`)]})})}var d2=s(93320);async function d5(e,t,s){try{let n=await e.get({...t,imagePreviewMode:"compressed"},s);if("image"!==n.kind)throw Error("该文件不是可展示的图片");return(0,di.E)(n)}catch(e){if(e instanceof d2.aw&&"errors:fileMissing"===e.errorKey)return null;throw e}}var d3=s(72114),d4=s(31761),d6=s(50479),d8=s(35989);let d7=[];function d9(e,t){let s=t.trim().toLocaleLowerCase();return s?e.filter(e=>e.toLocaleLowerCase().includes(s)):[...e]}function ue({target:e,runtime:t,mobile:s,onClose:i}){let{t:a}=(0,b.Bd)("workbench"),{locale:l}=(0,eQ.i)();(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let o=(0,X.G)(),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(e?.repositoryRoot!==null),[p,h]=(0,r.useState)(""),[g,f]=(0,r.useState)(()=>({repositoryRoot:null,overrides:new Map})),[x,w]=(0,r.useState)(null),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(""),[S,E]=(0,r.useState)(null),[M,z]=(0,r.useState)(null),$=t.getWorkspace(e?.cwd??null),R=$?.heads.repositories??d7,P=e?null!==e.repositoryRoot&&R.some(t=>t.root===e.repositoryRoot)?e.repositoryRoot:R.find(e=>""===e.root)?.root??R[0]?.root??null:null,D=c??P;(0,r.useEffect)(()=>{e&&t.refreshHeads(e.cwd)},[t,e]),(0,r.useEffect)(()=>{if(!e||null===D||$?.heads.status!=="ready")return;let s=R.find(e=>e.root===D);s?.state==="ready"&&t.loadBranches(e.cwd,D)},[D,R,t,e,$?.heads.status]);let T=R.find(e=>e.root===D)??null,O=null===D?null:$?.branches.get(D)??null,L=O?.data??null,F=null!==D&&!!$?.branchOperations.has(D),B=(0,r.useMemo)(()=>d9(L?.local??[],p),[L?.local,p]),q=(0,r.useMemo)(()=>d9(L?.remote??[],p),[L?.remote,p]),_=(0,r.useMemo)(()=>d9(L?.recent??[],p),[L?.recent,p]),W=(0,r.useMemo)(()=>(0,d8.oY)(B),[B]),Y=(0,r.useMemo)(()=>(0,d8.oY)(q),[q]),V=L?.head.type==="branch"?L.head.name:null,K=(0,r.useMemo)(()=>{let e=new Set;if(!V?.includes("/"))return e;let t=V.split("/");for(let s=1;s<t.length;s+=1)e.add(`local:${t.slice(0,s).join("/")}`);return e},[V]);if(!e)return null;let H=e=>{E(e),N(""),k(!0),w(null),z(null)},G=async(e,t)=>{z(null);try{await e(),o.success(t),i()}catch(e){z(e instanceof Error?e.message:a("gitOperationFailed"))}},J=R.length>1,Q=1===R.length?a("repositorySummary",{name:(0,d8.Hj)(e.projectName,R[0].root),branch:"ready"===R[0].state?(0,d8.ws)(R[0].head):a("repositoryUnavailable")}):R.length>1?a("repositoryCount",{count:R.length}):a("readingRepos"),Z=(s,r,i=s.name,l=0)=>{let o="local"===s.type&&s.name===V,c=x?.type===s.type&&x.name===s.name;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{type:"button","data-testid":"recent"===r?`git-branch-recent-${s.name}`:`git-branch-${s.type}-${s.name}`,className:(0,C.cn)("grid min-h-9 w-full cursor-pointer grid-cols-[1rem_minmax(0,1fr)_auto] items-center gap-2 rounded-lg pr-2 text-left outline-none hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-ring",o&&"font-medium text-foreground",c&&"bg-accent"),style:{paddingLeft:`${8+16*l}px`},title:s.name,onClick:()=>w(c?null:s),children:[(0,n.jsx)("span",{className:"text-muted-foreground",children:o?(0,n.jsx)(ep.A,{className:"size-4 text-foreground"}):"remote"===s.type?(0,n.jsx)(d3.A,{className:"size-3.5"}):(0,n.jsx)(d4.A,{className:"size-3.5"})}),(0,n.jsx)("span",{className:"truncate font-mono text-sm",children:i}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:o?a("current"):"recent"===r?a("recent"):""})]}),c?(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 border-l-2 border-border py-2 pl-2",style:{marginLeft:`${32+16*l}px`},children:[o?null:(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",disabled:F,onClick:()=>{null!==D&&!F&&G(()=>t.replaceBranch(e.cwd,D,s),a("remote"===s.type?"checkedOut":"switchedBranch",{name:s.name}))},children:a("remote"===s.type?"checkoutRemote":"switchGitBranch")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",disabled:F,onClick:()=>H(s),children:a("branchFromHere")})]}):null]},`${r}:${s.type}:${s.name}`)},ee=(e,t)=>{let s=`${e}:${t}`;return(g.repositoryRoot===D?g.overrides.get(s):void 0)??K.has(s)},et=(e,t,s=0)=>e.map(e=>{if(0===e.children.length&&e.branchName)return Z({type:t,name:e.branchName},t,e.name,s);let r=`${t}:${e.path}`,i=!!p.trim()||ee(t,e.path);return(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{type:"button","data-testid":`git-branch-group-${t}-${e.path}`,"aria-expanded":i,className:"grid min-h-9 w-full cursor-pointer grid-cols-[1rem_1rem_minmax(0,1fr)] items-center gap-2 rounded-lg pr-2 text-left text-muted-foreground outline-none hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",style:{paddingLeft:`${8+16*s}px`},title:e.path,onClick:()=>((e,t)=>{if(p.trim())return;let s=`${e}:${t}`,n=ee(e,t);f(e=>{let t=e.repositoryRoot===D?new Map(e.overrides):new Map;return t.set(s,!n),{repositoryRoot:D,overrides:t}})})(t,e.path),children:[(0,n.jsx)(e7.A,{className:(0,C.cn)("size-3 transition-transform",i&&"rotate-90")}),i?(0,n.jsx)(d6.A,{className:"size-4 text-muted-foreground"}):(0,n.jsx)(eP.A,{className:"size-4 text-muted-foreground"}),(0,n.jsx)("span",{className:"truncate font-mono text-sm",children:e.name})]}),i?et(e.children,t,s+1):null]},r)});return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>!e&&i(),children:(0,n.jsxs)(eN.hA,{"data-testid":"git-branch-picker",showCloseButton:!1,finalFocus:!1,className:"h-[min(40rem,calc(100dvh-2rem))] max-w-[45rem] gap-0",children:[(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 border-b px-3",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{children:a("gitBranches")}),(0,n.jsx)(eN.uX,{className:"truncate text-xs",children:Q})]}),(0,n.jsx)(I.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":a("refreshBranches"),disabled:$?.heads.status==="loading",onClick:()=>void t.refreshHeads(e.cwd),children:(0,n.jsx)(es.A,{className:(0,C.cn)("size-4",$?.heads.status==="loading"&&"animate-spin")})}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:i,children:a("close")})]}),(0,n.jsxs)("div",{className:(0,C.cn)("grid min-h-0 flex-1",J&&!s?"grid-cols-[220px_minmax(0,1fr)]":"grid-cols-1"),children:[!J||s&&u?null:(0,n.jsxs)("aside",{className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto border-r bg-sidebar p-2 max-sm:border-r-0",children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("repositories")}),R.map(t=>{let s=(0,d8.Hj)(e.projectName,t.root),r=t.root===D;return(0,n.jsxs)("button",{"data-testid":`git-branch-picker-repository-${t.root||"root"}`,type:"button",className:(0,C.cn)("grid min-h-12 w-full grid-cols-[minmax(0,1fr)_auto] items-center gap-2 rounded-lg px-2 text-left hover:bg-muted/70",r&&"bg-accent text-accent-foreground"),onClick:()=>{var e;d(e=t.root),m(!0),h(""),f({repositoryRoot:e,overrides:new Map}),w(null),k(!1),E(null),z(null)},children:[(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("strong",{className:"block truncate text-sm font-medium",children:s}),(0,n.jsx)("span",{className:"mt-1 block truncate font-mono text-xs text-muted-foreground",children:t.root||"."})]}),(0,n.jsx)("span",{className:"flex flex-col items-end gap-1 text-xs text-muted-foreground",children:(0,n.jsx)("span",{className:"max-w-28 truncate",children:"ready"===t.state?(0,d8.ws)(t.head):a("unavailable")})})]},t.root)})]}),s&&J&&!u?null:(0,n.jsxs)("section",{className:"flex min-h-0 min-w-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-13 shrink-0 items-center gap-2 border-b px-3",children:[s&&J?(0,n.jsx)(I.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":a("backRepositories"),onClick:()=>m(!1),children:(0,n.jsx)(A.A,{className:"size-4"})}):null,(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("p",{className:"truncate text-sm font-semibold",children:[T?(0,d8.Hj)(e.projectName,T.root):a("chooseRepository"),T?.state==="ready"?` \xb7 ${(0,d8.ws)(T.head)}`:""]}),(0,n.jsx)("p",{className:"mt-1 break-words font-mono text-xs text-muted-foreground",children:T?.root||"."})]}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",disabled:T?.state!=="ready"||F,onClick:()=>H(null),children:[(0,n.jsx)(U.A,{className:"size-3.5"})," ",a("createBranch")]})]}),$?.heads.status==="error"?(0,n.jsx)("p",{className:"border-b bg-muted px-3 py-2 text-sm text-destructive",children:$.heads.error}):null,M?(0,n.jsx)("p",{className:"border-b bg-muted px-3 py-2 text-sm text-destructive",children:M}):null,(0,n.jsx)("div",{className:"flex shrink-0 items-center gap-2 border-b p-2",children:y?(0,n.jsxs)("form",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",onSubmit:s=>{let n;s.preventDefault(),(n=j.trim())&&null!==D&&!F&&G(()=>t.addBranch(e.cwd,D,n,S),a("branchCreated",{name:n}))},children:[(0,n.jsx)(em.p,{autoFocus:!0,value:j,onChange:e=>N(e.currentTarget.value),placeholder:a("newBranchName"),"aria-label":a("newBranchName"),className:"min-w-[12rem] flex-1"}),(0,n.jsxs)(I.$,{type:"submit",size:"sm",disabled:!j.trim()||F,children:[F?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):null,a("createAndSwitch")]}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>{k(!1),E(null)},children:a("cancel")})]}):(0,n.jsx)(em.p,{value:p,onChange:e=>h(e.currentTarget.value),placeholder:a("searchBranches"),"aria-label":a("searchBranches")})}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-2",children:T?.state==="unavailable"?(0,n.jsx)("p",{className:"p-5 text-center text-xs text-destructive",children:(0,eJ.fD)(T.message,l)}):O?.status!=="loading"||L?O?.status==="error"?(0,n.jsxs)("div",{className:"flex min-h-24 flex-col items-center justify-center gap-2 text-center text-xs text-destructive",children:[(0,n.jsx)("p",{children:O.error}),null!==D?(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void t.loadBranches(e.cwd,D),children:a("retry")}):null]}):L?(0,n.jsxs)("div",{className:"space-y-3",children:[_.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("recentlyUsed")}),_.map(e=>Z({type:"local",name:e},"recent"))]}):null,B.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("localBranches")}),et(W,"local")]}):null,q.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("remoteBranches")}),et(Y,"remote")]}):null,0===_.length&&0===B.length&&0===q.length?(0,n.jsx)("p",{className:"p-5 text-center text-xs text-muted-foreground",children:a("noBranchMatches")}):null]}):null:(0,n.jsxs)("div",{className:"flex min-h-24 items-center justify-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"})," ",a("loadingBranches")]})})]})]})]})})}function ut(e,t){return e instanceof DOMException&&"AbortError"===e.name?t:e instanceof Error?e.message:t}class us{constructor(e,t){this.biz=e,this.onRepositoryChanged=t,this.listeners=new Set,this.workspaces=new Map,this.projectRefs=new Map,this.revision=0,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.getRevision=()=>this.revision}getWorkspace(e){return e?this.workspaces.get(e)??null:null}reconcileWorkSessions(e,t,s=[]){let n=new Map,r=t?e.find(e=>e.workId===t)??null:null;for(let t of(r&&n.set(r.cwd,{workId:r.workId,cwd:r.cwd}),e))n.has(t.cwd)||n.set(t.cwd,{workId:t.workId,cwd:t.cwd});for(let e of s)n.has(e.cwd)||n.set(e.cwd,{...e,readOnly:!0});if(n.size!==this.projectRefs.size||[...n].some(([e,t])=>this.projectRefs.get(e)?.workId!==t.workId||this.projectRefs.get(e)?.readOnly!==t.readOnly)){for(let[e,t]of(this.projectRefs.clear(),n))this.projectRefs.set(e,t);for(let[e,t]of this.workspaces)n.has(e)||(this.abortRequests(t),this.workspaces.delete(e))}}ensureSnapshot(e){let t=this.workspaceFor(e);return"ready"===t.snapshot.status||"loading"===t.snapshot.status?Promise.resolve():this.loadSnapshot(e)}refreshSnapshot(e){return this.loadSnapshot(e)}async refreshHeads(e){let t=this.workspaceFor(e);if(t.headsRequest||Date.now()-t.lastHeadsStartedAt<3e4)return;let s=this.projectRefs.get(e);if(!s){t.heads={...t.heads,status:"error",error:dR("gitNoProjectStatus")},this.publish();return}let n=new AbortController,r={};t.headsRequest={controller:n,token:r},t.lastHeadsStartedAt=Date.now(),t.heads={...t.heads,status:"loading",error:null},this.publish();try{let i=await this.biz.getHeads({workId:s.workId,cwd:e},n.signal);if(t.headsRequest?.token!==r)return;t.headsRequest=null,t.heads={status:"ready",repositories:i.repositories,error:null},this.publish()}catch(e){if(t.headsRequest?.token!==r||(t.headsRequest=null,n.signal.aborted))return;t.heads={...t.heads,status:"error",error:ut(e,dR("gitStatusReadFailed"))},this.publish()}}setLayout(e,t){let s=this.workspaceFor(e);s.layout!==t&&(s.layout=t,this.publish())}setChangesOnly(e,t){let s=this.workspaceFor(e);s.changesOnly!==t&&(s.changesOnly=t,this.publish())}toggleRepository(e,t){let s=this.workspaceFor(e);s.expandedRepositories.has(t)?s.expandedRepositories.delete(t):s.expandedRepositories.add(t),this.publish()}async loadBranches(e,t){let s=this.workspaceFor(e),n=this.projectRefs.get(e);if(!n){s.branches.set(t,{status:"error",data:null,error:dR("gitNoProjectBranches")}),this.publish();return}s.branchRequests.get(t)?.controller.abort();let r=new AbortController,i={};s.branchRequests.set(t,{controller:r,token:i}),s.branches.set(t,{status:"loading",data:s.branches.get(t)?.data??null,error:null}),this.publish();try{let a=await this.biz.listBranches({workId:n.workId,cwd:e,repositoryRoot:t},r.signal);if(s.branchRequests.get(t)?.token!==i)return;s.branchRequests.delete(t),s.branches.set(t,{status:"ready",data:a,error:null}),this.publish()}catch(e){if(s.branchRequests.get(t)?.token!==i||(s.branchRequests.delete(t),r.signal.aborted))return;s.branches.set(t,{status:"error",data:null,error:ut(e,dR("gitBranchesReadFailed"))}),this.publish()}}async replaceBranch(e,t,s){let n=this.requireWritableProject(e),r=this.workspaceFor(e);if(!r.branchOperations.has(t)){r.branchOperations.add(t),this.publish();try{let i=await this.biz.replaceBranch({...n,repositoryRoot:t,target:s});this.applyRepository(r,i.repository),this.clearBranches(r,t),this.onRepositoryChanged(e,t)}finally{r.branchOperations.delete(t),this.publish()}}}async addBranch(e,t,s,n){let r=this.requireWritableProject(e),i=this.workspaceFor(e);if(!i.branchOperations.has(t)){i.branchOperations.add(t),this.publish();try{let a=await this.biz.addBranch({...r,repositoryRoot:t,name:s,startPoint:n});this.applyRepository(i,a.repository),this.clearBranches(i,t),this.onRepositoryChanged(e,t)}finally{i.branchOperations.delete(t),this.publish()}}}getDiff(e,t,s,n){return this.biz.getDiff({...this.requireProject(e),repositoryRoot:t,path:s},n)}dispose(){for(let e of this.workspaces.values())this.abortRequests(e);this.workspaces.clear(),this.projectRefs.clear(),this.listeners.clear()}async loadSnapshot(e){let t=this.workspaceFor(e);if(t.snapshotRequest)return;let s=this.projectRefs.get(e);if(!s){t.snapshot={status:"error",repositories:t.snapshot.repositories,error:dR("gitNoProjectStatus")},this.publish();return}let n=new AbortController,r={};t.snapshotRequest={controller:n,token:r},"ready"!==t.snapshot.status&&(t.snapshot={status:"loading",repositories:t.snapshot.repositories,error:null},this.publish());try{let i=await this.biz.get({workId:s.workId,cwd:e},n.signal);if(t.snapshotRequest?.token!==r)return;t.snapshotRequest=null,t.snapshot={status:"ready",repositories:i.repositories,error:null};let a=new Set(i.repositories.map(e=>e.root));for(let e of(i.repositories.length>0&&!a.has("")&&a.add(""),[...t.expandedRepositories]))a.has(e)||t.expandedRepositories.delete(e);this.publish()}catch(e){if(t.snapshotRequest?.token!==r||(t.snapshotRequest=null,n.signal.aborted))return;t.snapshot={status:"error",repositories:t.snapshot.repositories,error:ut(e,dR("gitStatusReadFailed"))},this.publish()}}requireProject(e){let t=this.projectRefs.get(e);if(!t)throw Error(dR("gitNoProjectOperation"));return{workId:t.workId,cwd:t.cwd}}requireWritableProject(e){if(this.projectRefs.get(e)?.readOnly)throw Error(dR("gitNoProjectOperation"));return this.requireProject(e)}applyRepository(e,t){e.headsRequest?.controller.abort(),e.headsRequest=null,e.snapshotRequest?.controller.abort(),e.snapshotRequest=null;let s={root:t.root,state:t.state,head:t.head},n=[...e.heads.repositories],r=n.findIndex(e=>e.root===t.root);if(r>=0?n[r]=s:n.push(s),e.heads={status:"ready",repositories:n,error:null},e.lastHeadsStartedAt=Date.now(),"idle"===e.snapshot.status)return;let i="loading"===e.snapshot.status,a=[...e.snapshot.repositories],l=a.findIndex(e=>e.root===t.root);l>=0?a[l]=t:a.push(t),e.snapshot={status:"ready"===e.snapshot.status?"ready":"idle",repositories:a,error:null},i&&this.refreshSnapshot(e.cwd)}abortRequests(e){for(let t of(e.headsRequest?.controller.abort(),e.headsRequest=null,e.snapshotRequest?.controller.abort(),e.snapshotRequest=null,e.branchRequests.values()))t.controller.abort();e.branchRequests.clear()}clearBranches(e,t){e.branchRequests.get(t)?.controller.abort(),e.branchRequests.delete(t),e.branches.delete(t)}workspaceFor(e){let t=this.workspaces.get(e);if(t)return t;let s={cwd:e,heads:{status:"idle",repositories:[],error:null},headsRequest:null,lastHeadsStartedAt:0,snapshot:{status:"idle",repositories:[],error:null},snapshotRequest:null,branches:new Map,branchRequests:new Map,layout:"directory",changesOnly:!1,expandedRepositories:new Set,branchOperations:new Set};return this.workspaces.set(e,s),s}publish(){for(let e of(this.revision+=1,[...this.listeners]))e()}}var un=s(24985);let ur=un.y2,ui=a.Ik({workId:dd.eW,cwd:dd.ik}).strict(),ua=un.Ww,ul=un.cP,uo=un.zp,uc=un.u2;a.Ik({repositories:a.YO(uc).max(ur)}).strict();let ud=ui.extend({repositoryRoot:ua}).strict(),uu=un.zt,um=ui.extend({repositoryRoot:ua,target:uu}).strict(),up=ui.extend({repositoryRoot:ua,name:ul,startPoint:uu.nullable()}).strict(),uh=a.Ik({repository:uo}).strict(),ug=ui.extend({repositoryRoot:ua,path:s0._g}).strict();var uf=s(68269);let ux=Object.freeze({messages:[],temporaryMessages:[],runtime:{extensionMode:"normal",presentationMode:"normal",initializationError:null,queues:{steering:[],followUp:[]},model:null,capabilityMode:null,contextUsage:null,plugins:{}}});function ub(e){let t=new Set;for(let[s,n]of e.entries()){if(n.location.index!==s||t.has(n.location.entryId))return null;t.add(n.location.entryId)}let s=e.at(-1);return s?{index:s.location.index,entryId:s.location.entryId}:null}var uv=s(82639);let uw="messages",uy="source",uk="drafts",uj="outbox",uN="pi-super-chat",uI=null,uS=null;function uC(e){return Error((0,ed.B)({msg:uv.n["zh-CN"].common[e],i18n:{key:`common:${e}`}}))}function uE(e,t){e.objectStoreNames.contains(t)||e.createObjectStore(t,{keyPath:["sessionId","branchId"]})}function uM(){return new Promise((e,t)=>{let s=indexedDB.open(uN,2),n=!1,r=window.setTimeout(()=>{i(uC("dbOpenTimeout"))},1e4),i=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("upgradeneeded",()=>{let e=s.result;e.objectStoreNames.contains(uw)||e.createObjectStore(uw,{keyPath:["sessionId","branchId","index"]}).createIndex(uy,["sessionId","branchId"],{unique:!1}),uE(e,uk),uE(e,uj)},{once:!0}),s.addEventListener("blocked",()=>{i(uC("dbOpenBlocked"))},{once:!0}),s.addEventListener("success",()=>{let t=s.result;n?t.close():(n=!0,window.clearTimeout(r),e(t))},{once:!0}),s.addEventListener("error",()=>i(s.error??uC("dbOpenFailed")),{once:!0})})}async function uz(){try{return await uM()}catch(e){if(!("object"==typeof e&&null!==e&&"name"in e&&"VersionError"===e.name))throw e;return console.warn("[Pi Desk][ChatIndexedDB] 本地数据库版本高于当前版本,清空全部本地聊天数据后重建",{databaseName:uN,requestedVersion:2}),await new Promise((e,t)=>{let s=indexedDB.deleteDatabase(uN),n=!1,r=window.setTimeout(()=>{i(uC("dbDeleteTimeout"))},1e4),i=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("blocked",()=>{i(uC("dbDeleteBlocked"))},{once:!0}),s.addEventListener("success",()=>{n||(n=!0,window.clearTimeout(r),e())},{once:!0}),s.addEventListener("error",()=>i(s.error??uC("dbDeleteFailed")),{once:!0})}),uM()}}function uA(){return uS?Promise.resolve(uS):uI||(uI=uz().then(e=>(uS=e,e.addEventListener("versionchange",()=>{e.close(),uS===e&&(uS=null,uI=null),console.warn("[Pi Desk][ChatIndexedDB] 数据库版本已变化,当前连接已关闭")}),e)).catch(e=>{throw uI=null,e}))}function u$(e){return new Promise((t,s)=>{e.addEventListener("success",()=>t(e.result),{once:!0}),e.addEventListener("error",()=>s(e.error??uC("dbRequestFailed")),{once:!0})})}function uR(e,t,s){let n=e.target;return n?.error??t.error??Error(s)}function uP(e){return new Promise((t,s)=>{e.addEventListener("complete",()=>t(),{once:!0}),e.addEventListener("abort",t=>s(uR(t,e,uC("dbTransactionAborted").message)),{once:!0}),e.addEventListener("error",t=>s(uR(t,e,uC("dbTransactionFailed").message)),{once:!0})})}let uD=a.Ik({sessionId:a.Yj().trim().min(1),branchId:a.Yj().trim().min(1),index:a.ai().int().nonnegative(),entryId:a.Yj().trim().min(1),fixed:uf.ao,summary:uf.lV,detail:uf.wI.optional()}).strict();function uT(e,t){return uD.parse({sessionId:e.sessionId,branchId:e.branchId,index:t.location.index,entryId:t.location.entryId,fixed:t.fixed,summary:t.summary,...void 0===t.detail?{}:{detail:t.detail}})}function uO(e){let t=uD.parse(e);if("assistant"===t.fixed.type&&"pi-desk/assistant"===t.fixed.viewKey){if(!Object.hasOwn(t.summary,"errorMessage"))throw Error("Assistant Summary cache uses an outdated projection");uf.Y2.parse(t.summary),void 0!==t.detail&&uf.$f.parse(t.detail)}return uf.wR.parse({location:{index:t.index,entryId:t.entryId},fixed:t.fixed,summary:t.summary,...void 0===t.detail?{}:{detail:t.detail}})}function uL(e,t){e.delete(IDBKeyRange.bound([t.sessionId,t.branchId,0],[t.sessionId,t.branchId,Number.MAX_SAFE_INTEGER]))}let uF=a.Yj().max(65536),uB=a.Ik({id:a.Yj().uuid(),title:uF,expiresAt:a.ai().int().nonnegative().nullable()}),uq=a.gM("method",[uB.extend({method:a.eu("confirm"),message:uF}).strict(),uB.extend({method:a.eu("select"),options:a.YO(uF).max(200)}).strict(),uB.extend({method:a.eu("input"),placeholder:uF}).strict(),uB.extend({method:a.eu("editor"),prefill:uF}).strict()]),u_=a.Ik({requests:a.YO(uq).max(32),statuses:a.g1(a.Yj().max(128),uF),widgets:a.g1(a.Yj().max(128),a.Ik({lines:a.YO(uF).max(200),placement:a.k5(["aboveEditor","belowEditor"])}).strict())}).strict(),uW=a.Ik({id:a.Yj().uuid(),value:a.KC([a.zM(),uF,a.ch()])}).strict(),uY=a.gM("type",[a.Ik({type:a.eu("snapshot"),snapshot:u_}).strict(),a.Ik({type:a.eu("notify"),message:uF,level:a.k5(["info","warning","error"])}).strict(),a.Ik({type:a.eu("editor_text"),text:uF,mode:a.k5(["replace","paste"])}).strict()]),uV=a.Ik({source:ll.R}).strict(),uU=a.Ik({}).strict(),uK=Object.freeze({subscribe:(0,l.Vc)({path:"pi/ui/subscribe",inputSchema:uV,outputSchema:u_}),unsubscribe:(0,l.Vc)({path:"pi/ui/unsubscribe",inputSchema:uV,outputSchema:uU}),respond:(0,l.Vc)({path:"pi/ui/respond",inputSchema:uV.extend({response:uW}).strict(),outputSchema:uU}),event:(0,l._G)({path:"pi/ui/event",bodySchema:uV.extend({event:uY}).strict()})});function uH(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}class uG{constructor(e){this.socket=e,this.records=new Map,this.listeners=new Set,this.notices=new Set,this.releasePush=null,this.connected=!1,this.epoch=0,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e))}onNotice(e){return this.notices.add(e),()=>this.notices.delete(e)}getState(e){return this.record(e).state}watch(e){this.releasePush||(this.releasePush=this.socket.subscribe(uK.event,({source:e,event:t})=>{let s=this.records.get(uH(e));if(s&&this.connected)if("snapshot"===t.type)s.state.refreshing?s.latest=t.snapshot:this.apply(s,t.snapshot);else if("editor_text"===t.type)this.patch(s,{prefill:t});else for(let n of(this.appendNotice(s,t),this.notices))n(e,t)}));let t=this.record(e);!this.connected||t.state.ready||t.state.refreshing||this.refresh(t)}ready(e){for(let t of(this.reconcile(e),this.connected=!0,this.records.values()))this.refresh(t)}reconcile(e){let t=new Set(e.map(uH));for(let[e,s]of this.records)!t.has(e)&&(this.records.delete(e),this.connected&&this.socket.request(uK.unsubscribe,{source:s.source}).catch(()=>void 0));this.emit()}disconnected(){for(let e of(this.connected=!1,this.epoch+=1,this.records.values()))e.latest=null,this.patch(e,{ready:!1,refreshing:!1,submitting:null,commandPending:null,unknown:e.state.submitting??e.state.unknown})}edit(e,t){this.patch(this.record(e),t)}refreshSource(e){return this.refresh(this.record(e))}async respond(e,t){let s=this.record(e);if(!s.state.ready||s.state.submitting||s.state.unknown)return;let n=this.epoch;this.patch(s,{submitting:t.id,error:null});try{await this.socket.request(uK.respond,{source:e,response:t}),this.current(s,n)&&s.state.submitting===t.id&&this.patch(s,{submitting:null})}catch(r){if(!this.current(s,n)||!s.state.snapshot.requests.some(e=>e.id===t.id))return;let e=r instanceof Error&&"code"in r;this.patch(s,{submitting:null,unknown:e?null:t.id,error:e?r.message:dR("nativeUiUnknown")}),this.connected&&await this.refresh(s,e)}}async executeCommand(e,t,s){let n=this.record(e);if(!n.state.ready||n.state.commandPending)return;let r=this.epoch;this.patch(n,{commandPending:`/${t}${s?` ${s}`:""}`});try{await this.socket.request(dM.QV.commandExecute,{source:e,command:t,args:s})}catch(e){this.current(n,r)&&this.appendNotice(n,{level:"error",message:e instanceof Error?e.message:dR("operationFailed")})}finally{this.current(n,r)&&this.patch(n,{commandPending:null})}}dispose(){this.disconnected(),this.releasePush?.(),this.releasePush=null,this.records.clear(),this.listeners.clear(),this.notices.clear()}record(e){let t=uH(e),s=this.records.get(t);return s||(s={source:e,latest:null,state:{snapshot:{requests:[],statuses:{},widgets:{}},notices:[],commandPending:null,ready:!1,refreshing:!1,error:null,submitting:null,unknown:null,answers:{},collapsed:!1,prefill:null}},this.records.set(t,s)),s}current(e,t){return this.epoch===t&&this.records.get(uH(e.source))===e}async refresh(e,t=!1){if(!this.connected||e.state.refreshing)return;let s=this.epoch;e.latest=null,this.patch(e,{ready:!1,refreshing:!0});try{let n=await this.socket.request(uK.subscribe,{source:e.source});if(!this.current(e,s))return;this.apply(e,e.latest??n),this.patch(e,{ready:!0,unknown:null,...!t?{error:null}:{}})}catch(t){this.current(e,s)&&this.patch(e,{ready:!1,error:t instanceof Error?t.message:dR("nativeUiFailed")})}finally{this.current(e,s)&&(e.latest=null,this.patch(e,{refreshing:!1}))}}apply(e,t){let s=new Set(t.requests.map(e=>e.id)),n=Object.fromEntries(Object.entries(e.state.answers).filter(([e])=>s.has(e)));this.patch(e,{snapshot:t,answers:n,submitting:e.state.submitting&&s.has(e.state.submitting)?e.state.submitting:null,unknown:e.state.unknown&&s.has(e.state.unknown)?e.state.unknown:null,...t.requests[0]?.id!==e.state.snapshot.requests[0]?.id?{error:null}:{}})}appendNotice(e,t){let s=[...e.state.notices,{level:t.level,message:t.message.slice(0,65536)}].slice(-32),n=s.reduce((e,t)=>e+t.message.length,0);for(;n>65536&&s.length>1;)n-=s.shift().message.length;this.patch(e,{notices:s})}patch(e,t){e.state={...e.state,...t},this.emit()}emit(){for(let e of this.listeners)e()}}let uJ=Object.freeze({...ux,syncStatus:"loading"});function uQ(e){return uf.Pi.parse({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId})}function uX(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function uZ(e,t){return e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}let u0={text:"",images:[]};function u1(e){return[e.sessionId,e.branchId]}function u2(e,t){return{sessionId:e.sessionId,branchId:e.branchId,text:t.text,images:t.images}}function u5(e){if(!e||"object"!=typeof e||"string"!=typeof e.text||!Array.isArray(e.images))return null;let t=[];for(let s of e.images){if(!s||"object"!=typeof s||!(s.blob instanceof Blob)||"string"!=typeof s.mimeType||!Number.isSafeInteger(s.width)||s.width<=0||!Number.isSafeInteger(s.height)||s.height<=0||"boolean"!=typeof s.optimized)return null;t.push({blob:s.blob,mimeType:s.mimeType,width:s.width,height:s.height,optimized:s.optimized})}return{text:e.text,images:t}}function u3(e,t){return t?{text:[e.text,t.text].filter(e=>e.trim()).join("\n\n"),images:[...e.images,...t.images]}:e}var u4=s(67837);let u6=new Set(["image/jpeg","image/png","image/webp","image/gif","image/bmp"]),u8=new Set(["image/jpeg","image/png","image/webp","image/gif"]),u7=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function u9(e){return e.type.toLowerCase().split(";")[0]??""}async function me(e){let t;try{t=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{throw Error(dR("imageDecodeFailed"))}if(!Number.isSafeInteger(t.width)||t.width<=0||t.height<=0)throw t.close(),Error(dR("imageInvalidDimensions"));return{bitmap:t,width:t.width,height:t.height}}function mt(e,t,s){let n=Math.max(e,t);if(n<=s)return{width:e,height:t};let r=s/n;return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}}function ms(e,t,s,n,r){let i=document.createElement("canvas");i.width=t,i.height=s;let a=i.getContext("2d");if(!a)throw Error(dR("canvasUnavailable"));return a.drawImage(e,0,0,t,s),new Promise((e,t)=>{i.toBlob(s=>s?e(s):t(Error(dR("imageCompressFailed"))),n,r)})}async function mn(e){let t=new Uint8Array(await e.slice(0,262144).arrayBuffer());if(t.length<4||255!==t[0]||216!==t[1])return null;let s=2;for(;s+3<t.length;){for(;s<t.length&&255!==t[s];)s+=1;for(;s<t.length&&255===t[s];)s+=1;if(s>=t.length)break;let e=t[s];if(s+=1,216===e||1===e||e>=208&&e<=215)continue;if(217===e||218===e||s+1>=t.length)break;let n=t[s]<<8|t[s+1];if(n<2||s+n>t.length)break;if(u7.has(e)&&n>=7)return{width:t[s+5]<<8|t[s+6],height:t[s+3]<<8|t[s+4]};s+=n}return null}async function mr(e){let t=u9(e);if(!u6.has(t))throw Error(dR("imageTypeUnsupported"));let s=await me(e);return s.bitmap.close(),{blob:e,mimeType:t,width:s.width,height:s.height,optimized:"image/gif"===t}}async function mi(e){if(e.optimized){if(e.blob.size>0xa00000)throw Error(dR("singleImageLimit"));return e}let t=await me(e.blob);try{var s;let n=mt(t.width,t.height,2560),r=(s=e.mimeType,"image/jpeg"===s?"image/jpeg":"image/webp"),i=e.blob.size>5242880?.85:"image/jpeg"===r?.9:.92,a=await ms(t.bitmap,n.width,n.height,r,i),l=n.width,o=n.height,c=l!==t.width||o!==t.height,d="image/jpeg"===e.mimeType?await mn(e.blob):null,u="image/jpeg"===e.mimeType&&(null===d||d.width!==t.width||d.height!==t.height),m=u8.has(e.mimeType)&&!u;if(!c&&m&&a.size>=.9*e.blob.size&&(a=e.blob,l=t.width,o=t.height),a.size>0xa00000){let e=mt(t.width,t.height,2048);a=await ms(t.bitmap,e.width,e.height,r,.82),l=e.width,o=e.height}if(a.size>0xa00000)throw Error(dR("compressedImageTooLarge"));let p=u9(a);if(!u8.has(p))throw Error(dR("compressedTypeUnsupported"));return{blob:a,mimeType:p,width:l,height:o,optimized:!0}}finally{t.bitmap.close()}}async function ma(e){if(!e.optimized)throw Error(dR("imagesPending"));let t=new Uint8Array(await e.blob.arrayBuffer()),s="";for(let e=0;e<t.length;e+=32768)s+=String.fromCharCode(...t.subarray(e,e+32768));return{mimeType:e.mimeType,width:e.width,height:e.height,data:btoa(s)}}function ml(e,t,s=e.optimized?"ready":"optimizing"){return{...e,localId:(0,u4.y)(),objectUrl:URL.createObjectURL(e.blob),name:t,status:s,error:null}}function mo(e){URL.revokeObjectURL(e.objectUrl)}function mc(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function md(e){return e.map(({blob:e,mimeType:t,width:s,height:n,optimized:r})=>({blob:e,mimeType:t,width:s,height:n,optimized:r}))}function mu(e){return{text:e.text,images:md(e.images)}}function mm(e,t){return e instanceof Error&&e.message?e.message:t}function mp(e,t){return[e,t].filter(e=>e.trim()).join("\n\n")}function mh(e,t,s){return`${mc(e)}\u0000temp\u0000${t}\u0000${s}`}function mg(e,t,s){return`${mc(e)}\u0000entry\u0000${t}\u0000${s}`}function mf(e){for(let t of e)mo(t)}var mx=s(63273),mb=s(15104),mv=s(11039),mw=s(97906),my=s(94411);let mk=["title","user"];function mj({active:e,scope:t,query:s,searchIn:n,request:i,failureMessage:a}){let[l,o]=(0,r.useState)(0),c=(0,r.useRef)(!1),d=s.trim(),u=(0,r.useMemo)(()=>({active:e,scope:t,query:d,searchIn:n,request:i,attempt:l,failureMessage:a}),[e,t,d,n,i,l,a]),[m,p]=(0,r.useState)(null);m?.key!==u&&p({key:u,data:null,loading:u.active,error:null}),(0,r.useLayoutEffect)(()=>{let e=c.current;if(c.current=!1,!u.active)return;let t=new AbortController,s=window.setTimeout(()=>{i({query:u.query,searchIn:[...u.searchIn]},t.signal,e).then(e=>{t.signal.aborted||p({key:u,data:e,loading:!1,error:null})},e=>{t.signal.aborted||p({key:u,data:null,loading:!1,error:e instanceof Error?e.message:u.failureMessage})})},u.query&&!e?300:0);return()=>{window.clearTimeout(s),t.abort()}},[u,i]);let h=(0,r.useCallback)(()=>{c.current=!0,o(e=>e+1)},[]),g=m?.key===u?m:null;return{data:g?.data??null,loading:e&&(g?.loading??!0),error:g?.error??null,refresh:h}}let mN=[{value:"title",label:"scopeTitle"},{value:"user",label:"scopeUser"},{value:"assistant",label:"scopeAssistant"},{value:"sessionId",label:"Session ID"}];function mI({value:e,onChange:t,disabled:s=!1,compact:r=!1}){let{t:i}=(0,b.Bd)("workbenchPicker"),a=s=>{e.includes(s)?e.length>1&&t(e.filter(e=>e!==s)):t([...e,s])};return r?(0,n.jsxs)(H.rI,{children:[(0,n.jsx)(H.ty,{render:(0,n.jsx)("button",{"data-testid":"work-session-search-scopes",type:"button",disabled:s,"aria-label":i("searchScopes"),title:i("searchScopes"),className:(0,I.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(sW.A,{className:"size-4"})})}),(0,n.jsx)(H.SQ,{align:"end",children:mN.map(t=>(0,n.jsx)(H.hO,{checked:e.includes(t.value),disabled:s||1===e.length&&e.includes(t.value),closeOnClick:!1,onCheckedChange:()=>a(t.value),children:i(t.label)},t.value))})]}):(0,n.jsxs)("fieldset",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1.5 px-0.5",children:[(0,n.jsx)("legend",{className:"mr-1 text-xs text-muted-foreground",children:i("searchScopes")}),mN.map(t=>{let r=e.includes(t.value);return(0,n.jsxs)("label",{className:"flex min-h-7 cursor-pointer items-center gap-2 text-sm text-muted-foreground has-[:focus-visible]:rounded-sm has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring",children:[(0,n.jsx)("input",{type:"checkbox",checked:r,disabled:s||r&&1===e.length,onChange:()=>a(t.value),className:"size-4 accent-primary"}),(0,n.jsx)("span",{children:i(t.label)})]},t.value)})]})}function mS(e,t,s="bg-accent text-accent-foreground"){let r=t.trim().toLocaleLowerCase();if(!r)return e;let i=e.toLocaleLowerCase(),a=[],l=0,o=i.indexOf(r);for(;o>=0;){o>l&&a.push(e.slice(l,o));let t=o+r.length;a.push((0,n.jsx)("mark",{className:`rounded-sm px-px ${s}`,children:e.slice(o,t)},`${o}-${t}`)),l=t,o=i.indexOf(r,l)}return l<e.length&&a.push(e.slice(l)),a.length?a:e}function mC(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function mE(e){return e.trim().toLocaleLowerCase()}function mM(e,t,s){return"title"===e?s("scopeTitle"):"sessionId"===e?"Session ID":s("user"===e?"scopeUserMatches":"scopeAssistantMatches",{count:t})}function mz(e){switch(e){case"user":case"assistant":case"title":return"bg-muted text-foreground";case"sessionId":return"bg-muted text-muted-foreground"}}function mA(e){switch(e){case"user":case"assistant":case"title":return"bg-accent text-accent-foreground";case"sessionId":return"bg-muted-foreground/25 text-foreground"}}function m$({scope:e,className:t}){switch(e){case"user":return(0,n.jsx)(mx.A,{className:t});case"assistant":return(0,n.jsx)(eD.A,{className:t});case"title":return(0,n.jsx)(mb.A,{className:t});case"sessionId":return(0,n.jsx)(mv.A,{className:t})}}function mR({open:e,pickerMode:t,pickerView:s,pickerCwd:i,directories:a,ignoredDirectories:l,directoryBrowser:o,replacementTarget:c,unavailableSessionIds:d,error:u,loading:m,creatingCwd:p,replacingSessionId:h,updatingIgnoreCwd:g,onOpenChange:f,onBack:x,onListSessionHistory:v,onListSessionUserMessages:w,onRefresh:y,onOpenIgnoredDirectories:k,onOpenDirectoryBrowser:j,onNavigateDirectory:N,onSelectBrowserDirectory:S,onReplaceDirectoryIgnore:C,onSelectDirectory:E,onSelectSession:M}){let{t:z}=(0,b.Bd)("workbenchPicker"),{locale:$,timeZone:R}=(0,eQ.i)(),P=(0,r.useMemo)(()=>new Intl.DateTimeFormat("en"===$?"en-US":"zh-CN",{timeZone:R,month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),[$,R]),[D,T]=(0,r.useState)(""),[O,L]=(0,r.useState)(mk),[F,B]=(0,r.useState)(""),q=JSON.stringify([e,t,i,s]),[_,W]=(0,r.useState)(q);_!==q&&(W(q),T(""),L(mk),B(""));let Y=null!==p||null!==h||null!==g,V=function({active:e,cwd:t,query:s,searchIn:n,listSessionHistory:i,listSessionUserMessages:a}){let{t:l}=(0,b.Bd)("workbenchPicker"),o=(0,r.useCallback)((e,s,n)=>i({...e,cwd:t,forceRefresh:n},s),[t,i]),c=mj({active:e&&null!==t,scope:t,query:s,searchIn:n,request:o,failureMessage:l("loadHistoryFailed")}),[d,u]=(0,r.useState)(null),m=(0,r.useMemo)(()=>({active:e,cwd:t,query:s,searchIn:n}),[e,t,s,n]),[p,h]=(0,r.useState)(m);p!==m&&(h(m),u(null));let g=(0,r.useRef)(null),f=(0,r.useCallback)(()=>{g.current?.abort(),g.current=null,u(null)},[]);(0,r.useLayoutEffect)(()=>()=>{g.current?.abort(),g.current=null},[e,t,s,n]);let x=async(s,n,r,i)=>{if(!e||!t)return;g.current?.abort();let o=new AbortController;g.current=o,u(e=>({sessionId:s,query:n,messages:i&&e?.sessionId===s?e.messages:[],page:i&&e?.sessionId===s?e.page:null,loading:!0,error:null}));try{let e=await a({cwd:t,sessionId:s,query:n,page:{index:r,size:20}},o.signal);if(o.signal.aborted)return;u(t=>({sessionId:s,query:n,messages:i&&t?.sessionId===s?[...t.messages,...e.messages]:e.messages,page:e.page,loading:!1,error:null}))}catch(e){if(o.signal.aborted)return;u(t=>({sessionId:s,query:n,messages:t?.sessionId===s?t.messages:[],page:t?.sessionId===s?t.page:null,loading:!1,error:e instanceof Error?e.message:l("loadUserFailed")}))}finally{g.current===o&&(g.current=null)}};return{sessions:c.data?.sessions??[],loading:c.loading,error:c.error,refresh:()=>{f(),c.refresh()},expandedHistory:e?d:null,toggleUserMessages:e=>{if(d?.sessionId===e.sessionId)return void f();let t=e.matches?.some(e=>"user"===e.scope)?s:"";x(e.sessionId,t,1,!1)},loadUserMessages:x}}({active:e&&"history"===s&&!Y,cwd:i,query:D,searchIn:O,listSessionHistory:v,listSessionUserMessages:w}),{sessions:U,expandedHistory:K,toggleUserMessages:H,loadUserMessages:G}=V,J="history"===s?V.loading:m,Q=u??("history"===s?V.error:null),X=(0,r.useMemo)(()=>new Set(d),[d]),Z=mE(D),ee=function(e){let t=e.trim();if(t.length<2)return t;let s=t.at(0);return('"'===s||"'"===s)&&t.at(-1)===s?t.slice(1,-1).trim():t}(F),et=/^(?:[A-Za-z]:[\\/]|[\\/]{2}|\/)/.test(ee),en="ignored"===s?l:a,er=en.filter(e=>!Z||mE(`${mC(e.cwd)} ${e.cwd}`).includes(Z)),ei=(o?.directories??[]).filter(e=>!Z||mE(`${e.name} ${e.cwd}`).includes(Z)),ea="ignored"===s?z("ignoredRestoreTitle"):"browser"===s?z("browseOtherTitle"):"replace"===t?z("replaceTitle"):z("createTitle"),el="ignored"===s?z("ignoredRestoreDescription"):"browser"===s?z("browseDescription"):"replace"===t?c?z("replaceDescription",{project:c.projectName,session:c.sessionTitle??z("newSession")}):z("replaceMissingDescription"):z("createDescription"),eo="history"===s?z("searchHistory"):"browser"===s?z("searchBrowser"):"ignored"===s?z("searchIgnored"):z("searchProjects"),ec="history"===s?U.length:"browser"===s?o?.directories.length??0:en.length,ed=J&&("browser"===s?null===o:0===ec),eu="history"===s?z("currentProject",{path:i??""}):"ignored"===s?z("ignoredCount",{count:l.length}):"browser"===s?o?.cwd??z("rootChoose"):"replace"===t?z("replaceChooseFirst"):z("regularExcludesIgnored"),ep="history"===s?z("loadingHistory"):"ignored"===s?z("loadingIgnored"):"browser"===s?z("loadingBrowser"):z("loadingProjects"),eg=e=>{T(""),B(""),N(e)},ef=()=>{J||Y||!et||(T(""),N(ee))};return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{(e||!Y)&&f(e)},children:(0,n.jsxs)(eN.hA,{className:"h-[min(44rem,calc(100dvh-2rem))] max-w-[45rem]",showCloseButton:!Y,finalFocus:!1,children:[(0,n.jsx)(eN.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:["directories"!==s?(0,n.jsx)("button",{type:"button",disabled:Y,onClick:x,"aria-label":z("backFolders"),title:z("backFolders"),className:(0,I.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(A.A,{className:"size-4"})}):(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:(0,n.jsx)(eP.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{children:ea}),(0,n.jsx)(eN.uX,{className:"mt-1 truncate",title:el,children:el})]})]})}),(0,n.jsxs)("div",{className:"shrink-0 border-b px-3 py-2.5 sm:px-4",children:["browser"===s?(0,n.jsxs)("div",{className:"mb-2",children:[(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,n.jsx)(d6.A,{className:"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{value:F,onChange:e=>B(e.target.value),onKeyDown:e=>{"Enter"===e.key&&et&&(e.preventDefault(),ef())},placeholder:z("pastePath"),"aria-label":z("fullPath"),disabled:J||Y,className:"pl-9"})]}),(0,n.jsx)("button",{"data-testid":"workbench-picker-open-directory-path",type:"button",disabled:J||Y||!et,onClick:ef,title:et?z("openTyped"):z("enterAbsolute"),className:(0,I.r)({variant:"outline"}),children:z("open")})]}),(0,n.jsx)("p",{className:"mt-1.5 px-0.5 text-sm text-muted-foreground",children:F.trim()&&!et?z("absoluteExample"):z("pasteHint")})]}):null,(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(eh.A,{className:"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{"data-testid":"history"===s?"workbench-history-search-input":void 0,value:D,maxLength:"history"===s?120:void 0,onChange:e=>T(e.target.value),placeholder:eo,"aria-label":eo,disabled:Y,className:"pl-9"})]}),"history"===s?(0,n.jsx)(mI,{value:O,onChange:L,disabled:Y}):null]}),(0,n.jsx)(eN._Y,{className:"max-h-none min-h-0",children:(0,n.jsxs)("div",{className:"p-2 sm:p-3","aria-busy":J||Y,"aria-live":"polite",children:[Q?(0,n.jsx)("p",{role:"alert",className:"mb-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Q}):null,"replace"===t&&null===c?(0,n.jsx)("p",{role:"alert",className:"mb-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive",children:z("replaceTargetMissing")}):null,ed?(0,n.jsxs)("div",{className:"flex min-h-36 flex-col items-center justify-center gap-3 text-center text-sm text-muted-foreground",children:[(0,n.jsx)(es.A,{className:"size-5 animate-spin"}),(0,n.jsx)("p",{children:ep})]}):"history"===s?0===U.length?null===Q?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:Z?z("noHistoryMatches"):z("noReplaceHistory")}):null:(0,n.jsxs)(n.Fragment,{children:[Z?(0,n.jsx)("p",{className:"px-3 pb-1 pt-0.5 text-xs text-muted-foreground",children:z("sessionFound",{count:U.length})}):null,(0,n.jsx)("div",{className:"divide-y",children:U.map(e=>{let t,s=e.name?.trim()||e.firstMessage.trim()||z("sessionFallback",{id:e.sessionId.slice(0,8)}),r=z("sessionMessages",{users:e.userMessageCount,total:e.messageCount,time:(t=e.updatedAt,P.format(t))}),i=c?.sessionId===e.sessionId,a=X.has(e.sessionId),l=h===e.sessionId,o=null===c,d=Y||i||a||o,u=K?.sessionId===e.sessionId?K:null,m=e.matches??[],p=m.filter(e=>"title"!==e.scope),g=m.find(e=>"user"===e.scope),f=null===u&&p.length>0,x=`workbench-picker-user-message-panel-${e.sessionId}`,b=l?z("replacing"):i?z("current"):a?z("alreadyUsed"):o?z("targetUnavailable"):z("replace"),v=i?z("currentBound"):a?z("historyUsed"):o?z("replaceTargetUnavailable"):z("replaceWith",{name:s}),w=u?z("hideUserMessages"):g?z("viewMatching",{count:g.count}):z("viewUserMessages",{count:e.userMessageCount}),y=u?.page!==null&&null!==u&&u.messages.length<u.page.total;return(0,n.jsxs)("div",{className:"px-2 sm:px-3",children:[(0,n.jsxs)("div",{className:"flex min-h-15 items-center gap-2 py-2",children:[(0,n.jsx)(mw.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",title:s,children:m.some(e=>"title"===e.scope)?mS(s,Z,mA("title")):s}),(0,n.jsx)("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",title:r,children:r})]}),e.userMessageCount>0?(0,n.jsx)("button",{"data-testid":`workbench-picker-user-messages-${e.sessionId}`,type:"button",disabled:Y,"aria-label":w,"aria-expanded":null!==u,"aria-controls":x,onClick:()=>H(e),title:w,className:(0,I.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(eY.A,{className:`size-4 transition-transform${u?" rotate-180":""}`})}):null,(0,n.jsx)("button",{"data-testid":`workbench-picker-replace-${e.sessionId}`,type:"button",disabled:d,onClick:()=>M(e.sessionId),title:v,className:(0,I.r)({variant:"outline"}),children:l?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):b})]}),f?(0,n.jsx)("div",{className:"mb-2 ml-6 min-w-0 space-y-1.5 overflow-hidden",children:p.map(t=>{let s,r="user"===t.scope,i=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(m$,{scope:t.scope,className:"mt-0.5 size-3.5 shrink-0"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-xs leading-5",children:[(0,n.jsx)("span",{className:`shrink-0 rounded px-1.5 py-0.5 font-medium ${mz(t.scope)}`,children:mM(t.scope,t.count,z)}),null!==t.timestampMs?(0,n.jsx)("span",{className:"truncate text-muted-foreground",children:(s=t.timestampMs,P.format(s))}):null]}),(0,n.jsx)("p",{className:"mt-1 line-clamp-2 break-words text-sm leading-5 text-foreground",children:mS(t.preview,Z,mA(t.scope))})]})]}),a=`flex w-full max-w-full min-w-0 items-start gap-2 overflow-hidden rounded-md px-2.5 py-2 text-left ${mz(t.scope)}`;return r?(0,n.jsx)("button",{"data-testid":`workbench-picker-user-message-preview-${e.sessionId}`,type:"button",disabled:Y,onClick:()=>H(e),"aria-label":z("viewMatch",{label:mM(t.scope,t.count,z)}),className:`${a} outline-none transition-colors hover:brightness-95 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50`,children:i},t.scope):(0,n.jsx)("div",{className:a,children:i},t.scope)})}):null,u?(0,n.jsxs)("div",{id:x,"data-testid":x,className:"mb-2 ml-6 rounded-md border bg-background px-3 py-2.5",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[(0,n.jsxs)("p",{className:"flex min-w-0 items-center gap-1.5 text-xs font-medium",children:[(0,n.jsx)(my.A,{className:"size-3.5 shrink-0 text-primary"}),(0,n.jsx)("span",{className:"truncate",children:u.query?z("matchingUserCount",{count:u.page?.total??0}):z("userCount",{count:u.page?.total??e.userMessageCount})})]}),u.query?(0,n.jsx)("button",{type:"button",disabled:u.loading||Y,onClick:()=>void G(e.sessionId,"",1,!1),className:(0,I.r)({variant:"ghost",size:"sm"}),children:z("viewAll")}):null]}),u.error?(0,n.jsx)("p",{className:"mt-2 text-xs text-destructive",children:u.error}):null,u.loading&&0===u.messages.length?(0,n.jsx)("div",{className:"flex min-h-16 items-center justify-center text-muted-foreground",children:(0,n.jsx)(es.A,{className:"size-4 animate-spin"})}):0===u.messages.length?(0,n.jsx)("p",{className:"py-4 text-center text-xs text-muted-foreground",children:z("noUserMessages")}):(0,n.jsx)("div",{className:"mt-2 divide-y",children:u.messages.map(e=>{let t;return(0,n.jsxs)("div",{className:"py-2 first:pt-0 last:pb-0",children:[(0,n.jsx)("p",{className:"text-xs tabular-nums text-muted-foreground",children:(t=e.timestampMs,P.format(t))}),(0,n.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-sm leading-6",children:e.text?mS(e.text,u.query):z("noText")})]},e.entryId)})}),y?(0,n.jsxs)("button",{type:"button",disabled:u.loading||Y,onClick:()=>void G(e.sessionId,u.query,(u.page?.index??0)+1,!0),className:(0,I.r)({variant:"outline",className:"mt-2"}),children:[u.loading?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):null,z("loadMore")]}):null]}):null]},e.sessionId)})})]}):"browser"===s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"mb-2 flex min-h-10 items-center gap-2 rounded-md bg-muted/60 px-3 text-xs text-muted-foreground",children:[(0,n.jsx)(d6.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",title:o?.cwd??z("root"),children:o?.cwd??z("root")})]}),0===ei.length?null===Q?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:(o?.directories.length??0)===0?o?.cwd?z("browserEmpty"):z("rootsEmpty"):z("subfoldersNoMatches")}):null:(0,n.jsx)("div",{className:"divide-y",children:ei.map(e=>(0,n.jsxs)("button",{type:"button",disabled:J||Y,onClick:()=>eg(e.cwd),className:"group flex min-h-15 w-full items-center gap-3 rounded-md px-2 py-2 text-left outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55 sm:px-3",children:[(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-primary"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",title:e.name,children:e.name}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),(0,n.jsx)(e7.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-foreground"})]},e.cwd))})]}):0===er.length?null===Q?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:0===en.length?"ignored"===s?z("ignoredEmpty"):z("projectsEmpty"):z("projectNoMatches")}):null:"ignored"===s?(0,n.jsx)("div",{className:"divide-y",children:er.map(e=>{let t=mC(e.cwd),s=g===e.cwd;return(0,n.jsxs)("div",{className:"flex min-h-15 items-center gap-3 px-2 py-2 sm:px-3",children:[(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",title:t,children:t}),(0,n.jsx)("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),(0,n.jsxs)("button",{"data-testid":`workbench-picker-restore-directory-${e.cwd}`,type:"button",disabled:Y,onClick:()=>C(e.cwd,!1),"aria-label":z("restoreFolder",{name:t}),title:z("restoreTip"),className:(0,I.r)({variant:"outline"}),children:[s?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(lP.A,{className:"size-3.5"}),(0,n.jsx)("span",{children:z("restore")})]})]},e.cwd)})}):(0,n.jsx)("div",{className:"divide-y",children:er.map(e=>{let s,r=mC(e.cwd),i=z("directorySessions",{count:e.sessionCount,time:(s=e.updatedAt,P.format(s))}),a=p===e.cwd,l=g===e.cwd;return(0,n.jsxs)("div",{className:"flex items-center gap-1",children:[(0,n.jsxs)("button",{"data-testid":`workbench-picker-directory-${e.cwd}`,type:"button",disabled:Y,onClick:()=>E(e.cwd),className:"group flex min-h-15 min-w-0 flex-1 items-center gap-3 rounded-md px-2 py-2 text-left outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55 sm:px-3",children:[(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-primary"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",title:r,children:r}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),a?(0,n.jsxs)("span",{className:"flex min-h-10 shrink-0 items-center gap-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}),z("creating")]}):(0,n.jsxs)("span",{className:"flex shrink-0 items-center gap-1 text-xs text-muted-foreground",title:i,children:[(0,n.jsx)("span",{children:z("directoryCount",{count:e.sessionCount})}),(0,n.jsx)(e7.A,{className:"size-4 group-hover:text-foreground"})]})]}),"create"===t?(0,n.jsx)("button",{"data-testid":`workbench-picker-ignore-directory-${e.cwd}`,type:"button",disabled:Y,onClick:()=>C(e.cwd,!0),"aria-label":z("ignoreFolder",{name:r}),title:z("ignoreTip"),className:(0,I.r)({variant:"ghost",size:"icon"}),children:l?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(an.A,{className:"size-4"})}):null]},e.cwd)})})]})}),(0,n.jsxs)(eN.vu,{className:"flex-row flex-wrap items-center justify-between gap-2 px-3 py-2.5 sm:px-4",children:[(0,n.jsx)("p",{className:"min-w-24 flex-1 truncate text-xs text-muted-foreground",title:eu,children:eu}),(0,n.jsxs)("div",{className:"ml-auto flex items-center gap-2",children:["create"===t&&"directories"===s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",disabled:J||Y,onClick:k,className:(0,I.r)({variant:"outline"}),children:z("ignoredFolders")}),(0,n.jsx)("button",{type:"button",disabled:J||Y,onClick:j,className:(0,I.r)({variant:"outline"}),children:z("chooseOther")})]}):null,"browser"===s&&o?.cwd?(0,n.jsx)("button",{"data-testid":"workbench-picker-select-browser-directory",type:"button",disabled:J||Y,onClick:()=>S(o.cwd),className:(0,I.r)(),children:z("selectCurrent")}):null,"browser"===s&&o?.parentCwd?(0,n.jsx)("button",{type:"button",disabled:J||Y,onClick:()=>eg(o.parentCwd),"aria-label":z("parentDirectory"),title:z("parentDirectory"),className:(0,I.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(A.A,{className:"size-4"})}):null,"browser"===s&&o?.cwd?(0,n.jsx)("button",{type:"button",disabled:J||Y,onClick:()=>eg(null),"aria-label":z("backRoots"),title:z("backRoots"),className:(0,I.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(d6.A,{className:"size-4"})}):null,(0,n.jsx)("button",{"data-testid":"workbench-picker-refresh",type:"button",disabled:J||Y,onClick:"history"===s?V.refresh:y,"aria-label":z("refreshList"),title:z("refreshList"),className:(0,I.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(es.A,{className:`size-4${J?" animate-spin":""}`})})]})]})]})})}let mP="pi-super:workbench-layout";function mD(e,t,s=[]){let n=new Set(t.map(e=>e.workId)),r=new Set(s),i=e.primaryWorkId&&n.has(e.primaryWorkId)&&!r.has(e.primaryWorkId)?e.primaryWorkId:null;return e.primaryWorkId===i?e:{primaryWorkId:i}}function mT({variant:e,className:t,children:s}){let{t:r}=(0,b.Bd)("workbench");return(0,n.jsx)("div",{className:(0,C.cn)("@container/empty-state flex size-full min-h-0 flex-1 items-center justify-center overflow-hidden px-6 py-8 text-center",t),children:"select-session"===e?(0,n.jsxs)("div",{className:"relative",children:[s,(0,n.jsx)("h1",{className:"text-base font-medium text-muted-foreground",children:r("emptySelectSession")})]}):(0,n.jsxs)("div",{role:"status","aria-live":"polite",className:"flex flex-col items-center gap-3 animate-in fade-in-0 fill-mode-both delay-150 duration-150 motion-reduce:animate-none",children:[(0,n.jsx)(v.A,{className:"size-5 animate-spin text-muted-foreground motion-reduce:animate-none"}),(0,n.jsx)("p",{className:"text-sm font-medium text-muted-foreground",children:r("emptyLoading")})]})})}var mO=s(39569),mL=s(31175),mF=s(74873),mB=s(77065),mq=s(36919);let m_=new Set(["custom","model_change","thinking_level_change","session_info","label"]),mW="pi-desk:workbench-branch-filter",mY=[{value:"default",label:"filterDefault"},{value:"no-tools",label:"filterNoTools"},{value:"user-only",label:"filterUserOnly"},{value:"labeled-only",label:"filterLabeled"},{value:"all",label:"filterAll"}];function mV(){try{let e=window.localStorage.getItem(mW);return mY.find(t=>t.value===e)?.value??"default"}catch{return"default"}}let mU=[],mK={user:{label:"kindUser",labelClassName:"font-semibold text-primary",contentClassName:"font-medium text-foreground",rowClassName:""},assistant:{label:"AI",labelClassName:"font-medium text-muted-foreground",contentClassName:"text-foreground",rowClassName:""},tool:{label:"kindTool",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:"text-muted-foreground"},bash:{label:"Bash",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:"text-muted-foreground"},custom_message:{label:"kindMessage",labelClassName:"text-muted-foreground",contentClassName:"text-foreground",rowClassName:""},compaction:{label:"kindCompaction",labelClassName:"font-medium text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:"bg-primary/[0.025]"},branch_summary:{label:"kindBranchSummary",labelClassName:"font-medium text-foreground",contentClassName:"text-muted-foreground",rowClassName:"bg-amber-500/[0.025]"},custom:{label:"kindCustom",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:""},model_change:{label:"kindModel",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:""},thinking_level_change:{label:"kindThinking",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:""},session_info:{label:"kindSession",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:""},label:{label:"kindLabel",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:""}};function mH(e){switch(e.action){case"tree":return"treeIntent";case"resend":return"resendIntent";case"fork":return"forkIntent";case"clone":return"cloneIntent"}}function mG(e){e.preventDefault()}function mJ({confirmation:e,disabled:t,onConfirm:s,onBack:i}){let{t:a}=(0,b.Bd)("workbenchPicker"),[l,o]=(0,r.useState)(0),c=(0,r.useRef)(new Map);(0,r.useEffect)(()=>{c.current.get(0)?.focus()},[]);let d=n=>{e.waiting||t&&0===n||(0===n?s():i())};return(0,n.jsxs)("div",{className:"p-3 sm:p-4",onKeyDown:e=>{if(e.stopPropagation(),"Escape"===e.key){e.preventDefault(),i();return}if("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key){e.preventDefault();let t=+(0===l);o(t),queueMicrotask(()=>c.current.get(t)?.focus());return}"Enter"===e.key&&(e.preventDefault(),d(l))},children:[(0,n.jsxs)("div",{className:"rounded-lg border bg-muted/25 px-3 py-2.5",children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:a("runningTitle")}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:"main"===e.reason?a("runningStop",{action:a(mH(e.intent))}):a("runningWait",{action:a(mH(e.intent))})})]}),(0,n.jsx)("div",{className:"mt-3 grid grid-cols-2 gap-2",children:[{label:a(e.waiting?"confirming":"confirmContinue"),confirm:!0},{label:a("back"),confirm:!1}].map((s,r)=>(0,n.jsxs)("button",{ref:e=>{e?c.current.set(r,e):c.current.delete(r)},type:"button",disabled:e.waiting||t&&s.confirm,tabIndex:l===r?0:-1,className:(0,C.cn)("flex min-h-11 items-center justify-center gap-2 rounded-lg border px-3 text-sm font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-60",l===r?"border-primary/40 bg-primary/10 text-foreground":"border-border bg-background hover:bg-muted/60"),onFocus:()=>o(r),onClick:()=>d(r),children:[e.waiting&&s.confirm?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):null,s.label]},s.label))}),(0,n.jsx)("p",{className:"mt-2 text-center text-xs text-muted-foreground",children:a("confirmHint")})]})}function mQ({model:e,projectName:t,sessionTitle:s,mobile:i,onClose:a,onRetry:l,onSelectEntry:o,onAction:c,onConfirmRunning:d,onCancelRunning:u}){let{t:m}=(0,b.Bd)("workbenchPicker"),p=(0,mB.tF)(),h=(0,mq.I)(),{locale:g,timeZone:f}=(0,eQ.i)(),x=(0,r.useMemo)(()=>new Intl.DateTimeFormat("en"===g?"en-US":"zh-CN",{timeZone:f,timeZoneName:"shortOffset",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}),[g,f]),[w,y]=(0,r.useState)(""),[k,j]=(0,r.useState)(mV),[N,S]=(0,r.useState)(()=>new Set),[E,M]=(0,r.useState)(null),[z,A]=(0,r.useState)(0),[$,R]=(0,r.useState)(480),P=(0,r.useRef)(null),D=(0,r.useRef)(null),T=(0,r.useRef)(null),O=(0,r.useRef)(null),L=(0,r.useRef)(!1),F=e.tree?.nodes??mU,B=(0,r.useMemo)(()=>(function(e){let t=new Map;e.nodes.forEach((e,s)=>t.set(e.entryId,{node:e,index:s}));let s=function(e,t){let s=new Set,n=t;for(;n&&!s.has(n);){let t=e.get(n);if(!t)break;s.add(n),n=t.node.parentEntryId}return s}(t,e.leafEntryId),n=new Set(e.nodes.filter(t=>(function(e,t,s){if("assistant"===e.kind&&!e.preview&&e.entryId!==s)return!1;switch(t){case"default":return!m_.has(e.kind);case"no-tools":return!m_.has(e.kind)&&"tool"!==e.kind;case"user-only":return"user"===e.kind;case"labeled-only":return null!==e.label;case"all":return!0}})(t,e.filter,e.leafEntryId)&&function(e,t){let s=t.toLocaleLowerCase().split(/\s+/).filter(Boolean);if(0===s.length)return!0;let n=[e.kind,e.preview,e.label??""].join(" ").toLocaleLowerCase();return s.every(e=>n.includes(e))}(t,e.query)).map(e=>e.entryId)),r=new Map,i=new Map;for(let e of t.values()){if(!n.has(e.node.entryId))continue;let s=e.node.parentEntryId,a=new Set;for(;s&&!n.has(s);){if(a.has(s)){s=null;break}a.add(s),s=t.get(s)?.node.parentEntryId??null}s===e.node.entryId&&(s=null),i.set(e.node.entryId,s);let l=r.get(s)??[];l.push(e),r.set(s,l)}for(let e of r.values())e.sort((e,t)=>(function(e,t,s){let n=Number(!s.has(e.node.entryId))-Number(!s.has(t.node.entryId));if(0!==n)return n;let r=e.node.timestampMs-t.node.timestampMs;return 0!==r?r:e.index-t.index})(e,t,s));let a=[],l=new Set;return(t=>{let n=[...t].reverse().map(e=>({indexed:e,depth:0,connector:!1,lastSibling:!0}));for(;n.length>0;){let t=n.pop(),o=t.indexed.node.entryId;if(l.has(o))continue;l.add(o);let c=r.get(o)??[],d=i.get(o)??null,u=null===d?[]:r.get(d)??[],m=c.length>0&&(null===d||u.length>1),p=!m||!e.foldedEntryIds.has(o);if(a.push({node:t.indexed.node,depth:t.depth,active:s.has(o),current:o===e.leafEntryId,hasChildren:c.length>0,foldable:m,expanded:p,connector:t.connector,lastSibling:t.lastSibling,visibleParentEntryId:i.get(o)??null}),!p)continue;let h=c.length>1;for(let[e,s]of[...c].reverse().entries()){let r=c.length-e-1;n.push({indexed:s,depth:t.depth+ +!!h,connector:h,lastSibling:r===c.length-1})}}})(r.get(null)??[]),a})({nodes:F,leafEntryId:e.tree?.leafEntryId??null,filter:k,query:w,foldedEntryIds:N}),[k,N,e.tree?.leafEntryId,F,w]),q=function(e,t,s){if(0===t.length)return null;let n=new Set(t.map(e=>e.node.entryId)),r=new Map(e.map(e=>[e.entryId,e])),i=s,a=new Set;for(;i&&!a.has(i);){if(n.has(i))return i;a.add(i),i=r.get(i)?.parentEntryId??null}return t.at(-1)?.node.entryId??null}(F,B,E??e.tree?.leafEntryId??null),_=B.findIndex(e=>e.node.entryId===q),W=_>=0?B[_]:null,Y=Math.max(0,Math.floor(z/36)-8),U=Math.min(B.length,Math.ceil((z+$)/36)+8),K=Math.min(B.length,Math.max(U,Y+8)),H=B.slice(Y,K),G=e.detail?.entryId===q?e.detail:null,J=e.runningConfirmation,Q=`work-session-branch-tree-${e.workId}`,X=q?`${Q}-entry-${q}`:void 0,Z=(0,r.useCallback)(()=>{i?D.current?.focus({preventScroll:!0}):P.current?.focus({preventScroll:!0})},[i]),ee=(0,r.useCallback)(t=>{e.pending||(L.current=t,a())},[e.pending,a]);(0,r.useEffect)(()=>{if(p)return O.current=document.activeElement instanceof HTMLElement?document.activeElement:null,L.current=!1,queueMicrotask(Z),()=>{L.current&&O.current?.focus({preventScroll:!0})}},[Z,p]),(0,r.useEffect)(()=>{p&&!J&&queueMicrotask(Z)},[J,Z,p]),(0,r.useEffect)(()=>{if(!p)return;let t=t=>{if(e.pending)return;let s=t.target;s instanceof Node&&(D.current?.contains(s)||ee(!1))};return document.addEventListener("pointerdown",t,!0),()=>document.removeEventListener("pointerdown",t,!0)},[e.pending,p,ee]),(0,r.useEffect)(()=>{let e=T.current;if(!e)return;let t=new ResizeObserver(([e])=>{R(e?.contentRect.height??0)});return t.observe(e),()=>t.disconnect()},[J]),(0,r.useEffect)(()=>{if(!p||!q||J)return;o(q);let e=T.current;if(!e||_<0)return;let t=36*_,s=t+36,n=e.scrollTop;t<e.scrollTop?n=t:s>e.scrollTop+e.clientHeight&&(n=s-e.clientHeight),n!==e.scrollTop&&(e.scrollTop=n),queueMicrotask(()=>A(n))},[J,q,o,p,36,_]);let et=(0,r.useCallback)(e=>{T.current&&(T.current.scrollTop=e),A(e)},[]),es=(0,r.useCallback)(e=>{if(0===B.length)return;let t=Math.max(0,Math.min(B.length-1,e));M(B[t].node.entryId);let s=T.current;if(!s)return;let n=36*t,r=n+36,i=s.scrollTop;n<s.scrollTop?i=n:r>s.scrollTop+s.clientHeight&&(i=r-s.clientHeight),et(i)},[36,B,et]),en=(0,r.useCallback)((e,t)=>{S(s=>{let n=new Set(s);return t??!n.has(e)?n.add(e):n.delete(e),n})},[]),er=(0,r.useCallback)(e=>{j(e);try{window.localStorage.setItem(mW,e)}catch(e){console.warn("[Pi Desk][Workbench] 保存分支筛选失败,仅当前选择器生效",e)}S(new Set),et(0),queueMicrotask(Z)},[Z,et]),ei=(0,r.useCallback)(e=>{let t=(mY.findIndex(e=>e.value===k)+e+mY.length)%mY.length;er(mY[t].value)},[er,k]),ea=(0,r.useCallback)((t,s)=>{e.actionsDisabled||(L.current=!1,c(t,s))},[e.actionsDisabled,c]),el=(0,r.useCallback)(()=>{!W||W.current||e.pending||ea(W.node.entryId,"tree")},[e.pending,ea,W]),eo=(0,r.useCallback)(()=>{if(!W?.visibleParentEntryId)return;let e=B.findIndex(e=>e.node.entryId===W.visibleParentEntryId);e>=0&&es(e)},[B,es,W]),ec=(0,r.useCallback)(()=>{if(!W)return;let e=B.findIndex(e=>e.visibleParentEntryId===W.node.entryId);e>=0&&es(e)},[B,es,W]),ed=(0,r.useCallback)(()=>{J?u():w?(y(""),S(new Set),et(0)):ee(!0)},[J,u,w,ee,et]);(0,r.useEffect)(()=>{if(!i||!p)return;let e=e=>{"Escape"!==e.key||e.defaultPrevented||e.isComposing||e.repeat||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||D.current?.closest("[inert]")||(e.preventDefault(),e.stopImmediatePropagation(),ed())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ed,i,p]);let eu=W?.node??null,eg=eu?mK[eu.kind]:null,ef=J?i?"inset-x-0 bottom-0 rounded-t-2xl border-x-0 border-b-0":"inset-x-2 bottom-2 h-auto max-h-[calc(100%-4rem)] rounded-xl":i?"inset-x-0 bottom-0 top-14 rounded-t-2xl border-x-0 border-b-0":"inset-x-2 bottom-2 h-[min(82%,48rem)] rounded-xl";return(0,n.jsxs)(oU.PY1.div,{className:"pointer-events-none absolute inset-0 z-30","aria-hidden":!p||void 0,inert:!p||void 0,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15*!h,ease:"easeOut"},children:[(0,n.jsx)("div",{"aria-hidden":"true","data-carousel-swipe-lock":!0,className:(0,C.cn)("absolute inset-x-0 bottom-0 top-14 z-30 bg-background/65",p?"pointer-events-auto":"pointer-events-none")}),(0,n.jsxs)(oU.PY1.section,{ref:D,initial:{y:12*!h},animate:{y:0},exit:{y:8*!h},transition:{duration:.2*!h,ease:"easeOut"},tabIndex:-1,"data-carousel-swipe-lock":!0,role:"region","aria-label":m("branchPicker"),"aria-busy":e.pending||e.loading,className:(0,C.cn)("absolute z-40 flex min-h-0 flex-col overflow-hidden border bg-popover text-popover-foreground shadow-lg outline-none",p?"pointer-events-auto":"pointer-events-none",ef),children:[(0,n.jsxs)("header",{className:"shrink-0 border-b bg-muted/10",children:[(0,n.jsxs)("div",{className:"flex min-h-10 items-center gap-2 px-2.5",children:[(0,n.jsx)("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold",title:`${t} \xb7 ${s??m("newSession")}`,children:m("branchTitle")}),J?null:(0,n.jsxs)("span",{className:"shrink-0 text-xs text-muted-foreground",children:[_>=0?_+1:0," / ",B.length]}),(0,n.jsx)("button",{type:"button",disabled:e.pending,"aria-label":m("closeBranchPicker"),className:(0,I.r)({variant:"ghost",size:"icon"}),onClick:()=>ee(!0),children:(0,n.jsx)(V.A,{className:"size-4"})})]}),J?null:(0,n.jsx)("div",{className:"flex items-center gap-1.5 border-t border-border/60 px-2 py-1.5",children:(0,n.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,n.jsx)(eh.A,{className:"pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{ref:P,role:"combobox",value:w,"aria-label":m("branchSearch"),"aria-controls":Q,"aria-expanded":"true","aria-activedescendant":X,placeholder:m("branchSearchPlaceholder"),className:"pl-7",onChange:e=>{y(e.currentTarget.value),S(new Set),et(0)},onKeyDown:e=>{if(!e.nativeEvent.isComposing)switch(e.stopPropagation(),e.key){case"Tab":e.preventDefault(),ei(e.shiftKey?-1:1);return;case"ArrowUp":e.preventDefault(),es(_-1);return;case"ArrowDown":e.preventDefault(),es(_+1);return;case"PageUp":e.preventDefault(),es(_-Math.max(1,Math.floor($/36)));return;case"PageDown":e.preventDefault(),es(_+Math.max(1,Math.floor($/36)));return;case"ArrowLeft":if(w||!W)return;e.preventDefault(),W.foldable&&W.expanded?en(W.node.entryId,!0):eo();return;case"ArrowRight":if(w||!W)return;e.preventDefault(),W.foldable&&!W.expanded?en(W.node.entryId,!1):ec();return;case"Enter":e.preventDefault(),el();return;case"Escape":e.preventDefault(),ed();return}}})]})})]}),e.error?(0,n.jsx)("div",{role:"alert",className:"shrink-0 border-b bg-muted px-3 py-2 text-sm text-destructive",children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:e.error}),e.pending||e.tree?null:(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",disabled:e.actionsDisabled,onClick:l,children:m("retry")})]})}):null,J?(0,n.jsx)(mJ,{confirmation:J,disabled:e.actionsDisabled,onConfirm:d,onBack:()=>{L.current=!0,u()}},`${J.intent.action}:${"entryId"in J.intent?J.intent.entryId:""}`):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar h-36 shrink-0 overflow-y-auto border-b bg-muted px-3 py-3",children:eu&&eg?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)("span",{className:eg.labelClassName,children:m(eg.label)}),eu.label?(0,n.jsx)("span",{className:"min-w-0 truncate rounded-sm bg-amber-500/10 px-1 text-amber-700 dark:text-amber-300",children:eu.label}):null,(0,n.jsx)("time",{className:"ml-auto shrink-0",children:x.format(eu.timestampMs)})]}),(0,n.jsx)("div",{className:"mt-2 whitespace-pre-wrap break-words text-sm leading-6",children:e.detailLoading||!G?e.detailError?(0,n.jsx)("span",{className:"text-destructive",children:e.detailError}):(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}),m("loadingEntry")]}):(0,n.jsxs)(n.Fragment,{children:[G.content||m("entryEmpty"),G.truncated?(0,n.jsx)("span",{className:"mt-1 block text-muted-foreground",children:m("entryTruncated")}):null]})})]}):(0,n.jsx)("div",{className:"grid min-h-12 place-items-center text-xs text-muted-foreground",children:m("selectEntry")})}),(0,n.jsxs)("div",{role:"group","aria-label":m("branchFilters"),className:"flex shrink-0 flex-wrap items-center gap-1 border-b bg-muted/25 px-2 py-2",children:[(0,n.jsx)("span",{className:"px-1 text-sm font-medium text-muted-foreground",children:m("branchFilters")}),mY.map(e=>(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"ghost","aria-pressed":k===e.value,className:"aria-pressed:bg-primary aria-pressed:text-primary-foreground aria-pressed:hover:bg-[color-mix(in_oklab,var(--primary),var(--primary-foreground)_8%)]",onClick:()=>er(e.value),children:[k===e.value?(0,n.jsx)(ep.A,{className:"size-3.5"}):null,m(e.label)]},e.value))]}),e.pending&&!e.runningConfirmation?(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b bg-primary/8 px-2.5 py-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-3.5 animate-spin text-primary"}),m("branchWorking")]}):null,e.loading&&!e.tree?(0,n.jsx)("div",{className:"grid min-h-0 flex-1 place-items-center text-sm text-muted-foreground",children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),m("branchLoading")]})}):0===B.length?(0,n.jsx)("div",{className:"grid min-h-0 flex-1 place-items-center px-4 text-center text-sm text-muted-foreground",children:0===F.length?m("branchEmpty"):m("branchNoMatches")}):(0,n.jsxs)("div",{ref:T,id:Q,role:"tree","aria-label":m("branchTree"),className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto px-1 py-1",onScroll:e=>A(e.currentTarget.scrollTop),children:[(0,n.jsx)("div",{style:{height:`${36*Y}px`},"aria-hidden":"true"}),H.map(t=>{let s=t.node.entryId===q,r=Math.min(t.depth,10),a=mK[t.node.kind];return(0,n.jsxs)("div",{id:`${Q}-entry-${t.node.entryId}`,role:"treeitem","aria-level":t.depth+1,"aria-selected":s,"aria-expanded":t.foldable?t.expanded:void 0,className:(0,C.cn)("group relative flex min-w-0 items-center rounded-md outline-none transition-colors",a.rowClassName,s?"bg-accent text-accent-foreground":t.current?"bg-primary/[0.055] hover:bg-primary/[0.08]":"hover:bg-muted/50"),style:{height:"36px",paddingLeft:`${10*r}px`},children:[r>0?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("pointer-events-none absolute bottom-0 top-0 w-px",t.active?"bg-primary/25":"bg-border/60"),style:{left:`${10*r-5}px`}}):null,t.connector?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("pointer-events-none absolute h-px w-2",t.active?"bg-primary/25":"bg-border/60"),style:{left:`${10*r-5}px`}}):null,(0,n.jsx)("div",{className:"flex w-6 shrink-0 items-center justify-center",children:t.foldable?(0,n.jsx)("button",{type:"button","aria-label":m(t.expanded?"collapseBranch":"expandBranch"),className:"flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-foreground/8 hover:text-foreground",onMouseDown:mG,onClick:()=>{en(t.node.entryId),queueMicrotask(Z)},children:(0,n.jsx)(e7.A,{className:(0,C.cn)("size-3 transition-transform",t.expanded&&"rotate-90")})}):null}),(0,n.jsxs)("button",{type:"button",tabIndex:-1,className:"flex h-full min-w-0 flex-1 items-center gap-1.5 overflow-hidden text-left outline-none",onMouseDown:mG,onClick:()=>{M(t.node.entryId),queueMicrotask(Z)},onDoubleClick:()=>{i||t.current||ea(t.node.entryId,"tree")},children:[(0,n.jsx)("span",{className:(0,C.cn)("w-9 shrink-0 text-xs",a.labelClassName),children:m(a.label)}),t.node.label?(0,n.jsx)("span",{className:"max-w-24 shrink-0 truncate rounded-md bg-muted px-1 text-xs text-foreground",children:t.node.label}):null,(0,n.jsx)("span",{className:(0,C.cn)("min-w-0 flex-1 truncate text-sm",a.contentClassName,s&&"font-semibold text-accent-foreground"),children:t.node.preview||m("noPreview")})]}),i?(0,n.jsxs)("div",{className:"ml-2 flex shrink-0 items-center gap-1 border-l border-border/55 py-0.5 pl-1.5 pr-1",children:[(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||t.current||e.pending,"aria-label":m("switchToMessage",{kind:m(a.label)}),className:(0,I.r)({variant:"secondary",size:"sm"}),onClick:()=>ea(t.node.entryId,"tree"),children:m("switch")}),"user"===t.node.kind?(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||e.pending,"aria-label":m("forkFromUser"),className:(0,I.r)({variant:"outline",size:"sm"}),onClick:()=>ea(t.node.entryId,"fork"),children:"Fork"}):null]}):"user"===t.node.kind?(0,n.jsx)("div",{className:"ml-2 flex shrink-0 items-center border-l border-border/50 pl-2 pr-1",children:(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||e.pending,"aria-label":m("forkFromUser"),className:(0,I.r)({variant:"ghost",size:"sm"}),onMouseDown:mG,onClick:()=>ea(t.node.entryId,"fork"),children:"Fork"})}):null]},t.node.entryId)}),(0,n.jsx)("div",{style:{height:`${36*Math.max(0,B.length-K)}px`},"aria-hidden":"true"})]}),(0,n.jsxs)("footer",{className:"flex min-h-9 shrink-0 items-center gap-2 border-t bg-muted/10 px-2",children:[(0,n.jsxs)("span",{className:"min-w-0 flex-1 truncate text-xs text-muted-foreground",children:[_>=0?_+1:0," / ",B.length,i?"":` \xb7 ${m("branchShortcuts")}`]}),i?null:(0,n.jsx)(I.$,{type:"button",size:"sm",disabled:e.actionsDisabled||!W||W.current||e.loading||e.pending,onMouseDown:mG,onClick:el,children:m("switch")})]})]})]})]})}var mX=s(15450),mZ=s(31210),m0=s(66722),m1=s(40942),m2=s(61989),m5=s(63434),m3=s(26690),m4=s(2870),m6=s.n(m4);function m8({workSession:e,runtime:t,active:s,chatReady:i,onOpen:a}){let{t:l}=(0,b.Bd)("workbench"),{locale:o}=(0,eQ.i)();(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let c=t.getWorkspace(e.cwd)?.heads;(0,r.useEffect)(()=>{let n;if(!s||!i)return;let r=()=>{window.clearTimeout(n),n=void 0},a=()=>{r(),"visible"===document.visibilityState&&document.hasFocus()&&(n=window.setTimeout(()=>{n=void 0,"visible"===document.visibilityState&&document.hasFocus()&&t.refreshHeads(e.cwd)},1e3))},l=()=>{"visible"!==document.visibilityState&&r()};return a(),window.addEventListener("focus",a),window.addEventListener("blur",r),document.addEventListener("visibilitychange",l),()=>{r(),window.removeEventListener("focus",a),window.removeEventListener("blur",r),document.removeEventListener("visibilitychange",l)}},[s,i,t,e.cwd]);let d=c?.repositories??[],u=(0,d8.A_)(e.projectName,d,o);if(c?.status==="ready"&&!u)return null;let m=c?.status==="loading"&&!u,p=c?.status==="error"&&!u,h=m?null:u;return(0,n.jsxs)(lG,{"data-testid":"composer-git-branch",tooltip:p?c.error??l("gitStatusReadFailed"):h?.title??l("gitBranches"),"aria-label":l("gitBranches"),className:m6().branchTrigger,disabled:m,onClick:()=>a({workId:e.workId,cwd:e.cwd,projectName:e.projectName,repositoryRoot:null}),children:[m?(0,n.jsx)(v.A,{className:"size-4 shrink-0 animate-spin"}):(0,n.jsx)(d4.A,{className:"size-4 shrink-0 text-emerald-600 dark:text-emerald-400"}),p?(0,n.jsx)("span",{className:(0,C.cn)(m6().branchFallback,"text-amber-600 dark:text-amber-400"),children:"Git !"}):h?(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("span",{"data-git-branch-full":!0,className:(0,C.cn)(m6().branchFull,h.diverged&&"text-amber-600 dark:text-amber-400"),children:h.full})}):null]})}let m7="l2-workbench-slash-command-menu",m9={key:"builtin:reload",name:"reload",description:"重新读取 Pi 最新配置与扩展资源",source:"builtin"},pe=[{source:"builtin",label:"Pi 内置命令"},{source:"skill",label:"Skills"},{source:"prompt",label:"提示模板"},{source:"extension",label:"扩展命令"}];function pt(e){return`${m7}-option-${e}`}function ps(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function pn(e){return[...e.children].filter(e=>e instanceof HTMLElement)}function pr(e,t,s){return e.reduce((e,t)=>e+(s.get(t)??0),0)+Math.max(0,e.length-1)*t}var pi=s(64696);let pa=2*Math.PI*7;function pl(e){if(null===e)return"--";let t=Math.round(e);return t<1e3?String(t):`${Math.round(t/100)/10}K`}function po(e){return Math.min(100,Math.max(0,e))}function pc(e){return pa-e/100*pa}function pd({sessionId:e,cwd:t,tokens:s,contextWindow:i,contextIgnorePlugin:a,ignoreDisabled:l,ignorePending:o,compactDisabled:c,compactPending:d,onIgnoreContext:u,onCompactContext:m}){let p,h,g,f,x,{t:w}=(0,b.Bd)("workbench"),y=(0,r.useId)(),k=(0,r.useRef)(!1),[j,N]=(0,r.useState)(!1),[S,E]=(0,r.useState)(!1),[M,z]=(0,r.useState)(!1),A=(0,X.G)(),$=(p=!a||"object"!=typeof a||Array.isArray(a)||"number"!=typeof a.ignoredTokens||!Number.isFinite(a.ignoredTokens)||a.ignoredTokens<0||"number"!=typeof a.potentialTokens||!Number.isFinite(a.potentialTokens)||a.potentialTokens<0||void 0!==a.effectiveTokens&&null!==a.effectiveTokens&&("number"!=typeof a.effectiveTokens||!Number.isFinite(a.effectiveTokens)||a.effectiveTokens<0)?null:{ignoredTokens:a.ignoredTokens,potentialTokens:a.potentialTokens,...void 0!==a.effectiveTokens?{effectiveTokens:a.effectiveTokens}:{}},g=null===(h=p?.effectiveTokens===void 0?s:p.effectiveTokens)?0:po(h/i*100),x=null===(f=null===h||null===p?null:Math.max(0,h-p.potentialTokens))?null:po(f/i*100),{contextIgnore:p,currentTokens:h,usedPercent:g,projectedTokens:f,projectedPercent:x,potentialSegmentPercent:null===x?0:Math.max(0,g-x)}),R=Math.round($.usedPercent),P=null===$.projectedPercent?null:Math.round($.projectedPercent),D=R>=90?"text-destructive":R>=80?"text-status-warning":"text-muted-foreground",T=R>=90?"bg-destructive":R>=80?"bg-status-warning":"bg-primary",O=$.contextIgnore?w("contextUsageWithIgnore",{percent:R,projected:P??0,ignored:pl($.contextIgnore.ignoredTokens),potential:pl($.contextIgnore.potentialTokens)}):w("contextUsageSimple",{percent:R,limit:pl(i)});return(0,n.jsxs)(lY,{open:j,triggerId:y,onOpenChange:(e,t)=>{k.current&&"trigger-focus"===t.reason||(e||(E(!1),z(!1)),N(e))},children:[(0,n.jsx)(lV,{id:y,delay:100,closeDelay:100,render:(0,n.jsx)("button",{type:"button","aria-label":O,"aria-expanded":j,className:"inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full bg-transparent transition-colors outline-none hover:bg-accent focus-visible:ring-1 focus-visible:ring-ring/50 data-open:bg-accent",onPointerDown:e=>{k.current="mouse"!==e.pointerType},onPointerCancel:()=>{k.current=!1},onClick:e=>{k.current&&(e.preventDefault(),N(e=>!e),queueMicrotask(()=>{k.current=!1}))},children:(0,n.jsxs)("svg",{className:"pointer-events-none block size-5 -rotate-90",viewBox:"0 0 20 20","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-muted-foreground opacity-20"}),$.contextIgnore?(0,n.jsxs)(n.Fragment,{children:[$.usedPercent>0?(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2",strokeDasharray:pa,strokeDashoffset:pc($.usedPercent),className:"text-muted-foreground"}):null,null!==$.projectedPercent&&$.projectedPercent>0?(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2",strokeDasharray:pa,strokeDashoffset:pc($.projectedPercent),className:"text-foreground"}):null]}):$.usedPercent>0?(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2",strokeDasharray:pa,strokeDashoffset:pc($.usedPercent),className:D}):null]})})}),(0,n.jsx)(lU,{side:"top",align:"center",sideOffset:6,"aria-label":w("contextDetails"),className:"w-80 max-w-[calc(100vw-2rem)] p-4 text-sm",children:(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 text-sm",children:[(0,n.jsx)("span",{className:"whitespace-nowrap text-muted-foreground",children:w("contextMetrics")}),(0,n.jsxs)("span",{className:"whitespace-nowrap font-medium tabular-nums text-foreground",children:[pl($.currentTokens)," / ",pl(i)," / ",R,"%"]})]}),(0,n.jsx)("div",{className:"flex h-1.5 overflow-hidden rounded-full bg-muted",children:$.contextIgnore&&null!==$.projectedPercent?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"h-full bg-foreground",style:{width:`${$.projectedPercent}%`}}),(0,n.jsx)("div",{className:"h-full bg-muted-foreground",style:{width:`${$.potentialSegmentPercent}%`}})]}):(0,n.jsx)("div",{className:(0,C.cn)("h-full rounded-full",T),style:{width:`${$.usedPercent}%`}})})]}),$.contextIgnore&&null!==$.projectedTokens?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-2 rounded-full bg-foreground"}),w("afterIgnore")]}),(0,n.jsxs)("span",{className:"font-medium tabular-nums text-foreground",children:[pl($.projectedTokens)," \xb7 ",P,"%"]})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-2 rounded-full bg-muted-foreground"}),w("potentialIgnore")]}),(0,n.jsx)("span",{className:"font-medium tabular-nums text-foreground",children:pl($.contextIgnore.potentialTokens)})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,n.jsx)("span",{className:"text-muted-foreground",children:w("alreadyIgnored")}),(0,n.jsx)("span",{className:"font-medium tabular-nums text-foreground",children:pl($.contextIgnore.ignoredTokens)})]})]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:[(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",disabled:l||o||!$.contextIgnore||$.contextIgnore.potentialTokens<=0,"aria-label":$.contextIgnore&&$.contextIgnore.potentialTokens>0?w("ignoreNow",{amount:pl($.contextIgnore.potentialTokens)}):w("nothingToIgnore"),"aria-busy":o,onClick:()=>void u(),children:[o?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(pi.A,{}),o?w("ignoring"):w("ignore")]}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",disabled:c||d,"aria-busy":d,onClick:()=>void m(),children:[d?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(o_.A,{}),d?w("compacting"):w("compact")]})]}),R>=80?(0,n.jsx)("p",{className:(0,C.cn)("pt-1 text-sm",R>=90?"text-destructive":"text-status-warning"),children:R>=90?w("contextCritical"):w("contextWarning")}):null,(0,n.jsx)("div",{className:"border-t border-border"}),(0,n.jsxs)("button",{type:"button","aria-label":w("copySessionId",{id:e}),className:"w-full cursor-pointer rounded-md px-1 py-1 text-left transition-colors outline-none hover:bg-muted focus-visible:ring-1 focus-visible:ring-ring/50",onClick:()=>{(0,e9.x)(e).then(e=>{e?E(!0):A.error(w("copySessionFailed"))})},children:[(0,n.jsxs)("span",{className:"flex items-center justify-between gap-3 text-muted-foreground",children:[(0,n.jsx)("span",{children:w("currentSessionId")}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-1",children:[S?w("copied"):w("clickToCopy"),S?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})]})]}),(0,n.jsx)("span",{className:"mt-1 block break-all font-mono text-xs leading-5 text-foreground",children:e})]}),(0,n.jsxs)("button",{type:"button","aria-label":w("copyCurrentPath",{path:t}),className:"w-full cursor-pointer rounded-md px-1 py-1 text-left transition-colors outline-none hover:bg-muted focus-visible:ring-1 focus-visible:ring-ring/50",onClick:()=>{(0,e9.x)(t).then(e=>{e?z(!0):A.error(w("copyPathFailed"))})},children:[(0,n.jsxs)("span",{className:"flex items-center justify-between gap-3 text-muted-foreground",children:[(0,n.jsx)("span",{children:w("currentPath")}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-1",children:[M?w("copied"):w("clickToCopy"),M?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})]})]}),(0,n.jsx)("span",{className:"mt-1 block min-w-0 break-words font-mono text-xs leading-5 text-foreground",title:t,children:t})]})]})})]})}function pu(e,t){let[s,n]=(0,r.useState)({value:null,loading:!1,error:null}),[i,a]=(0,r.useState)(0);return(0,r.useEffect)(()=>{if(!e)return;let s=!0;return Promise.resolve().then(async()=>{if(s){n({value:null,loading:!0,error:null});try{let e=await t();s&&n({value:e,loading:!1,error:null})}catch(e){s&&n({value:null,loading:!1,error:e instanceof Error?e.message:String(e)})}}}),()=>{s=!1}},[i,e,t]),{...s,retry:()=>a(e=>e+1)}}let pm={direct:["toolExposureDirect","直接使用"],"model-only":["toolExposureModelOnly","仅模型调用"],codemode:["toolExposureCodemode","通过脚本调用"],deferred:["toolExposureDeferred","按需发现"],hidden:["toolExposureHidden","不可调用"]};function pp({tools:e}){let{t}=(0,b.Bd)("workbench"),[s,i]=(0,r.useState)(""),[a,l]=(0,r.useState)("all"),o=s.trim().toLocaleLowerCase(),c=e.filter(e=>(!o||`${e.name} ${e.source??""} ${e.description}`.toLocaleLowerCase().includes(o))&&("all"===a||("blocked"===a?e.blockedByMode:e.exposure===a)));return(0,n.jsxs)("section",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsxs)(nC.MG,{className:"min-w-0 flex-1 basis-56",children:[(0,n.jsx)(nC.Sq,{children:(0,n.jsx)(eh.A,{className:"size-4"})}),(0,n.jsx)(nC.iV,{"aria-label":t("searchTools"),placeholder:t("searchToolsSources",{defaultValue:"搜索名称、来源或描述"}),value:s,onChange:e=>i(e.target.value)})]}),(0,n.jsxs)(ea.l6,{value:a,onValueChange:e=>{"string"==typeof e&&l(e)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("toolFilter"),className:"max-w-full",children:(0,n.jsx)(ea.yv,{children:"all"===a?t("allTools"):"blocked"===a?t("toolBlockedByMode"):t(pm[a]?.[0]??"toolUnknown")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(ea.eb,{value:"all",children:t("allTools")}),Object.entries(pm).map(([e,[s,r]])=>(0,n.jsx)(ea.eb,{value:e,children:t(s,{defaultValue:r})},e)),(0,n.jsx)(ea.eb,{value:"blocked",children:t("toolBlockedByMode")})]})]})]}),(0,n.jsxs)("div",{className:"divide-y",children:[c.map(e=>{let s=e.exposure?pm[e.exposure]:null;return(0,n.jsxs)("article",{className:"space-y-2 py-3",children:[(0,n.jsx)("h3",{className:"wrap-anywhere font-mono text-sm font-medium",children:e.name}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:[t("toolSource",{defaultValue:"来源"}),":"," ",e.source??t("toolUnknown",{defaultValue:"未知"})]}),(0,n.jsx)("span",{children:s?t(s[0],{defaultValue:s[1]}):t("toolUnknown",{defaultValue:"未知"})}),(0,n.jsx)("span",{children:void 0===e.active?t("toolUnknown",{defaultValue:"未知"}):e.active?t("toolActive",{defaultValue:"当前已选用"}):t("toolInactive",{defaultValue:"当前未选用"})}),(0,n.jsx)("span",{children:void 0===e.blockedByMode?t("toolModeUnknown",{defaultValue:"模式限制未知"}):e.blockedByMode?t("toolBlockedByMode",{defaultValue:"受模式限制"}):t("toolNotBlocked",{defaultValue:"未受模式限制"})})]}),(0,n.jsx)("p",{className:"whitespace-pre-wrap wrap-anywhere text-sm text-muted-foreground",children:e.description}),(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{className:"min-h-7 cursor-pointer text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:t("parameterSchema")}),(0,n.jsx)("pre",{className:"mt-2 whitespace-pre-wrap wrap-anywhere rounded-lg bg-muted p-3 font-mono text-sm leading-[1.6]",children:JSON.stringify(e.parameters,null,2)})]})]},e.name)}),c.length?null:(0,n.jsxs)("div",{className:"space-y-3 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)("p",{children:o||"all"!==a?t("noMatchingTools"):t("noRegisteredTools",{defaultValue:"当前会话没有登记工具"})}),o||"all"!==a?(0,n.jsx)(I.$,{variant:"outline",size:"sm",onClick:()=>{i(""),l("all")},children:t("clearSearch")}):null]})]})]})}function ph({notices:e}){let{t}=(0,b.Bd)("workbench");return(0,n.jsx)("section",{"aria-label":t("nativeCommandOutput",{defaultValue:"会话命令输出"}),className:"space-y-3",children:e.length?e.map((e,t)=>(0,n.jsx)("p",{className:`whitespace-pre-wrap wrap-anywhere font-mono text-sm leading-[1.6] ${"error"===e.level?"text-destructive":"warning"===e.level?"text-amber-700 dark:text-amber-300":""}`,children:function(e){let t=[],s=0;for(let r of e.matchAll(/https?:\/\/[^\s<>"']+/g)){let i=r.index,a=r[0].replace(/[)\]。,.;]+$/,"");t.push(e.slice(s,i)),t.push((0,n.jsx)("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-2 wrap-anywhere",children:a},i)),s=i+a.length}return t.push(e.slice(s)),t}(e.message)},t)):(0,n.jsx)("p",{className:"py-6 text-sm text-muted-foreground",children:t("nativeCommandOutputEmpty",{defaultValue:"暂无会话命令输出"})})})}function pg({available:e,state:t,disabled:s,onExecute:i}){let{t:a}=(0,b.Bd)("workbench"),[l,o]=(0,r.useState)("status"),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(!1),p="status"!==l,h=c.trim(),g=p&&!/^[a-zA-Z0-9_-]+$/.test(h);return(0,n.jsxs)("div",{className:"space-y-4",children:[e?(0,n.jsxs)("form",{className:"space-y-3",onSubmit:e=>{e.preventDefault(),s||!t.ready||t.commandPending||g||"logout"===l&&!u||i("status"===l?"":`${l} ${h}`,"login"===l)},children:[(0,n.jsx)(n2,{label:a("mcpSessionActions",{defaultValue:"MCP 会话操作"}),layout:"segmented",value:l,onChange:e=>{o(e),m(!1)},options:[{value:"status",label:a("mcpStatus",{defaultValue:"状态"})},{value:"login",label:a("mcpLogin",{defaultValue:"登录"})},{value:"reconnect",label:a("mcpReconnect",{defaultValue:"重连"})},{value:"logout",label:a("mcpLogout",{defaultValue:"退出登录"})}]}),p?(0,n.jsxs)("label",{className:"block space-y-1 text-sm font-medium",children:[(0,n.jsx)("span",{children:a("mcpServerName",{defaultValue:"服务名称"})}),(0,n.jsx)(em.p,{value:c,onChange:e=>d(e.target.value),placeholder:a("mcpServerNamePlaceholder",{defaultValue:"输入真实服务名称"}),autoComplete:"off",maxLength:128})]}):null,p&&h&&g?(0,n.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:a("mcpServerNameInvalid",{defaultValue:"服务名称只能包含字母、数字、下划线和连字符。"})}):null,"logout"===l?(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-start gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",className:"mt-1 size-4 accent-primary",checked:u,onChange:e=>m(e.target.checked)}),(0,n.jsx)("span",{children:a("mcpLogoutConfirm",{defaultValue:"删除共享登录凭据,其他会话下次访问也可能需要重新登录。"})})]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(I.$,{type:"submit",size:"sm",disabled:s||!t.ready||null!==t.commandPending||g||"logout"===l&&!u,children:a("mcpExecute",{defaultValue:"执行"})}),t.commandPending?(0,n.jsxs)("span",{role:"status",className:"wrap-anywhere text-sm text-muted-foreground",children:[a("mcpExecuting",{defaultValue:"正在执行"})," ",t.commandPending]}):null]})]}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:a("mcpCommandUnavailable",{defaultValue:"当前会话未注册 MCP 命令。"})}),(0,n.jsxs)("div",{className:"border-t pt-4",children:[(0,n.jsx)("h3",{className:"mb-3 text-sm font-medium",children:a("nativeCommandOutput",{defaultValue:"会话命令输出"})}),(0,n.jsx)(ph,{notices:t.notices})]})]})}function pf({open:e,source:t,runtime:s,getContext:i,listCommands:a,nativeUi:l,nativeBiz:o,commandsDisabled:c,onOpenChange:d,onOpenSettings:u}){let{t:m,i18n:p}=(0,b.Bd)("workbench"),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)("tools"),v=(0,X.G)(),{context:w,tools:y,commands:k}=function(e){let{source:t,runtime:s,getContext:n,listCommands:i,open:a,tab:l}=e,o=(0,r.useCallback)(()=>n({source:t}),[n,t]),c=(0,r.useCallback)(()=>s.listTools(t),[s,t]),d=(0,r.useCallback)(()=>i({source:t}),[i,t]);return{context:pu(a&&"system"===l,o),tools:pu(a&&"tools"===l,c),commands:pu(a&&"mcp"===l,d)}}({source:t,open:e,tab:f,runtime:s,getContext:i,listCommands:a}),j="system"===f?w:"tools"===f?y:k,N=l.state.snapshot.requests[0]?.id;(0,r.useEffect)(()=>{e&&N&&(l.setCollapsed(!1),d(!1))},[e,N,l,d]);let S=async()=>{w.value&&(await (0,e9.x)(w.value.systemPrompt)?g(!0):v.error(m("contextCopyFailed")))};return(0,n.jsx)(eN.YV,{open:e,onOpenChange:d,children:(0,n.jsxs)(eN.hA,{className:"h-[min(42rem,calc(100dvh-2rem))] max-w-[45rem]",children:[(0,n.jsxs)(eN.Hl,{className:"border-b p-4 pr-12",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)(nI.A,{className:"size-5 shrink-0 text-muted-foreground"}),(0,n.jsx)(eN.YM,{children:m("toolsAndContext",{defaultValue:"工具与上下文"})})]}),(0,n.jsx)(eN.uX,{className:"sr-only",children:m("sessionContextDescription",{defaultValue:"当前会话的登记工具、系统提示词和 MCP 原生命令"})})]}),(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-b px-4 py-3",children:[(0,n.jsx)(n2,{label:m("contextContents"),layout:"segmented",value:f,onChange:x,options:[{value:"tools",label:m("tools")},{value:"system",label:m("systemPrompt")},{value:"mcp",label:m("mcpSession",{defaultValue:"会话 MCP"})}]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:["system"===f?(0,n.jsxs)(I.$,{variant:"ghost",size:"sm",disabled:!w.value||w.loading,onClick:()=>void S(),children:[h?(0,n.jsx)(ep.A,{}):(0,n.jsx)(ee.A,{}),h?m("copied"):m("copy")]}):null,u?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{d(!1),u()},children:m("openSettings",{defaultValue:(p.resolvedLanguage??p.language).startsWith("en")?"Open settings":"打开设置"})}):null]})]}),(0,n.jsx)(eN._Y,{children:(0,n.jsx)("div",{className:"p-4",children:!j.loading&&(j.value||j.error)?j.error?(0,n.jsxs)("div",{className:"space-y-3 py-6",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:j.error}),(0,n.jsxs)(I.$,{variant:"outline",size:"sm",onClick:j.retry,children:[(0,n.jsx)(es.A,{}),m("contextRetry")]})]}):"tools"===f&&y.value?(0,n.jsx)(pp,{tools:y.value.tools}):"system"===f&&w.value?(0,n.jsx)("section",{"aria-label":m("systemPrompt"),children:(0,n.jsx)("pre",{className:"whitespace-pre-wrap wrap-anywhere font-mono text-sm leading-[1.6]",children:w.value.systemPrompt||m("emptyContent")})}):"mcp"===f&&k.value?(0,n.jsx)(pg,{available:k.value.commands.some(e=>"mcp"===e.name&&"extension"===e.source),state:l.state,disabled:c,onExecute:(e,s)=>{o.executeCommand(t,"mcp",e),s&&(l.setCollapsed(!1),d(!1))}}):null:(0,n.jsxs)("div",{role:"status",className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)(es.A,{className:"size-4 animate-spin"}),m("contextLoading")]})})})]})})}let px={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pb({source:e,runtime:t,catalog:s,current:i,label:a,title:l,disabled:o,triggerClassName:c,detailsClassName:d,onOpenSettings:u}){let{t:m,i18n:p}=(0,b.Bd)("workbench"),[h,g]=(0,r.useState)(null),{open:f,pending:x,error:v,changeOpen:w,refresh:y,submit:k}=function(e,t,s){let[n,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)(null),d=(0,r.useRef)(null),u=(0,r.useRef)(!1),m=(0,r.useRef)(!0);(0,r.useEffect)(()=>(m.current=!0,()=>{m.current=!1,d.current=null}),[]);let p=()=>{t.loadModels(e,!0)},h=e=>{d.current=e?{}:null,i(e),e&&(c(null),p())},g=async(n,r)=>{if(s||u.current)return;let i=d.current;u.current=!0,l(!0),c(null);try{await t.setModel(e,{provider:n.provider,modelId:n.modelId,thinkingLevel:r}),i&&d.current===i&&h(!1)}catch(e){i&&d.current===i&&c(e instanceof Error?e.message:String(e))}finally{u.current=!1,m.current&&l(!1)}};return{open:n,pending:a,error:o,changeOpen:h,refresh:p,submit:g}}(e,t,o),j=s.models.find(e=>e.provider===i?.provider&&e.modelId===i.modelId),N=s.models.some(e=>"virtual"===e.kind)?[{key:"virtual",label:m("modelAutomaticRouting",{defaultValue:"自动路由"}),models:s.models.filter(e=>"virtual"===e.kind)},{key:"physical",label:m("modelFixed",{defaultValue:"固定模型"}),models:s.models.filter(e=>"physical"===e.kind)}].filter(e=>e.models.length>0):[{key:"all",label:m("allModels"),models:s.models}];return(0,n.jsxs)(H.rI,{open:f,onOpenChange:e=>{g(null),w(e)},children:[(0,n.jsxs)(H.ty,{render:(0,n.jsx)(lG,{title:l,"aria-label":m("chooseModel"),className:c}),children:[(0,n.jsx)(eD.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{"data-model-trigger-details":!0,className:d,children:(0,n.jsxs)("span",{className:"flex min-w-0 items-center gap-2 pl-2",children:[(0,n.jsx)("span",{className:"min-w-0 truncate",children:a}),(0,n.jsx)(eY.A,{className:"size-3 shrink-0"})]})})]}),(0,n.jsxs)(H.SQ,{align:"start",side:"top",className:"flex max-h-96 w-72 flex-col overflow-hidden p-0",children:[(0,n.jsxs)(H.I,{className:"shrink-0 p-1",children:[(0,n.jsx)(H.lp,{children:m("currentModel")}),(0,n.jsxs)("div",{className:"mx-1 mb-1 flex items-center gap-2 rounded-md border bg-muted/50 px-2 py-2",children:[(0,n.jsx)(eD.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",children:j?.name||i?.modelId||m("selectModel")}),(0,n.jsx)("p",{className:"truncate text-xs text-muted-foreground",children:i?.provider||m("selectModel")})]}),i?(0,n.jsx)("span",{className:"shrink-0 rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:m("thinkingLevel",{level:m(px[i.thinkingLevel])})}):null]}),v?(0,n.jsx)("p",{role:"alert",className:"wrap-anywhere px-2 py-1 text-sm text-destructive",children:v}):null,x?(0,n.jsx)("p",{role:"status",className:"px-2 py-1 text-sm text-muted-foreground",children:m("modelChanging",{defaultValue:"正在切换模型…"})}):null]}),(0,n.jsx)(H.mB,{className:"mx-0 my-0 shrink-0"}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-auto overflow-x-hidden overflow-y-auto overscroll-contain p-1",children:["loading"===s.status?(0,n.jsxs)(H._2,{disabled:!0,children:[(0,n.jsx)(es.A,{className:"size-4 animate-spin"}),m("modelsLoading")]}):null,"error"===s.status?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{role:"alert",className:"wrap-anywhere px-2 py-1 text-sm text-destructive",children:s.error||m("modelsFailed")}),(0,n.jsxs)(H._2,{closeOnClick:!1,onClick:y,children:[(0,n.jsx)(es.A,{className:"size-4"}),m("retry")]})]}):null,N.map(e=>(0,n.jsxs)(H.I,{children:[(0,n.jsx)(H.lp,{children:e.label}),e.models.map(e=>{let t=`${e.provider}:${e.modelId}`,s=i?.provider===e.provider&&i.modelId===e.modelId;return(0,n.jsxs)(H.lv,{open:h===t,onOpenChange:e=>{g(s=>e?t:s===t?null:s)},children:[(0,n.jsxs)(H.nV,{disabled:o||x,label:e.name||e.modelId,children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.name||e.modelId}),e.input.includes("image")?(0,n.jsx)(ru.A,{className:"size-3 text-muted-foreground"}):null,s?(0,n.jsx)(ep.A,{className:"size-3 text-muted-foreground"}):null]}),(0,n.jsx)(H.M5,{children:(0,n.jsxs)(H.I,{children:[(0,n.jsx)(H.lp,{children:m("thinkingLevels")}),e.thinkingLevels.map(t=>(0,n.jsxs)(H._2,{disabled:o||x,closeOnClick:!1,onClick:()=>{g(null),k(e,t)},children:[(0,n.jsx)("span",{className:"flex-1",children:m(px[t])}),s&&i?.thinkingLevel===t?(0,n.jsx)(ep.A,{className:"size-3 text-muted-foreground"}):null]},t))]})})]},t)})]},e.key)),"ready"===s.status&&0===s.models.length?(0,n.jsx)(H._2,{disabled:!0,children:m("noModels")}):null,u&&("error"===s.status||"ready"===s.status&&0===s.models.length)?(0,n.jsx)(H._2,{onClick:()=>u(),children:m("openSettings",{defaultValue:(p.resolvedLanguage??p.language).startsWith("en")?"Open settings":"打开设置"})}):null]}),"ready"===s.status||s.presets.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(H.mB,{className:"mx-0 my-0 shrink-0"}),(0,n.jsxs)(H.I,{className:"shrink-0 p-1",children:[(0,n.jsx)(H.lp,{children:m("presets")}),0===s.presets.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:m("commonCombinationsEmpty")}),u?(0,n.jsxs)(H._2,{onClick:()=>{w(!1),u("model-presets")},children:[(0,n.jsx)(aI.A,{className:"size-4"}),m("configureCommonCombinations")]}):null]}):null,s.presets.map((e,t)=>(0,n.jsxs)(H._2,{disabled:o||x,closeOnClick:!1,onClick:()=>void k(e,e.thinkingLevel),children:[(0,n.jsx)("span",{className:"size-2 rounded-full bg-current",style:e.color?{color:e.color}:void 0}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:s.models.find(t=>t.provider===e.provider&&t.modelId===e.modelId)?.name||e.modelId}),(0,n.jsx)("span",{className:"text-muted-foreground",children:m(px[e.thinkingLevel])})]},`${e.provider}:${e.modelId}:${e.thinkingLevel}:${t}`))]})]}):null]})]})}var pv=s(15824);function pw({label:e,description:t,markerClass:s,countClass:r,inputs:i}){let{t:a}=(0,b.Bd)("workbench");return 0===i.length?null:(0,n.jsxs)("section",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-3 px-1",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:`size-1.5 shrink-0 rounded-full ${s}`}),(0,n.jsx)("h3",{className:"text-sm font-medium text-foreground",children:e})]}),(0,n.jsx)("p",{className:"mt-1 pl-3.5 text-sm leading-5 text-muted-foreground",children:t})]}),(0,n.jsx)("span",{className:`shrink-0 rounded-md px-1.5 py-0.5 text-xs font-medium tabular-nums ${r}`,children:a("queueItems",{count:i.length})})]}),(0,n.jsx)("ol",{className:"divide-y divide-border overflow-hidden",children:i.map((e,t)=>{let s=e.text.trim();return(0,n.jsxs)("li",{className:"grid grid-cols-[1.25rem_minmax(0,1fr)] gap-2.5 px-3 py-2.5",children:[(0,n.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center rounded-md bg-muted text-xs tabular-nums text-muted-foreground",children:t+1}),(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsx)("p",{className:"whitespace-pre-wrap break-words text-sm leading-6 text-foreground",children:s||a(e.images.length>0?"imageOnly":"noMessageText")}),e.images.length>0?(0,n.jsxs)("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[(0,n.jsx)(ru.A,{className:"size-3"}),a("queueImages",{count:e.images.length})]}):null]})]},e.tempId)})})]})}function py({queues:e,disabled:t,onRestore:s}){let{t:i}=(0,b.Bd)("workbench"),a=(0,r.useId)(),l=(0,r.useRef)(!1),[o,c]=(0,r.useState)(!1),d=e.steering.length+e.followUp.length;return 0===d?null:(0,n.jsxs)(lY,{open:o,triggerId:a,onOpenChange:(e,t)=>{l.current&&"trigger-focus"===t.reason||c(e)},children:[(0,n.jsx)(lV,{id:a,delay:100,closeDelay:120,render:(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",disabled:t,"aria-label":i("viewQueued",{count:d}),"aria-expanded":o,onPointerDown:e=>{l.current="mouse"!==e.pointerType},onPointerCancel:()=>{l.current=!1},onClick:e=>{l.current&&(e.preventDefault(),c(e=>!e),queueMicrotask(()=>{l.current=!1}))},children:i("queuedCount",{count:d})})}),(0,n.jsxs)(lU,{side:"top",align:"end",sideOffset:6,"aria-label":i("queueCurrent"),className:"w-[22rem] max-w-[calc(100vw-2rem)] overflow-hidden p-0",children:[(0,n.jsx)("div",{className:"border-b px-4 py-3",children:(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground",children:(0,n.jsx)(pv.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("h2",{className:"text-sm font-semibold tracking-tight text-foreground",children:i("queueCurrent")}),(0,n.jsx)("p",{className:"mt-1 text-sm leading-5 text-muted-foreground",children:i("queuePendingDescription")})]}),(0,n.jsx)("span",{className:"shrink-0 rounded-md bg-muted px-2 py-1 text-xs tabular-nums text-foreground",children:i("queueItems",{count:d})})]})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar max-h-[min(24rem,55dvh)] space-y-4 overflow-y-auto p-4",children:[(0,n.jsx)(pw,{label:i("queueSteer"),description:i("queueSteerDescription"),markerClass:"bg-foreground",countClass:"bg-muted text-muted-foreground",inputs:e.steering}),(0,n.jsx)(pw,{label:i("queueFollowUp"),description:i("queueFollowUpDescription"),markerClass:"bg-muted-foreground",countClass:"bg-muted text-muted-foreground",inputs:e.followUp})]}),(0,n.jsx)("div",{className:"border-t border-border/60 bg-muted/15 p-2",children:(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",className:"w-full text-muted-foreground hover:text-foreground",disabled:t,onClick:s,children:[(0,n.jsx)(lP.A,{}),i("queueRestore")]})})]})]})}let pk={builtin:"slashGroupBuiltin",skill:"slashGroupSkill",prompt:"slashGroupPrompt",extension:"slashGroupExtension"};function pj({open:e,loading:t,error:s,groups:i,activeIndex:a,onActiveIndexChange:l,onSelect:o}){let{t:c}=(0,b.Bd)("workbench"),d=(0,r.useRef)(null),u=i.reduce((e,t)=>e+t.commands.length,0);if((0,r.useEffect)(()=>{d.current?.scrollIntoView({block:"nearest"})},[a]),!e)return null;let m=0,p=u>0,h=t?c("slashLoadingMore"):s?c("slashMoreFailed"):null;return(0,n.jsxs)("div",{id:m7,role:"listbox","aria-label":c("slashCandidates"),"aria-busy":t,className:"absolute bottom-full left-[-1px] z-20 mb-2 flex w-[calc(100%+2px)] origin-bottom-left flex-col overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2 duration-100",children:[(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar max-h-72 overflow-x-hidden overflow-y-auto overscroll-contain p-1 scroll-py-8 max-sm:max-h-[40dvh]",children:[i.map((e,t)=>(0,n.jsxs)("section",{role:"group","aria-label":c(pk[e.source]),className:(0,C.cn)(t>0&&"mt-1 border-t pt-1"),children:[(0,n.jsxs)("div",{className:"sticky -top-1 z-10 flex h-7 items-center gap-2 bg-popover px-2 text-xs font-medium text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-1.5 rounded-full bg-muted-foreground"}),(0,n.jsx)("span",{children:c(pk[e.source])}),(0,n.jsx)("span",{className:"ml-auto font-normal tabular-nums opacity-70",children:e.commands.length})]}),e.commands.map(e=>{let t=m++,s=t===a;return(0,n.jsxs)("div",{id:pt(t),ref:s?d:void 0,role:"option","aria-selected":s,"data-active":s?"true":"false",className:"grid min-h-9 cursor-pointer grid-cols-[minmax(6.75rem,0.9fr)_minmax(0,1.2fr)_0.75rem] items-center gap-2 rounded-md px-2 py-1 text-sm outline-none select-none data-[active=true]:bg-accent sm:grid-cols-[minmax(7rem,0.8fr)_minmax(0,1.5fr)_1rem]",onPointerMove:e=>{"mouse"===e.pointerType&&l(t)},onPointerDown:e=>e.preventDefault(),onClick:()=>o(t),children:[(0,n.jsxs)("span",{className:"min-w-0 truncate font-mono text-sm font-medium",children:[(0,n.jsx)("span",{className:"text-primary",children:"/"}),e.name]}),(0,n.jsx)("span",{className:"min-w-0 truncate text-sm text-muted-foreground",children:"builtin"===e.source&&"reload"===e.name?c("reloadDescription"):e.description}),(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("text-right text-sm text-muted-foreground opacity-0",s&&"opacity-80"),children:"↵"})]},e.key)})]},e.source)),p?h?(0,n.jsxs)("div",{className:"flex min-h-7 items-center gap-2 px-2 text-xs text-muted-foreground",children:[t?(0,n.jsx)(v.A,{className:"size-3 animate-spin"}):null,(0,n.jsx)("span",{children:h})]}):null:(0,n.jsxs)("div",{className:"flex min-h-20 items-center justify-center gap-2 px-4 text-xs text-muted-foreground",children:[t?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):null,(0,n.jsx)("span",{children:t?c("slashLoading"):s?c("slashFailed"):c("slashEmpty")})]})]}),(0,n.jsxs)("div",{className:"flex min-h-7 items-center justify-between gap-3 border-t px-2.5 text-xs text-muted-foreground",children:[(0,n.jsx)("span",{className:"tabular-nums",children:i.length>0?c("slashSummary",{commands:u,groups:i.length}):c("slashCount",{count:u})}),(0,n.jsxs)("span",{className:"flex items-center gap-2 max-sm:hidden","aria-hidden":"true",children:[(0,n.jsx)("span",{children:c("slashUpDown")}),(0,n.jsx)("span",{children:c("slashEnter")}),(0,n.jsx)("span",{children:c("slashEscape")})]})]})]})}var pN=s(58270),pI=s.n(pN);function pS({modes:e,value:t,disabled:s,onChange:r}){let{t:i}=(0,b.Bd)("capabilityModes");if(0===Object.keys(e).length)return null;let a=null===t?i("allEnabled"):Object.hasOwn(e,t)?e[t]:i("modeSwitching");return(0,n.jsxs)(H.rI,{children:[(0,n.jsxs)(H.ty,{render:(0,n.jsx)(I.$,{variant:"ghost",size:"sm",disabled:s,"aria-label":i("modePicker",{name:a}),className:"min-w-0 max-w-40 text-muted-foreground"}),children:[(0,n.jsx)(eg.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 truncate",children:a}),(0,n.jsx)(eY.A,{className:"size-3 shrink-0"})]}),(0,n.jsx)(H.SQ,{side:"top",align:"start",className:"max-h-80 min-w-40 overflow-y-auto",children:(0,n.jsxs)(H.Hr,{value:t??"",onValueChange:e=>r("string"==typeof e&&e?e:null),children:[(0,n.jsx)(H.Ht,{value:"",children:i("allEnabled")}),Object.entries(e).map(([e,t])=>(0,n.jsx)(H.Ht,{value:e,children:t},e))]})})]})}var pC=s(18903),pE=s(8356),pM=s(93192);function pz({request:e,model:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,r.useId)(),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)(()=>Date.now()),{state:d}=t,u=Object.hasOwn(d.answers,e.id),m=d.answers[e.id]??("editor"===e.method?e.prefill:""),p=null!==e.expiresAt&&e.expiresAt<=o,h=!d.ready||null!==d.submitting||null!==d.unknown||p,g=h||"select"===e.method&&!u;(0,r.useEffect)(()=>{if(null===e.expiresAt)return;let t=window.setInterval(()=>c(Date.now()),500);return()=>window.clearInterval(t)},[e.expiresAt]);let f=s=>{s?.preventDefault(),g||t.answer(e.id,"confirm"===e.method||m)},x=s=>(0,n.jsx)(t7.T,{"aria-label":e.title,"aria-labelledby":s?void 0:i,className:s?"min-h-0 flex-1 resize-none text-base":"h-32 min-h-20 resize-none text-base",value:m,disabled:null!==d.submitting,maxLength:65536,onChange:s=>t.setAnswer(e.id,s.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),f())}}),v=(r=!1)=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",disabled:!r&&!t.canStop,onClick:r?()=>l(!1):t.stop,children:r?s("nativeUiBack"):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(m2.A,{className:"size-3.5"}),s("nativeUiStop")]})}),(0,n.jsx)("span",{className:"flex-1"}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",disabled:h,onClick:()=>t.answer(e.id,"confirm"!==e.method&&null),children:s("confirm"===e.method?"nativeUiReject":"nativeUiCancel")}),(0,n.jsx)(I.$,{type:r?"button":"submit",size:"sm",disabled:g,onClick:r?()=>f():void 0,children:s(d.submitting?"nativeUiSubmitting":"confirm"===e.method?"nativeUiConfirm":"nativeUiSubmit")})]});return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("section",{className:"mb-2 overflow-hidden rounded-xl border border-input bg-background","aria-label":s("nativeUiTitle"),"data-testid":"native-ui-question",onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||a||(e.preventDefault(),e.stopPropagation(),t.setCollapsed(!0))},children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 px-3 pt-2 text-xs text-muted-foreground",children:[(0,n.jsx)(pC.A,{className:"size-3.5"}),(0,n.jsx)("span",{children:s("nativeUiTitle")}),d.snapshot.requests.length>1?(0,n.jsx)("span",{children:s("nativeUiMore",{count:d.snapshot.requests.length-1})}):null,(0,n.jsx)("span",{className:"flex-1"}),"editor"===e.method?(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>l(!0),children:[(0,n.jsx)(q.A,{className:"size-3.5"}),s("nativeUiExpand")]}):null,(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>t.setCollapsed(!0),children:s("nativeUiLater")})]}),(0,n.jsxs)("form",{onSubmit:f,children:[(0,n.jsxs)("div",{className:"max-h-[40dvh] space-y-3 overflow-y-auto px-3 pt-2 pb-3",children:[(0,n.jsx)("h3",{id:i,className:"text-base leading-6 font-medium whitespace-pre-wrap wrap-anywhere",children:e.title}),"confirm"===e.method?(0,n.jsx)("p",{className:"text-sm leading-6 whitespace-pre-wrap wrap-anywhere text-muted-foreground",children:e.message}):null,"select"===e.method?(0,n.jsx)(n2,{label:e.title,value:u?String(e.options.indexOf(m)):"",disabled:h,options:e.options.map((e,t)=>({value:String(t),label:e})),onChange:s=>t.setAnswer(e.id,e.options[Number(s)])}):null,"input"===e.method?(0,n.jsx)(em.p,{"aria-labelledby":i,value:m,placeholder:e.placeholder,maxLength:65536,className:"text-base",disabled:null!==d.submitting,onChange:s=>t.setAnswer(e.id,s.target.value)}):null,"editor"===e.method?x(!1):null,null!==e.expiresAt?(0,n.jsxs)("p",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(pE.A,{className:"size-3.5"}),s("nativeUiCountdown",{seconds:Math.max(0,Math.ceil((e.expiresAt-o)/1e3))})]}):null]}),(0,n.jsx)("div",{className:"flex flex-wrap items-center gap-2 border-t px-3 py-2",children:v()})]})]}),"editor"===e.method&&a?(0,n.jsx)(eN.YV,{open:!0,onOpenChange:l,children:(0,n.jsxs)(eN.hA,{className:"h-[min(40rem,calc(100dvh-2rem))] max-w-3xl","data-testid":"native-ui-editor-dialog",children:[(0,n.jsx)(eN.Hl,{className:"px-4 pt-4 pr-12 pb-3",children:(0,n.jsx)(eN.YM,{children:e.title})}),d.error||!d.ready?(0,n.jsx)("p",{role:"status",className:"px-4 pb-3 text-sm text-muted-foreground",children:d.error??s("nativeUiDisconnected")}):null,(0,n.jsx)("div",{className:"flex min-h-0 flex-1 px-4 pb-4",children:x(!0)}),(0,n.jsx)(eN.vu,{children:v(!0)})]})}):null]})}function pA({model:e}){let{t}=(0,b.Bd)("workbench"),{state:s}=e,r=s.snapshot.requests[0];return(0,n.jsxs)(n.Fragment,{children:[s.error||!s.ready&&r?(0,n.jsxs)("div",{role:"status",className:"mb-2 flex flex-wrap items-center gap-2 rounded-lg bg-muted px-3 py-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:s.error??t("nativeUiDisconnected")}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:s.refreshing,onClick:e.refresh,children:[s.refreshing?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):null,t("nativeUiRetry")]}),r?null:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:e.dismissError,children:t("close",{ns:"common"})})]}):null,r?s.collapsed?(0,n.jsxs)("div",{className:"mb-2 flex items-center gap-2 rounded-lg border px-3 py-2","data-testid":"native-ui-collapsed",children:[(0,n.jsx)(pC.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 text-sm",children:t("nativeUiPending",{count:s.snapshot.requests.length})}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>e.setCollapsed(!1),children:t("nativeUiResume")})]}):(0,n.jsx)(pz,{request:r,model:e},r.id):null,s.notices.length>0?(0,n.jsxs)(eV.Nt,{defaultOpen:!!(r||s.commandPending?.startsWith("/mcp login ")),className:"mb-2 rounded-lg border px-3 py-2","data-testid":"native-ui-output",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-7 min-w-0 flex-1 cursor-pointer items-center gap-2 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eY.A,{className:"size-3.5 shrink-0 transition-transform group-data-panel-open:rotate-180 motion-reduce:transition-none"}),t("nativeCommandOutput",{defaultValue:"会话命令输出"})]}),(0,n.jsx)(I.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":t("close",{ns:"common"}),onClick:e.dismissNotices,children:(0,n.jsx)(V.A,{className:"size-3.5"})})]}),(0,n.jsx)(eV.Ke,{children:(0,n.jsx)("div",{className:"mt-2 max-h-40 overflow-y-auto",children:(0,n.jsx)(ph,{notices:s.notices})})})]}):null,s.prefill?(0,n.jsxs)("div",{className:"mb-2 rounded-lg border px-3 py-2","data-testid":"native-ui-prefill",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"flex-1 text-sm font-medium",children:t("nativeUiDraft")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>e.usePrefill("dismiss"),children:t("nativeUiDismiss")})]}),(0,n.jsx)("p",{className:"my-2 max-h-24 overflow-y-auto text-sm whitespace-pre-wrap wrap-anywhere",children:s.prefill.text}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"secondary",onClick:()=>e.usePrefill("append"),children:t("nativeUiAppend")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>e.usePrefill("replace"),children:t("nativeUiReplace")})]})]}):null]})}function p$({snapshot:e,placement:t}){let{t:s}=(0,b.Bd)("workbench"),r=Object.entries(e.widgets).filter(([,e])=>e.placement===t),i="belowEditor"===t?Object.values(e.statuses):[];return r.length||i.length?(0,n.jsxs)("div",{className:"my-1.5 space-y-1","data-testid":`native-ui-extras-${t}`,children:[r.length?(0,n.jsxs)("details",{className:"group",children:[(0,n.jsxs)("summary",{className:"flex min-h-7 cursor-pointer items-center gap-2 text-xs text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(pM.A,{className:"size-3.5"}),s("nativeUiInfo"),(0,n.jsx)("span",{children:r.length>1?r.length:""}),(0,n.jsx)(eY.A,{className:"size-3.5 transition-transform group-open:rotate-180"})]}),(0,n.jsx)("div",{className:"max-h-36 space-y-2 overflow-y-auto px-2 pb-2 text-sm leading-6",children:r.map(([e,t])=>(0,n.jsx)("p",{className:"whitespace-pre-wrap wrap-anywhere",children:t.lines.join("\n")},e))})]}):null,i.length?(0,n.jsxs)("details",{className:"group",children:[(0,n.jsxs)("summary",{className:"flex min-h-7 cursor-pointer items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-1.5 shrink-0 rounded-full bg-current"}),(0,n.jsx)("span",{className:"min-w-0 truncate group-open:hidden",children:i[0]}),(0,n.jsx)("span",{className:"hidden group-open:inline",children:s("nativeUiStatus")}),i.length>1?(0,n.jsxs)("span",{children:["+",i.length-1]}):null]}),(0,n.jsx)("div",{className:"max-h-32 space-y-1 overflow-y-auto px-2 py-1 text-sm whitespace-pre-wrap wrap-anywhere",children:i.map((e,t)=>(0,n.jsx)("p",{children:e},t))})]}):null]}):null}let pR={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pP(e){return e<1048576?`${Math.max(1,Math.round(e/1024))}KB`:`${(e/1048576).toFixed(1)}MB`}let pD=(0,r.memo)(function({onOpenSettings:e,workSession:t,chatRuntime:s,inputRuntime:i,renderTaskSummary:a,renderTaskMenu:l,renderPluginComposerPanel:o,renderPluginWidgets:c,gitRuntime:d,active:u,widgetsVisible:m,mobile:p,invokePluginMethod:h,listPiCommands:g,getChatModelContext:f,capabilityModes:x,setChatCapabilityMode:w,newSessionPending:y,newSessionDisabled:k,onNewSession:j,clonePending:N,cloneDisabled:S,onCloneWorkSession:E,onOpenBranchPicker:M,onOpenGitBranchPicker:z}){var A;let $,R,D,T,O,{t:L}=(0,b.Bd)("workbench"),F=(0,X.G)(),B=(0,Q.So)(),q=(0,r.useMemo)(()=>uf.Pi.parse({workId:t.workId,sessionId:t.sessionId,branchId:t.branchId}),[t.branchId,t.sessionId,t.workId]),_=(0,r.useCallback)(()=>i.getState(q),[i,q]),W=(0,r.useCallback)(()=>s.getSourceState(q).runtime,[s,q]),Y=(0,r.useSyncExternalStore)(i.subscribe,_,_),U=(0,r.useSyncExternalStore)(s.subscribe,W,W),G=(0,r.useCallback)(()=>s.getSourceState(q).syncStatus,[s,q]),J="ready"===(0,r.useSyncExternalStore)(s.subscribe,G,G),Z=(A=s.nativeUi,$=(0,X.G)(),R=(0,r.useCallback)(()=>A.getState(q),[A,q]),D=(0,r.useSyncExternalStore)(A.subscribe,R,R),T=(0,r.useCallback)(()=>i.getState(q),[i,q]),O=(0,r.useSyncExternalStore)(i.subscribe,T,T),(0,r.useEffect)(()=>{A.watch(q)},[A,q]),(0,r.useEffect)(()=>A.onNotice((e,t)=>{e.workId===q.workId&&e.sessionId===q.sessionId&&e.branchId===q.branchId&&$.show({level:t.level,title:t.message})}),[A,q,$]),(0,r.useEffect)(()=>{!D.prefill||!O.loaded||O.loading||O.outbox||O.text.length>0||(i.setText(q,D.prefill.text),A.edit(q,{prefill:null}))},[A,q,i,D.prefill,O.loaded,O.loading,O.outbox,O.text]),{state:D,canStop:J,setAnswer:(e,t)=>A.edit(q,{answers:{...A.getState(q).answers,[e]:t}}),setCollapsed:e=>A.edit(q,{collapsed:e}),answer:(e,t)=>{A.respond(q,{id:e,value:t})},refresh:()=>{A.refreshSource(q)},dismissError:()=>A.edit(q,{error:null}),dismissNotices:()=>A.edit(q,{notices:[]}),usePrefill:e=>{let t=A.getState(q).prefill;if(t){if("dismiss"!==e){let s=i.getState(q).text;i.setText(q,"replace"===e?t.text:`${s}${s?"\n":""}${t.text}`)}A.edit(q,{prefill:null})}},stop:()=>{i.interrupt(q).catch(e=>$.error(e instanceof Error?e.message:String(e)))}}),ee=Z.state.snapshot.requests.length>0,en="basic"===U.extensionMode,er="basic"===U.presentationMode,ei=(0,r.useRef)(null),ea=(0,r.useRef)(null),el=(0,r.useRef)(null),eo=(0,r.useRef)(null),ec=function(e,t,s,n){let[i,a]=(0,r.useState)(!1);return(0,r.useLayoutEffect)(()=>{if(e)return;let r=t.current,i=r?.querySelector('[data-composer-tools="primary"]'),l=r?.querySelector('[data-composer-tools="metadata"]'),o=s.current;if(!r||!i||!l||!o)return;let c=0,d=null,u=()=>{if(null===d){let e=window.getComputedStyle(r);c=r.clientWidth-ps(e.paddingLeft)-ps(e.paddingRight);let t=ps(e.columnGap),s=pn(i),a=pn(l),u=pn(o),m=ps(window.getComputedStyle(i).columnGap),p=ps(window.getComputedStyle(l).columnGap),h=ps(window.getComputedStyle(o).columnGap),g=n.current,f=function(e){let t=[...new Set(e)],s=t.map(e=>({element:e,flex:e.style.flex,width:e.style.width,minWidth:e.style.minWidth}));try{for(let{element:e}of s)e.style.flex="0 0 auto",e.style.width="max-content",e.style.minWidth="max-content";return new Map(t.map(e=>[e,e.getBoundingClientRect().width]))}finally{for(let{element:e,flex:t,width:n,minWidth:r}of s)e.style.flex=t,e.style.width=n,e.style.minWidth=r}}([...s,...a,...u,...g?[g]:[]]),x=[pr(s,m,f),pr(a,p,f),g?f.get(g)??0:0,pr(u,h,f)].filter(e=>e>0);d=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*t}a(d>c+1)},m=null,p=()=>{null===m&&(m=window.requestAnimationFrame(()=>{m=null,u()}))},h=()=>{d=null,p()},g=new ResizeObserver(([e])=>{e&&c!==e.contentRect.width&&(c=e.contentRect.width,p())}),f=new MutationObserver(h);return g.observe(r),f.observe(r,{childList:!0,characterData:!0,subtree:!0}),window.addEventListener("resize",h),document.fonts.addEventListener("loadingdone",h),u(),()=>{g.disconnect(),f.disconnect(),window.removeEventListener("resize",h),document.fonts.removeEventListener("loadingdone",h),null!==m&&window.cancelAnimationFrame(m)}},[t,e,n,s]),i}(p,ea,el,eo),[ed,eu]=(0,r.useState)(null),[em,ep]=(0,r.useState)(null),eh=(0,r.useCallback)(()=>{ep(null)},[]),[eg,ef]=(0,r.useState)(!1),[ex,eb]=(0,r.useState)(null),[ev,ew]=(0,r.useState)(!1),[ey,ek]=(0,r.useState)(!1),[ej,eN]=(0,r.useState)(!1),[eI,eS]=(0,r.useState)(null),[eC,eE]=(0,r.useState)(null),eM=JSON.stringify([q.workId,q.sessionId,q.branchId]),ez=(0,r.useMemo)(()=>en?[]:B.flatMap(e=>e.contributions.flatMap(t=>"composer-panel"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[B,en]),eA=em?ez.find(e=>e.pluginName===em.pluginName&&e.descriptor.contributionName===em.contributionName):void 0;(0,r.useEffect)(()=>{let e=!0;return queueMicrotask(()=>{e&&(ep(e=>e&&e.sourceKey!==eM?null:e),eb(null))}),()=>{e=!1}},[eM]),(0,r.useEffect)(()=>{i.loadSource(q),i.loadModels(q)},[i,q]);let e$="main_running"===t.status,eR=e$||"background_running"===t.status,eP="completed"===t.status,eD=null!==eC,eT=eC?.text??Y.text,eO=eC?.images??Y.images,eL=0===eO.length&&eT.trim()===`/${m9.name}`,eF=eO.reduce((e,t)=>e+t.blob.size,0),eB=Y.outbox&&!(eD&&"sending"===Y.outbox.status)?Y.outbox:null,e_=e$&&!eD,eW=U.queues,eY=Y.images.reduce((e,t)=>e+t.blob.size,0),eV=Y.images.some(e=>"optimizing"===e.status),eU=Y.images.some(e=>"error"===e.status),eK=U.model,eH=eK?Y.models.models.find(e=>e.provider===eK.provider&&e.modelId===eK.modelId):null,eG=Y.images.length>0&&!eH?.input.includes("image"),eJ=eg&&!ey,eQ=J&&!ee&&Y.loaded&&!Y.outbox&&(Y.text.trim().length>0||Y.images.length>0)&&Y.images.length<=10&&!eV&&!eU&&eY<=0x1400000&&!eG,eX=U.plugins["task-center"],eZ=U.contextUsage,e0=eH?.name||eK?.modelId||L("noModelSelected"),e1=J?eK?`${e0} \xb7 ${L(pR[eK.thinkingLevel])}`:L("selectModel"):L("synchronizing"),e2=eK?L("modelTooltip",{model:e1}):L("chooseModel"),e5=ed??Y.error,e3=(0,r.useCallback)(async(e,t)=>{ef(!0),eu(null);try{await e(),t&&F.success(t)}catch(e){eu(e instanceof Error?e.message:L("operationFailed"))}finally{ef(!1)}},[L,F]),e4=(0,r.useCallback)(e=>{eu(null),w({source:q,capabilityMode:e}).catch(e=>{eu(e instanceof Error?e.message:L("modeChangeFailed"))})},[w,q,L]),e6=(0,r.useCallback)(async()=>{if(!ev&&"ready"===s.getSourceState(q).syncStatus){ew(!0);try{await e3(async()=>{await h({pluginName:"context-ignore",method:"ignore",scope:"session",source:q,input:{}})})}finally{ew(!1)}}},[s,ev,h,e3,q]),e8=(0,r.useCallback)(async()=>{if(!ey){ek(!0);try{await e3(()=>s.compact(q))}finally{ek(!1)}}},[s,ey,e3,q]),e7=(0,r.useCallback)(e=>{i.setText(q,`/${e.name} `)},[i,q]),e9=function({source:e,text:t,enabled:s,listPiCommands:n,onSelect:i}){let a=JSON.stringify([e.workId,e.sessionId,e.branchId]),[l,o]=(0,r.useState)(!1),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)({sourceKey:a,status:"idle",commands:[],error:null}),g=(0,r.useRef)(0),f=(0,r.useRef)(!0),x=s&&!l?/^\/[^\s/]*$/.test(t)?t.slice(1):null:null,b=null===x?null:`${a}\u0000${t}`,v=null!==b&&b!==c,{workId:w,sessionId:y,branchId:k}=e;(0,r.useEffect)(()=>(f.current=!0,()=>{f.current=!1,g.current+=1}),[]);let j=(0,r.useCallback)(async()=>{let e=++g.current;queueMicrotask(()=>{f.current&&g.current===e&&h(e=>e.sourceKey===a?{...e,status:"loading",error:null}:{sourceKey:a,status:"loading",commands:[],error:null})});try{let t=await n({source:{workId:w,sessionId:y,branchId:k}});if(!f.current||g.current!==e)return;h({sourceKey:a,status:"ready",commands:t.commands,error:null})}catch(t){if(!f.current||g.current!==e)return;throw console.warn("[Pi Desk][SlashCommand] 查询当前会话命令失败",{workId:w,sessionId:y,branchId:k,errorName:t instanceof Error?t.name:"UnknownError"}),h(e=>({sourceKey:a,status:"error",commands:e.sourceKey===a?e.commands:[],error:t instanceof Error?t.message:"查询命令失败"})),t}},[k,a,n,y,w]);(0,r.useEffect)(()=>{v&&j().catch(()=>void 0)},[v,j]);let N=(0,r.useMemo)(()=>[m9,...(p.sourceKey===a?p.commands:[]).filter(e=>e.name!==m9.name).map(e=>({key:`${e.source}:${e.name}`,name:e.name,description:e.description,source:e.source}))],[a,p.commands,p.sourceKey]),I=(0,r.useMemo)(()=>{let e;return e=(x??"").toLocaleLowerCase(),pe.flatMap(t=>{let s=N.map((t,s)=>({command:t,order:s,score:function(e,t){if(!t)return 3;let s=e.name.toLocaleLowerCase(),n=e.description?.toLocaleLowerCase()??"";return s===t?0:s.startsWith(t)?1:s.includes(t)?2:n.includes(t)?4:1/0}(t,e)})).filter(e=>e.command.source===t.source&&Number.isFinite(e.score)).sort((t,s)=>t.score!==s.score?t.score-s.score:e?t.order-s.order:t.command.name.localeCompare(s.command.name)).map(e=>e.command);return s.length>0?[{...t,commands:s}]:[]})},[N,x]),S=(0,r.useMemo)(()=>I.flatMap(e=>e.commands),[I]),C=b&&u?.contextKey===b?S.findIndex(e=>e.key===u.commandKey):-1,E=C>=0?C:0,M=(0,r.useCallback)(e=>{if(!b||0===S.length)return;let t=(e+S.length)%S.length,s=S[t];s&&m({contextKey:b,commandKey:s.key})},[S,b]),z=(0,r.useCallback)(()=>{b&&d(b)},[b]),A=(0,r.useCallback)(()=>{b&&d(null)},[b]),$=(0,r.useCallback)(e=>{let t=S[e];t&&(b&&d(b),i(t))},[S,b,i]),R=(0,r.useCallback)(e=>!!v&&!e.nativeEvent.isComposing&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&("Escape"===e.key?(e.preventDefault(),z(),!0):0!==S.length&&("ArrowDown"===e.key?(e.preventDefault(),M(E+1),!0):"ArrowUp"===e.key?(e.preventDefault(),M(E-1),!0):("Enter"===e.key||"Tab"===e.key)&&(e.preventDefault(),$(E),!0))),[E,S.length,z,v,$,M]),P=(0,r.useCallback)(()=>{o(!0)},[]),D=(0,r.useCallback)(()=>{o(!1),d(null)},[]);return{open:v,loading:p.sourceKey===a&&"loading"===p.status,error:p.sourceKey===a&&"error"===p.status?p.error:null,groups:I,commands:S,activeIndex:E,dismiss:z,reopen:A,refresh:j,select:$,setActiveIndex:M,handleKeyDown:R,handleCompositionStart:P,handleCompositionEnd:D}}({source:q,text:eT,enabled:u&&J&&Y.loaded&&!Y.loading&&!eD,listPiCommands:g,onSelect:e7}),te=e9.refresh,tt=(0,r.useCallback)(async e=>{if(!ej&&!eg){eN(!0);try{await e3(async()=>{await s.reload(q),await te(),await i.loadModels(q,!0),e&&i.setText(q,"")})}finally{eN(!1)}}},[eg,s,i,te,ej,e3,q]),ts=(0,r.useCallback)(e=>{eD||0===e.length||(eu(null),i.addFiles(q,e))},[eD,i,q]),tn=(0,r.useCallback)(async e=>{if("ready"!==s.getSourceState(q).syncStatus)return;if(eL){if(!Y.loaded||Y.loading)return;await tt(!0);return}if(!eQ||eJ)return;let t=e$?null:{text:Y.text,images:Y.images};t&&eE(t),eu(null);try{await i.send(q,e)}catch(e){eu(e instanceof Error?e.message:L("sendFailed"))}finally{t&&eE(null)}},[eQ,eJ,s,i,Y.images,Y.loaded,Y.loading,Y.text,eL,e$,tt,q,L]);return(0,n.jsxs)("div",{className:"mx-auto w-full max-w-3xl px-2 pb-2 sm:px-4 sm:pb-3",children:[eB?(0,n.jsx)("div",{className:(0,C.cn)("mb-2 rounded-lg border px-3 py-2 text-xs","unknown"===eB.status?"border-amber-500/50 bg-amber-500/10 text-amber-900 dark:text-amber-200":"failed"===eB.status?"border-destructive/40 bg-destructive/5 text-destructive":"border-border bg-muted/50 text-muted-foreground"),children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:"sending"===eB.status?L("confirmingSend"):"unknown"===eB.status?L("sendUnknown"):L("sendFailure",{error:eB.error??L("unknownError")})}),"sending"===eB.status?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:eg,onClick:()=>void e3(()=>i.restoreOutbox(q),L("outboxRestored")),children:[(0,n.jsx)(lP.A,{}),L("restoreDraft")]}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:eg,onClick:()=>void e3(()=>i.deleteOutbox(q),L("outboxDeleted")),children:[(0,n.jsx)(et.A,{}),L("delete")]})]})]})}):null,Y.notice||e5?(0,n.jsx)("div",{role:e5?"alert":"status",className:(0,C.cn)("mb-2 rounded-md px-2 py-1 text-sm",e5?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground"),children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:e5??Y.notice}),Y.loaded||Y.loading||!Y.error?Y.loaded?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{eu(null),i.dismissFeedback(q)},children:L("close",{ns:"common"})}):null:(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:eg,onClick:()=>void e3(()=>i.loadSource(q)),children:[(0,n.jsx)(lP.A,{}),L("retryDraft")]})]})}):null,a({source:q,cwd:t.cwd,pluginState:eX}),(0,n.jsx)(pA,{model:Z}),(0,n.jsx)(p$,{snapshot:Z.state.snapshot,placement:"aboveEditor"}),ee?(0,n.jsx)("p",{className:"mb-1 px-1 text-xs text-muted-foreground",children:L("nativeUiComposer")}):null,m&&!en?c({source:q,placement:"aboveEditor"}):null,(0,n.jsxs)("form",{"aria-label":eR?L("composerRunning"):eP?L("composerCompleted"):L("composer"),className:pI().inputFrame,"data-composer-mobile":p?"true":"false","data-composer-metadata-row":ec?"true":"false",onSubmit:e=>{e.preventDefault(),tn("auto")},onDragOver:e=>{e.dataTransfer.types.includes("Files")&&e.preventDefault()},onDrop:e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),ts([...e.dataTransfer.files]))},children:[(0,n.jsx)(pj,{open:e9.open,loading:e9.loading,error:e9.error,groups:e9.groups,activeIndex:e9.activeIndex,onActiveIndexChange:e9.setActiveIndex,onSelect:e9.select}),(0,n.jsx)("input",{ref:ei,type:"file",accept:"image/jpeg,image/png,image/webp,image/gif,image/bmp",multiple:!0,className:"hidden",onChange:e=>{e.currentTarget.files&&ts([...e.currentTarget.files]),e.currentTarget.value=""}}),(0,n.jsxs)(nC.MG,{className:"overflow-hidden rounded-xl border-border bg-card shadow-xs transition-[background-color,border-color] duration-150 ease-out has-disabled:bg-card has-disabled:opacity-100 dark:shadow-none motion-reduce:transition-none","aria-busy":eD,children:[eO.length>0?(0,n.jsxs)(nC.Sq,{align:"block-start",className:"pi-desk-chat-scrollbar gap-2 overflow-x-auto px-3 pt-3 pb-1",children:[eO.map(e=>(0,n.jsxs)("div",{className:"relative size-16 shrink-0 overflow-hidden rounded-md border bg-muted",title:`${e.name} \xb7 ${e.width}\xd7${e.height} \xb7 ${pP(e.blob.size)}`,children:[(0,n.jsx)("button",{type:"button",disabled:"ready"!==e.status,"aria-label":L("imagePreview",{name:e.name}),className:"group size-full cursor-zoom-in outline-none disabled:cursor-default focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",onClick:()=>{var t;let s,n;return t=e.localId,void(!((n=(s=eO.filter(e=>"ready"===e.status)).findIndex(e=>e.localId===t))<0)&&eS({index:n,slides:s.map(e=>({src:e.objectUrl,alt:e.name,width:e.width,height:e.height}))}))},children:(0,n.jsx)("img",{src:e.objectUrl,alt:e.name,className:"size-full object-cover transition-transform duration-200 group-hover:scale-105 motion-reduce:transition-none"})}),"optimizing"===e.status?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 grid place-items-center bg-background/85 text-xs",children:L("imageProcessing")}):null,"error"===e.status?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 bg-popover px-1 py-0.5 text-xs text-destructive",children:L("imageFailed")}):null,(0,n.jsx)("button",{type:"button","aria-label":L("imageRemove",{name:e.name}),"aria-disabled":eD,className:"absolute right-0.5 top-0.5 z-10 grid size-6 cursor-pointer place-items-center rounded-md bg-popover text-popover-foreground shadow-sm hover:bg-accent",onClick:()=>{eD||i.removeImage(q,e.localId)},children:(0,n.jsx)(V.A,{className:"size-3"})})]},e.localId)),(0,n.jsxs)("span",{className:"self-end whitespace-nowrap text-xs text-muted-foreground",children:[eO.length,"/10 \xb7 ",pP(eF)]})]}):null,(0,n.jsx)(nC.oR,{value:eT,disabled:!Y.loaded||Y.loading,readOnly:eD,"aria-disabled":eD,"aria-autocomplete":"list","aria-controls":e9.open?m7:void 0,"aria-expanded":e9.open,"aria-activedescendant":e9.open&&e9.commands.length>0?pt(e9.activeIndex):void 0,placeholder:Y.loading?L("draftLoading"):!Y.loaded&&Y.error?L("draftFailed"):L("inputPlaceholder"),className:(0,C.cn)(pI().inputText,"pi-desk-chat-scrollbar max-h-48 min-h-9 overflow-y-auto px-3 pt-3 pb-1"),onChange:e=>i.setText(q,e.currentTarget.value),onClick:e9.reopen,onBlur:e9.dismiss,onCompositionStart:e9.handleCompositionStart,onCompositionEnd:e9.handleCompositionEnd,onKeyDown:e=>{e9.handleKeyDown(e)||"Enter"!==e.key||e.shiftKey||e.nativeEvent.isComposing||null===e.currentTarget.form||(e.preventDefault(),e.currentTarget.form.requestSubmit())},onPaste:e=>{let t=[...e.clipboardData?.items??[]].flatMap(e=>{if("file"!==e.kind)return[];let t=e.getAsFile();return t?[t]:[]});0!==t.length&&(e.preventDefault(),ts(t))}}),(0,n.jsxs)(lK,{ref:ea,className:pI().footer,children:[(0,n.jsxs)(lH,{"data-composer-tools":"primary",className:pI().primaryTools,children:[(0,n.jsxs)(H.rI,{children:[(0,n.jsx)(H.ty,{render:(0,n.jsx)(lG,{tooltip:L("more"),"aria-label":L("moreActions")}),children:(0,n.jsx)(K.A,{className:"size-4"})}),(0,n.jsxs)(H.SQ,{align:"start",side:"top",className:"w-52",children:[(0,n.jsxs)(H.I,{children:[(0,n.jsx)(H.lp,{children:L("session")}),(0,n.jsxs)(H._2,{"aria-label":L("switchBranch"),disabled:!J||!Y.loaded||Y.loading,onClick:()=>M(t.workId),children:[(0,n.jsx)(d4.A,{className:"size-4"}),L("sessionBranch"),(0,n.jsx)("span",{className:"ml-auto text-xs text-muted-foreground",children:L("escapeTwice")})]}),(0,n.jsxs)(H._2,{"aria-label":L("clone"),disabled:!J||S||N,title:0===t.messageCounts.total?L("cloneEmpty"):L("cloneTip"),onClick:E,children:[N?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(mX.A,{className:"size-4"}),N?L("cloning"):L("clone")]}),(0,n.jsxs)(H._2,{"aria-label":L("replaceSession"),"aria-busy":y,disabled:!J||k||y,onClick:j,children:[y?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(mZ.A,{className:"size-4"}),y?L("replacing"):L("replaceSession")]})]}),(0,n.jsx)(H.mB,{}),(0,n.jsxs)(H.I,{children:[(0,n.jsx)(H.lp,{children:L("tools")}),l({source:q,cwd:t.cwd,pluginState:eX}),(0,n.jsxs)(H._2,{"aria-label":L("toolsAndContext",{defaultValue:"工具与上下文"}),disabled:!J||ee,onClick:()=>eb(eM),children:[(0,n.jsx)(nI.A,{className:"size-4"}),L("toolsAndContext",{defaultValue:"工具与上下文"})]}),(0,n.jsxs)(H._2,{"aria-label":L("reloadPi"),disabled:!Y.loaded||Y.loading||!J||eR||eg||ej,title:L("reloadPiTip"),onClick:()=>void tt(!1),children:[ej?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(es.A,{className:"size-4"}),ej?L("reloadingPi"):L("reloadPi")]}),er&&!en?(0,n.jsxs)(H._2,{disabled:!J||eg||ej,onClick:()=>void e3(()=>s.setPresentation(q,"normal")),children:[(0,n.jsx)(nI.A,{className:"size-4"}),L("restorePluginPresentation")]}):null]}),ez.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(H.mB,{}),(0,n.jsxs)(H.I,{children:[(0,n.jsx)(H.lp,{children:L("plugins")}),ez.map(e=>(0,n.jsxs)(H._2,{onClick:()=>ep({pluginName:e.pluginName,contributionName:e.descriptor.contributionName,sourceKey:eM}),children:[(0,n.jsx)(eq,{icon:e.descriptor.icon,className:"size-4"}),(0,n.jsx)("span",{className:"truncate",children:e.descriptor.label})]},`${e.pluginName}:${e.descriptor.contributionName}`))]})]}):null]})]}),(0,n.jsx)(lG,{tooltip:L("addImage"),"aria-label":L("addImage"),disabled:Y.images.length>=10,"aria-disabled":eD||Y.images.length>=10,onClick:()=>{eD||ei.current?.click()},children:(0,n.jsx)(m0.A,{className:"size-4"})}),eZ&&eH?.contextWindow!==null?(0,n.jsx)(pd,{sessionId:t.sessionId,cwd:t.cwd,tokens:eZ.tokens,contextWindow:eZ.contextWindow,contextIgnorePlugin:U.plugins["context-ignore"],ignoreDisabled:!J||e$||eg,ignorePending:ev,compactDisabled:!J||e$||eg,compactPending:ey,onIgnoreContext:e6,onCompactContext:e8}):eH?.contextWindow===null?(0,n.jsx)("span",{className:"px-1 text-xs text-muted-foreground",children:L("modelContextUnknown",{defaultValue:"上下文未知"})}):null]}),(0,n.jsxs)(lH,{"data-composer-tools":"metadata",className:pI().metadataTools,children:[(0,n.jsx)(m8,{workSession:t,runtime:d,active:u,chatReady:J,onOpen:z}),(0,n.jsx)(pS,{modes:x,value:U.capabilityMode,disabled:!J,onChange:e4}),(0,n.jsx)(pb,{source:q,runtime:i,catalog:Y.models,current:eK,label:e1,title:e2,disabled:!J||eR||eD||eg,triggerClassName:pI().modelTrigger,detailsClassName:pI().modelTriggerDetails,onOpenSettings:e},eM)]}),e$&&eD?(0,n.jsx)("span",{ref:eo,className:"min-w-0 truncate px-2 text-xs text-muted-foreground",children:L("preparingContext")}):null,(0,n.jsxs)("div",{ref:el,className:pI().submitTools,children:[(0,n.jsx)(py,{queues:eW,disabled:!J||eg,onRestore:()=>void e3(()=>i.restoreQueue(q),L("queuesRestored"))}),e_?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(lG,{tooltip:L("steerNow"),"aria-label":L("steerNow"),variant:"secondary",disabled:!eQ||eJ,onClick:()=>void tn("auto"),children:(0,n.jsx)(P.A,{className:"size-3.5"})}),(0,n.jsx)(lG,{tooltip:L("sendFollowUp"),"aria-label":L("sendFollowUp"),variant:"outline",disabled:!eQ||eJ,onClick:()=>void tn("follow_up"),children:(0,n.jsx)(m1.A,{className:"size-3.5"})}),(0,n.jsx)(lG,{tooltip:L("stopResponse"),"aria-label":L("stopResponse"),variant:"destructive",disabled:!J||eg,onClick:()=>void e3(()=>i.interrupt(q)),children:(0,n.jsx)(m2.A,{className:"size-3.5 fill-current"})})]}):(0,n.jsx)(I.$,{type:eD?"button":"submit",size:"icon",disabled:!eD&&(!eQ||eJ),"aria-disabled":eD||!eQ||eJ,"aria-busy":eD,"aria-label":eD?L("sending"):J?L("send"):L("synchronizing"),children:eD?(0,n.jsx)(m5.A,{className:"size-4"}):J?(0,n.jsx)(m3.A,{}):(0,n.jsx)(v.A,{className:"size-4 animate-spin"})})]})]})]})]}),m&&!en?c({source:q,placement:"belowEditor"}):null,(0,n.jsx)(p$,{snapshot:Z.state.snapshot,placement:"belowEditor"}),em&&em.sourceKey===eM&&eA?o({pluginName:em.pluginName,descriptor:eA.descriptor,source:q,onClose:eh}):null,ex===eM&&J?(0,n.jsx)(pf,{open:!0,source:q,runtime:i,getContext:f,listCommands:g,nativeUi:Z,nativeBiz:s.nativeUi,commandsDisabled:eR||eD||eg,onOpenChange:e=>eb(e?eM:null),onOpenSettings:e},eM):null,eI?(0,n.jsx)(ny.k,{mode:"modal",open:!0,slides:eI.slides,index:eI.index,ariaLabel:L("imagePreviewPending"),onClose:()=>eS(null),onIndexChange:e=>eS(t=>t?{...t,index:e}:t)}):null,Y.images.length>10?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:L("tooManyImages")}):eG?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:L("imageUnsupported")}):eY>0x1400000?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:L("imagesTooLarge")}):null]})});pD.displayName="L2WorkbenchChatComposer";var pT=s(61600);function pO({svgRef:e}){let t=(0,r.useId)(),s=`${t}-head`,i=`${t}-fur`;return(0,n.jsxs)("svg",{ref:e,viewBox:"0 0 640 560",fill:"none","aria-hidden":"true",className:"pointer-events-none absolute left-1/2 top-1/2 max-w-none -translate-x-1/2 -translate-y-1/2 overflow-visible",style:{width:"144.8%",height:"168.93%"},children:[(0,n.jsxs)("g",{"data-part":"busy-dots",opacity:"0",fill:"currentColor",children:[(0,n.jsx)("circle",{cx:"294",cy:"481",r:"5.5"}),(0,n.jsx)("circle",{cx:"320",cy:"481",r:"5.5"}),(0,n.jsx)("circle",{cx:"346",cy:"481",r:"5.5"})]}),(0,n.jsx)("g",{"data-part":"head",children:(0,n.jsxs)("g",{transform:"translate(64 20)",children:[(0,n.jsxs)("defs",{children:[(0,n.jsx)("path",{id:s,d:"M256 88C190 88 132 109 90 161C62 153 35 171 35 198C35 217 45 231 61 240L54 277C47 316 64 353 104 379C144 406 195 419 256 419C317 419 368 406 408 379C448 353 465 316 458 277L451 240C467 231 477 217 477 198C477 171 450 153 422 161C380 109 322 88 256 88Z"}),(0,n.jsxs)("mask",{id:i,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"512",height:"512",children:[(0,n.jsx)("rect",{width:"512",height:"512",fill:"white"}),(0,n.jsx)("path",{fill:"black",d:"M170 272C201 253 229 240 256 240C283 240 311 253 342 272C383 255 425 261 444 288C472 327 443 369 406 389C367 430 315 448 256 448C197 448 145 430 106 389C69 369 40 327 68 288C87 261 129 255 170 272Z"})]})]}),(0,n.jsx)("use",{href:`#${s}`,fill:"#F3E2C6"}),(0,n.jsx)("use",{href:`#${s}`,fill:"#B87945",mask:`url(#${i})`}),(0,n.jsxs)("g",{fill:"#303030",children:[(0,n.jsx)("path",{d:"M76 180C62 177 53 186 53 198C53 207 57 215 64 220L76 180Z"}),(0,n.jsx)("path",{d:"M436 180C450 177 459 186 459 198C459 207 455 215 448 220L436 180Z"})]}),(0,n.jsxs)("g",{"data-part":"face",children:[["left","right"].map((e,t)=>(0,n.jsxs)("g",{"data-part":`${e}-eye`,transform:`translate(${0===t?158:354} 239)`,children:[(0,n.jsx)("path",{"data-part":`${e}-eye-shape`,fill:"#303030",d:"M-26 0a26 28 0 1 0 52 0a26 28 0 1 0-52 0"}),(0,n.jsx)("circle",{"data-part":`${e}-eye-shine`,cx:"8",cy:"-11",r:"6.5",fill:"#fff"})]},e)),(0,n.jsxs)("g",{"data-part":"cheeks",fill:"#D69973",opacity:"0",children:[(0,n.jsx)("ellipse",{cx:"133",cy:"316",rx:"26",ry:"13"}),(0,n.jsx)("ellipse",{cx:"379",cy:"316",rx:"26",ry:"13"})]}),(0,n.jsx)("path",{fill:"#303030",d:"M219 269C219 254 240 254 256 254C272 254 293 254 293 269C293 282 276 299 256 303C236 299 219 282 219 269Z"}),(0,n.jsxs)("g",{"data-part":"smile",stroke:"#303030",strokeLinecap:"round",strokeWidth:"10",children:[(0,n.jsx)("path",{d:"M256 300C256 317 246 327 232 327C220 327 211 322 207 314"}),(0,n.jsx)("path",{d:"M256 300C256 317 266 327 280 327C292 327 301 322 305 314"})]}),(0,n.jsxs)("g",{"data-part":"mouth",opacity:"0",children:[(0,n.jsx)("ellipse",{cx:"256",cy:"333",rx:"16",ry:"22",fill:"#303030"}),(0,n.jsx)("ellipse",{cx:"256",cy:"347",rx:"9",ry:"5",fill:"#D69973"})]}),(0,n.jsx)("g",{stroke:"#303030",strokeLinecap:"round",strokeWidth:"9",children:(0,n.jsx)("path",{d:"M101 298C116 293 132 292 146 292M110 327C123 318 135 312 148 310M411 298C396 293 380 292 366 292M402 327C389 318 377 312 364 310"})})]})]})}),(0,n.jsxs)("g",{"data-part":"thoughts",fill:"currentColor",opacity:"0",children:[(0,n.jsx)("circle",{cx:"504",cy:"132",r:"5"}),(0,n.jsx)("circle",{cx:"524",cy:"102",r:"8"}),(0,n.jsx)("circle",{cx:"544",cy:"65",r:"11"})]}),(0,n.jsx)("g",{"data-part":"surprise",stroke:"currentColor",strokeWidth:"7",strokeLinecap:"round",opacity:"0",children:(0,n.jsx)("path",{d:"M465 91L479 66M498 113L521 100M443 69L446 44"})}),(0,n.jsxs)("g",{"data-part":"sleep",fill:"currentColor",fontFamily:"Arial,sans-serif",fontWeight:"600",opacity:"0",children:[(0,n.jsx)("text",{x:"479",y:"137",fontSize:"24",children:"z"}),(0,n.jsx)("text",{x:"522",y:"92",fontSize:"32",children:"z"})]}),(0,n.jsxs)("g",{"data-part":"sparkles",opacity:"0",fill:"#BE8656",children:[(0,n.jsx)("path",{d:"M93 158Q96 177 111 180Q96 184 93 202Q90 184 75 180Q90 177 93 158Z"}),(0,n.jsx)("path",{d:"M545 126Q550 151 570 155Q550 159 545 184Q540 159 521 155Q540 151 545 126Z"}),(0,n.jsx)("circle",{cx:"513",cy:"76",r:"5"})]})]})}let pL={x:0,y:0,angle:0,sx:1,sy:1,gazeX:0,gazeY:0,eye:1,wink:0,smile:0,sleepy:0,mouth:0,blush:0,thought:0,surprise:0,sleep:0,sparkle:0,busy:0,follow:1},pF=Object.keys(pL),pB={idle:.46,hello:.36,point:.45,think:.5,busy:.4,happy:.35,surprise:.2,sleep:.72};function pq(e){return Math.min(1,Math.max(0,e))}function p_(e){let t=pq(e);return t*t*t*(t*(6*t-15)+10)}function pW(e,t){let s={...pL};switch(e){case"hello":{let e=t%3.5,n=Math.exp(-Math.pow((e-.7)/.35,2));s.y=6*n,s.angle=-3+3*n,s.wink=.94*Math.exp(-Math.pow((e-1.2)/.23,2)),s.sx=1+.012*Math.sin(3.2*t),s.sy=1-.014*Math.sin(3.2*t),s.blush=.23;break}case"point":s.x=-9,s.y=-5,s.angle=-9,s.gazeX=-17,s.gazeY=-16,s.sx=1.018,s.sy=.987,s.follow=0;break;case"think":s.angle=8+2*Math.sin(1.6*t),s.gazeX=12+5*Math.sin(1.8*t),s.gazeY=-13,s.eye=.85,s.thought=1,s.follow=.1;break;case"busy":{let e=t%3.6,n=p_(e/1.45),r=p_((e-2.15)/.65),i=Math.exp(-Math.pow((e-1.9)/.22,2));s.gazeX=-11+22*n-22*r,s.gazeY=8+2*i,s.angle=.1*s.gazeX,s.y=3+4*i,s.eye=.9+.05*i,s.sy=1-.006*i,s.busy=1,s.follow=0;break}case"happy":{let e=(1-Math.cos(5.5*t))/2;s.y=-(14*e),s.sx=1.025-.035*e,s.sy=.975+.045*e,s.angle=4*Math.sin(2.5*t),s.smile=1,s.blush=.6,s.sparkle=1,s.follow=.15;break}case"surprise":s.y=-9-6*Math.exp(-(1.5*t)),s.eye=1.2,s.mouth=1,s.sx=.96,s.sy=1.045,s.surprise=1,s.follow=.25;break;case"sleep":s.angle=11+2*Math.sin(1.25*t),s.y=6+3*Math.sin(1.25*t),s.sy=.965+.01*Math.sin(1.25*t),s.sleepy=1,s.sleep=1,s.follow=0;break;default:s.gazeX=4*Math.sin(.8*t),s.gazeY=2*Math.sin(.67*t)}return s}class pY{setState(e,t){if(e===this.state)return;let s=this.transition&&t-this.transition.at<pB[this.state];this.transition=s?{pose:this.sample(t),at:t}:{state:this.state,started:this.started,at:t},this.state=e,this.started=t}sample(e,t=!1){let s=pW(this.state,t?1.2:Math.max(0,e-this.started));if(!this.transition||t)return s;let n=pq((e-this.transition.at)/pB[this.state]);if(1===n)return s;let r="pose"in this.transition?this.transition.pose:pW(this.transition.state,Math.max(0,e-this.transition.started)),i=1-(1-n)**5;for(let e of pF)s[e]=r[e]+(s[e]-r[e])*i;return s}constructor(){this.state="idle",this.started=0,this.transition=null}}let pV=["head","face","left-eye","right-eye","left-eye-shape","right-eye-shape","left-eye-shine","right-eye-shine","smile","mouth","cheeks","thoughts","surprise","sleep","sparkles","busy-dots"];function pU(e,t=0,s=1){return Math.min(s,Math.max(t,e))}function pK(e){return e.toFixed(3)}function pH({state:e,active:t=!0,size:s=100,className:i}){let a=(0,r.useRef)(null),l=(0,r.useRef)(null);return(0,r.useEffect)(()=>{let e=function(e){let t=Object.fromEntries(pV.map(t=>[t,e.querySelector(`[data-part="${t}"]`)])),s=e.parentElement,n=new pY,r=matchMedia("(prefers-reduced-motion: reduce)"),i=!0,a=!1,l=0,o=null,c=0,d=-10,u=1.7,m={x:0,y:0},p={x:0,y:0};function h(e,s){t[e].setAttribute("opacity",pK(s))}function g(e,s){t[e].setAttribute("transform",s)}function f(){let e=n.sample(c,r.matches),s=r.matches?1.2:c,i=r.matches?0:.005*Math.sin(1.7*c),a=e.gazeX+(r.matches?0:m.x*e.follow),l=e.gazeY+(r.matches?0:m.y*e.follow);g("head",`translate(${pK(e.x)} ${pK(e.y)}) translate(320 274) rotate(${pK(e.angle+(r.matches?0:m.x*e.follow*.12))}) scale(${pK(e.sx)} ${pK(e.sy+i)}) translate(-320 -274)`),g("face",`translate(${pK(.16*a)} ${pK(.12*l)})`);let o=r.matches?-1:(c-d)/.19,u=o>=0&&o<=1?.07+.93*Math.abs(2*o-1):1;for(let[s,n]of[["left",158],["right",354]]){g(`${s}-eye`,`translate(${pK(n+a)} ${pK(239+l)})`);let r=1-pU(e.smile+e.sleepy),i=(3.5+(28*e.eye-3.5)*r)*u*("left"===s?1-e.wink:1);t[`${s}-eye-shape`].setAttribute("d",function(e,t,s){let n=pK(e),r=pK(t+s),i=pK(-t+s),a=pK(.5523*e),l=pK(-(.5523*t)+s),o=pK(.5523*t+s);return`M-${n} 0C-${n} ${l} -${a} ${i} 0 ${i}C${a} ${i} ${n} ${l} ${n} 0C${n} ${o} ${a} ${r} 0 ${r}C-${a} ${r} -${n} ${o} -${n} 0Z`}(22+4*r,i,(-13*e.smile+8*e.sleepy)*u)),h(`${s}-eye-shine`,r*pU((i-8)/16))}h("smile",1-e.mouth),h("mouth",e.mouth),h("cheeks",e.blush),h("thoughts",e.thought),Array.from(t.thoughts.children).forEach((e,t)=>{e.setAttribute("opacity",pK(.25+.75*(1+Math.sin(2.8*s-.9*t))/2)),e.setAttribute("transform",`translate(0 ${pK(3*Math.sin(2*s-t))})`)}),h("surprise",e.surprise),h("sleep",e.sleep),Array.from(t.sleep.children).forEach((e,t)=>{let n=(.4*s+.45*t)%1;e.setAttribute("transform",`translate(${pK(8*n)} ${pK(-(20*n))})`),e.setAttribute("opacity",pK(Math.sin(n*Math.PI)))}),h("sparkles",e.sparkle*(.55+.45*(1+Math.sin(3*s))/2)),g("sparkles",`translate(0 ${pK(5*Math.sin(2*s))})`),h("busy-dots",e.busy),Array.from(t["busy-dots"].children).forEach((e,t)=>{let n=Math.sin(Math.PI*pU(((s-.18*t)%1.4+1.4)%1.4/.55));e.setAttribute("opacity",pK(.26+.65*n)),e.setAttribute("transform",`translate(0 ${pK(-4*n)})`)})}function x(){return i&&a&&!document.hidden&&!r.matches}function b(e){if(l=0,!x())return;let t=null===o?0:Math.min((e-o)/1e3,.05);o=e,(c+=t)>=u&&(d=c,u=c+2.4+2.8*Math.random());let s=1-Math.exp(-(9*t));m.x+=(p.x-m.x)*s,m.y+=(p.y-m.y)*s,f(),l=requestAnimationFrame(b)}function v(){cancelAnimationFrame(l),l=0,o=null,f(),x()&&(l=requestAnimationFrame(b))}function w(e){if("mouse"!==e.pointerType||!x())return;let t=s.getBoundingClientRect();p.x=pU((e.clientX-t.left-t.width/2)/Math.max(t.width,window.innerWidth/2)*24,-18,18),p.y=pU((e.clientY-t.top-t.height/2)/Math.max(t.height,window.innerHeight/2)*20,-14,12)}function y(){p.x=0,p.y=0}let k=new IntersectionObserver(([e])=>{a=e.isIntersecting,v()});return k.observe(s),document.addEventListener("visibilitychange",v),r.addEventListener("change",v),document.addEventListener("pointermove",w,{passive:!0}),document.documentElement.addEventListener("pointerleave",y),window.addEventListener("blur",y),f(),{setState(e){n.setState(e,c),"point"!==e&&"think"!==e||r.matches||(d=c),f()},setActive(e){i=e,v()},dispose(){cancelAnimationFrame(l),k.disconnect(),document.removeEventListener("visibilitychange",v),r.removeEventListener("change",v),document.removeEventListener("pointermove",w),document.documentElement.removeEventListener("pointerleave",y),window.removeEventListener("blur",y)}}}(a.current);return l.current=e,()=>{e.dispose(),l.current=null}},[]),(0,r.useEffect)(()=>{l.current?.setState(e)},[e]),(0,r.useEffect)(()=>{l.current?.setActive(t)},[t]),(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("relative block shrink-0 text-muted-foreground",i),style:{width:s,height:.75*s},children:(0,n.jsx)(pO,{svgRef:a})})}let pG=Object.keys(d$.R.en).filter(e=>e.startsWith("emptyQuip")),pJ=null;function pQ(){let{t:e}=(0,b.Bd)("workbench"),t=(0,mB.tF)(),s=!0===(0,pT.D)(),i=(0,mq.I)(),{state:a,textKey:l}=function(e){let[t,s]=(0,r.useState)(null),[n,i]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{let e=requestAnimationFrame(()=>{let e,t;return s((e=Math.floor(Math.random()*(null===pJ?pG.length:pG.length-1)),null!==pJ&&e>=pJ&&(e+=1),pJ=e,"emptyQuip16"===(t=pG[e])||"emptyQuip10"===t?{quip:t,waiting:"sleep",reaction:"surprise",recover:"hello",reply:"emptyWakeReply"}:"emptyQuip1"===t||"emptyQuip14"===t?{quip:t,waiting:"sleep",reaction:"hello",recover:"idle",reply:"emptyFishReply"}:"emptyQuip12"===t||"emptyQuip15"===t?{quip:t,waiting:"think",reaction:"surprise",recover:"idle",reply:"emptyCuriousReply"}:{quip:t,waiting:"idle",reaction:"happy",recover:"hello",reply:"emptyPartnerReply"}))});return()=>cancelAnimationFrame(e)},[]),(0,r.useEffect)(()=>{let t=window.setTimeout(()=>i(!e),320*!e);return()=>window.clearTimeout(t)},[e]),{state:t?e?t.waiting:n?t.recover:t.reaction:"sleep",textKey:t?e?t.quip:t.reply:null}}(t);return t||s&&!i?(0,n.jsxs)(oU.PY1.div,{"data-testid":"workbench-empty-session","data-otter-state":a,"data-leaving":t?void 0:"true",initial:!1,animate:{opacity:1,y:0},exit:{opacity:0,y:-4,transition:{delay:.55,duration:1.15,ease:"easeInOut"}},className:"flex max-w-sm flex-col items-center gap-5",children:[(0,n.jsx)(pH,{state:a,size:100}),(0,n.jsx)("p",{className:"min-h-6 text-sm leading-6 text-muted-foreground",children:l?e(l):null})]}):null}function pX({active:e,ready:t,empty:s,hasUserMessage:r}){return(0,n.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center px-6 py-8 text-center",children:[(0,n.jsx)(mF.N,{initial:!1,custom:e&&t&&r,children:e&&t&&s?(0,n.jsx)(pQ,{},"welcome"):null}),e&&!t&&s?(0,n.jsx)(mT,{variant:"loading"}):null]})}function pZ({active:e,turns:t,window:s}){return e?(0,n.jsx)(oz,{turns:t,window:s}):null}function p0(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function p1(){return"visible"===document.visibilityState}function p2(){return!0}function p5(e,t){e.scrollTop=t.scrollTop}function p3(e){let t=e.getBoundingClientRect().top,s=null;for(let n of e.querySelectorAll("[data-chat-scroll-anchor]")){let e=n.dataset.chatScrollAnchor;if(!e)continue;let r=n.getBoundingClientRect().top-t,i=Math.abs(r);(!s||i<s.distance)&&(s={messageId:e,offset:r,distance:i})}return s?{messageId:s.messageId,offset:s.offset}:null}function p4({active:e,visible:t=!0,running:s,ready:n,containsTail:i,latestUserAnchor:a,entrySnapshot:l,onResetToTail:o,onSaveSnapshot:c,onClearSnapshot:d}){let{isAtBottom:u,scrollRef:m,scrollToBottom:p,state:h,stopScroll:g}=(0,lT.B)(),f=(0,r.useSyncExternalStore)(p0,p1,p2),x=(0,r.useRef)(f),b=(0,r.useRef)(!1),v=(0,r.useRef)(!1),w=(0,r.useRef)(null),y=(0,r.useRef)(null),k=(0,r.useRef)(s?l:null),j=(0,r.useRef)(null);return(0,r.useLayoutEffect)(()=>{let e=m.current;if(!e||!t||!u)return;let s=e.style.overflowAnchor;return e.style.overflowAnchor="none",oc("viewport:anchor-lock",e),()=>{e.style.overflowAnchor=s}},[u,m,t]),(0,r.useLayoutEffect)(()=>{let n=m.current;if(!n)return;if(!e&&!s){v.current=!1,k.current=null,y.current=null,j.current=null,g(),oc("viewport:leave-ended",n);return}if(!t){y.current=null,v.current&&null===j.current&&(j.current=!e&&i&&h.isAtBottom?"follow":{snapshot:p3(n),scrollTop:n.scrollTop},oc("viewport:suspend",n,{follow:"follow"===j.current})),g();return}let r=j.current;if(null!==r){if("follow"===r)d(),n.scrollTop=Math.max(0,n.scrollHeight-n.clientHeight),p5(h,n),p({animation:"instant"}),oc("viewport:restore-follow",n);else{g();let{snapshot:e}=r,t=e?od(n,"data-chat-scroll-anchor",e.messageId):null;e&&t?ox(n,t,e.offset,i):n.scrollTop=r.scrollTop,p5(h,n),oc("viewport:restore-reading",n,{running:s,snapshot:e})}v.current=!0,w.current=a,j.current=null}},[e,i,a,d,s,m,p,h,g,t]),(0,r.useLayoutEffect)(()=>{let e=f&&!x.current;if(x.current=f,e&&t&&!s&&(v.current=!1,k.current=null,y.current=null),!n||!t||!f)return;s||d();let r=!v.current,l=null!==a&&a!==w.current,c=l?null:y.current;if(!r&&!l&&!c)return;if(r&&!s&&!i)return void o();let u=m.current;l&&(y.current=null,d(),u&&og(u));let j=null,N=null,I=null;b.current=!0;let S=()=>{let e=m.current;if(!e){b.current=!1;return}oc("viewport:initialize:start",e,{initializing:r,running:s,containsTail:i,latestUserAnchor:a});let t=null,n=12,l=c?c.anchor:r&&s?k.current:null;if(l){let s=od(e,"data-chat-scroll-anchor",l.messageId);s&&(t=s,n=l.offset)}!t&&a&&(t=od(e,"data-chat-scroll-anchor",a)),t??=od(e,"data-chat-user-message",void 0);let o=c?.follow??(null!==t&&null===l&&(s||!r)),d=c?.follow??(r&&s&&null===l),u=t;if(g(),u?ox(e,u,n,i):og(e),(d||!u)&&(e.scrollTop=Math.max(0,h.calculatedTargetScrollTop)),p5(h,e),(o||!u)&&p({animation:"instant"}),oc("viewport:initialize:positioned",e,{initializing:r,running:s,target:t?.dataset.chatScrollAnchor??null,followAfterPosition:o,enterRunningAtBottom:d}),v.current=!0,w.current=a,k.current=null,r||c){let s=t?.dataset.chatScrollAnchor;y.current={anchor:s?{messageId:s,offset:n}:null,follow:o||null===t};let r=new ResizeObserver(()=>{o||!u?(of(e),e.scrollTop=Math.max(0,h.calculatedTargetScrollTop)):(h.isAtBottom&&g(),ox(e,u,n,i)),p5(h,e)});r.observe(e),e.firstElementChild&&r.observe(e.firstElementChild);let a=e.parentElement,l=["wheel","touchstart","pointerdown","keydown","click"],c=e=>{for(let e of(r.disconnect(),l))a.removeEventListener(e,c,!0);e&&(y.current=null),I=null,b.current=!1};for(let e of l)a.addEventListener(e,c,{passive:!0,capture:!0});I=c}N=window.requestAnimationFrame(()=>{b.current=null!==I})};return m.current?S():j=window.requestAnimationFrame(S),()=>{null!==j&&window.cancelAnimationFrame(j),null!==N&&window.cancelAnimationFrame(N),I?.(),b.current=!1}},[i,a,d,o,f,n,s,m,p,h,g,t]),(0,r.useEffect)(()=>{let e=m.current;if(!e||!t)return;let s=()=>{if(oc("viewport:scroll",e,{positioning:b.current,isAtBottom:h.isAtBottom,escapedFromLock:h.escapedFromLock,resizeDifference:h.resizeDifference}),b.current||h.isAtBottom)return;let t=e.querySelector("[data-chat-tail-space]");!t||t.dataset.chatTailAnchor!==a||e.scrollHeight-e.scrollTop-e.clientHeight<=2&&(oc("viewport:resume-follow",e,{isAtBottom:h.isAtBottom,escapedFromLock:h.escapedFromLock}),d(),p({animation:"instant"}))};return e.addEventListener("scroll",s,{passive:!0}),()=>e.removeEventListener("scroll",s)},[a,d,m,p,h,t]),(0,r.useLayoutEffect)(()=>{if(!s||!t)return;let e=m.current;if(!e)return;let n=()=>{if(b.current)return;if(i&&h.isAtBottom)return void d();let t=p3(e);t?c(t):d()};return e.addEventListener("scroll",n,{passive:!0}),()=>{e.removeEventListener("scroll",n),n()}},[i,d,c,s,m,h,t]),null}let p6=(0,r.memo)(function({active:e,visible:t,workSession:s,chatRuntime:i,inputRuntime:a,onPreviewFile:l,onResend:o,resendDisabled:c}){let{t:d}=(0,b.Bd)("workbench"),u=(0,r.useMemo)(()=>uf.Pi.parse({workId:s.workId,sessionId:s.sessionId,branchId:s.branchId}),[s.branchId,s.sessionId,s.workId]),m=(0,r.useMemo)(()=>i.getViewportSnapshot(u),[i,u]),p=(0,r.useCallback)(()=>i.getSourceState(u),[i,u]),h=(0,r.useSyncExternalStore)(i.subscribe,p,p),g="main_running"===s.status||"background_running"===s.status,f=(0,r.useMemo)(()=>oi({messages:h.messages,temporaryMessages:h.temporaryMessages},g),[g,h.messages,h.temporaryMessages]),x=h.messages.length>0||h.temporaryMessages.length>0,v=h.messages.some(e=>"user"===e.fixed.type)||h.temporaryMessages.some(e=>"user"===e.fixed.type),w=g||h.temporaryMessages.length>0,y=f.findLast(e=>null!==e.user)??null,k=y?.user??null,j=k?`${k.identity}:user`:null,N=(0,r.useCallback)(async e=>e.durable?void 0!==e.detail?e.detail:i.loadMessageDetail(u,e.durable.location.index,e.durable.location.entryId):null,[i,u]),I=(0,r.useCallback)((e,t)=>a.acquireMessageImage({source:u,tempId:e.tempId,entryId:e.durable?.location.entryId??null,imageIndex:t}),[a,u]),S=(0,r.useCallback)(e=>l(u,e),[l,u]),C=(0,r.useCallback)(e=>o(u,e),[o,u]),E=(0,r.useCallback)(e=>{i.saveViewportSnapshot(u,e)},[i,u]),M=(0,r.useCallback)(()=>{i.clearViewportSnapshot(u)},[i,u]),z=(0,r.useCallback)(()=>i.setPresentation(u,"basic"),[i,u]);return(0,n.jsx)(o$,{basic:"basic"===h.runtime.presentationMode,onRecover:z,children:(0,n.jsxs)(lO,{className:"min-h-0",initial:!1,resize:"instant","aria-label":d("chatMessages",{name:s.sessionTitle??s.projectName}),children:[(0,n.jsx)(oI,{turns:f,active:t,focusTurnIdentity:y?.identity??null,initialAnchor:w?m?.messageId??null:null,children:r=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ci,{children:(0,n.jsx)(lL,{scrollClassName:"pi-desk-chat-scrollbar pi-desk-chat-conversation-scroll overflow-auto",className:"mx-auto min-h-full w-full max-w-3xl gap-6 px-3 pt-3 pb-4 sm:px-5",children:r.visibleTurns.map((e,t)=>{let i=r.startIndex+t;return(0,n.jsx)(cU,{turn:e,cwd:s.cwd,logicalTail:r.containsTail&&i===f.length-1,onLoadDetail:N,onAcquireImage:I,onPreviewFile:S,onResend:C,resendDisabled:c||"ready"!==h.syncStatus},e.identity)})})}),(0,n.jsx)(p4,{active:e,visible:t,running:w,ready:x,containsTail:r.containsTail,latestUserAnchor:j,entrySnapshot:m,onResetToTail:r.resetToTail,onSaveSnapshot:E,onClearSnapshot:M},`viewport:${u.sessionId}:${u.branchId}`),(0,n.jsx)(ob,{active:t}),(0,n.jsx)(pZ,{active:t,turns:f,window:r},`navigation:${u.sessionId}:${u.branchId}`)]})},`window:${u.sessionId}:${u.branchId}`),(0,n.jsx)(pX,{active:t,ready:"ready"===h.syncStatus,empty:!x,hasUserMessage:v})]})})});p6.displayName="L2WorkbenchChatView";var p8=s(78653),p7=s.n(p8);function p9({error:e,copied:t,reloading:s,canReload:r,onCopy:i,onReload:a}){let{t:l}=(0,b.Bd)("workbench");return(0,n.jsxs)(eW.AM,{children:[(0,n.jsxs)(eW.Wv,{openOnHover:!0,delay:150,closeDelay:150,render:(0,n.jsx)(I.$,{variant:"ghost",size:"sm","aria-label":l("initializationDegraded"),title:l("initializationDegraded"),className:(0,C.cn)(p7().headerAction,"text-xs text-destructive hover:text-destructive")}),children:[(0,n.jsx)(Y.A,{className:(0,C.cn)(p7().headerActionIcon,"size-4"),"aria-hidden":"true"}),(0,n.jsx)("span",{className:p7().headerActionLabel,children:l("initializationDegraded")})]}),(0,n.jsxs)(eW.hl,{align:"end",alignOffset:8,className:"max-h-[min(28rem,var(--available-height))] w-[28rem] gap-0 overflow-hidden p-0",initialFocus:e=>"keyboard"===e,children:[(0,n.jsx)(eW.eO,{className:"shrink-0 border-b px-3 py-2",children:l("initializationDetails")}),(0,n.jsx)("pre",{className:"min-h-0 overflow-auto overscroll-contain whitespace-pre-wrap break-words p-3 font-mono text-sm leading-[1.6]","aria-label":l("initializationDetails"),children:e}),(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t px-3 py-2",children:[(0,n.jsxs)(I.$,{variant:"outline",size:"sm",onClick:i,children:[t?(0,n.jsx)(ep.A,{}):(0,n.jsx)(ee.A,{}),l(t?"copied":"copyInitializationError")]}),(0,n.jsxs)(I.$,{size:"sm",disabled:!r,onClick:a,children:[s?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(es.A,{}),l(s?"reloadingPi":"reloadPi")]})]})]})]})}var he=s(4780),ht=s.n(he);function hs({sidebarOpen:e,onOpen:t}){let{t:s}=(0,b.Bd)("workbench"),r=(0,mq.I)();return(0,n.jsxs)("div",{"data-testid":"workbench-session-guide",className:ht().guide,children:[(0,n.jsx)(pH,{state:e?"idle":"point",size:120,className:ht().otter}),e?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("svg",{"data-testid":"workbench-session-guide-arrow","aria-hidden":"true",viewBox:"0 0 36 32",className:ht().arrow,fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)(oU.PY1.path,{d:"M30 26Q10 25 9 10",initial:!r&&{pathLength:0},animate:{pathLength:1},transition:{duration:.7*!r,ease:"easeOut"},opacity:".65"}),(0,n.jsx)("path",{d:"M4 16L9 10L15 15",opacity:".65"})]}),(0,n.jsx)(I.$,{variant:"ghost","aria-label":s("showSessionMenu"),onClick:t,className:"absolute inset-0 size-full p-0 hover:bg-foreground/5"})]})]})}var hn=s(45087);let hr=r.createContext(null);function hi(){let e=r.useContext(hr);if(!e)throw Error("useCarousel must be used within a <Carousel />");return e}function ha({orientation:e="horizontal",opts:t,setApi:s,plugins:i,className:a,children:l,...o}){let[c,d]=(0,hn.A)({...t,axis:"horizontal"===e?"x":"y"},i),[u,m]=r.useState(!1),[p,h]=r.useState(!1),g=r.useCallback(e=>{e&&(m(e.canScrollPrev()),h(e.canScrollNext()))},[]),f=r.useCallback(()=>{d?.scrollPrev()},[d]),x=r.useCallback(()=>{d?.scrollNext()},[d]),b=r.useCallback(e=>{"ArrowLeft"===e.key?(e.preventDefault(),f()):"ArrowRight"===e.key&&(e.preventDefault(),x())},[f,x]);return r.useEffect(()=>{d&&s&&s(d)},[d,s]),r.useEffect(()=>{if(!d)return;let e=!1;return queueMicrotask(()=>{e||g(d)}),d.on("reInit",g),d.on("select",g),()=>{e=!0,d.off("reInit",g),d.off("select",g)}},[d,g]),(0,n.jsx)(hr.Provider,{value:{carouselRef:c,api:d,opts:t,orientation:e||(t?.axis==="y"?"vertical":"horizontal"),scrollPrev:f,scrollNext:x,canScrollPrev:u,canScrollNext:p},children:(0,n.jsx)("div",{onKeyDownCapture:b,className:(0,C.cn)("relative",a),role:"region","aria-roledescription":"carousel","data-slot":"carousel",...o,children:l})})}function hl({className:e,...t}){let{carouselRef:s,orientation:r}=hi();return(0,n.jsx)("div",{ref:s,className:"overflow-hidden","data-slot":"carousel-content",children:(0,n.jsx)("div",{className:(0,C.cn)("flex","horizontal"===r?"-ml-4":"-mt-4 flex-col",e),...t})})}function ho({className:e,...t}){let{orientation:s}=hi();return(0,n.jsx)("div",{role:"group","aria-roledescription":"slide","data-slot":"carousel-item",className:(0,C.cn)("min-w-0 shrink-0 grow-0 basis-full","horizontal"===s?"pl-4":"pt-4",e),...t})}function hc(e){let t=e.scrollWidth-e.clientWidth;return t<=1||!["auto","scroll"].includes(getComputedStyle(e).overflowX)?null:{left:e.scrollLeft,maximum:t}}function hd(e){return e.sessionTitle?`${e.projectName} \xb7 ${e.sessionTitle}`:e.projectName}function hu({items:e,activeWorkId:t,onActiveWorkSessionChange:s,children:i}){let a,l,{t:o}=(0,b.Bd)("workbench"),c=(0,mq.I)(),d=r.Children.toArray(i),u=e[0]?.workId??null,m=e.some(e=>e.workId===t)?t:u,[p]=(0,r.useState)(()=>Math.max(0,e.findIndex(e=>e.workId===m))),h=(0,r.useRef)(null),g=(0,r.useRef)(!1),[f,x]=(0,r.useState)(),[v,w]=(0,r.useState)({index:p,position:p,visible:!1}),y=(0,r.useCallback)(()=>{null!==h.current&&(window.clearTimeout(h.current),h.current=null)},[]),k=(0,r.useCallback)(()=>{y(),h.current=window.setTimeout(()=>{h.current=null,w(e=>e.visible?{...e,visible:!1}:e)},900)},[y]),j=(0,r.useCallback)((t,s)=>{var n;let r=(n=t.scrollProgress()*(e.length-1),Math.max(0,Math.min(e.length-1,n))),i=Math.round(r);w(e=>{let t=s??e.visible;return e.index===i&&.001>Math.abs(e.position-r)&&e.visible===t?e:{index:i,position:r,visible:t}})},[e.length]),N=(0,r.useCallback)(e=>{j(e,!0),k()},[k,j]),I=(a=(0,r.useRef)(null),l=(0,r.useCallback)((e,t)=>{a.current=null;let s=t.target;if(!(s instanceof Element))return!0;if(s.closest('[data-carousel-swipe-lock],[data-testid="file-workspace"],[data-streamdown="mermaid-block"],[data-slot="plugin-scrollbar"],[data-slot="scroll-area-scrollbar"],.monaco-editor,[contenteditable="true"],[role="application"],[role="dialog"],[role="menu"],input,textarea,select,a,summary,img'))return!1;let n=s.closest("button");if(n&&(!("touches"in t)||!n.matches('[data-slot="collapsible-trigger"]')||!n.closest('[data-chat-scroll-anchor$=":tool"]')))return!1;let r=function(e){let t=[];for(let s=e;s&&!s.matches('[data-slot="carousel-item"]');s=s.parentElement){if(!(s instanceof HTMLElement))continue;let n=hc(s);if(n&&t.push(n),s.matches('[data-streamdown="code-block"],[data-streamdown="table-wrapper"],[data-pi-desk-scroll],[data-slot="l4-scroll-area"]'))for(let n of s.children){if(!(n instanceof HTMLElement)||n.contains(e))continue;let s=hc(n);s&&t.push(s)}}return t}(s);if(!("touches"in t))return!r.length&&!s.closest('pre,table,[data-streamdown="code-block"]');if(1!==t.touches.length)return!1;if(!r.length)return!0;let i=t.touches[0];return a.current={x:i.clientX,y:i.clientY,scrolls:r,owner:"pending"},!1},[]),(0,r.useEffect)(()=>{if(!f)return;let e=f.rootNode(),t=()=>{a.current=null},s=e=>{let s=a.current;if(!s)return;if(1!==e.touches.length)return void t();let n=e.touches[0],r=n.clientX-s.x,i=n.clientY-s.y;if("pending"===s.owner){if(6>Math.max(Math.abs(r),Math.abs(i)))return;let e=s.scrolls.some(e=>r<0?e.left<e.maximum-1:e.left>1);s.owner=Math.abs(i)>=Math.abs(r)||e?"content":r<0?"next":"previous"}if("content"!==s.owner){if(!e.cancelable){s.owner="content";return}e.preventDefault()}},n=s=>{let n=a.current;if(t(),!n||"pending"===n.owner||"content"===n.owner)return;let r=s.changedTouches[0],i=r.clientX-n.x,l=r.clientY-n.y,o=Math.max(50,Math.min(225,.2*e.clientWidth));("next"===n.owner?-i:i)<o||Math.abs(l)>=Math.abs(i)||("next"===n.owner?f.canScrollNext():f.canScrollPrev())&&(N(f),"next"===n.owner?f.scrollNext():f.scrollPrev())};return e.addEventListener("touchmove",s,{passive:!1}),e.addEventListener("touchend",n),e.addEventListener("touchcancel",t),f.on("reInit",t),()=>{t(),e.removeEventListener("touchmove",s),e.removeEventListener("touchend",n),e.removeEventListener("touchcancel",t),f.off("reInit",t)}},[f,N]),l),S=(0,r.useMemo)(()=>({align:"start",containScroll:"trimSnaps",dragFree:!1,loop:!1,skipSnaps:!1,duration:25*!c,startIndex:p,watchDrag:I}),[p,c,I]);if((0,r.useEffect)(()=>{m&&m!==t&&s(m)},[t,m,s]),(0,r.useLayoutEffect)(()=>{if(!f||!m)return;let t=e.findIndex(e=>e.workId===m);t<0||f.selectedScrollSnap()===t||f.scrollTo(t,!0)},[f,m,e]),(0,r.useEffect)(()=>{if(!f)return;let n=()=>{g.current=!0},r=()=>{g.current=!1,k()},i=e=>{if(g.current){y(),j(e,!0);return}j(e)},a=n=>{let r=e[n.selectedScrollSnap()];r&&r.workId!==t&&s(r.workId),j(n)},l=e=>{j(e),k()},o=e=>{j(e,!1)};return f.on("pointerDown",n),f.on("pointerUp",r),f.on("scroll",i),f.on("select",a),f.on("settle",l),f.on("reInit",o),()=>{g.current=!1,f.off("pointerDown",n),f.off("pointerUp",r),f.off("scroll",i),f.off("select",a),f.off("settle",l),f.off("reInit",o)}},[t,f,y,e,s,k,j]),(0,r.useEffect)(()=>y,[y]),e.length<=1)return(0,n.jsx)("div",{className:"size-full min-h-0 min-w-0 overflow-hidden",children:d[0]??null});let E=e[v.index]??e[0],M=`${100/e.length}%`,z=`translate3d(${100*v.position}%, 0, 0)`;return(0,n.jsxs)(ha,{opts:S,setApi:x,"aria-label":o("sessionWindows"),onKeyDownCapture:()=>void 0,className:"size-full min-h-0 min-w-0 [&_[data-slot=carousel-content]]:h-full [&_[data-slot=carousel-content]]:touch-auto",children:[(0,n.jsx)(hl,{className:"ml-0 h-full",children:e.map((t,s)=>(0,n.jsx)(ho,{"aria-label":`${s+1} / ${e.length},${hd(t)}`,className:"h-full pl-0",children:d[s]??null},t.workId))}),(0,n.jsx)("div",{"aria-hidden":"true","data-testid":"mobile-work-session-position",className:(0,C.cn)("pointer-events-none absolute top-16 left-1/2 z-30 w-[min(82vw,20rem)] -translate-x-1/2 transition-[opacity,transform] duration-150 ease-out motion-reduce:transition-none",v.visible?"translate-y-0 opacity-100":"-translate-y-2 opacity-0"),children:(0,n.jsxs)("div",{className:"rounded-xl border bg-popover px-3 py-2 text-popover-foreground shadow-lg",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-xs",children:[(0,n.jsx)("span",{className:"shrink-0 text-muted-foreground",children:o(E.fixed?"fixedSession":"primarySession")}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:hd(E)}),(0,n.jsxs)("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:[v.index+1," / ",e.length]})]}),(0,n.jsx)("div",{className:"mt-2 h-1 overflow-hidden rounded-full bg-muted",children:(0,n.jsx)("div",{className:"h-full rounded-full bg-foreground",style:{width:M,transform:z}})})]})})]})}function hm(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function hp({sidebarOpen:e,onToggle:t}){let{t:s}=(0,b.Bd)("workbench");return(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":s(e?"hideSessionMenu":"showSessionMenu"),className:(0,C.cn)((0,I.r)({variant:"ghost",size:"icon"}),"text-muted-foreground"),children:e?(0,n.jsx)(sG.A,{className:"size-4"}):(0,n.jsx)(mO.A,{className:"size-5"})})}let hh=(0,r.memo)(function({onOpenSettings:e,workSession:t,fixed:s,focused:i,contentActive:a,composerActive:l,sidebarOpen:o,replacingWithEmpty:c,replacementDisabled:d,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,renderPluginSessionHeader:x,gitRuntime:v,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,branchPicker:S,branchPending:E,onResendMessage:M,mobile:z,fileRuntime:A,onOpenFileSidebar:$,onPreviewFile:R,onAcknowledgeCompleted:P,onFocusWorkSession:D,onReplaceWithEmptyWorkSession:T,onOpenBranchPicker:O,onOpenGitBranchPicker:L,onCloseBranchPicker:F,onRetryBranchPicker:B,onSelectBranchEntry:q,onBranchAction:_,onConfirmRunningBranch:W,onCancelRunningBranch:Y,onCloneWorkSession:U,onUnpinWorkSession:K,onToggleSidebar:H}){let{t:G}=(0,b.Bd)("workbench"),J=(0,r.useRef)(null),Q=function(e,t){let{t:s}=(0,b.Bd)("workbench"),n=(0,X.G)(),i=(0,r.useMemo)(()=>({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId}),[e.workId,e.sessionId,e.branchId]),a=(0,r.useCallback)(()=>t.getSourceState(i).runtime,[t,i]),l=(0,r.useSyncExternalStore)(t.subscribe,a,a),o=(0,r.useCallback)(()=>t.getSourceState(i).syncStatus,[t,i]),c=(0,r.useSyncExternalStore)(t.subscribe,o,o),d="basic"===l.extensionMode?l.initializationError:null,[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),g=!p&&"ready"===c&&"main_running"!==e.status&&"background_running"!==e.status,f=d?`${e.cwd}
|
|
156
156
|
${i.sessionId}
|
|
157
157
|
|