@jetcrab/pi-desk 1.1.0-dev.1 → 1.1.1-dev
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/server/l4_foundation/model-settings/l4-model-settings-store.ts +3 -5
- package/src/server/l4_foundation/pi/l4-pi-session-catalog.ts +22 -63
- package/src/server/l4_foundation/pi/l4-pi-session-discovery.ts +139 -0
- package/src/server/l4_foundation/pi/l4-pi-session-history-catalog.ts +36 -7
- package/temp/build/pi-desk/release/.next/BUILD_ID +1 -1
- package/temp/build/pi-desk/release/.next/build-manifest.json +2 -2
- package/temp/build/pi-desk/release/.next/required-server-files.js +2 -2
- package/temp/build/pi-desk/release/.next/required-server-files.json +2 -2
- package/temp/build/pi-desk/release/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_global-error.html +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_global-error.rsc +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/temp/build/pi-desk/release/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/api/health/route.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/api/model-catalog/list/route.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/api/model-settings/get/route.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/api/model-settings/replace/route.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/api/project-model-default/get/route.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/api/project-model-default/replace/route.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/page.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/chunks/25406.js +6 -6
- package/temp/build/pi-desk/release/.next/server/chunks/3108.js +3 -3
- package/temp/build/pi-desk/release/.next/server/chunks/78262.js +3 -3
- package/temp/build/pi-desk/release/.next/server/middleware-build-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/pages/500.html +1 -1
- package/temp/build/pi-desk/release/.next/static/chunks/app/{page-d4483fde1c24ca09.js → page-a85b2f17c68cff60.js} +1 -1
- package/temp/build/pi-desk/release/.next/trace-build +1 -1
- /package/temp/build/pi-desk/release/.next/static/{1lCPwFThMmH5Cmw0l1LcT → AIPx4Oo1zqM8gixtv1I69}/_buildManifest.js +0 -0
- /package/temp/build/pi-desk/release/.next/static/{1lCPwFThMmH5Cmw0l1LcT → AIPx4Oo1zqM8gixtv1I69}/_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(84942);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(5464);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(87372),e1=s(79566),e2=s(13344),e5=s(54359),e3=s(24022),e4=s(77483),e6=s(95526),e8=s(66584),e7=s(76085),e9=s(58619),te=s(90695),tt=s(6609);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(94173),ti=s(86758),tl=s(81649);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 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(15265),tp=s(5816),th=s(90434),tg=s(99084);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:${tR(e)?.name??e}`}function tD(e){switch(e.kind){case"batch":return"add"===e.input.action?"batchInstall":"update"===e.input.action?"updateSelected":"del"===e.input.action?"removeSelected":"setChannel";case"add":return"actionAdd";case"update":return"actionUpdate";case"del":return"actionDelete";case"enable":return"enable";case"disable":return"disable";case"reload":return"normal"===e.mode?"restartNormal":"actionReload"}}let tL=a.Yj().trim().min(1).max(128).regex(/^[a-zA-Z][a-zA-Z0-9._-]*$/),tO=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 仓库地址"),tF=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:tO}).strict()]),tB=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),tB).optional()}).passthrough().optional()}).passthrough();let t_=a.Ik({downloadSource:tF,recommendedRegistry:tO}).strict(),tq=a.Ik({downloadSource:tF}).strict(),tW=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:tO.optional()}).strict(),tU=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:tO.optional()}).strict(),tY=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:tO}).strict(),tV=a.Ik({items:a.YO(tY),hasMore:a.zM()}).strict(),tK=tY.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 tH({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]})}var tG=s(60567),tJ=s(48742),tX=s(3058);function tQ({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 tZ({value:e,label:t,placeholder:s,disabled:r,onChange:a}){let{t:i}=(0,f.Bd)("pluginManagement"),l=[...s?[{value:"",label:s}]:[],{value:"latest",label:i("channelLatest")},{value:"dev",label:i("channelDev")}];return(0,n.jsxs)(eP.l6,{value:e,items:l,disabled:r,onValueChange:e=>{null!==e&&a(e)},children:[(0,n.jsx)(eP.bq,{"aria-label":t,className:"max-w-full",children:(0,n.jsx)(eP.yv,{})}),(0,n.jsx)(eP.gC,{positionerClassName:"z-[160]",children:l.map(e=>(0,n.jsx)(eP.eb,{value:e.value,children:e.label},e.value))})]})}function t0({snapshot:e,loading:t,filter:s,disabled:r,requests:a,errors:i,browserErrors:l,channel:o,selected:d,onChannel:c,onSelect:u,onCheckSelected:m,onUpdateSelected:p,onRemoveSelected:h,onTagSelected:g,onFilter:x,onDetail:b,onAction:v,onDirectInstall:w,onRefresh:y}){let{t:k}=(0,f.Bd)("pluginManagement"),{locale:j}=(0,tp.i)(),I=e?.plugins.filter(e=>(!o||e.source.startsWith("npm:")&&(e.updateTag??"latest")===o)&&`${tP(e)} ${e.description?(0,tm.fD)(e.description,j):""}`.toLocaleLowerCase().includes(s.toLocaleLowerCase()))??[],C=I.filter(e=>"extension"!==e.kind),S=e?.plugins.filter(e=>d.has(tT(e.source)))??[],M=S.filter(e=>e.source.startsWith("npm:")),z=S.filter(e=>!a.has(tT(e.source))&&(!e.operation||"failed"===e.operation.phase)),E=C.length>0&&C.every(e=>d.has(tT(e.source))),A=C.some(e=>d.has(tT(e.source))),$=z.filter(e=>e.source.startsWith("npm:")),R=S.length>32;return(0,n.jsxs)("section",{"aria-label":k("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:k("filterInstalled")}),(0,n.jsx)(eB.p,{id:"plugin-installed-filter",value:s,onChange:e=>x(e.target.value),placeholder:k("filterInstalled"),className:"min-w-0 flex-1 basis-48"}),(0,n.jsx)(tZ,{value:o,label:k("filterChannel"),placeholder:k("allChannels"),onChange:c}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:t,onClick:y,children:k(t?"checkingUpdates":"checkUpdates")}),(0,n.jsx)(N.$,{size:"sm",disabled:r,onClick:w,children:k("directInstall")})]}),C.length||S.length?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 rounded-lg bg-muted p-2",children:[(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 px-1 text-sm",children:[(0,n.jsx)(tG.y,{checked:E,indeterminate:A&&!E,disabled:!C.length,onCheckedChange:e=>u(C.map(e=>tT(e.source)),e),className:"flex size-5 shrink-0 items-center justify-center rounded border border-input bg-background outline-none data-checked:bg-primary data-checked:text-primary-foreground focus-visible:ring-2 focus-visible:ring-ring",children:(0,n.jsx)(tJ.P,{children:A&&!E?(0,n.jsx)(tX.A,{className:"size-4"}):(0,n.jsx)(ed.A,{className:"size-4"})})}),k("selectFiltered")]}),S.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:k("selectedCount",{count:S.length})}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:t||!M.length||R,onClick:m,children:k("checkSelected")}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:r||!z.length||R,onClick:p,children:k("updateSelected")}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:r||!z.length||R,onClick:h,children:k("removeSelected")}),(0,n.jsx)(tZ,{value:"",label:k("setChannel"),placeholder:k("setChannel"),disabled:r||!$.length||R,onChange:e=>{e&&g(e)}}),(0,n.jsx)(N.$,{size:"sm",variant:"ghost",onClick:()=>u([...d],!1),children:k("clearSelection")})]}):null,R?(0,n.jsx)("p",{role:"status",className:"w-full text-sm text-muted-foreground",children:k("batchLimit")}):null]}):null,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:k("loading")}):I.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:I.map(e=>{let t=tP(e),s=tT(e.source);return(0,n.jsxs)("article",{className:`min-w-0 space-y-3 p-4 ${d.has(s)?"bg-accent/40":""}`,children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:["extension"!==e.kind?(0,n.jsx)(tG.y,{checked:d.has(s),"aria-label":k("selectPlugin",{name:t}),onCheckedChange:e=>u([s],e),className:"flex size-6 shrink-0 items-center justify-center rounded border border-input bg-background outline-none data-checked:bg-primary data-checked:text-primary-foreground focus-visible:ring-2 focus-visible:ring-ring",children:(0,n.jsx)(tJ.P,{children:(0,n.jsx)(ed.A,{className:"size-4"})})}):null,(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":k("viewDetails",{name:t}),onClick:()=>b(e.source),children:t}),e.version?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",e.version]}):null]}),e.source.startsWith("npm:")?(0,n.jsxs)("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[(0,n.jsx)("span",{children:k("followingChannel",{tag:e.updateTag??"latest"})}),e.availableVersion?(0,n.jsx)("span",{children:k("targetVersion",{version:e.availableVersion})}):null,e.updateError?(0,n.jsx)("p",{role:"alert",className:"w-full text-sm text-destructive",children:k("itemCheckFailed",{error:e.updateError})}):null]}):null,(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.description?(0,tm.fD)(e.description,j):k("noPluginDescription")}),(0,n.jsx)(tQ,{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=>v(e,t)})]},s)})}):(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:k(s||o?"noMatches":"empty")})]})}function t1(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 t2=(0,s(73392).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 t5({className:e,orientation:t,...s}){return(0,n.jsx)("div",{role:"group","data-slot":"button-group","data-orientation":t,className:(0,C.cn)(t2({orientation:t}),e),...s})}var t3=s(32892),t4=s(57445),t6=s(73028),t8=s(48318),t7=s(93356),t9=s(10508);let se=({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}),st=({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}),ss=({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)(t3.Bc,{children:(0,n.jsxs)(t3.m_,{children:[(0,n.jsx)(t3.k$,{render:l}),(0,n.jsx)(t3.ZI,{children:(0,n.jsx)("p",{children:e})})]})}):l},sn={cjk:t4.h,code:t6.a,math:t8.D,mermaid:t7.a},sr=(0,r.memo)(({className:e,...t})=>(0,n.jsx)(t9.jH,{className:(0,C.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),plugins:sn,...t}),(e,t)=>e.children===t.children&&t.isAnimating===e.isAnimating);sr.displayName="MessageResponse";let sa=({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 si({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)(sr,{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 sl(e){if(!e)return null;try{let t=new URL(e);return["https:","http:"].includes(t.protocol)?t.href:null}catch{return null}}function so(e){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,tp.i)(),r=e.detail,a=e.installed&&e.installedVersion===r.version,i=sl(r.homepage),l=sl(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)(tH,{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)(si,{readme:r.readme},`${r.name}@${r.version}`)})]})}var sd=s(68017);function sc(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)(sd.T,{id:"plugin-direct-source",value:e.source,placeholder:t("batchSourcePlaceholder"),rows:3,onChange:t=>e.onSource(t.target.value)}),e.isNpm||e.multiple?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(tZ,{value:e.tag,label:t("installChannel"),placeholder:t("defaultChannel"),onChange:e.onTag})]}),e.isNpm?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onRead,children:t(e.loading?"loadingPackage":"readPackage")}):null,e.detail?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.detail.name}),(0,n.jsxs)(eP.l6,{value:e.selectedVersion,disabled:e.loading,items:[{value:"",label:t("automaticVersion")},...[...new Set([e.detail.version,...e.detail.versions])].map(e=>({value:e,label:e}))],onValueChange:t=>{null!==t&&e.onVersion(t)},children:[(0,n.jsx)(eP.bq,{"aria-label":t("version"),className:"max-w-full",children:(0,n.jsx)(eP.yv,{})}),(0,n.jsxs)(eP.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(eP.eb,{value:"",children:t("automaticVersion")}),[...new Set([e.detail.version,...e.detail.versions])].map(e=>(0,n.jsx)(eP.eb,{value:e,children:e},e))]})]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t("targetVersion",{version:e.detail.version})})]}):null,(0,n.jsx)(tH,{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 whitespace-pre-wrap text-destructive [overflow-wrap:anywhere]",children:e.error}):null,e.operationMessage?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operationMessage}):null,(0,n.jsx)(N.$,{size:"sm",disabled:e.disabled||e.loading||e.pending||!e.source.trim(),onClick:e.onInstall,children:t(e.pending?"installing":e.multiple?"batchInstall":"install")})]})}function su({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||"batch"===s.kind&&"del"===s.input.action?"removeDescription":"add"===s.kind||"batch"===s.kind&&"add"===s.input.action?"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?"batch"===s.kind?(0,n.jsx)("ul",{className:"space-y-2 text-sm",children:("add"===s.input.action?s.input.items.map(e=>e.source):s.input.sources).map(e=>(0,n.jsx)("li",{className:"font-medium [overflow-wrap:anywhere]",children:e},e))}):"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")})]}),s.input.tag?(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:l("installChannel")}),(0,n.jsx)("dd",{children:s.input.tag})]}):null,(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||"batch"===s.kind&&"del"===s.input.action?"destructive":"default",onClick:()=>a(s),children:o})]}):null]})})}function sm({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,h]=(0,r.useState)(""),[g,x]=(0,r.useState)(()=>new Set);(0,r.useEffect)(()=>{if(!t)return;let e=new Set(t.plugins.map(e=>tT(e.source)));[...g].some(t=>!e.has(t))&&queueMicrotask(()=>x(t=>new Set([...t].filter(t=>e.has(t)))))},[t,g]);let[b,v]=(0,r.useState)(""),[w,y]=(0,r.useState)(!1),k=function({biz:e,snapshot:t,onSnapshot:s,onRestartScheduled:n}){let{t:a}=(0,f.Bd)("pluginManagement"),i=(0,eI.t4)();(0,eI.So)();let[l,o]=(0,r.useState)(!1),[d,c]=(0,r.useState)(()=>new Set),u=(0,r.useRef)(new Set),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)({}),[x,b]=(0,r.useState)(null),[v,w]=(0,r.useState)(null),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(null),I=(0,r.useRef)(0),C=(0,r.useRef)(0),S=(0,r.useRef)(!0),M=(e,t)=>{t?u.current.add(e):u.current.delete(e),S.current&&c(new Set(u.current))},z=(e,t)=>{S.current&&g(s=>{let n={...s};return t?n[e]=t:delete n[e],n})},E=e=>{let s=tT(e);return u.current.has(s)||!!t?.plugins.some(e=>tT(e.source)===s&&e.operation&&"failed"!==e.operation.phase)},A=async(t=!1)=>{let n=++C.current,r=await e.list(t);S.current&&n===C.current&&s(r)},$=async(e,s)=>{if(u.current.has("check"))return;let n=e??t?.plugins.filter(e=>"package"===e.kind&&(!s||e.updateTag===s)).map(e=>e.source)??[],r=n.filter(E),i=n.filter(e=>!E(e));if(r.forEach(e=>z(tT(e),a("sourceBusy"))),!i.length)return;if(r.length&&i.length>32)return void z("list",a("batchLimit"));let l=i.map(tT);M("check",!0),l.forEach(e=>M(e,!0)),o(!0),z("list",null);try{await A({checkUpdates:!0,...e||r.length?{sources:i}:{},...s?{tag:s}:{}})}catch(e){z("list",e instanceof Error?e.message:a("updateCheckFailed"))}finally{M("check",!1),l.forEach(e=>M(e,!1)),S.current&&o(!1)}};(0,r.useEffect)(()=>{S.current=!0;let t=!0,n=++C.current;return queueMicrotask(()=>{t&&(o(!0),e.list(!1).then(e=>{t&&n===C.current&&s(e)}).catch(e=>{t&&z("list",e instanceof Error?e.message:a("updateCheckFailed"))}).finally(()=>{t&&o(!1)}))}),()=>{t=!1,S.current=!1,I.current+=1,C.current+=1}},[e,s,a]);let R=async t=>{let n="add"===t.action?t.items.map(e=>e.source):t.sources,r=n.filter(e=>!E(e));if(n.filter(E).forEach(e=>z(tT(e),a("sourceBusy"))),!r.length)return;let i=r.map(tT);i.forEach(e=>{M(e,!0),z(e,null)}),p(null);try{let n="add"===t.action?{...t,items:t.items.filter(e=>r.includes(e.source))}:{...t,sources:r},a=await e.batch(n);if(!S.current)return;C.current+=1,s(a.snapshot),a.results.forEach(e=>z(tT(e.source),e.error))}catch(t){let e=t instanceof Error?t.message:a("batchFailed");i.forEach(t=>z(t,e))}finally{i.forEach(e=>M(e,!1))}},P=async t=>{if("batch"===t.kind)return void await R(t.input);if("reload"!==t.kind&&E("add"===t.kind?t.input.source:t.source))return;let r="reload"===t.kind?"reload":tT("add"===t.kind?t.input.source:t.source);if(!u.current.has(r)){M(r,!0),p(null),z(r,null);try{let r="add"===t.kind?await e.add(t.input):"update"===t.kind?await e.update(t.source):"del"===t.kind?await e.del(t.source):"enable"===t.kind||"disable"===t.kind?await e.setEnabled(t.source,"enable"===t.kind):await e.reload(t.mode);if(!S.current)return;C.current+=1,s(r),"reload"===t.kind?n():await A()}catch(e){z(r,e instanceof Error?e.message:a("actionFailed",{action:a(tD(t))}))}finally{M(r,!1)}}},T=(e,t)=>{let s={kind:"add",input:e,package:t};t?.official===!0?P(s):p(s)},D=async t=>{let n=t?.[0]?tT(t[0]):"apply";if(!u.current.has(n)){M(n,!0),z(n,null);try{let n=await e.apply(t);S.current&&(C.current+=1,s(n),await A())}catch(e){z(n,e instanceof Error?e.message:a("actionFailed",{action:a("reloadOne")}))}finally{M(n,!1)}}},L=async(e,t)=>{if(!u.current.has(e)){M(e,!0),z(e,null);try{await t()}catch(t){z(e,t instanceof Error?t.message:a("retryFailed"))}finally{M(e,!1)}}},O=async t=>{let s=++I.current;k(!0),N(null);try{let n=await e.get(t);S.current&&s===I.current&&w(n)}catch(e){S.current&&s===I.current&&N(e instanceof Error?e.message:a("detailFailed"))}finally{S.current&&s===I.current&&k(!1)}};return{loading:l,requests:d,confirmation:m,setConfirmation:p,errors:h,detailSource:x,detail:v,detailLoading:y,detailError:j,pluginHost:i,refresh:$,executeBatch:R,execute:P,requestInstall:T,applyChanges:D,loadDetail:O,openDetail:e=>{b(e),w(null),O(e)},closeDetail:()=>{I.current+=1,b(null),w(null),N(null),k(!1)},handleControlAction:(e,t)=>{switch(t){case"reload":D([e.source]);break;case"update":P({kind:"update",source:e.source});break;case"remove":p({kind:"del",source:e.source});break;case"enable":case"disable":P({kind:t,source:e.source});break;case"retry-browser":e.pluginName&&L(`entry:${e.pluginName}`,()=>i.retryEntry(e.pluginName));break;case"retry":{let t=e.operation?.action;"apply"===t?D([e.source]):"add"===t?T({source:e.source}):t&&P({kind:t,source:e.source})}}},refreshEntries:()=>L("entries",()=>i.refreshEntries())}}({biz:s,snapshot:t,onSnapshot:a,onRestartScheduled:i}),j=t?.plugins.filter(e=>g.has(tT(e.source))).map(e=>e.source)??[],I=j.filter(e=>e.startsWith("npm:")),C=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?tO.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?tO.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:tF.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),S=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=tF.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),M=function(e,t=[]){let{t:s}=(0,f.Bd)("pluginManagement"),[n,a]=(0,r.useState)(!1),[i,l]=(0,r.useState)(""),[o,d]=(0,r.useState)(""),[c,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[x,b]=(0,r.useState)(null),[v,w]=(0,r.useState)("default"),[y,k]=(0,r.useState)(""),j=(0,r.useRef)(0),N=(0,r.useRef)(!0),I=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),C=1===I.length?tR(I[0]):null;(0,r.useEffect)(()=>(N.current=!0,()=>{N.current=!1,j.current+=1}),[]);let S=()=>{j.current+=1,p(null),g(!1),b(null)},M=async n=>{let r;if(!C)return null;void 0!==n&&u(n||null);let a=t.find(e=>tR(e.source)?.name===C.name)?.updateTag,i=C.version??(o||a||"latest"),l=""===n?i:n??c??i;if("custom"===v){let e=tO.safeParse(y);if(!e.success)return b(s("invalidRegistry")),null;r=e.data}else"official"===v?r="https://registry.npmjs.org":"domestic"===v&&(r="https://registry.npmmirror.com");let d=++j.current;g(!0),p(null),b(null);try{let t=await e.getCatalog({...C,...l?{version:l}:{},...r?{registry:r}:{}});if(!N.current||d!==j.current)return null;return p(t),t}catch(e){return N.current&&d===j.current&&b(e instanceof Error?e.message:s("detailFailed")),null}finally{N.current&&d===j.current&&g(!1)}},z=async(e,t)=>{if(!I.length||h)return;b(null);let n="default"===v?null:tF.safeParse("custom"===v?{mode:v,registry:y}:{mode:v});if(n&&!n.success)return void b(s("invalidRegistry"));let r={...o?{tag:o}:{},...n?.success?{downloadSource:n.data}:{}};if(I.length>1){let e=I.map(tR);if(I.length>32||e.some(e=>!e))return void b(s(I.length>32?"batchLimit":"batchNpmOnly"));let n=new Map;return e.forEach(e=>{e&&n.set(e.name,{source:`npm:${e.name}${e.version?`@${e.version}`:""}`,...r})}),void t([...n.values()])}if(!C)return void e({source:I[0]});let a=m?Promise.resolve(m):M(c??void 0),i=j.current,l=await a;if(l&&N.current&&i===j.current){if(!1===l.compatible)return void b(s("installIncompatible"));e({source:`npm:${l.name}${c||C.version?`@${c??C.version}`:""}`,registry:l.registry,...r},l)}};return{open:n,setOpen:a,source:i,sources:I,tag:o,selectedVersion:c??"",setTag:e=>{S(),u(null),d(e)},changeSource:e=>{S(),u(null),l(e)},spec:C,detail:m,loading:h,error:x,override:v,setOverride:e=>{S(),w(e)},registry:y,setRegistry:e=>{S(),k(e)},loadDetail:M,install:z}}(s,t?.plugins),z=e||k.requests.has("reload"),E=new Map(k.pluginHost.getFailedEntries().map(e=>[e.pluginName,e.error.message])),A=k.pluginHost.getEntryListError(),$=t?.plugins.find(e=>e.source===k.detailSource),R=C.selection?t?.plugins.find(e=>e.source.startsWith("npm:")&&tR(e.source)?.name===C.selection?.name):void 0,P=C.selection?tT(`npm:${C.selection.name}`):"",T=tT(M.detail?`npm:${M.detail.name}`:M.spec?`npm:${M.spec.name}`:M.source.trim()),D=t?.plugins.find(e=>tT(e.source)===T),L=k.requests.has(P)||!!(R?.operation&&"failed"!==R.operation.phase),O=M.sources.length>0&&M.sources.every(e=>{let s=tT(e),n=t?.plugins.find(e=>tT(e.source)===s);return k.requests.has(s)||!!(n?.operation&&"failed"!==n.operation.phase)}),F=M.sources.map(e=>{let s=tT(e),n=t?.plugins.find(e=>tT(e.source)===s),r=k.errors[s]??(n?.operation?.phase==="failed"?n.operation.message:null);return r?`${e}: ${r}`:null}).filter(Boolean).join("\n"),B=e=>{let s=t?.plugins.find(t=>tR(t.source)?.name===e.name),n=b||s?.updateTag;return n?{...e,version:n}:e},_=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"),":",S.loading&&!S.settings?l("loading"):l(`download_${S.settings?.downloadSource.mode??S.mode}`),(0,n.jsx)(ti.A,{className:"size-4"})]}),(0,n.jsx)(th.hl,{align:"end",positionerClassName:"z-[150]",children:(0,n.jsx)(tH,{id:"plugin-default-download",mode:S.mode,registry:S.registry,savedRegistry:S.settings?.downloadSource.mode==="custom"?S.settings.downloadSource.registry:void 0,recommendedRegistry:S.settings?.recommendedRegistry,loading:S.loading,saving:S.saving,error:S.error,onMode:e=>{"default"!==e&&S.changeMode(e)},onRegistry:S.setRegistry,onSave:()=>void S.save(),onRetry:()=>void S.retry()})})]}),e||t?.restartRequired?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:k.requests.has("reload"),onClick:()=>k.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||A?(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,A?(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:A}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:k.requests.has("entries"),onClick:()=>void k.refreshEntries(),children:l("retry")})]}):null]}):null,k.errors.reload||k.errors.entries?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:k.errors.reload??k.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:[M.open?(0,n.jsx)(sc,{source:M.source,isNpm:!!M.spec,multiple:M.sources.length>1,tag:M.tag,selectedVersion:M.selectedVersion,onTag:M.setTag,detail:M.detail,loading:M.loading,pending:O,disabled:z,error:M.error??(F||null)??(D?.operation?.phase==="failed"?D.operation.message:null),operationMessage:O?_(D?.operation?.phase)??l("submitting"):null,override:M.override,registry:M.registry,onSource:M.changeSource,onMode:M.setOverride,onRegistry:M.setRegistry,onRead:()=>void M.loadDetail(),onVersion:e=>void M.loadDetail(e),onInstall:()=>void M.install(k.requestInstall,e=>k.setConfirmation({kind:"batch",input:{action:"add",items:e}})),onClose:()=>M.setOpen(!1)}):null,(0,n.jsx)(t0,{snapshot:t,loading:k.loading,filter:u,channel:p,selected:g,onChannel:h,onSelect:(e,t)=>{x(s=>{let n=new Set(s);return e.forEach(e=>{t?n.add(e):n.delete(e)}),n})},onCheckSelected:()=>void k.refresh(I),onUpdateSelected:()=>void k.executeBatch({action:"update",sources:j}),onRemoveSelected:()=>k.setConfirmation({kind:"batch",input:{action:"del",sources:j}}),onTagSelected:e=>void k.executeBatch({action:"tag",sources:I,tag:e}),disabled:z,requests:k.requests,errors:k.errors,browserErrors:E,onFilter:m,onDetail:e=>{C.closeDetail(),k.openDetail(e)},onAction:k.handleControlAction,onDirectInstall:()=>M.setOpen(!0),onRefresh:()=>void k.refresh(void 0,p||void 0)})]})}),(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)(t1,{query:C.query,kind:C.kind,searchSource:C.searchSource,registry:C.registry,items:C.items,loading:C.loading,error:C.error,searched:C.searched,hasMore:C.hasMore,disabled:z,snapshot:t,requests:k.requests,preparing:C.preparing,errors:k.errors,installErrors:C.installErrors,onQuery:C.setQuery,onCompositionStart:C.beginComposition,onCompositionEnd:C.endComposition,onKind:C.setKind,onSearchSource:C.setSearchSource,onRegistry:C.setRegistry,onDetail:e=>{k.closeDetail(),y(!1),C.openDetail(B(e))},onInstall:e=>{C.prepareInstall(B(e),e=>k.requestInstall({source:`npm:${e.name}`,registry:e.registry,...b?{tag:b}:{}},e))},onUpdate:e=>void k.execute({kind:"update",source:e}),onMore:C.loadMore,onRetry:C.retry})}),(0,n.jsx)(su,{open:!!(k.confirmation||k.detailSource||C.selection),title:$?tP($):C.selection?.name??l("details"),confirmation:k.confirmation,onClose:()=>{k.confirmation?k.setConfirmation(null):(k.closeDetail(),C.closeDetail())},onConfirm:e=>void k.execute(e),children:$?(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[k.detail?.readme?(0,n.jsx)(si,{readme:k.detail.readme},$.source):null,(0,n.jsx)(t$,{plugin:$,detail:k.detail,detailLoading:k.detailLoading,detailError:k.detailError,browserContributions:$.pluginName?k.pluginHost.getRegisteredBrowserDescriptors().find(e=>e.pluginName===$.pluginName)?.contributions??[]:[],onRetry:()=>void k.loadDetail($.source)})]}):C.selection?C.detailLoading?(0,n.jsx)("p",{role:"status",className:"py-4 text-sm text-muted-foreground",children:l("loadingPackage")}):C.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:C.detailError}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",onClick:()=>void C.loadDetail(C.selection),children:l("retry")})]}):C.detail?(0,n.jsxs)("div",{className:"min-w-0 space-y-4",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:l("installChannel")}),(0,n.jsx)(tZ,{value:b,label:l("installChannel"),placeholder:l("defaultChannel"),disabled:L,onChange:e=>{v(e),y(!1),C.loadDetail(C.selection,e||R?.updateTag||"latest")}})]}),(0,n.jsx)(so,{detail:C.detail,disabled:z,pending:L,installed:!!(R&&(R.operation?.action!=="add"||"failed"!==R.operation.phase)),installedVersion:R?.version??null,updateAvailable:!!R?.updateAvailable,error:C.installErrors[C.detail.name]??k.errors[P]??(R?.operation?.phase==="failed"?R.operation.message:null),operationMessage:_(R?.operation?.phase),downloadMode:C.downloadMode,downloadRegistry:C.downloadRegistry,onDownloadMode:C.setDownloadMode,onDownloadRegistry:C.setDownloadRegistry,onVersion:e=>{y(!0),C.loadDetail(C.selection,e)},onInstall:()=>C.installDetail((e,t)=>k.requestInstall({...e,source:w?e.source:`npm:${t.name}`,...b?{tag:b}:{}},t)),onUpdate:()=>{R&&k.execute({kind:"update",source:R.source})}})]}):null:k.detailSource?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:l("pluginRemoved")}):null})]})}var sp=s(99739);let sh=a.Yj().trim().min(1).max(2048),sg=a.YO(sh).min(1).max(32),sx=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(),sf=a.Yj().trim().min(1).max(4096),sb=a.Yj().trim().min(1).max(256),sv=a.Yj().max(32768),sw=a.Ik({name:sb,label:sv,state:a.k5(["active","inactive","shadowed"]),description:sv,promptSnippet:sv.nullable(),promptGuidelineCount:a.ai().int().nonnegative(),promptGuidelinePreview:sv.nullable()}).strict(),sy=a.Ik({name:sb,label:sv,state:a.k5(["active","inactive","shadowed"]),description:sv,parameters:sp.Dz,promptSnippet:sv.nullable(),promptGuidelines:a.YO(sv)}).strict(),sk=a.Ik({path:sf,events:a.YO(a.Ik({name:sb,count:a.ai().int().positive()}).strict()),commands:a.YO(a.Ik({name:sb,description:sv.nullable()}).strict()),shortcuts:a.YO(a.Ik({shortcut:sb,description:sv.nullable()}).strict()),flags:a.YO(a.Ik({name:sb,type:a.k5(["boolean","string"]),description:sv.nullable(),default:a.KC([a.zM(),a.Yj(),a.ch()])}).strict()),messageRenderers:a.YO(sb),entryRenderers:a.YO(sb)}).strict(),sj=a.Ik({name:sb,description:sv,path:sf}).strict(),sN=sj.extend({modelVisible:a.zM()}).strict(),sI=sj.extend({content:a.Yj().max(65536),truncated:a.zM()}).strict(),sC=sI.extend({modelVisible:a.zM()}).strict(),sS=a.Ik({name:sb,path:sf}).strict(),sM=a.Ik({name:sb,kind:a.k5(["config","native"])}).strict(),sz=a.Ik({methods:a.YO(a.Ik({pluginName:sb,method:sb}).strict()),browserEntries:a.YO(a.Ik({pluginName:sb}).strict()),messageDeclarations:a.YO(a.Ik({pluginName:sb,declarationName:sb,priority:a.ai().int().safe()}).strict())}).strict(),sE=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(sk),tools:a.YO(sw),skills:a.YO(sN),prompts:a.YO(sj),themes:a.YO(sS),providers:a.YO(sM),piDesk:sz}).strict(),sA=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(),s$=(0,i._G)({path:"plugins/management-update",bodySchema:a.Ik({}).strict()}),sR=a.Ik({source:sh,kind:a.k5(["package","extension"]).default("package"),operation:sA.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(),updateTag:tL.nullable().optional(),availableVersion:a.Yj().min(1).nullable().optional(),updateError:a.Yj().max(4e3).nullable().optional(),status:a.k5(["ready","available","disabled","failed"]),error:sx.nullable(),capabilities:sE}).strict(),sP=a.Ik({source:sh,readme:tm.qf.nullable().default(null),tools:a.YO(sy),skills:a.YO(sC),prompts:a.YO(sI)}).strict(),sT=a.Ik({plugins:a.YO(sR),restartRequired:a.zM(),loadError:tm.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0).nullable()}).strict(),sD=a.Ik({sources:a.YO(sh).min(1).max(32).optional()}).strict(),sL=a.Ik({}).strict().extend({mode:a.k5(["normal","basic"]).optional()}).strict(),sO=a.Ik({checkUpdates:a.zM().optional(),sources:sg.optional(),tag:tL.optional()}).strict(),sF=a.Ik({source:sh}).strict(),sB=sF.extend({downloadSource:tF.optional(),registry:tO.optional(),tag:tL.optional()}).strict(),s_=a.gM("action",[a.Ik({action:a.eu("add"),items:a.YO(sB).min(1).max(32)}).strict(),a.Ik({action:a.eu("update"),sources:sg}).strict(),a.Ik({action:a.eu("del"),sources:sg}).strict(),a.Ik({action:a.eu("tag"),sources:sg,tag:tL}).strict()]),sq=a.Ik({snapshot:sT,results:a.YO(a.Ik({source:sh,error:a.Yj().max(4e3).nullable()}).strict()).max(32)}).strict(),sW=sF.extend({enabled:a.zM()}).strict();async function sU(e,t,s,n){return eF(e,t,s,n,{fallbackMessage:"插件管理请求失败"})}function sY({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 sV({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 sK=s(10263),sH=s(11831),sG=s(79615),sJ=s(24863),sX=s(10672);let sQ="1.1.0-dev.1".trim()||"未知",sZ="2026-10-09T20:49:19+08:00".trim()||null;var s0=s(42655),s1=s(36919);let s2="pi-desk:power-saving",s5="pi-desk:power-saving-change",s3=null;function s4(){if(null!==s3)return s3;try{s3="true"===window.localStorage.getItem(s2)}catch{s3=!1}return s3}function s6(e){let t=t=>{(null===t.key||t.key===s2)&&(s3=null,e())};return window.addEventListener(s5,e),window.addEventListener("storage",t),()=>{window.removeEventListener(s5,e),window.removeEventListener("storage",t)}}function s8(){return(0,r.useSyncExternalStore)(s6,s4,()=>!1)}function s7(e,t){let s=(0,s1.I)(),n=s8(),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 s9=s(55079),ne=s(49667),nt=s(61286),ns=s(33550),nn=s(66453),nr=s(67765);let na=a.Yj().min(1).max(nr.uV).refine(e=>!e.includes("\0")&&(e.startsWith("/")||e.startsWith("\\\\")||/^[a-zA-Z]:[\\/]/.test(e)),"必须是绝对路径"),ni=a.Ik({cwd:nn.m4.nullable()}).strict(),nl=a.Ik({skillPath:na,name:a.Yj().min(1),description:a.Yj(),packageSource:a.Yj().nullable()}).strict(),no=a.Ik({skills:a.YO(nl),diagnostics:a.YO(a.Ik({path:a.Yj(),message:tm.qf}).strict())}).strict(),nd=ni.extend({skillPath:na}),nc=nd.extend({path:nr.rh}).strict(),nu=a.Ik({entries:a.YO(a.Ik({name:a.Yj().min(1),type:a.k5(["directory","file"])}).strict()).max(nr.xm),truncated:a.zM()}).strict(),nm=nd.extend({path:nr._g}).strict(),np=a.gM("kind",[a.Ik({kind:a.eu("text"),content:a.Yj(),size:a.ai().int().nonnegative().max(nr.NL),readOnlyReason:tm.qf.nullable()}).strict(),a.Ik({kind:a.eu("image"),mimeType:nr.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()]),nh=nm.extend({content:a.Yj().max(nr.NL)}).strict(),ng=a.Ik({}).strict(),nx={path:"/api/skills/list",request:ni,response:no},nf={path:"/api/skill-files/list",request:nc,response:nu},nb={path:"/api/skill-files/get",request:nm,response:np},nv={path:"/api/skill-files/replace",request:nh,response:ng},nw=a.Ik({code:a.ai(),msg:a.Yj(),data:a.L5(),i18n:nt.N.optional()});async function ny(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=nw.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 nk(e){(0,ns.ZQ)({wrapLines:e})}async function nj(e){let t=e.skillPath.replaceAll("\\","/");await navigator.clipboard.writeText(t.slice(0,t.lastIndexOf("/")+1)+e.path)}var nN=s(46782);function nI(e){return(0,eO.B)({msg:nN.P["zh-CN"][e],i18n:{key:`skills:${e}`}})}function nC(e){return JSON.stringify(e)}function nS(e){return JSON.stringify([e.cwd,e.skillPath,e.path])}function nM(e){return e.replace(/\r\n|\r/g,"\n")}function nz(e){return e?.file?.kind==="text"&&e.draft!==nM(e.file.content)}var nE=s(60794),nA=s(89757),n$=s(55628),nR=s(91182);function nP(e){let{t}=(0,f.Bd)("common"),{wrapLines:s}=(0,ns.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,nR.cu)().then(r=>{if(e||!i.current)return;let a=m.current,o=r.editor.create(i.current,{model:null,theme:(0,nR.dC)(),automaticLayout:!0,readOnly:a.readOnly,domReadOnly:a.readOnly,wordWrap:(0,ns.E6)().wrapLines?"on":"off",wrappingIndent:"same",minimap:{enabled:!1},stickyScroll:{enabled:!1},scrollBeyondLastLine:!1,...(0,nR.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,nR.Tr)(e=>r.editor.setTheme(e)),n=(0,nR.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,nR.cu)().then(s=>{if(e||t!==u.current||!l.current)return;let n=m.current,r=s.editor.createModel(n.content,(0,nR.ix)(n.path,n.size),(0,nR.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 nT=s(58840);function nD({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)(nT.k,{mode:"inline",slides:a,className:"h-full w-full",ariaLabel:s("imagePreview")})}function nL(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)(nE.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)(nA.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)(nA.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)(nP,{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)(nD,{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)(nE.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)(n$.A,{className:"size-3.5"}),o("wrapLines")]})]})]})}function nO({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 nF=s(19932),nB=s(43326),n_=s(17511);function nq(e,t){return!!(e&&e.cwd===t.cwd&&e.skillPath===t.skillPath&&e.path===t.path)}function nW({target:e,props:t,depth:s=0,skillName:a}){let{t:i}=(0,f.Bd)("skills"),l=t.directories[nS(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)(nU,{target:o,props:t,depth:s,name:r.name,skillName:a},l);let d=nq(t.selected,o),c=nq(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)(nF.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(nE.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 nU({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)(nW,{target:e,props:t,depth:s+1,skillName:i})})]})}function nY({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:${tR(e)?.name??e}`}function tD(e){switch(e.kind){case"batch":return"add"===e.input.action?"batchInstall":"update"===e.input.action?"updateSelected":"del"===e.input.action?"removeSelected":"setChannel";case"add":return"actionAdd";case"update":return"actionUpdate";case"del":return"actionDelete";case"enable":return"enable";case"disable":return"disable";case"reload":return"normal"===e.mode?"restartNormal":"actionReload"}}let tL=a.Yj().trim().min(1).max(128).regex(/^[a-zA-Z][a-zA-Z0-9._-]*$/),tO=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 仓库地址"),tF=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:tO}).strict()]),tB=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),tB).optional()}).passthrough().optional()}).passthrough();let t_=a.Ik({downloadSource:tF,recommendedRegistry:tO}).strict(),tq=a.Ik({downloadSource:tF}).strict(),tW=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:tO.optional()}).strict(),tU=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:tO.optional()}).strict(),tY=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:tO}).strict(),tV=a.Ik({items:a.YO(tY),hasMore:a.zM()}).strict(),tK=tY.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 tH({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]})}var tG=s(60567),tJ=s(48742),tX=s(3058);function tQ({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 tZ({value:e,label:t,placeholder:s,disabled:r,onChange:a}){let{t:i}=(0,f.Bd)("pluginManagement"),l=[...s?[{value:"",label:s}]:[],{value:"latest",label:i("channelLatest")},{value:"dev",label:i("channelDev")}];return(0,n.jsxs)(eP.l6,{value:e,items:l,disabled:r,onValueChange:e=>{null!==e&&a(e)},children:[(0,n.jsx)(eP.bq,{"aria-label":t,className:"max-w-full",children:(0,n.jsx)(eP.yv,{})}),(0,n.jsx)(eP.gC,{positionerClassName:"z-[160]",children:l.map(e=>(0,n.jsx)(eP.eb,{value:e.value,children:e.label},e.value))})]})}function t0({snapshot:e,loading:t,filter:s,disabled:r,requests:a,errors:i,browserErrors:l,channel:o,selected:d,onChannel:c,onSelect:u,onCheckSelected:m,onUpdateSelected:p,onRemoveSelected:h,onTagSelected:g,onFilter:x,onDetail:b,onAction:v,onDirectInstall:w,onRefresh:y}){let{t:k}=(0,f.Bd)("pluginManagement"),{locale:j}=(0,tp.i)(),I=e?.plugins.filter(e=>(!o||e.source.startsWith("npm:")&&(e.updateTag??"latest")===o)&&`${tP(e)} ${e.description?(0,tm.fD)(e.description,j):""}`.toLocaleLowerCase().includes(s.toLocaleLowerCase()))??[],C=I.filter(e=>"extension"!==e.kind),S=e?.plugins.filter(e=>d.has(tT(e.source)))??[],M=S.filter(e=>e.source.startsWith("npm:")),z=S.filter(e=>!a.has(tT(e.source))&&(!e.operation||"failed"===e.operation.phase)),E=C.length>0&&C.every(e=>d.has(tT(e.source))),A=C.some(e=>d.has(tT(e.source))),$=z.filter(e=>e.source.startsWith("npm:")),R=S.length>32;return(0,n.jsxs)("section",{"aria-label":k("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:k("filterInstalled")}),(0,n.jsx)(eB.p,{id:"plugin-installed-filter",value:s,onChange:e=>x(e.target.value),placeholder:k("filterInstalled"),className:"min-w-0 flex-1 basis-48"}),(0,n.jsx)(tZ,{value:o,label:k("filterChannel"),placeholder:k("allChannels"),onChange:c}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:t,onClick:y,children:k(t?"checkingUpdates":"checkUpdates")}),(0,n.jsx)(N.$,{size:"sm",disabled:r,onClick:w,children:k("directInstall")})]}),C.length||S.length?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 rounded-lg bg-muted p-2",children:[(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 px-1 text-sm",children:[(0,n.jsx)(tG.y,{checked:E,indeterminate:A&&!E,disabled:!C.length,onCheckedChange:e=>u(C.map(e=>tT(e.source)),e),className:"flex size-5 shrink-0 items-center justify-center rounded border border-input bg-background outline-none data-checked:bg-primary data-checked:text-primary-foreground focus-visible:ring-2 focus-visible:ring-ring",children:(0,n.jsx)(tJ.P,{children:A&&!E?(0,n.jsx)(tX.A,{className:"size-4"}):(0,n.jsx)(ed.A,{className:"size-4"})})}),k("selectFiltered")]}),S.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:k("selectedCount",{count:S.length})}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:t||!M.length||R,onClick:m,children:k("checkSelected")}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:r||!z.length||R,onClick:p,children:k("updateSelected")}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:r||!z.length||R,onClick:h,children:k("removeSelected")}),(0,n.jsx)(tZ,{value:"",label:k("setChannel"),placeholder:k("setChannel"),disabled:r||!$.length||R,onChange:e=>{e&&g(e)}}),(0,n.jsx)(N.$,{size:"sm",variant:"ghost",onClick:()=>u([...d],!1),children:k("clearSelection")})]}):null,R?(0,n.jsx)("p",{role:"status",className:"w-full text-sm text-muted-foreground",children:k("batchLimit")}):null]}):null,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:k("loading")}):I.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:I.map(e=>{let t=tP(e),s=tT(e.source);return(0,n.jsxs)("article",{className:`min-w-0 space-y-3 p-4 ${d.has(s)?"bg-accent/40":""}`,children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:["extension"!==e.kind?(0,n.jsx)(tG.y,{checked:d.has(s),"aria-label":k("selectPlugin",{name:t}),onCheckedChange:e=>u([s],e),className:"flex size-6 shrink-0 items-center justify-center rounded border border-input bg-background outline-none data-checked:bg-primary data-checked:text-primary-foreground focus-visible:ring-2 focus-visible:ring-ring",children:(0,n.jsx)(tJ.P,{children:(0,n.jsx)(ed.A,{className:"size-4"})})}):null,(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":k("viewDetails",{name:t}),onClick:()=>b(e.source),children:t}),e.version?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",e.version]}):null]}),e.source.startsWith("npm:")?(0,n.jsxs)("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[(0,n.jsx)("span",{children:k("followingChannel",{tag:e.updateTag??"latest"})}),e.availableVersion?(0,n.jsx)("span",{children:k("targetVersion",{version:e.availableVersion})}):null,e.updateError?(0,n.jsx)("p",{role:"alert",className:"w-full text-sm text-destructive",children:k("itemCheckFailed",{error:e.updateError})}):null]}):null,(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.description?(0,tm.fD)(e.description,j):k("noPluginDescription")}),(0,n.jsx)(tQ,{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=>v(e,t)})]},s)})}):(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:k(s||o?"noMatches":"empty")})]})}function t1(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 t2=(0,s(73392).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 t5({className:e,orientation:t,...s}){return(0,n.jsx)("div",{role:"group","data-slot":"button-group","data-orientation":t,className:(0,C.cn)(t2({orientation:t}),e),...s})}var t3=s(32892),t4=s(57445),t6=s(73028),t8=s(48318),t7=s(93356),t9=s(10508);let se=({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}),st=({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}),ss=({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)(t3.Bc,{children:(0,n.jsxs)(t3.m_,{children:[(0,n.jsx)(t3.k$,{render:l}),(0,n.jsx)(t3.ZI,{children:(0,n.jsx)("p",{children:e})})]})}):l},sn={cjk:t4.h,code:t6.a,math:t8.D,mermaid:t7.a},sr=(0,r.memo)(({className:e,...t})=>(0,n.jsx)(t9.jH,{className:(0,C.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),plugins:sn,...t}),(e,t)=>e.children===t.children&&t.isAnimating===e.isAnimating);sr.displayName="MessageResponse";let sa=({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 si({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)(sr,{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 sl(e){if(!e)return null;try{let t=new URL(e);return["https:","http:"].includes(t.protocol)?t.href:null}catch{return null}}function so(e){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,tp.i)(),r=e.detail,a=e.installed&&e.installedVersion===r.version,i=sl(r.homepage),l=sl(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)(tH,{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)(si,{readme:r.readme},`${r.name}@${r.version}`)})]})}var sd=s(68017);function sc(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)(sd.T,{id:"plugin-direct-source",value:e.source,placeholder:t("batchSourcePlaceholder"),rows:3,onChange:t=>e.onSource(t.target.value)}),e.isNpm||e.multiple?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(tZ,{value:e.tag,label:t("installChannel"),placeholder:t("defaultChannel"),onChange:e.onTag})]}),e.isNpm?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onRead,children:t(e.loading?"loadingPackage":"readPackage")}):null,e.detail?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.detail.name}),(0,n.jsxs)(eP.l6,{value:e.selectedVersion,disabled:e.loading,items:[{value:"",label:t("automaticVersion")},...[...new Set([e.detail.version,...e.detail.versions])].map(e=>({value:e,label:e}))],onValueChange:t=>{null!==t&&e.onVersion(t)},children:[(0,n.jsx)(eP.bq,{"aria-label":t("version"),className:"max-w-full",children:(0,n.jsx)(eP.yv,{})}),(0,n.jsxs)(eP.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(eP.eb,{value:"",children:t("automaticVersion")}),[...new Set([e.detail.version,...e.detail.versions])].map(e=>(0,n.jsx)(eP.eb,{value:e,children:e},e))]})]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t("targetVersion",{version:e.detail.version})})]}):null,(0,n.jsx)(tH,{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 whitespace-pre-wrap text-destructive [overflow-wrap:anywhere]",children:e.error}):null,e.operationMessage?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operationMessage}):null,(0,n.jsx)(N.$,{size:"sm",disabled:e.disabled||e.loading||e.pending||!e.source.trim(),onClick:e.onInstall,children:t(e.pending?"installing":e.multiple?"batchInstall":"install")})]})}function su({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||"batch"===s.kind&&"del"===s.input.action?"removeDescription":"add"===s.kind||"batch"===s.kind&&"add"===s.input.action?"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?"batch"===s.kind?(0,n.jsx)("ul",{className:"space-y-2 text-sm",children:("add"===s.input.action?s.input.items.map(e=>e.source):s.input.sources).map(e=>(0,n.jsx)("li",{className:"font-medium [overflow-wrap:anywhere]",children:e},e))}):"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")})]}),s.input.tag?(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:l("installChannel")}),(0,n.jsx)("dd",{children:s.input.tag})]}):null,(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||"batch"===s.kind&&"del"===s.input.action?"destructive":"default",onClick:()=>a(s),children:o})]}):null]})})}function sm({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,h]=(0,r.useState)(""),[g,x]=(0,r.useState)(()=>new Set);(0,r.useEffect)(()=>{if(!t)return;let e=new Set(t.plugins.map(e=>tT(e.source)));[...g].some(t=>!e.has(t))&&queueMicrotask(()=>x(t=>new Set([...t].filter(t=>e.has(t)))))},[t,g]);let[b,v]=(0,r.useState)(""),[w,y]=(0,r.useState)(!1),k=function({biz:e,snapshot:t,onSnapshot:s,onRestartScheduled:n}){let{t:a}=(0,f.Bd)("pluginManagement"),i=(0,eI.t4)();(0,eI.So)();let[l,o]=(0,r.useState)(!1),[d,c]=(0,r.useState)(()=>new Set),u=(0,r.useRef)(new Set),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)({}),[x,b]=(0,r.useState)(null),[v,w]=(0,r.useState)(null),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(null),I=(0,r.useRef)(0),C=(0,r.useRef)(0),S=(0,r.useRef)(!0),M=(e,t)=>{t?u.current.add(e):u.current.delete(e),S.current&&c(new Set(u.current))},z=(e,t)=>{S.current&&g(s=>{let n={...s};return t?n[e]=t:delete n[e],n})},E=e=>{let s=tT(e);return u.current.has(s)||!!t?.plugins.some(e=>tT(e.source)===s&&e.operation&&"failed"!==e.operation.phase)},A=async(t=!1)=>{let n=++C.current,r=await e.list(t);S.current&&n===C.current&&s(r)},$=async(e,s)=>{if(u.current.has("check"))return;let n=e??t?.plugins.filter(e=>"package"===e.kind&&(!s||e.updateTag===s)).map(e=>e.source)??[],r=n.filter(E),i=n.filter(e=>!E(e));if(r.forEach(e=>z(tT(e),a("sourceBusy"))),!i.length)return;if(r.length&&i.length>32)return void z("list",a("batchLimit"));let l=i.map(tT);M("check",!0),l.forEach(e=>M(e,!0)),o(!0),z("list",null);try{await A({checkUpdates:!0,...e||r.length?{sources:i}:{},...s?{tag:s}:{}})}catch(e){z("list",e instanceof Error?e.message:a("updateCheckFailed"))}finally{M("check",!1),l.forEach(e=>M(e,!1)),S.current&&o(!1)}};(0,r.useEffect)(()=>{S.current=!0;let t=!0,n=++C.current;return queueMicrotask(()=>{t&&(o(!0),e.list(!1).then(e=>{t&&n===C.current&&s(e)}).catch(e=>{t&&z("list",e instanceof Error?e.message:a("updateCheckFailed"))}).finally(()=>{t&&o(!1)}))}),()=>{t=!1,S.current=!1,I.current+=1,C.current+=1}},[e,s,a]);let R=async t=>{let n="add"===t.action?t.items.map(e=>e.source):t.sources,r=n.filter(e=>!E(e));if(n.filter(E).forEach(e=>z(tT(e),a("sourceBusy"))),!r.length)return;let i=r.map(tT);i.forEach(e=>{M(e,!0),z(e,null)}),p(null);try{let n="add"===t.action?{...t,items:t.items.filter(e=>r.includes(e.source))}:{...t,sources:r},a=await e.batch(n);if(!S.current)return;C.current+=1,s(a.snapshot),a.results.forEach(e=>z(tT(e.source),e.error))}catch(t){let e=t instanceof Error?t.message:a("batchFailed");i.forEach(t=>z(t,e))}finally{i.forEach(e=>M(e,!1))}},P=async t=>{if("batch"===t.kind)return void await R(t.input);if("reload"!==t.kind&&E("add"===t.kind?t.input.source:t.source))return;let r="reload"===t.kind?"reload":tT("add"===t.kind?t.input.source:t.source);if(!u.current.has(r)){M(r,!0),p(null),z(r,null);try{let r="add"===t.kind?await e.add(t.input):"update"===t.kind?await e.update(t.source):"del"===t.kind?await e.del(t.source):"enable"===t.kind||"disable"===t.kind?await e.setEnabled(t.source,"enable"===t.kind):await e.reload(t.mode);if(!S.current)return;C.current+=1,s(r),"reload"===t.kind?n():await A()}catch(e){z(r,e instanceof Error?e.message:a("actionFailed",{action:a(tD(t))}))}finally{M(r,!1)}}},T=(e,t)=>{let s={kind:"add",input:e,package:t};t?.official===!0?P(s):p(s)},D=async t=>{let n=t?.[0]?tT(t[0]):"apply";if(!u.current.has(n)){M(n,!0),z(n,null);try{let n=await e.apply(t);S.current&&(C.current+=1,s(n),await A())}catch(e){z(n,e instanceof Error?e.message:a("actionFailed",{action:a("reloadOne")}))}finally{M(n,!1)}}},L=async(e,t)=>{if(!u.current.has(e)){M(e,!0),z(e,null);try{await t()}catch(t){z(e,t instanceof Error?t.message:a("retryFailed"))}finally{M(e,!1)}}},O=async t=>{let s=++I.current;k(!0),N(null);try{let n=await e.get(t);S.current&&s===I.current&&w(n)}catch(e){S.current&&s===I.current&&N(e instanceof Error?e.message:a("detailFailed"))}finally{S.current&&s===I.current&&k(!1)}};return{loading:l,requests:d,confirmation:m,setConfirmation:p,errors:h,detailSource:x,detail:v,detailLoading:y,detailError:j,pluginHost:i,refresh:$,executeBatch:R,execute:P,requestInstall:T,applyChanges:D,loadDetail:O,openDetail:e=>{b(e),w(null),O(e)},closeDetail:()=>{I.current+=1,b(null),w(null),N(null),k(!1)},handleControlAction:(e,t)=>{switch(t){case"reload":D([e.source]);break;case"update":P({kind:"update",source:e.source});break;case"remove":p({kind:"del",source:e.source});break;case"enable":case"disable":P({kind:t,source:e.source});break;case"retry-browser":e.pluginName&&L(`entry:${e.pluginName}`,()=>i.retryEntry(e.pluginName));break;case"retry":{let t=e.operation?.action;"apply"===t?D([e.source]):"add"===t?T({source:e.source}):t&&P({kind:t,source:e.source})}}},refreshEntries:()=>L("entries",()=>i.refreshEntries())}}({biz:s,snapshot:t,onSnapshot:a,onRestartScheduled:i}),j=t?.plugins.filter(e=>g.has(tT(e.source))).map(e=>e.source)??[],I=j.filter(e=>e.startsWith("npm:")),C=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?tO.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?tO.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:tF.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),S=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=tF.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),M=function(e,t=[]){let{t:s}=(0,f.Bd)("pluginManagement"),[n,a]=(0,r.useState)(!1),[i,l]=(0,r.useState)(""),[o,d]=(0,r.useState)(""),[c,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[x,b]=(0,r.useState)(null),[v,w]=(0,r.useState)("default"),[y,k]=(0,r.useState)(""),j=(0,r.useRef)(0),N=(0,r.useRef)(!0),I=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),C=1===I.length?tR(I[0]):null;(0,r.useEffect)(()=>(N.current=!0,()=>{N.current=!1,j.current+=1}),[]);let S=()=>{j.current+=1,p(null),g(!1),b(null)},M=async n=>{let r;if(!C)return null;void 0!==n&&u(n||null);let a=t.find(e=>tR(e.source)?.name===C.name)?.updateTag,i=C.version??(o||a||"latest"),l=""===n?i:n??c??i;if("custom"===v){let e=tO.safeParse(y);if(!e.success)return b(s("invalidRegistry")),null;r=e.data}else"official"===v?r="https://registry.npmjs.org":"domestic"===v&&(r="https://registry.npmmirror.com");let d=++j.current;g(!0),p(null),b(null);try{let t=await e.getCatalog({...C,...l?{version:l}:{},...r?{registry:r}:{}});if(!N.current||d!==j.current)return null;return p(t),t}catch(e){return N.current&&d===j.current&&b(e instanceof Error?e.message:s("detailFailed")),null}finally{N.current&&d===j.current&&g(!1)}},z=async(e,t)=>{if(!I.length||h)return;b(null);let n="default"===v?null:tF.safeParse("custom"===v?{mode:v,registry:y}:{mode:v});if(n&&!n.success)return void b(s("invalidRegistry"));let r={...o?{tag:o}:{},...n?.success?{downloadSource:n.data}:{}};if(I.length>1){let e=I.map(tR);if(I.length>32||e.some(e=>!e))return void b(s(I.length>32?"batchLimit":"batchNpmOnly"));let n=new Map;return e.forEach(e=>{e&&n.set(e.name,{source:`npm:${e.name}${e.version?`@${e.version}`:""}`,...r})}),void t([...n.values()])}if(!C)return void e({source:I[0]});let a=m?Promise.resolve(m):M(c??void 0),i=j.current,l=await a;if(l&&N.current&&i===j.current){if(!1===l.compatible)return void b(s("installIncompatible"));e({source:`npm:${l.name}${c||C.version?`@${c??C.version}`:""}`,registry:l.registry,...r},l)}};return{open:n,setOpen:a,source:i,sources:I,tag:o,selectedVersion:c??"",setTag:e=>{S(),u(null),d(e)},changeSource:e=>{S(),u(null),l(e)},spec:C,detail:m,loading:h,error:x,override:v,setOverride:e=>{S(),w(e)},registry:y,setRegistry:e=>{S(),k(e)},loadDetail:M,install:z}}(s,t?.plugins),z=e||k.requests.has("reload"),E=new Map(k.pluginHost.getFailedEntries().map(e=>[e.pluginName,e.error.message])),A=k.pluginHost.getEntryListError(),$=t?.plugins.find(e=>e.source===k.detailSource),R=C.selection?t?.plugins.find(e=>e.source.startsWith("npm:")&&tR(e.source)?.name===C.selection?.name):void 0,P=C.selection?tT(`npm:${C.selection.name}`):"",T=tT(M.detail?`npm:${M.detail.name}`:M.spec?`npm:${M.spec.name}`:M.source.trim()),D=t?.plugins.find(e=>tT(e.source)===T),L=k.requests.has(P)||!!(R?.operation&&"failed"!==R.operation.phase),O=M.sources.length>0&&M.sources.every(e=>{let s=tT(e),n=t?.plugins.find(e=>tT(e.source)===s);return k.requests.has(s)||!!(n?.operation&&"failed"!==n.operation.phase)}),F=M.sources.map(e=>{let s=tT(e),n=t?.plugins.find(e=>tT(e.source)===s),r=k.errors[s]??(n?.operation?.phase==="failed"?n.operation.message:null);return r?`${e}: ${r}`:null}).filter(Boolean).join("\n"),B=e=>{let s=t?.plugins.find(t=>tR(t.source)?.name===e.name),n=b||s?.updateTag;return n?{...e,version:n}:e},_=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"),":",S.loading&&!S.settings?l("loading"):l(`download_${S.settings?.downloadSource.mode??S.mode}`),(0,n.jsx)(ti.A,{className:"size-4"})]}),(0,n.jsx)(th.hl,{align:"end",positionerClassName:"z-[150]",children:(0,n.jsx)(tH,{id:"plugin-default-download",mode:S.mode,registry:S.registry,savedRegistry:S.settings?.downloadSource.mode==="custom"?S.settings.downloadSource.registry:void 0,recommendedRegistry:S.settings?.recommendedRegistry,loading:S.loading,saving:S.saving,error:S.error,onMode:e=>{"default"!==e&&S.changeMode(e)},onRegistry:S.setRegistry,onSave:()=>void S.save(),onRetry:()=>void S.retry()})})]}),e||t?.restartRequired?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:k.requests.has("reload"),onClick:()=>k.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||A?(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,A?(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:A}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:k.requests.has("entries"),onClick:()=>void k.refreshEntries(),children:l("retry")})]}):null]}):null,k.errors.reload||k.errors.entries?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:k.errors.reload??k.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:[M.open?(0,n.jsx)(sc,{source:M.source,isNpm:!!M.spec,multiple:M.sources.length>1,tag:M.tag,selectedVersion:M.selectedVersion,onTag:M.setTag,detail:M.detail,loading:M.loading,pending:O,disabled:z,error:M.error??(F||null)??(D?.operation?.phase==="failed"?D.operation.message:null),operationMessage:O?_(D?.operation?.phase)??l("submitting"):null,override:M.override,registry:M.registry,onSource:M.changeSource,onMode:M.setOverride,onRegistry:M.setRegistry,onRead:()=>void M.loadDetail(),onVersion:e=>void M.loadDetail(e),onInstall:()=>void M.install(k.requestInstall,e=>k.setConfirmation({kind:"batch",input:{action:"add",items:e}})),onClose:()=>M.setOpen(!1)}):null,(0,n.jsx)(t0,{snapshot:t,loading:k.loading,filter:u,channel:p,selected:g,onChannel:h,onSelect:(e,t)=>{x(s=>{let n=new Set(s);return e.forEach(e=>{t?n.add(e):n.delete(e)}),n})},onCheckSelected:()=>void k.refresh(I),onUpdateSelected:()=>void k.executeBatch({action:"update",sources:j}),onRemoveSelected:()=>k.setConfirmation({kind:"batch",input:{action:"del",sources:j}}),onTagSelected:e=>void k.executeBatch({action:"tag",sources:I,tag:e}),disabled:z,requests:k.requests,errors:k.errors,browserErrors:E,onFilter:m,onDetail:e=>{C.closeDetail(),k.openDetail(e)},onAction:k.handleControlAction,onDirectInstall:()=>M.setOpen(!0),onRefresh:()=>void k.refresh(void 0,p||void 0)})]})}),(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)(t1,{query:C.query,kind:C.kind,searchSource:C.searchSource,registry:C.registry,items:C.items,loading:C.loading,error:C.error,searched:C.searched,hasMore:C.hasMore,disabled:z,snapshot:t,requests:k.requests,preparing:C.preparing,errors:k.errors,installErrors:C.installErrors,onQuery:C.setQuery,onCompositionStart:C.beginComposition,onCompositionEnd:C.endComposition,onKind:C.setKind,onSearchSource:C.setSearchSource,onRegistry:C.setRegistry,onDetail:e=>{k.closeDetail(),y(!1),C.openDetail(B(e))},onInstall:e=>{C.prepareInstall(B(e),e=>k.requestInstall({source:`npm:${e.name}`,registry:e.registry,...b?{tag:b}:{}},e))},onUpdate:e=>void k.execute({kind:"update",source:e}),onMore:C.loadMore,onRetry:C.retry})}),(0,n.jsx)(su,{open:!!(k.confirmation||k.detailSource||C.selection),title:$?tP($):C.selection?.name??l("details"),confirmation:k.confirmation,onClose:()=>{k.confirmation?k.setConfirmation(null):(k.closeDetail(),C.closeDetail())},onConfirm:e=>void k.execute(e),children:$?(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[k.detail?.readme?(0,n.jsx)(si,{readme:k.detail.readme},$.source):null,(0,n.jsx)(t$,{plugin:$,detail:k.detail,detailLoading:k.detailLoading,detailError:k.detailError,browserContributions:$.pluginName?k.pluginHost.getRegisteredBrowserDescriptors().find(e=>e.pluginName===$.pluginName)?.contributions??[]:[],onRetry:()=>void k.loadDetail($.source)})]}):C.selection?C.detailLoading?(0,n.jsx)("p",{role:"status",className:"py-4 text-sm text-muted-foreground",children:l("loadingPackage")}):C.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:C.detailError}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",onClick:()=>void C.loadDetail(C.selection),children:l("retry")})]}):C.detail?(0,n.jsxs)("div",{className:"min-w-0 space-y-4",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:l("installChannel")}),(0,n.jsx)(tZ,{value:b,label:l("installChannel"),placeholder:l("defaultChannel"),disabled:L,onChange:e=>{v(e),y(!1),C.loadDetail(C.selection,e||R?.updateTag||"latest")}})]}),(0,n.jsx)(so,{detail:C.detail,disabled:z,pending:L,installed:!!(R&&(R.operation?.action!=="add"||"failed"!==R.operation.phase)),installedVersion:R?.version??null,updateAvailable:!!R?.updateAvailable,error:C.installErrors[C.detail.name]??k.errors[P]??(R?.operation?.phase==="failed"?R.operation.message:null),operationMessage:_(R?.operation?.phase),downloadMode:C.downloadMode,downloadRegistry:C.downloadRegistry,onDownloadMode:C.setDownloadMode,onDownloadRegistry:C.setDownloadRegistry,onVersion:e=>{y(!0),C.loadDetail(C.selection,e)},onInstall:()=>C.installDetail((e,t)=>k.requestInstall({...e,source:w?e.source:`npm:${t.name}`,...b?{tag:b}:{}},t)),onUpdate:()=>{R&&k.execute({kind:"update",source:R.source})}})]}):null:k.detailSource?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:l("pluginRemoved")}):null})]})}var sp=s(99739);let sh=a.Yj().trim().min(1).max(2048),sg=a.YO(sh).min(1).max(32),sx=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(),sf=a.Yj().trim().min(1).max(4096),sb=a.Yj().trim().min(1).max(256),sv=a.Yj().max(32768),sw=a.Ik({name:sb,label:sv,state:a.k5(["active","inactive","shadowed"]),description:sv,promptSnippet:sv.nullable(),promptGuidelineCount:a.ai().int().nonnegative(),promptGuidelinePreview:sv.nullable()}).strict(),sy=a.Ik({name:sb,label:sv,state:a.k5(["active","inactive","shadowed"]),description:sv,parameters:sp.Dz,promptSnippet:sv.nullable(),promptGuidelines:a.YO(sv)}).strict(),sk=a.Ik({path:sf,events:a.YO(a.Ik({name:sb,count:a.ai().int().positive()}).strict()),commands:a.YO(a.Ik({name:sb,description:sv.nullable()}).strict()),shortcuts:a.YO(a.Ik({shortcut:sb,description:sv.nullable()}).strict()),flags:a.YO(a.Ik({name:sb,type:a.k5(["boolean","string"]),description:sv.nullable(),default:a.KC([a.zM(),a.Yj(),a.ch()])}).strict()),messageRenderers:a.YO(sb),entryRenderers:a.YO(sb)}).strict(),sj=a.Ik({name:sb,description:sv,path:sf}).strict(),sN=sj.extend({modelVisible:a.zM()}).strict(),sI=sj.extend({content:a.Yj().max(65536),truncated:a.zM()}).strict(),sC=sI.extend({modelVisible:a.zM()}).strict(),sS=a.Ik({name:sb,path:sf}).strict(),sM=a.Ik({name:sb,kind:a.k5(["config","native"])}).strict(),sz=a.Ik({methods:a.YO(a.Ik({pluginName:sb,method:sb}).strict()),browserEntries:a.YO(a.Ik({pluginName:sb}).strict()),messageDeclarations:a.YO(a.Ik({pluginName:sb,declarationName:sb,priority:a.ai().int().safe()}).strict())}).strict(),sE=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(sk),tools:a.YO(sw),skills:a.YO(sN),prompts:a.YO(sj),themes:a.YO(sS),providers:a.YO(sM),piDesk:sz}).strict(),sA=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(),s$=(0,i._G)({path:"plugins/management-update",bodySchema:a.Ik({}).strict()}),sR=a.Ik({source:sh,kind:a.k5(["package","extension"]).default("package"),operation:sA.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(),updateTag:tL.nullable().optional(),availableVersion:a.Yj().min(1).nullable().optional(),updateError:a.Yj().max(4e3).nullable().optional(),status:a.k5(["ready","available","disabled","failed"]),error:sx.nullable(),capabilities:sE}).strict(),sP=a.Ik({source:sh,readme:tm.qf.nullable().default(null),tools:a.YO(sy),skills:a.YO(sC),prompts:a.YO(sI)}).strict(),sT=a.Ik({plugins:a.YO(sR),restartRequired:a.zM(),loadError:tm.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0).nullable()}).strict(),sD=a.Ik({sources:a.YO(sh).min(1).max(32).optional()}).strict(),sL=a.Ik({}).strict().extend({mode:a.k5(["normal","basic"]).optional()}).strict(),sO=a.Ik({checkUpdates:a.zM().optional(),sources:sg.optional(),tag:tL.optional()}).strict(),sF=a.Ik({source:sh}).strict(),sB=sF.extend({downloadSource:tF.optional(),registry:tO.optional(),tag:tL.optional()}).strict(),s_=a.gM("action",[a.Ik({action:a.eu("add"),items:a.YO(sB).min(1).max(32)}).strict(),a.Ik({action:a.eu("update"),sources:sg}).strict(),a.Ik({action:a.eu("del"),sources:sg}).strict(),a.Ik({action:a.eu("tag"),sources:sg,tag:tL}).strict()]),sq=a.Ik({snapshot:sT,results:a.YO(a.Ik({source:sh,error:a.Yj().max(4e3).nullable()}).strict()).max(32)}).strict(),sW=sF.extend({enabled:a.zM()}).strict();async function sU(e,t,s,n){return eF(e,t,s,n,{fallbackMessage:"插件管理请求失败"})}function sY({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 sV({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 sK=s(10263),sH=s(11831),sG=s(79615),sJ=s(24863),sX=s(10672);let sQ="1.1.1-dev".trim()||"未知",sZ="2026-10-09T23:49:04+08:00".trim()||null;var s0=s(42655),s1=s(36919);let s2="pi-desk:power-saving",s5="pi-desk:power-saving-change",s3=null;function s4(){if(null!==s3)return s3;try{s3="true"===window.localStorage.getItem(s2)}catch{s3=!1}return s3}function s6(e){let t=t=>{(null===t.key||t.key===s2)&&(s3=null,e())};return window.addEventListener(s5,e),window.addEventListener("storage",t),()=>{window.removeEventListener(s5,e),window.removeEventListener("storage",t)}}function s8(){return(0,r.useSyncExternalStore)(s6,s4,()=>!1)}function s7(e,t){let s=(0,s1.I)(),n=s8(),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 s9=s(55079),ne=s(49667),nt=s(61286),ns=s(33550),nn=s(66453),nr=s(67765);let na=a.Yj().min(1).max(nr.uV).refine(e=>!e.includes("\0")&&(e.startsWith("/")||e.startsWith("\\\\")||/^[a-zA-Z]:[\\/]/.test(e)),"必须是绝对路径"),ni=a.Ik({cwd:nn.m4.nullable()}).strict(),nl=a.Ik({skillPath:na,name:a.Yj().min(1),description:a.Yj(),packageSource:a.Yj().nullable()}).strict(),no=a.Ik({skills:a.YO(nl),diagnostics:a.YO(a.Ik({path:a.Yj(),message:tm.qf}).strict())}).strict(),nd=ni.extend({skillPath:na}),nc=nd.extend({path:nr.rh}).strict(),nu=a.Ik({entries:a.YO(a.Ik({name:a.Yj().min(1),type:a.k5(["directory","file"])}).strict()).max(nr.xm),truncated:a.zM()}).strict(),nm=nd.extend({path:nr._g}).strict(),np=a.gM("kind",[a.Ik({kind:a.eu("text"),content:a.Yj(),size:a.ai().int().nonnegative().max(nr.NL),readOnlyReason:tm.qf.nullable()}).strict(),a.Ik({kind:a.eu("image"),mimeType:nr.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()]),nh=nm.extend({content:a.Yj().max(nr.NL)}).strict(),ng=a.Ik({}).strict(),nx={path:"/api/skills/list",request:ni,response:no},nf={path:"/api/skill-files/list",request:nc,response:nu},nb={path:"/api/skill-files/get",request:nm,response:np},nv={path:"/api/skill-files/replace",request:nh,response:ng},nw=a.Ik({code:a.ai(),msg:a.Yj(),data:a.L5(),i18n:nt.N.optional()});async function ny(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=nw.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 nk(e){(0,ns.ZQ)({wrapLines:e})}async function nj(e){let t=e.skillPath.replaceAll("\\","/");await navigator.clipboard.writeText(t.slice(0,t.lastIndexOf("/")+1)+e.path)}var nN=s(46782);function nI(e){return(0,eO.B)({msg:nN.P["zh-CN"][e],i18n:{key:`skills:${e}`}})}function nC(e){return JSON.stringify(e)}function nS(e){return JSON.stringify([e.cwd,e.skillPath,e.path])}function nM(e){return e.replace(/\r\n|\r/g,"\n")}function nz(e){return e?.file?.kind==="text"&&e.draft!==nM(e.file.content)}var nE=s(60794),nA=s(89757),n$=s(55628),nR=s(91182);function nP(e){let{t}=(0,f.Bd)("common"),{wrapLines:s}=(0,ns.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,nR.cu)().then(r=>{if(e||!i.current)return;let a=m.current,o=r.editor.create(i.current,{model:null,theme:(0,nR.dC)(),automaticLayout:!0,readOnly:a.readOnly,domReadOnly:a.readOnly,wordWrap:(0,ns.E6)().wrapLines?"on":"off",wrappingIndent:"same",minimap:{enabled:!1},stickyScroll:{enabled:!1},scrollBeyondLastLine:!1,...(0,nR.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,nR.Tr)(e=>r.editor.setTheme(e)),n=(0,nR.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,nR.cu)().then(s=>{if(e||t!==u.current||!l.current)return;let n=m.current,r=s.editor.createModel(n.content,(0,nR.ix)(n.path,n.size),(0,nR.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 nT=s(58840);function nD({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)(nT.k,{mode:"inline",slides:a,className:"h-full w-full",ariaLabel:s("imagePreview")})}function nL(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)(nE.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)(nA.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)(nA.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)(nP,{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)(nD,{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)(nE.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)(n$.A,{className:"size-3.5"}),o("wrapLines")]})]})]})}function nO({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 nF=s(19932),nB=s(43326),n_=s(17511);function nq(e,t){return!!(e&&e.cwd===t.cwd&&e.skillPath===t.skillPath&&e.path===t.path)}function nW({target:e,props:t,depth:s=0,skillName:a}){let{t:i}=(0,f.Bd)("skills"),l=t.directories[nS(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)(nU,{target:o,props:t,depth:s,name:r.name,skillName:a},l);let d=nq(t.selected,o),c=nq(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)(nF.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(nE.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 nU({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)(nW,{target:e,props:t,depth:s+1,skillName:i})})]})}function nY({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)(nB.A,{"aria-label":a("packageSkill"),className:"size-3.5 shrink-0 text-muted-foreground"}):null]}),c&&(0,n.jsx)(nW,{target:{cwd:e,skillPath:t.skillPath,path:""},props:s,skillName:t.name})]})}function nV({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[nC(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)(nY,{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 nK(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)(nV,{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)(nV,{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 nH({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)=>ny(i,nx,e,t),listFiles:(e,t)=>ny(i,nf,e,t),getFile:(e,t)=>ny(i,nb,e,t),async replaceFile(e){await ny(i,nv,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=nC(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:nI("skillsReadFailed")}}))}finally{l.current.get(r)===a&&l.current.delete(r)}},[e]),c=(0,r.useCallback)(async t=>{let s=nS(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:nI("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([nC(null),...JSON.parse(u).map(nC)]);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(nC(JSON.parse(t)[0]))))),l.current)){let n=t.startsWith("scope:")?t.slice(6):nC(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,ns.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(!nz(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:nI("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(!nz(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()||nz(i.current)))return;if("discard"===e){let e=i.current;e?.file?.kind==="text"&&w({...e,draft:nM(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?nM(n.content):"",error:null}),!0}catch(e){if(!s.signal.aborted){let s=i.current,n=e instanceof Error?e.message:nI("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=nz(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:nk,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[nC(j.current)];if(!e||e.loading)return;let t=d.scopes[nC(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 nj(u.document.target),l.success(a("pathCopied"))}catch{l.error(a("copyFailed"))}},M=u.document?.target??null,z=M?d.scopes[nC(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)(sJ.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)(s9.A,{className:"size-4"}):(0,n.jsx)(ne.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)(nK,{...A})}),(0,n.jsx)("main",{className:"min-h-0 min-w-0 flex-1",children:(0,n.jsx)(nL,{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)(nK,{...A})})]})}),(0,n.jsx)(nO,{open:u.confirmOpen,saving:u.saving,path:M?.path??null,error:u.document?.error??null,onDecide:u.decide})]})}var nG=s(75851),nJ=s(17247),nX=s(19562);function nQ(){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 nZ=s(33941);async function n0(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 n1(e){await n0(e,"/api/auth/logout",{},nZ.Xm),window.location.replace("/login")}async function n2(e,t){let s=nZ.uZ.safeParse(t);if(!s.success)throw Error((0,eO.B)({msg:"请填写至少 8 位密码",i18n:{key:"auth:settingsInvalid"}}));await n0(e,"/api/auth-settings/replace",s.data,nZ.Kc),window.location.replace(null===t.password?"/":"/login")}function n5(){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}=nQ(),[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,n0(t,"/api/auth-settings/get",{},nZ.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 n2(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 n2(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 n1(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:nG.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)(nJ.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)(nX.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 n3=s(60471),n4=s(62851);let n6=Object.freeze({apply:(0,i.Vc)({path:"app-runtime/apply",inputSchema:n4.$C,outputSchema:n4.Pq}),update:(0,i._G)({path:"app-runtime/update",bodySchema:n4.YT})});var n8=s(48708);async function n7(e,t,s,n){let r=(0,n8.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(n6.apply,{key:"settings",update:{region:{locale:e}}})}catch{return"save-failed"}return a&&window.location.reload(),"changed"}async function n9(e,t){try{return await t.request(n6.apply,{key:"settings",update:{region:{timeZone:e}}}),!0}catch{return!1}}function re({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 n7(s,t("common:reloadConfirm"),a,e);"save-failed"===n&&l(t("common:localeError")),"blocked"===n&&l(t("common:reloadBlocked"))},m=async e=>{l(await n9(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)(n3.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 rt=s(90772),rs=s(90164),rn=s(52871),rr=s(96646);function ra({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 ri=s(74052),rl=s(38903),ro=s(90740),rd=s(67796),rc=s(46376),ru=s.n(rc);let rm={code:{copy:!0,download:!1}};function rp({href:e,children:t,...s}){return delete s.node,(0,n.jsx)("a",{...s,href:e,target:"_blank",rel:"noopener noreferrer",children:t})}function rh({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:ru().imageFallback,children:l("imageUnavailable")});let h=p[0].src;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",className:ru().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)(ru().image,s),onError:e=>{u(!0),a?.(e)}}),(0,n.jsx)("span",{className:ru().imageAction,"aria-hidden":"true",children:(0,n.jsx)(B.A,{className:"size-4"})})]}),o?(0,n.jsx)(nT.k,{mode:"modal",open:!0,slides:p,ariaLabel:l("imagePreview"),onClose:()=>d(!1)}):null]})}function rg({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)(sr,{className:(0,C.cn)("space-y-0",ru().markdown,e),controls:rm,isAnimating:t,lineNumbers:!1,components:{...s,a:rp,img:rh},...r,translations:"zh-CN"===l?rd.X:void 0})})}let rx=[{value:"system",label:"common:system",icon:rt.A},{value:"light",label:"themeLight",icon:rs.A},{value:"dark",label:"themeDark",icon:rn.A}],rf=[{value:"compact",label:"sizeCompact"},{value:"standard",label:"sizeStandard"},{value:"large",label:"sizeLarge"}];function rb(){let{t:e}=(0,f.Bd)("settings"),t=(0,r.useSyncExternalStore)(ri.Cy,ri.Is,()=>rr.Pl),s=s8(),a=(0,r.useSyncExternalStore)(ro.wm,ro.Ev,()=>rl.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)(ra,{label:e("theme"),layout:"segmented",value:t,options:rx.map(t=>({...t,label:e(t.label)})),onChange:ri.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)(ra,{label:e("displaySize"),layout:"segmented",value:a,options:rf.map(t=>({...t,label:e(t.label)})),onChange:ro.$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)(ra,{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){s3=e;try{window.localStorage.setItem(s2,String(e))}catch(e){console.warn("[Pi Desk][Appearance] 省电模式保存失败,仅当前页面生效",e)}window.dispatchEvent(new Event(s5))})("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)(rg,{mode:"static",isAnimating:!1,children:e("displayPreviewContent")})})]})]})]})}var rv=s(50163),rw=s(93780),ry=s(88707),rk=s(31848),rj=s(71057),rN=s(20476);let rI="pi-super:new-work-session-behavior",rC="activate",rS=new Set,rM=rC,rz=!1;function rE(){if(!rz){rz=!0;try{var e;e=window.localStorage.getItem(rI),rM="none"===e||"activate"===e||"pin"===e?e:rC}catch{rM=rC}}}function rA(){return rE(),rM}function r$(e){if(rE(),rM!==e){rM=e;try{window.localStorage.setItem(rI,e)}catch{}for(let e of[...rS])e()}}function rR(e){return rS.add(e),()=>rS.delete(e)}let rP=[{value:"none",label:"behaviorNone",description:"behaviorNoneDescription",icon:rv.A,testId:"new-work-session-behavior-none"},{value:"activate",label:"behaviorActivate",description:"behaviorActivateDescription",icon:rw.A,testId:"new-work-session-behavior-activate"},{value:"pin",label:"behaviorPin",description:"behaviorPinDescription",icon:ry.A,testId:"new-work-session-behavior-pin"}],rT=[{value:"compressed",label:"imageCompressed",description:"imageCompressedDescription",icon:rk.A,testId:"image-preview-mode-compressed"},{value:"original",label:"imageOriginal",description:"imageOriginalDescription",icon:rj.A,testId:"image-preview-mode-original"}];function rD(){let{t:e}=(0,f.Bd)("settings"),t=(0,r.useSyncExternalStore)(rR,rA,rA),s=(0,r.useSyncExternalStore)(rN.ku,rN.Wq,rN.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)(ra,{label:e("newSessionBehavior"),value:t,options:rP.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:r$}),(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)(ra,{label:e("imagePreviewMode"),value:s,options:rT.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:rN.lU}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:e("imagePreviewApply")})]})]})]})}var rL=s(17339),rO=s(26357),rF=s(70698);let rB=a.Yj().trim().min(1).max(128),r_=a.Yj().trim().min(1).max(256),rq=a.Yj().trim().min(1).max(256),rW=a.Yj().trim().min(1).nullable(),rU=a.g1(a.Yj().trim().min(1),a.Yj()),rY=a.Yj().trim().min(1).max(128),rV=a.g1(a.Yj(),a.Pq()),rK=a.Ik({level:rO.$,providerValue:a.Yj().trim().min(1).nullable()}).strict(),rH=a.Ik({input:a.ai().nonnegative().finite(),output:a.ai().nonnegative().finite(),cacheRead:a.ai().nonnegative().finite(),cacheWrite:a.ai().nonnegative().finite()}).strict(),rG=a.Ik({supportsDeveloperRole:a.zM().nullable(),thinkingFormat:a.Yj().trim().min(1).max(128).nullable(),requiresReasoningContentOnAssistantMessages:a.zM().nullable()}).strict(),rJ=a.Ik({modelId:r_,name:rq,api:rY.nullable(),baseUrl:rW,reasoning:a.zM(),thinkingLevels:a.YO(rK).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:rH.nullable(),headers:rU,compat:rG.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 思考等级"})}),rX=a.Ik({provider:rB,name:rW,baseUrl:rW,api:rY.nullable(),apiKey:a.Yj().nullable(),authHeader:a.zM().nullable(),headers:rU,models:a.YO(rJ)}).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)}),rQ=a.Ik({provider:rB,modelId:r_,thinkingLevel:rO.$,color:a.Yj().regex(/^#[0-9a-fA-F]{6}$/).nullable()}).strict(),rZ=a.Ik({provider:rB,modelId:r_,name:rq,input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),thinkingLevels:a.YO(rO.$).min(1).max(7)}).strict(),r0=a.Ik({provider:rB,modelId:r_,thinkingLevel:rO.$}).strict(),r1=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:rH.partial().optional()}).strict(),r2=a.Ik({provider:rB,modelId:r_,overrides:r1}).strict(),r5=a.Ik({provider:rB,name:rq,loggedIn:a.zM(),subscription:a.zM(),models:a.YO(rJ)}).strict();a.Ik({}).strict();let r3=a.Ik({providers:a.YO(rX),presets:a.YO(rQ),models:a.YO(rZ),nativeConfig:rV,accountModels:a.YO(r2),accounts:a.YO(r5)}).strict(),r4=a.Ik({providers:a.YO(rX).optional(),presets:a.YO(rQ).optional(),accountModels:a.YO(r2).optional()}).strict().refine(e=>void 0!==e.providers||void 0!==e.presets||void 0!==e.accountModels,{message:"请提交需要保存的模型配置"}),r6=a.KC([r4,a.Ik({nativeConfig:rV}).strict()]),r8=a.Ik({}).strict(),r7=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(),r9=a.Ik({reasoning:a.zM(),thinkingLevels:a.YO(rK).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:rH.nullable()}).strict(),ae=a.Ik({provider:rB,providerName:rq,modelId:r_,official:a.zM(),defaults:r9}).strict(),at=a.Ik({referenceId:a.Yj().trim().min(1).max(512),name:rq,match:a.k5(["exact","similar"]).nullable(),sources:a.YO(ae).min(1)}).strict(),as=a.Ik({updatedAt:rF.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(at)}).strict();a.Ik({cwd:nn.m4}).strict();let an=a.Ik({cwd:nn.m4,default:r0.nullable(),models:a.YO(rZ)}).strict(),ar=a.Ik({cwd:nn.m4,default:r0.nullable()}).strict(),aa=a.Ik({}).strict(),ai=a.Ik({cwd:nn.m4,sessionCount:a.ai().int().nonnegative(),updatedAt:rF.k}).strict();a.Ik({forceRefresh:a.zM().default(!1)}).strict();let al=a.Ik({directories:a.YO(ai)}).strict();a.Ik({cwd:nn.m4,ignored:a.zM()}).strict(),a.Ik({}).strict();let ao=a.Ik({cwd:nn.m4,name:a.Yj().trim().min(1)}).strict();a.Ik({cwd:nn.m4.nullable()}).strict();let ad=a.Ik({cwd:nn.m4.nullable(),parentCwd:nn.m4.nullable(),directories:a.YO(ao)}).strict(),ac=a.k5(["title","user","assistant","sessionId"]),au=a.Ik({scope:ac,count:a.ai().int().positive(),entryId:nn.Rv.nullable(),timestampMs:rF.k.nullable(),preview:a.Yj().min(1).max(160)}).strict(),am=a.Ik({sessionId:nn.$E,cwd:nn.m4,name:a.Yj().nullable(),createdAt:rF.k,updatedAt:rF.k,messageCount:a.ai().int().nonnegative(),userMessageCount:a.ai().int().nonnegative(),firstMessage:a.Yj().max(160),matches:a.YO(au).min(1).max(4).nullable()}).strict();a.Ik({cwd:nn.m4,query:a.Yj().trim().max(120).default(""),forceRefresh:a.zM().default(!1),searchIn:a.YO(ac).min(1).max(4).default(["title","user"])}).strict(),a.Ik({cwd:nn.m4,sessions:a.YO(am)}).strict(),a.Ik({cwd:nn.m4,sessionId:nn.$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 ap=a.Ik({entryId:nn.Rv,timestampMs:rF.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(ap)}).strict();let ah="pi-desk:pi-directories",ag="pi-desk:ignored-pi-directories",ax="pi-desk:pi-directory-entries",af=!1,ab=null,av=null,aw=!1,ay=new Map;function ak(e){if(null===e)return"<root>";let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function aj(e){try{return JSON.parse(window.localStorage.getItem(e)??"null")}catch{return null}}function aN(){af||(af=!0,ab=aj(ah),av=aj(ag))}function aI(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function aC(e){aN(),ab=e,aI(ah,e)}function aS(){if(aw)return;aw=!0;let e=aj(ax);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))ay.set(e,s)}function aM(e){return aS(),ay.get(ak(e))??null}let az="pi-desk:project-model-defaults",aE=!1,aA=new Map;function a$(e){let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function aR(){if(!aE){aE=!0;try{let e=JSON.parse(window.localStorage.getItem(az)??"null");if(!e||"object"!=typeof e||Array.isArray(e))return;for(let[t,s]of Object.entries(e)){let e=an.safeParse(s);e.success&&aA.set(t,e.data)}let t=!1;for(;aA.size>64;){let e=aA.keys().next().value;if(void 0===e)break;aA.delete(e),t=!0}t&&aP()}catch{aA.clear()}}}function aP(){try{window.localStorage.setItem(az,JSON.stringify(Object.fromEntries(aA)))}catch{}}function aT(e){let t=an.safeParse(e);if(!t.success)return;aR();let s=a$(t.data.cwd);for(aA.delete(s),aA.set(s,t.data);aA.size>64;){let e=aA.keys().next().value;if(void 0===e)break;aA.delete(e)}aP()}let aD=a.KC([a.k5(["appearance","region","habits","auth","models","mcp-settings","capability-modes","skills","plugins","about"]),a.Uy(["plugin:",a.Yj(),":",a.Yj()])]),aL=a.k5(["providers","presets","project-default"]),aO="pi-super:settings:section",aF="pi-super:settings:model-tab";function aB(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)}}function aq({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)(sd.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 aW=s(43209),aU=s(54346),aY=s(55289),aV=s(24121),aK=s(78844);let aH=[{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 aG(e){return aH.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 aJ=["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"],aX=["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:aJ[t]})),aQ=["openai","openrouter","together","deepseek","zai","qwen","chat-template","qwen-chat-template","string-thinking","ant-ling","baseten"];function aZ(e){return Object.entries(e).map(([e,t])=>`${e}: ${t}`).join("\n")}function a0({headers:e,onChange:t,placeholder:s}){let[a,i]=(0,r.useState)(null);return(0,n.jsx)(sd.T,{value:a??aZ(e),onFocus:()=>i(aZ(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 a1(e){let t=Math.floor(e/1e3),s=e%1e3;return s?`${t}.${String(s).padStart(3,"0").replace(/0+$/,"")}`:String(t)}function a2(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 a5({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 a3="__pi-desk_empty__";function a4({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?a3:t[0]?.value??null),u=!!e&&!t.some(t=>t.value===e);return(0,n.jsxs)(eP.l6,{value:c,onValueChange:e=>s(e===a3||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:a3,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 a6({value:e,onChange:t,ariaLabel:s}){let{t:r}=(0,f.Bd)("settings");return(0,n.jsx)(a4,{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 a8={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function a7(e,t){return JSON.stringify([e,t])}function a9(e,t){return JSON.stringify([e.provider,e.modelId,e.thinkingLevel,t])}function ie(e){return e.map(e=>({value:a7(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider}))}function it(e,t){return(e?.thinkingLevels??[]).map(e=>({value:e,label:t(a8[e])}))}function is({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,aU.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=aH.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")}]:[],...aH.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)(aY.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)(aV.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)(a5,{label:u("modelsHeading"),children:(0,n.jsx)(n3.b,{value:a7(t.provider,t.modelId),options:ie(r),ariaLabel:u("presetModel"),searchPlaceholder:u("modelSearch"),onChange:e=>{let s=r.find(t=>a7(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)(a5,{label:u("thinkingLevel"),children:(0,n.jsx)(a4,{value:t.thinkingLevel,options:it(s,u),ariaLabel:u("presetThinking"),allowEmpty:!1,onChange:e=>l({...t,thinkingLevel:e})})}),(0,n.jsx)(a5,{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)(aK.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)(aK.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 ir({presets:e,models:t,onChange:s}){let{t:a}=(0,f.Bd)("settings"),[i,l]=(0,r.useState)(()=>t[0]?a7(t[0].provider,t[0].modelId):""),o=t.find(e=>a7(e.provider,e.modelId)===i),[d,c]=(0,r.useState)(o?.thinkingLevels[0]??"off"),u=(0,aW.FR)((0,aW.MS)(aW.AN,{activationConstraint:{distance:6}}),(0,aW.MS)(aW.uN,{coordinateGetter:aU.JR})),m=(0,r.useMemo)(()=>e.map(a9),[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)(a5,{label:a("modelsHeading"),children:(0,n.jsx)(n3.b,{value:i,options:ie(t),ariaLabel:a("presetModelNew"),searchPlaceholder:a("modelSearch"),disabled:0===t.length,onChange:e=>{l(e);let s=t.find(t=>a7(t.provider,t.modelId)===e);s&&c(s.thinkingLevels[0])}})}),(0,n.jsx)(a5,{label:a("thinkingLevel"),children:(0,n.jsx)(a4,{value:d,options:it(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=>a7(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:aG(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)(aW.Mp,{sensors:u,collisionDetection:aW.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,aU.be)(e,n,r))},children:(0,n.jsx)(aU.gB,{items:m,strategy:aU._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)(is,{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,aU.be)(e,a,a-1)),onMoveDown:()=>s((0,aU.be)(e,a,a+1))},m[a])})})})})]})}var ia=s(72910),ii=s(61108),il=s(46783),io=s(89790);function id(e){return 100*!!e.official+10*!!e.defaults.cost}let ic=[["off","thinkingOff"],["minimal","thinkingMinimal"],["low","thinkingLow"],["medium","thinkingMedium"],["high","thinkingHigh"],["xhigh","thinkingXhigh"],["max","thinkingMax"]],iu=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function im(e){return{input:String(e.cost?.input??""),output:String(e.cost?.output??""),cacheRead:String(e.cost?.cacheRead??""),cacheWrite:String(e.cost?.cacheWrite??"")}}function ip(e,t){return Object.values(e).some(e=>null===a2(e))||Object.values(t).some(e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e)))}function ih({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:a1(s.contextWindow),maxTokens:a1(s.maxTokens)}),[u,m]=(0,r.useState)(()=>im(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)=>id(t)-id(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=aX.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)(io.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)(io.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)(il.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)(io.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)(io.xL,{className:"py-6 text-sm",children:l("noCatalogMatches")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(io.L$,{className:"p-0",children:y.map(e=>(0,n.jsx)(io.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:a1(r.contextWindow),maxTokens:a1(r.maxTokens)}),m(im(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:`${a1(e.source.defaults.contextWindow)}K`,output:`${a1(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)(a5,{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===a2(d[e]);return(0,n.jsxs)(a5,{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=ip(n,u),invalid:r}),void(null!==(a=a2(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:ic.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:[iu.map(([e,t])=>{let r=""!==u[e]&&(!Number.isFinite(Number(u[e]))||0>Number(u[e]));return(0,n.jsxs)(a5,{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=ip(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:ip(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)(a5,{label:l("apiOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(a4,{value:s.api??"",ariaLabel:l("apiOverride"),options:aX,placeholder:M?l("inheritServiceValue",{value:M}):l("inheritService"),onChange:e=>z({api:e||null})})}),(0,n.jsx)(a5,{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)(a5,{label:l("modelHeaders"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(a0,{headers:s.headers,onChange:e=>z({headers:e}),placeholder:l("headerPlaceholder")})}),(0,n.jsx)(a5,{label:l("developerRole"),children:(0,n.jsx)(a6,{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)(a5,{label:"Thinking Format",children:(0,n.jsx)(a4,{value:s.compat?.thinkingFormat??"",ariaLabel:"Thinking Format",options:aQ.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)(a5,{label:l("replayReasoning"),children:(0,n.jsx)(a6,{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 ig=s(66153),ix=s(95929);function ib({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)(ig.A,{className:"size-3.5"}):(0,n.jsx)(ix.A,{className:"size-3.5"})})]})}function iv({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}=nQ(),[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)(a5,{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)(a5,{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)(a5,{label:d("providerApiType"),children:(0,n.jsx)(a4,{value:m.api??"",ariaLabel:d("providerApiType"),options:aX,onChange:e=>b({api:e||null})})}),(0,n.jsx)(a5,{label:d("serviceKey"),children:(0,n.jsx)(ib,{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)(a5,{label:d("providerAuthHeader"),children:(0,n.jsx)(a6,{value:m.authHeader,ariaLabel:d("providerAuthHeader"),onChange:e=>b({authHeader:e})})}),(0,n.jsx)(a5,{label:d("providerHeaders"),children:(0,n.jsx)(a0,{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 iw=a.Ik({}).strict(),iy=a.Yj().trim().min(1).max(128),ik=a.Yj().max(32768),ij=a.Ik({url:ik,label:ik.optional()}).strict(),iN=a.Ik({provider:iy,name:ik,loggedIn:a.zM(),conflict:a.Yj().nullable()}).strict(),iI=a.Ik({id:a.Yj().uuid(),type:a.k5(["text","secret","select","manual_code"]),message:ik,placeholder:ik.optional(),options:a.YO(a.Ik({id:ik,label:ik,description:ik.optional()}).strict()).optional()}).strict(),iC=a.gM("type",[a.Ik({type:a.eu("auth_url"),url:ik,instructions:ik.optional()}).strict(),a.Ik({type:a.eu("device_code"),userCode:ik,verificationUri:ik}).strict(),a.Ik({type:a.eu("info"),message:ik,links:a.YO(ij).optional()}).strict(),a.Ik({type:a.eu("progress"),message:ik}).strict()]),iS=a.Ik({loginId:a.Yj().uuid(),provider:iy,status:a.k5(["running","completed","cancelled","error"]),notice:iC.nullable(),prompt:iI.nullable(),message:a.Yj().nullable()}).strict(),iM=Object.freeze({list:(0,i.Vc)({path:"model-auth/list",inputSchema:iw,outputSchema:a.Ik({providers:a.YO(iN)}).strict()}),start:(0,i.Vc)({path:"model-auth/start",inputSchema:a.Ik({loginId:a.Yj().uuid(),provider:iy}).strict(),outputSchema:iw}),respond:(0,i.Vc)({path:"model-auth/respond",inputSchema:a.Ik({loginId:a.Yj().uuid(),promptId:a.Yj().uuid(),value:ik}).strict(),outputSchema:iw}),cancel:(0,i.Vc)({path:"model-auth/cancel",inputSchema:a.Ik({loginId:a.Yj().uuid()}).strict(),outputSchema:iw}),logout:(0,i.Vc)({path:"model-auth/logout",inputSchema:a.Ik({provider:iy}).strict(),outputSchema:iw}),state:(0,i._G)({path:"model-auth/state",bodySchema:iS})});function iz(e){try{let t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}}function iE(e){let t=iz(e);t&&window.open(t,"_blank","noopener,noreferrer")}async function iA(e){await navigator.clipboard.writeText(e)}function i$({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)(a5,{label:e.message,children:"select"===e.type?(0,n.jsx)(a4,{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)(ib,{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 iR({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)=>iz(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 iP({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)(iR,{notice:r.notice,onCopy:u,onOpenUrl:m}):null,g&&r.prompt?(0,n.jsx)(i$,{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 iT({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 ",a1(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 iD=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function iL({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?"":a1(s.contextWindow),maxTokens:void 0===s.maxTokens?"":a1(s.maxTokens),...Object.fromEntries(iD.map(([e])=>[e,s.cost?.[e]===void 0?"":String(s.cost[e])]))})),c=e=>""!==e&&null===a2(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)||iD.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]=a2(t),a(n)}else{if(iD.some(([e])=>u(n[e])))return;let e={...s};iD.every(([e])=>""===n[e])?delete e.cost:e.cost=Object.fromEntries(iD.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:[a1(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:[a1(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?iD.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)(a5,{label:`${l("contextWindow"===t?"contextLength":"maximumOutput")} (K)`,children:[(0,n.jsx)(eB.p,{value:o[t],placeholder:a1(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:iD.map(([t,s])=>(0,n.jsxs)(a5,{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 iO=s(34506);function iF({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)(iO.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 iB({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)(iF,{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?`${a1(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)(ii.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 iq({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}=nQ(),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(iM.list,{})).providers,async start(e,t){await s.request(iM.start,{loginId:e,provider:t})},async respond(e,t,n){await s.request(iM.respond,{loginId:e,promptId:t,value:n})},async cancel(e){await s.request(iM.cancel,{loginId:e})},async logout(e){await s.request(iM.logout,{provider:e})},subscribe:e=>s.subscribe(iM.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)}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(),m(null),y(null),v(null),x(!1),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 iA(e),i.success(a("accountCopied"))}catch{i.error(a("accountCopyFailed"))}},openUrl:iE}}(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)(iB,{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.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>R.show(),children:[(0,n.jsx)(ia.A,{}),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)(iF,{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)(ii.A,{}),b("addModelPreset")]}),(0,n.jsxs)(t3.m_,{children:[(0,n.jsx)(t3.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)(t3.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)(iL,{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)(ih,{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)(iP,{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)(iT,{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)(iv,{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)(a5,{label:b("thinkingLevel"),children:(0,n.jsx)(a4,{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:aG(u)}]),V(!1))},disabled:!eh,children:b("presetAdd")})]})]})}),w]})}let iW={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function iU(e,t){return JSON.stringify([e,t])}function iY(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function iV({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}=nQ(),[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}),aT({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=al.safeParse((aN(),ab)),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=(aR(),aA.get(a$(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:iU(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:iY(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:iY(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)(ra,{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)(a5,{label:a("projectDefaultModel"),children:(0,n.jsx)(n3.b,{value:i.selection?iU(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=>iU(t.provider,t.modelId)===e);t&&i.selectModel(t)}})}),(0,n.jsx)(a5,{label:a("thinkingLevel"),children:(0,n.jsx)(a4,{value:i.selection?.thinkingLevel??"",options:(u?.thinkingLevels??[]).map(e=>({value:e,label:a(iW[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(iW[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 iK=[{value:"providers",label:"modelProviders"},{value:"presets",label:"modelPresets"},{value:"project-default",label:"projectDefault"}];function iH({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 iG({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}=nQ(),o=(0,r.useMemo)(()=>{let e;return e=null,{parseNativeConfig(e){let t=JSON.parse(e);return rV.parse(t)},getSettings:()=>(e||(e=eF(n,"/api/model-settings/get",{},r3).finally(()=>{e=null})),e),async replaceSettings(e){let t=r6.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,r8)},listCatalog:e=>eF(n,"/api/model-catalog/list",r7.parse(e),as),async listDirectories(){let e=await eF(n,"/api/pi/directories/list",{forceRefresh:!1},al);return aC(e),e},async getProjectDefault(e){let t=await eF(n,"/api/project-model-default/get",{cwd:e},an);return aT(t),t},async replaceProjectDefault(e){await eF(n,"/api/project-model-default/replace",ar.parse(e),aa)}}},[n]),[d,c]=(0,r.useState)(()=>t??aB(aF,aL,"providers"));(0,r.useEffect)(()=>{a_(aF,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)(ra,{label:a("models"),layout:"segmented",value:u,options:iK.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)(rL.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)(rL.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)(iV,{biz:c,presets:m?.presets??[],onDirtyChange:W}):m?null:(0,n.jsx)(iH,{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)(iq,{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)(ir,{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)(aq,{open:I,text:S,error:M,saving:O,dirty:z,onChange:E,onClose:$,onSave:R}),q]})}function iJ({render:e,input:t}){return e(t)}let iX=[{id:"appearance",label:"appearance",icon:sK.A},{id:"region",label:"region",icon:sH.A},{id:"habits",label:"habits",icon:sG.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:sJ.A},{id:"plugins",label:"plugins",icon:e0.A},{id:"auth",label:"loginProtection",icon:eA.A},{id:"about",label:"about",icon:sX.A}];function iQ(e,t){return`plugin:${e}:${t}`}function iZ(){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)(s0.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",sQ]})]}),(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)}(sZ,"en"===t.locale?"en-US":"zh-CN",t.timeZone,e("common:unavailable"))})]})]})]})}function i0({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":aB(aO,aD,"appearance"));(0,r.useEffect)(()=>{e&&a_(aO,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=>iQ(e.pluginName,e.descriptor.contributionName)===v),E=v.startsWith("plugin:")&&!z?"appearance":v,A=iX.find(e=>e.id===E),$=A?.icon,R=(0,r.useRef)(null);s7(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=iX.find(t=>t.id===e);if(t)return void L(t.id);let s=b.find(t=>iQ(t.pluginName,t.descriptor.contributionName)===e);s&&L(iQ(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:[iX.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=iQ(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:iX.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=iQ(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)(iJ,{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)(nH,{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)(iJ,{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)(iJ,{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)(iG,{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)(rb,{}):"habits"===E?(0,n.jsx)(rD,{}):"auth"===E?e&&(0,n.jsx)(n5,{}):"region"===E?(0,n.jsx)(re,{canLeave:p}):(0,n.jsx)(iZ,{})})})]})]})})}let i1=a.Ik({cwd:a.Yj().trim().min(1).nullable()}).strict(),i2=a.g1(a.Yj(),a.Pq()),i5=a.g1(a.Yj().min(1).max(128),i2),i3=a.Ik({local:i5,inherited:i5,projectTrusted:a.zM().nullable(),diagnostics:a.YO(a.Ik({name:a.Yj().nullable(),message:a.Yj()}).strict())}).strict();i1.extend({servers:i5}).strict(),i1.extend({name:a.Yj().min(1).max(128)}).strict();let i4=a.Ik({output:a.Yj()}).strict(),i6=a.Ik({}).strict(),i8=["command","args","url","type","description","enabled","exposure"];function i7(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&Object.values(e).every(e=>"string"==typeof e)}function i9(e){return i7(e)?Object.entries(e).map(([e,t])=>({key:e,value:t})):[]}function le(e){return!("command"in e)&&!("url"in e)&&!("type"in e)}function lt(e,t){let s=t??{};return{originalName:e,name:e??"",transport:t&&le(t)?"inherit":"url"in s?"http":"stdio",command:"string"==typeof s.command?s.command:"",args:Array.isArray(s.args)?s.args.join("\n"):"",env:i9(s.env),headers:i9(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])=>!i8.includes(e)&&!(["env","headers"].includes(e)&&i7(t)))),null,2)}}class ls extends Error{constructor(e,t){super(t),this.field=e}}function ln(e){return"string"==typeof e.url?e.url:"string"==typeof e.command?e.command:"继承全局连接"}let lr={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 la(){let{locale:e}=(0,tp.i)();return t=>"en"===e?lr[t]??t:t}function li(e){return e instanceof Error?e.message:"请求失败,请重试。"}function ll({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 lo({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 ld({message:e,id:t}){let s=la();return e?(0,n.jsx)("p",{id:t,role:"alert",className:"break-words text-sm text-destructive",children:s(e)}):null}function lc({rows:e,selectedName:t,pending:s,onSelect:r}){let a=la();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:ln(e.config)})]}),(0,n.jsx)(eo.A,{"aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"})]})},e.name)})})}function lu({id:e,label:t,rows:s,disabled:r,error:a,onChange:i}){let l=la();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)(ld,{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 lm=s(27315);function lp({check:e,onRetry:t,onDismiss:s}){let r=la(),a=e.loading?b.A:e.error?W.A:lm.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)(ld,{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 lh({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=la(),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)(ld,{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)(lo,{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)(lp,{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:ln(o[z])}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:v("连接参数沿用全局,仅保存本项目的启用和工具设置。")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ll,{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)(sd.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)(lu,{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)(lu,{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)(ll,{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)(sd.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)(ld,{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)(sd.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(le(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)(ld,{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 lg({pending:e,onAdd:t,onImport:s}){let r=la();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 lx({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{clientId:i}=(0,eR.gM)(),l=function(e,t){let s=la(),n=(0,r.useMemo)(()=>({getMcp:(t,s)=>eF(e,"/api/mcp-settings/get",{cwd:t},i3,{signal:s}),replaceMcp:(t,s)=>eF(e,"/api/mcp-settings/replace",t,i6,{signal:s}),deleteMcp:(t,s,n)=>eF(e,"/api/mcp-settings/del",{cwd:t,name:s},i6,{signal:n}),checkMcp:(t,s,n)=>eF(e,"/api/mcp-check/get",{cwd:t,name:s},i4,{signal:n})}),[e]),{confirm:i,dialog:l}=nQ(),[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(li(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=lt(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 ls?e.field:"save",message:li(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 ls("name","服务名称需要 1–128 个字符。");try{s=i2.parse(JSON.parse(e.advanced))}catch{throw new ls("advanced","高级配置需要是 JSON 对象。")}if(i8.some(e=>e in s))throw new ls("advanced","连接、说明、启用和曝光字段请在上方表单中填写。");if("inherit"===e.transport&&Object.keys(s).some(e=>"toolExposure"!==e))throw new ls("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||i7(t?.[n])){if(n in s)throw new ls("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 ls(t,"请填写名称,或删除空白行。");let e=r.key.trim(),a="headers"===t?e.toLowerCase():e;if(n.has(a))throw new ls(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 ls("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 ls("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 ls("json","请明确勾选替换已有配置。");if("manual"===m.kind&&s.some(e=>e!==m.draft.originalName))throw new ls("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=lt(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 ls?e.field:"save",message:li(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:li(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&&le(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:i5}).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 ls("json","服务名称不能为空或带有首尾空格。");if(le(n)){if(null===o||!Object.hasOwn(e,s)||Object.keys(n).some(e=>!["enabled","exposure","toolExposure"].includes(e)))throw new ls("json",`${s}:继承配置需要同名全局服务,且只允许启用和曝光设置。`)}else if("sse"===n.type)throw new ls("json",`${s}:不支持 SSE,请使用 HTTP 连接。`);else if("string"!=typeof n.command&&"string"!=typeof n.url)throw new ls("json",`${s}:请提供启动程序或服务地址。`)}p({...m,preview:t,overwrite:!1}),y(null)}catch(e){y({field:"json",message:li(e)})}},saveEditor:O,remove:F,dismissCheck:()=>{I(null)},beforeLeave:R}}(i,s),o=la(),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)(ll,{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)(ld,{message:`${e.name?`${e.name}:`:""}${e.message}`},t))}),l.loadError?(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(ld,{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)(ld,{message:l.error.message})}),(0,n.jsx)(lc,{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)(lh,{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)(lg,{pending:h,onAdd:x,onImport:f}):null]}):null]})}var lf=s(267),lb=s(59605),lv=s(55438);let lw=a.Yj().trim().min(1).max(200),ly=a.Yj().trim().min(1).max(100).nullable(),lk=a.Yj().trim().min(1).max(100).nullable(),lj=a.Yj().trim().min(1).max(200),lN=a.Ik({label:a.Yj().trim().min(1).max(64),value:a.Yj().trim().min(1).max(500)}).strict(),lI=a.Yj().trim().min(1).max(300).nullable(),lC=a.k5(["running","completed","failed","stopped","interrupted"]),lS=a.Ik({taskId:lw,taskKind:ly,taskType:lk,title:lj,info:a.YO(lN).max(12),status:lC,activity:lI,startedAt:rF.k,endedAt:rF.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"]})}),lM=a.Ik({tasks:a.YO(lS)}).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)}),lz=a.Ik({kind:a.eu("text"),text:a.Yj(),truncated:a.zM()}).strict(),lE=lb.RX.extend({kind:a.eu("conversation"),truncated:a.zM()}).strict(),lA=a.KC([a.ch(),lz,lE]),l$=a.Ik({taskId:lw,canInterrupt:a.zM(),body:lA}).strict(),lR=lv.mv,lP=a.KC([a.Ik({type:a.eu("snapshot"),snapshot:l$}).strict(),a.Ik({type:a.eu("text_append"),text:a.Yj().min(1)}).strict(),a.Ik({type:a.eu("conversation_event"),event:lR}).strict(),a.Ik({type:a.eu("unavailable")}).strict()]);a.Ik({source:lf.R,taskId:lw,entryId:nn.Rv}).strict().extend({imageIndex:a.ai().int().nonnegative()}).strict();let lT=a.Ik({source:lf.R,taskId:lw.nullable()}).strict(),lD=a.Ik({snapshot:l$.nullable()}).strict(),lL=a.Ik({source:lf.R,taskId:lw}).strict(),lO=a.Ik({}).strict(),lF=a.Ik({source:lf.R,taskId:lw,event:lP}).strict(),lB=Object.freeze({detailWatch:(0,i.Vc)({path:"task-center/detail-watch",inputSchema:lT,outputSchema:lD}),interrupt:(0,i.Vc)({path:"task-center/interrupt",inputSchema:lL,outputSchema:lO}),detailEvent:(0,i._G)({path:"task-center/detail-event",bodySchema:lF})});var l_=s(45811),lq=s(14510),lW=s(12019),lU=s(86075),lY=s(84571),lV=s(67011);let lK=({className:e,...t})=>(0,n.jsx)(lV.z,{className:(0,C.cn)("relative flex-1 overflow-y-hidden",e),initial:"smooth",resize:"smooth",role:"log",...t}),lH=({className:e,...t})=>(0,n.jsx)(lV.z.Content,{className:(0,C.cn)("flex flex-col gap-8 p-4",e),...t});var lG=s(47744),lJ=s(30973),lX=s(14203),lQ=s(26575),lZ=s(11953);function l0({...e}){return(0,n.jsx)(lG.j,{"data-slot":"hover-card",...e})}function l1({...e}){return(0,n.jsx)(lJ.Z,{"data-slot":"hover-card-trigger",...e})}function l2({className:e,side:t="bottom",sideOffset:s=4,align:r="center",alignOffset:a=4,...i}){return(0,n.jsx)(lX.D,{"data-slot":"hover-card-portal",children:(0,n.jsx)(lQ.p,{align:r,alignOffset:a,side:t,sideOffset:s,className:"isolate z-50",children:(0,n.jsx)(lZ.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 l5=({className:e,...t})=>(0,n.jsx)(n_.Sq,{align:"block-end",className:(0,C.cn)("justify-between gap-1",e),...t}),l3=({className:e,...t})=>(0,n.jsx)("div",{className:(0,C.cn)("flex min-w-0 items-center gap-1",e),...t}),l4=({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)(t3.m_,{children:[(0,n.jsx)(t3.k$,{render:o}),(0,n.jsxs)(t3.ZI,{side:u,children:[d,c&&(0,n.jsx)("span",{className:"ml-2 text-muted-foreground",children:c})]})]})},l6=a.Ik({input:a.g1(a.Yj(),a.Pq())}).strict(),l8=a.Ik({output:a.Yj()}).strict(),l7="pideskHelp",l9=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,oe=/^(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 ot(e){return/^[a-zA-Z0-9_./:@=+-]+$/.test(e)?e:JSON.stringify(e)}let os=a.Ik({name:a.Yj(),scope:a.eu("global").optional(),source:a.Yj(),kind:a.k5(["package","extension"]),version:a.Yj().nullable(),status:a.k5(["ready","available","disabled","failed"]),updateTag:a.Yj().nullish(),availableVersion:a.Yj().nullish(),updateError:a.Yj().nullish(),operation:a.Ik({action:a.k5(["add","update","del","apply"]),phase:a.k5(["queued","checking","applying","waiting","failed"]),message:a.Yj().nullable()}).strict().nullish(),error:a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:tm.qf}).strict().nullish()}).strict(),on=a.Ik({plugins:a.YO(os),restartRequired:a.zM(),loadError:tm.qf.nullish()}).strict(),or=os.extend({detail:a.g1(a.Yj(),a.Pq())}).strict(),oa=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(),oi=null,ol=new WeakMap,oo=new WeakMap,od=new WeakMap;function oc(e){switch(e.fixed.type){case"user":{let t=lb.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?lb.Er.safeParse(e.summary):null,s=t?.success?t.data:{text:"",errorMessage:null},n="pi-desk/assistant"===e.fixed.viewKey?lb.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=lb.UT.safeParse(e.summary),r=n.success?n.data:t,a=lb.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=l6.safeParse(e.summary),r=n.success?n.data:{input:{}},a=l8.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=lb.Qi.safeParse(e.summary),r=n.success?n.data:{...t,timing:null},a=lb.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=lb.Gx.safeParse(e.summary),r=n.success?n.data:{...t,path:null},a=lb.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=lb.aV.safeParse(e.summary),r=n.success?n.data:{...t,path:null},a=lb.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=lb.bN.safeParse(e.summary),r=n.success?n.data:{...t,path:null},a=lb.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=lb.Px.safeParse(e.summary),r=n.success?n.data:t,a=lb.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=lb.ai.safeParse(e.summary),s=t.success?t.data:{command:e.fixed.viewKey},n=lb.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=lb.sL.safeParse(e.detail);return{summary:{type:"compaction",hasDetail:e.fixed.hasDetail},detail:t.success?{type:"compaction",...t.data}:void 0}}let t=lb.Rt.safeParse(e.summary);return{summary:{type:"custom",text:(t.success?t.data:{text:""}).text,hasDetail:!1},detail:void 0}}}}function ou(e){return e.temporary||"status"in e.summary&&"running"===e.summary.status}function om(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 op(e,t,s){if("compaction"===s.summary.type){oh(e,t),e.push({identity:s.identity,user:null,processItems:[],finalAssistant:null,compaction:s,running:ou(s),toolCount:0});return}"user"!==s.summary.type?t.body.push(s):(oh(e,t),t.user=s)}function oh(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||om(t))&&a.push({message:t,hideAssistantText:!1});continue}om(t)&&a.push({message:t,hideAssistantText:!0})}return{identity:e,user:t,processItems:a,finalAssistant:r,compaction:null,running:s.some(ou),toolCount:s.filter(e=>"tool"===e.summary.type||"bash"===e.summary.type).length}}(s,t.user,t.body)),t.user=null,t.body=[]}function og(e,t=!1){let s=function(e){let t=od.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=ol.get(e);if(t)return t;let s=oc(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 ol.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)),op(s,n,e)}let l={turns:s,user:n.user,body:n.body};return od.set(e,l),l}(e.messages),n=[...s.turns],r={user:s.user,body:[...s.body]};for(let[t,s]of e.temporaryMessages.entries())op(n,r,function(e,t){let s=oo.get(e);if(s?.position===t)return s.message;let n=oc(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 oo.set(e,{position:t,message:r}),r}(s,e.messages.length+t));oh(n,r);let a=n.at(-1);return t&&a&&!a.compaction&&(a.running=!0),n}function ox(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}m`}function of(e){return 0===e?"$0":e<1e-4?"<$0.0001":`$${e.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function ob(e,t=Date.now(),s="en",n="UTC"){let r=new Date(e),a=new Date(t),i=function(e,t){if(oi?.locale===e&&oi.timeZone===t)return oi;let s="en"===e?"en-US":"zh-CN";return oi={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 ov(e,t,s={}){if("1"!==new URLSearchParams(window.location.search).get("chatScrollDebug"))return;let n=ok(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?oj(n):0,tailMinHeight:n?.style.minHeight||null,tailAnchor:n?.dataset.chatTailAnchor??null,...s})}function ow(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 oy(e){let t,s=(t=e.querySelectorAll("[data-chat-turn]")).item(t.length-1);return s?.hasAttribute("data-chat-logical-tail")?s:null}function ok(e){return e.querySelector("[data-chat-tail-space]")}function oj(e){let t=e.lastElementChild;return t instanceof HTMLElement?Math.max(0,e.getBoundingClientRect().bottom-t.getBoundingClientRect().bottom):0}function oN(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 oI(e){let t=ok(e);return t?oj(t):0}function oC(e){for(let t of e.querySelectorAll("[data-chat-tail-space]"))ov("tail:clear:start",e),t.style.removeProperty("min-height"),delete t.dataset.chatTailSpace,delete t.dataset.chatTailAnchor,delete t.dataset.chatTailOffset,ov("tail:clear:end",e)}function oS(e){let t=ok(e);if(!t)return;if(t!==oy(e))return void oC(e);let s=t.dataset.chatTailAnchor,n=Number.parseFloat(t.dataset.chatTailOffset??"");if(!s||!Number.isFinite(n))return;let r=ow(e,"data-chat-scroll-anchor",s);if(!r)return void oC(e);let{minHeight:a}=oN(e,r,t,n),i=`${Math.ceil(a)}px`;t.style.minHeight!==i&&(ov("tail:refresh:start",e,{nextMinHeight:i}),t.style.minHeight=i,ov("tail:refresh:end",e,{nextMinHeight:i}))}function oM(e,t,s,n){ov("position:start",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n}),oC(e);let r=n?oy(e):null;if(!r){e.scrollTop=Math.max(0,e.scrollTop+t.getBoundingClientRect().top-e.getBoundingClientRect().top-s),ov("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n});return}let{targetScrollTop:a,minHeight:i}=oN(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,ov("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n,minHeight:i})}function oz({active:e=!0}){let{scrollRef:t,state:s}=(0,lV.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,oS(r)}))},o=new ResizeObserver(l),d=()=>{let e=new Set,t=ok(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)?(ov("viewport:resize",r,{difference:i,isAtBottom:s.isAtBottom,escapedFromLock:s.escapedFromLock}),u=i,s.resizeDifference=i,null!==a&&(window.cancelAnimationFrame(a),a=null),oS(r),s.isAtBottom&&(s.scrollTop=Math.max(0,s.calculatedTargetScrollTop)),ov("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 oE(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 oA(e,t,s){let n=0;for(let r=t;r<s;r+=1)e[r]?.user&&(n+=1);return n}function o$(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,oA(e,0,s)),r=s,a=0,i=0,l=0;for(;r>0;){let t=e[r-1],s=oE(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 oR(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,oA(e,s,e.length)),r=s,a=0,i=0,l=0;for(;r<e.length;){let t=e[r],s=oE(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 oP(e){return{startIndex:o$(e,e.length),endIndex:e.length}}function oT(e,t){let s,n;if(0===e.length)return{startIndex:0,endIndex:0};if(!t)return oP(e);let r=(n=(s=t.lastIndexOf(":"))>0?t.slice(0,s):t,e.findIndex(e=>oE(e).some(e=>e.identity===n)));if(r<0)return oP(e);let a=Math.min(e.length,r+1+10);return{startIndex:o$(e,a),endIndex:a}}function oD({active:e=!0,turns:t,focusTurnIdentity:s,initialAnchor:a,children:i}){let{scrollRef:l}=(0,lV.B)(),[o,d]=(0,r.useState)(()=>({...oT(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 oP(t);if(0===o.turnCount&&0===o.endIndex)return oT(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=o$(t,m.startIndex);if(e>=m.startIndex)return;h();let s=l.current;s&&ov("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=oR(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,o$(t,e+1))}):p({...m,endIndex:Math.max(e+1,oR(t,e))}))},[p,m,t]),b=(0,r.useCallback)(()=>{p(oP(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;ov("window:anchor-correction:start",s,{turnIdentity:t.turnIdentity,previousOffset:t.offset,nextOffset:r,correction:a}),s.scrollTop+=a,ov("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 oL={canMoveUp:!1,canMoveDown:!1,hasNextMessage:!1};function oO(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 oF(e){return e.user?`${e.user.identity}:user`:null}function oB(e,t,s){let n=Array.from(e.querySelectorAll("[data-chat-user-message]")),r=e.getBoundingClientRect().top+12,a=oO(n,r,-2,!0),i=oO(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=oI(e),p=t.containsTail&&u<=2;return ov("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,lV.B)(),o=(0,r.useMemo)(()=>e.flatMap((e,t)=>e.user?[t]:[]),[e]),[d,c]=(0,r.useState)(!1),[u,m]=(0,r.useState)(oL),[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=oB(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(oL),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(),oM(e,n,12,t.containsTail))}j.current&&t.containsTail&&(j.current=!1,oC(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=oB(r,t,o),c="up"===s?d.previousMessage:d.atBottom?null:d.nextMessage;if(c){let s=o.findIndex(t=>oF(e[t])===c.dataset.chatScrollAnchor);s>=0&&R(s+1),y.current=!1,l(),oM(r,c,12,t.containsTail)}else{let a="up"===s?d.previousOutsideTurnIndex:d.nextOutsideTurnIndex;if(null!==a){let s=oF(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||(ov("navigation:bottom:start",r,{containsTail:t.containsTail}),y.current=!0,oC(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)(t5,{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 oq=(0,r.createContext)({basic:!1});function oW({basic:e,onRecover:t,children:s}){let a=(0,r.useMemo)(()=>({basic:e,recover:t}),[e,t]);return(0,n.jsx)(oq.Provider,{value:a,children:s})}function oU(e){return{location:e.snapshot.location,fixed:e.snapshot.fixed,summary:e.snapshot.summary,...void 0===e.snapshot.detail?{}:{detail:e.snapshot.detail}}}class oY{constructor(e,t){this.listeners=new Set,this.pending=null,this.requestEpoch=0,this.disposed=!1,this.basic=!1,this.message=e,this.snapshot=oU(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=oU(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 oV({message:e,pluginName:t,contributionName:s,phase:a,error:i,handle:l,fallback:o,onRetry:d}){let{t:c}=(0,f.Bd)("conversation"),[u,m]=(0,r.useState)(l.getSnapshot().detail),[p,h]=(0,r.useState)(!1),[g,x]=(0,r.useState)(null),v=(0,r.useContext)(oq),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),I=i.name,C=i.message,S=i.stack;return(0,r.useEffect)(()=>{console.error("[Pi Desk][MessageView] 消息视图无法展示",{messageId:e.identity,viewKey:e.viewKey,pluginName:t,contributionName:s,phase:a,errorName:I,message:C,stack:S})},[e.identity,e.viewKey,t,s,a,I,C,S]),(0,n.jsxs)("div",{className:"space-y-2","data-message-id":e.identity,children:[o,(0,n.jsx)("div",{role:"alert",className:"rounded-lg border border-destructive/35 bg-muted/30 p-3 text-sm",children:(0,n.jsxs)("div",{className:"flex items-start gap-2",children:[(0,n.jsx)(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:c("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??c("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:c("publicSnapshot")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto rounded-md bg-background p-3 font-mono text-sm whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(l.getSnapshot(),null,2)})]}),!e.temporary&&e.snapshot.fixed.hasDetail&&void 0===u?(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:p,onClick:()=>{h(!0),x(null),l.loadDetail().then(m,e=>{x(e instanceof Error?e.message:c("detailFailed"))}).finally(()=>h(!1))},children:[p?(0,n.jsx)(b.A,{className:"animate-spin"}):null,c("loadDetail")]}):null,g?(0,n.jsx)("p",{className:"text-sm text-destructive [overflow-wrap:anywhere]",children:g}):null,u?(0,n.jsx)("pre",{className:"max-h-48 overflow-auto rounded-md bg-background p-3 font-mono text-sm whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(u,null,2)}):null]}),v.recover?(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",className:"mt-2 mr-2",disabled:w,onClick:()=>{y(!0),v.recover().catch(e=>x(e instanceof Error?e.message:String(e))).finally(()=>y(!1))},children:[w?(0,n.jsx)(b.A,{className:"animate-spin"}):null,c("useBasicPresentation")]}):null,d?(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",className:"mt-2",disabled:k,onClick:()=>{j(!0),x(null),Promise.resolve().then(d).catch(e=>x(e instanceof Error?e.message:String(e))).finally(()=>j(!1))},children:[k?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(eE.A,{}),c("retry")]}):null]})]})})]})}function oK({message:e}){let{t}=(0,f.Bd)("conversation");return(0,n.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm","aria-busy":"true",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",role:"status",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"}),t("viewLoading")]}),(0,n.jsxs)("details",{className:"mt-2",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:t("messageContent")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(e.snapshot.summary,null,2)})]})]})}function oH({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)(oq),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 oY(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]);if((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",generation:S})},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)return(0,n.jsx)(n.Fragment,{children:s});if("pi-desk/message-declaration-error"===e.viewKey)return(0,n.jsx)(oV,{message:e,pluginName:"pi-desk",contributionName:"message-declaration-error",phase:"declaration",error:Error(a("declarationFailed")),handle:p});if(!b)return I?(0,n.jsx)(n.Fragment,{children:s}):(0,n.jsx)(oK,{message:e});if(x?.status==="conflict")return(0,n.jsx)(oV,{message:e,pluginName:null,contributionName:null,phase:"priority-conflict",error:Error(a("viewConflict")),handle:p,fallback:I?s:void 0});if(!x)return I?(0,n.jsx)(n.Fragment,{children:s}):v?(0,n.jsx)(oK,{message:e}):(0,n.jsx)(oV,{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)))}});if("error"===u.status&&u.generation===S)return(0,n.jsx)(oV,{message:e,pluginName:x.pluginName,contributionName:x.descriptor.contributionName,phase:u.phase,error:u.error,handle:p,fallback:I?s:void 0,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})})}});let z="ready"===u.status&&u.generation===S;return(0,n.jsxs)("div",{className:"relative","data-message-id":e.identity,"aria-busy":!z,children:[z?null:I?s:(0,n.jsx)(oK,{message:e}),(0,n.jsx)("div",{ref:o,className:z?void 0:"pointer-events-none invisible absolute inset-x-0 top-0","data-pi-desk-plugin":x.pluginName,"data-pi-desk-kind":"message-view","data-pi-desk-contribution":x.descriptor.contributionName})]})}var oG=s(41934),oJ=s(4795),oX=s(33353),oQ=s(15948),oZ=s(7010),o0=s(64572),o1=s(50153);let o2={src:"/_next/static/media/console.fdac8a18.svg",height:16,width:16,blurWidth:0,blurHeight:0},o5={src:"/_next/static/media/docker.1e10aab8.svg",height:24,width:24,blurWidth:0,blurHeight:0},o3={src:"/_next/static/media/git.f893cb5f.svg",height:32,width:32,blurWidth:0,blurHeight:0},o4={src:"/_next/static/media/html.97f145d3.svg",height:32,width:32,blurWidth:0,blurHeight:0},o6={src:"/_next/static/media/image.69ad851c.svg",height:16,width:16,blurWidth:0,blurHeight:0},o8={src:"/_next/static/media/javascript.9ef61c53.svg",height:16,width:16,blurWidth:0,blurHeight:0},o7={src:"/_next/static/media/json.eb8fe488.svg",height:960,width:960,blurWidth:0,blurHeight:0},o9={src:"/_next/static/media/markdown.ee1bbe18.svg",height:32,width:32,blurWidth:0,blurHeight:0},de={src:"/_next/static/media/nodejs.2f5d7983.svg",height:32,width:32,blurWidth:0,blurHeight:0},dt={src:"/_next/static/media/typescript.cd97905b.svg",height:16,width:16,blurWidth:0,blurHeight:0},ds={src:"/_next/static/media/yaml.8927dd24.svg",height:24,width:24,blurWidth:0,blurHeight:0},dn=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":de,"package-lock.json":de,"npm-shrinkwrap.json":de,dockerfile:o5,".dockerignore":o5,".gitignore":o3,".gitattributes":o3,".gitmodules":o3})),dr=new Map(Object.entries({ts:dt,mts:dt,cts:dt,tsx:{src:"/_next/static/media/react_ts.3d16336c.svg",height:32,width:32,blurWidth:0,blurHeight:0},js:o8,mjs:o8,cjs:o8,jsx:{src:"/_next/static/media/react.b5a87f7d.svg",height:32,width:32,blurWidth:0,blurHeight:0},json:o7,jsonc:o7,jsonl:o7,yaml:ds,yml:ds,md:o9,mdx:o9,png:o6,jpg:o6,jpeg:o6,gif:o6,webp:o6,avif:o6,bmp:o6,ico:o6,svg:{src:"/_next/static/media/svg.4aa98763.svg",height:32,width:32,blurWidth:0,blurHeight:0},sh:o2,bash:o2,zsh:o2,fish:o2,ps1:o2,bat:o2,cmd:o2,html:o4,htm:o4,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 da({path:e,className:t}){let s=e.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()??"",r=s.includes(".")?s.slice(s.lastIndexOf(".")+1):"",a=dn.get(s)??(s.startsWith("dockerfile.")?o5:void 0)??dr.get(r);return a?(0,n.jsx)(o1.default,{src:a,alt:"","aria-hidden":"true",width:16,height:16,className:t,unoptimized:!0}):(0,n.jsx)(nF.A,{className:t,"aria-hidden":"true"})}var di=s(47125),dl=s(9922);let dd=new Map,dc=(0,r.memo)(({children:e,as:t="p",className:s,duration:a=2,spread:i=2})=>{let l,o=((l=dd.get(t))||(l=dl.PY1.create(t),dd.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})}),du=(0,r.createContext)(null),dm=(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,di.i)({defaultProp:c,onChange:i,prop:s}),[h,g]=(0,di.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)(du.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})})}),dp=(e,t)=>e||0===t?(0,n.jsx)(dc,{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"]}),dh=(0,r.memo)(({className:e,children:t,getThinkingMessage:s=dp,...a})=>{let{isStreaming:i,isOpen:l,duration:o}=(()=>{let e=(0,r.useContext)(du);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)(oG.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")})]})})}),dg={cjk:t4.h,code:t6.a,math:t8.D,mermaid:t7.a},dx=(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)(t9.jH,{plugins:dg,children:t})}));dm.displayName="Reasoning",dh.displayName="ReasoningTrigger",dx.displayName="ReasoningContent";var df=s(52216),db=s.n(df);function dv({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)(db().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:db().table,children:[(0,n.jsxs)("div",{className:(0,C.cn)(db().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:db().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:ox(r.inputTokens)}),(0,n.jsx)("span",{children:ox(r.outputTokens)}),(0,n.jsx)("span",{children:ox(r.cacheReadTokens)}),(0,n.jsx)("span",{children:of(r.costUsd)})]},e.durable.location.entryId)})]})}):null]})]})}function dw({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",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 dy({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.updateTag||e.availableVersion?(0,n.jsxs)("p",{className:"flex flex-wrap gap-x-3 text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e.updateTag?(0,n.jsx)("span",{children:t("pidesk.updateChannel",{tag:e.updateTag})}):null,e.availableVersion?(0,n.jsx)("span",{children:t("pidesk.targetVersion",{version:e.availableVersion})}):null]}):null,e.updateError?(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:e.updateError}):null,e.operation?(0,n.jsxs)("p",{className:"[overflow-wrap:anywhere]",children:[t(`pidesk.action.${e.operation.action}`)," \xb7 ",t(`pidesk.phase.${e.operation.phase}`),e.operation.message?` \xb7 ${e.operation.message}`:""]}):null,e.error?(0,n.jsxs)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:[t(`pidesk.errorPhase.${e.error.phase}`)," \xb7 ",(0,tm.fD)(e.error.message,s)]}):null]})}function dk({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)(dy,{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)(dy,{plugin:e},`${e.source}:${t}`))}):(0,n.jsx)("p",{className:"text-muted-foreground",children:t("pidesk.noPlugins")})]})}function dj({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=on.safeParse(s);return e.success?{kind:"plugins",data:e.data}:null}case"pideskShowPlugin":{let e=or.safeParse(s);return e.success?{kind:"plugin",data:e.data}:null}case"pideskInfo":{let e=oa.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)(rt.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 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)(dk,{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 dN=s(43769),dI=s.n(dN);let dC="max-h-[min(20rem,45dvh)] overflow-auto [scrollbar-gutter:stable]",dS=(0,r.createContext)(()=>void 0),dM=(0,r.createContext)(null),dz=(0,r.createContext)(null),dE="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 dA({children:e}){let{isAtBottom:t,stopScroll:s}=(0,lV.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)(dS.Provider,{value:l,children:e})}function d$(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 dR(e,t){let[s,n]=(0,r.useState)(!1),a=(0,r.useContext)(dS),{loading:i,error:l,load:o}=d$(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 dP({timestampMs:e}){let{locale:t,timeZone:s}=(0,tp.i)(),r=ob(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 dT({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)(ss,{tooltip:u,label:u,size:"icon-sm",className:(0,C.cn)(!s&&dI().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 dD({usage:e,compactOnly:t=!1}){let{t:s}=(0,f.Bd)("conversation"),r=ox(e.inputTokens),a=ox(e.outputTokens),i=ox(e.cacheReadTokens),l=of(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:dI().usageLabeled,children:o}),(0,n.jsx)("span",{className:dI().usageCompact,children:d})]})}function dL({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)(sa,{className:(0,C.cn)(dI().usageToolbar,"mt-1 flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground"),children:[e.usageCalls?.length?(0,n.jsx)(dv,{messages:e.usageCalls,incomplete:e.usageIncomplete??!1,children:(0,n.jsx)(dD,{usage:e.summary.usage})},e.durable.location.entryId):(0,n.jsx)(dD,{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)(dT,{text:t}),null===e.timestampMs?null:(0,n.jsx)(dP,{timestampMs:e.timestampMs})]})]})}function dO({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)(nT.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 dF({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)(dS);(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&&dI().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 dB({message:e,onAcquireImage:t}){if("user"!==e.summary.type)throw Error("UserMessage requires a user summary");return(0,n.jsxs)(se,{from:"user","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:user`,"data-chat-user-message":"",className:(0,C.cn)(dI().copyableMessage,"max-w-[92%] sm:max-w-[84%]"),children:[(0,n.jsxs)(st,{className:(0,C.cn)(dI().userText,"group-[.is-user]:px-3 group-[.is-user]:py-2"),children:[e.summary.images.length>0?(0,n.jsx)(dO,{message:e,onAcquireImage:t},`${e.tempId}:${e.durable?.location.entryId??"temporary"}`):null,e.summary.text?(0,n.jsx)(dF,{text:e.summary.text}):null]}),null===e.timestampMs?null:(0,n.jsxs)(sa,{className:"mt-0 justify-end gap-1 text-xs text-muted-foreground",children:[(0,n.jsx)(dT,{text:e.summary.text}),(0,n.jsx)(dP,{timestampMs:e.timestampMs})]})]})}function d_({message:e,text:t}){let s=e.temporary&&"assistant"===e.summary.type&&"running"===e.summary.status;return(0,n.jsxs)(se,{from:"assistant","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:text`,className:(0,C.cn)(dI().copyableMessage,"max-w-full gap-1"),children:[(0,n.jsx)(st,{className:"w-full",children:(0,n.jsx)(rg,{isAnimating:s,mode:s?"streaming":"static",children:t})}),(0,n.jsx)(dL,{message:e})]})}function dq(){let{t:e}=(0,f.Bd)("conversation");return(0,n.jsxs)("div",{role:"status",className:(0,C.cn)(dI().detailText,"flex min-h-9 w-full items-center gap-2 py-1 text-muted-foreground"),children:[(0,n.jsx)(oG.A,{className:"size-4","aria-hidden":"true"}),(0,n.jsx)(dc,{as:"span",duration:1,children:e("thinking")})]})}function dW({content:e,streaming:t}){let{scrollRef:s,contentRef:r}=(0,o0.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)(rg,{isAnimating:t,mode:t?"streaming":"static",children:e})})})}function dU({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)(dm,{className:"mb-0 w-full",isStreaming:u,onOpenChange:e=>{e&&i()},children:[(0,n.jsx)(dh,{className:(0,C.cn)(dI().detailText,"min-h-9 justify-start py-1"),getThinkingMessage:e=>e?(0,n.jsx)(dc,{as:"span",duration:1,children:s("thinking")}):(0,n.jsx)("span",{children:s("thinkingProcess")})}),(0,n.jsx)(tl.Ke,{className:(0,C.cn)(dE,"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)(dW,{content:m,streaming:u})})})})]})}function dY({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 rd.W[t].streamInterrupted;case"request timed out":case"request timed out.":return rd.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)(dI().toolOutput,"whitespace-pre-wrap break-words rounded-lg border border-destructive/40 bg-muted p-3 font-sans text-destructive"),children:r}):null}function dV({item:e,onLoadDetail:t}){let{message:s,hideAssistantText:r}=e,a=d$(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)(dU,{message:s,detailLoad:a}),r||!s.summary.text.trim()?null:(0,n.jsx)(d_,{message:s,text:s.summary.text}),(0,n.jsx)(dY,{message:s})]})}function dK({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)(da,{path:t,...a}):(0,n.jsx)(nF.A,{...a});case"write":return(0,n.jsx)(oJ.A,{...a});case"edit":return(0,n.jsx)(oX.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 dH(e){let t=e.replaceAll("\\","/");return"/"===t||/^[A-Za-z]:\/$/.test(t)?t:t.replace(/\/+$/,"")}function dG({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 dJ({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)(dM),d=(0,r.useContext)(dz),c=!e.temporary&&"tool"===e.summary.type&&!!e.summary.images?.length,{open:u,expandable:m,loading:p,error:h,handleOpenChange:g}=dR(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=dH(e);if(!t)return{compactPath:s,fullPath:s};let n=dH(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)(dI().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)(dK,{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)(dD,{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)(dI().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)(dI().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)(dG,{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:dE,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)(dO,{message:e,onAcquireImage:d})}):null,i({loading:p,error:h})]})})]})}function dX({children:e,destructive:t=!1}){return(0,n.jsx)("p",{className:(0,C.cn)(dI().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)(dX,{children:r("loadingResult")}):s?(0,n.jsx)(dX,{destructive:!0,children:s}):i?(0,n.jsx)("pre",{role:"region","aria-label":r("toolOutput"),tabIndex:0,className:(0,C.cn)(dC,dI().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)(dX,{children:r("emptyResult")})}function dZ({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)(dX,{children:r("loadingRead")}):s?(0,n.jsx)(dX,{destructive:!0,children:s}):a?a.content?(0,n.jsx)("pre",{role:"region","aria-label":r("readContent"),tabIndex:0,className:(0,C.cn)(dC,dI().toolOutput,dI().toolCode,"px-3 py-3 font-mono"),children:a.content}):(0,n.jsx)(dX,{children:r("readEmpty")}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(dX,{children:r("readUnavailable")})}function d0({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)(dC,dI().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)(dI().toolCode,dI().toolCodeLine,"block px-3",s),children:e||" "},t)})})}function d1({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)(dX,{children:r("loadingDiff")}):s?(0,n.jsx)(dX,{destructive:!0,children:s}):a?"diff"===a.contentKind?(0,n.jsx)(d0,{content:a.content}):(0,n.jsx)("pre",{role:"region","aria-label":r("editResult"),tabIndex:0,className:(0,C.cn)(dC,dI().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)(dX,{children:r("diffUnavailable")})}function d2({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)(dX,{children:r("loadingWrite")}):s?(0,n.jsx)(dX,{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)(dC,dI().toolOutput,"px-3 py-3 font-mono","content"===a.contentKind?dI().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)(dX,{children:r("writeEmpty")}):(0,n.jsx)(dX,{children:r("writeUnavailable")})}function d5({message:e,onLoadDetail:t}){let{t:s}=(0,f.Bd)("conversation"),{open:r,expandable:a,loading:i,error:l,handleOpenChange:o}=dR(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.length>32||!t.every(e=>"string"==typeof e))return s;s.command=["pidesk",...t.map(ot)].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:l7};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:l7};let r=t[1];if("plugins"!==t[0]||!r||!["list","show","install","remove"].includes(r))return s;let a=null,i=[],l=null,o=null,d=!1;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&&oe.test(t[e+1]??""))l=t[++e];else if("--tag"===n&&["list","install"].includes(r)&&null===o&&(t[e+1]?.length??0)<=128&&/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(t[e+1]??""))o=t[++e];else if("--check-updates"!==n||"list"!==r||d)if(!("list"!==r&&("show"!==r||0===i.length)&&"node_modules"!==n&&l9.test(n)))return s;else i.push(n);else d=!0}if(null!==o&&null!==l||"list"!==r&&(0===i.length||null===a))return s;let c=i.length>0?i.join("、"):null;switch(r){case"list":return{...s,label:"pideskListPlugins"};case"show":return{...s,label:"pideskShowPlugin",name:c};case"install":return{...s,label:"pideskInstallPlugin",name:c,version:l};case"remove":return{...s,label:"pideskRemovePlugin",name:c};default:return s}}(e.summary.input),c=e.detail?.type==="tool"&&"pidesk"===e.detail.kind?e.detail.output:null;return(0,n.jsx)(dj,{identity:e.identity,command:d,output:c,expandable:a,open:r,loading:i,error:l,onOpenChange:o,commandAction:(0,n.jsx)(dT,{text:d.command,copyLabel:s("pidesk.copyCommand"),alwaysVisible:!0}),outputAction:c?(0,n.jsx)(dT,{text:c,copyLabel:s("pidesk.copyOutput"),alwaysVisible:!0}):null})}function d3({message:e,onLoadDetail:t}){return(0,n.jsx)(dJ,{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)(dw,{nestedCalls:e.detail.nestedCalls}):null]})})}function d4({message:e,onLoadDetail:t}){return(0,n.jsx)(d3,{message:e,onLoadDetail:t})}function d6({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)(dJ,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(dZ,{message:e,...t})})}function d8({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)(dJ,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(d1,{message:e,...t})})}function d7({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)(dJ,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(d2,{message:e,...t})})}function d9({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)(dI().toolOutput,"rounded-lg border-l-2 bg-muted px-3 py-2 text-muted-foreground"),children:e.summary.text||t("emptyMessage")})}function ce({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}=dR(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)(oZ.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:dE,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)(rg,{isAnimating:!1,mode:"static",children:d.text}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:s("compactionUnavailable")})})})})})]})}let ct=(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)(dV,{item:e,onLoadDetail:t});case"tool":switch(e.message.summary.kind){case"pidesk":return(0,n.jsx)(d5,{message:e.message,onLoadDetail:t});case"read":return(0,n.jsx)(d6,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"edit":return(0,n.jsx)(d8,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"write":return(0,n.jsx)(d7,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"bash":case"codemode":case"generic":return(0,n.jsx)(d3,{message:e.message,onLoadDetail:t})}case"bash":return(0,n.jsx)(d4,{message:e.message,onLoadDetail:t});case"custom":return(0,n.jsx)(d9,{message:e.message});case"compaction":return(0,n.jsx)(ce,{message:e.message,onLoadDetail:t});case"user":return(0,n.jsx)(dB,{message:e.message,onAcquireImage:s})}})();return(0,n.jsx)(oH,{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&&cr(e.item.message,t.item.message));function cs({items:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:a}){let{scrollRef:i}=(0,lV.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)(ct,{item:r,onLoadDetail:t,onAcquireImage:s,onPreviewFile:a})},r.message.identity)})]})}let cn=(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)(dS),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)(dI().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:dE,children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)(cs,{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&&ca(e.turn.processItems,t.turn.processItems));function cr(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 ca(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&&cr(e.message,n.message)})}let ci=(0,r.memo)(function({message:e,onLoadDetail:t,onAcquireImage:s}){return(0,n.jsx)(oH,{message:e,loadDetail:t,defaultView:(0,n.jsx)(dB,{message:e,onAcquireImage:s})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&cr(e.message,t.message)),cl=(0,r.memo)(function({message:e,onLoadDetail:t}){return"assistant"!==e.summary.type?null:(0,n.jsx)(oH,{message:e,loadDetail:t,defaultView:(0,n.jsx)(d_,{message:e,text:e.summary.text})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&cr(e.message,t.message)),co=(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)(oH,{message:e.compaction,loadDetail:r,defaultView:(0,n.jsx)(ce,{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)(ci,{message:e.user,onLoadDetail:r,onAcquireImage:a}):null,(0,n.jsx)(dz.Provider,{value:a,children:(0,n.jsx)(dM.Provider,{value:t,children:(0,n.jsx)(cn,{turn:e,onLoadDetail:r,onAcquireImage:a,onPreviewFile:i})})}),l?(0,n.jsx)(dq,{}):null,e.finalAssistant?(0,n.jsx)(cl,{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&&cr(s.user,n.user)&&cr(s.finalAssistant,n.finalAssistant)&&cr(s.compaction,n.compaction)&&ca(s.processItems,n.processItems))});co.displayName="L3ConversationTurnView";let cd={running:"statusRunning",completed:"statusCompleted",failed:"statusFailed",stopped:"statusStopped",interrupted:"statusInterrupted"};function cc(e,t){return null!==e&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}function cu(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 cm(e){return[e.taskKind,e.taskType].filter(e=>!!e).join(" / ")}function cp(e){switch(e){case"running":return(0,n.jsx)(b.A,{className:"size-4 animate-spin text-foreground"});case"completed":return(0,n.jsx)(lm.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)(lq.A,{className:"size-4 text-status-warning"});case"stopped":return(0,n.jsx)(lW.A,{className:"size-4 text-muted-foreground"})}}function ch({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 cg({snapshot:e,running:t,runtime:s,cwd:a}){let{t:i}=(0,f.Bd)("taskCenter"),l=(0,r.useMemo)(()=>og(e,t),[t,e]),o=l.findLast(e=>null!==e.user)??null;return(0,n.jsx)(lK,{className:"h-full min-h-0",initial:"instant",resize:"instant","aria-label":i("conversationDetails"),children:(0,n.jsx)(oD,{turns:l,focusTurnIdentity:o?.identity??null,initialAnchor:null,children:e=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oz,{}),(0,n.jsx)(dA,{children:(0,n.jsxs)(lH,{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)(co,{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 cx({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=cm(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:cp(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(cd[e.status])}),(0,n.jsx)("span",{className:"text-muted-foreground",children:cu(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)(lW.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)(ch,{info:e.info})}):null,(0,n.jsxs)("div",{className:"relative min-h-0 flex-1",children:[l?.body?.kind==="conversation"?(0,n.jsx)(cg,{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)(lU.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 cf({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&&cc(c.source,e)&&s.reconcileTasks(e,t)},[s,e,c.open,c.source,t]);let x=p&&null!==c.selectedTaskId,b=c.open&&cc(c.source,e),v=(0,r.useRef)(null),w=(0,r.useRef)(null);return(s7(v,b&&!x?"task-list":null),s7(w,b?`${c.selectedTaskId??"no-task"}:${x}`:null),c.open&&cc(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)(lY.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=cm(e),r=cu(e,(e,t)=>i(e,{count:t})),a=ob(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:cp(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)(cx,{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 cb({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)(l4,{tooltip:i("title"),"aria-label":i("open"),onClick:d,children:(0,n.jsx)(lY.A,{className:"size-4"})}):(0,n.jsx)(n.Fragment,{}):"menu"===a?(0,n.jsxs)(ex,{onClick:d,children:[(0,n.jsx)(lY.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)(cf,{source:e,tasks:s,runtime:r,cwd:t})]})}function cv({source:e,cwd:t,pluginState:s,runtime:a,variant:i}){let l=(0,r.useMemo)(()=>{let e=lM.safeParse(s);return e.success?e.data.tasks:[]},[s]);return(0,n.jsx)(cb,{source:e,cwd:t,tasks:l,runtime:a,variant:i})}var cw=s(74577),cy=s(85232);function ck(e){return`${e.location.index}:${e.location.entryId}`}let cj={user:["viewKey","hasDetail"],assistant:["viewKey","status","hasDetail","usage"],tool:["viewKey","status","hasDetail","usage"],bash:["viewKey","status","hasDetail"],custom:["viewKey","hasDetail"]};function cN(e,t,s){if(!t)return e;let n={...e,...t};return"summary"===s?lb.Hf.parse(n):lb.D8.parse(n)}function cI(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 cC(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 cI(r,`${r.value}${s}`),lb.Hf.parse(n)}if(!Array.isArray(r.value))throw Error("Increment target is not an array");return cI(r,[...r.value,...s]),lb.Hf.parse(n)}function cS(e,t,s){let n=new Map(e.messages.filter(e=>void 0!==e.detail).map(e=>[ck(e),e]));return{messages:t.map(e=>{let t=n.get(ck(e));return e.fixed.hasDetail&&t&&t.fixed.type===e.fixed.type&&t.fixed.viewKey===e.fixed.viewKey&&void 0!==t.detail?lb.mj.parse({...e,detail:t.detail}):e}),temporaryMessages:[...s]}}function cM(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,cj[s.type],`${s.type} fixed`),lb.q5.parse({...s,...n})):s),a=cN(e.summary,t.summary,"summary"),i=e.detail;if(void 0!==t.detail||Object.keys(t.increments??{}).some(e=>"detail"===(0,cy.U)(e).root)){if(t.fixed?.hasDetail===!1)throw Error("Realtime detail cannot be updated while explicitly clearing hasDetail");r.hasDetail||(r=lb.q5.parse({...r,hasDetail:!0}))}for(let[e,s]of(t.detail&&(i=cN(i??{},t.detail,"detail")),Object.entries(t.increments??{}))){let t=(0,cy.U)(e);"summary"===t.root?a=cC(a,t.segments,s):i=cC(i??{},t.segments,s)}return r.hasDetail||(i=void 0),lb.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=lb.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 cz(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]=lb.mj.parse({...n,...null===t.detail?{detail:void 0}:{detail:t.detail}}),{...e,messages:r}}function cE(e,t){return e.taskId!==t.taskId||e.body?.kind!=="conversation"||t.body?.kind!=="conversation"?t:l$.parse({...t,body:{kind:"conversation",truncated:t.body.truncated,...cS(e.body,t.body.messages,t.body.temporaryMessages)}})}var cA=s(7237);function c$(e){return(0,eO.B)({msg:cw.U["zh-CN"][e],i18n:{key:`taskCenter:${e}`}})}let cR=Object.freeze({open:!1,source:null,selectedTaskId:null,details:{},loading:!1,refreshing:!1,error:null});function cP(e,t){return e===t||null!==e&&null!==t&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}var cT=s(15381),cD=s(94853);let cL=nr.rh,cO=nr._g,cF=nr.eC,cB=a.Ik({workId:cT.eW,cwd:cT.ik}).strict(),c_=cB.extend({path:cL}).strict(),cq=cB.extend({query:a.Yj().trim().min(1).max(200)}).strict(),cW=cD.Ot.request.safeExtend({workId:cT.eW});cD.Ot.response;let cU=nr.p$,cY=cB.extend({path:cF,imagePreviewMode:cU}).strict();var cV=s(46117),cK=s.n(cV);function cH({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)(cK().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)(cK().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)(cK().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 cG=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 cJ=s(5011),cX=s(42515),cQ=s(91399),cZ=s(95826),c0=s(56592),c1=s(31343);function c2(e,t){return(0,eO.B)({msg:c1.R["zh-CN"][e],i18n:{key:`workbench:${e}`,...t?{params:t}:{}}})}function c5(e){let{workId:t,sessionId:s,branchId:n}=e.source;return JSON.stringify([t,s,n,e.cwd])}function c3(e,t,s){return`${c5(e)}\u0000${s}\u0000${t}`}class c4{peek(e,t,s){let n=this.images.get(c3(e,t,s));return!n||0===n.references&&Date.now()-n.unusedAt>=6e4?null:n.url}get(e,t,s){this.trim();let n=c3(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(c5(e)))throw Error("工作会话来源已变化");let r=c3(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(c3(e,t,s))}reconcileWorkSessions(e){for(let t of(this.validSources=new Set(e.map(e=>c5({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 c6{constructor(e,t,s=()=>void 0){this.biz=e,this.gitBiz=t,this.onNotice=s,this.standaloneImages=new c4,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(c2("sourceChanged"));let s=this.workspaces.get(e);if(s)return s;let n={workId:e,cwd:t.cwd},r=new c0.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:rN.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 c8=s(70657),c7=s(60354),c9=s(36510);let ue='data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/%3E';function ut({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,rN.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,cA.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)(nT.k,{mode:"inline",thumbnails:!1,slides:t.map(e=>{let t=d[e];return{src:t?.status==="ready"?t.objectUrl:e===m?g??ue:ue,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,rN.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 us(e){return e.replaceAll("\\","/").split("/").at(-1)??e}function un(e,t){return e instanceof Error?e.message:t}function ur({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,rN.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,rN.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,cA.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:un(t,l("standaloneReadFailed"))}),m({status:"error",message:un(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:us(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:us(g),children:us(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)(ut,{target:e,paths:e.imagePaths,index:p,onIndexChange:h,biz:t,images:s}):"loading"===u.status?(0,n.jsx)(ua,{}):"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,rN.Wq)()),m({status:"loading"}),c(e=>e+1)},children:l("reloadFile")})]}):"image"===u.status?(0,n.jsx)(nT.k,{mode:"inline",slides:[{src:u.objectUrl,alt:e.path}],ariaLabel:l("standaloneImage",{name:us(e.path)})}):x?(0,n.jsx)("iframe",{ref:o,className:"block size-full border-0 bg-white",sandbox:"allow-scripts",srcDoc:(0,c9.z)(u.content),title:l("standaloneHtml",{name:e.path})}):(0,n.jsx)(c7.e,{path:e.path,content:u.content,size:u.size,savedState:null,onSaveState:()=>void 0,onEscape:i})})]})]})})}function ua(){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 ui=s(3635),ul=s(76812),uo=s.n(ul);let ud=(0,ui.default)(()=>Promise.all([s.e(52354),s.e(19991)]).then(s.bind(s,19991)).then(e=>e.L2FileWorkspaceView),{loadableGenerated:{webpack:()=>[19991]},ssr:!1});function uc({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?[cK().panelGroup,uo().wide]:uo().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)(ud,{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 uu({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)(ud,{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 um=s(93320);async function up(e,t,s){try{let n=await e.get({...t,imagePreviewMode:"compressed"},s);if("image"!==n.kind)throw Error("该文件不是可展示的图片");return(0,cA.E)(n)}catch(e){if(e instanceof um.aw&&"errors:fileMissing"===e.errorKey)return null;throw e}}var uh=s(72114),ug=s(31761),ux=s(50479),uf=s(35989);let ub=[];function uv(e,t){let s=t.trim().toLocaleLowerCase();return s?e.filter(e=>e.toLocaleLowerCase().includes(s)):[...e]}function uw({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??ub,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)(()=>uv(O?.local??[],p),[O?.local,p]),_=(0,r.useMemo)(()=>uv(O?.remote??[],p),[O?.remote,p]),q=(0,r.useMemo)(()=>uv(O?.recent??[],p),[O?.recent,p]),W=(0,r.useMemo)(()=>(0,uf.oY)(B),[B]),U=(0,r.useMemo)(()=>(0,uf.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,uf.Hj)(e.projectName,R[0].root),branch:"ready"===R[0].state?(0,uf.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)(uh.A,{className:"size-3.5"}):(0,n.jsx)(ug.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)(ux.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,uf.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,uf.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,uf.Hj)(e.projectName,D.root):i("chooseRepository"),D?.state==="ready"?` \xb7 ${(0,uf.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 uy(e,t){return e instanceof DOMException&&"AbortError"===e.name?t:e instanceof Error?e.message:t}class uk{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:c2("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:uy(e,c2("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:c2("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:uy(e,c2("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:c2("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:uy(e,c2("gitStatusReadFailed"))},this.publish()}}requireProject(e){let t=this.projectRefs.get(e);if(!t)throw Error(c2("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 uj=s(24985);let uN=uj.y2,uI=a.Ik({workId:cT.eW,cwd:cT.ik}).strict(),uC=uj.Ww,uS=uj.cP,uM=uj.zp,uz=uj.u2;a.Ik({repositories:a.YO(uz).max(uN)}).strict();let uE=uI.extend({repositoryRoot:uC}).strict(),uA=uj.zt,u$=uI.extend({repositoryRoot:uC,target:uA}).strict(),uR=uI.extend({repositoryRoot:uC,name:uS,startPoint:uA.nullable()}).strict(),uP=a.Ik({repository:uM}).strict(),uT=uI.extend({repositoryRoot:uC,path:nr._g}).strict();var uD=s(68269);let uL=Object.freeze({messages:[],temporaryMessages:[],runtime:{extensionMode:"normal",presentationMode:"normal",initializationError:null,queues:{steering:[],followUp:[]},model:null,capabilityMode:null,contextUsage:null,plugins:{}}});function uO(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 uF=s(82639);let uB="messages",u_="source",uq="drafts",uW="outbox",uU="pi-super-chat",uY=null,uV=null;function uK(e){return Error((0,eO.B)({msg:uF.n["zh-CN"].common[e],i18n:{key:`common:${e}`}}))}function uH(e,t){e.objectStoreNames.contains(t)||e.createObjectStore(t,{keyPath:["sessionId","branchId"]})}function uG(){return new Promise((e,t)=>{let s=indexedDB.open(uU,2),n=!1,r=window.setTimeout(()=>{a(uK("dbOpenTimeout"))},1e4),a=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("upgradeneeded",()=>{let e=s.result;e.objectStoreNames.contains(uB)||e.createObjectStore(uB,{keyPath:["sessionId","branchId","index"]}).createIndex(u_,["sessionId","branchId"],{unique:!1}),uH(e,uq),uH(e,uW)},{once:!0}),s.addEventListener("blocked",()=>{a(uK("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??uK("dbOpenFailed")),{once:!0})})}async function uJ(){try{return await uG()}catch(e){if(!("object"==typeof e&&null!==e&&"name"in e&&"VersionError"===e.name))throw e;return console.warn("[Pi Desk][ChatIndexedDB] 本地数据库版本高于当前版本,清空全部本地聊天数据后重建",{databaseName:uU,requestedVersion:2}),await new Promise((e,t)=>{let s=indexedDB.deleteDatabase(uU),n=!1,r=window.setTimeout(()=>{a(uK("dbDeleteTimeout"))},1e4),a=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("blocked",()=>{a(uK("dbDeleteBlocked"))},{once:!0}),s.addEventListener("success",()=>{n||(n=!0,window.clearTimeout(r),e())},{once:!0}),s.addEventListener("error",()=>a(s.error??uK("dbDeleteFailed")),{once:!0})}),uG()}}function uX(){return uV?Promise.resolve(uV):uY||(uY=uJ().then(e=>(uV=e,e.addEventListener("versionchange",()=>{e.close(),uV===e&&(uV=null,uY=null),console.warn("[Pi Desk][ChatIndexedDB] 数据库版本已变化,当前连接已关闭")}),e)).catch(e=>{throw uY=null,e}))}function uQ(e){return new Promise((t,s)=>{e.addEventListener("success",()=>t(e.result),{once:!0}),e.addEventListener("error",()=>s(e.error??uK("dbRequestFailed")),{once:!0})})}function uZ(e,t,s){let n=e.target;return n?.error??t.error??Error(s)}function u0(e){return new Promise((t,s)=>{e.addEventListener("complete",()=>t(),{once:!0}),e.addEventListener("abort",t=>s(uZ(t,e,uK("dbTransactionAborted").message)),{once:!0}),e.addEventListener("error",t=>s(uZ(t,e,uK("dbTransactionFailed").message)),{once:!0})})}let u1=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:uD.ao,summary:uD.lV,detail:uD.wI.optional()}).strict();function u2(e,t){return u1.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 u5(e){let t=u1.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");uD.Y2.parse(t.summary),void 0!==t.detail&&uD.$f.parse(t.detail)}return uD.wR.parse({location:{index:t.index,entryId:t.entryId},fixed:t.fixed,summary:t.summary,...void 0===t.detail?{}:{detail:t.detail}})}function u3(e,t){e.delete(IDBKeyRange.bound([t.sessionId,t.branchId,0],[t.sessionId,t.branchId,Number.MAX_SAFE_INTEGER]))}let u4=a.Yj().max(65536),u6=a.Ik({id:a.Yj().uuid(),title:u4,expiresAt:a.ai().int().nonnegative().nullable()}),u8=a.gM("method",[u6.extend({method:a.eu("confirm"),message:u4}).strict(),u6.extend({method:a.eu("select"),options:a.YO(u4).max(200)}).strict(),u6.extend({method:a.eu("input"),placeholder:u4}).strict(),u6.extend({method:a.eu("editor"),prefill:u4}).strict()]),u7=a.Ik({requests:a.YO(u8).max(32),statuses:a.g1(a.Yj().max(128),u4),widgets:a.g1(a.Yj().max(128),a.Ik({lines:a.YO(u4).max(200),placement:a.k5(["aboveEditor","belowEditor"])}).strict())}).strict(),u9=a.Ik({id:a.Yj().uuid(),value:a.KC([a.zM(),u4,a.ch()])}).strict(),me=a.gM("type",[a.Ik({type:a.eu("snapshot"),snapshot:u7}).strict(),a.Ik({type:a.eu("notify"),message:u4,level:a.k5(["info","warning","error"])}).strict(),a.Ik({type:a.eu("editor_text"),text:u4,mode:a.k5(["replace","paste"])}).strict()]),mt=a.Ik({source:lf.R}).strict(),ms=a.Ik({}).strict(),mn=Object.freeze({subscribe:(0,i.Vc)({path:"pi/ui/subscribe",inputSchema:mt,outputSchema:u7}),unsubscribe:(0,i.Vc)({path:"pi/ui/unsubscribe",inputSchema:mt,outputSchema:ms}),respond:(0,i.Vc)({path:"pi/ui/respond",inputSchema:mt.extend({response:u9}).strict(),outputSchema:ms}),event:(0,i._G)({path:"pi/ui/event",bodySchema:mt.extend({event:me}).strict()})});function mr(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}class ma{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(mn.event,({source:e,event:t})=>{let s=this.records.get(mr(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(mr));for(let[e,s]of this.records)!t.has(e)&&(this.records.delete(e),this.connected&&this.socket.request(mn.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(mn.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:c2("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(cZ.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:c2("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=mr(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(mr(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(mn.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:c2("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 mi=Object.freeze({...uL,syncStatus:"loading"});function ml(e){return uD.Pi.parse({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId})}function mo(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function md(e,t){return e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}let mc={text:"",images:[]};function mu(e){return[e.sessionId,e.branchId]}function mm(e,t){return{sessionId:e.sessionId,branchId:e.branchId,text:t.text,images:t.images}}function mp(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 mh(e,t){return t?{text:[e.text,t.text].filter(e=>e.trim()).join("\n\n"),images:[...e.images,...t.images]}:e}var mg=s(67837);let mx=new Set(["image/jpeg","image/png","image/webp","image/gif","image/bmp"]),mf=new Set(["image/jpeg","image/png","image/webp","image/gif"]),mb=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function mv(e){return e.type.toLowerCase().split(";")[0]??""}async function mw(e){let t;try{t=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{throw Error(c2("imageDecodeFailed"))}if(!Number.isSafeInteger(t.width)||t.width<=0||t.height<=0)throw t.close(),Error(c2("imageInvalidDimensions"));return{bitmap:t,width:t.width,height:t.height}}function my(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 mk(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(c2("canvasUnavailable"));return i.drawImage(e,0,0,t,s),new Promise((e,t)=>{a.toBlob(s=>s?e(s):t(Error(c2("imageCompressFailed"))),n,r)})}async function mj(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(mb.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 mN(e){let t=mv(e);if(!mx.has(t))throw Error(c2("imageTypeUnsupported"));let s=await mw(e);return s.bitmap.close(),{blob:e,mimeType:t,width:s.width,height:s.height,optimized:"image/gif"===t}}async function mI(e){if(e.optimized){if(e.blob.size>0xa00000)throw Error(c2("singleImageLimit"));return e}let t=await mw(e.blob);try{var s;let n=my(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 mk(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 mj(e.blob):null,u="image/jpeg"===e.mimeType&&(null===c||c.width!==t.width||c.height!==t.height),m=mf.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=my(t.width,t.height,2048);i=await mk(t.bitmap,e.width,e.height,r,.82),l=e.width,o=e.height}if(i.size>0xa00000)throw Error(c2("compressedImageTooLarge"));let p=mv(i);if(!mf.has(p))throw Error(c2("compressedTypeUnsupported"));return{blob:i,mimeType:p,width:l,height:o,optimized:!0}}finally{t.bitmap.close()}}async function mC(e){if(!e.optimized)throw Error(c2("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 mS(e,t,s=e.optimized?"ready":"optimizing"){return{...e,localId:(0,mg.y)(),objectUrl:URL.createObjectURL(e.blob),name:t,status:s,error:null}}function mM(e){URL.revokeObjectURL(e.objectUrl)}function mz(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function mE(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 mA(e,t){return e instanceof Error&&e.message?e.message:t}function m$(e,t){return[e,t].filter(e=>e.trim()).join("\n\n")}function mR(e,t,s){return`${mz(e)}\u0000temp\u0000${t}\u0000${s}`}function mP(e,t,s){return`${mz(e)}\u0000entry\u0000${t}\u0000${s}`}function mT(e){for(let t of e)mM(t)}var mD=s(63273),mL=s(15104),mO=s(11039),mF=s(97906),mB=s(94411);function m_(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function mq(e){return e.trim().toLocaleLowerCase()}let mW=["title","user"],mU=[{value:"title",label:"scopeTitle"},{value:"user",label:"scopeUser"},{value:"assistant",label:"scopeAssistant"},{value:"sessionId",label:"Session ID"}];function mY(e,t,s){return"title"===e?s("scopeTitle"):"sessionId"===e?"Session ID":s("user"===e?"scopeUserMatches":"scopeAssistantMatches",{count:t})}function mV(e){switch(e){case"user":case"assistant":case"title":return"bg-muted text-foreground";case"sessionId":return"bg-muted text-muted-foreground"}}function mK(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 mH({scope:e,className:t}){switch(e){case"user":return(0,n.jsx)(mD.A,{className:t});case"assistant":return(0,n.jsx)(e7.A,{className:t});case"title":return(0,n.jsx)(mL.A,{className:t});case"sessionId":return(0,n.jsx)(mO.A,{className:t})}}function mG(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 mJ({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)(mW),[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=mq(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||mq(`${m_(e.cwd)} ${e.cwd}`).includes(G)),ee=(o?.directories??[]).filter(e=>!G||mq(`${e.name} ${e.cwd}`).includes(G));(0,r.useEffect)(()=>{L(""),F(mW),_(""),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)(ux.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")}),mU.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)(mF.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)?mG(s,G,mK("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)(mH,{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 ${mV(t.scope)}`,children:mY(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:mG(t.preview,G,mK(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 ${mV(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:mY(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)(mB.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?mG(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)(ux.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=m_(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)(lU.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=m_(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)(ig.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)(ux.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 mX="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 mZ({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 m0=s(39569),m1=s(31175),m2=s(74873),m5=s(77065);let m3=new Set(["custom","model_change","thinking_level_change","session_info","label"]),m4=[],m6=[{value:"default",label:"filterDefault"},{value:"no-tools",label:"filterNoTools"},{value:"user-only",label:"filterUserOnly"},{value:"labeled-only",label:"filterLabeled"},{value:"all",label:"filterAll"}],m8={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 m7(e){switch(e.action){case"tree":return"treeIntent";case"fork":return"forkIntent";case"clone":return"cloneIntent"}}function m9(e){e.preventDefault()}function pe({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(m7(e.intent))}):i("runningWait",{action:i(m7(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 pt({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,m5.tF)(),h=(0,s1.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??m4,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!m3.has(e.kind);case"no-tools":return!m3.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(m6.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=(m6.findIndex(e=>e.value===k)+e+m6.length)%m6.length;el(m6[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?m8[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)(dl.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)(dl.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:m6.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)(pe,{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=m8[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:m9,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:m9,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:m9,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:m9,onClick:eh,children:m("switch")})]})]})]})]})}var ps=s(15450),pn=s(31210),pr=s(66722),pa=s(40942),pi=s(61989),pl=s(63434),po=s(26690),pd=s(89517),pc=s.n(pd);function pu({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:pc().statusBorder,children:(0,n.jsx)("rect",{ref:s,x:"1",y:"1",pathLength:"100"})})}function pm(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 pp(e){return{className:pc().surface,style:pm(e)}}var ph=s(2870),pg=s.n(ph);function px({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,uf.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)(l4,{"data-testid":"composer-git-branch",tooltip:p?d.error??l("gitStatusReadFailed"):h?.title??l("gitBranches"),"aria-label":l("gitBranches"),className:pg().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)(ug.A,{className:"size-4 shrink-0 text-emerald-600 dark:text-emerald-400"}),p?(0,n.jsx)("span",{className:(0,C.cn)(pg().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)(pg().branchFull,h.diverged&&"text-amber-600 dark:text-amber-400"),children:h.full})}):null]})}let pf="l2-workbench-slash-command-menu",pb={key:"builtin:reload",name:"reload",description:"重新读取 Pi 最新配置与扩展资源",source:"builtin"},pv=[{source:"builtin",label:"Pi 内置命令"},{source:"skill",label:"Skills"},{source:"prompt",label:"提示模板"},{source:"extension",label:"扩展命令"}];function pw(e){return`${pf}-option-${e}`}function py(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function pk(e){return[...e.children].filter(e=>e instanceof HTMLElement)}function pj(e,t,s){return e.reduce((e,t)=>e+(s.get(t)??0),0)+Math.max(0,e.length-1)*t}var pN=s(64696);let pI=2*Math.PI*7;function pC(e){if(null===e)return"--";let t=Math.round(e);return t<1e3?String(t):`${Math.round(t/100)/10}K`}function pS(e){return Math.min(100,Math.max(0,e))}function pM(e){return pI-e/100*pI}function pz({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:pS(h/a*100),v=null===(x=null===h||null===p?null:Math.max(0,h-p.potentialTokens))?null:pS(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:pC($.contextIgnore.ignoredTokens),potential:pC($.contextIgnore.potentialTokens)}):w("contextUsageSimple",{percent:R,limit:pC(a)});return(0,n.jsxs)(l0,{open:j,triggerId:y,onOpenChange:(e,t)=>{k.current&&"trigger-focus"===t.reason||(e||(M(!1),E(!1)),I(e))},children:[(0,n.jsx)(l1,{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:pI,strokeDashoffset:pM($.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:pI,strokeDashoffset:pM($.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:pI,strokeDashoffset:pM($.usedPercent),className:T}):null]})})}),(0,n.jsx)(l2,{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:[pC($.currentTokens)," / ",pC(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:[pC($.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:pC($.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:pC($.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:pC($.contextIgnore.potentialTokens)}):w("nothingToIgnore"),"aria-busy":o,onClick:()=>void u(),children:[o?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(pN.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)(oZ.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 pE(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 pA={direct:["toolExposureDirect","直接使用"],"model-only":["toolExposureModelOnly","仅模型调用"],codemode:["toolExposureCodemode","通过脚本调用"],deferred:["toolExposureDeferred","按需发现"],hidden:["toolExposureHidden","不可调用"]};function p$({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(pA[i]?.[0]??"toolUnknown")})}),(0,n.jsxs)(eP.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(eP.eb,{value:"all",children:t("allTools")}),Object.entries(pA).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?pA[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 pR({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 pP({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)(ra,{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)(pR,{notices:t.notices})]})]})}function pT({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:pE(i&&"system"===l,o),tools:pE(i&&"tools"===l,d),commands:pE(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)(nF.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)(ra,{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)(p$,{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)(pP,{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 pD={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pL({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)(l4,{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(pD[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)(rj.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(pD[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)(iO.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(pD[e.thinkingLevel])})]},`${e.provider}:${e.modelId}:${e.thinkingLevel}:${t}`))]})]}):null]})]})}var pO=s(15824);function pF({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)(rj.A,{className:"size-3"}),i("queueImages",{count:e.images.length})]}):null]})]},e.tempId)})})]})}function pB({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)(l0,{open:o,triggerId:i,onOpenChange:(e,t)=>{l.current&&"trigger-focus"===t.reason||d(e)},children:[(0,n.jsx)(l1,{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)(l2,{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)(pO.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)(pF,{label:a("queueSteer"),description:a("queueSteerDescription"),markerClass:"bg-foreground",countClass:"bg-muted text-muted-foreground",inputs:e.steering}),(0,n.jsx)(pF,{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)(lU.A,{}),a("queueRestore")]})})]})]})}let p_={builtin:"slashGroupBuiltin",skill:"slashGroupSkill",prompt:"slashGroupPrompt",extension:"slashGroupExtension"};function pq({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:pf,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(p_[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(p_[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:pw(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 pW=s(58270),pU=s.n(pW);function pY({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 pV=s(18903),pK=s(8356),pH=s(93192);function pG({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)(sd.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)(pi.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)(pV.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)(ra,{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)(pK.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 pJ({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)(pV.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)(pG,{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)(pR,{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 pX({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)(pH.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 pZ(e){return e<1048576?`${Math.max(1,Math.round(e/1024))}KB`:`${(e/1048576).toFixed(1)}MB`}let p0=(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=s8(),B=(0,r.useMemo)(()=>uD.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-py(e.paddingLeft)-py(e.paddingRight);let t=py(e.columnGap),s=pk(a),i=pk(l),u=pk(o),m=py(window.getComputedStyle(a).columnGap),p=py(window.getComputedStyle(l).columnGap),h=py(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=[pj(s,m,x),pj(i,p,x),g?x.get(g)??0:0,pj(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()===`/${pb.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=pp(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)(()=>[pb,...(p.sourceKey===i?p.commands:[]).filter(e=>e.name!==pb.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(),pv.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)(lU.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)(lU.A,{}),D("retryDraft")]})]})}):null,i({source:B,cwd:t.cwd,pluginState:e2}),(0,n.jsx)(pJ,{model:G}),(0,n.jsx)(pX,{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)(pU().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)(pq,{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 ${pZ(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 ",pZ(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?pf:void 0,"aria-expanded":ti.open,"aria-activedescendant":ti.open&&ti.commands.length>0?pw(ti.activeIndex):void 0,placeholder:W.loading?D("draftLoading"):!W.loaded&&W.error?D("draftFailed"):D("inputPlaceholder"),className:(0,C.cn)(pU().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)(l5,{ref:ee,className:pU().footer,children:[(0,n.jsxs)(l3,{"data-composer-tools":"primary",className:pU().primaryTools,children:[(0,n.jsxs)(ec,{children:[(0,n.jsx)(em,{render:(0,n.jsx)(l4,{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)(ug.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)(ps.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)(pn.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)(nF.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)(nF.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)(l4,{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)(pr.A,{className:"size-4"})}),e5&&eQ?.contextWindow!==null?(0,n.jsx)(pz,{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)(l3,{"data-composer-tools":"metadata",className:pU().metadataTools,children:[(0,n.jsx)(px,{workSession:t,runtime:d,active:c,chatReady:H,onOpen:M}),(0,n.jsx)(pY,{modes:g,value:Y.capabilityMode,disabled:!H,onChange:tt}),(0,n.jsx)(pL,{source:B,runtime:a,catalog:W.models,current:eX,label:e4,title:e6,disabled:!H||eO||eB||ed,triggerClassName:pU().modelTrigger,detailsClassName:pU().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:pU().submitTools,children:[(0,n.jsx)(pB,{queues:eK,disabled:!H||ed,onRestore:()=>void te(()=>a.restoreQueue(B),D("queuesRestored"))}),eV?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(l4,{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)(l4,{tooltip:D("sendFollowUp"),"aria-label":D("sendFollowUp"),variant:"outline",disabled:!e1||e0,onClick:()=>void tc("follow_up"),children:(0,n.jsx)(pa.A,{className:"size-3.5"})}),(0,n.jsx)(l4,{tooltip:D("stopResponse"),"aria-label":D("stopResponse"),variant:"destructive",disabled:!H||ed,onClick:()=>void te(()=>a.interrupt(B)),children:(0,n.jsx)(pi.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)(pl.A,{className:(0,C.cn)("size-4",!F&&"pi-desk-chat-send-icon")}):H?(0,n.jsx)(po.A,{}):(0,n.jsx)(b.A,{className:"size-4 animate-spin"})})]})]})]}),(0,n.jsx)(pu,{state:e7,powerSaving:F})]})]}),(0,n.jsx)(pX,{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)(pT,{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)(nT.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]})});p0.displayName="L2WorkbenchChatComposer";var p1=s(61600);function p2({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 p5={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},p3=Object.keys(p5),p4={idle:.46,hello:.36,point:.45,think:.5,busy:.4,happy:.35,surprise:.2,sleep:.72};function p6(e){return Math.min(1,Math.max(0,e))}function p8(e){let t=p6(e);return t*t*t*(t*(6*t-15)+10)}function p7(e,t){let s={...p5};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=p8(e/1.45),r=p8((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 p9{setState(e,t){if(e===this.state)return;let s=this.transition&&t-this.transition.at<p4[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=p7(this.state,t?1.2:Math.max(0,e-this.started));if(!this.transition||t)return s;let n=p6((e-this.transition.at)/p4[this.state]);if(1===n)return s;let r="pose"in this.transition?this.transition.pose:p7(this.transition.state,Math.max(0,e-this.transition.started)),a=1-(1-n)**5;for(let e of p3)s[e]=r[e]+(s[e]-r[e])*a;return s}constructor(){this.state="idle",this.started=0,this.transition=null}}let he=["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 ht(e,t=0,s=1){return Math.min(s,Math.max(t,e))}function hs(e){return e.toFixed(3)}function hn({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(he.map(t=>[t,e.querySelector(`[data-part="${t}"]`)])),s=e.parentElement,n=new p9,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",hs(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(${hs(e.x)} ${hs(e.y)}) translate(320 274) rotate(${hs(e.angle+(r.matches?0:m.x*e.follow*.12))}) scale(${hs(e.sx)} ${hs(e.sy+a)}) translate(-320 -274)`),g("face",`translate(${hs(.16*i)} ${hs(.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(${hs(n+i)} ${hs(239+l)})`);let r=1-ht(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=hs(e),r=hs(t+s),a=hs(-t+s),i=hs(.5523*e),l=hs(-(.5523*t)+s),o=hs(.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*ht((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",hs(.25+.75*(1+Math.sin(2.8*s-.9*t))/2)),e.setAttribute("transform",`translate(0 ${hs(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(${hs(8*n)} ${hs(-(20*n))})`),e.setAttribute("opacity",hs(Math.sin(n*Math.PI)))}),h("sparkles",e.sparkle*(.55+.45*(1+Math.sin(3*s))/2)),g("sparkles",`translate(0 ${hs(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*ht(((s-.18*t)%1.4+1.4)%1.4/.55));e.setAttribute("opacity",hs(.26+.65*n)),e.setAttribute("transform",`translate(0 ${hs(-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=ht((e.clientX-t.left-t.width/2)/Math.max(t.width,window.innerWidth/2)*24,-18,18),p.y=ht((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)(p2,{svgRef:i})})}let hr=Object.keys(c1.R.en).filter(e=>e.startsWith("emptyQuip")),ha=null;function hi(){let{t:e}=(0,f.Bd)("workbench"),t=(0,m5.tF)(),s=!0===(0,p1.D)(),a=(0,s1.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===ha?hr.length:hr.length-1)),null!==ha&&e>=ha&&(e+=1),ha=e,"emptyQuip16"===(t=hr[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)(dl.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)(hn,{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 hl({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)(m2.N,{initial:!1,custom:e&&t&&r,children:e&&t&&s?(0,n.jsx)(hi,{},"welcome"):null}),e&&!t&&s?(0,n.jsx)(mZ,{variant:"loading"}):null]})}function ho({active:e,turns:t,window:s}){return e?(0,n.jsx)(o_,{turns:t,window:s}):null}function hd(e,t=!1){let s=e.scrollHeight-e.scrollTop-e.clientHeight;if(!t&&2>=oI(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 hc({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,lV.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=hd(t,!0),b.current=t.scrollTop),m();return}if(null===b.current)return;m();let s=f.current,r=s?ow(t,"data-chat-scroll-anchor",s.messageId):null;s&&r?oM(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&&oC(l));let u=null,f=null;p.current=!0;let b=()=>{let e=d.current;if(!e){p.current=!1;return}ov("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=ow(e,"data-chat-scroll-anchor",l.messageId);t&&(s=t,i=l.offset)}!s&&a&&(s=ow(e,"data-chat-scroll-anchor",a));let o=null!==(s??=ow(e,"data-chat-user-message",void 0))&&null===l&&(t||!r),u=r&&t&&null===l;s?(m(),oM(e,s,i,n),u&&(e.scrollTop=Math.max(0,e.scrollHeight-e.clientHeight),c({animation:"instant"}))):(oC(e),e.scrollTop=Math.max(0,e.scrollHeight-e.clientHeight),c({animation:"instant"})),ov("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(ov("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&&(ov("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=hd(s);e?l(e):o()};return s.addEventListener("scroll",n,{passive:!0}),()=>{s.removeEventListener("scroll",n),n()}},[o,l,t,d,e]),null}let hu=(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)(()=>uD.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)(()=>og({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)(oW,{basic:"basic"===u.runtime.presentationMode,onRecover:C,children:(0,n.jsxs)(lK,{className:"min-h-0",initial:!1,resize:"instant","aria-label":l("chatMessages",{name:t.sessionTitle??t.projectName}),children:[(0,n.jsx)(oD,{turns:p,active:e,focusTurnIdentity:b?.identity??null,initialAnchor:d?.messageId??null,children:s=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(hc,{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)(oz,{active:e}),(0,n.jsx)(dA,{children:(0,n.jsx)(lH,{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)(co,{turn:e,cwd:t.cwd,logicalTail:s.containsTail&&a===p.length-1,onLoadDetail:y,onAcquireImage:k,onPreviewFile:j},e.identity)})})}),(0,n.jsx)(ho,{active:e,turns:p,window:s},`navigation:${o.sessionId}:${o.branchId}`)]})},`window:${o.sessionId}:${o.branchId}`),(0,n.jsx)(hl,{active:e,ready:"ready"===u.syncStatus,empty:!h,hasUserMessage:g})]})})});function hm({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")]})]})]})]})}hu.displayName="L2WorkbenchChatView";var hp=s(4780),hh=s.n(hp);function hg({sidebarOpen:e,onOpen:t}){let{t:s}=(0,f.Bd)("workbench"),r=(0,s1.I)();return(0,n.jsxs)("div",{"data-testid":"workbench-session-guide",className:hh().guide,children:[(0,n.jsx)(hn,{state:e?"idle":"point",size:120,className:hh().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:hh().arrow,fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)(dl.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 hx=s(45087);let hf=r.createContext(null);function hb(){let e=r.useContext(hf);if(!e)throw Error("useCarousel must be used within a <Carousel />");return e}function hv({orientation:e="horizontal",opts:t,setApi:s,plugins:a,className:i,children:l,...o}){let[d,c]=(0,hx.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)(hf.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 hw({className:e,...t}){let{carouselRef:s,orientation:r}=hb();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 hy({className:e,...t}){let{orientation:s}=hb();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 hk(e){let t=e.scrollWidth-e.clientWidth;return t<=1||!["auto","scroll"].includes(getComputedStyle(e).overflowX)?null:{left:e.scrollLeft,maximum:t}}function hj(e){return e.sessionTitle?`${e.projectName} \xb7 ${e.sessionTitle}`:e.projectName}function hN({items:e,activeWorkId:t,onActiveWorkSessionChange:s,children:a}){let i,l,{t:o}=(0,f.Bd)("workbench"),d=(0,s1.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=hk(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=hk(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)(hv,{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)(hw,{className:"ml-0 h-full",children:e.map((t,s)=>(0,n.jsx)(hy,{"aria-label":`${s+1} / ${e.length},${hj(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:hj(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 hI(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}var hC=s(78653),hS=s.n(hC);function hM({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)(s9.A,{className:"size-4"}):(0,n.jsx)(m0.A,{className:"size-5"})})}let hz=(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);s7(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
|
|