@jetcrab/pi-desk 1.0.1-dev.9002 → 1.0.1-dev.9003

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.
Files changed (27) hide show
  1. package/package.json +3 -2
  2. package/src/server/l2_biz/plugin-management/l2-plugin-commands.ts +5 -2
  3. package/src/server/l4_foundation/pi/l4-pi-host-paths.mjs +31 -0
  4. package/src/server/l4_foundation/pi/l4-pi-package-maintenance-runner.mts +2 -1
  5. package/src/server/l4_foundation/pi/l4-pi-runtime-register.mjs +5 -2
  6. package/temp/build/pi-desk/release/.next/BUILD_ID +1 -1
  7. package/temp/build/pi-desk/release/.next/build-manifest.json +2 -2
  8. package/temp/build/pi-desk/release/.next/required-server-files.js +2 -2
  9. package/temp/build/pi-desk/release/.next/required-server-files.json +2 -2
  10. package/temp/build/pi-desk/release/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  11. package/temp/build/pi-desk/release/.next/server/app/_global-error.html +1 -1
  12. package/temp/build/pi-desk/release/.next/server/app/_global-error.rsc +1 -1
  13. package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  14. package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  15. package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  16. package/temp/build/pi-desk/release/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  17. package/temp/build/pi-desk/release/.next/server/app/api/health/route.js +1 -1
  18. package/temp/build/pi-desk/release/.next/server/app/login/page_client-reference-manifest.js +1 -1
  19. package/temp/build/pi-desk/release/.next/server/app/page.js +1 -1
  20. package/temp/build/pi-desk/release/.next/server/app/page_client-reference-manifest.js +1 -1
  21. package/temp/build/pi-desk/release/.next/server/chunks/45510.js +1 -1
  22. package/temp/build/pi-desk/release/.next/server/middleware-build-manifest.js +1 -1
  23. package/temp/build/pi-desk/release/.next/server/pages/500.html +1 -1
  24. package/temp/build/pi-desk/release/.next/static/chunks/app/{page-2f8de2d8dcc51430.js → page-6b7852c6b2ddec67.js} +1 -1
  25. package/temp/build/pi-desk/release/.next/trace-build +1 -1
  26. /package/temp/build/pi-desk/release/.next/static/{HZb6aCpVYMhWrd3rbv5Ng → s7sxIuj46JkJdK_-sM66b}/_buildManifest.js +0 -0
  27. /package/temp/build/pi-desk/release/.next/static/{HZb6aCpVYMhWrd3rbv5Ng → s7sxIuj46JkJdK_-sM66b}/_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 eU(...e){return e.filter(Boolean).join(" ")}function eY({className:e,children:t,...s}){return(0,n.jsxs)("div",{...s,"data-pi-desk-ui-root":"",className:eU("pi-desk-ui-root",e),children:[(0,n.jsx)("style",{href:"pi-desk-ui",precedence:"pi-desk-ui",children:eW}),t]})}function eV({className:e,...t}){return(0,n.jsx)("input",{...t,type:"checkbox",className:eU("pi-desk-ui-checkbox",e)})}r.Component;var eK=s(97107);let eH=[{key:"all",label:"policyAll"},{key:"allow",label:"policyAllow"},{key:"deny",label:"policyDeny"},{key:"none",label:"policyNone"}];function eG({label:e,rule:t,options:s,disabled:a,onChange:i}){let{t:l}=(0,f.Bd)("capabilityModes"),[o,d]=(0,r.useState)(()=>void 0!==t.allow?0===t.allow.length?"none":"allow":t.deny?.length?"deny":"all"),[c,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)(!1),[x,b]=(0,r.useState)(160),[v,w]=(0,r.useState)(()=>[...new Set([...t.allow??[],...t.deny??[]])]),y="deny"===o||"all"===o||"allow"===o&&c?"deny":"allow",k=t[y]??[],j=new Set(k),I=(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(),M=I.filter(e=>(!h||!!j.has(e.value))&&(!S||`${e.value} ${e.label??""} ${e.description??""}`.toLowerCase().includes(S.toLowerCase())||S.includes("*")&&(0,eK.RC)({allow:[S]},e.value))),z=M.slice(0,x),E=S.length>0&&S.length<=256&&!j.has(S);function A(e){"all"===o&&e.length>0&&d("deny"),"none"===o&&e.length>0&&d("allow"),i({...t,[y]:e})}function $(e,t){A(t?[...new Set([...k,e])]:k.filter(t=>t!==e))}function R(){E&&!a&&(w(e=>[...new Set([...e,S])]),$(S,!0),p(""))}return(0,n.jsxs)(eY,{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:eH.map(e=>(0,n.jsxs)(N.$,{size:"sm",variant:o===e.key?"secondary":"ghost","aria-pressed":o===e.key,disabled:a,onClick:()=>{var s;d(s=e.key),u(!1),g(!1),"all"===s?i({}):"none"===s?i({allow:[]}):"deny"===s?i({deny:t.deny??[]}):i({allow:t.allow??[],...t.deny?.length?{deny:t.deny}:{}})},children:[o===e.key&&(0,n.jsx)(ed.A,{className:"size-3.5"}),l(e.label)]},e.key))}),"allow"===o&&(0,n.jsxs)(N.$,{size:"sm",variant:c?"secondary":"ghost",disabled:a,"aria-pressed":c,onClick:()=>{u(!c),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)(e_.A,{className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(eB.p,{"aria-label":l("ruleSearch"),placeholder:l("ruleSearchPlaceholder"),maxLength:256,className:"pl-9 pr-9",value:m,disabled:a,onChange:e=>{p(e.target.value),b(160)},onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),R())}}),m&&(0,n.jsx)(N.$,{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)(U.A,{className:"size-3.5"})})]}),(0,n.jsxs)(N.$,{size:"sm",variant:h?"secondary":"ghost","aria-pressed":h,onClick:()=>g(!h),children:[(0,n.jsx)(eq.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)(N.$,{size:"sm",variant:"ghost",disabled:a||0===z.length,onClick:()=>A([...new Set([...k,...z.map(e=>e.value)])]),children:l("selectVisible")}),k.length>0&&(0,n.jsx)(N.$,{size:"sm",variant:"ghost",disabled:a,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:[E&&(0,n.jsxs)(N.$,{variant:"outline",disabled:a,className:"mb-3 h-auto min-h-9 max-w-full justify-start",onClick:R,children:[(0,n.jsx)(Y.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:z.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",a&&"pointer-events-none opacity-50"),children:[(0,n.jsx)(eV,{checked:t,disabled:a,"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===z.length&&(0,n.jsx)("p",{className:"px-3 py-6 text-sm text-muted-foreground",children:S?l("noMatches"):h?l("noSelection"):l("enterPattern")}),M.length>z.length&&(0,n.jsx)(N.$,{variant:"ghost",className:"mt-3",onClick:()=>b(e=>e+160),children:l("moreRules",{count:M.length-z.length})})]})]})}function eJ({modeKey:e,mode:t,catalog:s,disabled:a,onChange:i}){var l;let{t:o}=(0,f.Bd)("capabilityModes"),d=(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]),[c,u]=(0,r.useState)("tools"),m=d.find(e=>e.key===c)??d[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)(eB.p,{"aria-label":o("modeName"),value:t.name,maxLength:64,disabled:a,className:"min-w-40 flex-1",onChange:e=>i({...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:d.map(e=>(0,n.jsx)(N.$,{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)(eG,{label:m.label,rule:"plugin"===(l=m.target).kind?t.plugins?.[l.pluginName]?.[l.group]??{}:t[l.kind]??{},options:m.options,disabled:a,onChange:e=>i(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 a={...e.plugins?.[t.pluginName]};r?delete a[t.group]:a[t.group]=n;let i={...e.plugins};Object.keys(a).length?i[t.pluginName]=a:delete i[t.pluginName];let l={...e};return Object.keys(i).length?l.plugins=i:delete l.plugins,l}(t,m.target,e))},`${e}:${m.key}`)]})}var eX=s(80894);function eQ({open:e,deleteName:t,saving:s,error:r,onCancel:a,onDelete:i,onLeave:l}){let{t:o}=(0,f.Bd)("capabilityModes");return(0,n.jsx)(eX.YV,{open:e,onOpenChange:e=>{e||s||a()},children:(0,n.jsxs)(eX.hA,{className:"z-[150]",showCloseButton:!s,children:[(0,n.jsxs)(eX.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eX.YM,{children:o(t?"deleteConfirm":"saveConfirm")}),(0,n.jsx)(eX.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)(eX.vu,{children:[(0,n.jsx)(N.$,{variant:"outline",disabled:s,onClick:a,children:o("cancel")}),t?(0,n.jsx)(N.$,{variant:"destructive",onClick:i,children:o("delete")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.$,{variant:"ghost",disabled:s,onClick:()=>l("discard"),children:o("discard")}),(0,n.jsx)(N.$,{disabled:s,onClick:()=>l("save"),children:o(s?"saving":"saveContinue")})]})]})]})})}function eZ({modeNames:e,onBeforeLeaveChange:t}){let{t:s}=(0,f.Bd)("capabilityModes"),{clientId:a}=(0,eR.gM)(),i=(0,eC.G)(),l=function(e){let{t}=(0,f.Bd)("capabilityModes"),[s,n]=(0,r.useState)(null),[a,i]=(0,r.useState)({}),[l,o]=(0,r.useState)(null),[d,c]=(0,r.useState)(null),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(!1),[g,x]=(0,r.useState)(null),[b,v]=(0,r.useState)(!1),w=(0,r.useRef)(null),y=(0,r.useRef)(null),k=null!==s&&JSON.stringify(s)!==JSON.stringify(a);(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 a;m(!0),x(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),i(structuredClone(t.modes))),null!==s&&k?a:t.modes}catch(e){return y.current?.signal.aborted||x(e instanceof Error?e.message:t("catalogFailed")),null}finally{y.current?.signal.aborted||m(!1)}},[e,k,a,s,t]),N=(0,r.useCallback)(async e=>{if(null===e)return void c(null);let t=await j();t&&Object.hasOwn(t,e)&&c(e)},[j]),I=(0,r.useCallback)(async(e=!1)=>{let s=await j();if(!s)return;let n=e&&d?s[d]:void 0,r=crypto.randomUUID(),a=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"));i({...s,[r]:{...n?structuredClone(n):{},name:a}}),c(r)},[j,d,t]),C=(0,r.useCallback)(e=>{d&&i(t=>({...t,[d]:e}))},[d]),S=(0,r.useCallback)(()=>{d&&(i(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==d))),c(null))},[d]),M=(0,r.useCallback)(async()=>{if(!k)return!0;h(!0),x(null);try{let t=await e.replace(a,y.current?.signal);if(y.current?.signal.aborted)return!1;return n(t),i(structuredClone(t)),!0}catch(e){return y.current?.signal.aborted||x(e instanceof Error?e.message:t("saveFailed")),!1}finally{y.current?.signal.aborted||h(!1)}},[e,k,a,t]),z=(0,r.useCallback)(()=>k?(v(!0),new Promise(e=>{w.current=e})):Promise.resolve(!0),[k]);return{draft:a,saved:s,catalog:l,selected:d,loading:u,saving:p,error:g,dirty:k,leaveOpen:b,beforeLeave:z,decideLeave:(0,r.useCallback)(async e=>{("save"!==e||await M())&&(v(!1),w.current?.("cancel"!==e),w.current=null)},[M]),load:j,select:N,add:I,update:C,remove:S,save:M}}((0,r.useMemo)(()=>(function(e){async function t(t,s,n,r){return eF(e,t,s,n,{signal:r,fallbackMessage:(0,eO.B)({msg:"能力模式请求失败",i18n:{key:"errors:capabilityFailed"}})})}return{get:e=>t("/api/capability-modes/get",{},eT,e),async replace(e,s){let n=eD.safeParse({modes:e});if(!n.success)throw Error((0,eO.B)({msg:"请检查模式规则",i18n:{key:"errors:capabilityRuleInvalid"}}));return await t("/api/capability-modes/replace",n.data,eL,s),n.data.modes}}})(a),[a])),[o,d]=(0,r.useState)(null),{beforeLeave:c}=l;(0,r.useEffect)(()=>(t(c),()=>t(null)),[c,t]);let u=null===l.saved?e:(0,e$.HE)(l.draft),m=l.selected?l.draft[l.selected]:void 0,p=l.loading||l.saving,h=async()=>{await l.save()&&i.success(s("saved"))},g=(0,n.jsxs)(N.$,{size:"sm",disabled:!l.dirty||p,onClick:()=>void h(),children:[l.saving?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(eS.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)(eP.l6,{value:l.selected??"",disabled:p,onValueChange:e=>{"string"==typeof e&&l.select(e||null)},children:[(0,n.jsx)(eP.bq,{"aria-label":s("selectMode"),className:"w-40 sm:w-48",children:(0,n.jsx)(eP.yv,{children:l.selected?u[l.selected]||s("unnamedMode"):s("allDefault")})}),(0,n.jsxs)(eP.gC,{positionerClassName:"z-[140]",children:[(0,n.jsx)(eP.eb,{value:"",children:s("allDefault")}),Object.entries(u).map(([e,t])=>(0,n.jsx)(eP.eb,{value:e,children:t||s("unnamedMode")},e))]})]})]}),(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,n.jsxs)(N.$,{size:"sm",variant:"ghost",disabled:p,onClick:()=>void l.add(),children:[(0,n.jsx)(Y.A,{className:"size-4"}),s("addMode")]}),m&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost","aria-label":s("copyMode"),title:s("copyTitle"),disabled:p,onClick:()=>void l.add(!0),children:(0,n.jsx)(eM.A,{className:"size-4"})}),(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost","aria-label":s("deleteMode"),title:s("deleteTitle"),disabled:p,onClick:()=>d(m.name||s("unnamedMode")),children:(0,n.jsx)(ez.A,{className:"size-4"})})]}),l.catalog&&(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost","aria-label":s("refreshCatalog"),title:s("refreshCatalog"),disabled:p,onClick:()=>void l.load(!0),children:(0,n.jsx)(eE.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)(N.$,{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)(b.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)(eA.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)(eQ,{open:l.leaveOpen||null!==o,deleteName:o,saving:l.saving,error:l.leaveOpen?l.error:null,onCancel:()=>{null!==o?d(null):l.decideLeave("cancel")},onDelete:()=>{l.remove(),d(null)},onLeave:e=>void l.decideLeave(e)})]})}var e0=s(89842),e1=s(7251),e2=s(70434),e5=s(79369),e3=s(94292),e4=s(64993),e6=s(6428),e8=s(93222),e7=s(51251),e9=s(63381),te=s(67409),tt=s(35595);let ts={plugin:e0.A,server:e1.A,rocket:e2.A,settings:e5.A,panel:e3.A,message:e4.A,terminal:v.A,file:e6.A,folder:e8.A,bot:e7.A,wrench:e9.A,database:te.A,globe:tt.A},tn=new Map;function tr({icon:e,className:t}){if(e?.type==="svg"){let s=function(e){if(tn.has(e))return tn.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 tn.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"?ts[e.name]:e0.A;return(0,n.jsx)(s,{"aria-hidden":"true",className:t})}var ta=s(20847),ti=s(59728),tl=s(55379);function to({error:e,children:t}){let{t:s}=(0,f.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)(tl.Nt,{defaultOpen:!1,children:[(0,n.jsxs)(tl.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)(ti.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)(tl.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 overscroll-contain 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 td({pluginName:e,kind:t,contributionName:s,target:a,targetKey:i,className:l,layout:o="fill"}){let{t:d}=(0,f.Bd)("pluginManagement"),c=(0,eI.t4)();(0,eI.So)();let u=c.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)(a),x=i??a,[v,w]=(0,r.useState)(0),[y,k]=(0,r.useState)({status:"loading"});(0,r.useEffect)(()=>{g.current=a},[a]),(0,r.useEffect)(()=>{let n=h.current;if(!n)return;let r=new AbortController,a=!0,i=null;if("ready"!==u.status)return queueMicrotask(()=>{a&&k(p?{status:"error",error:p}:{status:"loading"})}),()=>{a=!1,r.abort()};let l=Promise.resolve().then(()=>a?((i=document.createElement("div")).className="intrinsic"===o?"inline-block min-h-0 min-w-0 align-top":"h-full min-h-0 w-full min-w-0",n.append(i),c.mountContribution({pluginName:e,kind:t,contributionName:s,container:i,target:g.current,signal:r.signal})):null);return queueMicrotask(()=>{a&&k({status:"loading"})}),l.then(e=>{a&&e&&k({status:"ready"})},e=>{a&&k({status:"error",error:e instanceof Error?e:Error(String(e))})}),()=>{a=!1,r.abort(),i?.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)}},[v,s,m,u.status,p,t,o,x,e,c]);let j="loading"===y.status?"h-[200px] w-[360px]":"error"===y.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)]",j):"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":"h-full min-h-0 w-full min-w-0","error"===y.status&&"hidden")}),"loading"===y.status?(0,n.jsxs)("div",{className:"absolute inset-0 flex items-center justify-center bg-popover p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"mr-2 size-4 animate-spin"}),d("viewLoading")]}):null,"error"===y.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)(ta.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:d("viewFailed")}),(0,n.jsx)(to,{error:y.error,children:(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e," \xb7 ",t," \xb7 ",s]})}),(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{if("failed"===u.status){k({status:"loading"}),c.retryEntry(e).catch(t=>{"failed"===c.getEntryState(e).status&&k({status:"error",error:t instanceof Error?t:Error(String(t))})});return}"failed"!==c.getContributionLoadState(e,t,s).status?w(e=>e+1):(k({status:"loading"}),c.retryContribution(e,t,s).then(()=>{c.getEntryState(e)===u&&w(e=>e+1)},t=>{c.getEntryState(e)===u&&k({status:"error",error:t instanceof Error?t:Error(String(t))})}))},children:[(0,n.jsx)(eE.A,{}),d("retry")]})]})]})})}):null]})}function tc({pluginName:e,descriptor:t,workSessions:s,preferredWorkId:a,onClose:i}){let{t:l}=(0,f.Bd)("pluginManagement"),o=(0,eI.t4)();(0,eI.So)();let d=o.getEntryState(e),[c]=(0,r.useState)(()=>{let e=s.find(e=>e.workId===a);return e?{source:{workId:e.workId,sessionId:e.sessionId,branchId:e.branchId},cwd:e.cwd}:null}),u=(0,r.useMemo)(()=>({kind:"application",initialContext:c,close:()=>{o.getEntryState(e)===d&&i()}}),[d,c,i,e,o]),m="host"===t.chrome;return(0,n.jsx)(eX.YV,{open:!0,onOpenChange:(e,t)=>{e||"focus-out"===t.reason||i()},children:(0,n.jsxs)(eX.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)(eX.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)(tr,{icon:t.icon,className:"size-5"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eX.YM,{className:"break-words",children:t.title}),(0,n.jsx)(eX.uX,{className:"sr-only",children:e})]}),(0,n.jsx)(N.$,{variant:"ghost",size:"icon","aria-label":l("closeNamedApplication",{name:t.title}),title:l("closeApplication"),onClick:i,className:"text-muted-foreground",children:(0,n.jsx)(U.A,{className:"size-4"})})]})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eX.YM,{className:"sr-only",children:t.title}),(0,n.jsx)(eX.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)(td,{pluginName:e,kind:"application",contributionName:t.contributionName,target:u,layout:"intrinsic"})})]})})}function tu({pluginName:e,descriptor:t,source:s,onClose:a}){let i=(0,r.useMemo)(()=>({kind:"composer-panel",source:s,close:a}),[a,s]);return(0,n.jsx)(eX.YV,{open:!0,onOpenChange:e=>!e&&a(),children:(0,n.jsxs)(eX.hA,{finalFocus:!1,className:"h-[min(720px,calc(100dvh-2rem))] max-w-4xl max-sm:h-dvh max-sm:max-h-dvh max-sm:w-full max-sm:max-w-none max-sm:rounded-none max-sm:border-0",children:[(0,n.jsx)(eX.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)(tr,{icon:t.icon,className:"size-5"})}),(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)(eX.YM,{className:"truncate",children:t.label}),(0,n.jsx)(eX.uX,{className:"sr-only",children:e})]})]})}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:(0,n.jsx)(td,{pluginName:e,kind:"composer-panel",contributionName:t.contributionName,target:i,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})})]})})}var tm=s(57380),tp=s(21154),th=s(70652),tg=s(84474);let tx=new Set(["bash","edit","find","grep","ls","read","write"]),tf="__pi_desk_unknown_schema_type__",tb={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"}},tv={application:"contributionApplication","composer-panel":"contributionComposer","settings-page":"contributionSettings","message-view":"contributionMessage","session-sidebar-tab":"contributionSidebar"};function tw(e){let t=[];for(let s of e.extensions)for(let e of s.events){let n=tb[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 ty(e){return null===e||"object"!=typeof e||Array.isArray(e)?null:e}function tk({state:e}){let{t}=(0,f.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 tj({text:e,label:t}){let{t:s}=(0,f.Bd)("pluginManagement"),[a,i]=(0,r.useState)(!1);return(0,n.jsx)(N.$,{type:"button",size:"icon",variant:"ghost","aria-label":t,title:s(a?"copied":"copy"),onClick:()=>{(0,tg.x)(e).then(e=>{e&&i(!0)})},children:a?(0,n.jsx)(ed.A,{className:"size-3.5"}):(0,n.jsx)(eM.A,{className:"size-3.5"})})}function tN({title:e,text:t}){let{t:s}=(0,f.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)(tj,{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 tI({title:e,description:t,children:s}){return(0,n.jsxs)(tl.Nt,{className:"border-t",children:[(0,n.jsxs)(tl.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)(eo.A,{"aria-hidden":"true",className:"size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),e]}),(0,n.jsx)(tl.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 tC({capabilities:e}){let{t}=(0,f.Bd)("pluginManagement"),s=tw(e);return 0===s.length?null:(0,n.jsx)(tI,{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 tS({tool:e}){let{t}=(0,f.Bd)("pluginManagement"),s=function(e){var t;let s=ty(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=ty(t);return{name:e,required:n.has(e),type:function e(t){let s=ty(t);if(!s)return tf;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===tf?"array":`${t}[]`}for(let t of["anyOf","oneOf"]){if(!Array.isArray(s[t]))continue;let n=s[t].map(e).filter(e=>e!==tf);if(n.length>0)return[...new Set(n)].join(" | ")}return tf}(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===tf?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)("details",{className:"mt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm text-muted-foreground",children:t("rawSchema")}),(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,f.Bd)("pluginManagement");return 0===e.tools.length?null:(0,n.jsx)(tI,{title:t("toolCapabilities"),description:t("toolDescription"),children:(0,n.jsx)("div",{className:"space-y-2",children:e.tools.map((e,s)=>(0,n.jsxs)("details",{className:"border-b py-3 last:border-b-0",children:[(0,n.jsxs)("summary",{className:"cursor-pointer text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsxs)("div",{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)(tk,{state:e.state}),tx.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)("p",{className:"mt-1.5 break-words text-sm leading-5 text-muted-foreground",children:e.description||t("noDescription")})]}),(0,n.jsx)(tS,{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)(tN,{title:"Available tools",text:e.promptSnippet}):null,e.promptGuidelines.length>0?(0,n.jsx)(tN,{title:`Guidelines \xb7 ${e.promptGuidelines.length}`,text:e.promptGuidelines.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}):null]}):null]},`${e.name}:${s}`))})})}function tz({title:e,content:t,truncated:s}){let{t:r}=(0,f.Bd)("pluginManagement");return(0,n.jsxs)("details",{className:"mt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer py-2 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:e}),(0,n.jsxs)("div",{className:"border-t",children:[(0,n.jsx)("div",{className:"flex justify-end px-2 pt-1",children:(0,n.jsx)(tj,{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 tE({detail:e}){let{t}=(0,f.Bd)("pluginManagement");return 0===e.skills.length&&0===e.prompts.length?null:(0,n.jsx)(tI,{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)(tN,{title:t("skillMetadata"),text:`name: ${e.name}
153
153
  description: ${e.description}
154
- location: ${e.path}`})}):null,(0,n.jsx)(tz,{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)(tz,{title:t("viewPromptContent"),content:e.content,truncated:e.truncated})]},e.path))]})})}function tA({capabilities:e,browserContributions:t}){let{t:s}=(0,f.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),a=e.piDesk.methods.length>0||e.piDesk.browserEntries.length>0||e.piDesk.messageDeclarations.length>0||t.length>0,i=e.themes.length>0||e.providers.length>0;return r||a||i?(0,n.jsx)(tI,{title:s("otherCapabilities"),children:(0,n.jsxs)("div",{className:"space-y-2",children:[a?(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(tv[e.kind]),":","message-view"===e.kind?e.viewKey:"application"===e.kind?e.title: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,i?(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 t$({plugin:e,detail:t,detailLoading:s,detailError:r,browserContributions:a,onRetry:i}){let{t:l}=(0,f.Bd)("pluginManagement"),{locale:o}=(0,tp.i)(),d=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 a=tw(e).reduce((e,t)=>e+t.count,0);a>0&&n.push({label:s("tagDynamic",{count:a}),tone:"dynamic"});let i=e.tools.filter(e=>"shadowed"!==e.state&&tx.has(e.name)).length;i>0&&n.push({label:s("tagOverride",{count:i}),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 d=e.providers.length+e.themes.length+e.extensions.reduce((e,t)=>e+t.commands.length+t.shortcuts.length+t.flags.length,0);return d>0&&n.push({label:s("tagInteraction",{count:d}),tone:"neutral"}),0===n.length&&e.extensions.length>0&&n.push({label:`Extension ${e.extensions.length}`,tone:"neutral"}),n}(e.capabilities,a,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}),d.length>0?(0,n.jsx)("div",{className:"flex flex-wrap gap-2","aria-label":l("capabilityCategories"),children:d.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,tm.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)(b.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)(N.$,{type:"button",size:"sm",variant:"outline",onClick:i,children:[(0,n.jsx)(eE.A,{"data-icon":"inline-start"}),l("retry")]})]}):t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(tM,{detail:t}),(0,n.jsx)(tE,{detail:t})]}):null,(0,n.jsx)(tC,{capabilities:e.capabilities}),(0,n.jsx)(tA,{capabilities:e.capabilities,browserContributions:a})]})}function tR(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 tP(e){return e.source.startsWith("npm:")?tR(e.source)?.name??e.source:e.pluginName??("extension"===e.kind?e.source.replaceAll("\\","/").split("/").at(-1):null)??e.source}function tT(e){return`source:${e.startsWith("npm:")?tR(e)?.name??e:e}`}function tD(e){switch(e.kind){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 tL=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 仓库地址"),tO=a.gM("mode",[a.Ik({mode:a.eu("auto")}).strict(),a.Ik({mode:a.eu("official")}).strict(),a.Ik({mode:a.eu("domestic")}).strict(),a.Ik({mode:a.eu("custom"),registry:tL}).strict()]),tF=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),tF).optional()}).passthrough().optional()}).passthrough();let tB=a.Ik({downloadSource:tO,recommendedRegistry:tL}).strict(),t_=a.Ik({downloadSource:tO}).strict(),tq=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:tL.optional()}).strict(),tW=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:tL.optional()}).strict(),tU=a.Ik({name:a.Yj(),description:tm.qf.nullable(),version:a.Yj(),publisher:a.Yj().nullable(),kind:a.k5(["desk","pi","unknown"]),official:a.zM(),registry:tL}).strict(),tY=a.Ik({items:a.YO(tU),hasMore:a.zM()}).strict(),tV=tU.extend({versions:a.YO(a.Yj()),readme:tm.qf.nullable(),homepage:a.Yj().nullable(),repository:a.Yj().nullable(),compatible:a.zM().nullable(),compatibilityNote:a.Yj().nullable()}).strict();function tK({id:e,mode:t,registry:s,recommendedRegistry:r,savedRegistry:a,loading:i,saving:l,error:o,override:d,onMode:c,onRegistry:u,onSave:m,onRetry:p}){let{t:h}=(0,f.Bd)("pluginManagement"),g="auto"===t?r:"official"===t?"https://registry.npmjs.org":"domestic"===t?"https://registry.npmmirror.com":"custom"===t?a??s:null;return(0,n.jsxs)("div",{className:"min-w-0 space-y-2 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(d?"installDownloadSource":"downloadSource")}),(0,n.jsxs)("select",{id:e,value:t,disabled:l,onChange:e=>c(e.target.value),className:"min-h-8 max-w-full rounded-lg border border-input bg-background px-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",children:[d?(0,n.jsx)("option",{value:"default",children:h("useDefaultSource")}):null,["auto","domestic","official","custom"].map(e=>(0,n.jsx)("option",{value:e,children:h(`download_${e}`)},e))]}),i?(0,n.jsx)("span",{role:"status",className:"text-muted-foreground",children:h("recommending")}):null,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)(eB.p,{id:`${e}-url`,type:"url",value:s,placeholder:"https://registry.example.com",className:"min-w-0 flex-1 basis-48",onChange:e=>u(e.target.value)}),m?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:l,onClick:m,children:h("save")}):null]})]}):null,d?null:(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{className:"cursor-pointer py-1 text-muted-foreground",children:h("sourceDetails")}),(0,n.jsx)("p",{className:"mt-1 break-all text-muted-foreground",children:g??h("recommending")})]}),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)(N.$,{variant:"outline",size:"sm",onClick:p,children:h("retry")}):null]}):null]})}function tH({plugin:e,displayName:t,browserError:s,requestError:r,disabled:a,pending:i,browserRetryPending:l,onAction:o}){let{t:d}=(0,f.Bd)("pluginManagement"),{locale:c}=(0,tp.i)(),u=e.operation?.phase,m=!!(e.operation&&"failed"!==u),p="disabled"!==e.status,h="failed"===e.status||null!==s,g=e.error?(0,tm.fD)(e.error.message,c):null,x=d(m?`phase_${u}`:h?"notLoaded":p?"enabled":"disabled");return(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[m||i||h?(0,n.jsxs)("span",{role:"status",className:`inline-flex items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs ${h&&!m?"text-destructive":"text-muted-foreground"}`,children:[m&&"waiting"!==u?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}):null,i&&!m?d("submitting"):x]}):null,"extension"===e.kind?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:d("localExtension")}):null,(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",role:"switch","aria-checked":p,"aria-label":d("togglePlugin",{name:t}),disabled:a||i,onClick:()=>o(p?"disable":"enable"),children:[(0,n.jsx)("span",{"aria-hidden":"true",className:`flex h-4 w-7 items-center rounded-full p-0.5 ${p?"bg-primary":"bg-muted-foreground"}`,children:(0,n.jsx)("span",{className:`size-3 rounded-full bg-primary-foreground transition-transform ${p?"translate-x-3":""}`})}),d(p?"enabled":"disabled")]}),e.updateAvailable&&"extension"!==e.kind?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:a||i,onClick:()=>o("update"),children:d("update")}):null,"extension"!==e.kind?(0,n.jsxs)(N.$,{size:"sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive",disabled:a||i,onClick:()=>o("remove"),children:[(0,n.jsx)(ez.A,{"data-icon":"inline-start"}),d("remove")]}):null,"failed"===u?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:a||i,onClick:()=>o("retry"),children:d("retry")}):null,s&&e.pluginName?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:a||l,onClick:()=>o("retry-browser"),children:d("retryView")}):null,(0,n.jsxs)("details",{className:"text-sm",children:[(0,n.jsx)("summary",{className:"cursor-pointer rounded-lg px-2 py-1.5 outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",children:d("more")}),(0,n.jsx)(N.$,{size:"sm",variant:"ghost",className:"mt-1",disabled:a||i&&"waiting"!==u,"aria-label":d("reloadSource",{name:t}),onClick:()=>o("reload"),children:d("reloadOne")})]})]}),e.operation?.message?(0,n.jsx)("p",{className:`whitespace-pre-wrap text-sm [overflow-wrap:anywhere] ${"failed"===u?"text-destructive":"text-muted-foreground"}`,children:e.operation.message}):null,[r,g,s].filter((t,s,n)=>t&&n.indexOf(t)===s&&t!==e.operation?.message).map(e=>(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive [overflow-wrap:anywhere]",children:e},e))]})}function tG({snapshot:e,loading:t,filter:s,disabled:r,requests:a,errors:i,browserErrors:l,onFilter:o,onDetail:d,onAction:c,onDirectInstall:u,onRefresh:m}){let{t:p}=(0,f.Bd)("pluginManagement"),{locale:h}=(0,tp.i)(),g=e?.plugins.filter(e=>`${tP(e)} ${e.description?(0,tm.fD)(e.description,h):""}`.toLocaleLowerCase().includes(s.toLocaleLowerCase()))??[];return(0,n.jsxs)("section",{"aria-label":p("installed"),className:"min-w-0 space-y-4",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:"plugin-installed-filter",className:"sr-only",children:p("filterInstalled")}),(0,n.jsx)(eB.p,{id:"plugin-installed-filter",value:s,onChange:e=>o(e.target.value),placeholder:p("filterInstalled"),className:"min-w-0 flex-1 basis-48"}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:t,onClick:m,children:p(t?"checkingUpdates":"checkUpdates")}),(0,n.jsx)(N.$,{size:"sm",disabled:r,onClick:u,children:p("directInstall")})]}),i.list?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:i.list}):null,t&&!e?(0,n.jsx)("p",{role:"status",className:"py-6 text-sm text-muted-foreground",children:p("loading")}):g.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:g.map(e=>{let t=tP(e),s=tT(e.source);return(0,n.jsxs)("article",{className:"min-w-0 space-y-3 p-4",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,n.jsx)(N.$,{variant:"link",className:"h-auto min-w-0 max-w-full justify-start p-0 text-left text-sm font-semibold whitespace-normal [overflow-wrap:anywhere]","aria-label":p("viewDetails",{name:t}),onClick:()=>d(e.source),children:t}),e.version?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",e.version]}):null]}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.description?(0,tm.fD)(e.description,h):p("noPluginDescription")}),(0,n.jsx)(tH,{plugin:e,displayName:t,browserError:e.pluginName?l.get(e.pluginName)??null:null,requestError:i[s]??i[`entry:${e.pluginName}`],disabled:r,pending:a.has(s)||!!(e.operation&&"failed"!==e.operation.phase),browserRetryPending:a.has(`entry:${e.pluginName}`),onAction:t=>c(e,t)})]},e.source)})}):(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:p(s?"noMatches":"empty")})]})}function tJ(e){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,tp.i)(),r=new Map(e.snapshot?.plugins.filter(e=>e.source.startsWith("npm:")).map(e=>[tR(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:"space-y-3",children:[(0,n.jsx)("label",{htmlFor:"plugin-catalog-query",className:"sr-only",children:t("searchPlugins")}),(0,n.jsx)(eB.p,{id:"plugin-catalog-query",value:e.query,placeholder:t("searchPlaceholder"),maxLength:200,onChange:t=>e.onQuery(t.target.value),onCompositionStart:e.onCompositionStart,onCompositionEnd:e.onCompositionEnd}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-3",children:[(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm",children:[t("searchSource"),(0,n.jsxs)("select",{value:e.searchSource,onChange:t=>e.onSearchSource(t.target.value),className:"min-h-8 rounded-lg border border-input bg-background px-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)("option",{value:"public",children:t("publicNpm")}),(0,n.jsx)("option",{value:"custom",children:t("customSearchSource")})]})]}),(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm",children:[t("pluginKind"),(0,n.jsx)("select",{value:e.kind,onChange:t=>e.onKind(t.target.value),className:"min-h-8 rounded-lg border border-input bg-background px-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",children:["all","desk","pi"].map(e=>(0,n.jsx)("option",{value:e,children:t(`kind_${e}`)},e))})]})]}),"custom"===e.searchSource?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:"plugin-search-registry",className:"block text-sm",children:t("searchRegistryUrl")}),(0,n.jsx)(eB.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)(N.$,{size:"sm",variant:"outline",onClick:e.onRetry,children:t("retry")})]}):null,e.items.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:e.items.map(a=>{let i=r.get(a.name),l=tT(`npm:${a.name}`),o=i?.description??a.description,d=!!(i?.operation&&"failed"!==i.operation.phase),c=e.requests.has(l)||d||e.preparing.has(a.name),u=i&&(i.operation?.action!=="add"||"failed"!==i.operation.phase),m=e.installErrors[a.name]??e.errors[l]??(i?.error?(0,tm.fD)(i.error.message,s):null);return(0,n.jsxs)("article",{className:"min-w-0 space-y-2 p-4",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-2",children:[(0,n.jsx)(N.$,{variant:"link",className:"h-auto min-w-0 max-w-full p-0 text-left text-sm font-semibold whitespace-normal [overflow-wrap:anywhere]",onClick:()=>e.onDetail(a),children:a.name}),(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",a.version]}),a.official?(0,n.jsx)("span",{className:"rounded-md bg-secondary px-1.5 py-0.5 text-xs text-secondary-foreground",children:t("official")}):null,(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`kind_${a.kind}`)})]}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:o?(0,tm.fD)(o,s):t("noPluginDescription")}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 text-xs text-muted-foreground [overflow-wrap:anywhere]",children:a.publisher??t("unknownPublisher")}),c?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:d?t(`phase_${i?.operation?.phase}`):e.preparing.has(a.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")}),i.updateAvailable?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onUpdate(i.source),children:t("update")}):null]}):(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onInstall(a),children:t("install")})]}),m?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:m}):null,i?.operation?.phase==="failed"&&i.operation.message?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:i.operation.message}):null]},a.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)(N.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onMore,children:t("loadMore")}):null]})}let tX=(0,s(11550).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 tQ({className:e,orientation:t,...s}){return(0,n.jsx)("div",{role:"group","data-slot":"button-group","data-orientation":t,className:(0,C.cn)(tX({orientation:t}),e),...s})}var tZ=s(71558),t0=s(86049),t1=s(74082),t2=s(67935),t5=s(67446),t3=s(9486);let t4=({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}),t6=({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}),t8=({tooltip:e,children:t,label:s,variant:r="ghost",size:a="icon-sm",...i})=>{let l=(0,n.jsxs)(N.$,{size:a,type:"button",variant:r,...i,children:[t,(0,n.jsx)("span",{className:"sr-only",children:s||e})]});return e?(0,n.jsx)(tZ.Bc,{children:(0,n.jsxs)(tZ.m_,{children:[(0,n.jsx)(tZ.k$,{render:l}),(0,n.jsx)(tZ.ZI,{children:(0,n.jsx)("p",{children:e})})]})}):l},t7={cjk:t0.h,code:t1.a,math:t2.D,mermaid:t5.a},t9=(0,r.memo)(({className:e,...t})=>(0,n.jsx)(t3.jH,{className:(0,C.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),plugins:t7,...t}),(e,t)=>e.children===t.children&&t.isAnimating===e.isAnimating);t9.displayName="MessageResponse";let se=({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 st({readme:e}){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,tp.i)(),[a,i]=(0,r.useState)(null),l=e&&"string"!=typeof e?e.translations:{},o=Object.keys(l).filter(e=>/^(zh(?:-|$)|en(?:-|$))/.test(e)),d=a&&void 0!==l[a]?a:null,c=e?d?l[d]:(0,tm.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)("label",{className:"flex items-center gap-2 text-sm",children:[t("readmeLanguage"),(0,n.jsxs)("select",{value:d??"",onChange:e=>i(e.target.value||null),className:"min-h-8 rounded-lg border border-input bg-background px-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)("option",{value:"",children:t("defaultLanguage")}),o.map(e=>(0,n.jsx)("option",{value:e,children:e.startsWith("zh")?"中文":"English"},e))]})]}):null]}),c?(0,n.jsx)("div",{className:"min-w-0 overflow-x-auto text-base leading-relaxed [overflow-wrap:anywhere]",children:(0,n.jsx)(t9,{mode:"static",isAnimating:!1,skipHtml:!0,controls:!1,className:"min-w-0 [&_img]:max-w-full [&_pre]:overflow-x-auto",children:c})}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:t("noReadme")})]})}function ss(e){if(!e)return null;try{let t=new URL(e);return["https:","http:"].includes(t.protocol)?t.href:null}catch{return null}}function sn(e){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,tp.i)(),r=e.detail,a=e.installed&&e.installedVersion===r.version,i=ss(r.homepage),l=ss(r.repository);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:[r.official?(0,n.jsx)("span",{className:"rounded-md bg-secondary px-2 py-1 text-secondary-foreground",children:t("official")}):null,(0,n.jsx)("span",{children:t(`kind_${r.kind}`)}),(0,n.jsx)("span",{className:"[overflow-wrap:anywhere]",children:r.publisher??t("unknownPublisher")})]}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:r.description?(0,tm.fD)(r.description,s):t("noPluginDescription")}),(0,n.jsxs)("label",{className:"flex flex-wrap items-center gap-2 text-sm",children:[t("version"),(0,n.jsx)("select",{value:r.version,onChange:t=>e.onVersion(t.target.value),className:"min-h-8 min-w-0 max-w-full rounded-lg border border-input bg-background px-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[...new Set([r.version,...r.versions])].map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:t(!0===r.compatible?"compatible":!1===r.compatible?"incompatible":"compatibilityUnknown")}),r.compatibilityNote?(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:r.compatibilityNote}):null,(0,n.jsxs)("div",{className:"flex flex-wrap gap-3 text-sm",children:[i?(0,n.jsx)("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-4",children:t("homepage")}):null,l?(0,n.jsx)("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-4",children:t("repository")}):null]}),a?null:(0,n.jsx)(tK,{id:"plugin-detail-download",mode:e.downloadMode,registry:e.downloadRegistry,override:!0,onMode:e.onDownloadMode,onRegistry:e.onDownloadRegistry}),(0,n.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:e.pending?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:e.operationMessage??t("submitting")}):a?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),e.updateAvailable?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:e.onUpdate,children:t("update")}):null]}):(0,n.jsx)(N.$,{size:"sm",disabled:e.disabled,onClick:e.onInstall,children:t(e.installed?"installVersion":"install")})}),e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.error}):null]}),(0,n.jsx)("div",{className:"border-t pt-4",children:(0,n.jsx)(st,{readme:r.readme},`${r.name}@${r.version}`)})]})}function sr(e){let{t}=(0,f.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)(N.$,{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)(eB.p,{id:"plugin-direct-source",value:e.source,placeholder:t("sourcePlaceholder"),onChange:t=>e.onSource(t.target.value)}),e.isNpm?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onRead,children:t(e.loading?"loadingPackage":"readPackage")}),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)("label",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[t("version"),(0,n.jsx)("select",{value:e.detail.version,disabled:e.loading,onChange:t=>e.onVersion(t.target.value),className:"min-h-8 min-w-0 max-w-full rounded-lg border border-input bg-background px-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[...new Set([e.detail.version,...e.detail.versions])].map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]})]}):null,(0,n.jsx)(tK,{id:"plugin-direct-download",mode:e.override,registry:e.registry,override:!0,onMode:e.onMode,onRegistry:e.onRegistry})]}):null,e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm 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)(N.$,{size:"sm",disabled:e.disabled||e.loading||e.pending||!e.source.trim(),onClick:e.onInstall,children:t(e.pending?"installing":"install")})]})}function sa({open:e,title:t,confirmation:s,onClose:r,onConfirm:a,children:i}){let{t:l}=(0,f.Bd)("pluginManagement"),o=s?l(tD(s)):null;return(0,n.jsx)(eX.YV,{open:e,onOpenChange:e=>{e||r()},children:(0,n.jsxs)(eX.hA,{finalFocus:!0,className:s?"max-w-lg":"h-[min(85dvh,52rem)] max-w-3xl",children:[(0,n.jsxs)(eX.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eX.YM,{className:"min-w-0 [overflow-wrap:anywhere]",children:s?l("confirmAction",{action:o}):t}),(0,n.jsx)(eX.uX,{children:l(s?"del"===s.kind?"removeDescription":"add"===s.kind?"thirdPartyDescription":"reload"===s.kind?"normal"===s.mode?"restartNormalDescription":"restartDescription":"confirmChange":"pluginDetails")})]}),(0,n.jsx)(eX._Y,{className:"min-h-0",children:(0,n.jsx)("div",{className:"min-w-0 p-4 pt-0",children:s?"add"===s.kind?(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:l("packageName")}),(0,n.jsx)("dd",{className:"mt-1 font-medium [overflow-wrap:anywhere]",children:s.package?.name??s.input.source})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:l("version")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:s.package?.version??tR(s.input.source)?.version??l("fromSource")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:l("publisher")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:s.package?.publisher??l("unknownPublisher")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:l("source")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:s.input.registry??s.package?.registry??s.input.source})]})]}):"reload"!==s.kind?(0,n.jsx)("p",{className:"text-sm font-medium [overflow-wrap:anywhere]",children:s.source}):null:i})}),s?(0,n.jsxs)(eX.vu,{children:[(0,n.jsx)(N.$,{size:"sm",variant:"outline",onClick:r,children:l("cancel")}),(0,n.jsx)(N.$,{size:"sm",variant:"del"===s.kind?"destructive":"default",onClick:()=>a(s),children:o})]}):null]})})}function si({basicMode:e=!1,snapshot:t,biz:s,onSnapshot:a,onRestartScheduled:i}){let{t:l}=(0,f.Bd)("pluginManagement"),{locale:o}=(0,tp.i)(),[d,c]=(0,r.useState)("installed"),[u,m]=(0,r.useState)(""),p=function({biz:e,onSnapshot:t,onRestartScheduled:s}){let{t:n}=(0,f.Bd)("pluginManagement"),a=(0,eI.t4)();(0,eI.So)();let[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)(()=>new Set),c=(0,r.useRef)(new Set),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)({}),[g,x]=(0,r.useState)(null),[b,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(null),N=(0,r.useRef)(0),I=(0,r.useRef)(0),C=(0,r.useRef)(!0),S=(e,t)=>{t?c.current.add(e):c.current.delete(e),C.current&&d(new Set(c.current))},M=(e,t)=>{C.current&&h(s=>{let n={...s};return t?n[e]=t:delete n[e],n})},z=async(s=!1)=>{let n=++I.current,r=await e.list(s);C.current&&n===I.current&&t(r)},E=async()=>{l(!0),M("list",null);try{await z(!0)}catch(e){M("list",e instanceof Error?e.message:n("updateCheckFailed"))}finally{C.current&&l(!1)}};(0,r.useEffect)(()=>{C.current=!0;let s=!0,r=++I.current;return queueMicrotask(()=>{s&&(l(!0),e.list(!1).then(e=>{s&&r===I.current&&t(e)}).catch(e=>{s&&M("list",e instanceof Error?e.message:n("updateCheckFailed"))}).finally(()=>{s&&l(!1)}))}),()=>{s=!1,C.current=!1,N.current+=1,I.current+=1}},[e,t,n]);let A=async r=>{let a="reload"===r.kind?"reload":tT("add"===r.kind?r.input.source:r.source);if(!c.current.has(a)){S(a,!0),m(null),M(a,null);try{let n="add"===r.kind?await e.add(r.input):"update"===r.kind?await e.update(r.source):"del"===r.kind?await e.del(r.source):"enable"===r.kind||"disable"===r.kind?await e.setEnabled(r.source,"enable"===r.kind):await e.reload(r.mode);if(!C.current)return;I.current+=1,t(n),"reload"===r.kind?s():await z()}catch(e){M(a,e instanceof Error?e.message:n("actionFailed",{action:n(tD(r))}))}finally{S(a,!1)}}},$=(e,t)=>{let s={kind:"add",input:e,package:t};t?.official===!0?A(s):m(s)},R=async s=>{let r=s?.[0]?tT(s[0]):"apply";if(!c.current.has(r)){S(r,!0),M(r,null);try{let n=await e.apply(s);C.current&&(I.current+=1,t(n),await z())}catch(e){M(r,e instanceof Error?e.message:n("actionFailed",{action:n("reloadOne")}))}finally{S(r,!1)}}},P=async(e,t)=>{if(!c.current.has(e)){S(e,!0),M(e,null);try{await t()}catch(t){M(e,t instanceof Error?t.message:n("retryFailed"))}finally{S(e,!1)}}},T=async t=>{let s=++N.current;y(!0),j(null);try{let n=await e.get(t);C.current&&s===N.current&&v(n)}catch(e){C.current&&s===N.current&&j(e instanceof Error?e.message:n("detailFailed"))}finally{C.current&&s===N.current&&y(!1)}};return{loading:i,requests:o,confirmation:u,setConfirmation:m,errors:p,detailSource:g,detail:b,detailLoading:w,detailError:k,pluginHost:a,refresh:E,execute:A,requestInstall:$,applyChanges:R,loadDetail:T,openDetail:e=>{x(e),v(null),T(e)},closeDetail:()=>{N.current+=1,x(null),v(null),j(null),y(!1)},handleControlAction:(e,t)=>{switch(t){case"reload":R([e.source]);break;case"update":A({kind:"update",source:e.source});break;case"remove":m({kind:"del",source:e.source});break;case"enable":case"disable":A({kind:t,source:e.source});break;case"retry-browser":e.pluginName&&P(`entry:${e.pluginName}`,()=>a.retryEntry(e.pluginName));break;case"retry":{let t=e.operation?.action;"apply"===t?R([e.source]):"add"===t?$({source:e.source}):t&&A({kind:t,source:e.source})}}},refreshEntries:()=>P("entries",()=>a.refreshEntries())}}({biz:s,onSnapshot:a,onRestartScheduled:i}),h=function(e,t){let{t:s}=(0,f.Bd)("pluginManagement"),[n,a]=(0,r.useState)(""),[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)("all"),[c,u]=(0,r.useState)("public"),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)([]),[x,b]=(0,r.useState)(!1),[v,w]=(0,r.useState)(1),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(null),[I,C]=(0,r.useState)(!1),[S,M]=(0,r.useState)(null),[z,E]=(0,r.useState)(null),[A,$]=(0,r.useState)(!1),[R,P]=(0,r.useState)(null),[T,D]=(0,r.useState)(()=>new Set),[L,O]=(0,r.useState)({}),F=(0,r.useRef)(0),B=(0,r.useRef)(0),_=(0,r.useRef)(new Set),q=(0,r.useRef)(null),[W,U]=(0,r.useState)(!1),[Y,V]=(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),b(s.hasMore),C(!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(()=>U(!0))},[t]),(0,r.useEffect)(()=>{if(!W||i)return;let e=++F.current;q.current=null,queueMicrotask(()=>{G.current&&e===F.current&&(k(!0),N(null),b(!1))});let t=setTimeout(()=>{let t="custom"===c?tL.safeParse(m):null;if(t&&!t.success){q.current=null,g([]),b(!1),C(!1),N(s("invalidRegistry")),k(!1);return}let r={query:n.trim(),kind:o,page:1,...t?.success?{registry:t.data}:{}};q.current=r,g([]),b(!1),C(!1),J(r,e)},300);return()=>clearTimeout(t)},[n,o,c,m,i,J,W,s]);let X=async(t,n=t.version)=>{let r=++B.current;$(!0),P(null),E(null),O(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&&E(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:a,composing:i,beginComposition:()=>{F.current+=1,q.current=null,k(!1),l(!0)},endComposition:()=>l(!1),kind:o,setKind:d,searchSource:c,setSearchSource:u,registry:m,setRegistry:p,items:h,loading:y,error:j,searched:I,hasMore:x,loadMore:()=>{q.current&&!y&&x&&J({...q.current,page:v+1},F.current)},retry:()=>{if(i||y)return;let e="custom"===c?tL.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}:{}};q.current=t,g([]),J(t,++F.current)},selection:S,detail:z,detailLoading:A,detailError:R,openDetail:e=>{M(e),X(e)},closeDetail:()=>{B.current+=1,M(null),E(null),$(!1),P(null)},loadDetail:X,prepareInstall:async(t,n)=>{if(!_.current.has(t.name)){_.current.add(t.name),D(new Set(_.current)),O(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 O(e=>({...e,[t.name]:s("installIncompatible")}));n(r)}catch(e){G.current&&O(n=>({...n,[t.name]:e instanceof Error?e.message:s("detailFailed")}))}finally{_.current.delete(t.name),G.current&&D(new Set(_.current))}}},preparing:T,installErrors:L,downloadMode:Y,setDownloadMode:V,downloadRegistry:K,setDownloadRegistry:H,installDetail:e=>{if(!z||A)return;if(!1===z.compatible)return void O(e=>({...e,[z.name]:s("installIncompatible")}));let t="default"===Y?null:tO.safeParse("custom"===Y?{mode:Y,registry:K}:{mode:Y});t&&!t.success?O(e=>({...e,[z.name]:s("invalidRegistry")})):(O(e=>{let t={...e};return delete t[z.name],t}),e({source:`npm:${z.name}@${z.version}`,registry:z.registry,...t?.success?{downloadSource:t.data}:{}},z))}}}(s,"search"===d),g=function(e){let{t}=(0,f.Bd)("pluginManagement"),[s,n]=(0,r.useState)(null),[a,i]=(0,r.useState)("auto"),[l,o]=(0,r.useState)(""),[d,c]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(null),g=(0,r.useRef)(!0),x=(0,r.useRef)(!1),b=(0,r.useRef)(0),v=(0,r.useRef)("load"),w=async()=>{let s=b.current;c(!0),h(null);try{let t=await e.getCatalogSettings();if(!g.current)return;s===b.current?(n(t),i(t.downloadSource.mode),"custom"===t.downloadSource.mode&&o(t.downloadSource.registry)):n(e=>e??t)}catch(e){v.current="load",g.current&&h(e instanceof Error?e.message:t("settingsFailed"))}finally{g.current&&c(!1)}};(0,r.useEffect)(()=>{g.current=!0;let e=!0;return queueMicrotask(()=>{e&&w()}),()=>{e=!1,g.current=!1}},[e]);let y=async(s=a)=>{if(x.current)return;let r=tO.safeParse("custom"===s?{mode:s,registry:l}:{mode:s});if(!r.success){v.current="save",h(t("invalidRegistry"));return}x.current=!0,m(!0),h(null);try{let t=await e.saveCatalogSettings(r.data);g.current&&(n(t),i(t.downloadSource.mode))}catch(e){v.current="save",g.current&&h(e instanceof Error?e.message:t("settingsFailed"))}finally{x.current=!1,g.current&&m(!1)}};return{settings:s,mode:a,registry:l,setRegistry:e=>{b.current+=1,o(e)},loading:d,saving:u,error:p,load:w,save:y,changeMode:e=>{b.current+=1,i(e),"custom"!==e&&y(e)},retry:()=>"save"===v.current?y():w()}}(s),x=function(e){let{t}=(0,f.Bd)("pluginManagement"),[s,n]=(0,r.useState)(!1),[a,i]=(0,r.useState)(""),[l,o]=(0,r.useState)(null),[d,c]=(0,r.useState)(!1),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)("default"),[g,x]=(0,r.useState)(""),b=(0,r.useRef)(0),v=(0,r.useRef)(!0),w=tR(a.trim());(0,r.useEffect)(()=>(v.current=!0,()=>{v.current=!1,b.current+=1}),[]);let y=()=>{b.current+=1,o(null),c(!1),m(null)},k=async s=>{let n;if(!w)return null;if("custom"===p){let e=tL.safeParse(g);if(!e.success)return m(t("invalidRegistry")),null;n=e.data}else"official"===p?n="https://registry.npmjs.org":"domestic"===p&&(n="https://registry.npmmirror.com");let r=++b.current;c(!0),o(null),m(null);try{let t=await e.getCatalog({...w,...s?{version:s}:{},...n?{registry:n}:{}});if(!v.current||r!==b.current)return null;return o(t),t}catch(e){return v.current&&r===b.current&&m(e instanceof Error?e.message:t("detailFailed")),null}finally{v.current&&r===b.current&&c(!1)}},j=async e=>{if(!a.trim()||d)return;if(m(null),!w)return void e({source:a.trim()});let s="default"===p?null:tO.safeParse("custom"===p?{mode:p,registry:g}:{mode:p});if(s&&!s.success)return void m(t("invalidRegistry"));let n=l?Promise.resolve(l):k(),r=b.current,i=await n;if(i&&v.current&&r===b.current){if(!1===i.compatible)return void m(t("installIncompatible"));e({source:`npm:${i.name}@${i.version}`,registry:i.registry,...s?.success?{downloadSource:s.data}:{}},i)}};return{open:s,setOpen:n,source:a,changeSource:e=>{y(),i(e)},spec:w,detail:l,loading:d,error:u,override:p,setOverride:e=>{y(),h(e)},registry:g,setRegistry:e=>{y(),x(e)},loadDetail:k,install:j}}(s),b=e||p.requests.has("reload"),v=new Map(p.pluginHost.getFailedEntries().map(e=>[e.pluginName,e.error.message])),w=p.pluginHost.getEntryListError(),y=t?.plugins.find(e=>e.source===p.detailSource),k=h.selection?t?.plugins.find(e=>e.source.startsWith("npm:")&&tR(e.source)?.name===h.selection?.name):void 0,j=h.selection?tT(`npm:${h.selection.name}`):"",I=tT(x.detail?`npm:${x.detail.name}`:x.spec?`npm:${x.spec.name}`:x.source.trim()),C=t?.plugins.find(e=>tT(e.source)===I),S=p.requests.has(j)||!!(k?.operation&&"failed"!==k.operation.phase),M=p.requests.has(I)||!!(C?.operation&&"failed"!==C.operation.phase),z=e=>e?l(`phase_${e}`):null;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)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h2",{className:"text-xl font-semibold",children:l("title")}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)(th.AM,{children:[(0,n.jsxs)(th.Wv,{render:(0,n.jsx)(N.$,{size:"sm",variant:"outline"}),children:[l("downloadSource"),":",g.loading&&!g.settings?l("loading"):l(`download_${g.settings?.downloadSource.mode??g.mode}`),(0,n.jsx)(ti.A,{className:"size-4"})]}),(0,n.jsx)(th.hl,{align:"end",positionerClassName:"z-[150]",children:(0,n.jsx)(tK,{id:"plugin-default-download",mode:g.mode,registry:g.registry,savedRegistry:g.settings?.downloadSource.mode==="custom"?g.settings.downloadSource.registry:void 0,recommendedRegistry:g.settings?.recommendedRegistry,loading:g.loading,saving:g.saving,error:g.error,onMode:e=>{"default"!==e&&g.changeMode(e)},onRegistry:g.setRegistry,onSave:()=>void g.save(),onRetry:()=>void g.retry()})})]}),e||t?.restartRequired?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:p.requests.has("reload"),onClick:()=>p.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||w?(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,tm.fD)(t.loadError,o)}):null,w?(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:w}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:p.requests.has("entries"),onClick:()=>void p.refreshEntries(),children:l("retry")})]}):null]}):null,p.errors.reload||p.errors.entries?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:p.errors.reload??p.errors.entries}):null]}),(0,n.jsx)("div",{role:"tablist","aria-label":l("title"),className:"flex shrink-0 gap-1 border-b px-4 pt-2 sm:px-6",children:["installed","search"].map(e=>(0,n.jsx)("button",{id:`plugin-tab-${e}`,type:"button",role:"tab","aria-selected":d===e,"aria-controls":`plugin-panel-${e}`,tabIndex:d===e?0:-1,className:`min-h-9 border-b-2 px-3 text-sm font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring ${d===e?"border-primary text-foreground":"border-transparent text-muted-foreground hover:bg-accent"}`,onClick:()=>c(e),onKeyDown:e=>{if(["ArrowLeft","ArrowRight","Home","End"].includes(e.key)){e.preventDefault();let t="Home"===e.key?"installed":"End"===e.key||"installed"===d?"search":"installed";c(t),document.getElementById(`plugin-tab-${t}`)?.focus()}},children:l("installed"===e?"installedTab":"searchPlugins")},e))}),(0,n.jsx)("div",{id:"plugin-panel-installed",role:"tabpanel","aria-labelledby":"plugin-tab-installed",tabIndex:0,hidden:"installed"!==d,className:`pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring sm:p-6 ${"installed"!==d?"hidden":""}`,children:(0,n.jsxs)("div",{className:"space-y-4",children:[x.open?(0,n.jsx)(sr,{source:x.source,isNpm:!!x.spec,detail:x.detail,loading:x.loading,pending:M,disabled:b,error:x.error??p.errors[I]??(C?.operation?.phase==="failed"?C.operation.message:null),operationMessage:M?z(C?.operation?.phase)??l("submitting"):null,override:x.override,registry:x.registry,onSource:x.changeSource,onMode:x.setOverride,onRegistry:x.setRegistry,onRead:()=>void x.loadDetail(),onVersion:e=>void x.loadDetail(e),onInstall:()=>void x.install(p.requestInstall),onClose:()=>x.setOpen(!1)}):null,(0,n.jsx)(tG,{snapshot:t,loading:p.loading,filter:u,disabled:b,requests:p.requests,errors:p.errors,browserErrors:v,onFilter:m,onDetail:e=>{h.closeDetail(),p.openDetail(e)},onAction:p.handleControlAction,onDirectInstall:()=>x.setOpen(!0),onRefresh:()=>void p.refresh()})]})}),(0,n.jsx)("div",{id:"plugin-panel-search",role:"tabpanel","aria-labelledby":"plugin-tab-search",tabIndex:0,hidden:"search"!==d,className:`pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring sm:p-6 ${"search"!==d?"hidden":""}`,children:(0,n.jsx)(tJ,{query:h.query,kind:h.kind,searchSource:h.searchSource,registry:h.registry,items:h.items,loading:h.loading,error:h.error,searched:h.searched,hasMore:h.hasMore,disabled:b,snapshot:t,requests:p.requests,preparing:h.preparing,errors:p.errors,installErrors:h.installErrors,onQuery:h.setQuery,onCompositionStart:h.beginComposition,onCompositionEnd:h.endComposition,onKind:h.setKind,onSearchSource:h.setSearchSource,onRegistry:h.setRegistry,onDetail:e=>{p.closeDetail(),h.openDetail(e)},onInstall:e=>{h.prepareInstall(e,e=>p.requestInstall({source:`npm:${e.name}@${e.version}`,registry:e.registry},e))},onUpdate:e=>void p.execute({kind:"update",source:e}),onMore:h.loadMore,onRetry:h.retry})}),(0,n.jsx)(sa,{open:!!(p.confirmation||p.detailSource||h.selection),title:y?tP(y):h.selection?.name??l("details"),confirmation:p.confirmation,onClose:()=>{p.confirmation?p.setConfirmation(null):(p.closeDetail(),h.closeDetail())},onConfirm:e=>void p.execute(e),children:y?(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[p.detail?.readme?(0,n.jsx)(st,{readme:p.detail.readme},y.source):null,(0,n.jsx)(t$,{plugin:y,detail:p.detail,detailLoading:p.detailLoading,detailError:p.detailError,browserContributions:y.pluginName?p.pluginHost.getRegisteredBrowserDescriptors().find(e=>e.pluginName===y.pluginName)?.contributions??[]:[],onRetry:()=>void p.loadDetail(y.source)})]}):h.selection?h.detailLoading?(0,n.jsx)("p",{role:"status",className:"py-4 text-sm text-muted-foreground",children:l("loadingPackage")}):h.detailError?(0,n.jsxs)("div",{role:"alert",className:"space-y-2 text-sm",children:[(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:h.detailError}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",onClick:()=>void h.loadDetail(h.selection),children:l("retry")})]}):h.detail?(0,n.jsx)(sn,{detail:h.detail,disabled:b,pending:S,installed:!!(k&&(k.operation?.action!=="add"||"failed"!==k.operation.phase)),installedVersion:k?.version??null,updateAvailable:!!k?.updateAvailable,error:h.installErrors[h.detail.name]??p.errors[j]??(k?.operation?.phase==="failed"?k.operation.message:null),operationMessage:z(k?.operation?.phase),downloadMode:h.downloadMode,downloadRegistry:h.downloadRegistry,onDownloadMode:h.setDownloadMode,onDownloadRegistry:h.setDownloadRegistry,onVersion:e=>void h.loadDetail(h.selection,e),onInstall:()=>h.installDetail(p.requestInstall),onUpdate:()=>{k&&p.execute({kind:"update",source:k.source})}}):null:p.detailSource?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:l("pluginRemoved")}):null})]})}var sl=s(77125);let so=a.Yj().trim().min(1).max(2048),sd=a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:tm.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0)}).strict(),sc=a.Yj().trim().min(1).max(4096),su=a.Yj().trim().min(1).max(256),sm=a.Yj().max(32768),sp=a.Ik({name:su,label:sm,state:a.k5(["active","inactive","shadowed"]),description:sm,promptSnippet:sm.nullable(),promptGuidelineCount:a.ai().int().nonnegative(),promptGuidelinePreview:sm.nullable()}).strict(),sh=a.Ik({name:su,label:sm,state:a.k5(["active","inactive","shadowed"]),description:sm,parameters:sl.Dz,promptSnippet:sm.nullable(),promptGuidelines:a.YO(sm)}).strict(),sg=a.Ik({path:sc,events:a.YO(a.Ik({name:su,count:a.ai().int().positive()}).strict()),commands:a.YO(a.Ik({name:su,description:sm.nullable()}).strict()),shortcuts:a.YO(a.Ik({shortcut:su,description:sm.nullable()}).strict()),flags:a.YO(a.Ik({name:su,type:a.k5(["boolean","string"]),description:sm.nullable(),default:a.KC([a.zM(),a.Yj(),a.ch()])}).strict()),messageRenderers:a.YO(su),entryRenderers:a.YO(su)}).strict(),sx=a.Ik({name:su,description:sm,path:sc}).strict(),sf=sx.extend({modelVisible:a.zM()}).strict(),sb=sx.extend({content:a.Yj().max(65536),truncated:a.zM()}).strict(),sv=sb.extend({modelVisible:a.zM()}).strict(),sw=a.Ik({name:su,path:sc}).strict(),sy=a.Ik({name:su,kind:a.k5(["config","native"])}).strict(),sk=a.Ik({methods:a.YO(a.Ik({pluginName:su,method:su}).strict()),browserEntries:a.YO(a.Ik({pluginName:su}).strict()),messageDeclarations:a.YO(a.Ik({pluginName:su,declarationName:su,priority:a.ai().int().safe()}).strict())}).strict(),sj=a.Ik({error:tm.qf.refine(e=>"string"==typeof e?e.length<=32768:[e.default,...Object.values(e.translations)].every(e=>e.length<=32768)).nullable(),extensions:a.YO(sg),tools:a.YO(sp),skills:a.YO(sf),prompts:a.YO(sx),themes:a.YO(sw),providers:a.YO(sy),piDesk:sk}).strict(),sN=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(),sI=(0,i._G)({path:"plugins/management-update",bodySchema:a.Ik({}).strict()}),sC=a.Ik({source:so,kind:a.k5(["package","extension"]).default("package"),operation:sN.nullable().default(null),pluginName:a.Yj().trim().min(1).nullable(),description:tm.qf.nullable().default(null),version:a.Yj().trim().min(1).nullable(),updateAvailable:a.zM().nullable(),status:a.k5(["ready","available","disabled","failed"]),error:sd.nullable(),capabilities:sj}).strict(),sS=a.Ik({source:so,readme:tm.qf.nullable().default(null),tools:a.YO(sh),skills:a.YO(sv),prompts:a.YO(sb)}).strict(),sM=a.Ik({plugins:a.YO(sC),restartRequired:a.zM(),loadError:tm.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0).nullable()}).strict(),sz=a.Ik({sources:a.YO(so).min(1).max(32).optional()}).strict(),sE=a.Ik({}).strict().extend({mode:a.k5(["normal","basic"]).optional()}).strict(),sA=a.Ik({checkUpdates:a.zM().optional()}).strict(),s$=a.Ik({source:so}).strict(),sR=s$.extend({downloadSource:tO.optional(),registry:tL.optional()}).strict(),sP=s$.extend({enabled:a.zM()}).strict();async function sT(e,t,s,n){return eF(e,t,s,n,{fallbackMessage:"插件管理请求失败"})}function sD({pluginName:e,descriptor:t,source:s,cwd:r,onPreviewFile:a,onRevealFile:i}){let l=`${s.workId}\u0000${s.sessionId}\u0000${s.branchId}\u0000${r}`;return(0,n.jsx)(td,{pluginName:e,kind:"session-sidebar-tab",contributionName:t.contributionName,target:{kind:"session-sidebar-tab",source:s,cwd:r,files:{preview:a,reveal:i}},targetKey:l,layout:"fill"})}function sL({pluginName:e,descriptor:t,onClose:s,onBeforeLeaveChange:a}){let i=(0,eI.t4)();(0,eI.So)();let l=i.getEntryState(e),o="ready"===l.status?l.runtime:l.status;(0,r.useEffect)(()=>()=>{a(null)},[o,a]);let d=(0,r.useMemo)(()=>({kind:"settings-page",close:()=>{i.getEntryState(e)===l&&s()},setBeforeLeave:t=>{i.getEntryState(e)===l&&a(t)}}),[l,a,s,e,i]);return(0,n.jsx)(td,{pluginName:e,kind:"settings-page",contributionName:t.contributionName,target:d,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})}var sO=s(84157),sF=s(56101),sB=s(49265),s_=s(37525),sq=s(77910);let sW="1.0.1-dev.9002".trim()||"未知",sU="2026-10-09T09:37:05+08:00".trim()||null;var sY=s(71052),sV=s(6747);let sK="pi-desk:power-saving",sH="pi-desk:power-saving-change",sG=null;function sJ(){if(null!==sG)return sG;try{sG="true"===window.localStorage.getItem(sK)}catch{sG=!1}return sG}function sX(e){let t=t=>{(null===t.key||t.key===sK)&&(sG=null,e())};return window.addEventListener(sH,e),window.addEventListener("storage",t),()=>{window.removeEventListener(sH,e),window.removeEventListener("storage",t)}}function sQ(){return(0,r.useSyncExternalStore)(sX,sJ,()=>!1)}function sZ(e,t){let s=(0,sV.I)(),n=sQ(),a=(0,r.useRef)(null);(0,r.useLayoutEffect)(()=>{let r=e.current,i=a.current!==t;if(a.current=t,!r||!t||!i||s||n)return;let l=r.animate([{opacity:0,transform:"translateY(5px)"},{opacity:1,transform:"translateY(0)"}],{duration:200,easing:"cubic-bezier(0.22, 1, 0.36, 1)"});return()=>l.cancel()},[e,t,n,s])}var s0=s(33541),s1=s(13937),s2=s(52632),s5=s(73704),s3=s(78511),s4=s(319);let s6=a.Yj().min(1).max(s4.uV).refine(e=>!e.includes("\0")&&(e.startsWith("/")||e.startsWith("\\\\")||/^[a-zA-Z]:[\\/]/.test(e)),"必须是绝对路径"),s8=a.Ik({cwd:s3.m4.nullable()}).strict(),s7=a.Ik({skillPath:s6,name:a.Yj().min(1),description:a.Yj(),packageSource:a.Yj().nullable()}).strict(),s9=a.Ik({skills:a.YO(s7),diagnostics:a.YO(a.Ik({path:a.Yj(),message:tm.qf}).strict())}).strict(),ne=s8.extend({skillPath:s6}),nt=ne.extend({path:s4.rh}).strict(),ns=a.Ik({entries:a.YO(a.Ik({name:a.Yj().min(1),type:a.k5(["directory","file"])}).strict()).max(s4.xm),truncated:a.zM()}).strict(),nn=ne.extend({path:s4._g}).strict(),nr=a.gM("kind",[a.Ik({kind:a.eu("text"),content:a.Yj(),size:a.ai().int().nonnegative().max(s4.NL),readOnlyReason:tm.qf.nullable()}).strict(),a.Ik({kind:a.eu("image"),mimeType:s4.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()]),na=nn.extend({content:a.Yj().max(s4.NL)}).strict(),ni=a.Ik({}).strict(),nl={path:"/api/skills/list",request:s8,response:s9},no={path:"/api/skill-files/list",request:nt,response:ns},nd={path:"/api/skill-files/get",request:nn,response:nr},nc={path:"/api/skill-files/replace",request:na,response:ni},nu=a.Ik({code:a.ai(),msg:a.Yj(),data:a.L5(),i18n:s2.N.optional()});async function nm(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}),a=nu.parse(await r.json());if(!r.ok||0!==a.code||null===a.data)throw Error(a.msg?(0,eO.B)(a):"Skills 请求失败");return t.response.parse(a.data)}function np(e){(0,s5.ZQ)({wrapLines:e})}async function nh(e){let t=e.skillPath.replaceAll("\\","/");await navigator.clipboard.writeText(t.slice(0,t.lastIndexOf("/")+1)+e.path)}var ng=s(14312);function nx(e){return(0,eO.B)({msg:ng.P["zh-CN"][e],i18n:{key:`skills:${e}`}})}function nf(e){return JSON.stringify(e)}function nb(e){return JSON.stringify([e.cwd,e.skillPath,e.path])}function nv(e){return e.replace(/\r\n|\r/g,"\n")}function nw(e){return e?.file?.kind==="text"&&e.draft!==nv(e.file.content)}var ny=s(38948),nk=s(52979),nj=s(90578),nN=s(32168);function nI(e){let{t}=(0,f.Bd)("common"),{wrapLines:s}=(0,s5.TX)(),a=e.path,i=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useRef)(null),d=(0,r.useRef)(null),c=(0,r.useRef)(null),u=(0,r.useRef)(0),m=(0,r.useRef)(e),[p,h]=(0,r.useState)(!1),[g,x]=(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,nN.cu)().then(r=>{if(e||!i.current)return;let a=m.current,o=r.editor.create(i.current,{model:null,theme:(0,nN.dC)(),automaticLayout:!0,readOnly:a.readOnly,domReadOnly:a.readOnly,wordWrap:(0,s5.E6)().wrapLines?"on":"off",wrappingIndent:"same",minimap:{enabled:!1},stickyScroll:{enabled:!1},scrollBeyondLastLine:!1,...(0,nN.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,nN.Tr)(e=>r.editor.setTheme(e)),n=(0,nN.BK)(e=>o.updateOptions(e)),x(!0)}).catch(()=>{e||h(!0)}),()=>{e=!0,s(),n(),d.current?.dispose(),d.current=null,o.current?.dispose(),o.current=null,c.current=null,l.current?.dispose(),l.current=null}},[t]),(0,r.useEffect)(()=>{let e=!1,t=u.current+1;return u.current=t,(0,nN.cu)().then(s=>{if(e||t!==u.current||!l.current)return;let n=m.current,r=s.editor.createModel(n.content,(0,nN.ix)(n.path,n.size),(0,nN.B3)(s,n.path,"edit")),i=o.current;d.current?.dispose(),d.current=r.onDidChangeContent(()=>{m.current.onChange(r.getValue(s.editor.EndOfLinePreference.LF))}),o.current=r,c.current=a,l.current.setModel(r),i?.dispose()}),()=>{e=!0}},[a]),(0,r.useEffect)(()=>{let t=o.current;t&&c.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:i,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 nC=s(55734);function nS({file:e,path:t}){let{t:s}=(0,f.Bd)("skills"),a=(0,r.useMemo)(()=>[{src:`data:${e.mimeType};base64,${e.data}`,alt:t}],[e,t]);return(0,n.jsx)(nC.k,{mode:"inline",slides:a,className:"h-full w-full",ariaLabel:s("imagePreview")})}function nM(e){let{document:t,skill:s,dirty:r,loading:a,saving:i,opening:l}=e,{t:o}=(0,f.Bd)("skills"),{locale:d}=(0,tp.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)(ny.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 c=t.file,u=c?.kind==="text"?c.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})]}),c?.kind==="text"&&(0,n.jsxs)("span",{role:"status","aria-label":o(i?"saving":l?"switchingFile":r?"unsavedChanges":u?"readOnlyFile":"fileSaved"),className:"hidden shrink-0 items-center gap-1 text-xs text-muted-foreground sm:flex",children:[i||l?(0,n.jsx)(b.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)(nk.A,{className:"size-3.5"}):(0,n.jsx)(ed.A,{className:"size-3.5"}),o(i?"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)(N.$,{variant:"ghost",size:"icon","aria-label":o("copySkillPath"),title:o("copyPath"),onClick:e.onCopy,children:(0,n.jsx)(eM.A,{className:"size-4"})}),(0,n.jsxs)(N.$,{"aria-label":o("saveSkill"),disabled:!r||!!u||a||i,onClick:e.onSave,children:[i?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(eS.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)(nk.A,{className:"mt-0.5 size-3.5 shrink-0"}),(0,n.jsx)("p",{children:(0,tm.fD)(u,d)})]}),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,!c&&(0,n.jsx)(N.$,{variant:"ghost",size:"sm",onClick:e.onReload,children:o("reload")})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:a&&!c?(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)(b.A,{className:"size-4 animate-spin"}),o("loadingFile")]}):c?.kind==="text"?(0,n.jsx)(nI,{path:t.target.skillPath.slice(0,t.target.skillPath.lastIndexOf("/")+1)+t.target.path,content:t.draft,size:c.size,readOnly:!!u||i||l,onChange:e.onChange,onSave:e.onSave}):c?.kind==="image"?(0,n.jsx)(nS,{file:c,path:t.target.path}):c?.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)(ny.A,{className:"mb-2 size-8"}),(0,n.jsx)("p",{children:c.reason}),(0,n.jsx)("p",{children:o("fileSize",{size:c.size.toLocaleString("en"===d?"en-US":"zh-CN")})})]}):null}),c?.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)(N.$,{variant:"ghost",size:"sm","aria-label":o("wrapLines"),"aria-pressed":e.wrapLines,onClick:e.onWrapLines,children:[(0,n.jsx)(nj.A,{className:"size-3.5"}),o("wrapLines")]})]})]})}function nz({open:e,saving:t,path:s,error:r,onDecide:a}){let{t:i}=(0,f.Bd)("skills");return(0,n.jsx)(eX.YV,{open:e,onOpenChange:e=>{e||t||a("cancel")},children:(0,n.jsxs)(eX.hA,{className:"z-[150]",showCloseButton:!t,children:[(0,n.jsxs)(eX.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eX.YM,{children:i("saveChangesTitle")}),(0,n.jsx)(eX.uX,{children:i("saveChangesDescription",{path:s??""})})]}),r&&(0,n.jsx)("p",{role:"alert",className:"px-4 pb-4 text-sm text-destructive",children:r}),(0,n.jsxs)(eX.vu,{children:[(0,n.jsx)(N.$,{variant:"outline",disabled:t,onClick:()=>void a("cancel"),children:i("cancel")}),(0,n.jsx)(N.$,{variant:"ghost",disabled:t,onClick:()=>void a("discard"),children:i("discard")}),(0,n.jsx)(N.$,{disabled:t,onClick:()=>void a("save"),children:i(t?"savingChanges":"saveContinue")})]})]})})}var nE=s(30406),nA=s(42904),n$=s(87001);function nR(e,t){return!!(e&&e.cwd===t.cwd&&e.skillPath===t.skillPath&&e.path===t.path)}function nP({target:e,props:t,depth:s=0,skillName:a}){let{t:i}=(0,f.Bd)("skills"),l=t.directories[nb(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)(N.$,{variant:"ghost",size:"sm",onClick:()=>void t.onLoadDirectory(e),children:i("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)(nT,{target:o,props:t,depth:s,name:r.name,skillName:a},l);let d=nR(t.selected,o),c=nR(t.pending,o);return(0,n.jsxs)(N.$,{variant:"ghost","aria-label":i("skillFile",{path:`${a}/${l}`}),"aria-pressed":d,title:l,className:(0,C.cn)("min-h-9 w-full justify-start text-left font-normal text-muted-foreground",d&&"font-medium",c&&"bg-muted text-foreground"),onClick:()=>void t.onOpenFile(o),children:["SKILL.md"===r.name?(0,n.jsx)(nE.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(ny.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r.name}),c&&(0,n.jsx)(b.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:i("emptyFolder")}),l.data.truncated&&(0,n.jsx)("p",{className:"px-3 py-2 text-sm text-status-warning",children:i("folderTruncated")})]}):(0,n.jsx)("p",{role:"status",className:"px-4 py-2 text-xs text-muted-foreground",children:i("loadingFolder")})}function nT({target:e,props:t,depth:s,name:a,skillName:i}){let{t:l}=(0,f.Bd)("skills"),[o,d]=(0,r.useState)(!1);return(0,n.jsxs)("div",{children:[(0,n.jsxs)(N.$,{variant:"ghost","aria-expanded":o,"aria-label":l("skillFolder",{path:`${i}/${e.path}`}),className:(0,C.cn)("min-h-9 w-full justify-start font-normal text-muted-foreground",o&&"bg-muted text-foreground"),onClick:()=>d(!o),children:[o?(0,n.jsx)(ti.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(eo.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)(e8.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:a})]}),o&&(0,n.jsx)("div",{className:s>3?"-ml-3":void 0,children:(0,n.jsx)(nP,{target:e,props:t,depth:s+1,skillName:i})})]})}function nD({cwd:e,skill:t,props:s}){let{t:a}=(0,f.Bd)("skills"),i=s.selected?.cwd===e&&s.selected.skillPath===t.skillPath,l=s.pending?.cwd===e&&s.pending.skillPath===t.skillPath,[o,d]=(0,r.useState)(null),c=o??i,u=async()=>{if(c)return void d(!1);let n=t.skillPath.replaceAll("\\","/").split("/").at(-1);await s.onOpenFile({cwd:e,skillPath:t.skillPath,path:n})&&d(!0)};return(0,n.jsxs)("div",{className:"py-0.5",children:[(0,n.jsxs)(N.$,{variant:"ghost","aria-label":a("skillName",{name:t.name}),"aria-expanded":c,title:`${t.description}
154
+ location: ${e.path}`})}):null,(0,n.jsx)(tz,{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)(tz,{title:t("viewPromptContent"),content:e.content,truncated:e.truncated})]},e.path))]})})}function tA({capabilities:e,browserContributions:t}){let{t:s}=(0,f.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),a=e.piDesk.methods.length>0||e.piDesk.browserEntries.length>0||e.piDesk.messageDeclarations.length>0||t.length>0,i=e.themes.length>0||e.providers.length>0;return r||a||i?(0,n.jsx)(tI,{title:s("otherCapabilities"),children:(0,n.jsxs)("div",{className:"space-y-2",children:[a?(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(tv[e.kind]),":","message-view"===e.kind?e.viewKey:"application"===e.kind?e.title: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,i?(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 t$({plugin:e,detail:t,detailLoading:s,detailError:r,browserContributions:a,onRetry:i}){let{t:l}=(0,f.Bd)("pluginManagement"),{locale:o}=(0,tp.i)(),d=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 a=tw(e).reduce((e,t)=>e+t.count,0);a>0&&n.push({label:s("tagDynamic",{count:a}),tone:"dynamic"});let i=e.tools.filter(e=>"shadowed"!==e.state&&tx.has(e.name)).length;i>0&&n.push({label:s("tagOverride",{count:i}),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 d=e.providers.length+e.themes.length+e.extensions.reduce((e,t)=>e+t.commands.length+t.shortcuts.length+t.flags.length,0);return d>0&&n.push({label:s("tagInteraction",{count:d}),tone:"neutral"}),0===n.length&&e.extensions.length>0&&n.push({label:`Extension ${e.extensions.length}`,tone:"neutral"}),n}(e.capabilities,a,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}),d.length>0?(0,n.jsx)("div",{className:"flex flex-wrap gap-2","aria-label":l("capabilityCategories"),children:d.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,tm.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)(b.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)(N.$,{type:"button",size:"sm",variant:"outline",onClick:i,children:[(0,n.jsx)(eE.A,{"data-icon":"inline-start"}),l("retry")]})]}):t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(tM,{detail:t}),(0,n.jsx)(tE,{detail:t})]}):null,(0,n.jsx)(tC,{capabilities:e.capabilities}),(0,n.jsx)(tA,{capabilities:e.capabilities,browserContributions:a})]})}function tR(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 tP(e){return e.source.startsWith("npm:")?tR(e.source)?.name??e.source:e.pluginName??("extension"===e.kind?e.source.replaceAll("\\","/").split("/").at(-1):null)??e.source}function tT(e){return`source:${e.startsWith("npm:")?tR(e)?.name??e:e}`}function tD(e){switch(e.kind){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 tL=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 仓库地址"),tO=a.gM("mode",[a.Ik({mode:a.eu("auto")}).strict(),a.Ik({mode:a.eu("official")}).strict(),a.Ik({mode:a.eu("domestic")}).strict(),a.Ik({mode:a.eu("custom"),registry:tL}).strict()]),tF=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),tF).optional()}).passthrough().optional()}).passthrough();let tB=a.Ik({downloadSource:tO,recommendedRegistry:tL}).strict(),t_=a.Ik({downloadSource:tO}).strict(),tq=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:tL.optional()}).strict(),tW=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:tL.optional()}).strict(),tU=a.Ik({name:a.Yj(),description:tm.qf.nullable(),version:a.Yj(),publisher:a.Yj().nullable(),kind:a.k5(["desk","pi","unknown"]),official:a.zM(),registry:tL}).strict(),tY=a.Ik({items:a.YO(tU),hasMore:a.zM()}).strict(),tV=tU.extend({versions:a.YO(a.Yj()),readme:tm.qf.nullable(),homepage:a.Yj().nullable(),repository:a.Yj().nullable(),compatible:a.zM().nullable(),compatibilityNote:a.Yj().nullable()}).strict();function tK({id:e,mode:t,registry:s,recommendedRegistry:r,savedRegistry:a,loading:i,saving:l,error:o,override:d,onMode:c,onRegistry:u,onSave:m,onRetry:p}){let{t:h}=(0,f.Bd)("pluginManagement"),g="auto"===t?r:"official"===t?"https://registry.npmjs.org":"domestic"===t?"https://registry.npmmirror.com":"custom"===t?a??s:null;return(0,n.jsxs)("div",{className:"min-w-0 space-y-2 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(d?"installDownloadSource":"downloadSource")}),(0,n.jsxs)("select",{id:e,value:t,disabled:l,onChange:e=>c(e.target.value),className:"min-h-8 max-w-full rounded-lg border border-input bg-background px-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",children:[d?(0,n.jsx)("option",{value:"default",children:h("useDefaultSource")}):null,["auto","domestic","official","custom"].map(e=>(0,n.jsx)("option",{value:e,children:h(`download_${e}`)},e))]}),i?(0,n.jsx)("span",{role:"status",className:"text-muted-foreground",children:h("recommending")}):null,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)(eB.p,{id:`${e}-url`,type:"url",value:s,placeholder:"https://registry.example.com",className:"min-w-0 flex-1 basis-48",onChange:e=>u(e.target.value)}),m?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:l,onClick:m,children:h("save")}):null]})]}):null,d?null:(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{className:"cursor-pointer py-1 text-muted-foreground",children:h("sourceDetails")}),(0,n.jsx)("p",{className:"mt-1 break-all text-muted-foreground",children:g??h("recommending")})]}),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)(N.$,{variant:"outline",size:"sm",onClick:p,children:h("retry")}):null]}):null]})}function tH({plugin:e,displayName:t,browserError:s,requestError:r,disabled:a,pending:i,browserRetryPending:l,onAction:o}){let{t:d}=(0,f.Bd)("pluginManagement"),{locale:c}=(0,tp.i)(),u=e.operation?.phase,m=!!(e.operation&&"failed"!==u),p="disabled"!==e.status,h="failed"===e.status||null!==s,g=e.error?(0,tm.fD)(e.error.message,c):null,x=d(m?`phase_${u}`:h?"notLoaded":p?"enabled":"disabled");return(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[m||i||h?(0,n.jsxs)("span",{role:"status",className:`inline-flex items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs ${h&&!m?"text-destructive":"text-muted-foreground"}`,children:[m&&"waiting"!==u?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}):null,i&&!m?d("submitting"):x]}):null,"extension"===e.kind?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:d("localExtension")}):null,(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",role:"switch","aria-checked":p,"aria-label":d("togglePlugin",{name:t}),disabled:a||i,onClick:()=>o(p?"disable":"enable"),children:[(0,n.jsx)("span",{"aria-hidden":"true",className:`flex h-4 w-7 items-center rounded-full p-0.5 ${p?"bg-primary":"bg-muted-foreground"}`,children:(0,n.jsx)("span",{className:`size-3 rounded-full bg-primary-foreground transition-transform ${p?"translate-x-3":""}`})}),d(p?"enabled":"disabled")]}),e.updateAvailable&&"extension"!==e.kind?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:a||i,onClick:()=>o("update"),children:d("update")}):null,"extension"!==e.kind?(0,n.jsxs)(N.$,{size:"sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive",disabled:a||i,onClick:()=>o("remove"),children:[(0,n.jsx)(ez.A,{"data-icon":"inline-start"}),d("remove")]}):null,"failed"===u?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:a||i,onClick:()=>o("retry"),children:d("retry")}):null,s&&e.pluginName?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:a||l,onClick:()=>o("retry-browser"),children:d("retryView")}):null,(0,n.jsxs)("details",{className:"text-sm",children:[(0,n.jsx)("summary",{className:"cursor-pointer rounded-lg px-2 py-1.5 outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",children:d("more")}),(0,n.jsx)(N.$,{size:"sm",variant:"ghost",className:"mt-1",disabled:a||i&&"waiting"!==u,"aria-label":d("reloadSource",{name:t}),onClick:()=>o("reload"),children:d("reloadOne")})]})]}),e.operation?.message?(0,n.jsx)("p",{className:`whitespace-pre-wrap text-sm [overflow-wrap:anywhere] ${"failed"===u?"text-destructive":"text-muted-foreground"}`,children:e.operation.message}):null,[r,g,s].filter((t,s,n)=>t&&n.indexOf(t)===s&&t!==e.operation?.message).map(e=>(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive [overflow-wrap:anywhere]",children:e},e))]})}function tG({snapshot:e,loading:t,filter:s,disabled:r,requests:a,errors:i,browserErrors:l,onFilter:o,onDetail:d,onAction:c,onDirectInstall:u,onRefresh:m}){let{t:p}=(0,f.Bd)("pluginManagement"),{locale:h}=(0,tp.i)(),g=e?.plugins.filter(e=>`${tP(e)} ${e.description?(0,tm.fD)(e.description,h):""}`.toLocaleLowerCase().includes(s.toLocaleLowerCase()))??[];return(0,n.jsxs)("section",{"aria-label":p("installed"),className:"min-w-0 space-y-4",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:"plugin-installed-filter",className:"sr-only",children:p("filterInstalled")}),(0,n.jsx)(eB.p,{id:"plugin-installed-filter",value:s,onChange:e=>o(e.target.value),placeholder:p("filterInstalled"),className:"min-w-0 flex-1 basis-48"}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:t,onClick:m,children:p(t?"checkingUpdates":"checkUpdates")}),(0,n.jsx)(N.$,{size:"sm",disabled:r,onClick:u,children:p("directInstall")})]}),i.list?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:i.list}):null,t&&!e?(0,n.jsx)("p",{role:"status",className:"py-6 text-sm text-muted-foreground",children:p("loading")}):g.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:g.map(e=>{let t=tP(e),s=tT(e.source);return(0,n.jsxs)("article",{className:"min-w-0 space-y-3 p-4",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,n.jsx)(N.$,{variant:"link",className:"h-auto min-w-0 max-w-full justify-start p-0 text-left text-sm font-semibold whitespace-normal [overflow-wrap:anywhere]","aria-label":p("viewDetails",{name:t}),onClick:()=>d(e.source),children:t}),e.version?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",e.version]}):null]}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.description?(0,tm.fD)(e.description,h):p("noPluginDescription")}),(0,n.jsx)(tH,{plugin:e,displayName:t,browserError:e.pluginName?l.get(e.pluginName)??null:null,requestError:i[s]??i[`entry:${e.pluginName}`],disabled:r,pending:a.has(s)||!!(e.operation&&"failed"!==e.operation.phase),browserRetryPending:a.has(`entry:${e.pluginName}`),onAction:t=>c(e,t)})]},e.source)})}):(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:p(s?"noMatches":"empty")})]})}function tJ(e){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,tp.i)(),r=new Map(e.snapshot?.plugins.filter(e=>e.source.startsWith("npm:")).map(e=>[tR(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:"space-y-3",children:[(0,n.jsx)("label",{htmlFor:"plugin-catalog-query",className:"sr-only",children:t("searchPlugins")}),(0,n.jsx)(eB.p,{id:"plugin-catalog-query",value:e.query,placeholder:t("searchPlaceholder"),maxLength:200,onChange:t=>e.onQuery(t.target.value),onCompositionStart:e.onCompositionStart,onCompositionEnd:e.onCompositionEnd}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-3",children:[(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm",children:[t("searchSource"),(0,n.jsxs)("select",{value:e.searchSource,onChange:t=>e.onSearchSource(t.target.value),className:"min-h-8 rounded-lg border border-input bg-background px-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)("option",{value:"public",children:t("publicNpm")}),(0,n.jsx)("option",{value:"custom",children:t("customSearchSource")})]})]}),(0,n.jsxs)("label",{className:"flex items-center gap-2 text-sm",children:[t("pluginKind"),(0,n.jsx)("select",{value:e.kind,onChange:t=>e.onKind(t.target.value),className:"min-h-8 rounded-lg border border-input bg-background px-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",children:["all","desk","pi"].map(e=>(0,n.jsx)("option",{value:e,children:t(`kind_${e}`)},e))})]})]}),"custom"===e.searchSource?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:"plugin-search-registry",className:"block text-sm",children:t("searchRegistryUrl")}),(0,n.jsx)(eB.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)(N.$,{size:"sm",variant:"outline",onClick:e.onRetry,children:t("retry")})]}):null,e.items.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:e.items.map(a=>{let i=r.get(a.name),l=tT(`npm:${a.name}`),o=i?.description??a.description,d=!!(i?.operation&&"failed"!==i.operation.phase),c=e.requests.has(l)||d||e.preparing.has(a.name),u=i&&(i.operation?.action!=="add"||"failed"!==i.operation.phase),m=e.installErrors[a.name]??e.errors[l]??(i?.error?(0,tm.fD)(i.error.message,s):null);return(0,n.jsxs)("article",{className:"min-w-0 space-y-2 p-4",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-2",children:[(0,n.jsx)(N.$,{variant:"link",className:"h-auto min-w-0 max-w-full p-0 text-left text-sm font-semibold whitespace-normal [overflow-wrap:anywhere]",onClick:()=>e.onDetail(a),children:a.name}),(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",a.version]}),a.official?(0,n.jsx)("span",{className:"rounded-md bg-secondary px-1.5 py-0.5 text-xs text-secondary-foreground",children:t("official")}):null,(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`kind_${a.kind}`)})]}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:o?(0,tm.fD)(o,s):t("noPluginDescription")}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 text-xs text-muted-foreground [overflow-wrap:anywhere]",children:a.publisher??t("unknownPublisher")}),c?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:d?t(`phase_${i?.operation?.phase}`):e.preparing.has(a.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")}),i.updateAvailable?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onUpdate(i.source),children:t("update")}):null]}):(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onInstall(a),children:t("install")})]}),m?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:m}):null,i?.operation?.phase==="failed"&&i.operation.message?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:i.operation.message}):null]},a.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)(N.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onMore,children:t("loadMore")}):null]})}let tX=(0,s(11550).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 tQ({className:e,orientation:t,...s}){return(0,n.jsx)("div",{role:"group","data-slot":"button-group","data-orientation":t,className:(0,C.cn)(tX({orientation:t}),e),...s})}var tZ=s(71558),t0=s(86049),t1=s(74082),t2=s(67935),t5=s(67446),t3=s(9486);let t4=({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}),t6=({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}),t8=({tooltip:e,children:t,label:s,variant:r="ghost",size:a="icon-sm",...i})=>{let l=(0,n.jsxs)(N.$,{size:a,type:"button",variant:r,...i,children:[t,(0,n.jsx)("span",{className:"sr-only",children:s||e})]});return e?(0,n.jsx)(tZ.Bc,{children:(0,n.jsxs)(tZ.m_,{children:[(0,n.jsx)(tZ.k$,{render:l}),(0,n.jsx)(tZ.ZI,{children:(0,n.jsx)("p",{children:e})})]})}):l},t7={cjk:t0.h,code:t1.a,math:t2.D,mermaid:t5.a},t9=(0,r.memo)(({className:e,...t})=>(0,n.jsx)(t3.jH,{className:(0,C.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),plugins:t7,...t}),(e,t)=>e.children===t.children&&t.isAnimating===e.isAnimating);t9.displayName="MessageResponse";let se=({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 st({readme:e}){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,tp.i)(),[a,i]=(0,r.useState)(null),l=e&&"string"!=typeof e?e.translations:{},o=Object.keys(l).filter(e=>/^(zh(?:-|$)|en(?:-|$))/.test(e)),d=a&&void 0!==l[a]?a:null,c=e?d?l[d]:(0,tm.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)("label",{className:"flex items-center gap-2 text-sm",children:[t("readmeLanguage"),(0,n.jsxs)("select",{value:d??"",onChange:e=>i(e.target.value||null),className:"min-h-8 rounded-lg border border-input bg-background px-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)("option",{value:"",children:t("defaultLanguage")}),o.map(e=>(0,n.jsx)("option",{value:e,children:e.startsWith("zh")?"中文":"English"},e))]})]}):null]}),c?(0,n.jsx)("div",{className:"min-w-0 overflow-x-auto text-base leading-relaxed [overflow-wrap:anywhere]",children:(0,n.jsx)(t9,{mode:"static",isAnimating:!1,skipHtml:!0,controls:!1,className:"min-w-0 [&_img]:max-w-full [&_pre]:overflow-x-auto",children:c})}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:t("noReadme")})]})}function ss(e){if(!e)return null;try{let t=new URL(e);return["https:","http:"].includes(t.protocol)?t.href:null}catch{return null}}function sn(e){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,tp.i)(),r=e.detail,a=e.installed&&e.installedVersion===r.version,i=ss(r.homepage),l=ss(r.repository);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:[r.official?(0,n.jsx)("span",{className:"rounded-md bg-secondary px-2 py-1 text-secondary-foreground",children:t("official")}):null,(0,n.jsx)("span",{children:t(`kind_${r.kind}`)}),(0,n.jsx)("span",{className:"[overflow-wrap:anywhere]",children:r.publisher??t("unknownPublisher")})]}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:r.description?(0,tm.fD)(r.description,s):t("noPluginDescription")}),(0,n.jsxs)("label",{className:"flex flex-wrap items-center gap-2 text-sm",children:[t("version"),(0,n.jsx)("select",{value:r.version,onChange:t=>e.onVersion(t.target.value),className:"min-h-8 min-w-0 max-w-full rounded-lg border border-input bg-background px-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[...new Set([r.version,...r.versions])].map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:t(!0===r.compatible?"compatible":!1===r.compatible?"incompatible":"compatibilityUnknown")}),r.compatibilityNote?(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:r.compatibilityNote}):null,(0,n.jsxs)("div",{className:"flex flex-wrap gap-3 text-sm",children:[i?(0,n.jsx)("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-4",children:t("homepage")}):null,l?(0,n.jsx)("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-4",children:t("repository")}):null]}),a?null:(0,n.jsx)(tK,{id:"plugin-detail-download",mode:e.downloadMode,registry:e.downloadRegistry,override:!0,onMode:e.onDownloadMode,onRegistry:e.onDownloadRegistry}),(0,n.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:e.pending?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:e.operationMessage??t("submitting")}):a?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),e.updateAvailable?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:e.onUpdate,children:t("update")}):null]}):(0,n.jsx)(N.$,{size:"sm",disabled:e.disabled,onClick:e.onInstall,children:t(e.installed?"installVersion":"install")})}),e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.error}):null]}),(0,n.jsx)("div",{className:"border-t pt-4",children:(0,n.jsx)(st,{readme:r.readme},`${r.name}@${r.version}`)})]})}function sr(e){let{t}=(0,f.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)(N.$,{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)(eB.p,{id:"plugin-direct-source",value:e.source,placeholder:t("sourcePlaceholder"),onChange:t=>e.onSource(t.target.value)}),e.isNpm?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onRead,children:t(e.loading?"loadingPackage":"readPackage")}),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)("label",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[t("version"),(0,n.jsx)("select",{value:e.detail.version,disabled:e.loading,onChange:t=>e.onVersion(t.target.value),className:"min-h-8 min-w-0 max-w-full rounded-lg border border-input bg-background px-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[...new Set([e.detail.version,...e.detail.versions])].map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]})]}):null,(0,n.jsx)(tK,{id:"plugin-direct-download",mode:e.override,registry:e.registry,override:!0,onMode:e.onMode,onRegistry:e.onRegistry})]}):null,e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm 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)(N.$,{size:"sm",disabled:e.disabled||e.loading||e.pending||!e.source.trim(),onClick:e.onInstall,children:t(e.pending?"installing":"install")})]})}function sa({open:e,title:t,confirmation:s,onClose:r,onConfirm:a,children:i}){let{t:l}=(0,f.Bd)("pluginManagement"),o=s?l(tD(s)):null;return(0,n.jsx)(eX.YV,{open:e,onOpenChange:e=>{e||r()},children:(0,n.jsxs)(eX.hA,{finalFocus:!0,className:s?"max-w-lg":"h-[min(85dvh,52rem)] max-w-3xl",children:[(0,n.jsxs)(eX.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eX.YM,{className:"min-w-0 [overflow-wrap:anywhere]",children:s?l("confirmAction",{action:o}):t}),(0,n.jsx)(eX.uX,{children:l(s?"del"===s.kind?"removeDescription":"add"===s.kind?"thirdPartyDescription":"reload"===s.kind?"normal"===s.mode?"restartNormalDescription":"restartDescription":"confirmChange":"pluginDetails")})]}),(0,n.jsx)(eX._Y,{className:"min-h-0",children:(0,n.jsx)("div",{className:"min-w-0 p-4 pt-0",children:s?"add"===s.kind?(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:l("packageName")}),(0,n.jsx)("dd",{className:"mt-1 font-medium [overflow-wrap:anywhere]",children:s.package?.name??s.input.source})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:l("version")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:s.package?.version??tR(s.input.source)?.version??l("fromSource")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:l("publisher")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:s.package?.publisher??l("unknownPublisher")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:l("source")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:s.input.registry??s.package?.registry??s.input.source})]})]}):"reload"!==s.kind?(0,n.jsx)("p",{className:"text-sm font-medium [overflow-wrap:anywhere]",children:s.source}):null:i})}),s?(0,n.jsxs)(eX.vu,{children:[(0,n.jsx)(N.$,{size:"sm",variant:"outline",onClick:r,children:l("cancel")}),(0,n.jsx)(N.$,{size:"sm",variant:"del"===s.kind?"destructive":"default",onClick:()=>a(s),children:o})]}):null]})})}function si({basicMode:e=!1,snapshot:t,biz:s,onSnapshot:a,onRestartScheduled:i}){let{t:l}=(0,f.Bd)("pluginManagement"),{locale:o}=(0,tp.i)(),[d,c]=(0,r.useState)("installed"),[u,m]=(0,r.useState)(""),p=function({biz:e,onSnapshot:t,onRestartScheduled:s}){let{t:n}=(0,f.Bd)("pluginManagement"),a=(0,eI.t4)();(0,eI.So)();let[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)(()=>new Set),c=(0,r.useRef)(new Set),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)({}),[g,x]=(0,r.useState)(null),[b,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(null),N=(0,r.useRef)(0),I=(0,r.useRef)(0),C=(0,r.useRef)(!0),S=(e,t)=>{t?c.current.add(e):c.current.delete(e),C.current&&d(new Set(c.current))},M=(e,t)=>{C.current&&h(s=>{let n={...s};return t?n[e]=t:delete n[e],n})},z=async(s=!1)=>{let n=++I.current,r=await e.list(s);C.current&&n===I.current&&t(r)},E=async()=>{l(!0),M("list",null);try{await z(!0)}catch(e){M("list",e instanceof Error?e.message:n("updateCheckFailed"))}finally{C.current&&l(!1)}};(0,r.useEffect)(()=>{C.current=!0;let s=!0,r=++I.current;return queueMicrotask(()=>{s&&(l(!0),e.list(!1).then(e=>{s&&r===I.current&&t(e)}).catch(e=>{s&&M("list",e instanceof Error?e.message:n("updateCheckFailed"))}).finally(()=>{s&&l(!1)}))}),()=>{s=!1,C.current=!1,N.current+=1,I.current+=1}},[e,t,n]);let A=async r=>{let a="reload"===r.kind?"reload":tT("add"===r.kind?r.input.source:r.source);if(!c.current.has(a)){S(a,!0),m(null),M(a,null);try{let n="add"===r.kind?await e.add(r.input):"update"===r.kind?await e.update(r.source):"del"===r.kind?await e.del(r.source):"enable"===r.kind||"disable"===r.kind?await e.setEnabled(r.source,"enable"===r.kind):await e.reload(r.mode);if(!C.current)return;I.current+=1,t(n),"reload"===r.kind?s():await z()}catch(e){M(a,e instanceof Error?e.message:n("actionFailed",{action:n(tD(r))}))}finally{S(a,!1)}}},$=(e,t)=>{let s={kind:"add",input:e,package:t};t?.official===!0?A(s):m(s)},R=async s=>{let r=s?.[0]?tT(s[0]):"apply";if(!c.current.has(r)){S(r,!0),M(r,null);try{let n=await e.apply(s);C.current&&(I.current+=1,t(n),await z())}catch(e){M(r,e instanceof Error?e.message:n("actionFailed",{action:n("reloadOne")}))}finally{S(r,!1)}}},P=async(e,t)=>{if(!c.current.has(e)){S(e,!0),M(e,null);try{await t()}catch(t){M(e,t instanceof Error?t.message:n("retryFailed"))}finally{S(e,!1)}}},T=async t=>{let s=++N.current;y(!0),j(null);try{let n=await e.get(t);C.current&&s===N.current&&v(n)}catch(e){C.current&&s===N.current&&j(e instanceof Error?e.message:n("detailFailed"))}finally{C.current&&s===N.current&&y(!1)}};return{loading:i,requests:o,confirmation:u,setConfirmation:m,errors:p,detailSource:g,detail:b,detailLoading:w,detailError:k,pluginHost:a,refresh:E,execute:A,requestInstall:$,applyChanges:R,loadDetail:T,openDetail:e=>{x(e),v(null),T(e)},closeDetail:()=>{N.current+=1,x(null),v(null),j(null),y(!1)},handleControlAction:(e,t)=>{switch(t){case"reload":R([e.source]);break;case"update":A({kind:"update",source:e.source});break;case"remove":m({kind:"del",source:e.source});break;case"enable":case"disable":A({kind:t,source:e.source});break;case"retry-browser":e.pluginName&&P(`entry:${e.pluginName}`,()=>a.retryEntry(e.pluginName));break;case"retry":{let t=e.operation?.action;"apply"===t?R([e.source]):"add"===t?$({source:e.source}):t&&A({kind:t,source:e.source})}}},refreshEntries:()=>P("entries",()=>a.refreshEntries())}}({biz:s,onSnapshot:a,onRestartScheduled:i}),h=function(e,t){let{t:s}=(0,f.Bd)("pluginManagement"),[n,a]=(0,r.useState)(""),[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)("all"),[c,u]=(0,r.useState)("public"),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)([]),[x,b]=(0,r.useState)(!1),[v,w]=(0,r.useState)(1),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(null),[I,C]=(0,r.useState)(!1),[S,M]=(0,r.useState)(null),[z,E]=(0,r.useState)(null),[A,$]=(0,r.useState)(!1),[R,P]=(0,r.useState)(null),[T,D]=(0,r.useState)(()=>new Set),[L,O]=(0,r.useState)({}),F=(0,r.useRef)(0),B=(0,r.useRef)(0),_=(0,r.useRef)(new Set),q=(0,r.useRef)(null),[W,U]=(0,r.useState)(!1),[Y,V]=(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),b(s.hasMore),C(!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(()=>U(!0))},[t]),(0,r.useEffect)(()=>{if(!W||i)return;let e=++F.current;q.current=null,queueMicrotask(()=>{G.current&&e===F.current&&(k(!0),N(null),b(!1))});let t=setTimeout(()=>{let t="custom"===c?tL.safeParse(m):null;if(t&&!t.success){q.current=null,g([]),b(!1),C(!1),N(s("invalidRegistry")),k(!1);return}let r={query:n.trim(),kind:o,page:1,...t?.success?{registry:t.data}:{}};q.current=r,g([]),b(!1),C(!1),J(r,e)},300);return()=>clearTimeout(t)},[n,o,c,m,i,J,W,s]);let X=async(t,n=t.version)=>{let r=++B.current;$(!0),P(null),E(null),O(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&&E(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:a,composing:i,beginComposition:()=>{F.current+=1,q.current=null,k(!1),l(!0)},endComposition:()=>l(!1),kind:o,setKind:d,searchSource:c,setSearchSource:u,registry:m,setRegistry:p,items:h,loading:y,error:j,searched:I,hasMore:x,loadMore:()=>{q.current&&!y&&x&&J({...q.current,page:v+1},F.current)},retry:()=>{if(i||y)return;let e="custom"===c?tL.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}:{}};q.current=t,g([]),J(t,++F.current)},selection:S,detail:z,detailLoading:A,detailError:R,openDetail:e=>{M(e),X(e)},closeDetail:()=>{B.current+=1,M(null),E(null),$(!1),P(null)},loadDetail:X,prepareInstall:async(t,n)=>{if(!_.current.has(t.name)){_.current.add(t.name),D(new Set(_.current)),O(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 O(e=>({...e,[t.name]:s("installIncompatible")}));n(r)}catch(e){G.current&&O(n=>({...n,[t.name]:e instanceof Error?e.message:s("detailFailed")}))}finally{_.current.delete(t.name),G.current&&D(new Set(_.current))}}},preparing:T,installErrors:L,downloadMode:Y,setDownloadMode:V,downloadRegistry:K,setDownloadRegistry:H,installDetail:e=>{if(!z||A)return;if(!1===z.compatible)return void O(e=>({...e,[z.name]:s("installIncompatible")}));let t="default"===Y?null:tO.safeParse("custom"===Y?{mode:Y,registry:K}:{mode:Y});t&&!t.success?O(e=>({...e,[z.name]:s("invalidRegistry")})):(O(e=>{let t={...e};return delete t[z.name],t}),e({source:`npm:${z.name}@${z.version}`,registry:z.registry,...t?.success?{downloadSource:t.data}:{}},z))}}}(s,"search"===d),g=function(e){let{t}=(0,f.Bd)("pluginManagement"),[s,n]=(0,r.useState)(null),[a,i]=(0,r.useState)("auto"),[l,o]=(0,r.useState)(""),[d,c]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(null),g=(0,r.useRef)(!0),x=(0,r.useRef)(!1),b=(0,r.useRef)(0),v=(0,r.useRef)("load"),w=async()=>{let s=b.current;c(!0),h(null);try{let t=await e.getCatalogSettings();if(!g.current)return;s===b.current?(n(t),i(t.downloadSource.mode),"custom"===t.downloadSource.mode&&o(t.downloadSource.registry)):n(e=>e??t)}catch(e){v.current="load",g.current&&h(e instanceof Error?e.message:t("settingsFailed"))}finally{g.current&&c(!1)}};(0,r.useEffect)(()=>{g.current=!0;let e=!0;return queueMicrotask(()=>{e&&w()}),()=>{e=!1,g.current=!1}},[e]);let y=async(s=a)=>{if(x.current)return;let r=tO.safeParse("custom"===s?{mode:s,registry:l}:{mode:s});if(!r.success){v.current="save",h(t("invalidRegistry"));return}x.current=!0,m(!0),h(null);try{let t=await e.saveCatalogSettings(r.data);g.current&&(n(t),i(t.downloadSource.mode))}catch(e){v.current="save",g.current&&h(e instanceof Error?e.message:t("settingsFailed"))}finally{x.current=!1,g.current&&m(!1)}};return{settings:s,mode:a,registry:l,setRegistry:e=>{b.current+=1,o(e)},loading:d,saving:u,error:p,load:w,save:y,changeMode:e=>{b.current+=1,i(e),"custom"!==e&&y(e)},retry:()=>"save"===v.current?y():w()}}(s),x=function(e){let{t}=(0,f.Bd)("pluginManagement"),[s,n]=(0,r.useState)(!1),[a,i]=(0,r.useState)(""),[l,o]=(0,r.useState)(null),[d,c]=(0,r.useState)(!1),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)("default"),[g,x]=(0,r.useState)(""),b=(0,r.useRef)(0),v=(0,r.useRef)(!0),w=tR(a.trim());(0,r.useEffect)(()=>(v.current=!0,()=>{v.current=!1,b.current+=1}),[]);let y=()=>{b.current+=1,o(null),c(!1),m(null)},k=async s=>{let n;if(!w)return null;if("custom"===p){let e=tL.safeParse(g);if(!e.success)return m(t("invalidRegistry")),null;n=e.data}else"official"===p?n="https://registry.npmjs.org":"domestic"===p&&(n="https://registry.npmmirror.com");let r=++b.current;c(!0),o(null),m(null);try{let t=await e.getCatalog({...w,...s?{version:s}:{},...n?{registry:n}:{}});if(!v.current||r!==b.current)return null;return o(t),t}catch(e){return v.current&&r===b.current&&m(e instanceof Error?e.message:t("detailFailed")),null}finally{v.current&&r===b.current&&c(!1)}},j=async e=>{if(!a.trim()||d)return;if(m(null),!w)return void e({source:a.trim()});let s="default"===p?null:tO.safeParse("custom"===p?{mode:p,registry:g}:{mode:p});if(s&&!s.success)return void m(t("invalidRegistry"));let n=l?Promise.resolve(l):k(),r=b.current,i=await n;if(i&&v.current&&r===b.current){if(!1===i.compatible)return void m(t("installIncompatible"));e({source:`npm:${i.name}@${i.version}`,registry:i.registry,...s?.success?{downloadSource:s.data}:{}},i)}};return{open:s,setOpen:n,source:a,changeSource:e=>{y(),i(e)},spec:w,detail:l,loading:d,error:u,override:p,setOverride:e=>{y(),h(e)},registry:g,setRegistry:e=>{y(),x(e)},loadDetail:k,install:j}}(s),b=e||p.requests.has("reload"),v=new Map(p.pluginHost.getFailedEntries().map(e=>[e.pluginName,e.error.message])),w=p.pluginHost.getEntryListError(),y=t?.plugins.find(e=>e.source===p.detailSource),k=h.selection?t?.plugins.find(e=>e.source.startsWith("npm:")&&tR(e.source)?.name===h.selection?.name):void 0,j=h.selection?tT(`npm:${h.selection.name}`):"",I=tT(x.detail?`npm:${x.detail.name}`:x.spec?`npm:${x.spec.name}`:x.source.trim()),C=t?.plugins.find(e=>tT(e.source)===I),S=p.requests.has(j)||!!(k?.operation&&"failed"!==k.operation.phase),M=p.requests.has(I)||!!(C?.operation&&"failed"!==C.operation.phase),z=e=>e?l(`phase_${e}`):null;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)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h2",{className:"text-xl font-semibold",children:l("title")}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)(th.AM,{children:[(0,n.jsxs)(th.Wv,{render:(0,n.jsx)(N.$,{size:"sm",variant:"outline"}),children:[l("downloadSource"),":",g.loading&&!g.settings?l("loading"):l(`download_${g.settings?.downloadSource.mode??g.mode}`),(0,n.jsx)(ti.A,{className:"size-4"})]}),(0,n.jsx)(th.hl,{align:"end",positionerClassName:"z-[150]",children:(0,n.jsx)(tK,{id:"plugin-default-download",mode:g.mode,registry:g.registry,savedRegistry:g.settings?.downloadSource.mode==="custom"?g.settings.downloadSource.registry:void 0,recommendedRegistry:g.settings?.recommendedRegistry,loading:g.loading,saving:g.saving,error:g.error,onMode:e=>{"default"!==e&&g.changeMode(e)},onRegistry:g.setRegistry,onSave:()=>void g.save(),onRetry:()=>void g.retry()})})]}),e||t?.restartRequired?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:p.requests.has("reload"),onClick:()=>p.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||w?(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,tm.fD)(t.loadError,o)}):null,w?(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:w}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:p.requests.has("entries"),onClick:()=>void p.refreshEntries(),children:l("retry")})]}):null]}):null,p.errors.reload||p.errors.entries?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:p.errors.reload??p.errors.entries}):null]}),(0,n.jsx)("div",{role:"tablist","aria-label":l("title"),className:"flex shrink-0 gap-1 border-b px-4 pt-2 sm:px-6",children:["installed","search"].map(e=>(0,n.jsx)("button",{id:`plugin-tab-${e}`,type:"button",role:"tab","aria-selected":d===e,"aria-controls":`plugin-panel-${e}`,tabIndex:d===e?0:-1,className:`min-h-9 border-b-2 px-3 text-sm font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring ${d===e?"border-primary text-foreground":"border-transparent text-muted-foreground hover:bg-accent"}`,onClick:()=>c(e),onKeyDown:e=>{if(["ArrowLeft","ArrowRight","Home","End"].includes(e.key)){e.preventDefault();let t="Home"===e.key?"installed":"End"===e.key||"installed"===d?"search":"installed";c(t),document.getElementById(`plugin-tab-${t}`)?.focus()}},children:l("installed"===e?"installedTab":"searchPlugins")},e))}),(0,n.jsx)("div",{id:"plugin-panel-installed",role:"tabpanel","aria-labelledby":"plugin-tab-installed",tabIndex:0,hidden:"installed"!==d,className:`pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring sm:p-6 ${"installed"!==d?"hidden":""}`,children:(0,n.jsxs)("div",{className:"space-y-4",children:[x.open?(0,n.jsx)(sr,{source:x.source,isNpm:!!x.spec,detail:x.detail,loading:x.loading,pending:M,disabled:b,error:x.error??p.errors[I]??(C?.operation?.phase==="failed"?C.operation.message:null),operationMessage:M?z(C?.operation?.phase)??l("submitting"):null,override:x.override,registry:x.registry,onSource:x.changeSource,onMode:x.setOverride,onRegistry:x.setRegistry,onRead:()=>void x.loadDetail(),onVersion:e=>void x.loadDetail(e),onInstall:()=>void x.install(p.requestInstall),onClose:()=>x.setOpen(!1)}):null,(0,n.jsx)(tG,{snapshot:t,loading:p.loading,filter:u,disabled:b,requests:p.requests,errors:p.errors,browserErrors:v,onFilter:m,onDetail:e=>{h.closeDetail(),p.openDetail(e)},onAction:p.handleControlAction,onDirectInstall:()=>x.setOpen(!0),onRefresh:()=>void p.refresh()})]})}),(0,n.jsx)("div",{id:"plugin-panel-search",role:"tabpanel","aria-labelledby":"plugin-tab-search",tabIndex:0,hidden:"search"!==d,className:`pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring sm:p-6 ${"search"!==d?"hidden":""}`,children:(0,n.jsx)(tJ,{query:h.query,kind:h.kind,searchSource:h.searchSource,registry:h.registry,items:h.items,loading:h.loading,error:h.error,searched:h.searched,hasMore:h.hasMore,disabled:b,snapshot:t,requests:p.requests,preparing:h.preparing,errors:p.errors,installErrors:h.installErrors,onQuery:h.setQuery,onCompositionStart:h.beginComposition,onCompositionEnd:h.endComposition,onKind:h.setKind,onSearchSource:h.setSearchSource,onRegistry:h.setRegistry,onDetail:e=>{p.closeDetail(),h.openDetail(e)},onInstall:e=>{h.prepareInstall(e,e=>p.requestInstall({source:`npm:${e.name}@${e.version}`,registry:e.registry},e))},onUpdate:e=>void p.execute({kind:"update",source:e}),onMore:h.loadMore,onRetry:h.retry})}),(0,n.jsx)(sa,{open:!!(p.confirmation||p.detailSource||h.selection),title:y?tP(y):h.selection?.name??l("details"),confirmation:p.confirmation,onClose:()=>{p.confirmation?p.setConfirmation(null):(p.closeDetail(),h.closeDetail())},onConfirm:e=>void p.execute(e),children:y?(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[p.detail?.readme?(0,n.jsx)(st,{readme:p.detail.readme},y.source):null,(0,n.jsx)(t$,{plugin:y,detail:p.detail,detailLoading:p.detailLoading,detailError:p.detailError,browserContributions:y.pluginName?p.pluginHost.getRegisteredBrowserDescriptors().find(e=>e.pluginName===y.pluginName)?.contributions??[]:[],onRetry:()=>void p.loadDetail(y.source)})]}):h.selection?h.detailLoading?(0,n.jsx)("p",{role:"status",className:"py-4 text-sm text-muted-foreground",children:l("loadingPackage")}):h.detailError?(0,n.jsxs)("div",{role:"alert",className:"space-y-2 text-sm",children:[(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:h.detailError}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",onClick:()=>void h.loadDetail(h.selection),children:l("retry")})]}):h.detail?(0,n.jsx)(sn,{detail:h.detail,disabled:b,pending:S,installed:!!(k&&(k.operation?.action!=="add"||"failed"!==k.operation.phase)),installedVersion:k?.version??null,updateAvailable:!!k?.updateAvailable,error:h.installErrors[h.detail.name]??p.errors[j]??(k?.operation?.phase==="failed"?k.operation.message:null),operationMessage:z(k?.operation?.phase),downloadMode:h.downloadMode,downloadRegistry:h.downloadRegistry,onDownloadMode:h.setDownloadMode,onDownloadRegistry:h.setDownloadRegistry,onVersion:e=>void h.loadDetail(h.selection,e),onInstall:()=>h.installDetail(p.requestInstall),onUpdate:()=>{k&&p.execute({kind:"update",source:k.source})}}):null:p.detailSource?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:l("pluginRemoved")}):null})]})}var sl=s(77125);let so=a.Yj().trim().min(1).max(2048),sd=a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:tm.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0)}).strict(),sc=a.Yj().trim().min(1).max(4096),su=a.Yj().trim().min(1).max(256),sm=a.Yj().max(32768),sp=a.Ik({name:su,label:sm,state:a.k5(["active","inactive","shadowed"]),description:sm,promptSnippet:sm.nullable(),promptGuidelineCount:a.ai().int().nonnegative(),promptGuidelinePreview:sm.nullable()}).strict(),sh=a.Ik({name:su,label:sm,state:a.k5(["active","inactive","shadowed"]),description:sm,parameters:sl.Dz,promptSnippet:sm.nullable(),promptGuidelines:a.YO(sm)}).strict(),sg=a.Ik({path:sc,events:a.YO(a.Ik({name:su,count:a.ai().int().positive()}).strict()),commands:a.YO(a.Ik({name:su,description:sm.nullable()}).strict()),shortcuts:a.YO(a.Ik({shortcut:su,description:sm.nullable()}).strict()),flags:a.YO(a.Ik({name:su,type:a.k5(["boolean","string"]),description:sm.nullable(),default:a.KC([a.zM(),a.Yj(),a.ch()])}).strict()),messageRenderers:a.YO(su),entryRenderers:a.YO(su)}).strict(),sx=a.Ik({name:su,description:sm,path:sc}).strict(),sf=sx.extend({modelVisible:a.zM()}).strict(),sb=sx.extend({content:a.Yj().max(65536),truncated:a.zM()}).strict(),sv=sb.extend({modelVisible:a.zM()}).strict(),sw=a.Ik({name:su,path:sc}).strict(),sy=a.Ik({name:su,kind:a.k5(["config","native"])}).strict(),sk=a.Ik({methods:a.YO(a.Ik({pluginName:su,method:su}).strict()),browserEntries:a.YO(a.Ik({pluginName:su}).strict()),messageDeclarations:a.YO(a.Ik({pluginName:su,declarationName:su,priority:a.ai().int().safe()}).strict())}).strict(),sj=a.Ik({error:tm.qf.refine(e=>"string"==typeof e?e.length<=32768:[e.default,...Object.values(e.translations)].every(e=>e.length<=32768)).nullable(),extensions:a.YO(sg),tools:a.YO(sp),skills:a.YO(sf),prompts:a.YO(sx),themes:a.YO(sw),providers:a.YO(sy),piDesk:sk}).strict(),sN=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(),sI=(0,i._G)({path:"plugins/management-update",bodySchema:a.Ik({}).strict()}),sC=a.Ik({source:so,kind:a.k5(["package","extension"]).default("package"),operation:sN.nullable().default(null),pluginName:a.Yj().trim().min(1).nullable(),description:tm.qf.nullable().default(null),version:a.Yj().trim().min(1).nullable(),updateAvailable:a.zM().nullable(),status:a.k5(["ready","available","disabled","failed"]),error:sd.nullable(),capabilities:sj}).strict(),sS=a.Ik({source:so,readme:tm.qf.nullable().default(null),tools:a.YO(sh),skills:a.YO(sv),prompts:a.YO(sb)}).strict(),sM=a.Ik({plugins:a.YO(sC),restartRequired:a.zM(),loadError:tm.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0).nullable()}).strict(),sz=a.Ik({sources:a.YO(so).min(1).max(32).optional()}).strict(),sE=a.Ik({}).strict().extend({mode:a.k5(["normal","basic"]).optional()}).strict(),sA=a.Ik({checkUpdates:a.zM().optional()}).strict(),s$=a.Ik({source:so}).strict(),sR=s$.extend({downloadSource:tO.optional(),registry:tL.optional()}).strict(),sP=s$.extend({enabled:a.zM()}).strict();async function sT(e,t,s,n){return eF(e,t,s,n,{fallbackMessage:"插件管理请求失败"})}function sD({pluginName:e,descriptor:t,source:s,cwd:r,onPreviewFile:a,onRevealFile:i}){let l=`${s.workId}\u0000${s.sessionId}\u0000${s.branchId}\u0000${r}`;return(0,n.jsx)(td,{pluginName:e,kind:"session-sidebar-tab",contributionName:t.contributionName,target:{kind:"session-sidebar-tab",source:s,cwd:r,files:{preview:a,reveal:i}},targetKey:l,layout:"fill"})}function sL({pluginName:e,descriptor:t,onClose:s,onBeforeLeaveChange:a}){let i=(0,eI.t4)();(0,eI.So)();let l=i.getEntryState(e),o="ready"===l.status?l.runtime:l.status;(0,r.useEffect)(()=>()=>{a(null)},[o,a]);let d=(0,r.useMemo)(()=>({kind:"settings-page",close:()=>{i.getEntryState(e)===l&&s()},setBeforeLeave:t=>{i.getEntryState(e)===l&&a(t)}}),[l,a,s,e,i]);return(0,n.jsx)(td,{pluginName:e,kind:"settings-page",contributionName:t.contributionName,target:d,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})}var sO=s(84157),sF=s(56101),sB=s(49265),s_=s(37525),sq=s(77910);let sW="1.0.1-dev.9003".trim()||"未知",sU="2026-10-09T13:10:48+08:00".trim()||null;var sY=s(71052),sV=s(6747);let sK="pi-desk:power-saving",sH="pi-desk:power-saving-change",sG=null;function sJ(){if(null!==sG)return sG;try{sG="true"===window.localStorage.getItem(sK)}catch{sG=!1}return sG}function sX(e){let t=t=>{(null===t.key||t.key===sK)&&(sG=null,e())};return window.addEventListener(sH,e),window.addEventListener("storage",t),()=>{window.removeEventListener(sH,e),window.removeEventListener("storage",t)}}function sQ(){return(0,r.useSyncExternalStore)(sX,sJ,()=>!1)}function sZ(e,t){let s=(0,sV.I)(),n=sQ(),a=(0,r.useRef)(null);(0,r.useLayoutEffect)(()=>{let r=e.current,i=a.current!==t;if(a.current=t,!r||!t||!i||s||n)return;let l=r.animate([{opacity:0,transform:"translateY(5px)"},{opacity:1,transform:"translateY(0)"}],{duration:200,easing:"cubic-bezier(0.22, 1, 0.36, 1)"});return()=>l.cancel()},[e,t,n,s])}var s0=s(33541),s1=s(13937),s2=s(52632),s5=s(73704),s3=s(78511),s4=s(319);let s6=a.Yj().min(1).max(s4.uV).refine(e=>!e.includes("\0")&&(e.startsWith("/")||e.startsWith("\\\\")||/^[a-zA-Z]:[\\/]/.test(e)),"必须是绝对路径"),s8=a.Ik({cwd:s3.m4.nullable()}).strict(),s7=a.Ik({skillPath:s6,name:a.Yj().min(1),description:a.Yj(),packageSource:a.Yj().nullable()}).strict(),s9=a.Ik({skills:a.YO(s7),diagnostics:a.YO(a.Ik({path:a.Yj(),message:tm.qf}).strict())}).strict(),ne=s8.extend({skillPath:s6}),nt=ne.extend({path:s4.rh}).strict(),ns=a.Ik({entries:a.YO(a.Ik({name:a.Yj().min(1),type:a.k5(["directory","file"])}).strict()).max(s4.xm),truncated:a.zM()}).strict(),nn=ne.extend({path:s4._g}).strict(),nr=a.gM("kind",[a.Ik({kind:a.eu("text"),content:a.Yj(),size:a.ai().int().nonnegative().max(s4.NL),readOnlyReason:tm.qf.nullable()}).strict(),a.Ik({kind:a.eu("image"),mimeType:s4.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()]),na=nn.extend({content:a.Yj().max(s4.NL)}).strict(),ni=a.Ik({}).strict(),nl={path:"/api/skills/list",request:s8,response:s9},no={path:"/api/skill-files/list",request:nt,response:ns},nd={path:"/api/skill-files/get",request:nn,response:nr},nc={path:"/api/skill-files/replace",request:na,response:ni},nu=a.Ik({code:a.ai(),msg:a.Yj(),data:a.L5(),i18n:s2.N.optional()});async function nm(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}),a=nu.parse(await r.json());if(!r.ok||0!==a.code||null===a.data)throw Error(a.msg?(0,eO.B)(a):"Skills 请求失败");return t.response.parse(a.data)}function np(e){(0,s5.ZQ)({wrapLines:e})}async function nh(e){let t=e.skillPath.replaceAll("\\","/");await navigator.clipboard.writeText(t.slice(0,t.lastIndexOf("/")+1)+e.path)}var ng=s(14312);function nx(e){return(0,eO.B)({msg:ng.P["zh-CN"][e],i18n:{key:`skills:${e}`}})}function nf(e){return JSON.stringify(e)}function nb(e){return JSON.stringify([e.cwd,e.skillPath,e.path])}function nv(e){return e.replace(/\r\n|\r/g,"\n")}function nw(e){return e?.file?.kind==="text"&&e.draft!==nv(e.file.content)}var ny=s(38948),nk=s(52979),nj=s(90578),nN=s(32168);function nI(e){let{t}=(0,f.Bd)("common"),{wrapLines:s}=(0,s5.TX)(),a=e.path,i=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useRef)(null),d=(0,r.useRef)(null),c=(0,r.useRef)(null),u=(0,r.useRef)(0),m=(0,r.useRef)(e),[p,h]=(0,r.useState)(!1),[g,x]=(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,nN.cu)().then(r=>{if(e||!i.current)return;let a=m.current,o=r.editor.create(i.current,{model:null,theme:(0,nN.dC)(),automaticLayout:!0,readOnly:a.readOnly,domReadOnly:a.readOnly,wordWrap:(0,s5.E6)().wrapLines?"on":"off",wrappingIndent:"same",minimap:{enabled:!1},stickyScroll:{enabled:!1},scrollBeyondLastLine:!1,...(0,nN.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,nN.Tr)(e=>r.editor.setTheme(e)),n=(0,nN.BK)(e=>o.updateOptions(e)),x(!0)}).catch(()=>{e||h(!0)}),()=>{e=!0,s(),n(),d.current?.dispose(),d.current=null,o.current?.dispose(),o.current=null,c.current=null,l.current?.dispose(),l.current=null}},[t]),(0,r.useEffect)(()=>{let e=!1,t=u.current+1;return u.current=t,(0,nN.cu)().then(s=>{if(e||t!==u.current||!l.current)return;let n=m.current,r=s.editor.createModel(n.content,(0,nN.ix)(n.path,n.size),(0,nN.B3)(s,n.path,"edit")),i=o.current;d.current?.dispose(),d.current=r.onDidChangeContent(()=>{m.current.onChange(r.getValue(s.editor.EndOfLinePreference.LF))}),o.current=r,c.current=a,l.current.setModel(r),i?.dispose()}),()=>{e=!0}},[a]),(0,r.useEffect)(()=>{let t=o.current;t&&c.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:i,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 nC=s(55734);function nS({file:e,path:t}){let{t:s}=(0,f.Bd)("skills"),a=(0,r.useMemo)(()=>[{src:`data:${e.mimeType};base64,${e.data}`,alt:t}],[e,t]);return(0,n.jsx)(nC.k,{mode:"inline",slides:a,className:"h-full w-full",ariaLabel:s("imagePreview")})}function nM(e){let{document:t,skill:s,dirty:r,loading:a,saving:i,opening:l}=e,{t:o}=(0,f.Bd)("skills"),{locale:d}=(0,tp.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)(ny.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 c=t.file,u=c?.kind==="text"?c.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})]}),c?.kind==="text"&&(0,n.jsxs)("span",{role:"status","aria-label":o(i?"saving":l?"switchingFile":r?"unsavedChanges":u?"readOnlyFile":"fileSaved"),className:"hidden shrink-0 items-center gap-1 text-xs text-muted-foreground sm:flex",children:[i||l?(0,n.jsx)(b.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)(nk.A,{className:"size-3.5"}):(0,n.jsx)(ed.A,{className:"size-3.5"}),o(i?"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)(N.$,{variant:"ghost",size:"icon","aria-label":o("copySkillPath"),title:o("copyPath"),onClick:e.onCopy,children:(0,n.jsx)(eM.A,{className:"size-4"})}),(0,n.jsxs)(N.$,{"aria-label":o("saveSkill"),disabled:!r||!!u||a||i,onClick:e.onSave,children:[i?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(eS.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)(nk.A,{className:"mt-0.5 size-3.5 shrink-0"}),(0,n.jsx)("p",{children:(0,tm.fD)(u,d)})]}),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,!c&&(0,n.jsx)(N.$,{variant:"ghost",size:"sm",onClick:e.onReload,children:o("reload")})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:a&&!c?(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)(b.A,{className:"size-4 animate-spin"}),o("loadingFile")]}):c?.kind==="text"?(0,n.jsx)(nI,{path:t.target.skillPath.slice(0,t.target.skillPath.lastIndexOf("/")+1)+t.target.path,content:t.draft,size:c.size,readOnly:!!u||i||l,onChange:e.onChange,onSave:e.onSave}):c?.kind==="image"?(0,n.jsx)(nS,{file:c,path:t.target.path}):c?.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)(ny.A,{className:"mb-2 size-8"}),(0,n.jsx)("p",{children:c.reason}),(0,n.jsx)("p",{children:o("fileSize",{size:c.size.toLocaleString("en"===d?"en-US":"zh-CN")})})]}):null}),c?.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)(N.$,{variant:"ghost",size:"sm","aria-label":o("wrapLines"),"aria-pressed":e.wrapLines,onClick:e.onWrapLines,children:[(0,n.jsx)(nj.A,{className:"size-3.5"}),o("wrapLines")]})]})]})}function nz({open:e,saving:t,path:s,error:r,onDecide:a}){let{t:i}=(0,f.Bd)("skills");return(0,n.jsx)(eX.YV,{open:e,onOpenChange:e=>{e||t||a("cancel")},children:(0,n.jsxs)(eX.hA,{className:"z-[150]",showCloseButton:!t,children:[(0,n.jsxs)(eX.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eX.YM,{children:i("saveChangesTitle")}),(0,n.jsx)(eX.uX,{children:i("saveChangesDescription",{path:s??""})})]}),r&&(0,n.jsx)("p",{role:"alert",className:"px-4 pb-4 text-sm text-destructive",children:r}),(0,n.jsxs)(eX.vu,{children:[(0,n.jsx)(N.$,{variant:"outline",disabled:t,onClick:()=>void a("cancel"),children:i("cancel")}),(0,n.jsx)(N.$,{variant:"ghost",disabled:t,onClick:()=>void a("discard"),children:i("discard")}),(0,n.jsx)(N.$,{disabled:t,onClick:()=>void a("save"),children:i(t?"savingChanges":"saveContinue")})]})]})})}var nE=s(30406),nA=s(42904),n$=s(87001);function nR(e,t){return!!(e&&e.cwd===t.cwd&&e.skillPath===t.skillPath&&e.path===t.path)}function nP({target:e,props:t,depth:s=0,skillName:a}){let{t:i}=(0,f.Bd)("skills"),l=t.directories[nb(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)(N.$,{variant:"ghost",size:"sm",onClick:()=>void t.onLoadDirectory(e),children:i("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)(nT,{target:o,props:t,depth:s,name:r.name,skillName:a},l);let d=nR(t.selected,o),c=nR(t.pending,o);return(0,n.jsxs)(N.$,{variant:"ghost","aria-label":i("skillFile",{path:`${a}/${l}`}),"aria-pressed":d,title:l,className:(0,C.cn)("min-h-9 w-full justify-start text-left font-normal text-muted-foreground",d&&"font-medium",c&&"bg-muted text-foreground"),onClick:()=>void t.onOpenFile(o),children:["SKILL.md"===r.name?(0,n.jsx)(nE.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(ny.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r.name}),c&&(0,n.jsx)(b.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:i("emptyFolder")}),l.data.truncated&&(0,n.jsx)("p",{className:"px-3 py-2 text-sm text-status-warning",children:i("folderTruncated")})]}):(0,n.jsx)("p",{role:"status",className:"px-4 py-2 text-xs text-muted-foreground",children:i("loadingFolder")})}function nT({target:e,props:t,depth:s,name:a,skillName:i}){let{t:l}=(0,f.Bd)("skills"),[o,d]=(0,r.useState)(!1);return(0,n.jsxs)("div",{children:[(0,n.jsxs)(N.$,{variant:"ghost","aria-expanded":o,"aria-label":l("skillFolder",{path:`${i}/${e.path}`}),className:(0,C.cn)("min-h-9 w-full justify-start font-normal text-muted-foreground",o&&"bg-muted text-foreground"),onClick:()=>d(!o),children:[o?(0,n.jsx)(ti.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(eo.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)(e8.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:a})]}),o&&(0,n.jsx)("div",{className:s>3?"-ml-3":void 0,children:(0,n.jsx)(nP,{target:e,props:t,depth:s+1,skillName:i})})]})}function nD({cwd:e,skill:t,props:s}){let{t:a}=(0,f.Bd)("skills"),i=s.selected?.cwd===e&&s.selected.skillPath===t.skillPath,l=s.pending?.cwd===e&&s.pending.skillPath===t.skillPath,[o,d]=(0,r.useState)(null),c=o??i,u=async()=>{if(c)return void d(!1);let n=t.skillPath.replaceAll("\\","/").split("/").at(-1);await s.onOpenFile({cwd:e,skillPath:t.skillPath,path:n})&&d(!0)};return(0,n.jsxs)("div",{className:"py-0.5",children:[(0,n.jsxs)(N.$,{variant:"ghost","aria-label":a("skillName",{name:t.name}),"aria-expanded":c,title:`${t.description}
155
155
  ${t.skillPath}`,className:(0,C.cn)("min-h-14 w-full justify-start whitespace-normal text-left",c&&"bg-accent hover:bg-accent",i&&"text-foreground"),onClick:()=>void u(),children:[c?(0,n.jsx)(ti.A,{className:"size-3.5 shrink-0 text-muted-foreground"}):(0,n.jsx)(eo.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)(b.A,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground"}):t.packageSource?(0,n.jsx)(nA.A,{"aria-label":a("packageSkill"),className:"size-3.5 shrink-0 text-muted-foreground"}):null]}),c&&(0,n.jsx)(nP,{target:{cwd:e,skillPath:t.skillPath,path:""},props:s,skillName:t.name})]})}function nL({cwd:e,name:t,props:s}){let{t:a}=(0,f.Bd)("skills"),{locale:i}=(0,tp.i)(),l=s.selected?.cwd===e||s.pending?.cwd===e,[o,d]=(0,r.useState)(null),{onLoadScope:c}=s,u=s.scopes[nf(e)],m=s.query.trim().toLowerCase(),p=o??(null===e||s.focusedCwd===e||l),h=p||!!m;(0,r.useEffect)(()=>{h&&!u&&c(e)},[e,h,u,c]);let g=`${t} ${e??""}`.toLowerCase().includes(m),x=u?.data?.skills.filter(e=>!m||g||`${e.name} ${e.description}`.toLowerCase().includes(m))??[];if(m&&u?.data&&!x.length&&!g&&!u.error)return null;let v=null===e;return(0,n.jsxs)("section",{className:"mx-2 mt-2 min-w-0 border-b pb-2","aria-label":v?a("globalSkills"):a("projectSkills",{name:t}),children:[(0,n.jsxs)(N.$,{variant:"ghost",className:"min-h-14 w-full justify-start text-left","aria-label":a("skillsGroup",{name:v?a("global"):t}),"aria-expanded":h,onClick:()=>d(!p),children:[h?(0,n.jsx)(ti.A,{className:"size-4 shrink-0"}):(0,n.jsx)(eo.A,{className:"size-4 shrink-0"}),v?(0,n.jsx)(tt.A,{className:"size-4 shrink-0 text-primary"}):(0,n.jsx)(e8.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:v?a("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)(b.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?x.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)(N.$,{variant:"ghost",size:"sm",onClick:()=>void s.onLoadScope(e),children:a("retryGroup")})]}),x.map(t=>(0,n.jsx)(nD,{cwd:e,skill:t,props:s},t.skillPath)),u?.data&&0===x.length&&!u.error&&(0,n.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground",children:a(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:a("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,tm.fD)(e.message,i)}),(0,n.jsx)("p",{className:"mt-1 break-all text-xs",children:e.path})]},`${e.path}:${t}`))})]})]})]})}function nO(e){let{t}=(0,f.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)(n$.MG,{children:[(0,n.jsx)(n$.Sq,{children:(0,n.jsx)(e_.A,{className:"size-4"})}),(0,n.jsx)(n$.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)(nL,{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)(nL,{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 nF({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{t:a}=(0,f.Bd)("skills"),{clientId:i}=(0,eR.gM)(),l=(0,eC.G)(),o=(0,r.useMemo)(()=>({list:(e,t)=>nm(i,nl,e,t),listFiles:(e,t)=>nm(i,no,e,t),getFile:(e,t)=>nm(i,nd,e,t),async replaceFile(e){await nm(i,nc,e)}}),[i]),d=function(e,t){let[s,n]=(0,r.useState)({}),[a,i]=(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 d=(0,r.useCallback)(async t=>{let s=nf(t),r=`scope:${s}`;l.current.get(r)?.abort();let a=new AbortController;l.current.set(r,a),n(e=>({...e,[s]:{data:e[s]?.data??null,loading:!0,error:null}}));try{let r=await e.list({cwd:t},a.signal);!a.signal.aborted&&o.current&&n(e=>({...e,[s]:{data:r,loading:!1,error:null}}))}catch(e){!a.signal.aborted&&o.current&&n(t=>({...t,[s]:{data:t[s]?.data??null,loading:!1,error:e instanceof Error?e.message:nx("skillsReadFailed")}}))}finally{l.current.get(r)===a&&l.current.delete(r)}},[e]),c=(0,r.useCallback)(async t=>{let s=nb(t),n=`directory:${s}`;l.current.get(n)?.abort();let r=new AbortController;l.current.set(n,r),i(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&&i(e=>({...e,[s]:{data:n,loading:!1,error:null}}))}catch(e){!r.signal.aborted&&o.current&&i(t=>({...t,[s]:{data:null,loading:!1,error:e instanceof Error?e.message:nx("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([nf(null),...JSON.parse(u).map(nf)]);for(let[t,s]of(n(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),i(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(nf(JSON.parse(t)[0]))))),l.current)){let n=t.startsWith("scope:")?t.slice(6):nf(JSON.parse(t.slice(10))[0]);e.has(n)||(s.abort(),l.current.delete(t))}},[u]),{scopes:s,directories:a,loadScope:d,loadDirectory:c}}(o,e),{loadScope:c}=d,u=function(e,t){let{wrapLines:s}=(0,s5.TX)(),[n,a]=(0,r.useState)(null),i=(0,r.useRef)(null),l=(0,r.useRef)(!0),[o,d]=(0,r.useState)(!1),[c,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(!1),h=(0,r.useRef)(null),g=(0,r.useRef)(!1),x=(0,r.useRef)(null),[f,b]=(0,r.useState)(!1),v=(0,r.useRef)(null),w=(0,r.useCallback)(e=>{l.current&&(i.current=e,a(e))},[]);(0,r.useEffect)(()=>(l.current=!0,()=>{l.current=!1,x.current?.abort(),v.current?.resolve(!1),v.current=null}),[]);let y=(0,r.useCallback)(()=>{if(h.current)return h.current;let s=i.current;if(!s||s.file?.kind!=="text"||s.file.readOnlyReason)return Promise.resolve(!1);if(!nw(s))return Promise.resolve(!0);p(!0);let n=(async()=>{try{await e.replaceFile({...s.target,content:s.draft});let n=i.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=i.current;return e?.target===s.target&&w({...e,error:t instanceof Error?t.message:nx("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(!nw(i.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()||nw(i.current)))return;if("discard"===e){let e=i.current;e?.file?.kind==="text"&&w({...e,draft:nv(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;x.current?.abort();let s=new AbortController;x.current=s,u(t),d(!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?nv(n.content):"",error:null}),!0}catch(e){if(!s.signal.aborted){let s=i.current,n=e instanceof Error?e.message:nx("fileReadFailed");w(s?{...s,error:n}:{target:t,file:null,draft:"",error:n})}return!1}finally{l.current&&(u(null),d(!1))}}finally{g.current=!1}},[w,k,e]),I=(0,r.useCallback)(e=>{let t=i.current;t?.file?.kind!=="text"||t.file.readOnlyReason||t.draft===e||w({...t,draft:e})},[w]),C=nw(n);return(0,r.useEffect)(()=>{if(!C)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[C]),{document:n,dirty:C,loading:o,openingTarget:c,saving:m,confirmOpen:f,wrapLines:s,setWrapLines:np,change:I,open:N,save:y,beforeLeave:k,decide:j}}(o,(0,r.useCallback)(e=>{c(e)},[c])),{document:m,open:p}=u,[h,g]=(0,r.useState)(""),[x,v]=(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=d.scopes[nf(j.current)];if(!e||e.loading)return;let t=d.scopes[nf(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)})},[d.scopes,m,p]);let I=(0,r.useCallback)(async e=>{let t=await p(e);return t&&v(!1),t},[p]),S=async()=>{if(u.document)try{await nh(u.document.target),l.success(a("pathCopied"))}catch{l.error(a("copyFailed"))}},M=u.document?.target??null,z=M?d.scopes[nf(M.cwd)]?.data?.skills.find(e=>e.skillPath===M.skillPath)??null:null,E=Object.values(d.scopes).some(e=>e.loading)||Object.values(d.directories).some(e=>e.loading),A={projects:e,focusedCwd:t,query:h,onQuery:g,scopes:d.scopes,directories:d.directories,selected:M,pending:u.openingTarget,onLoadScope:d.loadScope,onLoadDirectory:d.loadDirectory,onOpenFile:I};return(0,n.jsxs)("section",{"aria-label":a("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)(N.$,{variant:"ghost",size:"icon",className:"lg:hidden","aria-label":a("openSkillsFolder"),onClick:()=>v(!0),children:(0,n.jsx)(s_.A,{className:"size-4"})}),(0,n.jsx)(N.$,{variant:"ghost",size:"icon",className:"hidden lg:inline-flex","aria-label":a(w?"collapseSkillsFolder":"expandSkillsFolder"),onClick:()=>y(!w),children:w?(0,n.jsx)(s0.A,{className:"size-4"}):(0,n.jsx)(s1.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)(N.$,{variant:"ghost",size:"sm",disabled:E,"aria-label":a("refreshSkillsFolder"),onClick:()=>{for(let e of Object.keys(d.scopes))d.loadScope(JSON.parse(e));for(let e of Object.keys(d.directories)){let[t,s,n]=JSON.parse(e);d.loadDirectory({cwd:t,skillPath:s,path:n})}},children:[E?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(eE.A,{className:"size-3.5"}),a("refreshFolder")]})]}),(0,n.jsxs)("div",{className:"flex min-h-0 flex-1",children:[(0,n.jsx)("aside",{"aria-label":a("skillsProjectFolder"),className:(0,C.cn)("hidden w-64 shrink-0 border-r bg-sidebar xl:w-72",w&&"lg:block"),children:(0,n.jsx)(nO,{...A})}),(0,n.jsx)("main",{className:"min-h-0 min-w-0 flex-1",children:(0,n.jsx)(nM,{document:u.document,skill:z,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:()=>{M&&I(M)},onCopy:()=>void S()})})]}),(0,n.jsx)(eX.YV,{open:x,onOpenChange:v,children:(0,n.jsxs)(eX.hA,{className:"left-0 top-0 z-[130] h-dvh max-h-dvh w-[min(360px,calc(100dvw-2rem))] max-w-none translate-x-0 translate-y-0 rounded-l-none",finalFocus:!1,children:[(0,n.jsx)(eX.Hl,{className:"shrink-0 border-b px-4 py-3 pr-12",children:(0,n.jsx)(eX.YM,{children:a("skillsFolderTitle")})}),(0,n.jsx)("div",{className:"min-h-0 flex-1",children:(0,n.jsx)(nO,{...A})})]})}),(0,n.jsx)(nz,{open:u.confirmOpen,saving:u.saving,path:M?.path??null,error:u.document?.error??null,onDecide:u.decide})]})}var nB=s(81725),n_=s(59833),nq=s(37912);function nW(){let{t:e}=(0,f.Bd)("common"),[t,s]=(0,r.useState)(null),a=(0,r.useRef)(null),i=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{a.current?.(!1),a.current=null},[]);let l=e=>{let t=a.current;a.current=null,s(null),t?.(e)};return{confirm:e=>(a.current?.(!1),s(e),new Promise(e=>{a.current=e})),dialog:t?(0,n.jsx)(eX.YV,{open:!0,onOpenChange:e=>{e||l(!1)},children:(0,n.jsxs)(eX.hA,{initialFocus:i,className:"z-[130] max-w-[27.5rem]",children:[(0,n.jsxs)(eX.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eX.YM,{children:t.title}),(0,n.jsx)(eX.uX,{className:"break-words",children:t.description})]}),(0,n.jsxs)(eX.vu,{children:[(0,n.jsx)(N.$,{ref:i,variant:"outline",onClick:()=>l(!1),children:e("cancel")}),(0,n.jsx)(N.$,{variant:"destructive",onClick:()=>l(!0),children:t.confirmLabel??e("delete")})]})]})}):null}}var nU=s(20927);async function nY(e,t,s,n,r){let a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s),signal:r});401===a.status&&window.location.replace("/login");let i=await a.json();if(!a.ok||0!==i.code||null===i.data)throw Error(0===i.code?(0,eO.B)({msg:"登录保护设置处理失败",i18n:{key:"auth:settingsFailed"}}):(0,eO.B)(i));return n.parse(i.data)}async function nV(e){await nY(e,"/api/auth/logout",{},nU.Xm),window.location.replace("/login")}async function nK(e,t){let s=nU.uZ.safeParse(t);if(!s.success)throw Error((0,eO.B)({msg:"请填写至少 8 位密码",i18n:{key:"auth:settingsInvalid"}}));await nY(e,"/api/auth-settings/replace",s.data,nU.Kc),window.location.replace(null===t.password?"/":"/login")}function nH(){let{t:e}=(0,f.Bd)("auth"),t=function(){let{t:e}=(0,f.Bd)("auth"),{clientId:t}=(0,eR.gM)(),{confirm:s,dialog:n}=nW(),[a,i]=(0,r.useState)(null),[l,o]=(0,r.useState)(!0),[d,c]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(null),[g,x]=(0,r.useState)(0),[b,v]=(0,r.useState)(""),w=(0,r.useRef)(!1);(0,r.useEffect)(()=>{var s;let n=new AbortController;return(s=n.signal,nY(t,"/api/auth-settings/get",{},nU.G6,s)).then(e=>{n.signal.aborted||(i(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&&a){w.current=!0,c(!0),h(null);try{await nK(t,{password:b})}catch(t){w.current=!1,c(!1),h(t instanceof Error?t.message:e("settingsFailed"))}}},k=async()=>{if(!w.current&&a){if(w.current=!0,!await s({title:e("disableTitle"),description:e("disableDescription"),confirmLabel:e("disable")})){w.current=!1;return}c(!0),h(null);try{await nK(t,{password:null})}catch(t){w.current=!1,c(!1),h(t instanceof Error?t.message:e("settingsFailed"))}}},j=async()=>{if(!w.current&&a?.enabled){w.current=!0,m(!0),h(null);try{await nV(t)}catch(t){w.current=!1,m(!1),h(t instanceof Error?t.message:e("logoutFailed"))}}};return{settings:a,loading:l,saving:d,signingOut:u,error:p,password:b,setPassword:v,save:y,disable:k,logout:j,dialog:n,retry:()=>{o(!0),h(null),x(e=>e+1)}}}(),s=t.settings?.enabled??!1,a=t.saving||t.signingOut,i=s?eA.A:nB.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)(i,{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)(N.$,{type:"button",variant:"outline",className:"border-destructive/50 text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:a,"aria-busy":t.signingOut,onClick:()=>void t.logout(),children:[t.signingOut?(0,n.jsx)(b.A,{className:"motion-safe:animate-spin","aria-hidden":"true"}):(0,n.jsx)(n_.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":a,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.jsx)("label",{className:"block text-sm font-medium",htmlFor:"auth-password",children:e(s?"newPassword":"password")}),(0,n.jsx)(nq.k,{id:"auth-password",name:"password",className:"[&::-ms-reveal]:hidden",autoComplete:"new-password",minLength:8,maxLength:256,required:!0,disabled:a,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-xs 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)(N.$,{type:"submit",disabled:a,children:[t.saving?(0,n.jsx)(b.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)(eo.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)(N.$,{type:"button",variant:"ghost",className:"text-muted-foreground",disabled:a,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)(N.$,{variant:"outline",onClick:t.retry,children:e("common:retry")})]}),t.dialog]})}var nG=s(91501),nJ=s(79741);let nX=Object.freeze({apply:(0,i.Vc)({path:"app-runtime/apply",inputSchema:nJ.$C,outputSchema:nJ.Pq}),update:(0,i._G)({path:"app-runtime/update",bodySchema:nJ.YT})});var nQ=s(84922);async function nZ(e,t,s,n){let r=(0,nQ.fx)();if(!r)return"cancelled";let a=e!==r.locale;if(a&&!window.confirm(t))return"cancelled";if(a&&n&&!await n())return"blocked";try{await s.request(nX.apply,{key:"settings",update:{region:{locale:e}}})}catch{return"save-failed"}return a&&window.location.reload(),"changed"}async function n0(e,t){try{return await t.request(nX.apply,{key:"settings",update:{region:{timeZone:e}}}),!0}catch{return!1}}function n1({canLeave:e}){let{t}=(0,f.Bd)("settings"),s=(0,tp.i)(),{appSocket:a}=(0,eR.gM)(),[i,l]=(0,r.useState)(null),[o,d]=(0,r.useState)(()=>new Date);(0,r.useEffect)(()=>{let e=window.setInterval(()=>d(new Date),6e4);return()=>window.clearInterval(e)},[]);let c=(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 nZ(s,t("common:reloadConfirm"),a,e);"save-failed"===n&&l(t("common:localeError")),"blocked"===n&&l(t("common:reloadBlocked"))},m=async e=>{l(await n0(e,a)?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)(eP.l6,{value:s.localePreference,onValueChange:e=>{("zh-CN"===e||"en"===e)&&u(e)},children:[(0,n.jsx)(eP.bq,{id:"region-language",className:"w-full",children:(0,n.jsx)(eP.yv,{children:"zh-CN"===s.localePreference?t("common:chinese"):"English"})}),(0,n.jsxs)(eP.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(eP.eb,{value:"zh-CN",children:t("common:chinese")}),(0,n.jsx)(eP.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)(N.$,{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)(nG.b,{value:s.timeZonePreference,options:c,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)})]}),i&&(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:i})]})}var n2=s(47546),n5=s(218),n3=s(83629),n4=s(38832);function n6({label:e,value:t,options:s,onChange:r,layout:a="list",disabled:i=!1}){let l=s.some(e=>e.value===t);return(0,n.jsx)("div",{role:"radiogroup","aria-label":e,onKeyDown:e=>{if(i||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 a=Math.max(0,s.findIndex(e=>e.value===t)),l="Home"===e.key?0:"End"===e.key?s.length-1:(a+n+s.length)%s.length,o=s[l];o&&(r(o.value),e.currentTarget.querySelectorAll('[role="radio"]')[l]?.focus())},className:(0,C.cn)("segmented"===a?"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,d=e.icon;return(0,n.jsxs)("button",{type:"button",role:"radio","aria-checked":o,tabIndex:o||!l&&0===s?0:-1,disabled:i,"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"===a?"min-h-7 rounded-md px-2 py-0.5":"min-h-9 rounded-lg border border-transparent px-3 py-2",o?"segmented"===a?"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:[d?(0,n.jsx)(d,{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"===a?(0,n.jsx)(ed.A,{"aria-hidden":"true",className:(0,C.cn)("size-4 shrink-0",!o&&"invisible")}):null]},e.value)})})}var n8=s(53638),n7=s(45581),n9=s(74962),re=s(79990),rt=s(19128),rs=s.n(rt);let rn={code:{copy:!0,download:!1}};function rr({href:e,children:t,...s}){return delete s.node,(0,n.jsx)("a",{...s,href:e,target:"_blank",rel:"noopener noreferrer",children:t})}function ra({src:e,alt:t,className:s,onError:a,...i}){let{t:l}=(0,f.Bd)("conversation"),[o,d]=(0,r.useState)(!1),[c,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 i.node,0===p.length)return null;if(c)return(0,n.jsx)("span",{className:rs().imageFallback,children:l("imageUnavailable")});let h=p[0].src;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",className:rs().imageTrigger,"aria-label":l("previewImage",{name:m}),onClick:()=>d(!0),children:[(0,n.jsx)("img",{...i,src:h,alt:m,"data-streamdown":"image",className:(0,C.cn)(rs().image,s),onError:e=>{u(!0),a?.(e)}}),(0,n.jsx)("span",{className:rs().imageAction,"aria-hidden":"true",children:(0,n.jsx)(B.A,{className:"size-4"})})]}),o?(0,n.jsx)(nC.k,{mode:"modal",open:!0,slides:p,ariaLabel:l("imagePreview"),onClose:()=>d(!1)}):null]})}function ri({className:e,isAnimating:t,components:s,...r}){let a=(0,eC.G)(),{t:i}=(0,f.Bd)("conversation"),{locale:l}=(0,tp.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,tg.x)(t).then(e=>{e||a.error(i("codeCopyFailed"))}))},children:(0,n.jsx)(t9,{className:(0,C.cn)("space-y-0",rs().markdown,e),controls:rn,isAnimating:t,lineNumbers:!1,components:{...s,a:rr,img:ra},...r,translations:"zh-CN"===l?re.X:void 0})})}let rl=[{value:"system",label:"common:system",icon:n2.A},{value:"light",label:"themeLight",icon:n5.A},{value:"dark",label:"themeDark",icon:n3.A}],ro=[{value:"compact",label:"sizeCompact"},{value:"standard",label:"sizeStandard"},{value:"large",label:"sizeLarge"}];function rd(){let{t:e}=(0,f.Bd)("settings"),t=(0,r.useSyncExternalStore)(n8.Cy,n8.Is,()=>n4.Pl),s=sQ(),a=(0,r.useSyncExternalStore)(n9.wm,n9.Ev,()=>n7.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)(n6,{label:e("theme"),layout:"segmented",value:t,options:rl.map(t=>({...t,label:e(t.label)})),onChange:n8.VS})]}),(0,n.jsxs)("div",{className:"space-y-2 border-b pb-4",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("displaySize")}),(0,n.jsx)(n6,{label:e("displaySize"),layout:"segmented",value:a,options:ro.map(t=>({...t,label:e(t.label)})),onChange:n9.$y})]}),(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("powerSaving")}),(0,n.jsx)(n6,{label:e("powerSaving"),layout:"segmented",value:s?"on":"off",options:[{value:"off",label:e("powerSavingOff"),testId:"power-saving-off"},{value:"on",label:e("powerSavingOn"),testId:"power-saving-on"}],onChange:e=>(function(e){sG=e;try{window.localStorage.setItem(sK,String(e))}catch(e){console.warn("[Pi Desk][Appearance] 省电模式保存失败,仅当前页面生效",e)}window.dispatchEvent(new Event(sH))})("on"===e)})]})]}),(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)(ri,{mode:"static",isAnimating:!1,children:e("displayPreviewContent")})})]})]})]})}var rc=s(58313),ru=s(87642),rm=s(74013),rp=s(82130),rh=s(45803),rg=s(44598);let rx="pi-super:new-work-session-behavior",rf="activate",rb=new Set,rv=rf,rw=!1;function ry(){if(!rw){rw=!0;try{var e;e=window.localStorage.getItem(rx),rv="none"===e||"activate"===e||"pin"===e?e:rf}catch{rv=rf}}}function rk(){return ry(),rv}function rj(e){if(ry(),rv!==e){rv=e;try{window.localStorage.setItem(rx,e)}catch{}for(let e of[...rb])e()}}function rN(e){return rb.add(e),()=>rb.delete(e)}let rI=[{value:"none",label:"behaviorNone",description:"behaviorNoneDescription",icon:rc.A,testId:"new-work-session-behavior-none"},{value:"activate",label:"behaviorActivate",description:"behaviorActivateDescription",icon:ru.A,testId:"new-work-session-behavior-activate"},{value:"pin",label:"behaviorPin",description:"behaviorPinDescription",icon:rm.A,testId:"new-work-session-behavior-pin"}],rC=[{value:"compressed",label:"imageCompressed",description:"imageCompressedDescription",icon:rp.A,testId:"image-preview-mode-compressed"},{value:"original",label:"imageOriginal",description:"imageOriginalDescription",icon:rh.A,testId:"image-preview-mode-original"}];function rS(){let{t:e}=(0,f.Bd)("settings"),t=(0,r.useSyncExternalStore)(rN,rk,rk),s=(0,r.useSyncExternalStore)(rg.ku,rg.Wq,rg.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)(n6,{label:e("newSessionBehavior"),value:t,options:rI.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:rj}),(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)(n6,{label:e("imagePreviewMode"),value:s,options:rC.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:rg.lU}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:e("imagePreviewApply")})]})]})]})}var rM=s(1549),rz=s(21183),rE=s(9156);let rA=a.Yj().trim().min(1).max(128),r$=a.Yj().trim().min(1).max(256),rR=a.Yj().trim().min(1).max(256),rP=a.Yj().trim().min(1).nullable(),rT=a.g1(a.Yj().trim().min(1),a.Yj()),rD=a.Yj().trim().min(1).max(128),rL=a.g1(a.Yj(),a.Pq()),rO=a.Ik({level:rz.$,providerValue:a.Yj().trim().min(1).nullable()}).strict(),rF=a.Ik({input:a.ai().nonnegative().finite(),output:a.ai().nonnegative().finite(),cacheRead:a.ai().nonnegative().finite(),cacheWrite:a.ai().nonnegative().finite()}).strict(),rB=a.Ik({supportsDeveloperRole:a.zM().nullable(),thinkingFormat:a.Yj().trim().min(1).max(128).nullable(),requiresReasoningContentOnAssistantMessages:a.zM().nullable()}).strict(),r_=a.Ik({modelId:r$,name:rR,api:rD.nullable(),baseUrl:rP,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:rF.nullable(),headers:rT,compat:rB.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:rA,name:rP,baseUrl:rP,api:rD.nullable(),apiKey:a.Yj().nullable(),authHeader:a.zM().nullable(),headers:rT,models:a.YO(r_)}).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)}),rW=a.Ik({provider:rA,modelId:r$,thinkingLevel:rz.$,color:a.Yj().regex(/^#[0-9a-fA-F]{6}$/).nullable()}).strict(),rU=a.Ik({provider:rA,modelId:r$,name:rR,input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),thinkingLevels:a.YO(rz.$).min(1).max(7)}).strict(),rY=a.Ik({provider:rA,modelId:r$,thinkingLevel:rz.$}).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:rF.partial().optional()}).strict(),rK=a.Ik({provider:rA,modelId:r$,overrides:rV}).strict(),rH=a.Ik({provider:rA,name:rR,loggedIn:a.zM(),subscription:a.zM(),models:a.YO(r_)}).strict();a.Ik({}).strict();let rG=a.Ik({providers:a.YO(rq),presets:a.YO(rW),models:a.YO(rU),nativeConfig:rL,accountModels:a.YO(rK),accounts:a.YO(rH)}).strict(),rJ=a.Ik({providers:a.YO(rq).optional(),presets:a.YO(rW).optional(),accountModels:a.YO(rK).optional()}).strict().refine(e=>void 0!==e.providers||void 0!==e.presets||void 0!==e.accountModels,{message:"请提交需要保存的模型配置"}),rX=a.KC([rJ,a.Ik({nativeConfig:rL}).strict()]),rQ=a.Ik({}).strict(),rZ=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(),r0=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:rF.nullable()}).strict(),r1=a.Ik({provider:rA,providerName:rR,modelId:r$,official:a.zM(),defaults:r0}).strict(),r2=a.Ik({referenceId:a.Yj().trim().min(1).max(512),name:rR,match:a.k5(["exact","similar"]).nullable(),sources:a.YO(r1).min(1)}).strict(),r5=a.Ik({updatedAt:rE.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(r2)}).strict();a.Ik({cwd:s3.m4}).strict();let r3=a.Ik({cwd:s3.m4,default:rY.nullable(),models:a.YO(rU)}).strict(),r4=a.Ik({cwd:s3.m4,default:rY.nullable()}).strict(),r6=a.Ik({}).strict(),r8=a.Ik({cwd:s3.m4,sessionCount:a.ai().int().nonnegative(),updatedAt:rE.k}).strict();a.Ik({forceRefresh:a.zM().default(!1)}).strict();let r7=a.Ik({directories:a.YO(r8)}).strict();a.Ik({cwd:s3.m4,ignored:a.zM()}).strict(),a.Ik({}).strict();let r9=a.Ik({cwd:s3.m4,name:a.Yj().trim().min(1)}).strict();a.Ik({cwd:s3.m4.nullable()}).strict();let ae=a.Ik({cwd:s3.m4.nullable(),parentCwd:s3.m4.nullable(),directories:a.YO(r9)}).strict(),at=a.k5(["title","user","assistant","sessionId"]),as=a.Ik({scope:at,count:a.ai().int().positive(),entryId:s3.Rv.nullable(),timestampMs:rE.k.nullable(),preview:a.Yj().min(1).max(160)}).strict(),an=a.Ik({sessionId:s3.$E,cwd:s3.m4,name:a.Yj().nullable(),createdAt:rE.k,updatedAt:rE.k,messageCount:a.ai().int().nonnegative(),userMessageCount:a.ai().int().nonnegative(),firstMessage:a.Yj().max(160),matches:a.YO(as).min(1).max(4).nullable()}).strict();a.Ik({cwd:s3.m4,query:a.Yj().trim().max(120).default(""),forceRefresh:a.zM().default(!1),searchIn:a.YO(at).min(1).max(4).default(["title","user"])}).strict(),a.Ik({cwd:s3.m4,sessions:a.YO(an)}).strict(),a.Ik({cwd:s3.m4,sessionId:s3.$E,query:a.Yj().trim().max(120).default(""),page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive().max(50)}).strict()}).strict();let ar=a.Ik({entryId:s3.Rv,timestampMs:rE.k,text:a.Yj()}).strict();a.Ik({page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive(),total:a.ai().int().nonnegative()}).strict(),messages:a.YO(ar)}).strict();let aa="pi-desk:pi-directories",ai="pi-desk:ignored-pi-directories",al="pi-desk:pi-directory-entries",ao=!1,ad=null,ac=null,au=!1,am=new Map;function ap(e){if(null===e)return"<root>";let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function ah(e){try{return JSON.parse(window.localStorage.getItem(e)??"null")}catch{return null}}function ag(){ao||(ao=!0,ad=ah(aa),ac=ah(ai))}function ax(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function af(e){ag(),ad=e,ax(aa,e)}function ab(){if(au)return;au=!0;let e=ah(al);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))am.set(e,s)}function av(e){return ab(),am.get(ap(e))??null}let aw="pi-desk:project-model-defaults",ay=!1,ak=new Map;function aj(e){let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function aN(){if(!ay){ay=!0;try{let e=JSON.parse(window.localStorage.getItem(aw)??"null");if(!e||"object"!=typeof e||Array.isArray(e))return;for(let[t,s]of Object.entries(e)){let e=r3.safeParse(s);e.success&&ak.set(t,e.data)}let t=!1;for(;ak.size>64;){let e=ak.keys().next().value;if(void 0===e)break;ak.delete(e),t=!0}t&&aI()}catch{ak.clear()}}}function aI(){try{window.localStorage.setItem(aw,JSON.stringify(Object.fromEntries(ak)))}catch{}}function aC(e){let t=r3.safeParse(e);if(!t.success)return;aN();let s=aj(t.data.cwd);for(ak.delete(s),ak.set(s,t.data);ak.size>64;){let e=ak.keys().next().value;if(void 0===e)break;ak.delete(e)}aI()}let aS=a.KC([a.k5(["appearance","region","habits","auth","models","mcp-settings","capability-modes","skills","plugins","about"]),a.Uy(["plugin:",a.Yj(),":",a.Yj()])]),aM=a.k5(["providers","presets","project-default"]),az="pi-super:settings:section",aE="pi-super:settings:model-tab";function aA(e,t,s){try{let n=t.safeParse(window.localStorage.getItem(e));return n.success?n.data:s}catch{return s}}function a$(e,t){try{window.localStorage.setItem(e,t)}catch(e){console.warn("[Pi Desk][Settings] 保存设置导航位置失败,仅当前窗口生效",e)}}var aR=s(5099);function aP({open:e,text:t,error:s,saving:r,dirty:a,onChange:i,onClose:l,onSave:o}){let{t:d}=(0,f.Bd)("settings");return(0,n.jsx)(eX.YV,{open:e,onOpenChange:e=>{e||l()},children:(0,n.jsxs)(eX.hA,{className:"max-w-[52rem]",initialFocus:!1,showCloseButton:!r,children:[(0,n.jsxs)(eX.Hl,{className:"border-b px-4 py-4 pr-12",children:[(0,n.jsx)(eX.YM,{children:d("nativeConfig")}),(0,n.jsx)(eX.uX,{children:d("nativeConfigScope")})]}),(0,n.jsx)(eX._Y,{className:"max-h-[70dvh]",children:(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(aR.T,{"aria-label":d("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=>i(e.target.value)}),s?(0,n.jsx)("p",{role:"alert",className:"break-words text-sm text-destructive",children:s}):null]})}),(0,n.jsxs)(eX.vu,{children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",disabled:r,onClick:l,children:d("cancel",{ns:"common"})}),(0,n.jsxs)(N.$,{type:"button",disabled:r||!a,onClick:o,children:[r?(0,n.jsx)(b.A,{className:"animate-spin"}):null,d(r?"savingModels":"saveNativeConfig")]})]})]})})}var aT=s(10942),aD=s(77250),aL=s(67323),aO=s(57143),aF=s(51553);let aB=[{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 a_(e){return aB.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 aq=["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"],aW=["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:aq[t]})),aU=["openai","openrouter","together","deepseek","zai","qwen","chat-template","qwen-chat-template","string-thinking","ant-ling","baseten"];function aY(e){return Object.entries(e).map(([e,t])=>`${e}: ${t}`).join("\n")}function aV({headers:e,onChange:t,placeholder:s}){let[a,i]=(0,r.useState)(null);return(0,n.jsx)(aR.T,{value:a??aY(e),onFocus:()=>i(aY(e)),onChange:e=>{let s=e.target.value;i(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:()=>i(null),rows:4,placeholder:s,className:"font-mono"})}function aK(e){let t=Math.floor(e/1e3),s=e%1e3;return s?`${t}.${String(s).padStart(3,"0").replace(/0+$/,"")}`:String(t)}function aH(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 aG({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 aJ="__pi-desk_empty__";function aX({value:e,options:t,onChange:s,ariaLabel:r,placeholder:a,allowEmpty:i=!0,className:l}){let{t:o}=(0,f.Bd)("settings"),d=a??o("useDefault"),c=e||(i?aJ:t[0]?.value??null),u=!!e&&!t.some(t=>t.value===e);return(0,n.jsxs)(eP.l6,{value:c,onValueChange:e=>s(e===aJ||null===e?"":e),children:[(0,n.jsx)(eP.bq,{"aria-label":r,className:(0,C.cn)("w-full",l),children:(0,n.jsx)(eP.yv,{children:t.find(t=>t.value===e)?.label??(e||d)})}),(0,n.jsxs)(eP.gC,{positionerClassName:"z-[120]",children:[i?(0,n.jsx)(eP.eb,{value:aJ,children:d}):null,u?(0,n.jsx)(eP.eb,{value:e,children:e}):null,t.map(e=>(0,n.jsx)(eP.eb,{value:e.value,children:e.label},e.value))]})]})}function aQ({value:e,onChange:t,ariaLabel:s}){let{t:r}=(0,f.Bd)("settings");return(0,n.jsx)(aX,{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 aZ={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function a0(e,t){return JSON.stringify([e,t])}function a1(e,t){return JSON.stringify([e.provider,e.modelId,e.thinkingLevel,t])}function a2(e){return e.map(e=>({value:a0(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider}))}function a5(e,t){return(e?.thinkingLevels??[]).map(e=>({value:e,label:t(aZ[e])}))}function a3({id:e,preset:t,model:s,models:r,canMoveUp:a,canMoveDown:i,onChange:l,onDelete:o,onMoveUp:d,onMoveDown:c}){let{t:u}=(0,f.Bd)("settings"),{attributes:m,listeners:p,setActivatorNodeRef:h,setNodeRef:g,transform:x,transition:b,isDragging:v}=(0,aD.gl)({id:e}),w=x?`translate3d(${x.x}px, ${x.y}px, 0) scaleX(${x.scaleX??1}) scaleY(${x.scaleY??1})`:void 0,y=t.color?.toLowerCase()??"none",k=aB.find(e=>e.value===y),j=k?u(k.label):u(t.color?"presetColorCustom":"presetColorNone"),I=[{value:"none",color:null,label:u("presetColorNone")},...t.color&&!k?[{value:y,color:t.color,label:u("presetColorCustom")}]:[],...aB.map(e=>({value:e.value,color:e.value,label:u(e.label)}))];return(0,n.jsxs)("div",{ref:g,style:{transform:w,transition:b},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)(N.$,{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)(aL.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(N.$,{variant:"ghost",size:"icon-sm",type:"button",title:u("presetMoveUp"),"aria-label":u("presetMoveUp"),disabled:!a,onClick:d,children:(0,n.jsx)(aO.A,{className:"size-4"})}),(0,n.jsx)(N.$,{variant:"ghost",size:"icon-sm",type:"button",title:u("presetMoveDown"),"aria-label":u("presetMoveDown"),disabled:!i,onClick:c,children:(0,n.jsx)(ti.A,{className:"size-4"})})]})]}),(0,n.jsx)(aG,{label:u("modelsHeading"),children:(0,n.jsx)(nG.b,{value:a0(t.provider,t.modelId),options:a2(r),ariaLabel:u("presetModel"),searchPlaceholder:u("modelSearch"),onChange:e=>{let s=r.find(t=>a0(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)(aG,{label:u("thinkingLevel"),children:(0,n.jsx)(aX,{value:t.thinkingLevel,options:a5(s,u),ariaLabel:u("presetThinking"),allowEmpty:!1,onChange:e=>l({...t,thinkingLevel:e})})}),(0,n.jsx)(aG,{label:u("presetColor"),children:(0,n.jsxs)(eP.l6,{value:y,onValueChange:e=>{null!==e&&l({...t,color:"none"===e?null:e})},children:[(0,n.jsx)(eP.bq,{"aria-label":u("presetColorLabel"),className:"w-16",children:(0,n.jsxs)(eP.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)(aF.A,{"aria-hidden":"true",className:"size-4 text-muted-foreground"}),(0,n.jsx)("span",{className:"sr-only",children:j})]})}),(0,n.jsx)(eP.gC,{positionerClassName:"z-[120]",className:"w-40 min-w-40",align:"end",alignItemWithTrigger:!1,children:(0,n.jsx)(eP.s3,{className:"grid grid-cols-4 gap-1 p-2",children:I.map(e=>(0,n.jsx)(eP.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)(aF.A,{"aria-hidden":"true",className:"size-4 text-muted-foreground"})},e.value))})})]})}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm",title:u("presetDelete"),"aria-label":u("presetDelete"),onClick:o,children:(0,n.jsx)(ez.A,{})})]})}function a4({presets:e,models:t,onChange:s}){let{t:a}=(0,f.Bd)("settings"),[i,l]=(0,r.useState)(()=>t[0]?a0(t[0].provider,t[0].modelId):""),o=t.find(e=>a0(e.provider,e.modelId)===i),[d,c]=(0,r.useState)(o?.thinkingLevels[0]??"off"),u=(0,aT.FR)((0,aT.MS)(aT.AN,{activationConstraint:{distance:6}}),(0,aT.MS)(aT.uN,{coordinateGetter:aD.JR})),m=(0,r.useMemo)(()=>e.map(a1),[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:a("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)(aG,{label:a("modelsHeading"),children:(0,n.jsx)(nG.b,{value:i,options:a2(t),ariaLabel:a("presetModelNew"),searchPlaceholder:a("modelSearch"),disabled:0===t.length,onChange:e=>{l(e);let s=t.find(t=>a0(t.provider,t.modelId)===e);s&&c(s.thinkingLevels[0])}})}),(0,n.jsx)(aG,{label:a("thinkingLevel"),children:(0,n.jsx)(aX,{value:d,options:a5(o,a),ariaLabel:a("presetThinkingNew"),allowEmpty:!1,onChange:e=>c(e)})}),(0,n.jsxs)(N.$,{type:"button",variant:"outline",className:"self-end justify-self-start",onClick:function(){let n=t.find(e=>a0(e.provider,e.modelId)===i);if(!n)return;let r=n.thinkingLevels.includes(d)?d: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:a_(e)}])},disabled:!o,children:[(0,n.jsx)(Y.A,{})," ",a("presetAdd")]})]}),0===e.length?(0,n.jsx)("p",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:a("presetEmpty")}):(0,n.jsx)(aT.Mp,{sensors:u,collisionDetection:aT.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,aD.be)(e,n,r))},children:(0,n.jsx)(aD.gB,{items:m,strategy:aD._G,children:(0,n.jsx)("div",{className:"space-y-2",children:e.map((r,a)=>{let i=t.find(e=>e.provider===r.provider&&e.modelId===r.modelId);return(0,n.jsx)(a3,{id:m[a],preset:r,model:i,models:t,canMoveUp:a>0,canMoveDown:a<e.length-1,onChange:t=>s(e.map((e,s)=>s===a?t:e)),onDelete:()=>s(e.filter((e,t)=>t!==a)),onMoveUp:()=>s((0,aD.be)(e,a,a-1)),onMoveDown:()=>s((0,aD.be)(e,a,a+1))},m[a])})})})})]})}var a6=s(60222),a8=s(54901),a7=s(10180);function a9(e){return 100*!!e.official+10*!!e.defaults.cost}let ie=[["off","thinkingOff"],["minimal","thinkingMinimal"],["low","thinkingLow"],["medium","thinkingMedium"],["high","thinkingHigh"],["xhigh","thinkingXhigh"],["max","thinkingMax"]],it=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function is(e){return{input:String(e.cost?.input??""),output:String(e.cost?.output??""),cacheRead:String(e.cost?.cacheRead??""),cacheWrite:String(e.cost?.cacheWrite??"")}}function ir(e,t){return Object.values(e).some(e=>null===aH(e))||Object.values(t).some(e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e)))}function ia({biz:e,provider:t,model:s,onChange:a,onInputState:i}){let{t:l}=(0,f.Bd)("settings"),o=(0,r.useId)(),[d,c]=(0,r.useState)({contextWindow:aK(s.contextWindow),maxTokens:aK(s.maxTokens)}),[u,m]=(0,r.useState)(()=>is(s)),{searchText:p,setSearchText:h,catalogOpen:g,setCatalogOpen:x,loadingCatalog:v,candidates:w,visibleCandidates:y,showAllCandidates:k,setShowAllCandidates:j,selectedCandidateKey:I,setSelectedCandidateKey:C}=function(e,t){let{t:s}=(0,f.Bd)("settings"),n=(0,eC.G)(),a=(0,r.useRef)(0),[i,l]=(0,r.useState)(t),[o,d]=(0,r.useState)([]),[c,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[x,b]=(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=i.trim().toLocaleLowerCase();return[...e.entries()].map(([e,t])=>{let s=[...t.sources].sort((e,t)=>a9(t)-a9(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,i]);return(0,r.useEffect)(()=>{let t=++a.current;if(!c)return;let r=window.setTimeout(()=>{g(!0),e.listCatalog({query:i.trim(),refresh:!1,page:{index:1,size:10}}).then(e=>{a.current===t&&d(e.models)}).catch(e=>{a.current===t&&(d([]),n.error(e instanceof Error?e.message:s("catalogSearchFailed")))}).finally(()=>{a.current===t&&g(!1)})},250);return()=>{window.clearTimeout(r),a.current===t&&(a.current+=1)}},[e,c,i,n,s]),{searchText:i,setSearchText:l,catalogOpen:c,setCatalogOpen:e=>{u(e),e||g(!1)},loadingCatalog:h,candidates:v,visibleCandidates:x?v:v.slice(0,6),showAllCandidates:x,setShowAllCandidates:b,selectedCandidateKey:m,setSelectedCandidateKey:p}}(e,s.modelId),S=new Map(s.thinkingLevels.map(e=>[e.level,e])),M=aW.find(e=>e.value===t.api)?.label??t.api;function z(e){a({...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)(a7.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(),x(!1))},children:(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(a7.G7,{id:o,value:p,onValueChange:e=>{h(e),z({modelId:e}),C(null),j(!1),x(!0)},placeholder:l("modelIdSearch"),"aria-label":l("modelId"),"aria-autocomplete":"list",className:"pr-9"}),(0,n.jsxs)(th.AM,{open:g,onOpenChange:e=>{x(e),e&&j(!1)},children:[(0,n.jsx)(th.Wv,{render:(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm",title:l("chooseModel"),"aria-label":l("chooseModel"),"aria-busy":v,className:"absolute top-0.5 right-0.5 z-10",children:v?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(a8.A,{})})}),(0,n.jsx)(th.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)(a7.oI,{className:"max-h-[min(24rem,var(--available-height))] p-1",children:v&&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)(a7.xL,{className:"py-6 text-sm",children:l("noCatalogMatches")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a7.L$,{className:"p-0",children:y.map(e=>(0,n.jsx)(a7.h_,{value:e.key,"data-checked":I===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};a(r),c({contextWindow:aK(r.contextWindow),maxTokens:aK(r.maxTokens)}),m(is(r)),i({dirty:!1,invalid:!1}),h(n.modelId),C(e.key),j(!1),x(!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:`${aK(e.source.defaults.contextWindow)}K`,output:`${aK(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)(N.$,{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)(aG,{label:l("modelName"),className:"@[32rem]/model-editor:col-span-2",children:[(0,n.jsx)(eB.p,{value:s.name,onChange:e=>z({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===aH(d[e]);return(0,n.jsxs)(aG,{label:l(t),children:[(0,n.jsxs)(n$.MG,{children:[(0,n.jsx)(n$.iV,{"aria-label":l(t),inputMode:"decimal",value:d[e],"aria-invalid":s,"aria-describedby":s?`${o}-${e}-error`:void 0,onChange:t=>{var s;let n,r,a;return s=t.target.value,c(n={...d,[e]:s}),i({dirty:r=ir(n,u),invalid:r}),void(null!==(a=aH(s))&&z({[e]:a}))}}),(0,n.jsx)(n$.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)(N.$,{type:"button",size:"sm",variant:"outline","aria-pressed":t,onClick:()=>{t&&1===s.input.length||z({input:t?s.input.filter(t=>t!==e):[...s.input,e]})},children:[t?(0,n.jsx)(ed.A,{}):null,l("text"===e?"textInput":"imageInput")]},e)}),(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline","aria-pressed":s.reasoning,onClick:()=>z({reasoning:!s.reasoning,thinkingLevels:s.reasoning?[{level:"off",providerValue:null}]:[{level:"high",providerValue:null}]}),children:[s.reasoning?(0,n.jsx)(ed.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:ie.map(([e,t])=>{let r=S.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)(N.$,{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&&z({thinkingLevels:t})},children:[r?(0,n.jsx)(ed.A,{}):null,l(t)]}),(0,n.jsx)(eB.p,{"aria-label":l("providerMapping",{level:l(t)}),disabled:!r||"off"===e,value:"off"===e?l("noMapping"):r?.providerValue??"",placeholder:e,onChange:t=>z({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:[it.map(([e,t])=>{let r=""!==u[e]&&(!Number.isFinite(Number(u[e]))||0>Number(u[e]));return(0,n.jsxs)(aG,{label:l(t),children:[(0,n.jsx)(eB.p,{inputMode:"decimal",value:u[e],"aria-invalid":r,onChange:t=>(function(e,t){let n={...u,[e]:t};m(n);let r=ir(d,n);if(i({dirty:r,invalid:r}),Object.values(n).every(e=>""===e))return void z({cost:null});let a=Number(t);Number.isFinite(a)&&!(a<0)&&z({cost:{input:s.cost?.input??0,output:s.cost?.output??0,cacheRead:s.cost?.cacheRead??0,cacheWrite:s.cost?.cacheWrite??0,[e]:a}})})(e,t.target.value)}),r?(0,n.jsx)("span",{role:"alert",className:"text-xs text-destructive",children:l("priceInvalid")}):null]},e)}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",className:"justify-self-start",onClick:()=>{let e={input:"",output:"",cacheRead:"",cacheWrite:""};m(e),i({dirty:!0,invalid:ir(d,e)}),z({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)(aG,{label:l("apiOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(aX,{value:s.api??"",ariaLabel:l("apiOverride"),options:aW,placeholder:M?l("inheritServiceValue",{value:M}):l("inheritService"),onChange:e=>z({api:e||null})})}),(0,n.jsx)(aG,{label:l("baseUrlOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(eB.p,{value:s.baseUrl??"","aria-label":l("baseUrlOverride"),placeholder:t.baseUrl?l("inheritServiceValue",{value:t.baseUrl}):l("inheritService"),onChange:e=>z({baseUrl:e.target.value||null})})}),(0,n.jsx)(aG,{label:l("modelHeaders"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(aV,{headers:s.headers,onChange:e=>z({headers:e}),placeholder:l("headerPlaceholder")})}),(0,n.jsx)(aG,{label:l("developerRole"),children:(0,n.jsx)(aQ,{value:s.compat?.supportsDeveloperRole??null,ariaLabel:l("developerRole"),onChange:e=>z({compat:{supportsDeveloperRole:e,thinkingFormat:s.compat?.thinkingFormat??null,requiresReasoningContentOnAssistantMessages:s.compat?.requiresReasoningContentOnAssistantMessages??null}})})}),(0,n.jsx)(aG,{label:"Thinking Format",children:(0,n.jsx)(aX,{value:s.compat?.thinkingFormat??"",ariaLabel:"Thinking Format",options:aU.map(e=>({value:e,label:e})),onChange:e=>z({compat:{supportsDeveloperRole:s.compat?.supportsDeveloperRole??null,thinkingFormat:e||null,requiresReasoningContentOnAssistantMessages:s.compat?.requiresReasoningContentOnAssistantMessages??null}})})}),(0,n.jsx)(aG,{label:l("replayReasoning"),children:(0,n.jsx)(aQ,{value:s.compat?.requiresReasoningContentOnAssistantMessages??null,ariaLabel:l("replayReasoning"),onChange:e=>z({compat:{supportsDeveloperRole:s.compat?.supportsDeveloperRole??null,thinkingFormat:s.compat?.thinkingFormat??null,requiresReasoningContentOnAssistantMessages:e}})})})]})]})]})}var ii=s(3219),il=s(90279);function io({className:e,disabled:t,id:s,...a}){let{t:i}=(0,f.Bd)("common"),[l,o]=r.useState(!1),d=i(l?"hideSecret":"revealSecret");return(0,n.jsxs)("div",{className:"relative min-w-0",children:[(0,n.jsx)(eB.p,{...a,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":d,"aria-controls":s,"aria-pressed":l,title:d,disabled:t,onClick:()=>o(e=>!e),children:l?(0,n.jsx)(ii.A,{className:"size-3.5"}):(0,n.jsx)(il.A,{className:"size-3.5"})})]})}function id({provider:e,existingIds:t,isNew:s,onApply:a,onDelete:i,onClose:l,onDirtyChange:o}){let{t:d}=(0,f.Bd)("settings"),{confirm:c,dialog:u}=nW(),[m,p]=(0,r.useState)(()=>structuredClone(e)),h=JSON.stringify(m)!==JSON.stringify(e),g=!m.provider.trim()||t.includes(m.provider.trim()),x=m.provider||d("providerUnnamed");function b(e){p(t=>({...t,...e}))}async function v(){(!h||await c({title:d("discardServiceTitle"),description:d("discardServiceDescription"),confirmLabel:d("discardModelConfirm")}))&&l()}async function w(){await c({title:d("providerDeleteTitle"),description:d("providerDeleteDescription",{name:x,count:e.models.length})})&&i()}return(0,r.useEffect)(()=>(o(h),()=>o(!1)),[h,o]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eX.YV,{open:!0,onOpenChange:e=>{e||v()},children:(0,n.jsxs)(eX.hA,{className:"max-w-[40rem]",initialFocus:!1,children:[(0,n.jsxs)(eX.Hl,{className:"border-b px-4 py-4 pr-12",children:[(0,n.jsx)(eX.YM,{children:d("serviceConnection")}),(0,n.jsx)(eX.uX,{children:d("serviceDraftScope",{count:e.models.length})})]}),(0,n.jsx)(eX._Y,{className:"max-h-[65dvh]",children:(0,n.jsxs)("div",{className:"space-y-5 p-4",children:[(0,n.jsxs)(aG,{label:d("serviceId"),children:[(0,n.jsx)(eB.p,{value:m.provider,"aria-label":d("serviceId"),autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:d("providerIdExample"),"aria-invalid":g,onChange:e=>b({provider:e.target.value})}),g?(0,n.jsx)("span",{role:"alert",className:"text-xs text-destructive",children:d("serviceIdInvalid")}):null]}),(0,n.jsx)(aG,{label:d("serviceAddress"),children:(0,n.jsx)(eB.p,{value:m.baseUrl??"",placeholder:"https://api.example.com/v1",onChange:e=>b({baseUrl:e.target.value||null})})}),(0,n.jsx)(aG,{label:d("providerApiType"),children:(0,n.jsx)(aX,{value:m.api??"",ariaLabel:d("providerApiType"),options:aW,onChange:e=>b({api:e||null})})}),(0,n.jsx)(aG,{label:d("serviceKey"),children:(0,n.jsx)(io,{value:m.apiKey??"",onChange:e=>b({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:d("providerAdvanced")}),(0,n.jsxs)("div",{className:"mt-3 space-y-3",children:[(0,n.jsx)(aG,{label:d("providerAuthHeader"),children:(0,n.jsx)(aQ,{value:m.authHeader,ariaLabel:d("providerAuthHeader"),onChange:e=>b({authHeader:e})})}),(0,n.jsx)(aG,{label:d("providerHeaders"),children:(0,n.jsx)(aV,{headers:m.headers,onChange:e=>b({headers:e}),placeholder:d("headerPlaceholder")})})]})]})]})}),(0,n.jsxs)(eX.vu,{children:[s?null:(0,n.jsxs)(N.$,{type:"button",variant:"ghost",className:"mr-auto text-destructive hover:text-destructive",onClick:w,children:[(0,n.jsx)(ez.A,{}),d("providerDelete")]}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",onClick:l,children:d("cancel",{ns:"common"})}),(0,n.jsx)(N.$,{type:"button",disabled:g||!h&&!s,onClick:()=>a(m),children:d("applyServiceDraft")})]})]})}),u]})}let ic=a.Ik({}).strict(),iu=a.Yj().trim().min(1).max(128),im=a.Yj().max(32768),ip=a.Ik({url:im,label:im.optional()}).strict(),ih=a.Ik({provider:iu,name:im,loggedIn:a.zM(),conflict:a.Yj().nullable()}).strict(),ig=a.Ik({id:a.Yj().uuid(),type:a.k5(["text","secret","select","manual_code"]),message:im,placeholder:im.optional(),options:a.YO(a.Ik({id:im,label:im,description:im.optional()}).strict()).optional()}).strict(),ix=a.gM("type",[a.Ik({type:a.eu("auth_url"),url:im,instructions:im.optional()}).strict(),a.Ik({type:a.eu("device_code"),userCode:im,verificationUri:im}).strict(),a.Ik({type:a.eu("info"),message:im,links:a.YO(ip).optional()}).strict(),a.Ik({type:a.eu("progress"),message:im}).strict()]),ib=a.Ik({loginId:a.Yj().uuid(),provider:iu,status:a.k5(["running","completed","cancelled","error"]),notice:ix.nullable(),prompt:ig.nullable(),message:a.Yj().nullable()}).strict(),iv=Object.freeze({list:(0,i.Vc)({path:"model-auth/list",inputSchema:ic,outputSchema:a.Ik({providers:a.YO(ih)}).strict()}),start:(0,i.Vc)({path:"model-auth/start",inputSchema:a.Ik({loginId:a.Yj().uuid(),provider:iu}).strict(),outputSchema:ic}),respond:(0,i.Vc)({path:"model-auth/respond",inputSchema:a.Ik({loginId:a.Yj().uuid(),promptId:a.Yj().uuid(),value:im}).strict(),outputSchema:ic}),cancel:(0,i.Vc)({path:"model-auth/cancel",inputSchema:a.Ik({loginId:a.Yj().uuid()}).strict(),outputSchema:ic}),logout:(0,i.Vc)({path:"model-auth/logout",inputSchema:a.Ik({provider:iu}).strict(),outputSchema:ic}),state:(0,i._G)({path:"model-auth/state",bodySchema:ib})});function iw(e){try{let t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}}function iy(e){let t=iw(e);t&&window.open(t,"_blank","noopener,noreferrer")}async function ik(e){await navigator.clipboard.writeText(e)}function ij({prompt:e,submitting:t,onRespond:s}){let{t:a}=(0,f.Bd)("settings"),[i,l]=(0,r.useState)(""),o="select"!==e.type||i.length>0;return(0,n.jsxs)("form",{className:"grid gap-3",onSubmit:n=>{n.preventDefault(),o&&!t&&s(e.id,i)},children:[(0,n.jsx)(aG,{label:e.message,children:"select"===e.type?(0,n.jsx)(aX,{value:i,ariaLabel:e.message,placeholder:e.placeholder??a("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)(io,{value:i,placeholder:e.placeholder,disabled:t,onChange:e=>l(e.target.value)}):(0,n.jsx)(eB.p,{value:i,placeholder:e.placeholder,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,disabled:t,onChange:e=>l(e.target.value)})}),(0,n.jsx)(N.$,{type:"submit",disabled:!o||t,className:"justify-self-end",children:a("accountContinue")})]})}function iN({notice:e,onCopy:t,onOpenUrl:s}){let{t:r}=(0,f.Bd)("settings"),a="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)(N.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void t(e.userCode),children:r("accountCopyCode")})]}):null,a.map((e,a)=>iw(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)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>s(e.url),children:e.label??r("accountOpenLink")}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>void t(e.url),children:r("accountCopyLink")})]})]},`${a}:${e.url}`):(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:r("accountInvalidLink")},a))]})}function iI({open:e,connected:t,providers:s,state:r,loading:a,submitting:i,error:l,onClose:o,onStart:d,onRespond:c,onCopy:u,onOpenUrl:m,onRetry:p}){let{t:h}=(0,f.Bd)("settings"),g=r?.status==="running";return(0,n.jsx)(eX.YV,{open:e,onOpenChange:e=>{e||o()},children:(0,n.jsxs)(eX.hA,{className:"max-w-lg",children:[(0,n.jsx)(eX.Hl,{className:"border-b p-4 pr-12",children:(0,n.jsx)(eX.YM,{children:r?s.find(e=>e.provider===r.provider)?.name??r.provider:h("accountLogin")})}),(0,n.jsx)(eX._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:a?(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)(N.$,{type:"button",variant:"outline",className:"h-auto min-h-10 justify-between whitespace-normal text-left",disabled:!t||!!e.conflict,onClick:()=>void d(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)(iN,{notice:r.notice,onCopy:u,onOpenUrl:m}):null,g&&r.prompt?(0,n.jsx)(ij,{prompt:r.prompt,submitting:i||!t,onRespond:c},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)(eX.vu,{children:[l&&!g?(0,n.jsx)(N.$,{type:"button",variant:"outline",disabled:a,onClick:p,children:h("retry",{ns:"common"})}):null,(0,n.jsx)(N.$,{type:"button",variant:"ghost",onClick:o,children:h(g?"cancel":"close",{ns:"common"})})]})]})})}function iC({account:e,existingIds:t,onAdd:s,onClose:a}){let{t:i}=(0,f.Bd)("settings"),[l,o]=(0,r.useState)(""),[d,c]=(0,r.useState)([]),u=e.models.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(l.toLocaleLowerCase()));return(0,n.jsx)(eX.YV,{open:!0,onOpenChange:e=>{e||a()},children:(0,n.jsxs)(eX.hA,{className:"max-w-xl",children:[(0,n.jsx)(eX.Hl,{className:"border-b p-4 pr-12",children:(0,n.jsx)(eX.YM,{children:i("modelAddToService",{name:e.name})})}),(0,n.jsx)("div",{className:"p-4 pb-2",children:(0,n.jsx)(eB.p,{value:l,"aria-label":i("accountModelSearch"),placeholder:i("accountModelSearch"),onChange:e=>o(e.target.value)})}),(0,n.jsx)(eX._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||d.includes(e.modelId),disabled:s,onChange:t=>c(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 ",aK(e.contextWindow)," K"]})]}),s?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:i("accountModelAdded")}):null]},e.modelId)}),u.length?null:(0,n.jsx)("p",{className:"py-6 text-center text-sm text-muted-foreground",children:i("accountNoModels")})]})}),(0,n.jsxs)(eX.vu,{children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",onClick:a,children:i("accountAddLater")}),(0,n.jsx)(N.$,{type:"button",disabled:!d.length,onClick:()=>s(d),children:i("accountAddSelected",{count:d.length})})]})]})})}let iS=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function iM({model:e,account:t,overrides:s,onChange:a,onInputState:i}){let{t:l}=(0,f.Bd)("settings"),[o,d]=(0,r.useState)(()=>({contextWindow:void 0===s.contextWindow?"":aK(s.contextWindow),maxTokens:void 0===s.maxTokens?"":aK(s.maxTokens),...Object.fromEntries(iS.map(([e])=>[e,s.cost?.[e]===void 0?"":String(s.cost[e])]))})),c=e=>""!==e&&null===aH(e),u=e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e));function m(e,t){let n={...o,[e]:t};d(n);let r=c(n.contextWindow)||c(n.maxTokens)||iS.some(([e])=>u(n[e]));if(i({dirty:r,invalid:r}),"contextWindow"===e||"maxTokens"===e){if(c(t))return;let n={...s};""===t?delete n[e]:n[e]=aH(t),a(n)}else{if(iS.some(([e])=>u(n[e])))return;let e={...s};iS.every(([e])=>""===n[e])?delete e.cost:e.cost=Object.fromEntries(iS.filter(([e])=>""!==n[e]).map(([e])=>[e,Number(n[e])])),a(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:[aK(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:[aK(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?iS.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)(aG,{label:`${l("contextWindow"===t?"contextLength":"maximumOutput")} (K)`,children:[(0,n.jsx)(eB.p,{value:o[t],placeholder:aK(e[t]),inputMode:"decimal","aria-invalid":c(o[t]),onChange:e=>m(t,e.target.value)}),c(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:iS.map(([t,s])=>(0,n.jsxs)(aG,{label:l(s),children:[(0,n.jsx)(eB.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)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>{d({contextWindow:"",maxTokens:"",input:"",output:"",cacheRead:"",cacheWrite:""}),a({}),i({dirty:!1,invalid:!1})},children:l("accountRestoreDefaults")})]})]})]})}var iz=s(73160);function iE({name:e,hasAccount:t,loggedIn:s,hasCustom:a,onCustomSettings:i,onLogin:l,onLogout:o}){let{t:d}=(0,f.Bd)("settings"),[c,u]=(0,r.useState)(!1),m=(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":d("serviceSettingsNamed",{name:e}),onClick:t?void 0:i,children:(0,n.jsx)(iz.A,{})});function p(e){u(!1),e()}return t?(0,n.jsxs)(th.AM,{open:c,onOpenChange:u,children:[(0,n.jsx)(th.Wv,{render:m}),(0,n.jsxs)(th.hl,{align:"end",positionerClassName:"z-[120]",className:"w-52 gap-1 p-1",children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",className:"justify-start",onClick:()=>p(l),children:d(s?"accountRelogin":"accountLogin")}),s?(0,n.jsx)(N.$,{type:"button",variant:"ghost",className:"justify-start text-destructive",onClick:()=>p(o),children:d("accountLogout")}):null,a?(0,n.jsx)(N.$,{type:"button",variant:"ghost",className:"justify-start",onClick:()=>p(i),children:d("accountCustomSettings")}):null]})]}):m}function iA({providerId:e,custom:t,account:s,accountModels:r,query:a,modelKeys:i,selectedCustomIndex:l,selectedAccountId:o,presets:d,onSelectCustom:c,onSelectAccount:u,onCustomSettings:m,onAddCustom:p,onAddAccount:h,onLogin:g,onLogout:x,onGroupRef:b,onRowRef:v}){let{t:w}=(0,f.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:i[t],modelId:e.modelId,name:e.name,model:e,selected:l===t,select:()=>c(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)}})],I=j.filter(t=>`${e} ${y} ${s?.name??""} ${t.name} ${t.modelId}`.toLocaleLowerCase().includes(a.toLocaleLowerCase()));if(a&&!I.length&&!`${e} ${y} ${s?.name??""}`.toLocaleLowerCase().includes(a.toLocaleLowerCase()))return null;let S=!!s||r.length>0;return(0,n.jsxs)("section",{ref:b,className:"mb-3",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-foreground",children:[(0,n.jsx)(e1.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)(iE,{name:y,hasAccount:S,loggedIn:s?.loggedIn??!1,hasCustom:!!t,onCustomSettings:m,onLogin:g,onLogout:x})]}),(0,n.jsxs)("div",{className:"space-y-1",children:[I.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?`${aK(t.model.contextWindow)} K \xb7 ${w(t.model.input.includes("image")?"imageInput":"textInput")}`:w("accountModelUnavailableShort")})]}),d.some(s=>s.provider===e&&s.modelId===t.modelId)?(0,n.jsx)(a6.A,{className:"size-4 shrink-0 text-muted-foreground"}):null]},t.key)),S?(0,n.jsxs)(N.$,{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)(Y.A,{}),w("modelAdd")]}):null,t?(0,n.jsxs)(N.$,{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)(Y.A,{}),S?w("accountCustomModel"):null]}):null]})]})}let i$={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function iR({biz:e,connectionReady:t,providers:s,accounts:a,accountModels:i,onAccountModelsChange:l,onRefreshAccounts:o,savedModels:d,savedProviders:c,presets:u,resetVersion:m,onChange:p,onPresetsChange:h,onInputState:g,onServiceDirtyChange:x}){let{t:b}=(0,f.Bd)("settings"),{confirm:v,dialog:w}=nW(),y=(0,eC.G)(),[k,j]=(0,r.useState)(null),[I,S]=(0,r.useState)(null),[M,z]=(0,r.useState)(!1),[A,$]=(0,r.useState)(()=>new Set),R=function(e,t){let{appSocket:s}=(0,eR.gM)(),n=(0,r.useMemo)(()=>({list:async()=>(await s.request(iv.list,{})).providers,async start(e,t){await s.request(iv.start,{loginId:e,provider:t})},async respond(e,t,n){await s.request(iv.respond,{loginId:e,promptId:t,value:n})},async cancel(e){await s.request(iv.cancel,{loginId:e})},async logout(e){await s.request(iv.logout,{provider:e})},subscribe:e=>s.subscribe(iv.state,e)}),[s]),{t:a}=(0,f.Bd)("settings"),i=(0,eC.G)(),[l,o]=(0,r.useState)(!1),[d,c]=(0,r.useState)([]),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),[g,x]=(0,r.useState)(!1),[b,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),C=(0,r.useRef)(null),S=(0,r.useRef)(0),M=(0,r.useRef)(t);function z(){let e=j.current;j.current=null,N.current=null,I.current=null,C.current?.(),C.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 E(){S.current+=1,z(),o(!1),m(null),y(null),v(null),x(!1)}async function A(){let e=j.current;if(!e||"completed"!==e.status||I.current)return;I.current=e.loginId,x(!0),y(null);let t=()=>j.current?.loginId===e.loginId;try{await M.current(e.provider,t),t()&&E()}catch(e){t()&&y(e instanceof Error?e.message:a("accountRefreshFailed"))}finally{t()&&(I.current=null,x(!1))}}async function $(e){if(!k.current)return void y(a("accountConnectionNotReady"));if(j.current?.status==="running")return;z();let t={loginId:crypto.randomUUID(),provider:e,status:"running",notice:null,prompt:null,message:null};j.current=t,m(t),y(null),v(null),C.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:a("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;z(),m(null),y(e instanceof Error?e.message:a("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:a("accountLoginFailed"))}finally{N.current===r&&(N.current=null,v(null))}}return(0,r.useEffect)(()=>{M.current=t},[t]),(0,r.useEffect)(()=>()=>{S.current+=1;let e=j.current;j.current=null,C.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,C.current?.(),C.current=null,n.cancel(t.loginId).catch(()=>void 0);let s=S.current;queueMicrotask(()=>{S.current===s&&(m(null),v(null),y(a("accountDisconnected")))})},[e,n,a]),{open:l,providers:d,state:u,loading:p||g,submitting:null!==b&&b===u?.prompt?.id,error:w,show:function(e){if(E(),o(!0),!k.current){h(!1),y(a("accountConnectionNotReady"));return}h(!0);let t=++S.current;n.list().then(s=>{S.current===t&&(c(s),e&&s.some(t=>t.provider===e&&!t.conflict)&&$(e))}).catch(e=>{S.current===t&&y(e instanceof Error?e.message:a("accountLoginFailed"))}).finally(()=>{S.current===t&&h(!1)})},close:E,start:$,respond:R,finish:A,async logout(e){if(!k.current)throw Error(a("accountConnectionNotReady"));await n.logout(e)},async copy(e){try{await ik(e),i.success(a("accountCopied"))}catch{i.error(a("accountCopyFailed"))}},openUrl:iy}}(t,async(e,t)=>{await o(),t()&&S(e)}),P=function(e,t,s,n){let[a,i]=(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),[d,c]=(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,g]=(0,r.useState)({}),[x,f]=(0,r.useState)(null),[b,v]=(0,r.useState)(!1),w=(0,r.useRef)(e);function y(e){g(t=>Object.fromEntries(Object.entries(t).filter(([t])=>!e.includes(t))))}function k(){f(null),v(!1)}return(0,r.useEffect)(()=>{w.current=e},[e]),(0,r.useEffect)(()=>{queueMicrotask(()=>{let e=w.current;g({}),m(e.map((e,t)=>e.models.map((e,s)=>`${t}:${s}`))),i(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(h);s({dirty:e.some(e=>e.dirty),invalid:e.some(e=>e.invalid)})},[h,s]),{selection:a,mobileDetail:l,query:d,setQuery:c,modelKeys:u,serviceIndex:x,newService:b,openService:e=>{f(e),v(null===e)},closeService:k,applyService:s=>{b?(t([...e,s]),m(e=>[...e,[]])):t(e.map((e,t)=>t===x?s:e)),k()},deleteService:()=>{if(null===x)return;y(u[x]);let s=e.filter((e,t)=>t!==x);t(s),m(e=>e.filter((e,t)=>t!==x)),i(e=>{if(!e||e.providerIndex===x){let e=s.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),k()},addModel:s=>{let n=e[s];t(e.map((e,t)=>t===s?{...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));let r=`new-${++p.current}`;m(e=>e.map((e,t)=>t===s?[...e,r]:e)),i({providerIndex:s,modelIndex:n.models.length}),c(""),o(!0)},selectModel:(e,t)=>{i({providerIndex:e,modelIndex:t}),o(!0)},backToList:()=>{o(!1),c("")},updateModel:function(s,n,r){t(e.map((e,t)=>t===s?{...e,models:e.models.map((e,t)=>t===n?r:e)}:e))},deleteModel:(s,n)=>{y([u[s][n]]);let r=e.map((e,t)=>t===s?{...e,models:e.models.filter((e,t)=>t!==n)}:e);t(r),m(e=>e.map((e,t)=>t===s?e.filter((e,t)=>t!==n):e)),i(e=>{if(!e||e.providerIndex!==s)return e;if(e.modelIndex===n){if(r[s].models.length)return{providerIndex:s,modelIndex:Math.min(n,r[s].models.length-1)};let e=r.findIndex(e=>e.models.length);return e<0?null:{providerIndex:e,modelIndex:0}}return e.modelIndex>n?{...e,modelIndex:e.modelIndex-1}:e}),o(!1)},updateInputState:(e,t)=>g(s=>({...s,[e]:t}))}}(s,p,g,m),{selection:T,mobileDetail:D,query:L,setQuery:O,modelKeys:F,serviceIndex:B,newService:_}=P,q=(0,r.useRef)(new Map),W=(0,r.useRef)(new Map),[U,V]=(0,r.useState)(!1),[K,H]=(0,r.useState)("off"),G=i.find(e=>e.provider===k?.provider&&e.modelId===k?.modelId)??(s.some(e=>e.models.length)?void 0:i[0]),J=a.find(e=>e.provider===G?.provider),X=J?.models.find(e=>e.modelId===G?.modelId),Q=!!G,Z=!Q&&T?s[T.providerIndex]:null,ee=!Q&&T?Z?.models[T.modelIndex]:null,et=Q?M:D&&!!ee,es=Q?X?.name??G?.modelId:ee?.name||ee?.modelId||b("modelUnnamed"),en=G?.provider||Z?.provider||b("providerUnnamed"),er=a.find(e=>e.provider===I),ea=[...new Set([...s.map(e=>e.provider),...a.map(e=>e.provider),...i.map(e=>e.provider)])],ei=e=>`account:${e.provider}:${e.modelId}`,el=new Set(i.map(ei)),eo=new Set([...A].filter(e=>el.has(e)));G&&eo.add(ei(G)),(eo.size!==A.size||G&&!A.has(ei(G)))&&$(eo);let[ed,ec]=(0,r.useState)(()=>new Set),eu=T?F[T.providerIndex]?.[T.modelIndex]:void 0,em=new Set(F.flat()),ep=new Set([...ed].filter(e=>em.has(e)));eu&&ep.add(eu),(ep.size!==ed.size||eu&&!ed.has(eu))&&ec(ep);let eh=Q?d.find(e=>e.provider===G?.provider&&e.modelId===G.modelId):Z&&ee&&c.some(e=>e.provider===Z.provider&&e.models.some(e=>e.modelId===ee.modelId))?d.find(e=>e.provider===Z.provider&&e.modelId===ee.modelId):void 0;async function eg(){if(G){await v({title:b("accountRemoveTitle"),description:b("accountRemoveDescription",{name:es})})&&(l(i.filter(e=>e!==G)),P.updateInputState(ei(G),{dirty:!1,invalid:!1}),j(null),z(!1));return}T&&ee&&await v({title:b("modelDeleteTitle"),description:b("modelDeleteDescription",{name:ee.name||ee.modelId||b("modelUnnamed")})})&&P.deleteModel(T.providerIndex,T.modelIndex)}async function ex(e){if(await v({title:b("accountLogoutTitle"),description:b("accountLogoutDescription",{name:a.find(t=>t.provider===e)?.name??e}),confirmLabel:b("accountLogout")}))try{await R.logout(e),await o()}catch(e){y.error(e instanceof Error?e.message:b("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":b("providerList"),className:(0,C.cn)("min-h-0 min-w-0 flex-col bg-sidebar @[48rem]/models:flex @[48rem]/models:border-r",et?"hidden":"flex"),children:[(0,n.jsx)("div",{className:"shrink-0 p-3",children:(0,n.jsx)(eB.p,{value:L,"aria-label":b("modelSearch"),placeholder:b("modelSearch"),onChange:e=>O(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:[ea.map(e=>{let t=s.findIndex(t=>t.provider===e);return(0,n.jsx)(iA,{providerId:e,custom:s[t],account:a.find(t=>t.provider===e),accountModels:i.filter(t=>t.provider===e),query:L,modelKeys:F[t]??[],selectedCustomIndex:Q||T?.providerIndex!==t?null:T.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}),z(!0),$(s=>new Set([...s,ei({provider:e,modelId:t})]))},onCustomSettings:()=>P.openService(t),onAddCustom:()=>{j(null),P.addModel(t)},onAddAccount:()=>{let t;return t=a.find(t=>t.provider===e),void(t?.loggedIn?S(e):R.show(e))},onLogin:()=>R.show(e),onLogout:()=>void ex(e),onGroupRef:e=>{t<0||(e?q.current.set(t,e):q.current.delete(t))},onRowRef:(e,t)=>{t?W.current.set(e,t):W.current.delete(e)}},e)}),ea.length?null:(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:b("providerEmpty")})]}),(0,n.jsxs)("div",{className:"flex shrink-0 gap-2 border-t p-3",children:[(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>P.openService(null),children:[(0,n.jsx)(Y.A,{}),b("accountCustomApi")]}),(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>R.show(),children:b("accountLogin")})]})]}),(0,n.jsx)("section",{"aria-label":b("modelsHeading"),className:(0,C.cn)("min-h-0 min-w-0 flex-col @[48rem]/models:flex",et?"flex":"hidden"),children:Q||ee&&T?(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)(N.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":b("backModelList"),onClick:function(){if(G){z(!1),window.requestAnimationFrame(()=>{let e=W.current.get(ei(G));e?.scrollIntoView({block:"nearest"}),e?.focus({preventScroll:!0})});return}P.backToList(),window.requestAnimationFrame(()=>{if(!T)return;let e=F[T.providerIndex]?.[T.modelIndex];q.current.get(T.providerIndex)?.scrollIntoView({block:"nearest"}),W.current.get(e)?.scrollIntoView({block:"nearest"}),W.current.get(e)?.focus({preventScroll:!0})})},children:(0,n.jsx)(E.A,{})}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",title:J?.name??en,children:J?.name??en}),(0,n.jsx)(iE,{name:en,hasAccount:a.some(e=>e.provider===en)||i.some(e=>e.provider===en),loggedIn:a.find(e=>e.provider===en)?.loggedIn??!1,hasCustom:s.some(e=>e.provider===en),onCustomSettings:()=>P.openService(s.findIndex(e=>e.provider===en)),onLogin:()=>R.show(en),onLogout:()=>void ex(en)})]}),(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:es}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:!eh,title:eh?void 0:b("saveBeforePreset"),onClick:()=>{H(eh?.thinkingLevels[0]??"off"),V(!0)},children:[(0,n.jsx)(a6.A,{}),b("addModelPreset")]}),(0,n.jsxs)(tZ.m_,{children:[(0,n.jsx)(tZ.k$,{render:(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm",className:"text-destructive hover:text-destructive","aria-label":Q?`${b("accountRemove")} ${es}`:b("modelDeleteNamed",{name:es}),onClick:eg,children:(0,n.jsx)(ez.A,{})})}),(0,n.jsx)(tZ.ZI,{children:b(Q?"accountRemove":"modelDelete")})]})]})]}),i.map(e=>{let t=ei(e);if(!eo.has(t))return null;let s=a.find(t=>t.provider===e.provider);return(0,n.jsx)("div",{hidden:!Q||G!==e,children:(0,n.jsx)(iM,{account:s,model:s?.models.find(t=>t.modelId===e.modelId),overrides:e.overrides,onChange:t=>l(i.map(s=>s===e?{...e,overrides:t}:s)),onInputState:e=>P.updateInputState(t,e)})},`${t}:${m}`)}),s.flatMap((t,s)=>t.models.map((r,a)=>{let i=!Q&&T?.providerIndex===s&&T.modelIndex===a,l=F[s]?.[a];return ep.has(l)?(0,n.jsx)("div",{hidden:!i,children:(0,n.jsx)(ia,{biz:e,provider:t,model:r,onChange:e=>P.updateModel(s,a,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)(te.A,{className:"size-6"}),b("selectModelToEdit")]})})]}),(0,n.jsx)(iI,{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()}),er?(0,n.jsx)(iC,{account:er,existingIds:[...i.filter(e=>e.provider===er.provider).map(e=>e.modelId),...s.filter(e=>e.provider===er.provider).flatMap(e=>e.models.map(e=>e.modelId))],onAdd:function(e){if(!er)return;let t=e.filter(e=>!i.some(t=>t.provider===er.provider&&t.modelId===e)&&!s.some(t=>t.provider===er.provider&&t.models.some(t=>t.modelId===e))).map(e=>({provider:er.provider,modelId:e,overrides:{}}));l([...i,...t]),S(null)},onClose:()=>S(null)},er.provider):null,_||null!==B?(0,n.jsx)(id,{provider:_?{provider:"",name:null,baseUrl:null,api:"openai-responses",apiKey:null,authHeader:null,headers:{},models:[]}:s[B],existingIds:s.filter((e,t)=>_||t!==B).map(e=>e.provider),isNew:_,onApply:P.applyService,onDelete:P.deleteService,onClose:P.closeService,onDirtyChange:x}):null,(0,n.jsx)(eX.YV,{open:U,onOpenChange:V,children:(0,n.jsxs)(eX.hA,{children:[(0,n.jsx)(eX.Hl,{className:"border-b px-4 py-4 pr-12",children:(0,n.jsx)(eX.YM,{children:b("addModelPreset")})}),(0,n.jsx)(eX._Y,{children:(0,n.jsx)("div",{className:"p-4",children:(0,n.jsx)(aG,{label:b("thinkingLevel"),children:(0,n.jsx)(aX,{value:K,allowEmpty:!1,ariaLabel:b("presetThinkingNew"),options:(eh?.thinkingLevels??[]).map(e=>({value:e,label:b(i$[e])})),onChange:e=>H(e)})})})}),(0,n.jsxs)(eX.vu,{children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",onClick:()=>V(!1),children:b("cancel",{ns:"common"})}),(0,n.jsx)(N.$,{type:"button",onClick:function(){eh&&(u.some(e=>e.provider===eh.provider&&e.modelId===eh.modelId&&e.thinkingLevel===K)||h([...u,{provider:eh.provider,modelId:eh.modelId,thinkingLevel:K,color:a_(u)}]),V(!1))},disabled:!eh,children:b("presetAdd")})]})]})}),w]})}let iP={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function iT(e,t){return JSON.stringify([e,t])}function iD(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function iL({biz:e,presets:t,onDirtyChange:s}){let{t:a}=(0,f.Bd)("settings"),i=function(e,t){let{t:s}=(0,f.Bd)("settings"),n=(0,eC.G)(),{confirm:a,dialog:i}=nW(),[l,o]=(0,r.useState)([]),[d,c]=(0,r.useState)(""),[u,m]=(0,r.useState)([]),[p,h]=(0,r.useState)(null),[g,x]=(0,r.useState)(!1),[b,v]=(0,r.useState)(!0),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(!1),[C,S]=(0,r.useState)(null),[M,z]=(0,r.useState)(null),[E,A]=(0,r.useState)(null),[$,R]=(0,r.useState)(0),[P,T]=(0,r.useState)(0),D=C===d&&null===E,L=(0,r.useRef)(!1),O=(0,r.useRef)(""),F=(0,r.useCallback)(e=>{L.current=e,t?.(e)},[t]);function B(e){m(e.models),x(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===d||(!L.current||!!await a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}))&&(c(e),!0))}async function q(){if(d&&D&&!w&&!k&&!N&&(!g||p)){I(!0);try{await e.replaceProjectDefault({cwd:d,default:g?p:null}),aC({cwd:d,default:g?p:null,models:u}),F(!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=r7.safeParse((ag(),ad)),r=n.success?n.data.directories:null;return queueMicrotask(()=>{!t&&(z(null),v(!r),r&&(o(r),c(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),c(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}),z(t)}}finally{t||v(!1)}})(),()=>{t=!0}},[e,s,$]),(0,r.useEffect)(()=>{let t=!1,n=O.current!==d;if(O.current=d,n&&F(!1),!d)return queueMicrotask(()=>{t||(m([]),h(null),x(!1),S(null),A(null),y(!1),j(!1))}),()=>{t=!0};let r=(aN(),ak.get(aj(d))??null);return queueMicrotask(()=>{t||(A(null),L.current||(r?(B(r),S(d)):(m([]),h(null),x(!1),S(null))),y(!r&&!L.current),j(!!r||L.current))}),(async()=>{try{let s=await e.getProjectDefault(d);if(t)return;L.current||B(s),S(d)}catch(e){if(!t){let t=e instanceof Error?e.message:s("projectDefaultFailed");console.warn("[Pi Desk][ProjectModelDefault] 读取项目模型配置失败",{cwd:d,message:t}),A(t)}}finally{t||(y(!1),j(!1))}})(),()=>{t=!0}},[e,d,s,F,P]),{directories:l,cwd:d,models:u,selection:p,fixed:g,directoriesLoading:b,projectLoading:w,projectRefreshing:k,saving:N,projectReady:D,directoriesError:M,projectError:E,dialog:i,selectProject:_,changeFixed:function(e){F(!0),x(e)},selectModel:function(e){F(!0),h({provider:e.provider,modelId:e.modelId,thinkingLevel:e.thinkingLevels[0]})},selectThinking:function(e){let t=u.find(e=>e.provider===p?.provider&&e.modelId===p.modelId),s=t?.thinkingLevels.find(t=>t===e);p&&s&&(F(!0),h({...p,thinkingLevel:s}))},applyPreset:function(e){F(!0),h({provider:e.provider,modelId:e.modelId,thinkingLevel:e.thinkingLevel})},retryDirectories:function(){R(e=>e+1)},retryProject:function(){T(e=>e+1)},save:q}}(e,s),[l,o]=(0,r.useState)(""),[d,c]=(0,r.useState)(!1),u=i.models.find(e=>e.provider===i.selection?.provider&&e.modelId===i.selection.modelId),m=t.filter(e=>i.models.some(t=>t.provider===e.provider&&t.modelId===e.modelId&&t.thinkingLevels.includes(e.thinkingLevel))),p=i.directories.filter(e=>e.cwd.toLocaleLowerCase().includes(l.trim().toLocaleLowerCase())),h=i.models.map(e=>({value:iT(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider})),g=i.projectLoading||i.projectRefreshing||i.saving;async function x(e){await i.selectProject(e)&&c(!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":a("projectList"),className:(0,C.cn)("min-h-0 min-w-0 flex-col bg-sidebar @[48rem]/project-default:flex @[48rem]/project-default:border-r",d&&i.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:a("projectList")}),(0,n.jsx)(eB.p,{value:l,"aria-label":a("projectSearch"),placeholder:a("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:i.directoriesLoading&&0===i.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)(b.A,{"aria-hidden":"true",className:"size-4 animate-spin"}),a("projectLoading")]}):i.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:i.directoriesError}),(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",onClick:i.retryDirectories,children:a("retry",{ns:"common"})})]}):0===p.length?(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:a("projectEmpty")}):(0,n.jsx)("div",{className:"space-y-1",children:p.map(e=>{let t=e.cwd===i.cwd;return(0,n.jsx)(N.$,{type:"button",variant:"ghost","aria-current":t?"true":void 0,disabled:i.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:iD(e.cwd)}),t?(0,n.jsx)(ed.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:a("projectSessionCount",{count:e.sessionCount})})]})},e.cwd)})})})]}),(0,n.jsx)("section",{"aria-label":a("projectDefaultSource"),className:(0,C.cn)("min-h-0 min-w-0 flex-col @[48rem]/project-default:flex",d&&i.cwd?"flex":"hidden"),children:i.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)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(!1),children:[(0,n.jsx)(E.A,{"aria-hidden":"true"}),a("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.jsx)("h3",{className:"break-all text-lg font-semibold",children:iD(i.cwd)}),(0,n.jsx)("p",{className:"break-all text-sm text-muted-foreground",children:i.cwd}),i.projectLoading&&!i.projectReady?(0,n.jsxs)("p",{role:"status",className:"flex items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)(b.A,{"aria-hidden":"true",className:"size-3.5 animate-spin"}),a("projectLoading")]}):null]}),i.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:i.projectError}),(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",onClick:i.retryProject,children:a("retry",{ns:"common"})})]}):i.projectReady?(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:a("projectDefaultSource")}),(0,n.jsx)(n6,{label:a("projectDefaultSource"),value:i.fixed?"fixed":"global",layout:"segmented",disabled:g,options:[{value:"global",label:a("projectFollowGlobal")},{value:"fixed",label:a("projectFixed")}],onChange:e=>i.changeFixed("fixed"===e)})]}),i.fixed?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)(aG,{label:a("projectDefaultModel"),children:(0,n.jsx)(nG.b,{value:i.selection?iT(i.selection.provider,i.selection.modelId):"",options:h,ariaLabel:a("projectDefaultModel"),searchPlaceholder:a("modelSearch"),disabled:g||0===i.models.length,onChange:function(e){let t=i.models.find(t=>iT(t.provider,t.modelId)===e);t&&i.selectModel(t)}})}),(0,n.jsx)(aG,{label:a("thinkingLevel"),children:(0,n.jsx)(aX,{value:i.selection?.thinkingLevel??"",options:(u?.thinkingLevels??[]).map(e=>({value:e,label:a(iP[e])})),ariaLabel:a("projectDefaultThinking"),allowEmpty:!1,onChange:i.selectThinking})}),m.length>0?(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:a("fromPreset")}),(0,n.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:m.map((e,t)=>{let s=i.models.find(t=>t.provider===e.provider&&t.modelId===e.modelId);return(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"xs",className:"h-auto min-h-7 max-w-full whitespace-normal text-left",onClick:()=>i.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"," ",a(iP[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)(N.$,{type:"button",onClick:i.save,disabled:!i.projectReady||g||i.fixed&&!i.selection,children:[i.saving?(0,n.jsx)(b.A,{"aria-hidden":"true",className:"animate-spin"}):(0,n.jsx)(eS.A,{"aria-hidden":"true"}),i.saving?a("savingModels"):a("saveProjectDefault")]})})]}):(0,n.jsxs)("div",{className:"flex items-center gap-2 p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(e8.A,{"aria-hidden":"true",className:"size-6 shrink-0"}),a("selectProjectToConfigure")]})})]}),i.dialog]})}let iO=[{value:"providers",label:"modelProviders"},{value:"presets",label:"modelPresets"},{value:"project-default",label:"projectDefault"}];function iF({loading:e,error:t,onRetry:s}){let{t:r}=(0,f.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)(b.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)(N.$,{type:"button",variant:"outline",size:"sm",onClick:s,children:r("retry",{ns:"common"})})]})})}function iB({onBeforeLeaveChange:e,connectionReady:t=!1,initialTab:s}){let{t:a}=(0,f.Bd)("settings"),{locale:i,timeZone:l}=(0,tp.i)(),[o,d]=(0,r.useState)(!1),{biz:c,tab:u,settings:m,providers:p,presets:h,accountModels:g,changeAccountModels:x,refreshAccounts:v,resetVersion:w,formDirty:y,formInvalid:k,serviceDirty:j,nativeOpen:I,nativeText:S,nativeError:M,nativeDirty:z,setNativeText:E,openNative:A,closeNative:$,saveNative:R,revertConfig:P,setInputState:T,setServiceDirty:D,loading:L,saving:O,refreshing:F,catalogUpdatedAt:B,loadError:_,dialog:q,setProjectDefaultDirty:W,changeProviders:U,changePresets:Y,selectTab:K,retry:H,refreshCatalog:G,saveConfig:J}=function(e,t){let{t:s}=(0,f.Bd)("settings"),{clientId:n}=(0,eR.gM)(),a=(0,eC.G)(),{confirm:i,dialog:l}=nW(),o=(0,r.useMemo)(()=>{let e;return e=null,{parseNativeConfig(e){let t=JSON.parse(e);return rL.parse(t)},getSettings:()=>(e||(e=eF(n,"/api/model-settings/get",{},rG).finally(()=>{e=null})),e),async replaceSettings(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("模型配置不完整或格式不正确,请检查必填字段和数值。")}await eF(n,"/api/model-settings/replace",t.data,rQ)},listCatalog:e=>eF(n,"/api/model-catalog/list",rZ.parse(e),r5),async listDirectories(){let e=await eF(n,"/api/pi/directories/list",{forceRefresh:!1},r7);return af(e),e},async getProjectDefault(e){let t=await eF(n,"/api/project-model-default/get",{cwd:e},r3);return aC(t),t},async replaceProjectDefault(e){await eF(n,"/api/project-model-default/replace",r4.parse(e),r6)}}},[n]),[d,c]=(0,r.useState)(()=>t??aA(aE,aM,"providers"));(0,r.useEffect)(()=>{a$(aE,d)},[d]);let[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)([]),[g,x]=(0,r.useState)([]),[b,v]=(0,r.useState)([]),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(!1),[C,S]=(0,r.useState)(!1),[M,z]=(0,r.useState)(!0),[E,A]=(0,r.useState)(!1),[$,R]=(0,r.useState)(!1),[P,T]=(0,r.useState)(null),[D,L]=(0,r.useState)(null),[O,F]=(0,r.useState)(0),[B,_]=(0,r.useState)(0),[q,W]=(0,r.useState)({dirty:!1,invalid:!1}),[U,Y]=(0,r.useState)(!1),[V,K]=(0,r.useState)(!1),[H,G]=(0,r.useState)(""),[J,X]=(0,r.useState)(null),Q=(0,r.useRef)(!1),Z=u?JSON.stringify(u.nativeConfig,null,2):"",ee=V&&H!==Z,et=k||N||w||q.dirty,es=et||C||U||ee;(0,r.useEffect)(()=>(e(es?()=>!E&&i({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}):null),()=>e(null)),[e,es,E,i,s]),(0,r.useEffect)(()=>{if(!es)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[es]);let en=(0,r.useCallback)(e=>{m(e),h(structuredClone(e.providers)),x(structuredClone(e.presets)),v(structuredClone(e.accountModels)),y(!1),j(!1),I(!1),W({dirty:!1,invalid:!1}),_(e=>e+1)},[]);async function er(){R(!0);try{let e=await o.listCatalog({query:"",refresh:!0,page:{index:1,size:1}});T(e.updatedAt),await ei(),a.success("cached"===e.refreshResult?s("catalogCached"):"partial"===e.refreshResult?s("catalogPartial"):"unchanged"===e.refreshResult?s("catalogUnchanged"):s("catalogUpdated"))}catch(e){a.error(e instanceof Error?e.message:s("catalogRefreshFailed"))}finally{R(!1)}}async function ea(){if(!Q.current&&!q.invalid&&!U&&!V){if(!u||!et)return void a.success(s("modelsNoChanges"));Q.current=!0,A(!0);try{let e=new Set([...p.flatMap(e=>e.models.map(t=>`${e.provider}\u0000${t.modelId}`)),...b.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;if(r>0&&!await i({title:s("removeInvalidPresetsTitle"),description:s("removeInvalidPresets",{count:r}),confirmLabel:s("removeAndSave")}))return;let l={...k||q.dirty?{providers:p}:{},...w?{accountModels:b}:{},...N||r>0?{presets:n}:{}};await o.replaceSettings(l),en(await o.getSettings()),j(!1),I(!1),a.success(s("modelSaved"))}catch(e){a.error(e instanceof Error?e.message:s("modelSaveFailed"))}finally{Q.current=!1,A(!1)}}}async function ei(){let e=await o.getSettings();return m(t=>t?{...t,accounts:e.accounts,models:e.models,nativeConfig:e.nativeConfig}:e),e}async function el(){!u||Q.current||U||await i({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")})&&en(u)}async function eo(){Q.current||(!ee||await i({title:s("discardNativeTitle"),description:s("discardNativeDescription"),confirmLabel:s("discardModelConfirm")}))&&K(!1)}async function ed(){if(!Q.current&&V&&ee){Q.current=!0,A(!0),X(null);try{let e=o.parseNativeConfig(H);await o.replaceSettings({nativeConfig:e}),en(await o.getSettings()),K(!1),a.success(s("modelSaved"))}catch(t){let e=t instanceof Error?t.message:s("modelSaveFailed");console.warn("[Pi Desk][ModelSettings] 保存 Pi 配置失败",{message:e}),X(e)}finally{Q.current=!1,A(!1)}}}return(0,r.useEffect)(()=>{let e=!1;return queueMicrotask(()=>{e||(z(!0),L(null))}),o.getSettings().then(t=>{e||en(t)}).catch(t=>{if(e)return;let n=t instanceof Error?t.message:s("modelsLoadFailed");console.warn("[Pi Desk][ModelSettings] 读取模型配置失败",{message:n}),L(n)}).finally(()=>{e||z(!1)}),()=>{e=!0}},[o,s,O,en]),{biz:o,tab:d,settings:u,providers:p,presets:g,accountModels:b,changeAccountModels:e=>{v(e),y(JSON.stringify(e)!==JSON.stringify(u?.accountModels))},refreshAccounts:ei,providersDirty:k,presetsDirty:N,loading:M,saving:E,refreshing:$,catalogUpdatedAt:P,loadError:D,resetVersion:B,formDirty:et,formInvalid:q.invalid,serviceDirty:U,nativeOpen:V,nativeText:H,nativeError:J,nativeDirty:ee,setNativeText:G,openNative:function(){if(u&&!Q.current){if(et||U||C)return void a.error(s("nativeProtectDraft"));G(Z),X(null),K(!0)}},closeNative:eo,saveNative:ed,revertConfig:el,setInputState:W,setServiceDirty:Y,dialog:l,setProjectDefaultDirty:S,changeProviders:e=>{h(e),j(JSON.stringify(e)!==JSON.stringify(u?.providers))},changePresets:e=>{x(e),I(JSON.stringify(e)!==JSON.stringify(u?.presets))},selectTab:e=>{if(e!==d&&!Q.current){if("project-default"===d&&C)return void i({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}).then(t=>{t&&(S(!1),c(e))});c(e)}},retry:()=>F(e=>e+1),refreshCatalog:er,saveConfig:ea}}(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)(n6,{label:a("models"),layout:"segmented",value:u,options:iO.map(e=>({...e,label:a(e.label)})),onChange:K}),(0,n.jsxs)("div",{className:"hidden gap-2 @[40rem]/model-settings:flex",children:[(0,n.jsxs)(N.$,{type:"button",variant:"ghost",size:"sm",disabled:!m||O,onClick:A,children:[(0,n.jsx)(rM.A,{}),a("nativeConfig")]}),(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",title:B?a("catalogUpdatedAt",{time:new Date(B).toLocaleString("en"===i?"en-US":"zh-CN",{timeZone:l,timeZoneName:"shortOffset",hourCycle:"h23"})}):a("catalogUnavailable"),onClick:G,disabled:F,children:[(0,n.jsx)(eE.A,{className:(0,C.cn)(F&&"animate-spin")}),F?a("refreshingCatalog"):a("refreshCatalog")]})]}),(0,n.jsxs)(th.AM,{open:o,onOpenChange:d,children:[(0,n.jsx)(th.Wv,{render:(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":a("modelMoreActions"),className:"shrink-0 @[40rem]/model-settings:hidden",children:(0,n.jsx)(V.A,{})})}),(0,n.jsxs)(th.hl,{align:"end",positionerClassName:"z-[120]",className:"w-48 gap-1 p-1",children:[(0,n.jsxs)(N.$,{type:"button",variant:"ghost",className:"justify-start",disabled:!m||O,onClick:()=>{d(!1),A()},children:[(0,n.jsx)(rM.A,{}),a("nativeConfig")]}),(0,n.jsxs)(N.$,{type:"button",variant:"ghost",className:"justify-start",disabled:F,onClick:()=>{d(!1),G()},children:[(0,n.jsx)(eE.A,{}),a("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)(iL,{biz:c,presets:m?.presets??[],onDirtyChange:W}):m?null:(0,n.jsx)(iF,{loading:L,error:_,onRetry:H}),m?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("fieldset",{disabled:O,className:(0,C.cn)("h-full min-h-0 min-w-0","providers"!==u&&"hidden"),children:(0,n.jsx)(iR,{biz:c,connectionReady:t,providers:p,accounts:m.accounts,accountModels:g,onAccountModelsChange:x,onRefreshAccounts:v,savedProviders:m.providers,savedModels:m.models,presets:h,resetVersion:w,onChange:U,onPresetsChange:Y,onInputState:T,onServiceDirtyChange:D})}),(0,n.jsx)("fieldset",{disabled:O,className:(0,C.cn)("min-w-0","presets"!==u&&"hidden"),children:(0,n.jsx)(a4,{presets:h,models:m.models,onChange:Y})})]}):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?a("fixModelInputs"):y?a("modelDraftPending"):a("modelDraftClean")}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",disabled:O||!y||j,onClick:P,children:a("revertModels")}),(0,n.jsxs)(N.$,{type:"button",size:"sm",onClick:J,disabled:O||!y||k||j,children:[O?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(eS.A,{}),O?a("savingModels"):a("saveModels")]})]})]}):null,(0,n.jsx)(aP,{open:I,text:S,error:M,saving:O,dirty:z,onChange:E,onClose:$,onSave:R}),q]})}function i_({render:e,input:t}){return e(t)}let iq=[{id:"appearance",label:"appearance",icon:sO.A},{id:"region",label:"region",icon:sF.A},{id:"habits",label:"habits",icon:sB.A},{id:"models",label:"models",icon:e7.A},{id:"mcp-settings",label:"mcpSettings",icon:e0.A},{id:"capability-modes",label:"capabilityModes",icon:eq.A},{id:"skills",label:"skills",icon:s_.A},{id:"plugins",label:"plugins",icon:e0.A},{id:"auth",label:"loginProtection",icon:eA.A},{id:"about",label:"about",icon:sq.A}];function iW(e,t){return`plugin:${e}:${t}`}function iU(){let{t:e}=(0,f.Bd)("settings"),t=(0,tp.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)(sY.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",sW]})]}),(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)}(sU,"en"===t.locale?"en-US":"zh-CN",t.timeZone,e("common:unavailable"))})]})]})]})}function iY({open:e,connectionReady:t=!1,initialModelTab:s,workSessions:a,focusedCwd:i,pluginAttention:l,renderPluginManagement:o,renderMcpSettings:d,renderCapabilityModesSettings:c,renderPluginSettingsPage:u,onOpenChange:m,onBeforeReload:p}){let{t:h}=(0,f.Bd)("settings"),g=(0,eI.So)(),x=(0,r.useMemo)(()=>{let e=new Map;for(let{cwd:t,projectName:s}of a){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()]},[a]),b=(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":aA(az,aS,"appearance"));(0,r.useEffect)(()=>{e&&a$(az,v)},[v,e]);let[y,k]=(0,r.useState)(!1),[j,I]=(0,r.useState)(!1),S=(0,r.useRef)(null),M=(0,r.useRef)(!1),z=b.find(e=>iW(e.pluginName,e.descriptor.contributionName)===v),E=v.startsWith("plugin:")&&!z?"appearance":v,A=iq.find(e=>e.id===E),$=A?.icon,R=(0,r.useRef)(null);sZ(R,e&&!z?E:null);let P=(0,r.useCallback)(async e=>{if(!M.current){M.current=!0,I(!0);try{let t=S.current;if(t&&!await t())return;S.current=null,e()}finally{M.current=!1,I(!1)}}},[]),T=(0,r.useCallback)(()=>{P(()=>m(!1))},[m,P]),D=(0,r.useCallback)(e=>{S.current=e},[]),L=e=>{e!==E&&P(()=>w(e))};return(0,n.jsx)(eX.YV,{open:e,onOpenChange:(e,t)=>{e?m(!0):"focus-out"!==t.reason&&T()},children:(0,n.jsxs)(eX.hA,{className:"h-[min(48rem,calc(100dvh-2rem))] max-w-6xl max-sm:h-dvh max-sm:max-h-dvh 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)(eX.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsx)(eX.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)(eP.l6,{value:E,disabled:j,onValueChange:e=>{if("string"!=typeof e)return;let t=iq.find(t=>t.id===e);if(t)return void L(t.id);let s=b.find(t=>iW(t.pluginName,t.descriptor.contributionName)===e);s&&L(iW(s.pluginName,s.descriptor.contributionName))},children:[(0,n.jsx)(eP.bq,{"aria-label":h("category"),className:"w-full",children:(0,n.jsx)(eP.yv,{children:z?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(tr,{icon:z.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:z.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)(eP.gC,{positionerClassName:"z-[120]",align:"start",children:[iq.map(e=>{let t=e.icon;return(0,n.jsxs)(eP.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)}),b.length>0?(0,n.jsxs)(eP.s3,{children:[(0,n.jsx)(eP.TR,{children:h("pluginSettings")}),b.map(e=>{let t=iW(e.pluginName,e.descriptor.contributionName);return(0,n.jsxs)(eP.eb,{value:t,children:[(0,n.jsx)(tr,{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:iq.map(e=>{let t=e.icon,s=e.id===E;return(0,n.jsxs)(N.$,{variant:"ghost",disabled:j,"aria-current":s?"page":void 0,"aria-label":`${h("category")}:${h(e.label)}`,onClick:()=>L(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)})}),b.length>0?(0,n.jsxs)(tl.Nt,{open:y||!!z,onOpenChange:k,className:"mt-2 border-t pt-2",children:[(0,n.jsxs)(tl.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:b.length}),(0,n.jsx)(ti.A,{className:(0,C.cn)("size-3.5 transition-transform",y||z?"rotate-180":null)})]}),(0,n.jsx)(tl.Ke,{children:(0,n.jsx)("div",{className:"mt-1 grid grid-cols-1 gap-1",children:b.map(e=>{let t=iW(e.pluginName,e.descriptor.contributionName),s=t===E;return(0,n.jsxs)(N.$,{variant:"ghost",disabled:j,"aria-current":s?"page":void 0,onClick:()=>L(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)(tr,{icon:e.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:e.descriptor.label})]},t)})})})]}):null]}),z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:(0,n.jsx)(i_,{render:u,input:{pluginName:z.pluginName,descriptor:z.descriptor,onClose:T,onBeforeLeaveChange:D}})}):"skills"===E?(0,n.jsx)("div",{ref:R,className:"min-h-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(nF,{projects:x,focusedCwd:i,onBeforeLeaveChange:D})}):"mcp-settings"===E?(0,n.jsx)("div",{ref:R,className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(i_,{render:d,input:{onBeforeLeaveChange:D}})}):"capability-modes"===E?(0,n.jsx)("div",{ref:R,className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(i_,{render:c,input:{onBeforeLeaveChange:D}})}):"models"===E?(0,n.jsx)("div",{ref:R,className:"min-h-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(iB,{connectionReady:t,initialTab:s,onBeforeLeaveChange:D})}):"plugins"===E?(0,n.jsx)("div",{ref:R,className:"min-h-0 flex-1 overflow-hidden",children:o()}):(0,n.jsx)(eX._Y,{className:"min-w-0 max-h-none",children:(0,n.jsx)("div",{ref:R,className:"p-4 sm:p-6",children:"appearance"===E?(0,n.jsx)(rd,{}):"habits"===E?(0,n.jsx)(rS,{}):"auth"===E?e&&(0,n.jsx)(nH,{}):"region"===E?(0,n.jsx)(n1,{canLeave:p}):(0,n.jsx)(iU,{})})})]})]})})}let iV=a.Ik({cwd:a.Yj().trim().min(1).nullable()}).strict(),iK=a.g1(a.Yj(),a.Pq()),iH=a.g1(a.Yj().min(1).max(128),iK),iG=a.Ik({local:iH,inherited:iH,projectTrusted:a.zM().nullable(),diagnostics:a.YO(a.Ik({name:a.Yj().nullable(),message:a.Yj()}).strict())}).strict();iV.extend({servers:iH}).strict(),iV.extend({name:a.Yj().min(1).max(128)}).strict();let iJ=a.Ik({output:a.Yj()}).strict(),iX=a.Ik({}).strict(),iQ=["command","args","url","type","description","enabled","exposure"];function iZ(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&Object.values(e).every(e=>"string"==typeof e)}function i0(e){return iZ(e)?Object.entries(e).map(([e,t])=>({key:e,value:t})):[]}function i1(e){return!("command"in e)&&!("url"in e)&&!("type"in e)}function i2(e,t){let s=t??{};return{originalName:e,name:e??"",transport:t&&i1(t)?"inherit":"url"in s?"http":"stdio",command:"string"==typeof s.command?s.command:"",args:Array.isArray(s.args)?s.args.join("\n"):"",env:i0(s.env),headers:i0(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])=>!iQ.includes(e)&&!(["env","headers"].includes(e)&&iZ(t)))),null,2)}}class i5 extends Error{constructor(e,t){super(t),this.field=e}}function i3(e){return"string"==typeof e.url?e.url:"string"==typeof e.command?e.command:"继承全局连接"}let i4={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 i6(){let{locale:e}=(0,tp.i)();return t=>"en"===e?i4[t]??t:t}function i8(e){return e instanceof Error?e.message:"请求失败,请重试。"}function i7({id:e,label:t,value:s,options:r,disabled:a,onChange:i}){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)(eP.l6,{value:s,disabled:a,onValueChange:e=>{"string"==typeof e&&i(e)},children:[(0,n.jsx)(eP.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)(eP.yv,{children:r.find(e=>e.value===s)?.label??s})}),(0,n.jsx)(eP.gC,{positionerClassName:"z-[125]",align:"start",children:r.map(e=>(0,n.jsx)(eP.eb,{value:e.value,className:"[&_span]:whitespace-normal [&_span]:break-all",children:e.label},e.value))})]})]})}function i9({trigger:e,children:t}){return(0,n.jsxs)(ec,{children:[(0,n.jsx)(em,{render:e}),(0,n.jsx)(eu,{children:(0,n.jsx)(J.y,{sideOffset:4,align:"end",className:"z-[125] outline-none",children:(0,n.jsx)(X._,{className:el.hD,children:t})})})]})}function le({message:e,id:t}){let s=i6();return e?(0,n.jsx)("p",{id:t,role:"alert",className:"break-words text-sm text-destructive",children:s(e)}):null}function lt({rows:e,selectedName:t,pending:s,onSelect:r}){let a=i6();return(0,n.jsx)("ul",{"aria-label":a("服务列表"),className:"divide-y",children:e.map(e=>{let i="string"==typeof e.config.url?tt.A:v.A;return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button","aria-label":`${a("配置服务")} \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 disabled:opacity-50",t===e.name&&"bg-accent"),children:[(0,n.jsx)(i,{"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:a(!1===e.config.enabled?"已停用":"已启用")})]}),(0,n.jsxs)("span",{className:"block text-xs text-muted-foreground",children:[a(e.source)," \xb7"," ",a("string"==typeof e.config.url?"HTTP 地址":"本地程序")]}),(0,n.jsx)("span",{className:"block truncate font-mono text-xs text-muted-foreground",children:i3(e.config)})]}),(0,n.jsx)(eo.A,{"aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"})]})},e.name)})})}function ls({id:e,label:t,rows:s,disabled:r,error:a,onChange:i}){let l=i6();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,d)=>(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_2rem] gap-2",children:[(0,n.jsx)(eB.p,{"aria-label":`${t} \xb7 ${l("名称")} ${d+1}`,"aria-invalid":!!a,"aria-describedby":a?`${e}-error`:void 0,value:o.key,spellCheck:!1,className:"min-w-0 font-mono",onChange:e=>i(s.map((t,s)=>s===d?{...t,key:e.target.value}:t))}),(0,n.jsx)(eB.p,{"aria-label":`${t} \xb7 ${l("值")} ${d+1}`,value:o.value,spellCheck:!1,autoComplete:"off",className:"min-w-0 font-mono",onChange:e=>i(s.map((t,s)=>s===d?{...t,value:e.target.value}:t))}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon","aria-label":`${l("删除行")} \xb7 ${t} ${d+1}`,disabled:r,onClick:()=>i(s.filter((e,t)=>t!==d)),children:(0,n.jsx)(ez.A,{"aria-hidden":"true"})})]},d)),(0,n.jsx)(le,{id:`${e}-error`,message:a}),(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>i([...s,{key:"",value:""}]),children:[(0,n.jsx)(Y.A,{"aria-hidden":"true"}),l("添加"),t]})]})}var ln=s(94213);function lr({check:e,onRetry:t,onDismiss:s}){let r=i6(),a=e.loading?b.A:e.error?W.A:ln.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)(a,{"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)(le,{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)(N.$,{type:"button",variant:"outline",size:"sm",onClick:t,children:r("重试")}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:s,children:r("关闭结果")})]})]})]})}function la({editor:e,scopeLabel:t,project:s,projectTrusted:a,check:i,local:l,inherited:o,pending:d,error:c,onDraft:u,onJson:m,onPreview:p,onOverwrite:h,onSave:g,onCancel:x,onRemove:f,onDismissCheck:b}){let v=i6(),w=(0,r.useId)(),y=(0,r.useRef)(null),[k,j]=(0,r.useState)(!1);(0,r.useEffect)(()=>{c&&y.current?.querySelector('[aria-invalid="true"]')?.focus()},[c]);let I=e=>`${w}-${e}`,C="manual"===e.kind?e.draft:null,S="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,A=!!(z&&Object.hasOwn(l,z)),$=!!(s&&z&&Object.hasOwn(o,z)),R=(e,t,s)=>(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:I(e),className:"text-sm font-medium",children:v(t)}),s,(0,n.jsx)(le,{id:I(`${e}-error`),message:c?.field===e?c.message:null})]}),P=(e,t)=>R(e,t,(0,n.jsx)(eB.p,{id:I(e),value:C?.[e]??"",disabled:d||"name"===e&&!!C?.originalName,"aria-invalid":c?.field===e,"aria-describedby":c?.field===e?I(`${e}-error`):void 0,onChange:t=>u({[e]:t.target.value})}));return(0,n.jsxs)("form",{ref:y,"aria-label":v(M),className:"flex min-h-0 min-w-0 flex-1 flex-col",onSubmit:e=>{e.preventDefault(),g()},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)(N.$,{type:"button",variant:"ghost",size:"icon","aria-label":v("返回服务列表"),disabled:d,onClick:x,children:(0,n.jsx)(E.A,{"aria-hidden":"true"})}),(0,n.jsx)("h3",{className:"min-w-0 flex-1 text-sm font-semibold",children:v(M)}),A&&z&&(0,n.jsx)(i9,{trigger:(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon","aria-label":v("服务操作"),disabled:d,children:(0,n.jsx)(V.A,{"aria-hidden":"true"})}),children:(0,n.jsx)(ex,{variant:$?"default":"destructive",onClick:()=>f(z),children:v($?"恢复全局配置":"删除服务")})})]}),s&&(0,n.jsxs)("p",{className:"break-all text-xs text-muted-foreground",children:[v("保存范围"),":",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:[i&&(0,n.jsx)(lr,{check:i,onRetry:()=>g(!0),onDismiss:b}),P("name","服务名称"),"inherit"===C.transport?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:v("继承全局连接")}),z&&o[z]&&(0,n.jsx)("p",{className:"break-all font-mono text-sm text-muted-foreground",children:i3(o[z])}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:v("连接参数沿用全局,仅保存本项目的启用和工具设置。")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(i7,{id:I("transport"),label:v("连接方式"),value:C.transport,disabled:d,options:[{value:"stdio",label:v("本地程序")},{value:"http",label:v("HTTP 地址")}],onChange:e=>u({transport:"http"===e?"http":"stdio"})}),"stdio"===C.transport?(0,n.jsxs)(n.Fragment,{children:[P("command","启动程序"),R("args","参数(每行一个)",(0,n.jsx)(aR.T,{id:I("args"),className:"min-h-24 font-mono",value:C.args,disabled:d,onChange:e=>u({args:e.target.value})}))]}):P("url","HTTP 地址"),("stdio"===C.transport||c?.field==="env")&&(0,n.jsx)(ls,{id:I("env"),label:v("环境变量"),rows:C.env,disabled:d,error:c?.field==="env"?c.message:null,onChange:e=>u({env:e})}),("http"===C.transport||c?.field==="headers")&&(0,n.jsx)(ls,{id:I("headers"),label:v("请求头"),rows:C.headers,disabled:d,error:c?.field==="headers"?c.message:null,onChange:e=>u({headers:e})}),s&&(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:v("本项目的完整定义会整体替换同名全局配置。")})]}),(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:d,onChange:e=>u({enabled:e.target.checked}),className:"size-4 shrink-0 accent-primary"}),v("已启用")]}),(0,n.jsxs)(tl.Nt,{open:k||c?.field==="advanced",onOpenChange:j,children:[(0,n.jsxs)(tl.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)(ti.A,{"aria-hidden":"true",className:"size-4 transition-transform group-data-panel-open:rotate-180"}),v("高级设置")]}),(0,n.jsxs)(tl.Ke,{className:"space-y-3 pt-3",children:["inherit"!==C.transport&&P("description","服务说明(可选)"),(0,n.jsx)(i7,{id:I("exposure"),label:v("工具使用方式"),value:C.exposure,disabled:d,options:[{value:"",label:v("沿用默认")},{value:"codemode",label:v("通过脚本调用")},{value:"deferred",label:v("按需发现")},{value:"direct",label:v("直接使用")},{value:"hidden",label:v("隐藏")},...["","codemode","deferred","direct","hidden"].includes(C.exposure)?[]:[{value:C.exposure,label:C.exposure}]],onChange:e=>u({exposure:e})}),(0,n.jsx)("label",{htmlFor:I("advanced"),className:"block text-sm font-medium",children:v("其他配置(JSON)")}),(0,n.jsx)(aR.T,{id:I("advanced"),onFocus:()=>j(!0),value:C.advanced,disabled:d,className:"min-h-40 font-mono",spellCheck:!1,"aria-invalid":c?.field==="advanced","aria-describedby":c?.field==="advanced"?I("advanced-error"):void 0,onChange:e=>u({advanced:e.target.value})}),(0,n.jsx)(le,{id:I("advanced-error"),message:c?.field==="advanced"?c.message:null})]})]})]}):"json"===e.kind?(0,n.jsxs)("div",{className:"space-y-3",children:[R("json","配置 JSON",(0,n.jsx)(aR.T,{id:I("json"),value:e.text,disabled:d,"aria-invalid":c?.field==="json","aria-describedby":c?.field==="json"?I("json-error"):void 0,spellCheck:!1,className:"min-h-48 font-mono",placeholder:'{ "mcpServers": { "docs": { "url": "https://example.com/mcp" } } }',onChange:e=>m(e.target.value)})),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:v("仅接受包含 mcpServers 的标准 JSON。")}),(0,n.jsx)(N.$,{type:"button",variant:"outline",onClick:p,disabled:d||!e.text.trim(),children:v("解析预览")}),e.preview&&(0,n.jsxs)("section",{"aria-label":v("待保存服务"),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:v(i1(t)?"继承全局连接":"url"in t?"HTTP 地址":"本地程序")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:v(Object.hasOwn(l,e)?"替换已有配置":Object.hasOwn(o,e)?"覆盖全局(仅本项目)":"新增")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:v(!1===t.enabled?"已停用":"已启用")})]},e))}),S.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:d,className:"mt-1 size-4 shrink-0 accent-primary",onChange:e=>h(e.target.checked)}),(0,n.jsx)("span",{children:v("允许替换以上同名已有配置")})]})]})]}):null,(0,n.jsx)("div",{className:"mt-3",children:(0,n.jsx)(le,{message:c?.field==="save"?c.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)(N.$,{type:"button",variant:"outline",disabled:d,onClick:x,children:v("取消")}),C&&(0,n.jsx)(N.$,{type:"button",variant:"outline",disabled:d||!C.enabled||!1===a,onClick:()=>g(!0),children:v("保存并测试")}),(0,n.jsx)(N.$,{type:"submit",disabled:d||"json"===e.kind&&(!e.preview||S.length>0&&!e.overwrite),children:v(i?.loading?"正在测试连接…":d?"保存中…":"保存")})]})]})}function li({pending:e,onAdd:t,onImport:s}){let r=i6();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)(v.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)(e0.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)(tt.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)(N.$,{disabled:e,onClick:t,children:[(0,n.jsx)(Y.A,{"aria-hidden":"true"}),r("添加服务")]}),(0,n.jsx)(N.$,{variant:"outline",disabled:e,onClick:s,children:r("导入 JSON")})]})]})})})}function ll({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{clientId:i}=(0,eR.gM)(),l=function(e,t){let s=i6(),n=(0,r.useMemo)(()=>({getMcp:(t,s)=>eF(e,"/api/mcp-settings/get",{cwd:t},iG,{signal:s}),replaceMcp:(t,s)=>eF(e,"/api/mcp-settings/replace",t,iX,{signal:s}),deleteMcp:(t,s,n)=>eF(e,"/api/mcp-settings/del",{cwd:t,name:s},iX,{signal:n}),checkMcp:(t,s,n)=>eF(e,"/api/mcp-check/get",{cwd:t,name:s},iJ,{signal:n})}),[e]),{confirm:i,dialog:l}=nW(),[o,d]=(0,r.useState)(null),[c,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!0),[x,f]=(0,r.useState)(!1),[b,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(null),[k,j]=(0,r.useState)(null),[N,I]=(0,r.useState)(null),C=(0,r.useRef)(null),S=(0,r.useRef)(0),M=(0,r.useRef)(0),z=(0,r.useRef)(i),E=(0,r.useRef)(s);(0,r.useEffect)(()=>{z.current=i,E.current=s},[i,s]);let A=m?.kind==="manual"&&JSON.stringify(m.draft)!==m.initial||m?.kind==="json"&&!!m.text,$=(0,r.useCallback)(()=>{p(null),y(null)},[]),R=(0,r.useCallback)(async()=>{if(x||N?.loading)return!1;if(!A)return!0;let e=await z.current({title:E.current("放弃未保存的修改?"),description:E.current("当前修改尚未保存。放弃后将保留已保存的配置。"),confirmLabel:E.current("放弃修改")});return e&&$(),e},[A,$,x,N?.loading]);(0,r.useEffect)(()=>(t(R),()=>t(null)),[R,t]);let P=(0,r.useCallback)(async(e,t)=>{g(!0),v(null);try{let s=await n.getMcp(o,e);e.aborted||S.current!==t||u(s)}catch(s){e.aborted||S.current!==t||v(i8(s))}finally{e.aborted||S.current!==t||g(!1)}},[n,o]);(0,r.useEffect)(()=>{let e=new AbortController;C.current=e;let t=++S.current;return P(e.signal,t),()=>e.abort()},[P]);let T=async e=>{await R()&&($(),j(null),e())},D=(e,t)=>{let s=i2(e,t);y(null),j(null),I(null),p({kind:"manual",draft:s,initial:JSON.stringify(s)})},L=async(e,t)=>{let s=C.current?.signal;if(!s||x||N?.loading)return!1;let n=S.current;f(!0),y(null),j(null);try{if(await e(s),s.aborted||S.current!==n)return!1;return t(),I(null),j("已保存。新会话使用新配置;已有会话需重载 Pi 配置。"),u(null),await P(s,n),!s.aborted&&S.current===n}catch(e){return s.aborted||S.current!==n||y({field:e instanceof i5?e.field:"save",message:i8(e)}),!1}finally{s.aborted||S.current!==n||f(!1)}},O=async(e=!1)=>{if(!(!m||!c||x||N?.loading)&&(!e||"manual"===m.kind&&m.draft.enabled&&!1!==c.projectTrusted))try{let t="manual"===m.kind?function(e,t){let s,n=e.name.trim();if(!n||n.length>128)throw new i5("name","服务名称需要 1–128 个字符。");try{s=iK.parse(JSON.parse(e.advanced))}catch{throw new i5("advanced","高级配置需要是 JSON 对象。")}if(iQ.some(e=>e in s))throw new i5("advanced","连接、说明、启用和曝光字段请在上方表单中填写。");if("inherit"===e.transport&&Object.keys(s).some(e=>"toolExposure"!==e))throw new i5("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||iZ(t?.[n])){if(n in s)throw new i5("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 i5(t,"请填写名称,或删除空白行。");let e=r.key.trim(),a="headers"===t?e.toLowerCase():e;if(n.has(a))throw new i5(t,"名称不能重复。");n.add(a),s.push([e,r.value])}return Object.fromEntries(s)}(e[n],n)}}if("stdio"===e.transport){if(!e.command.trim())throw new i5("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 i5("url","请输入有效的 HTTP 或 HTTPS 地址。")}r.url=e.url.trim(),(t?.type!==void 0||!t||"command"in t)&&(r.type="http")}return{[n]:r}}(m.draft,m.draft.originalName?c.local[m.draft.originalName]:void 0):m.preview;if(!t)return;let s=Object.keys(t).filter(e=>Object.hasOwn(c.local,e));if("json"===m.kind&&s.length&&!m.overwrite)throw new i5("json","请明确勾选替换已有配置。");if("manual"===m.kind&&s.some(e=>e!==m.draft.originalName))throw new i5("name","该名称已存在,请编辑已有服务或使用其他名称。");if(await L(e=>n.replaceMcp({cwd:o,servers:t},e),()=>{if("json"===m.kind)p(null);else{let e=m.draft.name.trim(),s=i2(e,t[e]);p({kind:"manual",draft:s,initial:JSON.stringify(s)})}})&&e&&"manual"===m.kind){let e=await B(m.draft.name.trim());C.current?.signal.aborted||j(e?"已保存,连接测试通过。":"已保存,连接测试失败。")}}catch(e){y({field:e instanceof i5?e.field:"save",message:i8(e)})}},F=async e=>{if(!c||!Object.hasOwn(c.local,e))return;let t=null!==o&&Object.hasOwn(c.inherited,e);await z.current({title:`${E.current(t?"恢复全局配置":"删除服务")} \xb7 ${e}`,description:E.current(t?"删除本项目配置后,将恢复使用同名全局配置。":"此范围内的服务配置将被删除。"),confirmLabel:E.current(t?"恢复全局配置":"删除服务")})&&await L(t=>n.deleteMcp(o,e,t),()=>p(null))},B=async e=>{let t=C.current?.signal;if(!t||!c||!1===c.projectTrusted||N?.loading)return!1;let s=++M.current;I({name:e,loading:!0,output:null,error:null});try{let r=await n.checkMcp(o,e,t);return t.aborted||M.current!==s||I({name:e,loading:!1,output:r.output.slice(0,32768),error:null}),!0}catch(n){return t.aborted||M.current!==s||I({name:e,loading:!1,output:null,error:i8(n)}),!1}},_=c?[...new Set([...Object.keys(c.inherited),...Object.keys(c.local)])].map(e=>{let t=c.local[e],s=c.inherited[e],n=!!(t&&s&&i1(t));return{name:e,config:n?{...s,...t}:t??s,local:t??null,source:null===o?"全局":t?n?"项目配置 \xb7 继承全局连接":"项目配置":"继承全局"}}):[];return{cwd:o,mcp:c,editor:m,setEditor:p,loading:h,pending:x,loadError:b,error:w,notice:k,check:N,rows:_,dirty:A,dialog:l,retry:()=>{C.current&&P(C.current.signal,S.current)},navigate:T,setCwd:e=>{u(null),I(null),v(null),g(!0),d(e)},startManual:D,startInherited:(e,t)=>{D(e,{enabled:!1!==t.enabled})},updateDraft:e=>{p(t=>t?.kind==="manual"?{...t,draft:{...t.draft,...e}}:t),y(null),j(null),I(null)},updateJson:e=>{p({kind:"json",text:e,preview:null,overwrite:!1}),y(null)},previewJson:()=>{if(m?.kind==="json"&&c)try{let t=function(e){let t;try{t=JSON.parse(e)}catch{throw Error("请输入有效的 JSON。")}let s=a.Ik({mcpServers:iH}).strict().safeParse(t);if(!s.success)throw Error("仅接受包含 mcpServers 的标准配置,不允许其他根级字段。");if(0===Object.keys(s.data.mcpServers).length)throw Error("配置中至少需要一个服务。");return s.data.mcpServers}(m.text);var e=c.inherited;for(let[s,n]of Object.entries(t)){if(!s.trim()||s!==s.trim())throw new i5("json","服务名称不能为空或带有首尾空格。");if(i1(n)){if(null===o||!Object.hasOwn(e,s)||Object.keys(n).some(e=>!["enabled","exposure","toolExposure"].includes(e)))throw new i5("json",`${s}:继承配置需要同名全局服务,且只允许启用和曝光设置。`)}else if("sse"===n.type)throw new i5("json",`${s}:不支持 SSE,请使用 HTTP 连接。`);else if("string"!=typeof n.command&&"string"!=typeof n.url)throw new i5("json",`${s}:请提供启动程序或服务地址。`)}p({...m,preview:t,overwrite:!1}),y(null)}catch(e){y({field:"json",message:i8(e)})}},saveEditor:O,remove:F,dismissCheck:()=>{I(null)},beforeLeave:R}}(i,s),o=i6(),d=(0,r.useId)(),c=(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.cwd?o("全局"):`${c.find(e=>e.cwd===l.cwd)?.projectName??o("当前项目")} \xb7 ${l.cwd}`,m=!!(l.editor&&l.mcp),p=!!(l.mcp&&!l.loading&&!l.loadError&&!m&&0===l.rows.length),h=l.pending||!!l.check?.loading,g=l.editor?.kind==="manual"?l.editor.draft.originalName:null,x=()=>{l.navigate(()=>l.startManual(null))},f=()=>{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:(0,C.cn)("grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 border-b p-4",!p&&"@min-[40rem]/mcp:grid-cols-[auto_minmax(0,1fr)_auto]"),children:[(0,n.jsx)("h2",{className:"text-xl font-semibold",children:"MCP"}),!p&&(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)(N.$,{disabled:h||l.loading||!l.mcp,onClick:x,children:[(0,n.jsx)(Y.A,{"aria-hidden":"true"}),o("添加服务")]}),(0,n.jsx)(N.$,{variant:"outline",disabled:h||l.loading||!l.mcp,onClick:f,children:o("导入 JSON")})]}),(0,n.jsx)("div",{className:(0,C.cn)("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",p&&"@min-[40rem]/mcp:w-56"),children:(0,n.jsx)(i7,{id:`${d}-scope`,label:o("配置范围"),value:l.cwd??"",disabled:h,options:[{value:"",label:o("全局")},...c.map(e=>({value:e.cwd,label:`${e.projectName}${e.cwd===t?` \xb7 ${o("当前项目")}`:""}`}))],onChange:e=>{e!==(l.cwd??"")&&l.navigate(()=>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)(le,{message:`${e.name?`${e.name}:`:""}${e.message}`},t))}),l.loadError?(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(le,{message:l.loadError}),(0,n.jsx)(N.$,{variant:"outline",onClick:l.retry,disabled:l.loading,children:o("重试")})]}):l.loading&&!m?(0,n.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:o("正在读取配置…")}):l.mcp?(0,n.jsxs)("div",{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)(le,{message:l.error.message})}),(0,n.jsx)(lt,{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)(la,{editor:l.editor,scopeLabel:u,project:null!==l.cwd,projectTrusted:l.mcp.projectTrusted,local:l.mcp.local,inherited:l.mcp.inherited,pending:h,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:x,onImport:f}):null]}):null]})}var lo=s(99481),ld=s(94159),lc=s(7576);let lu=a.Yj().trim().min(1).max(200),lm=a.Yj().trim().min(1).max(100).nullable(),lp=a.Yj().trim().min(1).max(100).nullable(),lh=a.Yj().trim().min(1).max(200),lg=a.Ik({label:a.Yj().trim().min(1).max(64),value:a.Yj().trim().min(1).max(500)}).strict(),lx=a.Yj().trim().min(1).max(300).nullable(),lf=a.k5(["running","completed","failed","stopped","interrupted"]),lb=a.Ik({taskId:lu,taskKind:lm,taskType:lp,title:lh,info:a.YO(lg).max(12),status:lf,activity:lx,startedAt:rE.k,endedAt:rE.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"]})}),lv=a.Ik({tasks:a.YO(lb)}).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)}),lw=a.Ik({kind:a.eu("text"),text:a.Yj(),truncated:a.zM()}).strict(),ly=ld.RX.extend({kind:a.eu("conversation"),truncated:a.zM()}).strict(),lk=a.KC([a.ch(),lw,ly]),lj=a.Ik({taskId:lu,canInterrupt:a.zM(),body:lk}).strict(),lN=lc.mv,lI=a.KC([a.Ik({type:a.eu("snapshot"),snapshot:lj}).strict(),a.Ik({type:a.eu("text_append"),text:a.Yj().min(1)}).strict(),a.Ik({type:a.eu("conversation_event"),event:lN}).strict(),a.Ik({type:a.eu("unavailable")}).strict()]);a.Ik({source:lo.R,taskId:lu,entryId:s3.Rv}).strict().extend({imageIndex:a.ai().int().nonnegative()}).strict();let lC=a.Ik({source:lo.R,taskId:lu.nullable()}).strict(),lS=a.Ik({snapshot:lj.nullable()}).strict(),lM=a.Ik({source:lo.R,taskId:lu}).strict(),lz=a.Ik({}).strict(),lE=a.Ik({source:lo.R,taskId:lu,event:lI}).strict(),lA=Object.freeze({detailWatch:(0,i.Vc)({path:"task-center/detail-watch",inputSchema:lC,outputSchema:lS}),interrupt:(0,i.Vc)({path:"task-center/interrupt",inputSchema:lM,outputSchema:lz}),detailEvent:(0,i._G)({path:"task-center/detail-event",bodySchema:lE})});var l$=s(217),lR=s(19580),lP=s(3005),lT=s(95513),lD=s(2325),lL=s(88649);let lO=({className:e,...t})=>(0,n.jsx)(lL.z,{className:(0,C.cn)("relative flex-1 overflow-y-hidden",e),initial:"smooth",resize:"smooth",role:"log",...t}),lF=({className:e,...t})=>(0,n.jsx)(lL.z.Content,{className:(0,C.cn)("flex flex-col gap-8 p-4",e),...t});var lB=s(3831),l_=s(62824),lq=s(50394),lW=s(12718),lU=s(64080);function lY({...e}){return(0,n.jsx)(lB.j,{"data-slot":"hover-card",...e})}function lV({...e}){return(0,n.jsx)(l_.Z,{"data-slot":"hover-card-trigger",...e})}function lK({className:e,side:t="bottom",sideOffset:s=4,align:r="center",alignOffset:a=4,...i}){return(0,n.jsx)(lq.D,{"data-slot":"hover-card-portal",children:(0,n.jsx)(lW.p,{align:r,alignOffset:a,side:t,sideOffset:s,className:"isolate z-50",children:(0,n.jsx)(lU.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),...i})})})}let lH=({className:e,...t})=>(0,n.jsx)(n$.Sq,{align:"block-end",className:(0,C.cn)("justify-between gap-1",e),...t}),lG=({className:e,...t})=>(0,n.jsx)("div",{className:(0,C.cn)("flex min-w-0 items-center gap-1",e),...t}),lJ=({variant:e="ghost",className:t,size:s,tooltip:a,...i})=>{let l=s??(r.Children.count(i.children)>1?"sm":"icon-sm"),o=(0,n.jsx)(n$.Ik,{className:(0,C.cn)(t),size:l,type:"button",variant:e,...i});if(!a)return o;let d="string"==typeof a?a:a.content,c="string"==typeof a?void 0:a.shortcut,u="string"==typeof a?"top":a.side??"top";return(0,n.jsxs)(tZ.m_,{children:[(0,n.jsx)(tZ.k$,{render:o}),(0,n.jsxs)(tZ.ZI,{side:u,children:[d,c&&(0,n.jsx)("span",{className:"ml-2 text-muted-foreground",children:c})]})]})},lX=a.Ik({input:a.g1(a.Yj(),a.Pq())}).strict(),lQ=a.Ik({output:a.Yj()}).strict(),lZ="pideskHelp",l0=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,l1=/^(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 l2(e){return/^[a-zA-Z0-9_./:@=+-]+$/.test(e)?e:JSON.stringify(e)}let l5=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"]),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:tm.qf}).strict().nullish()}).strict(),l3=a.Ik({plugins:a.YO(l5),restartRequired:a.zM(),loadError:tm.qf.nullish()}).strict(),l4=l5.extend({detail:a.g1(a.Yj(),a.Pq())}).strict(),l6=a.Ik({version:a.Yj(),environment:a.k5(["development","production"]),mode:a.k5(["basic","normal"]),cwd:a.Yj(),agentDir:a.Yj(),skillDirectory:a.Yj()}).strict(),l8=null,l7=new WeakMap,l9=new WeakMap,oe=new WeakMap;function ot(e){switch(e.fixed.type){case"user":{let t=ld.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?ld.Er.safeParse(e.summary):null,s=t?.success?t.data:{text:"",errorMessage:null},n="pi-desk/assistant"===e.fixed.viewKey?ld.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=ld.UT.safeParse(e.summary),r=n.success?n.data:t,a=ld.ny.safeParse(e.detail);return{summary:{type:"tool",kind:"codemode",...r,...s},detail:a.success?{type:"tool",kind:"codemode",...a.data}:void 0}}case"pi-desk/pidesk":{let n=lX.safeParse(e.summary),r=n.success?n.data:{input:{}},a=lQ.safeParse(e.detail);return{summary:{type:"tool",kind:"pidesk",...t,...r,...s},detail:a.success?{type:"tool",kind:"pidesk",output:a.data.output}:void 0}}case"pi-desk/bash-tool":{let n=ld.Qi.safeParse(e.summary),r=n.success?n.data:{...t,timing:null},a=ld.Ok.safeParse(e.detail);return{summary:{type:"tool",kind:"bash",...r,...s},detail:a.success?{type:"tool",kind:"bash",output:a.data.output}:void 0}}case"pi-desk/read":{let n=ld.Gx.safeParse(e.summary),r=n.success?n.data:{...t,path:null},a=ld.Xj.safeParse(e.detail);return{summary:{type:"tool",kind:"read",...r,...s},detail:a.success?{type:"tool",kind:"read",content:a.data.content}:void 0}}case"pi-desk/edit":{let n=ld.aV.safeParse(e.summary),r=n.success?n.data:{...t,path:null},a=ld.Rk.safeParse(e.detail);return{summary:{type:"tool",kind:"edit",...r,...s},detail:a.success?{type:"tool",kind:"edit",contentKind:a.data.kind,content:a.data.content}:void 0}}case"pi-desk/write":{let n=ld.bN.safeParse(e.summary),r=n.success?n.data:{...t,path:null},a=ld.O_.safeParse(e.detail);return{summary:{type:"tool",kind:"write",...r,...s},detail:a.success?{type:"tool",kind:"write",contentKind:a.data.kind,content:a.data.content}:void 0}}default:{let n=ld.Px.safeParse(e.summary),r=n.success?n.data:t,a=ld.Ok.safeParse(e.detail);return{summary:{type:"tool",kind:"generic",...r,...s},detail:a.success?{type:"tool",kind:"generic",output:a.data.output}:void 0}}}}case"bash":{let t=ld.ai.safeParse(e.summary),s=t.success?t.data:{command:e.fixed.viewKey},n=ld.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=ld.sL.safeParse(e.detail);return{summary:{type:"compaction",hasDetail:e.fixed.hasDetail},detail:t.success?{type:"compaction",...t.data}:void 0}}let t=ld.Rt.safeParse(e.summary);return{summary:{type:"custom",text:(t.success?t.data:{text:""}).text,hasDetail:!1},detail:void 0}}}}function os(e){return e.temporary||"status"in e.summary&&"running"===e.summary.status}function on(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 or(e,t,s){if("compaction"===s.summary.type){oa(e,t),e.push({identity:s.identity,user:null,processItems:[],finalAssistant:null,compaction:s,running:os(s),toolCount:0});return}"user"!==s.summary.type?t.body.push(s):(oa(e,t),t.user=s)}function oa(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,a=[];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||on(t))&&a.push({message:t,hideAssistantText:!1});continue}on(t)&&a.push({message:t,hideAssistantText:!0})}return{identity:e,user:t,processItems:a,finalAssistant:r,compaction:null,running:s.some(os),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=oe.get(e);if(t)return t;let s=[],n={user:null,body:[]},r=new Set,a=[],i=(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=l7.get(e);if(t)return t;let s=ot(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 l7.set(e,n),n}(t);"compaction"===e.summary.type?(a=[],i=!1):"assistant"===t.fixed.type&&(a.push(e),"assistant"===e.summary.type&&null!==e.timestampMs&&(e.summary.text.trim()||"pi-desk/assistant"!==e.viewKey)&&(e={...e,usageCalls:a,usageIncomplete:i},a=[],i=!1)),or(s,n,e)}let l={turns:s,user:n.user,body:n.body};return oe.set(e,l),l}(e.messages),n=[...s.turns],r={user:s.user,body:[...s.body]};for(let[t,s]of e.temporaryMessages.entries())or(n,r,function(e,t){let s=l9.get(e);if(s?.position===t)return s.message;let n=ot(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 l9.set(e,{position:t,message:r}),r}(s,e.messages.length+t));oa(n,r);let a=n.at(-1);return t&&a&&!a.compaction&&(a.running=!0),n}function ol(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}m`}function oo(e){return 0===e?"$0":e<1e-4?"<$0.0001":`$${e.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function od(e,t=Date.now(),s="en",n="UTC"){let r=new Date(e),a=new Date(t),i=function(e,t){if(l8?.locale===e&&l8.timeZone===t)return l8;let s="en"===e?"en-US":"zh-CN";return l8={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:i.dateKey.format(r)===i.dateKey.format(a)?i.compactTime.format(r):i.compactDateTime.format(r),full:i.fullDateTime.format(r)}}function oc(e,t,s={}){if("1"!==new URLSearchParams(window.location.search).get("chatScrollDebug"))return;let n=op(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?oh(n):0,tailMinHeight:n?.style.minHeight||null,tailAnchor:n?.dataset.chatTailAnchor??null,...s})}function ou(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 om(e){let t,s=(t=e.querySelectorAll("[data-chat-turn]")).item(t.length-1);return s?.hasAttribute("data-chat-logical-tail")?s:null}function op(e){return e.querySelector("[data-chat-tail-space]")}function oh(e){let t=e.lastElementChild;return t instanceof HTMLElement?Math.max(0,e.getBoundingClientRect().bottom-t.getBoundingClientRect().bottom):0}function og(e,t,s,n){let r=e.getBoundingClientRect(),a=e.scrollTop,i=Math.max(0,a+t.getBoundingClientRect().top-r.top-n),l=a+s.getBoundingClientRect().top-r.top;return{targetScrollTop:i,minHeight:Math.max(0,i+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 ox(e){let t=op(e);return t?oh(t):0}function of(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 ob(e){let t=op(e);if(!t)return;if(t!==om(e))return void of(e);let s=t.dataset.chatTailAnchor,n=Number.parseFloat(t.dataset.chatTailOffset??"");if(!s||!Number.isFinite(n))return;let r=ou(e,"data-chat-scroll-anchor",s);if(!r)return void of(e);let{minHeight:a}=og(e,r,t,n),i=`${Math.ceil(a)}px`;t.style.minHeight!==i&&(oc("tail:refresh:start",e,{nextMinHeight:i}),t.style.minHeight=i,oc("tail:refresh:end",e,{nextMinHeight:i}))}function ov(e,t,s,n){oc("position:start",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n}),of(e);let r=n?om(e):null;if(!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:a,minHeight:i}=og(e,t,r,s);r.style.minHeight=`${Math.ceil(i)}px`,r.dataset.chatTailSpace="";let l=t.dataset.chatScrollAnchor;l&&(r.dataset.chatTailAnchor=l),r.dataset.chatTailOffset=String(s),e.scrollTop=a,oc("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n,minHeight:i})}function ow({active:e=!0}){let{scrollRef:t,state:s}=(0,lL.B)();return(0,r.useEffect)(()=>{let n,r=t.current;if(!r||!e)return;let a=null,i=new Set,l=()=>{null===a&&(a=window.requestAnimationFrame(()=>{a=null,ob(r)}))},o=new ResizeObserver(l),d=()=>{let e=new Set,t=op(r);if(t)for(let s of t.children)s instanceof HTMLElement&&e.add(s);for(let t of i)e.has(t)||o.unobserve(t);for(let t of e)i.has(t)||o.observe(t);i=e},c=new MutationObserver(()=>{d(),l()}),u=0,m=null,p=null,h=new ResizeObserver(([e])=>{let t=e?.contentRect.height;if(void 0===t)return;let i=t-(n??t);(n=t,i)?(oc("viewport:resize",r,{difference:i,isAtBottom:s.isAtBottom,escapedFromLock:s.escapedFromLock}),u=i,s.resizeDifference=i,null!==a&&(window.cancelAnimationFrame(a),a=null),ob(r),s.isAtBottom&&(s.scrollTop=Math.max(0,s.calculatedTargetScrollTop)),oc("viewport:resize:positioned",r,{difference:i}),null!==m&&window.cancelAnimationFrame(m),null!==p&&window.clearTimeout(p),m=window.requestAnimationFrame(()=>{m=null,p=window.setTimeout(()=>{p=null,s.resizeDifference===i&&(s.resizeDifference=0),u=0},1)})):l()});return c.observe(r,{attributes:!0,attributeFilter:["data-chat-tail-space","data-chat-logical-tail"],childList:!0,subtree:!0}),h.observe(r),d(),l(),()=>{null!==a&&window.cancelAnimationFrame(a),null!==m&&window.cancelAnimationFrame(m),null!==p&&window.clearTimeout(p),u&&s.resizeDifference===u&&(s.resizeDifference=0),c.disconnect(),o.disconnect(),h.disconnect()}},[e,t,s]),null}function oy(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 ok(e,t,s){let n=0;for(let r=t;r<s;r+=1)e[r]?.user&&(n+=1);return n}function oj(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,ok(e,0,s)),r=s,a=0,i=0,l=0;for(;r>0;){let t=e[r-1],s=oy(t).length,o=l<n;if(a>0&&!o&&(a>=30||i+s>200))break;r-=1,a+=1,i+=s,t.user&&(l+=1)}return r}function oN(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,ok(e,s,e.length)),r=s,a=0,i=0,l=0;for(;r<e.length;){let t=e[r],s=oy(t).length,o=l<n;if(a>0&&!o&&(a>=30||i+s>200))break;r+=1,a+=1,i+=s,t.user&&(l+=1)}return r}function oI(e){return{startIndex:oj(e,e.length),endIndex:e.length}}function oC(e,t){let s,n;if(0===e.length)return{startIndex:0,endIndex:0};if(!t)return oI(e);let r=(n=(s=t.lastIndexOf(":"))>0?t.slice(0,s):t,e.findIndex(e=>oy(e).some(e=>e.identity===n)));if(r<0)return oI(e);let a=Math.min(e.length,r+1+10);return{startIndex:oj(e,a),endIndex:a}}function oS({active:e=!0,turns:t,focusTurnIdentity:s,initialAnchor:a,children:i}){let{scrollRef:l}=(0,lL.B)(),[o,d]=(0,r.useState)(()=>({...oC(t,a),turnCount:t.length,focusTurnIdentity:s}));e||o.focusTurnIdentity===s||d({...o,focusTurnIdentity:s});let c=(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 oI(t);if(0===o.turnCount&&0===o.endIndex)return oC(t,a);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,a,t,o]),p=(0,r.useCallback)(e=>{d({...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&&(c.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=oj(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]),x=(0,r.useCallback)(()=>{if(m.endIndex>=t.length||u.current)return;let e=oN(t,m.endIndex);e<=m.endIndex||(u.current=!0,p({...m,endIndex:e}))},[p,m,t]),f=(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,oj(t,e+1))}):p({...m,endIndex:Math.max(e+1,oN(t,e))}))},[p,m,t]),b=(0,r.useCallback)(()=>{p(oI(t))},[p,t]);(0,r.useLayoutEffect)(()=>{var e;u.current=!1;let t=c.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(c.current=null,!s||!n)return;let r=n.getBoundingClientRect().top-s.getBoundingClientRect().top,a=r-t.offset;oc("window:anchor-correction:start",s,{turnIdentity:t.turnIdentity,previousOffset:t.offset,nextOffset:r,correction:a}),s.scrollTop+=a,oc("window:anchor-correction:end",s,{turnIdentity:t.turnIdentity,correction:a})},[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&&x()},a=()=>{null===n&&(n=window.requestAnimationFrame(r))},i=e=>{e.deltaY<0&&s.scrollTop<=24?g():e.deltaY>0&&a()},o=()=>{s.scrollTop<=24?g():a()};return s.addEventListener("scroll",a,{passive:!0}),s.addEventListener("wheel",i,{passive:!0}),s.addEventListener("touchmove",o,{passive:!0}),()=>{s.removeEventListener("scroll",a),s.removeEventListener("wheel",i),s.removeEventListener("touchmove",o),null!==n&&window.cancelAnimationFrame(n)}},[e,m,g,x,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:f,resetToTail:b}),[m,b,f,t.length,v]);return(0,n.jsx)(n.Fragment,{children:i(w)})}let oM={canMoveUp:!1,canMoveDown:!1,hasNextMessage:!1};function oz(e,t,s,n){let r=0,a=e.length;for(;r<a;){let i=Math.floor((r+a)/2),l=e[i].getBoundingClientRect().top-t;(n?l>=s:l>s)?a=i:r=i+1}return r}function oE(e){return e.user?`${e.user.identity}:user`:null}function oA(e,t,s){let n=Array.from(e.querySelectorAll("[data-chat-user-message]")),r=e.getBoundingClientRect().top+12,a=oz(n,r,-2,!0),i=oz(n,r,2,!1),l=s.find(e=>e>=t.startIndex&&e<t.endIndex),o=s.findLast(e=>e>=t.startIndex&&e<t.endIndex),d=0===a?s.findLast(e=>e<(l??t.startIndex))??null:null,c=i>=n.length?s.find(e=>e>(o??t.endIndex-1))??null:null,u=e.scrollHeight-e.scrollTop-e.clientHeight,m=ox(e),p=t.containsTail&&u<=2;return oc("navigation:inspect",e,{containsTail:t.containsTail,tailSpacerHeight:m,atBottom:p,previousMessage:n[a-1]?.dataset.chatUserMessage??null,nextMessage:n[i]?.dataset.chatUserMessage??null,previousOutsideTurnIndex:d,nextOutsideTurnIndex:c}),{previousMessage:n[a-1]??null,nextMessage:n[i]??null,previousOutsideTurnIndex:d,nextOutsideTurnIndex:c,atBottom:p}}function o$({turns:e,window:t}){let{t:s}=(0,f.Bd)("conversation"),{scrollRef:a,scrollToBottom:i,stopScroll:l}=(0,lL.B)(),o=(0,r.useMemo)(()=>e.flatMap((e,t)=>e.user?[t]:[]),[e]),[d,c]=(0,r.useState)(!1),[u,m]=(0,r.useState)(oM),[p,h]=(0,r.useState)(null),g=(0,r.useRef)(null),x=(0,r.useRef)(!1),b=(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),I=(0,r.useRef)(!1),C=(0,r.useCallback)(e=>{var s;let n,r=(n=!(s=oA(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]),S=(0,r.useCallback)(e=>{null===w.current&&(w.current=window.requestAnimationFrame(()=>{w.current=null,C(e)}))},[C]),M=(0,r.useCallback)(()=>{null!==v.current&&(window.clearTimeout(v.current),v.current=null)},[]),z=(0,r.useCallback)(()=>{M(),b.current||(v.current=window.setTimeout(()=>{v.current=null,x.current=!1,c(!1),null!==w.current&&(window.cancelAnimationFrame(w.current),w.current=null)},2e3))},[M]),E=(0,r.useCallback)(()=>{null!==g.current&&window.clearTimeout(g.current),g.current=null,h(e=>e?.visible?{...e,visible:!1}:e)},[]),R=(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=a.current;e&&(x.current||m(oM),x.current=!0,c(!0),S(e),z())},[S,z,a]);(0,r.useLayoutEffect)(()=>{let e=a.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(),ov(e,n,12,t.containsTail))}j.current&&t.containsTail&&(j.current=!1,of(e),Promise.resolve(i({animation:"instant"})).finally(()=>{y.current=!1,I.current&&x.current&&S(e)}))},[S,a,i,l,t.containsTail,t.endIndex,t.startIndex]),(0,r.useLayoutEffect)(()=>{let e=a.current;if(!e)return;I.current=!0;let t=()=>{E(),P()},s=()=>{x.current&&S(e)},n=t=>{t.target===e&&E()},r=e=>{["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(e.key)&&E()};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),I.current=!1}},[E,S,a,P]),(0,r.useLayoutEffect)(()=>()=>{M(),null!==g.current&&window.clearTimeout(g.current),y.current=!1,k.current=null,j.current=!1},[M]),(0,r.useLayoutEffect)(()=>{d&&(u.canMoveUp||u.canMoveDown)||(b.current=!1)},[u.canMoveDown,u.canMoveUp,d]);let T=(0,r.useCallback)((s,n)=>{let r=a.current;if(!r)return;P();let d=oA(r,t,o),c="up"===s?d.previousMessage:d.atBottom?null:d.nextMessage;if(c){let s=o.findIndex(t=>oE(e[t])===c.dataset.chatScrollAnchor);s>=0&&R(s+1),y.current=!1,l(),ov(r,c,12,t.containsTail)}else{let a="up"===s?d.previousOutsideTurnIndex:d.nextOutsideTurnIndex;if(null!==a){let s=oE(e[a]);s&&(R(o.indexOf(a)+1),y.current=!1,k.current={anchor:s},t.revealTurn(a))}else"down"===s&&(o.length>0&&R(o.length),n&&(n.disabled=!0),m(e=>e.canMoveDown?{...e,canMoveDown:!1}:e),d.atBottom||y.current||(oc("navigation:bottom:start",r,{containsTail:t.containsTail}),y.current=!0,of(r),t.containsTail?Promise.resolve(i({animation:"instant"})).finally(()=>{y.current=!1,I.current&&x.current&&S(r)}):(j.current=!0,t.resetToTail())))}S(r)},[S,a,i,P,R,l,e,t,o]),D=d&&(u.canMoveUp||u.canMoveDown),L=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,D?(0,n.jsxs)(tQ,{orientation:"vertical",className:"absolute right-3 bottom-4 z-10 rounded-lg shadow-sm sm:right-4","aria-label":s("userNavigation"),onMouseEnter:()=>{b.current=!0,M()},onMouseLeave:()=>{b.current=!1,x.current&&z()},children:[(0,n.jsx)(N.$,{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:()=>T("up"),children:(0,n.jsx)(A.A,{className:"size-4"})}),(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"icon",className:"size-10 bg-background/90 backdrop-blur dark:bg-background/90",disabled:!u.canMoveDown,"aria-label":L,title:L,onClick:e=>T("down",e.currentTarget),children:(0,n.jsx)($.A,{className:"size-4"})})]}):null]})}let oR=(0,r.createContext)({basic:!1});function oP({basic:e,onRecover:t,children:s}){let a=(0,r.useMemo)(()=>({basic:e,recover:t}),[e,t]);return(0,n.jsx)(oR.Provider,{value:a,children:s})}function oT(e){return{location:e.snapshot.location,fixed:e.snapshot.fixed,summary:e.snapshot.summary,...void 0===e.snapshot.detail?{}:{detail:e.snapshot.detail}}}class oD{constructor(e,t){this.listeners=new Set,this.pending=null,this.requestEpoch=0,this.disposed=!1,this.basic=!1,this.message=e,this.snapshot=oT(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=oT(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 oL({message:e,pluginName:t,contributionName:s,phase:a,error:i,handle:l,onRetry:o}){let{t:d}=(0,f.Bd)("conversation"),[c,u]=(0,r.useState)(l.getSnapshot().detail),[m,p]=(0,r.useState)(!1),[h,g]=(0,r.useState)(null),x=(0,r.useContext)(oR),[v,w]=(0,r.useState)(!1),[y,k]=(0,r.useState)(!1),j=i.name,I=i.message,C=i.stack;return(0,r.useEffect)(()=>{console.error("[Pi Desk][MessageView] 消息视图无法展示",{messageId:e.identity,viewKey:e.viewKey,pluginName:t,contributionName:s,phase:a,errorName:j,message:I,stack:C})},[e.identity,e.viewKey,t,s,a,j,I,C]),(0,n.jsx)("div",{role:"alert","data-message-id":e.identity,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)(ta.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)(to,{error:i,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"," ",a]}),(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===c?(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:m,onClick:()=>{p(!0),g(null),l.loadDetail().then(u,e=>{g(e instanceof Error?e.message:d("detailFailed"))}).finally(()=>p(!1))},children:[m?(0,n.jsx)(b.A,{className:"animate-spin"}):null,d("loadDetail")]}):null,h?(0,n.jsx)("p",{className:"text-sm text-destructive [overflow-wrap:anywhere]",children:h}):null,c?(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(c,null,2)}):null]}),x.recover?(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",className:"mt-2 mr-2",disabled:v,onClick:()=>{w(!0),x.recover().catch(e=>g(e instanceof Error?e.message:String(e))).finally(()=>w(!1))},children:[v?(0,n.jsx)(b.A,{className:"animate-spin"}):null,d("useBasicPresentation")]}):null,o?(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",className:"mt-2",disabled:y,onClick:()=>{k(!0),g(null),Promise.resolve().then(o).catch(e=>g(e instanceof Error?e.message:String(e))).finally(()=>k(!1))},children:[y?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(eE.A,{}),d("retry")]}):null]})]})})}function oO({message:e,loadDetail:t,defaultView:s}){let{t:a}=(0,f.Bd)("conversation"),i=(0,eI.t4)();(0,eI.So)();let l=(0,r.useContext)(oR),o=(0,r.useRef)(null),d=(0,r.useRef)(null),c=(0,r.useRef)(null),[u,m]=(0,r.useState)({status:"loading"}),[p]=(0,r.useState)(()=>new oD(e,t)),[h,g]=(0,r.useState)(0),x=i.getMessageViewResolution(e.viewKey),b=i.areEntriesInitialized(),v=!x&&i.isRefreshingEntries(),w=x?.status==="winner"?`${e.viewKey}\u0000${x.pluginName}\u0000${x.descriptor.contributionName}\u0000${x.descriptor.priority}`:x?.status==="conflict"?`${e.viewKey}\u0000${x.candidates.map(e=>`${e.pluginName}:${e.descriptor.contributionName}`).join(",")}`:e.viewKey,y=x?.status==="winner"?x.pluginName:null,k=x?.status==="winner"?x.descriptor.contributionName:null,j=y?i.getEntryState(y):null,N=j?.status==="ready"?j.runtime:j?.status,I=e.viewKey.startsWith("pi-desk/")&&"pi-desk/message-declaration-error"!==e.viewKey,C=I&&null===x,S=(0,r.useMemo)(()=>({attempt:h,basic:l.basic,resolutionKey:w,winnerIdentity:N}),[h,l.basic,w,N]),M=(0,r.useMemo)(()=>({kind:"message-view",message:{getSnapshot:()=>p.getSnapshot(),subscribe:e=>c.current!==S?()=>void 0:p.subscribe(()=>{if(c.current===S&&y&&i.getEntryState(y)===j)try{e()}catch(e){m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"update",generation:S})}}),loadDetail:async()=>{if(c.current!==S)throw Error("Message View 已释放");let e=await p.loadDetail();if(c.current!==S)throw Error("Message View 已释放");return e}},reportError(e){c.current===S&&y&&i.getEntryState(y)===j&&m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"report-error",generation:S})}}),[p,S,i,j,y]);return((0,r.useLayoutEffect)(()=>(c.current=S,p.replace(e,t,l.basic),()=>{c.current===S&&(c.current=null)}),[p,t,e,l.basic,S]),(0,r.useEffect)(()=>{let e={};return d.current=e,()=>{d.current===e&&(d.current=null),queueMicrotask(()=>{null===d.current&&p.dispose()})}},[p]),(0,r.useEffect)(()=>{if(l.basic)return void queueMicrotask(()=>m({status:"loading"}));if(!b||C||"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 a=Promise.resolve().then(()=>n?(r=document.createElement("div"),t.append(r),i.mountContribution({pluginName:y,kind:"message-view",contributionName:k,container:r,target:M,signal:s.signal})):null);return a.then(e=>{n&&e&&i.getEntryState(y)===j&&m(e=>"error"===e.status&&e.generation===S?e:{status:"ready"})},e=>{n&&i.getEntryState(y)===j&&m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"mount",generation:S})}),()=>{n=!1,s.abort(),r?.remove(),a.then(async e=>{await e?.()},()=>void 0)}},[h,C,b,e.viewKey,S,y,k,j,i,M,l.basic]),l.basic)?(0,n.jsx)(n.Fragment,{children:s}):"pi-desk/message-declaration-error"===e.viewKey?(0,n.jsx)(oL,{message:e,pluginName:"pi-desk",contributionName:"message-declaration-error",phase:"declaration",error:Error(a("declarationFailed")),handle:p}):b?x?.status==="conflict"?(0,n.jsx)(oL,{message:e,pluginName:null,contributionName:null,phase:"priority-conflict",error:Error(a("viewConflict")),handle:p}):x?"error"===u.status&&u.generation===S?(0,n.jsx)(oL,{message:e,pluginName:x.pluginName,contributionName:x.descriptor.contributionName,phase:u.phase,error:u.error,handle:p,onRetry:()=>{let e=i.getContributionLoadState(x.pluginName,"message-view",x.descriptor.contributionName);(m({status:"loading"}),"failed"!==e.status)?g(e=>e+1):i.retryContribution(x.pluginName,"message-view",x.descriptor.contributionName).then(()=>g(e=>e+1),e=>{m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"load",generation:S})})}}):(0,n.jsx)("div",{className:"relative min-h-12","data-message-id":e.identity,"aria-busy":"loading"===u.status,children:(0,n.jsx)("div",{ref:o,"data-pi-desk-plugin":x.pluginName,"data-pi-desk-kind":"message-view","data-pi-desk-contribution":x.descriptor.contributionName})}):v?(0,n.jsx)("div",{className:"min-h-12","aria-busy":"true"}):I?(0,n.jsx)(n.Fragment,{children:s}):(0,n.jsx)(oL,{message:e,pluginName:null,contributionName:null,phase:"missing-view",error:Error(a("viewMissing",{viewKey:e.viewKey})),handle:p,onRetry:async()=>{await i.refreshEntries(),await Promise.all(i.getFailedEntries().map(({pluginName:e})=>i.retryEntry(e)))}}):I?(0,n.jsx)(n.Fragment,{children:s}):(0,n.jsx)("div",{className:"min-h-12","aria-busy":"true"})}var oF=s(41040),oB=s(54169),o_=s(67419),oq=s(41570),oW=s(4972),oU=s(94394),oY=s(21182);let oV={src:"/_next/static/media/console.fdac8a18.svg",height:16,width:16,blurWidth:0,blurHeight:0},oK={src:"/_next/static/media/docker.1e10aab8.svg",height:24,width:24,blurWidth:0,blurHeight:0},oH={src:"/_next/static/media/git.f893cb5f.svg",height:32,width:32,blurWidth:0,blurHeight:0},oG={src:"/_next/static/media/html.97f145d3.svg",height:32,width:32,blurWidth:0,blurHeight:0},oJ={src:"/_next/static/media/image.69ad851c.svg",height:16,width:16,blurWidth:0,blurHeight:0},oX={src:"/_next/static/media/javascript.9ef61c53.svg",height:16,width:16,blurWidth:0,blurHeight:0},oQ={src:"/_next/static/media/json.eb8fe488.svg",height:960,width:960,blurWidth:0,blurHeight:0},oZ={src:"/_next/static/media/markdown.ee1bbe18.svg",height:32,width:32,blurWidth:0,blurHeight:0},o0={src:"/_next/static/media/nodejs.2f5d7983.svg",height:32,width:32,blurWidth:0,blurHeight:0},o1={src:"/_next/static/media/typescript.cd97905b.svg",height:16,width:16,blurWidth:0,blurHeight:0},o2={src:"/_next/static/media/yaml.8927dd24.svg",height:24,width:24,blurWidth:0,blurHeight:0},o5=new Map(Object.entries({"agents.md":{src:"/_next/static/media/agent.84538518.svg",height:32,width:32,blurWidth:0,blurHeight:0},"skill.md":{src:"/_next/static/media/skill.a97e8eb6.svg",height:16,width:16,blurWidth:0,blurHeight:0},"package.json":o0,"package-lock.json":o0,"npm-shrinkwrap.json":o0,dockerfile:oK,".dockerignore":oK,".gitignore":oH,".gitattributes":oH,".gitmodules":oH})),o3=new Map(Object.entries({ts:o1,mts:o1,cts:o1,tsx:{src:"/_next/static/media/react_ts.3d16336c.svg",height:32,width:32,blurWidth:0,blurHeight:0},js:oX,mjs:oX,cjs:oX,jsx:{src:"/_next/static/media/react.b5a87f7d.svg",height:32,width:32,blurWidth:0,blurHeight:0},json:oQ,jsonc:oQ,jsonl:oQ,yaml:o2,yml:o2,md:oZ,mdx:oZ,png:oJ,jpg:oJ,jpeg:oJ,gif:oJ,webp:oJ,avif:oJ,bmp:oJ,ico:oJ,svg:{src:"/_next/static/media/svg.4aa98763.svg",height:32,width:32,blurWidth:0,blurHeight:0},sh:oV,bash:oV,zsh:oV,fish:oV,ps1:oV,bat:oV,cmd:oV,html:oG,htm:oG,css:{src:"/_next/static/media/css.0d88d948.svg",height:32,width:32,blurWidth:0,blurHeight:0},py:{src:"/_next/static/media/python.e376d0bc.svg",height:24,width:24,blurWidth:0,blurHeight:0}}));function o4({path:e,className:t}){let s=e.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()??"",r=s.includes(".")?s.slice(s.lastIndexOf(".")+1):"",a=o5.get(s)??(s.startsWith("dockerfile.")?oK:void 0)??o3.get(r);return a?(0,n.jsx)(oY.default,{src:a,alt:"","aria-hidden":"true",width:16,height:16,className:t,unoptimized:!0}):(0,n.jsx)(nE.A,{className:t,"aria-hidden":"true"})}var o6=s(32229),o8=s(4362);let o7=new Map,o9=(0,r.memo)(({children:e,as:t="p",className:s,duration:a=2,spread:i=2})=>{let l,o=((l=o7.get(t))||(l=o8.PY1.create(t),o7.set(t,l)),l),d=(0,r.useMemo)(()=>(e?.length??0)*i,[e,i]);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":`${d}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{duration:a,ease:"linear",repeat:1/0},children:e})}),de=(0,r.createContext)(null),dt=(0,r.memo)(({className:e,isStreaming:t=!1,open:s,defaultOpen:a,onOpenChange:i,duration:l,children:o,...d})=>{let c=a??t,u=!1===a,[m,p]=(0,o6.i)({defaultProp:c,onChange:i,prop:s}),[h,g]=(0,o6.i)({defaultProp:void 0,prop:l}),x=(0,r.useRef)(t),[f,b]=(0,r.useState)(!1),v=(0,r.useRef)(null);(0,r.useEffect)(()=>{t?(x.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(x.current&&!t&&m&&!f){let e=setTimeout(()=>{p(!1),b(!0)},1e3);return()=>clearTimeout(e)}},[t,m,p,f]);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)(de.Provider,{value:y,children:(0,n.jsx)(tl.Nt,{className:(0,C.cn)("not-prose mb-4",e),onOpenChange:w,open:m,...d,children:o})})}),ds=(e,t)=>e||0===t?(0,n.jsx)(o9,{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"]}),dn=(0,r.memo)(({className:e,children:t,getThinkingMessage:s=ds,...a})=>{let{isStreaming:i,isOpen:l,duration:o}=(()=>{let e=(0,r.useContext)(de);if(!e)throw Error("Reasoning components must be used within Reasoning");return e})();return(0,n.jsx)(tl.R6,{className:(0,C.cn)("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...a,children:t??(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oF.A,{className:"size-4"}),s(i,o),(0,n.jsx)(ti.A,{className:(0,C.cn)("size-4 transition-transform",l?"rotate-180":"rotate-0")})]})})}),dr={cjk:t0.h,code:t1.a,math:t2.D,mermaid:t5.a},da=(0,r.memo)(({className:e,children:t,...s})=>(0,n.jsx)(tl.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)(t3.jH,{plugins:dr,children:t})}));dt.displayName="Reasoning",dn.displayName="ReasoningTrigger",da.displayName="ReasoningContent";var di=s(6632),dl=s.n(di);function dd({messages:e,incomplete:t,children:s}){let{t:a}=(0,f.Bd)("conversation"),[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)(!1),c=(0,r.useRef)(null),u=(0,r.useRef)(null),m=(0,r.useRef)(!1);return(0,n.jsxs)(th.AM,{open:i,onOpenChange:(e,t)=>{if(!e&&"trigger-press"===t.reason&&m.current){m.current=!1,t.cancel();return}e&&"trigger-hover"===t.reason&&o||!e&&"trigger-hover"===t.reason&&(!m.current||u.current?.contains(document.activeElement))?t.cancel():(e?m.current="trigger-hover"===t.reason:"trigger-hover"!==t.reason&&(m.current=!1,d(!0)),l(e))},children:[(0,n.jsx)(th.Wv,{ref:c,openOnHover:!o,delay:250,closeDelay:180,onPointerLeave:()=>d(!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)(th.hl,{ref:u,align:"start",side:"top",initialFocus:()=>!m.current,finalFocus:()=>!m.current&&c.current,className:(0,C.cn)(dl().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)(th.eO,{className:"min-w-0 flex-1 text-xs font-medium text-muted-foreground",children:a(t?"calls.loadedTitle":"calls.title")}),(0,n.jsx)("button",{type:"button","aria-label":a("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:()=>{m.current=!1,d(!0),l(!1)},children:(0,n.jsx)(U.A,{className:"size-3.5"})})]}),i?(0,n.jsx)("div",{className:"min-h-0 overflow-y-auto overscroll-contain",children:(0,n.jsxs)("div",{className:dl().table,children:[(0,n.jsxs)("div",{className:(0,C.cn)(dl().row,"text-muted-foreground"),children:[(0,n.jsx)("span",{children:a("calls.model")}),(0,n.jsx)("span",{children:a("calls.input")}),(0,n.jsx)("span",{children:a("calls.output")}),(0,n.jsx)("span",{children:a("calls.cached")}),(0,n.jsx)("span",{children:a("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:dl().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||a("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:a(`calls.${t.status}`)}):null]}),(0,n.jsx)("span",{children:ol(r.inputTokens)}),(0,n.jsx)("span",{children:ol(r.outputTokens)}),(0,n.jsx)("span",{children:ol(r.cacheReadTokens)}),(0,n.jsx)("span",{children:oo(r.costUsd)})]},e.durable.location.entryId)})]})}):null]})]})}function dc({nestedCalls:e}){let{t}=(0,f.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 overscroll-contain",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 du({plugin:e}){let{t}=(0,f.Bd)("conversation"),{locale:s}=(0,tp.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.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,tm.fD)(e.error.message,s)]}):null]})}function dm({result:e}){let{t}=(0,f.Bd)("conversation"),{locale:s}=(0,tp.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)(du,{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,tm.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)(du,{plugin:e},`${e.source}:${t}`))}):(0,n.jsx)("p",{className:"text-muted-foreground",children:t("pidesk.noPlugins")})]})}function dp({identity:e,command:t,output:s,expandable:r,open:a,loading:i,error:l,onOpenChange:o,commandAction:d,outputAction:c}){let{t:u}=(0,f.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=l3.safeParse(s);return e.success?{kind:"plugins",data:e.data}:null}case"pideskShowPlugin":{let e=l4.safeParse(s);return e.success?{kind:"plugin",data:e.data}:null}case"pideskInfo":{let e=l6.safeParse(s);return e.success?{kind:"info",data:e.data}:null}default:return null}}(t.label,s);return(0,n.jsxs)(tl.Nt,{open:r&&a,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)(tl.R6,{disabled:!r,"aria-label":r?u(a?"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)(n2.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)(ti.A,{className:(0,C.cn)("size-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-180"),"aria-hidden":"true"}):null]}),(0,n.jsx)(tl.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")}),d]}),(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")}),c]}),(0,n.jsx)("div",{className:"max-h-[min(24rem,50dvh)] overflow-auto overscroll-contain px-3 pt-1 pb-3",role:"region","aria-label":u("pidesk.output"),tabIndex:0,children:i?(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)(dm,{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 dh=s(75881),dg=s.n(dh);let dx="max-h-[min(20rem,45dvh)] overflow-auto overscroll-contain [scrollbar-gutter:stable]",df=(0,r.createContext)(()=>void 0),db=(0,r.createContext)(null),dv=(0,r.createContext)(null),dw="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 dy({children:e}){let{isAtBottom:t,stopScroll:s}=(0,lL.B)(),a=(0,r.useRef)(t),i=(0,r.useRef)(s);(0,r.useLayoutEffect)(()=>{a.current=t,i.current=s},[t,s]);let l=(0,r.useCallback)(()=>{a.current&&i.current()},[]);return(0,n.jsx)(df.Provider,{value:l,children:e})}function dk(e,t){let{t:s}=(0,f.Bd)("conversation"),[n,a]=(0,r.useState)(!1),[i,l]=(0,r.useState)(null),o=(0,r.useCallback)(async()=>{if(!e.temporary&&e.durable&&e.snapshot.fixed.hasDetail&&void 0===e.detail&&!n){a(!0),l(null);try{await t(e)}catch(e){l(e instanceof Error?e.message:s("detailFailed"))}finally{a(!1)}}},[n,e,t,s]);return{loading:n,error:i,load:o}}function dj(e,t){let[s,n]=(0,r.useState)(!1),a=(0,r.useContext)(df),{loading:i,error:l,load:o}=dk(e,t),d=!e.temporary&&(e.summary.hasDetail||"tool"===e.summary.type&&!!e.summary.images?.length);return{open:s,expandable:d,loading:i,error:l,handleOpenChange:e=>{d&&(e&&(a(),o()),n(e))}}}function dN({timestampMs:e}){let{locale:t,timeZone:s}=(0,tp.i)(),r=od(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 dI({text:e,copyLabel:t,alwaysVisible:s=!1}){let{t:a}=(0,f.Bd)("conversation"),i=(0,eC.G)(),[l,o]=(0,r.useState)(!1),d=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{null!==d.current&&window.clearTimeout(d.current)},[]);let c=(0,r.useCallback)(async()=>{let t=!1;try{t=await (0,tg.x)(e)}catch{t=!1}t?(o(!0),null!==d.current&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{d.current=null,o(!1)},1500)):i.error(a("messageCopyFailed"))},[e,i,a]);if(!e.trim())return null;let u=l?a("copied"):t??a("copyMessage");return(0,n.jsx)(t8,{tooltip:u,label:u,size:"icon-sm",className:(0,C.cn)(!s&&dg().messageCopyAction,"text-muted-foreground"),onClick:()=>void c(),children:l?(0,n.jsx)(ed.A,{className:"size-3.5"}):(0,n.jsx)(eM.A,{className:"size-3.5"})})}function dC({usage:e,compactOnly:t=!1}){let{t:s}=(0,f.Bd)("conversation"),r=ol(e.inputTokens),a=ol(e.outputTokens),i=ol(e.cacheReadTokens),l=oo(e.costUsd),o=s("usage",{input:r,output:a,cached:i,cost:l}),d=`${r}/${a}/${i}/${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:d}):(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("span",{className:dg().usageLabeled,children:o}),(0,n.jsx)("span",{className:dg().usageCompact,children:d})]})}function dS({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)(se,{className:(0,C.cn)(dg().usageToolbar,"mt-1 flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground"),children:[e.usageCalls?.length?(0,n.jsx)(dd,{messages:e.usageCalls,incomplete:e.usageIncomplete??!1,children:(0,n.jsx)(dC,{usage:e.summary.usage})},e.durable.location.entryId):(0,n.jsx)(dC,{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)(dI,{text:t}),null===e.timestampMs?null:(0,n.jsx)(dN,{timestampMs:e.timestampMs})]})]})}function dM({message:e,onAcquireImage:t}){let{t:s}=(0,f.Bd)("conversation"),a="user"===e.summary.type||"tool"===e.summary.type?e.summary.images??[]:[],i=a.length,l=(0,r.useRef)(e);(0,r.useLayoutEffect)(()=>{l.current=e},[e]);let[o,d]=(0,r.useState)(()=>Array.from({length:i},()=>({status:"loading"}))),[c,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(0);return(0,r.useLayoutEffect)(()=>{let e=!0,s=Array.from({length:i},()=>null);for(let n=0;n<i;n+=1){let r=t=>{e?(s[n]=t.release,d(e=>{let s=[...e];return s[n]={status:"ready",url:t.url},s})):t.release()},a=()=>{e&&d(e=>{let t=[...e];return t[n]={status:"error"},t})};try{let e=t(l.current,n);"then"in e?e.then(r).catch(a):r(e)}catch{a()}}return()=>{e=!1,s.forEach(e=>e?.())}},[i,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:a.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),d(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,i)=>{if("ready"!==r.status)return;i===t&&(n=e.length);let l=a[i];e.push({src:r.url,alt:s("chatImage",{count:i+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}`)})}),c?(0,n.jsx)(nC.k,{mode:"modal",open:!0,slides:c.slides,index:c.index,ariaLabel:s("chatImagePreview"),onClose:()=>u(null),onIndexChange:e=>u(t=>t?{...t,index:e}:t)}):null]})}function dz({text:e}){let{t}=(0,f.Bd)("conversation"),s=(0,r.useRef)(null),[a,i]=(0,r.useState)(!1),[l,o]=(0,r.useState)(null),d=(0,r.useContext)(df);(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 c=(0,r.useCallback)(()=>{a||d(),i(e=>!e)},[d,a]);return(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("div",{className:(0,C.cn)("relative",!a&&!1!==l&&dg().userTextCollapsed),children:[(0,n.jsx)("p",{ref:s,className:"whitespace-pre-wrap break-words",children:e}),l&&!a?(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":a,onClick:c,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(a?"collapse":"expand"),(0,n.jsx)(ti.A,{className:(0,C.cn)("size-3.5 transition-transform",a&&"rotate-180"),"aria-hidden":"true"})]}):null]})}function dE({message:e,onAcquireImage:t}){if("user"!==e.summary.type)throw Error("UserMessage requires a user summary");return(0,n.jsxs)(t4,{from:"user","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:user`,"data-chat-user-message":"",className:(0,C.cn)(dg().copyableMessage,"max-w-[92%] sm:max-w-[84%]"),children:[(0,n.jsxs)(t6,{className:(0,C.cn)(dg().userText,"group-[.is-user]:px-3 group-[.is-user]:py-2"),children:[e.summary.images.length>0?(0,n.jsx)(dM,{message:e,onAcquireImage:t},`${e.tempId}:${e.durable?.location.entryId??"temporary"}`):null,e.summary.text?(0,n.jsx)(dz,{text:e.summary.text}):null]}),null===e.timestampMs?null:(0,n.jsxs)(se,{className:"mt-0 justify-end gap-1 text-xs text-muted-foreground",children:[(0,n.jsx)(dI,{text:e.summary.text}),(0,n.jsx)(dN,{timestampMs:e.timestampMs})]})]})}function dA({message:e,text:t}){let s=e.temporary&&"assistant"===e.summary.type&&"running"===e.summary.status;return(0,n.jsxs)(t4,{from:"assistant","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:text`,className:(0,C.cn)(dg().copyableMessage,"max-w-full gap-1"),children:[(0,n.jsx)(t6,{className:"w-full",children:(0,n.jsx)(ri,{isAnimating:s,mode:s?"streaming":"static",children:t})}),(0,n.jsx)(dS,{message:e})]})}function d$(){let{t:e}=(0,f.Bd)("conversation");return(0,n.jsxs)("div",{role:"status",className:(0,C.cn)(dg().detailText,"flex min-h-9 w-full items-center gap-2 py-1 text-muted-foreground"),children:[(0,n.jsx)(oF.A,{className:"size-4","aria-hidden":"true"}),(0,n.jsx)(o9,{as:"span",duration:1,children:e("thinking")})]})}function dR({content:e,streaming:t}){let{scrollRef:s,contentRef:r}=(0,oU.q)({initial:!!t&&"instant",resize:"instant"});return(0,n.jsx)("div",{ref:s,className:"max-h-56 overflow-y-auto pb-2 pr-2 [scrollbar-gutter:stable] sm:max-h-72",children:(0,n.jsx)("div",{ref:r,children:(0,n.jsx)(ri,{isAnimating:t,mode:t?"streaming":"static",children:e})})})}function dP({message:e,detailLoad:t}){let{t:s}=(0,f.Bd)("conversation");if("assistant"!==e.summary.type)return null;let{loading:r,error:a,load:i}=t,l=void 0!==e.detail,o=e.detail?.type==="assistant"?e.detail:null,d=o?.thinking??"",c=d.trim().length>0,u=c&&e.temporary&&"running"===e.summary.status&&0===e.summary.text.trim().length;if(!(c||!l&&e.summary.hasDetail))return null;let m=d||(r?s("thinkingLoading"):a??s("thinkingUnavailable"));return(0,n.jsxs)(dt,{className:"mb-0 w-full",isStreaming:u,onOpenChange:e=>{e&&i()},children:[(0,n.jsx)(dn,{className:(0,C.cn)(dg().detailText,"min-h-9 justify-start py-1"),getThinkingMessage:e=>e?(0,n.jsx)(o9,{as:"span",duration:1,children:s("thinking")}):(0,n.jsx)("span",{children:s("thinkingProcess")})}),(0,n.jsx)(tl.Ke,{className:(0,C.cn)(dw,"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)(dR,{content:m,streaming:u})})})})]})}function dT({message:e}){let{t}=(0,f.Bd)("conversation"),{locale:s}=(0,tp.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 re.W[t].streamInterrupted;case"request timed out":case"request timed out.":return re.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)(dg().toolOutput,"whitespace-pre-wrap break-words rounded-lg border border-destructive/40 bg-muted p-3 font-sans text-destructive"),children:r}):null}function dD({item:e,onLoadDetail:t}){let{message:s,hideAssistantText:r}=e,a=dk(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)(dP,{message:s,detailLoad:a}),r||!s.summary.text.trim()?null:(0,n.jsx)(dA,{message:s,text:s.summary.text}),(0,n.jsx)(dT,{message:s})]})}function dL({name:e,filePath:t,className:s}){let r=e.toLowerCase().split(".").at(-1)??e.toLowerCase(),a={className:s};switch(r){case"read":return t?(0,n.jsx)(o4,{path:t,...a}):(0,n.jsx)(nE.A,{...a});case"write":return(0,n.jsx)(oB.A,{...a});case"edit":return(0,n.jsx)(o_.A,{...a});case"bash":return(0,n.jsx)(v.A,{...a});case"grep":case"find":return(0,n.jsx)(e_.A,{...a});case"ls":return(0,n.jsx)(e8.A,{...a});case"agent":case"agent_resume":return(0,n.jsx)(e7.A,{...a});default:return(0,n.jsx)(e9.A,{...a})}}function dO(e){let t=e.replaceAll("\\","/");return"/"===t||/^[A-Za-z]:\/$/.test(t)?t:t.replace(/\/+$/,"")}function dF({status:e,timing:t}){let s=t&&"startedAtMs"in t?t.startedAtMs:null,a=t&&"durationMs"in t?t.durationMs:null,[i,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=a??(null===s?null:Math.max(0,i-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,a=Math.floor(n/60);return 0===a?`${r}m ${s}s`:`${a}h ${r}m ${s}s`}(o)})}function dB({message:e,onLoadDetail:t,previewPath:s,onPreviewFile:a,renderDetail:i}){let{t:l}=(0,f.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)(db),d=(0,r.useContext)(dv),c=!e.temporary&&"tool"===e.summary.type&&!!e.summary.images?.length,{open:u,expandable:m,loading:p,error:h,handleOpenChange:g}=dj(e,t),{name:x,reasoning:b,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!==a,I=s?function(e,t){let{compactPath:s,fullPath:n}=function(e,t){let s=dO(e);if(!t)return{compactPath:s,fullPath:s};let n=dO(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}/`,a=/^[A-Za-z]:\//.test(s)&&/^[A-Za-z]:\//.test(n),i=a?s.toLowerCase():s,l=a?r.toLowerCase():r;return i.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("/")?"/":""),a=s.slice(r.length).split("/").filter(Boolean),i=a.pop()??s,l=i.lastIndexOf("."),o=a.length>2?`…/${a.slice(-2).join("/")}`:`${r}${a.join("/")}`;return{fileStem:l>0?i.slice(0,l):i,fileExtension:l>0?i.slice(l):"",directory:o||null,fullPath:n}}(s,o):null;return(0,n.jsxs)(tl.Nt,{open:m&&u,onOpenChange:g,className:(0,C.cn)(dg().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)(tl.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:x}),children:[(0,n.jsx)(dL,{name:x,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:x}),b?(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-foreground",children:b}):null,y?(0,n.jsx)(dC,{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)(ti.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)(dg().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)(dg().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)(dF,{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:()=>a(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)(tl.Ke,{className:dw,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&&c&&d?(0,n.jsx)("div",{className:"px-3 pt-3",children:(0,n.jsx)(dM,{message:e,onAcquireImage:d})}):null,i({loading:p,error:h})]})})]})}function d_({children:e,destructive:t=!1}){return(0,n.jsx)("p",{className:(0,C.cn)(dg().detailText,"px-3 py-3",t?"text-destructive":"text-muted-foreground"),children:e})}function dq({message:e,loading:t,error:s}){let{t:r}=(0,f.Bd)("conversation"),a=e.detail?.type==="bash"||e.detail?.type==="tool"&&("generic"===e.detail.kind||"bash"===e.detail.kind||"codemode"===e.detail.kind)?e.detail:null,i=a?.output??"";return t?(0,n.jsx)(d_,{children:r("loadingResult")}):s?(0,n.jsx)(d_,{destructive:!0,children:s}):i?(0,n.jsx)("pre",{role:"region","aria-label":r("toolOutput"),tabIndex:0,className:(0,C.cn)(dx,dg().toolOutput,"whitespace-pre-wrap break-words px-3 py-3 font-mono"),children:i}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(d_,{children:r("emptyResult")})}function dW({message:e,loading:t,error:s}){let{t:r}=(0,f.Bd)("conversation"),a=e.detail?.type==="tool"&&"read"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(d_,{children:r("loadingRead")}):s?(0,n.jsx)(d_,{destructive:!0,children:s}):a?a.content?(0,n.jsx)("pre",{role:"region","aria-label":r("readContent"),tabIndex:0,className:(0,C.cn)(dx,dg().toolOutput,dg().toolCode,"px-3 py-3 font-mono"),children:a.content}):(0,n.jsx)(d_,{children:r("readEmpty")}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(d_,{children:r("readUnavailable")})}function dU({content:e}){let{t}=(0,f.Bd)("conversation");return(0,n.jsx)("div",{role:"region","aria-label":t("editDiff"),tabIndex:0,className:(0,C.cn)(dx,dg().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)(dg().toolCode,dg().toolCodeLine,"block px-3",s),children:e||" "},t)})})}function dY({message:e,loading:t,error:s}){let{t:r}=(0,f.Bd)("conversation"),a=e.detail?.type==="tool"&&"edit"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(d_,{children:r("loadingDiff")}):s?(0,n.jsx)(d_,{destructive:!0,children:s}):a?"diff"===a.contentKind?(0,n.jsx)(dU,{content:a.content}):(0,n.jsx)("pre",{role:"region","aria-label":r("editResult"),tabIndex:0,className:(0,C.cn)(dx,dg().toolOutput,"whitespace-pre-wrap break-words px-3 py-3 font-mono","tool"===e.summary.type&&"error"===e.summary.status&&"text-destructive"),children:a.content}):(0,n.jsx)(d_,{children:r("diffUnavailable")})}function dV({message:e,loading:t,error:s}){let{t:r}=(0,f.Bd)("conversation"),a=e.detail?.type==="tool"&&"write"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(d_,{children:r("loadingWrite")}):s?(0,n.jsx)(d_,{destructive:!0,children:s}):a?"content"!==a.contentKind||a.content?(0,n.jsx)("pre",{role:"region","aria-label":r("content"===a.contentKind?"writeContent":"writeResult"),tabIndex:0,className:(0,C.cn)(dx,dg().toolOutput,"px-3 py-3 font-mono","content"===a.contentKind?dg().toolCode:"whitespace-pre-wrap break-words","output"===a.contentKind&&"tool"===e.summary.type&&"error"===e.summary.status&&"text-destructive"),children:a.content}):(0,n.jsx)(d_,{children:r("writeEmpty")}):(0,n.jsx)(d_,{children:r("writeUnavailable")})}function dK({message:e,onLoadDetail:t}){let{t:s}=(0,f.Bd)("conversation"),{open:r,expandable:a,loading:i,error:l,handleOpenChange:o}=dj(e,t);if("tool"!==e.summary.type||"pidesk"!==e.summary.kind)throw Error("PiDeskToolView requires a pidesk summary");let d=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.every(e=>"string"==typeof e))return s;s.command=["pidesk",...t.map(l2)].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:lZ};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:lZ};let r=t[1];if("plugins"!==t[0]||!r||!["list","show","install","remove"].includes(r))return s;let a=null,i=null,l=null;for(let e=2;e<t.length;e+=1){let n=t[e];if("--scope"===n&&null===a&&"global"===t[e+1])a=t[++e];else if("--version"===n&&"install"===r&&null===l&&l1.test(t[e+1]??""))l=t[++e];else{if(!("list"!==r&&null===i&&"node_modules"!==n&&l0.test(n)))return s;i=n}}if("list"!==r&&(null===i||null===a))return s;switch(r){case"list":return{...s,label:"pideskListPlugins"};case"show":return{...s,label:"pideskShowPlugin",name:i};case"install":return{...s,label:"pideskInstallPlugin",name:i,version:l};case"remove":return{...s,label:"pideskRemovePlugin",name:i};default:return s}}(e.summary.input),c=e.detail?.type==="tool"&&"pidesk"===e.detail.kind?e.detail.output:null;return(0,n.jsx)(dp,{identity:e.identity,command:d,output:c,expandable:a,open:r,loading:i,error:l,onOpenChange:o,commandAction:(0,n.jsx)(dI,{text:d.command,copyLabel:s("pidesk.copyCommand"),alwaysVisible:!0}),outputAction:c?(0,n.jsx)(dI,{text:c,copyLabel:s("pidesk.copyOutput"),alwaysVisible:!0}):null})}function dH({message:e,onLoadDetail:t}){return(0,n.jsx)(dB,{message:e,onLoadDetail:t,previewPath:null,renderDetail:t=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(dq,{message:e,...t}),e.detail?.type==="tool"&&"codemode"===e.detail.kind&&e.detail.nestedCalls?(0,n.jsx)(dc,{nestedCalls:e.detail.nestedCalls}):null]})})}function dG({message:e,onLoadDetail:t}){return(0,n.jsx)(dH,{message:e,onLoadDetail:t})}function dJ({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)(dB,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(dW,{message:e,...t})})}function dX({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)(dB,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(dY,{message:e,...t})})}function dQ({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)(dB,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(dV,{message:e,...t})})}function dZ({message:e}){let{t}=(0,f.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)(dg().toolOutput,"rounded-lg border-l-2 bg-muted px-3 py-2 text-muted-foreground"),children:e.summary.text||t("emptyMessage")})}function d0({message:e,onLoadDetail:t}){let{t:s}=(0,f.Bd)("conversation");if("compaction"!==e.summary.type)throw Error("CompactionMessage requires a compaction summary");let{open:r,expandable:a,loading:i,error:l,handleOpenChange:o}=dj(e,t),d=e.detail?.type==="compaction"?e.detail:null;return(0,n.jsxs)(tl.Nt,{open:a&&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)(tl.R6,{disabled:!a,"aria-label":a?`${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",a?"hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring":"cursor-default"),children:[e.temporary?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin","aria-hidden":"true"}):(0,n.jsx)(oW.A,{className:"size-3.5","aria-hidden":"true"}),(0,n.jsx)("span",{children:s(e.temporary?"compactionRunning":"compactionComplete")}),a?(0,n.jsx)(ti.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)(tl.Ke,{className:dw,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:i?(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}):d?.text?(0,n.jsx)(ri,{isAnimating:!1,mode:"static",children:d.text}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:s("compactionUnavailable")})})})})})]})}let d1=(0,r.memo)(function({item:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:r}){let a=(()=>{switch(e.message.summary.type){case"assistant":return(0,n.jsx)(dD,{item:e,onLoadDetail:t});case"tool":switch(e.message.summary.kind){case"pidesk":return(0,n.jsx)(dK,{message:e.message,onLoadDetail:t});case"read":return(0,n.jsx)(dJ,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"edit":return(0,n.jsx)(dX,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"write":return(0,n.jsx)(dQ,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"bash":case"codemode":case"generic":return(0,n.jsx)(dH,{message:e.message,onLoadDetail:t})}case"bash":return(0,n.jsx)(dG,{message:e.message,onLoadDetail:t});case"custom":return(0,n.jsx)(dZ,{message:e.message});case"compaction":return(0,n.jsx)(d0,{message:e.message,onLoadDetail:t});case"user":return(0,n.jsx)(dE,{message:e.message,onAcquireImage:s})}})();return(0,n.jsx)(oO,{message:e.message,loadDetail:t,defaultView:a})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&e.onPreviewFile===t.onPreviewFile&&e.item.hideAssistantText===t.item.hideAssistantText&&d3(e.item.message,t.item.message));function d2({items:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:a}){let{scrollRef:i}=(0,lL.B)(),l=(0,r.useRef)(null),o=(0,r.useRef)(null),d=(0,r.useRef)(e.length),c=(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=i.current,s=l.current?.querySelector("[data-chat-process-item]");t&&s?.dataset.chatProcessItem&&(c.current={identity:s.dataset.chatProcessItem,offset:s.getBoundingClientRect().top-t.getBoundingClientRect().top}),m(t=>Math.min(e.length,t+64))},[h,e.length,i]);return(0,r.useLayoutEffect)(()=>{let t=d.current;d.current=e.length,u>=t&&u<e.length&&m(e.length)},[u,e.length]),(0,r.useLayoutEffect)(()=>{let e=c.current;if(!e)return;let t=i.current,s=Array.from(l.current?.querySelectorAll("[data-chat-process-item]")??[]).find(t=>t.dataset.chatProcessItem===e.identity);if(c.current=null,!t||!s)return;let n=s.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=n-e.offset},[p,i]),(0,r.useEffect)(()=>{let e=i.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,i]),(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,i)=>{let l=p+i,o=e[l-1],d=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?d?"mt-5":"mt-2":void 0,children:(0,n.jsx)(d1,{item:r,onLoadDetail:t,onAcquireImage:s,onPreviewFile:a})},r.message.identity)})]})}let d5=(0,r.memo)(function({turn:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:a}){let{t:i}=(0,f.Bd)("conversation"),[l,o]=(0,r.useState)(!1),d=(0,r.useContext)(df),c=(0,eI.t4)();(0,eI.So)();let u=e.processItems.filter(e=>!e.hideAssistantText||"pi-desk/assistant"===e.message.viewKey&&null===c.getMessageViewResolution(e.message.viewKey)),m=e.running||l,p=(0,r.useCallback)(t=>{e.running||(t&&d(),o(t))},[d,e.running]);return 0===u.length?null:(0,n.jsxs)(tl.Nt,{open:m,onOpenChange:p,className:"w-full",children:[(0,n.jsxs)(tl.R6,{className:(0,C.cn)(dg().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:[i("processGroup"),e.toolCount>0?` \xb7 ${i("toolCalls",{count:e.toolCount})}`:""]}),(0,n.jsx)(ti.A,{className:(0,C.cn)("size-4 transition-transform",m&&"rotate-180")})]}),(0,n.jsx)(tl.Ke,{className:dw,children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)(d2,{items:u,onLoadDetail:t,onAcquireImage:s,onPreviewFile:a})})})]})},(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&&d4(e.turn.processItems,t.turn.processItems));function d3(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 d4(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&&d3(e.message,n.message)})}let d6=(0,r.memo)(function({message:e,onLoadDetail:t,onAcquireImage:s}){return(0,n.jsx)(oO,{message:e,loadDetail:t,defaultView:(0,n.jsx)(dE,{message:e,onAcquireImage:s})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&d3(e.message,t.message)),d8=(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)(dA,{message:e,text:e.summary.text})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&d3(e.message,t.message)),d7=(0,r.memo)(function({turn:e,cwd:t,logicalTail:s=!1,onLoadDetail:r,onAcquireImage:a,onPreviewFile:i}){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)(d0,{message:e.compaction,onLoadDetail:r})})});let l=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)(d6,{message:e.user,onLoadDetail:r,onAcquireImage:a}):null,(0,n.jsx)(dv.Provider,{value:a,children:(0,n.jsx)(db.Provider,{value:t,children:(0,n.jsx)(d5,{turn:e,onLoadDetail:r,onAcquireImage:a,onPreviewFile:i})})}),l?(0,n.jsx)(d$,{}):null,e.finalAssistant?(0,n.jsx)(d8,{message:e.finalAssistant,onLoadDetail:r}):null]})},(e,t)=>{var s,n;return e.cwd===t.cwd&&e.logicalTail===t.logicalTail&&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&&d3(s.user,n.user)&&d3(s.finalAssistant,n.finalAssistant)&&d3(s.compaction,n.compaction)&&d4(s.processItems,n.processItems))});d7.displayName="L3ConversationTurnView";let d9={running:"statusRunning",completed:"statusCompleted",failed:"statusFailed",stopped:"statusStopped",interrupted:"statusInterrupted"};function ce(e,t){return null!==e&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}function ct(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 cs(e){return[e.taskKind,e.taskType].filter(e=>!!e).join(" / ")}function cn(e){switch(e){case"running":return(0,n.jsx)(b.A,{className:"size-4 animate-spin text-foreground"});case"completed":return(0,n.jsx)(ln.A,{className:"size-4 text-status-success"});case"failed":return(0,n.jsx)(l$.A,{className:"size-4 text-destructive"});case"interrupted":return(0,n.jsx)(lR.A,{className:"size-4 text-status-warning"});case"stopped":return(0,n.jsx)(lP.A,{className:"size-4 text-muted-foreground"})}}function cr({info:e}){let{t}=(0,f.Bd)("taskCenter"),s=(0,eC.G)(),[a,i]=(0,r.useState)(null);if(0===e.length)return null;let l=(e,n)=>{(0,tg.x)(e.value).then(r=>{r?i(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}`,i=a===r;return(0,n.jsxs)("div",{role:"button",tabIndex:0,"aria-label":t(i?"copied":"copy",{name:e.label}),title:i?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",i&&"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:i?(0,n.jsx)(ed.A,{className:"size-3.5 text-status-success"}):(0,n.jsx)(eM.A,{className:"size-3.5"})})]},`${e.label}:${s}`)})})})}function ca({snapshot:e,running:t,runtime:s,cwd:a}){let{t:i}=(0,f.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":i("conversationDetails"),children:(0,n.jsx)(oS,{turns:l,focusTurnIdentity:o?.identity??null,initialAnchor:null,children:e=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ow,{}),(0,n.jsx)(dy,{children:(0,n.jsxs)(lF,{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 i=e.startIndex+r;return(0,n.jsx)(d7,{turn:t,cwd:a,logicalTail:e.containsTail&&i===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:i("noMessages")}),(0,n.jsx)("div",{className:"h-4 shrink-0","aria-hidden":"true"})]})}),(0,n.jsx)(o$,{turns:l,window:e})]})})})}function ci({task:e,runtime:t,cwd:s}){let{t:a}=(0,f.Bd)("taskCenter"),i=(0,r.useSyncExternalStore)(t.subscribe,t.getState,t.getState),l=e?i.details[e.taskId]:void 0,[o,d]=(0,r.useState)(!1),[c,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),h=async()=>{if(!o)return void d(!0);u(!0),p(null);try{await t.interruptSelected(),d(!1)}catch(e){p(e instanceof Error?e.message:a("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:a("selectTask")});let g=cs(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:cn(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:a(d9[e.status])}),(0,n.jsx)("span",{className:"text-muted-foreground",children:ct(e,(e,t)=>a(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)(N.$,{className:"shrink-0",type:"button",size:"sm",variant:o?"destructive":"outline",disabled:c,onClick:()=>void h(),children:[c?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(lP.A,{}),o?a("confirmInterrupt"):a("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)(cr,{info:e.info})}):null,(0,n.jsxs)("div",{className:"relative min-h-0 flex-1",children:[l?.body?.kind==="conversation"?(0,n.jsx)(ca,{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||a("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:a("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:i.error?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("p",{className:"text-destructive",children:i.error}),(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",onClick:()=>t.selectTask(e.taskId),children:[(0,n.jsx)(lT.A,{}),a("retry")]})]}):(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"}),a("loadingDetail")]})})}),i.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)(b.A,{className:"size-3 animate-spin"}),a("refreshing")]}):null]})]})}function cl({source:e,tasks:t,runtime:s,cwd:a}){let{t:i}=(0,f.Bd)("taskCenter"),{locale:l,timeZone:o}=(0,tp.i)(),d=(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,d,d);let c=s.getState(),u=(0,r.useRef)(null),m=(0,r.useRef)(null),[p,h]=(0,r.useState)(!1),g=t.find(e=>e.taskId===c.selectedTaskId)??null;(0,r.useEffect)(()=>{c.open&&ce(c.source,e)&&s.reconcileTasks(e,t)},[s,e,c.open,c.source,t]);let x=p&&null!==c.selectedTaskId,b=c.open&&ce(c.source,e),v=(0,r.useRef)(null),w=(0,r.useRef)(null);return(sZ(v,b&&!x?"task-list":null),sZ(w,b?`${c.selectedTaskId??"no-task"}:${x}`:null),c.open&&ce(c.source,e)&&!("u"<typeof document))?(0,n.jsx)(eX.YV,{open:!0,onOpenChange:e=>{e||s.close()},children:(0,n.jsxs)(eX.hA,{"aria-label":i("title"),initialFocus:()=>m.current?.getClientRects().length?m.current:u.current,showCloseButton:!1,className:"h-[calc(100dvh-2rem)] max-w-[70rem] flex-row bg-background data-open:animate-none max-lg:h-dvh max-lg:max-h-dvh max-lg:w-dvw max-lg:max-w-none max-lg:rounded-none max-lg:border-0",children:[(0,n.jsxs)("div",{ref:v,className:(0,C.cn)("flex min-w-0 flex-1 flex-col border-r bg-sidebar lg:max-w-80",x&&"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)(eX.YM,{children:i("title")}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:i("recordCount",{count:t.length})})]}),(0,n.jsx)(N.$,{ref:x?void 0:u,className:"lg:hidden",type:"button",variant:"ghost",size:"icon","aria-label":i("close"),onClick:()=>s.close(),children:(0,n.jsx)(U.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=cs(e),r=ct(e,(e,t)=>i(e,{count:t})),a=od(e.startedAt,void 0,l,o);return(0,n.jsxs)("button",{type:"button","aria-current":e.taskId===c.selectedTaskId?"true":void 0,onClick:()=>{var t;return t=e.taskId,void(s.selectTask(t),h(!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===c.selectedTaskId&&"bg-accent text-accent-foreground hover:bg-accent"),children:[(0,n.jsx)("span",{className:"mt-0.5 shrink-0",children:cn(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":i("runningTime",{duration:r,time:a.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:a.compact})]})]}),t?(0,n.jsx)("span",{className:"mt-1 block truncate text-xs text-muted-foreground",children:t}):null]}),(0,n.jsx)(eo.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:i("noTasks")})})]}),(0,n.jsx)("div",{ref:w,className:(0,C.cn)("min-w-0 flex-1",!x&&"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)(N.$,{type:"button",variant:"ghost",size:"icon","aria-label":i("back"),onClick:()=>h(!1),children:(0,n.jsx)(E.A,{})}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-center text-xs text-muted-foreground",children:g?.title??i("detail")}),(0,n.jsx)(N.$,{ref:x?u:void 0,type:"button",variant:"ghost",size:"icon","aria-label":i("close"),onClick:()=>s.close(),children:(0,n.jsx)(U.A,{})})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1",children:(0,n.jsx)(ci,{task:g,runtime:s,cwd:a},g?.taskId??"no-task")})]})}),(0,n.jsx)(N.$,{ref:m,className:"absolute right-4 top-3 z-10 hidden lg:inline-flex",type:"button",variant:"ghost",size:"icon","aria-label":i("close"),onClick:()=>s.close(),children:(0,n.jsx)(U.A,{})})]})}):null}function co({source:e,cwd:t,tasks:s,runtime:r,variant:a}){let{t:i}=(0,f.Bd)("taskCenter"),l=s.filter(e=>"running"===e.status),o=l[0],d=()=>{r.open(e,(s.find(e=>"running"===e.status)??s[0]??null)?.taskId??null)};return"footer"===a?s.length>0?(0,n.jsx)(lJ,{tooltip:i("title"),"aria-label":i("open"),onClick:d,children:(0,n.jsx)(lD.A,{className:"size-4"})}):(0,n.jsx)(n.Fragment,{}):"menu"===a?(0,n.jsxs)(ex,{onClick:d,children:[(0,n.jsx)(lD.A,{className:"size-4"}),i("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:d,"aria-label":`${i("open")}, ${i("runningCount",{count:l.length})}`,children:[(0,n.jsx)(b.A,{className:"size-3.5 shrink-0 animate-spin text-foreground"}),(0,n.jsx)("span",{className:"shrink-0 font-medium text-foreground",children:i("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)(eo.A,{className:"size-3.5 shrink-0"})]}):null,(0,n.jsx)(cl,{source:e,tasks:s,runtime:r,cwd:t})]})}function cd({source:e,cwd:t,pluginState:s,runtime:a,variant:i}){let l=(0,r.useMemo)(()=>{let e=lv.safeParse(s);return e.success?e.data.tasks:[]},[s]);return(0,n.jsx)(co,{source:e,cwd:t,tasks:l,runtime:a,variant:i})}var cc=s(43663),cu=s(82078);function cm(e){return`${e.location.index}:${e.location.entryId}`}let cp={user:["viewKey","hasDetail"],assistant:["viewKey","status","hasDetail","usage"],tool:["viewKey","status","hasDetail","usage"],bash:["viewKey","status","hasDetail"],custom:["viewKey","hasDetail"]};function ch(e,t,s){if(!t)return e;let n={...e,...t};return"summary"===s?ld.Hf.parse(n):ld.D8.parse(n)}function cg(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 cx(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 cg(r,`${r.value}${s}`),ld.Hf.parse(n)}if(!Array.isArray(r.value))throw Error("Increment target is not an array");return cg(r,[...r.value,...s]),ld.Hf.parse(n)}function cf(e,t,s){let n=new Map(e.messages.filter(e=>void 0!==e.detail).map(e=>[cm(e),e]));return{messages:t.map(e=>{let t=n.get(cm(e));return e.fixed.hasDetail&&t&&t.fixed.type===e.fixed.type&&t.fixed.viewKey===e.fixed.viewKey&&void 0!==t.detail?ld.mj.parse({...e,detail:t.detail}):e}),temporaryMessages:[...s]}}function cb(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,cp[s.type],`${s.type} fixed`),ld.q5.parse({...s,...n})):s),a=ch(e.summary,t.summary,"summary"),i=e.detail;if(void 0!==t.detail||Object.keys(t.increments??{}).some(e=>"detail"===(0,cu.U)(e).root)){if(t.fixed?.hasDetail===!1)throw Error("Realtime detail cannot be updated while explicitly clearing hasDetail");r.hasDetail||(r=ld.q5.parse({...r,hasDetail:!0}))}for(let[e,s]of(t.detail&&(i=ch(i??{},t.detail,"detail")),Object.entries(t.increments??{}))){let t=(0,cu.U)(e);"summary"===t.root?a=cx(a,t.segments,s):i=cx(i??{},t.segments,s)}return r.hasDetail||(i=void 0),ld.s4.parse({location:e.location,fixed:r,summary:a,...void 0===i?{}:{detail:i}})}(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,...a}=e.temporaryMessages[s],i=ld.mj.parse({...a,location:t.durable,fixed:{...r,timestampMs:t.fixed.timestampMs},...r.hasDetail&&void 0!==n?{detail:n}:{}});return{messages:[...e.messages,i],temporaryMessages:e.temporaryMessages.filter(e=>e.location.tempId!==t.location.tempId)}}function cv(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]=ld.mj.parse({...n,...null===t.detail?{detail:void 0}:{detail:t.detail}}),{...e,messages:r}}function cw(e,t){return e.taskId!==t.taskId||e.body?.kind!=="conversation"||t.body?.kind!=="conversation"?t:lj.parse({...t,body:{kind:"conversation",truncated:t.body.truncated,...cf(e.body,t.body.messages,t.body.temporaryMessages)}})}var cy=s(56659);function ck(e){return(0,eO.B)({msg:cc.U["zh-CN"][e],i18n:{key:`taskCenter:${e}`}})}let cj=Object.freeze({open:!1,source:null,selectedTaskId:null,details:{},loading:!1,refreshing:!1,error:null});function cN(e,t){return e===t||null!==e&&null!==t&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}var cI=s(37967),cC=s(65791);let cS=s4.rh,cM=s4._g,cz=s4.eC,cE=a.Ik({workId:cI.eW,cwd:cI.ik}).strict(),cA=cE.extend({path:cS}).strict(),c$=cE.extend({query:a.Yj().trim().min(1).max(200)}).strict(),cR=cC.Ot.request.safeExtend({workId:cI.eW});cC.Ot.response;let cP=s4.p$,cT=cE.extend({path:cz,imagePreviewMode:cP}).strict();var cD=s(96981),cL=s.n(cD);function cO({mobile:e,open:t,sidebar:s,children:a,onClose:i}){let{t:l}=(0,f.Bd)("workbench"),o=(0,S.fk)(),d=(0,r.useRef)(288);return((0,r.useLayoutEffect)(()=>{if(e)return;let s=requestAnimationFrame(()=>{o.current?.resize(t?d.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:i,className:(0,C.cn)(cL().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)(cL().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}),a]}):(0,n.jsxs)(I.HK,{orientation:"horizontal",disableCursor:!0,className:(0,C.cn)(cL().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&&(d.current=n)},children:[(0,n.jsx)(I.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)(I.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)(I.wV,{id:"work-session-content",minSize:360,className:"flex h-full min-h-0 min-w-0 !overflow-hidden",children:a})]})}let cF=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 cB=s(29981),c_=s(48477),cq=s(46233),cW=s(49040),cU=s(87666),cY=s(79031);function cV(e,t){return(0,eO.B)({msg:cY.R["zh-CN"][e],i18n:{key:`workbench:${e}`,...t?{params:t}:{}}})}function cK(e){let{workId:t,sessionId:s,branchId:n}=e.source;return JSON.stringify([t,s,n,e.cwd])}function cH(e,t,s){return`${cK(e)}\u0000${s}\u0000${t}`}class cG{peek(e,t,s){let n=this.images.get(cH(e,t,s));return!n||0===n.references&&Date.now()-n.unusedAt>=6e4?null:n.url}get(e,t,s){this.trim();let n=cH(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(cK(e)))throw Error("工作会话来源已变化");let r=cH(e,t,s),a=this.images.get(r);if(a)return this.acquire(r,a);let i={url:URL.createObjectURL(n),size:n.size,references:0,unusedAt:Date.now()};return this.images.set(r,i),this.acquire(r,i)}invalidate(e,t,s){this.remove(cH(e,t,s))}reconcileWorkSessions(e){for(let t of(this.validSources=new Set(e.map(e=>cK({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 cJ{constructor(e,t,s=()=>void 0){this.biz=e,this.gitBiz=t,this.onNotice=s,this.standaloneImages=new cG,this.listeners=new Set,this.workspaces=new Map,this.sources=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}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 a=this.workspaces.get(e);a&&(a.unsubscribe(),a.files.dispose(),this.workspaces.delete(e),s=!0),this.expandedWorkId===e&&(this.expandedWorkId=null)}for(let[e,s]of(this.sources.clear(),t))this.sources.set(e,s);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())s.files.cwd===e&&s.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()))e.unsubscribe(),e.files.dispose();this.workspaces.clear(),this.sources.clear(),this.expandedWorkId=null,this.listeners.clear()}workspaceFor(e){let t=this.sources.get(e);if(!t)throw Error(cV("sourceChanged"));let s=this.workspaces.get(e);if(s)return s;let n={workId:e,cwd:t.cwd},r=new cU.h(t.cwd,{list:(e,t)=>this.biz.list({...n,path:e},t),search:(e,t)=>this.biz.search({...n,query:e},t),get:(e,t,s)=>this.biz.get({...n,path:e,imagePreviewMode:t},s),diff:(e,t,s)=>this.gitBiz.getDiff({...n,repositoryRoot:e,path:t},s)},{imagePreviewMode:rg.Wq,htmlPreview:!0,onNotice:this.onNotice,reveal:async(e,t)=>{await this.biz.reveal({...n,path:e,..."directory"===t?{targetType:t}:{}})}}),a={files:r,windowOpen:!1,chatWidthPercent:50,activePane:"files",unsubscribe:()=>void 0};return a.unsubscribe=r.subscribe(()=>{r.state.activePath||r.state.activeDiff||this.expandedWorkId===e||(a.windowOpen=!1,a.activePane="chat"),this.publish()}),this.workspaces.set(e,a),a}publish(){for(let e of(this.revision+=1,this.listeners))e()}}var cX=s(1407),cQ=s(91308),cZ=s(35616);let c0='data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/%3E';function c1({target:e,paths:t,index:s,onIndexChange:a,biz:i,images:l}){let{t:o}=(0,f.Bd)("workbench"),[d,c]=(0,r.useState)({}),u=(0,r.useRef)(new Map),m=t[s],p=d[m],h=(0,rg.Wq)(),g=l.peek(e,m,h),x=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 i.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,cy.E)(n));let a=new Image;if(a.src=t.url,await a.decode(),r.signal.aborted)return;let d=t.url;s.set(m,t),c(e=>({...e,[m]:{status:"ready",objectUrl:d}}))}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}),c(e=>({...e,[m]:{status:"error",message:s}}))}})(),()=>{r.abort(),s.get(m)!==t&&t?.release()}},[i,p,l,h,m,o,e]),(0,n.jsxs)("div",{className:"relative size-full","data-testid":"standalone-image-gallery",children:[(0,n.jsx)(nC.k,{mode:"inline",thumbnails:!1,slides:t.map(e=>{let t=d[e];return{src:t?.status==="ready"?t.objectUrl:e===m?g??c0:c0,alt:e}}),index:s,onIndexChange:a}),x?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)(N.$,{className:"pointer-events-auto",variant:"outline",onClick:()=>{l.invalidate(e,m,(0,rg.Wq)()),c(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)(b.A,{className:"size-4 animate-spin"}),o("loadingFile")]})})]})}function c2(e){return e.replaceAll("\\","/").split("/").at(-1)??e}function c5(e,t){return e instanceof Error?e.message:t}function c3({target:e,biz:t,images:s,mobile:a,onClose:i}){let{t:l}=(0,f.Bd)("workbench"),o=(0,r.useRef)(null),[d,c]=(0,r.useState)(0),[u,m]=(0,r.useState)(()=>{let t=e&&!e.imagePaths?s.peek(e,e.path,(0,rg.Wq)()):null;return t?{status:"image",objectUrl:t}:{status:"loading"}}),[p,h]=(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,a=!0,i=(0,rg.Wq)(),o=s.get(e,e.path,i);return o?o.release:(t.get({workId:e.source.workId,cwd:e.cwd,path:e.path,imagePreviewMode:i},r.signal).then(t=>{if(!a)return;if("text"===t.kind)return void m({status:"text",content:t.content,size:t.size});let r=s.store(e,e.path,i,(0,cy.E)(t));n=r.release,m({status:"image",objectUrl:r.url})}).catch(t=>{a&&!r.signal.aborted&&(console.warn("[Pi Desk][PluginStandaloneFilePreview] 读取文件失败",{workId:e.source.workId,path:e.path,error:c5(t,l("standaloneReadFailed"))}),m({status:"error",message:c5(t,l("standaloneReadFailed"))}))}),()=>{a=!1,r.abort(),n?.()})},[t,s,d,e,l]),(0,r.useEffect)(()=>{if(!e)return;let t=e=>{e.source===o.current?.contentWindow&&"pi-desk:file-escape"===e.data&&i()};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[i,e]),!e)return null;let g=e.imagePaths?.[p]??e.path,x=/\.html?$/i.test(g);return(0,n.jsx)(eX.YV,{open:!0,onOpenChange:e=>{e||i()},children:(0,n.jsxs)(eX.hA,{className:a?"inset-0 h-dvh 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)(eX.YM,{className:"sr-only",children:c2(g)}),(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.jsx)("header",{className:"flex min-h-14 shrink-0 items-center border-b pl-3 pr-14 pt-[env(safe-area-inset-top)]",children:(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("p",{className:"truncate text-sm font-semibold",title:c2(g),children:c2(g)}),(0,n.jsxs)("p",{className:"truncate text-xs text-muted-foreground",title:`${e.projectName} \xb7 ${g}`,children:[e.projectName," \xb7 ",g]})]})}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden pb-[env(safe-area-inset-bottom)]",children:e.imagePaths?(0,n.jsx)(c1,{target:e,paths:e.imagePaths,index:p,onIndexChange:h,biz:t,images:s}):"loading"===u.status?(0,n.jsx)(c4,{}):"error"===u.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:u.message}),(0,n.jsx)(N.$,{variant:"outline",onClick:()=>{s.invalidate(e,e.path,(0,rg.Wq)()),m({status:"loading"}),c(e=>e+1)},children:l("reloadFile")})]}):"image"===u.status?(0,n.jsx)(nC.k,{mode:"inline",slides:[{src:u.objectUrl,alt:e.path}],ariaLabel:l("standaloneImage",{name:c2(e.path)})}):x?(0,n.jsx)("iframe",{ref:o,className:"block size-full border-0 bg-white",sandbox:"allow-scripts",srcDoc:(0,cZ.z)(u.content),title:l("standaloneHtml",{name:e.path})}):(0,n.jsx)(cQ.e,{path:e.path,content:u.content,size:u.size,savedState:null,onSaveState:()=>void 0,onEscape:i})})]})]})})}function c4(){let{t:e}=(0,f.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)(b.A,{className:"size-4 animate-spin"}),e("loadingFile")]})}var c6=s(70788),c8=s(26844),c7=s.n(c8);let c9=(0,c6.default)(()=>Promise.all([s.e(53588),s.e(33314)]).then(s.bind(s,33314)).then(e=>e.L2FileWorkspaceView),{loadableGenerated:{webpack:()=>[33314]},ssr:!1});function ue({workSession:e,runtime:t,gitRuntime:s,mobile:a,onOpenGitBranches:i,onOpenSidebar:l,children:o}){let{t:d}=(0,f.Bd)("workbench");(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let c=(0,r.useRef)(null),u=(0,S.OG)(),m=(0,r.useRef)(null),p=(0,r.useRef)(null),h=(0,r.useRef)(null),g=(0,r.useRef)(null),x=(0,r.useRef)(null),[b,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}`,M=y?.chatWidthPercent??50,[z]=(0,r.useState)(()=>k?M:100),E=!!(y?.tabs.length||y?.activeDiff),A=b&&!a,$=A&&k,R=t.getExpandedWorkId()===w,P=k&&($||y?.activePane==="files"),T=!P||$;(0,r.useLayoutEffect)(()=>{let e=c.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?M:100,[N]:k?100-M:0})});return()=>cancelAnimationFrame(e)},[j,M,N,k,u,A]);let D=e=>{x.current=e};(0,r.useLayoutEffect)(()=>{let e=x.current;if(e&&("chat"===e?T:P)){let t,s;x.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})}},[T,P,y?.activePane]);let L=()=>{if(!E)return;let e=t.getWorkspace(w)?.activePane==="files"?"chat":"files";D(e),"files"===e?t.showWindow(w):t.setActivePane(w,"chat")};return(0,n.jsx)("div",{ref:c,"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||!E||e.target instanceof Element&&e.target.closest('[role="menu"], [data-slot="app-dialog-content"]')||(e.preventDefault(),e.stopPropagation(),L())},children:(0,n.jsxs)(I.HK,{groupRef:u,className:(0,C.cn)("pi-desk-workbench-resize-group relative size-full min-h-0 min-w-0",A?[cL().panelGroup,c7().wide]:c7().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)(I.wV,{id:j,"data-pane":"chat",defaultSize:`${z}%`,minSize:320*!!$,"aria-hidden":!T||void 0,inert:!T||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(T)})}),(0,n.jsx)(I.WM,{id:`session-file-divider-${w}`,"aria-label":d("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)(I.wV,{id:N,"data-pane":"files",defaultSize:`${100-z}%`,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:E&&!R?(0,n.jsx)(c9,{workSession:e,runtime:t,gitRuntime:s,mobile:a,presentation:A?"split":"single",onOpenGitBranches:i,onOpenSidebar:l,onHide:()=>{D("chat"),t.hideWindow(w)},onExpand:()=>t.expandWindow(w),onSwitchPane:L},`${e.sessionId}:${e.branchId}`):null})})]})})}function ut({workSessions:e,runtime:t,gitRuntime:s,mobile:a,onOpenGitBranches:i,onOpenSidebar:l,onOpenTerminal:o}){let{t:d}=(0,f.Bd)("workbench");(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let c=e.find(e=>e.workId===t.getExpandedWorkId());if(!c)return null;let u=()=>{let e=document.querySelector(`[data-work-id="${CSS.escape(c.workId)}"] textarea`);e&&(t.hideWindow(c.workId),requestAnimationFrame(()=>e.focus({preventScroll:!0})))};return(0,n.jsx)(eX.YV,{open:!0,onOpenChange:e=>{e||t.collapseExpandedWindow()},children:(0,n.jsxs)(eX.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(),u())},className:a?"inset-0 h-dvh 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(c.workId)}"]`);return e?.querySelector("[data-file-expand-trigger]")??e?.querySelector('[data-testid="session-files-entry"]')??!1},children:[(0,n.jsx)(eX.YM,{className:"sr-only",children:d("fileViewer",{name:c.projectName})}),(0,n.jsx)(c9,{workSession:c,runtime:t,gitRuntime:s,mobile:a,presentation:a?"single":"expanded",onOpenGitBranches:i,onOpenSidebar:()=>{t.collapseExpandedWindow(),l(c.workId)},onSwitchPane:u,onOpenTerminal:o,onHide:()=>t.hideWindow(c.workId),onExpand:()=>t.collapseExpandedWindow()},`${c.workId}:${c.sessionId}:${c.branchId}`)]})})}var us=s(52342);async function un(e,t,s){try{let n=await e.get({...t,imagePreviewMode:"compressed"},s);if("image"!==n.kind)throw Error("该文件不是可展示的图片");return(0,cy.E)(n)}catch(e){if(e instanceof us.aw&&"errors:fileMissing"===e.errorKey)return null;throw e}}var ur=s(17924),ua=s(85607),ui=s(68537),ul=s(76223);let uo=[];function ud(e,t){let s=t.trim().toLocaleLowerCase();return s?e.filter(e=>e.toLocaleLowerCase().includes(s)):[...e]}function uc({target:e,runtime:t,mobile:s,onClose:a}){let{t:i}=(0,f.Bd)("workbench"),{locale:l}=(0,tp.i)();(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let o=(0,eC.G)(),[d,c]=(0,r.useState)(null),[u,m]=(0,r.useState)(e?.repositoryRoot!==null),[p,h]=(0,r.useState)(""),[g,x]=(0,r.useState)(()=>({repositoryRoot:null,overrides:new Map})),[v,w]=(0,r.useState)(null),[y,k]=(0,r.useState)(!1),[j,I]=(0,r.useState)(""),[S,M]=(0,r.useState)(null),[z,A]=(0,r.useState)(null),$=t.getWorkspace(e?.cwd??null),R=$?.heads.repositories??uo,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,T=d??P;(0,r.useEffect)(()=>{e&&t.refreshHeads(e.cwd)},[t,e]),(0,r.useEffect)(()=>{if(!e||null===T||$?.heads.status!=="ready")return;let s=R.find(e=>e.root===T);s?.state==="ready"&&t.loadBranches(e.cwd,T)},[T,R,t,e,$?.heads.status]);let D=R.find(e=>e.root===T)??null,L=null===T?null:$?.branches.get(T)??null,O=L?.data??null,F=null!==T&&!!$?.branchOperations.has(T),B=(0,r.useMemo)(()=>ud(O?.local??[],p),[O?.local,p]),_=(0,r.useMemo)(()=>ud(O?.remote??[],p),[O?.remote,p]),q=(0,r.useMemo)(()=>ud(O?.recent??[],p),[O?.recent,p]),W=(0,r.useMemo)(()=>(0,ul.oY)(B),[B]),U=(0,r.useMemo)(()=>(0,ul.oY)(_),[_]),V=O?.head.type==="branch"?O.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=>{M(e),I(""),k(!0),w(null),A(null)},G=async(e,t)=>{A(null);try{await e(),o.success(t),a()}catch(e){A(e instanceof Error?e.message:i("gitOperationFailed"))}},J=R.length>1,X=1===R.length?i("repositorySummary",{name:(0,ul.Hj)(e.projectName,R[0].root),branch:"ready"===R[0].state?(0,ul.ws)(R[0].head):i("repositoryUnavailable")}):R.length>1?i("repositoryCount",{count:R.length}):i("readingRepos"),Q=(s,r,a=s.name,l=0)=>{let o="local"===s.type&&s.name===V,d=v?.type===s.type&&v.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",d&&"bg-accent"),style:{paddingLeft:`${8+16*l}px`},title:s.name,onClick:()=>w(d?null:s),children:[(0,n.jsx)("span",{className:"text-muted-foreground",children:o?(0,n.jsx)(ed.A,{className:"size-4 text-foreground"}):"remote"===s.type?(0,n.jsx)(ur.A,{className:"size-3.5"}):(0,n.jsx)(ua.A,{className:"size-3.5"})}),(0,n.jsx)("span",{className:"truncate font-mono text-sm",children:a}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:o?i("current"):"recent"===r?i("recent"):""})]}),d?(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)(N.$,{type:"button",size:"sm",variant:"outline",disabled:F,onClick:()=>{null!==T&&!F&&G(()=>t.replaceBranch(e.cwd,T,s),i("remote"===s.type?"checkedOut":"switchedBranch",{name:s.name}))},children:i("remote"===s.type?"checkoutRemote":"switchGitBranch")}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",disabled:F,onClick:()=>H(s),children:i("branchFromHere")})]}):null]},`${r}:${s.type}:${s.name}`)},Z=(e,t)=>{let s=`${e}:${t}`;return(g.repositoryRoot===T?g.overrides.get(s):void 0)??K.has(s)},ee=(e,t,s=0)=>e.map(e=>{if(0===e.children.length&&e.branchName)return Q({type:t,name:e.branchName},t,e.name,s);let r=`${t}:${e.path}`,a=!!p.trim()||Z(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":a,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=Z(e,t);x(e=>{let t=e.repositoryRoot===T?new Map(e.overrides):new Map;return t.set(s,!n),{repositoryRoot:T,overrides:t}})})(t,e.path),children:[(0,n.jsx)(eo.A,{className:(0,C.cn)("size-3 transition-transform",a&&"rotate-90")}),a?(0,n.jsx)(ui.A,{className:"size-4 text-muted-foreground"}):(0,n.jsx)(e8.A,{className:"size-4 text-muted-foreground"}),(0,n.jsx)("span",{className:"truncate font-mono text-sm",children:e.name})]}),a?ee(e.children,t,s+1):null]},r)});return(0,n.jsx)(eX.YV,{open:!0,onOpenChange:e=>!e&&a(),children:(0,n.jsxs)(eX.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)(eX.YM,{children:i("gitBranches")}),(0,n.jsx)(eX.uX,{className:"truncate text-xs",children:X})]}),(0,n.jsx)(N.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":i("refreshBranches"),disabled:$?.heads.status==="loading",onClick:()=>void t.refreshHeads(e.cwd),children:(0,n.jsx)(eE.A,{className:(0,C.cn)("size-4",$?.heads.status==="loading"&&"animate-spin")})}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:a,children:i("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:i("repositories")}),R.map(t=>{let s=(0,ul.Hj)(e.projectName,t.root),r=t.root===T;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;c(e=t.root),m(!0),h(""),x({repositoryRoot:e,overrides:new Map}),w(null),k(!1),M(null),A(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,ul.ws)(t.head):i("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)(N.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":i("backRepositories"),onClick:()=>m(!1),children:(0,n.jsx)(E.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:[D?(0,ul.Hj)(e.projectName,D.root):i("chooseRepository"),D?.state==="ready"?` \xb7 ${(0,ul.ws)(D.head)}`:""]}),(0,n.jsx)("p",{className:"mt-1 break-words font-mono text-xs text-muted-foreground",children:D?.root||"."})]}),(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",disabled:D?.state!=="ready"||F,onClick:()=>H(null),children:[(0,n.jsx)(Y.A,{className:"size-3.5"})," ",i("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,z?(0,n.jsx)("p",{className:"border-b bg-muted px-3 py-2 text-sm text-destructive",children:z}):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!==T&&!F&&G(()=>t.addBranch(e.cwd,T,n,S),i("branchCreated",{name:n}))},children:[(0,n.jsx)(eB.p,{autoFocus:!0,value:j,onChange:e=>I(e.currentTarget.value),placeholder:i("newBranchName"),"aria-label":i("newBranchName"),className:"min-w-[12rem] flex-1"}),(0,n.jsxs)(N.$,{type:"submit",size:"sm",disabled:!j.trim()||F,children:[F?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}):null,i("createAndSwitch")]}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>{k(!1),M(null)},children:i("cancel")})]}):(0,n.jsx)(eB.p,{value:p,onChange:e=>h(e.currentTarget.value),placeholder:i("searchBranches"),"aria-label":i("searchBranches")})}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-2",children:D?.state==="unavailable"?(0,n.jsx)("p",{className:"p-5 text-center text-xs text-destructive",children:(0,tm.fD)(D.message,l)}):L?.status!=="loading"||O?L?.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:L.error}),null!==T?(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void t.loadBranches(e.cwd,T),children:i("retry")}):null]}):O?(0,n.jsxs)("div",{className:"space-y-3",children:[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:i("recentlyUsed")}),q.map(e=>Q({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:i("localBranches")}),ee(W,"local")]}):null,_.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:i("remoteBranches")}),ee(U,"remote")]}):null,0===q.length&&0===B.length&&0===_.length?(0,n.jsx)("p",{className:"p-5 text-center text-xs text-muted-foreground",children:i("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)(b.A,{className:"size-4 animate-spin"})," ",i("loadingBranches")]})})]})]})]})})}function uu(e,t){return e instanceof DOMException&&"AbortError"===e.name?t:e instanceof Error?e.message:t}class um{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){let s=new Map,n=t?e.find(e=>e.workId===t)??null:null;for(let t of(n&&s.set(n.cwd,{workId:n.workId,cwd:n.cwd}),e))s.has(t.cwd)||s.set(t.cwd,{workId:t.workId,cwd:t.cwd});if(s.size!==this.projectRefs.size||[...s].some(([e,t])=>this.projectRefs.get(e)?.workId!==t.workId)){for(let[e,t]of(this.projectRefs.clear(),s))this.projectRefs.set(e,t);for(let[e,t]of this.workspaces)s.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,!1)}refreshSnapshot(e){return this.loadSnapshot(e,!0)}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:cV("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 e=await this.biz.getHeads(s,n.signal);if(t.headsRequest?.token!==r)return;t.headsRequest=null,t.heads={status:"ready",repositories:e.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:uu(e,cV("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:cV("gitNoProjectBranches")}),this.publish();return}s.branchRequests.get(t)?.controller.abort();let r=new AbortController,a={};s.branchRequests.set(t,{controller:r,token:a}),s.branches.set(t,{status:"loading",data:s.branches.get(t)?.data??null,error:null}),this.publish();try{let e=await this.biz.listBranches({...n,repositoryRoot:t},r.signal);if(s.branchRequests.get(t)?.token!==a)return;s.branchRequests.delete(t),s.branches.set(t,{status:"ready",data:e,error:null}),this.publish()}catch(e){if(s.branchRequests.get(t)?.token!==a||(s.branchRequests.delete(t),r.signal.aborted))return;s.branches.set(t,{status:"error",data:null,error:uu(e,cV("gitBranchesReadFailed"))}),this.publish()}}async replaceBranch(e,t,s){let n=this.requireProject(e),r=this.workspaceFor(e);if(!r.branchOperations.has(t)){r.branchOperations.add(t),this.publish();try{let a=await this.biz.replaceBranch({...n,repositoryRoot:t,target:s});this.applyRepository(r,a.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.requireProject(e),a=this.workspaceFor(e);if(!a.branchOperations.has(t)){a.branchOperations.add(t),this.publish();try{let i=await this.biz.addBranch({...r,repositoryRoot:t,name:s,startPoint:n});this.applyRepository(a,i.repository),this.clearBranches(a,t),this.onRepositoryChanged(e,t)}finally{a.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,t){let s=this.workspaceFor(e);if(s.snapshotRequest&&!t)return;let n=this.projectRefs.get(e);if(!n){s.snapshot={status:"error",repositories:s.snapshot.repositories,error:cV("gitNoProjectStatus")},this.publish();return}s.snapshotRequest?.controller.abort();let r=new AbortController,a={};s.snapshotRequest={controller:r,token:a},s.snapshot={status:"loading",repositories:s.snapshot.repositories,error:null},this.publish();try{let e=await this.biz.get(n,r.signal);if(s.snapshotRequest?.token!==a)return;s.snapshotRequest=null,s.snapshot={status:"ready",repositories:e.repositories,error:null};let t=new Set(e.repositories.map(e=>e.root));for(let n of(e.repositories.length>0&&!t.has("")&&t.add(""),[...s.expandedRepositories]))t.has(n)||s.expandedRepositories.delete(n);this.publish()}catch(e){if(s.snapshotRequest?.token!==a||(s.snapshotRequest=null,r.signal.aborted))return;s.snapshot={status:"error",repositories:s.snapshot.repositories,error:uu(e,cV("gitStatusReadFailed"))},this.publish()}}requireProject(e){let t=this.projectRefs.get(e);if(!t)throw Error(cV("gitNoProjectOperation"));return t}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 a="loading"===e.snapshot.status,i=[...e.snapshot.repositories],l=i.findIndex(e=>e.root===t.root);l>=0?i[l]=t:i.push(t),e.snapshot={status:"ready"===e.snapshot.status?"ready":"idle",repositories:i,error:null},a&&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 up=s(39963);let uh=up.y2,ug=a.Ik({workId:cI.eW,cwd:cI.ik}).strict(),ux=up.Ww,uf=up.cP,ub=up.zp,uv=up.u2;a.Ik({repositories:a.YO(uv).max(uh)}).strict();let uw=ug.extend({repositoryRoot:ux}).strict(),uy=up.zt,uk=ug.extend({repositoryRoot:ux,target:uy}).strict(),uj=ug.extend({repositoryRoot:ux,name:uf,startPoint:uy.nullable()}).strict(),uN=a.Ik({repository:ub}).strict(),uI=ug.extend({repositoryRoot:ux,path:s4._g}).strict();var uC=s(85887);let uS=Object.freeze({messages:[],temporaryMessages:[],runtime:{extensionMode:"normal",presentationMode:"normal",initializationError:null,queues:{steering:[],followUp:[]},model:null,capabilityMode:null,contextUsage:null,plugins:{}}});function uM(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 uz=s(57029);let uE="messages",uA="source",u$="drafts",uR="outbox",uP="pi-super-chat",uT=null,uD=null;function uL(e){return Error((0,eO.B)({msg:uz.n["zh-CN"].common[e],i18n:{key:`common:${e}`}}))}function uO(e,t){e.objectStoreNames.contains(t)||e.createObjectStore(t,{keyPath:["sessionId","branchId"]})}function uF(){return new Promise((e,t)=>{let s=indexedDB.open(uP,2),n=!1,r=window.setTimeout(()=>{a(uL("dbOpenTimeout"))},1e4),a=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("upgradeneeded",()=>{let e=s.result;e.objectStoreNames.contains(uE)||e.createObjectStore(uE,{keyPath:["sessionId","branchId","index"]}).createIndex(uA,["sessionId","branchId"],{unique:!1}),uO(e,u$),uO(e,uR)},{once:!0}),s.addEventListener("blocked",()=>{a(uL("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",()=>a(s.error??uL("dbOpenFailed")),{once:!0})})}async function uB(){try{return await uF()}catch(e){if(!("object"==typeof e&&null!==e&&"name"in e&&"VersionError"===e.name))throw e;return console.warn("[Pi Desk][ChatIndexedDB] 本地数据库版本高于当前版本,清空全部本地聊天数据后重建",{databaseName:uP,requestedVersion:2}),await new Promise((e,t)=>{let s=indexedDB.deleteDatabase(uP),n=!1,r=window.setTimeout(()=>{a(uL("dbDeleteTimeout"))},1e4),a=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("blocked",()=>{a(uL("dbDeleteBlocked"))},{once:!0}),s.addEventListener("success",()=>{n||(n=!0,window.clearTimeout(r),e())},{once:!0}),s.addEventListener("error",()=>a(s.error??uL("dbDeleteFailed")),{once:!0})}),uF()}}function u_(){return uD?Promise.resolve(uD):uT||(uT=uB().then(e=>(uD=e,e.addEventListener("versionchange",()=>{e.close(),uD===e&&(uD=null,uT=null),console.warn("[Pi Desk][ChatIndexedDB] 数据库版本已变化,当前连接已关闭")}),e)).catch(e=>{throw uT=null,e}))}function uq(e){return new Promise((t,s)=>{e.addEventListener("success",()=>t(e.result),{once:!0}),e.addEventListener("error",()=>s(e.error??uL("dbRequestFailed")),{once:!0})})}function uW(e,t,s){let n=e.target;return n?.error??t.error??Error(s)}function uU(e){return new Promise((t,s)=>{e.addEventListener("complete",()=>t(),{once:!0}),e.addEventListener("abort",t=>s(uW(t,e,uL("dbTransactionAborted").message)),{once:!0}),e.addEventListener("error",t=>s(uW(t,e,uL("dbTransactionFailed").message)),{once:!0})})}let uY=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:uC.ao,summary:uC.lV,detail:uC.wI.optional()}).strict();function uV(e,t){return uY.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 uK(e){let t=uY.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");uC.Y2.parse(t.summary),void 0!==t.detail&&uC.$f.parse(t.detail)}return uC.wR.parse({location:{index:t.index,entryId:t.entryId},fixed:t.fixed,summary:t.summary,...void 0===t.detail?{}:{detail:t.detail}})}function uH(e,t){e.delete(IDBKeyRange.bound([t.sessionId,t.branchId,0],[t.sessionId,t.branchId,Number.MAX_SAFE_INTEGER]))}let uG=a.Yj().max(65536),uJ=a.Ik({id:a.Yj().uuid(),title:uG,expiresAt:a.ai().int().nonnegative().nullable()}),uX=a.gM("method",[uJ.extend({method:a.eu("confirm"),message:uG}).strict(),uJ.extend({method:a.eu("select"),options:a.YO(uG).max(200)}).strict(),uJ.extend({method:a.eu("input"),placeholder:uG}).strict(),uJ.extend({method:a.eu("editor"),prefill:uG}).strict()]),uQ=a.Ik({requests:a.YO(uX).max(32),statuses:a.g1(a.Yj().max(128),uG),widgets:a.g1(a.Yj().max(128),a.Ik({lines:a.YO(uG).max(200),placement:a.k5(["aboveEditor","belowEditor"])}).strict())}).strict(),uZ=a.Ik({id:a.Yj().uuid(),value:a.KC([a.zM(),uG,a.ch()])}).strict(),u0=a.gM("type",[a.Ik({type:a.eu("snapshot"),snapshot:uQ}).strict(),a.Ik({type:a.eu("notify"),message:uG,level:a.k5(["info","warning","error"])}).strict(),a.Ik({type:a.eu("editor_text"),text:uG,mode:a.k5(["replace","paste"])}).strict()]),u1=a.Ik({source:lo.R}).strict(),u2=a.Ik({}).strict(),u5=Object.freeze({subscribe:(0,i.Vc)({path:"pi/ui/subscribe",inputSchema:u1,outputSchema:uQ}),unsubscribe:(0,i.Vc)({path:"pi/ui/unsubscribe",inputSchema:u1,outputSchema:u2}),respond:(0,i.Vc)({path:"pi/ui/respond",inputSchema:u1.extend({response:uZ}).strict(),outputSchema:u2}),event:(0,i._G)({path:"pi/ui/event",bodySchema:u1.extend({event:u0}).strict()})});function u3(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}class u4{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(u5.event,({source:e,event:t})=>{let s=this.records.get(u3(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(u3));for(let[e,s]of this.records)!t.has(e)&&(this.records.delete(e),this.connected&&this.socket.request(u5.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(u5.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:cV("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(cW.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:cV("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=u3(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(u3(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(u5.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:cV("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 u6=Object.freeze({...uS,syncStatus:"loading"});function u8(e){return uC.Pi.parse({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId})}function u7(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function u9(e,t){return e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}let me={text:"",images:[]};function mt(e){return[e.sessionId,e.branchId]}function ms(e,t){return{sessionId:e.sessionId,branchId:e.branchId,text:t.text,images:t.images}}function mn(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 mr(e,t){return t?{text:[e.text,t.text].filter(e=>e.trim()).join("\n\n"),images:[...e.images,...t.images]}:e}var ma=s(68607);let mi=new Set(["image/jpeg","image/png","image/webp","image/gif","image/bmp"]),ml=new Set(["image/jpeg","image/png","image/webp","image/gif"]),mo=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function md(e){return e.type.toLowerCase().split(";")[0]??""}async function mc(e){let t;try{t=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{throw Error(cV("imageDecodeFailed"))}if(!Number.isSafeInteger(t.width)||t.width<=0||t.height<=0)throw t.close(),Error(cV("imageInvalidDimensions"));return{bitmap:t,width:t.width,height:t.height}}function mu(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 mm(e,t,s,n,r){let a=document.createElement("canvas");a.width=t,a.height=s;let i=a.getContext("2d");if(!i)throw Error(cV("canvasUnavailable"));return i.drawImage(e,0,0,t,s),new Promise((e,t)=>{a.toBlob(s=>s?e(s):t(Error(cV("imageCompressFailed"))),n,r)})}async function mp(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(mo.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 mh(e){let t=md(e);if(!mi.has(t))throw Error(cV("imageTypeUnsupported"));let s=await mc(e);return s.bitmap.close(),{blob:e,mimeType:t,width:s.width,height:s.height,optimized:"image/gif"===t}}async function mg(e){if(e.optimized){if(e.blob.size>0xa00000)throw Error(cV("singleImageLimit"));return e}let t=await mc(e.blob);try{var s;let n=mu(t.width,t.height,2560),r=(s=e.mimeType,"image/jpeg"===s?"image/jpeg":"image/webp"),a=e.blob.size>5242880?.85:"image/jpeg"===r?.9:.92,i=await mm(t.bitmap,n.width,n.height,r,a),l=n.width,o=n.height,d=l!==t.width||o!==t.height,c="image/jpeg"===e.mimeType?await mp(e.blob):null,u="image/jpeg"===e.mimeType&&(null===c||c.width!==t.width||c.height!==t.height),m=ml.has(e.mimeType)&&!u;if(!d&&m&&i.size>=.9*e.blob.size&&(i=e.blob,l=t.width,o=t.height),i.size>0xa00000){let e=mu(t.width,t.height,2048);i=await mm(t.bitmap,e.width,e.height,r,.82),l=e.width,o=e.height}if(i.size>0xa00000)throw Error(cV("compressedImageTooLarge"));let p=md(i);if(!ml.has(p))throw Error(cV("compressedTypeUnsupported"));return{blob:i,mimeType:p,width:l,height:o,optimized:!0}}finally{t.bitmap.close()}}async function mx(e){if(!e.optimized)throw Error(cV("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 mf(e,t,s=e.optimized?"ready":"optimizing"){return{...e,localId:(0,ma.y)(),objectUrl:URL.createObjectURL(e.blob),name:t,status:s,error:null}}function mb(e){URL.revokeObjectURL(e.objectUrl)}function mv(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function mw(e){return{text:e.text,images:e.images.map(({blob:e,mimeType:t,width:s,height:n,optimized:r})=>({blob:e,mimeType:t,width:s,height:n,optimized:r}))}}function my(e,t){return e instanceof Error&&e.message?e.message:t}function mk(e,t){return[e,t].filter(e=>e.trim()).join("\n\n")}function mj(e,t,s){return`${mv(e)}\u0000temp\u0000${t}\u0000${s}`}function mN(e,t,s){return`${mv(e)}\u0000entry\u0000${t}\u0000${s}`}function mI(e){for(let t of e)mb(t)}var mC=s(38995),mS=s(98470),mM=s(71813),mz=s(3696),mE=s(37045);function mA(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function m$(e){return e.trim().toLocaleLowerCase()}let mR=["title","user"],mP=[{value:"title",label:"scopeTitle"},{value:"user",label:"scopeUser"},{value:"assistant",label:"scopeAssistant"},{value:"sessionId",label:"Session ID"}];function mT(e,t,s){return"title"===e?s("scopeTitle"):"sessionId"===e?"Session ID":s("user"===e?"scopeUserMatches":"scopeAssistantMatches",{count:t})}function mD(e){switch(e){case"user":case"assistant":case"title":return"bg-muted text-foreground";case"sessionId":return"bg-muted text-muted-foreground"}}function mL(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 mO({scope:e,className:t}){switch(e){case"user":return(0,n.jsx)(mC.A,{className:t});case"assistant":return(0,n.jsx)(e7.A,{className:t});case"title":return(0,n.jsx)(mS.A,{className:t});case"sessionId":return(0,n.jsx)(mM.A,{className:t})}}function mF(e,t,s="bg-primary/20 text-foreground"){if(!t)return e;let r=e.toLocaleLowerCase(),a=[],i=0,l=r.indexOf(t);for(;l>=0;){l>i&&a.push(e.slice(i,l));let o=l+t.length;a.push((0,n.jsx)("mark",{className:`rounded-sm px-px ${s}`,children:e.slice(l,o)},`${l}-${o}`)),i=o,l=r.indexOf(t,i)}return i<e.length&&a.push(e.slice(i)),a.length?a:e}function mB({open:e,pickerMode:t,pickerView:s,pickerCwd:a,directories:i,ignoredDirectories:l,directoryBrowser:o,historySessions:d,replacementTarget:c,unavailableSessionIds:u,error:m,loading:p,creatingCwd:h,replacingSessionId:g,updatingIgnoreCwd:x,onOpenChange:b,onBack:v,onSearchHistory:w,onListSessionUserMessages:y,onRefresh:k,onOpenIgnoredDirectories:j,onOpenDirectoryBrowser:I,onNavigateDirectory:C,onSelectBrowserDirectory:S,onReplaceDirectoryIgnore:M,onSelectDirectory:z,onSelectSession:A}){let{t:$}=(0,f.Bd)("workbenchPicker"),{locale:R,timeZone:P}=(0,tp.i)(),T=(0,r.useMemo)(()=>new Intl.DateTimeFormat("en"===R?"en-US":"zh-CN",{timeZone:P,month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),[R,P]),[D,L]=(0,r.useState)(""),[O,F]=(0,r.useState)(mR),[B,_]=(0,r.useState)(""),[q,W]=(0,r.useState)(null),U=(0,r.useRef)(""),Y=(0,r.useRef)(0),V=(0,r.useRef)(null),K=null!==h||null!==g||null!==x,H=(0,r.useMemo)(()=>new Set(u),[u]),G=m$(D),J=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}(B),X=/^(?:[A-Za-z]:[\\/]|[\\/]{2}|\/)/.test(J),Q="ignored"===s?l:i,Z=Q.filter(e=>!G||m$(`${mA(e.cwd)} ${e.cwd}`).includes(G)),ee=(o?.directories??[]).filter(e=>!G||m$(`${e.name} ${e.cwd}`).includes(G));(0,r.useEffect)(()=>{L(""),F(mR),_(""),U.current=""},[e,t,a,s]);let et=`${G}\u0000${O.join("\0")}`;(0,r.useEffect)(()=>{if("history"!==s||!G||et===U.current)return;let e=window.setTimeout(()=>{U.current=et,w(G,O)},300);return()=>window.clearTimeout(e)},[et,w,s,G,O]),(0,r.useEffect)(()=>{Y.current+=1,V.current?.abort(),V.current=null,W(null)},[e,a,s,G]),(0,r.useEffect)(()=>()=>{V.current?.abort()},[]);let es=async(e,t,s,n)=>{if(!a)return;let r=++Y.current;V.current?.abort();let i=new AbortController;V.current=i,W(s=>({sessionId:e,query:t,messages:n&&s?.sessionId===e?s.messages:[],page:n&&s?.sessionId===e?s.page:null,loading:!0,error:null}));try{let l=await y({cwd:a,sessionId:e,query:t,page:{index:s,size:20}},i.signal);if(Y.current!==r)return;W(s=>({sessionId:e,query:t,messages:n&&s?.sessionId===e?[...s.messages,...l.messages]:l.messages,page:l.page,loading:!1,error:null}))}catch(s){if(Y.current!==r||s instanceof Error&&"AbortError"===s.name)return;W(n=>({sessionId:e,query:t,messages:n?.sessionId===e?n.messages:[],page:n?.sessionId===e?n.page:null,loading:!1,error:s instanceof Error?s.message:$("loadUserFailed")}))}finally{V.current===i&&(V.current=null)}},en=e=>{if(q?.sessionId===e.sessionId){Y.current+=1,V.current?.abort(),V.current=null,W(null);return}let t=e.matches?.some(e=>"user"===e.scope)?G:"";es(e.sessionId,t,1,!1)},er="ignored"===s?$("ignoredRestoreTitle"):"browser"===s?$("browseOtherTitle"):"replace"===t?$("replaceTitle"):$("createTitle"),ea="ignored"===s?$("ignoredRestoreDescription"):"browser"===s?$("browseDescription"):"replace"===t?c?$("replaceDescription",{project:c.projectName,session:c.sessionTitle??$("newSession")}):$("replaceMissingDescription"):$("createDescription"),ei="history"===s?$("searchHistory"):"browser"===s?$("searchBrowser"):"ignored"===s?$("searchIgnored"):$("searchProjects"),el="history"===s?d.length:"browser"===s?o?.directories.length??0:Q.length,ed=p&&("browser"===s?null===o:0===el),ec="history"===s?$("currentProject",{path:a??""}):"ignored"===s?$("ignoredCount",{count:l.length}):"browser"===s?o?.cwd??$("rootChoose"):"replace"===t?$("replaceChooseFirst"):$("regularExcludesIgnored"),eu="history"===s?$("loadingHistory"):"ignored"===s?$("loadingIgnored"):"browser"===s?$("loadingBrowser"):$("loadingProjects"),em=e=>{L(""),_(""),C(e)},ep=()=>{p||K||!X||(L(""),C(J))};return(0,n.jsx)(eX.YV,{open:e,onOpenChange:e=>{(e||!K)&&b(e)},children:(0,n.jsxs)(eX.hA,{className:"h-[min(44rem,calc(100dvh-2rem))] max-w-[45rem]",showCloseButton:!K,finalFocus:!1,children:[(0,n.jsx)(eX.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:K,onClick:v,"aria-label":$("backFolders"),title:$("backFolders"),className:(0,N.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(E.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)(e8.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eX.YM,{children:er}),(0,n.jsx)(eX.uX,{className:"mt-1 truncate",title:ea,children:ea})]})]})}),(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)(ui.A,{className:"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(eB.p,{value:B,onChange:e=>_(e.target.value),onKeyDown:e=>{"Enter"===e.key&&X&&(e.preventDefault(),ep())},placeholder:$("pastePath"),"aria-label":$("fullPath"),disabled:p||K,className:"pl-9"})]}),(0,n.jsx)("button",{"data-testid":"workbench-picker-open-directory-path",type:"button",disabled:p||K||!X,onClick:ep,title:X?$("openTyped"):$("enterAbsolute"),className:(0,N.r)({variant:"outline"}),children:$("open")})]}),(0,n.jsx)("p",{className:"mt-1.5 px-0.5 text-sm text-muted-foreground",children:B.trim()&&!X?$("absoluteExample"):$("pasteHint")})]}):null,(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(e_.A,{className:"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(eB.p,{value:D,onChange:e=>L(e.target.value),placeholder:ei,"aria-label":ei,disabled:K,className:"pl-9"})]}),"history"===s?(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:$("searchScopes")}),mP.map(e=>{let t=O.includes(e.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:t,disabled:K||t&&1===O.length,onChange:()=>{var t;return t=e.value,void F(e=>e.includes(t)?1===e.length?e:e.filter(e=>e!==t):[...e,t])},className:"size-4 accent-primary"}),(0,n.jsx)("span",{children:$(e.label)})]},e.value)})]}):null]}),(0,n.jsx)(eX._Y,{className:"max-h-none min-h-0",children:(0,n.jsxs)("div",{className:"p-2 sm:p-3","aria-busy":p||K,"aria-live":"polite",children:[m?(0,n.jsx)("p",{role:"alert",className:"mb-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive",children:m}):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:$("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)(eE.A,{className:"size-5 animate-spin"}),(0,n.jsx)("p",{children:eu})]}):"history"===s?0===d.length?null===m?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:G?$("noHistoryMatches"):$("noReplaceHistory")}):null:(0,n.jsxs)(n.Fragment,{children:[G?(0,n.jsx)("p",{className:"px-3 pb-1 pt-0.5 text-xs text-muted-foreground",children:$("sessionFound",{count:d.length})}):null,(0,n.jsx)("div",{className:"divide-y",children:d.map(e=>{let t,s=e.name?.trim()||e.firstMessage.trim()||$("sessionFallback",{id:e.sessionId.slice(0,8)}),r=$("sessionMessages",{users:e.userMessageCount,total:e.messageCount,time:(t=e.updatedAt,T.format(t))}),a=c?.sessionId===e.sessionId,i=H.has(e.sessionId),l=g===e.sessionId,o=null===c,d=K||a||i||o,u=q?.sessionId===e.sessionId?q:null,m=e.matches??[],p=m.filter(e=>"title"!==e.scope),h=m.find(e=>"user"===e.scope),x=null===u&&p.length>0,f=`workbench-picker-user-message-panel-${e.sessionId}`,b=l?$("replacing"):a?$("current"):i?$("alreadyUsed"):o?$("targetUnavailable"):$("replace"),v=a?$("currentBound"):i?$("historyUsed"):o?$("replaceTargetUnavailable"):$("replaceWith",{name:s}),w=u?$("hideUserMessages"):h?$("viewMatching",{count:h.count}):$("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)(mz.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)?mF(s,G,mL("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:K,"aria-label":w,"aria-expanded":null!==u,"aria-controls":f,onClick:()=>en(e),title:w,className:(0,N.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(ti.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:()=>A(e.sessionId),title:v,className:(0,N.r)({variant:"outline"}),children:l?(0,n.jsx)(eE.A,{className:"size-3.5 animate-spin"}):b})]}),x?(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,a=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(mO,{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 ${mD(t.scope)}`,children:mT(t.scope,t.count,$)}),null!==t.timestampMs?(0,n.jsx)("span",{className:"truncate text-muted-foreground",children:(s=t.timestampMs,T.format(s))}):null]}),(0,n.jsx)("p",{className:"mt-1 line-clamp-2 break-words text-sm leading-5 text-foreground",children:mF(t.preview,G,mL(t.scope))})]})]}),i=`flex w-full max-w-full min-w-0 items-start gap-2 overflow-hidden rounded-md px-2.5 py-2 text-left ${mD(t.scope)}`;return r?(0,n.jsx)("button",{"data-testid":`workbench-picker-user-message-preview-${e.sessionId}`,type:"button",disabled:K,onClick:()=>en(e),"aria-label":$("viewMatch",{label:mT(t.scope,t.count,$)}),className:`${i} outline-none transition-colors hover:brightness-95 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50`,children:a},t.scope):(0,n.jsx)("div",{className:i,children:a},t.scope)})}):null,u?(0,n.jsxs)("div",{id:f,"data-testid":f,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)(mE.A,{className:"size-3.5 shrink-0 text-primary"}),(0,n.jsx)("span",{className:"truncate",children:u.query?$("matchingUserCount",{count:u.page?.total??0}):$("userCount",{count:u.page?.total??e.userMessageCount})})]}),u.query?(0,n.jsx)("button",{type:"button",disabled:u.loading||K,onClick:()=>void es(e.sessionId,"",1,!1),className:(0,N.r)({variant:"ghost",size:"sm"}),children:$("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)(eE.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:$("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,T.format(t))}),(0,n.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-sm leading-6",children:e.text?mF(e.text,u.query):$("noText")})]},e.entryId)})}),y?(0,n.jsxs)("button",{type:"button",disabled:u.loading||K,onClick:()=>void es(e.sessionId,u.query,(u.page?.index??0)+1,!0),className:(0,N.r)({variant:"outline",className:"mt-2"}),children:[u.loading?(0,n.jsx)(eE.A,{className:"size-3.5 animate-spin"}):null,$("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)(ui.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",title:o?.cwd??$("root"),children:o?.cwd??$("root")})]}),0===ee.length?null===m?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:(o?.directories.length??0)===0?o?.cwd?$("browserEmpty"):$("rootsEmpty"):$("subfoldersNoMatches")}):null:(0,n.jsx)("div",{className:"divide-y",children:ee.map(e=>(0,n.jsxs)("button",{type:"button",disabled:p||K,onClick:()=>em(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)(e8.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)(eo.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-foreground"})]},e.cwd))})]}):0===Z.length?null===m?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:0===Q.length?"ignored"===s?$("ignoredEmpty"):$("projectsEmpty"):$("projectNoMatches")}):null:"ignored"===s?(0,n.jsx)("div",{className:"divide-y",children:Z.map(e=>{let t=mA(e.cwd),s=x===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)(e8.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:K,onClick:()=>M(e.cwd,!1),"aria-label":$("restoreFolder",{name:t}),title:$("restoreTip"),className:(0,N.r)({variant:"outline"}),children:[s?(0,n.jsx)(eE.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(lT.A,{className:"size-3.5"}),(0,n.jsx)("span",{children:$("restore")})]})]},e.cwd)})}):(0,n.jsx)("div",{className:"divide-y",children:Z.map(e=>{let s,r=mA(e.cwd),a=$("directorySessions",{count:e.sessionCount,time:(s=e.updatedAt,T.format(s))}),i=h===e.cwd,l=x===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:K,onClick:()=>z(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)(e8.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})]}),i?(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)(eE.A,{className:"size-3.5 animate-spin"}),$("creating")]}):(0,n.jsxs)("span",{className:"flex shrink-0 items-center gap-1 text-xs text-muted-foreground",title:a,children:[(0,n.jsx)("span",{children:$("directoryCount",{count:e.sessionCount})}),(0,n.jsx)(eo.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:K,onClick:()=>M(e.cwd,!0),"aria-label":$("ignoreFolder",{name:r}),title:$("ignoreTip"),className:(0,N.r)({variant:"ghost",size:"icon"}),children:l?(0,n.jsx)(eE.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(ii.A,{className:"size-4"})}):null]},e.cwd)})})]})}),(0,n.jsxs)(eX.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:ec,children:ec}),(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:p||K,onClick:j,className:(0,N.r)({variant:"outline"}),children:$("ignoredFolders")}),(0,n.jsx)("button",{type:"button",disabled:p||K,onClick:I,className:(0,N.r)({variant:"outline"}),children:$("chooseOther")})]}):null,"browser"===s&&o?.cwd?(0,n.jsx)("button",{"data-testid":"workbench-picker-select-browser-directory",type:"button",disabled:p||K,onClick:()=>S(o.cwd),className:(0,N.r)(),children:$("selectCurrent")}):null,"browser"===s&&o?.parentCwd?(0,n.jsx)("button",{type:"button",disabled:p||K,onClick:()=>em(o.parentCwd),"aria-label":$("parentDirectory"),title:$("parentDirectory"),className:(0,N.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(E.A,{className:"size-4"})}):null,"browser"===s&&o?.cwd?(0,n.jsx)("button",{type:"button",disabled:p||K,onClick:()=>em(null),"aria-label":$("backRoots"),title:$("backRoots"),className:(0,N.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(ui.A,{className:"size-4"})}):null,(0,n.jsx)("button",{"data-testid":"workbench-picker-refresh",type:"button",disabled:p||K,onClick:()=>k(G,O),"aria-label":$("refreshList"),title:$("refreshList"),className:(0,N.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(eE.A,{className:`size-4${p?" animate-spin":""}`})})]})]})]})})}let m_="pi-super:workbench-layout";function mq(e,t,s=[]){let n=new Set(t.map(e=>e.workId)),r=new Set(s),a=e.primaryWorkId&&n.has(e.primaryWorkId)&&!r.has(e.primaryWorkId)?e.primaryWorkId:null;return e.primaryWorkId===a?e:{primaryWorkId:a}}function mW({variant:e,className:t,children:s}){let{t:r}=(0,f.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)(b.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 mU=s(58911),mY=s(58013),mV=s(54081),mK=s(22157);let mH=new Set(["custom","model_change","thinking_level_change","session_info","label"]),mG=[],mJ=[{value:"default",label:"filterDefault"},{value:"no-tools",label:"filterNoTools"},{value:"user-only",label:"filterUserOnly"},{value:"labeled-only",label:"filterLabeled"},{value:"all",label:"filterAll"}],mX={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 mQ(e){switch(e.action){case"tree":return"treeIntent";case"fork":return"forkIntent";case"clone":return"cloneIntent"}}function mZ(e){e.preventDefault()}function m0({confirmation:e,disabled:t,onConfirm:s,onBack:a}){let{t:i}=(0,f.Bd)("workbenchPicker"),[l,o]=(0,r.useState)(0),d=(0,r.useRef)(new Map);(0,r.useEffect)(()=>{d.current.get(0)?.focus()},[]);let c=n=>{e.waiting||t&&0===n||(0===n?s():a())};return(0,n.jsxs)("div",{className:"p-3 sm:p-4",onKeyDown:e=>{if(e.stopPropagation(),"Escape"===e.key){e.preventDefault(),a();return}if("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key){e.preventDefault();let t=+(0===l);o(t),queueMicrotask(()=>d.current.get(t)?.focus());return}"Enter"===e.key&&(e.preventDefault(),c(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:i("runningTitle")}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:"main"===e.reason?i("runningStop",{action:i(mQ(e.intent))}):i("runningWait",{action:i(mQ(e.intent))})})]}),(0,n.jsx)("div",{className:"mt-3 grid grid-cols-2 gap-2",children:[{label:i(e.waiting?"confirming":"confirmContinue"),confirm:!0},{label:i("back"),confirm:!1}].map((s,r)=>(0,n.jsxs)("button",{ref:e=>{e?d.current.set(r,e):d.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:()=>c(r),children:[e.waiting&&s.confirm?(0,n.jsx)(b.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:i("confirmHint")})]})}function m1({model:e,projectName:t,sessionTitle:s,mobile:a,onClose:i,onRetry:l,onSelectEntry:o,onAction:d,onConfirmRunning:c,onCancelRunning:u}){let{t:m}=(0,f.Bd)("workbenchPicker"),p=(0,mK.tF)(),h=(0,sV.I)(),{locale:g,timeZone:x}=(0,tp.i)(),v=(0,r.useMemo)(()=>new Intl.DateTimeFormat("en"===g?"en-US":"zh-CN",{timeZone:x,timeZoneName:"shortOffset",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}),[g,x]),[w,y]=(0,r.useState)(""),[k,j]=(0,r.useState)("default"),[I,S]=(0,r.useState)(!1),[M,z]=(0,r.useState)(()=>new Set),[E,A]=(0,r.useState)(null),[$,R]=(0,r.useState)(0),[P,T]=(0,r.useState)(480),D=(0,r.useRef)(null),L=(0,r.useRef)(null),O=(0,r.useRef)(null),F=(0,r.useRef)(null),B=(0,r.useRef)(!1),_=e.tree?.nodes??mG,q=(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!mH.has(e.kind);case"no-tools":return!mH.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,a=new Map;for(let e of t.values()){if(!n.has(e.node.entryId))continue;let s=e.node.parentEntryId,i=new Set;for(;s&&!n.has(s);){if(i.has(s)){s=null;break}i.add(s),s=t.get(s)?.node.parentEntryId??null}s===e.node.entryId&&(s=null),a.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 i=[],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 d=r.get(o)??[],c=a.get(o)??null,u=null===c?[]:r.get(c)??[],m=d.length>0&&(null===c||u.length>1),p=!m||!e.foldedEntryIds.has(o);if(i.push({node:t.indexed.node,depth:t.depth,active:s.has(o),current:o===e.leafEntryId,hasChildren:d.length>0,foldable:m,expanded:p,connector:t.connector,lastSibling:t.lastSibling,visibleParentEntryId:a.get(o)??null}),!p)continue;let h=d.length>1;for(let[e,s]of[...d].reverse().entries()){let r=d.length-e-1;n.push({indexed:s,depth:t.depth+ +!!h,connector:h,lastSibling:r===d.length-1})}}})(r.get(null)??[]),i})({nodes:_,leafEntryId:e.tree?.leafEntryId??null,filter:k,query:w,foldedEntryIds:M}),[k,M,e.tree?.leafEntryId,_,w]),W=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])),a=s,i=new Set;for(;a&&!i.has(a);){if(n.has(a))return a;i.add(a),a=r.get(a)?.parentEntryId??null}return t.at(-1)?.node.entryId??null}(_,q,E??e.tree?.leafEntryId??null),Y=q.findIndex(e=>e.node.entryId===W),V=Y>=0?q[Y]:null,K=Math.max(0,Math.floor($/36)-8),H=Math.min(q.length,Math.ceil(($+P)/36)+8),G=Math.min(q.length,Math.max(H,K+8)),J=q.slice(K,G),X=e.detail?.entryId===W?e.detail:null,Q=m(mJ.find(e=>e.value===k)?.label??"filterDefault"),Z=e.runningConfirmation,ee=`work-session-branch-tree-${e.workId}`,et=W?`${ee}-entry-${W}`:void 0,es=(0,r.useCallback)(()=>{a?L.current?.focus({preventScroll:!0}):D.current?.focus({preventScroll:!0})},[a]),en=(0,r.useCallback)(t=>{e.pending||(B.current=t,i())},[e.pending,i]);(0,r.useEffect)(()=>{if(p)return F.current=document.activeElement instanceof HTMLElement?document.activeElement:null,B.current=!1,queueMicrotask(es),()=>{B.current&&F.current?.focus({preventScroll:!0})}},[es,p]),(0,r.useEffect)(()=>{p&&!Z&&queueMicrotask(es)},[Z,es,p]),(0,r.useEffect)(()=>{if(!p)return;let t=t=>{if(e.pending)return;let s=t.target;!(s instanceof Node)||L.current?.contains(s)||s instanceof Element&&s.closest('[data-workbench-branch-picker-popup="true"]')||en(!1)};return document.addEventListener("pointerdown",t,!0),()=>document.removeEventListener("pointerdown",t,!0)},[e.pending,p,en]),(0,r.useEffect)(()=>{let e=O.current;if(!e)return;let t=new ResizeObserver(([e])=>{T(e?.contentRect.height??0)});return t.observe(e),()=>t.disconnect()},[Z]),(0,r.useEffect)(()=>{if(!p||!W||Z)return;o(W);let e=O.current;if(!e||Y<0)return;let t=36*Y,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(()=>R(n))},[Z,W,o,p,36,Y]);let er=(0,r.useCallback)(e=>{O.current&&(O.current.scrollTop=e),R(e)},[]),ea=(0,r.useCallback)(e=>{if(0===q.length)return;let t=Math.max(0,Math.min(q.length-1,e));A(q[t].node.entryId);let s=O.current;if(!s)return;let n=36*t,r=n+36,a=s.scrollTop;n<s.scrollTop?a=n:r>s.scrollTop+s.clientHeight&&(a=r-s.clientHeight),er(a)},[36,q,er]),ei=(0,r.useCallback)((e,t)=>{z(s=>{let n=new Set(s);return t??!n.has(e)?n.add(e):n.delete(e),n})},[]),el=(0,r.useCallback)(e=>{j(e),z(new Set),er(0),queueMicrotask(es)},[es,er]),ed=(0,r.useCallback)(e=>{let t=(mJ.findIndex(e=>e.value===k)+e+mJ.length)%mJ.length;el(mJ[t].value)},[el,k]),eu=(0,r.useCallback)((t,s)=>{e.actionsDisabled||(B.current=!1,d(t,s))},[e.actionsDisabled,d]),eh=(0,r.useCallback)(()=>{!V||V.current||e.pending||eu(V.node.entryId,"tree")},[e.pending,eu,V]),eg=(0,r.useCallback)(()=>{if(!V?.visibleParentEntryId)return;let e=q.findIndex(e=>e.node.entryId===V.visibleParentEntryId);e>=0&&ea(e)},[q,ea,V]),ef=(0,r.useCallback)(()=>{if(!V)return;let e=q.findIndex(e=>e.visibleParentEntryId===V.node.entryId);e>=0&&ea(e)},[q,ea,V]),eb=V?.node??null,ev=eb?mX[eb.kind]:null,ew=Z?a?"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":a?"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)(o8.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)(o8.PY1.section,{ref:L,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",ew),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")}),Z?null:(0,n.jsxs)("span",{className:"shrink-0 text-xs text-muted-foreground",children:[Y>=0?Y+1:0," / ",q.length]}),(0,n.jsx)("button",{type:"button",disabled:e.pending,"aria-label":m("closeBranchPicker"),className:(0,N.r)({variant:"ghost",size:"icon"}),onClick:()=>en(!0),children:(0,n.jsx)(U.A,{className:"size-4"})})]}),Z?null:(0,n.jsxs)("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)(e_.A,{className:"pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(eB.p,{ref:D,role:"combobox",value:w,"aria-label":m("branchSearch"),"aria-controls":ee,"aria-expanded":"true","aria-activedescendant":et,placeholder:m("branchSearchPlaceholder"),className:"pl-7",onChange:e=>{y(e.currentTarget.value),z(new Set),er(0)},onKeyDown:e=>{if(!e.nativeEvent.isComposing)switch(e.stopPropagation(),e.key){case"Tab":e.preventDefault(),ed(e.shiftKey?-1:1);return;case"ArrowUp":e.preventDefault(),ea(Y-1);return;case"ArrowDown":e.preventDefault(),ea(Y+1);return;case"PageUp":e.preventDefault(),ea(Y-Math.max(1,Math.floor(P/36)));return;case"PageDown":e.preventDefault(),ea(Y+Math.max(1,Math.floor(P/36)));return;case"ArrowLeft":if(w||!V)return;e.preventDefault(),V.foldable&&V.expanded?ei(V.node.entryId,!0):eg();return;case"ArrowRight":if(w||!V)return;e.preventDefault(),V.foldable&&!V.expanded?ei(V.node.entryId,!1):ef();return;case"Enter":e.preventDefault(),eh();return;case"Escape":e.preventDefault(),w?(y(""),z(new Set),er(0)):en(!0);return}}})]}),(0,n.jsxs)(ec,{open:I,onOpenChange:S,onOpenChangeComplete:e=>{e||queueMicrotask(es)},children:[(0,n.jsxs)(em,{render:(0,n.jsx)("button",{type:"button","aria-label":m("branchFilter",{filter:Q}),className:(0,N.r)({variant:"outline"})}),children:[Q,(0,n.jsx)(ti.A,{className:"size-3.5"})]}),(0,n.jsx)(ep,{"data-workbench-branch-picker-popup":"true",align:"end",side:"bottom",className:"w-32",finalFocus:()=>a?L.current:D.current,children:mJ.map(e=>(0,n.jsxs)(ex,{onClick:()=>el(e.value),children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:m(e.label)}),k===e.value?(0,n.jsx)("span",{className:"text-xs text-primary",children:"●"}):null]},e.value))})]})]})]}),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)(N.$,{type:"button",size:"sm",variant:"outline",disabled:e.actionsDisabled,onClick:l,children:m("retry")})]})}):null,Z?(0,n.jsx)(m0,{confirmation:Z,disabled:e.actionsDisabled,onConfirm:c,onBack:()=>{B.current=!0,u()}},`${Z.intent.action}:${"entryId"in Z.intent?Z.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:eb&&ev?(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:ev.labelClassName,children:m(ev.label)}),eb.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:eb.label}):null,(0,n.jsx)("time",{className:"ml-auto shrink-0",children:v.format(eb.timestampMs)})]}),(0,n.jsx)("div",{className:"mt-2 whitespace-pre-wrap break-words text-sm leading-6",children:e.detailLoading||!X?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)(b.A,{className:"size-3.5 animate-spin"}),m("loadingEntry")]}):(0,n.jsxs)(n.Fragment,{children:[X.content||m("entryEmpty"),X.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")})}),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)(b.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)(b.A,{className:"size-4 animate-spin"}),m("branchLoading")]})}):0===q.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===_.length?m("branchEmpty"):m("branchNoMatches")}):(0,n.jsxs)("div",{ref:O,id:ee,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=>R(e.currentTarget.scrollTop),children:[(0,n.jsx)("div",{style:{height:`${36*K}px`},"aria-hidden":"true"}),J.map(t=>{let s=t.node.entryId===W,r=Math.min(t.depth,10),i=mX[t.node.kind];return(0,n.jsxs)("div",{id:`${ee}-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",i.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:mZ,onClick:()=>{ei(t.node.entryId),queueMicrotask(es)},children:(0,n.jsx)(eo.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:mZ,onClick:()=>{A(t.node.entryId),queueMicrotask(es)},onDoubleClick:()=>{a||t.current||eu(t.node.entryId,"tree")},children:[(0,n.jsx)("span",{className:(0,C.cn)("w-9 shrink-0 text-xs",i.labelClassName),children:m(i.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",i.contentClassName,s&&"font-semibold text-accent-foreground"),children:t.node.preview||m("noPreview")})]}),a?(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(i.label)}),className:(0,N.r)({variant:"secondary",size:"sm"}),onClick:()=>eu(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,N.r)({variant:"outline",size:"sm"}),onClick:()=>eu(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,N.r)({variant:"ghost",size:"sm"}),onMouseDown:mZ,onClick:()=>eu(t.node.entryId,"fork"),children:"Fork"})}):null]},t.node.entryId)}),(0,n.jsx)("div",{style:{height:`${36*Math.max(0,q.length-G)}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:[Y>=0?Y+1:0," / ",q.length,a?"":` \xb7 ${m("branchShortcuts")}`]}),a?null:(0,n.jsx)(N.$,{type:"button",size:"sm",disabled:e.actionsDisabled||!V||V.current||e.loading||e.pending,onMouseDown:mZ,onClick:eh,children:m("switch")})]})]})]})]})}var m2=s(97556),m5=s(78680),m3=s(29280),m4=s(3240),m6=s(92151),m8=s(69492),m7=s(56299),m9=s(7997),pe=s.n(m9);function pt({state:e,powerSaving:t}){let s=(0,r.useRef)(null);return((0,r.useLayoutEffect)(()=>{let n=s.current;if(!n||t||"idle"===e)return;let r="completed"===e?30:14,a=n.animate([{strokeDashoffset:r},{strokeDashoffset:r-100}],{duration:6e3,iterations:1/0,easing:"linear"}),i=!0,l=()=>{document.hidden||!i?a.pause():(a.play(),a.startTime=0)},o=new IntersectionObserver(([e])=>{i=e.isIntersecting,l()});return o.observe(n),document.addEventListener("visibilitychange",l),l(),()=>{o.disconnect(),document.removeEventListener("visibilitychange",l),a.cancel()}},[t,e]),t||"idle"===e)?null:(0,n.jsx)("svg",{"aria-hidden":"true",focusable:"false","data-testid":"work-session-status-border","data-state":e,className:pe().statusBorder,children:(0,n.jsx)("rect",{ref:s,x:"1",y:"1",pathLength:"100"})})}function ps(e){return{"--pi-desk-project-color":function(e){let t=e.replaceAll("\\","/").toLowerCase(),s=0x811c9dc5;for(let e=0;e<t.length;e+=1)s^=t.charCodeAt(e),s=Math.imul(s,0x1000193);let n=(s>>>0)%360;return`oklch(var(--project-color-lightness, 0.49) var(--project-color-chroma, 0.1) ${n})`}(e)}}function pn(e){return{className:pe().surface,style:ps(e)}}var pr=s(6726),pa=s.n(pr);function pi({workSession:e,runtime:t,active:s,chatReady:a,onOpen:i}){let{t:l}=(0,f.Bd)("workbench"),{locale:o}=(0,tp.i)();(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let d=t.getWorkspace(e.cwd)?.heads;(0,r.useEffect)(()=>{let n;if(!s||!a)return;let r=()=>{window.clearTimeout(n),n=void 0},i=()=>{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 i(),window.addEventListener("focus",i),window.addEventListener("blur",r),document.addEventListener("visibilitychange",l),()=>{r(),window.removeEventListener("focus",i),window.removeEventListener("blur",r),document.removeEventListener("visibilitychange",l)}},[s,a,t,e.cwd]);let c=d?.repositories??[],u=(0,ul.A_)(e.projectName,c,o);if(d?.status==="ready"&&!u)return null;let m=d?.status==="loading"&&!u,p=d?.status==="error"&&!u,h=m?null:u;return(0,n.jsxs)(lJ,{"data-testid":"composer-git-branch",tooltip:p?d.error??l("gitStatusReadFailed"):h?.title??l("gitBranches"),"aria-label":l("gitBranches"),className:pa().branchTrigger,disabled:m,onClick:()=>i({workId:e.workId,cwd:e.cwd,projectName:e.projectName,repositoryRoot:null}),children:[m?(0,n.jsx)(b.A,{className:"size-4 shrink-0 animate-spin"}):(0,n.jsx)(ua.A,{className:"size-4 shrink-0 text-emerald-600 dark:text-emerald-400"}),p?(0,n.jsx)("span",{className:(0,C.cn)(pa().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)(pa().branchFull,h.diverged&&"text-amber-600 dark:text-amber-400"),children:h.full})}):null]})}let pl="l2-workbench-slash-command-menu",po={key:"builtin:reload",name:"reload",description:"重新读取 Pi 最新配置与扩展资源",source:"builtin"},pd=[{source:"builtin",label:"Pi 内置命令"},{source:"skill",label:"Skills"},{source:"prompt",label:"提示模板"},{source:"extension",label:"扩展命令"}];function pc(e){return`${pl}-option-${e}`}function pu(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function pm(e){return[...e.children].filter(e=>e instanceof HTMLElement)}function pp(e,t,s){return e.reduce((e,t)=>e+(s.get(t)??0),0)+Math.max(0,e.length-1)*t}var ph=s(7638);let pg=2*Math.PI*7;function px(e){if(null===e)return"--";let t=Math.round(e);return t<1e3?String(t):`${Math.round(t/100)/10}K`}function pf(e){return Math.min(100,Math.max(0,e))}function pb(e){return pg-e/100*pg}function pv({sessionId:e,cwd:t,tokens:s,contextWindow:a,contextIgnorePlugin:i,ignoreDisabled:l,ignorePending:o,compactDisabled:d,compactPending:c,onIgnoreContext:u,onCompactContext:m}){let p,h,g,x,v,{t:w}=(0,f.Bd)("workbench"),y=(0,r.useId)(),k=(0,r.useRef)(!1),[j,I]=(0,r.useState)(!1),[S,M]=(0,r.useState)(!1),[z,E]=(0,r.useState)(!1),A=(0,eC.G)(),$=(p=!i||"object"!=typeof i||Array.isArray(i)||"number"!=typeof i.ignoredTokens||!Number.isFinite(i.ignoredTokens)||i.ignoredTokens<0||"number"!=typeof i.potentialTokens||!Number.isFinite(i.potentialTokens)||i.potentialTokens<0||void 0!==i.effectiveTokens&&null!==i.effectiveTokens&&("number"!=typeof i.effectiveTokens||!Number.isFinite(i.effectiveTokens)||i.effectiveTokens<0)?null:{ignoredTokens:i.ignoredTokens,potentialTokens:i.potentialTokens,...void 0!==i.effectiveTokens?{effectiveTokens:i.effectiveTokens}:{}},g=null===(h=p?.effectiveTokens===void 0?s:p.effectiveTokens)?0:pf(h/a*100),v=null===(x=null===h||null===p?null:Math.max(0,h-p.potentialTokens))?null:pf(x/a*100),{contextIgnore:p,currentTokens:h,usedPercent:g,projectedTokens:x,projectedPercent:v,potentialSegmentPercent:null===v?0:Math.max(0,g-v)}),R=Math.round($.usedPercent),P=null===$.projectedPercent?null:Math.round($.projectedPercent),T=R>=90?"text-destructive":R>=80?"text-status-warning":"text-muted-foreground",D=R>=90?"bg-destructive":R>=80?"bg-status-warning":"bg-primary",L=$.contextIgnore?w("contextUsageWithIgnore",{percent:R,projected:P??0,ignored:px($.contextIgnore.ignoredTokens),potential:px($.contextIgnore.potentialTokens)}):w("contextUsageSimple",{percent:R,limit:px(a)});return(0,n.jsxs)(lY,{open:j,triggerId:y,onOpenChange:(e,t)=>{k.current&&"trigger-focus"===t.reason||(e||(M(!1),E(!1)),I(e))},children:[(0,n.jsx)(lV,{id:y,delay:100,closeDelay:100,render:(0,n.jsx)("button",{type:"button","aria-label":L,"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(),I(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:pg,strokeDashoffset:pb($.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:pg,strokeDashoffset:pb($.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:pg,strokeDashoffset:pb($.usedPercent),className:T}):null]})})}),(0,n.jsx)(lK,{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:[px($.currentTokens)," / ",px(a)," / ",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",D),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:[px($.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:px($.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:px($.contextIgnore.ignoredTokens)})]})]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:[(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",disabled:l||o||!$.contextIgnore||$.contextIgnore.potentialTokens<=0,"aria-label":$.contextIgnore&&$.contextIgnore.potentialTokens>0?w("ignoreNow",{amount:px($.contextIgnore.potentialTokens)}):w("nothingToIgnore"),"aria-busy":o,onClick:()=>void u(),children:[o?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(ph.A,{}),o?w("ignoring"):w("ignore")]}),(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",disabled:d||c,"aria-busy":c,onClick:()=>void m(),children:[c?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(oW.A,{}),c?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,tg.x)(e).then(e=>{e?M(!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)(ed.A,{className:"size-3.5"}):(0,n.jsx)(eM.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,tg.x)(t).then(e=>{e?E(!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:[z?w("copied"):w("clickToCopy"),z?(0,n.jsx)(ed.A,{className:"size-3.5"}):(0,n.jsx)(eM.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 pw(e,t){let[s,n]=(0,r.useState)({value:null,loading:!1,error:null}),[a,i]=(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}},[a,e,t]),{...s,retry:()=>i(e=>e+1)}}let py={direct:["toolExposureDirect","直接使用"],"model-only":["toolExposureModelOnly","仅模型调用"],codemode:["toolExposureCodemode","通过脚本调用"],deferred:["toolExposureDeferred","按需发现"],hidden:["toolExposureHidden","不可调用"]};function pk({tools:e}){let{t}=(0,f.Bd)("workbench"),[s,a]=(0,r.useState)(""),[i,l]=(0,r.useState)("all"),o=s.trim().toLocaleLowerCase(),d=e.filter(e=>(!o||`${e.name} ${e.source??""} ${e.description}`.toLocaleLowerCase().includes(o))&&("all"===i||("blocked"===i?e.blockedByMode:e.exposure===i)));return(0,n.jsxs)("section",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsxs)(n$.MG,{className:"min-w-0 flex-1 basis-56",children:[(0,n.jsx)(n$.Sq,{children:(0,n.jsx)(e_.A,{className:"size-4"})}),(0,n.jsx)(n$.iV,{"aria-label":t("searchTools"),placeholder:t("searchToolsSources",{defaultValue:"搜索名称、来源或描述"}),value:s,onChange:e=>a(e.target.value)})]}),(0,n.jsxs)(eP.l6,{value:i,onValueChange:e=>{"string"==typeof e&&l(e)},children:[(0,n.jsx)(eP.bq,{"aria-label":t("toolFilter"),className:"max-w-full",children:(0,n.jsx)(eP.yv,{children:"all"===i?t("allTools"):"blocked"===i?t("toolBlockedByMode"):t(py[i]?.[0]??"toolUnknown")})}),(0,n.jsxs)(eP.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(eP.eb,{value:"all",children:t("allTools")}),Object.entries(py).map(([e,[s,r]])=>(0,n.jsx)(eP.eb,{value:e,children:t(s,{defaultValue:r})},e)),(0,n.jsx)(eP.eb,{value:"blocked",children:t("toolBlockedByMode")})]})]})]}),(0,n.jsxs)("div",{className:"divide-y",children:[d.map(e=>{let s=e.exposure?py[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)}),d.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"!==i?t("noMatchingTools"):t("noRegisteredTools",{defaultValue:"当前会话没有登记工具"})}),o||"all"!==i?(0,n.jsx)(N.$,{variant:"outline",size:"sm",onClick:()=>{a(""),l("all")},children:t("clearSearch")}):null]})]})]})}function pj({notices:e}){let{t}=(0,f.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 a=r.index,i=r[0].replace(/[)\]。,.;]+$/,"");t.push(e.slice(s,a)),t.push((0,n.jsx)("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-2 wrap-anywhere",children:i},a)),s=a+i.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 pN({available:e,state:t,disabled:s,onExecute:a}){let{t:i}=(0,f.Bd)("workbench"),[l,o]=(0,r.useState)("status"),[d,c]=(0,r.useState)(""),[u,m]=(0,r.useState)(!1),p="status"!==l,h=d.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||a("status"===l?"":`${l} ${h}`,"login"===l)},children:[(0,n.jsx)(n6,{label:i("mcpSessionActions",{defaultValue:"MCP 会话操作"}),layout:"segmented",value:l,onChange:e=>{o(e),m(!1)},options:[{value:"status",label:i("mcpStatus",{defaultValue:"状态"})},{value:"login",label:i("mcpLogin",{defaultValue:"登录"})},{value:"reconnect",label:i("mcpReconnect",{defaultValue:"重连"})},{value:"logout",label:i("mcpLogout",{defaultValue:"退出登录"})}]}),p?(0,n.jsxs)("label",{className:"block space-y-1 text-sm font-medium",children:[(0,n.jsx)("span",{children:i("mcpServerName",{defaultValue:"服务名称"})}),(0,n.jsx)(eB.p,{value:d,onChange:e=>c(e.target.value),placeholder:i("mcpServerNamePlaceholder",{defaultValue:"输入真实服务名称"}),autoComplete:"off",maxLength:128})]}):null,p&&h&&g?(0,n.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:i("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:i("mcpLogoutConfirm",{defaultValue:"删除共享登录凭据,其他会话下次访问也可能需要重新登录。"})})]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(N.$,{type:"submit",size:"sm",disabled:s||!t.ready||null!==t.commandPending||g||"logout"===l&&!u,children:i("mcpExecute",{defaultValue:"执行"})}),t.commandPending?(0,n.jsxs)("span",{role:"status",className:"wrap-anywhere text-sm text-muted-foreground",children:[i("mcpExecuting",{defaultValue:"正在执行"})," ",t.commandPending]}):null]})]}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:i("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:i("nativeCommandOutput",{defaultValue:"会话命令输出"})}),(0,n.jsx)(pj,{notices:t.notices})]})]})}function pI({open:e,source:t,runtime:s,getContext:a,listCommands:i,nativeUi:l,nativeBiz:o,commandsDisabled:d,onOpenChange:c,onOpenSettings:u}){let{t:m,i18n:p}=(0,f.Bd)("workbench"),[h,g]=(0,r.useState)(!1),[x,b]=(0,r.useState)("tools"),v=(0,eC.G)(),{context:w,tools:y,commands:k}=function(e){let{source:t,runtime:s,getContext:n,listCommands:a,open:i,tab:l}=e,o=(0,r.useCallback)(()=>n({source:t}),[n,t]),d=(0,r.useCallback)(()=>s.listTools(t),[s,t]),c=(0,r.useCallback)(()=>a({source:t}),[a,t]);return{context:pw(i&&"system"===l,o),tools:pw(i&&"tools"===l,d),commands:pw(i&&"mcp"===l,c)}}({source:t,open:e,tab:x,runtime:s,getContext:a,listCommands:i}),j="system"===x?w:"tools"===x?y:k,I=l.state.snapshot.requests[0]?.id;(0,r.useEffect)(()=>{e&&I&&(l.setCollapsed(!1),c(!1))},[e,I,l,c]);let C=async()=>{w.value&&(await (0,tg.x)(w.value.systemPrompt)?g(!0):v.error(m("contextCopyFailed")))};return(0,n.jsx)(eX.YV,{open:e,onOpenChange:c,children:(0,n.jsxs)(eX.hA,{className:"h-[min(42rem,calc(100dvh-2rem))] max-w-[45rem]",children:[(0,n.jsxs)(eX.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)(nE.A,{className:"size-5 shrink-0 text-muted-foreground"}),(0,n.jsx)(eX.YM,{children:m("toolsAndContext",{defaultValue:"工具与上下文"})})]}),(0,n.jsx)(eX.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)(n6,{label:m("contextContents"),layout:"segmented",value:x,onChange:b,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"===x?(0,n.jsxs)(N.$,{variant:"ghost",size:"sm",disabled:!w.value||w.loading,onClick:()=>void C(),children:[h?(0,n.jsx)(ed.A,{}):(0,n.jsx)(eM.A,{}),h?m("copied"):m("copy")]}):null,u?(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{c(!1),u()},children:m("openSettings",{defaultValue:(p.resolvedLanguage??p.language).startsWith("en")?"Open settings":"打开设置"})}):null]})]}),(0,n.jsx)(eX._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)(N.$,{variant:"outline",size:"sm",onClick:j.retry,children:[(0,n.jsx)(eE.A,{}),m("contextRetry")]})]}):"tools"===x&&y.value?(0,n.jsx)(pk,{tools:y.value.tools}):"system"===x&&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"===x&&k.value?(0,n.jsx)(pN,{available:k.value.commands.some(e=>"mcp"===e.name&&"extension"===e.source),state:l.state,disabled:d,onExecute:(e,s)=>{o.executeCommand(t,"mcp",e),s&&(l.setCollapsed(!1),c(!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)(eE.A,{className:"size-4 animate-spin"}),m("contextLoading")]})})})]})})}let pC={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pS({source:e,runtime:t,catalog:s,current:a,label:i,title:l,disabled:o,triggerClassName:d,detailsClassName:c,onOpenSettings:u}){let{t:m,i18n:p}=(0,f.Bd)("workbench"),[h,g]=(0,r.useState)(null),{open:x,pending:b,error:v,changeOpen:w,refresh:y,submit:k}=function(e,t,s){let[n,a]=(0,r.useState)(!1),[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)(null),c=(0,r.useRef)(null),u=(0,r.useRef)(!1),m=(0,r.useRef)(!0);(0,r.useEffect)(()=>(m.current=!0,()=>{m.current=!1,c.current=null}),[]);let p=()=>{t.loadModels(e,!0)},h=e=>{c.current=e?{}:null,a(e),e&&(d(null),p())},g=async(n,r)=>{if(s||u.current)return;let a=c.current;u.current=!0,l(!0),d(null);try{await t.setModel(e,{provider:n.provider,modelId:n.modelId,thinkingLevel:r}),a&&c.current===a&&h(!1)}catch(e){a&&c.current===a&&d(e instanceof Error?e.message:String(e))}finally{u.current=!1,m.current&&l(!1)}};return{open:n,pending:i,error:o,changeOpen:h,refresh:p,submit:g}}(e,t,o),j=s.models.find(e=>e.provider===a?.provider&&e.modelId===a.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)(ec,{open:x,onOpenChange:e=>{g(null),w(e)},children:[(0,n.jsxs)(em,{render:(0,n.jsx)(lJ,{title:l,"aria-label":m("chooseModel"),className:d}),children:[(0,n.jsx)(e7.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{"data-model-trigger-details":!0,className:c,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:i}),(0,n.jsx)(ti.A,{className:"size-3 shrink-0"})]})})]}),(0,n.jsxs)(ep,{align:"start",side:"top",className:"flex max-h-96 w-72 flex-col overflow-hidden p-0",children:[(0,n.jsxs)(eh,{className:"shrink-0 p-1",children:[(0,n.jsx)(eg,{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)(e7.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||a?.modelId||m("selectModel")}),(0,n.jsx)("p",{className:"truncate text-xs text-muted-foreground",children:a?.provider||m("selectModel")})]}),a?(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(pC[a.thinkingLevel])})}):null]}),v?(0,n.jsx)("p",{role:"alert",className:"wrap-anywhere px-2 py-1 text-sm text-destructive",children:v}):null,b?(0,n.jsx)("p",{role:"status",className:"px-2 py-1 text-sm text-muted-foreground",children:m("modelChanging",{defaultValue:"正在切换模型…"})}):null]}),(0,n.jsx)(ek,{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)(ex,{disabled:!0,children:[(0,n.jsx)(eE.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)(ex,{closeOnClick:!1,onClick:y,children:[(0,n.jsx)(eE.A,{className:"size-4"}),m("retry")]})]}):null,N.map(e=>(0,n.jsxs)(eh,{children:[(0,n.jsx)(eg,{children:e.label}),e.models.map(e=>{let t=`${e.provider}:${e.modelId}`,s=a?.provider===e.provider&&a.modelId===e.modelId;return(0,n.jsxs)(ef,{open:h===t,onOpenChange:e=>{g(s=>e?t:s===t?null:s)},children:[(0,n.jsxs)(eb,{disabled:o||b,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)(rh.A,{className:"size-3 text-muted-foreground"}):null,s?(0,n.jsx)(ed.A,{className:"size-3 text-muted-foreground"}):null]}),(0,n.jsx)(ev,{children:(0,n.jsxs)(eh,{children:[(0,n.jsx)(eg,{children:m("thinkingLevels")}),e.thinkingLevels.map(t=>(0,n.jsxs)(ex,{disabled:o||b,closeOnClick:!1,onClick:()=>{g(null),k(e,t)},children:[(0,n.jsx)("span",{className:"flex-1",children:m(pC[t])}),s&&a?.thinkingLevel===t?(0,n.jsx)(ed.A,{className:"size-3 text-muted-foreground"}):null]},t))]})})]},t)})]},e.key)),"ready"===s.status&&0===s.models.length?(0,n.jsx)(ex,{disabled:!0,children:m("noModels")}):null,u&&("error"===s.status||"ready"===s.status&&0===s.models.length)?(0,n.jsx)(ex,{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)(ek,{className:"mx-0 my-0 shrink-0"}),(0,n.jsxs)(eh,{className:"shrink-0 p-1",children:[(0,n.jsx)(eg,{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)(ex,{onClick:()=>{w(!1),u("model-presets")},children:[(0,n.jsx)(iz.A,{className:"size-4"}),m("configureCommonCombinations")]}):null]}):null,s.presets.map((e,t)=>(0,n.jsxs)(ex,{disabled:o||b,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(pC[e.thinkingLevel])})]},`${e.provider}:${e.modelId}:${e.thinkingLevel}:${t}`))]})]}):null]})]})}var pM=s(62994);function pz({label:e,description:t,markerClass:s,countClass:r,inputs:a}){let{t:i}=(0,f.Bd)("workbench");return 0===a.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:i("queueItems",{count:a.length})})]}),(0,n.jsx)("ol",{className:"divide-y divide-border overflow-hidden",children:a.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||i(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)(rh.A,{className:"size-3"}),i("queueImages",{count:e.images.length})]}):null]})]},e.tempId)})})]})}function pE({queues:e,disabled:t,onRestore:s}){let{t:a}=(0,f.Bd)("workbench"),i=(0,r.useId)(),l=(0,r.useRef)(!1),[o,d]=(0,r.useState)(!1),c=e.steering.length+e.followUp.length;return 0===c?null:(0,n.jsxs)(lY,{open:o,triggerId:i,onOpenChange:(e,t)=>{l.current&&"trigger-focus"===t.reason||d(e)},children:[(0,n.jsx)(lV,{id:i,delay:100,closeDelay:120,render:(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",disabled:t,"aria-label":a("viewQueued",{count:c}),"aria-expanded":o,onPointerDown:e=>{l.current="mouse"!==e.pointerType},onPointerCancel:()=>{l.current=!1},onClick:e=>{l.current&&(e.preventDefault(),d(e=>!e),queueMicrotask(()=>{l.current=!1}))},children:a("queuedCount",{count:c})})}),(0,n.jsxs)(lK,{side:"top",align:"end",sideOffset:6,"aria-label":a("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)(pM.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:a("queueCurrent")}),(0,n.jsx)("p",{className:"mt-1 text-sm leading-5 text-muted-foreground",children:a("queuePendingDescription")})]}),(0,n.jsx)("span",{className:"shrink-0 rounded-md bg-muted px-2 py-1 text-xs tabular-nums text-foreground",children:a("queueItems",{count:c})})]})}),(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)(pz,{label:a("queueSteer"),description:a("queueSteerDescription"),markerClass:"bg-foreground",countClass:"bg-muted text-muted-foreground",inputs:e.steering}),(0,n.jsx)(pz,{label:a("queueFollowUp"),description:a("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)(N.$,{type:"button",variant:"ghost",size:"sm",className:"w-full text-muted-foreground hover:text-foreground",disabled:t,onClick:s,children:[(0,n.jsx)(lT.A,{}),a("queueRestore")]})})]})]})}let pA={builtin:"slashGroupBuiltin",skill:"slashGroupSkill",prompt:"slashGroupPrompt",extension:"slashGroupExtension"};function p$({open:e,loading:t,error:s,groups:a,activeIndex:i,onActiveIndexChange:l,onSelect:o}){let{t:d}=(0,f.Bd)("workbench"),c=(0,r.useRef)(null),u=a.reduce((e,t)=>e+t.commands.length,0);if((0,r.useEffect)(()=>{c.current?.scrollIntoView({block:"nearest"})},[i]),!e)return null;let m=0,p=u>0,h=t?d("slashLoadingMore"):s?d("slashMoreFailed"):null;return(0,n.jsxs)("div",{id:pl,role:"listbox","aria-label":d("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:[a.map((e,t)=>(0,n.jsxs)("section",{role:"group","aria-label":d(pA[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:d(pA[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===i;return(0,n.jsxs)("div",{id:pc(t),ref:s?c: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?d("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)(b.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)(b.A,{className:"size-3.5 animate-spin"}):null,(0,n.jsx)("span",{children:t?d("slashLoading"):s?d("slashFailed"):d("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:a.length>0?d("slashSummary",{commands:u,groups:a.length}):d("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:d("slashUpDown")}),(0,n.jsx)("span",{children:d("slashEnter")}),(0,n.jsx)("span",{children:d("slashEscape")})]})]})]})}var pR=s(22702),pP=s.n(pR);function pT({modes:e,value:t,disabled:s,onChange:r}){let{t:a}=(0,f.Bd)("capabilityModes");if(0===Object.keys(e).length)return null;let i=null===t?a("allEnabled"):Object.hasOwn(e,t)?e[t]:a("modeSwitching");return(0,n.jsxs)(ec,{children:[(0,n.jsxs)(em,{render:(0,n.jsx)(N.$,{variant:"ghost",size:"sm",disabled:s,"aria-label":a("modePicker",{name:i}),className:"min-w-0 max-w-40 text-muted-foreground"}),children:[(0,n.jsx)(eq.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 truncate",children:i}),(0,n.jsx)(ti.A,{className:"size-3 shrink-0"})]}),(0,n.jsx)(ep,{side:"top",align:"start",className:"max-h-80 min-w-40 overflow-y-auto",children:(0,n.jsxs)(ew,{value:t??"",onValueChange:e=>r("string"==typeof e&&e?e:null),children:[(0,n.jsx)(ey,{value:"",children:a("allEnabled")}),Object.entries(e).map(([e,t])=>(0,n.jsx)(ey,{value:e,children:t},e))]})})]})}var pD=s(32901),pL=s(79062),pO=s(5354);function pF({request:e,model:t}){let{t:s}=(0,f.Bd)("workbench"),a=(0,r.useId)(),[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)(()=>Date.now()),{state:c}=t,u=Object.hasOwn(c.answers,e.id),m=c.answers[e.id]??("editor"===e.method?e.prefill:""),p=null!==e.expiresAt&&e.expiresAt<=o,h=!c.ready||null!==c.submitting||null!==c.unknown||p,g=h||"select"===e.method&&!u;(0,r.useEffect)(()=>{if(null===e.expiresAt)return;let t=window.setInterval(()=>d(Date.now()),500);return()=>window.clearInterval(t)},[e.expiresAt]);let x=s=>{s?.preventDefault(),g||t.answer(e.id,"confirm"===e.method||m)},b=s=>(0,n.jsx)(aR.T,{"aria-label":e.title,"aria-labelledby":s?void 0:a,className:s?"min-h-0 flex-1 resize-none text-base":"h-32 min-h-20 resize-none text-base",value:m,disabled:null!==c.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(),x())}}),v=(r=!1)=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.$,{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)(m6.A,{className:"size-3.5"}),s("nativeUiStop")]})}),(0,n.jsx)("span",{className:"flex-1"}),(0,n.jsx)(N.$,{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)(N.$,{type:r?"button":"submit",size:"sm",disabled:g,onClick:r?()=>x():void 0,children:s(c.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||i||(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)(pD.A,{className:"size-3.5"}),(0,n.jsx)("span",{children:s("nativeUiTitle")}),c.snapshot.requests.length>1?(0,n.jsx)("span",{children:s("nativeUiMore",{count:c.snapshot.requests.length-1})}):null,(0,n.jsx)("span",{className:"flex-1"}),"editor"===e.method?(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>l(!0),children:[(0,n.jsx)(B.A,{className:"size-3.5"}),s("nativeUiExpand")]}):null,(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>t.setCollapsed(!0),children:s("nativeUiLater")})]}),(0,n.jsxs)("form",{onSubmit:x,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:a,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)(n6,{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)(eB.p,{"aria-labelledby":a,value:m,placeholder:e.placeholder,maxLength:65536,className:"text-base",disabled:null!==c.submitting,onChange:s=>t.setAnswer(e.id,s.target.value)}):null,"editor"===e.method?b(!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)(pL.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&&i?(0,n.jsx)(eX.YV,{open:!0,onOpenChange:l,children:(0,n.jsxs)(eX.hA,{className:"h-[min(40rem,calc(100dvh-2rem))] max-w-3xl","data-testid":"native-ui-editor-dialog",children:[(0,n.jsx)(eX.Hl,{className:"px-4 pt-4 pr-12 pb-3",children:(0,n.jsx)(eX.YM,{children:e.title})}),c.error||!c.ready?(0,n.jsx)("p",{role:"status",className:"px-4 pb-3 text-sm text-muted-foreground",children:c.error??s("nativeUiDisconnected")}):null,(0,n.jsx)("div",{className:"flex min-h-0 flex-1 px-4 pb-4",children:b(!0)}),(0,n.jsx)(eX.vu,{children:v(!0)})]})}):null]})}function pB({model:e}){let{t}=(0,f.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)(N.$,{type:"button",variant:"ghost",size:"sm",disabled:s.refreshing,onClick:e.refresh,children:[s.refreshing?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}):null,t("nativeUiRetry")]}),r?null:(0,n.jsx)(N.$,{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)(pD.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)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>e.setCollapsed(!1),children:t("nativeUiResume")})]}):(0,n.jsx)(pF,{request:r,model:e},r.id):null,s.notices.length>0?(0,n.jsxs)(tl.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)(tl.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)(ti.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)(N.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":t("close",{ns:"common"}),onClick:e.dismissNotices,children:(0,n.jsx)(U.A,{className:"size-3.5"})})]}),(0,n.jsx)(tl.Ke,{children:(0,n.jsx)("div",{className:"mt-2 max-h-40 overflow-y-auto",children:(0,n.jsx)(pj,{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)(N.$,{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)(N.$,{type:"button",size:"sm",variant:"secondary",onClick:()=>e.usePrefill("append"),children:t("nativeUiAppend")}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>e.usePrefill("replace"),children:t("nativeUiReplace")})]})]}):null]})}function p_({snapshot:e,placement:t}){let{t:s}=(0,f.Bd)("workbench"),r=Object.entries(e.widgets).filter(([,e])=>e.placement===t),a="belowEditor"===t?Object.values(e.statuses):[];return r.length||a.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)(pO.A,{className:"size-3.5"}),s("nativeUiInfo"),(0,n.jsx)("span",{children:r.length>1?r.length:""}),(0,n.jsx)(ti.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,a.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:a[0]}),(0,n.jsx)("span",{className:"hidden group-open:inline",children:s("nativeUiStatus")}),a.length>1?(0,n.jsxs)("span",{children:["+",a.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:a.map((e,t)=>(0,n.jsx)("p",{children:e},t))})]}):null]}):null}let pq={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pW(e){return e<1048576?`${Math.max(1,Math.round(e/1024))}KB`:`${(e/1048576).toFixed(1)}MB`}let pU=(0,r.memo)(function({onOpenSettings:e,workSession:t,chatRuntime:s,inputRuntime:a,renderTaskSummary:i,renderTaskMenu:l,renderPluginComposerPanel:o,gitRuntime:d,active:c,mobile:u,invokePluginMethod:m,listPiCommands:p,getChatModelContext:h,capabilityModes:g,setChatCapabilityMode:x,newSessionPending:v,newSessionDisabled:w,onNewSession:y,clonePending:k,cloneDisabled:j,onCloneWorkSession:I,onOpenBranchPicker:S,onOpenGitBranchPicker:M}){var z;let E,A,$,P,T,{t:D}=(0,f.Bd)("workbench"),L=(0,eC.G)(),O=(0,eI.So)(),F=sQ(),B=(0,r.useMemo)(()=>uC.Pi.parse({workId:t.workId,sessionId:t.sessionId,branchId:t.branchId}),[t.branchId,t.sessionId,t.workId]),_=(0,r.useCallback)(()=>a.getState(B),[a,B]),q=(0,r.useCallback)(()=>s.getSourceState(B).runtime,[s,B]),W=(0,r.useSyncExternalStore)(a.subscribe,_,_),Y=(0,r.useSyncExternalStore)(s.subscribe,q,q),K=(0,r.useCallback)(()=>s.getSourceState(B).syncStatus,[s,B]),H="ready"===(0,r.useSyncExternalStore)(s.subscribe,K,K),G=(z=s.nativeUi,E=(0,eC.G)(),A=(0,r.useCallback)(()=>z.getState(B),[z,B]),$=(0,r.useSyncExternalStore)(z.subscribe,A,A),P=(0,r.useCallback)(()=>a.getState(B),[a,B]),T=(0,r.useSyncExternalStore)(a.subscribe,P,P),(0,r.useEffect)(()=>{z.watch(B)},[z,B]),(0,r.useEffect)(()=>z.onNotice((e,t)=>{e.workId===B.workId&&e.sessionId===B.sessionId&&e.branchId===B.branchId&&E.show({level:t.level,title:t.message})}),[z,B,E]),(0,r.useEffect)(()=>{!$.prefill||!T.loaded||T.loading||T.outbox||T.text.length>0||(a.setText(B,$.prefill.text),z.edit(B,{prefill:null}))},[z,B,a,$.prefill,T.loaded,T.loading,T.outbox,T.text]),{state:$,canStop:H,setAnswer:(e,t)=>z.edit(B,{answers:{...z.getState(B).answers,[e]:t}}),setCollapsed:e=>z.edit(B,{collapsed:e}),answer:(e,t)=>{z.respond(B,{id:e,value:t})},refresh:()=>{z.refreshSource(B)},dismissError:()=>z.edit(B,{error:null}),dismissNotices:()=>z.edit(B,{notices:[]}),usePrefill:e=>{let t=z.getState(B).prefill;if(t){if("dismiss"!==e){let s=a.getState(B).text;a.setText(B,"replace"===e?t.text:`${s}${s?"\n":""}${t.text}`)}z.edit(B,{prefill:null})}},stop:()=>{a.interrupt(B).catch(e=>E.error(e instanceof Error?e.message:String(e)))}}),J=G.state.snapshot.requests.length>0,X="basic"===Y.extensionMode,Q="basic"===Y.presentationMode,Z=(0,r.useRef)(null),ee=(0,r.useRef)(null),et=(0,r.useRef)(null),es=(0,r.useRef)(null),en=function(e,t,s,n){let[a,i]=(0,r.useState)(!1);return(0,r.useLayoutEffect)(()=>{if(e)return;let r=t.current,a=r?.querySelector('[data-composer-tools="primary"]'),l=r?.querySelector('[data-composer-tools="metadata"]'),o=s.current;if(!r||!a||!l||!o)return;let d=0,c=null,u=()=>{if(null===c){let e=window.getComputedStyle(r);d=r.clientWidth-pu(e.paddingLeft)-pu(e.paddingRight);let t=pu(e.columnGap),s=pm(a),i=pm(l),u=pm(o),m=pu(window.getComputedStyle(a).columnGap),p=pu(window.getComputedStyle(l).columnGap),h=pu(window.getComputedStyle(o).columnGap),g=n.current,x=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,...i,...u,...g?[g]:[]]),f=[pp(s,m,x),pp(i,p,x),g?x.get(g)??0:0,pp(u,h,x)].filter(e=>e>0);c=f.reduce((e,t)=>e+t,0)+Math.max(0,f.length-1)*t}i(c>d+1)},m=null,p=()=>{null===m&&(m=window.requestAnimationFrame(()=>{m=null,u()}))},h=()=>{c=null,p()},g=new ResizeObserver(([e])=>{e&&d!==e.contentRect.width&&(d=e.contentRect.width,p())}),x=new MutationObserver(h);return g.observe(r),x.observe(r,{childList:!0,characterData:!0,subtree:!0}),window.addEventListener("resize",h),document.fonts.addEventListener("loadingdone",h),u(),()=>{g.disconnect(),x.disconnect(),window.removeEventListener("resize",h),document.fonts.removeEventListener("loadingdone",h),null!==m&&window.cancelAnimationFrame(m)}},[t,e,n,s]),a}(u,ee,et,es),[er,ea]=(0,r.useState)(null),[ei,el]=(0,r.useState)(null),eo=(0,r.useCallback)(()=>{el(null)},[]),[ed,eu]=(0,r.useState)(!1),[ef,eb]=(0,r.useState)(null),[ev,ew]=(0,r.useState)(!1),[ey,ej]=(0,r.useState)(!1),[eN,eS]=(0,r.useState)(!1),[eM,eA]=(0,r.useState)(null),[e$,eR]=(0,r.useState)(null),eP=JSON.stringify([B.workId,B.sessionId,B.branchId]),eT=(0,r.useMemo)(()=>X?[]:O.flatMap(e=>e.contributions.flatMap(t=>"composer-panel"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[O,X]),eD=ei?eT.find(e=>e.pluginName===ei.pluginName&&e.descriptor.contributionName===ei.contributionName):void 0;(0,r.useEffect)(()=>{let e=!0;return queueMicrotask(()=>{e&&(el(e=>e&&e.sourceKey!==eP?null:e),eb(null))}),()=>{e=!1}},[eP]),(0,r.useEffect)(()=>{a.loadSource(B),a.loadModels(B)},[a,B]);let eL="main_running"===t.status,eO=eL||"background_running"===t.status,eF="completed"===t.status,eB=null!==e$,e_=e$?.text??W.text,eq=e$?.images??W.images,eW=0===eq.length&&e_.trim()===`/${po.name}`,eU=eq.reduce((e,t)=>e+t.blob.size,0),eY=W.outbox&&!(eB&&"sending"===W.outbox.status)?W.outbox:null,eV=eL&&!eB,eK=Y.queues,eH=W.images.reduce((e,t)=>e+t.blob.size,0),eG=W.images.some(e=>"optimizing"===e.status),eJ=W.images.some(e=>"error"===e.status),eX=Y.model,eQ=eX?W.models.models.find(e=>e.provider===eX.provider&&e.modelId===eX.modelId):null,eZ=W.images.length>0&&!eQ?.input.includes("image"),e0=ed&&!ey,e1=H&&!J&&W.loaded&&!W.outbox&&(W.text.trim().length>0||W.images.length>0)&&W.images.length<=10&&!eG&&!eJ&&eH<=0x1400000&&!eZ,e2=Y.plugins["task-center"],e5=Y.contextUsage,e3=eQ?.name||eX?.modelId||D("noModelSelected"),e4=H?eX?`${e3} \xb7 ${D(pq[eX.thinkingLevel])}`:D("selectModel"):D("synchronizing"),e6=eX?D("modelTooltip",{model:e4}):D("chooseModel"),e8=er??W.error,e7=eO?"running":eF?"completed":"idle",e9=pn(t.cwd),te=(0,r.useCallback)(async(e,t)=>{eu(!0),ea(null);try{await e(),t&&L.success(t)}catch(e){ea(e instanceof Error?e.message:D("operationFailed"))}finally{eu(!1)}},[D,L]),tt=(0,r.useCallback)(e=>{ea(null),x({source:B,capabilityMode:e}).catch(e=>{ea(e instanceof Error?e.message:D("modeChangeFailed"))})},[x,B,D]),ts=(0,r.useCallback)(async()=>{if(!ev&&"ready"===s.getSourceState(B).syncStatus){ew(!0);try{await te(async()=>{await m({pluginName:"context-ignore",method:"ignore",scope:"session",source:B,input:{}})})}finally{ew(!1)}}},[s,ev,m,te,B]),tn=(0,r.useCallback)(async()=>{if(!ey){ej(!0);try{await te(()=>s.compact(B))}finally{ej(!1)}}},[s,ey,te,B]),ta=(0,r.useCallback)(e=>{a.setText(B,`/${e.name} `)},[a,B]),ti=function({source:e,text:t,enabled:s,listPiCommands:n,onSelect:a}){let i=JSON.stringify([e.workId,e.sessionId,e.branchId]),[l,o]=(0,r.useState)(!1),[d,c]=(0,r.useState)(null),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)({sourceKey:i,status:"idle",commands:[],error:null}),g=(0,r.useRef)(0),x=(0,r.useRef)(!0),f=s&&!l?/^\/[^\s/]*$/.test(t)?t.slice(1):null:null,b=null===f?null:`${i}\u0000${t}`,v=null!==b&&b!==d,{workId:w,sessionId:y,branchId:k}=e;(0,r.useEffect)(()=>(x.current=!0,()=>{x.current=!1,g.current+=1}),[]);let j=(0,r.useCallback)(async()=>{let e=++g.current;queueMicrotask(()=>{x.current&&g.current===e&&h(e=>e.sourceKey===i?{...e,status:"loading",error:null}:{sourceKey:i,status:"loading",commands:[],error:null})});try{let t=await n({source:{workId:w,sessionId:y,branchId:k}});if(!x.current||g.current!==e)return;h({sourceKey:i,status:"ready",commands:t.commands,error:null})}catch(t){if(!x.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:i,status:"error",commands:e.sourceKey===i?e.commands:[],error:t instanceof Error?t.message:"查询命令失败"})),t}},[k,i,n,y,w]);(0,r.useEffect)(()=>{v&&j().catch(()=>void 0)},[v,j]);let N=(0,r.useMemo)(()=>[po,...(p.sourceKey===i?p.commands:[]).filter(e=>e.name!==po.name).map(e=>({key:`${e.source}:${e.name}`,name:e.name,description:e.description,source:e.source}))],[i,p.commands,p.sourceKey]),I=(0,r.useMemo)(()=>{let e;return e=(f??"").toLocaleLowerCase(),pd.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,f]),C=(0,r.useMemo)(()=>I.flatMap(e=>e.commands),[I]),S=b&&u?.contextKey===b?C.findIndex(e=>e.key===u.commandKey):-1,M=S>=0?S:0,z=(0,r.useCallback)(e=>{if(!b||0===C.length)return;let t=(e+C.length)%C.length,s=C[t];s&&m({contextKey:b,commandKey:s.key})},[C,b]),E=(0,r.useCallback)(()=>{b&&c(b)},[b]),A=(0,r.useCallback)(()=>{b&&c(null)},[b]),$=(0,r.useCallback)(e=>{let t=C[e];t&&(b&&c(b),a(t))},[C,b,a]),R=(0,r.useCallback)(e=>!!v&&!e.nativeEvent.isComposing&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&("Escape"===e.key?(e.preventDefault(),E(),!0):0!==C.length&&("ArrowDown"===e.key?(e.preventDefault(),z(M+1),!0):"ArrowUp"===e.key?(e.preventDefault(),z(M-1),!0):("Enter"===e.key||"Tab"===e.key)&&(e.preventDefault(),$(M),!0))),[M,C.length,E,v,$,z]),P=(0,r.useCallback)(()=>{o(!0)},[]),T=(0,r.useCallback)(()=>{o(!1),c(null)},[]);return{open:v,loading:p.sourceKey===i&&"loading"===p.status,error:p.sourceKey===i&&"error"===p.status?p.error:null,groups:I,commands:C,activeIndex:M,dismiss:E,reopen:A,refresh:j,select:$,setActiveIndex:z,handleKeyDown:R,handleCompositionStart:P,handleCompositionEnd:T}}({source:B,text:e_,enabled:c&&H&&W.loaded&&!W.loading&&!eB,listPiCommands:p,onSelect:ta}),tl=ti.refresh,to=(0,r.useCallback)(async e=>{if(!eN&&!ed){eS(!0);try{await te(async()=>{await s.reload(B),await tl(),await a.loadModels(B,!0),e&&a.setText(B,"")})}finally{eS(!1)}}},[ed,s,a,tl,eN,te,B]),td=(0,r.useCallback)(e=>{eB||0===e.length||(ea(null),a.addFiles(B,e))},[eB,a,B]),tc=(0,r.useCallback)(async e=>{if("ready"!==s.getSourceState(B).syncStatus)return;if(eW){if(!W.loaded||W.loading)return;await to(!0);return}if(!e1||e0)return;let t=eL?null:{text:W.text,images:W.images};t&&eR(t),ea(null);try{await a.send(B,e)}catch(e){ea(e instanceof Error?e.message:D("sendFailed"))}finally{t&&eR(null)}},[e1,e0,s,a,W.images,W.loaded,W.loading,W.text,eW,eL,to,B,D]);return(0,n.jsxs)("div",{className:"mx-auto w-full max-w-3xl px-2 pb-2 sm:px-4 sm:pb-3",children:[eY?(0,n.jsx)("div",{className:(0,C.cn)("mb-2 rounded-lg border px-3 py-2 text-xs","unknown"===eY.status?"border-amber-500/50 bg-amber-500/10 text-amber-900 dark:text-amber-200":"failed"===eY.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"===eY.status?D("confirmingSend"):"unknown"===eY.status?D("sendUnknown"):D("sendFailure",{error:eY.error??D("unknownError")})}),"sending"===eY.status?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:ed,onClick:()=>void te(()=>a.restoreOutbox(B),D("outboxRestored")),children:[(0,n.jsx)(lT.A,{}),D("restoreDraft")]}),(0,n.jsxs)(N.$,{type:"button",variant:"ghost",size:"sm",disabled:ed,onClick:()=>void te(()=>a.deleteOutbox(B),D("outboxDeleted")),children:[(0,n.jsx)(ez.A,{}),D("delete")]})]})]})}):null,W.notice||e8?(0,n.jsx)("div",{role:e8?"alert":"status",className:(0,C.cn)("mb-2 rounded-md px-2 py-1 text-sm",e8?"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:e8??W.notice}),W.loaded||W.loading||!W.error?W.loaded?(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{ea(null),a.dismissFeedback(B)},children:D("close",{ns:"common"})}):null:(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:ed,onClick:()=>void te(()=>a.loadSource(B)),children:[(0,n.jsx)(lT.A,{}),D("retryDraft")]})]})}):null,i({source:B,cwd:t.cwd,pluginState:e2}),(0,n.jsx)(pB,{model:G}),(0,n.jsx)(p_,{snapshot:G.state.snapshot,placement:"aboveEditor"}),J?(0,n.jsx)("p",{className:"mb-1 px-1 text-xs text-muted-foreground",children:D("nativeUiComposer")}):null,(0,n.jsxs)("form",{"aria-label":eO?D("composerRunning"):eF?D("composerCompleted"):D("composer"),className:(0,C.cn)(pP().inputFrame,e9.className),"data-composer-mobile":u?"true":"false","data-composer-metadata-row":en?"true":"false",style:e9.style,onSubmit:e=>{e.preventDefault(),tc("auto")},onDragOver:e=>{e.dataTransfer.types.includes("Files")&&e.preventDefault()},onDrop:e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),td([...e.dataTransfer.files]))},children:[(0,n.jsx)(p$,{open:ti.open,loading:ti.loading,error:ti.error,groups:ti.groups,activeIndex:ti.activeIndex,onActiveIndexChange:ti.setActiveIndex,onSelect:ti.select}),(0,n.jsx)("input",{ref:Z,type:"file",accept:"image/jpeg,image/png,image/webp,image/gif,image/bmp",multiple:!0,className:"hidden",onChange:e=>{e.currentTarget.files&&td([...e.currentTarget.files]),e.currentTarget.value=""}}),(0,n.jsxs)("div",{className:"relative rounded-xl",children:[(0,n.jsxs)(n$.MG,{className:"relative z-[1] 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":eB,children:[eq.length>0?(0,n.jsxs)(n$.Sq,{align:"block-start",className:"pi-desk-chat-scrollbar gap-2 overflow-x-auto px-3 pt-3 pb-1",children:[eq.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 ${pW(e.blob.size)}`,children:[(0,n.jsx)("button",{type:"button",disabled:"ready"!==e.status,"aria-label":D("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=eq.filter(e=>"ready"===e.status)).findIndex(e=>e.localId===t))<0)&&eA({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:D("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:D("imageFailed")}):null,(0,n.jsx)("button",{type:"button","aria-label":D("imageRemove",{name:e.name}),"aria-disabled":eB,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:()=>{eB||a.removeImage(B,e.localId)},children:(0,n.jsx)(U.A,{className:"size-3"})})]},e.localId)),(0,n.jsxs)("span",{className:"self-end whitespace-nowrap text-xs text-muted-foreground",children:[eq.length,"/10 \xb7 ",pW(eU)]})]}):null,(0,n.jsx)(n$.oR,{value:e_,disabled:!W.loaded||W.loading,readOnly:eB,"aria-disabled":eB,"aria-autocomplete":"list","aria-controls":ti.open?pl:void 0,"aria-expanded":ti.open,"aria-activedescendant":ti.open&&ti.commands.length>0?pc(ti.activeIndex):void 0,placeholder:W.loading?D("draftLoading"):!W.loaded&&W.error?D("draftFailed"):D("inputPlaceholder"),className:(0,C.cn)(pP().inputText,"pi-desk-chat-scrollbar max-h-48 min-h-9 overflow-y-auto px-3 pt-3 pb-1"),onChange:e=>a.setText(B,e.currentTarget.value),onClick:ti.reopen,onBlur:ti.dismiss,onCompositionStart:ti.handleCompositionStart,onCompositionEnd:ti.handleCompositionEnd,onKeyDown:e=>{ti.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(),td(t))}}),(0,n.jsxs)(lH,{ref:ee,className:pP().footer,children:[(0,n.jsxs)(lG,{"data-composer-tools":"primary",className:pP().primaryTools,children:[(0,n.jsxs)(ec,{children:[(0,n.jsx)(em,{render:(0,n.jsx)(lJ,{tooltip:D("more"),"aria-label":D("moreActions")}),children:(0,n.jsx)(V.A,{className:"size-4"})}),(0,n.jsxs)(ep,{align:"start",side:"top",className:"w-52",children:[(0,n.jsxs)(eh,{children:[(0,n.jsx)(eg,{children:D("session")}),(0,n.jsxs)(ex,{"aria-label":D("switchBranch"),disabled:!H||!W.loaded||W.loading,onClick:()=>S(t.workId),children:[(0,n.jsx)(ua.A,{className:"size-4"}),D("sessionBranch"),(0,n.jsx)("span",{className:"ml-auto text-xs text-muted-foreground",children:D("escapeTwice")})]}),(0,n.jsxs)(ex,{"aria-label":D("clone"),disabled:!H||j||k,title:0===t.messageCounts.total?D("cloneEmpty"):D("cloneTip"),onClick:I,children:[k?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(m2.A,{className:"size-4"}),k?D("cloning"):D("clone")]}),(0,n.jsxs)(ex,{"aria-label":D("replaceSession"),"aria-busy":v,disabled:!H||w||v,onClick:y,children:[v?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(m5.A,{className:"size-4"}),v?D("replacing"):D("replaceSession")]})]}),(0,n.jsx)(ek,{}),(0,n.jsxs)(eh,{children:[(0,n.jsx)(eg,{children:D("tools")}),l({source:B,cwd:t.cwd,pluginState:e2}),(0,n.jsxs)(ex,{"aria-label":D("toolsAndContext",{defaultValue:"工具与上下文"}),disabled:!H||J,onClick:()=>eb(eP),children:[(0,n.jsx)(nE.A,{className:"size-4"}),D("toolsAndContext",{defaultValue:"工具与上下文"})]}),(0,n.jsxs)(ex,{"aria-label":D("reloadPi"),disabled:!W.loaded||W.loading||!H||eO||ed||eN,title:D("reloadPiTip"),onClick:()=>void to(!1),children:[eN?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(eE.A,{className:"size-4"}),eN?D("reloadingPi"):D("reloadPi")]}),Q&&!X?(0,n.jsxs)(ex,{disabled:!H||ed||eN,onClick:()=>void te(()=>s.setPresentation(B,"normal")),children:[(0,n.jsx)(nE.A,{className:"size-4"}),D("restorePluginPresentation")]}):null]}),eT.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ek,{}),(0,n.jsxs)(eh,{children:[(0,n.jsx)(eg,{children:D("plugins")}),eT.map(e=>(0,n.jsxs)(ex,{onClick:()=>el({pluginName:e.pluginName,contributionName:e.descriptor.contributionName,sourceKey:eP}),children:[(0,n.jsx)(tr,{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)(lJ,{tooltip:D("addImage"),"aria-label":D("addImage"),disabled:W.images.length>=10,"aria-disabled":eB||W.images.length>=10,onClick:()=>{eB||Z.current?.click()},children:(0,n.jsx)(m3.A,{className:"size-4"})}),e5&&eQ?.contextWindow!==null?(0,n.jsx)(pv,{sessionId:t.sessionId,cwd:t.cwd,tokens:e5.tokens,contextWindow:e5.contextWindow,contextIgnorePlugin:Y.plugins["context-ignore"],ignoreDisabled:!H||eL||ed,ignorePending:ev,compactDisabled:!H||eL||ed,compactPending:ey,onIgnoreContext:ts,onCompactContext:tn}):eQ?.contextWindow===null?(0,n.jsx)("span",{className:"px-1 text-xs text-muted-foreground",children:D("modelContextUnknown",{defaultValue:"上下文未知"})}):null]}),(0,n.jsxs)(lG,{"data-composer-tools":"metadata",className:pP().metadataTools,children:[(0,n.jsx)(pi,{workSession:t,runtime:d,active:c,chatReady:H,onOpen:M}),(0,n.jsx)(pT,{modes:g,value:Y.capabilityMode,disabled:!H,onChange:tt}),(0,n.jsx)(pS,{source:B,runtime:a,catalog:W.models,current:eX,label:e4,title:e6,disabled:!H||eO||eB||ed,triggerClassName:pP().modelTrigger,detailsClassName:pP().modelTriggerDetails,onOpenSettings:e},eP)]}),eL&&eB?(0,n.jsx)("span",{ref:es,className:"min-w-0 truncate px-2 text-xs text-muted-foreground",children:D("preparingContext")}):null,(0,n.jsxs)("div",{ref:et,className:pP().submitTools,children:[(0,n.jsx)(pE,{queues:eK,disabled:!H||ed,onRestore:()=>void te(()=>a.restoreQueue(B),D("queuesRestored"))}),eV?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(lJ,{tooltip:D("steerNow"),"aria-label":D("steerNow"),variant:"secondary",disabled:!e1||e0,onClick:()=>void tc("auto"),children:(0,n.jsx)(R.A,{className:"size-3.5"})}),(0,n.jsx)(lJ,{tooltip:D("sendFollowUp"),"aria-label":D("sendFollowUp"),variant:"outline",disabled:!e1||e0,onClick:()=>void tc("follow_up"),children:(0,n.jsx)(m4.A,{className:"size-3.5"})}),(0,n.jsx)(lJ,{tooltip:D("stopResponse"),"aria-label":D("stopResponse"),variant:"destructive",disabled:!H||ed,onClick:()=>void te(()=>a.interrupt(B)),children:(0,n.jsx)(m6.A,{className:"size-3.5 fill-current"})})]}):(0,n.jsx)(N.$,{type:eB?"button":"submit",size:"icon",disabled:!eB&&(!e1||e0),"aria-disabled":eB||!e1||e0,"aria-busy":eB,"aria-label":eB?D("sending"):H?D("send"):D("synchronizing"),children:eB?(0,n.jsx)(m8.A,{className:(0,C.cn)("size-4",!F&&"pi-desk-chat-send-icon")}):H?(0,n.jsx)(m7.A,{}):(0,n.jsx)(b.A,{className:"size-4 animate-spin"})})]})]})]}),(0,n.jsx)(pt,{state:e7,powerSaving:F})]})]}),(0,n.jsx)(p_,{snapshot:G.state.snapshot,placement:"belowEditor"}),ei&&ei.sourceKey===eP&&eD?o({pluginName:ei.pluginName,descriptor:eD.descriptor,source:B,onClose:eo}):null,ef===eP&&H?(0,n.jsx)(pI,{open:!0,source:B,runtime:a,getContext:h,listCommands:p,nativeUi:G,nativeBiz:s.nativeUi,commandsDisabled:eO||eB||ed,onOpenChange:e=>eb(e?eP:null),onOpenSettings:e},eP):null,eM?(0,n.jsx)(nC.k,{mode:"modal",open:!0,slides:eM.slides,index:eM.index,ariaLabel:D("imagePreviewPending"),onClose:()=>eA(null),onIndexChange:e=>eA(t=>t?{...t,index:e}:t)}):null,W.images.length>10?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:D("tooManyImages")}):eZ?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:D("imageUnsupported")}):eH>0x1400000?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:D("imagesTooLarge")}):null]})});pU.displayName="L2WorkbenchChatComposer";var pY=s(28500);function pV({svgRef:e}){let t=(0,r.useId)(),s=`${t}-head`,a=`${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:a,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(#${a})`}),(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 pK={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},pH=Object.keys(pK),pG={idle:.46,hello:.36,point:.45,think:.5,busy:.4,happy:.35,surprise:.2,sleep:.72};function pJ(e){return Math.min(1,Math.max(0,e))}function pX(e){let t=pJ(e);return t*t*t*(t*(6*t-15)+10)}function pQ(e,t){let s={...pK};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=pX(e/1.45),r=pX((e-2.15)/.65),a=Math.exp(-Math.pow((e-1.9)/.22,2));s.gazeX=-11+22*n-22*r,s.gazeY=8+2*a,s.angle=.1*s.gazeX,s.y=3+4*a,s.eye=.9+.05*a,s.sy=1-.006*a,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 pZ{setState(e,t){if(e===this.state)return;let s=this.transition&&t-this.transition.at<pG[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=pQ(this.state,t?1.2:Math.max(0,e-this.started));if(!this.transition||t)return s;let n=pJ((e-this.transition.at)/pG[this.state]);if(1===n)return s;let r="pose"in this.transition?this.transition.pose:pQ(this.transition.state,Math.max(0,e-this.transition.started)),a=1-(1-n)**5;for(let e of pH)s[e]=r[e]+(s[e]-r[e])*a;return s}constructor(){this.state="idle",this.started=0,this.transition=null}}let p0=["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 p1(e,t=0,s=1){return Math.min(s,Math.max(t,e))}function p2(e){return e.toFixed(3)}function p5({state:e,active:t=!0,size:s=100,className:a}){let i=(0,r.useRef)(null),l=(0,r.useRef)(null);return(0,r.useEffect)(()=>{let e=function(e){let t=Object.fromEntries(p0.map(t=>[t,e.querySelector(`[data-part="${t}"]`)])),s=e.parentElement,n=new pZ,r=matchMedia("(prefers-reduced-motion: reduce)"),a=!0,i=!1,l=0,o=null,d=0,c=-10,u=1.7,m={x:0,y:0},p={x:0,y:0};function h(e,s){t[e].setAttribute("opacity",p2(s))}function g(e,s){t[e].setAttribute("transform",s)}function x(){let e=n.sample(d,r.matches),s=r.matches?1.2:d,a=r.matches?0:.005*Math.sin(1.7*d),i=e.gazeX+(r.matches?0:m.x*e.follow),l=e.gazeY+(r.matches?0:m.y*e.follow);g("head",`translate(${p2(e.x)} ${p2(e.y)}) translate(320 274) rotate(${p2(e.angle+(r.matches?0:m.x*e.follow*.12))}) scale(${p2(e.sx)} ${p2(e.sy+a)}) translate(-320 -274)`),g("face",`translate(${p2(.16*i)} ${p2(.12*l)})`);let o=r.matches?-1:(d-c)/.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(${p2(n+i)} ${p2(239+l)})`);let r=1-p1(e.smile+e.sleepy),a=(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=p2(e),r=p2(t+s),a=p2(-t+s),i=p2(.5523*e),l=p2(-(.5523*t)+s),o=p2(.5523*t+s);return`M-${n} 0C-${n} ${l} -${i} ${a} 0 ${a}C${i} ${a} ${n} ${l} ${n} 0C${n} ${o} ${i} ${r} 0 ${r}C-${i} ${r} -${n} ${o} -${n} 0Z`}(22+4*r,a,(-13*e.smile+8*e.sleepy)*u)),h(`${s}-eye-shine`,r*p1((a-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",p2(.25+.75*(1+Math.sin(2.8*s-.9*t))/2)),e.setAttribute("transform",`translate(0 ${p2(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(${p2(8*n)} ${p2(-(20*n))})`),e.setAttribute("opacity",p2(Math.sin(n*Math.PI)))}),h("sparkles",e.sparkle*(.55+.45*(1+Math.sin(3*s))/2)),g("sparkles",`translate(0 ${p2(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*p1(((s-.18*t)%1.4+1.4)%1.4/.55));e.setAttribute("opacity",p2(.26+.65*n)),e.setAttribute("transform",`translate(0 ${p2(-4*n)})`)})}function f(){return a&&i&&!document.hidden&&!r.matches}function b(e){if(l=0,!f())return;let t=null===o?0:Math.min((e-o)/1e3,.05);o=e,(d+=t)>=u&&(c=d,u=d+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,x(),l=requestAnimationFrame(b)}function v(){cancelAnimationFrame(l),l=0,o=null,x(),f()&&(l=requestAnimationFrame(b))}function w(e){if("mouse"!==e.pointerType||!f())return;let t=s.getBoundingClientRect();p.x=p1((e.clientX-t.left-t.width/2)/Math.max(t.width,window.innerWidth/2)*24,-18,18),p.y=p1((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])=>{i=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),x(),{setState(e){n.setState(e,d),"point"!==e&&"think"!==e||r.matches||(c=d),x()},setActive(e){a=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)}}}(i.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",a),style:{width:s,height:.75*s},children:(0,n.jsx)(pV,{svgRef:i})})}let p3=Object.keys(cY.R.en).filter(e=>e.startsWith("emptyQuip")),p4=null;function p6(){let{t:e}=(0,f.Bd)("workbench"),t=(0,mK.tF)(),s=!0===(0,pY.D)(),a=(0,sV.I)(),{state:i,textKey:l}=function(e){let[t,s]=(0,r.useState)(null),[n,a]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{let e=requestAnimationFrame(()=>{let e,t;return s((e=Math.floor(Math.random()*(null===p4?p3.length:p3.length-1)),null!==p4&&e>=p4&&(e+=1),p4=e,"emptyQuip16"===(t=p3[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(()=>a(!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&&!a?(0,n.jsxs)(o8.PY1.div,{"data-testid":"workbench-empty-session","data-otter-state":i,"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)(p5,{state:i,size:100}),(0,n.jsx)("p",{className:"min-h-6 text-sm leading-6 text-muted-foreground",children:l?e(l):null})]}):null}function p8({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)(mV.N,{initial:!1,custom:e&&t&&r,children:e&&t&&s?(0,n.jsx)(p6,{},"welcome"):null}),e&&!t&&s?(0,n.jsx)(mW,{variant:"loading"}):null]})}function p7({active:e,turns:t,window:s}){return e?(0,n.jsx)(o$,{turns:t,window:s}):null}function p9(e,t=!1){let s=e.scrollHeight-e.scrollTop-e.clientHeight;if(!t&&2>=ox(e)&&s<=2)return null;let n=e.getBoundingClientRect().top,r=null;for(let t of e.querySelectorAll("[data-chat-scroll-anchor]")){let e=t.dataset.chatScrollAnchor;if(!e)continue;let s=t.getBoundingClientRect().top-n,a=Math.abs(s);(!r||a<r.distance)&&(r={messageId:e,offset:s,distance:a})}return r?{messageId:r.messageId,offset:r.offset}:null}function he({visible:e=!0,running:t,ready:s,containsTail:n,latestUserAnchor:a,entrySnapshot:i,onSaveSnapshot:l,onClearSnapshot:o}){let{scrollRef:d,scrollToBottom:c,state:u,stopScroll:m}=(0,lL.B)(),p=(0,r.useRef)(!1),h=(0,r.useRef)(!1),g=(0,r.useRef)(null),x=(0,r.useRef)(t?i:null),f=(0,r.useRef)(null),b=(0,r.useRef)(null);return(0,r.useLayoutEffect)(()=>{let t=d.current;if(!t)return;if(!e){null===b.current&&(f.current=p9(t,!0),b.current=t.scrollTop),m();return}if(null===b.current)return;m();let s=f.current,r=s?ou(t,"data-chat-scroll-anchor",s.messageId):null;s&&r?ov(t,r,s.offset,n):t.scrollTop=b.current,h.current=!0,g.current=a,f.current=null,b.current=null},[n,a,d,m,e]),(0,r.useLayoutEffect)(()=>{if(!s||!e)return;t||o();let r=!h.current,i=null!==a&&a!==g.current;if(!r&&!i)return;let l=d.current;i&&(o(),l&&of(l));let u=null,f=null;p.current=!0;let b=()=>{let e=d.current;if(!e){p.current=!1;return}oc("viewport:initialize:start",e,{initializing:r,running:t,containsTail:n,latestUserAnchor:a});let s=null,i=12,l=r?x.current:null;if(l){let t=ou(e,"data-chat-scroll-anchor",l.messageId);t&&(s=t,i=l.offset)}!s&&a&&(s=ou(e,"data-chat-scroll-anchor",a));let o=null!==(s??=ou(e,"data-chat-user-message",void 0))&&null===l&&(t||!r),u=r&&t&&null===l;s?(m(),ov(e,s,i,n),u&&(e.scrollTop=Math.max(0,e.scrollHeight-e.clientHeight),c({animation:"instant"}))):(of(e),e.scrollTop=Math.max(0,e.scrollHeight-e.clientHeight),c({animation:"instant"})),oc("viewport:initialize:positioned",e,{initializing:r,running:t,target:s?.dataset.chatScrollAnchor??null,followAfterPosition:o,enterRunningAtBottom:u}),h.current=!0,g.current=a,x.current=null,f=window.requestAnimationFrame(()=>{o?c({animation:"instant"}):s&&m(),p.current=!1})};return r&&d.current?b():u=window.requestAnimationFrame(b),()=>{null!==u&&window.cancelAnimationFrame(u),null!==f&&window.cancelAnimationFrame(f)}},[n,a,o,s,t,d,c,m,e]),(0,r.useEffect)(()=>{let t=d.current;if(!t||!e)return;let s=()=>{if(oc("viewport:scroll",t,{positioning:p.current,isAtBottom:u.isAtBottom,escapedFromLock:u.escapedFromLock,resizeDifference:u.resizeDifference}),p.current||u.isAtBottom)return;let e=t.querySelector("[data-chat-tail-space]");!e||e.dataset.chatTailAnchor!==a||t.scrollHeight-t.scrollTop-t.clientHeight<=2&&(oc("viewport:resume-follow",t,{isAtBottom:u.isAtBottom,escapedFromLock:u.escapedFromLock}),c({animation:"instant"}))};return t.addEventListener("scroll",s,{passive:!0}),()=>t.removeEventListener("scroll",s)},[a,d,c,u,e]),(0,r.useLayoutEffect)(()=>{if(!t||!e)return;let s=d.current;if(!s)return;let n=()=>{if(p.current)return;let e=p9(s);e?l(e):o()};return s.addEventListener("scroll",n,{passive:!0}),()=>{s.removeEventListener("scroll",n),n()}},[o,l,t,d,e]),null}let ht=(0,r.memo)(function({visible:e,workSession:t,chatRuntime:s,inputRuntime:a,onPreviewFile:i}){let{t:l}=(0,f.Bd)("workbench"),o=(0,r.useMemo)(()=>uC.Pi.parse({workId:t.workId,sessionId:t.sessionId,branchId:t.branchId}),[t.branchId,t.sessionId,t.workId]),d=(0,r.useMemo)(()=>s.getViewportSnapshot(o),[s,o]),c=(0,r.useCallback)(()=>s.getSourceState(o),[s,o]),u=(0,r.useSyncExternalStore)(s.subscribe,c,c),m="main_running"===t.status||"background_running"===t.status,p=(0,r.useMemo)(()=>oi({messages:u.messages,temporaryMessages:u.temporaryMessages},m),[m,u.messages,u.temporaryMessages]),h=u.messages.length>0||u.temporaryMessages.length>0,g=u.messages.some(e=>"user"===e.fixed.type)||u.temporaryMessages.some(e=>"user"===e.fixed.type),x=m||u.temporaryMessages.length>0,b=p.findLast(e=>null!==e.user)??null,v=b?.user??null,w=v?`${v.identity}:user`:null,y=(0,r.useCallback)(async e=>e.durable?void 0!==e.detail?e.detail:s.loadMessageDetail(o,e.durable.location.index,e.durable.location.entryId):null,[s,o]),k=(0,r.useCallback)((e,t)=>a.acquireMessageImage({source:o,tempId:e.tempId,entryId:e.durable?.location.entryId??null,imageIndex:t}),[a,o]),j=(0,r.useCallback)(e=>i(o,e),[i,o]),N=(0,r.useCallback)(e=>{s.saveViewportSnapshot(o,e)},[s,o]),I=(0,r.useCallback)(()=>{s.clearViewportSnapshot(o)},[s,o]),C=(0,r.useCallback)(()=>s.setPresentation(o,"basic"),[s,o]);return(0,n.jsx)(oP,{basic:"basic"===u.runtime.presentationMode,onRecover:C,children:(0,n.jsxs)(lO,{className:"min-h-0",initial:!1,resize:"instant","aria-label":l("chatMessages",{name:t.sessionTitle??t.projectName}),children:[(0,n.jsx)(oS,{turns:p,active:e,focusTurnIdentity:b?.identity??null,initialAnchor:d?.messageId??null,children:s=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(he,{visible:e,running:x,ready:h,containsTail:s.containsTail,latestUserAnchor:w,entrySnapshot:d,onSaveSnapshot:N,onClearSnapshot:I},`viewport:${o.sessionId}:${o.branchId}`),(0,n.jsx)(ow,{active:e}),(0,n.jsx)(dy,{children:(0,n.jsx)(lF,{scrollClassName:"pi-desk-chat-scrollbar pi-desk-chat-conversation-scroll",className:"mx-auto min-h-full w-full max-w-3xl gap-6 px-3 pt-3 pb-4 sm:px-5",children:s.visibleTurns.map((e,r)=>{let a=s.startIndex+r;return(0,n.jsx)(d7,{turn:e,cwd:t.cwd,logicalTail:s.containsTail&&a===p.length-1,onLoadDetail:y,onAcquireImage:k,onPreviewFile:j},e.identity)})})}),(0,n.jsx)(p7,{active:e,turns:p,window:s},`navigation:${o.sessionId}:${o.branchId}`)]})},`window:${o.sessionId}:${o.branchId}`),(0,n.jsx)(p8,{active:e,ready:"ready"===u.syncStatus,empty:!h,hasUserMessage:g})]})})});function hs({error:e,copied:t,reloading:s,canReload:r,onCopy:a,onReload:i}){let{t:l}=(0,f.Bd)("workbench");return(0,n.jsxs)(th.AM,{children:[(0,n.jsx)(th.Wv,{openOnHover:!0,delay:150,closeDelay:150,render:(0,n.jsx)(N.$,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive"}),children:l("initializationDegraded")}),(0,n.jsxs)(th.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)(th.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)(N.$,{variant:"outline",size:"sm",onClick:a,children:[t?(0,n.jsx)(ed.A,{}):(0,n.jsx)(eM.A,{}),l(t?"copied":"copyInitializationError")]}),(0,n.jsxs)(N.$,{size:"sm",disabled:!r,onClick:i,children:[s?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(eE.A,{}),l(s?"reloadingPi":"reloadPi")]})]})]})]})}ht.displayName="L2WorkbenchChatView";var hn=s(51932),hr=s.n(hn);function ha({sidebarOpen:e,onOpen:t}){let{t:s}=(0,f.Bd)("workbench"),r=(0,sV.I)();return(0,n.jsxs)("div",{"data-testid":"workbench-session-guide",className:hr().guide,children:[(0,n.jsx)(p5,{state:e?"idle":"point",size:120,className:hr().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:hr().arrow,fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)(o8.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)(N.$,{variant:"ghost","aria-label":s("showSessionMenu"),onClick:t,className:"absolute inset-0 size-full p-0 hover:bg-foreground/5"})]})]})}var hi=s(16410);let hl=r.createContext(null);function ho(){let e=r.useContext(hl);if(!e)throw Error("useCarousel must be used within a <Carousel />");return e}function hd({orientation:e="horizontal",opts:t,setApi:s,plugins:a,className:i,children:l,...o}){let[d,c]=(0,hi.A)({...t,axis:"horizontal"===e?"x":"y"},a),[u,m]=r.useState(!1),[p,h]=r.useState(!1),g=r.useCallback(e=>{e&&(m(e.canScrollPrev()),h(e.canScrollNext()))},[]),x=r.useCallback(()=>{c?.scrollPrev()},[c]),f=r.useCallback(()=>{c?.scrollNext()},[c]),b=r.useCallback(e=>{"ArrowLeft"===e.key?(e.preventDefault(),x()):"ArrowRight"===e.key&&(e.preventDefault(),f())},[x,f]);return r.useEffect(()=>{c&&s&&s(c)},[c,s]),r.useEffect(()=>{if(!c)return;let e=!1;return queueMicrotask(()=>{e||g(c)}),c.on("reInit",g),c.on("select",g),()=>{e=!0,c.off("reInit",g),c.off("select",g)}},[c,g]),(0,n.jsx)(hl.Provider,{value:{carouselRef:d,api:c,opts:t,orientation:e||(t?.axis==="y"?"vertical":"horizontal"),scrollPrev:x,scrollNext:f,canScrollPrev:u,canScrollNext:p},children:(0,n.jsx)("div",{onKeyDownCapture:b,className:(0,C.cn)("relative",i),role:"region","aria-roledescription":"carousel","data-slot":"carousel",...o,children:l})})}function hc({className:e,...t}){let{carouselRef:s,orientation:r}=ho();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 hu({className:e,...t}){let{orientation:s}=ho();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 hm(e){let t=e.scrollWidth-e.clientWidth;return t<=1||!["auto","scroll"].includes(getComputedStyle(e).overflowX)?null:{left:e.scrollLeft,maximum:t}}function hp(e){return e.sessionTitle?`${e.projectName} \xb7 ${e.sessionTitle}`:e.projectName}function hh({items:e,activeWorkId:t,onActiveWorkSessionChange:s,children:a}){let i,l,{t:o}=(0,f.Bd)("workbench"),d=(0,sV.I)(),c=r.Children.toArray(a),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),[x,b]=(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))),a=Math.round(r);w(e=>{let t=s??e.visible;return e.index===a&&.001>Math.abs(e.position-r)&&e.visible===t?e:{index:a,position:r,visible:t}})},[e.length]),N=(0,r.useCallback)(e=>{j(e,!0),k()},[k,j]),I=(i=(0,r.useRef)(null),l=(0,r.useCallback)((e,t)=>{i.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=hm(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=hm(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 a=t.touches[0];return i.current={x:a.clientX,y:a.clientY,scrolls:r,owner:"pending"},!1},[]),(0,r.useEffect)(()=>{if(!x)return;let e=x.rootNode(),t=()=>{i.current=null},s=e=>{let s=i.current;if(!s)return;if(1!==e.touches.length)return void t();let n=e.touches[0],r=n.clientX-s.x,a=n.clientY-s.y;if("pending"===s.owner){if(6>Math.max(Math.abs(r),Math.abs(a)))return;let e=s.scrolls.some(e=>r<0?e.left<e.maximum-1:e.left>1);s.owner=Math.abs(a)>=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=i.current;if(t(),!n||"pending"===n.owner||"content"===n.owner)return;let r=s.changedTouches[0],a=r.clientX-n.x,l=r.clientY-n.y,o=Math.max(50,Math.min(225,.2*e.clientWidth));("next"===n.owner?-a:a)<o||Math.abs(l)>=Math.abs(a)||("next"===n.owner?x.canScrollNext():x.canScrollPrev())&&(N(x),"next"===n.owner?x.scrollNext():x.scrollPrev())};return e.addEventListener("touchmove",s,{passive:!1}),e.addEventListener("touchend",n),e.addEventListener("touchcancel",t),x.on("reInit",t),()=>{t(),e.removeEventListener("touchmove",s),e.removeEventListener("touchend",n),e.removeEventListener("touchcancel",t),x.off("reInit",t)}},[x,N]),l),S=(0,r.useMemo)(()=>({align:"start",containScroll:"trimSnaps",dragFree:!1,loop:!1,skipSnaps:!1,duration:25*!d,startIndex:p,watchDrag:I}),[p,d,I]);if((0,r.useEffect)(()=>{m&&m!==t&&s(m)},[t,m,s]),(0,r.useLayoutEffect)(()=>{if(!x||!m)return;let t=e.findIndex(e=>e.workId===m);t<0||x.selectedScrollSnap()===t||x.scrollTo(t,!0)},[x,m,e]),(0,r.useEffect)(()=>{if(!x)return;let n=()=>{g.current=!0},r=()=>{g.current=!1,k()},a=e=>{if(g.current){y(),j(e,!0);return}j(e)},i=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 x.on("pointerDown",n),x.on("pointerUp",r),x.on("scroll",a),x.on("select",i),x.on("settle",l),x.on("reInit",o),()=>{g.current=!1,x.off("pointerDown",n),x.off("pointerUp",r),x.off("scroll",a),x.off("select",i),x.off("settle",l),x.off("reInit",o)}},[t,x,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:c[0]??null});let M=e[v.index]??e[0],z=`${100/e.length}%`,E=`translate3d(${100*v.position}%, 0, 0)`;return(0,n.jsxs)(hd,{opts:S,setApi:b,"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)(hc,{className:"ml-0 h-full",children:e.map((t,s)=>(0,n.jsx)(hu,{"aria-label":`${s+1} / ${e.length},${hp(t)}`,className:"h-full pl-0",children:c[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(M.fixed?"fixedSession":"primarySession")}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:hp(M)}),(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:z,transform:E}})})]})})]})}function hg(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}var hx=s(58618),hf=s.n(hx);function hb({sidebarOpen:e,onToggle:t}){let{t:s}=(0,f.Bd)("workbench");return(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":s(e?"hideSessionMenu":"showSessionMenu"),className:(0,C.cn)((0,N.r)({variant:"ghost",size:"icon"}),"text-muted-foreground"),children:e?(0,n.jsx)(s0.A,{className:"size-4"}):(0,n.jsx)(mU.A,{className:"size-5"})})}let hv=(0,r.memo)(function({onOpenSettings:e,workSession:t,fixed:s,focused:a,contentActive:i,composerActive:l,sidebarOpen:o,replacingWithEmpty:d,replacementDisabled:c,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,gitRuntime:x,invokePluginMethod:b,listPiCommands:v,getChatModelContext:w,capabilityModes:y,setChatCapabilityMode:k,branchPicker:j,branchPending:I,mobile:S,fileRuntime:M,onOpenFileSidebar:z,onPreviewFile:E,onAcknowledgeCompleted:A,onFocusWorkSession:$,onReplaceWithEmptyWorkSession:R,onOpenBranchPicker:P,onOpenGitBranchPicker:T,onCloseBranchPicker:D,onRetryBranchPicker:L,onSelectBranchEntry:O,onBranchAction:F,onConfirmRunningBranch:B,onCancelRunningBranch:_,onCloneWorkSession:q,onUnpinWorkSession:W,onToggleSidebar:Y}){let{t:V}=(0,f.Bd)("workbench"),K=(0,r.useRef)(null);sZ(K,`${t.workId}:${t.sessionId}:${t.branchId}`);let H=function(e,t){let{t:s}=(0,f.Bd)("workbench"),n=(0,eC.G)(),a=(0,r.useMemo)(()=>({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId}),[e.workId,e.sessionId,e.branchId]),i=(0,r.useCallback)(()=>t.getSourceState(a).runtime,[t,a]),l=(0,r.useSyncExternalStore)(t.subscribe,i,i),o=(0,r.useCallback)(()=>t.getSourceState(a).syncStatus,[t,a]),d=(0,r.useSyncExternalStore)(t.subscribe,o,o),c="basic"===l.extensionMode?l.initializationError:null,[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),g=!p&&"ready"===d&&"main_running"!==e.status&&"background_running"!==e.status,x=c?`${e.cwd}
156
156
  ${a.sessionId}
157
157