@jetcrab/pi-desk 1.1.24-dev → 1.1.28-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/app/project-preview/page.tsx +13 -0
- package/src/client/l1_entry/pages/l1-project-preview-page.tsx +1 -5
- package/src/client/l2_biz/project-preview/hooks/l2-use-project-preview.ts +25 -0
- package/src/client/l2_biz/project-preview/l2-project-preview-storage.ts +7 -7
- package/src/client/l2_biz/project-preview/l2-project-preview.tsx +8 -5
- package/src/client/l2_biz/project-preview/runtime/l2-project-history-runtime.ts +14 -11
- package/src/client/l2_biz/project-preview/views/l2-project-branch-select.tsx +347 -0
- package/src/client/l2_biz/project-preview/views/l2-project-change-tree.tsx +28 -11
- package/src/client/l2_biz/project-preview/views/l2-project-history-list.tsx +35 -8
- package/src/client/l2_biz/project-preview/views/l2-project-history-view.tsx +46 -48
- package/src/client/l2_biz/workbench/file-workspace/l2-file-workspace-runtime.ts +2 -1
- package/src/client/l2_biz/workbench/file-workspace/l2-file-workspace-view.tsx +6 -2
- package/src/client/l3_modules/conversation/l3-conversation-viewport.tsx +18 -8
- package/src/client/l3_modules/project-files/l3-project-document-view.tsx +7 -4
- package/src/client/l3_modules/project-files/l3-project-file-runtime.ts +181 -89
- package/src/client/l3_modules/project-files/l3-project-file-tabs.tsx +80 -28
- package/src/common/l2_biz/project-preview/l2-project-history-messages.ts +4 -2
- package/src/common/l2_biz/project-preview/l2-project-preview-navigation.ts +14 -0
- package/src/server/l4_foundation/process/l4-process-tree.js +159 -40
- package/temp/build/pi-desk/release/.next/BUILD_ID +1 -1
- package/temp/build/pi-desk/release/.next/build-manifest.json +3 -3
- package/temp/build/pi-desk/release/.next/react-loadable-manifest.json +1 -1
- 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/login/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/page.js +2 -2
- package/temp/build/pi-desk/release/.next/server/app/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/project-preview/page.js +1 -1
- package/temp/build/pi-desk/release/.next/server/app/project-preview/page_client-reference-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/chunks/27344.js +15 -0
- package/temp/build/pi-desk/release/.next/server/chunks/35985.js +1 -1
- package/temp/build/pi-desk/release/.next/server/middleware-build-manifest.js +1 -1
- package/temp/build/pi-desk/release/.next/server/middleware-react-loadable-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/15302-6e070e13fa65c863.js +1 -0
- package/temp/build/pi-desk/release/.next/static/chunks/19991.bcca96d396b83030.js +1 -0
- package/temp/build/pi-desk/release/.next/static/chunks/65232-ef4e5a4174f62faf.js +15 -0
- package/temp/build/pi-desk/release/.next/static/chunks/app/{page-ff44dcf27c2ba1c2.js → page-ce2ebf7d8ea7a330.js} +3 -3
- package/temp/build/pi-desk/release/.next/static/chunks/app/project-preview/page-038b6c14e03ed878.js +1 -0
- package/temp/build/pi-desk/release/.next/static/chunks/{webpack-48eecbb66781c006.js → webpack-c0b805df46fcf8b3.js} +1 -1
- package/temp/build/pi-desk/release/.next/static/css/c43b04c244a64fb4.css +1 -0
- package/temp/build/pi-desk/release/.next/trace-build +1 -1
- package/temp/build/pi-desk/release/.next/server/chunks/20460.js +0 -15
- package/temp/build/pi-desk/release/.next/static/chunks/15302-9c807afc6c60de0c.js +0 -1
- package/temp/build/pi-desk/release/.next/static/chunks/19991.8aa2e4b6df15fad6.js +0 -1
- package/temp/build/pi-desk/release/.next/static/chunks/9038-05fd2688407b39c1.js +0 -15
- package/temp/build/pi-desk/release/.next/static/chunks/app/project-preview/page-bc18765121950e65.js +0 -1
- package/temp/build/pi-desk/release/.next/static/css/10e063cfb3cda7bd.css +0 -1
- /package/temp/build/pi-desk/release/.next/static/{w3CeIboVupqJdq890TlcG → bj2dB_Z10YB_CqK_VNhDx}/_buildManifest.js +0 -0
- /package/temp/build/pi-desk/release/.next/static/{w3CeIboVupqJdq890TlcG → bj2dB_Z10YB_CqK_VNhDx}/_ssgManifest.js +0 -0
|
@@ -151,8 +151,8 @@ textarea.pi-desk-ui-control{min-height:13rem;resize:vertical;font-family:ui-mono
|
|
|
151
151
|
@container (max-width:28rem){.pi-desk-ui-action-row-mobile-stack{align-items:flex-start;flex-direction:column}.pi-desk-ui-key-value{grid-template-columns:minmax(0,1fr)}.pi-desk-ui-key-value-action{justify-self:start}}
|
|
152
152
|
`;function ex(...e){return e.filter(Boolean).join(" ")}function eb({className:e,children:t,...s}){return(0,n.jsxs)("div",{...s,"data-pi-desk-ui-root":"",className:ex("pi-desk-ui-root",e),children:[(0,n.jsx)("style",{href:"pi-desk-ui",precedence:"pi-desk-ui",children:ef}),t]})}function ev({className:e,...t}){return(0,n.jsx)("input",{...t,type:"checkbox",className:ex("pi-desk-ui-checkbox",e)})}r.Component;var ew=s(84942);let ey=[{key:"all",label:"policyAll"},{key:"allow",label:"policyAllow"},{key:"deny",label:"policyDeny"},{key:"none",label:"policyNone"}];function ek({label:e,rule:t,options:s,disabled:i,onChange:a}){let{t:l}=(0,b.Bd)("capabilityModes"),[o,c]=(0,r.useState)(()=>void 0!==t.allow?0===t.allow.length?"none":"allow":t.deny?.length?"deny":"all"),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(160),[v,w]=(0,r.useState)(()=>[...new Set([...t.allow??[],...t.deny??[]])]),y="deny"===o||"all"===o||"allow"===o&&d?"deny":"allow",k=t[y]??[],j=new Set(k),N=(0,r.useMemo)(()=>{let e=new Map(s.map(e=>[e.value,e]));for(let s of[...v,...t.allow??[],...t.deny??[]])e.has(s)||e.set(s,{value:s});return[...e.values()].sort((e,t)=>e.value.localeCompare(t.value))},[v,s,t.allow,t.deny]),S=m.trim(),E=N.filter(e=>(!h||!!j.has(e.value))&&(!S||`${e.value} ${e.label??""} ${e.description??""}`.toLowerCase().includes(S.toLowerCase())||S.includes("*")&&(0,ew.RC)({allow:[S]},e.value))),M=E.slice(0,f),z=S.length>0&&S.length<=256&&!j.has(S);function A(e){"all"===o&&e.length>0&&c("deny"),"none"===o&&e.length>0&&c("allow"),a({...t,[y]:e})}function $(e,t){A(t?[...new Set([...k,e])]:k.filter(t=>t!==e))}function R(){z&&!i&&(w(e=>[...new Set([...e,S])]),$(S,!0),p(""))}return(0,n.jsxs)(eb,{className:"flex min-h-0 flex-1 flex-col","aria-label":l("ruleEditor",{name:e}),children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 border-b px-4 py-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("div",{className:"flex flex-wrap gap-1",role:"group","aria-label":l("ruleMode",{name:e}),children:ey.map(e=>(0,n.jsxs)(I.$,{size:"sm",variant:o===e.key?"secondary":"ghost","aria-pressed":o===e.key,disabled:i,onClick:()=>{var s;c(s=e.key),u(!1),g(!1),"all"===s?a({}):"none"===s?a({allow:[]}):"deny"===s?a({deny:t.deny??[]}):a({allow:t.allow??[],...t.deny?.length?{deny:t.deny}:{}})},children:[o===e.key&&(0,n.jsx)(ep.A,{className:"size-3.5"}),l(e.label)]},e.key))}),"allow"===o&&(0,n.jsxs)(I.$,{size:"sm",variant:d?"secondary":"ghost",disabled:i,"aria-pressed":d,onClick:()=>{u(!d),g(!1)},children:[l("exclusions"),t.deny?.length?` \xb7 ${t.deny.length}`:""]})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,n.jsx)(eh.A,{className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{"aria-label":l("ruleSearch"),placeholder:l("ruleSearchPlaceholder"),maxLength:256,className:"pl-9 pr-9",value:m,disabled:i,onChange:e=>{p(e.target.value),x(160)},onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),R())}}),m&&(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost","aria-label":l("clearSearch"),className:"absolute right-0.5 top-1/2 -translate-y-1/2",onClick:()=>p(""),children:(0,n.jsx)(V.A,{className:"size-3.5"})})]}),(0,n.jsxs)(I.$,{size:"sm",variant:h?"secondary":"ghost","aria-pressed":h,onClick:()=>g(!h),children:[(0,n.jsx)(eg.A,{className:"size-4"}),(0,n.jsx)("span",{className:"hidden @min-[420px]:inline",children:l("selectedOnly")}),(0,n.jsx)("span",{className:"@min-[420px]:hidden",children:l("selectedShort")})]})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:[l("allow"===y?"allowRules":"excludeRules")," \xb7"," ",l("selectedCount",{count:k.length})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1",children:[(0,n.jsx)(I.$,{size:"sm",variant:"ghost",disabled:i||0===M.length,onClick:()=>A([...new Set([...k,...M.map(e=>e.value)])]),children:l("selectVisible")}),k.length>0&&(0,n.jsx)(I.$,{size:"sm",variant:"ghost",disabled:i,onClick:()=>A([]),children:l("clearSelected")})]})]})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain p-3",children:[z&&(0,n.jsxs)(I.$,{variant:"outline",disabled:i,className:"mb-3 h-auto min-h-9 max-w-full justify-start",onClick:R,children:[(0,n.jsx)(U.A,{className:"size-4 shrink-0"}),l("addRule")," ",(0,n.jsx)("span",{className:"min-w-0 truncate font-mono",children:S})]}),(0,n.jsx)("div",{className:"grid min-w-0 grid-cols-1 gap-1 @min-[620px]:grid-cols-2",children:M.map(e=>{let t=j.has(e.value);return(0,n.jsxs)("label",{className:(0,C.cn)("flex min-h-9 min-w-0 cursor-pointer items-start gap-3 rounded-lg px-3 py-2 transition-colors hover:bg-muted",t&&"bg-accent text-accent-foreground",i&&"pointer-events-none opacity-50"),children:[(0,n.jsx)(ev,{checked:t,disabled:i,"aria-label":l("allow"===y?"allowValue":"excludeValue",{name:e.value}),className:"mt-1 shrink-0",onChange:t=>$(e.value,t.target.checked)}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block break-all text-sm font-medium",children:e.label??e.value}),e.label&&e.label!==e.value&&(0,n.jsx)("span",{className:"block break-all font-mono text-xs text-muted-foreground",children:e.value}),e.description?(0,n.jsxs)("details",{className:"mt-0.5 text-xs leading-5 text-muted-foreground",onClick:e=>e.stopPropagation(),children:[(0,n.jsx)("summary",{className:"line-clamp-1 cursor-pointer list-none",children:e.description}),(0,n.jsx)("span",{className:"block whitespace-pre-wrap break-words pt-1 text-sm",children:e.description})]}):e.value.includes("*")?(0,n.jsx)("span",{className:"block text-xs text-muted-foreground",children:l("pattern")}):null]})]},e.value)})}),0===M.length&&(0,n.jsx)("p",{className:"px-3 py-6 text-sm text-muted-foreground",children:S?l("noMatches"):h?l("noSelection"):l("enterPattern")}),E.length>M.length&&(0,n.jsx)(I.$,{variant:"ghost",className:"mt-3",onClick:()=>x(e=>e+160),children:l("moreRules",{count:E.length-M.length})})]})]})}function ej({modeKey:e,mode:t,catalog:s,disabled:i,onChange:a}){var l;let{t:o}=(0,b.Bd)("capabilityModes"),c=(0,r.useMemo)(()=>(function(e,t,s){let n=[{key:"tools",label:s,options:e?.tools??[],target:{kind:"tools"}},{key:"skills",label:"Skills",options:e?.skills??[],target:{kind:"skills"}}];for(let s of new Set([...Object.keys(e?.plugins??{}),...Object.keys(t.plugins??{})])){let r=e?.plugins[s]??{};for(let e of new Set([...Object.keys(r),...Object.keys(t.plugins?.[s]??{})]))n.push({key:`plugin:${s}:${e}`,label:r[e]?.label??`${s} / ${e}`,options:r[e]?.options??[],target:{kind:"plugin",pluginName:s,group:e}})}return n})(s,t,o("groupTools")),[s,t,o]),[d,u]=(0,r.useState)("tools"),m=c.find(e=>e.key===d)??c[0];return(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col",children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-3",children:(0,n.jsxs)("label",{className:"flex max-w-xl flex-wrap items-center gap-2 text-sm font-medium",children:[(0,n.jsx)("span",{children:o("modeName")}),(0,n.jsx)(em.p,{"aria-label":o("modeName"),value:t.name,maxLength:64,disabled:i,className:"min-w-40 flex-1",onChange:e=>a({...t,name:e.target.value})})]})}),(0,n.jsx)("div",{className:"flex shrink-0 flex-wrap gap-1 border-b px-4 py-2",role:"tablist","aria-label":o("category"),children:c.map(e=>(0,n.jsx)(I.$,{variant:e.key===m.key?"secondary":"ghost",size:"sm",role:"tab","aria-selected":e.key===m.key,onClick:()=>u(e.key),children:e.label},e.key))}),(0,n.jsx)(ek,{label:m.label,rule:"plugin"===(l=m.target).kind?t.plugins?.[l.pluginName]?.[l.group]??{}:t[l.kind]??{},options:m.options,disabled:i,onChange:e=>a(function(e,t,s){let n={...void 0===s.allow?{}:{allow:[...new Set(s.allow)]},...s.deny?.length?{deny:[...new Set(s.deny)]}:{}},r=0===Object.keys(n).length;if("plugin"!==t.kind){let s={...e};return r?delete s[t.kind]:s[t.kind]=n,s}let i={...e.plugins?.[t.pluginName]};r?delete i[t.group]:i[t.group]=n;let a={...e.plugins};Object.keys(i).length?a[t.pluginName]=i:delete a[t.pluginName];let l={...e};return Object.keys(a).length?l.plugins=a:delete l.plugins,l}(t,m.target,e))},`${e}:${m.key}`)]})}var eN=s(5464);function eI({open:e,deleteName:t,saving:s,error:r,onCancel:i,onDelete:a,onLeave:l}){let{t:o}=(0,b.Bd)("capabilityModes");return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||s||i()},children:(0,n.jsxs)(eN.hA,{className:"z-[150]",showCloseButton:!s,children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:o(t?"deleteConfirm":"saveConfirm")}),(0,n.jsx)(eN.uX,{children:t?o("deleteDescription",{name:t}):o("unsavedDescription")})]}),r&&(0,n.jsx)("p",{role:"alert",className:"px-4 pb-3 text-sm text-destructive",children:r}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{variant:"outline",disabled:s,onClick:i,children:o("cancel")}),t?(0,n.jsx)(I.$,{variant:"destructive",onClick:a,children:o("delete")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{variant:"ghost",disabled:s,onClick:()=>l("discard"),children:o("discard")}),(0,n.jsx)(I.$,{disabled:s,onClick:()=>l("save"),children:o(s?"saving":"saveContinue")})]})]})]})})}function eS({modeNames:e,onBeforeLeaveChange:t}){let{t:s}=(0,b.Bd)("capabilityModes"),{clientId:i}=(0,ei.gM)(),a=(0,X.G)(),l=function(e){let{t}=(0,b.Bd)("capabilityModes"),[s,n]=(0,r.useState)(null),[i,a]=(0,r.useState)({}),[l,o]=(0,r.useState)(null),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(null),[x,v]=(0,r.useState)(!1),w=(0,r.useRef)(null),y=(0,r.useRef)(null),k=null!==s&&JSON.stringify(s)!==JSON.stringify(i);(0,r.useEffect)(()=>{let e=new AbortController;return y.current=e,()=>{e.abort(),w.current?.(!1),w.current=null}},[]);let j=(0,r.useCallback)(async(r=!1)=>{if(null!==s&&!r)return i;m(!0),f(null);try{let t=await e.get(y.current?.signal);if(y.current?.signal.aborted)return null;return o(t.catalog),null!==s&&k||(n(t.modes),a(structuredClone(t.modes))),null!==s&&k?i:t.modes}catch(e){return y.current?.signal.aborted||f(e instanceof Error?e.message:t("catalogFailed")),null}finally{y.current?.signal.aborted||m(!1)}},[e,k,i,s,t]),N=(0,r.useCallback)(async e=>{if(null===e)return void d(null);let t=await j();t&&Object.hasOwn(t,e)&&d(e)},[j]),I=(0,r.useCallback)(async(e=!1)=>{let s=await j();if(!s)return;let n=e&&c?s[c]:void 0,r=crypto.randomUUID(),i=function(e,t){let s=new Set(Object.values(e).map(e=>e.name));if(!s.has(t))return t;let n=2;for(;s.has(`${t} ${n}`);)n+=1;return`${t} ${n}`}(s,n?t("copySuffix",{name:n.name}):t("newMode"));a({...s,[r]:{...n?structuredClone(n):{},name:i}}),d(r)},[j,c,t]),S=(0,r.useCallback)(e=>{c&&a(t=>({...t,[c]:e}))},[c]),C=(0,r.useCallback)(()=>{c&&(a(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==c))),d(null))},[c]),E=(0,r.useCallback)(async()=>{if(!k)return!0;h(!0),f(null);try{let t=await e.replace(i,y.current?.signal);if(y.current?.signal.aborted)return!1;return n(t),a(structuredClone(t)),!0}catch(e){return y.current?.signal.aborted||f(e instanceof Error?e.message:t("saveFailed")),!1}finally{y.current?.signal.aborted||h(!1)}},[e,k,i,t]),M=(0,r.useCallback)(()=>k?(v(!0),new Promise(e=>{w.current=e})):Promise.resolve(!0),[k]);return{draft:i,saved:s,catalog:l,selected:c,loading:u,saving:p,error:g,dirty:k,leaveOpen:x,beforeLeave:M,decideLeave:(0,r.useCallback)(async e=>{("save"!==e||await E())&&(v(!1),w.current?.("cancel"!==e),w.current=null)},[E]),load:j,select:N,add:I,update:S,remove:C,save:E}}((0,r.useMemo)(()=>(function(e){async function t(t,s,n,r){return eu(e,t,s,n,{signal:r,fallbackMessage:(0,ed.B)({msg:"能力模式请求失败",i18n:{key:"errors:capabilityFailed"}})})}return{get:e=>t("/api/capability-modes/get",{},el,e),async replace(e,s){let n=eo.safeParse({modes:e});if(!n.success)throw Error((0,ed.B)({msg:"请检查模式规则",i18n:{key:"errors:capabilityRuleInvalid"}}));return await t("/api/capability-modes/replace",n.data,ec,s),n.data.modes}}})(i),[i])),[o,c]=(0,r.useState)(null),{beforeLeave:d}=l;(0,r.useEffect)(()=>(t(d),()=>t(null)),[d,t]);let u=null===l.saved?e:(0,er.HE)(l.draft),m=l.selected?l.draft[l.selected]:void 0,p=l.loading||l.saving,h=async()=>{await l.save()&&a.success(s("saved"))},g=(0,n.jsxs)(I.$,{size:"sm",disabled:!l.dirty||p,onClick:()=>void h(),children:[l.saving?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(Z.A,{className:"size-4"}),l.saving?s("saving"):s("saveModes")]});return(0,n.jsxs)("section",{"aria-label":s("settings"),className:"flex h-full min-h-0 flex-col bg-background",children:[(0,n.jsxs)("header",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-b px-4 py-3",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"shrink-0 text-sm font-medium",children:s("editMode")}),(0,n.jsxs)(ea.l6,{value:l.selected??"",disabled:p,onValueChange:e=>{"string"==typeof e&&l.select(e||null)},children:[(0,n.jsx)(ea.bq,{"aria-label":s("selectMode"),className:"w-40 sm:w-48",children:(0,n.jsx)(ea.yv,{children:l.selected?u[l.selected]||s("unnamedMode"):s("allDefault")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[140]",children:[(0,n.jsx)(ea.eb,{value:"",children:s("allDefault")}),Object.entries(u).map(([e,t])=>(0,n.jsx)(ea.eb,{value:e,children:t||s("unnamedMode")},e))]})]})]}),(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,n.jsxs)(I.$,{size:"sm",variant:"ghost",disabled:p,onClick:()=>void l.add(),children:[(0,n.jsx)(U.A,{className:"size-4"}),s("addMode")]}),m&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost","aria-label":s("copyMode"),title:s("copyTitle"),disabled:p,onClick:()=>void l.add(!0),children:(0,n.jsx)(ee.A,{className:"size-4"})}),(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost","aria-label":s("deleteMode"),title:s("deleteTitle"),disabled:p,onClick:()=>c(m.name||s("unnamedMode")),children:(0,n.jsx)(et.A,{className:"size-4"})})]}),l.catalog&&(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost","aria-label":s("refreshCatalog"),title:s("refreshCatalog"),disabled:p,onClick:()=>void l.load(!0),children:(0,n.jsx)(es.A,{className:"size-4"})}),(0,n.jsx)("span",{className:"ml-1 hidden sm:inline-flex",children:g})]})]}),l.error&&(0,n.jsxs)("div",{role:"alert",className:"shrink-0 border-b px-4 py-3 text-sm text-destructive",children:[l.error,(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:()=>void l.load(!0),children:s("retryRead")})]}),l.loading&&(0,n.jsxs)("div",{role:"status",className:"flex shrink-0 items-center gap-2 border-b px-4 py-3 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),s("loadingCatalog")]}),m&&l.selected?(0,n.jsx)(ej,{modeKey:l.selected,mode:m,catalog:l.catalog,disabled:l.saving,onChange:l.update}):(0,n.jsxs)("div",{className:"flex items-start gap-3 p-6",children:[(0,n.jsx)(en.A,{className:"mt-0.5 size-6 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:"text-sm font-semibold",children:s("allEnabled")}),(0,n.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:s("allDescription")})]})]}),(0,n.jsxs)("footer",{className:"mt-auto flex shrink-0 items-center justify-between gap-3 border-t px-4 py-3 pb-[max(.75rem,env(safe-area-inset-bottom))] text-xs text-muted-foreground sm:py-2",children:[(0,n.jsx)("span",{role:"status",children:l.dirty?s("unsaved"):s("allIsDefault")}),(0,n.jsx)("span",{className:"sm:hidden",children:g})]}),(0,n.jsx)(eI,{open:l.leaveOpen||null!==o,deleteName:o,saving:l.saving,error:l.leaveOpen?l.error:null,onCancel:()=>{null!==o?c(null):l.decideLeave("cancel")},onDelete:()=>{l.remove(),c(null)},onLeave:e=>void l.decideLeave(e)})]})}var eC=s(87372),eE=s(79566),eM=s(13344),ez=s(54359),eA=s(24022),e$=s(77483),eR=s(95526),eP=s(66584),eD=s(76085),eT=s(58619),eO=s(90695),eL=s(6609);let eF={plugin:eC.A,server:eE.A,rocket:eM.A,settings:ez.A,panel:eA.A,message:e$.A,terminal:w.A,file:eR.A,folder:eP.A,bot:eD.A,wrench:eT.A,database:eO.A,globe:eL.A},eB=new Map;function eq({icon:e,className:t}){if(e?.type==="svg"){let s=function(e){if(eB.has(e))return eB.get(e)??null;let t=e.trim(),s=t.length>16384||!/^<svg[\s>]/i.test(t)||!/<\/svg>$/i.test(t)||/<\s*(script|foreignObject|iframe|object|embed|link|style)\b/i.test(t)||/\son[a-z]+\s*=/i.test(t)||/(javascript:|data:text\/html|https?:\/\/)/i.test(t)?null:t;return eB.set(e,s),s}(e.content);if(s)return(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("block [&>svg]:size-full",t),dangerouslySetInnerHTML:{__html:s}})}let s=e?.type==="builtin"?eF[e.name]:eC.A;return(0,n.jsx)(s,{"aria-hidden":"true",className:t})}var e_=s(94173),eW=s(90434),eY=s(86758),eV=s(81649);function eU({error:e,children:t}){let{t:s}=(0,b.Bd)("common"),r=e.message.trim().split(/\r?\n/)[0]||s("unknownError");return(0,n.jsxs)("div",{className:"mt-1 min-w-0",children:[(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:r}),(0,n.jsxs)(eV.Nt,{defaultOpen:!1,children:[(0,n.jsxs)(eV.R6,{className:"group mt-1 inline-flex min-h-8 cursor-pointer items-center gap-2 rounded-md text-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eY.A,{"aria-hidden":"true",className:"size-4 shrink-0 transition-transform group-aria-expanded:rotate-180 motion-reduce:transition-none"}),s("errorDetails")]}),(0,n.jsx)(eV.Ke,{className:"h-[var(--collapsible-panel-height)] overflow-hidden transition-[height,opacity] duration-200 ease-out data-starting-style:h-0 data-starting-style:opacity-0 data-ending-style:h-0 data-ending-style:opacity-0 motion-reduce:transition-none",children:(0,n.jsxs)("div",{className:"space-y-3 pt-2",children:[(0,n.jsx)("pre",{className:"max-h-[min(20rem,45dvh)] overflow-auto rounded-md bg-background p-3 font-mono text-sm leading-relaxed whitespace-pre-wrap [overflow-wrap:anywhere]",children:e.stack||e.message}),t]})})]})]})}function eH({pluginName:e,kind:t,contributionName:s,target:i,targetKey:a,className:l,layout:o="fill"}){let{t:c}=(0,b.Bd)("pluginManagement"),d=(0,Q.t4)();(0,Q.So)();let u=d.getEntryState(e),m="ready"===u.status?u.runtime:u.status,p="failed"===u.status?u.error:null,h=(0,r.useRef)(null),g=(0,r.useRef)(i),f=a??i,x="session-header-item"===i.kind?i.presentation:void 0,[w,y]=(0,r.useState)(0),[k,j]=(0,r.useState)({status:"loading"});(0,r.useEffect)(()=>{g.current=i},[i]),(0,r.useEffect)(()=>{let n=h.current;if(!n)return;let r=new AbortController,i=!0,a=null;if("ready"!==u.status)return queueMicrotask(()=>{i&&j(p?{status:"error",error:p}:{status:"loading"})}),()=>{i=!1,r.abort()};let l=Promise.resolve().then(()=>i?((a=document.createElement("div")).className="intrinsic"===o?"inline-block min-h-0 min-w-0 align-top":"inline"===o?"min-w-0 w-full":"h-full min-h-0 w-full min-w-0",n.append(a),d.mountContribution({pluginName:e,kind:t,contributionName:s,container:a,target:g.current,signal:r.signal})):null);return queueMicrotask(()=>{i&&j({status:"loading"})}),l.then(e=>{i&&e&&j({status:"ready"})},e=>{i&&j({status:"error",error:e instanceof Error?e:Error(String(e))})}),()=>{i=!1,r.abort(),a?.remove(),l.then(async n=>{if(n)try{await n()}catch(n){console.error("[Pi Desk][PluginHost] Contribution disposer 执行失败",{pluginName:e,kind:t,contributionName:s,errorName:n instanceof Error?n.name:"UnknownError",message:n instanceof Error?n.message:String(n)})}},()=>void 0)}},[w,s,m,u.status,p,t,o,f,e,d]);let N=()=>{if("failed"===u.status){j({status:"loading"}),d.retryEntry(e).catch(t=>{"failed"===d.getEntryState(e).status&&j({status:"error",error:t instanceof Error?t:Error(String(t))})});return}"failed"!==d.getContributionLoadState(e,t,s,x).status?y(e=>e+1):(j({status:"loading"}),d.retryContribution(e,t,s,x).then(()=>{d.getEntryState(e)===u&&y(e=>e+1)},t=>{d.getEntryState(e)===u&&j({status:"error",error:t instanceof Error?t:Error(String(t))})}))},S="loading"===k.status?"h-[200px] w-[360px]":"error"===k.status?"w-[min(480px,calc(100dvw-3rem))]":"h-fit w-fit";return(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar relative min-h-0 min-w-0","intrinsic"===o?(0,C.cn)("max-h-[calc(100dvh-7rem)] max-w-[calc(100dvw-3rem)] overflow-auto max-sm:max-h-[calc(100dvh-5rem)] max-sm:max-w-[calc(100dvw-2rem)]",S):"inline"===o?"w-full":"h-full w-full",l),children:[(0,n.jsx)("div",{ref:h,"data-pi-desk-plugin":e,"data-pi-desk-kind":t,"data-pi-desk-contribution":s,className:(0,C.cn)("intrinsic"===o?"inline-block min-h-0 min-w-0 align-top":"inline"===o?"w-full min-w-0":"h-full min-h-0 w-full min-w-0","error"===k.status&&"hidden")}),"loading"===k.status?(0,n.jsxs)("div",{role:"status",className:(0,C.cn)("flex items-center text-sm text-muted-foreground","inline"===o?"min-h-7 gap-1 py-1":"absolute inset-0 justify-center bg-popover p-6"),children:[(0,n.jsx)(v.A,{className:"mr-2 size-4 shrink-0 animate-spin"}),(0,n.jsx)("span",{className:"min-w-0 truncate",children:c("viewLoading")})]}):null,"error"===k.status&&"inline"===o?(0,n.jsx)("div",{role:"alert",className:"min-w-0",children:(0,n.jsxs)(eW.AM,{children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":c("viewFailed"),title:c("viewFailed"),className:"text-destructive"}),children:(0,n.jsx)(e_.A,{className:"size-4"})}),(0,n.jsxs)(eW.hl,{align:"start",finalFocus:!0,children:[(0,n.jsx)(eW.eO,{children:c("viewFailed")}),(0,n.jsx)(eU,{error:k.error,children:(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e," \xb7 ",t," \xb7 ",s]})}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",onClick:N,children:[(0,n.jsx)(es.A,{}),c("retry")]})]})]})}):"error"===k.status?(0,n.jsx)("div",{role:"alert",className:(0,C.cn)("flex items-center justify-center overflow-auto bg-background p-4","fill"===o&&"absolute inset-0"),children:(0,n.jsx)("div",{className:"w-full max-w-xl rounded-lg border border-destructive/35 bg-muted p-4",children:(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)(e_.A,{className:"mt-0.5 size-5 shrink-0 text-destructive"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"font-medium text-destructive",children:c("viewFailed")}),(0,n.jsx)(eU,{error:k.error,children:(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e," \xb7 ",t," \xb7 ",s]})}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:N,children:[(0,n.jsx)(es.A,{}),c("retry")]})]})]})})}):null]})}function eK({pluginName:e,descriptor:t,workSessions:s,preferredWorkId:i,onClose:a}){let{t:l}=(0,b.Bd)("pluginManagement"),o=(0,Q.t4)();(0,Q.So)();let c=o.getEntryState(e),[d]=(0,r.useState)(()=>{let e=s.find(e=>e.workId===i);return e?{source:{workId:e.workId,sessionId:e.sessionId,branchId:e.branchId},cwd:e.cwd}:null}),u=(0,r.useMemo)(()=>({kind:"application",initialContext:d,close:()=>{o.getEntryState(e)===c&&a()}}),[c,d,a,e,o]),m="host"===t.chrome;return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:(e,t)=>{e||"focus-out"===t.reason||a()},children:(0,n.jsxs)(eN.hA,{finalFocus:!1,showCloseButton:!1,className:(0,C.cn)("w-fit max-w-[calc(100dvw-2rem)] max-h-[calc(100dvh-2rem)]",!m&&"rounded-none border-0 bg-transparent shadow-none ring-0"),children:[m?(0,n.jsx)(eN.Hl,{className:"border-b px-4 py-3",children:(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground",children:(0,n.jsx)(eq,{icon:t.icon,className:"size-5"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{className:"break-words",children:t.title}),(0,n.jsx)(eN.uX,{className:"sr-only",children:e})]}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon","aria-label":l("closeNamedApplication",{name:t.title}),title:l("closeApplication"),onClick:a,className:"text-muted-foreground",children:(0,n.jsx)(V.A,{className:"size-4"})})]})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eN.YM,{className:"sr-only",children:t.title}),(0,n.jsx)(eN.uX,{className:"sr-only",children:e})]}),(0,n.jsx)("div",{className:"min-h-0 min-w-0 max-w-full overflow-hidden",children:(0,n.jsx)(eH,{pluginName:e,kind:"application",contributionName:t.contributionName,target:u,layout:"intrinsic"})})]})})}function eG({pluginName:e,descriptor:t,source:s,onClose:i}){let a=(0,r.useMemo)(()=>({kind:"composer-panel",source:s,close:i}),[i,s]);return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>!e&&i(),children:(0,n.jsxs)(eN.hA,{finalFocus:!1,className:"h-[min(720px,calc(100dvh-2rem))] max-w-4xl max-sm:h-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)(eN.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground",children:(0,n.jsx)(eq,{icon:t.icon,className:"size-5"})}),(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)(eN.YM,{className:"truncate",children:t.label}),(0,n.jsx)(eN.uX,{className:"sr-only",children:e})]})]})}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:(0,n.jsx)(eH,{pluginName:e,kind:"composer-panel",contributionName:t.contributionName,target:a,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})})]})})}var eJ=s(15265),eQ=s(5816),eX=s(31026),eZ=s(59095),e0=s(12720),e1=s(43016),e2=s(73392);function e5({className:e,orientation:t="horizontal",...s}){return(0,n.jsx)(eX.p,{"data-slot":"tabs","data-orientation":t,className:(0,C.cn)("group/tabs flex gap-2 data-horizontal:flex-col",e),...s})}let e3=(0,e2.F)("group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",{variants:{variant:{default:"bg-muted",line:"gap-1 bg-transparent"}},defaultVariants:{variant:"default"}});function e4({className:e,variant:t="default",...s}){return(0,n.jsx)(eZ.j,{"data-slot":"tabs-list","data-variant":t,className:(0,C.cn)(e3({variant:t}),e),...s})}function e6({className:e,...t}){return(0,n.jsx)(e0.M,{"data-slot":"tabs-trigger",className:(0,C.cn)("relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4","group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent","data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground","after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",e),...t})}function e8({className:e,...t}){return(0,n.jsx)(e1.R,{"data-slot":"tabs-content",className:(0,C.cn)("flex-1 text-sm outline-none",e),...t})}var e7=s(36670),e9=s(99084);let te=new Set(["bash","edit","find","grep","ls","read","write"]),tt="__pi_desk_unknown_schema_type__",ts={before_agent_start:{label:"eventAgentStart",description:"eventAgentStartDescription"},context:{label:"eventContext",description:"eventContextDescription"},input:{label:"eventInput",description:"eventInputDescription"},before_provider_request:{label:"eventProvider",description:"eventProviderDescription"},tool_call:{label:"eventToolCall",description:"eventToolCallDescription"},tool_result:{label:"eventToolResult",description:"eventToolResultDescription"},message_end:{label:"eventMessageEnd",description:"eventMessageEndDescription"},session_before_compact:{label:"eventBeforeCompact",description:"eventBeforeCompactDescription"}},tn={application:"contributionApplication","composer-panel":"contributionComposer","settings-page":"contributionSettings","message-view":"contributionMessage","session-sidebar-tab":"contributionSidebar",widget:"contributionWidget","session-header-item":"contributionSessionHeader"};function tr(e){let t=[];for(let s of e.extensions)for(let e of s.events){let n=ts[e.name];n&&t.push({name:e.name,count:e.count,path:s.path,label:n.label,description:n.description})}return t.sort((e,t)=>{let s=e.name.localeCompare(t.name);return 0===s?e.path.localeCompare(t.path):s})}function ti(e){return null===e||"object"!=typeof e||Array.isArray(e)?null:e}function ta({state:e}){let{t}=(0,b.Bd)("pluginManagement"),s=t("active"===e?"stateActive":"inactive"===e?"stateInactive":"stateShadowed");return(0,n.jsx)("span",{className:`rounded-md px-1.5 py-0.5 text-xs font-medium ${"active"===e?"bg-muted text-status-success":"inactive"===e?"bg-muted text-muted-foreground":"bg-muted text-status-warning"}`,children:s})}function tl({text:e,label:t}){let{t:s}=(0,b.Bd)("pluginManagement"),[i,a]=(0,r.useState)(!1);return(0,n.jsx)(I.$,{type:"button",size:"icon",variant:"ghost","aria-label":t,title:s(i?"copied":"copy"),onClick:()=>{(0,e9.x)(e).then(e=>{e&&a(!0)})},children:i?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})})}function to({title:e,text:t}){let{t:s}=(0,b.Bd)("pluginManagement");return(0,n.jsxs)("div",{className:"rounded-lg bg-muted",children:[(0,n.jsxs)("div",{className:"flex min-h-9 items-center justify-between gap-2 px-3",children:[(0,n.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:e}),(0,n.jsx)(tl,{text:t,label:s("copyNamed",{name:e})})]}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words px-3 py-3 font-mono text-sm leading-[1.6]",children:t})]})}function tc({title:e,description:t,children:s}){return(0,n.jsxs)(eV.Nt,{className:"border-t",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-8 w-full cursor-pointer items-center gap-2 py-2 text-left text-sm font-medium outline-none hover:text-muted-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:[(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),e]}),(0,n.jsx)(eV.Ke,{children:(0,n.jsxs)("div",{className:"space-y-3 pb-3",children:[t?(0,n.jsx)("p",{className:"text-sm leading-5 text-muted-foreground",children:t}):null,s]})})]})}function td({capabilities:e}){let{t}=(0,b.Bd)("pluginManagement"),s=tr(e);return 0===s.length?null:(0,n.jsx)(tc,{title:t("dynamicTitle"),description:t("dynamicDescription"),children:(0,n.jsx)("div",{className:"divide-y",children:s.map((e,s)=>(0,n.jsxs)("div",{className:"px-3 py-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"text-xs font-semibold",children:e.name}),e.count>1?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["\xd7",e.count]}):null,(0,n.jsx)("span",{className:"text-xs font-medium",children:t(e.label)})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:t(e.description)}),(0,n.jsx)("p",{className:"mt-1 truncate font-mono text-xs text-muted-foreground",title:e.path,children:e.path})]},`${e.path}:${e.name}:${s}`))})})}function tu({tool:e}){let{t}=(0,b.Bd)("pluginManagement"),s=function(e){var t;let s=ti(e.properties);if(!s)return[];let n=new Set(Array.isArray(t=e.required)?t.filter(e=>"string"==typeof e):[]);return Object.entries(s).map(([e,t])=>{let s=ti(t);return{name:e,required:n.has(e),type:function e(t){let s=ti(t);if(!s)return tt;let n=Array.isArray(s.enum)?s.enum.filter(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e):[];if(n.length>0)return n.map(String).join(" | ");if("string"==typeof s.type){if("array"!==s.type)return s.type;let t=e(s.items);return t===tt?"array":`${t}[]`}for(let t of["anyOf","oneOf"]){if(!Array.isArray(s[t]))continue;let n=s[t].map(e).filter(e=>e!==tt);if(n.length>0)return[...new Set(n)].join(" | ")}return tt}(t),description:"string"==typeof s?.description?s.description:null}})}(e.parameters);return(0,n.jsxs)("div",{className:"mt-4",children:[(0,n.jsxs)("p",{className:"text-sm font-medium",children:[t("arguments")," \xb7 ",s.length>0?s.length:t("none")]}),(0,n.jsxs)("div",{className:"py-3",children:[s.length>0?(0,n.jsx)("div",{className:"space-y-2",children:s.map(e=>(0,n.jsxs)("div",{className:"grid gap-1 text-sm sm:grid-cols-[minmax(8rem,0.8fr)_minmax(0,1.5fr)] sm:gap-3",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[(0,n.jsx)("code",{className:"font-semibold",children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(e.required?"required":"optional")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.type===tt?t("unknown"):e.type})]}),(0,n.jsx)("p",{className:"min-w-0 break-words leading-5 text-muted-foreground",children:e.description??"—"})]},e.name))}):(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("noArguments")}),(0,n.jsxs)(eV.Nt,{className:"mt-3",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-8 cursor-pointer items-center gap-2 text-sm text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),t("rawSchema")]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,children:(0,n.jsx)("pre",{className:"mt-2 whitespace-pre-wrap break-words rounded-lg bg-muted p-3 font-mono text-sm leading-[1.6]",children:JSON.stringify(e.parameters,null,2)})})]})]})]})}function tm({detail:e}){let{t}=(0,b.Bd)("pluginManagement");return 0===e.tools.length?null:(0,n.jsx)(tc,{title:t("toolCapabilities"),description:t("toolDescription"),children:(0,n.jsx)("div",{className:"space-y-2",children:e.tools.map((e,s)=>(0,n.jsxs)(eV.Nt,{className:"border-b py-3 last:border-b-0",children:[(0,n.jsxs)(eV.R6,{className:"group w-full cursor-pointer text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"mr-2 inline-block size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),(0,n.jsxs)("span",{className:"inline-flex min-w-0 flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"font-semibold",children:e.name}),e.label&&e.label!==e.name?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.label}):null,(0,n.jsx)(ta,{state:e.state}),te.has(e.name)&&"shadowed"!==e.state?(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs font-medium text-foreground",children:t("overridesBuiltin")}):null]}),(0,n.jsx)("span",{className:"mt-1.5 block break-words text-sm leading-5 text-muted-foreground",children:e.description||t("noDescription")})]}),(0,n.jsxs)(eV.Ke,{keepMounted:!0,children:[(0,n.jsx)(tu,{tool:e}),e.promptSnippet||e.promptGuidelines.length>0?(0,n.jsxs)("div",{className:"mt-3 space-y-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"text-xs font-medium",children:t("systemPrompts")}),"active"!==e.state?(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("inactivePrompt")}):null]}),e.promptSnippet?(0,n.jsx)(to,{title:"Available tools",text:e.promptSnippet}):null,e.promptGuidelines.length>0?(0,n.jsx)(to,{title:`Guidelines \xb7 ${e.promptGuidelines.length}`,text:e.promptGuidelines.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}):null]}):null]})]},`${e.name}:${s}`))})})}function tp({title:e,content:t,truncated:s}){let{t:r}=(0,b.Bd)("pluginManagement");return(0,n.jsxs)(eV.Nt,{className:"mt-3",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-8 w-full cursor-pointer items-center gap-2 py-2 text-left text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),e]}),(0,n.jsxs)(eV.Ke,{keepMounted:!0,className:"border-t",children:[(0,n.jsx)("div",{className:"flex justify-end px-2 pt-1",children:(0,n.jsx)(tl,{text:t,label:r("copyNamed",{name:e})})}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words rounded-lg bg-muted p-3 font-mono text-sm leading-[1.6]",children:t}),s?(0,n.jsx)("p",{className:"py-2 text-sm text-status-warning",children:r("truncated")}):null]})]})}function th({detail:e}){let{t}=(0,b.Bd)("pluginManagement");return 0===e.skills.length&&0===e.prompts.length?null:(0,n.jsx)(tc,{title:t("resourcesTitle"),description:t("resourcesDescription"),children:(0,n.jsxs)("div",{className:"space-y-2",children:[e.skills.map(e=>(0,n.jsxs)("article",{className:"border-b py-4 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"font-semibold",children:e.name}),(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:t(e.modelVisible?"skillModelVisible":"manualOnly")})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:e.description}),(0,n.jsx)("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:e.path}),e.modelVisible?(0,n.jsx)("div",{className:"mt-2",children:(0,n.jsx)(to,{title:t("skillMetadata"),text:`name: ${e.name}
|
|
153
153
|
description: ${e.description}
|
|
154
|
-
location: ${e.path}`})}):null,(0,n.jsx)(tp,{title:t("viewSkillContent"),content:e.content,truncated:e.truncated})]},e.path)),e.prompts.map(e=>(0,n.jsxs)("article",{className:"border-b py-4 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)("code",{className:"font-semibold",children:["/",e.name]}),(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:t("manualOnly")})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:e.description}),(0,n.jsx)("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:e.path}),(0,n.jsx)(tp,{title:t("viewPromptContent"),content:e.content,truncated:e.truncated})]},e.path))]})})}function tg({capabilities:e,browserContributions:t}){let{t:s}=(0,b.Bd)("pluginManagement"),r=e.extensions.some(e=>e.events.length>0||e.commands.length>0||e.shortcuts.length>0||e.flags.length>0||e.messageRenderers.length>0||e.entryRenderers.length>0),i=e.piDesk.methods.length>0||e.piDesk.browserEntries.length>0||e.piDesk.messageDeclarations.length>0||t.length>0,a=e.themes.length>0||e.providers.length>0;return r||i||a?(0,n.jsx)(tc,{title:s("otherCapabilities"),children:(0,n.jsxs)("div",{className:"space-y-2",children:[i?(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs",children:[(0,n.jsx)("p",{className:"font-semibold",children:"Pi Desk"}),(0,n.jsxs)("div",{className:"mt-2 space-y-1.5 text-muted-foreground",children:[e.piDesk.methods.map(e=>(0,n.jsxs)("p",{children:["Method:",(0,n.jsxs)("code",{children:[e.pluginName,"/",e.method]})]},`${e.pluginName}:${e.method}`)),t.map(e=>(0,n.jsxs)("p",{children:[s(tn[e.kind]),":","message-view"===e.kind?e.viewKey:"application"===e.kind?e.title:"widget"===e.kind||"session-header-item"===e.kind?e.contributionName:e.label]},`${e.kind}:${e.contributionName}`)),e.piDesk.messageDeclarations.map(e=>(0,n.jsxs)("p",{children:[s("messageDeclarations"),(0,n.jsxs)("code",{children:[e.pluginName,"/",e.declarationName]})]},`${e.pluginName}:${e.declarationName}`))]})]}):null,r?e.extensions.map(e=>(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs",children:[(0,n.jsx)("code",{className:"block break-all font-semibold",children:e.path}),e.commands.length>0?(0,n.jsxs)("p",{className:"mt-2 leading-5 text-muted-foreground",children:["Commands:",e.commands.map(e=>`/${e.name}`).join("、")]}):null,e.shortcuts.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Shortcuts:",e.shortcuts.map(e=>e.shortcut).join("、")]}):null,e.flags.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Flags:",e.flags.map(e=>`--${e.name}`).join("、")]}):null,e.events.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Events:",e.events.map(e=>e.name).join("、")]}):null]},e.path)):null,a?(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs text-muted-foreground",children:[e.themes.length>0?(0,n.jsxs)("p",{children:["Theme:",e.themes.map(e=>e.name).join("、")]}):null,e.providers.length>0?(0,n.jsxs)("p",{className:"mt-1",children:["Provider:",e.providers.map(e=>e.name).join("、")]}):null]}):null]})}):null}function tf({plugin:e,detail:t,detailLoading:s,detailError:r,browserContributions:i,onRetry:a}){let{t:l}=(0,b.Bd)("pluginManagement"),{locale:o}=(0,eQ.i)(),c=function(e,t,s){let n=[];e.tools.length>0&&n.push({label:s("tagTools",{count:e.tools.length}),tone:"neutral"});let r=e.tools.reduce((e,t)=>"active"!==t.state?e:e+ +!!t.promptSnippet+t.promptGuidelineCount,0)+e.skills.filter(e=>e.modelVisible).length;r>0&&n.push({label:s("tagFixed",{count:r}),tone:"prompt"});let i=tr(e).reduce((e,t)=>e+t.count,0);i>0&&n.push({label:s("tagDynamic",{count:i}),tone:"dynamic"});let a=e.tools.filter(e=>"shadowed"!==e.state&&te.has(e.name)).length;a>0&&n.push({label:s("tagOverride",{count:a}),tone:"override"});let l=e.prompts.length+e.skills.filter(e=>!e.modelVisible).length;l>0&&n.push({label:s("tagManual",{count:l}),tone:"neutral"});let o=t.length+e.piDesk.methods.length+e.piDesk.messageDeclarations.length;o>0&&n.push({label:`Pi Desk ${o}`,tone:"neutral"});let c=e.providers.length+e.themes.length+e.extensions.reduce((e,t)=>e+t.commands.length+t.shortcuts.length+t.flags.length,0);return c>0&&n.push({label:s("tagInteraction",{count:c}),tone:"neutral"}),0===n.length&&e.extensions.length>0&&n.push({label:`Extension ${e.extensions.length}`,tone:"neutral"}),n}(e.capabilities,i,l);return(0,n.jsxs)("div",{className:"space-y-3 text-sm","data-testid":"plugin-capability-detail",children:[(0,n.jsx)("p",{className:"break-all font-mono text-xs text-muted-foreground",children:e.source}),c.length>0?(0,n.jsx)("div",{className:"flex flex-wrap gap-2","aria-label":l("capabilityCategories"),children:c.map(e=>(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-0.5 text-xs text-muted-foreground",children:e.label},e.label))}):null,e.capabilities.error?(0,n.jsx)("p",{className:"whitespace-pre-wrap break-words text-sm leading-5 text-status-warning",children:l("incompleteCapabilities",{error:(0,eJ.fD)(e.capabilities.error,o)})}):null,s?(0,n.jsxs)("div",{className:"flex items-center gap-2 py-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),l("loadingFullDetails")]}):r?(0,n.jsxs)("div",{className:"flex items-start gap-2",role:"alert",children:[(0,n.jsx)("p",{className:"min-w-0 flex-1 break-words text-sm text-destructive",children:r}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",onClick:a,children:[(0,n.jsx)(es.A,{"data-icon":"inline-start"}),l("retry")]})]}):t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(tm,{detail:t}),(0,n.jsx)(th,{detail:t})]}):null,(0,n.jsx)(td,{capabilities:e.capabilities}),(0,n.jsx)(tg,{capabilities:e.capabilities,browserContributions:i})]})}var tx=s(76782),tb=s(44980);function tv({className:e,size:t="default",...s}){return(0,n.jsx)(tx.l,{"data-slot":"switch","data-size":t,className:(0,C.cn)("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",e),...s,children:(0,n.jsx)(tb.p,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"})})}function tw({plugin:e,displayName:t,browserError:s,disabled:r,pending:i,browserRetryPending:a,onAction:l}){let{t:o}=(0,b.Bd)("pluginManagement"),c=e.operation?.phase,d="disabled"!==e.status;return(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-3",children:[i?(0,n.jsxs)("span",{role:"status",className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:["waiting"!==c?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):null,o(c&&"failed"!==c?`phase_${c}`:"submitting")]}):e.updateAvailable&&"extension"!==e.kind&&"failed"!==c?(0,n.jsx)(I.$,{size:"sm",disabled:r,onClick:()=>l("update"),children:o("update")}):null,"failed"===c?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||i,onClick:()=>l("retry"),children:o("retry")}):"failed"===e.status?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||i,onClick:()=>l("reload"),children:o("reloadOne")}):s&&e.pluginName?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||a,onClick:()=>l("retry-browser"),children:o("retryView")}):null,(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(tv,{checked:d,"aria-label":o("togglePlugin",{name:t}),disabled:r||i,onCheckedChange:e=>l(e?"enable":"disable")}),o(d?"enabled":"disabled")]}),"extension"!==e.kind?(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive","aria-label":o("removeNamed",{name:t}),title:o("remove"),disabled:r||i,onClick:()=>l("remove"),children:(0,n.jsx)(et.A,{})}):null]})}function ty({plugin:e,requestError:t,browserError:s}){let{t:r}=(0,b.Bd)("pluginManagement"),{locale:i}=(0,eQ.i)(),a=e.operation?.phase,l=[t,"failed"===a?e.operation?.message:null,e.error?(0,eJ.fD)(e.error.message,i):null,s,e.updateError?r("itemCheckFailed",{error:e.updateError}):null].filter((e,t,s)=>!!e&&s.indexOf(e)===t);return l.length||"waiting"===a||"failed"===e.status?(0,n.jsxs)("div",{className:"space-y-1",children:[l.map(e=>(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive [overflow-wrap:anywhere]",children:e},e)),l.length||"failed"!==e.status?null:(0,n.jsx)("p",{className:"text-sm text-destructive",children:r("notLoaded")}),"waiting"===a&&e.operation?.message?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operation.message}):null]}):null}function tk(e){let t=e.startsWith("npm:")?e.slice(4):e,s=/^((?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*)(?:@([^\s/]+))?$/i.exec(t);return s?{name:s[1],...s[2]?{version:s[2]}:{}}:null}function tj(e){return e.source.startsWith("npm:")?tk(e.source)?.name??e.source:e.pluginName??("extension"===e.kind?e.source.replaceAll("\\","/").split("/").at(-1):null)??e.source}function tN(e){return`source:${tk(e)?.name??e}`}function tI(e){switch(e.kind){case"batch":return"add"===e.input.action?"batchInstall":"update"===e.input.action?"updateSelected":"del"===e.input.action?"removeSelected":"setChannel";case"add":return"actionAdd";case"update":return"actionUpdate";case"del":return"actionDelete";case"enable":return"enable";case"disable":return"disable";case"reload":return"normal"===e.mode?"restartNormal":"actionReload"}}let tS=a.Yj().trim().min(1).max(128).regex(/^[a-zA-Z][a-zA-Z0-9._-]*$/),tC=a.Yj().trim().url().max(2048).refine(e=>{let t=new URL(e);return["https:","http:"].includes(t.protocol)&&!t.username&&!t.password&&!t.search&&!t.hash},"插件源必须是 HTTP 或 HTTPS 仓库地址"),tE=a.gM("mode",[a.Ik({mode:a.eu("auto")}).strict(),a.Ik({mode:a.eu("local")}).strict(),a.Ik({mode:a.eu("official")}).strict(),a.Ik({mode:a.eu("domestic")}).strict(),a.Ik({mode:a.eu("custom"),registry:tC}).strict()]),tM=a.Ik({description:a.Yj().trim().min(1).max(4e3).optional(),readme:a.Yj().trim().min(1).max(1024).optional()});a.Ik({description:a.Yj().optional(),piDesk:a.Ik({i18n:a.g1(a.Yj().min(1).max(35),tM).optional()}).passthrough().optional()}).passthrough();let tz=a.Ik({downloadSource:tE,recommendedRegistry:tC}).strict(),tA=a.Ik({downloadSource:tE}).strict(),t$=a.Ik({query:a.Yj().trim().max(200).default(""),page:a.ai().int().min(1).max(100).default(1),kind:a.k5(["all","desk","pi"]).default("all"),registry:tC.optional()}).strict(),tR=a.Ik({name:a.Yj().trim().min(1).max(214).regex(/^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/i),version:a.Yj().trim().min(1).max(128).optional(),registry:tC.optional()}).strict(),tP=a.Ik({name:a.Yj(),description:eJ.qf.nullable(),version:a.Yj(),publisher:a.Yj().nullable(),kind:a.k5(["desk","pi","unknown"]),official:a.zM(),registry:tC}).strict(),tD=a.Ik({items:a.YO(tP),hasMore:a.zM()}).strict(),tT=tP.extend({versions:a.YO(a.Yj()),readme:eJ.qf.nullable(),homepage:a.Yj().nullable(),repository:a.Yj().nullable(),compatible:a.zM().nullable(),compatibilityNote:a.Yj().nullable()}).strict();function tO({id:e,mode:t,registry:s,recommendedRegistry:r,savedRegistry:i,loading:a,saving:l,error:o,override:c,onMode:d,onRegistry:u,onSave:m,onRetry:p}){let{t:h}=(0,b.Bd)("pluginManagement"),g="auto"===t?r:"official"===t?"https://registry.npmjs.org":"domestic"===t?"https://mirrors.cloud.tencent.com/npm":"custom"===t?i??s:null,f=[...c?[{value:"default",label:h("useDefaultSource")}]:[],...["local","auto","domestic","official","custom"].map(e=>({value:e,label:h(`download_${e}`)}))];return(0,n.jsxs)("div",{className:"min-w-0 space-y-3 text-sm",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:e,className:"font-medium",children:h(c?"installDownloadSource":"downloadSource")}),(0,n.jsxs)(ea.l6,{value:t,items:f,disabled:a,onValueChange:e=>{e&&!l&&d(e)},children:[(0,n.jsx)(ea.bq,{id:e,className:"max-w-full",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:f.map(e=>(0,n.jsx)(ea.eb,{value:e.value,disabled:l,children:e.label},e.value))})]}),l?(0,n.jsx)("span",{role:"status",className:"text-muted-foreground",children:h("saving")}):null]}),"custom"===t?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:`${e}-url`,className:"block",children:h("registryUrl")}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(em.p,{id:`${e}-url`,type:"url",value:s,placeholder:"https://registry.example.com",className:"min-w-0 flex-1 basis-48",disabled:l,onChange:e=>u(e.target.value)}),m?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:l,onClick:m,children:h("save")}):null]})]}):!c&&g?(0,n.jsx)("p",{className:"break-all text-xs text-muted-foreground",children:g}):null,o?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:o}),p?(0,n.jsx)(I.$,{variant:"outline",size:"sm",onClick:p,children:h("retry")}):null]}):null]})}var tL=s(3058),tF=s(97724),tB=s(48742);function tq({className:e,...t}){return(0,n.jsx)(tF.y,{"data-slot":"checkbox",className:(0,C.cn)("peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",e),...t,children:(0,n.jsx)(tB.P,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none [&>svg]:size-3.5",children:(0,n.jsx)(ep.A,{})})})}function t_(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=e.snapshot?.plugins??[],i=t=>e.requests.has(tN(t.source))||!!(t.operation&&"failed"!==t.operation.phase),a=r.filter(t=>("updates"!==e.statusFilter||!!t.updateAvailable)&&("disabled"!==e.statusFilter||"disabled"===t.status)&&("failed"!==e.statusFilter||!!("failed"===t.status||t.operation?.phase==="failed"||t.updateError||t.pluginName&&e.browserErrors.has(t.pluginName)))&&`${tj(t)} ${t.description?(0,eJ.fD)(t.description,s):""}`.toLocaleLowerCase().includes(e.filter.trim().toLocaleLowerCase())),l=a.filter(e=>"extension"!==e.kind),o=r.filter(t=>e.selected.has(tN(t.source))),c=r.filter(e=>!0===e.updateAvailable&&"extension"!==e.kind&&!i(e)),d=c.filter(t=>e.selected.has(tN(t.source))),u=o.filter(e=>!i(e)),m=l.length>0&&l.every(t=>e.selected.has(tN(t.source))),p=l.some(t=>e.selected.has(tN(t.source))),h=["all","updates","disabled","failed"].map(e=>({value:e,label:t(`statusFilter_${e}`)}));return(0,n.jsxs)("section",{"aria-label":t("installed"),className:"flex min-h-0 min-w-0 flex-col gap-3",children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 bg-popover pb-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(em.p,{"aria-label":t("filterInstalled"),value:e.filter,onChange:t=>e.onFilter(t.target.value),placeholder:t("filterInstalled"),className:"min-w-40 flex-1 basis-52"}),(0,n.jsxs)(ea.l6,{value:e.statusFilter,items:h,onValueChange:t=>{t&&e.onStatusFilter(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("filterStatus"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:h.map(e=>(0,n.jsx)(ea.eb,{value:e.value,children:e.label},e.value))})]}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading||e.disabled,onClick:e.onRefresh,children:t(e.loading?"checkingUpdates":"checkUpdates")}),c.length>0?(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||e.loading,onClick:e.onUpdateAll,children:t("updateAll",{count:c.length})}):null,r.some(e=>"extension"!==e.kind)?(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:()=>e.onBatchMode(!e.batchMode),children:t(e.batchMode?"finishSelection":"batchManage")}):null]}),e.batchMode?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 rounded-lg bg-muted px-3 py-2",children:[(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,n.jsxs)("span",{className:"relative flex size-4 items-center justify-center",children:[(0,n.jsx)(tq,{checked:m,indeterminate:p&&!m,className:"data-indeterminate:[&_svg]:hidden",disabled:!l.length,onCheckedChange:t=>e.onSelect(l.map(e=>tN(e.source)),t)}),p&&!m?(0,n.jsx)(tL.A,{"aria-hidden":!0,className:"pointer-events-none absolute size-3.5"}):null]}),t(e.filter||"all"!==e.statusFilter?"selectFiltered":"selectAll")]}),(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("selectedCount",{count:o.length})}),o.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled||e.loading||!d.length,onClick:e.onUpdateSelected,children:t("updateSelected")}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled||!u.length,onClick:e.onRemoveSelected,children:t("removeSelected")}),(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:()=>e.onSelect([...e.selected],!1),children:t("clearSelection")})]}):null]}):null,e.errors.list?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.errors.list}):null]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto",children:e.loading&&!e.snapshot?(0,n.jsx)("p",{role:"status",className:"py-6 text-sm text-muted-foreground",children:t("loading")}):a.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:a.map(r=>{let a=tj(r),l=tN(r.source),o=r.pluginName?e.browserErrors.get(r.pluginName)??null:null;return(0,n.jsx)("article",{"aria-label":a,className:`min-w-0 px-4 py-3 ${e.selected.has(l)&&e.batchMode?"bg-accent/40":""}`,children:(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[e.batchMode&&"extension"!==r.kind?(0,n.jsx)("div",{className:"flex min-h-8 shrink-0 items-center",children:(0,n.jsx)(tq,{checked:e.selected.has(l),"aria-label":t("selectPlugin",{name:a}),onCheckedChange:t=>e.onSelect([l],t)})}):null,(0,n.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-1 basis-64 flex-wrap items-center gap-x-2 gap-y-1",children:[(0,n.jsx)(I.$,{variant:"link",className:"h-auto min-h-8 min-w-0 max-w-full justify-start p-0 text-left text-sm font-semibold whitespace-normal no-underline hover:underline [overflow-wrap:anywhere]","aria-label":t("viewDetails",{name:a}),onClick:()=>e.onDetail(r.source),children:a}),r.version?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",r.version]}):null,r.updateAvailable?(0,n.jsx)("span",{className:"inline-flex rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:r.availableVersion?t("newVersion",{version:r.availableVersion}):t("updateAvailable")}):null,r.updateTag&&"latest"!==r.updateTag?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:"dev"===r.updateTag?t("channelDev"):r.updateTag}):null]}),(0,n.jsx)(tw,{plugin:r,displayName:a,browserError:o,disabled:e.disabled,pending:i(r),browserRetryPending:e.requests.has(`entry:${r.pluginName}`),onAction:t=>e.onAction(r,t)})]}),r.description?(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:(0,eJ.fD)(r.description,s)}):null,(0,n.jsx)(ty,{plugin:r,browserError:o,requestError:e.errors[l]??e.errors[`entry:${r.pluginName}`]})]})]})},l)})}):(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:t(e.filter||"all"!==e.statusFilter?"noMatches":"empty")})})]})}function tW(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=new Map(e.snapshot?.plugins.filter(e=>e.source.startsWith("npm:")).map(e=>[tk(e.source)?.name,e]));return(0,n.jsxs)("section",{className:"min-w-0 space-y-4","aria-label":t("searchPlugins"),children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:"plugin-catalog-query",className:"sr-only",children:t("searchPlugins")}),(0,n.jsx)(em.p,{id:"plugin-catalog-query",value:e.query,placeholder:t("searchPlaceholder"),className:"min-w-40 flex-1 basis-56",maxLength:200,onChange:t=>e.onQuery(t.target.value),onCompositionStart:e.onCompositionStart,onCompositionEnd:e.onCompositionEnd}),(0,n.jsxs)(ea.l6,{value:e.searchSource,items:[{value:"public",label:t("publicNpm")},{value:"custom",label:t("customSearchSource")}],onValueChange:t=>{t&&e.onSearchSource(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("searchSource"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"public",children:t("publicNpm")}),(0,n.jsx)(ea.eb,{value:"custom",children:t("customSearchSource")})]})]}),(0,n.jsxs)(ea.l6,{value:e.kind,items:["all","desk","pi"].map(e=>({value:e,label:t(`kind_${e}`)})),onValueChange:t=>{t&&e.onKind(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("pluginKind"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:["all","desk","pi"].map(e=>(0,n.jsx)(ea.eb,{value:e,children:t(`kind_${e}`)},e))})]}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:e.onDirectInstall,children:t("directInstall")}),"custom"===e.searchSource?(0,n.jsxs)("div",{className:"w-full space-y-1",children:[(0,n.jsx)("label",{htmlFor:"plugin-search-registry",className:"block text-sm",children:t("searchRegistryUrl")}),(0,n.jsx)(em.p,{id:"plugin-search-registry",type:"url",value:e.registry,onChange:t=>e.onRegistry(t.target.value),placeholder:"https://registry.example.com"})]}):null]}),e.error?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 text-sm text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:e.error}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:e.onRetry,children:t("retry")})]}):null,e.items.length?(0,n.jsx)("div",{className:"@container/catalog divide-y rounded-lg border bg-card",children:e.items.map(i=>{let a=r.get(i.name),l=tN(`npm:${i.name}`),o=a?.description??i.description,c=!!(a?.operation&&"failed"!==a.operation.phase),d=e.requests.has(l)||c||e.preparing.has(i.name),u=a&&(a.operation?.action!=="add"||"failed"!==a.operation.phase),m=e.installErrors[i.name]??e.errors[l]??(a?.error?(0,eJ.fD)(a.error.message,s):null);return(0,n.jsxs)("article",{"aria-label":i.name,className:"grid min-w-0 gap-x-4 gap-y-2 px-4 py-3 @xl/catalog:grid-cols-[minmax(0,1fr)_auto]",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(I.$,{variant:"link",className:"h-auto min-h-8 min-w-0 max-w-full p-0 text-left text-sm font-semibold whitespace-normal no-underline hover:underline [overflow-wrap:anywhere]",onClick:()=>e.onDetail(i),children:i.name}),(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",u&&a.version?a.version:i.version]}),u&&a.updateAvailable?(0,n.jsx)("span",{className:"rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:a.availableVersion?t("newVersion",{version:a.availableVersion}):t("updateAvailable")}):null,(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`kind_${i.kind}`)}),i.publisher?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:i.publisher}):null]}),(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:o?(0,eJ.fD)(o,s):t("noPluginDescription")})]}),(0,n.jsx)("div",{className:"flex min-h-8 items-center self-start @xl/catalog:justify-end",children:d?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:c?t(`phase_${a?.operation?.phase}`):e.preparing.has(i.name)?t("loadingPackage"):t("submitting")}):u?(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),a.updateAvailable?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onUpdate(a.source),children:t("update")}):null]}):(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onInstall(i),children:t("install")})}),m?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere] @xl/catalog:col-span-2",children:m}):null,a?.operation?.phase==="failed"&&a.operation.message?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere] @xl/catalog:col-span-2",children:a.operation.message}):null]},i.name)})}):null,e.loading?(0,n.jsx)("p",{role:"status",className:"py-4 text-sm text-muted-foreground",children:t("searching")}):e.error||!e.searched||e.items.length?null:(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:t("noSearchResults")}),e.hasMore?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onMore,children:t("loadMore")}):null]})}let tY=(0,e2.F)("flex w-fit items-stretch *:focus-visible:relative *:focus-visible:z-10 has-[>[data-slot=button-group]]:gap-2 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-lg [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1",{variants:{orientation:{horizontal:"*:data-slot:rounded-r-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-r-lg! [&>[data-slot]~[data-slot]]:rounded-l-none [&>[data-slot]~[data-slot]]:border-l-0",vertical:"flex-col *:data-slot:rounded-b-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-b-lg! [&>[data-slot]~[data-slot]]:rounded-t-none [&>[data-slot]~[data-slot]]:border-t-0"}},defaultVariants:{orientation:"horizontal"}});function tV({className:e,orientation:t,...s}){return(0,n.jsx)("div",{role:"group","data-slot":"button-group","data-orientation":t,className:(0,C.cn)(tY({orientation:t}),e),...s})}var tU=s(32892),tH=s(57445),tK=s(73028),tG=s(48318),tJ=s(93356),tQ=s(10508);let tX=({className:e,from:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("group flex w-full max-w-[95%] flex-col gap-2","user"===t?"is-user ml-auto justify-end":"is-assistant",e),...s}),tZ=({children:e,className:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("flex w-fit min-w-0 max-w-full flex-col gap-2 overflow-hidden text-base leading-[1.8]","group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground","group-[.is-assistant]:text-foreground",t),...s,children:e}),t0=({tooltip:e,children:t,label:s,variant:r="ghost",size:i="icon-sm",...a})=>{let l=(0,n.jsxs)(I.$,{size:i,type:"button",variant:r,...a,children:[t,(0,n.jsx)("span",{className:"sr-only",children:s||e})]});return e?(0,n.jsx)(tU.Bc,{children:(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:l}),(0,n.jsx)(tU.ZI,{children:(0,n.jsx)("p",{children:e})})]})}):l},t1={cjk:tH.h,code:tK.a,math:tG.D,mermaid:tJ.a},t2=(0,r.memo)(({className:e,...t})=>(0,n.jsx)(tQ.jH,{className:(0,C.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),plugins:t1,...t}),(e,t)=>e.children===t.children&&t.isAnimating===e.isAnimating);t2.displayName="MessageResponse";let t5=({className:e,children:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("mt-4 flex w-full items-center justify-between gap-4",e),...s,children:t});function t3({readme:e}){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),[i,a]=(0,r.useState)(null),l=e&&"string"!=typeof e?e.translations:{},o=Object.keys(l).filter(e=>/^(zh(?:-|$)|en(?:-|$))/.test(e)),c=i&&void 0!==l[i]?i:null,d=e?c?l[c]:(0,eJ.fD)(e,s):null;return(0,n.jsxs)("section",{className:"min-w-0 space-y-3","aria-label":t("readme"),children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:t("readme")}),o.length>0?(0,n.jsxs)("div",{className:"flex items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("readmeLanguage")}),(0,n.jsxs)(ea.l6,{value:c??"",onValueChange:e=>a(e||null),children:[(0,n.jsx)(ea.bq,{"aria-label":t("readmeLanguage"),children:(0,n.jsx)(ea.yv,{children:c?c.startsWith("zh")?"中文":"English":t("defaultLanguage")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"",children:t("defaultLanguage")}),o.map(e=>(0,n.jsx)(ea.eb,{value:e,children:e.startsWith("zh")?"中文":"English"},e))]})]})]}):null]}),d?(0,n.jsx)("div",{className:"min-w-0 overflow-x-auto text-base leading-relaxed [overflow-wrap:anywhere]",children:(0,n.jsx)(t2,{mode:"static",isAnimating:!1,skipHtml:!0,controls:!1,className:"min-w-0 [&_img]:max-w-full [&_pre]:overflow-x-auto",children:d})}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:t("noReadme")})]})}function t4({value:e,label:t,placeholder:s,disabled:r,onChange:i}){let{t:a}=(0,b.Bd)("pluginManagement"),l=[...s?[{value:"",label:s}]:[],{value:"latest",label:a("channelLatest")},{value:"dev",label:a("channelDev")},...e&&!["latest","dev"].includes(e)?[{value:e,label:e}]:[]];return(0,n.jsxs)(ea.l6,{value:e,items:l,onOpenChange:(e,t)=>{e&&r&&t.cancel()},onValueChange:e=>{null===e||r||i(e)},children:[(0,n.jsx)(ea.bq,{"aria-label":t,"aria-disabled":r,className:"max-w-full aria-disabled:opacity-50",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:l.map(e=>(0,n.jsx)(ea.eb,{value:e.value,disabled:r,children:e.label},e.value))})]})}function t6(e){if(!e)return null;try{let t=new URL(e);return["https:","http:"].includes(t.protocol)?t.href:null}catch{return null}}function t8(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=e.detail,i=e.installed&&e.installedVersion===r.version,a=t6(r.homepage),l=t6(r.repository),o=[...new Set([r.version,...r.versions])];return(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:["v",r.version]}),(0,n.jsx)("span",{children:t(`kind_${r.kind}`)}),r.publisher?(0,n.jsx)("span",{className:"[overflow-wrap:anywhere]",children:r.publisher}):null]}),r.description?(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:(0,eJ.fD)(r.description,s)}):null,!1===r.compatible?(0,n.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:[t("incompatible"),r.compatibilityNote?` \xb7 ${r.compatibilityNote}`:""]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[e.pending?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:e.operationMessage??t("submitting")}):i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),e.updateAvailable?(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled,onClick:e.onUpdate,children:t("update")}):null]}):(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||!1===r.compatible,onClick:e.onInstall,children:t(e.installed?"installVersion":"install")}),a?(0,n.jsx)("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"text-sm underline underline-offset-4",children:t("homepage")}):null,l?(0,n.jsx)("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"text-sm underline underline-offset-4",children:t("repository")}):null]}),e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.error}):null]}),(0,n.jsxs)(eV.Nt,{className:"rounded-lg border",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between px-3 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"space-y-3 px-3 pb-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(t4,{value:e.channel,label:t("installChannel"),placeholder:t("defaultChannel"),disabled:e.pending,onChange:e.onChannel}),(0,n.jsxs)(ea.l6,{value:r.version,items:o.map(e=>({value:e,label:e})),onOpenChange:(t,s)=>{t&&e.pending&&s.cancel()},onValueChange:t=>{t&&!e.pending&&e.onVersion(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("version"),"aria-disabled":e.pending,children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:o.map(t=>(0,n.jsx)(ea.eb,{value:t,disabled:e.pending,children:t},t))})]})]}),(0,n.jsx)(tO,{id:"plugin-detail-download",mode:e.downloadMode,registry:e.downloadRegistry,override:!0,saving:e.pending,onMode:e.onDownloadMode,onRegistry:e.onDownloadRegistry})]})})]}),(0,n.jsx)("div",{className:"border-t pt-4",children:(0,n.jsx)(t3,{readme:r.readme},`${r.name}@${r.version}`)})]})}var t7=s(68017);function t9(e){let{t}=(0,b.Bd)("pluginManagement");return(0,n.jsxs)("section",{"aria-label":t("directInstall"),className:"min-w-0 space-y-3 rounded-lg border bg-card p-4",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:t("directInstall")}),(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:e.onClose,children:t("close")})]}),(0,n.jsx)("label",{htmlFor:"plugin-direct-source",className:"block text-sm font-medium",children:t("source")}),(0,n.jsx)(t7.T,{id:"plugin-direct-source",value:e.source,placeholder:t("batchSourcePlaceholder"),rows:2,disabled:e.pending,onChange:t=>e.onSource(t.target.value)}),e.isNpm||e.multiple?(0,n.jsxs)(eV.Nt,{children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-8 items-center gap-2 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"space-y-3 pt-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(t4,{value:e.tag,label:t("installChannel"),placeholder:t("defaultChannel"),disabled:e.pending,onChange:e.onTag})]}),e.isNpm?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onRead,children:t(e.loading?"loadingPackage":"readPackage")}):null,e.detail?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.detail.name}),(0,n.jsxs)(ea.l6,{value:e.selectedVersion,onOpenChange:(t,s)=>{t&&(e.loading||e.pending)&&s.cancel()},items:[{value:"",label:t("automaticVersion")},...[...new Set([e.detail.version,...e.detail.versions])].map(e=>({value:e,label:e}))],onValueChange:t=>{null===t||e.loading||e.pending||e.onVersion(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("version"),"aria-disabled":e.loading||e.pending,className:"max-w-full",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"",disabled:e.loading||e.pending,children:t("automaticVersion")}),[...new Set([e.detail.version,...e.detail.versions])].map(t=>(0,n.jsx)(ea.eb,{value:t,disabled:e.loading||e.pending,children:t},t))]})]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t("targetVersion",{version:e.detail.version})})]}):null,(0,n.jsx)(tO,{id:"plugin-direct-download",mode:e.override,registry:e.registry,override:!0,saving:e.pending,onMode:e.onMode,onRegistry:e.onRegistry})]})})]}):null,e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm whitespace-pre-wrap text-destructive [overflow-wrap:anywhere]",children:e.error}):null,e.operationMessage?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operationMessage}):null,(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||e.loading||e.pending||!e.source.trim(),onClick:e.onInstall,children:t(e.pending?"installing":e.multiple?"batchInstall":"install")})]})}function se({confirmation:e,onClose:t,onConfirm:s}){let{t:r}=(0,b.Bd)("pluginManagement"),i=e?r(tI(e)):null,a=e?.kind==="del"||e?.kind==="batch"&&"del"===e.input.action,l=e?.kind==="add"||e?.kind==="batch"&&"add"===e.input.action;return(0,n.jsx)(eN.YV,{open:!!e,onOpenChange:e=>{e||t()},children:(0,n.jsxs)(eN.hA,{className:"z-[150] max-w-lg",backdropClassName:"z-[140]",children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:r("confirmAction",{action:i})}),(0,n.jsx)(eN.uX,{children:r(a?"removeDescription":l?"thirdPartyDescription":e?.kind==="reload"?"normal"===e.mode?"restartNormalDescription":"restartDescription":"confirmChange")})]}),(0,n.jsx)(eN._Y,{className:"min-h-0",children:(0,n.jsx)("div",{className:"min-w-0 p-4 pt-0",children:e?.kind==="batch"?(0,n.jsx)("ul",{className:"space-y-2 text-sm",children:("add"===e.input.action?e.input.items.map(e=>e.source):e.input.sources).map(e=>(0,n.jsx)("li",{className:"font-medium [overflow-wrap:anywhere]",children:e.startsWith("npm:")?tk(e)?.name??e:e},e))}):e?.kind==="add"?(0,n.jsxs)("dl",{className:"space-y-3 text-sm",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("packageName")}),(0,n.jsx)("dd",{className:"mt-1 font-medium [overflow-wrap:anywhere]",children:e.package?.name??e.input.source})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("version")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.package?.version??tk(e.input.source)?.version??r("fromSource")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("publisher")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.package?.publisher??r("unknownPublisher")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("source")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.input.registry??e.package?.registry??e.input.source})]})]}):e&&"reload"!==e.kind?(0,n.jsx)("p",{className:"text-sm font-medium [overflow-wrap:anywhere]",children:e.source.startsWith("npm:")?tk(e.source)?.name??e.source:e.source}):null})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:t,children:r("cancel")}),(0,n.jsx)(I.$,{size:"sm",variant:a?"destructive":"default",onClick:()=>{e&&s(e)},children:i})]})]})})}function st({basicMode:e=!1,snapshot:t,biz:s,onSnapshot:i,onRestartScheduled:a}){let{t:l}=(0,b.Bd)("pluginManagement"),{locale:o}=(0,eQ.i)(),[c,d]=(0,r.useState)("installed"),[u,m]=(0,r.useState)(""),[p,h]=(0,r.useState)("all"),[g,f]=(0,r.useState)(!1),[x,v]=(0,r.useState)(()=>new Set);(0,r.useEffect)(()=>{if(!t)return;let e=new Set(t.plugins.map(e=>tN(e.source)));[...x].some(t=>!e.has(t))&&queueMicrotask(()=>v(t=>new Set([...t].filter(t=>e.has(t)))))},[t,x]);let[w,y]=(0,r.useState)(""),[k,j]=(0,r.useState)(!1),N=function({basicMode:e=!1,biz:t,snapshot:s,onSnapshot:n,onRestartScheduled:i}){let{t:a}=(0,b.Bd)("pluginManagement"),l=(0,Q.t4)();(0,Q.So)();let[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(()=>new Set),m=(0,r.useRef)(new Set),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)({}),[x,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(null),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(null),S=(0,r.useRef)(0),C=(0,r.useRef)(0),E=(0,r.useRef)(!0),M=(e,t)=>{t?m.current.add(e):m.current.delete(e),E.current&&u(new Set(m.current))},z=(e,t)=>{E.current&&f(s=>{let n={...s};return t?n[e]=t:delete n[e],n})},A=e=>{let t=tN(e);return m.current.has(t)||!!s?.plugins.some(e=>tN(e.source)===t&&e.operation&&"failed"!==e.operation.phase)},$=async(e=!1)=>{let s=++C.current,r=await t.list(e);E.current&&s===C.current&&n(r)},R=async(e,t)=>{if(m.current.has("check"))return;let n=e??s?.plugins.filter(e=>"package"===e.kind&&(!t||e.updateTag===t)).map(e=>e.source)??[],r=n.filter(A),i=n.filter(e=>!A(e));if(r.forEach(e=>z(tN(e),a("sourceBusy"))),!i.length)return;let l=i.map(tN);M("check",!0),l.forEach(e=>M(e,!0)),c(!0),z("list",null);try{if(e||r.length)for(let e=0;e<i.length&&(await $({checkUpdates:!0,sources:i.slice(e,e+32),...t?{tag:t}:{}}),E.current);e+=32);else await $({checkUpdates:!0,...t?{tag:t}:{}})}catch(e){z("list",e instanceof Error?e.message:a("updateCheckFailed"))}finally{M("check",!1),l.forEach(e=>M(e,!1)),E.current&&c(!1)}};(0,r.useEffect)(()=>{E.current=!0;let s=!0,r=++C.current;return queueMicrotask(()=>{s&&(c(!0),t.list(!1).then(async i=>{if(!s||r!==C.current)return;n(i);let a=i.plugins.some(e=>"package"===e.kind&&/^(npm:|git:|https?:|git@)/.test(e.source)&&null===e.updateAvailable&&!e.updateError&&!e.operation);if(!e&&a){let e=await t.list(!0);s&&r===C.current&&n(e)}}).catch(e=>{s&&z("list",e instanceof Error?e.message:a("updateCheckFailed"))}).finally(()=>{s&&c(!1)}))}),()=>{s=!1,E.current=!1,S.current+=1,C.current+=1}},[t,n,a,e]);let P=async e=>{let s="add"===e.action?e.items.map(e=>e.source):e.sources,r=s.filter(e=>!A(e));if(s.filter(A).forEach(e=>z(tN(e),a("sourceBusy"))),!r.length)return;let i=r.map(tN);i.forEach(e=>{M(e,!0),z(e,null)}),h(null);let l=[...r];try{let s=await t.list(),r=Date.now()+9e5;for(;l.length;){let i=s.plugins.filter(e=>e.operation&&"failed"!==e.operation.phase),o="tag"===e.action?32:Math.max(0,32-i.length);if(!o){if(i.some(e=>e.operation?.phase==="waiting")||Date.now()>=r){l.forEach(e=>z(tN(e),a("batchWaiting")));break}await new Promise(e=>setTimeout(e,750)),s=await t.list(),E.current&&(C.current+=1,n(s));continue}let c=l.slice(0,o),d="add"===e.action?{...e,items:e.items.filter(e=>c.includes(e.source))}:{...e,sources:c},u=await t.batch(d);s=u.snapshot,E.current&&(C.current+=1,n(s)),u.results.forEach(e=>z(tN(e.source),e.error)),c.forEach(e=>M(tN(e),!1)),l=l.slice(c.length)}}catch(t){let e=t instanceof Error?t.message:a("batchFailed");l.forEach(t=>z(tN(t),e))}finally{i.forEach(e=>M(e,!1))}},D=async e=>{if("batch"===e.kind)return void await P(e.input);if("reload"!==e.kind&&A("add"===e.kind?e.input.source:e.source))return;let s="reload"===e.kind?"reload":tN("add"===e.kind?e.input.source:e.source);if(!m.current.has(s)){M(s,!0),h(null),z(s,null);try{let s="add"===e.kind?await t.add(e.input):"update"===e.kind?await t.update(e.source):"del"===e.kind?await t.del(e.source):"enable"===e.kind||"disable"===e.kind?await t.setEnabled(e.source,"enable"===e.kind):await t.reload(e.mode);if(!E.current)return;C.current+=1,n(s),"reload"===e.kind?i():await $()}catch(t){z(s,t instanceof Error?t.message:a("actionFailed",{action:a(tI(e))}))}finally{M(s,!1)}}},T=(e,t)=>{let s={kind:"add",input:e,package:t};t?.official===!0?D(s):h(s)},O=async e=>{let s=e?.[0]?tN(e[0]):"apply";if(!m.current.has(s)){M(s,!0),z(s,null);try{let s=await t.apply(e);E.current&&(C.current+=1,n(s),await $())}catch(e){z(s,e instanceof Error?e.message:a("actionFailed",{action:a("reloadOne")}))}finally{M(s,!1)}}},L=async(e,t)=>{if(!m.current.has(e)){M(e,!0),z(e,null);try{await t()}catch(t){z(e,t instanceof Error?t.message:a("retryFailed"))}finally{M(e,!1)}}},F=async e=>{let s=++S.current;j(!0),I(null);try{let n=await t.get(e);E.current&&s===S.current&&y(n)}catch(e){E.current&&s===S.current&&I(e instanceof Error?e.message:a("detailFailed"))}finally{E.current&&s===S.current&&j(!1)}};return{loading:o,requests:d,confirmation:p,setConfirmation:h,errors:g,detailSource:x,detail:w,detailLoading:k,detailError:N,pluginHost:l,refresh:R,executeBatch:P,execute:D,requestInstall:T,applyChanges:O,loadDetail:F,openDetail:e=>{v(e),y(null),F(e)},closeDetail:()=>{S.current+=1,v(null),y(null),I(null),j(!1)},handleControlAction:(e,t)=>{switch(t){case"reload":O([e.source]);break;case"update":D({kind:"update",source:e.source});break;case"remove":h({kind:"del",source:e.source});break;case"enable":case"disable":D({kind:t,source:e.source});break;case"retry-browser":e.pluginName&&L(`entry:${e.pluginName}`,()=>l.retryEntry(e.pluginName));break;case"retry":{let t=e.operation?.action;"apply"===t?O([e.source]):"add"===t?T({source:e.source}):t&&D({kind:t,source:e.source})}}},refreshEntries:()=>L("entries",()=>l.refreshEntries())}}({biz:s,snapshot:t,onSnapshot:i,onRestartScheduled:a,basicMode:e}),S=function(e,t){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(""),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)("all"),[d,u]=(0,r.useState)("public"),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)([]),[f,x]=(0,r.useState)(!1),[v,w]=(0,r.useState)(1),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(null),[I,S]=(0,r.useState)(!1),[C,E]=(0,r.useState)(null),[M,z]=(0,r.useState)(null),[A,$]=(0,r.useState)(!1),[R,P]=(0,r.useState)(null),[D,T]=(0,r.useState)(()=>new Set),[O,L]=(0,r.useState)({}),F=(0,r.useRef)(0),B=(0,r.useRef)(0),q=(0,r.useRef)(new Set),_=(0,r.useRef)(null),[W,Y]=(0,r.useState)(!1),[V,U]=(0,r.useState)("default"),[H,K]=(0,r.useState)(""),G=(0,r.useRef)(!0);(0,r.useEffect)(()=>(G.current=!0,()=>{G.current=!1,F.current+=1,B.current+=1}),[]);let J=(0,r.useCallback)(async(t,n)=>{k(!0),N(null);try{let s=await e.searchCatalog(t);if(!G.current||n!==F.current)return;g(e=>{let n=1===t.page?s.items:[...e,...s.items],r=e=>e.official?0:"desk"===e.kind?1:"pi"===e.kind?2:3;return[...new Map(n.map(e=>[e.name,e])).values()].sort((e,t)=>r(e)-r(t))}),w(t.page),x(s.hasMore),S(!0)}catch(e){G.current&&n===F.current&&N(e instanceof Error?e.message:s("searchFailed"))}finally{G.current&&n===F.current&&k(!1)}},[e,s]);(0,r.useEffect)(()=>{t&&queueMicrotask(()=>Y(!0))},[t]),(0,r.useEffect)(()=>{if(!W||a)return;let e=++F.current;_.current=null,queueMicrotask(()=>{G.current&&e===F.current&&(k(!0),N(null),x(!1))});let t=setTimeout(()=>{let t="custom"===d?tC.safeParse(m):null;if(t&&!t.success){_.current=null,g([]),x(!1),S(!1),N(s("invalidRegistry")),k(!1);return}let r={query:n.trim(),kind:o,page:1,...t?.success?{registry:t.data}:{}};_.current=r,g([]),x(!1),S(!1),J(r,e)},300);return()=>clearTimeout(t)},[n,o,d,m,a,J,W,s]);let Q=async(t,n=t.version)=>{let r=++B.current;$(!0),P(null),L(e=>{let s={...e};return delete s[t.name],s});try{let s=await e.getCatalog({name:t.name,registry:t.registry,version:n});G.current&&r===B.current&&z(s)}catch(e){G.current&&r===B.current&&P(e instanceof Error?e.message:s("detailFailed"))}finally{G.current&&r===B.current&&$(!1)}};return{query:n,setQuery:i,composing:a,beginComposition:()=>{F.current+=1,_.current=null,k(!1),l(!0)},endComposition:()=>l(!1),kind:o,setKind:c,searchSource:d,setSearchSource:u,registry:m,setRegistry:p,items:h,loading:y,error:j,searched:I,hasMore:f,loadMore:()=>{_.current&&!y&&f&&J({..._.current,page:v+1},F.current)},retry:()=>{if(a||y)return;let e="custom"===d?tC.safeParse(m):null;if(e&&!e.success)return void N(s("invalidRegistry"));let t={query:n.trim(),kind:o,page:1,...e?.success?{registry:e.data}:{}};_.current=t,g([]),J(t,++F.current)},selection:C,detail:M,detailLoading:A,detailError:R,openDetail:e=>{E(e),z(null),U("default"),K(""),Q(e)},closeDetail:()=>{B.current+=1,E(null),z(null),$(!1),P(null)},loadDetail:Q,prepareInstall:async(t,n)=>{if(!q.current.has(t.name)){q.current.add(t.name),T(new Set(q.current)),L(e=>{let s={...e};return delete s[t.name],s});try{let r=await e.getCatalog({name:t.name,version:t.version,registry:t.registry});if(!G.current)return;if(!1===r.compatible)return void L(e=>({...e,[t.name]:s("installIncompatible")}));n(r)}catch(e){G.current&&L(n=>({...n,[t.name]:e instanceof Error?e.message:s("detailFailed")}))}finally{q.current.delete(t.name),G.current&&T(new Set(q.current))}}},preparing:D,installErrors:O,downloadMode:V,setDownloadMode:U,downloadRegistry:H,setDownloadRegistry:K,installDetail:e=>{if(!M||A)return;if(!1===M.compatible)return void L(e=>({...e,[M.name]:s("installIncompatible")}));let t="default"===V?null:tE.safeParse("custom"===V?{mode:V,registry:H}:{mode:V});t&&!t.success?L(e=>({...e,[M.name]:s("invalidRegistry")})):(L(e=>{let t={...e};return delete t[M.name],t}),e({source:`npm:${M.name}@${M.version}`,registry:M.registry,...t?.success?{downloadSource:t.data}:{}},M))}}}(s,"search"===c),C=function(e,t){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(null),[a,l]=(0,r.useState)("auto"),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(!1),[h,g]=(0,r.useState)(null),f=(0,r.useRef)(!0),x=(0,r.useRef)(!1),v=(0,r.useRef)(0),w=(0,r.useRef)("load"),y=async()=>{let t=v.current;u(!0),g(null);try{let s=await e.getCatalogSettings();if(!f.current)return;t===v.current?(i(s),l(s.downloadSource.mode),"custom"===s.downloadSource.mode&&c(s.downloadSource.registry)):i(e=>e??s)}catch(e){w.current="load",f.current&&g(e instanceof Error?e.message:s("settingsFailed"))}finally{f.current&&u(!1)}};(0,r.useEffect)(()=>{f.current=!0;let e=!0;return queueMicrotask(()=>{e&&y()}),()=>{e=!1,f.current=!1}},[e]);let k=async(n=a)=>{if(x.current)return;let r=tE.safeParse("custom"===n?{mode:n,registry:o}:{mode:n});if(!r.success){w.current="save",g(s("invalidRegistry"));return}x.current=!0,p(!0),g(null);try{let s=await e.saveCatalogSettings(r.data);f.current&&(i(s),l(s.downloadSource.mode),t())}catch(e){w.current="save",f.current&&g(e instanceof Error?e.message:s("settingsFailed"))}finally{x.current=!1,f.current&&p(!1)}};return{settings:n,mode:a,registry:o,setRegistry:e=>{v.current+=1,c(e)},loading:d,saving:m,error:h,load:y,save:k,changeMode:e=>{v.current+=1,l(e),"custom"!==e&&k(e)},retry:()=>"save"===w.current?k():y()}}(s,()=>{e||N.refresh()}),E=function(e,t=[]){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(""),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(null),[v,w]=(0,r.useState)("default"),[y,k]=(0,r.useState)(""),j=(0,r.useRef)(0),N=(0,r.useRef)(!0),I=a.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),S=1===I.length?tk(I[0]):null;(0,r.useEffect)(()=>(N.current=!0,()=>{N.current=!1,j.current+=1}),[]);let C=()=>{j.current+=1,p(null),g(!1),x(null)},E=async n=>{let r;if(!S)return null;void 0!==n&&u(n||null);let i=t.find(e=>tk(e.source)?.name===S.name)?.updateTag,a=S.version??(o||i||"latest"),l=""===n?a:n??d??a;if("custom"===v){let e=tC.safeParse(y);if(!e.success)return x(s("invalidRegistry")),null;r=e.data}else"official"===v?r="https://registry.npmjs.org":"domestic"===v&&(r="https://registry.npmmirror.com");let c=++j.current;g(!0),p(null),x(null);try{let t=await e.getCatalog({...S,...l?{version:l}:{},...r?{registry:r}:{}});if(!N.current||c!==j.current)return null;return p(t),t}catch(e){return N.current&&c===j.current&&x(e instanceof Error?e.message:s("detailFailed")),null}finally{N.current&&c===j.current&&g(!1)}},M=async(e,t)=>{if(!I.length||h)return;x(null);let n="default"===v?null:tE.safeParse("custom"===v?{mode:v,registry:y}:{mode:v});if(n&&!n.success)return void x(s("invalidRegistry"));let r={...o?{tag:o}:{},...n?.success?{downloadSource:n.data}:{}};if(I.length>1){let e=I.map(tk);if(I.length>32||e.some(e=>!e))return void x(s(I.length>32?"batchLimit":"batchNpmOnly"));let n=new Map;return e.forEach(e=>{e&&n.set(e.name,{source:`npm:${e.name}${e.version?`@${e.version}`:""}`,...r})}),void t([...n.values()])}if(!S)return void e({source:I[0]});let i=m?Promise.resolve(m):E(d??void 0),a=j.current,l=await i;if(l&&N.current&&a===j.current){if(!1===l.compatible)return void x(s("installIncompatible"));e({source:`npm:${l.name}${d||S.version?`@${d??S.version}`:""}`,registry:l.registry,...r},l)}};return{open:n,setOpen:i,source:a,sources:I,tag:o,selectedVersion:d??"",setTag:e=>{C(),u(null),c(e)},changeSource:e=>{C(),u(null),l(e)},spec:S,detail:m,loading:h,error:f,override:v,setOverride:e=>{C(),w(e)},registry:y,setRegistry:e=>{C(),k(e)},loadDetail:E,install:M}}(s,t?.plugins),M=e||N.requests.has("reload"),z=new Map(N.pluginHost.getFailedEntries().map(e=>[e.pluginName,e.error.message])),$=N.pluginHost.getEntryListError(),R=t?.plugins.find(e=>e.source===N.detailSource),P=S.selection?t?.plugins.find(e=>e.source.startsWith("npm:")&&tk(e.source)?.name===S.selection?.name):void 0,D=S.selection?tN(`npm:${S.selection.name}`):"",T=tN(E.detail?`npm:${E.detail.name}`:E.spec?`npm:${E.spec.name}`:E.source.trim()),O=t?.plugins.find(e=>tN(e.source)===T),L=e=>{let s=t?.plugins.find(t=>tN(t.source)===tN(e));return N.requests.has(tN(e))||!!(s?.operation&&"failed"!==s.operation.phase)},F=L(`npm:${S.selection?.name??""}`),B=E.sources.some(L),q=E.sources.map(e=>{let s=tN(e),n=t?.plugins.find(e=>tN(e.source)===s),r=N.errors[s]??(n?.operation?.phase==="failed"?n.operation.message:null);return r?`${e}: ${r}`:null}).filter(Boolean).join("\n"),_=!!(N.detailSource||S.selection),W=(0,r.useRef)(null),Y=(0,r.useRef)(null);(0,r.useEffect)(()=>{_?W.current?.focus():Y.current?.isConnected&&(Y.current.focus(),Y.current=null)},[_]);let V=()=>{Y.current=document.activeElement instanceof HTMLElement?document.activeElement:null},U=e=>{let s=t?.plugins.find(t=>tk(t.source)?.name===e.name);return{...e,version:s?.updateTag??"latest"}},H=e=>t?.plugins.filter(t=>"extension"!==t.kind&&!0===t.updateAvailable&&!L(t.source)&&(!e||x.has(tN(t.source)))).map(e=>e.source)??[],K=e=>e?l(`phase_${e}`):null,G=()=>{d("installed"),E.setOpen(!0)};return(0,n.jsxs)("div",{className:"flex h-full min-h-0 min-w-0 flex-col",children:[(0,n.jsxs)("header",{className:"shrink-0 space-y-3 border-b p-4 sm:px-6",children:[_?(0,n.jsxs)(I.$,{ref:W,size:"sm",variant:"ghost",className:"-ml-2",onClick:()=>{N.closeDetail(),S.closeDetail()},children:[(0,n.jsx)(A.A,{}),l("backToList")]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h2",{className:"min-w-0 text-xl font-semibold [overflow-wrap:anywhere]",children:_?R?tj(R):S.selection?.name??l("details"):l("title")}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[_?null:(0,n.jsxs)(eW.AM,{children:[(0,n.jsxs)(eW.Wv,{render:(0,n.jsx)(I.$,{size:"sm",variant:"ghost"}),children:[l("downloadSource"),":",C.loading&&!C.settings?l("loading"):l(`download_${C.settings?.downloadSource.mode??C.mode}`),(0,n.jsx)(eY.A,{className:"size-4"})]}),(0,n.jsx)(eW.hl,{align:"end",positionerClassName:"z-[150]",className:"w-80 max-w-[calc(100vw-2rem)]",children:(0,n.jsx)(tO,{id:"plugin-default-download",mode:C.mode,registry:C.registry,savedRegistry:C.settings?.downloadSource.mode==="custom"?C.settings.downloadSource.registry:void 0,recommendedRegistry:C.settings?.recommendedRegistry,loading:C.loading,saving:C.saving,error:C.error,onMode:e=>{"default"!==e&&C.changeMode(e)},onRegistry:C.setRegistry,onSave:()=>void C.save(),onRetry:()=>void C.retry()})})]}),e||t?.restartRequired?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:N.requests.has("reload"),onClick:()=>N.setConfirmation({kind:"reload",mode:e?"normal":void 0}),children:l(e?"restartNormal":"restartApply")}):null]})]}),e?(0,n.jsx)("p",{role:"status",className:"rounded-lg bg-muted p-3 text-sm",children:l("basicModeNotice")}):null,t?.restartRequired?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("pendingRestart")}):null,t?.loadError||$?(0,n.jsxs)("div",{role:"alert",className:"max-h-32 space-y-1 overflow-y-auto text-sm text-destructive",children:[t?.loadError?(0,n.jsx)("p",{className:"[overflow-wrap:anywhere]",children:(0,eJ.fD)(t.loadError,o)}):null,$?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"min-w-0 [overflow-wrap:anywhere]",children:$}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:N.requests.has("entries"),onClick:()=>void N.refreshEntries(),children:l("retry")})]}):null]}):null,N.errors.reload||N.errors.entries?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:N.errors.reload??N.errors.entries}):null]}),(0,n.jsxs)(e5,{value:c,onValueChange:e=>d(String(e)),className:`min-h-0 flex-1 gap-0 ${_?"hidden":""}`,children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 pt-2 sm:px-6",children:(0,n.jsxs)(e4,{variant:"line","aria-label":l("title"),className:"h-9",children:[(0,n.jsxs)(e6,{value:"installed",className:"px-3",children:[l("installedTab"),t?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t.plugins.length}):null]}),(0,n.jsx)(e6,{value:"search",className:"px-3",children:l("searchPlugins")})]})}),(0,n.jsx)(e8,{value:"installed",keepMounted:!0,className:"flex min-h-0 flex-col overflow-hidden p-4 data-[hidden]:hidden sm:p-6",children:(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[E.open?(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar max-h-1/2 shrink-0 overflow-y-auto",children:(0,n.jsx)(t9,{source:E.source,isNpm:!!E.spec,multiple:E.sources.length>1,tag:E.tag,selectedVersion:E.selectedVersion,onTag:E.setTag,detail:E.detail,loading:E.loading,pending:B,disabled:M,error:E.error??(q||null),operationMessage:B?K(O?.operation?.phase)??l("submitting"):null,override:E.override,registry:E.registry,onSource:E.changeSource,onMode:E.setOverride,onRegistry:E.setRegistry,onRead:()=>void E.loadDetail(),onVersion:e=>void E.loadDetail(e),onInstall:()=>void E.install(N.requestInstall,e=>N.setConfirmation({kind:"batch",input:{action:"add",items:e}})),onClose:()=>E.setOpen(!1)})}):null,(0,n.jsx)(t_,{snapshot:t,loading:N.loading,filter:u,statusFilter:p,batchMode:g,selected:x,onStatusFilter:h,onBatchMode:e=>{f(e),e||v(new Set)},onSelect:(e,t)=>{v(s=>{let n=new Set(s);return e.forEach(e=>{t?n.add(e):n.delete(e)}),n})},onUpdateAll:()=>void N.executeBatch({action:"update",sources:H(!1)}),onUpdateSelected:()=>void N.executeBatch({action:"update",sources:H(!0)}),onRemoveSelected:()=>N.setConfirmation({kind:"batch",input:{action:"del",sources:t?.plugins.filter(e=>x.has(tN(e.source))&&!L(e.source)).map(e=>e.source)??[]}}),disabled:M,requests:N.requests,errors:N.errors,browserErrors:z,onFilter:m,onDetail:e=>{V(),S.closeDetail(),N.openDetail(e)},onAction:N.handleControlAction,onRefresh:()=>void N.refresh()}),t?.plugins.length||E.open?null:(0,n.jsx)(I.$,{size:"sm",variant:"outline",className:"shrink-0 self-start",disabled:M,onClick:G,children:l("directInstall")})]})}),(0,n.jsx)(e8,{value:"search",keepMounted:!0,className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto p-4 data-[hidden]:hidden sm:p-6",children:(0,n.jsx)(tW,{query:S.query,kind:S.kind,searchSource:S.searchSource,registry:S.registry,items:S.items,loading:S.loading,error:S.error,searched:S.searched,hasMore:S.hasMore,disabled:M,snapshot:t,requests:N.requests,preparing:S.preparing,errors:N.errors,installErrors:S.installErrors,onQuery:S.setQuery,onCompositionStart:S.beginComposition,onCompositionEnd:S.endComposition,onKind:S.setKind,onSearchSource:e=>{S.setSearchSource(e),"custom"!==e||S.registry||C.settings?.downloadSource.mode!=="custom"||S.setRegistry(C.settings.downloadSource.registry)},onRegistry:S.setRegistry,onDetail:e=>{V(),N.closeDetail(),y(""),j(!1),S.openDetail(U(e))},onInstall:e=>{S.prepareInstall(U(e),e=>N.requestInstall({source:`npm:${e.name}`,registry:e.registry},e))},onUpdate:e=>void N.execute({kind:"update",source:e}),onMore:S.loadMore,onRetry:S.retry,onDirectInstall:G})})]}),_?(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:R?(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[R.version?(0,n.jsxs)("span",{children:["v",R.version]}):null,R.updateAvailable?(0,n.jsx)("span",{className:"rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:R.availableVersion?l("newVersion",{version:R.availableVersion}):l("updateAvailable")}):null]}),(0,n.jsx)(tw,{plugin:R,displayName:tj(R),browserError:R.pluginName?z.get(R.pluginName)??null:null,disabled:M,pending:L(R.source),browserRetryPending:N.requests.has(`entry:${R.pluginName}`),onAction:e=>N.handleControlAction(R,e)})]}),R.description?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:(0,eJ.fD)(R.description,o)}):null,(0,n.jsx)(ty,{plugin:R,requestError:N.errors[tN(R.source)],browserError:R.pluginName?z.get(R.pluginName)??null:null})]}),(0,n.jsxs)(eV.Nt,{className:"rounded-lg border",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between px-3 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 px-3 pb-3",children:[R.source.startsWith("npm:")?(0,n.jsx)(t4,{value:R.updateTag??"latest",label:l("installChannel"),disabled:M||L(R.source),onChange:e=>void N.executeBatch({action:"tag",sources:[R.source],tag:e})}):null,(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:M||L(R.source)&&R.operation?.phase!=="waiting",onClick:()=>N.handleControlAction(R,"reload"),children:l("reloadOne")})]})})]}),N.detailLoading?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("loadingPackage")}):null,N.detail?.readme?(0,n.jsx)(t3,{readme:N.detail.readme},R.source):null,(0,n.jsxs)(eV.Nt,{className:"border-t pt-2",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l("capabilityDetails"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsx)(tf,{plugin:R,detail:N.detail,detailLoading:N.detailLoading,detailError:N.detailError,browserContributions:R.pluginName?N.pluginHost.getRegisteredBrowserDescriptors().find(e=>e.pluginName===R.pluginName)?.contributions??[]:[],onRetry:()=>void N.loadDetail(R.source)})})]}),N.detailError?(0,n.jsxs)("div",{role:"alert",className:"flex items-center gap-2 text-sm text-destructive",children:[(0,n.jsx)("span",{children:N.detailError}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:()=>void N.loadDetail(R.source),children:l("retry")})]}):null]}):S.selection?(0,n.jsxs)(n.Fragment,{children:[S.detailLoading?(0,n.jsx)("p",{role:"status",className:"mb-3 text-sm text-muted-foreground",children:l("loadingPackage")}):null,S.detailError?(0,n.jsxs)("div",{role:"alert",className:"mb-3 space-y-2 text-sm",children:[(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:S.detailError}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:()=>void S.loadDetail(S.selection),children:l("retry")})]}):null,S.detail?(0,n.jsx)(t8,{detail:S.detail,disabled:M||!!S.detailError,pending:F||S.detailLoading,installed:!!(P&&(P.operation?.action!=="add"||"failed"!==P.operation.phase)),installedVersion:P?.version??null,updateAvailable:!!P?.updateAvailable,error:S.installErrors[S.detail.name]??N.errors[D]??(P?.operation?.phase==="failed"?P.operation.message:null),operationMessage:S.detailLoading?l("loadingPackage"):K(P?.operation?.phase),channel:w,onChannel:e=>{y(e),j(!1),S.loadDetail(S.selection,e||P?.updateTag||"latest")},downloadMode:S.downloadMode,downloadRegistry:S.downloadRegistry,onDownloadMode:S.setDownloadMode,onDownloadRegistry:S.setDownloadRegistry,onVersion:e=>{j(!0),S.loadDetail(S.selection,e)},onInstall:()=>S.installDetail((e,t)=>N.requestInstall({...e,source:k?e.source:`npm:${t.name}`,...w?{tag:w}:{}},t)),onUpdate:()=>{P&&N.execute({kind:"update",source:P.source})}}):null]}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:l("pluginRemoved")})}):null,(0,n.jsx)(se,{confirmation:N.confirmation,onClose:()=>N.setConfirmation(null),onConfirm:e=>void N.execute(e)})]})}var ss=s(99739);let sn=a.Yj().trim().min(1).max(2048),sr=a.YO(sn).min(1).max(32),si=a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:eJ.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0)}).strict(),sa=a.Yj().trim().min(1).max(4096),sl=a.Yj().trim().min(1).max(256),so=a.Yj().max(32768),sc=a.Ik({name:sl,label:so,state:a.k5(["active","inactive","shadowed"]),description:so,promptSnippet:so.nullable(),promptGuidelineCount:a.ai().int().nonnegative(),promptGuidelinePreview:so.nullable()}).strict(),sd=a.Ik({name:sl,label:so,state:a.k5(["active","inactive","shadowed"]),description:so,parameters:ss.Dz,promptSnippet:so.nullable(),promptGuidelines:a.YO(so)}).strict(),su=a.Ik({path:sa,events:a.YO(a.Ik({name:sl,count:a.ai().int().positive()}).strict()),commands:a.YO(a.Ik({name:sl,description:so.nullable()}).strict()),shortcuts:a.YO(a.Ik({shortcut:sl,description:so.nullable()}).strict()),flags:a.YO(a.Ik({name:sl,type:a.k5(["boolean","string"]),description:so.nullable(),default:a.KC([a.zM(),a.Yj(),a.ch()])}).strict()),messageRenderers:a.YO(sl),entryRenderers:a.YO(sl)}).strict(),sm=a.Ik({name:sl,description:so,path:sa}).strict(),sp=sm.extend({modelVisible:a.zM()}).strict(),sh=sm.extend({content:a.Yj().max(65536),truncated:a.zM()}).strict(),sg=sh.extend({modelVisible:a.zM()}).strict(),sf=a.Ik({name:sl,path:sa}).strict(),sx=a.Ik({name:sl,kind:a.k5(["config","native"])}).strict(),sb=a.Ik({methods:a.YO(a.Ik({pluginName:sl,method:sl}).strict()),browserEntries:a.YO(a.Ik({pluginName:sl}).strict()),messageDeclarations:a.YO(a.Ik({pluginName:sl,declarationName:sl,priority:a.ai().int().safe()}).strict())}).strict(),sv=a.Ik({error:eJ.qf.refine(e=>"string"==typeof e?e.length<=32768:[e.default,...Object.values(e.translations)].every(e=>e.length<=32768)).nullable(),extensions:a.YO(su),tools:a.YO(sc),skills:a.YO(sp),prompts:a.YO(sm),themes:a.YO(sf),providers:a.YO(sx),piDesk:sb}).strict(),sw=a.Ik({action:a.k5(["add","update","del","apply","enable","disable"]),phase:a.k5(["queued","checking","applying","waiting","failed"]),message:a.Yj().max(4e3).nullable()}).strict(),sy=(0,l._G)({path:"plugins/management-update",bodySchema:a.Ik({}).strict()}),sk=a.Ik({source:sn,kind:a.k5(["package","extension"]).default("package"),operation:sw.nullable().default(null),pluginName:a.Yj().trim().min(1).nullable(),description:eJ.qf.nullable().default(null),version:a.Yj().trim().min(1).nullable(),updateAvailable:a.zM().nullable(),updateTag:tS.nullable().optional(),availableVersion:a.Yj().min(1).nullable().optional(),updateError:a.Yj().max(4e3).nullable().optional(),status:a.k5(["ready","available","disabled","failed"]),error:si.nullable(),capabilities:sv}).strict(),sj=a.Ik({source:sn,readme:eJ.qf.nullable().default(null),tools:a.YO(sd),skills:a.YO(sg),prompts:a.YO(sh)}).strict(),sN=a.Ik({plugins:a.YO(sk),restartRequired:a.zM(),loadError:eJ.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0).nullable()}).strict(),sI=a.Ik({sources:a.YO(sn).min(1).max(32).optional()}).strict(),sS=a.Ik({}).strict().extend({mode:a.k5(["normal","basic"]).optional()}).strict(),sC=a.Ik({checkUpdates:a.zM().optional(),sources:sr.optional(),tag:tS.optional()}).strict(),sE=a.Ik({source:sn}).strict(),sM=sE.extend({downloadSource:tE.optional(),registry:tC.optional(),tag:tS.optional()}).strict(),sz=a.gM("action",[a.Ik({action:a.eu("add"),items:a.YO(sM).min(1).max(32)}).strict(),a.Ik({action:a.eu("update"),sources:sr}).strict(),a.Ik({action:a.eu("del"),sources:sr}).strict(),a.Ik({action:a.eu("tag"),sources:sr,tag:tS}).strict()]),sA=a.Ik({snapshot:sN,results:a.YO(a.Ik({source:sn,error:a.Yj().max(4e3).nullable()}).strict()).max(32)}).strict(),s$=sE.extend({enabled:a.zM()}).strict();async function sR(e,t,s,n){return eu(e,t,s,n,{fallbackMessage:"插件管理请求失败"})}function sP({pluginName:e,descriptor:t,source:s,cwd:r,onPreviewFile:i,onRevealFile:a,onHeaderActionsChange:l}){let o=`${s.workId}\u0000${s.sessionId}\u0000${s.branchId}\u0000${r}`;return(0,n.jsx)(eH,{pluginName:e,kind:"session-sidebar-tab",contributionName:t.contributionName,target:{kind:"session-sidebar-tab",source:s,cwd:r,files:{preview:i,reveal:a},setHeaderActions:l},targetKey:o,layout:"fill"})}function sD({pluginName:e,descriptor:t,onClose:s,onBeforeLeaveChange:i}){let a=(0,Q.t4)();(0,Q.So)();let l=a.getEntryState(e),o="ready"===l.status?l.runtime:l.status;(0,r.useEffect)(()=>()=>{i(null)},[o,i]);let c=(0,r.useMemo)(()=>({kind:"settings-page",close:()=>{a.getEntryState(e)===l&&s()},setBeforeLeave:t=>{a.getEntryState(e)===l&&i(t)}}),[l,i,s,e,a]);return(0,n.jsx)(eH,{pluginName:e,kind:"settings-page",contributionName:t.contributionName,target:c,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})}function sT({source:e,placement:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,Q.So)(),a=(0,r.useMemo)(()=>({kind:"widget",source:e}),[e]),l=JSON.stringify([e.workId,e.sessionId,e.branchId]),o=i.flatMap(e=>e.contributions.flatMap(s=>"widget"===s.kind&&s.placement===t?[{pluginName:e.pluginName,descriptor:s}]:[]));return 0===o.length?null:(0,n.jsx)("div",{"data-testid":`plugin-widgets-${t}`,"aria-label":s("composer"),className:"min-w-0 w-full",children:o.map(({pluginName:e,descriptor:t})=>(0,n.jsx)(eH,{pluginName:e,kind:"widget",contributionName:t.contributionName,target:a,targetKey:l,layout:"inline"},`${e}:${t.contributionName}:${l}`))})}function sO({pluginName:e,contributionName:t,presentation:s,source:i,icon:a,label:l,onSelected:o}){let c=(0,Q.t4)();(0,Q.So)();let d=c.getEntryState(e),u=(0,X.G)(),{t:m}=(0,b.Bd)("workbench"),p=(0,r.useRef)(null),h=(0,r.useRef)(!1),[g,f]=(0,r.useState)(!1);(0,r.useLayoutEffect)(()=>{let e=new AbortController;return p.current=e,h.current=!1,queueMicrotask(()=>{e.signal.aborted||f(!1)}),()=>{e.abort(),p.current===e&&(p.current=null)}},[d,s,i]);let x=async()=>{let n=p.current;if(!n||n.signal.aborted||h.current)return;let r=()=>!n.signal.aborted&&c.getEntryState(e)===d;h.current=!0,f(!0);try{await c.invokeSessionHeaderAction({pluginName:e,contributionName:t,presentation:s,source:i,signal:n.signal}),r()&&o?.()}catch(a){if(!r())return;let n=a instanceof Error?a.message:m("operationFailed");console.error("[Pi Desk][PluginHost] 会话标题操作失败",{pluginName:e,contributionName:t,presentation:s,source:i,message:n}),u.error(n)}finally{r()&&(h.current=!1,f(!1))}};return(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm","aria-label":l,"aria-busy":g,disabled:g,"data-testid":"plugin-session-header-action","data-plugin-name":e,"data-contribution-name":t,"data-presentation":s,className:(0,C.cn)("overflow"===s&&"w-full justify-start whitespace-normal text-left"),onClick:()=>void x(),children:[(0,n.jsx)(eq,{icon:a,className:"size-4"}),(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:l})]})}function sL(e){return`${e.pluginName}:${e.descriptor.contributionName}`}function sF({item:e,source:t,presentation:s,onSelected:i}){let a=e.descriptor[s],l=(0,r.useMemo)(()=>({kind:"session-header-item",source:t,presentation:s}),[s,t]),o=JSON.stringify([t.workId,t.sessionId,t.branchId,s]);return"action"===a.type?(0,n.jsx)(sO,{pluginName:e.pluginName,contributionName:e.descriptor.contributionName,presentation:s,source:t,icon:a.icon,label:a.label,onSelected:i}):(0,n.jsx)("div",{"data-testid":"plugin-session-header-custom","data-plugin-name":e.pluginName,"data-contribution-name":e.descriptor.contributionName,"data-presentation":s,className:"min-w-0 shrink-0",style:"inline"===s&&"custom"===e.descriptor.inline.type?{width:`${e.descriptor.inline.minWidthRem}rem`}:void 0,children:(0,n.jsx)(eH,{pluginName:e.pluginName,kind:"session-header-item",contributionName:e.descriptor.contributionName,target:l,targetKey:o,layout:"inline"})})}function sB({source:e,title:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,Q.So)(),a=(0,r.useMemo)(()=>i.flatMap(e=>e.contributions.flatMap(t=>"session-header-item"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[i]),l=(0,r.useRef)(null),o=(0,r.useRef)(null),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(!1),p=c?.items===a?c.count:0,h=a.slice(0,p),g=a.slice(p);return(0,r.useLayoutEffect)(()=>{let e=l.current,t=o.current;if(!e||!t||0===a.length)return;let s=[...t.querySelectorAll("[data-header-item-width]")],n=t.querySelector("[data-header-title-width]"),r=t.querySelector("[data-header-more-width]"),i=t.querySelector("[data-header-gap-width]"),c=()=>{let t=i.getBoundingClientRect().width,l=e.getBoundingClientRect().width-n.getBoundingClientRect().width-t,o=function(e,t,s,n){if(e.reduce((e,t)=>e+t,0)+Math.max(0,e.length-1)*n<=t)return e.length;let r=s,i=0;for(let s of e){if(r+n+s>t)break;r+=n+s,i+=1}return i}(s.map(e=>e.getBoundingClientRect().width),l,r.getBoundingClientRect().width,t);o===a.length&&m(!1),d(e=>e?.items===a&&e.count===o?e:{items:a,count:o})},u=new ResizeObserver(c);for(let t of(u.observe(e),[...s,n,r,i]))u.observe(t);return c(),()=>u.disconnect()},[a]),(0,n.jsxs)("div",{ref:l,className:"relative flex min-w-0 flex-1 items-center gap-1","data-testid":"plugin-session-header",children:[(0,n.jsx)("div",{className:"min-w-[3rem] flex-1",children:t}),a.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-1","data-testid":"session-header-items",children:[h.map(t=>(0,n.jsx)(sF,{item:t,source:e,presentation:"inline"},sL(t))),g.length>0?(0,n.jsxs)(eW.AM,{open:u,onOpenChange:m,children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":s("moreActions"),"data-testid":"session-header-more"}),children:(0,n.jsx)(H.A,{className:"size-4"})}),(0,n.jsxs)(eW.hl,{align:"end",finalFocus:!0,className:"pi-desk-chat-scrollbar max-h-[min(28rem,var(--available-height))] gap-1 overflow-auto p-1","data-testid":"session-header-overflow","aria-label":s("moreActions"),children:[(0,n.jsx)(eW.eO,{className:"sr-only",children:s("moreActions")}),u?g.map(t=>(0,n.jsx)(sF,{item:t,source:e,presentation:"overflow",onSelected:()=>m(!1)},sL(t))):null]})]}):null]}),(0,n.jsx)("div",{ref:o,"aria-hidden":"true",inert:!0,className:"pointer-events-none invisible absolute inset-0 overflow-hidden",children:(0,n.jsxs)("div",{className:"flex w-max items-center",children:[(0,n.jsx)("span",{"data-header-title-width":!0,className:"inline-block w-[3rem]"}),(0,n.jsx)("span",{"data-header-gap-width":!0,className:"inline-block w-1"}),(0,n.jsx)("span",{"data-header-more-width":!0,className:(0,I.r)({variant:"ghost",size:"icon-sm"}),children:(0,n.jsx)(H.A,{className:"size-4"})}),a.map(e=>"action"===e.descriptor.inline.type?(0,n.jsxs)("span",{"data-header-item-width":!0,className:(0,I.r)({variant:"ghost",size:"sm"}),children:[(0,n.jsx)(eq,{icon:e.descriptor.inline.icon,className:"size-4"}),(0,n.jsx)("span",{children:e.descriptor.inline.label})]},sL(e)):(0,n.jsx)("span",{"data-header-item-width":!0,className:"inline-block shrink-0",style:{width:`${e.descriptor.inline.minWidthRem}rem`}},sL(e)))]})})]}):null]})}var sq=s(10263),s_=s(11831),sW=s(79615),sY=s(24863),sV=s(10672);let sU="1.1.24-dev".trim()||"未知",sH="2026-10-27T14:12:45+08:00".trim()||null;var sK=s(42655),sG=s(55079),sJ=s(49667),sQ=s(61286),sX=s(33550),sZ=s(66453),s0=s(67765);let s1=a.Yj().min(1).max(s0.uV).refine(e=>!e.includes("\0")&&(e.startsWith("/")||e.startsWith("\\\\")||/^[a-zA-Z]:[\\/]/.test(e)),"必须是绝对路径"),s2=a.Ik({cwd:sZ.m4.nullable()}).strict(),s5=a.Ik({skillPath:s1,name:a.Yj().min(1),description:a.Yj(),packageSource:a.Yj().nullable()}).strict(),s3=a.Ik({skills:a.YO(s5),diagnostics:a.YO(a.Ik({path:a.Yj(),message:eJ.qf}).strict())}).strict(),s4=s2.extend({skillPath:s1}),s6=s4.extend({path:s0.rh}).strict(),s8=a.Ik({entries:a.YO(a.Ik({name:a.Yj().min(1),type:a.k5(["directory","file"])}).strict()).max(s0.xm),truncated:a.zM()}).strict(),s7=s4.extend({path:s0._g}).strict(),s9=a.gM("kind",[a.Ik({kind:a.eu("text"),content:a.Yj(),size:a.ai().int().nonnegative().max(s0.NL),readOnlyReason:eJ.qf.nullable()}).strict(),a.Ik({kind:a.eu("image"),mimeType:s0.CT,data:a.Yj(),size:a.ai().int().nonnegative()}).strict(),a.Ik({kind:a.eu("unsupported"),size:a.ai().int().nonnegative(),reason:a.Yj()}).strict()]),ne=s7.extend({content:a.Yj().max(s0.NL)}).strict(),nt=a.Ik({}).strict(),ns={path:"/api/skills/list",request:s2,response:s3},nn={path:"/api/skill-files/list",request:s6,response:s8},nr={path:"/api/skill-files/get",request:s7,response:s9},ni={path:"/api/skill-files/replace",request:ne,response:nt},na=a.Ik({code:a.ai(),msg:a.Yj(),data:a.L5(),i18n:sQ.N.optional()});async function nl(e,t,s,n){let r=await fetch(t.path,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(t.request.parse(s)),signal:n}),i=na.parse(await r.json());if(!r.ok||0!==i.code||null===i.data)throw Error(i.msg?(0,ed.B)(i):"Skills 请求失败");return t.response.parse(i.data)}function no(e){(0,sX.ZQ)({wrapLines:e})}async function nc(e){let t=e.skillPath.replaceAll("\\","/");await navigator.clipboard.writeText(t.slice(0,t.lastIndexOf("/")+1)+e.path)}var nd=s(46782);function nu(e){return(0,ed.B)({msg:nd.P["zh-CN"][e],i18n:{key:`skills:${e}`}})}function nm(e){return JSON.stringify(e)}function np(e){return JSON.stringify([e.cwd,e.skillPath,e.path])}function nh(e){return e.replace(/\r\n|\r/g,"\n")}function ng(e){return e?.file?.kind==="text"&&e.draft!==nh(e.file.content)}var nf=s(60794),nx=s(89757),nb=s(55628),nv=s(91182);function nw(e){let{t}=(0,b.Bd)("common"),{wrapLines:s}=(0,sX.TX)(),i=e.path,a=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(null),d=(0,r.useRef)(null),u=(0,r.useRef)(0),m=(0,r.useRef)(e),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{m.current=e}),(0,r.useEffect)(()=>{let e=!1,s=()=>void 0,n=()=>void 0;return(0,nv.cu)().then(r=>{if(e||!a.current)return;let i=m.current,o=r.editor.create(a.current,{model:null,theme:(0,nv.dC)(),automaticLayout:!0,readOnly:i.readOnly,domReadOnly:i.readOnly,wordWrap:(0,sX.E6)().wrapLines?"on":"off",wrappingIndent:"same",minimap:{enabled:!1},stickyScroll:{enabled:!1},scrollBeyondLastLine:!1,...(0,nv.R)(),lineNumbersMinChars:3,padding:{top:14,bottom:14},unicodeHighlight:{nonBasicASCII:!1},renderWhitespace:"selection",overviewRulerBorder:!1,ariaLabel:t("skillEditor")});l.current=o,o.addCommand(r.KeyMod.CtrlCmd|r.KeyCode.KeyS,()=>m.current.onSave()),s=(0,nv.Tr)(e=>r.editor.setTheme(e)),n=(0,nv.BK)(e=>o.updateOptions(e)),f(!0)}).catch(()=>{e||h(!0)}),()=>{e=!0,s(),n(),c.current?.dispose(),c.current=null,o.current?.dispose(),o.current=null,d.current=null,l.current?.dispose(),l.current=null}},[t]),(0,r.useEffect)(()=>{let e=!1,t=u.current+1;return u.current=t,(0,nv.cu)().then(s=>{if(e||t!==u.current||!l.current)return;let n=m.current,r=s.editor.createModel(n.content,(0,nv.ix)(n.path,n.size),(0,nv.B3)(s,n.path,"edit")),a=o.current;c.current?.dispose(),c.current=r.onDidChangeContent(()=>{m.current.onChange(r.getValue(s.editor.EndOfLinePreference.LF))}),o.current=r,d.current=i,l.current.setModel(r),a?.dispose()}),()=>{e=!0}},[i]),(0,r.useEffect)(()=>{let t=o.current;t&&d.current===e.path&&t.getValue().replace(/\r\n|\r/g,"\n")!==e.content&&t.setValue(e.content)},[e.content,e.path]),(0,r.useEffect)(()=>{l.current?.updateOptions({readOnly:e.readOnly,domReadOnly:e.readOnly,wordWrap:s?"on":"off"})},[e.readOnly,s]),(0,n.jsxs)("div",{"data-testid":"code-editor",className:"relative h-full min-h-0 w-full overflow-hidden bg-background",children:[(0,n.jsx)("div",{ref:a,className:"size-full"}),!g&&(0,n.jsx)("div",{role:"status",className:"absolute inset-0 flex items-center justify-center p-6 text-sm text-muted-foreground",children:p?t("editorFailed"):t("editorLoading")})]})}var ny=s(58840);function nk({file:e,path:t}){let{t:s}=(0,b.Bd)("skills"),i=(0,r.useMemo)(()=>[{src:`data:${e.mimeType};base64,${e.data}`,alt:t}],[e,t]);return(0,n.jsx)(ny.k,{mode:"inline",slides:i,className:"h-full w-full",ariaLabel:s("imagePreview")})}function nj(e){let{document:t,skill:s,dirty:r,loading:i,saving:a,opening:l}=e,{t:o}=(0,b.Bd)("skills"),{locale:c}=(0,eQ.i)();if(!t)return(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center",children:[(0,n.jsx)(nf.A,{className:"size-6 text-muted-foreground"}),(0,n.jsx)("h3",{className:"text-sm font-medium",children:o("chooseFile")}),(0,n.jsx)("p",{className:"max-w-xs text-sm leading-6 text-muted-foreground",children:o("chooseFileDescription")})]});let d=t.file,u=d?.kind==="text"?d.readOnlyReason:null;return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-14 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-2",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("p",{className:"truncate text-xs text-muted-foreground",title:s?.description,children:[s?.name??t.target.skillPath.split("/").at(-2),(0,n.jsx)("span",{className:"mx-1.5",children:"/"}),o(null===t.target.cwd?"global":"project"),` \xb7 ${o(s?.packageSource?"package":"local")}`]}),(0,n.jsx)("p",{className:"mt-1 truncate font-mono text-sm",title:t.target.path,children:t.target.path})]}),d?.kind==="text"&&(0,n.jsxs)("span",{role:"status","aria-label":o(a?"saving":l?"switchingFile":r?"unsavedChanges":u?"readOnlyFile":"fileSaved"),className:"hidden shrink-0 items-center gap-1 text-xs text-muted-foreground sm:flex",children:[a||l?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):r?(0,n.jsx)("span",{className:"size-1.5 rounded-full bg-status-warning"}):u?(0,n.jsx)(nx.A,{className:"size-3.5"}):(0,n.jsx)(ep.A,{className:"size-3.5"}),o(a?"saving":l?"switchingFile":r?"unsaved":u?"readOnly":"saved")]}),r&&(0,n.jsx)("span",{"aria-label":o("unsavedChanges"),className:"size-2 shrink-0 rounded-full bg-status-warning sm:hidden"}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon","aria-label":o("copySkillPath"),title:o("copyPath"),onClick:e.onCopy,children:(0,n.jsx)(ee.A,{className:"size-4"})}),(0,n.jsxs)(I.$,{"aria-label":o("saveSkill"),disabled:!r||!!u||i||a,onClick:e.onSave,children:[a?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(Z.A,{className:"size-4"}),o("save")]})]}),u&&(0,n.jsxs)("div",{role:"note",className:"flex shrink-0 items-start gap-2 border-b bg-muted px-4 py-2 text-sm leading-5 text-muted-foreground",children:[(0,n.jsx)(nx.A,{className:"mt-0.5 size-3.5 shrink-0"}),(0,n.jsx)("p",{children:(0,eJ.fD)(u,c)})]}),t.error&&(0,n.jsxs)("div",{role:"alert",className:"shrink-0 border-b bg-muted px-4 py-2 text-sm text-destructive",children:[t.error,!d&&(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:e.onReload,children:o("reload")})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:i&&!d?(0,n.jsxs)("div",{role:"status",className:"flex h-full items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),o("loadingFile")]}):d?.kind==="text"?(0,n.jsx)(nw,{path:t.target.skillPath.slice(0,t.target.skillPath.lastIndexOf("/")+1)+t.target.path,content:t.draft,size:d.size,readOnly:!!u||a||l,onChange:e.onChange,onSave:e.onSave}):d?.kind==="image"?(0,n.jsx)(nk,{file:d,path:t.target.path}):d?.kind==="unsupported"?(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-sm text-muted-foreground",children:[(0,n.jsx)(nf.A,{className:"mb-2 size-8"}),(0,n.jsx)("p",{children:d.reason}),(0,n.jsx)("p",{children:o("fileSize",{size:d.size.toLocaleString("en"===c?"en-US":"zh-CN")})})]}):null}),d?.kind==="text"&&(0,n.jsxs)("div",{className:"flex min-h-9 shrink-0 items-center justify-between gap-2 border-t px-3 py-1 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{className:"truncate",children:["UTF-8 \xb7 ",o(u?"readOnly":"saveShortcut")]}),(0,n.jsxs)(I.$,{variant:"ghost",size:"sm","aria-label":o("wrapLines"),"aria-pressed":e.wrapLines,onClick:e.onWrapLines,children:[(0,n.jsx)(nb.A,{className:"size-3.5"}),o("wrapLines")]})]})]})}function nN({open:e,saving:t,path:s,error:r,onDecide:i}){let{t:a}=(0,b.Bd)("skills");return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||t||i("cancel")},children:(0,n.jsxs)(eN.hA,{className:"z-[150]",showCloseButton:!t,children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:a("saveChangesTitle")}),(0,n.jsx)(eN.uX,{children:a("saveChangesDescription",{path:s??""})})]}),r&&(0,n.jsx)("p",{role:"alert",className:"px-4 pb-4 text-sm text-destructive",children:r}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{variant:"outline",disabled:t,onClick:()=>void i("cancel"),children:a("cancel")}),(0,n.jsx)(I.$,{variant:"ghost",disabled:t,onClick:()=>void i("discard"),children:a("discard")}),(0,n.jsx)(I.$,{disabled:t,onClick:()=>void i("save"),children:a(t?"savingChanges":"saveContinue")})]})]})})}var nI=s(19932),nS=s(43326),nC=s(17511);function nE(e,t){return!!(e&&e.cwd===t.cwd&&e.skillPath===t.skillPath&&e.path===t.path)}function nM({target:e,props:t,depth:s=0,skillName:i}){let{t:a}=(0,b.Bd)("skills"),l=t.directories[np(e)],{onLoadDirectory:o}=t;return((0,r.useEffect)(()=>{l||o(e)},[l,o,e]),l?.error)?(0,n.jsxs)("div",{className:"px-3 py-2 text-xs text-destructive",children:[l.error,(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:()=>void t.onLoadDirectory(e),children:a("retryFolder")})]}):l?.data?(0,n.jsxs)("div",{className:"relative ml-5 border-l border-border/70 py-1 pl-3",children:[l.data.entries.map(r=>{let l=e.path?`${e.path}/${r.name}`:r.name,o={...e,path:l};if("directory"===r.type)return(0,n.jsx)(nz,{target:o,props:t,depth:s,name:r.name,skillName:i},l);let c=nE(t.selected,o),d=nE(t.pending,o);return(0,n.jsxs)(I.$,{variant:"ghost","aria-label":a("skillFile",{path:`${i}/${l}`}),"aria-pressed":c,title:l,className:(0,C.cn)("min-h-9 w-full justify-start text-left font-normal text-muted-foreground",c&&"font-medium",d&&"bg-muted text-foreground"),onClick:()=>void t.onOpenFile(o),children:["SKILL.md"===r.name?(0,n.jsx)(nI.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(nf.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r.name}),d&&(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin"})]},l)}),0===l.data.entries.length&&(0,n.jsx)("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:a("emptyFolder")}),l.data.truncated&&(0,n.jsx)("p",{className:"px-3 py-2 text-sm text-status-warning",children:a("folderTruncated")})]}):(0,n.jsx)("p",{role:"status",className:"px-4 py-2 text-xs text-muted-foreground",children:a("loadingFolder")})}function nz({target:e,props:t,depth:s,name:i,skillName:a}){let{t:l}=(0,b.Bd)("skills"),[o,c]=(0,r.useState)(!1);return(0,n.jsxs)("div",{children:[(0,n.jsxs)(I.$,{variant:"ghost","aria-expanded":o,"aria-label":l("skillFolder",{path:`${a}/${e.path}`}),className:(0,C.cn)("min-h-9 w-full justify-start font-normal text-muted-foreground",o&&"bg-muted text-foreground"),onClick:()=>c(!o),children:[o?(0,n.jsx)(eY.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(e7.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)(eP.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:i})]}),o&&(0,n.jsx)("div",{className:s>3?"-ml-3":void 0,children:(0,n.jsx)(nM,{target:e,props:t,depth:s+1,skillName:a})})]})}function nA({cwd:e,skill:t,props:s}){let{t:i}=(0,b.Bd)("skills"),a=s.selected?.cwd===e&&s.selected.skillPath===t.skillPath,l=s.pending?.cwd===e&&s.pending.skillPath===t.skillPath,[o,c]=(0,r.useState)(null),d=o??a,u=async()=>{if(d)return void c(!1);let n=t.skillPath.replaceAll("\\","/").split("/").at(-1);await s.onOpenFile({cwd:e,skillPath:t.skillPath,path:n})&&c(!0)};return(0,n.jsxs)("div",{className:"py-0.5",children:[(0,n.jsxs)(I.$,{variant:"ghost","aria-label":i("skillName",{name:t.name}),"aria-expanded":d,title:`${t.description}
|
|
155
|
-
${t.skillPath}`,className:(0,C.cn)("min-h-14 w-full justify-start whitespace-normal text-left",d&&"bg-accent hover:bg-accent",a&&"text-foreground"),onClick:()=>void u(),children:[d?(0,n.jsx)(eY.A,{className:"size-3.5 shrink-0 text-muted-foreground"}):(0,n.jsx)(e7.A,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",children:t.name}),t.description&&(0,n.jsx)("p",{className:"mt-0.5 truncate text-xs font-normal text-muted-foreground",children:t.description})]}),l?(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground"}):t.packageSource?(0,n.jsx)(nS.A,{"aria-label":i("packageSkill"),className:"size-3.5 shrink-0 text-muted-foreground"}):null]}),d&&(0,n.jsx)(nM,{target:{cwd:e,skillPath:t.skillPath,path:""},props:s,skillName:t.name})]})}function n$({cwd:e,name:t,props:s}){let{t:i}=(0,b.Bd)("skills"),{locale:a}=(0,eQ.i)(),l=s.selected?.cwd===e||s.pending?.cwd===e,[o,c]=(0,r.useState)(null),{onLoadScope:d}=s,u=s.scopes[nm(e)],m=s.query.trim().toLowerCase(),p=o??(null===e||s.focusedCwd===e||l),h=p||!!m;(0,r.useEffect)(()=>{h&&!u&&d(e)},[e,h,u,d]);let g=`${t} ${e??""}`.toLowerCase().includes(m),f=u?.data?.skills.filter(e=>!m||g||`${e.name} ${e.description}`.toLowerCase().includes(m))??[];if(m&&u?.data&&!f.length&&!g&&!u.error)return null;let x=null===e;return(0,n.jsxs)("section",{className:"mx-2 mt-2 min-w-0 border-b pb-2","aria-label":x?i("globalSkills"):i("projectSkills",{name:t}),children:[(0,n.jsxs)(I.$,{variant:"ghost",className:"min-h-14 w-full justify-start text-left","aria-label":i("skillsGroup",{name:x?i("global"):t}),"aria-expanded":h,onClick:()=>c(!p),children:[h?(0,n.jsx)(eY.A,{className:"size-4 shrink-0"}):(0,n.jsx)(e7.A,{className:"size-4 shrink-0"}),x?(0,n.jsx)(eL.A,{className:"size-4 shrink-0 text-primary"}):(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-semibold",children:x?i("globalSkills"):t}),e&&(0,n.jsx)("p",{title:e,className:"mt-1 truncate text-xs font-normal text-muted-foreground",children:e})]}),u?.loading?(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground"}):u?.data?(0,n.jsx)("span",{className:"text-xs tabular-nums text-muted-foreground",children:m?f.length:u.data.skills.length}):null]}),h&&(0,n.jsxs)("div",{className:"px-1 py-1",children:[u?.error&&(0,n.jsxs)("p",{className:"px-3 py-2 text-xs text-destructive",children:[u.error,(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:()=>void s.onLoadScope(e),children:i("retryGroup")})]}),f.map(t=>(0,n.jsx)(nA,{cwd:e,skill:t,props:s},t.skillPath)),u?.data&&0===f.length&&!u.error&&(0,n.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground",children:i(m?"noSkillMatches":"noSkills")}),!!u?.data?.diagnostics.length&&(0,n.jsxs)("details",{className:"mx-2 mb-1 mt-2 rounded-md bg-muted p-2 text-sm text-muted-foreground",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-status-warning",children:i("diagnostics",{count:u.data.diagnostics.length})}),(0,n.jsx)("div",{className:"mt-2 space-y-3",children:u.data.diagnostics.map((e,t)=>(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"break-words",children:(0,eJ.fD)(e.message,a)}),(0,n.jsx)("p",{className:"mt-1 break-all text-xs",children:e.path})]},`${e.path}:${t}`))})]})]})]})}function nR(e){let{t}=(0,b.Bd)("skills");return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsx)("div",{className:"shrink-0 border-b p-3",children:(0,n.jsxs)(nC.MG,{children:[(0,n.jsx)(nC.Sq,{children:(0,n.jsx)(eh.A,{className:"size-4"})}),(0,n.jsx)(nC.iV,{"aria-label":t("searchSkills"),value:e.query,onChange:t=>e.onQuery(t.target.value),placeholder:t("searchSkillsPlaceholder")})]})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain pb-4",children:[(0,n.jsx)(n$,{cwd:null,name:t("global"),props:e}),(0,n.jsxs)("div",{className:"flex items-center gap-2 px-4 pb-1 pt-5",children:[(0,n.jsx)("span",{className:"h-px flex-1 bg-border"}),(0,n.jsx)("p",{className:"shrink-0 text-xs font-medium text-muted-foreground",children:t("workspaceCount",{count:e.projects.length})}),(0,n.jsx)("span",{className:"h-px flex-1 bg-border"})]}),e.projects.map(t=>(0,n.jsx)(n$,{cwd:t.cwd,name:t.projectName,props:e},t.cwd)),0===e.projects.length&&(0,n.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground",children:t("workspaceEmpty")})]})]})}function nP({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{t:i}=(0,b.Bd)("skills"),{clientId:a}=(0,ei.gM)(),l=(0,X.G)(),o=(0,r.useMemo)(()=>({list:(e,t)=>nl(a,ns,e,t),listFiles:(e,t)=>nl(a,nn,e,t),getFile:(e,t)=>nl(a,nr,e,t),async replaceFile(e){await nl(a,ni,e)}}),[a]),c=function(e,t){let[s,n]=(0,r.useState)({}),[i,a]=(0,r.useState)({}),l=(0,r.useRef)(new Map),o=(0,r.useRef)(!0);(0,r.useEffect)(()=>{o.current=!0;let e=l.current;return()=>{for(let t of(o.current=!1,e.values()))t.abort();e.clear()}},[]);let c=(0,r.useCallback)(async t=>{let s=nm(t),r=`scope:${s}`;l.current.get(r)?.abort();let i=new AbortController;l.current.set(r,i),n(e=>({...e,[s]:{data:e[s]?.data??null,loading:!0,error:null}}));try{let r=await e.list({cwd:t},i.signal);!i.signal.aborted&&o.current&&n(e=>({...e,[s]:{data:r,loading:!1,error:null}}))}catch(e){!i.signal.aborted&&o.current&&n(t=>({...t,[s]:{data:t[s]?.data??null,loading:!1,error:e instanceof Error?e.message:nu("skillsReadFailed")}}))}finally{l.current.get(r)===i&&l.current.delete(r)}},[e]),d=(0,r.useCallback)(async t=>{let s=np(t),n=`directory:${s}`;l.current.get(n)?.abort();let r=new AbortController;l.current.set(n,r),a(e=>({...e,[s]:{data:e[s]?.data??null,loading:!0,error:null}}));try{let n=await e.listFiles(t,r.signal);!r.signal.aborted&&o.current&&a(e=>({...e,[s]:{data:n,loading:!1,error:null}}))}catch(e){!r.signal.aborted&&o.current&&a(t=>({...t,[s]:{data:null,loading:!1,error:e instanceof Error?e.message:nu("directoryReadFailed")}}))}finally{l.current.get(n)===r&&l.current.delete(n)}},[e]),u=JSON.stringify(t.map(e=>e.cwd));return(0,r.useEffect)(()=>{let e=new Set([nm(null),...JSON.parse(u).map(nm)]);for(let[t,s]of(n(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),a(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(nm(JSON.parse(t)[0]))))),l.current)){let n=t.startsWith("scope:")?t.slice(6):nm(JSON.parse(t.slice(10))[0]);e.has(n)||(s.abort(),l.current.delete(t))}},[u]),{scopes:s,directories:i,loadScope:c,loadDirectory:d}}(o,e),{loadScope:d}=c,u=function(e,t){let{wrapLines:s}=(0,sX.TX)(),[n,i]=(0,r.useState)(null),a=(0,r.useRef)(null),l=(0,r.useRef)(!0),[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(!1),h=(0,r.useRef)(null),g=(0,r.useRef)(!1),f=(0,r.useRef)(null),[x,b]=(0,r.useState)(!1),v=(0,r.useRef)(null),w=(0,r.useCallback)(e=>{l.current&&(a.current=e,i(e))},[]);(0,r.useEffect)(()=>(l.current=!0,()=>{l.current=!1,f.current?.abort(),v.current?.resolve(!1),v.current=null}),[]);let y=(0,r.useCallback)(()=>{if(h.current)return h.current;let s=a.current;if(!s||s.file?.kind!=="text"||s.file.readOnlyReason)return Promise.resolve(!1);if(!ng(s))return Promise.resolve(!0);p(!0);let n=(async()=>{try{await e.replaceFile({...s.target,content:s.draft});let n=a.current;return n?.file?.kind==="text"&&n.target===s.target&&w({...n,file:{...n.file,content:s.draft},error:null}),l.current&&t(s.target.cwd),!0}catch(t){let e=a.current;return e?.target===s.target&&w({...e,error:t instanceof Error?t.message:nu("saveFailed")}),!1}finally{h.current=null,l.current&&p(!1)}})();return h.current=n,n},[w,e,t]),k=(0,r.useCallback)(async()=>{let e;if(h.current&&await h.current,!l.current)return!1;if(!ng(a.current))return!0;if(v.current)return v.current.promise;let t=new Promise(t=>{e=t});return v.current={promise:t,resolve:e},b(!0),t},[]),j=(0,r.useCallback)(async e=>{if(!v.current||h.current||"save"===e&&(!await y()||ng(a.current)))return;if("discard"===e){let e=a.current;e?.file?.kind==="text"&&w({...e,draft:nh(e.file.content),error:null})}let t=v.current;v.current=null,b(!1),t?.resolve("cancel"!==e)},[w,y]),N=(0,r.useCallback)(async t=>{if(g.current)return!1;g.current=!0;try{if(!await k()||!l.current)return!1;f.current?.abort();let s=new AbortController;f.current=s,u(t),c(!0);try{let n=await e.getFile(t,s.signal);if(s.signal.aborted||!l.current)return!1;return w({target:t,file:n,draft:"text"===n.kind?nh(n.content):"",error:null}),!0}catch(e){if(!s.signal.aborted){let s=a.current,n=e instanceof Error?e.message:nu("fileReadFailed");w(s?{...s,error:n}:{target:t,file:null,draft:"",error:n})}return!1}finally{l.current&&(u(null),c(!1))}}finally{g.current=!1}},[w,k,e]),I=(0,r.useCallback)(e=>{let t=a.current;t?.file?.kind!=="text"||t.file.readOnlyReason||t.draft===e||w({...t,draft:e})},[w]),S=ng(n);return(0,r.useEffect)(()=>{if(!S)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[S]),{document:n,dirty:S,loading:o,openingTarget:d,saving:m,confirmOpen:x,wrapLines:s,setWrapLines:no,change:I,open:N,save:y,beforeLeave:k,decide:j}}(o,(0,r.useCallback)(e=>{d(e)},[d])),{document:m,open:p}=u,[h,g]=(0,r.useState)(""),[f,x]=(0,r.useState)(!1),[w,y]=(0,r.useState)(!0),k=(0,r.useRef)(!1),j=(0,r.useRef)(t);(0,r.useEffect)(()=>(s(u.beforeLeave),()=>s(null)),[u.beforeLeave,s]),(0,r.useEffect)(()=>{if(k.current||m)return;let e=c.scopes[nm(j.current)];if(!e||e.loading)return;let t=c.scopes[nm(null)],s=e.data?.skills[0];if(!s&&(!t||t.loading))return;let n=s??t?.data?.skills[0];k.current=!0,n&&p({cwd:s?j.current:null,skillPath:n.skillPath,path:n.skillPath.split("/").at(-1)})},[c.scopes,m,p]);let N=(0,r.useCallback)(async e=>{let t=await p(e);return t&&x(!1),t},[p]),S=async()=>{if(u.document)try{await nc(u.document.target),l.success(i("pathCopied"))}catch{l.error(i("copyFailed"))}},E=u.document?.target??null,M=E?c.scopes[nm(E.cwd)]?.data?.skills.find(e=>e.skillPath===E.skillPath)??null:null,z=Object.values(c.scopes).some(e=>e.loading)||Object.values(c.directories).some(e=>e.loading),A={projects:e,focusedCwd:t,query:h,onQuery:g,scopes:c.scopes,directories:c.directories,selected:E,pending:u.openingTarget,onLoadScope:c.loadScope,onLoadDirectory:c.loadDirectory,onOpenFile:N};return(0,n.jsxs)("section",{"aria-label":i("skillsManagement"),className:"flex h-full min-h-0 flex-col bg-background",children:[(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 border-b px-4 py-2",children:[(0,n.jsx)(I.$,{variant:"ghost",size:"icon",className:"lg:hidden","aria-label":i("openSkillsFolder"),onClick:()=>x(!0),children:(0,n.jsx)(sY.A,{className:"size-4"})}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon",className:"hidden lg:inline-flex","aria-label":i(w?"collapseSkillsFolder":"expandSkillsFolder"),onClick:()=>y(!w),children:w?(0,n.jsx)(sG.A,{className:"size-4"}):(0,n.jsx)(sJ.A,{className:"size-4"})}),(0,n.jsx)("h2",{className:"text-xl font-semibold",children:"Skills"}),(0,n.jsx)("div",{className:"flex-1"}),(0,n.jsxs)(I.$,{variant:"ghost",size:"sm",disabled:z,"aria-label":i("refreshSkillsFolder"),onClick:()=>{for(let e of Object.keys(c.scopes))c.loadScope(JSON.parse(e));for(let e of Object.keys(c.directories)){let[t,s,n]=JSON.parse(e);c.loadDirectory({cwd:t,skillPath:s,path:n})}},children:[z?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(es.A,{className:"size-3.5"}),i("refreshFolder")]})]}),(0,n.jsxs)("div",{className:"flex min-h-0 flex-1",children:[(0,n.jsx)("aside",{"aria-label":i("skillsProjectFolder"),className:(0,C.cn)("hidden w-64 shrink-0 border-r bg-sidebar xl:w-72",w&&"lg:block"),children:(0,n.jsx)(nR,{...A})}),(0,n.jsx)("main",{className:"min-h-0 min-w-0 flex-1",children:(0,n.jsx)(nj,{document:u.document,skill:M,dirty:u.dirty,loading:u.loading,saving:u.saving,opening:!!u.openingTarget,wrapLines:u.wrapLines,onWrapLines:()=>u.setWrapLines(!u.wrapLines),onChange:u.change,onSave:()=>void u.save(),onReload:()=>{E&&N(E)},onCopy:()=>void S()})})]}),(0,n.jsx)(eN.YV,{open:f,onOpenChange:x,children:(0,n.jsxs)(eN.hA,{className:"left-0 top-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)(eN.Hl,{className:"shrink-0 border-b px-4 py-3 pr-12",children:(0,n.jsx)(eN.YM,{children:i("skillsFolderTitle")})}),(0,n.jsx)("div",{className:"min-h-0 flex-1",children:(0,n.jsx)(nR,{...A})})]})}),(0,n.jsx)(nN,{open:u.confirmOpen,saving:u.saving,path:E?.path??null,error:u.document?.error??null,onDecide:u.decide})]})}var nD=s(75851),nT=s(17247),nO=s(4090),nL=s(19562);function nF(){let{t:e}=(0,b.Bd)("common"),[t,s]=(0,r.useState)(null),i=(0,r.useRef)(null),a=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{i.current?.(!1),i.current=null},[]);let l=e=>{let t=i.current;i.current=null,s(null),t?.(e)};return{confirm:e=>(i.current?.(!1),s(e),new Promise(e=>{i.current=e})),dialog:t?(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||l(!1)},children:(0,n.jsxs)(eN.hA,{initialFocus:a,className:"z-[130] max-w-[27.5rem]",children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:t.title}),(0,n.jsx)(eN.uX,{className:"break-words",children:t.description})]}),t.content?(0,n.jsx)(eN._Y,{className:"grid grid-rows-[minmax(0,1fr)]",children:t.content}):null,(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{ref:a,variant:"outline",onClick:()=>l(!1),children:e("cancel")}),(0,n.jsx)(I.$,{variant:t.confirmVariant??"destructive",onClick:()=>l(!0),children:t.confirmLabel??e("delete")})]})]})}):null}}var nB=s(33941);async function nq(e,t,s,n,r){let i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s),signal:r});401===i.status&&window.location.replace("/login");let a=await i.json();if(!i.ok||0!==a.code||null===a.data)throw Error(0===a.code?(0,ed.B)({msg:"登录保护设置处理失败",i18n:{key:"auth:settingsFailed"}}):(0,ed.B)(a));return n.parse(a.data)}async function n_(e){await nq(e,"/api/auth/logout",{},nB.Xm),window.location.replace("/login")}async function nW(e,t){let s=nB.uZ.safeParse(t);if(!s.success)throw Error((0,ed.B)({msg:"密码不符合要求,请按输入框下方的规则调整。",i18n:{key:"auth:settingsInvalid"}}));await nq(e,"/api/auth-settings/replace",s.data,nB.Kc),window.location.replace(null===t.password?"/":"/login")}function nY(){let{t:e}=(0,b.Bd)("auth"),t=function(){let{t:e}=(0,b.Bd)("auth"),{clientId:t}=(0,ei.gM)(),{confirm:s,dialog:n}=nF(),[i,a]=(0,r.useState)(null),[l,o]=(0,r.useState)(!0),[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)(0),[x,v]=(0,r.useState)(""),w=(0,r.useRef)(!1);(0,r.useEffect)(()=>{var s;let n=new AbortController;return(s=n.signal,nq(t,"/api/auth-settings/get",{},nB.G6,s)).then(e=>{n.signal.aborted||(a(e),o(!1))}).catch(t=>{n.signal.aborted||(h(t instanceof Error?t.message:e("settingsFailed")),o(!1))}),()=>n.abort()},[t,g,e]);let y=async()=>{if(!w.current&&i){w.current=!0,d(!0),h(null);try{await nW(t,{password:x})}catch(t){w.current=!1,d(!1),h(t instanceof Error?t.message:e("settingsFailed"))}}},k=async()=>{if(!w.current&&i){if(w.current=!0,!await s({title:e("disableTitle"),description:e("disableDescription"),confirmLabel:e("disable")})){w.current=!1;return}d(!0),h(null);try{await nW(t,{password:null})}catch(t){w.current=!1,d(!1),h(t instanceof Error?t.message:e("settingsFailed"))}}},j=async()=>{if(!w.current&&i?.enabled){w.current=!0,m(!0),h(null);try{await n_(t)}catch(t){w.current=!1,m(!1),h(t instanceof Error?t.message:e("logoutFailed"))}}};return{settings:i,loading:l,saving:c,signingOut:u,error:p,password:x,setPassword:v,save:y,generatePassword:()=>{if(!w.current)try{v(function(){for(;;){let e=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@"[e%64]).join("");if(/[A-Z]/.test(e)&&/[a-z]/.test(e)&&/[0-9]/.test(e)&&/[!@]/.test(e))return e}}()),h(null)}catch{h(e("generatePasswordFailed"))}},disable:k,logout:j,dialog:n,retry:()=>{o(!0),h(null),f(e=>e+1)}}}(),s=t.settings?.enabled??!1,i=t.saving||t.signingOut,a=s?en.A:nD.A;return(0,n.jsxs)("section",{"aria-labelledby":"auth-settings-title",className:"@container min-w-0 space-y-6",children:[(0,n.jsx)("h2",{id:"auth-settings-title",className:"text-xl font-semibold",children:e("settings:loginProtection")}),t.loading?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",role:"status",children:e("common:loading")}):t.settings?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 rounded-xl bg-muted p-4",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[(0,n.jsx)(a,{className:"size-5 shrink-0","aria-hidden":"true"}),(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:e("protection")}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e(s?"enabled":"disabled")})]})]}),s?(0,n.jsxs)(I.$,{type:"button",variant:"outline",className:"border-destructive/50 text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:i,"aria-busy":t.signingOut,onClick:()=>void t.logout(),children:[t.signingOut?(0,n.jsx)(v.A,{className:"motion-safe:animate-spin","aria-hidden":"true"}):(0,n.jsx)(nT.A,{"aria-hidden":"true"}),e(t.signingOut?"signingOut":"logout")]}):null]}),(0,n.jsxs)("form",{className:"grid gap-4 @min-[36rem]:grid-cols-[10rem_minmax(0,1fr)] @min-[36rem]:gap-6","aria-busy":i,onSubmit:e=>{e.preventDefault(),t.save()},children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:e(s?"changePassword":"setPassword")}),s?null:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("publicAccess")})]}),(0,n.jsxs)("div",{className:"min-w-0 max-w-[40rem] space-y-4",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("label",{className:"block text-sm font-medium",htmlFor:"auth-password",children:e(s?"newPassword":"password")}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:i,title:e("generatePasswordHint"),onClick:t.generatePassword,children:[(0,n.jsx)(nO.A,{"aria-hidden":"true"}),e("generatePassword")]})]}),(0,n.jsx)(nL.k,{id:"auth-password",name:"password",className:"[&::-ms-reveal]:hidden",autoComplete:"new-password",minLength:12,maxLength:64,required:!0,disabled:i,value:t.password,"aria-describedby":`auth-password-hint${t.error?" auth-settings-error":""}`,onChange:e=>t.setPassword(e.target.value)}),(0,n.jsx)("p",{id:"auth-password-hint",className:"text-sm text-muted-foreground",children:e("passwordHint")})]}),t.error?(0,n.jsx)("p",{id:"auth-settings-error",className:"text-sm text-destructive",role:"alert",children:t.error}):null,(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("saveEffect")}),(0,n.jsxs)(I.$,{type:"submit",disabled:i,children:[t.saving?(0,n.jsx)(v.A,{className:"motion-safe:animate-spin","aria-hidden":"true"}):null,e(t.saving?"saving":s?"saveAndSignIn":"enable")]})]})]}),s?(0,n.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4 border-t pt-4",children:[(0,n.jsxs)("details",{className:"group min-w-0 flex-1 text-sm",children:[(0,n.jsxs)("summary",{className:"flex min-h-8 w-fit cursor-pointer items-center gap-1 rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring",children:[(0,n.jsx)(e7.A,{className:"size-4 shrink-0 transition-transform group-open:rotate-90","aria-hidden":"true"}),e("recovery")]}),(0,n.jsxs)("div",{className:"mt-2 space-y-2",children:[(0,n.jsx)("p",{className:"text-muted-foreground",children:e("recoveryDescription")}),(0,n.jsx)("code",{className:"block break-all text-xs",children:t.settings.configPath})]})]}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"text-muted-foreground",disabled:i,onClick:()=>void t.disable(),children:e("disable")})]}):null]}):(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:t.error}),(0,n.jsx)(I.$,{variant:"outline",onClick:t.retry,children:e("common:retry")})]}),t.dialog]})}var nV=s(60471),nU=s(62851);let nH=Object.freeze({apply:(0,l.Vc)({path:"app-runtime/apply",inputSchema:nU.$C,outputSchema:nU.Pq}),update:(0,l._G)({path:"app-runtime/update",bodySchema:nU.YT})});var nK=s(48708);async function nG(e,t,s,n){let r=(0,nK.fx)();if(!r)return"cancelled";let i=e!==r.locale;if(i&&!window.confirm(t))return"cancelled";if(i&&n&&!await n())return"blocked";try{await s.request(nH.apply,{key:"settings",update:{region:{locale:e}}})}catch{return"save-failed"}return i&&window.location.reload(),"changed"}async function nJ(e,t){try{return await t.request(nH.apply,{key:"settings",update:{region:{timeZone:e}}}),!0}catch{return!1}}function nQ({canLeave:e}){let{t}=(0,b.Bd)("settings"),s=(0,eQ.i)(),{appSocket:i}=(0,ei.gM)(),[a,l]=(0,r.useState)(null),[o,c]=(0,r.useState)(()=>new Date);(0,r.useEffect)(()=>{let e=window.setInterval(()=>c(new Date),6e4);return()=>window.clearInterval(e)},[]);let d=(0,r.useMemo)(()=>[...["UTC",...Intl.supportedValuesOf("timeZone").filter(e=>"UTC"!==e)].map(e=>({value:e,label:e.replaceAll("_"," ")}))],[]),u=async s=>{l(null);let n=await nG(s,t("common:reloadConfirm"),i,e);"save-failed"===n&&l(t("common:localeError")),"blocked"===n&&l(t("common:reloadBlocked"))},m=async e=>{l(await nJ(e,i)?null:t("common:timeZoneError"))};return(0,n.jsxs)("section",{className:"@container min-w-0 space-y-6","aria-labelledby":"region-settings-title",children:[(0,n.jsx)("h2",{id:"region-settings-title",className:"text-xl font-semibold",children:t("region")}),(0,n.jsxs)("div",{className:"grid max-w-[40rem] gap-6 @min-[32rem]:grid-cols-2",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("label",{className:"block text-sm font-medium",htmlFor:"region-language",children:t("language")}),(0,n.jsxs)(ea.l6,{value:s.localePreference,onValueChange:e=>{("zh-CN"===e||"en"===e)&&u(e)},children:[(0,n.jsx)(ea.bq,{id:"region-language",className:"w-full",children:(0,n.jsx)(ea.yv,{children:"zh-CN"===s.localePreference?t("common:chinese"):"English"})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(ea.eb,{value:"zh-CN",children:t("common:chinese")}),(0,n.jsx)(ea.eb,{value:"en",children:"English"})]})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("currentLanguage",{locale:s.locale})}),s.pendingLocale&&(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("common:languagePending")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void u(s.localePreference),children:t("reloadLanguage")})]})]}),(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("span",{className:"block text-sm font-medium",children:t("timeZone")}),(0,n.jsx)(nV.b,{value:s.timeZonePreference,options:d,onChange:e=>void m(e),ariaLabel:t("timeZone"),searchPlaceholder:t("searchTimeZones"),emptyText:t("common:unavailable"),className:"w-full"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("currentTimeZone",{timeZone:s.timeZone})})]})]}),(0,n.jsxs)("div",{className:"space-y-1 rounded-xl bg-muted p-4",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("timeExample")}),(0,n.jsx)("p",{className:"text-sm font-medium tabular-nums",children:new Intl.DateTimeFormat("en"===s.locale?"en-US":"zh-CN",{timeZone:s.timeZone,year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(o)})]}),a&&(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:a})]})}var nX=s(90772),nZ=s(90164),n0=s(52871),n1=s(96646);function n2({label:e,value:t,options:s,onChange:r,layout:i="list",disabled:a=!1}){let l=s.some(e=>e.value===t);return(0,n.jsx)("div",{role:"radiogroup","aria-label":e,onKeyDown:e=>{if(a||e.nativeEvent.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=["ArrowRight","ArrowDown"].includes(e.key)?1:["ArrowLeft","ArrowUp"].includes(e.key)?-1:0;if(!n&&"Home"!==e.key&&"End"!==e.key)return;e.preventDefault();let i=Math.max(0,s.findIndex(e=>e.value===t)),l="Home"===e.key?0:"End"===e.key?s.length-1:(i+n+s.length)%s.length,o=s[l];o&&(r(o.value),e.currentTarget.querySelectorAll('[role="radio"]')[l]?.focus())},className:(0,C.cn)("segmented"===i?"inline-flex max-w-full flex-wrap gap-0.5 rounded-lg bg-muted p-0.5":"grid gap-2"),children:s.map((e,s)=>{let o=e.value===t,c=e.icon;return(0,n.jsxs)("button",{type:"button",role:"radio","aria-checked":o,tabIndex:o||!l&&0===s?0:-1,disabled:a,"data-testid":e.testId,onClick:()=>r(e.value),className:(0,C.cn)("flex min-w-0 cursor-pointer items-center gap-2 text-left text-sm leading-5 outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset","segmented"===i?"min-h-7 rounded-md px-2 py-0.5":"min-h-9 rounded-lg border border-transparent px-3 py-2",o?"segmented"===i?"bg-card text-card-foreground shadow-sm":"border-border bg-accent text-accent-foreground":"text-muted-foreground hover:bg-foreground/8 hover:text-foreground"),children:[c?(0,n.jsx)(c,{className:"size-4 shrink-0"}):null,(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block font-medium",children:e.label}),e.description?(0,n.jsx)("span",{className:"mt-1 block text-sm font-normal text-muted-foreground",children:e.description}):null]}),"list"===i?(0,n.jsx)(ep.A,{"aria-hidden":"true",className:(0,C.cn)("size-4 shrink-0",!o&&"invisible")}):null]},e.value)})})}var n5=s(74052),n3=s(38903),n4=s(90740),n6=s(67796),n8=s(8001),n7=s(46376),n9=s.n(n7);let re={code:{copy:!0,download:!1}};function rt({href:e,children:t,...s}){return delete s.node,(0,n.jsx)("a",{...s,href:e,target:"_blank",rel:"noopener noreferrer",children:t})}function rs({src:e,alt:t,className:s,onError:i,...a}){let{t:l}=(0,b.Bd)("conversation"),[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(!1),m=t||l("image"),p=(0,r.useMemo)(()=>"string"==typeof e&&e?[{src:e,alt:m}]:[],[m,e]);if(delete a.node,0===p.length)return null;if(d)return(0,n.jsx)("span",{className:n9().imageFallback,children:l("imageUnavailable")});let h=p[0].src;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",className:n9().imageTrigger,"aria-label":l("previewImage",{name:m}),onClick:()=>c(!0),children:[(0,n.jsx)("img",{...a,src:h,alt:m,"data-streamdown":"image",className:(0,C.cn)(n9().image,s),onError:e=>{u(!0),i?.(e)}}),(0,n.jsx)("span",{className:n9().imageAction,"aria-hidden":"true",children:(0,n.jsx)(q.A,{className:"size-4"})})]}),o?(0,n.jsx)(ny.k,{mode:"modal",open:!0,slides:p,ariaLabel:l("imagePreview"),onClose:()=>c(!1)}):null]})}function rn({className:e,isAnimating:t,components:s,...r}){let i=(0,X.G)(),{t:a}=(0,b.Bd)("conversation"),{locale:l}=(0,eQ.i)();return(0,n.jsx)("div",{className:"contents",onClickCapture:e=>{if("u">typeof navigator&&"function"==typeof navigator.clipboard?.writeText)return;let t=function(e){if(!(e instanceof Element))return null;let t=e.closest('[data-streamdown="code-block-copy-button"]');return t?t.closest('[data-streamdown="code-block"]')?.querySelector('[data-streamdown="code-block-body"]')?.textContent??null:null}(e.target);null!==t&&(e.preventDefault(),e.stopPropagation(),(0,e9.x)(t).then(e=>{e||i.error(a("codeCopyFailed"))}))},children:(0,n.jsx)(t2,{className:(0,C.cn)("space-y-0",n9().markdown,n8.om,e),controls:re,isAnimating:t,lineNumbers:!1,allowedTags:n8.IV,remarkPlugins:n8.XC,components:{...n8.e6,...s,a:rt,img:rs},...r,translations:"zh-CN"===l?n6.X:void 0})})}let rr=[{value:"system",label:"common:system",icon:nX.A},{value:"light",label:"themeLight",icon:nZ.A},{value:"dark",label:"themeDark",icon:n0.A}],ri=[{value:"compact",label:"sizeCompact"},{value:"standard",label:"sizeStandard"},{value:"large",label:"sizeLarge"}];function ra(){let{t:e}=(0,b.Bd)("settings"),t=(0,r.useSyncExternalStore)(n5.Cy,n5.Is,()=>n1.Pl),s=(0,r.useSyncExternalStore)(n4.wm,n4.Ev,()=>n3.Y8);return(0,n.jsxs)("section",{"aria-labelledby":"settings-appearance-title",className:"@container grid gap-6",children:[(0,n.jsx)("h2",{id:"settings-appearance-title",className:"text-xl font-semibold",children:e("appearance")}),(0,n.jsxs)("div",{className:"grid min-w-0 gap-6 @min-[40rem]:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-4",children:[(0,n.jsxs)("div",{className:"space-y-2 border-b pb-4",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("theme")}),(0,n.jsx)(n2,{label:e("theme"),layout:"segmented",value:t,options:rr.map(t=>({...t,label:e(t.label)})),onChange:n5.VS})]}),(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("displaySize")}),(0,n.jsx)(n2,{label:e("displaySize"),layout:"segmented",value:s,options:ri.map(t=>({...t,label:e(t.label)})),onChange:n4.$y})]})]}),(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("displayPreview")}),(0,n.jsx)("div",{"aria-label":e("displayPreview"),className:"min-w-0 rounded-xl bg-muted p-4",children:(0,n.jsx)(rn,{mode:"static",isAnimating:!1,children:e("displayPreviewContent")})})]})]})]})}var rl=s(50163),ro=s(93780),rc=s(88707),rd=s(31848),ru=s(71057),rm=s(20476);let rp="pi-super:new-work-session-behavior",rh="activate",rg=new Set,rf=rh,rx=!1;function rb(){if(!rx){rx=!0;try{var e;e=window.localStorage.getItem(rp),rf="none"===e||"activate"===e||"pin"===e?e:rh}catch{rf=rh}}}function rv(){return rb(),rf}function rw(e){if(rb(),rf!==e){rf=e;try{window.localStorage.setItem(rp,e)}catch{}for(let e of[...rg])e()}}function ry(e){return rg.add(e),()=>rg.delete(e)}let rk=[{value:"none",label:"behaviorNone",description:"behaviorNoneDescription",icon:rl.A,testId:"new-work-session-behavior-none"},{value:"activate",label:"behaviorActivate",description:"behaviorActivateDescription",icon:ro.A,testId:"new-work-session-behavior-activate"},{value:"pin",label:"behaviorPin",description:"behaviorPinDescription",icon:rc.A,testId:"new-work-session-behavior-pin"}],rj=[{value:"compressed",label:"imageCompressed",description:"imageCompressedDescription",icon:rd.A,testId:"image-preview-mode-compressed"},{value:"original",label:"imageOriginal",description:"imageOriginalDescription",icon:ru.A,testId:"image-preview-mode-original"}];function rN(){let{t:e}=(0,b.Bd)("settings"),t=(0,r.useSyncExternalStore)(ry,rv,rv),s=(0,r.useSyncExternalStore)(rm.ku,rm.Wq,rm.Wq);return(0,n.jsxs)("section",{"aria-labelledby":"settings-habits-title",className:"@container grid min-w-0 gap-6",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"settings-habits-title",className:"text-xl font-semibold",children:e("habits")}),(0,n.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:e("browserOnly")})]}),(0,n.jsxs)("div",{className:"grid min-w-0 gap-6 lg:@min-[40rem]:grid-cols-2",children:[(0,n.jsxs)("section",{className:"hidden min-w-0 lg:block","aria-labelledby":"new-session-behavior-title",children:[(0,n.jsx)("h3",{id:"new-session-behavior-title",className:"mb-3 text-sm font-semibold",children:e("newSessionBehavior")}),(0,n.jsx)(n2,{label:e("newSessionBehavior"),value:t,options:rk.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:rw}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:e("desktopOnlyBehavior")})]}),(0,n.jsxs)("section",{className:"min-w-0 lg:border-t lg:pt-4 lg:@min-[40rem]:border-t-0 lg:@min-[40rem]:border-l lg:@min-[40rem]:pt-0 lg:@min-[40rem]:pl-6","aria-labelledby":"image-preview-mode-title",children:[(0,n.jsx)("h3",{id:"image-preview-mode-title",className:"mb-3 text-sm font-semibold",children:e("imagePreviewMode")}),(0,n.jsx)(n2,{label:e("imagePreviewMode"),value:s,options:rj.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:rm.lU}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:e("imagePreviewApply")})]})]})]})}var rI=s(17339);let rS={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function rC({projectDefaults:e}){let{t}=(0,b.Bd)("settings");return(0,n.jsx)("ul",{className:"space-y-3 px-4 pb-4",children:e.map(({cwd:e,from:s,to:r})=>(0,n.jsxs)("li",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"break-all font-medium",children:e}),(0,n.jsxs)("p",{className:"break-all text-muted-foreground",children:[s.provider,"/",s.modelId," \xb7 ",t(rS[s.thinkingLevel]),(0,n.jsx)("span",{className:"mx-1.5",children:"→"}),(0,n.jsx)("span",{className:"text-foreground",children:r?(0,n.jsxs)(n.Fragment,{children:[r.provider,"/",r.modelId," \xb7 ",t(rS[r.thinkingLevel])]}):t("clearProjectDefault")})]})]},e))})}var rE=s(26357),rM=s(70698);let rz=a.Yj().trim().min(1).max(128),rA=a.Yj().trim().min(1).max(256),r$=a.Yj().trim().min(1).max(256),rR=a.Yj().trim().min(1).nullable(),rP=a.g1(a.Yj().trim().min(1),a.Yj()),rD=a.Yj().trim().min(1).max(128),rT=a.g1(a.Yj(),a.Pq()),rO=a.Ik({level:rE.$,providerValue:a.Yj().trim().min(1).nullable()}).strict(),rL=a.Ik({input:a.ai().nonnegative().finite(),output:a.ai().nonnegative().finite(),cacheRead:a.ai().nonnegative().finite(),cacheWrite:a.ai().nonnegative().finite()}).strict(),rF=a.Ik({supportsDeveloperRole:a.zM().nullable(),thinkingFormat:a.Yj().trim().min(1).max(128).nullable(),requiresReasoningContentOnAssistantMessages:a.zM().nullable()}).strict(),rB=a.Ik({modelId:rA,name:r$,api:rD.nullable(),baseUrl:rR,reasoning:a.zM(),thinkingLevels:a.YO(rO).min(1).max(7),input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),cost:rL.nullable(),headers:rP,compat:rF.nullable()}).strict().superRefine((e,t)=>{let s=new Set;for(let n of e.thinkingLevels)s.has(n.level)&&t.addIssue({code:"custom",message:`思考等级 ${n.level} 重复`}),s.add(n.level),("xhigh"===n.level||"max"===n.level)&&null===n.providerValue&&t.addIssue({code:"custom",message:`${n.level} 必须配置 Provider 映射`});e.reasoning||1===e.thinkingLevels.length&&s.has("off")||t.addIssue({code:"custom",message:"非推理模型只允许 off 思考等级"})}),rq=a.Ik({provider:rz,name:rR,baseUrl:rR,api:rD.nullable(),apiKey:a.Yj().nullable(),authHeader:a.zM().nullable(),headers:rP,models:a.YO(rB)}).strict().superRefine((e,t)=>{let s=new Set;for(let n of e.models)s.has(n.modelId)&&t.addIssue({code:"custom",message:`模型 ${n.modelId} 重复`}),s.add(n.modelId)}),r_=a.Ik({provider:rz,modelId:rA,thinkingLevel:rE.$,color:a.Yj().regex(/^#[0-9a-fA-F]{6}$/).nullable()}).strict(),rW=a.Ik({provider:rz,modelId:rA,name:r$,input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),thinkingLevels:a.YO(rE.$).min(1).max(7)}).strict(),rY=a.Ik({provider:rz,modelId:rA,thinkingLevel:rE.$}).strict(),rV=a.Ik({contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),cost:rL.partial().optional()}).strict(),rU=a.Ik({provider:rz,modelId:rA,overrides:rV}).strict(),rH=a.Ik({provider:rz,name:r$,loggedIn:a.zM(),subscription:a.zM(),models:a.YO(rB)}).strict();a.Ik({}).strict();let rK=a.Ik({providers:a.YO(rq),presets:a.YO(r_),models:a.YO(rW),nativeConfig:rT,accountModels:a.YO(rU),accounts:a.YO(rH)}).strict(),rG=a.Ik({provider:rz,modelId:rA}).strict(),rJ=a.Ik({from:rG,to:rG}).strict(),rQ=a.Ik({providers:a.YO(rq).optional(),presets:a.YO(r_).optional(),accountModels:a.YO(rU).optional(),modelReplacements:a.YO(rJ).optional()}).strict().refine(e=>void 0!==e.providers||void 0!==e.presets||void 0!==e.accountModels,{message:"请提交需要保存的模型配置"}),rX=a.KC([rQ,a.Ik({nativeConfig:rT}).strict()]),rZ=a.Ik({}).strict(),r0=a.Ik({projectDefaults:a.YO(a.Ik({cwd:sZ.m4,from:rY,to:rY.nullable()}).strict())}).strict(),r1=a.Ik({query:a.Yj().trim().max(256),refresh:a.zM(),page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive().max(100)}).strict()}).strict(),r2=a.Ik({reasoning:a.zM(),thinkingLevels:a.YO(rO).min(1).max(7),input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),cost:rL.nullable()}).strict(),r5=a.Ik({provider:rz,providerName:r$,modelId:rA,official:a.zM(),defaults:r2}).strict(),r3=a.Ik({referenceId:a.Yj().trim().min(1).max(512),name:r$,match:a.k5(["exact","similar"]).nullable(),sources:a.YO(r5).min(1)}).strict(),r4=a.Ik({updatedAt:rM.k,refreshResult:a.k5(["not-requested","updated","unchanged","partial","cached"]),page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive(),total:a.ai().int().nonnegative()}).strict(),models:a.YO(r3)}).strict();a.Ik({cwd:sZ.m4}).strict();let r6=a.Ik({cwd:sZ.m4,default:rY.nullable(),models:a.YO(rW)}).strict(),r8=a.Ik({cwd:sZ.m4,default:rY.nullable()}).strict(),r7=a.Ik({}).strict();var r9=s(29029);let ie="pi-desk:pi-directories",it="pi-desk:ignored-pi-directories",is="pi-desk:pi-directory-entries",ir=!1,ii=null,ia=null,il=!1,io=new Map;function ic(e){if(null===e)return"<root>";let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function id(e){try{return JSON.parse(window.localStorage.getItem(e)??"null")}catch{return null}}function iu(){ir||(ir=!0,ii=id(ie),ia=id(it))}function im(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function ip(e){iu(),ii=e,im(ie,e)}function ih(){if(il)return;il=!0;let e=id(is);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.entries;if(!(!t||"object"!=typeof t||Array.isArray(t)))for(let[e,s]of Object.entries(t))io.set(e,s)}function ig(e){return ih(),io.get(ic(e))??null}let ix="pi-desk:project-model-defaults",ib=!1,iv=new Map;function iw(e){let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function iy(){if(!ib){ib=!0;try{let e=JSON.parse(window.localStorage.getItem(ix)??"null");if(!e||"object"!=typeof e||Array.isArray(e))return;for(let[t,s]of Object.entries(e)){let e=r6.safeParse(s);e.success&&iv.set(t,e.data)}let t=!1;for(;iv.size>64;){let e=iv.keys().next().value;if(void 0===e)break;iv.delete(e),t=!0}t&&ik()}catch{iv.clear()}}}function ik(){try{window.localStorage.setItem(ix,JSON.stringify(Object.fromEntries(iv)))}catch{}}function ij(e){let t=r6.safeParse(e);if(!t.success)return;iy();let s=iw(t.data.cwd);for(iv.delete(s),iv.set(s,t.data);iv.size>64;){let e=iv.keys().next().value;if(void 0===e)break;iv.delete(e)}ik()}function iN(e){let t=rX.safeParse(e);if(!t.success){let e=t.error.issues[0]?.path.at(-1);if("modelId"===e)throw Error("请填写模型 ID 后再保存配置。");if("provider"===e)throw Error("请填写 Provider ID 后再保存配置。");throw Error("模型配置不完整或格式不正确,请检查必填字段和数值。")}return t.data}let iI=a.KC([a.k5(["appearance","region","habits","auth","models","mcp-settings","capability-modes","skills","plugins","about"]),a.Uy(["plugin:",a.Yj(),":",a.Yj()])]),iS=a.k5(["providers","presets","project-default"]),iC="pi-super:settings:section",iE="pi-super:settings:model-tab";function iM(e,t,s){try{let n=t.safeParse(window.localStorage.getItem(e));return n.success?n.data:s}catch{return s}}function iz(e,t){try{window.localStorage.setItem(e,t)}catch(e){console.warn("[Pi Desk][Settings] 保存设置导航位置失败,仅当前窗口生效",e)}}function iA({open:e,text:t,error:s,saving:r,dirty:i,onChange:a,onClose:l,onSave:o}){let{t:c}=(0,b.Bd)("settings");return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||l()},children:(0,n.jsxs)(eN.hA,{className:"max-w-[52rem]",initialFocus:!1,showCloseButton:!r,children:[(0,n.jsxs)(eN.Hl,{className:"border-b px-4 py-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:c("nativeConfig")}),(0,n.jsx)(eN.uX,{children:c("nativeConfigScope")})]}),(0,n.jsx)(eN._Y,{className:"max-h-[70dvh]",children:(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(t7.T,{"aria-label":c("nativeConfigEditor"),value:t,disabled:r,spellCheck:!1,autoCapitalize:"none",autoCorrect:"off",className:"min-h-[min(28rem,50dvh)] resize-y font-mono text-sm",onChange:e=>a(e.target.value)}),s?(0,n.jsx)("p",{role:"alert",className:"break-words text-sm text-destructive",children:s}):null]})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",disabled:r,onClick:l,children:c("cancel",{ns:"common"})}),(0,n.jsxs)(I.$,{type:"button",disabled:r||!i,onClick:o,children:[r?(0,n.jsx)(v.A,{className:"animate-spin"}):null,c(r?"savingModels":"saveNativeConfig")]})]})]})})}var i$=s(43209),iR=s(54346),iP=s(55289),iD=s(24121),iT=s(78844);let iO=[{value:"#3b82f6",label:"presetColorBlue"},{value:"#0891b2",label:"presetColorCyan"},{value:"#16a34a",label:"presetColorGreen"},{value:"#b7791f",label:"presetColorAmber"},{value:"#ea580c",label:"presetColorOrange"},{value:"#dc2626",label:"presetColorRed"},{value:"#db2777",label:"presetColorPink"},{value:"#8b5cf6",label:"presetColorPurple"}];function iL(e){return iO.map(({value:t})=>({value:t,count:e.filter(e=>e.color?.toLowerCase()===t).length})).reduce((e,t)=>t.count<e.count?t:e).value}let iF=["OpenAI Chat Completions","OpenAI Responses","Anthropic Messages","Google Generative AI","Mistral Conversations","Azure OpenAI Responses","OpenAI Codex Responses","Amazon Bedrock","Google Vertex AI","Pi Messages"],iB=["openai-completions","openai-responses","anthropic-messages","google-generative-ai","mistral-conversations","azure-openai-responses","openai-codex-responses","bedrock-converse-stream","google-vertex","pi-messages"].map((e,t)=>({value:e,label:iF[t]})),iq=["openai","openrouter","together","deepseek","zai","qwen","chat-template","qwen-chat-template","string-thinking","ant-ling","baseten"];function i_(e){return Object.entries(e).map(([e,t])=>`${e}: ${t}`).join("\n")}function iW({headers:e,onChange:t,placeholder:s}){let[i,a]=(0,r.useState)(null);return(0,n.jsx)(t7.T,{value:i??i_(e),onFocus:()=>a(i_(e)),onChange:e=>{let s=e.target.value;a(s),t(Object.fromEntries(s.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(":");return t>0?[e.slice(0,t).trim(),e.slice(t+1).trim()]:[e,""]})))},onBlur:()=>a(null),rows:4,placeholder:s,className:"font-mono"})}function iY(e){let t=Math.floor(e/1e3),s=e%1e3;return s?`${t}.${String(s).padStart(3,"0").replace(/0+$/,"")}`:String(t)}function iV(e){if(!/^\d+(?:\.\d{0,3})?$/.test(e))return null;let[t,s=""]=e.split("."),n=1e3*Number(t)+Number(s.padEnd(3,"0"));return Number.isSafeInteger(n)&&n>0?n:null}function iU({label:e,children:t,className:s}){return(0,n.jsxs)("label",{className:(0,C.cn)("grid gap-1 text-sm text-foreground",s),children:[(0,n.jsx)("span",{className:"font-medium",children:e}),t]})}let iH="__pi-desk_empty__";function iK({value:e,options:t,onChange:s,ariaLabel:r,placeholder:i,allowEmpty:a=!0,className:l}){let{t:o}=(0,b.Bd)("settings"),c=i??o("useDefault"),d=e||(a?iH:t[0]?.value??null),u=!!e&&!t.some(t=>t.value===e);return(0,n.jsxs)(ea.l6,{value:d,onValueChange:e=>s(e===iH||null===e?"":e),children:[(0,n.jsx)(ea.bq,{"aria-label":r,className:(0,C.cn)("w-full",l),children:(0,n.jsx)(ea.yv,{children:t.find(t=>t.value===e)?.label??(e||c)})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[a?(0,n.jsx)(ea.eb,{value:iH,children:c}):null,u?(0,n.jsx)(ea.eb,{value:e,children:e}):null,t.map(e=>(0,n.jsx)(ea.eb,{value:e.value,children:e.label},e.value))]})]})}function iG({value:e,onChange:t,ariaLabel:s}){let{t:r}=(0,b.Bd)("settings");return(0,n.jsx)(iK,{value:null===e?"":String(e),ariaLabel:s,options:[{value:"true",label:r("yes")},{value:"false",label:r("no")}],onChange:e=>t(""===e?null:"true"===e)})}let iJ={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function iQ(e,t){return JSON.stringify([e,t])}function iX(e,t){return JSON.stringify([e.provider,e.modelId,e.thinkingLevel,t])}function iZ(e){return e.map(e=>({value:iQ(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider}))}function i0(e,t){return(e?.thinkingLevels??[]).map(e=>({value:e,label:t(iJ[e])}))}function i1({id:e,preset:t,model:s,models:r,canMoveUp:i,canMoveDown:a,onChange:l,onDelete:o,onMoveUp:c,onMoveDown:d}){let{t:u}=(0,b.Bd)("settings"),{attributes:m,listeners:p,setActivatorNodeRef:h,setNodeRef:g,transform:f,transition:x,isDragging:v}=(0,iR.gl)({id:e}),w=f?`translate3d(${f.x}px, ${f.y}px, 0) scaleX(${f.scaleX??1}) scaleY(${f.scaleY??1})`:void 0,y=t.color?.toLowerCase()??"none",k=iO.find(e=>e.value===y),j=k?u(k.label):u(t.color?"presetColorCustom":"presetColorNone"),N=[{value:"none",color:null,label:u("presetColorNone")},...t.color&&!k?[{value:y,color:t.color,label:u("presetColorCustom")}]:[],...iO.map(e=>({value:e.value,color:e.value,label:u(e.label)}))];return(0,n.jsxs)("div",{ref:g,style:{transform:w,transition:x},className:(0,C.cn)("grid min-w-0 items-center gap-3 border-b bg-card py-3 @[48rem]/presets:grid-cols-[auto_minmax(0,1fr)_7.5rem_4rem_auto]",v&&"z-10 opacity-70 shadow-lg"),children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(I.$,{variant:"ghost",size:"icon-sm",ref:h,type:"button",title:u("presetDrag"),"aria-label":u("presetDrag"),className:"touch-none cursor-grab text-muted-foreground active:cursor-grabbing",...m,...p,children:(0,n.jsx)(iP.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(I.$,{variant:"ghost",size:"icon-sm",type:"button",title:u("presetMoveUp"),"aria-label":u("presetMoveUp"),disabled:!i,onClick:c,children:(0,n.jsx)(iD.A,{className:"size-4"})}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon-sm",type:"button",title:u("presetMoveDown"),"aria-label":u("presetMoveDown"),disabled:!a,onClick:d,children:(0,n.jsx)(eY.A,{className:"size-4"})})]})]}),(0,n.jsx)(iU,{label:u("modelsHeading"),children:(0,n.jsx)(nV.b,{value:iQ(t.provider,t.modelId),options:iZ(r),ariaLabel:u("presetModel"),searchPlaceholder:u("modelSearch"),onChange:e=>{let s=r.find(t=>iQ(t.provider,t.modelId)===e);s&&l({...t,provider:s.provider,modelId:s.modelId,thinkingLevel:s.thinkingLevels.includes(t.thinkingLevel)?t.thinkingLevel:s.thinkingLevels[0]})}})}),(0,n.jsx)(iU,{label:u("thinkingLevel"),children:(0,n.jsx)(iK,{value:t.thinkingLevel,options:i0(s,u),ariaLabel:u("presetThinking"),allowEmpty:!1,onChange:e=>l({...t,thinkingLevel:e})})}),(0,n.jsx)(iU,{label:u("presetColor"),children:(0,n.jsxs)(ea.l6,{value:y,onValueChange:e=>{null!==e&&l({...t,color:"none"===e?null:e})},children:[(0,n.jsx)(ea.bq,{"aria-label":u("presetColorLabel"),className:"w-16",children:(0,n.jsxs)(ea.yv,{children:[t.color?(0,n.jsx)("span",{"aria-hidden":"true",className:"size-4 shrink-0 rounded-full",style:{backgroundColor:t.color}}):(0,n.jsx)(iT.A,{"aria-hidden":"true",className:"size-4 text-muted-foreground"}),(0,n.jsx)("span",{className:"sr-only",children:j})]})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[120]",className:"w-40 min-w-40",align:"end",alignItemWithTrigger:!1,children:(0,n.jsx)(ea.s3,{className:"grid grid-cols-4 gap-1 p-2",children:N.map(e=>(0,n.jsx)(ea.eb,{value:e.value,label:e.label,"aria-label":e.label,className:"size-8 justify-center p-0 data-selected:bg-accent data-selected:ring-1 data-selected:ring-ring data-selected:ring-inset [&>span:first-child]:justify-center [&>span:last-child]:hidden",children:e.color?(0,n.jsx)("span",{"aria-hidden":"true",className:"size-4 shrink-0 self-center rounded-full",style:{backgroundColor:e.color}}):(0,n.jsx)(iT.A,{"aria-hidden":"true",className:"size-4 text-muted-foreground"})},e.value))})})]})}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm",title:u("presetDelete"),"aria-label":u("presetDelete"),onClick:o,children:(0,n.jsx)(et.A,{})})]})}function i2({presets:e,models:t,onChange:s}){let{t:i}=(0,b.Bd)("settings"),[a,l]=(0,r.useState)(()=>t[0]?iQ(t[0].provider,t[0].modelId):""),o=t.find(e=>iQ(e.provider,e.modelId)===a),[c,d]=(0,r.useState)(o?.thinkingLevels[0]??"off"),u=(0,i$.FR)((0,i$.MS)(i$.AN,{activationConstraint:{distance:6}}),(0,i$.MS)(i$.uN,{coordinateGetter:iR.JR})),m=(0,r.useMemo)(()=>e.map(iX),[e]);return(0,n.jsxs)("div",{className:"@container/presets space-y-4 p-4 sm:p-6",children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:i("presetDescription")}),(0,n.jsxs)("div",{className:"grid gap-3 border-b pb-4 @[32rem]/presets:grid-cols-[minmax(0,1fr)_7.5rem_auto]",children:[(0,n.jsx)(iU,{label:i("modelsHeading"),children:(0,n.jsx)(nV.b,{value:a,options:iZ(t),ariaLabel:i("presetModelNew"),searchPlaceholder:i("modelSearch"),disabled:0===t.length,onChange:e=>{l(e);let s=t.find(t=>iQ(t.provider,t.modelId)===e);s&&d(s.thinkingLevels[0])}})}),(0,n.jsx)(iU,{label:i("thinkingLevel"),children:(0,n.jsx)(iK,{value:c,options:i0(o,i),ariaLabel:i("presetThinkingNew"),allowEmpty:!1,onChange:e=>d(e)})}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",className:"self-end justify-self-start",onClick:function(){let n=t.find(e=>iQ(e.provider,e.modelId)===a);if(!n)return;let r=n.thinkingLevels.includes(c)?c:n.thinkingLevels[0];e.some(e=>e.provider===n.provider&&e.modelId===n.modelId&&e.thinkingLevel===r)||s([...e,{provider:n.provider,modelId:n.modelId,thinkingLevel:r,color:iL(e)}])},disabled:!o,children:[(0,n.jsx)(U.A,{})," ",i("presetAdd")]})]}),0===e.length?(0,n.jsx)("p",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:i("presetEmpty")}):(0,n.jsx)(i$.Mp,{sensors:u,collisionDetection:i$.fp,onDragEnd:function(t){if(!t.over||t.active.id===t.over.id)return;let n=m.indexOf(String(t.active.id)),r=m.indexOf(String(t.over.id));n>=0&&r>=0&&s((0,iR.be)(e,n,r))},children:(0,n.jsx)(iR.gB,{items:m,strategy:iR._G,children:(0,n.jsx)("div",{className:"space-y-2",children:e.map((r,i)=>{let a=t.find(e=>e.provider===r.provider&&e.modelId===r.modelId);return(0,n.jsx)(i1,{id:m[i],preset:r,model:a,models:t,canMoveUp:i>0,canMoveDown:i<e.length-1,onChange:t=>s(e.map((e,s)=>s===i?t:e)),onDelete:()=>s(e.filter((e,t)=>t!==i)),onMoveUp:()=>s((0,iR.be)(e,i,i-1)),onMoveDown:()=>s((0,iR.be)(e,i,i+1))},m[i])})})})})]})}var i5=s(72910),i3=s(61108),i4=s(46783),i6=s(89790);function i8(e){return 100*!!e.official+10*!!e.defaults.cost}let i7=[["off","thinkingOff"],["minimal","thinkingMinimal"],["low","thinkingLow"],["medium","thinkingMedium"],["high","thinkingHigh"],["xhigh","thinkingXhigh"],["max","thinkingMax"]],i9=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function ae(e){return{input:String(e.cost?.input??""),output:String(e.cost?.output??""),cacheRead:String(e.cost?.cacheRead??""),cacheWrite:String(e.cost?.cacheWrite??"")}}function at(e,t){return Object.values(e).some(e=>null===iV(e))||Object.values(t).some(e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e)))}function as({biz:e,provider:t,model:s,onChange:i,onInputState:a}){let{t:l}=(0,b.Bd)("settings"),o=(0,r.useId)(),[c,d]=(0,r.useState)({contextWindow:iY(s.contextWindow),maxTokens:iY(s.maxTokens)}),[u,m]=(0,r.useState)(()=>ae(s)),{searchText:p,setSearchText:h,catalogOpen:g,setCatalogOpen:f,loadingCatalog:x,candidates:w,visibleCandidates:y,showAllCandidates:k,setShowAllCandidates:j,selectedCandidateKey:N,setSelectedCandidateKey:S}=function(e,t){let{t:s}=(0,b.Bd)("settings"),n=(0,X.G)(),i=(0,r.useRef)(0),[a,l]=(0,r.useState)(t),[o,c]=(0,r.useState)([]),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(!1),v=(0,r.useMemo)(()=>{let e=new Map,t=o.filter(e=>"exact"===e.match);for(let s of t.length?t:o)for(let t of s.sources){let n=JSON.stringify([s.referenceId,t.modelId,t.defaults]),r=e.get(n);r?r.sources.push(t):e.set(n,{item:s,sources:[t]})}let s=a.trim().toLocaleLowerCase();return[...e.entries()].map(([e,t])=>{let s=[...t.sources].sort((e,t)=>i8(t)-i8(e)||e.providerName.localeCompare(t.providerName)),n=s[0];return{key:e,item:t.item,source:n,equivalentSourceCount:s.length,recommended:n.official}}).sort((e,t)=>("exact"===e.item.match?0:"similar"===e.item.match?1:2)-("exact"===t.item.match?0:"similar"===t.item.match?1:2)||Number(t.recommended)-Number(e.recommended)||Number(t.source.modelId.toLocaleLowerCase()===s)-Number(e.source.modelId.toLocaleLowerCase()===s)||e.source.providerName.localeCompare(t.source.providerName))},[o,a]);return(0,r.useEffect)(()=>{let t=++i.current;if(!d)return;let r=window.setTimeout(()=>{g(!0),e.listCatalog({query:a.trim(),refresh:!1,page:{index:1,size:10}}).then(e=>{i.current===t&&c(e.models)}).catch(e=>{i.current===t&&(c([]),n.error(e instanceof Error?e.message:s("catalogSearchFailed")))}).finally(()=>{i.current===t&&g(!1)})},250);return()=>{window.clearTimeout(r),i.current===t&&(i.current+=1)}},[e,d,a,n,s]),{searchText:a,setSearchText:l,catalogOpen:d,setCatalogOpen:e=>{u(e),e||g(!1)},loadingCatalog:h,candidates:v,visibleCandidates:f?v:v.slice(0,6),showAllCandidates:f,setShowAllCandidates:x,selectedCandidateKey:m,setSelectedCandidateKey:p}}(e,s.modelId),C=new Map(s.thinkingLevels.map(e=>[e.level,e])),E=iB.find(e=>e.value===t.api)?.label??t.api;function M(e){i({...s,...e})}return(0,n.jsxs)("div",{className:"@container/model-editor space-y-6",children:[(0,n.jsxs)("div",{className:"grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[(0,n.jsxs)("div",{className:"grid gap-1 text-sm @[32rem]/model-editor:col-span-2",children:[(0,n.jsx)("label",{htmlFor:o,className:"font-medium",children:l("modelId")}),(0,n.jsx)(i6.uB,{shouldFilter:!1,loop:!0,className:"h-auto w-full overflow-visible rounded-none bg-transparent p-0 [&_[data-slot=command-input-wrapper]]:p-0 [&_[data-slot=input-group-addon]]:hidden",onKeyDown:e=>{"Escape"===e.key&&g&&(e.preventDefault(),e.stopPropagation(),f(!1))},children:(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(i6.G7,{id:o,value:p,onValueChange:e=>{h(e),M({modelId:e}),S(null),j(!1),f(!0)},placeholder:l("modelIdSearch"),"aria-label":l("modelId"),"aria-autocomplete":"list",className:"pr-9"}),(0,n.jsxs)(eW.AM,{open:g,onOpenChange:e=>{f(e),e&&j(!1)},children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm",title:l("chooseModel"),"aria-label":l("chooseModel"),"aria-busy":x,className:"absolute top-0.5 right-0.5 z-10",children:x?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(i4.A,{})})}),(0,n.jsx)(eW.hl,{align:"end",sideOffset:4,initialFocus:!1,finalFocus:!1,positionerClassName:"z-[120]",className:"w-[min(32rem,calc(100vw-2rem))] gap-0 p-0",children:(0,n.jsx)(i6.oI,{className:"max-h-[min(24rem,var(--available-height))] p-1",children:x&&0===w.length?(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:l("matchingCatalog")}):0===w.length?(0,n.jsx)(i6.xL,{className:"py-6 text-sm",children:l("noCatalogMatches")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(i6.L$,{className:"p-0",children:y.map(e=>(0,n.jsx)(i6.h_,{value:e.key,"data-checked":N===e.key?"true":void 0,className:"px-3 py-2",onSelect:()=>(function(e){let{item:t,source:n}=e,r={...s,modelId:n.modelId,name:t.name,...n.defaults};i(r),d({contextWindow:iY(r.contextWindow),maxTokens:iY(r.maxTokens)}),m(ae(r)),a({dirty:!1,invalid:!1}),h(n.modelId),S(e.key),j(!1),f(!1)})(e),children:(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("span",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("span",{className:"break-all font-mono text-sm font-semibold",children:e.source.modelId}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.source.providerName})]}),(0,n.jsxs)("span",{className:"mt-1 block text-xs text-muted-foreground",children:[e.item.name," \xb7"," ",l("contextAndOutput",{context:`${iY(e.source.defaults.contextWindow)}K`,output:`${iY(e.source.defaults.maxTokens)}K`})]}),(0,n.jsx)("span",{className:"mt-1 block text-xs text-muted-foreground",children:e.source.defaults.cost?`${l("priceInput",{price:`$${e.source.defaults.cost.input}`})} \xb7 ${l("priceOutput",{price:`$${e.source.defaults.cost.output}`})}${l("perMillionTokens")}`:l("priceMissing")})]})},e.key))}),!k&&w.length>y.length?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:()=>j(!0),children:l("moreConfigurations",{count:w.length-y.length})}):null]})})})]})]})}),s.modelId.trim()?null:(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("modelIdRequired")})]}),(0,n.jsxs)(iU,{label:l("modelName"),className:"@[32rem]/model-editor:col-span-2",children:[(0,n.jsx)(em.p,{value:s.name,onChange:e=>M({name:e.target.value})}),s.name.trim()?null:(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("modelNameRequired")})]}),[["contextWindow","contextLength"],["maxTokens","maximumOutput"]].map(([e,t])=>{let s=null===iV(c[e]);return(0,n.jsxs)(iU,{label:l(t),children:[(0,n.jsxs)(nC.MG,{children:[(0,n.jsx)(nC.iV,{"aria-label":l(t),inputMode:"decimal",value:c[e],"aria-invalid":s,"aria-describedby":s?`${o}-${e}-error`:void 0,onChange:t=>{var s;let n,r,i;return s=t.target.value,d(n={...c,[e]:s}),a({dirty:r=at(n,u),invalid:r}),void(null!==(i=iV(s))&&M({[e]:i}))}}),(0,n.jsx)(nC.Sq,{align:"inline-end",children:"K"})]}),s?(0,n.jsx)("span",{id:`${o}-${e}-error`,role:"alert",className:"text-xs text-destructive",children:l("capacityInvalid")}):null]},e)})]}),(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:l("capabilities")}),(0,n.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2 text-sm",children:[s.input.map(e=>(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-1",children:l("text"===e?"textInput":"imageInput")},e)),s.reasoning?(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-1",children:l("supportsThinking")}):null]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("inputAndThinking")}),(0,n.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:[["text","image"].map(e=>{let t=s.input.includes(e);return(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline","aria-pressed":t,onClick:()=>{t&&1===s.input.length||M({input:t?s.input.filter(t=>t!==e):[...s.input,e]})},children:[t?(0,n.jsx)(ep.A,{}):null,l("text"===e?"textInput":"imageInput")]},e)}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline","aria-pressed":s.reasoning,onClick:()=>M({reasoning:!s.reasoning,thinkingLevels:s.reasoning?[{level:"off",providerValue:null}]:[{level:"high",providerValue:null}]}),children:[s.reasoning?(0,n.jsx)(ep.A,{}):null,l("supportsThinking")]})]}),s.reasoning?(0,n.jsxs)("details",{className:"mt-4 border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-medium",children:l("thinkingMapping")}),(0,n.jsx)("div",{className:"mt-2 grid max-w-[40rem] gap-x-4 @[32rem]/model-editor:grid-cols-2",children:i7.map(([e,t])=>{let r=C.get(e);return(0,n.jsxs)("div",{className:"grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-2 border-b py-2",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm","aria-pressed":!!r,className:"justify-start",onClick:()=>{let t=r?s.thinkingLevels.filter(t=>t.level!==e):[...s.thinkingLevels,{level:e,providerValue:"off"===e?null:e}];t.length&&M({thinkingLevels:t})},children:[r?(0,n.jsx)(ep.A,{}):null,l(t)]}),(0,n.jsx)(em.p,{"aria-label":l("providerMapping",{level:l(t)}),disabled:!r||"off"===e,value:"off"===e?l("noMapping"):r?.providerValue??"",placeholder:e,onChange:t=>M({thinkingLevels:s.thinkingLevels.map(s=>s.level===e?{...s,providerValue:t.target.value||null}:s)})})]},e)})})]}):null]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("price")}),(0,n.jsxs)("div",{className:"mt-3 grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[i9.map(([e,t])=>{let r=""!==u[e]&&(!Number.isFinite(Number(u[e]))||0>Number(u[e]));return(0,n.jsxs)(iU,{label:l(t),children:[(0,n.jsx)(em.p,{inputMode:"decimal",value:u[e],"aria-invalid":r,onChange:t=>(function(e,t){let n={...u,[e]:t};m(n);let r=at(c,n);if(a({dirty:r,invalid:r}),Object.values(n).every(e=>""===e))return void M({cost:null});let i=Number(t);Number.isFinite(i)&&!(i<0)&&M({cost:{input:s.cost?.input??0,output:s.cost?.output??0,cacheRead:s.cost?.cacheRead??0,cacheWrite:s.cost?.cacheWrite??0,[e]:i}})})(e,t.target.value)}),r?(0,n.jsx)("span",{role:"alert",className:"text-xs text-destructive",children:l("priceInvalid")}):null]},e)}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",className:"justify-self-start",onClick:()=>{let e={input:"",output:"",cacheRead:"",cacheWrite:""};m(e),a({dirty:!0,invalid:at(c,e)}),M({cost:null})},children:l("clearPrice")})]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("advancedCompatibility")}),(0,n.jsxs)("div",{className:"mt-3 grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[(0,n.jsx)(iU,{label:l("apiOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(iK,{value:s.api??"",ariaLabel:l("apiOverride"),options:iB,placeholder:E?l("inheritServiceValue",{value:E}):l("inheritService"),onChange:e=>M({api:e||null})})}),(0,n.jsx)(iU,{label:l("baseUrlOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(em.p,{value:s.baseUrl??"","aria-label":l("baseUrlOverride"),placeholder:t.baseUrl?l("inheritServiceValue",{value:t.baseUrl}):l("inheritService"),onChange:e=>M({baseUrl:e.target.value||null})})}),(0,n.jsx)(iU,{label:l("modelHeaders"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(iW,{headers:s.headers,onChange:e=>M({headers:e}),placeholder:l("headerPlaceholder")})}),(0,n.jsx)(iU,{label:l("developerRole"),children:(0,n.jsx)(iG,{value:s.compat?.supportsDeveloperRole??null,ariaLabel:l("developerRole"),onChange:e=>M({compat:{supportsDeveloperRole:e,thinkingFormat:s.compat?.thinkingFormat??null,requiresReasoningContentOnAssistantMessages:s.compat?.requiresReasoningContentOnAssistantMessages??null}})})}),(0,n.jsx)(iU,{label:"Thinking Format",children:(0,n.jsx)(iK,{value:s.compat?.thinkingFormat??"",ariaLabel:"Thinking Format",options:iq.map(e=>({value:e,label:e})),onChange:e=>M({compat:{supportsDeveloperRole:s.compat?.supportsDeveloperRole??null,thinkingFormat:e||null,requiresReasoningContentOnAssistantMessages:s.compat?.requiresReasoningContentOnAssistantMessages??null}})})}),(0,n.jsx)(iU,{label:l("replayReasoning"),children:(0,n.jsx)(iG,{value:s.compat?.requiresReasoningContentOnAssistantMessages??null,ariaLabel:l("replayReasoning"),onChange:e=>M({compat:{supportsDeveloperRole:s.compat?.supportsDeveloperRole??null,thinkingFormat:s.compat?.thinkingFormat??null,requiresReasoningContentOnAssistantMessages:e}})})})]})]})]})}var an=s(66153),ar=s(95929);function ai({className:e,disabled:t,id:s,...i}){let{t:a}=(0,b.Bd)("common"),[l,o]=r.useState(!1),c=a(l?"hideSecret":"revealSecret");return(0,n.jsxs)("div",{className:"relative min-w-0",children:[(0,n.jsx)(em.p,{...i,id:s,disabled:t,type:"text",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,className:(0,C.cn)("pr-9",!l&&"[-webkit-text-security:disc]",e)}),(0,n.jsx)("button",{type:"button",className:"absolute top-1/2 right-1 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50","aria-label":c,"aria-controls":s,"aria-pressed":l,title:c,disabled:t,onClick:()=>o(e=>!e),children:l?(0,n.jsx)(an.A,{className:"size-3.5"}):(0,n.jsx)(ar.A,{className:"size-3.5"})})]})}function aa({provider:e,existingIds:t,isNew:s,onApply:i,onDelete:a,onClose:l,onDirtyChange:o}){let{t:c}=(0,b.Bd)("settings"),{confirm:d,dialog:u}=nF(),[m,p]=(0,r.useState)(()=>structuredClone(e)),h=JSON.stringify(m)!==JSON.stringify(e),g=!m.provider.trim()||t.includes(m.provider.trim()),f=m.provider||c("providerUnnamed");function x(e){p(t=>({...t,...e}))}async function v(){(!h||await d({title:c("discardServiceTitle"),description:c("discardServiceDescription"),confirmLabel:c("discardModelConfirm")}))&&l()}async function w(){await d({title:c("providerDeleteTitle"),description:c("providerDeleteDescription",{name:f,count:e.models.length})})&&a()}return(0,r.useEffect)(()=>(o(h),()=>o(!1)),[h,o]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||v()},children:(0,n.jsxs)(eN.hA,{className:"max-w-[40rem]",initialFocus:!1,children:[(0,n.jsxs)(eN.Hl,{className:"border-b px-4 py-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:c("serviceConnection")}),(0,n.jsx)(eN.uX,{children:c("serviceDraftScope",{count:e.models.length})})]}),(0,n.jsx)(eN._Y,{className:"max-h-[65dvh]",children:(0,n.jsxs)("div",{className:"space-y-5 p-4",children:[(0,n.jsxs)(iU,{label:c("serviceId"),children:[(0,n.jsx)(em.p,{value:m.provider,"aria-label":c("serviceId"),autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:c("providerIdExample"),"aria-invalid":g,onChange:e=>x({provider:e.target.value})}),g?(0,n.jsx)("span",{role:"alert",className:"text-xs text-destructive",children:c("serviceIdInvalid")}):null]}),(0,n.jsx)(iU,{label:c("serviceAddress"),children:(0,n.jsx)(em.p,{value:m.baseUrl??"",placeholder:"https://api.example.com/v1",onChange:e=>x({baseUrl:e.target.value||null})})}),(0,n.jsx)(iU,{label:c("providerApiType"),children:(0,n.jsx)(iK,{value:m.api??"",ariaLabel:c("providerApiType"),options:iB,onChange:e=>x({api:e||null})})}),(0,n.jsx)(iU,{label:c("serviceKey"),children:(0,n.jsx)(ai,{value:m.apiKey??"",onChange:e=>x({apiKey:e.target.value||null})})}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:c("providerAdvanced")}),(0,n.jsxs)("div",{className:"mt-3 space-y-3",children:[(0,n.jsx)(iU,{label:c("providerAuthHeader"),children:(0,n.jsx)(iG,{value:m.authHeader,ariaLabel:c("providerAuthHeader"),onChange:e=>x({authHeader:e})})}),(0,n.jsx)(iU,{label:c("providerHeaders"),children:(0,n.jsx)(iW,{headers:m.headers,onChange:e=>x({headers:e}),placeholder:c("headerPlaceholder")})})]})]})]})}),(0,n.jsxs)(eN.vu,{children:[s?null:(0,n.jsxs)(I.$,{type:"button",variant:"ghost",className:"mr-auto text-destructive hover:text-destructive",onClick:w,children:[(0,n.jsx)(et.A,{}),c("providerDelete")]}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:l,children:c("cancel",{ns:"common"})}),(0,n.jsx)(I.$,{type:"button",disabled:g||!h&&!s,onClick:()=>i(m),children:c("applyServiceDraft")})]})]})}),u]})}let al=a.Ik({}).strict(),ao=a.Yj().trim().min(1).max(128),ac=a.Yj().max(32768),ad=a.Ik({url:ac,label:ac.optional()}).strict(),au=a.Ik({provider:ao,name:ac,loggedIn:a.zM(),conflict:a.Yj().nullable()}).strict(),am=a.Ik({id:a.Yj().uuid(),type:a.k5(["text","secret","select","manual_code"]),message:ac,placeholder:ac.optional(),options:a.YO(a.Ik({id:ac,label:ac,description:ac.optional()}).strict()).optional()}).strict(),ap=a.gM("type",[a.Ik({type:a.eu("auth_url"),url:ac,instructions:ac.optional()}).strict(),a.Ik({type:a.eu("device_code"),userCode:ac,verificationUri:ac}).strict(),a.Ik({type:a.eu("info"),message:ac,links:a.YO(ad).optional()}).strict(),a.Ik({type:a.eu("progress"),message:ac}).strict()]),ah=a.Ik({loginId:a.Yj().uuid(),provider:ao,status:a.k5(["running","completed","cancelled","error"]),notice:ap.nullable(),prompt:am.nullable(),message:a.Yj().nullable()}).strict(),ag=Object.freeze({list:(0,l.Vc)({path:"model-auth/list",inputSchema:al,outputSchema:a.Ik({providers:a.YO(au)}).strict()}),start:(0,l.Vc)({path:"model-auth/start",inputSchema:a.Ik({loginId:a.Yj().uuid(),provider:ao}).strict(),outputSchema:al}),respond:(0,l.Vc)({path:"model-auth/respond",inputSchema:a.Ik({loginId:a.Yj().uuid(),promptId:a.Yj().uuid(),value:ac}).strict(),outputSchema:al}),cancel:(0,l.Vc)({path:"model-auth/cancel",inputSchema:a.Ik({loginId:a.Yj().uuid()}).strict(),outputSchema:al}),logout:(0,l.Vc)({path:"model-auth/logout",inputSchema:a.Ik({provider:ao}).strict(),outputSchema:al}),state:(0,l._G)({path:"model-auth/state",bodySchema:ah})});function af(e){try{let t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}}function ax(e){let t=af(e);t&&window.open(t,"_blank","noopener,noreferrer")}async function ab(e){await navigator.clipboard.writeText(e)}function av({prompt:e,submitting:t,onRespond:s}){let{t:i}=(0,b.Bd)("settings"),[a,l]=(0,r.useState)(""),o="select"!==e.type||a.length>0;return(0,n.jsxs)("form",{className:"grid gap-3",onSubmit:n=>{n.preventDefault(),o&&!t&&s(e.id,a)},children:[(0,n.jsx)(iU,{label:e.message,children:"select"===e.type?(0,n.jsx)(iK,{value:a,ariaLabel:e.message,placeholder:e.placeholder??i("accountChooseOption"),options:(e.options??[]).map(e=>({value:e.id,label:e.description?`${e.label} — ${e.description}`:e.label})),onChange:l}):"secret"===e.type?(0,n.jsx)(ai,{value:a,placeholder:e.placeholder,disabled:t,onChange:e=>l(e.target.value)}):(0,n.jsx)(em.p,{value:a,placeholder:e.placeholder,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,disabled:t,onChange:e=>l(e.target.value)})}),(0,n.jsx)(I.$,{type:"submit",disabled:!o||t,className:"justify-self-end",children:i("accountContinue")})]})}function aw({notice:e,onCopy:t,onOpenUrl:s}){let{t:r}=(0,b.Bd)("settings"),i="auth_url"===e.type?[{url:e.url}]:"device_code"===e.type?[{url:e.verificationUri}]:"info"===e.type?e.links??[]:[];return(0,n.jsxs)("div",{className:"space-y-3",children:["auth_url"===e.type&&e.instructions?(0,n.jsx)("p",{className:"whitespace-pre-wrap text-sm",children:e.instructions}):null,"info"===e.type||"progress"===e.type?(0,n.jsx)("p",{className:"whitespace-pre-wrap text-sm",role:"status",children:e.message}):null,"device_code"===e.type?(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-lg border p-3",children:[(0,n.jsx)("span",{className:"text-sm",children:r("accountDeviceCode")}),(0,n.jsx)("code",{className:"select-all break-all text-lg font-semibold",children:e.userCode}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void t(e.userCode),children:r("accountCopyCode")})]}):null,i.map((e,i)=>af(e.url)?(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("p",{className:"break-all text-sm text-muted-foreground",children:e.url}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>s(e.url),children:e.label??r("accountOpenLink")}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>void t(e.url),children:r("accountCopyLink")})]})]},`${i}:${e.url}`):(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:r("accountInvalidLink")},i))]})}function ay({open:e,connected:t,providers:s,state:r,loading:i,submitting:a,error:l,onClose:o,onStart:c,onRespond:d,onCopy:u,onOpenUrl:m,onRetry:p}){let{t:h}=(0,b.Bd)("settings"),g=r?.status==="running";return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||o()},children:(0,n.jsxs)(eN.hA,{className:"max-w-lg",children:[(0,n.jsx)(eN.Hl,{className:"border-b p-4 pr-12",children:(0,n.jsx)(eN.YM,{children:r?s.find(e=>e.provider===r.provider)?.name??r.provider:h("accountLogin")})}),(0,n.jsx)(eN._Y,{className:"max-h-[65dvh]",children:(0,n.jsxs)("div",{className:"space-y-4 p-4",children:[l?(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive",children:l}):null,r?.message?(0,n.jsx)("p",{role:"error"===r.status?"alert":"status",className:"whitespace-pre-wrap text-sm",children:r.message}):null,r&&"cancelled"!==r.status&&"error"!==r.status?null:i?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:h("accountLoadingProviders")}):(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:h("accountChooseProvider")}),s.length?null:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:h("accountNoProviders")}),s.map(e=>(0,n.jsxs)("div",{className:"grid gap-1",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",className:"h-auto min-h-10 justify-between whitespace-normal text-left",disabled:!t||!!e.conflict,onClick:()=>void c(e.provider),children:[(0,n.jsx)("span",{children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.loggedIn?h("accountRelogin"):h("accountLogin")})]}),e.conflict?(0,n.jsx)("p",{className:"text-sm text-destructive",children:e.conflict}):null]},e.provider))]}),g&&r.notice?(0,n.jsx)(aw,{notice:r.notice,onCopy:u,onOpenUrl:m}):null,g&&r.prompt?(0,n.jsx)(av,{prompt:r.prompt,submitting:a||!t,onRespond:d},r.prompt.id):null,g&&!r.prompt?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:h("accountWaiting")}):null,r?.status==="completed"?(0,n.jsx)("p",{role:"status",className:"text-sm",children:h("accountLoggedIn")}):null]})}),(0,n.jsxs)(eN.vu,{children:[l&&!g?(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:i,onClick:p,children:h("retry",{ns:"common"})}):null,(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:o,children:h(g?"cancel":"close",{ns:"common"})})]})]})})}function ak({account:e,existingIds:t,onAdd:s,onClose:i}){let{t:a}=(0,b.Bd)("settings"),[l,o]=(0,r.useState)(""),[c,d]=(0,r.useState)([]),u=e.models.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(l.toLocaleLowerCase()));return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||i()},children:(0,n.jsxs)(eN.hA,{className:"max-w-xl",children:[(0,n.jsx)(eN.Hl,{className:"border-b p-4 pr-12",children:(0,n.jsx)(eN.YM,{children:a("modelAddToService",{name:e.name})})}),(0,n.jsx)("div",{className:"p-4 pb-2",children:(0,n.jsx)(em.p,{value:l,"aria-label":a("accountModelSearch"),placeholder:a("accountModelSearch"),onChange:e=>o(e.target.value)})}),(0,n.jsx)(eN._Y,{className:"max-h-[55dvh]",children:(0,n.jsxs)("div",{className:"space-y-1 px-4 pb-4",children:[u.map(e=>{let s=t.includes(e.modelId);return(0,n.jsxs)("label",{className:"flex min-h-14 cursor-pointer items-center gap-3 rounded-lg px-3 py-2 hover:bg-accent",children:[(0,n.jsx)("input",{type:"checkbox",className:"size-4 shrink-0 accent-primary",checked:s||c.includes(e.modelId),disabled:s,onChange:t=>d(s=>t.target.checked?[...s,e.modelId]:s.filter(t=>t!==e.modelId))}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block break-words text-sm font-medium",children:e.name}),(0,n.jsxs)("span",{className:"block break-all text-xs text-muted-foreground",children:[e.modelId," \xb7 ",iY(e.contextWindow)," K"]})]}),s?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:a("accountModelAdded")}):null]},e.modelId)}),u.length?null:(0,n.jsx)("p",{className:"py-6 text-center text-sm text-muted-foreground",children:a("accountNoModels")})]})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:i,children:a("accountAddLater")}),(0,n.jsx)(I.$,{type:"button",disabled:!c.length,onClick:()=>s(c),children:a("accountAddSelected",{count:c.length})})]})]})})}let aj=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function aN({model:e,account:t,overrides:s,onChange:i,onInputState:a}){let{t:l}=(0,b.Bd)("settings"),[o,c]=(0,r.useState)(()=>({contextWindow:void 0===s.contextWindow?"":iY(s.contextWindow),maxTokens:void 0===s.maxTokens?"":iY(s.maxTokens),...Object.fromEntries(aj.map(([e])=>[e,s.cost?.[e]===void 0?"":String(s.cost[e])]))})),d=e=>""!==e&&null===iV(e),u=e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e));function m(e,t){let n={...o,[e]:t};c(n);let r=d(n.contextWindow)||d(n.maxTokens)||aj.some(([e])=>u(n[e]));if(a({dirty:r,invalid:r}),"contextWindow"===e||"maxTokens"===e){if(d(t))return;let n={...s};""===t?delete n[e]:n[e]=iV(t),i(n)}else{if(aj.some(([e])=>u(n[e])))return;let e={...s};aj.every(([e])=>""===n[e])?delete e.cost:e.cost=Object.fromEntries(aj.filter(([e])=>""!==n[e]).map(([e])=>[e,Number(n[e])])),i(e)}}if(!e)return(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("accountModelUnavailable")});let p=e.cost?{...e.cost,...s.cost}:s.cost;return(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-6",children:[(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)("span",{children:l(t?.loggedIn?"accountLoggedIn":"accountLoggedOut")}),t?.subscription?(0,n.jsx)("span",{className:"rounded-md bg-muted px-2",children:l("accountSubscription")}):null]}),(0,n.jsxs)("dl",{className:"grid gap-4 sm:grid-cols-2",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("contextLength")}),(0,n.jsxs)("dd",{className:"mt-1 text-lg font-semibold",children:[iY(s.contextWindow??e.contextWindow)," K"]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("maximumOutput")}),(0,n.jsxs)("dd",{className:"mt-1 text-lg font-semibold",children:[iY(s.maxTokens??e.maxTokens)," K"]})]}),(0,n.jsxs)("div",{className:"sm:col-span-2",children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("capabilities")}),(0,n.jsx)("dd",{className:"mt-1 text-sm",children:[...e.input.map(e=>l("image"===e?"imageInput":"textInput")),...e.reasoning?[l("supportsThinking")]:[]].join(" \xb7 ")})]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("accountReferencePrice")}),(0,n.jsx)("div",{className:"mt-3 text-sm text-muted-foreground",children:p?aj.map(([e,t])=>(0,n.jsxs)("p",{children:[l(t),": ",void 0===p[e]?"—":`$${p[e]}`]},e)):l("priceMissing")})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("accountAdjustParameters")}),(0,n.jsxs)("div",{className:"mt-4 space-y-4",children:[(0,n.jsx)("div",{className:"grid gap-3 sm:grid-cols-2",children:["contextWindow","maxTokens"].map(t=>(0,n.jsxs)(iU,{label:`${l("contextWindow"===t?"contextLength":"maximumOutput")} (K)`,children:[(0,n.jsx)(em.p,{value:o[t],placeholder:iY(e[t]),inputMode:"decimal","aria-invalid":d(o[t]),onChange:e=>m(t,e.target.value)}),d(o[t])?(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("capacityInvalid")}):null]},t))}),(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-medium",children:l("price")}),(0,n.jsx)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:aj.map(([t,s])=>(0,n.jsxs)(iU,{label:l(s),children:[(0,n.jsx)(em.p,{value:o[t],inputMode:"decimal",placeholder:String(e.cost?.[t]??""),"aria-invalid":u(o[t]),onChange:e=>m(t,e.target.value)}),u(o[t])?(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("priceInvalid")}):null]},t))})]}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>{c({contextWindow:"",maxTokens:"",input:"",output:"",cacheRead:"",cacheWrite:""}),i({}),a({dirty:!1,invalid:!1})},children:l("accountRestoreDefaults")})]})]})]})}var aI=s(34506);function aS({name:e,hasAccount:t,loggedIn:s,hasCustom:i,onCustomSettings:a,onLogin:l,onLogout:o}){let{t:c}=(0,b.Bd)("settings"),[d,u]=(0,r.useState)(!1),m=(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":c("serviceSettingsNamed",{name:e}),onClick:t?void 0:a,children:(0,n.jsx)(aI.A,{})});function p(e){u(!1),e()}return t?(0,n.jsxs)(eW.AM,{open:d,onOpenChange:u,children:[(0,n.jsx)(eW.Wv,{render:m}),(0,n.jsxs)(eW.hl,{align:"end",positionerClassName:"z-[120]",className:"w-52 gap-1 p-1",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"justify-start",onClick:()=>p(l),children:c(s?"accountRelogin":"accountLogin")}),s?(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"justify-start text-destructive",onClick:()=>p(o),children:c("accountLogout")}):null,i?(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"justify-start",onClick:()=>p(a),children:c("accountCustomSettings")}):null]})]}):m}function aC({providerId:e,custom:t,account:s,accountModels:r,query:i,modelKeys:a,selectedCustomIndex:l,selectedAccountId:o,presets:c,onSelectCustom:d,onSelectAccount:u,onCustomSettings:m,onAddCustom:p,onAddAccount:h,onLogin:g,onLogout:f,onGroupRef:x,onRowRef:v}){let{t:w}=(0,b.Bd)("settings"),y=(t?e:s?.name)||e||w("providerUnnamed"),k=r.filter(e=>!t?.models.some(t=>t.modelId===e.modelId)),j=[...(t?.models??[]).map((e,t)=>({key:a[t],modelId:e.modelId,name:e.name,model:e,selected:l===t,select:()=>d(t)})),...k.map(t=>{let n=s?.models.find(e=>e.modelId===t.modelId);return{key:`account:${e}:${t.modelId}`,modelId:t.modelId,name:n?.name??t.modelId,model:n?{...n,...t.overrides}:void 0,selected:o===t.modelId,select:()=>u(t.modelId)}})],N=j.filter(t=>`${e} ${y} ${s?.name??""} ${t.name} ${t.modelId}`.toLocaleLowerCase().includes(i.toLocaleLowerCase()));if(i&&!N.length&&!`${e} ${y} ${s?.name??""}`.toLocaleLowerCase().includes(i.toLocaleLowerCase()))return null;let S=!!s||r.length>0;return(0,n.jsxs)("section",{ref:x,className:"mb-3",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-foreground",children:[(0,n.jsx)(eE.A,{"aria-hidden":"true",className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold",title:s?.name,children:y}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:j.length}),(0,n.jsx)(aS,{name:y,hasAccount:S,loggedIn:s?.loggedIn??!1,hasCustom:!!t,onCustomSettings:m,onLogin:g,onLogout:f})]}),(0,n.jsxs)("div",{className:"space-y-1",children:[N.map(t=>(0,n.jsxs)("button",{ref:e=>v(t.key,e),type:"button","aria-current":t.selected?"true":void 0,className:(0,C.cn)("flex min-h-14 w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",t.selected&&"bg-accent text-accent-foreground"),onClick:t.select,children:[(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",children:t.name||t.modelId||w("modelUnnamed")}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:t.model?`${iY(t.model.contextWindow)} K \xb7 ${w(t.model.input.includes("image")?"imageInput":"textInput")}`:w("accountModelUnavailableShort")})]}),c.some(s=>s.provider===e&&s.modelId===t.modelId)?(0,n.jsx)(i3.A,{className:"size-4 shrink-0 text-muted-foreground"}):null]},t.key)),S?(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",className:"mt-1 w-full border border-dashed border-input","aria-label":w("modelAddToService",{name:s?.name??y}),onClick:h,children:[(0,n.jsx)(U.A,{}),w("modelAdd")]}):null,t?(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",className:"mt-1 w-full border border-dashed border-input","aria-label":w("modelAddToService",{name:y}),onClick:p,children:[(0,n.jsx)(U.A,{}),S?w("accountCustomModel"):null]}):null]})]})}let aE={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function aM({biz:e,connectionReady:t,providers:s,accounts:i,accountModels:a,onAccountModelsChange:l,onRefreshAccounts:o,savedModels:c,savedProviders:d,presets:u,resetVersion:m,onChange:p,onPresetsChange:h,onInputState:g,onServiceDirtyChange:f}){let{t:x}=(0,b.Bd)("settings"),{confirm:v,dialog:w}=nF(),y=(0,X.G)(),[k,j]=(0,r.useState)(null),[N,S]=(0,r.useState)(null),[E,M]=(0,r.useState)(!1),[z,$]=(0,r.useState)(()=>new Set),R=function(e,t){let{appSocket:s}=(0,ei.gM)(),n=(0,r.useMemo)(()=>({list:async()=>(await s.request(ag.list,{})).providers,async start(e,t){await s.request(ag.start,{loginId:e,provider:t})},async respond(e,t,n){await s.request(ag.respond,{loginId:e,promptId:t,value:n})},async cancel(e){await s.request(ag.cancel,{loginId:e})},async logout(e){await s.request(ag.logout,{provider:e})},subscribe:e=>s.subscribe(ag.state,e)}),[s]),{t:i}=(0,b.Bd)("settings"),a=(0,X.G)(),[l,o]=(0,r.useState)(!1),[c,d]=(0,r.useState)([]),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(!1),[x,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(null),k=(0,r.useRef)(e),j=(0,r.useRef)(null),N=(0,r.useRef)(null),I=(0,r.useRef)(null),S=(0,r.useRef)(null),C=(0,r.useRef)(0),E=(0,r.useRef)(t);function M(){let e=j.current;j.current=null,N.current=null,I.current=null,S.current?.(),S.current=null,e?.status==="running"&&n.cancel(e.loginId).catch(e=>{console.warn("[Pi Desk][ModelAuth] 取消登录失败",{message:e instanceof Error?e.message:String(e)})})}function z(){C.current+=1,M(),o(!1)}async function A(){let e=j.current;if(!e||"completed"!==e.status||I.current)return;I.current=e.loginId,f(!0),y(null);let t=()=>j.current?.loginId===e.loginId;try{await E.current(e.provider,t),t()&&z()}catch(e){t()&&y(e instanceof Error?e.message:i("accountRefreshFailed"))}finally{t()&&(I.current=null,f(!1))}}async function $(e){if(!k.current)return void y(i("accountConnectionNotReady"));if(j.current?.status==="running")return;M();let t={loginId:crypto.randomUUID(),provider:e,status:"running",notice:null,prompt:null,message:null};j.current=t,m(t),y(null),v(null),S.current=n.subscribe(e=>{j.current?.loginId===e.loginId&&((j.current.prompt?.id!==e.prompt?.id||"running"!==e.status)&&(N.current=null,v(null)),j.current=e,m(e),y("error"!==e.status||e.message?null:i("accountLoginFailed")),"completed"===e.status&&A())});try{await n.start(t.loginId,e)}catch(e){if(j.current?.loginId!==t.loginId||"running"!==j.current.status)return;M(),m(null),y(e instanceof Error?e.message:i("accountLoginFailed"))}}async function R(e,t){let s=j.current;if(!k.current||!s||"running"!==s.status||s.prompt?.id!==e||N.current)return;let r={loginId:s.loginId,promptId:e};N.current=r,v(e),y(null);try{await n.respond(s.loginId,e,t)}catch(t){j.current?.loginId===s.loginId&&j.current.prompt?.id===e&&y(t instanceof Error?t.message:i("accountLoginFailed"))}finally{N.current===r&&(N.current=null,v(null))}}return(0,r.useEffect)(()=>{E.current=t},[t]),(0,r.useEffect)(()=>()=>{C.current+=1;let e=j.current;j.current=null,S.current?.(),e?.status==="running"&&n.cancel(e.loginId).catch(()=>void 0)},[n]),(0,r.useEffect)(()=>{k.current=e;let t=j.current;if(e||t?.status!=="running")return;j.current=null,N.current=null,S.current?.(),S.current=null,n.cancel(t.loginId).catch(()=>void 0);let s=C.current;queueMicrotask(()=>{C.current===s&&(m(null),v(null),y(i("accountDisconnected")))})},[e,n,i]),{open:l,providers:c,state:u,loading:p||g,submitting:null!==x&&x===u?.prompt?.id,error:w,show:function(e){if(z(),m(null),y(null),v(null),f(!1),o(!0),!k.current){h(!1),y(i("accountConnectionNotReady"));return}h(!0);let t=++C.current;n.list().then(s=>{C.current===t&&(d(s),e&&s.some(t=>t.provider===e&&!t.conflict)&&$(e))}).catch(e=>{C.current===t&&y(e instanceof Error?e.message:i("accountLoginFailed"))}).finally(()=>{C.current===t&&h(!1)})},close:z,start:$,respond:R,finish:A,async logout(e){if(!k.current)throw Error(i("accountConnectionNotReady"));await n.logout(e)},async copy(e){try{await ab(e),a.success(i("accountCopied"))}catch{a.error(i("accountCopyFailed"))}},openUrl:ax}}(t,async(e,t)=>{await o(),t()&&S(e)}),P=function(e,t,s,n){let[i,a]=(0,r.useState)(()=>{let t=e.findIndex(e=>e.models.length>0);return t<0?null:{providerIndex:t,modelIndex:0}}),[l,o]=(0,r.useState)(!1),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(()=>e.map((e,t)=>e.models.map((e,s)=>`${t}:${s}`))),p=(0,r.useRef)(0),h=(0,r.useRef)(new Map(e.flatMap((e,t)=>e.models.map((s,n)=>[`${t}:${n}`,{provider:e.provider,modelId:s.modelId}])))),[g,f]=(0,r.useState)({}),[x,b]=(0,r.useState)(null),[v,w]=(0,r.useState)(!1),y=(0,r.useRef)(e);function k(e){f(t=>Object.fromEntries(Object.entries(t).filter(([t])=>!e.includes(t))))}function j(e,s=u){let n=[];e.forEach((e,t)=>{e.models.forEach((r,i)=>{let a=h.current.get(s[t][i]),l={provider:e.provider.trim(),modelId:r.modelId.trim()};a&&(a.provider!==l.provider||a.modelId!==l.modelId)&&n.push({from:a,to:l})})}),t(e,n)}function N(){b(null),w(!1)}return(0,r.useEffect)(()=>{y.current=e},[e]),(0,r.useEffect)(()=>{queueMicrotask(()=>{let e=y.current;h.current=new Map(e.flatMap((e,t)=>e.models.map((s,n)=>[`${t}:${n}`,{provider:e.provider,modelId:s.modelId}]))),f({}),m(e.map((e,t)=>e.models.map((e,s)=>`${t}:${s}`))),a(t=>{if(t&&e[t.providerIndex]?.models[t.modelIndex])return t;let s=e.findIndex(e=>e.models.length);return s<0?null:{providerIndex:s,modelIndex:0}})})},[n]),(0,r.useEffect)(()=>{let e=Object.values(g);s({dirty:e.some(e=>e.dirty),invalid:e.some(e=>e.invalid)})},[g,s]),{selection:i,mobileDetail:l,query:c,setQuery:d,modelKeys:u,serviceIndex:x,newService:v,openService:e=>{b(e),w(null===e)},closeService:N,applyService:t=>{v?(j([...e,t],[...u,[]]),m(e=>[...e,[]])):j(e.map((e,s)=>s===x?t:e)),N()},deleteService:()=>{if(null===x)return;k(u[x]);let t=e.filter((e,t)=>t!==x);j(t,u.filter((e,t)=>t!==x)),m(e=>e.filter((e,t)=>t!==x)),a(e=>{if(!e||e.providerIndex===x){let e=t.findIndex(e=>e.models.length);return e<0?null:{providerIndex:e,modelIndex:0}}return e.providerIndex>x?{...e,providerIndex:e.providerIndex-1}:e}),o(!1),N()},addModel:t=>{let s=e[t],n=`new-${++p.current}`;j(e.map((e,s)=>s===t?{...e,models:[...e.models,{modelId:"",name:"",api:null,baseUrl:null,reasoning:!1,thinkingLevels:[{level:"off",providerValue:null}],input:["text"],contextWindow:128e3,maxTokens:16384,cost:null,headers:{},compat:null}]}:e),u.map((e,s)=>s===t?[...e,n]:e)),m(e=>e.map((e,s)=>s===t?[...e,n]:e)),a({providerIndex:t,modelIndex:s.models.length}),d(""),o(!0)},selectModel:(e,t)=>{a({providerIndex:e,modelIndex:t}),o(!0)},backToList:()=>{o(!1),d("")},updateModel:function(t,s,n){j(e.map((e,r)=>r===t?{...e,models:e.models.map((e,t)=>t===s?n:e)}:e))},deleteModel:(t,s)=>{k([u[t][s]]);let n=e.map((e,n)=>n===t?{...e,models:e.models.filter((e,t)=>t!==s)}:e);j(n,u.map((e,n)=>n===t?e.filter((e,t)=>t!==s):e)),m(e=>e.map((e,n)=>n===t?e.filter((e,t)=>t!==s):e)),a(e=>{if(!e||e.providerIndex!==t)return e;if(e.modelIndex===s){if(n[t].models.length)return{providerIndex:t,modelIndex:Math.min(s,n[t].models.length-1)};let e=n.findIndex(e=>e.models.length);return e<0?null:{providerIndex:e,modelIndex:0}}return e.modelIndex>s?{...e,modelIndex:e.modelIndex-1}:e}),o(!1)},updateInputState:(e,t)=>f(s=>({...s,[e]:t}))}}(s,p,g,m),{selection:D,mobileDetail:T,query:O,setQuery:L,modelKeys:F,serviceIndex:B,newService:q}=P,_=(0,r.useRef)(new Map),W=(0,r.useRef)(new Map),[Y,V]=(0,r.useState)(!1),[H,K]=(0,r.useState)("off"),G=a.find(e=>e.provider===k?.provider&&e.modelId===k?.modelId)??(s.some(e=>e.models.length)?void 0:a[0]),J=i.find(e=>e.provider===G?.provider),Q=J?.models.find(e=>e.modelId===G?.modelId),Z=!!G,ee=!Z&&D?s[D.providerIndex]:null,es=!Z&&D?ee?.models[D.modelIndex]:null,en=Z?E:T&&!!es,er=Z?Q?.name??G?.modelId:es?.name||es?.modelId||x("modelUnnamed"),ea=G?.provider||ee?.provider||x("providerUnnamed"),el=i.find(e=>e.provider===N),eo=[...new Set([...s.map(e=>e.provider),...i.map(e=>e.provider),...a.map(e=>e.provider)])],ec=e=>`account:${e.provider}:${e.modelId}`,ed=new Set(a.map(ec)),eu=new Set([...z].filter(e=>ed.has(e)));G&&eu.add(ec(G)),(eu.size!==z.size||G&&!z.has(ec(G)))&&$(eu);let[ep,eh]=(0,r.useState)(()=>new Set),eg=D?F[D.providerIndex]?.[D.modelIndex]:void 0,ef=new Set(F.flat()),ex=new Set([...ep].filter(e=>ef.has(e)));eg&&ex.add(eg),(ex.size!==ep.size||eg&&!ep.has(eg))&&eh(ex);let eb=Z?c.find(e=>e.provider===G?.provider&&e.modelId===G.modelId):ee&&es&&d.some(e=>e.provider===ee.provider&&e.models.some(e=>e.modelId===es.modelId))?c.find(e=>e.provider===ee.provider&&e.modelId===es.modelId):void 0;async function ev(){if(G){await v({title:x("accountRemoveTitle"),description:x("accountRemoveDescription",{name:er})})&&(l(a.filter(e=>e!==G)),P.updateInputState(ec(G),{dirty:!1,invalid:!1}),j(null),M(!1));return}D&&es&&await v({title:x("modelDeleteTitle"),description:x("modelDeleteDescription",{name:es.name||es.modelId||x("modelUnnamed")})})&&P.deleteModel(D.providerIndex,D.modelIndex)}async function ew(e){if(await v({title:x("accountLogoutTitle"),description:x("accountLogoutDescription",{name:i.find(t=>t.provider===e)?.name??e}),confirmLabel:x("accountLogout")}))try{await R.logout(e),await o()}catch(e){y.error(e instanceof Error?e.message:x("accountLogoutFailed"))}}return(0,n.jsxs)("section",{className:"@container/models h-full min-h-0 overflow-hidden bg-card",children:[(0,n.jsxs)("div",{className:"grid h-full min-h-0 grid-cols-1 @[48rem]/models:grid-cols-[15rem_minmax(0,1fr)]",children:[(0,n.jsxs)("aside",{"aria-label":x("providerList"),className:(0,C.cn)("min-h-0 min-w-0 flex-col bg-sidebar @[48rem]/models:flex @[48rem]/models:border-r",en?"hidden":"flex"),children:[(0,n.jsx)("div",{className:"shrink-0 p-3",children:(0,n.jsx)(em.p,{value:O,"aria-label":x("modelSearch"),placeholder:x("modelSearch"),onChange:e=>L(e.target.value)})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto px-2 pb-3",children:[eo.map(e=>{let t=s.findIndex(t=>t.provider===e);return(0,n.jsx)(aC,{providerId:e,custom:s[t],account:i.find(t=>t.provider===e),accountModels:a.filter(t=>t.provider===e),query:O,modelKeys:F[t]??[],selectedCustomIndex:Z||D?.providerIndex!==t?null:D.modelIndex,selectedAccountId:G?.provider===e?G.modelId:null,presets:u,onSelectCustom:e=>{j(null),P.selectModel(t,e)},onSelectAccount:t=>{j({provider:e,modelId:t}),M(!0),$(s=>new Set([...s,ec({provider:e,modelId:t})]))},onCustomSettings:()=>P.openService(t),onAddCustom:()=>{j(null),P.addModel(t)},onAddAccount:()=>{let t;return t=i.find(t=>t.provider===e),void(t?.loggedIn?S(e):R.show(e))},onLogin:()=>R.show(e),onLogout:()=>void ew(e),onGroupRef:e=>{t<0||(e?_.current.set(t,e):_.current.delete(t))},onRowRef:(e,t)=>{t?W.current.set(e,t):W.current.delete(e)}},e)}),eo.length?null:(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:x("providerEmpty")})]}),(0,n.jsxs)("div",{className:"flex shrink-0 gap-2 border-t p-3",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>P.openService(null),children:[(0,n.jsx)(U.A,{}),x("accountCustomApi")]}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>R.show(),children:[(0,n.jsx)(i5.A,{}),x("accountLogin")]})]})]}),(0,n.jsx)("section",{"aria-label":x("modelsHeading"),className:(0,C.cn)("min-h-0 min-w-0 flex-col @[48rem]/models:flex",en?"flex":"hidden"),children:Z||es&&D?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2 @[48rem]/models:hidden",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":x("backModelList"),onClick:function(){if(G){M(!1),window.requestAnimationFrame(()=>{let e=W.current.get(ec(G));e?.scrollIntoView({block:"nearest"}),e?.focus({preventScroll:!0})});return}P.backToList(),window.requestAnimationFrame(()=>{if(!D)return;let e=F[D.providerIndex]?.[D.modelIndex];_.current.get(D.providerIndex)?.scrollIntoView({block:"nearest"}),W.current.get(e)?.scrollIntoView({block:"nearest"}),W.current.get(e)?.focus({preventScroll:!0})})},children:(0,n.jsx)(A.A,{})}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",title:J?.name??ea,children:J?.name??ea}),(0,n.jsx)(aS,{name:ea,hasAccount:i.some(e=>e.provider===ea)||a.some(e=>e.provider===ea),loggedIn:i.find(e=>e.provider===ea)?.loggedIn??!1,hasCustom:s.some(e=>e.provider===ea),onCustomSettings:()=>P.openService(s.findIndex(e=>e.provider===ea)),onLogin:()=>R.show(ea),onLogout:()=>void ew(ea)})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 @[48rem]/models:p-6",children:[(0,n.jsxs)("div",{className:"mb-5 flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"min-w-0 break-all text-lg font-semibold",children:er}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:!eb,title:eb?void 0:x("saveBeforePreset"),onClick:()=>{K(eb?.thinkingLevels[0]??"off"),V(!0)},children:[(0,n.jsx)(i3.A,{}),x("addModelPreset")]}),(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm",className:"text-destructive hover:text-destructive","aria-label":Z?`${x("accountRemove")} ${er}`:x("modelDeleteNamed",{name:er}),onClick:ev,children:(0,n.jsx)(et.A,{})})}),(0,n.jsx)(tU.ZI,{children:x(Z?"accountRemove":"modelDelete")})]})]})]}),a.map(e=>{let t=ec(e);if(!eu.has(t))return null;let s=i.find(t=>t.provider===e.provider);return(0,n.jsx)("div",{hidden:!Z||G!==e,children:(0,n.jsx)(aN,{account:s,model:s?.models.find(t=>t.modelId===e.modelId),overrides:e.overrides,onChange:t=>l(a.map(s=>s===e?{...e,overrides:t}:s)),onInputState:e=>P.updateInputState(t,e)})},`${t}:${m}`)}),s.flatMap((t,s)=>t.models.map((r,i)=>{let a=!Z&&D?.providerIndex===s&&D.modelIndex===i,l=F[s]?.[i];return ex.has(l)?(0,n.jsx)("div",{hidden:!a,children:(0,n.jsx)(as,{biz:e,provider:t,model:r,onChange:e=>P.updateModel(s,i,e),onInputState:e=>P.updateInputState(l,e)})},`${l}:${m}`):null}))]})]}):(0,n.jsxs)("div",{className:"flex flex-col items-center gap-3 p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(eO.A,{className:"size-6"}),x("selectModelToEdit")]})})]}),(0,n.jsx)(ay,{open:R.open,connected:t,providers:R.providers,state:R.state,loading:R.loading,submitting:R.submitting,error:R.error,onClose:R.close,onStart:R.start,onRespond:R.respond,onCopy:R.copy,onOpenUrl:R.openUrl,onRetry:()=>R.state?.status==="completed"?void R.finish():R.show()}),el?(0,n.jsx)(ak,{account:el,existingIds:[...a.filter(e=>e.provider===el.provider).map(e=>e.modelId),...s.filter(e=>e.provider===el.provider).flatMap(e=>e.models.map(e=>e.modelId))],onAdd:function(e){if(!el)return;let t=e.filter(e=>!a.some(t=>t.provider===el.provider&&t.modelId===e)&&!s.some(t=>t.provider===el.provider&&t.models.some(t=>t.modelId===e))).map(e=>({provider:el.provider,modelId:e,overrides:{}}));l([...a,...t]),S(null)},onClose:()=>S(null)},el.provider):null,q||null!==B?(0,n.jsx)(aa,{provider:q?{provider:"",name:null,baseUrl:null,api:"openai-responses",apiKey:null,authHeader:null,headers:{},models:[]}:s[B],existingIds:s.filter((e,t)=>q||t!==B).map(e=>e.provider),isNew:q,onApply:P.applyService,onDelete:P.deleteService,onClose:P.closeService,onDirtyChange:f}):null,(0,n.jsx)(eN.YV,{open:Y,onOpenChange:V,children:(0,n.jsxs)(eN.hA,{children:[(0,n.jsx)(eN.Hl,{className:"border-b px-4 py-4 pr-12",children:(0,n.jsx)(eN.YM,{children:x("addModelPreset")})}),(0,n.jsx)(eN._Y,{children:(0,n.jsx)("div",{className:"p-4",children:(0,n.jsx)(iU,{label:x("thinkingLevel"),children:(0,n.jsx)(iK,{value:H,allowEmpty:!1,ariaLabel:x("presetThinkingNew"),options:(eb?.thinkingLevels??[]).map(e=>({value:e,label:x(aE[e])})),onChange:e=>K(e)})})})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:()=>V(!1),children:x("cancel",{ns:"common"})}),(0,n.jsx)(I.$,{type:"button",onClick:function(){eb&&(u.some(e=>e.provider===eb.provider&&e.modelId===eb.modelId&&e.thinkingLevel===H)||h([...u,{provider:eb.provider,modelId:eb.modelId,thinkingLevel:H,color:iL(u)}]),V(!1))},disabled:!eb,children:x("presetAdd")})]})]})}),w]})}let az={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function aA(e,t){return JSON.stringify([e,t])}function a$(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function aR({biz:e,presets:t,onDirtyChange:s}){let{t:i}=(0,b.Bd)("settings"),a=function(e,t){let{t:s}=(0,b.Bd)("settings"),n=(0,X.G)(),{confirm:i,dialog:a}=nF(),[l,o]=(0,r.useState)([]),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)([]),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)(!1),[x,v]=(0,r.useState)(!0),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(!1),[S,C]=(0,r.useState)(null),[E,M]=(0,r.useState)(null),[z,A]=(0,r.useState)(null),[$,R]=(0,r.useState)(0),[P,D]=(0,r.useState)(0),T=S===c&&null===z&&!w&&!k,O=(0,r.useRef)(!1),L=(0,r.useRef)(""),F=(0,r.useRef)(0),B=(0,r.useCallback)(e=>{O.current=e,t?.(e)},[t]);function q(e){m(e.models),f(null!==e.default),h(e.default??(e.models[0]?{provider:e.models[0].provider,modelId:e.models[0].modelId,thinkingLevel:e.models[0].thinkingLevels[0]}:null))}async function _(e){return!N&&(e===c||(!O.current||!!await i({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}))&&(F.current+=1,j(!0),d(e),!0))}async function W(){if(c&&T&&!w&&!k&&!N&&(!g||p)){I(!0);try{await e.replaceProjectDefault({cwd:c,default:g?p:null}),ij({cwd:c,default:g?p:null,models:u}),B(!1),n.success(g?s("projectDefaultSaved"):s("projectDefaultGlobalSaved"))}catch(e){n.error(e instanceof Error?e.message:s("projectDefaultSaveFailed"))}finally{I(!1)}}}return(0,r.useEffect)(()=>{let t=!1,n=r9.N$.safeParse((iu(),ii)),r=n.success?n.data.directories:null;return queueMicrotask(()=>{!t&&(M(null),v(!r),r&&(o(r),d(e=>e&&r.some(t=>t.cwd===e)?e:r[0]?.cwd??"")))}),(async()=>{try{let s=await e.listDirectories();if(t)return;o(s.directories),d(e=>e&&s.directories.some(t=>t.cwd===e)?e:s.directories[0]?.cwd??"")}catch(e){if(!t&&!r){let t=e instanceof Error?e.message:s("projectDirectoriesFailed");console.warn("[Pi Desk][ProjectModelDefault] 读取项目目录失败",{message:t}),M(t)}}finally{t||v(!1)}})(),()=>{t=!0}},[e,s,$]),(0,r.useEffect)(()=>{let t=!1,n=++F.current;function r(){return!t&&n===F.current}let i=L.current!==c;if(L.current=c,i&&B(!1),!c)return queueMicrotask(()=>{r()&&(m([]),h(null),f(!1),C(null),A(null),y(!1),j(!1))}),()=>{t=!0};let a=(iy(),iv.get(iw(c))??null);return queueMicrotask(()=>{r()&&(A(null),!O.current&&a&&(q(a),C(c)),y(!a&&!O.current),j(!!a||O.current))}),(async()=>{try{let t=await e.getProjectDefault(c);if(!r())return;O.current||q(t),C(c)}catch(e){if(r()){let t=e instanceof Error?e.message:s("projectDefaultFailed");console.warn("[Pi Desk][ProjectModelDefault] 读取项目模型配置失败",{cwd:c,message:t}),A(t)}}finally{r()&&(y(!1),j(!1))}})(),()=>{t=!0}},[e,c,s,B,P]),{directories:l,cwd:c,loadedCwd:S,models:u,selection:p,fixed:g,directoriesLoading:x,projectLoading:w,projectRefreshing:k,saving:N,projectReady:T,directoriesError:E,projectError:z,dialog:a,selectProject:_,changeFixed:function(e){T&&!N&&(B(!0),f(e))},selectModel:function(e){T&&!N&&(B(!0),h({provider:e.provider,modelId:e.modelId,thinkingLevel:e.thinkingLevels[0]}))},selectThinking:function(e){if(!T||N)return;let t=u.find(e=>e.provider===p?.provider&&e.modelId===p.modelId),s=t?.thinkingLevels.find(t=>t===e);p&&s&&(B(!0),h({...p,thinkingLevel:s}))},applyPreset:function(e){T&&!N&&(B(!0),h({provider:e.provider,modelId:e.modelId,thinkingLevel:e.thinkingLevel}))},retryDirectories:function(){R(e=>e+1)},retryProject:function(){F.current+=1,j(!0),D(e=>e+1)},save:W}}(e,s),[l,o]=(0,r.useState)(""),[c,d]=(0,r.useState)(!1),u=a.models.find(e=>e.provider===a.selection?.provider&&e.modelId===a.selection.modelId),m=t.filter(e=>a.models.some(t=>t.provider===e.provider&&t.modelId===e.modelId&&t.thinkingLevels.includes(e.thinkingLevel))),p=a.directories.filter(e=>e.cwd.toLocaleLowerCase().includes(l.trim().toLocaleLowerCase())),h=a.models.map(e=>({value:aA(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider})),g=!a.projectReady||a.saving,f=a.loadedCwd??a.cwd;async function x(e){await a.selectProject(e)&&d(!0)}return(0,n.jsxs)("section",{className:"@container/project-default h-full min-h-0 overflow-hidden bg-card",children:[(0,n.jsxs)("div",{className:"grid h-full min-h-0 grid-cols-1 @[48rem]/project-default:grid-cols-[18rem_minmax(0,1fr)]",children:[(0,n.jsxs)("aside",{"aria-label":i("projectList"),className:(0,C.cn)("min-h-0 min-w-0 flex-col bg-sidebar @[48rem]/project-default:flex @[48rem]/project-default:border-r",c&&a.cwd?"hidden":"flex"),children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 p-3",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:i("projectList")}),(0,n.jsx)(em.p,{value:l,"aria-label":i("projectSearch"),placeholder:i("projectSearch"),onChange:e=>o(e.target.value)})]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto px-2 pb-3",children:a.directoriesLoading&&0===a.directories.length?(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 px-3 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{"aria-hidden":"true",className:"size-4 animate-spin"}),i("projectLoading")]}):a.directoriesError?(0,n.jsxs)("div",{className:"space-y-3 px-3 py-6 text-sm",children:[(0,n.jsx)("p",{role:"alert",className:"break-words text-destructive",children:a.directoriesError}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:a.retryDirectories,children:i("retry",{ns:"common"})})]}):0===p.length?(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:i("projectEmpty")}):(0,n.jsx)("div",{className:"space-y-1",children:p.map(e=>{let t=e.cwd===a.cwd;return(0,n.jsx)(I.$,{type:"button",variant:"ghost","aria-current":t?"true":void 0,disabled:a.saving,className:(0,C.cn)("h-auto min-h-14 w-full items-start justify-start gap-2 whitespace-normal px-3 py-2 text-left",t&&"bg-accent text-accent-foreground ring-1 ring-border ring-inset"),onClick:()=>{x(e.cwd)},children:(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("span",{className:"flex items-start gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 break-all text-sm font-medium",children:a$(e.cwd)}),t?(0,n.jsx)(ep.A,{"aria-hidden":"true",className:"mt-0.5 size-4 shrink-0"}):null]}),(0,n.jsx)("span",{className:"mt-1 block break-all text-xs font-normal text-muted-foreground",children:e.cwd}),(0,n.jsx)("span",{className:"mt-1 block text-xs font-normal text-muted-foreground",children:i("projectSessionCount",{count:e.sessionCount})})]})},e.cwd)})})})]}),(0,n.jsx)("section",{"aria-label":i("projectDefaultSource"),className:(0,C.cn)("min-h-0 min-w-0 flex-col @[48rem]/project-default:flex",c&&a.cwd?"flex":"hidden"),children:a.cwd?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-2 @[48rem]/project-default:hidden",children:(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(!1),children:[(0,n.jsx)(A.A,{"aria-hidden":"true"}),i("backProjectList")]})}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 @[48rem]/project-default:p-6",children:(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-6",children:[(0,n.jsxs)("header",{className:"space-y-1",children:[(0,n.jsxs)("h3",{className:"flex items-center gap-2 text-lg font-semibold",children:[(0,n.jsx)("span",{className:"min-w-0 break-all",children:a$(f)}),(0,n.jsx)("span",{className:"inline-flex size-4 shrink-0",children:!a.projectReady&&!a.projectError&&(0,n.jsx)(v.A,{role:"status","aria-label":i("projectLoading"),className:"size-4 animate-spin text-muted-foreground"})})]}),(0,n.jsx)("p",{className:"break-all text-sm text-muted-foreground",children:f})]}),a.projectError?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("p",{role:"alert",className:"min-w-0 flex-1 break-words text-destructive",children:a.projectError}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:a.retryProject,disabled:a.projectLoading||a.projectRefreshing,children:i("retry",{ns:"common"})})]}):null,null!==a.loadedCwd?(0,n.jsxs)("fieldset",{disabled:g,className:"min-w-0 space-y-6",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:i("projectDefaultSource")}),(0,n.jsx)(n2,{label:i("projectDefaultSource"),value:a.fixed?"fixed":"global",layout:"segmented",disabled:g,options:[{value:"global",label:i("projectFollowGlobal")},{value:"fixed",label:i("projectFixed")}],onChange:e=>a.changeFixed("fixed"===e)})]}),a.fixed?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)(iU,{label:i("projectDefaultModel"),children:(0,n.jsx)(nV.b,{value:a.selection?aA(a.selection.provider,a.selection.modelId):"",options:h,ariaLabel:i("projectDefaultModel"),searchPlaceholder:i("modelSearch"),disabled:g||0===a.models.length,onChange:function(e){let t=a.models.find(t=>aA(t.provider,t.modelId)===e);t&&a.selectModel(t)}})}),(0,n.jsx)(iU,{label:i("thinkingLevel"),children:(0,n.jsx)(iK,{value:a.selection?.thinkingLevel??"",options:(u?.thinkingLevels??[]).map(e=>({value:e,label:i(az[e])})),ariaLabel:i("projectDefaultThinking"),allowEmpty:!1,onChange:a.selectThinking})}),m.length>0?(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:i("fromPreset")}),(0,n.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:m.map((e,t)=>{let s=a.models.find(t=>t.provider===e.provider&&t.modelId===e.modelId);return(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"xs",disabled:g,className:"h-auto min-h-7 max-w-full whitespace-normal text-left",onClick:()=>a.applyPreset(e),children:[(0,n.jsx)("span",{className:"size-2 shrink-0 rounded-full bg-current",style:e.color?{color:e.color}:void 0}),(0,n.jsxs)("span",{className:"min-w-0 break-all",children:[s?.name||e.modelId," \xb7"," ",i(az[e.thinkingLevel])]})]},`${e.provider}/${e.modelId}/${e.thinkingLevel}/${t}`)})})]}):null]}):null]}):null]})}),(0,n.jsx)("div",{className:"shrink-0 border-t px-4 py-3 @[48rem]/project-default:px-6",children:(0,n.jsxs)(I.$,{type:"button",onClick:a.save,disabled:!a.projectReady||g||a.fixed&&!a.selection,children:[a.saving?(0,n.jsx)(v.A,{"aria-hidden":"true",className:"animate-spin"}):(0,n.jsx)(Z.A,{"aria-hidden":"true"}),a.saving?i("savingModels"):i("saveProjectDefault")]})})]}):(0,n.jsxs)("div",{className:"flex items-center gap-2 p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(eP.A,{"aria-hidden":"true",className:"size-6 shrink-0"}),i("selectProjectToConfigure")]})})]}),a.dialog]})}let aP=[{value:"providers",label:"modelProviders"},{value:"presets",label:"modelPresets"},{value:"project-default",label:"projectDefault"}];function aD({loading:e,error:t,onRetry:s}){let{t:r}=(0,b.Bd)("settings");return(0,n.jsx)("div",{className:"flex min-h-72 flex-col items-center justify-center gap-3 p-5 text-sm text-muted-foreground",children:e?(0,n.jsxs)("span",{className:"flex items-center gap-2",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"})," ",r("loadingModels")]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{role:"alert",className:"rounded-lg bg-destructive/10 px-3 py-2 text-destructive",children:t??r("modelsUnavailable")}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:s,children:r("retry",{ns:"common"})})]})})}function aT({onBeforeLeaveChange:e,connectionReady:t=!1,initialTab:s}){let{t:i}=(0,b.Bd)("settings"),{locale:a,timeZone:l}=(0,eQ.i)(),[o,c]=(0,r.useState)(!1),{biz:d,tab:u,settings:m,providers:p,presets:h,accountModels:g,changeAccountModels:f,refreshAccounts:x,resetVersion:w,formDirty:y,formInvalid:k,serviceDirty:j,nativeOpen:N,nativeText:S,nativeError:E,nativeDirty:M,setNativeText:z,openNative:A,closeNative:$,saveNative:R,revertConfig:P,setInputState:D,setServiceDirty:T,loading:O,saving:L,refreshing:F,catalogUpdatedAt:B,loadError:q,dialog:_,setProjectDefaultDirty:W,changeProviders:Y,changePresets:V,selectTab:U,retry:K,refreshCatalog:G,saveConfig:J}=function(e,t){let{t:s}=(0,b.Bd)("settings"),{clientId:n}=(0,ei.gM)(),i=(0,X.G)(),{confirm:a,dialog:l}=nF(),o=(0,r.useMemo)(()=>{let e;return e=null,{parseNativeConfig(e){let t=JSON.parse(e);return rT.parse(t)},getSettings:()=>(e||(e=eu(n,"/api/model-settings/get",{},rK).finally(()=>{e=null})),e),previewSettings:e=>eu(n,"/api/model-settings/preview",iN(e),r0),async replaceSettings(e){await eu(n,"/api/model-settings/replace",iN(e),rZ)},listCatalog:e=>eu(n,"/api/model-catalog/list",r1.parse(e),r4),async listDirectories(){let e=await eu(n,"/api/pi/directories/list",{forceRefresh:!1},r9.N$);return ip(e),e},async getProjectDefault(e){let t=await eu(n,"/api/project-model-default/get",{cwd:e},r6);return ij(t),t},async replaceProjectDefault(e){await eu(n,"/api/project-model-default/replace",r8.parse(e),r7)}}},[n]),[c,d]=(0,r.useState)(()=>t??iM(iE,iS,"providers"));(0,r.useEffect)(()=>{iz(iE,c)},[c]);let[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)([]),[g,f]=(0,r.useState)([]),[x,v]=(0,r.useState)([]),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(!1),[S,C]=(0,r.useState)(!1),[E,M]=(0,r.useState)(!0),[z,A]=(0,r.useState)(!1),[$,R]=(0,r.useState)(!1),[P,D]=(0,r.useState)(null),[T,O]=(0,r.useState)(null),[L,F]=(0,r.useState)(0),[B,q]=(0,r.useState)(0),[_,W]=(0,r.useState)({dirty:!1,invalid:!1}),[Y,V]=(0,r.useState)(!1),[U,H]=(0,r.useState)(!1),[K,G]=(0,r.useState)(""),[J,Q]=(0,r.useState)(null),Z=(0,r.useRef)(!1),ee=(0,r.useRef)([]),et=u?JSON.stringify(u.nativeConfig,null,2):"",es=U&&K!==et,en=k||N||w||_.dirty,er=en||S||Y||es;(0,r.useEffect)(()=>(e(er?()=>!z&&a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}):null),()=>e(null)),[e,er,z,a,s]),(0,r.useEffect)(()=>{if(!er)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[er]);let ea=(0,r.useCallback)(e=>{ee.current=[],m(e),h(structuredClone(e.providers)),f(structuredClone(e.presets)),v(structuredClone(e.accountModels)),y(!1),j(!1),I(!1),W({dirty:!1,invalid:!1}),q(e=>e+1)},[]);async function el(){R(!0);try{let e=await o.listCatalog({query:"",refresh:!0,page:{index:1,size:1}});D(e.updatedAt),await ed(),i.success("cached"===e.refreshResult?s("catalogCached"):"partial"===e.refreshResult?s("catalogPartial"):"unchanged"===e.refreshResult?s("catalogUnchanged"):s("catalogUpdated"))}catch(e){i.error(e instanceof Error?e.message:s("catalogRefreshFailed"))}finally{R(!1)}}async function eo(e,t=0){let{projectDefaults:n}=await o.previewSettings(e);if(n.length>0){let e=[s("replaceProjectDefaultsDescription"),...t>0?[s("removeInvalidPresets",{count:t})]:[]].join(" ");return a({title:s("replaceProjectDefaultsTitle"),description:e,content:(0,r.createElement)(rC,{projectDefaults:n}),confirmLabel:s("confirmAndSaveModels"),confirmVariant:"default"})}return 0===t||a({title:s("removeInvalidPresetsTitle"),description:s("removeInvalidPresets",{count:t}),confirmLabel:s("removeAndSave")})}async function ec(){if(!Z.current&&!_.invalid&&!Y&&!U){if(!u||!en)return void i.success(s("modelsNoChanges"));Z.current=!0,A(!0);try{let e=new Set([...p.flatMap(e=>e.models.map(t=>`${e.provider}\u0000${t.modelId}`)),...x.map(e=>`${e.provider}\u0000${e.modelId}`)]),t=new Set([...u.providers.flatMap(e=>e.models.map(t=>`${e.provider}\u0000${t.modelId}`)),...u.accountModels.map(e=>`${e.provider}\u0000${e.modelId}`)]),n=g.filter(s=>{let n=`${s.provider}\u0000${s.modelId}`;return!t.has(n)||e.has(n)}),r=g.length-n.length,a={...k||_.dirty?{providers:p}:{},...w?{accountModels:x}:{},...N||r>0?{presets:n}:{},...ee.current.length?{modelReplacements:ee.current}:{}};if(!await eo(a,r))return;await o.replaceSettings(a),ea(await o.getSettings()),j(!1),I(!1),i.success(s("modelSaved"))}catch(e){i.error(e instanceof Error?e.message:s("modelSaveFailed"))}finally{Z.current=!1,A(!1)}}}async function ed(){let e=await o.getSettings();return m(t=>t?{...t,accounts:e.accounts,models:e.models,nativeConfig:e.nativeConfig}:e),e}async function em(){!u||Z.current||Y||await a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")})&&ea(u)}async function ep(){Z.current||(!es||await a({title:s("discardNativeTitle"),description:s("discardNativeDescription"),confirmLabel:s("discardModelConfirm")}))&&H(!1)}async function eh(){if(!Z.current&&U&&es){Z.current=!0,A(!0),Q(null);try{let e={nativeConfig:o.parseNativeConfig(K)};if(!await eo(e))return;await o.replaceSettings(e),ea(await o.getSettings()),H(!1),i.success(s("modelSaved"))}catch(t){let e=t instanceof Error?t.message:s("modelSaveFailed");console.warn("[Pi Desk][ModelSettings] 保存 Pi 配置失败",{message:e}),Q(e)}finally{Z.current=!1,A(!1)}}}return(0,r.useEffect)(()=>{let e=!1;return queueMicrotask(()=>{e||(M(!0),O(null))}),o.getSettings().then(t=>{e||ea(t)}).catch(t=>{if(e)return;let n=t instanceof Error?t.message:s("modelsLoadFailed");console.warn("[Pi Desk][ModelSettings] 读取模型配置失败",{message:n}),O(n)}).finally(()=>{e||M(!1)}),()=>{e=!0}},[o,s,L,ea]),{biz:o,tab:c,settings:u,providers:p,presets:g,accountModels:x,changeAccountModels:e=>{v(e),y(JSON.stringify(e)!==JSON.stringify(u?.accountModels))},refreshAccounts:ed,providersDirty:k,presetsDirty:N,loading:E,saving:z,refreshing:$,catalogUpdatedAt:P,loadError:T,resetVersion:B,formDirty:en,formInvalid:_.invalid,serviceDirty:Y,nativeOpen:U,nativeText:K,nativeError:J,nativeDirty:es,setNativeText:G,openNative:function(){if(u&&!Z.current){if(en||Y||S)return void i.error(s("nativeProtectDraft"));G(et),Q(null),H(!0)}},closeNative:ep,saveNative:eh,revertConfig:em,setInputState:W,setServiceDirty:V,dialog:l,setProjectDefaultDirty:C,changeProviders:(e,t)=>{ee.current=t,h(e),j(JSON.stringify(e)!==JSON.stringify(u?.providers))},changePresets:e=>{f(e),I(JSON.stringify(e)!==JSON.stringify(u?.presets))},selectTab:e=>{if(e!==c&&!Z.current){if("project-default"===c&&S)return void a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}).then(t=>{t&&(C(!1),d(e))});d(e)}},retry:()=>F(e=>e+1),refreshCatalog:el,saveConfig:ec}}(e,s);return(0,n.jsxs)("div",{className:"@container/model-settings flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center justify-between gap-2 border-b p-4",children:[(0,n.jsx)(n2,{label:i("models"),layout:"segmented",value:u,options:aP.map(e=>({...e,label:i(e.label)})),onChange:U}),(0,n.jsxs)("div",{className:"hidden gap-2 @[40rem]/model-settings:flex",children:[(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:!m||L,onClick:A,children:[(0,n.jsx)(rI.A,{}),i("nativeConfig")]}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",title:B?i("catalogUpdatedAt",{time:new Date(B).toLocaleString("en"===a?"en-US":"zh-CN",{timeZone:l,timeZoneName:"shortOffset",hourCycle:"h23"})}):i("catalogUnavailable"),onClick:G,disabled:F,children:[(0,n.jsx)(es.A,{className:(0,C.cn)(F&&"animate-spin")}),F?i("refreshingCatalog"):i("refreshCatalog")]})]}),(0,n.jsxs)(eW.AM,{open:o,onOpenChange:c,children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":i("modelMoreActions"),className:"shrink-0 @[40rem]/model-settings:hidden",children:(0,n.jsx)(H.A,{})})}),(0,n.jsxs)(eW.hl,{align:"end",positionerClassName:"z-[120]",className:"w-48 gap-1 p-1",children:[(0,n.jsxs)(I.$,{type:"button",variant:"ghost",className:"justify-start",disabled:!m||L,onClick:()=>{c(!1),A()},children:[(0,n.jsx)(rI.A,{}),i("nativeConfig")]}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",className:"justify-start",disabled:F,onClick:()=>{c(!1),G()},children:[(0,n.jsx)(es.A,{}),i("refreshCatalog")]})]})]})]}),(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar min-h-0 flex-1","presets"===u?"overflow-y-auto":"overflow-hidden"),children:["project-default"===u?(0,n.jsx)(aR,{biz:d,presets:m?.presets??[],onDirtyChange:W}):m?null:(0,n.jsx)(aD,{loading:O,error:q,onRetry:K}),m?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("fieldset",{disabled:L,className:(0,C.cn)("h-full min-h-0 min-w-0","providers"!==u&&"hidden"),children:(0,n.jsx)(aM,{biz:d,connectionReady:t,providers:p,accounts:m.accounts,accountModels:g,onAccountModelsChange:f,onRefreshAccounts:x,savedProviders:m.providers,savedModels:m.models,presets:h,resetVersion:w,onChange:Y,onPresetsChange:V,onInputState:D,onServiceDirtyChange:T})}),(0,n.jsx)("fieldset",{disabled:L,className:(0,C.cn)("min-w-0","presets"!==u&&"hidden"),children:(0,n.jsx)(i2,{presets:h,models:m.models,onChange:V})})]}):null]}),"project-default"!==u&&m?(0,n.jsxs)("footer",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-t bg-card px-4 py-3",children:[(0,n.jsx)("span",{className:(0,C.cn)("text-xs text-muted-foreground",k&&"text-destructive"),role:"status",children:k?i("fixModelInputs"):y?i("modelDraftPending"):i("modelDraftClean")}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:L||!y||j,onClick:P,children:i("revertModels")}),(0,n.jsxs)(I.$,{type:"button",size:"sm",onClick:J,disabled:L||!y||k||j,children:[L?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(Z.A,{}),L?i("savingModels"):i("saveModels")]})]})]}):null,(0,n.jsx)(iA,{open:N,text:S,error:E,saving:L,dirty:M,onChange:z,onClose:$,onSave:R}),_]})}function aO({render:e,input:t}){return e(t)}let aL=[{id:"appearance",label:"appearance",icon:sq.A},{id:"region",label:"region",icon:s_.A},{id:"habits",label:"habits",icon:sW.A},{id:"models",label:"models",icon:eD.A},{id:"mcp-settings",label:"mcpSettings",icon:eC.A},{id:"capability-modes",label:"capabilityModes",icon:eg.A},{id:"skills",label:"skills",icon:sY.A},{id:"plugins",label:"plugins",icon:eC.A},{id:"auth",label:"loginProtection",icon:en.A},{id:"about",label:"about",icon:sV.A}];function aF(e,t){return`plugin:${e}:${t}`}function aB(){let{t:e}=(0,b.Bd)("settings"),t=(0,eQ.i)();return(0,n.jsxs)("section",{"aria-labelledby":"settings-about-title",className:"min-w-0 space-y-6",children:[(0,n.jsx)("h2",{id:"settings-about-title",className:"text-xl font-semibold",children:e("about")}),(0,n.jsxs)("div",{className:"flex items-center gap-3 rounded-xl bg-muted p-4",children:[(0,n.jsx)(sK.V,{size:48,className:"shrink-0"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:"Pi Desk"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("webDescription")})]})]}),(0,n.jsxs)("dl",{className:"divide-y border-y text-sm",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:e("version")}),(0,n.jsxs)("dd",{className:"font-mono",children:["v",sU]})]}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:e("versionUpdated")}),(0,n.jsx)("dd",{className:"tabular-nums",children:function(e,t,s,n){if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:new Intl.DateTimeFormat(t,{timeZone:s,year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(r)}(sH,"en"===t.locale?"en-US":"zh-CN",t.timeZone,e("common:unavailable"))})]})]})]})}function aq({open:e,connectionReady:t=!1,initialModelTab:s,workSessions:i,focusedCwd:a,pluginAttention:l,renderPluginManagement:o,renderMcpSettings:c,renderCapabilityModesSettings:d,renderPluginSettingsPage:u,onOpenChange:m,onBeforeReload:p}){let{t:h}=(0,b.Bd)("settings"),g=(0,Q.So)(),f=(0,r.useMemo)(()=>{let e=new Map;for(let{cwd:t,projectName:s}of i){let n=t.replaceAll("\\","/").replace(/\/+$/,""),r=/^[a-zA-Z]:\//.test(n)||n.startsWith("//")?n.toLowerCase():n;e.has(r)||e.set(r,{cwd:t,projectName:s})}return[...e.values()]},[i]),x=(0,r.useMemo)(()=>g.flatMap(e=>e.contributions.flatMap(t=>"settings-page"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[g]),[v,w]=(0,r.useState)(()=>s?"models":iM(iC,iI,"appearance"));(0,r.useEffect)(()=>{e&&iz(iC,v)},[v,e]);let[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(!1),S=(0,r.useRef)(null),E=(0,r.useRef)(!1),M=x.find(e=>aF(e.pluginName,e.descriptor.contributionName)===v),z=v.startsWith("plugin:")&&!M?"appearance":v,A=aL.find(e=>e.id===z),$=A?.icon,R=(0,r.useCallback)(async e=>{if(!E.current){E.current=!0,N(!0);try{let t=S.current;if(t&&!await t())return;S.current=null,e()}finally{E.current=!1,N(!1)}}},[]),P=(0,r.useCallback)(()=>{R(()=>m(!1))},[m,R]),D=(0,r.useCallback)(e=>{S.current=e},[]),T=e=>{e!==z&&R(()=>w(e))};return(0,n.jsx)(eN.YV,{open:e,onOpenChange:(e,t)=>{e?m(!0):"focus-out"!==t.reason&&P()},children:(0,n.jsxs)(eN.hA,{className:"h-[min(48rem,calc(100dvh-2rem))] max-w-6xl max-sm:h-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)(eN.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsx)(eN.YM,{children:h("title")})}),(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col sm:flex-row",children:[(0,n.jsx)("div",{className:"shrink-0 border-b bg-sidebar p-3 sm:hidden",children:(0,n.jsxs)(ea.l6,{value:z,disabled:j,onValueChange:e=>{if("string"!=typeof e)return;let t=aL.find(t=>t.id===e);if(t)return void T(t.id);let s=x.find(t=>aF(t.pluginName,t.descriptor.contributionName)===e);s&&T(aF(s.pluginName,s.descriptor.contributionName))},children:[(0,n.jsx)(ea.bq,{"aria-label":h("category"),className:"w-full",children:(0,n.jsx)(ea.yv,{children:M?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eq,{icon:M.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:M.descriptor.label})]}):A&&$?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)($,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:h(A.label)})]}):null})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",align:"start",children:[aL.map(e=>{let t=e.icon;return(0,n.jsxs)(ea.eb,{value:e.id,children:[(0,n.jsxs)("span",{className:"relative shrink-0",children:[(0,n.jsx)(t,{className:"size-4"}),"plugins"===e.id&&l?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute -right-1 -top-1 size-1.5 rounded-full","error"===l?"bg-destructive":"bg-primary")}):null]}),(0,n.jsx)("span",{children:h(e.label)})]},e.id)}),x.length>0?(0,n.jsxs)(ea.s3,{children:[(0,n.jsx)(ea.TR,{children:h("pluginSettings")}),x.map(e=>{let t=aF(e.pluginName,e.descriptor.contributionName);return(0,n.jsxs)(ea.eb,{value:t,children:[(0,n.jsx)(eq,{icon:e.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{children:e.descriptor.label})]},t)})]}):null]})]})}),(0,n.jsxs)("nav",{"aria-label":h("category"),className:"pi-desk-chat-scrollbar hidden w-48 shrink-0 space-y-4 overflow-auto border-r bg-sidebar p-3 sm:block",children:[(0,n.jsx)("div",{className:"grid grid-cols-1 gap-1",children:aL.map(e=>{let t=e.icon,s=e.id===z;return(0,n.jsxs)(I.$,{variant:"ghost",disabled:j,"aria-current":s?"page":void 0,"aria-label":`${h("category")}:${h(e.label)}`,onClick:()=>T(e.id),className:(0,C.cn)("min-w-0 justify-start",s?"bg-accent text-accent-foreground hover:bg-accent":"text-muted-foreground"),children:[(0,n.jsxs)("span",{className:"relative shrink-0",children:[(0,n.jsx)(t,{className:"size-4"}),"plugins"===e.id&&l?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute -right-1 -top-1 size-1.5 rounded-full","error"===l?"bg-destructive":"bg-primary")}):null]}),(0,n.jsx)("span",{className:"truncate",children:h(e.label)})]},e.id)})}),x.length>0?(0,n.jsxs)(eV.Nt,{open:y||!!M,onOpenChange:k,className:"mt-2 border-t pt-2",children:[(0,n.jsxs)(eV.R6,{type:"button","aria-label":h("pluginSettings"),className:"flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1 text-sm font-medium text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 text-left",children:h("pluginSettings")}),(0,n.jsx)("span",{className:"tabular-nums",children:x.length}),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-3.5 transition-transform",y||M?"rotate-180":null)})]}),(0,n.jsx)(eV.Ke,{children:(0,n.jsx)("div",{className:"mt-1 grid grid-cols-1 gap-1",children:x.map(e=>{let t=aF(e.pluginName,e.descriptor.contributionName),s=t===z;return(0,n.jsxs)(I.$,{variant:"ghost",disabled:j,"aria-current":s?"page":void 0,onClick:()=>T(t),className:(0,C.cn)("min-w-0 justify-start",s?"bg-accent text-accent-foreground hover:bg-accent":"text-muted-foreground"),children:[(0,n.jsx)(eq,{icon:e.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:e.descriptor.label})]},t)})})})]}):null]}),M?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:(0,n.jsx)(aO,{render:u,input:{pluginName:M.pluginName,descriptor:M.descriptor,onClose:P,onBeforeLeaveChange:D}})}):"skills"===z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(nP,{projects:f,focusedCwd:a,onBeforeLeaveChange:D})}):"mcp-settings"===z?(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(aO,{render:c,input:{onBeforeLeaveChange:D}})}):"capability-modes"===z?(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(aO,{render:d,input:{onBeforeLeaveChange:D}})}):"models"===z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(aT,{connectionReady:t,initialTab:s,onBeforeLeaveChange:D})}):"plugins"===z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:o()}):(0,n.jsx)(eN._Y,{className:"min-w-0 max-h-none",children:(0,n.jsx)("div",{className:"p-4 sm:p-6",children:"appearance"===z?(0,n.jsx)(ra,{}):"habits"===z?(0,n.jsx)(rN,{}):"auth"===z?e&&(0,n.jsx)(nY,{}):"region"===z?(0,n.jsx)(nQ,{canLeave:p}):(0,n.jsx)(aB,{})})})]})]})})}let a_=a.Ik({cwd:a.Yj().trim().min(1).nullable()}).strict(),aW=a.g1(a.Yj(),a.Pq()),aY=a.g1(a.Yj().min(1).max(128),aW),aV=a.Ik({local:aY,inherited:aY,projectTrusted:a.zM().nullable(),diagnostics:a.YO(a.Ik({name:a.Yj().nullable(),message:a.Yj()}).strict())}).strict();a_.extend({servers:aY}).strict(),a_.extend({name:a.Yj().min(1).max(128)}).strict();let aU=a.Ik({output:a.Yj()}).strict(),aH=a.Ik({}).strict(),aK=["command","args","url","type","description","enabled","exposure"];function aG(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&Object.values(e).every(e=>"string"==typeof e)}function aJ(e){return aG(e)?Object.entries(e).map(([e,t])=>({key:e,value:t})):[]}function aQ(e){return!("command"in e)&&!("url"in e)&&!("type"in e)}function aX(e,t){let s=t??{};return{originalName:e,name:e??"",transport:t&&aQ(t)?"inherit":"url"in s?"http":"stdio",command:"string"==typeof s.command?s.command:"",args:Array.isArray(s.args)?s.args.join("\n"):"",env:aJ(s.env),headers:aJ(s.headers),url:"string"==typeof s.url?s.url:"",description:"string"==typeof s.description?s.description:"",enabled:!1!==s.enabled,exposure:"string"==typeof s.exposure?s.exposure:"",advanced:JSON.stringify(Object.fromEntries(Object.entries(s).filter(([e,t])=>!aK.includes(e)&&!(["env","headers"].includes(e)&&aG(t)))),null,2)}}class aZ extends Error{constructor(e,t){super(t),this.field=e}}function a0(e){return"string"==typeof e.url?e.url:"string"==typeof e.command?e.command:"继承全局连接"}let a1={MCP:"MCP",服务列表:"Servers",配置服务:"Configure server",服务配置:"Server configuration",手动配置:"Configure manually","导入 JSON":"Import JSON",返回服务列表:"Back to servers",服务操作:"Server actions",恢复全局配置:"Restore global configuration",删除服务:"Delete server",继承全局:"Inherited from global",项目配置:"Project configuration","项目配置 \xb7 继承全局连接":"Project configuration \xb7 inherits global connection","连接参数沿用全局,仅保存本项目的启用和工具设置。":"Connection settings are inherited from global. Only enablement and tool settings are saved for this project.",环境变量:"Environment variables",请求头:"Request headers",名称:"Name",值:"Value",添加:"Add ",删除行:"Remove row",高级设置:"Advanced settings","其他配置(JSON)":"Other configuration (JSON)",保存并测试:"Save and test",连接测试结果:"Connection test result","正在测试连接…":"Testing connection…","已保存,正在测试连接…":"Saved. Testing connection…",连接测试通过:"Connection test passed",连接测试失败:"Connection test failed",查看详细输出:"View output","已保存,连接测试通过。":"Saved. Connection test passed.","已保存,连接测试失败。":"Saved. Connection test failed.","请填写名称,或删除空白行。":"Enter a name or remove the empty row.","名称不能重复。":"Names must be unique.","环境变量和请求头不能在表单与 JSON 中重复配置。":"Do not configure environment variables or request headers in both the form and JSON.","连接请求最多等待 10 秒;凭据命令可能延长检查时间。":"Connection requests wait up to 10 seconds; credential commands may extend the check.",配置范围:"Configuration scope",全局:"Global",当前项目:"Current project",手动添加:"Add manually","添加 JSON":"Add JSON","正在读取配置…":"Loading configuration…",重试:"Retry","添加第一个 MCP 服务":"Add your first MCP server","添加服务地址或本地程序。":"Add a server URL or a local program.",已启用:"Enabled",已停用:"Disabled",启用:"Enable",停用:"Disable",编辑:"Edit",为本项目配置:"Configure for this project",独立检查:"Check independently",删除:"Delete",来自全局:"Inherited from global",本项目:"This project",覆盖全局:"Overrides global","项目设置 \xb7 继承全局连接":"Project settings \xb7 inherits global connection",继承全局连接:"Inherit global connection","本项目尚未受信任,不能执行检查;仍可编辑和保存配置。":"This project is not trusted. Checking is disabled; editing and saving remain available.","配置启用不代表已连接。保存不会自动连接或重载会话。":"Enabled configuration does not mean connected. Saving does not connect or reload sessions.","正在检查…":"Checking…",检查输出:"Check output",检查完成:"Check completed",检查失败:"Check failed","检查连接已关闭,当前聊天会话状态未改变。":"The check connection is closed. Current chat session state is unchanged.",返回编辑:"Edit configuration",关闭结果:"Dismiss result",返回:"Back",添加服务:"Add server",编辑服务:"Edit server",保存范围:"Save scope",服务名称:"Server name",连接方式:"Transport",本地程序:"Local program","HTTP 地址":"HTTP URL",启动程序:"Command","参数(每行一个)":"Arguments (one per line)","服务说明(可选)":"Description (optional)",工具使用方式:"Tool exposure",沿用默认:"Use default",通过脚本调用:"Via scripts",按需发现:"On-demand discovery",直接使用:"Direct use",隐藏:"Hidden","高级配置(JSON)":"Advanced configuration (JSON)","继承全局连接,仅保存本项目启用与曝光设置,不复制全局凭据。":"Inherits the global connection. Only project enablement and exposure settings are saved; global credentials are not copied.","本项目的完整定义会整体替换同名全局配置。":"A complete project definition replaces the global configuration of the same name.","配置 JSON":"Configuration JSON","仅接受包含 mcpServers 的标准 JSON。":"Only standard JSON with mcpServers is accepted.",解析预览:"Preview",待保存服务:"Servers to save",新增:"New",替换已有配置:"Replace existing configuration","覆盖全局(仅本项目)":"Override global (this project only)",允许替换以上同名已有配置:"Allow replacing existing configuration with the same names","重新编辑 JSON":"Edit JSON again",取消:"Cancel",保存:"Save","保存中…":"Saving…","已保存。新会话使用新配置;已有会话需重载 Pi 配置。":"Saved. New sessions use the new configuration; existing sessions must reload Pi configuration.","放弃未保存的修改?":"Discard unsaved changes?","当前修改尚未保存。放弃后将保留已保存的配置。":"Your changes have not been saved. Discarding keeps the saved configuration.",放弃修改:"Discard changes",删除配置:"Delete configuration","删除本项目配置后,将恢复使用同名全局配置。":"Deleting this project configuration restores the global configuration of the same name.","此范围内的服务配置将被删除。":"The server configuration will be deleted from this scope.","请输入有效的 JSON。":"Enter valid JSON.","仅接受包含 mcpServers 的标准配置,不允许其他根级字段。":"Only a standard mcpServers object is accepted; other root fields are not allowed.","配置中至少需要一个服务。":"At least one server is required.","服务名称需要 1–128 个字符。":"Server names must contain 1–128 characters.","高级配置需要是 JSON 对象。":"Advanced configuration must be a JSON object.","连接、说明、启用和曝光字段请在上方表单中填写。":"Set connection, description, enablement and exposure in the fields above.","继承连接只允许启用、曝光和 toolExposure 设置。":"Inherited connections only allow enablement, exposure and toolExposure settings.","请输入启动程序。":"Enter a command.","请输入有效的 HTTP 或 HTTPS 地址。":"Enter a valid HTTP or HTTPS URL.","请明确勾选替换已有配置。":"Explicitly allow replacing existing configuration.","该名称已存在,请编辑已有服务或使用其他名称。":"This name already exists. Edit that server or choose another name.","请求失败,请重试。":"The request failed. Please retry."};function a2(){let{locale:e}=(0,eQ.i)();return t=>"en"===e?a1[t]??t:t}function a5(e){return e instanceof Error?e.message:"请求失败,请重试。"}var a3=s(60454),a4=s(93750),a6=s(13464);function a8({id:e,label:t,value:s,options:r,disabled:i,onChange:a}){return(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsx)("label",{id:`${e}-label`,htmlFor:e,className:"text-sm font-medium",children:t}),(0,n.jsxs)(ea.l6,{value:s,disabled:i,onValueChange:e=>{"string"==typeof e&&a(e)},children:[(0,n.jsx)(ea.bq,{id:e,"aria-labelledby":`${e}-label`,className:"w-full min-w-0 whitespace-normal [&_[data-slot=select-value]]:line-clamp-none [&_[data-slot=select-value]]:break-all",children:(0,n.jsx)(ea.yv,{children:r.find(e=>e.value===s)?.label??s})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[125]",align:"start",children:r.map(e=>(0,n.jsx)(ea.eb,{value:e.value,className:"[&_span]:whitespace-normal [&_span]:break-all",children:e.label},e.value))})]})]})}function a7({trigger:e,children:t}){return(0,n.jsxs)(K.rI,{children:[(0,n.jsx)(K.ty,{render:e}),(0,n.jsx)(K.dc,{children:(0,n.jsx)(a3.y,{sideOffset:4,align:"end",className:"z-[125] outline-none",children:(0,n.jsx)(a4._,{className:a6.hD,children:t})})})]})}function a9({message:e,id:t}){let s=a2();return e?(0,n.jsx)("p",{id:t,role:"alert",className:"break-words text-sm text-destructive",children:s(e)}):null}function le({rows:e,selectedName:t,pending:s,onSelect:r}){let i=a2();return(0,n.jsx)("ul",{"aria-label":i("服务列表"),className:"divide-y",children:e.map(e=>{let a="string"==typeof e.config.url?eL.A:w.A;return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button","aria-label":`${i("配置服务")} \xb7 ${e.name}`,"aria-current":t===e.name?"true":void 0,disabled:s,onClick:()=>r(e),className:(0,C.cn)("flex w-full min-w-0 cursor-pointer items-center gap-3 p-4 text-left outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-default",t===e.name&&"bg-accent"),children:[(0,n.jsx)(a,{"aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1 space-y-1",children:[(0,n.jsxs)("span",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,n.jsx)("span",{className:"min-w-0 break-all text-sm font-medium",children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:i(!1===e.config.enabled?"已停用":"已启用")})]}),(0,n.jsxs)("span",{className:"block text-xs text-muted-foreground",children:[i(e.source)," \xb7"," ",i("string"==typeof e.config.url?"HTTP 地址":"本地程序")]}),(0,n.jsx)("span",{className:"block truncate font-mono text-xs text-muted-foreground",children:a0(e.config)})]}),(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"})]})},e.name)})})}function lt({id:e,label:t,rows:s,disabled:r,error:i,onChange:a}){let l=a2();return(0,n.jsxs)("fieldset",{className:"min-w-0 space-y-2",disabled:r,children:[(0,n.jsx)("legend",{className:"text-sm font-medium",children:t}),s.length>0&&(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_2rem] gap-2 text-xs text-muted-foreground","aria-hidden":"true",children:[(0,n.jsx)("span",{children:l("名称")}),(0,n.jsx)("span",{children:l("值")})]}),s.map((o,c)=>(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_2rem] gap-2",children:[(0,n.jsx)(em.p,{"aria-label":`${t} \xb7 ${l("名称")} ${c+1}`,"aria-invalid":!!i,"aria-describedby":i?`${e}-error`:void 0,value:o.key,spellCheck:!1,className:"min-w-0 font-mono",onChange:e=>a(s.map((t,s)=>s===c?{...t,key:e.target.value}:t))}),(0,n.jsx)(em.p,{"aria-label":`${t} \xb7 ${l("值")} ${c+1}`,value:o.value,spellCheck:!1,autoComplete:"off",className:"min-w-0 font-mono",onChange:e=>a(s.map((t,s)=>s===c?{...t,value:e.target.value}:t))}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":`${l("删除行")} \xb7 ${t} ${c+1}`,disabled:r,onClick:()=>a(s.filter((e,t)=>t!==c)),children:(0,n.jsx)(et.A,{"aria-hidden":"true"})})]},c)),(0,n.jsx)(a9,{id:`${e}-error`,message:i}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>a([...s,{key:"",value:""}]),children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),l("添加"),t]})]})}var ls=s(27315);function ln({check:e,onRetry:t,onDismiss:s}){let r=a2(),i=e.loading?v.A:e.error?Y.A:ls.A;return(0,n.jsxs)("section",{"aria-label":r("连接测试结果"),"aria-busy":e.loading,className:"space-y-2 border-b pb-4",children:[(0,n.jsxs)("p",{role:"status",className:"flex items-center gap-2 text-sm font-medium",children:[(0,n.jsx)(i,{"aria-hidden":"true",className:`size-4 shrink-0 ${e.loading?"motion-safe:animate-spin":e.error?"text-destructive":""}`}),r(e.loading?"已保存,正在测试连接…":e.error?"已保存,连接测试失败。":"已保存,连接测试通过。")]}),(0,n.jsx)(a9,{message:e.error}),e.loading?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:r("连接请求最多等待 10 秒;凭据命令可能延长检查时间。")}):(0,n.jsxs)(n.Fragment,{children:[e.output&&(0,n.jsxs)("details",{className:"text-sm",children:[(0,n.jsx)("summary",{className:"w-fit cursor-pointer rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:r("查看详细输出")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap break-all rounded-lg bg-muted p-3 font-mono text-sm",children:e.output})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:r("检查连接已关闭,当前聊天会话状态未改变。")}),(0,n.jsxs)("div",{className:"flex gap-2",children:[e.error&&(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:t,children:r("重试")}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:s,children:r("关闭结果")})]})]})]})}function lr({editor:e,scopeLabel:t,project:s,projectTrusted:i,check:a,local:l,inherited:o,pending:c,saving:d,error:u,onDraft:m,onJson:p,onPreview:h,onOverwrite:g,onSave:f,onCancel:x,onRemove:b,onDismissCheck:v}){let w=a2(),y=(0,r.useId)(),k=(0,r.useRef)(null),[j,N]=(0,r.useState)(!1);(0,r.useEffect)(()=>{u&&k.current?.querySelector('[aria-invalid="true"]')?.focus()},[u]);let S=e=>`${y}-${e}`,C="manual"===e.kind?e.draft:null,E="json"===e.kind&&e.preview?Object.keys(e.preview).filter(e=>Object.hasOwn(l,e)):[],M="json"===e.kind?"导入 JSON":C?.originalName?"服务配置":"添加服务",z=C?.originalName,$=!!(z&&Object.hasOwn(l,z)),R=!!(s&&z&&Object.hasOwn(o,z)),P=(e,t,s)=>(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:S(e),className:"text-sm font-medium",children:w(t)}),s,(0,n.jsx)(a9,{id:S(`${e}-error`),message:u?.field===e?u.message:null})]}),D=(e,t)=>P(e,t,(0,n.jsx)(em.p,{id:S(e),value:C?.[e]??"",disabled:c||"name"===e&&!!C?.originalName,"aria-invalid":u?.field===e,"aria-describedby":u?.field===e?S(`${e}-error`):void 0,onChange:t=>m({[e]:t.target.value})}));return(0,n.jsxs)("form",{ref:k,"aria-label":w(M),className:"flex min-h-0 min-w-0 flex-1 flex-col",onSubmit:e=>{e.preventDefault(),f()},children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-1 border-b p-4 sm:px-6",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":w("返回服务列表"),disabled:c,onClick:x,children:(0,n.jsx)(A.A,{"aria-hidden":"true"})}),(0,n.jsx)("h3",{className:"min-w-0 flex-1 text-sm font-semibold",children:w(M)}),$&&z&&(0,n.jsx)(a7,{trigger:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":w("服务操作"),disabled:c,children:(0,n.jsx)(H.A,{"aria-hidden":"true"})}),children:(0,n.jsx)(K._2,{variant:R?"default":"destructive",onClick:()=>b(z),children:w(R?"恢复全局配置":"删除服务")})})]}),s&&(0,n.jsxs)("p",{className:"break-all text-xs text-muted-foreground",children:[w("保存范围"),":",t]})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:[C?(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-4",children:[a&&(0,n.jsx)(ln,{check:a,onRetry:()=>f(!0),onDismiss:v}),D("name","服务名称"),"inherit"===C.transport?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:w("继承全局连接")}),z&&o[z]&&(0,n.jsx)("p",{className:"break-all font-mono text-sm text-muted-foreground",children:a0(o[z])}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("连接参数沿用全局,仅保存本项目的启用和工具设置。")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a8,{id:S("transport"),label:w("连接方式"),value:C.transport,disabled:c,options:[{value:"stdio",label:w("本地程序")},{value:"http",label:w("HTTP 地址")}],onChange:e=>m({transport:"http"===e?"http":"stdio"})}),"stdio"===C.transport?(0,n.jsxs)(n.Fragment,{children:[D("command","启动程序"),P("args","参数(每行一个)",(0,n.jsx)(t7.T,{id:S("args"),className:"min-h-24 font-mono",value:C.args,disabled:c,onChange:e=>m({args:e.target.value})}))]}):D("url","HTTP 地址"),("stdio"===C.transport||u?.field==="env")&&(0,n.jsx)(lt,{id:S("env"),label:w("环境变量"),rows:C.env,disabled:c,error:u?.field==="env"?u.message:null,onChange:e=>m({env:e})}),("http"===C.transport||u?.field==="headers")&&(0,n.jsx)(lt,{id:S("headers"),label:w("请求头"),rows:C.headers,disabled:c,error:u?.field==="headers"?u.message:null,onChange:e=>m({headers:e})}),s&&(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("本项目的完整定义会整体替换同名全局配置。")})]}),(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",checked:C.enabled,disabled:c,onChange:e=>m({enabled:e.target.checked}),className:"size-4 shrink-0 accent-primary"}),w("已启用")]}),(0,n.jsxs)(eV.Nt,{open:j||u?.field==="advanced",onOpenChange:N,children:[(0,n.jsxs)(eV.R6,{type:"button",className:"group flex min-h-8 cursor-pointer items-center gap-2 rounded-lg px-2 text-sm font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eY.A,{"aria-hidden":"true",className:"size-4 transition-transform group-data-panel-open:rotate-180"}),w("高级设置")]}),(0,n.jsxs)(eV.Ke,{className:"space-y-3 pt-3",children:["inherit"!==C.transport&&D("description","服务说明(可选)"),(0,n.jsx)(a8,{id:S("exposure"),label:w("工具使用方式"),value:C.exposure,disabled:c,options:[{value:"",label:w("沿用默认")},{value:"codemode",label:w("通过脚本调用")},{value:"deferred",label:w("按需发现")},{value:"direct",label:w("直接使用")},{value:"hidden",label:w("隐藏")},...["","codemode","deferred","direct","hidden"].includes(C.exposure)?[]:[{value:C.exposure,label:C.exposure}]],onChange:e=>m({exposure:e})}),(0,n.jsx)("label",{htmlFor:S("advanced"),className:"block text-sm font-medium",children:w("其他配置(JSON)")}),(0,n.jsx)(t7.T,{id:S("advanced"),onFocus:()=>N(!0),value:C.advanced,disabled:c,className:"min-h-40 font-mono",spellCheck:!1,"aria-invalid":u?.field==="advanced","aria-describedby":u?.field==="advanced"?S("advanced-error"):void 0,onChange:e=>m({advanced:e.target.value})}),(0,n.jsx)(a9,{id:S("advanced-error"),message:u?.field==="advanced"?u.message:null})]})]})]}):"json"===e.kind?(0,n.jsxs)("div",{className:"space-y-3",children:[P("json","配置 JSON",(0,n.jsx)(t7.T,{id:S("json"),value:e.text,disabled:c,"aria-invalid":u?.field==="json","aria-describedby":u?.field==="json"?S("json-error"):void 0,spellCheck:!1,className:"min-h-48 font-mono",placeholder:'{ "mcpServers": { "docs": { "url": "https://example.com/mcp" } } }',onChange:e=>p(e.target.value)})),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("仅接受包含 mcpServers 的标准 JSON。")}),(0,n.jsx)(I.$,{type:"button",variant:"outline",onClick:h,disabled:c||!e.text.trim(),children:w("解析预览")}),e.preview&&(0,n.jsxs)("section",{"aria-label":w("待保存服务"),className:"space-y-3",children:[(0,n.jsx)("ul",{className:"divide-y border-y",children:Object.entries(e.preview).map(([e,t])=>(0,n.jsxs)("li",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 break-all font-medium",children:e}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(aQ(t)?"继承全局连接":"url"in t?"HTTP 地址":"本地程序")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(Object.hasOwn(l,e)?"替换已有配置":Object.hasOwn(o,e)?"覆盖全局(仅本项目)":"新增")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(!1===t.enabled?"已停用":"已启用")})]},e))}),E.length>0&&(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-start gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",checked:e.overwrite,disabled:c,className:"mt-1 size-4 shrink-0 accent-primary",onChange:e=>g(e.target.checked)}),(0,n.jsx)("span",{children:w("允许替换以上同名已有配置")})]})]})]}):null,(0,n.jsx)("div",{className:"mt-3",children:(0,n.jsx)(a9,{message:u?.field==="save"?u.message:null})})]}),(0,n.jsxs)("footer",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t bg-background px-4 py-3 sm:px-6",children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:c,onClick:x,children:w("取消")}),C&&(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:c||!C.enabled||!1===i,onClick:()=>f(!0),children:w("保存并测试")}),(0,n.jsx)(I.$,{type:"submit",disabled:c||"json"===e.kind&&(!e.preview||E.length>0&&!e.overwrite),children:w(a?.loading?"正在测试连接…":d?"保存中…":"保存")})]})]})}function li({pending:e,onAdd:t,onImport:s}){let r=a2();return(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-6",children:(0,n.jsx)("div",{className:"grid min-h-full grid-rows-[1fr_auto_2fr]",children:(0,n.jsxs)("div",{className:"row-start-2 flex flex-col items-center gap-6 text-center",children:[(0,n.jsxs)("div",{"aria-hidden":"true",className:"relative h-28 w-60 shrink-0 text-muted-foreground",children:[(0,n.jsxs)("svg",{viewBox:"0 0 240 112",fill:"none",className:"absolute inset-0 size-full text-muted-foreground/40",children:[(0,n.jsx)("path",{d:"M44 76H64Q76 76 76 64V60Q76 56 92 56M148 56H164Q180 56 180 44Q180 40 196 40M120 12V28",stroke:"currentColor"}),(0,n.jsx)("circle",{cx:"120",cy:"8",r:"3",className:"fill-background stroke-current"}),(0,n.jsx)("circle",{cx:"64",cy:"76",r:"2",className:"fill-muted-foreground"}),(0,n.jsx)("circle",{cx:"180",cy:"44",r:"2",className:"fill-muted-foreground"})]}),(0,n.jsx)("div",{className:"absolute top-14 left-1 flex size-10 items-center justify-center rounded-xl border bg-muted/50",children:(0,n.jsx)(w.A,{className:"size-4"})}),(0,n.jsx)("div",{className:"absolute top-7 left-[92px] flex size-14 items-center justify-center rounded-xl border bg-background text-foreground",children:(0,n.jsx)(eC.A,{className:"size-6"})}),(0,n.jsx)("div",{className:"absolute top-5 right-1 flex size-10 items-center justify-center rounded-xl border bg-muted/50",children:(0,n.jsx)(eL.A,{className:"size-4"})})]}),(0,n.jsx)("h3",{className:"text-lg font-semibold",children:r("添加第一个 MCP 服务")}),(0,n.jsxs)("div",{className:"flex flex-wrap justify-center gap-2",children:[(0,n.jsxs)(I.$,{disabled:e,onClick:t,children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),r("添加服务")]}),(0,n.jsx)(I.$,{variant:"outline",disabled:e,onClick:s,children:r("导入 JSON")})]})]})})})}function la({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{clientId:i}=(0,ei.gM)(),l=function(e,t){let s=a2(),n=(0,r.useMemo)(()=>({getMcp:(t,s)=>eu(e,"/api/mcp-settings/get",{cwd:t},aV,{signal:s}),replaceMcp:(t,s)=>eu(e,"/api/mcp-settings/replace",t,aH,{signal:s}),deleteMcp:(t,s,n)=>eu(e,"/api/mcp-settings/del",{cwd:t,name:s},aH,{signal:n}),checkMcp:(t,s,n)=>eu(e,"/api/mcp-check/get",{cwd:t,name:s},aU,{signal:n})}),[e]),{confirm:i,dialog:l}=nF(),[o,c]=(0,r.useState)(null),[d,u]=(0,r.useState)(null),m=d?.data??null,p=d?d.cwd:o,[h,g]=(0,r.useState)(null),[f,x]=(0,r.useState)(!0),[b,v]=(0,r.useState)(!1),[w,y]=(0,r.useState)(null),[k,j]=(0,r.useState)(null),[N,I]=(0,r.useState)(null),[S,C]=(0,r.useState)(null),E=(0,r.useRef)(null),M=(0,r.useRef)(0),z=(0,r.useRef)(0),A=(0,r.useRef)(i),$=(0,r.useRef)(s);(0,r.useEffect)(()=>{A.current=i,$.current=s},[i,s]);let R=null!==d&&d.cwd===o&&!f&&!w,P=R&&(h?.kind==="manual"&&JSON.stringify(h.draft)!==h.initial||h?.kind==="json"&&!!h.text),D=(0,r.useCallback)(()=>{g(null),j(null)},[]),T=(0,r.useCallback)(async()=>!(b||S?.loading)&&(!P||await A.current({title:$.current("放弃未保存的修改?"),description:$.current("当前修改尚未保存。放弃后将保留已保存的配置。"),confirmLabel:$.current("放弃修改")})),[P,b,S?.loading]);(0,r.useEffect)(()=>(t(T),()=>t(null)),[T,t]);let O=(0,r.useCallback)(async(e,t,s=!1)=>{x(!0),y(null);try{let r=await n.getMcp(o,e);if(e.aborted||M.current!==t)return!1;return u({cwd:o,data:r}),s&&g(null),!0}catch(s){return e.aborted||M.current!==t||(console.warn("[Pi Desk][MCP] 读取配置失败",{cwd:o,message:a5(s)}),y(a5(s))),!1}finally{e.aborted||M.current!==t||x(!1)}},[n,o]);(0,r.useEffect)(()=>{let e=new AbortController;E.current=e;let t=++M.current;return O(e.signal,t,!0),()=>e.abort()},[O]);let L=async e=>{await T()&&(D(),I(null),e())},F=async e=>{e!==o&&await T()&&(E.current?.abort(),j(null),I(null),C(null),y(null),x(!0),c(e))},B=(e,t)=>{let s=aX(e,t);j(null),I(null),C(null),g({kind:"manual",draft:s,initial:JSON.stringify(s)})},q=async(e,t)=>{let s=E.current?.signal;if(!s||!R||b||S?.loading)return!1;let n=M.current;v(!0),j(null),I(null);try{if(await e(s),s.aborted||M.current!==n)return!1;return t(),C(null),I("已保存。新会话使用新配置;已有会话需重载 Pi 配置。"),await O(s,n)}catch(e){return s.aborted||M.current!==n||j({field:e instanceof aZ?e.field:"save",message:a5(e)}),!1}finally{s.aborted||M.current!==n||v(!1)}},_=async(e=!1)=>{if(!(!h||!m||!R||b||S?.loading)&&(!e||"manual"===h.kind&&h.draft.enabled&&!1!==m.projectTrusted))try{let t="manual"===h.kind?function(e,t){let s,n=e.name.trim();if(!n||n.length>128)throw new aZ("name","服务名称需要 1–128 个字符。");try{s=aW.parse(JSON.parse(e.advanced))}catch{throw new aZ("advanced","高级配置需要是 JSON 对象。")}if(aK.some(e=>e in s))throw new aZ("advanced","连接、说明、启用和曝光字段请在上方表单中填写。");if("inherit"===e.transport&&Object.keys(s).some(e=>"toolExposure"!==e))throw new aZ("advanced","继承连接只允许启用、曝光和 toolExposure 设置。");let r={...s,enabled:e.enabled};if(e.exposure&&(r.exposure=e.exposure),"inherit"!==e.transport){for(let n of(e.description&&(r.description=e.description),["env","headers"]))if(e[n].length>0||aG(t?.[n])){if(n in s)throw new aZ("advanced","环境变量和请求头不能在表单与 JSON 中重复配置。");r[n]=function(e,t){let s=[],n=new Set;for(let r of e){if(!r.key.trim()&&!r.value)continue;if(!r.key.trim())throw new aZ(t,"请填写名称,或删除空白行。");let e=r.key.trim(),i="headers"===t?e.toLowerCase():e;if(n.has(i))throw new aZ(t,"名称不能重复。");n.add(i),s.push([e,r.value])}return Object.fromEntries(s)}(e[n],n)}}if("stdio"===e.transport){if(!e.command.trim())throw new aZ("command","请输入启动程序。");r.command=e.command.trim(),r.args=Array.isArray(t?.args)&&t.args.join("\n")===e.args?t.args:e.args?e.args.split(/\r?\n/):[],(t?.type!==void 0||!t||"url"in t)&&(r.type="stdio")}else if("http"===e.transport){try{let t=new URL(e.url.trim());if(!["https:","http:"].includes(t.protocol))throw Error()}catch{throw new aZ("url","请输入有效的 HTTP 或 HTTPS 地址。")}r.url=e.url.trim(),(t?.type!==void 0||!t||"command"in t)&&(r.type="http")}return{[n]:r}}(h.draft,h.draft.originalName?m.local[h.draft.originalName]:void 0):h.preview;if(!t)return;let s=Object.keys(t).filter(e=>Object.hasOwn(m.local,e));if("json"===h.kind&&s.length&&!h.overwrite)throw new aZ("json","请明确勾选替换已有配置。");if("manual"===h.kind&&s.some(e=>e!==h.draft.originalName))throw new aZ("name","该名称已存在,请编辑已有服务或使用其他名称。");if(await q(e=>n.replaceMcp({cwd:o,servers:t},e),()=>{if("json"===h.kind)g(null);else{let e=h.draft.name.trim(),s=aX(e,t[e]);g({kind:"manual",draft:s,initial:JSON.stringify(s)})}})&&e&&"manual"===h.kind){let e=await Y(h.draft.name.trim());E.current?.signal.aborted||I(e?"已保存,连接测试通过。":"已保存,连接测试失败。")}}catch(e){j({field:e instanceof aZ?e.field:"save",message:a5(e)})}},W=async e=>{if(!m||!R||b||!Object.hasOwn(m.local,e))return;let t=null!==o&&Object.hasOwn(m.inherited,e);await A.current({title:`${$.current(t?"恢复全局配置":"删除服务")} \xb7 ${e}`,description:$.current(t?"删除本项目配置后,将恢复使用同名全局配置。":"此范围内的服务配置将被删除。"),confirmLabel:$.current(t?"恢复全局配置":"删除服务")})&&await q(t=>n.deleteMcp(o,e,t),()=>g(null))},Y=async e=>{let t=E.current?.signal;if(!t||!m||!1===m.projectTrusted||S?.loading)return!1;let s=++z.current;C({name:e,loading:!0,output:null,error:null});try{let r=await n.checkMcp(o,e,t);return t.aborted||z.current!==s||C({name:e,loading:!1,output:r.output.slice(0,32768),error:null}),!0}catch(n){return t.aborted||z.current!==s||C({name:e,loading:!1,output:null,error:a5(n)}),!1}},V=m?[...new Set([...Object.keys(m.inherited),...Object.keys(m.local)])].map(e=>{let t=m.local[e],s=m.inherited[e],n=!!(t&&s&&aQ(t));return{name:e,config:n?{...s,...t}:t??s,local:t??null,source:null===p?"全局":t?n?"项目配置 \xb7 继承全局连接":"项目配置":"继承全局"}}):[];return{cwd:o,displayCwd:p,ready:R,mcp:m,editor:h,setEditor:g,loading:f,pending:b,loadError:w,error:k,notice:N,check:S,rows:V,dirty:P,dialog:l,retry:()=>{E.current&&O(E.current.signal,M.current,d?.cwd!==o)},navigate:L,setCwd:F,startManual:B,startInherited:(e,t)=>{B(e,{enabled:!1!==t.enabled})},updateDraft:e=>{g(t=>t?.kind==="manual"?{...t,draft:{...t.draft,...e}}:t),j(null),I(null),C(null)},updateJson:e=>{g({kind:"json",text:e,preview:null,overwrite:!1}),j(null)},previewJson:()=>{if(h?.kind==="json"&&m)try{let t=function(e){let t;try{t=JSON.parse(e)}catch{throw Error("请输入有效的 JSON。")}let s=a.Ik({mcpServers:aY}).strict().safeParse(t);if(!s.success)throw Error("仅接受包含 mcpServers 的标准配置,不允许其他根级字段。");if(0===Object.keys(s.data.mcpServers).length)throw Error("配置中至少需要一个服务。");return s.data.mcpServers}(h.text);var e=m.inherited;for(let[s,n]of Object.entries(t)){if(!s.trim()||s!==s.trim())throw new aZ("json","服务名称不能为空或带有首尾空格。");if(aQ(n)){if(null===o||!Object.hasOwn(e,s)||Object.keys(n).some(e=>!["enabled","exposure","toolExposure"].includes(e)))throw new aZ("json",`${s}:继承配置需要同名全局服务,且只允许启用和曝光设置。`)}else if("sse"===n.type)throw new aZ("json",`${s}:不支持 SSE,请使用 HTTP 连接。`);else if("string"!=typeof n.command&&"string"!=typeof n.url)throw new aZ("json",`${s}:请提供启动程序或服务地址。`)}g({...h,preview:t,overwrite:!1}),j(null)}catch(e){j({field:"json",message:a5(e)})}},saveEditor:_,remove:W,dismissCheck:()=>{C(null)},beforeLeave:T}}(i,s),o=a2(),c=(0,r.useId)(),d=(0,r.useMemo)(()=>{let s=new Map;for(let t of e){let e=t.cwd.replaceAll("\\","/").replace(/\/+$/,""),n=/^[a-zA-Z]:\//.test(e)||e.startsWith("//")?e.toLowerCase():e;s.has(n)||s.set(n,t)}return[...s.values()].sort((e,s)=>Number(s.cwd===t)-Number(e.cwd===t))},[e,t]),u=null===l.displayCwd?o("全局"):`${d.find(e=>e.cwd===l.displayCwd)?.projectName??o("当前项目")} \xb7 ${l.displayCwd}`,m=!!(l.editor&&l.mcp),p=l.pending||!!l.check?.loading,h=p||!l.ready,g=l.editor?.kind==="manual"?l.editor.draft.originalName:null,f=()=>{l.navigate(()=>l.startManual(null))},x=()=>{l.navigate(()=>l.setEditor({kind:"json",text:"",preview:null,overwrite:!1}))};return(0,n.jsxs)("section",{"aria-label":"MCP",className:"@container/mcp flex h-full min-h-0 min-w-0 flex-col",children:[l.dialog,(0,n.jsxs)("header",{className:"grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 border-b p-4 @min-[40rem]/mcp:grid-cols-[auto_minmax(0,1fr)_auto]",children:[(0,n.jsxs)("h2",{className:"flex items-center gap-2 text-xl font-semibold",children:["MCP",(0,n.jsx)("span",{className:"inline-flex size-4",children:l.loading&&(0,n.jsx)(v.A,{role:"status","aria-label":o("正在读取配置…"),className:"size-4 animate-spin text-muted-foreground"})})]}),(0,n.jsxs)("div",{className:"col-start-2 flex flex-wrap justify-end gap-2 @min-[40rem]/mcp:col-start-3 @min-[40rem]/mcp:self-end",children:[(0,n.jsxs)(I.$,{disabled:h,onClick:f,children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),o("添加服务")]}),(0,n.jsx)(I.$,{variant:"outline",disabled:h,onClick:x,children:o("导入 JSON")})]}),(0,n.jsx)("div",{className:"col-span-2 row-start-2 w-full @min-[40rem]/mcp:col-span-1 @min-[40rem]/mcp:col-start-2 @min-[40rem]/mcp:row-start-1 @min-[40rem]/mcp:max-w-80 @min-[40rem]/mcp:justify-self-end @min-[40rem]/mcp:[&_[data-slot=select-trigger]]:mb-0",children:(0,n.jsx)(a8,{id:`${c}-scope`,label:o("配置范围"),value:l.cwd??"",disabled:p,options:[{value:"",label:o("全局")},...d.map(e=>({value:e.cwd,label:`${e.projectName}${e.cwd===t?` \xb7 ${o("当前项目")}`:""}`}))],onChange:e=>{l.setCwd(e||null)}})})]}),l.notice&&!l.check&&(0,n.jsx)("p",{role:"status",className:"shrink-0 break-words border-b px-4 py-2 text-sm",children:o(l.notice)}),l.mcp?.projectTrusted===!1&&(0,n.jsx)("p",{className:"shrink-0 px-4 pt-3 text-sm text-muted-foreground",children:o("本项目尚未受信任,不能执行检查;仍可编辑和保存配置。")}),l.mcp&&l.mcp.diagnostics.length>0&&(0,n.jsx)("div",{className:"max-h-32 shrink-0 space-y-2 overflow-y-auto px-4 pt-3",children:l.mcp.diagnostics.map((e,t)=>(0,n.jsx)(a9,{message:`${e.name?`${e.name}:`:""}${e.message}`},t))}),l.loadError&&(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(a9,{message:l.loadError}),(0,n.jsx)(I.$,{variant:"outline",onClick:l.retry,disabled:l.loading,children:o("重试")})]}),l.loading&&!l.mcp?(0,n.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:o("正在读取配置…")}):l.mcp?(0,n.jsxs)("div",{"aria-busy":l.loading,className:"flex min-h-0 min-w-0 flex-1",children:[l.editor?.kind!=="json"&&l.rows.length>0&&(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar min-h-0 min-w-0 overflow-y-auto",m?"hidden @min-[48rem]/mcp:block @min-[48rem]/mcp:w-56 @min-[48rem]/mcp:shrink-0 @min-[48rem]/mcp:border-r":"flex-1"),children:[!m&&l.error&&(0,n.jsx)("div",{className:"p-4",children:(0,n.jsx)(a9,{message:l.error.message})}),(0,n.jsx)(le,{rows:l.rows,selectedName:g,pending:h,onSelect:e=>{g!==e.name&&l.navigate(()=>e.local?l.startManual(e.name,e.local):l.startInherited(e.name,e.config))}})]}),l.editor?(0,n.jsx)(lr,{editor:l.editor,scopeLabel:u,project:null!==l.displayCwd,projectTrusted:l.mcp.projectTrusted,local:l.mcp.local,inherited:l.mcp.inherited,pending:h,saving:l.pending,error:l.error,check:l.check?.name===g?l.check:null,onDraft:l.updateDraft,onJson:l.updateJson,onPreview:l.previewJson,onOverwrite:e=>l.setEditor(t=>t?.kind==="json"?{...t,overwrite:e}:t),onSave:e=>void l.saveEditor(e),onCancel:()=>void l.navigate(()=>l.setEditor(null)),onRemove:e=>void l.remove(e),onDismissCheck:l.dismissCheck},"manual"===l.editor.kind?g??"new":"json"):0===l.rows.length?(0,n.jsx)(li,{pending:h,onAdd:f,onImport:x}):null]}):null]})}var ll=s(267),lo=s(59605),lc=s(55438);let ld=a.Yj().trim().min(1).max(200),lu=a.Yj().trim().min(1).max(100).nullable(),lm=a.Yj().trim().min(1).max(100).nullable(),lp=a.Yj().trim().min(1).max(200),lh=a.Ik({label:a.Yj().trim().min(1).max(64),value:a.Yj().trim().min(1).max(500)}).strict(),lg=a.Yj().trim().min(1).max(300).nullable(),lf=a.k5(["running","completed","failed","stopped","interrupted"]),lx=a.Ik({taskId:ld,taskKind:lu,taskType:lm,title:lp,info:a.YO(lh).max(12),status:lf,activity:lg,startedAt:rM.k,endedAt:rM.k.nullable()}).strict().superRefine((e,t)=>{"running"===e.status&&null!==e.endedAt&&t.addIssue({code:"custom",message:"running task requires endedAt=null",path:["endedAt"]}),"running"!==e.status&&null===e.endedAt&&t.addIssue({code:"custom",message:"terminal task requires endedAt",path:["endedAt"]})}),lb=a.Ik({tasks:a.YO(lx)}).strict().superRefine((e,t)=>{let s=new Set;for(let[n,r]of e.tasks.entries())s.has(r.taskId)&&t.addIssue({code:"custom",message:"taskId values must be unique",path:["tasks",n,"taskId"]}),s.add(r.taskId)}),lv=a.Ik({kind:a.eu("text"),text:a.Yj(),truncated:a.zM()}).strict(),lw=lo.RX.extend({kind:a.eu("conversation"),truncated:a.zM()}).strict(),ly=a.KC([a.ch(),lv,lw]),lk=a.Ik({taskId:ld,canInterrupt:a.zM(),body:ly}).strict(),lj=lc.mv,lN=a.KC([a.Ik({type:a.eu("snapshot"),snapshot:lk}).strict(),a.Ik({type:a.eu("text_append"),text:a.Yj().min(1)}).strict(),a.Ik({type:a.eu("conversation_event"),event:lj}).strict(),a.Ik({type:a.eu("unavailable")}).strict()]);a.Ik({source:ll.R,taskId:ld,entryId:sZ.Rv}).strict().extend({imageIndex:a.ai().int().nonnegative()}).strict();let lI=a.Ik({source:ll.R,taskId:ld.nullable()}).strict(),lS=a.Ik({snapshot:lk.nullable()}).strict(),lC=a.Ik({source:ll.R,taskId:ld}).strict(),lE=a.Ik({}).strict(),lM=a.Ik({source:ll.R,taskId:ld,event:lN}).strict(),lz=Object.freeze({detailWatch:(0,l.Vc)({path:"task-center/detail-watch",inputSchema:lI,outputSchema:lS}),interrupt:(0,l.Vc)({path:"task-center/interrupt",inputSchema:lC,outputSchema:lE}),detailEvent:(0,l._G)({path:"task-center/detail-event",bodySchema:lM})});var lA=s(45811),l$=s(14510),lR=s(12019),lP=s(86075),lD=s(84571),lT=s(67011);let lO=({className:e,...t})=>(0,n.jsx)(lT.z,{className:(0,C.cn)("relative flex-1 overflow-y-hidden",e),initial:"smooth",resize:"smooth",role:"log",...t}),lL=({className:e,...t})=>(0,n.jsx)(lT.z.Content,{className:(0,C.cn)("flex flex-col gap-8 p-4",e),...t});var lF=s(47744),lB=s(30973),lq=s(14203),l_=s(26575),lW=s(11953);function lY({onOpenChange:e,...t}){let s=(0,r.useRef)(null);return(0,n.jsx)(lF.j,{"data-slot":"hover-card",...t,onOpenChange:(t,n)=>{if(e?.(t,n),n.isCanceled)return;if(t){s.current=n.trigger??null;return}let r=s.current;s.current=null,"escape-key"===n.reason&&r instanceof HTMLElement&&r.ownerDocument.activeElement===r&&r.blur()}})}function lV({...e}){return(0,n.jsx)(lB.Z,{"data-slot":"hover-card-trigger",...e})}function lU({className:e,side:t="bottom",sideOffset:s=4,align:r="center",alignOffset:i=4,...a}){return(0,n.jsx)(lq.D,{"data-slot":"hover-card-portal",children:(0,n.jsx)(l_.p,{align:r,alignOffset:i,side:t,sideOffset:s,className:"isolate z-50",children:(0,n.jsx)(lW.p,{"data-slot":"hover-card-content",className:(0,C.cn)("z-50 w-80 max-w-[calc(100vw-2rem)] origin-(--transform-origin) rounded-lg border border-border bg-popover p-3 text-sm text-popover-foreground shadow-md outline-hidden duration-100 motion-reduce:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...a})})})}let lH=({className:e,...t})=>(0,n.jsx)(nC.Sq,{align:"block-end",className:(0,C.cn)("justify-between gap-1",e),...t}),lK=({className:e,...t})=>(0,n.jsx)("div",{className:(0,C.cn)("flex min-w-0 items-center gap-1",e),...t}),lG=({variant:e="ghost",className:t,size:s,tooltip:i,...a})=>{let l=s??(r.Children.count(a.children)>1?"sm":"icon-sm"),o=(0,n.jsx)(nC.Ik,{className:(0,C.cn)(t),size:l,type:"button",variant:e,...a});if(!i)return o;let c="string"==typeof i?i:i.content,d="string"==typeof i?void 0:i.shortcut,u="string"==typeof i?"top":i.side??"top";return(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:o}),(0,n.jsxs)(tU.ZI,{side:u,children:[c,d&&(0,n.jsx)("span",{className:"ml-2 text-muted-foreground",children:d})]})]})},lJ=a.Ik({input:a.g1(a.Yj(),a.Pq())}).strict(),lQ=a.Ik({output:a.Yj()}).strict(),lX="pideskHelp",lZ=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,l0=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function l1(e){return/^[a-zA-Z0-9_./:@=+-]+$/.test(e)?e:JSON.stringify(e)}let l2=a.Ik({name:a.Yj(),scope:a.eu("global").optional(),source:a.Yj(),kind:a.k5(["package","extension"]),version:a.Yj().nullable(),status:a.k5(["ready","available","disabled","failed"]),updateTag:a.Yj().nullish(),availableVersion:a.Yj().nullish(),updateError:a.Yj().nullish(),operation:a.Ik({action:a.k5(["add","update","del","apply"]),phase:a.k5(["queued","checking","applying","waiting","failed"]),message:a.Yj().nullable()}).strict().nullish(),error:a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:eJ.qf}).strict().nullish()}).strict(),l5=a.Ik({plugins:a.YO(l2),restartRequired:a.zM(),loadError:eJ.qf.nullish()}).strict(),l3=l2.extend({detail:a.g1(a.Yj(),a.Pq())}).strict(),l4=a.Ik({version:a.Yj(),environment:a.k5(["development","production"]),mode:a.k5(["basic","normal"]),cwd:a.Yj(),agentDir:a.Yj(),docsDirectory:a.Yj()}).strict(),l6=null,l8=new WeakMap,l7=new WeakMap,l9=new WeakMap;function oe(e){switch(e.fixed.type){case"user":{let t=lo.lJ.safeParse(e.summary);return{summary:{type:"user",...t.success?t.data:{text:"",images:[]},hasDetail:!1},detail:void 0}}case"assistant":{let t="pi-desk/assistant"===e.fixed.viewKey?lo.Er.safeParse(e.summary):null,s=t?.success?t.data:{text:"",errorMessage:null},n="pi-desk/assistant"===e.fixed.viewKey?lo.Rh.safeParse(e.detail):null;return{summary:{type:"assistant",text:s.text,model:"model"in s?s.model:null,errorMessage:s.errorMessage,status:e.fixed.status,usage:e.fixed.usage,hasDetail:e.fixed.hasDetail},detail:n?.success?{type:"assistant",...n.data}:void 0}}case"tool":{let t={name:e.fixed.viewKey,reasoning:null,inputPreview:null,activity:null},s={status:e.fixed.status,usage:e.fixed.usage,hasDetail:e.fixed.hasDetail};switch(e.fixed.viewKey){case"pi-desk/codemode":{let n=lo.UT.safeParse(e.summary),r=n.success?n.data:t,i=lo.ny.safeParse(e.detail);return{summary:{type:"tool",kind:"codemode",...r,...s},detail:i.success?{type:"tool",kind:"codemode",...i.data}:void 0}}case"pi-desk/pidesk":{let n=lJ.safeParse(e.summary),r=n.success?n.data:{input:{}},i=lQ.safeParse(e.detail);return{summary:{type:"tool",kind:"pidesk",...t,...r,...s},detail:i.success?{type:"tool",kind:"pidesk",output:i.data.output}:void 0}}case"pi-desk/bash-tool":{let n=lo.Qi.safeParse(e.summary),r=n.success?n.data:{...t,timing:null},i=lo.Ok.safeParse(e.detail);return{summary:{type:"tool",kind:"bash",...r,...s},detail:i.success?{type:"tool",kind:"bash",output:i.data.output}:void 0}}case"pi-desk/read":{let n=lo.Gx.safeParse(e.summary),r=n.success?n.data:{...t,path:null},i=lo.Xj.safeParse(e.detail);return{summary:{type:"tool",kind:"read",...r,...s},detail:i.success?{type:"tool",kind:"read",content:i.data.content}:void 0}}case"pi-desk/edit":{let n=lo.aV.safeParse(e.summary),r=n.success?n.data:{...t,path:null},i=lo.Rk.safeParse(e.detail);return{summary:{type:"tool",kind:"edit",...r,...s},detail:i.success?{type:"tool",kind:"edit",contentKind:i.data.kind,content:i.data.content}:void 0}}case"pi-desk/write":{let n=lo.bN.safeParse(e.summary),r=n.success?n.data:{...t,path:null},i=lo.O_.safeParse(e.detail);return{summary:{type:"tool",kind:"write",...r,...s},detail:i.success?{type:"tool",kind:"write",contentKind:i.data.kind,content:i.data.content}:void 0}}default:{let n=lo.Px.safeParse(e.summary),r=n.success?n.data:t,i=lo.Ok.safeParse(e.detail);return{summary:{type:"tool",kind:"generic",...r,...s},detail:i.success?{type:"tool",kind:"generic",output:i.data.output}:void 0}}}}case"bash":{let t=lo.ai.safeParse(e.summary),s=t.success?t.data:{command:e.fixed.viewKey},n=lo.bG.safeParse(e.detail);return{summary:{type:"bash",command:s.command,status:e.fixed.status,hasDetail:e.fixed.hasDetail},detail:n.success?{type:"bash",...n.data}:void 0}}case"custom":{if("pi-desk/compaction"===e.fixed.viewKey){let t=lo.sL.safeParse(e.detail);return{summary:{type:"compaction",hasDetail:e.fixed.hasDetail},detail:t.success?{type:"compaction",...t.data}:void 0}}let t=lo.Rt.safeParse(e.summary);return{summary:{type:"custom",text:(t.success?t.data:{text:""}).text,hasDetail:!1},detail:void 0}}}}function ot(e){return e.temporary||"status"in e.summary&&"running"===e.summary.status}function os(e){return"assistant"===e.summary.type&&("error"===e.summary.status||!!e.summary.errorMessage||(e.detail?.type==="assistant"?e.detail.thinking.trim().length>0:e.summary.hasDetail))}function on(e,t,s){if("compaction"===s.summary.type){or(e,t),e.push({identity:s.identity,user:null,processItems:[],finalAssistant:null,compaction:s,running:ot(s),toolCount:0});return}"user"!==s.summary.type?t.body.push(s):(or(e,t),t.user=s)}function or(e,t){if(!t.user&&0===t.body.length)return;let s=t.user?.identity??t.body[0].identity;e.push(function(e,t,s){let n=function(e){for(let t=e.length-1;t>=0;t-=1){let s=e[t];if("custom"!==s.summary.type){if("assistant"!==s.summary.type)return -1;return s.summary.text.trim()||"pi-desk/assistant"!==s.viewKey?t:-1}}return -1}(s),r=n>=0?s[n]:null,i=[];for(let[e,t]of s.entries()){if(e!==n){("assistant"!==t.summary.type||"pi-desk/assistant"!==t.viewKey||t.summary.text.trim().length>0||os(t))&&i.push({message:t,hideAssistantText:!1});continue}os(t)&&i.push({message:t,hideAssistantText:!0})}return{identity:e,user:t,processItems:i,finalAssistant:r,compaction:null,running:s.some(ot),toolCount:s.filter(e=>"tool"===e.summary.type||"bash"===e.summary.type).length}}(s,t.user,t.body)),t.user=null,t.body=[]}function oi(e,t=!1){let s=function(e){let t=l9.get(e);if(t)return t;let s=[],n={user:null,body:[]},r=new Set,i=[],a=(e[0]?.location.index??0)>0;for(let t of e){if(r.has(t.location.entryId))continue;r.add(t.location.entryId);let e=function(e){let t=l8.get(e);if(t)return t;let s=oe(e),n={identity:`position:${e.location.index}`,position:e.location.index,viewKey:e.fixed.viewKey,snapshot:e,...s,temporary:!1,timestampMs:e.fixed.timestampMs,durable:e,tempId:null};return l8.set(e,n),n}(t);"compaction"===e.summary.type?(i=[],a=!1):"assistant"===t.fixed.type&&(i.push(e),"assistant"===e.summary.type&&null!==e.timestampMs&&(e.summary.text.trim()||"pi-desk/assistant"!==e.viewKey)&&(e={...e,usageCalls:i,usageIncomplete:a},i=[],a=!1)),on(s,n,e)}let l={turns:s,user:n.user,body:n.body};return l9.set(e,l),l}(e.messages),n=[...s.turns],r={user:s.user,body:[...s.body]};for(let[t,s]of e.temporaryMessages.entries())on(n,r,function(e,t){let s=l7.get(e);if(s?.position===t)return s.message;let n=oe(e),r={identity:`position:${t}`,position:t,viewKey:e.fixed.viewKey,snapshot:e,...n,temporary:!0,timestampMs:e.fixed.timestampMs,durable:null,tempId:e.location.tempId};return l7.set(e,{position:t,message:r}),r}(s,e.messages.length+t));or(n,r);let i=n.at(-1);return t&&i&&!i.compaction&&(i.running=!0),n}function oa(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}m`}function ol(e){return 0===e?"$0":e<1e-4?"<$0.0001":`$${e.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function oo(e,t=Date.now(),s="en",n="UTC"){let r=new Date(e),i=new Date(t),a=function(e,t){if(l6?.locale===e&&l6.timeZone===t)return l6;let s="en"===e?"en-US":"zh-CN";return l6={locale:e,timeZone:t,compactTime:new Intl.DateTimeFormat(s,{timeZone:t,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),compactDateTime:new Intl.DateTimeFormat(s,{timeZone:t,month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),fullDateTime:new Intl.DateTimeFormat(s,{timeZone:t,timeZoneName:"shortOffset",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}),dateKey:new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"})}}(s,n);return{compact:a.dateKey.format(r)===a.dateKey.format(i)?a.compactTime.format(r):a.compactDateTime.format(r),full:a.fullDateTime.format(r)}}function oc(e,t,s={}){if("1"!==new URLSearchParams(window.location.search).get("chatScrollDebug"))return;let n=om(t);console.info("[Pi Desk][ChatScroll]",e,{time:Math.round(10*performance.now())/10,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight,distanceFromBottom:t.scrollHeight-t.scrollTop-t.clientHeight,tailSpace:n?op(n):0,tailMinHeight:n?.style.minHeight||null,tailAnchor:n?.dataset.chatTailAnchor??null,...s})}function od(e,t,s){let n=Array.from(e.querySelectorAll(`[${t}]`));return void 0===s?n.at(-1)??null:n.find(e=>e.getAttribute(t)===s)??null}function ou(e){let t,s=(t=e.querySelectorAll("[data-chat-turn]")).item(t.length-1);return s?.hasAttribute("data-chat-logical-tail")?s:null}function om(e){return e.querySelector("[data-chat-tail-space]")}function op(e){let t=e.lastElementChild;return t instanceof HTMLElement?Math.max(0,e.getBoundingClientRect().bottom-t.getBoundingClientRect().bottom):0}function oh(e,t,s,n){let r=e.getBoundingClientRect(),i=e.scrollTop,a=Math.max(0,i+t.getBoundingClientRect().top-r.top-n),l=i+s.getBoundingClientRect().top-r.top;return{targetScrollTop:a,minHeight:Math.max(0,a+e.clientHeight-l-function(e){let t=e.parentElement;if(!t)return 0;let s=Number.parseFloat(getComputedStyle(t).paddingBottom);return Number.isFinite(s)?s:0}(s))}}function og(e){for(let t of e.querySelectorAll("[data-chat-tail-space]"))oc("tail:clear:start",e),t.style.removeProperty("min-height"),delete t.dataset.chatTailSpace,delete t.dataset.chatTailAnchor,delete t.dataset.chatTailOffset,oc("tail:clear:end",e)}function of(e){let t=om(e);if(!t)return;if(t!==ou(e))return void og(e);let s=t.dataset.chatTailAnchor,n=Number.parseFloat(t.dataset.chatTailOffset??"");if(!s||!Number.isFinite(n))return;let r=od(e,"data-chat-scroll-anchor",s);if(!r)return void og(e);let{minHeight:i}=oh(e,r,t,n),a=`${Math.ceil(i)}px`;t.style.minHeight!==a&&(oc("tail:refresh:start",e,{nextMinHeight:a}),t.style.minHeight=a,oc("tail:refresh:end",e,{nextMinHeight:a}))}function ox(e,t,s,n){oc("position:start",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n});let r=n?ou(e):null;if(r&&om(e)===r||og(e),!r){e.scrollTop=Math.max(0,e.scrollTop+t.getBoundingClientRect().top-e.getBoundingClientRect().top-s),oc("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n});return}let{targetScrollTop:i,minHeight:a}=oh(e,t,r,s),l=`${Math.ceil(a)}px`;r.style.minHeight!==l&&(r.style.minHeight=l),r.hasAttribute("data-chat-tail-space")||(r.dataset.chatTailSpace="");let o=t.dataset.chatScrollAnchor;r.dataset.chatTailAnchor!==o&&(o?r.dataset.chatTailAnchor=o:delete r.dataset.chatTailAnchor),r.dataset.chatTailOffset!==String(s)&&(r.dataset.chatTailOffset=String(s)),e.scrollTop=i,oc("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n,minHeight:a})}function ob({active:e=!0}){let{scrollRef:t,state:s}=(0,lT.B)();return(0,r.useEffect)(()=>{let n,r=t.current;if(!r||!e)return;let i=null,a=new Set,l=()=>{null===i&&(i=window.requestAnimationFrame(()=>{i=null,of(r)}))},o=new ResizeObserver(l),c=()=>{let e=new Set,t=om(r);if(t)for(let s of t.children)s instanceof HTMLElement&&e.add(s);for(let t of a)e.has(t)||o.unobserve(t);for(let t of e)a.has(t)||o.observe(t);a=e},d=new MutationObserver(()=>{c(),l()}),u=0,m=null,p=null,h=new ResizeObserver(([e])=>{let t=e?.contentRect.height;if(void 0===t)return;let a=t-(n??t);(n=t,a)?(oc("viewport:resize",r,{difference:a,isAtBottom:s.isAtBottom,escapedFromLock:s.escapedFromLock}),u=a,s.resizeDifference=a,null!==i&&(window.cancelAnimationFrame(i),i=null),of(r),s.isAtBottom&&(s.scrollTop=Math.max(0,s.calculatedTargetScrollTop)),oc("viewport:resize:positioned",r,{difference:a}),null!==m&&window.cancelAnimationFrame(m),null!==p&&window.clearTimeout(p),m=window.requestAnimationFrame(()=>{m=null,p=window.setTimeout(()=>{p=null,s.resizeDifference===a&&(s.resizeDifference=0),u=0},1)})):l()});return d.observe(r,{attributes:!0,attributeFilter:["data-chat-tail-space","data-chat-logical-tail"],childList:!0,subtree:!0}),h.observe(r),c(),l(),()=>{null!==i&&window.cancelAnimationFrame(i),null!==m&&window.cancelAnimationFrame(m),null!==p&&window.clearTimeout(p),u&&s.resizeDifference===u&&(s.resizeDifference=0),d.disconnect(),o.disconnect(),h.disconnect()}},[e,t,s]),null}function ov(e){let t=[e.user,...e.processItems.map(e=>e.message),e.finalAssistant,e.compaction].filter(e=>null!==e),s=new Set;return t.filter(e=>!s.has(e.identity)&&(s.add(e.identity),!0))}function ow(e,t,s){let n=0;for(let r=t;r<s;r+=1)e[r]?.user&&(n+=1);return n}function oy(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,ow(e,0,s)),r=s,i=0,a=0,l=0;for(;r>0;){let t=e[r-1],s=ov(t).length,o=l<n;if(i>0&&!o&&(i>=30||a+s>200))break;r-=1,i+=1,a+=s,t.user&&(l+=1)}return r}function ok(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,ow(e,s,e.length)),r=s,i=0,a=0,l=0;for(;r<e.length;){let t=e[r],s=ov(t).length,o=l<n;if(i>0&&!o&&(i>=30||a+s>200))break;r+=1,i+=1,a+=s,t.user&&(l+=1)}return r}function oj(e){return{startIndex:oy(e,e.length),endIndex:e.length}}function oN(e,t){let s,n;if(0===e.length)return{startIndex:0,endIndex:0};if(!t)return oj(e);let r=(n=(s=t.lastIndexOf(":"))>0?t.slice(0,s):t,e.findIndex(e=>ov(e).some(e=>e.identity===n)));if(r<0)return oj(e);let i=Math.min(e.length,r+1+10);return{startIndex:oy(e,i),endIndex:i}}function oI({active:e=!0,turns:t,focusTurnIdentity:s,initialAnchor:i,children:a}){let{scrollRef:l}=(0,lT.B)(),[o,c]=(0,r.useState)(()=>({...oN(t,i),turnCount:t.length,focusTurnIdentity:s}));e||o.focusTurnIdentity===s||c({...o,focusTurnIdentity:s});let d=(0,r.useRef)(null),u=(0,r.useRef)(!1),m=(0,r.useMemo)(()=>{if(0===t.length)return{startIndex:0,endIndex:0};if(e&&o.focusTurnIdentity!==s)return oj(t);if(0===o.turnCount&&0===o.endIndex)return oN(t,i);let n=o.endIndex>=o.turnCount;return{startIndex:Math.min(o.startIndex,t.length),endIndex:n?t.length:Math.max(o.startIndex,Math.min(o.endIndex,t.length))}},[e,s,i,t,o]),p=(0,r.useCallback)(e=>{c({...e,turnCount:t.length,focusTurnIdentity:s})},[s,t.length]),h=(0,r.useCallback)(()=>{let e=l.current,t=e?.querySelector("[data-chat-turn]");e&&t?.dataset.chatTurn&&(d.current={turnIdentity:t.dataset.chatTurn,offset:t.getBoundingClientRect().top-e.getBoundingClientRect().top})},[l]),g=(0,r.useCallback)(()=>{if(m.startIndex<=0||u.current)return;let e=oy(t,m.startIndex);if(e>=m.startIndex)return;h();let s=l.current;s&&oc("window:expand-earlier",s,{previousStartIndex:m.startIndex,nextStartIndex:e}),u.current=!0,p({...m,startIndex:e})},[h,p,m,l,t]),f=(0,r.useCallback)(()=>{if(m.endIndex>=t.length||u.current)return;let e=ok(t,m.endIndex);e<=m.endIndex||(u.current=!0,p({...m,endIndex:e}))},[p,m,t]),x=(0,r.useCallback)(e=>{!Number.isSafeInteger(e)||e<0||e>=t.length||e>=m.startIndex&&e<m.endIndex||(e<m.startIndex?p({...m,startIndex:Math.min(e,oy(t,e+1))}):p({...m,endIndex:Math.max(e+1,ok(t,e))}))},[p,m,t]),b=(0,r.useCallback)(()=>{p(oj(t))},[p,t]);(0,r.useLayoutEffect)(()=>{var e;u.current=!1;let t=d.current;if(!t)return;let s=l.current,n=s?(e=t.turnIdentity,Array.from(s.querySelectorAll("[data-chat-turn]")).find(t=>t.dataset.chatTurn===e)??null):null;if(d.current=null,!s||!n)return;let r=n.getBoundingClientRect().top-s.getBoundingClientRect().top,i=r-t.offset;oc("window:anchor-correction:start",s,{turnIdentity:t.turnIdentity,previousOffset:t.offset,nextOffset:r,correction:i}),s.scrollTop+=i,oc("window:anchor-correction:end",s,{turnIdentity:t.turnIdentity,correction:i})},[m.endIndex,m.startIndex,l]),(0,r.useLayoutEffect)(()=>{let s=l.current;if(!s||!e)return;let n=null,r=()=>{(n=null,s.scrollTop<=24&&m.startIndex>0)?g():s.scrollHeight-s.scrollTop-s.clientHeight<=24&&m.endIndex<t.length&&f()},i=()=>{null===n&&(n=window.requestAnimationFrame(r))},a=e=>{e.deltaY<0&&s.scrollTop<=24?g():e.deltaY>0&&i()},o=()=>{s.scrollTop<=24?g():i()};return s.addEventListener("scroll",i,{passive:!0}),s.addEventListener("wheel",a,{passive:!0}),s.addEventListener("touchmove",o,{passive:!0}),()=>{s.removeEventListener("scroll",i),s.removeEventListener("wheel",a),s.removeEventListener("touchmove",o),null!==n&&window.cancelAnimationFrame(n)}},[e,m,g,f,l,t.length]);let v=(0,r.useMemo)(()=>t.slice(m.startIndex,m.endIndex),[m.endIndex,m.startIndex,t]),w=(0,r.useMemo)(()=>({...m,visibleTurns:v,containsTail:m.endIndex>=t.length,revealTurn:x,resetToTail:b}),[m,b,x,t.length,v]);return(0,n.jsx)(n.Fragment,{children:a(w)})}let oS={canMoveUp:!1,canMoveDown:!1,hasNextMessage:!1};function oC(e,t,s,n){let r=0,i=e.length;for(;r<i;){let a=Math.floor((r+i)/2),l=e[a].getBoundingClientRect().top-t;(n?l>=s:l>s)?i=a:r=a+1}return r}function oE(e){return e.user?`${e.user.identity}:user`:null}function oM(e,t,s){let n,r=Array.from(e.querySelectorAll("[data-chat-user-message]")),i=e.getBoundingClientRect().top+12,a=oC(r,i,-2,!0),l=oC(r,i,2,!1),o=s.find(e=>e>=t.startIndex&&e<t.endIndex),c=s.findLast(e=>e>=t.startIndex&&e<t.endIndex),d=0===a?s.findLast(e=>e<(o??t.startIndex))??null:null,u=l>=r.length?s.find(e=>e>(c??t.endIndex-1))??null:null,m=e.scrollHeight-e.scrollTop-e.clientHeight,p=(n=om(e))?op(n):0,h=t.containsTail&&m<=2;return oc("navigation:inspect",e,{containsTail:t.containsTail,tailSpacerHeight:p,atBottom:h,previousMessage:r[a-1]?.dataset.chatUserMessage??null,nextMessage:r[l]?.dataset.chatUserMessage??null,previousOutsideTurnIndex:d,nextOutsideTurnIndex:u}),{previousMessage:r[a-1]??null,nextMessage:r[l]??null,previousOutsideTurnIndex:d,nextOutsideTurnIndex:u,atBottom:h}}function oz({turns:e,window:t}){let{t:s}=(0,b.Bd)("conversation"),{scrollRef:i,scrollToBottom:a,stopScroll:l}=(0,lT.B)(),o=(0,r.useMemo)(()=>e.flatMap((e,t)=>e.user?[t]:[]),[e]),[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(oS),[p,h]=(0,r.useState)(null),g=(0,r.useRef)(null),f=(0,r.useRef)(!1),x=(0,r.useRef)(!1),v=(0,r.useRef)(null),w=(0,r.useRef)(null),y=(0,r.useRef)(!1),k=(0,r.useRef)(null),j=(0,r.useRef)(!1),N=(0,r.useRef)(!1),S=(0,r.useCallback)(e=>{var s;let n,r=(n=!(s=oM(e,t,o)).atBottom,{canMoveUp:null!==s.previousMessage||null!==s.previousOutsideTurnIndex,canMoveDown:n,hasNextMessage:n&&(null!==s.nextMessage||null!==s.nextOutsideTurnIndex)});y.current&&(r.canMoveDown=!1),m(e=>e.canMoveUp===r.canMoveUp&&e.canMoveDown===r.canMoveDown&&e.hasNextMessage===r.hasNextMessage?e:r)},[t,o]),C=(0,r.useCallback)(e=>{null===w.current&&(w.current=window.requestAnimationFrame(()=>{w.current=null,S(e)}))},[S]),E=(0,r.useCallback)(()=>{null!==v.current&&(window.clearTimeout(v.current),v.current=null)},[]),M=(0,r.useCallback)(()=>{E(),x.current||(v.current=window.setTimeout(()=>{v.current=null,f.current=!1,d(!1),null!==w.current&&(window.cancelAnimationFrame(w.current),w.current=null)},2e3))},[E]),z=(0,r.useCallback)(()=>{null!==g.current&&window.clearTimeout(g.current),g.current=null,h(e=>e?.visible?{...e,visible:!1}:e)},[]),A=(0,r.useCallback)(e=>{null!==g.current&&window.clearTimeout(g.current),h({index:e,visible:!0}),g.current=window.setTimeout(()=>{g.current=null,h(e=>e?.visible?{...e,visible:!1}:e)},2e3)},[]),P=(0,r.useCallback)(()=>{let e=i.current;e&&(f.current||m(oS),f.current=!0,d(!0),C(e),M())},[C,M,i]);(0,r.useLayoutEffect)(()=>{let e=i.current;if(!e)return;let s=k.current;if(s){let n=Array.from(e.querySelectorAll("[data-chat-scroll-anchor]")).find(e=>e.dataset.chatScrollAnchor===s.anchor);n&&(k.current=null,l(),ox(e,n,12,t.containsTail))}j.current&&t.containsTail&&(j.current=!1,og(e),Promise.resolve(a({animation:"instant"})).finally(()=>{y.current=!1,N.current&&f.current&&C(e)}))},[C,i,a,l,t.containsTail,t.endIndex,t.startIndex]),(0,r.useLayoutEffect)(()=>{let e=i.current;if(!e)return;N.current=!0;let t=()=>{z(),P()},s=()=>{f.current&&C(e)},n=t=>{t.target===e&&z()},r=e=>{["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(e.key)&&z()};return e.addEventListener("wheel",t,{passive:!0}),e.addEventListener("touchmove",t,{passive:!0}),e.addEventListener("pointerdown",n,{passive:!0}),e.addEventListener("keydown",r),e.addEventListener("scroll",s,{passive:!0}),()=>{e.removeEventListener("wheel",t),e.removeEventListener("touchmove",t),e.removeEventListener("pointerdown",n),e.removeEventListener("keydown",r),e.removeEventListener("scroll",s),null!==w.current&&(window.cancelAnimationFrame(w.current),w.current=null),N.current=!1}},[z,C,i,P]),(0,r.useLayoutEffect)(()=>()=>{E(),null!==g.current&&window.clearTimeout(g.current),y.current=!1,k.current=null,j.current=!1},[E]),(0,r.useLayoutEffect)(()=>{c&&(u.canMoveUp||u.canMoveDown)||(x.current=!1)},[u.canMoveDown,u.canMoveUp,c]);let D=(0,r.useCallback)((s,n)=>{let r=i.current;if(!r)return;P();let c=oM(r,t,o),d="up"===s?c.previousMessage:c.atBottom?null:c.nextMessage;if(d){let s=o.findIndex(t=>oE(e[t])===d.dataset.chatScrollAnchor);s>=0&&A(s+1),y.current=!1,l(),ox(r,d,12,t.containsTail)}else{let i="up"===s?c.previousOutsideTurnIndex:c.nextOutsideTurnIndex;if(null!==i){let s=oE(e[i]);s&&(A(o.indexOf(i)+1),y.current=!1,k.current={anchor:s},t.revealTurn(i))}else"down"===s&&(o.length>0&&A(o.length),n&&(n.disabled=!0),m(e=>e.canMoveDown?{...e,canMoveDown:!1}:e),c.atBottom||y.current||(oc("navigation:bottom:start",r,{containsTail:t.containsTail}),y.current=!0,og(r),t.containsTail?Promise.resolve(a({animation:"instant"})).finally(()=>{y.current=!1,N.current&&f.current&&C(r)}):(j.current=!0,t.resetToTail())))}C(r)},[C,i,a,P,A,l,e,t,o]),T=c&&(u.canMoveUp||u.canMoveDown),O=s(u.hasNextMessage?"nextUserMessage":"bottom");return(0,n.jsxs)(n.Fragment,{children:[p&&o.length>0?(0,n.jsxs)("div",{role:"status","aria-hidden":!p.visible,"aria-label":`${s("userNavigation")} ${p.index} / ${o.length}`,className:`pointer-events-none absolute top-1/2 left-3 z-10 -translate-y-1/2 rounded-lg border bg-background/95 px-2 py-2 shadow-sm transition-opacity duration-150 motion-reduce:transition-none sm:left-4 ${p.visible?"opacity-100":"opacity-0"}`,children:[(0,n.jsxs)("div",{className:"text-center text-sm font-medium tabular-nums",children:[p.index," / ",o.length]}),(0,n.jsx)("div",{className:"relative mx-auto mt-2 h-28 w-0.5 rounded-full bg-border",children:(0,n.jsx)("span",{className:"absolute left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground",style:{top:`${(p.index-1)/Math.max(1,o.length-1)*100}%`}})})]}):null,T?(0,n.jsxs)(tV,{orientation:"vertical",className:"absolute right-3 bottom-4 z-10 rounded-lg shadow-sm sm:right-4","aria-label":s("userNavigation"),onMouseEnter:()=>{x.current=!0,E()},onMouseLeave:()=>{x.current=!1,f.current&&M()},children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"icon",className:"size-10 bg-background/90 backdrop-blur dark:bg-background/90",disabled:!u.canMoveUp,"aria-label":s("previousUserMessage"),title:s("previousUserShort"),onClick:()=>D("up"),children:(0,n.jsx)($.A,{className:"size-4"})}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"icon",className:"size-10 bg-background/90 backdrop-blur dark:bg-background/90",disabled:!u.canMoveDown,"aria-label":O,title:O,onClick:e=>D("down",e.currentTarget),children:(0,n.jsx)(R.A,{className:"size-4"})})]}):null]})}let oA=(0,r.createContext)({basic:!1});function o$({basic:e,onRecover:t,children:s}){let i=(0,r.useMemo)(()=>({basic:e,recover:t}),[e,t]);return(0,n.jsx)(oA.Provider,{value:i,children:s})}function oR(e){return{location:e.snapshot.location,fixed:e.snapshot.fixed,summary:e.snapshot.summary,...void 0===e.snapshot.detail?{}:{detail:e.snapshot.detail}}}class oP{constructor(e,t){this.listeners=new Set,this.pending=null,this.requestEpoch=0,this.disposed=!1,this.basic=!1,this.message=e,this.snapshot=oR(e),this.loader=t,this.detailLoaded=void 0!==this.snapshot.detail||!this.snapshot.fixed.hasDetail}getSnapshot(){return this.snapshot}subscribe(e){if(this.disposed)throw Error("Message Handle has been disposed");return this.listeners.add(e),()=>{this.listeners.delete(e)}}loadDetail(){if(this.detailLoaded)return Promise.resolve(this.snapshot.detail??null);if(!this.snapshot.fixed.hasDetail)return Promise.resolve(null);if(!("entryId"in this.snapshot.location))return Promise.reject(Error("Temporary Message 不能读取 canonical Detail"));if(this.pending)return this.pending;let e=this.requestEpoch,t=this.loader(this.message).then(t=>(this.disposed||e!==this.requestEpoch||(this.detailLoaded=!0,this.snapshot={...this.snapshot,...null===t?{}:{detail:t}},this.notify()),t)).finally(()=>{this.pending===t&&(this.pending=null)});return this.pending=t,t}replace(e,t,s){if(this.disposed)return;let n=oR(e);if(this.snapshot===n)return;let r=this.basic!==s||void 0!==this.snapshot.detail&&void 0===n.detail||this.snapshot.fixed.viewKey!==n.fixed.viewKey||"entryId"in this.snapshot.location&&"entryId"in n.location&&this.snapshot.location.entryId!==n.location.entryId;this.basic=s,this.message=e,this.loader=t,this.snapshot=n,r?(this.requestEpoch+=1,this.pending=null,this.detailLoaded=void 0!==n.detail||!n.fixed.hasDetail):void 0===n.detail&&n.fixed.hasDetail||(this.detailLoaded=!0),this.notify()}dispose(){this.disposed||(this.disposed=!0,this.listeners.clear(),this.requestEpoch+=1,this.pending=null)}notify(){for(let e of[...this.listeners])e()}}function oD({message:e,pluginName:t,contributionName:s,phase:i,error:a,handle:l,fallback:o,onRetry:c}){let{t:d}=(0,b.Bd)("conversation"),[u,m]=(0,r.useState)(l.getSnapshot().detail),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(null),x=(0,r.useContext)(oA),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),N=a.name,S=a.message,C=a.stack;return(0,r.useEffect)(()=>{console.error("[Pi Desk][MessageView] 消息视图无法展示",{messageId:e.identity,viewKey:e.viewKey,pluginName:t,contributionName:s,phase:i,errorName:N,message:S,stack:C})},[e.identity,e.viewKey,t,s,i,N,S,C]),(0,n.jsxs)("div",{className:"space-y-2","data-message-id":e.identity,children:[o,(0,n.jsx)("div",{role:"alert",className:"rounded-lg border border-destructive/35 bg-muted/30 p-3 text-sm",children:(0,n.jsxs)("div",{className:"flex items-start gap-2",children:[(0,n.jsx)(e_.A,{className:"mt-0.5 size-4 shrink-0 text-destructive"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"font-medium text-destructive",children:d("viewFailed")}),"pi-desk/message-declaration-error"===e.viewKey&&"string"==typeof e.snapshot.summary.text&&e.snapshot.summary.text.length>0?(0,n.jsx)("p",{className:"mt-2 whitespace-pre-wrap break-words text-foreground",children:e.snapshot.summary.text}):null,(0,n.jsxs)(eU,{error:a,children:[(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[t??"Host"," \xb7 ",s??d("reservedView")," \xb7 ",e.viewKey," ","\xb7 ",i]}),(0,n.jsxs)("details",{className:"text-sm",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:d("publicSnapshot")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto rounded-md bg-background p-3 font-mono text-sm whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(l.getSnapshot(),null,2)})]}),!e.temporary&&e.snapshot.fixed.hasDetail&&void 0===u?(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:p,onClick:()=>{h(!0),f(null),l.loadDetail().then(m,e=>{f(e instanceof Error?e.message:d("detailFailed"))}).finally(()=>h(!1))},children:[p?(0,n.jsx)(v.A,{className:"animate-spin"}):null,d("loadDetail")]}):null,g?(0,n.jsx)("p",{className:"text-sm text-destructive [overflow-wrap:anywhere]",children:g}):null,u?(0,n.jsx)("pre",{className:"max-h-48 overflow-auto rounded-md bg-background p-3 font-mono text-sm whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(u,null,2)}):null]}),x.recover?(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",className:"mt-2 mr-2",disabled:w,onClick:()=>{y(!0),x.recover().catch(e=>f(e instanceof Error?e.message:String(e))).finally(()=>y(!1))},children:[w?(0,n.jsx)(v.A,{className:"animate-spin"}):null,d("useBasicPresentation")]}):null,c?(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",className:"mt-2",disabled:k,onClick:()=>{j(!0),f(null),Promise.resolve().then(c).catch(e=>f(e instanceof Error?e.message:String(e))).finally(()=>j(!1))},children:[k?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(es.A,{}),d("retry")]}):null]})]})})]})}function oT({message:e}){let{t}=(0,b.Bd)("conversation");return(0,n.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm","aria-busy":"true",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",role:"status",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),t("viewLoading")]}),(0,n.jsxs)("details",{className:"mt-2",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:t("messageContent")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(e.snapshot.summary,null,2)})]})]})}function oO({message:e,loadDetail:t,defaultView:s}){let{t:i}=(0,b.Bd)("conversation"),a=(0,Q.t4)();(0,Q.So)();let l=(0,r.useContext)(oA),o=(0,r.useRef)(null),c=(0,r.useRef)(null),d=(0,r.useRef)(null),[u,m]=(0,r.useState)({status:"loading"}),[p]=(0,r.useState)(()=>new oP(e,t)),[h,g]=(0,r.useState)(0),f=a.getMessageViewResolution(e.viewKey),x=a.areEntriesInitialized(),v=!f&&a.isRefreshingEntries(),w=f?.status==="winner"?`${e.viewKey}\u0000${f.pluginName}\u0000${f.descriptor.contributionName}\u0000${f.descriptor.priority}`:f?.status==="conflict"?`${e.viewKey}\u0000${f.candidates.map(e=>`${e.pluginName}:${e.descriptor.contributionName}`).join(",")}`:e.viewKey,y=f?.status==="winner"?f.pluginName:null,k=f?.status==="winner"?f.descriptor.contributionName:null,j=y?a.getEntryState(y):null,N=j?.status==="ready"?j.runtime:j?.status,I=e.viewKey.startsWith("pi-desk/")&&"pi-desk/message-declaration-error"!==e.viewKey,S=I&&null===f,C=(0,r.useMemo)(()=>({attempt:h,basic:l.basic,resolutionKey:w,winnerIdentity:N}),[h,l.basic,w,N]),E=(0,r.useMemo)(()=>({kind:"message-view",message:{getSnapshot:()=>p.getSnapshot(),subscribe:e=>d.current!==C?()=>void 0:p.subscribe(()=>{if(d.current===C&&y&&a.getEntryState(y)===j)try{e()}catch(e){m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"update",generation:C})}}),loadDetail:async()=>{if(d.current!==C)throw Error("Message View 已释放");let e=await p.loadDetail();if(d.current!==C)throw Error("Message View 已释放");return e}},reportError(e){d.current===C&&y&&a.getEntryState(y)===j&&m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"report-error",generation:C})}}),[p,C,a,j,y]);if((0,r.useLayoutEffect)(()=>(d.current=C,p.replace(e,t,l.basic),()=>{d.current===C&&(d.current=null)}),[p,t,e,l.basic,C]),(0,r.useEffect)(()=>{let e={};return c.current=e,()=>{c.current===e&&(c.current=null),queueMicrotask(()=>{null===c.current&&p.dispose()})}},[p]),(0,r.useEffect)(()=>{if(l.basic)return void queueMicrotask(()=>m({status:"loading"}));if(!x||S||"pi-desk/message-declaration-error"===e.viewKey||!y||!k||j?.status!=="ready")return;let t=o.current;if(!t)return;let s=new AbortController,n=!0,r=null;queueMicrotask(()=>{n&&m({status:"loading"})});let i=Promise.resolve().then(()=>n?(r=document.createElement("div"),t.append(r),a.mountContribution({pluginName:y,kind:"message-view",contributionName:k,container:r,target:E,signal:s.signal})):null);return i.then(e=>{n&&e&&a.getEntryState(y)===j&&m(e=>"error"===e.status&&e.generation===C?e:{status:"ready",generation:C})},e=>{n&&a.getEntryState(y)===j&&m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"mount",generation:C})}),()=>{n=!1,s.abort(),r?.remove(),i.then(async e=>{await e?.()},()=>void 0)}},[h,S,x,e.viewKey,C,y,k,j,a,E,l.basic]),l.basic)return(0,n.jsx)(n.Fragment,{children:s});if("pi-desk/message-declaration-error"===e.viewKey)return(0,n.jsx)(oD,{message:e,pluginName:"pi-desk",contributionName:"message-declaration-error",phase:"declaration",error:Error(i("declarationFailed")),handle:p});if(!x)return I?(0,n.jsx)(n.Fragment,{children:s}):(0,n.jsx)(oT,{message:e});if(f?.status==="conflict")return(0,n.jsx)(oD,{message:e,pluginName:null,contributionName:null,phase:"priority-conflict",error:Error(i("viewConflict")),handle:p,fallback:I?s:void 0});if(!f)return I?(0,n.jsx)(n.Fragment,{children:s}):v?(0,n.jsx)(oT,{message:e}):(0,n.jsx)(oD,{message:e,pluginName:null,contributionName:null,phase:"missing-view",error:Error(i("viewMissing",{viewKey:e.viewKey})),handle:p,onRetry:async()=>{await a.refreshEntries(),await Promise.all(a.getFailedEntries().map(({pluginName:e})=>a.retryEntry(e)))}});if("error"===u.status&&u.generation===C)return(0,n.jsx)(oD,{message:e,pluginName:f.pluginName,contributionName:f.descriptor.contributionName,phase:u.phase,error:u.error,handle:p,fallback:I?s:void 0,onRetry:()=>{let e=a.getContributionLoadState(f.pluginName,"message-view",f.descriptor.contributionName);(m({status:"loading"}),"failed"!==e.status)?g(e=>e+1):a.retryContribution(f.pluginName,"message-view",f.descriptor.contributionName).then(()=>g(e=>e+1),e=>{m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"load",generation:C})})}});let M="ready"===u.status&&u.generation===C;return(0,n.jsxs)("div",{className:"relative","data-message-id":e.identity,"aria-busy":!M,children:[M?null:I?s:(0,n.jsx)(oT,{message:e}),(0,n.jsx)("div",{ref:o,className:M?void 0:"pointer-events-none invisible absolute inset-x-0 top-0","data-pi-desk-plugin":f.pluginName,"data-pi-desk-kind":"message-view","data-pi-desk-contribution":f.descriptor.contributionName})]})}var oL=s(41934),oF=s(4795),oB=s(33353),oq=s(15948),o_=s(7010),oW=s(64572),oY=s(50153);let oV={src:"/_next/static/media/console.fdac8a18.svg",height:16,width:16,blurWidth:0,blurHeight:0},oU={src:"/_next/static/media/docker.1e10aab8.svg",height:24,width:24,blurWidth:0,blurHeight:0},oH={src:"/_next/static/media/git.f893cb5f.svg",height:32,width:32,blurWidth:0,blurHeight:0},oK={src:"/_next/static/media/html.97f145d3.svg",height:32,width:32,blurWidth:0,blurHeight:0},oG={src:"/_next/static/media/image.69ad851c.svg",height:16,width:16,blurWidth:0,blurHeight:0},oJ={src:"/_next/static/media/javascript.9ef61c53.svg",height:16,width:16,blurWidth:0,blurHeight:0},oQ={src:"/_next/static/media/json.eb8fe488.svg",height:960,width:960,blurWidth:0,blurHeight:0},oX={src:"/_next/static/media/markdown.ee1bbe18.svg",height:32,width:32,blurWidth:0,blurHeight:0},oZ={src:"/_next/static/media/nodejs.2f5d7983.svg",height:32,width:32,blurWidth:0,blurHeight:0},o0={src:"/_next/static/media/typescript.cd97905b.svg",height:16,width:16,blurWidth:0,blurHeight:0},o1={src:"/_next/static/media/yaml.8927dd24.svg",height:24,width:24,blurWidth:0,blurHeight:0},o2=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":oZ,"package-lock.json":oZ,"npm-shrinkwrap.json":oZ,dockerfile:oU,".dockerignore":oU,".gitignore":oH,".gitattributes":oH,".gitmodules":oH})),o5=new Map(Object.entries({ts:o0,mts:o0,cts:o0,tsx:{src:"/_next/static/media/react_ts.3d16336c.svg",height:32,width:32,blurWidth:0,blurHeight:0},js:oJ,mjs:oJ,cjs:oJ,jsx:{src:"/_next/static/media/react.b5a87f7d.svg",height:32,width:32,blurWidth:0,blurHeight:0},json:oQ,jsonc:oQ,jsonl:oQ,yaml:o1,yml:o1,md:oX,mdx:oX,png:oG,jpg:oG,jpeg:oG,gif:oG,webp:oG,avif:oG,bmp:oG,ico:oG,svg:{src:"/_next/static/media/svg.4aa98763.svg",height:32,width:32,blurWidth:0,blurHeight:0},sh:oV,bash:oV,zsh:oV,fish:oV,ps1:oV,bat:oV,cmd:oV,html:oK,htm:oK,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 o3({path:e,className:t}){let s=e.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()??"",r=s.includes(".")?s.slice(s.lastIndexOf(".")+1):"",i=o2.get(s)??(s.startsWith("dockerfile.")?oU:void 0)??o5.get(r);return i?(0,n.jsx)(oY.default,{src:i,alt:"","aria-hidden":"true",width:16,height:16,className:t,unoptimized:!0}):(0,n.jsx)(nI.A,{className:t,"aria-hidden":"true"})}var o4=s(47125),o6=s(9922);let o8=new Map,o7=(0,r.memo)(({children:e,as:t="p",className:s,duration:i=2,spread:a=2})=>{let l,o=((l=o8.get(t))||(l=o6.PY1.create(t),o8.set(t,l)),l),c=(0,r.useMemo)(()=>(e?.length??0)*a,[e,a]);return(0,n.jsx)(o,{animate:{backgroundPosition:"0% center"},className:(0,C.cn)("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",s),initial:{backgroundPosition:"100% center"},style:{"--spread":`${c}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{duration:i,ease:"linear",repeat:1/0},children:e})}),o9=(0,r.createContext)(null),ce=(0,r.memo)(({className:e,isStreaming:t=!1,open:s,defaultOpen:i,onOpenChange:a,duration:l,children:o,...c})=>{let d=i??t,u=!1===i,[m,p]=(0,o4.i)({defaultProp:d,onChange:a,prop:s}),[h,g]=(0,o4.i)({defaultProp:void 0,prop:l}),f=(0,r.useRef)(t),[x,b]=(0,r.useState)(!1),v=(0,r.useRef)(null);(0,r.useEffect)(()=>{t?(f.current=!0,null===v.current&&(v.current=Date.now())):null!==v.current&&(g(Math.ceil((Date.now()-v.current)/1e3)),v.current=null)},[t,g]),(0,r.useEffect)(()=>{!t||m||u||p(!0)},[t,m,p,u]),(0,r.useEffect)(()=>{if(f.current&&!t&&m&&!x){let e=setTimeout(()=>{p(!1),b(!0)},1e3);return()=>clearTimeout(e)}},[t,m,p,x]);let w=(0,r.useCallback)(e=>{p(e)},[p]),y=(0,r.useMemo)(()=>({duration:h,isOpen:m,isStreaming:t,setIsOpen:p}),[h,m,t,p]);return(0,n.jsx)(o9.Provider,{value:y,children:(0,n.jsx)(eV.Nt,{className:(0,C.cn)("not-prose mb-4",e),onOpenChange:w,open:m,...c,children:o})})}),ct=(e,t)=>e||0===t?(0,n.jsx)(o7,{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"]}),cs=(0,r.memo)(({className:e,children:t,getThinkingMessage:s=ct,...i})=>{let{isStreaming:a,isOpen:l,duration:o}=(()=>{let e=(0,r.useContext)(o9);if(!e)throw Error("Reasoning components must be used within Reasoning");return e})();return(0,n.jsx)(eV.R6,{className:(0,C.cn)("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...i,children:t??(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oL.A,{className:"size-4"}),s(a,o),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-4 transition-transform",l?"rotate-180":"rotate-0")})]})})}),cn={cjk:tH.h,code:tK.a,math:tG.D,mermaid:tJ.a},cr=(0,r.memo)(({className:e,children:t,...s})=>(0,n.jsx)(eV.Ke,{className:(0,C.cn)("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...s,children:(0,n.jsx)(tQ.jH,{plugins:cn,children:t})}));ce.displayName="Reasoning",cs.displayName="ReasoningTrigger",cr.displayName="ReasoningContent";var ci=s(52216),ca=s.n(ci);function cl({messages:e,incomplete:t,children:s}){let{t:i}=(0,b.Bd)("conversation"),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)(!1),d=(0,r.useRef)(null),u=(0,r.useRef)(!1);return(0,n.jsxs)(eW.AM,{open:a,onOpenChange:(e,t)=>{if(!e&&"trigger-press"===t.reason&&u.current){u.current=!1,t.cancel();return}e&&"trigger-hover"===t.reason&&o||!e&&"trigger-hover"===t.reason&&(!u.current||d.current?.contains(document.activeElement))?t.cancel():(e?u.current="trigger-hover"===t.reason:"trigger-hover"!==t.reason&&(u.current=!1,c(!0)),l(e))},children:[(0,n.jsx)(eW.Wv,{openOnHover:!o,delay:250,closeDelay:180,onPointerLeave:()=>c(!1),className:"min-w-0 cursor-pointer rounded-sm text-left text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:s}),(0,n.jsxs)(eW.hl,{ref:d,align:"start",side:"top",initialFocus:()=>!u.current,className:(0,C.cn)(ca().panel,"w-[30rem] gap-0 p-2"),children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b px-1 pb-1",children:[(0,n.jsx)(eW.eO,{className:"min-w-0 flex-1 text-xs font-medium text-muted-foreground",children:i(t?"calls.loadedTitle":"calls.title")}),(0,n.jsx)("button",{type:"button","aria-label":i("calls.close"),className:"flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{u.current=!1,c(!0),l(!1)},children:(0,n.jsx)(V.A,{className:"size-3.5"})})]}),a?(0,n.jsx)("div",{className:"min-h-0 overflow-y-auto overscroll-contain",children:(0,n.jsxs)("div",{className:ca().table,children:[(0,n.jsxs)("div",{className:(0,C.cn)(ca().row,"text-muted-foreground"),children:[(0,n.jsx)("span",{children:i("calls.model")}),(0,n.jsx)("span",{children:i("calls.input")}),(0,n.jsx)("span",{children:i("calls.output")}),(0,n.jsx)("span",{children:i("calls.cached")}),(0,n.jsx)("span",{children:i("calls.cost")})]}),e.map(e=>{let t=e.snapshot.fixed;if("assistant"!==t.type)return null;let s="assistant"===e.summary.type?e.summary.model:null,r=t.usage;return(0,n.jsxs)("div",{className:ca().row,children:[(0,n.jsxs)("span",{className:"flex min-w-0 items-center gap-1",children:[(0,n.jsxs)("span",{className:"min-w-0 truncate",title:s?`${s.modelId} \xb7 ${s.provider}`:void 0,children:[s?.modelId||i("calls.unknownModel"),s?.provider?(0,n.jsxs)("span",{className:"text-muted-foreground",children:[" \xb7 ",s.provider]}):null]}),"error"===t.status||"aborted"===t.status?(0,n.jsx)("span",{className:"shrink-0 text-destructive",children:i(`calls.${t.status}`)}):null]}),(0,n.jsx)("span",{children:oa(r.inputTokens)}),(0,n.jsx)("span",{children:oa(r.outputTokens)}),(0,n.jsx)("span",{children:oa(r.cacheReadTokens)}),(0,n.jsx)("span",{children:ol(r.costUsd)})]},e.durable.location.entryId)})]})}):null]})]})}function co({nestedCalls:e}){let{t}=(0,b.Bd)("conversation");return(0,n.jsxs)("section",{className:"border-t px-3 py-3 text-sm",children:[(0,n.jsx)("h4",{className:"mb-2 font-medium",children:t(e.complete?"nestedCalls":"nestedCallsIncomplete")}),(0,n.jsx)("ol",{className:"max-h-[min(24rem,45dvh)] space-y-2 overflow-auto",children:e.calls.map((e,s)=>(0,n.jsxs)("li",{className:"border-b pb-2 last:border-0 last:pb-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,n.jsx)("span",{className:"text-xs tabular-nums text-muted-foreground",children:s+1}),(0,n.jsx)("span",{className:"min-w-0 break-words font-mono font-medium",children:e.name}),(0,n.jsx)("span",{className:"error"===e.status?"text-xs text-destructive":"text-xs text-muted-foreground",children:t(`nestedStatus.${e.status}`)}),void 0===e.durationMs?null:(0,n.jsxs)("span",{className:"ml-auto text-xs tabular-nums text-muted-foreground",children:[e.durationMs," ms"]})]}),e.arguments?(0,n.jsxs)("details",{className:"mt-1",children:[(0,n.jsx)("summary",{className:"min-h-7 cursor-pointer text-xs text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring",children:t("nestedArguments")}),(0,n.jsx)("pre",{className:"max-h-48 overflow-auto whitespace-pre-wrap break-words py-2 font-mono text-sm",children:JSON.stringify(e.arguments,null,2)})]}):null,void 0===e.argumentsBytes?null:(0,n.jsx)("p",{className:"mt-1 text-xs tabular-nums text-muted-foreground",children:t("nestedArgumentsBytes",{count:e.argumentsBytes})}),e.error?(0,n.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-destructive",children:e.error}):null]},s))})]})}function cc({plugin:e}){let{t}=(0,b.Bd)("conversation"),{locale:s}=(0,eQ.i)();return(0,n.jsxs)("div",{className:"min-w-0 space-y-1 py-2 first:pt-0 last:pb-0",role:"listitem",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.name}),(0,n.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:e.version??t("pidesk.unknownVersion")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`pidesk.status.${e.status}`)})]}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[t(`pidesk.kind.${e.kind}`)," \xb7 ",(0,n.jsx)("span",{className:"font-mono",children:e.source})]}),e.updateTag||e.availableVersion?(0,n.jsxs)("p",{className:"flex flex-wrap gap-x-3 text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e.updateTag?(0,n.jsx)("span",{children:t("pidesk.updateChannel",{tag:e.updateTag})}):null,e.availableVersion?(0,n.jsx)("span",{children:t("pidesk.targetVersion",{version:e.availableVersion})}):null]}):null,e.updateError?(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:e.updateError}):null,e.operation?(0,n.jsxs)("p",{className:"[overflow-wrap:anywhere]",children:[t(`pidesk.action.${e.operation.action}`)," \xb7 ",t(`pidesk.phase.${e.operation.phase}`),e.operation.message?` \xb7 ${e.operation.message}`:""]}):null,e.error?(0,n.jsxs)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:[t(`pidesk.errorPhase.${e.error.phase}`)," \xb7 ",(0,eJ.fD)(e.error.message,s)]}):null]})}function cd({result:e}){let{t}=(0,b.Bd)("conversation"),{locale:s}=(0,eQ.i)();return"info"===e.kind?(0,n.jsx)("dl",{className:"grid grid-cols-[max-content_minmax(0,1fr)] gap-x-4 gap-y-2",children:Object.entries(e.data).map(([e,s])=>(0,n.jsxs)("div",{className:"contents",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:t(`pidesk.info.${e}`)}),(0,n.jsx)("dd",{className:"min-w-0 [overflow-wrap:anywhere]",children:"environment"===e?t(`pidesk.environment.${s}`):"mode"===e?t(`pidesk.mode.${s}`):(0,n.jsx)("span",{className:"font-mono",children:s})})]},e))}):"plugin"===e.kind?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{role:"list",children:(0,n.jsx)(cc,{plugin:e.data})}),(0,n.jsx)("p",{className:"mt-3 mb-2 font-medium",children:t("pidesk.pluginDetail")}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono leading-relaxed",children:JSON.stringify(e.data.detail,null,2)})]}):(0,n.jsxs)(n.Fragment,{children:[e.data.restartRequired?(0,n.jsx)("p",{className:"mb-2",children:t("pidesk.restartRequired")}):null,e.data.loadError?(0,n.jsx)("p",{className:"mb-2 text-destructive [overflow-wrap:anywhere]",children:(0,eJ.fD)(e.data.loadError,s)}):null,e.data.plugins.length>0?(0,n.jsx)("div",{className:"divide-y divide-border",role:"list",children:e.data.plugins.map((e,t)=>(0,n.jsx)(cc,{plugin:e},`${e.source}:${t}`))}):(0,n.jsx)("p",{className:"text-muted-foreground",children:t("pidesk.noPlugins")})]})}function cu({identity:e,command:t,output:s,expandable:r,open:i,loading:a,error:l,onOpenChange:o,commandAction:c,outputAction:d}){let{t:u}=(0,b.Bd)("conversation"),m=t.label?[u(t.label),t.name,t.version].filter(Boolean).join(" \xb7 "):t.command,p=null===s?null:function(e,t){let s;if(!["pideskListPlugins","pideskShowPlugin","pideskInfo"].includes(e??""))return null;try{s=JSON.parse(t)}catch{return null}switch(e){case"pideskListPlugins":{let e=l5.safeParse(s);return e.success?{kind:"plugins",data:e.data}:null}case"pideskShowPlugin":{let e=l3.safeParse(s);return e.success?{kind:"plugin",data:e.data}:null}case"pideskInfo":{let e=l4.safeParse(s);return e.success?{kind:"info",data:e.data}:null}default:return null}}(t.label,s);return(0,n.jsxs)(eV.Nt,{open:r&&i,onOpenChange:o,className:"w-full min-w-0 overflow-hidden rounded-lg border border-border bg-card text-sm leading-relaxed","data-message-id":e,"data-chat-scroll-anchor":`${e}:tool`,children:[(0,n.jsxs)(eV.R6,{disabled:!r,"aria-label":r?u(i?"collapseTool":"expandTool",{name:m}):m,className:(0,C.cn)("flex min-h-9 w-full min-w-0 items-center gap-2 px-3 py-1.5 text-left",r&&"cursor-pointer hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"),children:[(0,n.jsx)(nX.A,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,n.jsx)("span",{className:(0,C.cn)("min-w-0 flex-1 truncate font-medium",!t.label&&"font-mono"),title:m,children:m}),r?(0,n.jsx)(eY.A,{className:(0,C.cn)("size-4 shrink-0 text-muted-foreground transition-transform",i&&"rotate-180"),"aria-hidden":"true"}):null]}),(0,n.jsx)(eV.Ke,{className:"h-[var(--collapsible-panel-height)] overflow-hidden transition-[height,opacity] duration-200 ease-out data-starting-style:h-0 data-starting-style:opacity-0 data-ending-style:h-0 data-ending-style:opacity-0 motion-reduce:transition-none",children:(0,n.jsxs)("div",{className:"border-t",children:[(0,n.jsxs)("section",{className:"border-b px-3 py-2","aria-label":u("pidesk.command"),children:[(0,n.jsxs)("div",{className:"mb-1 flex min-h-7 items-center justify-between gap-2",children:[(0,n.jsx)("h4",{className:"font-medium text-muted-foreground",children:u("pidesk.command")}),c]}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono leading-relaxed",children:t.command})]}),(0,n.jsxs)("section",{"aria-label":u("pidesk.output"),children:[(0,n.jsxs)("div",{className:"flex min-h-9 items-center justify-between gap-2 px-3 pt-2",children:[(0,n.jsx)("h4",{className:"font-medium text-muted-foreground",children:u("pidesk.output")}),d]}),(0,n.jsx)("div",{className:"max-h-[min(24rem,50dvh)] overflow-auto px-3 pt-1 pb-3",role:"region","aria-label":u("pidesk.output"),tabIndex:0,children:a?(0,n.jsx)("p",{className:"text-muted-foreground",children:u("loadingResult")}):l?(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:l}):s?p?(0,n.jsx)(cd,{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 cm=s(43769),cp=s.n(cm);let ch="max-h-[min(20rem,45dvh)] overflow-auto [scrollbar-gutter:stable]",cg=(0,r.createContext)(()=>void 0),cf=(0,r.createContext)(null),cx=(0,r.createContext)(null),cb="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 cv({children:e}){let{isAtBottom:t,stopScroll:s}=(0,lT.B)(),i=(0,r.useRef)(t),a=(0,r.useRef)(s);(0,r.useLayoutEffect)(()=>{i.current=t,a.current=s},[t,s]);let l=(0,r.useCallback)(()=>{i.current&&a.current()},[]);return(0,n.jsx)(cg.Provider,{value:l,children:e})}function cw(e,t){let{t:s}=(0,b.Bd)("conversation"),[n,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(null),o=(0,r.useCallback)(async()=>{if(!e.temporary&&e.durable&&e.snapshot.fixed.hasDetail&&void 0===e.detail&&!n){i(!0),l(null);try{await t(e)}catch(e){l(e instanceof Error?e.message:s("detailFailed"))}finally{i(!1)}}},[n,e,t,s]);return{loading:n,error:a,load:o}}function cy(e,t){let[s,n]=(0,r.useState)(!1),i=(0,r.useContext)(cg),{loading:a,error:l,load:o}=cw(e,t),c=!e.temporary&&(e.summary.hasDetail||"tool"===e.summary.type&&!!e.summary.images?.length);return{open:s,expandable:c,loading:a,error:l,handleOpenChange:e=>{c&&(e&&(i(),o()),n(e))}}}function ck({timestampMs:e}){let{locale:t,timeZone:s}=(0,eQ.i)(),r=oo(e,void 0,t,s);return(0,n.jsx)("time",{dateTime:new Date(e).toISOString(),title:r.full,className:"shrink-0",children:r.compact})}function cj({text:e,copyLabel:t,alwaysVisible:s=!1}){let{t:i}=(0,b.Bd)("conversation"),a=(0,X.G)(),[l,o]=(0,r.useState)(!1),c=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{null!==c.current&&window.clearTimeout(c.current)},[]);let d=(0,r.useCallback)(async()=>{let t=!1;try{t=await (0,e9.x)(e)}catch{t=!1}t?(o(!0),null!==c.current&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{c.current=null,o(!1)},1500)):a.error(i("messageCopyFailed"))},[e,a,i]);if(!e.trim())return null;let u=l?i("copied"):t??i("copyMessage");return(0,n.jsx)(t0,{tooltip:u,label:u,size:"icon-sm",className:(0,C.cn)(!s&&cp().messageCopyAction,"text-muted-foreground"),onClick:()=>void d(),children:l?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})})}function cN({usage:e,compactOnly:t=!1}){let{t:s}=(0,b.Bd)("conversation"),r=oa(e.inputTokens),i=oa(e.outputTokens),a=oa(e.cacheReadTokens),l=ol(e.costUsd),o=s("usage",{input:r,output:i,cached:a,cost:l}),c=`${r}/${i}/${a}/${l}`;return t?(0,n.jsx)("span",{className:"shrink-0 font-mono text-xs tabular-nums text-muted-foreground",title:o,"aria-label":o,children:c}):(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("span",{className:cp().usageLabeled,children:o}),(0,n.jsx)("span",{className:cp().usageCompact,children:c})]})}function cI({message:e}){if("assistant"!==e.summary.type||null===e.timestampMs)return null;let t="running"!==e.summary.status?e.summary.text:null;return(0,n.jsxs)(t5,{className:(0,C.cn)(cp().usageToolbar,"mt-1 flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground"),children:[e.usageCalls?.length?(0,n.jsx)(cl,{messages:e.usageCalls,incomplete:e.usageIncomplete??!1,children:(0,n.jsx)(cN,{usage:e.summary.usage})},e.durable.location.entryId):(0,n.jsx)(cN,{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)(cj,{text:t}),null===e.timestampMs?null:(0,n.jsx)(ck,{timestampMs:e.timestampMs})]})]})}function cS({message:e,onAcquireImage:t}){let{t:s}=(0,b.Bd)("conversation"),i="user"===e.summary.type||"tool"===e.summary.type?e.summary.images??[]:[],a=i.length,l=(0,r.useRef)(e);(0,r.useLayoutEffect)(()=>{l.current=e},[e]);let[o,c]=(0,r.useState)(()=>Array.from({length:a},()=>({status:"loading"}))),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(0);return(0,r.useLayoutEffect)(()=>{let e=!0,s=Array.from({length:a},()=>null);for(let n=0;n<a;n+=1){let r=t=>{e?(s[n]=t.release,c(e=>{let s=[...e];return s[n]={status:"ready",url:t.url},s})):t.release()},i=()=>{e&&c(e=>{let t=[...e];return t[n]={status:"error"},t})};try{let e=t(l.current,n);"then"in e?e.then(r).catch(i):r(e)}catch{i()}}return()=>{e=!1,s.forEach(e=>e?.())}},[a,e.identity,e.tempId,e.durable?.location.entryId,t,m]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"mb-2 grid grid-cols-2 gap-2 sm:grid-cols-3",children:i.map((e,t)=>{let r=o[t];return r?.status==="error"?(0,n.jsxs)("button",{type:"button",className:"flex aspect-square min-h-20 cursor-pointer flex-col items-center justify-center gap-2 rounded-md border bg-muted px-2 text-center text-xs text-muted-foreground hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{u(null),c(e=>e.map(e=>"error"===e.status?{status:"loading"}:e)),p(e=>e+1)},children:[(0,n.jsx)("span",{children:s("imageUnavailable")}),(0,n.jsx)("span",{className:"text-sm font-medium text-foreground",children:s("retry",{ns:"common"})})]},`${t}:${e.width}:${e.height}`):r?.status!=="ready"?(0,n.jsx)("div",{className:"grid aspect-square min-h-20 place-items-center rounded-md border bg-muted px-2 text-center text-xs text-muted-foreground",children:s("imageLoading")},`${t}:${e.width}:${e.height}`):(0,n.jsx)("button",{type:"button",className:"group block aspect-square w-full cursor-zoom-in overflow-hidden rounded-md border bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{let e,n;return e=[],n=-1,void(o.forEach((r,a)=>{if("ready"!==r.status)return;a===t&&(n=e.length);let l=i[a];e.push({src:r.url,alt:s("chatImage",{count:a+1}),width:l.width,height:l.height})}),n>=0&&u({slides:e,index:n}))},"aria-label":s("previewImageNumber",{count:t+1}),children:(0,n.jsx)("img",{src:r.url,alt:s("chatImage",{count:t+1}),className:"aspect-square size-full object-cover transition-transform duration-200 group-hover:scale-[1.02] motion-reduce:transition-none"})},`${t}:${e.width}:${e.height}`)})}),d?(0,n.jsx)(ny.k,{mode:"modal",open:!0,slides:d.slides,index:d.index,ariaLabel:s("chatImagePreview"),onClose:()=>u(null),onIndexChange:e=>u(t=>t?{...t,index:e}:t)}):null]})}function cC({text:e}){let{t}=(0,b.Bd)("conversation"),s=(0,r.useRef)(null),[i,a]=(0,r.useState)(!1),[l,o]=(0,r.useState)(null),c=(0,r.useContext)(cg);(0,r.useLayoutEffect)(()=>{let e=s.current;if(!e)return;let t=new ResizeObserver(([t])=>{if(!t||0===t.contentRect.height)return;let s=Number.parseFloat(getComputedStyle(e).lineHeight);o(t.contentRect.height>6*s+1)});return t.observe(e),()=>t.disconnect()},[]);let d=(0,r.useCallback)(()=>{i||c(),a(e=>!e)},[c,i]);return(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("div",{className:(0,C.cn)("relative",!i&&!1!==l&&cp().userTextCollapsed),children:[(0,n.jsx)("p",{ref:s,className:"whitespace-pre-wrap break-words",children:e}),l&&!i?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-secondary to-transparent","aria-hidden":"true"}):null]}),l?(0,n.jsxs)("button",{type:"button","aria-expanded":i,onClick:d,className:"-mb-1 ml-auto mt-1 flex min-h-7 cursor-pointer items-center gap-1 rounded-md px-1 text-xs font-medium text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t(i?"collapse":"expand"),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-3.5 transition-transform",i&&"rotate-180"),"aria-hidden":"true"})]}):null]})}function cE({message:e,onAcquireImage:t}){if("user"!==e.summary.type)throw Error("UserMessage requires a user summary");return(0,n.jsxs)(tX,{from:"user","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:user`,"data-chat-user-message":"",className:(0,C.cn)(cp().copyableMessage,"max-w-[92%] sm:max-w-[84%]"),children:[(0,n.jsxs)(tZ,{className:(0,C.cn)(cp().userText,"group-[.is-user]:px-3 group-[.is-user]:py-2"),children:[e.summary.images.length>0?(0,n.jsx)(cS,{message:e,onAcquireImage:t},`${e.tempId}:${e.durable?.location.entryId??"temporary"}`):null,e.summary.text?(0,n.jsx)(cC,{text:e.summary.text}):null]}),null===e.timestampMs?null:(0,n.jsxs)(t5,{className:"mt-0 justify-end gap-1 text-xs text-muted-foreground",children:[(0,n.jsx)(cj,{text:e.summary.text}),(0,n.jsx)(ck,{timestampMs:e.timestampMs})]})]})}function cM({message:e,text:t}){let s=e.temporary&&"assistant"===e.summary.type&&"running"===e.summary.status;return(0,n.jsxs)(tX,{from:"assistant","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:text`,className:(0,C.cn)(cp().copyableMessage,"max-w-full gap-1"),children:[(0,n.jsx)(tZ,{className:"w-full",children:(0,n.jsx)(rn,{isAnimating:s,mode:s?"streaming":"static",children:t})}),(0,n.jsx)(cI,{message:e})]})}function cz(){let{t:e}=(0,b.Bd)("conversation");return(0,n.jsxs)("div",{role:"status",className:(0,C.cn)(cp().detailText,"flex min-h-9 w-full items-center gap-2 py-1 text-muted-foreground"),children:[(0,n.jsx)(oL.A,{className:"size-4","aria-hidden":"true"}),(0,n.jsx)(o7,{as:"span",duration:1,children:e("thinking")})]})}function cA({content:e,streaming:t}){let{t:s}=(0,b.Bd)("conversation"),{scrollRef:r,contentRef:i}=(0,oW.q)({initial:!!t&&"instant",resize:"instant"}),a=e.length>5e3,l=e.slice(-5e3);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{ref:r,className:"max-h-56 overflow-y-auto pb-2 pr-2 [scrollbar-gutter:stable] sm:max-h-72",children:(0,n.jsx)("div",{ref:i,children:(0,n.jsx)(rn,{isAnimating:t,mode:t?"streaming":"static",children:l},a?e.length:void 0)})}),a?(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 pt-1",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:s("thinkingTruncated",{count:5e3})}),(0,n.jsx)(cj,{text:e,copyLabel:s("copyThinking"),alwaysVisible:!0})]}):null]})}function c$({message:e,detailLoad:t}){let{t:s}=(0,b.Bd)("conversation");if("assistant"!==e.summary.type)return null;let{loading:r,error:i,load:a}=t,l=void 0!==e.detail,o=e.detail?.type==="assistant"?e.detail:null,c=o?.thinking??"",d=c.trim().length>0,u=d&&e.temporary&&"running"===e.summary.status&&0===e.summary.text.trim().length;if(!(d||!l&&e.summary.hasDetail))return null;let m=c||(r?s("thinkingLoading"):i??s("thinkingUnavailable"));return(0,n.jsxs)(ce,{className:"mb-0 w-full",isStreaming:u,onOpenChange:e=>{e&&a()},children:[(0,n.jsx)(cs,{className:(0,C.cn)(cp().detailText,"min-h-9 justify-start py-1"),getThinkingMessage:e=>e?(0,n.jsx)(o7,{as:"span",duration:1,children:s("thinking")}):(0,n.jsx)("span",{children:s("thinkingProcess")})}),(0,n.jsx)(eV.Ke,{className:(0,C.cn)(cb,"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)(cA,{content:m,streaming:u})})})})]})}function cR({message:e}){let{t}=(0,b.Bd)("conversation"),{locale:s}=(0,eQ.i)();if("assistant"!==e.summary.type)return null;let r=function(e,t){let s=e?.trim();if(!s)return null;switch(s.toLowerCase()){case"terminated":return n6.W[t].streamInterrupted;case"request timed out":case"request timed out.":return n6.W[t].requestTimedOut;default:return e}}(e.summary.errorMessage,s)??("error"===e.summary.status?t("modelFailed"):null);return r?(0,n.jsx)("pre",{className:(0,C.cn)(cp().toolOutput,"whitespace-pre-wrap break-words rounded-lg border border-destructive/40 bg-muted p-3 font-sans text-destructive"),children:r}):null}function cP({item:e,onLoadDetail:t}){let{message:s,hideAssistantText:r}=e,i=cw(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)(c$,{message:s,detailLoad:i}),r||!s.summary.text.trim()?null:(0,n.jsx)(cM,{message:s,text:s.summary.text}),(0,n.jsx)(cR,{message:s})]})}function cD({name:e,filePath:t,className:s}){let r=e.toLowerCase().split(".").at(-1)??e.toLowerCase(),i={className:s};switch(r){case"read":return t?(0,n.jsx)(o3,{path:t,...i}):(0,n.jsx)(nI.A,{...i});case"write":return(0,n.jsx)(oF.A,{...i});case"edit":return(0,n.jsx)(oB.A,{...i});case"bash":return(0,n.jsx)(w.A,{...i});case"grep":case"find":return(0,n.jsx)(eh.A,{...i});case"ls":return(0,n.jsx)(eP.A,{...i});case"agent":case"agent_resume":return(0,n.jsx)(eD.A,{...i});default:return(0,n.jsx)(eT.A,{...i})}}function cT(e){let t=e.replaceAll("\\","/");return"/"===t||/^[A-Za-z]:\/$/.test(t)?t:t.replace(/\/+$/,"")}function cO({status:e,timing:t}){let s=t&&"startedAtMs"in t?t.startedAtMs:null,i=t&&"durationMs"in t?t.durationMs:null,[a,l]=(0,r.useState)(()=>Date.now());(0,r.useEffect)(()=>{if("running"!==e||null===s)return;let t=window.setInterval(()=>l(Date.now()),1e3);return()=>window.clearInterval(t)},[s,e]);let o=i??(null===s?null:Math.max(0,a-s));return null===o?null:(0,n.jsx)(n.Fragment,{children:function(e){let t=Math.max(0,Math.floor(e/1e3)),s=t%60,n=Math.floor(t/60);if(0===n)return`${s}s`;let r=n%60,i=Math.floor(n/60);return 0===i?`${r}m ${s}s`:`${i}h ${r}m ${s}s`}(o)})}function cL({message:e,onLoadDetail:t,previewPath:s,onPreviewFile:i,renderDetail:a}){let{t:l}=(0,b.Bd)("conversation");if("tool"!==e.summary.type&&"bash"!==e.summary.type)throw Error("ToolCardShell requires a tool or bash summary");let o=(0,r.useContext)(cf),c=(0,r.useContext)(cx),d=!e.temporary&&"tool"===e.summary.type&&!!e.summary.images?.length,{open:u,expandable:m,loading:p,error:h,handleOpenChange:g}=cy(e,t),{name:f,reasoning:x,inputPreview:v,activity:w,usage:y}="tool"===e.summary.type?{name:e.summary.name,reasoning:e.summary.reasoning,inputPreview:e.summary.inputPreview,activity:e.summary.activity,usage:e.summary.usage}:{name:"bash",reasoning:null,inputPreview:e.summary.command,activity:null,usage:null},k="tool"===e.summary.type&&"bash"===e.summary.kind?e.summary:null,j="error"===e.summary.status,N=!e.temporary&&null!==s&&void 0!==i,I=s?function(e,t){let{compactPath:s,fullPath:n}=function(e,t){let s=cT(e);if(!t)return{compactPath:s,fullPath:s};let n=cT(t);if(!(s.startsWith("/")||/^[A-Za-z]:\//.test(s))){let e=s.replace(/^(?:\.\/)+/,""),t=n.endsWith("/")?n:`${n}/`;return{compactPath:e,fullPath:`${t}${e}`}}let r=n.endsWith("/")?n:`${n}/`,i=/^[A-Za-z]:\//.test(s)&&/^[A-Za-z]:\//.test(n),a=i?s.toLowerCase():s,l=i?r.toLowerCase():r;return a.startsWith(l)?{compactPath:s.slice(r.length),fullPath:s}:{compactPath:s,fullPath:s}}(e,t),r=s.match(/^[A-Za-z]:\//)?.[0]??null??(s.startsWith("/")?"/":""),i=s.slice(r.length).split("/").filter(Boolean),a=i.pop()??s,l=a.lastIndexOf("."),o=i.length>2?`…/${i.slice(-2).join("/")}`:`${r}${i.join("/")}`;return{fileStem:l>0?a.slice(0,l):a,fileExtension:l>0?a.slice(l):"",directory:o||null,fullPath:n}}(s,o):null;return(0,n.jsxs)(eV.Nt,{open:m&&u,onOpenChange:g,className:(0,C.cn)(cp().detailText,"w-full overflow-hidden rounded-lg border bg-muted/45 dark:bg-card",j?"border-destructive":"border-border"),"data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:tool`,children:[(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsxs)(eV.R6,{disabled:!m,className:(0,C.cn)("relative grid min-h-14 w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-2 px-3 py-1.5 text-left",m&&"cursor-pointer hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"),"aria-label":l(m?u?"collapseTool":"expandTool":"tool",{name:f}),children:[(0,n.jsx)(cD,{name:f,filePath:s,className:"col-start-1 row-start-1 size-4 text-muted-foreground"}),(0,n.jsxs)("span",{className:"col-start-2 row-start-1 flex min-h-7 min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"shrink-0 font-mono font-medium",children:f}),x?(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-foreground",children:x}):null,y?(0,n.jsx)(cN,{usage:y,compactOnly:!0}):null]}),(0,n.jsxs)("span",{className:"col-start-3 row-start-1 flex min-h-7 items-center justify-end gap-2",children:[N?(0,n.jsx)("span",{className:"size-7","aria-hidden":"true"}):null,m?(0,n.jsx)("span",{className:"flex size-7 items-center justify-center","aria-hidden":"true",children:(0,n.jsx)(eY.A,{"data-tool-disclosure":"",className:(0,C.cn)("size-4 text-muted-foreground transition-transform",u&&"rotate-180")})}):null]}),I?(0,n.jsxs)("span",{className:(0,C.cn)(cp().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)(cp().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)(cO,{status:k.status,timing:k.timing})}):w?(0,n.jsx)("span",{className:"col-start-3 row-start-2 max-w-36 truncate text-right font-mono text-xs tabular-nums text-muted-foreground",title:w,children:w}):null]}),N?(0,n.jsx)("button",{type:"button",title:l("previewFile"),"aria-label":l("previewFilePath",{path:s}),onClick:()=>i(s),className:(0,C.cn)("absolute top-1.5 flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",m?"right-12":"right-3"),children:(0,n.jsx)(oq.A,{className:"size-4","aria-hidden":"true"})}):null]}),(0,n.jsx)(eV.Ke,{className:cb,children:(0,n.jsxs)("div",{className:"border-t",children:[I?(0,n.jsx)("p",{className:"border-b px-3 py-2 font-mono text-xs text-muted-foreground [overflow-wrap:anywhere]",children:I.fullPath}):null,u&&d&&c?(0,n.jsx)("div",{className:"px-3 pt-3",children:(0,n.jsx)(cS,{message:e,onAcquireImage:c})}):null,a({loading:p,error:h})]})})]})}function cF({children:e,destructive:t=!1}){return(0,n.jsx)("p",{className:(0,C.cn)(cp().detailText,"px-3 py-3",t?"text-destructive":"text-muted-foreground"),children:e})}function cB({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="bash"||e.detail?.type==="tool"&&("generic"===e.detail.kind||"bash"===e.detail.kind||"codemode"===e.detail.kind)?e.detail:null,a=i?.output??"";return t?(0,n.jsx)(cF,{children:r("loadingResult")}):s?(0,n.jsx)(cF,{destructive:!0,children:s}):a?(0,n.jsx)("pre",{role:"region","aria-label":r("toolOutput"),tabIndex:0,className:(0,C.cn)(ch,cp().toolOutput,"whitespace-pre-wrap break-words px-3 py-3 font-mono"),children:a}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(cF,{children:r("emptyResult")})}function cq({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="tool"&&"read"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(cF,{children:r("loadingRead")}):s?(0,n.jsx)(cF,{destructive:!0,children:s}):i?i.content?(0,n.jsx)("pre",{role:"region","aria-label":r("readContent"),tabIndex:0,className:(0,C.cn)(ch,cp().toolOutput,cp().toolCode,"px-3 py-3 font-mono"),children:i.content}):(0,n.jsx)(cF,{children:r("readEmpty")}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(cF,{children:r("readUnavailable")})}function c_({content:e}){let{t}=(0,b.Bd)("conversation");return(0,n.jsx)("div",{role:"region","aria-label":t("editDiff"),tabIndex:0,className:(0,C.cn)(ch,cp().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)(cp().toolCode,cp().toolCodeLine,"block px-3",s),children:e||" "},t)})})}function cW({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="tool"&&"edit"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(cF,{children:r("loadingDiff")}):s?(0,n.jsx)(cF,{destructive:!0,children:s}):i?"diff"===i.contentKind?(0,n.jsx)(c_,{content:i.content}):(0,n.jsx)("pre",{role:"region","aria-label":r("editResult"),tabIndex:0,className:(0,C.cn)(ch,cp().toolOutput,"whitespace-pre-wrap break-words px-3 py-3 font-mono","tool"===e.summary.type&&"error"===e.summary.status&&"text-destructive"),children:i.content}):(0,n.jsx)(cF,{children:r("diffUnavailable")})}function cY({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="tool"&&"write"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(cF,{children:r("loadingWrite")}):s?(0,n.jsx)(cF,{destructive:!0,children:s}):i?"content"!==i.contentKind||i.content?(0,n.jsx)("pre",{role:"region","aria-label":r("content"===i.contentKind?"writeContent":"writeResult"),tabIndex:0,className:(0,C.cn)(ch,cp().toolOutput,"px-3 py-3 font-mono","content"===i.contentKind?cp().toolCode:"whitespace-pre-wrap break-words","output"===i.contentKind&&"tool"===e.summary.type&&"error"===e.summary.status&&"text-destructive"),children:i.content}):(0,n.jsx)(cF,{children:r("writeEmpty")}):(0,n.jsx)(cF,{children:r("writeUnavailable")})}function cV({message:e,onLoadDetail:t}){let{t:s}=(0,b.Bd)("conversation"),{open:r,expandable:i,loading:a,error:l,handleOpenChange:o}=cy(e,t);if("tool"!==e.summary.type||"pidesk"!==e.summary.kind)throw Error("PiDeskToolView requires a pidesk summary");let c=function(e){let t=e.args,s={command:0===Object.keys(e).length?"pidesk":`pidesk ${JSON.stringify(e)}`,label:null,name:null,version:null};if(1!==Object.keys(e).length||!Array.isArray(t)||t.length>32||!t.every(e=>"string"==typeof e))return s;s.command=["pidesk",...t.map(l1)].join(" ");let n=t.some(e=>/\s/.test(e))?"":t.join(" ");if(0===t.length||["--help","-h","plugins","session","plugins --help","plugins -h","session --help","session -h"].includes(n))return{...s,label:lX};if("--version"===n)return{...s,label:"pideskVersion"};if("info"===n)return{...s,label:"pideskInfo"};if("session reload"===n)return{...s,label:"pideskReload"};if(3===t.length&&["--help","-h"].includes(t[2])&&("plugins"===t[0]&&["list","show","install","remove"].includes(t[1])||"session"===t[0]&&"reload"===t[1]))return{...s,label:lX};let r=t[1];if("plugins"!==t[0]||!r||!["list","show","install","remove"].includes(r))return s;let i=null,a=[],l=null,o=null,c=!1;for(let e=2;e<t.length;e+=1){let n=t[e];if("--scope"===n&&null===i&&"global"===t[e+1])i=t[++e];else if("--version"===n&&"install"===r&&null===l&&l0.test(t[e+1]??""))l=t[++e];else if("--tag"===n&&["list","install"].includes(r)&&null===o&&(t[e+1]?.length??0)<=128&&/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(t[e+1]??""))o=t[++e];else if("--check-updates"!==n||"list"!==r||c)if(!("list"!==r&&("show"!==r||0===a.length)&&"node_modules"!==n&&lZ.test(n)))return s;else a.push(n);else c=!0}if(null!==o&&null!==l||"list"!==r&&(0===a.length||null===i))return s;let d=a.length>0?a.join("、"):null;switch(r){case"list":return{...s,label:"pideskListPlugins"};case"show":return{...s,label:"pideskShowPlugin",name:d};case"install":return{...s,label:"pideskInstallPlugin",name:d,version:l};case"remove":return{...s,label:"pideskRemovePlugin",name:d};default:return s}}(e.summary.input),d=e.detail?.type==="tool"&&"pidesk"===e.detail.kind?e.detail.output:null;return(0,n.jsx)(cu,{identity:e.identity,command:c,output:d,expandable:i,open:r,loading:a,error:l,onOpenChange:o,commandAction:(0,n.jsx)(cj,{text:c.command,copyLabel:s("pidesk.copyCommand"),alwaysVisible:!0}),outputAction:d?(0,n.jsx)(cj,{text:d,copyLabel:s("pidesk.copyOutput"),alwaysVisible:!0}):null})}function cU({message:e,onLoadDetail:t}){return(0,n.jsx)(cL,{message:e,onLoadDetail:t,previewPath:null,renderDetail:t=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cB,{message:e,...t}),e.detail?.type==="tool"&&"codemode"===e.detail.kind&&e.detail.nestedCalls?(0,n.jsx)(co,{nestedCalls:e.detail.nestedCalls}):null]})})}function cH({message:e,onLoadDetail:t}){return(0,n.jsx)(cU,{message:e,onLoadDetail:t})}function cK({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)(cL,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(cq,{message:e,...t})})}function cG({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)(cL,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(cW,{message:e,...t})})}function cJ({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)(cL,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(cY,{message:e,...t})})}function cQ({message:e}){let{t}=(0,b.Bd)("conversation");if("custom"!==e.summary.type)throw Error("CustomMessage requires a custom summary");return(0,n.jsx)("div",{"data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:custom`,className:(0,C.cn)(cp().toolOutput,"rounded-lg border-l-2 bg-muted px-3 py-2 text-muted-foreground"),children:e.summary.text||t("emptyMessage")})}function cX({message:e,onLoadDetail:t}){let{t:s}=(0,b.Bd)("conversation");if("compaction"!==e.summary.type)throw Error("CompactionMessage requires a compaction summary");let{open:r,expandable:i,loading:a,error:l,handleOpenChange:o}=cy(e,t),c=e.detail?.type==="compaction"?e.detail:null;return(0,n.jsxs)(eV.Nt,{open:i&&r,onOpenChange:o,className:"w-full py-1","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:compaction`,children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"h-px min-w-3 flex-1 bg-border/70","aria-hidden":"true"}),(0,n.jsxs)(eV.R6,{disabled:!i,"aria-label":i?`${s(r?"collapse":"expand")} ${s("compactionSummary")}`:s(e.temporary?"compactionRunning":"compactionComplete"),className:(0,C.cn)("inline-flex min-h-8 max-w-full items-center gap-2 rounded-full border border-border/70 bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground outline-none transition-colors",i?"hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring":"cursor-default"),children:[e.temporary?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin","aria-hidden":"true"}):(0,n.jsx)(o_.A,{className:"size-3.5","aria-hidden":"true"}),(0,n.jsx)("span",{children:s(e.temporary?"compactionRunning":"compactionComplete")}),i?(0,n.jsx)(eY.A,{className:(0,C.cn)("size-3.5 transition-transform",r&&"rotate-180"),"aria-hidden":"true"}):null]}),(0,n.jsx)("span",{className:"h-px min-w-3 flex-1 bg-border/70","aria-hidden":"true"})]}),(0,n.jsx)(eV.Ke,{className:cb,children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)("div",{className:"rounded-xl border border-border/70 bg-muted/20 px-3 py-3 sm:px-4",children:(0,n.jsx)("div",{role:"region","aria-label":s("compactionSummaryContent"),tabIndex:0,className:"max-h-80 overflow-y-auto pr-2 [scrollbar-gutter:stable]",children:a?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:s("compactionLoading")}):l?(0,n.jsx)("p",{className:"text-sm text-destructive",children:l}):c?.text?(0,n.jsx)(rn,{isAnimating:!1,mode:"static",children:c.text}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:s("compactionUnavailable")})})})})})]})}let cZ=(0,r.memo)(function({item:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:r}){let i=(()=>{switch(e.message.summary.type){case"assistant":return(0,n.jsx)(cP,{item:e,onLoadDetail:t});case"tool":switch(e.message.summary.kind){case"pidesk":return(0,n.jsx)(cV,{message:e.message,onLoadDetail:t});case"read":return(0,n.jsx)(cK,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"edit":return(0,n.jsx)(cG,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"write":return(0,n.jsx)(cJ,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"bash":case"codemode":case"generic":return(0,n.jsx)(cU,{message:e.message,onLoadDetail:t})}case"bash":return(0,n.jsx)(cH,{message:e.message,onLoadDetail:t});case"custom":return(0,n.jsx)(cQ,{message:e.message});case"compaction":return(0,n.jsx)(cX,{message:e.message,onLoadDetail:t});case"user":return(0,n.jsx)(cE,{message:e.message,onAcquireImage:s})}})();return(0,n.jsx)(oO,{message:e.message,loadDetail:t,defaultView:i})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&e.onPreviewFile===t.onPreviewFile&&e.item.hideAssistantText===t.item.hideAssistantText&&c2(e.item.message,t.item.message));function c0({items:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i}){let{scrollRef:a}=(0,lT.B)(),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(e.length),d=(0,r.useRef)(null),[u,m]=(0,r.useState)(()=>Math.min(64,e.length)),p=Math.max(0,e.length-u),h=p>0,g=(0,r.useCallback)(()=>{if(!h)return;let t=a.current,s=l.current?.querySelector("[data-chat-process-item]");t&&s?.dataset.chatProcessItem&&(d.current={identity:s.dataset.chatProcessItem,offset:s.getBoundingClientRect().top-t.getBoundingClientRect().top}),m(t=>Math.min(e.length,t+64))},[h,e.length,a]);return(0,r.useLayoutEffect)(()=>{let t=c.current;c.current=e.length,u>=t&&u<e.length&&m(e.length)},[u,e.length]),(0,r.useLayoutEffect)(()=>{let e=d.current;if(!e)return;let t=a.current,s=Array.from(l.current?.querySelectorAll("[data-chat-process-item]")??[]).find(t=>t.dataset.chatProcessItem===e.identity);if(d.current=null,!t||!s)return;let n=s.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=n-e.offset},[p,a]),(0,r.useEffect)(()=>{let e=a.current,t=o.current;if(!e||!t||!h)return;let s=()=>{let s=e.getBoundingClientRect().top,n=t.getBoundingClientRect().top;return n>=s-96&&n<=s+96},n=e=>{e.deltaY<0&&s()&&g()},r=()=>{s()&&g()};return e.addEventListener("wheel",n,{passive:!0}),e.addEventListener("touchmove",r,{passive:!0}),()=>{e.removeEventListener("wheel",n),e.removeEventListener("touchmove",r)}},[h,g,a]),(0,n.jsxs)("div",{ref:l,children:[h?(0,n.jsx)("div",{ref:o,className:"h-px","data-chat-process-history":!0,"aria-hidden":"true"}):null,e.slice(p).map((r,a)=>{let l=p+a,o=e[l-1],c=o?.message.summary.type==="assistant"&&!o.hideAssistantText&&!!o.message.summary.text.trim();return(0,n.jsx)("div",{"data-chat-process-item":r.message.identity,className:l>0?c?"mt-5":"mt-2":void 0,children:(0,n.jsx)(cZ,{item:r,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i})},r.message.identity)})]})}let c1=(0,r.memo)(function({turn:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i}){let{t:a}=(0,b.Bd)("conversation"),[l,o]=(0,r.useState)(!1),c=(0,r.useContext)(cg),d=(0,Q.t4)();(0,Q.So)();let u=e.processItems.filter(e=>!e.hideAssistantText||"pi-desk/assistant"===e.message.viewKey&&null===d.getMessageViewResolution(e.message.viewKey)),m=e.running||l,p=(0,r.useCallback)(t=>{e.running||(t&&c(),o(t))},[c,e.running]);return 0===u.length?null:(0,n.jsxs)(eV.Nt,{open:m,onOpenChange:p,className:"w-full",children:[(0,n.jsxs)(eV.R6,{className:(0,C.cn)(cp().detailText,"flex min-h-9 w-full cursor-pointer items-center gap-2 py-1 text-left text-muted-foreground hover:text-foreground"),children:[(0,n.jsxs)("span",{className:"flex-1",children:[a("processGroup"),e.toolCount>0?` \xb7 ${a("toolCalls",{count:e.toolCount})}`:""]}),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-4 transition-transform",m&&"rotate-180")})]}),(0,n.jsx)(eV.Ke,{className:cb,children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)(c0,{items:u,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i})})})]})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&e.onPreviewFile===t.onPreviewFile&&e.turn.running===t.turn.running&&e.turn.toolCount===t.turn.toolCount&&c5(e.turn.processItems,t.turn.processItems));function c2(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 c5(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&&c2(e.message,n.message)})}let c3=(0,r.memo)(function({message:e,onLoadDetail:t,onAcquireImage:s}){return(0,n.jsx)(oO,{message:e,loadDetail:t,defaultView:(0,n.jsx)(cE,{message:e,onAcquireImage:s})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&c2(e.message,t.message)),c4=(0,r.memo)(function({message:e,onLoadDetail:t}){return"assistant"!==e.summary.type?null:(0,n.jsx)(oO,{message:e,loadDetail:t,defaultView:(0,n.jsx)(cM,{message:e,text:e.summary.text})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&c2(e.message,t.message)),c6=(0,r.memo)(function({turn:e,cwd:t,logicalTail:s=!1,onLoadDetail:r,onAcquireImage:i,onPreviewFile:a}){if(e.compaction)return(0,n.jsx)("section",{className:(0,C.cn)(!e.running&&"pi-desk-chat-turn-contained"),"data-chat-turn":e.identity,"data-chat-logical-tail":s?"":void 0,children:(0,n.jsx)(oO,{message:e.compaction,loadDetail:r,defaultView:(0,n.jsx)(cX,{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)(c3,{message:e.user,onLoadDetail:r,onAcquireImage:i}):null,(0,n.jsx)(cx.Provider,{value:i,children:(0,n.jsx)(cf.Provider,{value:t,children:(0,n.jsx)(c1,{turn:e,onLoadDetail:r,onAcquireImage:i,onPreviewFile:a})})}),l?(0,n.jsx)(cz,{}):null,e.finalAssistant?(0,n.jsx)(c4,{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&&c2(s.user,n.user)&&c2(s.finalAssistant,n.finalAssistant)&&c2(s.compaction,n.compaction)&&c5(s.processItems,n.processItems))});c6.displayName="L3ConversationTurnView";let c8={running:"statusRunning",completed:"statusCompleted",failed:"statusFailed",stopped:"statusStopped",interrupted:"statusInterrupted"};function c7(e,t){return null!==e&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}function c9(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 de(e){return[e.taskKind,e.taskType].filter(e=>!!e).join(" / ")}function dt(e){switch(e){case"running":return(0,n.jsx)(v.A,{className:"size-4 animate-spin text-foreground"});case"completed":return(0,n.jsx)(ls.A,{className:"size-4 text-status-success"});case"failed":return(0,n.jsx)(lA.A,{className:"size-4 text-destructive"});case"interrupted":return(0,n.jsx)(l$.A,{className:"size-4 text-status-warning"});case"stopped":return(0,n.jsx)(lR.A,{className:"size-4 text-muted-foreground"})}}function ds({info:e}){let{t}=(0,b.Bd)("taskCenter"),s=(0,X.G)(),[i,a]=(0,r.useState)(null);if(0===e.length)return null;let l=(e,n)=>{(0,e9.x)(e.value).then(r=>{r?a(n):s.error(t("copyFailed",{name:e.label}))})};return(0,n.jsx)("div",{"data-task-info-scroll":"",className:"max-h-32 overflow-y-auto pr-1 [scrollbar-gutter:stable]",children:(0,n.jsx)("dl",{className:"flex flex-wrap gap-2",children:e.map((e,s)=>{let r=`${e.label}:${s}:${e.value}`,a=i===r;return(0,n.jsxs)("div",{role:"button",tabIndex:0,"aria-label":t(a?"copied":"copy",{name:e.label}),title:a?t("copiedShort"):t("clickToCopy",{name:e.label}),className:(0,C.cn)("flex min-h-8 min-w-0 max-w-full cursor-pointer items-start gap-2 rounded-md px-2 py-1 text-sm outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",a&&"bg-muted"),onClick:()=>l(e,r),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),l(e,r))},children:[(0,n.jsx)("dt",{className:"shrink-0 pt-0.5 font-medium text-muted-foreground",children:e.label}),(0,n.jsx)("dd",{className:"min-w-0 flex-1 break-words text-foreground",children:e.value}),(0,n.jsx)("span",{className:"shrink-0 pt-0.5 text-muted-foreground","aria-hidden":"true",children:a?(0,n.jsx)(ep.A,{className:"size-3.5 text-status-success"}):(0,n.jsx)(ee.A,{className:"size-3.5"})})]},`${e.label}:${s}`)})})})}function dn({snapshot:e,running:t,runtime:s,cwd:i}){let{t:a}=(0,b.Bd)("taskCenter"),l=(0,r.useMemo)(()=>oi(e,t),[t,e]),o=l.findLast(e=>null!==e.user)??null;return(0,n.jsx)(lO,{className:"h-full min-h-0",initial:"instant",resize:"instant","aria-label":a("conversationDetails"),children:(0,n.jsx)(oI,{turns:l,focusTurnIdentity:o?.identity??null,initialAnchor:null,children:e=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ob,{}),(0,n.jsx)(cv,{children:(0,n.jsxs)(lL,{scrollClassName:"pi-desk-chat-scrollbar",className:"mx-auto min-h-full w-full max-w-3xl gap-6 px-4 pt-3 pb-6 sm:px-6",children:[l.length>0?e.visibleTurns.map((t,r)=>{let a=e.startIndex+r;return(0,n.jsx)(c6,{turn:t,cwd:i,logicalTail:e.containsTail&&a===l.length-1,onLoadDetail:s.loadMessageDetail,onAcquireImage:s.acquireImage},t.identity)}):(0,n.jsx)("div",{className:"grid min-h-48 place-items-center text-sm text-muted-foreground",children:a("noMessages")}),(0,n.jsx)("div",{className:"h-4 shrink-0","aria-hidden":"true"})]})}),(0,n.jsx)(oz,{turns:l,window:e})]})})})}function dr({task:e,runtime:t,cwd:s}){let{t:i}=(0,b.Bd)("taskCenter"),a=(0,r.useSyncExternalStore)(t.subscribe,t.getState,t.getState),l=e?a.details[e.taskId]:void 0,[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),h=async()=>{if(!o)return void c(!0);u(!0),p(null);try{await t.interruptSelected(),c(!1)}catch(e){p(e instanceof Error?e.message:i("interruptFailed"))}finally{u(!1)}};if(!e)return(0,n.jsx)("div",{className:"grid h-full min-h-0 place-items-center px-6 text-center text-sm text-muted-foreground",children:i("selectTask")});let g=de(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:dt(e.status)}),(0,n.jsx)("h3",{className:"min-w-0 break-words text-sm font-semibold",children:g?`${g} \xb7 ${e.title}`:e.title})]}),(0,n.jsxs)("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs",children:[(0,n.jsx)("span",{className:(0,C.cn)("rounded-md px-1.5 py-0.5 font-medium",function(e){switch(e){case"running":return"bg-muted text-foreground";case"completed":return"bg-muted text-status-success";case"failed":return"bg-muted text-destructive";case"interrupted":return"bg-muted text-status-warning";case"stopped":return"bg-muted text-muted-foreground"}}(e.status)),children:i(c8[e.status])}),(0,n.jsx)("span",{className:"text-muted-foreground",children:c9(e,(e,t)=>i(e,{count:t}))}),e.activity?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"text-muted-foreground/60",children:"\xb7"}),(0,n.jsx)("span",{className:"min-w-0 break-words text-muted-foreground",children:e.activity})]}):null]})]}),l?.canInterrupt?(0,n.jsxs)(I.$,{className:"shrink-0",type:"button",size:"sm",variant:o?"destructive":"outline",disabled:d,onClick:()=>void h(),children:[d?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(lR.A,{}),o?i("confirmInterrupt"):i("interrupt")]}):null]})}),m?(0,n.jsx)("p",{role:"alert",className:"shrink-0 border-b bg-muted px-4 py-2 text-sm text-destructive",children:m}):null,e.info.length>0?(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-2",children:(0,n.jsx)(ds,{info:e.info})}):null,(0,n.jsxs)("div",{className:"relative min-h-0 flex-1",children:[l?.body?.kind==="conversation"?(0,n.jsx)(dn,{snapshot:l.body,running:"running"===e.status,runtime:t,cwd:s}):l?.body?.kind==="text"?(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("pre",{className:(0,C.cn)("whitespace-pre-wrap break-words font-mono text-sm leading-[1.6]"),children:l.body.text||i("waitingOutput")})}):l?(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("div",{className:"grid min-h-48 place-items-center px-2 text-center text-sm text-muted-foreground",children:i("noDetails")})}):(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("div",{className:"grid min-h-48 place-items-center px-2 text-center text-sm text-muted-foreground",children:a.error?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("p",{className:"text-destructive",children:a.error}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>t.selectTask(e.taskId),children:[(0,n.jsx)(lP.A,{}),i("retry")]})]}):(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),i("loadingDetail")]})})}),a.refreshing?(0,n.jsxs)("div",{className:"pointer-events-none absolute right-3 top-3 flex items-center gap-2 rounded-md border bg-popover px-2 py-1 text-xs text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-3 animate-spin"}),i("refreshing")]}):null]})]})}function di({source:e,tasks:t,runtime:s,cwd:i}){let{t:a}=(0,b.Bd)("taskCenter"),{locale:l,timeZone:o}=(0,eQ.i)(),c=(0,r.useCallback)(()=>{let e=s.getState();return JSON.stringify([e.open,e.source?.workId??null,e.source?.sessionId??null,e.source?.branchId??null,e.selectedTaskId])},[s]);(0,r.useSyncExternalStore)(s.subscribe,c,c);let d=s.getState(),[u,m]=(0,r.useState)(!1),p=t.find(e=>e.taskId===d.selectedTaskId)??null;(0,r.useEffect)(()=>{d.open&&c7(d.source,e)&&s.reconcileTasks(e,t)},[s,e,d.open,d.source,t]);let h=u&&null!==d.selectedTaskId,g=d.open&&c7(d.source,e);return(0,n.jsx)(eN.YV,{open:g,onOpenChange:e=>{e||s.close()},children:(0,n.jsxs)(eN.hA,{"aria-label":a("title"),showCloseButton:!1,className:"h-[calc(100dvh-2rem)] max-w-[70rem] flex-row bg-background max-lg:h-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",{className:(0,C.cn)("flex min-w-0 flex-1 flex-col border-r bg-sidebar lg:max-w-80",h&&"hidden lg:flex"),children:[(0,n.jsxs)("header",{className:"flex min-h-14 items-center gap-3 border-b px-4 py-3",children:[(0,n.jsx)(lD.A,{className:"size-5 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{children:a("title")}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:a("recordCount",{count:t.length})})]}),(0,n.jsx)(I.$,{className:"lg:hidden",type:"button",variant:"ghost",size:"icon","aria-label":a("close"),onClick:()=>s.close(),children:(0,n.jsx)(V.A,{})})]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-2",children:t.length>0?(0,n.jsx)("div",{className:"space-y-1",children:t.map(e=>{let t=de(e),r=c9(e,(e,t)=>a(e,{count:t})),i=oo(e.startedAt,void 0,l,o);return(0,n.jsxs)("button",{type:"button","aria-current":e.taskId===d.selectedTaskId?"true":void 0,onClick:()=>{var t;return t=e.taskId,void(s.selectTask(t),m(!0))},className:(0,C.cn)("grid min-h-14 w-full cursor-pointer grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-x-2 rounded-lg px-3 py-3 text-left outline-none transition-colors hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",e.taskId===d.selectedTaskId&&"bg-accent text-accent-foreground hover:bg-accent"),children:[(0,n.jsx)("span",{className:"mt-0.5 shrink-0",children:dt(e.status)}),(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsxs)("span",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-baseline gap-x-3",children:[(0,n.jsx)("span",{className:"truncate text-sm font-medium",children:e.title}),(0,n.jsxs)("span",{className:"whitespace-nowrap text-xs tabular-nums text-muted-foreground","aria-label":a("runningTime",{duration:r,time:i.full}),children:[r,(0,n.jsx)("span",{className:"mx-1 text-muted-foreground/50","aria-hidden":"true",children:"\xb7"}),(0,n.jsx)("time",{dateTime:new Date(e.startedAt).toISOString(),children:i.compact})]})]}),t?(0,n.jsx)("span",{className:"mt-1 block truncate text-xs text-muted-foreground",children:t}):null]}),(0,n.jsx)(e7.A,{className:"mt-1 size-4 shrink-0 text-muted-foreground lg:hidden"})]},e.taskId)})}):(0,n.jsx)("div",{className:"grid min-h-48 place-items-center text-sm text-muted-foreground",children:a("noTasks")})})]}),(0,n.jsx)("div",{className:(0,C.cn)("min-w-0 flex-1",!h&&"hidden lg:block"),children:(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-12 items-center gap-2 border-b bg-muted/10 px-3 lg:hidden",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":a("back"),onClick:()=>m(!1),children:(0,n.jsx)(A.A,{})}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-center text-xs text-muted-foreground",children:p?.title??a("detail")}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":a("close"),onClick:()=>s.close(),children:(0,n.jsx)(V.A,{})})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1",children:(0,n.jsx)(dr,{task:p,runtime:s,cwd:i},p?.taskId??"no-task")})]})}),(0,n.jsx)(I.$,{className:"absolute right-4 top-3 z-10 hidden lg:inline-flex",type:"button",variant:"ghost",size:"icon","aria-label":a("close"),onClick:()=>s.close(),children:(0,n.jsx)(V.A,{})})]})})}function da({source:e,cwd:t,tasks:s,runtime:r,variant:i}){let{t:a}=(0,b.Bd)("taskCenter"),l=s.filter(e=>"running"===e.status),o=l[0],c=()=>{r.open(e,(s.find(e=>"running"===e.status)??s[0]??null)?.taskId??null)};return"footer"===i?s.length>0?(0,n.jsx)(lG,{tooltip:a("title"),"aria-label":a("open"),onClick:c,children:(0,n.jsx)(lD.A,{className:"size-4"})}):(0,n.jsx)(n.Fragment,{}):"menu"===i?(0,n.jsxs)(K._2,{onClick:c,children:[(0,n.jsx)(lD.A,{className:"size-4"}),a("title")]}):(0,n.jsxs)(n.Fragment,{children:[o?(0,n.jsxs)("button",{type:"button",className:"mb-2 flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-md border bg-muted px-2.5 text-left text-sm text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",onClick:c,"aria-label":`${a("open")}, ${a("runningCount",{count:l.length})}`,children:[(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin text-foreground"}),(0,n.jsx)("span",{className:"shrink-0 font-medium text-foreground",children:a("runningCount",{count:l.length})}),(0,n.jsxs)("span",{className:"min-w-0 flex-1 truncate",children:[o.title,o.activity?` \xb7 ${o.activity}`:""]}),(0,n.jsx)(e7.A,{className:"size-3.5 shrink-0"})]}):null,(0,n.jsx)(di,{source:e,tasks:s,runtime:r,cwd:t})]})}function dl({source:e,cwd:t,pluginState:s,runtime:i,variant:a}){let l=(0,r.useMemo)(()=>{let e=lb.safeParse(s);return e.success?e.data.tasks:[]},[s]);return(0,n.jsx)(da,{source:e,cwd:t,tasks:l,runtime:i,variant:a})}var dc=s(74577),dd=s(85232);function du(e){return`${e.location.index}:${e.location.entryId}`}let dm={user:["viewKey","hasDetail"],assistant:["viewKey","status","hasDetail","usage"],tool:["viewKey","status","hasDetail","usage"],bash:["viewKey","status","hasDetail"],custom:["viewKey","hasDetail"]};function dp(e,t,s){if(!t)return e;let n={...e,...t};return"summary"===s?lo.Hf.parse(n):lo.D8.parse(n)}function dh(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 dg(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 dh(r,`${r.value}${s}`),lo.Hf.parse(n)}if(!Array.isArray(r.value))throw Error("Increment target is not an array");return dh(r,[...r.value,...s]),lo.Hf.parse(n)}function df(e,t,s){let n=new Map(e.messages.filter(e=>void 0!==e.detail).map(e=>[du(e),e]));return{messages:t.map(e=>{let t=n.get(du(e));return e.fixed.hasDetail&&t&&t.fixed.type===e.fixed.type&&t.fixed.viewKey===e.fixed.viewKey&&void 0!==t.detail?lo.mj.parse({...e,detail:t.detail}):e}),temporaryMessages:[...s]}}function dx(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,dm[s.type],`${s.type} fixed`),lo.q5.parse({...s,...n})):s),i=dp(e.summary,t.summary,"summary"),a=e.detail;if(void 0!==t.detail||Object.keys(t.increments??{}).some(e=>"detail"===(0,dd.U)(e).root)){if(t.fixed?.hasDetail===!1)throw Error("Realtime detail cannot be updated while explicitly clearing hasDetail");r.hasDetail||(r=lo.q5.parse({...r,hasDetail:!0}))}for(let[e,s]of(t.detail&&(a=dp(a??{},t.detail,"detail")),Object.entries(t.increments??{}))){let t=(0,dd.U)(e);"summary"===t.root?i=dg(i,t.segments,s):a=dg(a??{},t.segments,s)}return r.hasDetail||(a=void 0),lo.s4.parse({location:e.location,fixed:r,summary:i,...void 0===a?{}:{detail:a}})}(n[s],t),{...e,temporaryMessages:n}}if("message_discard"===t.type)return{...e,temporaryMessages:e.temporaryMessages.filter(e=>e.location.tempId!==t.location.tempId)};if(t.durable.index!==e.messages.length)throw Error(`Conversation commit index is not continuous: expected ${e.messages.length}, received ${t.durable.index}`);if(e.messages.some(e=>e.location.entryId===t.durable.entryId))throw Error(`Conversation commit entryId already exists: ${t.durable.entryId}`);let{detail:n,fixed:r,...i}=e.temporaryMessages[s],a=lo.mj.parse({...i,location:t.durable,fixed:{...r,timestampMs:t.fixed.timestampMs},...r.hasDetail&&void 0!==n?{detail:n}:{}});return{messages:[...e.messages,a],temporaryMessages:e.temporaryMessages.filter(e=>e.location.tempId!==t.location.tempId)}}function db(e,t){let s=e.messages.findIndex(e=>e.location.index===t.index&&e.location.entryId===t.entryId);if(s<0)throw Error(`Conversation detail target was not found: ${t.index}/${t.entryId}`);let n=e.messages[s];if(null!==t.detail&&!n.fixed.hasDetail)throw Error("Message without hasDetail cannot accept detail");let r=[...e.messages];return r[s]=lo.mj.parse({...n,...null===t.detail?{detail:void 0}:{detail:t.detail}}),{...e,messages:r}}function dv(e,t){return e.taskId!==t.taskId||e.body?.kind!=="conversation"||t.body?.kind!=="conversation"?t:lk.parse({...t,body:{kind:"conversation",truncated:t.body.truncated,...df(e.body,t.body.messages,t.body.temporaryMessages)}})}var dw=s(7237);function dy(e){return(0,ed.B)({msg:dc.U["zh-CN"][e],i18n:{key:`taskCenter:${e}`}})}let dk=Object.freeze({open:!1,source:null,selectedTaskId:null,details:{},loading:!1,refreshing:!1,error:null});function dj(e,t){return e===t||null!==e&&null!==t&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}var dN=s(15381),dI=s(94853);let dS=s0.rh,dC=s0.eC,dE=a.Ik({workId:dN.eW,cwd:dN.ik}).strict(),dM=dE.extend({path:dS}).strict(),dz=dE.extend(s0.Nu.shape).strict(),dA=dI.Ot.request.safeExtend({workId:dN.eW});dI.Ot.response;let d$=s0.p$,dR=dE.extend({path:dC,imagePreviewMode:d$}).strict();var dP=s(46117),dD=s.n(dP);function dT({mobile:e,open:t,sidebar:s,children:i,onClose:a}){let{t:l}=(0,b.Bd)("workbench"),o=(0,E.fk)(),c=(0,r.useRef)(288);return((0,r.useLayoutEffect)(()=>{if(e)return;let s=requestAnimationFrame(()=>{o.current?.resize(t?c.current:0)});return()=>cancelAnimationFrame(s)},[e,t,o]),e)?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button","aria-label":l("closeSessionMenu"),"aria-hidden":!t,tabIndex:t?0:-1,onClick:a,className:(0,C.cn)(dD().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)(dD().drawer,"fixed inset-y-0 left-0 z-50 flex w-[min(86vw,320px)] flex-col border-r bg-sidebar shadow-2xl",!t&&"pointer-events-none"),children:s}),(0,n.jsx)("div",{className:"flex min-h-0 min-w-0 flex-1",inert:t||void 0,children:i})]}):(0,n.jsxs)(S.HK,{orientation:"horizontal",disableCursor:!0,className:(0,C.cn)(dD().panelGroup,"pi-desk-workbench-resize-group min-h-0 min-w-0 flex-1"),onLayoutChanged:(e,s)=>{if(!s.isUserInteraction||!t)return;let n=o.current?.getSize().inPixels;void 0!==n&&(c.current=n)},children:[(0,n.jsx)(S.wV,{id:"work-session-sidebar",panelRef:o,defaultSize:288,minSize:224*!!t,maxSize:480*!!t,disabled:!t,"aria-hidden":!t||void 0,inert:!t||void 0,className:"flex h-full min-h-0 min-w-0 !overflow-hidden bg-sidebar",children:(0,n.jsx)("div",{className:"flex h-full w-full min-w-[224px] flex-col border-r",children:s})}),(0,n.jsx)(S.WM,{withHandle:!0,"aria-label":l("resizeSessionList"),"aria-hidden":!t||void 0,disabled:!t,className:(0,C.cn)("cursor-col-resize",!t&&"w-0 pointer-events-none opacity-0")}),(0,n.jsx)(S.wV,{id:"work-session-content",minSize:360,className:"flex h-full min-h-0 min-w-0 !overflow-hidden",children:i})]})}let dO=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 dL=s(5011),dF=s(42515),dB=s(91399),dq=s(95826),d_=s(37975),dW=s(56592),dY=s(31343);function dV(e,t){return(0,ed.B)({msg:dY.R["zh-CN"][e],i18n:{key:`workbench:${e}`,...t?{params:t}:{}}})}function dU(e){let{workId:t,sessionId:s,branchId:n}=e.source;return JSON.stringify([t,s,n,e.cwd])}function dH(e,t,s){return`${dU(e)}\u0000${s}\u0000${t}`}class dK{peek(e,t,s){let n=this.images.get(dH(e,t,s));return!n||0===n.references&&Date.now()-n.unusedAt>=6e4?null:n.url}get(e,t,s){this.trim();let n=dH(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(dU(e)))throw Error("工作会话来源已变化");let r=dH(e,t,s),i=this.images.get(r);if(i)return this.acquire(r,i);let a={url:URL.createObjectURL(n),size:n.size,references:0,unusedAt:Date.now()};return this.images.set(r,a),this.acquire(r,a)}invalidate(e,t,s){this.remove(dH(e,t,s))}reconcileWorkSessions(e){for(let t of(this.validSources=new Set(e.map(e=>dU({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 dG{constructor(e,t,s=()=>void 0){this.biz=e,this.gitBiz=t,this.onNotice=s,this.standaloneImages=new dK,this.listeners=new Set,this.workspaces=new Map,this.sources=new Map,this.previewDirectories=new Map,this.expandedWorkId=null,this.revision=0,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.getRevision=()=>this.revision}getWorkspace(e){let t=e?this.workspaces.get(e):null;return t?{...t.files.state,cwd:t.files.cwd,windowOpen:t.windowOpen,chatWidthPercent:t.chatWidthPercent,activePane:t.activePane}:null}getFileRuntime(e){return this.workspaceFor(e).files}getExpandedWorkId(){return this.expandedWorkId}getDirectories(e){return this.previewDirectories.get(e)?.directories??[]}getDirectory(e){let t=this.previewDirectories.get(e);if(!t)throw Error(dV("sourceChanged"));return t.selectedDirectory}applyPreviewDirectories(e,t){let s=this.sources.get(e.workId);if(!s||s.sessionId!==e.sessionId||s.branchId!==e.branchId)return;let n=this.previewDirectories.get(e.workId),r=new Map([[(0,d_.Yj)(s.cwd),s.cwd]]);for(let e of t.directories){let t=(0,d_.Yj)(e);r.has(t)||r.set(t,e)}let i=t.defaultDirectory?r.get((0,d_.Yj)(t.defaultDirectory))??null:null,a=(n.defaultDirectory?(0,d_.Yj)(n.defaultDirectory):null)!==(i?(0,d_.Yj)(i):null)?i??s.cwd:r.get((0,d_.Yj)(n.selectedDirectory))??s.cwd,l=[...r.values()];if(n.defaultDirectory===i&&n.selectedDirectory===a&&n.directories.length===l.length&&n.directories.every((e,t)=>e===l[t]))return;this.previewDirectories.set(e.workId,{directories:l,defaultDirectory:i,selectedDirectory:a});let o=this.workspaces.get(e.workId);if(o){for(let[e,t]of o.roots)r.has(e)||(t.unsubscribe(),t.files.dispose(),o.roots.delete(e));this.switchFiles(e.workId,o)}this.publish()}selectDirectory(e,t){let s=this.previewDirectories.get(e);if(!s)throw Error(dV("sourceChanged"));let n=s.directories.find(e=>(0,d_.Yj)(e)===(0,d_.Yj)(t));if(!n)throw Error(dV("sourceChanged"));if(s.selectedDirectory===n)return;s.selectedDirectory=n;let r=this.workspaces.get(e);r&&this.switchFiles(e,r),this.publish()}reconcileWorkSessions(e){this.standaloneImages.reconcileWorkSessions(e);let t=new Map(e.map(({workId:e,cwd:t,sessionId:s,branchId:n})=>[e,{workId:e,cwd:t,sessionId:s,branchId:n}])),s=!1;for(let[e,n]of this.sources){let r=t.get(e);if(r?.cwd===n.cwd&&r.sessionId===n.sessionId&&r.branchId===n.branchId)continue;let i=this.workspaces.get(e);i&&(this.disposeLayout(i),this.workspaces.delete(e)),this.previewDirectories.delete(e),s=!0,this.expandedWorkId===e&&(this.expandedWorkId=null)}for(let[e,s]of(this.sources.clear(),t))this.sources.set(e,s),this.previewDirectories.has(e)||this.previewDirectories.set(e,{directories:[s.cwd],defaultDirectory:null,selectedDirectory:s.cwd});s&&this.publish()}ensureRoot(e){return this.getFileRuntime(e).ensureRoot()}ensureDirectory(e,t){return this.getFileRuntime(e).ensureDirectory(t)}setExpandedPaths(e,t){this.getFileRuntime(e).setExpandedPaths(t)}setTreeScrollTop(e,t){this.workspaces.get(e)?.files.setTreeScrollTop(t)}refreshTree(e){this.getFileRuntime(e).refreshTree()}setSearchQuery(e,t){this.getFileRuntime(e).setSearchQuery(t)}search(e,t){return this.getFileRuntime(e).search(t)}openFile(e,t){let s=this.workspaceFor(e);s.windowOpen=!0,s.activePane="files",s.files.openFile(t)}async revealFile(e,t){await this.getFileRuntime(e).revealFile(t)}activateFile(e,t){this.workspaces.get(e)?.files.state.tabs.includes(t)&&this.openFile(e,t)}closeFile(e,t){this.closeTabs(e,t,"current")}closeTabs(e,t,s){this.workspaces.get(e)?.files.closeTabs(t,s)}hideWindow(e){let t=this.workspaces.get(e);t?.windowOpen&&(t.windowOpen=!1,t.activePane="chat",this.expandedWorkId===e&&(this.expandedWorkId=null),this.publish())}showWindow(e){let t=this.workspaceFor(e),{tabs:s,activeDiff:n,activePath:r}=t.files.state;(s.length||n||this.expandedWorkId===e)&&(t.windowOpen=!0,t.activePane="files",this.publish(),!n&&r&&t.files.ensureDocument(r))}setChatWidthPercent(e,t){let s=this.workspaces.get(e);!s||!Number.isFinite(t)||t<=0||t>=100||.001>Math.abs(s.chatWidthPercent-t)||(s.chatWidthPercent=t,this.publish())}setActivePane(e,t){let s=this.workspaces.get(e);s&&s.activePane!==t&&(s.activePane=t,this.publish())}expandWindow(e){this.expandedWorkId=e,this.showWindow(e)}collapseExpandedWindow(){if(!this.expandedWorkId)return;let e=this.workspaces.get(this.expandedWorkId);this.expandedWorkId=null,!e||e.files.state.tabs.length||e.files.state.activeDiff||(e.windowOpen=!1,e.activePane="chat"),this.publish()}reloadFile(e,t){this.workspaces.get(e)?.files.reloadFile(t)}openDiff(e,t,s){let n=this.workspaceFor(e);n.windowOpen=!0,n.activePane="files",n.files.openDiff(t,s)}closeDiff(e){this.closeTabs(e,null,"current")}reloadDiff(e){this.workspaces.get(e)?.files.reloadDiff()}setDiffViewMode(e,t){this.workspaces.get(e)?.files.setDiffViewMode(t)}setDiffWrapLines(e,t){this.workspaces.get(e)?.files.setDiffWrapLines(t)}setDiffCollapseUnchanged(e,t){this.workspaces.get(e)?.files.setDiffCollapseUnchanged(t)}handleGitBranchChanged(e,t){for(let s of this.workspaces.values())for(let n of s.roots.values())n.files.cwd===e&&n.files.handleGitBranchChanged(t)}saveEditorState(e,t,s){this.workspaces.get(e)?.files.saveEditorState(t,s)}setWrapLines(e,t,s){this.workspaces.get(e)?.files.setWrapLines(t,s)}setTextViewMode(e,t,s){this.workspaces.get(e)?.files.setTextViewMode(t,s)}dispose(){for(let e of(this.standaloneImages.dispose(),this.workspaces.values()))this.disposeLayout(e);this.workspaces.clear(),this.sources.clear(),this.previewDirectories.clear(),this.expandedWorkId=null,this.listeners.clear()}workspaceFor(e){if(!this.sources.get(e))throw Error(dV("sourceChanged"));let t=this.workspaces.get(e);if(t)return t;let s={files:this.createFiles(e,this.getDirectory(e)),roots:new Map,windowOpen:!1,chatWidthPercent:50,activePane:"files"};return this.attachRoot(e,s,s.files),this.workspaces.set(e,s),s}createFiles(e,t){let s={workId:e,cwd:t};return new dW.h(t,{list:(e,t)=>this.biz.list({...s,path:e},t),search:(e,t)=>this.biz.search({...s,...e},t),get:(e,t,n)=>this.biz.get({...s,path:e,imagePreviewMode:t},n),diff:(e,t,n)=>this.gitBiz.getDiff({...s,repositoryRoot:e,path:t},n)},{imagePreviewMode:rm.Wq,htmlPreview:!0,onNotice:this.onNotice,reveal:async(e,t)=>{await this.biz.reveal({...s,path:e,..."directory"===t?{targetType:t}:{}})}})}attachRoot(e,t,s){let n=s.subscribe(()=>{t.files===s&&(s.state.activePath||s.state.activeDiff||this.expandedWorkId===e||(t.windowOpen=!1,t.activePane="chat"),this.publish())});t.roots.set((0,d_.Yj)(s.cwd),{files:s,unsubscribe:n})}switchFiles(e,t){let s=this.getDirectory(e),n=(0,d_.Yj)(s);if((0,d_.Yj)(t.files.cwd)===n)return;let r=t.roots.get(n);if(!r){let i=this.createFiles(e,s);this.attachRoot(e,t,i),r=t.roots.get(n)}t.files=r.files,r.files.state.activePath||r.files.state.activeDiff||this.expandedWorkId===e||(t.windowOpen=!1,t.activePane="chat")}disposeLayout(e){for(let t of e.roots.values())t.unsubscribe(),t.files.dispose();e.roots.clear()}publish(){for(let e of(this.revision+=1,this.listeners))e()}}var dJ=s(70657);function dQ(e,t,s,n){t.reconcileWorkSessions(s,n,s.flatMap(({workId:t})=>e.getDirectories(t).map(e=>({workId:t,cwd:e}))))}var dX=s(90504),dZ=s(46487),d0=s(97921),d1=s(36510);let d2='data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/%3E';function d5({target:e,paths:t,index:s,onIndexChange:i,biz:a,images:l}){let{t:o}=(0,b.Bd)("workbench"),[c,d]=(0,r.useState)({}),u=(0,r.useRef)(new Map),m=t[s],p=c[m],h=(0,rm.Wq)(),g=l.peek(e,m,h),f=p?.status==="ready"||!p&&null!==g;return(0,r.useLayoutEffect)(()=>{let e=u.current;return()=>{for(let t of e.values())t.release();e.clear()}},[]),(0,r.useLayoutEffect)(()=>{let t,s=u.current;if(p?.status==="error"||s.has(m))return;let n=l.get(e,m,h);if(n)return void s.set(m,n);let r=new AbortController;return(async()=>{try{let n=await a.get({workId:e.source.workId,cwd:e.cwd,path:m,imagePreviewMode:h},r.signal);if(r.signal.aborted)return;if("image"!==n.kind)throw Error(o("standaloneReadFailed"));t=l.store(e,m,h,(0,dw.E)(n));let i=new Image;if(i.src=t.url,await i.decode(),r.signal.aborted)return;let c=t.url;s.set(m,t),d(e=>({...e,[m]:{status:"ready",objectUrl:c}}))}catch(n){if(t&&(t.release(),l.invalidate(e,m,h)),r.signal.aborted)return;let s=n instanceof Error?n.message:o("standaloneReadFailed");console.warn("[Pi Desk][StandaloneImageGallery] 读取图片失败",{workId:e.source.workId,path:m,error:s}),d(e=>({...e,[m]:{status:"error",message:s}}))}})(),()=>{r.abort(),s.get(m)!==t&&t?.release()}},[a,p,l,h,m,o,e]),(0,n.jsxs)("div",{className:"relative size-full","data-testid":"standalone-image-gallery",children:[(0,n.jsx)(ny.k,{mode:"inline",thumbnails:!1,slides:t.map(e=>{let t=c[e];return{src:t?.status==="ready"?t.objectUrl:e===m?g??d2:d2,alt:e}}),index:s,onIndexChange:i}),f?null:(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 z-[2] flex items-center justify-center p-6 pb-20",children:p?.status==="error"?(0,n.jsxs)("div",{className:"flex max-w-full flex-col items-center gap-3 rounded-lg bg-background/95 p-4 text-center",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:p.message}),(0,n.jsx)(I.$,{className:"pointer-events-auto",variant:"outline",onClick:()=>{l.invalidate(e,m,(0,rm.Wq)()),d(e=>{let t={...e};return delete t[m],t})},children:o("reloadFile")})]}):(0,n.jsxs)("div",{role:"status",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),o("loadingFile")]})})]})}function d3(e){return e.replaceAll("\\","/").split("/").at(-1)??e}function d4(e,t){return e instanceof Error?e.message:t}function d6({target:e,biz:t,images:s,mobile:i,onClose:a}){let{t:l}=(0,b.Bd)("workbench"),{t:o}=(0,b.Bd)("projectFiles"),c=(0,r.useRef)(null),[d,u]=(0,r.useState)({mode:"preview",scrollTop:0}),m=(0,r.useRef)(0),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)(0),[x,v]=(0,r.useState)(()=>{let t=e&&!e.imagePaths?s.peek(e,e.path,(0,rm.Wq)()):null;return t?{status:"image",objectUrl:t}:{status:"loading"}}),[w,y]=(0,r.useState)(()=>e?.imagePaths?e.imagePaths.indexOf(e.path):0);if((0,r.useLayoutEffect)(()=>{let n;if(!e||e.imagePaths)return;let r=new AbortController,i=!0,a=(0,rm.Wq)(),o=s.get(e,e.path,a);return o?o.release:(t.get({workId:e.source.workId,cwd:e.cwd,path:e.path,imagePreviewMode:a},r.signal).then(t=>{if(!i)return;if("text"===t.kind)return void v({status:"text",content:t.content,size:t.size});let r=s.store(e,e.path,a,(0,dw.E)(t));n=r.release,v({status:"image",objectUrl:r.url})}).catch(t=>{i&&!r.signal.aborted&&(console.warn("[Pi Desk][PluginStandaloneFilePreview] 读取文件失败",{workId:e.source.workId,path:e.path,error:d4(t,l("standaloneReadFailed"))}),v({status:"error",message:d4(t,l("standaloneReadFailed"))}))}),()=>{i=!1,r.abort(),n?.()})},[t,s,g,e,l]),(0,r.useEffect)(()=>{if(!e)return;let t=e=>{e.source===c.current?.contentWindow&&"pi-desk:file-escape"===e.data&&a()};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[a,e]),!e)return null;let k=e.imagePaths?.[w]??e.path,j=(0,d0.g)(k);return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||a()},children:(0,n.jsxs)(eN.hA,{className:i?"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)(eN.YM,{className:"sr-only",children:d3(k)}),(0,n.jsxs)("section",{"data-testid":"plugin-standalone-file-preview",className:"flex size-full min-h-0 min-w-0 flex-col overflow-hidden bg-background","aria-label":l("standaloneViewer",{name:e.projectName}),children:[(0,n.jsxs)("header",{className:"flex min-h-14 shrink-0 items-center gap-3 border-b pl-3 pr-14 pt-[env(safe-area-inset-top)]",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-semibold",title:d3(k),children:d3(k)}),(0,n.jsxs)("p",{className:"truncate text-xs text-muted-foreground",title:`${e.projectName} \xb7 ${k}`,children:[e.projectName," \xb7 ",k]})]}),"markdown"===j&&"text"===x.status?(0,n.jsx)("div",{className:"flex shrink-0",role:"group","aria-label":o("markdownMode"),children:["preview","source"].map(e=>(0,n.jsx)(I.$,{size:"sm",variant:d.mode===e?"secondary":"ghost","aria-pressed":d.mode===e,onClick:()=>{d.mode!==e&&u({mode:e,scrollTop:m.current})},children:o("preview"===e?"previewMode":"sourceMode")},e))}):null]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden pb-[env(safe-area-inset-bottom)]",children:e.imagePaths?(0,n.jsx)(d5,{target:e,paths:e.imagePaths,index:w,onIndexChange:y,biz:t,images:s}):"loading"===x.status?(0,n.jsx)(d8,{}):"error"===x.status?(0,n.jsxs)("div",{className:"flex size-full flex-col items-center justify-center gap-3 p-6 text-center",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:x.message}),(0,n.jsx)(I.$,{variant:"outline",onClick:()=>{s.invalidate(e,e.path,(0,rm.Wq)()),v({status:"loading"}),f(e=>e+1)},children:l("reloadFile")})]}):"image"===x.status?(0,n.jsx)(ny.k,{mode:"inline",slides:[{src:x.objectUrl,alt:e.path}],ariaLabel:l("standaloneImage",{name:d3(e.path)})}):"markdown"===j&&"preview"===d.mode?(0,n.jsx)(dZ.n,{content:x.content,label:o("markdownPreview",{name:k}),savedScrollTop:d.scrollTop,onScroll:e=>{m.current=e}}):"html"===j?(0,n.jsx)("iframe",{ref:c,className:"block size-full border-0 bg-white",sandbox:"allow-scripts",srcDoc:(0,d1.z)(x.content),title:l("standaloneHtml",{name:e.path})}):(0,n.jsx)(dX.e,{path:e.path,content:x.content,size:x.size,savedState:p,onSaveState:(e,t)=>h(t),onEscape:a})})]})]})})}function d8(){let{t:e}=(0,b.Bd)("workbench");return(0,n.jsxs)("div",{className:"flex size-full items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),e("loadingFile")]})}var d7=s(3635),d9=s(76812),ue=s.n(d9);let ut=(0,d7.default)(()=>s.e(19991).then(s.bind(s,19991)).then(e=>e.L2FileWorkspaceView),{loadableGenerated:{webpack:()=>[19991]},ssr:!1});function us({workSession:e,runtime:t,gitRuntime:s,mobile:i,onOpenGitBranches:a,onOpenSidebar:l,children:o}){let{t:c}=(0,b.Bd)("workbench");(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let d=(0,r.useRef)(null),u=(0,E.OG)(),m=(0,r.useRef)(null),p=(0,r.useRef)(null),h=(0,r.useRef)(null),g=(0,r.useRef)(null),f=(0,r.useRef)(null),[x,v]=(0,r.useState)(!1),{workId:w}=e,y=t.getWorkspace(w),k=y?.windowOpen===!0,j=`session-chat-pane-${w}`,N=`session-file-pane-${w}`,I=y?.chatWidthPercent??50,[M]=(0,r.useState)(()=>k?I:100),z=!!(y?.tabs.length||y?.activeDiff),A=x&&!i,$=A&&k,R=t.getExpandedWorkId()===w,P=k&&($||y?.activePane==="files"),D=!P||$;(0,r.useLayoutEffect)(()=>{let e=d.current;if(!e)return;let t=new ResizeObserver(([e])=>{v((e?.contentRect.width??0)>=880)});return t.observe(e),()=>t.disconnect()},[]),(0,r.useLayoutEffect)(()=>{if(!A)return;let e=requestAnimationFrame(()=>{u.current?.setLayout({[j]:k?I:100,[N]:k?100-I:0})});return()=>cancelAnimationFrame(e)},[j,I,N,k,u,A]);let T=e=>{f.current=e};(0,r.useLayoutEffect)(()=>{let e=f.current;if(e&&("chat"===e?D:P)){let t,s;f.current=null,t="chat"===e?m.current:p.current,s="chat"===e?h.current:g.current,s?.isConnected&&t?.contains(s)&&!s.closest("[inert]")?s.focus({preventScroll:!0}):t?.querySelector("chat"===e?'textarea, [data-testid="session-files-entry"]':'[data-testid="file-workspace"]')?.focus({preventScroll:!0})}},[D,P,y?.activePane]);let O=()=>{if(!z)return;let e=t.getWorkspace(w)?.activePane==="files"?"chat":"files";T(e),"files"===e?t.showWindow(w):t.setActivePane(w,"chat")};return(0,n.jsx)("div",{ref:d,"data-testid":"session-file-layout","data-file-layout":$?"split":"single",className:"relative size-full min-h-0 min-w-0 overflow-hidden",onKeyDownCapture:e=>{"Tab"!==e.key||!e.ctrlKey||e.altKey||e.metaKey||e.repeat||e.nativeEvent.isComposing||!z||e.target instanceof Element&&e.target.closest('[role="menu"], [data-slot="app-dialog-content"]')||(e.preventDefault(),e.stopPropagation(),O())},children:(0,n.jsxs)(S.HK,{groupRef:u,className:(0,C.cn)("pi-desk-workbench-resize-group relative size-full min-h-0 min-w-0",A?[dD().panelGroup,ue().wide]:ue().single),orientation:"horizontal",disabled:!$,resizeTargetMinimumSize:{fine:8,coarse:20},onLayoutChanged:(e,s)=>{if(!$||!s.isUserInteraction)return;let n=e[j];void 0!==n&&t.setChatWidthPercent(w,n)},children:[(0,n.jsx)(S.wV,{id:j,"data-pane":"chat",defaultSize:`${M}%`,minSize:320*!!$,"aria-hidden":!D||void 0,inert:!D||void 0,className:"flex min-h-0 min-w-0 !overflow-hidden",children:(0,n.jsx)("div",{ref:m,className:"size-full min-h-0 min-w-0",onPointerDownCapture:()=>t.setActivePane(w,"chat"),onFocusCapture:e=>{h.current=e.target,t.setActivePane(w,"chat")},children:o(D)})}),(0,n.jsx)(S.WM,{id:`session-file-divider-${w}`,"aria-label":c("resizeChatFile"),"aria-hidden":!$||void 0,disabled:!$,disableDoubleClick:!0,className:(0,C.cn)("z-10 w-px cursor-col-resize bg-transparent aria-disabled:cursor-default",!$&&"hidden")}),(0,n.jsx)(S.wV,{id:N,"data-pane":"files",defaultSize:`${100-M}%`,minSize:320*!!$,maxSize:A&&!k?0:void 0,"aria-hidden":!P||void 0,inert:!P||void 0,className:"flex min-h-0 min-w-0 !overflow-hidden",children:(0,n.jsx)("div",{ref:p,className:"size-full min-h-0 min-w-0 overflow-hidden",onPointerDownCapture:()=>t.setActivePane(w,"files"),onFocusCapture:e=>{g.current=e.target,t.setActivePane(w,"files")},children:z&&!R?(0,n.jsx)(ut,{workSession:e,runtime:t,gitRuntime:s,mobile:i,presentation:A?"split":"single",onOpenGitBranches:a,onOpenSidebar:l,onHide:()=>{T("chat"),t.hideWindow(w)},onExpand:()=>t.expandWindow(w),onSwitchPane:O},`${e.sessionId}:${e.branchId}`):null})})]})})}function un({workSessions:e,runtime:t,gitRuntime:s,mobile:i,onOpenGitBranches:a,onOpenSidebar:l,onOpenTerminal:o}){let{t:c}=(0,b.Bd)("workbench");(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let d=e.find(e=>e.workId===t.getExpandedWorkId());if(!d)return null;let u=()=>{i?t.hideWindow(d.workId):t.collapseExpandedWindow()},m=()=>{let e=document.querySelector(`[data-work-id="${CSS.escape(d.workId)}"] textarea`);e&&(t.hideWindow(d.workId),requestAnimationFrame(()=>e.focus({preventScroll:!0})))};return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||u()},children:(0,n.jsxs)(eN.hA,{showCloseButton:!1,onKeyDownCapture:e=>{"Tab"!==e.key||!e.ctrlKey||e.altKey||e.metaKey||e.repeat||e.nativeEvent.isComposing||e.target instanceof Element&&e.target.closest('[role="menu"]')||(e.preventDefault(),e.stopPropagation(),m())},className:i?"inset-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(d.workId)}"]`);return e?.querySelector("[data-file-expand-trigger]")??e?.querySelector('[data-testid="session-files-entry"]')??!1},children:[(0,n.jsx)(eN.YM,{className:"sr-only",children:c("fileViewer",{name:d.projectName})}),(0,n.jsx)(ut,{workSession:d,runtime:t,gitRuntime:s,mobile:i,presentation:i?"single":"expanded",onOpenGitBranches:a,onOpenSidebar:()=>{t.collapseExpandedWindow(),l(d.workId)},onSwitchPane:m,onOpenTerminal:o,onHide:()=>t.hideWindow(d.workId),onExpand:u},`${d.workId}:${d.sessionId}:${d.branchId}`)]})})}var ur=s(93320);async function ui(e,t,s){try{let n=await e.get({...t,imagePreviewMode:"compressed"},s);if("image"!==n.kind)throw Error("该文件不是可展示的图片");return(0,dw.E)(n)}catch(e){if(e instanceof ur.aw&&"errors:fileMissing"===e.errorKey)return null;throw e}}var ua=s(72114),ul=s(31761),uo=s(50479),uc=s(35989);let ud=[];function uu(e,t){let s=t.trim().toLocaleLowerCase();return s?e.filter(e=>e.toLocaleLowerCase().includes(s)):[...e]}function um({target:e,runtime:t,mobile:s,onClose:i}){let{t:a}=(0,b.Bd)("workbench"),{locale:l}=(0,eQ.i)();(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let o=(0,X.G)(),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(e?.repositoryRoot!==null),[p,h]=(0,r.useState)(""),[g,f]=(0,r.useState)(()=>({repositoryRoot:null,overrides:new Map})),[x,w]=(0,r.useState)(null),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(""),[S,E]=(0,r.useState)(null),[M,z]=(0,r.useState)(null),$=t.getWorkspace(e?.cwd??null),R=$?.heads.repositories??ud,P=e?null!==e.repositoryRoot&&R.some(t=>t.root===e.repositoryRoot)?e.repositoryRoot:R.find(e=>""===e.root)?.root??R[0]?.root??null:null,D=c??P;(0,r.useEffect)(()=>{e&&t.refreshHeads(e.cwd)},[t,e]),(0,r.useEffect)(()=>{if(!e||null===D||$?.heads.status!=="ready")return;let s=R.find(e=>e.root===D);s?.state==="ready"&&t.loadBranches(e.cwd,D)},[D,R,t,e,$?.heads.status]);let T=R.find(e=>e.root===D)??null,O=null===D?null:$?.branches.get(D)??null,L=O?.data??null,F=null!==D&&!!$?.branchOperations.has(D),B=(0,r.useMemo)(()=>uu(L?.local??[],p),[L?.local,p]),q=(0,r.useMemo)(()=>uu(L?.remote??[],p),[L?.remote,p]),_=(0,r.useMemo)(()=>uu(L?.recent??[],p),[L?.recent,p]),W=(0,r.useMemo)(()=>(0,uc.oY)(B),[B]),Y=(0,r.useMemo)(()=>(0,uc.oY)(q),[q]),V=L?.head.type==="branch"?L.head.name:null,H=(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 K=e=>{E(e),N(""),k(!0),w(null),z(null)},G=async(e,t)=>{z(null);try{await e(),o.success(t),i()}catch(e){z(e instanceof Error?e.message:a("gitOperationFailed"))}},J=R.length>1,Q=1===R.length?a("repositorySummary",{name:(0,uc.Hj)(e.projectName,R[0].root),branch:"ready"===R[0].state?(0,uc.ws)(R[0].head):a("repositoryUnavailable")}):R.length>1?a("repositoryCount",{count:R.length}):a("readingRepos"),Z=(s,r,i=s.name,l=0)=>{let o="local"===s.type&&s.name===V,c=x?.type===s.type&&x.name===s.name;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{type:"button","data-testid":"recent"===r?`git-branch-recent-${s.name}`:`git-branch-${s.type}-${s.name}`,className:(0,C.cn)("grid min-h-9 w-full cursor-pointer grid-cols-[1rem_minmax(0,1fr)_auto] items-center gap-2 rounded-lg pr-2 text-left outline-none hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-ring",o&&"font-medium text-foreground",c&&"bg-accent"),style:{paddingLeft:`${8+16*l}px`},title:s.name,onClick:()=>w(c?null:s),children:[(0,n.jsx)("span",{className:"text-muted-foreground",children:o?(0,n.jsx)(ep.A,{className:"size-4 text-foreground"}):"remote"===s.type?(0,n.jsx)(ua.A,{className:"size-3.5"}):(0,n.jsx)(ul.A,{className:"size-3.5"})}),(0,n.jsx)("span",{className:"truncate font-mono text-sm",children:i}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:o?a("current"):"recent"===r?a("recent"):""})]}),c?(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 border-l-2 border-border py-2 pl-2",style:{marginLeft:`${32+16*l}px`},children:[o?null:(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",disabled:F,onClick:()=>{null!==D&&!F&&G(()=>t.replaceBranch(e.cwd,D,s),a("remote"===s.type?"checkedOut":"switchedBranch",{name:s.name}))},children:a("remote"===s.type?"checkoutRemote":"switchGitBranch")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",disabled:F,onClick:()=>K(s),children:a("branchFromHere")})]}):null]},`${r}:${s.type}:${s.name}`)},ee=(e,t)=>{let s=`${e}:${t}`;return(g.repositoryRoot===D?g.overrides.get(s):void 0)??H.has(s)},et=(e,t,s=0)=>e.map(e=>{if(0===e.children.length&&e.branchName)return Z({type:t,name:e.branchName},t,e.name,s);let r=`${t}:${e.path}`,i=!!p.trim()||ee(t,e.path);return(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{type:"button","data-testid":`git-branch-group-${t}-${e.path}`,"aria-expanded":i,className:"grid min-h-9 w-full cursor-pointer grid-cols-[1rem_1rem_minmax(0,1fr)] items-center gap-2 rounded-lg pr-2 text-left text-muted-foreground outline-none hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",style:{paddingLeft:`${8+16*s}px`},title:e.path,onClick:()=>((e,t)=>{if(p.trim())return;let s=`${e}:${t}`,n=ee(e,t);f(e=>{let t=e.repositoryRoot===D?new Map(e.overrides):new Map;return t.set(s,!n),{repositoryRoot:D,overrides:t}})})(t,e.path),children:[(0,n.jsx)(e7.A,{className:(0,C.cn)("size-3 transition-transform",i&&"rotate-90")}),i?(0,n.jsx)(uo.A,{className:"size-4 text-muted-foreground"}):(0,n.jsx)(eP.A,{className:"size-4 text-muted-foreground"}),(0,n.jsx)("span",{className:"truncate font-mono text-sm",children:e.name})]}),i?et(e.children,t,s+1):null]},r)});return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>!e&&i(),children:(0,n.jsxs)(eN.hA,{"data-testid":"git-branch-picker",showCloseButton:!1,finalFocus:!1,className:"h-[min(40rem,calc(100dvh-2rem))] max-w-[45rem] gap-0",children:[(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 border-b px-3",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{children:a("gitBranches")}),(0,n.jsx)(eN.uX,{className:"truncate text-xs",children:Q})]}),(0,n.jsx)(I.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":a("refreshBranches"),disabled:$?.heads.status==="loading",onClick:()=>void t.refreshHeads(e.cwd),children:(0,n.jsx)(es.A,{className:(0,C.cn)("size-4",$?.heads.status==="loading"&&"animate-spin")})}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:i,children:a("close")})]}),(0,n.jsxs)("div",{className:(0,C.cn)("grid min-h-0 flex-1",J&&!s?"grid-cols-[220px_minmax(0,1fr)]":"grid-cols-1"),children:[!J||s&&u?null:(0,n.jsxs)("aside",{className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto border-r bg-sidebar p-2 max-sm:border-r-0",children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("repositories")}),R.map(t=>{let s=(0,uc.Hj)(e.projectName,t.root),r=t.root===D;return(0,n.jsxs)("button",{"data-testid":`git-branch-picker-repository-${t.root||"root"}`,type:"button",className:(0,C.cn)("grid min-h-12 w-full grid-cols-[minmax(0,1fr)_auto] items-center gap-2 rounded-lg px-2 text-left hover:bg-muted/70",r&&"bg-accent text-accent-foreground"),onClick:()=>{var e;d(e=t.root),m(!0),h(""),f({repositoryRoot:e,overrides:new Map}),w(null),k(!1),E(null),z(null)},children:[(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("strong",{className:"block truncate text-sm font-medium",children:s}),(0,n.jsx)("span",{className:"mt-1 block truncate font-mono text-xs text-muted-foreground",children:t.root||"."})]}),(0,n.jsx)("span",{className:"flex flex-col items-end gap-1 text-xs text-muted-foreground",children:(0,n.jsx)("span",{className:"max-w-28 truncate",children:"ready"===t.state?(0,uc.ws)(t.head):a("unavailable")})})]},t.root)})]}),s&&J&&!u?null:(0,n.jsxs)("section",{className:"flex min-h-0 min-w-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-13 shrink-0 items-center gap-2 border-b px-3",children:[s&&J?(0,n.jsx)(I.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":a("backRepositories"),onClick:()=>m(!1),children:(0,n.jsx)(A.A,{className:"size-4"})}):null,(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("p",{className:"truncate text-sm font-semibold",children:[T?(0,uc.Hj)(e.projectName,T.root):a("chooseRepository"),T?.state==="ready"?` \xb7 ${(0,uc.ws)(T.head)}`:""]}),(0,n.jsx)("p",{className:"mt-1 break-words font-mono text-xs text-muted-foreground",children:T?.root||"."})]}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",disabled:T?.state!=="ready"||F,onClick:()=>K(null),children:[(0,n.jsx)(U.A,{className:"size-3.5"})," ",a("createBranch")]})]}),$?.heads.status==="error"?(0,n.jsx)("p",{className:"border-b bg-muted px-3 py-2 text-sm text-destructive",children:$.heads.error}):null,M?(0,n.jsx)("p",{className:"border-b bg-muted px-3 py-2 text-sm text-destructive",children:M}):null,(0,n.jsx)("div",{className:"flex shrink-0 items-center gap-2 border-b p-2",children:y?(0,n.jsxs)("form",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",onSubmit:s=>{let n;s.preventDefault(),(n=j.trim())&&null!==D&&!F&&G(()=>t.addBranch(e.cwd,D,n,S),a("branchCreated",{name:n}))},children:[(0,n.jsx)(em.p,{autoFocus:!0,value:j,onChange:e=>N(e.currentTarget.value),placeholder:a("newBranchName"),"aria-label":a("newBranchName"),className:"min-w-[12rem] flex-1"}),(0,n.jsxs)(I.$,{type:"submit",size:"sm",disabled:!j.trim()||F,children:[F?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):null,a("createAndSwitch")]}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>{k(!1),E(null)},children:a("cancel")})]}):(0,n.jsx)(em.p,{value:p,onChange:e=>h(e.currentTarget.value),placeholder:a("searchBranches"),"aria-label":a("searchBranches")})}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-2",children:T?.state==="unavailable"?(0,n.jsx)("p",{className:"p-5 text-center text-xs text-destructive",children:(0,eJ.fD)(T.message,l)}):O?.status!=="loading"||L?O?.status==="error"?(0,n.jsxs)("div",{className:"flex min-h-24 flex-col items-center justify-center gap-2 text-center text-xs text-destructive",children:[(0,n.jsx)("p",{children:O.error}),null!==D?(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void t.loadBranches(e.cwd,D),children:a("retry")}):null]}):L?(0,n.jsxs)("div",{className:"space-y-3",children:[_.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("recentlyUsed")}),_.map(e=>Z({type:"local",name:e},"recent"))]}):null,B.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("localBranches")}),et(W,"local")]}):null,q.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("remoteBranches")}),et(Y,"remote")]}):null,0===_.length&&0===B.length&&0===q.length?(0,n.jsx)("p",{className:"p-5 text-center text-xs text-muted-foreground",children:a("noBranchMatches")}):null]}):null:(0,n.jsxs)("div",{className:"flex min-h-24 items-center justify-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"})," ",a("loadingBranches")]})})]})]})]})})}function up(e,t){return e instanceof DOMException&&"AbortError"===e.name?t:e instanceof Error?e.message:t}class uh{constructor(e,t){this.biz=e,this.onRepositoryChanged=t,this.listeners=new Set,this.workspaces=new Map,this.projectRefs=new Map,this.revision=0,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.getRevision=()=>this.revision}getWorkspace(e){return e?this.workspaces.get(e)??null:null}reconcileWorkSessions(e,t,s=[]){let n=new Map,r=t?e.find(e=>e.workId===t)??null:null;for(let t of(r&&n.set(r.cwd,{workId:r.workId,cwd:r.cwd}),e))n.has(t.cwd)||n.set(t.cwd,{workId:t.workId,cwd:t.cwd});for(let e of s)n.has(e.cwd)||n.set(e.cwd,{...e,readOnly:!0});if(n.size!==this.projectRefs.size||[...n].some(([e,t])=>this.projectRefs.get(e)?.workId!==t.workId||this.projectRefs.get(e)?.readOnly!==t.readOnly)){for(let[e,t]of(this.projectRefs.clear(),n))this.projectRefs.set(e,t);for(let[e,t]of this.workspaces)n.has(e)||(this.abortRequests(t),this.workspaces.delete(e))}}ensureSnapshot(e){let t=this.workspaceFor(e);return"ready"===t.snapshot.status||"loading"===t.snapshot.status?Promise.resolve():this.loadSnapshot(e,!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:dV("gitNoProjectStatus")},this.publish();return}let n=new AbortController,r={};t.headsRequest={controller:n,token:r},t.lastHeadsStartedAt=Date.now(),t.heads={...t.heads,status:"loading",error:null},this.publish();try{let i=await this.biz.getHeads({workId:s.workId,cwd:e},n.signal);if(t.headsRequest?.token!==r)return;t.headsRequest=null,t.heads={status:"ready",repositories:i.repositories,error:null},this.publish()}catch(e){if(t.headsRequest?.token!==r||(t.headsRequest=null,n.signal.aborted))return;t.heads={...t.heads,status:"error",error:up(e,dV("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:dV("gitNoProjectBranches")}),this.publish();return}s.branchRequests.get(t)?.controller.abort();let r=new AbortController,i={};s.branchRequests.set(t,{controller:r,token:i}),s.branches.set(t,{status:"loading",data:s.branches.get(t)?.data??null,error:null}),this.publish();try{let a=await this.biz.listBranches({workId:n.workId,cwd:e,repositoryRoot:t},r.signal);if(s.branchRequests.get(t)?.token!==i)return;s.branchRequests.delete(t),s.branches.set(t,{status:"ready",data:a,error:null}),this.publish()}catch(e){if(s.branchRequests.get(t)?.token!==i||(s.branchRequests.delete(t),r.signal.aborted))return;s.branches.set(t,{status:"error",data:null,error:up(e,dV("gitBranchesReadFailed"))}),this.publish()}}async replaceBranch(e,t,s){let n=this.requireWritableProject(e),r=this.workspaceFor(e);if(!r.branchOperations.has(t)){r.branchOperations.add(t),this.publish();try{let i=await this.biz.replaceBranch({...n,repositoryRoot:t,target:s});this.applyRepository(r,i.repository),this.clearBranches(r,t),this.onRepositoryChanged(e,t)}finally{r.branchOperations.delete(t),this.publish()}}}async addBranch(e,t,s,n){let r=this.requireWritableProject(e),i=this.workspaceFor(e);if(!i.branchOperations.has(t)){i.branchOperations.add(t),this.publish();try{let a=await this.biz.addBranch({...r,repositoryRoot:t,name:s,startPoint:n});this.applyRepository(i,a.repository),this.clearBranches(i,t),this.onRepositoryChanged(e,t)}finally{i.branchOperations.delete(t),this.publish()}}}getDiff(e,t,s,n){return this.biz.getDiff({...this.requireProject(e),repositoryRoot:t,path:s},n)}dispose(){for(let e of this.workspaces.values())this.abortRequests(e);this.workspaces.clear(),this.projectRefs.clear(),this.listeners.clear()}async loadSnapshot(e,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:dV("gitNoProjectStatus")},this.publish();return}s.snapshotRequest?.controller.abort();let r=new AbortController,i={};s.snapshotRequest={controller:r,token:i},s.snapshot={status:"loading",repositories:s.snapshot.repositories,error:null},this.publish();try{let t=await this.biz.get({workId:n.workId,cwd:e},r.signal);if(s.snapshotRequest?.token!==i)return;s.snapshotRequest=null,s.snapshot={status:"ready",repositories:t.repositories,error:null};let a=new Set(t.repositories.map(e=>e.root));for(let e of(t.repositories.length>0&&!a.has("")&&a.add(""),[...s.expandedRepositories]))a.has(e)||s.expandedRepositories.delete(e);this.publish()}catch(e){if(s.snapshotRequest?.token!==i||(s.snapshotRequest=null,r.signal.aborted))return;s.snapshot={status:"error",repositories:s.snapshot.repositories,error:up(e,dV("gitStatusReadFailed"))},this.publish()}}requireProject(e){let t=this.projectRefs.get(e);if(!t)throw Error(dV("gitNoProjectOperation"));return{workId:t.workId,cwd:t.cwd}}requireWritableProject(e){if(this.projectRefs.get(e)?.readOnly)throw Error(dV("gitNoProjectOperation"));return this.requireProject(e)}applyRepository(e,t){e.headsRequest?.controller.abort(),e.headsRequest=null,e.snapshotRequest?.controller.abort(),e.snapshotRequest=null;let s={root:t.root,state:t.state,head:t.head},n=[...e.heads.repositories],r=n.findIndex(e=>e.root===t.root);if(r>=0?n[r]=s:n.push(s),e.heads={status:"ready",repositories:n,error:null},e.lastHeadsStartedAt=Date.now(),"idle"===e.snapshot.status)return;let i="loading"===e.snapshot.status,a=[...e.snapshot.repositories],l=a.findIndex(e=>e.root===t.root);l>=0?a[l]=t:a.push(t),e.snapshot={status:"ready"===e.snapshot.status?"ready":"idle",repositories:a,error:null},i&&this.refreshSnapshot(e.cwd)}abortRequests(e){for(let t of(e.headsRequest?.controller.abort(),e.headsRequest=null,e.snapshotRequest?.controller.abort(),e.snapshotRequest=null,e.branchRequests.values()))t.controller.abort();e.branchRequests.clear()}clearBranches(e,t){e.branchRequests.get(t)?.controller.abort(),e.branchRequests.delete(t),e.branches.delete(t)}workspaceFor(e){let t=this.workspaces.get(e);if(t)return t;let s={cwd:e,heads:{status:"idle",repositories:[],error:null},headsRequest:null,lastHeadsStartedAt:0,snapshot:{status:"idle",repositories:[],error:null},snapshotRequest:null,branches:new Map,branchRequests:new Map,layout:"directory",changesOnly:!1,expandedRepositories:new Set,branchOperations:new Set};return this.workspaces.set(e,s),s}publish(){for(let e of(this.revision+=1,[...this.listeners]))e()}}var ug=s(24985);let uf=ug.y2,ux=a.Ik({workId:dN.eW,cwd:dN.ik}).strict(),ub=ug.Ww,uv=ug.cP,uw=ug.zp,uy=ug.u2;a.Ik({repositories:a.YO(uy).max(uf)}).strict();let uk=ux.extend({repositoryRoot:ub}).strict(),uj=ug.zt,uN=ux.extend({repositoryRoot:ub,target:uj}).strict(),uI=ux.extend({repositoryRoot:ub,name:uv,startPoint:uj.nullable()}).strict(),uS=a.Ik({repository:uw}).strict(),uC=ux.extend({repositoryRoot:ub,path:s0._g}).strict();var uE=s(68269);let uM=Object.freeze({messages:[],temporaryMessages:[],runtime:{extensionMode:"normal",presentationMode:"normal",initializationError:null,queues:{steering:[],followUp:[]},model:null,capabilityMode:null,contextUsage:null,plugins:{}}});function uz(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 uA=s(82639);let u$="messages",uR="source",uP="drafts",uD="outbox",uT="pi-super-chat",uO=null,uL=null;function uF(e){return Error((0,ed.B)({msg:uA.n["zh-CN"].common[e],i18n:{key:`common:${e}`}}))}function uB(e,t){e.objectStoreNames.contains(t)||e.createObjectStore(t,{keyPath:["sessionId","branchId"]})}function uq(){return new Promise((e,t)=>{let s=indexedDB.open(uT,2),n=!1,r=window.setTimeout(()=>{i(uF("dbOpenTimeout"))},1e4),i=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("upgradeneeded",()=>{let e=s.result;e.objectStoreNames.contains(u$)||e.createObjectStore(u$,{keyPath:["sessionId","branchId","index"]}).createIndex(uR,["sessionId","branchId"],{unique:!1}),uB(e,uP),uB(e,uD)},{once:!0}),s.addEventListener("blocked",()=>{i(uF("dbOpenBlocked"))},{once:!0}),s.addEventListener("success",()=>{let t=s.result;n?t.close():(n=!0,window.clearTimeout(r),e(t))},{once:!0}),s.addEventListener("error",()=>i(s.error??uF("dbOpenFailed")),{once:!0})})}async function u_(){try{return await uq()}catch(e){if(!("object"==typeof e&&null!==e&&"name"in e&&"VersionError"===e.name))throw e;return console.warn("[Pi Desk][ChatIndexedDB] 本地数据库版本高于当前版本,清空全部本地聊天数据后重建",{databaseName:uT,requestedVersion:2}),await new Promise((e,t)=>{let s=indexedDB.deleteDatabase(uT),n=!1,r=window.setTimeout(()=>{i(uF("dbDeleteTimeout"))},1e4),i=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("blocked",()=>{i(uF("dbDeleteBlocked"))},{once:!0}),s.addEventListener("success",()=>{n||(n=!0,window.clearTimeout(r),e())},{once:!0}),s.addEventListener("error",()=>i(s.error??uF("dbDeleteFailed")),{once:!0})}),uq()}}function uW(){return uL?Promise.resolve(uL):uO||(uO=u_().then(e=>(uL=e,e.addEventListener("versionchange",()=>{e.close(),uL===e&&(uL=null,uO=null),console.warn("[Pi Desk][ChatIndexedDB] 数据库版本已变化,当前连接已关闭")}),e)).catch(e=>{throw uO=null,e}))}function uY(e){return new Promise((t,s)=>{e.addEventListener("success",()=>t(e.result),{once:!0}),e.addEventListener("error",()=>s(e.error??uF("dbRequestFailed")),{once:!0})})}function uV(e,t,s){let n=e.target;return n?.error??t.error??Error(s)}function uU(e){return new Promise((t,s)=>{e.addEventListener("complete",()=>t(),{once:!0}),e.addEventListener("abort",t=>s(uV(t,e,uF("dbTransactionAborted").message)),{once:!0}),e.addEventListener("error",t=>s(uV(t,e,uF("dbTransactionFailed").message)),{once:!0})})}let uH=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:uE.ao,summary:uE.lV,detail:uE.wI.optional()}).strict();function uK(e,t){return uH.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 uG(e){let t=uH.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");uE.Y2.parse(t.summary),void 0!==t.detail&&uE.$f.parse(t.detail)}return uE.wR.parse({location:{index:t.index,entryId:t.entryId},fixed:t.fixed,summary:t.summary,...void 0===t.detail?{}:{detail:t.detail}})}function uJ(e,t){e.delete(IDBKeyRange.bound([t.sessionId,t.branchId,0],[t.sessionId,t.branchId,Number.MAX_SAFE_INTEGER]))}let uQ=a.Yj().max(65536),uX=a.Ik({id:a.Yj().uuid(),title:uQ,expiresAt:a.ai().int().nonnegative().nullable()}),uZ=a.gM("method",[uX.extend({method:a.eu("confirm"),message:uQ}).strict(),uX.extend({method:a.eu("select"),options:a.YO(uQ).max(200)}).strict(),uX.extend({method:a.eu("input"),placeholder:uQ}).strict(),uX.extend({method:a.eu("editor"),prefill:uQ}).strict()]),u0=a.Ik({requests:a.YO(uZ).max(32),statuses:a.g1(a.Yj().max(128),uQ),widgets:a.g1(a.Yj().max(128),a.Ik({lines:a.YO(uQ).max(200),placement:a.k5(["aboveEditor","belowEditor"])}).strict())}).strict(),u1=a.Ik({id:a.Yj().uuid(),value:a.KC([a.zM(),uQ,a.ch()])}).strict(),u2=a.gM("type",[a.Ik({type:a.eu("snapshot"),snapshot:u0}).strict(),a.Ik({type:a.eu("notify"),message:uQ,level:a.k5(["info","warning","error"])}).strict(),a.Ik({type:a.eu("editor_text"),text:uQ,mode:a.k5(["replace","paste"])}).strict()]),u5=a.Ik({source:ll.R}).strict(),u3=a.Ik({}).strict(),u4=Object.freeze({subscribe:(0,l.Vc)({path:"pi/ui/subscribe",inputSchema:u5,outputSchema:u0}),unsubscribe:(0,l.Vc)({path:"pi/ui/unsubscribe",inputSchema:u5,outputSchema:u3}),respond:(0,l.Vc)({path:"pi/ui/respond",inputSchema:u5.extend({response:u1}).strict(),outputSchema:u3}),event:(0,l._G)({path:"pi/ui/event",bodySchema:u5.extend({event:u2}).strict()})});function u6(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}class u8{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(u4.event,({source:e,event:t})=>{let s=this.records.get(u6(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(u6));for(let[e,s]of this.records)!t.has(e)&&(this.records.delete(e),this.connected&&this.socket.request(u4.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(u4.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:dV("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(dq.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:dV("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=u6(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(u6(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(u4.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:dV("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 u7=Object.freeze({...uM,syncStatus:"loading"});function u9(e){return uE.Pi.parse({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId})}function me(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function mt(e,t){return e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}let ms={text:"",images:[]};function mn(e){return[e.sessionId,e.branchId]}function mr(e,t){return{sessionId:e.sessionId,branchId:e.branchId,text:t.text,images:t.images}}function mi(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 ma(e,t){return t?{text:[e.text,t.text].filter(e=>e.trim()).join("\n\n"),images:[...e.images,...t.images]}:e}var ml=s(67837);let mo=new Set(["image/jpeg","image/png","image/webp","image/gif","image/bmp"]),mc=new Set(["image/jpeg","image/png","image/webp","image/gif"]),md=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function mu(e){return e.type.toLowerCase().split(";")[0]??""}async function mm(e){let t;try{t=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{throw Error(dV("imageDecodeFailed"))}if(!Number.isSafeInteger(t.width)||t.width<=0||t.height<=0)throw t.close(),Error(dV("imageInvalidDimensions"));return{bitmap:t,width:t.width,height:t.height}}function mp(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 mh(e,t,s,n,r){let i=document.createElement("canvas");i.width=t,i.height=s;let a=i.getContext("2d");if(!a)throw Error(dV("canvasUnavailable"));return a.drawImage(e,0,0,t,s),new Promise((e,t)=>{i.toBlob(s=>s?e(s):t(Error(dV("imageCompressFailed"))),n,r)})}async function mg(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(md.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 mf(e){let t=mu(e);if(!mo.has(t))throw Error(dV("imageTypeUnsupported"));let s=await mm(e);return s.bitmap.close(),{blob:e,mimeType:t,width:s.width,height:s.height,optimized:"image/gif"===t}}async function mx(e){if(e.optimized){if(e.blob.size>0xa00000)throw Error(dV("singleImageLimit"));return e}let t=await mm(e.blob);try{var s;let n=mp(t.width,t.height,2560),r=(s=e.mimeType,"image/jpeg"===s?"image/jpeg":"image/webp"),i=e.blob.size>5242880?.85:"image/jpeg"===r?.9:.92,a=await mh(t.bitmap,n.width,n.height,r,i),l=n.width,o=n.height,c=l!==t.width||o!==t.height,d="image/jpeg"===e.mimeType?await mg(e.blob):null,u="image/jpeg"===e.mimeType&&(null===d||d.width!==t.width||d.height!==t.height),m=mc.has(e.mimeType)&&!u;if(!c&&m&&a.size>=.9*e.blob.size&&(a=e.blob,l=t.width,o=t.height),a.size>0xa00000){let e=mp(t.width,t.height,2048);a=await mh(t.bitmap,e.width,e.height,r,.82),l=e.width,o=e.height}if(a.size>0xa00000)throw Error(dV("compressedImageTooLarge"));let p=mu(a);if(!mc.has(p))throw Error(dV("compressedTypeUnsupported"));return{blob:a,mimeType:p,width:l,height:o,optimized:!0}}finally{t.bitmap.close()}}async function mb(e){if(!e.optimized)throw Error(dV("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 mv(e,t,s=e.optimized?"ready":"optimizing"){return{...e,localId:(0,ml.y)(),objectUrl:URL.createObjectURL(e.blob),name:t,status:s,error:null}}function mw(e){URL.revokeObjectURL(e.objectUrl)}function my(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function mk(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 mj(e,t){return e instanceof Error&&e.message?e.message:t}function mN(e,t){return[e,t].filter(e=>e.trim()).join("\n\n")}function mI(e,t,s){return`${my(e)}\u0000temp\u0000${t}\u0000${s}`}function mS(e,t,s){return`${my(e)}\u0000entry\u0000${t}\u0000${s}`}function mC(e){for(let t of e)mw(t)}var mE=s(63273),mM=s(15104),mz=s(11039),mA=s(97906),m$=s(94411);function mR(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function mP(e){return e.trim().toLocaleLowerCase()}let mD=["title","user"],mT=[{value:"title",label:"scopeTitle"},{value:"user",label:"scopeUser"},{value:"assistant",label:"scopeAssistant"},{value:"sessionId",label:"Session ID"}];function mO(e,t,s){return"title"===e?s("scopeTitle"):"sessionId"===e?"Session ID":s("user"===e?"scopeUserMatches":"scopeAssistantMatches",{count:t})}function mL(e){switch(e){case"user":case"assistant":case"title":return"bg-muted text-foreground";case"sessionId":return"bg-muted text-muted-foreground"}}function mF(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 mB({scope:e,className:t}){switch(e){case"user":return(0,n.jsx)(mE.A,{className:t});case"assistant":return(0,n.jsx)(eD.A,{className:t});case"title":return(0,n.jsx)(mM.A,{className:t});case"sessionId":return(0,n.jsx)(mz.A,{className:t})}}function mq(e,t,s="bg-primary/20 text-foreground"){if(!t)return e;let r=e.toLocaleLowerCase(),i=[],a=0,l=r.indexOf(t);for(;l>=0;){l>a&&i.push(e.slice(a,l));let o=l+t.length;i.push((0,n.jsx)("mark",{className:`rounded-sm px-px ${s}`,children:e.slice(l,o)},`${l}-${o}`)),a=o,l=r.indexOf(t,a)}return a<e.length&&i.push(e.slice(a)),i.length?i:e}function m_({open:e,pickerMode:t,pickerView:s,pickerCwd:i,directories:a,ignoredDirectories:l,directoryBrowser:o,historySessions:c,replacementTarget:d,unavailableSessionIds:u,error:m,loading:p,creatingCwd:h,replacingSessionId:g,updatingIgnoreCwd:f,onOpenChange:x,onBack:v,onSearchHistory:w,onListSessionUserMessages:y,onRefresh:k,onOpenIgnoredDirectories:j,onOpenDirectoryBrowser:N,onNavigateDirectory:S,onSelectBrowserDirectory:C,onReplaceDirectoryIgnore:E,onSelectDirectory:M,onSelectSession:z}){let{t:$}=(0,b.Bd)("workbenchPicker"),{locale:R,timeZone:P}=(0,eQ.i)(),D=(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]),[T,O]=(0,r.useState)(""),[L,F]=(0,r.useState)(mD),[B,q]=(0,r.useState)(""),[_,W]=(0,r.useState)(null),Y=(0,r.useRef)(""),V=(0,r.useRef)(0),U=(0,r.useRef)(null),H=null!==h||null!==g||null!==f,K=(0,r.useMemo)(()=>new Set(u),[u]),G=mP(T),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),Q=/^(?:[A-Za-z]:[\\/]|[\\/]{2}|\/)/.test(J),X="ignored"===s?l:a,Z=X.filter(e=>!G||mP(`${mR(e.cwd)} ${e.cwd}`).includes(G)),ee=(o?.directories??[]).filter(e=>!G||mP(`${e.name} ${e.cwd}`).includes(G));(0,r.useEffect)(()=>{O(""),F(mD),q(""),Y.current=""},[e,t,i,s]);let et=`${G}\u0000${L.join("\0")}`;(0,r.useEffect)(()=>{if("history"!==s||!G||et===Y.current)return;let e=window.setTimeout(()=>{Y.current=et,w(G,L)},300);return()=>window.clearTimeout(e)},[et,w,s,G,L]),(0,r.useEffect)(()=>{V.current+=1,U.current?.abort(),U.current=null,W(null)},[e,i,s,G]),(0,r.useEffect)(()=>()=>{U.current?.abort()},[]);let en=async(e,t,s,n)=>{if(!i)return;let r=++V.current;U.current?.abort();let a=new AbortController;U.current=a,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:i,sessionId:e,query:t,page:{index:s,size:20}},a.signal);if(V.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(V.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{U.current===a&&(U.current=null)}},er=e=>{if(_?.sessionId===e.sessionId){V.current+=1,U.current?.abort(),U.current=null,W(null);return}let t=e.matches?.some(e=>"user"===e.scope)?G:"";en(e.sessionId,t,1,!1)},ei="ignored"===s?$("ignoredRestoreTitle"):"browser"===s?$("browseOtherTitle"):"replace"===t?$("replaceTitle"):$("createTitle"),ea="ignored"===s?$("ignoredRestoreDescription"):"browser"===s?$("browseDescription"):"replace"===t?d?$("replaceDescription",{project:d.projectName,session:d.sessionTitle??$("newSession")}):$("replaceMissingDescription"):$("createDescription"),el="history"===s?$("searchHistory"):"browser"===s?$("searchBrowser"):"ignored"===s?$("searchIgnored"):$("searchProjects"),eo="history"===s?c.length:"browser"===s?o?.directories.length??0:X.length,ec=p&&("browser"===s?null===o:0===eo),ed="history"===s?$("currentProject",{path:i??""}):"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"),ep=e=>{O(""),q(""),S(e)},eg=()=>{p||H||!Q||(O(""),S(J))};return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{(e||!H)&&x(e)},children:(0,n.jsxs)(eN.hA,{className:"h-[min(44rem,calc(100dvh-2rem))] max-w-[45rem]",showCloseButton:!H,finalFocus:!1,children:[(0,n.jsx)(eN.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:["directories"!==s?(0,n.jsx)("button",{type:"button",disabled:H,onClick:v,"aria-label":$("backFolders"),title:$("backFolders"),className:(0,I.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(A.A,{className:"size-4"})}):(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:(0,n.jsx)(eP.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{children:ei}),(0,n.jsx)(eN.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)(uo.A,{className:"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{value:B,onChange:e=>q(e.target.value),onKeyDown:e=>{"Enter"===e.key&&Q&&(e.preventDefault(),eg())},placeholder:$("pastePath"),"aria-label":$("fullPath"),disabled:p||H,className:"pl-9"})]}),(0,n.jsx)("button",{"data-testid":"workbench-picker-open-directory-path",type:"button",disabled:p||H||!Q,onClick:eg,title:Q?$("openTyped"):$("enterAbsolute"),className:(0,I.r)({variant:"outline"}),children:$("open")})]}),(0,n.jsx)("p",{className:"mt-1.5 px-0.5 text-sm text-muted-foreground",children:B.trim()&&!Q?$("absoluteExample"):$("pasteHint")})]}):null,(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(eh.A,{className:"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{value:T,onChange:e=>O(e.target.value),placeholder:el,"aria-label":el,disabled:H,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")}),mT.map(e=>{let t=L.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:H||t&&1===L.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)(eN._Y,{className:"max-h-none min-h-0",children:(0,n.jsxs)("div",{className:"p-2 sm:p-3","aria-busy":p||H,"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===d?(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,ec?(0,n.jsxs)("div",{className:"flex min-h-36 flex-col items-center justify-center gap-3 text-center text-sm text-muted-foreground",children:[(0,n.jsx)(es.A,{className:"size-5 animate-spin"}),(0,n.jsx)("p",{children:eu})]}):"history"===s?0===c.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:c.length})}):null,(0,n.jsx)("div",{className:"divide-y",children:c.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,D.format(t))}),i=d?.sessionId===e.sessionId,a=K.has(e.sessionId),l=g===e.sessionId,o=null===d,c=H||i||a||o,u=_?.sessionId===e.sessionId?_:null,m=e.matches??[],p=m.filter(e=>"title"!==e.scope),h=m.find(e=>"user"===e.scope),f=null===u&&p.length>0,x=`workbench-picker-user-message-panel-${e.sessionId}`,b=l?$("replacing"):i?$("current"):a?$("alreadyUsed"):o?$("targetUnavailable"):$("replace"),v=i?$("currentBound"):a?$("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)(mA.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)?mq(s,G,mF("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:H,"aria-label":w,"aria-expanded":null!==u,"aria-controls":x,onClick:()=>er(e),title:w,className:(0,I.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(eY.A,{className:`size-4 transition-transform${u?" rotate-180":""}`})}):null,(0,n.jsx)("button",{"data-testid":`workbench-picker-replace-${e.sessionId}`,type:"button",disabled:c,onClick:()=>z(e.sessionId),title:v,className:(0,I.r)({variant:"outline"}),children:l?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):b})]}),f?(0,n.jsx)("div",{className:"mb-2 ml-6 min-w-0 space-y-1.5 overflow-hidden",children:p.map(t=>{let s,r="user"===t.scope,i=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(mB,{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 ${mL(t.scope)}`,children:mO(t.scope,t.count,$)}),null!==t.timestampMs?(0,n.jsx)("span",{className:"truncate text-muted-foreground",children:(s=t.timestampMs,D.format(s))}):null]}),(0,n.jsx)("p",{className:"mt-1 line-clamp-2 break-words text-sm leading-5 text-foreground",children:mq(t.preview,G,mF(t.scope))})]})]}),a=`flex w-full max-w-full min-w-0 items-start gap-2 overflow-hidden rounded-md px-2.5 py-2 text-left ${mL(t.scope)}`;return r?(0,n.jsx)("button",{"data-testid":`workbench-picker-user-message-preview-${e.sessionId}`,type:"button",disabled:H,onClick:()=>er(e),"aria-label":$("viewMatch",{label:mO(t.scope,t.count,$)}),className:`${a} outline-none transition-colors hover:brightness-95 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50`,children:i},t.scope):(0,n.jsx)("div",{className:a,children:i},t.scope)})}):null,u?(0,n.jsxs)("div",{id:x,"data-testid":x,className:"mb-2 ml-6 rounded-md border bg-background px-3 py-2.5",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[(0,n.jsxs)("p",{className:"flex min-w-0 items-center gap-1.5 text-xs font-medium",children:[(0,n.jsx)(m$.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||H,onClick:()=>void en(e.sessionId,"",1,!1),className:(0,I.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)(es.A,{className:"size-4 animate-spin"})}):0===u.messages.length?(0,n.jsx)("p",{className:"py-4 text-center text-xs text-muted-foreground",children:$("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,D.format(t))}),(0,n.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-sm leading-6",children:e.text?mq(e.text,u.query):$("noText")})]},e.entryId)})}),y?(0,n.jsxs)("button",{type:"button",disabled:u.loading||H,onClick:()=>void en(e.sessionId,u.query,(u.page?.index??0)+1,!0),className:(0,I.r)({variant:"outline",className:"mt-2"}),children:[u.loading?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):null,$("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)(uo.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||H,onClick:()=>ep(e.cwd),className:"group flex min-h-15 w-full items-center gap-3 rounded-md px-2 py-2 text-left outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55 sm:px-3",children:[(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-primary"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",title:e.name,children:e.name}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),(0,n.jsx)(e7.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-foreground"})]},e.cwd))})]}):0===Z.length?null===m?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:0===X.length?"ignored"===s?$("ignoredEmpty"):$("projectsEmpty"):$("projectNoMatches")}):null:"ignored"===s?(0,n.jsx)("div",{className:"divide-y",children:Z.map(e=>{let t=mR(e.cwd),s=f===e.cwd;return(0,n.jsxs)("div",{className:"flex min-h-15 items-center gap-3 px-2 py-2 sm:px-3",children:[(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",title:t,children:t}),(0,n.jsx)("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),(0,n.jsxs)("button",{"data-testid":`workbench-picker-restore-directory-${e.cwd}`,type:"button",disabled:H,onClick:()=>E(e.cwd,!1),"aria-label":$("restoreFolder",{name:t}),title:$("restoreTip"),className:(0,I.r)({variant:"outline"}),children:[s?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(lP.A,{className:"size-3.5"}),(0,n.jsx)("span",{children:$("restore")})]})]},e.cwd)})}):(0,n.jsx)("div",{className:"divide-y",children:Z.map(e=>{let s,r=mR(e.cwd),i=$("directorySessions",{count:e.sessionCount,time:(s=e.updatedAt,D.format(s))}),a=h===e.cwd,l=f===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:H,onClick:()=>M(e.cwd),className:"group flex min-h-15 min-w-0 flex-1 items-center gap-3 rounded-md px-2 py-2 text-left outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55 sm:px-3",children:[(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-primary"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",title:r,children:r}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),a?(0,n.jsxs)("span",{className:"flex min-h-10 shrink-0 items-center gap-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}),$("creating")]}):(0,n.jsxs)("span",{className:"flex shrink-0 items-center gap-1 text-xs text-muted-foreground",title:i,children:[(0,n.jsx)("span",{children:$("directoryCount",{count:e.sessionCount})}),(0,n.jsx)(e7.A,{className:"size-4 group-hover:text-foreground"})]})]}),"create"===t?(0,n.jsx)("button",{"data-testid":`workbench-picker-ignore-directory-${e.cwd}`,type:"button",disabled:H,onClick:()=>E(e.cwd,!0),"aria-label":$("ignoreFolder",{name:r}),title:$("ignoreTip"),className:(0,I.r)({variant:"ghost",size:"icon"}),children:l?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(an.A,{className:"size-4"})}):null]},e.cwd)})})]})}),(0,n.jsxs)(eN.vu,{className:"flex-row flex-wrap items-center justify-between gap-2 px-3 py-2.5 sm:px-4",children:[(0,n.jsx)("p",{className:"min-w-24 flex-1 truncate text-xs text-muted-foreground",title:ed,children:ed}),(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||H,onClick:j,className:(0,I.r)({variant:"outline"}),children:$("ignoredFolders")}),(0,n.jsx)("button",{type:"button",disabled:p||H,onClick:N,className:(0,I.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||H,onClick:()=>C(o.cwd),className:(0,I.r)(),children:$("selectCurrent")}):null,"browser"===s&&o?.parentCwd?(0,n.jsx)("button",{type:"button",disabled:p||H,onClick:()=>ep(o.parentCwd),"aria-label":$("parentDirectory"),title:$("parentDirectory"),className:(0,I.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(A.A,{className:"size-4"})}):null,"browser"===s&&o?.cwd?(0,n.jsx)("button",{type:"button",disabled:p||H,onClick:()=>ep(null),"aria-label":$("backRoots"),title:$("backRoots"),className:(0,I.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(uo.A,{className:"size-4"})}):null,(0,n.jsx)("button",{"data-testid":"workbench-picker-refresh",type:"button",disabled:p||H,onClick:()=>k(G,L),"aria-label":$("refreshList"),title:$("refreshList"),className:(0,I.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(es.A,{className:`size-4${p?" animate-spin":""}`})})]})]})]})})}let mW="pi-super:workbench-layout";function mY(e,t,s=[]){let n=new Set(t.map(e=>e.workId)),r=new Set(s),i=e.primaryWorkId&&n.has(e.primaryWorkId)&&!r.has(e.primaryWorkId)?e.primaryWorkId:null;return e.primaryWorkId===i?e:{primaryWorkId:i}}function mV({variant:e,className:t,children:s}){let{t:r}=(0,b.Bd)("workbench");return(0,n.jsx)("div",{className:(0,C.cn)("@container/empty-state flex size-full min-h-0 flex-1 items-center justify-center overflow-hidden px-6 py-8 text-center",t),children:"select-session"===e?(0,n.jsxs)("div",{className:"relative",children:[s,(0,n.jsx)("h1",{className:"text-base font-medium text-muted-foreground",children:r("emptySelectSession")})]}):(0,n.jsxs)("div",{role:"status","aria-live":"polite",className:"flex flex-col items-center gap-3 animate-in fade-in-0 fill-mode-both delay-150 duration-150 motion-reduce:animate-none",children:[(0,n.jsx)(v.A,{className:"size-5 animate-spin text-muted-foreground motion-reduce:animate-none"}),(0,n.jsx)("p",{className:"text-sm font-medium text-muted-foreground",children:r("emptyLoading")})]})})}var mU=s(39569),mH=s(31175),mK=s(74873),mG=s(77065),mJ=s(36919);let mQ=new Set(["custom","model_change","thinking_level_change","session_info","label"]),mX=[],mZ=[{value:"default",label:"filterDefault"},{value:"no-tools",label:"filterNoTools"},{value:"user-only",label:"filterUserOnly"},{value:"labeled-only",label:"filterLabeled"},{value:"all",label:"filterAll"}],m0={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 m1(e){switch(e.action){case"tree":return"treeIntent";case"fork":return"forkIntent";case"clone":return"cloneIntent"}}function m2(e){e.preventDefault()}function m5({confirmation:e,disabled:t,onConfirm:s,onBack:i}){let{t:a}=(0,b.Bd)("workbenchPicker"),[l,o]=(0,r.useState)(0),c=(0,r.useRef)(new Map);(0,r.useEffect)(()=>{c.current.get(0)?.focus()},[]);let d=n=>{e.waiting||t&&0===n||(0===n?s():i())};return(0,n.jsxs)("div",{className:"p-3 sm:p-4",onKeyDown:e=>{if(e.stopPropagation(),"Escape"===e.key){e.preventDefault(),i();return}if("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key){e.preventDefault();let t=+(0===l);o(t),queueMicrotask(()=>c.current.get(t)?.focus());return}"Enter"===e.key&&(e.preventDefault(),d(l))},children:[(0,n.jsxs)("div",{className:"rounded-lg border bg-muted/25 px-3 py-2.5",children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:a("runningTitle")}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:"main"===e.reason?a("runningStop",{action:a(m1(e.intent))}):a("runningWait",{action:a(m1(e.intent))})})]}),(0,n.jsx)("div",{className:"mt-3 grid grid-cols-2 gap-2",children:[{label:a(e.waiting?"confirming":"confirmContinue"),confirm:!0},{label:a("back"),confirm:!1}].map((s,r)=>(0,n.jsxs)("button",{ref:e=>{e?c.current.set(r,e):c.current.delete(r)},type:"button",disabled:e.waiting||t&&s.confirm,tabIndex:l===r?0:-1,className:(0,C.cn)("flex min-h-11 items-center justify-center gap-2 rounded-lg border px-3 text-sm font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-60",l===r?"border-primary/40 bg-primary/10 text-foreground":"border-border bg-background hover:bg-muted/60"),onFocus:()=>o(r),onClick:()=>d(r),children:[e.waiting&&s.confirm?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):null,s.label]},s.label))}),(0,n.jsx)("p",{className:"mt-2 text-center text-xs text-muted-foreground",children:a("confirmHint")})]})}function m3({model:e,projectName:t,sessionTitle:s,mobile:i,onClose:a,onRetry:l,onSelectEntry:o,onAction:c,onConfirmRunning:d,onCancelRunning:u}){let{t:m}=(0,b.Bd)("workbenchPicker"),p=(0,mG.tF)(),h=(0,mJ.I)(),{locale:g,timeZone:f}=(0,eQ.i)(),x=(0,r.useMemo)(()=>new Intl.DateTimeFormat("en"===g?"en-US":"zh-CN",{timeZone:f,timeZoneName:"shortOffset",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}),[g,f]),[w,y]=(0,r.useState)(""),[k,j]=(0,r.useState)("default"),[N,S]=(0,r.useState)(!1),[E,M]=(0,r.useState)(()=>new Set),[z,A]=(0,r.useState)(null),[$,R]=(0,r.useState)(0),[P,D]=(0,r.useState)(480),T=(0,r.useRef)(null),O=(0,r.useRef)(null),L=(0,r.useRef)(null),F=(0,r.useRef)(null),B=(0,r.useRef)(!1),q=e.tree?.nodes??mX,_=(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!mQ.has(e.kind);case"no-tools":return!mQ.has(e.kind)&&"tool"!==e.kind;case"user-only":return"user"===e.kind;case"labeled-only":return null!==e.label;case"all":return!0}})(t,e.filter,e.leafEntryId)&&function(e,t){let s=t.toLocaleLowerCase().split(/\s+/).filter(Boolean);if(0===s.length)return!0;let n=[e.kind,e.preview,e.label??""].join(" ").toLocaleLowerCase();return s.every(e=>n.includes(e))}(t,e.query)).map(e=>e.entryId)),r=new Map,i=new Map;for(let e of t.values()){if(!n.has(e.node.entryId))continue;let s=e.node.parentEntryId,a=new Set;for(;s&&!n.has(s);){if(a.has(s)){s=null;break}a.add(s),s=t.get(s)?.node.parentEntryId??null}s===e.node.entryId&&(s=null),i.set(e.node.entryId,s);let l=r.get(s)??[];l.push(e),r.set(s,l)}for(let e of r.values())e.sort((e,t)=>(function(e,t,s){let n=Number(!s.has(e.node.entryId))-Number(!s.has(t.node.entryId));if(0!==n)return n;let r=e.node.timestampMs-t.node.timestampMs;return 0!==r?r:e.index-t.index})(e,t,s));let a=[],l=new Set;return(t=>{let n=[...t].reverse().map(e=>({indexed:e,depth:0,connector:!1,lastSibling:!0}));for(;n.length>0;){let t=n.pop(),o=t.indexed.node.entryId;if(l.has(o))continue;l.add(o);let c=r.get(o)??[],d=i.get(o)??null,u=null===d?[]:r.get(d)??[],m=c.length>0&&(null===d||u.length>1),p=!m||!e.foldedEntryIds.has(o);if(a.push({node:t.indexed.node,depth:t.depth,active:s.has(o),current:o===e.leafEntryId,hasChildren:c.length>0,foldable:m,expanded:p,connector:t.connector,lastSibling:t.lastSibling,visibleParentEntryId:i.get(o)??null}),!p)continue;let h=c.length>1;for(let[e,s]of[...c].reverse().entries()){let r=c.length-e-1;n.push({indexed:s,depth:t.depth+ +!!h,connector:h,lastSibling:r===c.length-1})}}})(r.get(null)??[]),a})({nodes:q,leafEntryId:e.tree?.leafEntryId??null,filter:k,query:w,foldedEntryIds:E}),[k,E,e.tree?.leafEntryId,q,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])),i=s,a=new Set;for(;i&&!a.has(i);){if(n.has(i))return i;a.add(i),i=r.get(i)?.parentEntryId??null}return t.at(-1)?.node.entryId??null}(q,_,z??e.tree?.leafEntryId??null),Y=_.findIndex(e=>e.node.entryId===W),U=Y>=0?_[Y]:null,H=Math.max(0,Math.floor($/36)-8),G=Math.min(_.length,Math.ceil(($+P)/36)+8),J=Math.min(_.length,Math.max(G,H+8)),Q=_.slice(H,J),X=e.detail?.entryId===W?e.detail:null,Z=m(mZ.find(e=>e.value===k)?.label??"filterDefault"),ee=e.runningConfirmation,et=`work-session-branch-tree-${e.workId}`,es=W?`${et}-entry-${W}`:void 0,en=(0,r.useCallback)(()=>{i?O.current?.focus({preventScroll:!0}):T.current?.focus({preventScroll:!0})},[i]),er=(0,r.useCallback)(t=>{e.pending||(B.current=t,a())},[e.pending,a]);(0,r.useEffect)(()=>{if(p)return F.current=document.activeElement instanceof HTMLElement?document.activeElement:null,B.current=!1,queueMicrotask(en),()=>{B.current&&F.current?.focus({preventScroll:!0})}},[en,p]),(0,r.useEffect)(()=>{p&&!ee&&queueMicrotask(en)},[ee,en,p]),(0,r.useEffect)(()=>{if(!p)return;let t=t=>{if(e.pending)return;let s=t.target;!(s instanceof Node)||O.current?.contains(s)||s instanceof Element&&s.closest('[data-workbench-branch-picker-popup="true"]')||er(!1)};return document.addEventListener("pointerdown",t,!0),()=>document.removeEventListener("pointerdown",t,!0)},[e.pending,p,er]),(0,r.useEffect)(()=>{let e=L.current;if(!e)return;let t=new ResizeObserver(([e])=>{D(e?.contentRect.height??0)});return t.observe(e),()=>t.disconnect()},[ee]),(0,r.useEffect)(()=>{if(!p||!W||ee)return;o(W);let e=L.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))},[ee,W,o,p,36,Y]);let ei=(0,r.useCallback)(e=>{L.current&&(L.current.scrollTop=e),R(e)},[]),ea=(0,r.useCallback)(e=>{if(0===_.length)return;let t=Math.max(0,Math.min(_.length-1,e));A(_[t].node.entryId);let s=L.current;if(!s)return;let n=36*t,r=n+36,i=s.scrollTop;n<s.scrollTop?i=n:r>s.scrollTop+s.clientHeight&&(i=r-s.clientHeight),ei(i)},[36,_,ei]),el=(0,r.useCallback)((e,t)=>{M(s=>{let n=new Set(s);return t??!n.has(e)?n.add(e):n.delete(e),n})},[]),eo=(0,r.useCallback)(e=>{j(e),M(new Set),ei(0),queueMicrotask(en)},[en,ei]),ec=(0,r.useCallback)(e=>{let t=(mZ.findIndex(e=>e.value===k)+e+mZ.length)%mZ.length;eo(mZ[t].value)},[eo,k]),ed=(0,r.useCallback)((t,s)=>{e.actionsDisabled||(B.current=!1,c(t,s))},[e.actionsDisabled,c]),eu=(0,r.useCallback)(()=>{!U||U.current||e.pending||ed(U.node.entryId,"tree")},[e.pending,ed,U]),ep=(0,r.useCallback)(()=>{if(!U?.visibleParentEntryId)return;let e=_.findIndex(e=>e.node.entryId===U.visibleParentEntryId);e>=0&&ea(e)},[_,ea,U]),eg=(0,r.useCallback)(()=>{if(!U)return;let e=_.findIndex(e=>e.visibleParentEntryId===U.node.entryId);e>=0&&ea(e)},[_,ea,U]),ef=(0,r.useCallback)(()=>{ee?u():w?(y(""),M(new Set),ei(0)):er(!0)},[ee,u,w,er,ei]);(0,r.useEffect)(()=>{if(!i||!p)return;let e=e=>{"Escape"!==e.key||e.defaultPrevented||e.isComposing||e.repeat||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||O.current?.closest("[inert]")||(e.preventDefault(),e.stopImmediatePropagation(),ef())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ef,i,p]);let ex=U?.node??null,eb=ex?m0[ex.kind]:null,ev=ee?i?"inset-x-0 bottom-0 rounded-t-2xl border-x-0 border-b-0":"inset-x-2 bottom-2 h-auto max-h-[calc(100%-4rem)] rounded-xl":i?"inset-x-0 bottom-0 top-14 rounded-t-2xl border-x-0 border-b-0":"inset-x-2 bottom-2 h-[min(82%,48rem)] rounded-xl";return(0,n.jsxs)(o6.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)(o6.PY1.section,{ref:O,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",ev),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")}),ee?null:(0,n.jsxs)("span",{className:"shrink-0 text-xs text-muted-foreground",children:[Y>=0?Y+1:0," / ",_.length]}),(0,n.jsx)("button",{type:"button",disabled:e.pending,"aria-label":m("closeBranchPicker"),className:(0,I.r)({variant:"ghost",size:"icon"}),onClick:()=>er(!0),children:(0,n.jsx)(V.A,{className:"size-4"})})]}),ee?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)(eh.A,{className:"pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{ref:T,role:"combobox",value:w,"aria-label":m("branchSearch"),"aria-controls":et,"aria-expanded":"true","aria-activedescendant":es,placeholder:m("branchSearchPlaceholder"),className:"pl-7",onChange:e=>{y(e.currentTarget.value),M(new Set),ei(0)},onKeyDown:e=>{if(!e.nativeEvent.isComposing)switch(e.stopPropagation(),e.key){case"Tab":e.preventDefault(),ec(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||!U)return;e.preventDefault(),U.foldable&&U.expanded?el(U.node.entryId,!0):ep();return;case"ArrowRight":if(w||!U)return;e.preventDefault(),U.foldable&&!U.expanded?el(U.node.entryId,!1):eg();return;case"Enter":e.preventDefault(),eu();return;case"Escape":e.preventDefault(),ef();return}}})]}),(0,n.jsxs)(K.rI,{open:N,onOpenChange:S,onOpenChangeComplete:e=>{e||queueMicrotask(en)},children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)("button",{type:"button","aria-label":m("branchFilter",{filter:Z}),className:(0,I.r)({variant:"outline"})}),children:[Z,(0,n.jsx)(eY.A,{className:"size-3.5"})]}),(0,n.jsx)(K.SQ,{"data-workbench-branch-picker-popup":"true",align:"end",side:"bottom",className:"w-32",finalFocus:()=>i?O.current:T.current,children:mZ.map(e=>(0,n.jsxs)(K._2,{onClick:()=>eo(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)(I.$,{type:"button",size:"sm",variant:"outline",disabled:e.actionsDisabled,onClick:l,children:m("retry")})]})}):null,ee?(0,n.jsx)(m5,{confirmation:ee,disabled:e.actionsDisabled,onConfirm:d,onBack:()=>{B.current=!0,u()}},`${ee.intent.action}:${"entryId"in ee.intent?ee.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:ex&&eb?(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:eb.labelClassName,children:m(eb.label)}),ex.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:ex.label}):null,(0,n.jsx)("time",{className:"ml-auto shrink-0",children:x.format(ex.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)(v.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)(v.A,{className:"size-3.5 animate-spin text-primary"}),m("branchWorking")]}):null,e.loading&&!e.tree?(0,n.jsx)("div",{className:"grid min-h-0 flex-1 place-items-center text-sm text-muted-foreground",children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),m("branchLoading")]})}):0===_.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===q.length?m("branchEmpty"):m("branchNoMatches")}):(0,n.jsxs)("div",{ref:L,id:et,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*H}px`},"aria-hidden":"true"}),Q.map(t=>{let s=t.node.entryId===W,r=Math.min(t.depth,10),a=m0[t.node.kind];return(0,n.jsxs)("div",{id:`${et}-entry-${t.node.entryId}`,role:"treeitem","aria-level":t.depth+1,"aria-selected":s,"aria-expanded":t.foldable?t.expanded:void 0,className:(0,C.cn)("group relative flex min-w-0 items-center rounded-md outline-none transition-colors",a.rowClassName,s?"bg-accent text-accent-foreground":t.current?"bg-primary/[0.055] hover:bg-primary/[0.08]":"hover:bg-muted/50"),style:{height:"36px",paddingLeft:`${10*r}px`},children:[r>0?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("pointer-events-none absolute bottom-0 top-0 w-px",t.active?"bg-primary/25":"bg-border/60"),style:{left:`${10*r-5}px`}}):null,t.connector?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("pointer-events-none absolute h-px w-2",t.active?"bg-primary/25":"bg-border/60"),style:{left:`${10*r-5}px`}}):null,(0,n.jsx)("div",{className:"flex w-6 shrink-0 items-center justify-center",children:t.foldable?(0,n.jsx)("button",{type:"button","aria-label":m(t.expanded?"collapseBranch":"expandBranch"),className:"flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-foreground/8 hover:text-foreground",onMouseDown:m2,onClick:()=>{el(t.node.entryId),queueMicrotask(en)},children:(0,n.jsx)(e7.A,{className:(0,C.cn)("size-3 transition-transform",t.expanded&&"rotate-90")})}):null}),(0,n.jsxs)("button",{type:"button",tabIndex:-1,className:"flex h-full min-w-0 flex-1 items-center gap-1.5 overflow-hidden text-left outline-none",onMouseDown:m2,onClick:()=>{A(t.node.entryId),queueMicrotask(en)},onDoubleClick:()=>{i||t.current||ed(t.node.entryId,"tree")},children:[(0,n.jsx)("span",{className:(0,C.cn)("w-9 shrink-0 text-xs",a.labelClassName),children:m(a.label)}),t.node.label?(0,n.jsx)("span",{className:"max-w-24 shrink-0 truncate rounded-md bg-muted px-1 text-xs text-foreground",children:t.node.label}):null,(0,n.jsx)("span",{className:(0,C.cn)("min-w-0 flex-1 truncate text-sm",a.contentClassName,s&&"font-semibold text-accent-foreground"),children:t.node.preview||m("noPreview")})]}),i?(0,n.jsxs)("div",{className:"ml-2 flex shrink-0 items-center gap-1 border-l border-border/55 py-0.5 pl-1.5 pr-1",children:[(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||t.current||e.pending,"aria-label":m("switchToMessage",{kind:m(a.label)}),className:(0,I.r)({variant:"secondary",size:"sm"}),onClick:()=>ed(t.node.entryId,"tree"),children:m("switch")}),"user"===t.node.kind?(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||e.pending,"aria-label":m("forkFromUser"),className:(0,I.r)({variant:"outline",size:"sm"}),onClick:()=>ed(t.node.entryId,"fork"),children:"Fork"}):null]}):"user"===t.node.kind?(0,n.jsx)("div",{className:"ml-2 flex shrink-0 items-center border-l border-border/50 pl-2 pr-1",children:(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||e.pending,"aria-label":m("forkFromUser"),className:(0,I.r)({variant:"ghost",size:"sm"}),onMouseDown:m2,onClick:()=>ed(t.node.entryId,"fork"),children:"Fork"})}):null]},t.node.entryId)}),(0,n.jsx)("div",{style:{height:`${36*Math.max(0,_.length-J)}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," / ",_.length,i?"":` \xb7 ${m("branchShortcuts")}`]}),i?null:(0,n.jsx)(I.$,{type:"button",size:"sm",disabled:e.actionsDisabled||!U||U.current||e.loading||e.pending,onMouseDown:m2,onClick:eu,children:m("switch")})]})]})]})]})}var m4=s(15450),m6=s(31210),m8=s(66722),m7=s(40942),m9=s(61989),pe=s(63434),pt=s(26690),ps=s(2870),pn=s.n(ps);function pr({workSession:e,runtime:t,active:s,chatReady:i,onOpen:a}){let{t:l}=(0,b.Bd)("workbench"),{locale:o}=(0,eQ.i)();(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let c=t.getWorkspace(e.cwd)?.heads;(0,r.useEffect)(()=>{let n;if(!s||!i)return;let r=()=>{window.clearTimeout(n),n=void 0},a=()=>{r(),"visible"===document.visibilityState&&document.hasFocus()&&(n=window.setTimeout(()=>{n=void 0,"visible"===document.visibilityState&&document.hasFocus()&&t.refreshHeads(e.cwd)},1e3))},l=()=>{"visible"!==document.visibilityState&&r()};return a(),window.addEventListener("focus",a),window.addEventListener("blur",r),document.addEventListener("visibilitychange",l),()=>{r(),window.removeEventListener("focus",a),window.removeEventListener("blur",r),document.removeEventListener("visibilitychange",l)}},[s,i,t,e.cwd]);let d=c?.repositories??[],u=(0,uc.A_)(e.projectName,d,o);if(c?.status==="ready"&&!u)return null;let m=c?.status==="loading"&&!u,p=c?.status==="error"&&!u,h=m?null:u;return(0,n.jsxs)(lG,{"data-testid":"composer-git-branch",tooltip:p?c.error??l("gitStatusReadFailed"):h?.title??l("gitBranches"),"aria-label":l("gitBranches"),className:pn().branchTrigger,disabled:m,onClick:()=>a({workId:e.workId,cwd:e.cwd,projectName:e.projectName,repositoryRoot:null}),children:[m?(0,n.jsx)(v.A,{className:"size-4 shrink-0 animate-spin"}):(0,n.jsx)(ul.A,{className:"size-4 shrink-0 text-emerald-600 dark:text-emerald-400"}),p?(0,n.jsx)("span",{className:(0,C.cn)(pn().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)(pn().branchFull,h.diverged&&"text-amber-600 dark:text-amber-400"),children:h.full})}):null]})}let pi="l2-workbench-slash-command-menu",pa={key:"builtin:reload",name:"reload",description:"重新读取 Pi 最新配置与扩展资源",source:"builtin"},pl=[{source:"builtin",label:"Pi 内置命令"},{source:"skill",label:"Skills"},{source:"prompt",label:"提示模板"},{source:"extension",label:"扩展命令"}];function po(e){return`${pi}-option-${e}`}function pc(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function pd(e){return[...e.children].filter(e=>e instanceof HTMLElement)}function pu(e,t,s){return e.reduce((e,t)=>e+(s.get(t)??0),0)+Math.max(0,e.length-1)*t}var pm=s(64696);let pp=2*Math.PI*7;function ph(e){if(null===e)return"--";let t=Math.round(e);return t<1e3?String(t):`${Math.round(t/100)/10}K`}function pg(e){return Math.min(100,Math.max(0,e))}function pf(e){return pp-e/100*pp}function px({sessionId:e,cwd:t,tokens:s,contextWindow:i,contextIgnorePlugin:a,ignoreDisabled:l,ignorePending:o,compactDisabled:c,compactPending:d,onIgnoreContext:u,onCompactContext:m}){let p,h,g,f,x,{t:w}=(0,b.Bd)("workbench"),y=(0,r.useId)(),k=(0,r.useRef)(!1),[j,N]=(0,r.useState)(!1),[S,E]=(0,r.useState)(!1),[M,z]=(0,r.useState)(!1),A=(0,X.G)(),$=(p=!a||"object"!=typeof a||Array.isArray(a)||"number"!=typeof a.ignoredTokens||!Number.isFinite(a.ignoredTokens)||a.ignoredTokens<0||"number"!=typeof a.potentialTokens||!Number.isFinite(a.potentialTokens)||a.potentialTokens<0||void 0!==a.effectiveTokens&&null!==a.effectiveTokens&&("number"!=typeof a.effectiveTokens||!Number.isFinite(a.effectiveTokens)||a.effectiveTokens<0)?null:{ignoredTokens:a.ignoredTokens,potentialTokens:a.potentialTokens,...void 0!==a.effectiveTokens?{effectiveTokens:a.effectiveTokens}:{}},g=null===(h=p?.effectiveTokens===void 0?s:p.effectiveTokens)?0:pg(h/i*100),x=null===(f=null===h||null===p?null:Math.max(0,h-p.potentialTokens))?null:pg(f/i*100),{contextIgnore:p,currentTokens:h,usedPercent:g,projectedTokens:f,projectedPercent:x,potentialSegmentPercent:null===x?0:Math.max(0,g-x)}),R=Math.round($.usedPercent),P=null===$.projectedPercent?null:Math.round($.projectedPercent),D=R>=90?"text-destructive":R>=80?"text-status-warning":"text-muted-foreground",T=R>=90?"bg-destructive":R>=80?"bg-status-warning":"bg-primary",O=$.contextIgnore?w("contextUsageWithIgnore",{percent:R,projected:P??0,ignored:ph($.contextIgnore.ignoredTokens),potential:ph($.contextIgnore.potentialTokens)}):w("contextUsageSimple",{percent:R,limit:ph(i)});return(0,n.jsxs)(lY,{open:j,triggerId:y,onOpenChange:(e,t)=>{k.current&&"trigger-focus"===t.reason||(e||(E(!1),z(!1)),N(e))},children:[(0,n.jsx)(lV,{id:y,delay:100,closeDelay:100,render:(0,n.jsx)("button",{type:"button","aria-label":O,"aria-expanded":j,className:"inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full bg-transparent transition-colors outline-none hover:bg-accent focus-visible:ring-1 focus-visible:ring-ring/50 data-open:bg-accent",onPointerDown:e=>{k.current="mouse"!==e.pointerType},onPointerCancel:()=>{k.current=!1},onClick:e=>{k.current&&(e.preventDefault(),N(e=>!e),queueMicrotask(()=>{k.current=!1}))},children:(0,n.jsxs)("svg",{className:"pointer-events-none block size-5 -rotate-90",viewBox:"0 0 20 20","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-muted-foreground opacity-20"}),$.contextIgnore?(0,n.jsxs)(n.Fragment,{children:[$.usedPercent>0?(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2",strokeDasharray:pp,strokeDashoffset:pf($.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:pp,strokeDashoffset:pf($.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:pp,strokeDashoffset:pf($.usedPercent),className:D}):null]})})}),(0,n.jsx)(lU,{side:"top",align:"center",sideOffset:6,"aria-label":w("contextDetails"),className:"w-80 max-w-[calc(100vw-2rem)] p-4 text-sm",children:(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 text-sm",children:[(0,n.jsx)("span",{className:"whitespace-nowrap text-muted-foreground",children:w("contextMetrics")}),(0,n.jsxs)("span",{className:"whitespace-nowrap font-medium tabular-nums text-foreground",children:[ph($.currentTokens)," / ",ph(i)," / ",R,"%"]})]}),(0,n.jsx)("div",{className:"flex h-1.5 overflow-hidden rounded-full bg-muted",children:$.contextIgnore&&null!==$.projectedPercent?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"h-full bg-foreground",style:{width:`${$.projectedPercent}%`}}),(0,n.jsx)("div",{className:"h-full bg-muted-foreground",style:{width:`${$.potentialSegmentPercent}%`}})]}):(0,n.jsx)("div",{className:(0,C.cn)("h-full rounded-full",T),style:{width:`${$.usedPercent}%`}})})]}),$.contextIgnore&&null!==$.projectedTokens?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-2 rounded-full bg-foreground"}),w("afterIgnore")]}),(0,n.jsxs)("span",{className:"font-medium tabular-nums text-foreground",children:[ph($.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:ph($.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:ph($.contextIgnore.ignoredTokens)})]})]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:[(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",disabled:l||o||!$.contextIgnore||$.contextIgnore.potentialTokens<=0,"aria-label":$.contextIgnore&&$.contextIgnore.potentialTokens>0?w("ignoreNow",{amount:ph($.contextIgnore.potentialTokens)}):w("nothingToIgnore"),"aria-busy":o,onClick:()=>void u(),children:[o?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(pm.A,{}),o?w("ignoring"):w("ignore")]}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",disabled:c||d,"aria-busy":d,onClick:()=>void m(),children:[d?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(o_.A,{}),d?w("compacting"):w("compact")]})]}),R>=80?(0,n.jsx)("p",{className:(0,C.cn)("pt-1 text-sm",R>=90?"text-destructive":"text-status-warning"),children:R>=90?w("contextCritical"):w("contextWarning")}):null,(0,n.jsx)("div",{className:"border-t border-border"}),(0,n.jsxs)("button",{type:"button","aria-label":w("copySessionId",{id:e}),className:"w-full cursor-pointer rounded-md px-1 py-1 text-left transition-colors outline-none hover:bg-muted focus-visible:ring-1 focus-visible:ring-ring/50",onClick:()=>{(0,e9.x)(e).then(e=>{e?E(!0):A.error(w("copySessionFailed"))})},children:[(0,n.jsxs)("span",{className:"flex items-center justify-between gap-3 text-muted-foreground",children:[(0,n.jsx)("span",{children:w("currentSessionId")}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-1",children:[S?w("copied"):w("clickToCopy"),S?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})]})]}),(0,n.jsx)("span",{className:"mt-1 block break-all font-mono text-xs leading-5 text-foreground",children:e})]}),(0,n.jsxs)("button",{type:"button","aria-label":w("copyCurrentPath",{path:t}),className:"w-full cursor-pointer rounded-md px-1 py-1 text-left transition-colors outline-none hover:bg-muted focus-visible:ring-1 focus-visible:ring-ring/50",onClick:()=>{(0,e9.x)(t).then(e=>{e?z(!0):A.error(w("copyPathFailed"))})},children:[(0,n.jsxs)("span",{className:"flex items-center justify-between gap-3 text-muted-foreground",children:[(0,n.jsx)("span",{children:w("currentPath")}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-1",children:[M?w("copied"):w("clickToCopy"),M?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})]})]}),(0,n.jsx)("span",{className:"mt-1 block min-w-0 break-words font-mono text-xs leading-5 text-foreground",title:t,children:t})]})]})})]})}function pb(e,t){let[s,n]=(0,r.useState)({value:null,loading:!1,error:null}),[i,a]=(0,r.useState)(0);return(0,r.useEffect)(()=>{if(!e)return;let s=!0;return Promise.resolve().then(async()=>{if(s){n({value:null,loading:!0,error:null});try{let e=await t();s&&n({value:e,loading:!1,error:null})}catch(e){s&&n({value:null,loading:!1,error:e instanceof Error?e.message:String(e)})}}}),()=>{s=!1}},[i,e,t]),{...s,retry:()=>a(e=>e+1)}}let pv={direct:["toolExposureDirect","直接使用"],"model-only":["toolExposureModelOnly","仅模型调用"],codemode:["toolExposureCodemode","通过脚本调用"],deferred:["toolExposureDeferred","按需发现"],hidden:["toolExposureHidden","不可调用"]};function pw({tools:e}){let{t}=(0,b.Bd)("workbench"),[s,i]=(0,r.useState)(""),[a,l]=(0,r.useState)("all"),o=s.trim().toLocaleLowerCase(),c=e.filter(e=>(!o||`${e.name} ${e.source??""} ${e.description}`.toLocaleLowerCase().includes(o))&&("all"===a||("blocked"===a?e.blockedByMode:e.exposure===a)));return(0,n.jsxs)("section",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsxs)(nC.MG,{className:"min-w-0 flex-1 basis-56",children:[(0,n.jsx)(nC.Sq,{children:(0,n.jsx)(eh.A,{className:"size-4"})}),(0,n.jsx)(nC.iV,{"aria-label":t("searchTools"),placeholder:t("searchToolsSources",{defaultValue:"搜索名称、来源或描述"}),value:s,onChange:e=>i(e.target.value)})]}),(0,n.jsxs)(ea.l6,{value:a,onValueChange:e=>{"string"==typeof e&&l(e)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("toolFilter"),className:"max-w-full",children:(0,n.jsx)(ea.yv,{children:"all"===a?t("allTools"):"blocked"===a?t("toolBlockedByMode"):t(pv[a]?.[0]??"toolUnknown")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(ea.eb,{value:"all",children:t("allTools")}),Object.entries(pv).map(([e,[s,r]])=>(0,n.jsx)(ea.eb,{value:e,children:t(s,{defaultValue:r})},e)),(0,n.jsx)(ea.eb,{value:"blocked",children:t("toolBlockedByMode")})]})]})]}),(0,n.jsxs)("div",{className:"divide-y",children:[c.map(e=>{let s=e.exposure?pv[e.exposure]:null;return(0,n.jsxs)("article",{className:"space-y-2 py-3",children:[(0,n.jsx)("h3",{className:"wrap-anywhere font-mono text-sm font-medium",children:e.name}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:[t("toolSource",{defaultValue:"来源"}),":"," ",e.source??t("toolUnknown",{defaultValue:"未知"})]}),(0,n.jsx)("span",{children:s?t(s[0],{defaultValue:s[1]}):t("toolUnknown",{defaultValue:"未知"})}),(0,n.jsx)("span",{children:void 0===e.active?t("toolUnknown",{defaultValue:"未知"}):e.active?t("toolActive",{defaultValue:"当前已选用"}):t("toolInactive",{defaultValue:"当前未选用"})}),(0,n.jsx)("span",{children:void 0===e.blockedByMode?t("toolModeUnknown",{defaultValue:"模式限制未知"}):e.blockedByMode?t("toolBlockedByMode",{defaultValue:"受模式限制"}):t("toolNotBlocked",{defaultValue:"未受模式限制"})})]}),(0,n.jsx)("p",{className:"whitespace-pre-wrap wrap-anywhere text-sm text-muted-foreground",children:e.description}),(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{className:"min-h-7 cursor-pointer text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:t("parameterSchema")}),(0,n.jsx)("pre",{className:"mt-2 whitespace-pre-wrap wrap-anywhere rounded-lg bg-muted p-3 font-mono text-sm leading-[1.6]",children:JSON.stringify(e.parameters,null,2)})]})]},e.name)}),c.length?null:(0,n.jsxs)("div",{className:"space-y-3 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)("p",{children:o||"all"!==a?t("noMatchingTools"):t("noRegisteredTools",{defaultValue:"当前会话没有登记工具"})}),o||"all"!==a?(0,n.jsx)(I.$,{variant:"outline",size:"sm",onClick:()=>{i(""),l("all")},children:t("clearSearch")}):null]})]})]})}function py({notices:e}){let{t}=(0,b.Bd)("workbench");return(0,n.jsx)("section",{"aria-label":t("nativeCommandOutput",{defaultValue:"会话命令输出"}),className:"space-y-3",children:e.length?e.map((e,t)=>(0,n.jsx)("p",{className:`whitespace-pre-wrap wrap-anywhere font-mono text-sm leading-[1.6] ${"error"===e.level?"text-destructive":"warning"===e.level?"text-amber-700 dark:text-amber-300":""}`,children:function(e){let t=[],s=0;for(let r of e.matchAll(/https?:\/\/[^\s<>"']+/g)){let i=r.index,a=r[0].replace(/[)\]。,.;]+$/,"");t.push(e.slice(s,i)),t.push((0,n.jsx)("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-2 wrap-anywhere",children:a},i)),s=i+a.length}return t.push(e.slice(s)),t}(e.message)},t)):(0,n.jsx)("p",{className:"py-6 text-sm text-muted-foreground",children:t("nativeCommandOutputEmpty",{defaultValue:"暂无会话命令输出"})})})}function pk({available:e,state:t,disabled:s,onExecute:i}){let{t:a}=(0,b.Bd)("workbench"),[l,o]=(0,r.useState)("status"),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(!1),p="status"!==l,h=c.trim(),g=p&&!/^[a-zA-Z0-9_-]+$/.test(h);return(0,n.jsxs)("div",{className:"space-y-4",children:[e?(0,n.jsxs)("form",{className:"space-y-3",onSubmit:e=>{e.preventDefault(),s||!t.ready||t.commandPending||g||"logout"===l&&!u||i("status"===l?"":`${l} ${h}`,"login"===l)},children:[(0,n.jsx)(n2,{label:a("mcpSessionActions",{defaultValue:"MCP 会话操作"}),layout:"segmented",value:l,onChange:e=>{o(e),m(!1)},options:[{value:"status",label:a("mcpStatus",{defaultValue:"状态"})},{value:"login",label:a("mcpLogin",{defaultValue:"登录"})},{value:"reconnect",label:a("mcpReconnect",{defaultValue:"重连"})},{value:"logout",label:a("mcpLogout",{defaultValue:"退出登录"})}]}),p?(0,n.jsxs)("label",{className:"block space-y-1 text-sm font-medium",children:[(0,n.jsx)("span",{children:a("mcpServerName",{defaultValue:"服务名称"})}),(0,n.jsx)(em.p,{value:c,onChange:e=>d(e.target.value),placeholder:a("mcpServerNamePlaceholder",{defaultValue:"输入真实服务名称"}),autoComplete:"off",maxLength:128})]}):null,p&&h&&g?(0,n.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:a("mcpServerNameInvalid",{defaultValue:"服务名称只能包含字母、数字、下划线和连字符。"})}):null,"logout"===l?(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-start gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",className:"mt-1 size-4 accent-primary",checked:u,onChange:e=>m(e.target.checked)}),(0,n.jsx)("span",{children:a("mcpLogoutConfirm",{defaultValue:"删除共享登录凭据,其他会话下次访问也可能需要重新登录。"})})]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(I.$,{type:"submit",size:"sm",disabled:s||!t.ready||null!==t.commandPending||g||"logout"===l&&!u,children:a("mcpExecute",{defaultValue:"执行"})}),t.commandPending?(0,n.jsxs)("span",{role:"status",className:"wrap-anywhere text-sm text-muted-foreground",children:[a("mcpExecuting",{defaultValue:"正在执行"})," ",t.commandPending]}):null]})]}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:a("mcpCommandUnavailable",{defaultValue:"当前会话未注册 MCP 命令。"})}),(0,n.jsxs)("div",{className:"border-t pt-4",children:[(0,n.jsx)("h3",{className:"mb-3 text-sm font-medium",children:a("nativeCommandOutput",{defaultValue:"会话命令输出"})}),(0,n.jsx)(py,{notices:t.notices})]})]})}function pj({open:e,source:t,runtime:s,getContext:i,listCommands:a,nativeUi:l,nativeBiz:o,commandsDisabled:c,onOpenChange:d,onOpenSettings:u}){let{t:m,i18n:p}=(0,b.Bd)("workbench"),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)("tools"),v=(0,X.G)(),{context:w,tools:y,commands:k}=function(e){let{source:t,runtime:s,getContext:n,listCommands:i,open:a,tab:l}=e,o=(0,r.useCallback)(()=>n({source:t}),[n,t]),c=(0,r.useCallback)(()=>s.listTools(t),[s,t]),d=(0,r.useCallback)(()=>i({source:t}),[i,t]);return{context:pb(a&&"system"===l,o),tools:pb(a&&"tools"===l,c),commands:pb(a&&"mcp"===l,d)}}({source:t,open:e,tab:f,runtime:s,getContext:i,listCommands:a}),j="system"===f?w:"tools"===f?y:k,N=l.state.snapshot.requests[0]?.id;(0,r.useEffect)(()=>{e&&N&&(l.setCollapsed(!1),d(!1))},[e,N,l,d]);let S=async()=>{w.value&&(await (0,e9.x)(w.value.systemPrompt)?g(!0):v.error(m("contextCopyFailed")))};return(0,n.jsx)(eN.YV,{open:e,onOpenChange:d,children:(0,n.jsxs)(eN.hA,{className:"h-[min(42rem,calc(100dvh-2rem))] max-w-[45rem]",children:[(0,n.jsxs)(eN.Hl,{className:"border-b p-4 pr-12",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)(nI.A,{className:"size-5 shrink-0 text-muted-foreground"}),(0,n.jsx)(eN.YM,{children:m("toolsAndContext",{defaultValue:"工具与上下文"})})]}),(0,n.jsx)(eN.uX,{className:"sr-only",children:m("sessionContextDescription",{defaultValue:"当前会话的登记工具、系统提示词和 MCP 原生命令"})})]}),(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-b px-4 py-3",children:[(0,n.jsx)(n2,{label:m("contextContents"),layout:"segmented",value:f,onChange:x,options:[{value:"tools",label:m("tools")},{value:"system",label:m("systemPrompt")},{value:"mcp",label:m("mcpSession",{defaultValue:"会话 MCP"})}]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:["system"===f?(0,n.jsxs)(I.$,{variant:"ghost",size:"sm",disabled:!w.value||w.loading,onClick:()=>void S(),children:[h?(0,n.jsx)(ep.A,{}):(0,n.jsx)(ee.A,{}),h?m("copied"):m("copy")]}):null,u?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{d(!1),u()},children:m("openSettings",{defaultValue:(p.resolvedLanguage??p.language).startsWith("en")?"Open settings":"打开设置"})}):null]})]}),(0,n.jsx)(eN._Y,{children:(0,n.jsx)("div",{className:"p-4",children:!j.loading&&(j.value||j.error)?j.error?(0,n.jsxs)("div",{className:"space-y-3 py-6",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:j.error}),(0,n.jsxs)(I.$,{variant:"outline",size:"sm",onClick:j.retry,children:[(0,n.jsx)(es.A,{}),m("contextRetry")]})]}):"tools"===f&&y.value?(0,n.jsx)(pw,{tools:y.value.tools}):"system"===f&&w.value?(0,n.jsx)("section",{"aria-label":m("systemPrompt"),children:(0,n.jsx)("pre",{className:"whitespace-pre-wrap wrap-anywhere font-mono text-sm leading-[1.6]",children:w.value.systemPrompt||m("emptyContent")})}):"mcp"===f&&k.value?(0,n.jsx)(pk,{available:k.value.commands.some(e=>"mcp"===e.name&&"extension"===e.source),state:l.state,disabled:c,onExecute:(e,s)=>{o.executeCommand(t,"mcp",e),s&&(l.setCollapsed(!1),d(!1))}}):null:(0,n.jsxs)("div",{role:"status",className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)(es.A,{className:"size-4 animate-spin"}),m("contextLoading")]})})})]})})}let pN={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pI({source:e,runtime:t,catalog:s,current:i,label:a,title:l,disabled:o,triggerClassName:c,detailsClassName:d,onOpenSettings:u}){let{t:m,i18n:p}=(0,b.Bd)("workbench"),[h,g]=(0,r.useState)(null),{open:f,pending:x,error:v,changeOpen:w,refresh:y,submit:k}=function(e,t,s){let[n,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)(null),d=(0,r.useRef)(null),u=(0,r.useRef)(!1),m=(0,r.useRef)(!0);(0,r.useEffect)(()=>(m.current=!0,()=>{m.current=!1,d.current=null}),[]);let p=()=>{t.loadModels(e,!0)},h=e=>{d.current=e?{}:null,i(e),e&&(c(null),p())},g=async(n,r)=>{if(s||u.current)return;let i=d.current;u.current=!0,l(!0),c(null);try{await t.setModel(e,{provider:n.provider,modelId:n.modelId,thinkingLevel:r}),i&&d.current===i&&h(!1)}catch(e){i&&d.current===i&&c(e instanceof Error?e.message:String(e))}finally{u.current=!1,m.current&&l(!1)}};return{open:n,pending:a,error:o,changeOpen:h,refresh:p,submit:g}}(e,t,o),j=s.models.find(e=>e.provider===i?.provider&&e.modelId===i.modelId),N=s.models.some(e=>"virtual"===e.kind)?[{key:"virtual",label:m("modelAutomaticRouting",{defaultValue:"自动路由"}),models:s.models.filter(e=>"virtual"===e.kind)},{key:"physical",label:m("modelFixed",{defaultValue:"固定模型"}),models:s.models.filter(e=>"physical"===e.kind)}].filter(e=>e.models.length>0):[{key:"all",label:m("allModels"),models:s.models}];return(0,n.jsxs)(K.rI,{open:f,onOpenChange:e=>{g(null),w(e)},children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)(lG,{title:l,"aria-label":m("chooseModel"),className:c}),children:[(0,n.jsx)(eD.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{"data-model-trigger-details":!0,className:d,children:(0,n.jsxs)("span",{className:"flex min-w-0 items-center gap-2 pl-2",children:[(0,n.jsx)("span",{className:"min-w-0 truncate",children:a}),(0,n.jsx)(eY.A,{className:"size-3 shrink-0"})]})})]}),(0,n.jsxs)(K.SQ,{align:"start",side:"top",className:"flex max-h-96 w-72 flex-col overflow-hidden p-0",children:[(0,n.jsxs)(K.I,{className:"shrink-0 p-1",children:[(0,n.jsx)(K.lp,{children:m("currentModel")}),(0,n.jsxs)("div",{className:"mx-1 mb-1 flex items-center gap-2 rounded-md border bg-muted/50 px-2 py-2",children:[(0,n.jsx)(eD.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",children:j?.name||i?.modelId||m("selectModel")}),(0,n.jsx)("p",{className:"truncate text-xs text-muted-foreground",children:i?.provider||m("selectModel")})]}),i?(0,n.jsx)("span",{className:"shrink-0 rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:m("thinkingLevel",{level:m(pN[i.thinkingLevel])})}):null]}),v?(0,n.jsx)("p",{role:"alert",className:"wrap-anywhere px-2 py-1 text-sm text-destructive",children:v}):null,x?(0,n.jsx)("p",{role:"status",className:"px-2 py-1 text-sm text-muted-foreground",children:m("modelChanging",{defaultValue:"正在切换模型…"})}):null]}),(0,n.jsx)(K.mB,{className:"mx-0 my-0 shrink-0"}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-auto overflow-x-hidden overflow-y-auto overscroll-contain p-1",children:["loading"===s.status?(0,n.jsxs)(K._2,{disabled:!0,children:[(0,n.jsx)(es.A,{className:"size-4 animate-spin"}),m("modelsLoading")]}):null,"error"===s.status?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{role:"alert",className:"wrap-anywhere px-2 py-1 text-sm text-destructive",children:s.error||m("modelsFailed")}),(0,n.jsxs)(K._2,{closeOnClick:!1,onClick:y,children:[(0,n.jsx)(es.A,{className:"size-4"}),m("retry")]})]}):null,N.map(e=>(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:e.label}),e.models.map(e=>{let t=`${e.provider}:${e.modelId}`,s=i?.provider===e.provider&&i.modelId===e.modelId;return(0,n.jsxs)(K.lv,{open:h===t,onOpenChange:e=>{g(s=>e?t:s===t?null:s)},children:[(0,n.jsxs)(K.nV,{disabled:o||x,label:e.name||e.modelId,children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.name||e.modelId}),e.input.includes("image")?(0,n.jsx)(ru.A,{className:"size-3 text-muted-foreground"}):null,s?(0,n.jsx)(ep.A,{className:"size-3 text-muted-foreground"}):null]}),(0,n.jsx)(K.M5,{children:(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:m("thinkingLevels")}),e.thinkingLevels.map(t=>(0,n.jsxs)(K._2,{disabled:o||x,closeOnClick:!1,onClick:()=>{g(null),k(e,t)},children:[(0,n.jsx)("span",{className:"flex-1",children:m(pN[t])}),s&&i?.thinkingLevel===t?(0,n.jsx)(ep.A,{className:"size-3 text-muted-foreground"}):null]},t))]})})]},t)})]},e.key)),"ready"===s.status&&0===s.models.length?(0,n.jsx)(K._2,{disabled:!0,children:m("noModels")}):null,u&&("error"===s.status||"ready"===s.status&&0===s.models.length)?(0,n.jsx)(K._2,{onClick:()=>u(),children:m("openSettings",{defaultValue:(p.resolvedLanguage??p.language).startsWith("en")?"Open settings":"打开设置"})}):null]}),"ready"===s.status||s.presets.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(K.mB,{className:"mx-0 my-0 shrink-0"}),(0,n.jsxs)(K.I,{className:"shrink-0 p-1",children:[(0,n.jsx)(K.lp,{children:m("presets")}),0===s.presets.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:m("commonCombinationsEmpty")}),u?(0,n.jsxs)(K._2,{onClick:()=>{w(!1),u("model-presets")},children:[(0,n.jsx)(aI.A,{className:"size-4"}),m("configureCommonCombinations")]}):null]}):null,s.presets.map((e,t)=>(0,n.jsxs)(K._2,{disabled:o||x,closeOnClick:!1,onClick:()=>void k(e,e.thinkingLevel),children:[(0,n.jsx)("span",{className:"size-2 rounded-full bg-current",style:e.color?{color:e.color}:void 0}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:s.models.find(t=>t.provider===e.provider&&t.modelId===e.modelId)?.name||e.modelId}),(0,n.jsx)("span",{className:"text-muted-foreground",children:m(pN[e.thinkingLevel])})]},`${e.provider}:${e.modelId}:${e.thinkingLevel}:${t}`))]})]}):null]})]})}var pS=s(15824);function pC({label:e,description:t,markerClass:s,countClass:r,inputs:i}){let{t:a}=(0,b.Bd)("workbench");return 0===i.length?null:(0,n.jsxs)("section",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-3 px-1",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:`size-1.5 shrink-0 rounded-full ${s}`}),(0,n.jsx)("h3",{className:"text-sm font-medium text-foreground",children:e})]}),(0,n.jsx)("p",{className:"mt-1 pl-3.5 text-sm leading-5 text-muted-foreground",children:t})]}),(0,n.jsx)("span",{className:`shrink-0 rounded-md px-1.5 py-0.5 text-xs font-medium tabular-nums ${r}`,children:a("queueItems",{count:i.length})})]}),(0,n.jsx)("ol",{className:"divide-y divide-border overflow-hidden",children:i.map((e,t)=>{let s=e.text.trim();return(0,n.jsxs)("li",{className:"grid grid-cols-[1.25rem_minmax(0,1fr)] gap-2.5 px-3 py-2.5",children:[(0,n.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center rounded-md bg-muted text-xs tabular-nums text-muted-foreground",children:t+1}),(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsx)("p",{className:"whitespace-pre-wrap break-words text-sm leading-6 text-foreground",children:s||a(e.images.length>0?"imageOnly":"noMessageText")}),e.images.length>0?(0,n.jsxs)("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[(0,n.jsx)(ru.A,{className:"size-3"}),a("queueImages",{count:e.images.length})]}):null]})]},e.tempId)})})]})}function pE({queues:e,disabled:t,onRestore:s}){let{t:i}=(0,b.Bd)("workbench"),a=(0,r.useId)(),l=(0,r.useRef)(!1),[o,c]=(0,r.useState)(!1),d=e.steering.length+e.followUp.length;return 0===d?null:(0,n.jsxs)(lY,{open:o,triggerId:a,onOpenChange:(e,t)=>{l.current&&"trigger-focus"===t.reason||c(e)},children:[(0,n.jsx)(lV,{id:a,delay:100,closeDelay:120,render:(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",disabled:t,"aria-label":i("viewQueued",{count:d}),"aria-expanded":o,onPointerDown:e=>{l.current="mouse"!==e.pointerType},onPointerCancel:()=>{l.current=!1},onClick:e=>{l.current&&(e.preventDefault(),c(e=>!e),queueMicrotask(()=>{l.current=!1}))},children:i("queuedCount",{count:d})})}),(0,n.jsxs)(lU,{side:"top",align:"end",sideOffset:6,"aria-label":i("queueCurrent"),className:"w-[22rem] max-w-[calc(100vw-2rem)] overflow-hidden p-0",children:[(0,n.jsx)("div",{className:"border-b px-4 py-3",children:(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground",children:(0,n.jsx)(pS.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("h2",{className:"text-sm font-semibold tracking-tight text-foreground",children:i("queueCurrent")}),(0,n.jsx)("p",{className:"mt-1 text-sm leading-5 text-muted-foreground",children:i("queuePendingDescription")})]}),(0,n.jsx)("span",{className:"shrink-0 rounded-md bg-muted px-2 py-1 text-xs tabular-nums text-foreground",children:i("queueItems",{count:d})})]})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar max-h-[min(24rem,55dvh)] space-y-4 overflow-y-auto p-4",children:[(0,n.jsx)(pC,{label:i("queueSteer"),description:i("queueSteerDescription"),markerClass:"bg-foreground",countClass:"bg-muted text-muted-foreground",inputs:e.steering}),(0,n.jsx)(pC,{label:i("queueFollowUp"),description:i("queueFollowUpDescription"),markerClass:"bg-muted-foreground",countClass:"bg-muted text-muted-foreground",inputs:e.followUp})]}),(0,n.jsx)("div",{className:"border-t border-border/60 bg-muted/15 p-2",children:(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",className:"w-full text-muted-foreground hover:text-foreground",disabled:t,onClick:s,children:[(0,n.jsx)(lP.A,{}),i("queueRestore")]})})]})]})}let pM={builtin:"slashGroupBuiltin",skill:"slashGroupSkill",prompt:"slashGroupPrompt",extension:"slashGroupExtension"};function pz({open:e,loading:t,error:s,groups:i,activeIndex:a,onActiveIndexChange:l,onSelect:o}){let{t:c}=(0,b.Bd)("workbench"),d=(0,r.useRef)(null),u=i.reduce((e,t)=>e+t.commands.length,0);if((0,r.useEffect)(()=>{d.current?.scrollIntoView({block:"nearest"})},[a]),!e)return null;let m=0,p=u>0,h=t?c("slashLoadingMore"):s?c("slashMoreFailed"):null;return(0,n.jsxs)("div",{id:pi,role:"listbox","aria-label":c("slashCandidates"),"aria-busy":t,className:"absolute bottom-full left-[-1px] z-20 mb-2 flex w-[calc(100%+2px)] origin-bottom-left flex-col overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2 duration-100",children:[(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar max-h-72 overflow-x-hidden overflow-y-auto overscroll-contain p-1 scroll-py-8 max-sm:max-h-[40dvh]",children:[i.map((e,t)=>(0,n.jsxs)("section",{role:"group","aria-label":c(pM[e.source]),className:(0,C.cn)(t>0&&"mt-1 border-t pt-1"),children:[(0,n.jsxs)("div",{className:"sticky -top-1 z-10 flex h-7 items-center gap-2 bg-popover px-2 text-xs font-medium text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-1.5 rounded-full bg-muted-foreground"}),(0,n.jsx)("span",{children:c(pM[e.source])}),(0,n.jsx)("span",{className:"ml-auto font-normal tabular-nums opacity-70",children:e.commands.length})]}),e.commands.map(e=>{let t=m++,s=t===a;return(0,n.jsxs)("div",{id:po(t),ref:s?d:void 0,role:"option","aria-selected":s,"data-active":s?"true":"false",className:"grid min-h-9 cursor-pointer grid-cols-[minmax(6.75rem,0.9fr)_minmax(0,1.2fr)_0.75rem] items-center gap-2 rounded-md px-2 py-1 text-sm outline-none select-none data-[active=true]:bg-accent sm:grid-cols-[minmax(7rem,0.8fr)_minmax(0,1.5fr)_1rem]",onPointerMove:e=>{"mouse"===e.pointerType&&l(t)},onPointerDown:e=>e.preventDefault(),onClick:()=>o(t),children:[(0,n.jsxs)("span",{className:"min-w-0 truncate font-mono text-sm font-medium",children:[(0,n.jsx)("span",{className:"text-primary",children:"/"}),e.name]}),(0,n.jsx)("span",{className:"min-w-0 truncate text-sm text-muted-foreground",children:"builtin"===e.source&&"reload"===e.name?c("reloadDescription"):e.description}),(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("text-right text-sm text-muted-foreground opacity-0",s&&"opacity-80"),children:"↵"})]},e.key)})]},e.source)),p?h?(0,n.jsxs)("div",{className:"flex min-h-7 items-center gap-2 px-2 text-xs text-muted-foreground",children:[t?(0,n.jsx)(v.A,{className:"size-3 animate-spin"}):null,(0,n.jsx)("span",{children:h})]}):null:(0,n.jsxs)("div",{className:"flex min-h-20 items-center justify-center gap-2 px-4 text-xs text-muted-foreground",children:[t?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):null,(0,n.jsx)("span",{children:t?c("slashLoading"):s?c("slashFailed"):c("slashEmpty")})]})]}),(0,n.jsxs)("div",{className:"flex min-h-7 items-center justify-between gap-3 border-t px-2.5 text-xs text-muted-foreground",children:[(0,n.jsx)("span",{className:"tabular-nums",children:i.length>0?c("slashSummary",{commands:u,groups:i.length}):c("slashCount",{count:u})}),(0,n.jsxs)("span",{className:"flex items-center gap-2 max-sm:hidden","aria-hidden":"true",children:[(0,n.jsx)("span",{children:c("slashUpDown")}),(0,n.jsx)("span",{children:c("slashEnter")}),(0,n.jsx)("span",{children:c("slashEscape")})]})]})]})}var pA=s(58270),p$=s.n(pA);function pR({modes:e,value:t,disabled:s,onChange:r}){let{t:i}=(0,b.Bd)("capabilityModes");if(0===Object.keys(e).length)return null;let a=null===t?i("allEnabled"):Object.hasOwn(e,t)?e[t]:i("modeSwitching");return(0,n.jsxs)(K.rI,{children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)(I.$,{variant:"ghost",size:"sm",disabled:s,"aria-label":i("modePicker",{name:a}),className:"min-w-0 max-w-40 text-muted-foreground"}),children:[(0,n.jsx)(eg.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 truncate",children:a}),(0,n.jsx)(eY.A,{className:"size-3 shrink-0"})]}),(0,n.jsx)(K.SQ,{side:"top",align:"start",className:"max-h-80 min-w-40 overflow-y-auto",children:(0,n.jsxs)(K.Hr,{value:t??"",onValueChange:e=>r("string"==typeof e&&e?e:null),children:[(0,n.jsx)(K.Ht,{value:"",children:i("allEnabled")}),Object.entries(e).map(([e,t])=>(0,n.jsx)(K.Ht,{value:e,children:t},e))]})})]})}var pP=s(18903),pD=s(8356),pT=s(93192);function pO({request:e,model:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,r.useId)(),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)(()=>Date.now()),{state:d}=t,u=Object.hasOwn(d.answers,e.id),m=d.answers[e.id]??("editor"===e.method?e.prefill:""),p=null!==e.expiresAt&&e.expiresAt<=o,h=!d.ready||null!==d.submitting||null!==d.unknown||p,g=h||"select"===e.method&&!u;(0,r.useEffect)(()=>{if(null===e.expiresAt)return;let t=window.setInterval(()=>c(Date.now()),500);return()=>window.clearInterval(t)},[e.expiresAt]);let f=s=>{s?.preventDefault(),g||t.answer(e.id,"confirm"===e.method||m)},x=s=>(0,n.jsx)(t7.T,{"aria-label":e.title,"aria-labelledby":s?void 0:i,className:s?"min-h-0 flex-1 resize-none text-base":"h-32 min-h-20 resize-none text-base",value:m,disabled:null!==d.submitting,maxLength:65536,onChange:s=>t.setAnswer(e.id,s.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),f())}}),v=(r=!1)=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",disabled:!r&&!t.canStop,onClick:r?()=>l(!1):t.stop,children:r?s("nativeUiBack"):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(m9.A,{className:"size-3.5"}),s("nativeUiStop")]})}),(0,n.jsx)("span",{className:"flex-1"}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",disabled:h,onClick:()=>t.answer(e.id,"confirm"!==e.method&&null),children:s("confirm"===e.method?"nativeUiReject":"nativeUiCancel")}),(0,n.jsx)(I.$,{type:r?"button":"submit",size:"sm",disabled:g,onClick:r?()=>f():void 0,children:s(d.submitting?"nativeUiSubmitting":"confirm"===e.method?"nativeUiConfirm":"nativeUiSubmit")})]});return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("section",{className:"mb-2 overflow-hidden rounded-xl border border-input bg-background","aria-label":s("nativeUiTitle"),"data-testid":"native-ui-question",onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||a||(e.preventDefault(),e.stopPropagation(),t.setCollapsed(!0))},children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 px-3 pt-2 text-xs text-muted-foreground",children:[(0,n.jsx)(pP.A,{className:"size-3.5"}),(0,n.jsx)("span",{children:s("nativeUiTitle")}),d.snapshot.requests.length>1?(0,n.jsx)("span",{children:s("nativeUiMore",{count:d.snapshot.requests.length-1})}):null,(0,n.jsx)("span",{className:"flex-1"}),"editor"===e.method?(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>l(!0),children:[(0,n.jsx)(q.A,{className:"size-3.5"}),s("nativeUiExpand")]}):null,(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>t.setCollapsed(!0),children:s("nativeUiLater")})]}),(0,n.jsxs)("form",{onSubmit:f,children:[(0,n.jsxs)("div",{className:"max-h-[40dvh] space-y-3 overflow-y-auto px-3 pt-2 pb-3",children:[(0,n.jsx)("h3",{id:i,className:"text-base leading-6 font-medium whitespace-pre-wrap wrap-anywhere",children:e.title}),"confirm"===e.method?(0,n.jsx)("p",{className:"text-sm leading-6 whitespace-pre-wrap wrap-anywhere text-muted-foreground",children:e.message}):null,"select"===e.method?(0,n.jsx)(n2,{label:e.title,value:u?String(e.options.indexOf(m)):"",disabled:h,options:e.options.map((e,t)=>({value:String(t),label:e})),onChange:s=>t.setAnswer(e.id,e.options[Number(s)])}):null,"input"===e.method?(0,n.jsx)(em.p,{"aria-labelledby":i,value:m,placeholder:e.placeholder,maxLength:65536,className:"text-base",disabled:null!==d.submitting,onChange:s=>t.setAnswer(e.id,s.target.value)}):null,"editor"===e.method?x(!1):null,null!==e.expiresAt?(0,n.jsxs)("p",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(pD.A,{className:"size-3.5"}),s("nativeUiCountdown",{seconds:Math.max(0,Math.ceil((e.expiresAt-o)/1e3))})]}):null]}),(0,n.jsx)("div",{className:"flex flex-wrap items-center gap-2 border-t px-3 py-2",children:v()})]})]}),"editor"===e.method&&a?(0,n.jsx)(eN.YV,{open:!0,onOpenChange:l,children:(0,n.jsxs)(eN.hA,{className:"h-[min(40rem,calc(100dvh-2rem))] max-w-3xl","data-testid":"native-ui-editor-dialog",children:[(0,n.jsx)(eN.Hl,{className:"px-4 pt-4 pr-12 pb-3",children:(0,n.jsx)(eN.YM,{children:e.title})}),d.error||!d.ready?(0,n.jsx)("p",{role:"status",className:"px-4 pb-3 text-sm text-muted-foreground",children:d.error??s("nativeUiDisconnected")}):null,(0,n.jsx)("div",{className:"flex min-h-0 flex-1 px-4 pb-4",children:x(!0)}),(0,n.jsx)(eN.vu,{children:v(!0)})]})}):null]})}function pL({model:e}){let{t}=(0,b.Bd)("workbench"),{state:s}=e,r=s.snapshot.requests[0];return(0,n.jsxs)(n.Fragment,{children:[s.error||!s.ready&&r?(0,n.jsxs)("div",{role:"status",className:"mb-2 flex flex-wrap items-center gap-2 rounded-lg bg-muted px-3 py-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:s.error??t("nativeUiDisconnected")}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:s.refreshing,onClick:e.refresh,children:[s.refreshing?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):null,t("nativeUiRetry")]}),r?null:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:e.dismissError,children:t("close",{ns:"common"})})]}):null,r?s.collapsed?(0,n.jsxs)("div",{className:"mb-2 flex items-center gap-2 rounded-lg border px-3 py-2","data-testid":"native-ui-collapsed",children:[(0,n.jsx)(pP.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 text-sm",children:t("nativeUiPending",{count:s.snapshot.requests.length})}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>e.setCollapsed(!1),children:t("nativeUiResume")})]}):(0,n.jsx)(pO,{request:r,model:e},r.id):null,s.notices.length>0?(0,n.jsxs)(eV.Nt,{defaultOpen:!!(r||s.commandPending?.startsWith("/mcp login ")),className:"mb-2 rounded-lg border px-3 py-2","data-testid":"native-ui-output",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-7 min-w-0 flex-1 cursor-pointer items-center gap-2 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eY.A,{className:"size-3.5 shrink-0 transition-transform group-data-panel-open:rotate-180 motion-reduce:transition-none"}),t("nativeCommandOutput",{defaultValue:"会话命令输出"})]}),(0,n.jsx)(I.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":t("close",{ns:"common"}),onClick:e.dismissNotices,children:(0,n.jsx)(V.A,{className:"size-3.5"})})]}),(0,n.jsx)(eV.Ke,{children:(0,n.jsx)("div",{className:"mt-2 max-h-40 overflow-y-auto",children:(0,n.jsx)(py,{notices:s.notices})})})]}):null,s.prefill?(0,n.jsxs)("div",{className:"mb-2 rounded-lg border px-3 py-2","data-testid":"native-ui-prefill",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"flex-1 text-sm font-medium",children:t("nativeUiDraft")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>e.usePrefill("dismiss"),children:t("nativeUiDismiss")})]}),(0,n.jsx)("p",{className:"my-2 max-h-24 overflow-y-auto text-sm whitespace-pre-wrap wrap-anywhere",children:s.prefill.text}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"secondary",onClick:()=>e.usePrefill("append"),children:t("nativeUiAppend")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>e.usePrefill("replace"),children:t("nativeUiReplace")})]})]}):null]})}function pF({snapshot:e,placement:t}){let{t:s}=(0,b.Bd)("workbench"),r=Object.entries(e.widgets).filter(([,e])=>e.placement===t),i="belowEditor"===t?Object.values(e.statuses):[];return r.length||i.length?(0,n.jsxs)("div",{className:"my-1.5 space-y-1","data-testid":`native-ui-extras-${t}`,children:[r.length?(0,n.jsxs)("details",{className:"group",children:[(0,n.jsxs)("summary",{className:"flex min-h-7 cursor-pointer items-center gap-2 text-xs text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(pT.A,{className:"size-3.5"}),s("nativeUiInfo"),(0,n.jsx)("span",{children:r.length>1?r.length:""}),(0,n.jsx)(eY.A,{className:"size-3.5 transition-transform group-open:rotate-180"})]}),(0,n.jsx)("div",{className:"max-h-36 space-y-2 overflow-y-auto px-2 pb-2 text-sm leading-6",children:r.map(([e,t])=>(0,n.jsx)("p",{className:"whitespace-pre-wrap wrap-anywhere",children:t.lines.join("\n")},e))})]}):null,i.length?(0,n.jsxs)("details",{className:"group",children:[(0,n.jsxs)("summary",{className:"flex min-h-7 cursor-pointer items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-1.5 shrink-0 rounded-full bg-current"}),(0,n.jsx)("span",{className:"min-w-0 truncate group-open:hidden",children:i[0]}),(0,n.jsx)("span",{className:"hidden group-open:inline",children:s("nativeUiStatus")}),i.length>1?(0,n.jsxs)("span",{children:["+",i.length-1]}):null]}),(0,n.jsx)("div",{className:"max-h-32 space-y-1 overflow-y-auto px-2 py-1 text-sm whitespace-pre-wrap wrap-anywhere",children:i.map((e,t)=>(0,n.jsx)("p",{children:e},t))})]}):null]}):null}let pB={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pq(e){return e<1048576?`${Math.max(1,Math.round(e/1024))}KB`:`${(e/1048576).toFixed(1)}MB`}let p_=(0,r.memo)(function({onOpenSettings:e,workSession:t,chatRuntime:s,inputRuntime:i,renderTaskSummary:a,renderTaskMenu:l,renderPluginComposerPanel:o,renderPluginWidgets:c,gitRuntime:d,active:u,widgetsVisible:m,mobile:p,invokePluginMethod:h,listPiCommands:g,getChatModelContext:f,capabilityModes:x,setChatCapabilityMode:w,newSessionPending:y,newSessionDisabled:k,onNewSession:j,clonePending:N,cloneDisabled:S,onCloneWorkSession:E,onOpenBranchPicker:M,onOpenGitBranchPicker:z}){var A;let $,R,D,T,O,{t:L}=(0,b.Bd)("workbench"),F=(0,X.G)(),B=(0,Q.So)(),q=(0,r.useMemo)(()=>uE.Pi.parse({workId:t.workId,sessionId:t.sessionId,branchId:t.branchId}),[t.branchId,t.sessionId,t.workId]),_=(0,r.useCallback)(()=>i.getState(q),[i,q]),W=(0,r.useCallback)(()=>s.getSourceState(q).runtime,[s,q]),Y=(0,r.useSyncExternalStore)(i.subscribe,_,_),U=(0,r.useSyncExternalStore)(s.subscribe,W,W),G=(0,r.useCallback)(()=>s.getSourceState(q).syncStatus,[s,q]),J="ready"===(0,r.useSyncExternalStore)(s.subscribe,G,G),Z=(A=s.nativeUi,$=(0,X.G)(),R=(0,r.useCallback)(()=>A.getState(q),[A,q]),D=(0,r.useSyncExternalStore)(A.subscribe,R,R),T=(0,r.useCallback)(()=>i.getState(q),[i,q]),O=(0,r.useSyncExternalStore)(i.subscribe,T,T),(0,r.useEffect)(()=>{A.watch(q)},[A,q]),(0,r.useEffect)(()=>A.onNotice((e,t)=>{e.workId===q.workId&&e.sessionId===q.sessionId&&e.branchId===q.branchId&&$.show({level:t.level,title:t.message})}),[A,q,$]),(0,r.useEffect)(()=>{!D.prefill||!O.loaded||O.loading||O.outbox||O.text.length>0||(i.setText(q,D.prefill.text),A.edit(q,{prefill:null}))},[A,q,i,D.prefill,O.loaded,O.loading,O.outbox,O.text]),{state:D,canStop:J,setAnswer:(e,t)=>A.edit(q,{answers:{...A.getState(q).answers,[e]:t}}),setCollapsed:e=>A.edit(q,{collapsed:e}),answer:(e,t)=>{A.respond(q,{id:e,value:t})},refresh:()=>{A.refreshSource(q)},dismissError:()=>A.edit(q,{error:null}),dismissNotices:()=>A.edit(q,{notices:[]}),usePrefill:e=>{let t=A.getState(q).prefill;if(t){if("dismiss"!==e){let s=i.getState(q).text;i.setText(q,"replace"===e?t.text:`${s}${s?"\n":""}${t.text}`)}A.edit(q,{prefill:null})}},stop:()=>{i.interrupt(q).catch(e=>$.error(e instanceof Error?e.message:String(e)))}}),ee=Z.state.snapshot.requests.length>0,en="basic"===U.extensionMode,er="basic"===U.presentationMode,ei=(0,r.useRef)(null),ea=(0,r.useRef)(null),el=(0,r.useRef)(null),eo=(0,r.useRef)(null),ec=function(e,t,s,n){let[i,a]=(0,r.useState)(!1);return(0,r.useLayoutEffect)(()=>{if(e)return;let r=t.current,i=r?.querySelector('[data-composer-tools="primary"]'),l=r?.querySelector('[data-composer-tools="metadata"]'),o=s.current;if(!r||!i||!l||!o)return;let c=0,d=null,u=()=>{if(null===d){let e=window.getComputedStyle(r);c=r.clientWidth-pc(e.paddingLeft)-pc(e.paddingRight);let t=pc(e.columnGap),s=pd(i),a=pd(l),u=pd(o),m=pc(window.getComputedStyle(i).columnGap),p=pc(window.getComputedStyle(l).columnGap),h=pc(window.getComputedStyle(o).columnGap),g=n.current,f=function(e){let t=[...new Set(e)],s=t.map(e=>({element:e,flex:e.style.flex,width:e.style.width,minWidth:e.style.minWidth}));try{for(let{element:e}of s)e.style.flex="0 0 auto",e.style.width="max-content",e.style.minWidth="max-content";return new Map(t.map(e=>[e,e.getBoundingClientRect().width]))}finally{for(let{element:e,flex:t,width:n,minWidth:r}of s)e.style.flex=t,e.style.width=n,e.style.minWidth=r}}([...s,...a,...u,...g?[g]:[]]),x=[pu(s,m,f),pu(a,p,f),g?f.get(g)??0:0,pu(u,h,f)].filter(e=>e>0);d=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*t}a(d>c+1)},m=null,p=()=>{null===m&&(m=window.requestAnimationFrame(()=>{m=null,u()}))},h=()=>{d=null,p()},g=new ResizeObserver(([e])=>{e&&c!==e.contentRect.width&&(c=e.contentRect.width,p())}),f=new MutationObserver(h);return g.observe(r),f.observe(r,{childList:!0,characterData:!0,subtree:!0}),window.addEventListener("resize",h),document.fonts.addEventListener("loadingdone",h),u(),()=>{g.disconnect(),f.disconnect(),window.removeEventListener("resize",h),document.fonts.removeEventListener("loadingdone",h),null!==m&&window.cancelAnimationFrame(m)}},[t,e,n,s]),i}(p,ea,el,eo),[ed,eu]=(0,r.useState)(null),[em,ep]=(0,r.useState)(null),eh=(0,r.useCallback)(()=>{ep(null)},[]),[eg,ef]=(0,r.useState)(!1),[ex,eb]=(0,r.useState)(null),[ev,ew]=(0,r.useState)(!1),[ey,ek]=(0,r.useState)(!1),[ej,eN]=(0,r.useState)(!1),[eI,eS]=(0,r.useState)(null),[eC,eE]=(0,r.useState)(null),eM=JSON.stringify([q.workId,q.sessionId,q.branchId]),ez=(0,r.useMemo)(()=>en?[]:B.flatMap(e=>e.contributions.flatMap(t=>"composer-panel"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[B,en]),eA=em?ez.find(e=>e.pluginName===em.pluginName&&e.descriptor.contributionName===em.contributionName):void 0;(0,r.useEffect)(()=>{let e=!0;return queueMicrotask(()=>{e&&(ep(e=>e&&e.sourceKey!==eM?null:e),eb(null))}),()=>{e=!1}},[eM]),(0,r.useEffect)(()=>{i.loadSource(q),i.loadModels(q)},[i,q]);let e$="main_running"===t.status,eR=e$||"background_running"===t.status,eP="completed"===t.status,eD=null!==eC,eT=eC?.text??Y.text,eO=eC?.images??Y.images,eL=0===eO.length&&eT.trim()===`/${pa.name}`,eF=eO.reduce((e,t)=>e+t.blob.size,0),eB=Y.outbox&&!(eD&&"sending"===Y.outbox.status)?Y.outbox:null,e_=e$&&!eD,eW=U.queues,eY=Y.images.reduce((e,t)=>e+t.blob.size,0),eV=Y.images.some(e=>"optimizing"===e.status),eU=Y.images.some(e=>"error"===e.status),eH=U.model,eK=eH?Y.models.models.find(e=>e.provider===eH.provider&&e.modelId===eH.modelId):null,eG=Y.images.length>0&&!eK?.input.includes("image"),eJ=eg&&!ey,eQ=J&&!ee&&Y.loaded&&!Y.outbox&&(Y.text.trim().length>0||Y.images.length>0)&&Y.images.length<=10&&!eV&&!eU&&eY<=0x1400000&&!eG,eX=U.plugins["task-center"],eZ=U.contextUsage,e0=eK?.name||eH?.modelId||L("noModelSelected"),e1=J?eH?`${e0} \xb7 ${L(pB[eH.thinkingLevel])}`:L("selectModel"):L("synchronizing"),e2=eH?L("modelTooltip",{model:e1}):L("chooseModel"),e5=ed??Y.error,e3=(0,r.useCallback)(async(e,t)=>{ef(!0),eu(null);try{await e(),t&&F.success(t)}catch(e){eu(e instanceof Error?e.message:L("operationFailed"))}finally{ef(!1)}},[L,F]),e4=(0,r.useCallback)(e=>{eu(null),w({source:q,capabilityMode:e}).catch(e=>{eu(e instanceof Error?e.message:L("modeChangeFailed"))})},[w,q,L]),e6=(0,r.useCallback)(async()=>{if(!ev&&"ready"===s.getSourceState(q).syncStatus){ew(!0);try{await e3(async()=>{await h({pluginName:"context-ignore",method:"ignore",scope:"session",source:q,input:{}})})}finally{ew(!1)}}},[s,ev,h,e3,q]),e8=(0,r.useCallback)(async()=>{if(!ey){ek(!0);try{await e3(()=>s.compact(q))}finally{ek(!1)}}},[s,ey,e3,q]),e7=(0,r.useCallback)(e=>{i.setText(q,`/${e.name} `)},[i,q]),e9=function({source:e,text:t,enabled:s,listPiCommands:n,onSelect:i}){let a=JSON.stringify([e.workId,e.sessionId,e.branchId]),[l,o]=(0,r.useState)(!1),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)({sourceKey:a,status:"idle",commands:[],error:null}),g=(0,r.useRef)(0),f=(0,r.useRef)(!0),x=s&&!l?/^\/[^\s/]*$/.test(t)?t.slice(1):null:null,b=null===x?null:`${a}\u0000${t}`,v=null!==b&&b!==c,{workId:w,sessionId:y,branchId:k}=e;(0,r.useEffect)(()=>(f.current=!0,()=>{f.current=!1,g.current+=1}),[]);let j=(0,r.useCallback)(async()=>{let e=++g.current;queueMicrotask(()=>{f.current&&g.current===e&&h(e=>e.sourceKey===a?{...e,status:"loading",error:null}:{sourceKey:a,status:"loading",commands:[],error:null})});try{let t=await n({source:{workId:w,sessionId:y,branchId:k}});if(!f.current||g.current!==e)return;h({sourceKey:a,status:"ready",commands:t.commands,error:null})}catch(t){if(!f.current||g.current!==e)return;throw console.warn("[Pi Desk][SlashCommand] 查询当前会话命令失败",{workId:w,sessionId:y,branchId:k,errorName:t instanceof Error?t.name:"UnknownError"}),h(e=>({sourceKey:a,status:"error",commands:e.sourceKey===a?e.commands:[],error:t instanceof Error?t.message:"查询命令失败"})),t}},[k,a,n,y,w]);(0,r.useEffect)(()=>{v&&j().catch(()=>void 0)},[v,j]);let N=(0,r.useMemo)(()=>[pa,...(p.sourceKey===a?p.commands:[]).filter(e=>e.name!==pa.name).map(e=>({key:`${e.source}:${e.name}`,name:e.name,description:e.description,source:e.source}))],[a,p.commands,p.sourceKey]),I=(0,r.useMemo)(()=>{let e;return e=(x??"").toLocaleLowerCase(),pl.flatMap(t=>{let s=N.map((t,s)=>({command:t,order:s,score:function(e,t){if(!t)return 3;let s=e.name.toLocaleLowerCase(),n=e.description?.toLocaleLowerCase()??"";return s===t?0:s.startsWith(t)?1:s.includes(t)?2:n.includes(t)?4:1/0}(t,e)})).filter(e=>e.command.source===t.source&&Number.isFinite(e.score)).sort((t,s)=>t.score!==s.score?t.score-s.score:e?t.order-s.order:t.command.name.localeCompare(s.command.name)).map(e=>e.command);return s.length>0?[{...t,commands:s}]:[]})},[N,x]),S=(0,r.useMemo)(()=>I.flatMap(e=>e.commands),[I]),C=b&&u?.contextKey===b?S.findIndex(e=>e.key===u.commandKey):-1,E=C>=0?C:0,M=(0,r.useCallback)(e=>{if(!b||0===S.length)return;let t=(e+S.length)%S.length,s=S[t];s&&m({contextKey:b,commandKey:s.key})},[S,b]),z=(0,r.useCallback)(()=>{b&&d(b)},[b]),A=(0,r.useCallback)(()=>{b&&d(null)},[b]),$=(0,r.useCallback)(e=>{let t=S[e];t&&(b&&d(b),i(t))},[S,b,i]),R=(0,r.useCallback)(e=>!!v&&!e.nativeEvent.isComposing&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&("Escape"===e.key?(e.preventDefault(),z(),!0):0!==S.length&&("ArrowDown"===e.key?(e.preventDefault(),M(E+1),!0):"ArrowUp"===e.key?(e.preventDefault(),M(E-1),!0):("Enter"===e.key||"Tab"===e.key)&&(e.preventDefault(),$(E),!0))),[E,S.length,z,v,$,M]),P=(0,r.useCallback)(()=>{o(!0)},[]),D=(0,r.useCallback)(()=>{o(!1),d(null)},[]);return{open:v,loading:p.sourceKey===a&&"loading"===p.status,error:p.sourceKey===a&&"error"===p.status?p.error:null,groups:I,commands:S,activeIndex:E,dismiss:z,reopen:A,refresh:j,select:$,setActiveIndex:M,handleKeyDown:R,handleCompositionStart:P,handleCompositionEnd:D}}({source:q,text:eT,enabled:u&&J&&Y.loaded&&!Y.loading&&!eD,listPiCommands:g,onSelect:e7}),te=e9.refresh,tt=(0,r.useCallback)(async e=>{if(!ej&&!eg){eN(!0);try{await e3(async()=>{await s.reload(q),await te(),await i.loadModels(q,!0),e&&i.setText(q,"")})}finally{eN(!1)}}},[eg,s,i,te,ej,e3,q]),ts=(0,r.useCallback)(e=>{eD||0===e.length||(eu(null),i.addFiles(q,e))},[eD,i,q]),tn=(0,r.useCallback)(async e=>{if("ready"!==s.getSourceState(q).syncStatus)return;if(eL){if(!Y.loaded||Y.loading)return;await tt(!0);return}if(!eQ||eJ)return;let t=e$?null:{text:Y.text,images:Y.images};t&&eE(t),eu(null);try{await i.send(q,e)}catch(e){eu(e instanceof Error?e.message:L("sendFailed"))}finally{t&&eE(null)}},[eQ,eJ,s,i,Y.images,Y.loaded,Y.loading,Y.text,eL,e$,tt,q,L]);return(0,n.jsxs)("div",{className:"mx-auto w-full max-w-3xl px-2 pb-2 sm:px-4 sm:pb-3",children:[eB?(0,n.jsx)("div",{className:(0,C.cn)("mb-2 rounded-lg border px-3 py-2 text-xs","unknown"===eB.status?"border-amber-500/50 bg-amber-500/10 text-amber-900 dark:text-amber-200":"failed"===eB.status?"border-destructive/40 bg-destructive/5 text-destructive":"border-border bg-muted/50 text-muted-foreground"),children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:"sending"===eB.status?L("confirmingSend"):"unknown"===eB.status?L("sendUnknown"):L("sendFailure",{error:eB.error??L("unknownError")})}),"sending"===eB.status?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:eg,onClick:()=>void e3(()=>i.restoreOutbox(q),L("outboxRestored")),children:[(0,n.jsx)(lP.A,{}),L("restoreDraft")]}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:eg,onClick:()=>void e3(()=>i.deleteOutbox(q),L("outboxDeleted")),children:[(0,n.jsx)(et.A,{}),L("delete")]})]})]})}):null,Y.notice||e5?(0,n.jsx)("div",{role:e5?"alert":"status",className:(0,C.cn)("mb-2 rounded-md px-2 py-1 text-sm",e5?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground"),children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:e5??Y.notice}),Y.loaded||Y.loading||!Y.error?Y.loaded?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{eu(null),i.dismissFeedback(q)},children:L("close",{ns:"common"})}):null:(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:eg,onClick:()=>void e3(()=>i.loadSource(q)),children:[(0,n.jsx)(lP.A,{}),L("retryDraft")]})]})}):null,a({source:q,cwd:t.cwd,pluginState:eX}),(0,n.jsx)(pL,{model:Z}),(0,n.jsx)(pF,{snapshot:Z.state.snapshot,placement:"aboveEditor"}),ee?(0,n.jsx)("p",{className:"mb-1 px-1 text-xs text-muted-foreground",children:L("nativeUiComposer")}):null,m&&!en?c({source:q,placement:"aboveEditor"}):null,(0,n.jsxs)("form",{"aria-label":eR?L("composerRunning"):eP?L("composerCompleted"):L("composer"),className:p$().inputFrame,"data-composer-mobile":p?"true":"false","data-composer-metadata-row":ec?"true":"false",onSubmit:e=>{e.preventDefault(),tn("auto")},onDragOver:e=>{e.dataTransfer.types.includes("Files")&&e.preventDefault()},onDrop:e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),ts([...e.dataTransfer.files]))},children:[(0,n.jsx)(pz,{open:e9.open,loading:e9.loading,error:e9.error,groups:e9.groups,activeIndex:e9.activeIndex,onActiveIndexChange:e9.setActiveIndex,onSelect:e9.select}),(0,n.jsx)("input",{ref:ei,type:"file",accept:"image/jpeg,image/png,image/webp,image/gif,image/bmp",multiple:!0,className:"hidden",onChange:e=>{e.currentTarget.files&&ts([...e.currentTarget.files]),e.currentTarget.value=""}}),(0,n.jsxs)(nC.MG,{className:"overflow-hidden rounded-xl border-border bg-card shadow-xs transition-[background-color,border-color] duration-150 ease-out has-disabled:bg-card has-disabled:opacity-100 dark:shadow-none motion-reduce:transition-none","aria-busy":eD,children:[eO.length>0?(0,n.jsxs)(nC.Sq,{align:"block-start",className:"pi-desk-chat-scrollbar gap-2 overflow-x-auto px-3 pt-3 pb-1",children:[eO.map(e=>(0,n.jsxs)("div",{className:"relative size-16 shrink-0 overflow-hidden rounded-md border bg-muted",title:`${e.name} \xb7 ${e.width}\xd7${e.height} \xb7 ${pq(e.blob.size)}`,children:[(0,n.jsx)("button",{type:"button",disabled:"ready"!==e.status,"aria-label":L("imagePreview",{name:e.name}),className:"group size-full cursor-zoom-in outline-none disabled:cursor-default focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",onClick:()=>{var t;let s,n;return t=e.localId,void(!((n=(s=eO.filter(e=>"ready"===e.status)).findIndex(e=>e.localId===t))<0)&&eS({index:n,slides:s.map(e=>({src:e.objectUrl,alt:e.name,width:e.width,height:e.height}))}))},children:(0,n.jsx)("img",{src:e.objectUrl,alt:e.name,className:"size-full object-cover transition-transform duration-200 group-hover:scale-105 motion-reduce:transition-none"})}),"optimizing"===e.status?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 grid place-items-center bg-background/85 text-xs",children:L("imageProcessing")}):null,"error"===e.status?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 bg-popover px-1 py-0.5 text-xs text-destructive",children:L("imageFailed")}):null,(0,n.jsx)("button",{type:"button","aria-label":L("imageRemove",{name:e.name}),"aria-disabled":eD,className:"absolute right-0.5 top-0.5 z-10 grid size-6 cursor-pointer place-items-center rounded-md bg-popover text-popover-foreground shadow-sm hover:bg-accent",onClick:()=>{eD||i.removeImage(q,e.localId)},children:(0,n.jsx)(V.A,{className:"size-3"})})]},e.localId)),(0,n.jsxs)("span",{className:"self-end whitespace-nowrap text-xs text-muted-foreground",children:[eO.length,"/10 \xb7 ",pq(eF)]})]}):null,(0,n.jsx)(nC.oR,{value:eT,disabled:!Y.loaded||Y.loading,readOnly:eD,"aria-disabled":eD,"aria-autocomplete":"list","aria-controls":e9.open?pi:void 0,"aria-expanded":e9.open,"aria-activedescendant":e9.open&&e9.commands.length>0?po(e9.activeIndex):void 0,placeholder:Y.loading?L("draftLoading"):!Y.loaded&&Y.error?L("draftFailed"):L("inputPlaceholder"),className:(0,C.cn)(p$().inputText,"pi-desk-chat-scrollbar max-h-48 min-h-9 overflow-y-auto px-3 pt-3 pb-1"),onChange:e=>i.setText(q,e.currentTarget.value),onClick:e9.reopen,onBlur:e9.dismiss,onCompositionStart:e9.handleCompositionStart,onCompositionEnd:e9.handleCompositionEnd,onKeyDown:e=>{e9.handleKeyDown(e)||"Enter"!==e.key||e.shiftKey||e.nativeEvent.isComposing||null===e.currentTarget.form||(e.preventDefault(),e.currentTarget.form.requestSubmit())},onPaste:e=>{let t=[...e.clipboardData?.items??[]].flatMap(e=>{if("file"!==e.kind)return[];let t=e.getAsFile();return t?[t]:[]});0!==t.length&&(e.preventDefault(),ts(t))}}),(0,n.jsxs)(lH,{ref:ea,className:p$().footer,children:[(0,n.jsxs)(lK,{"data-composer-tools":"primary",className:p$().primaryTools,children:[(0,n.jsxs)(K.rI,{children:[(0,n.jsx)(K.ty,{render:(0,n.jsx)(lG,{tooltip:L("more"),"aria-label":L("moreActions")}),children:(0,n.jsx)(H.A,{className:"size-4"})}),(0,n.jsxs)(K.SQ,{align:"start",side:"top",className:"w-52",children:[(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:L("session")}),(0,n.jsxs)(K._2,{"aria-label":L("switchBranch"),disabled:!J||!Y.loaded||Y.loading,onClick:()=>M(t.workId),children:[(0,n.jsx)(ul.A,{className:"size-4"}),L("sessionBranch"),(0,n.jsx)("span",{className:"ml-auto text-xs text-muted-foreground",children:L("escapeTwice")})]}),(0,n.jsxs)(K._2,{"aria-label":L("clone"),disabled:!J||S||N,title:0===t.messageCounts.total?L("cloneEmpty"):L("cloneTip"),onClick:E,children:[N?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(m4.A,{className:"size-4"}),N?L("cloning"):L("clone")]}),(0,n.jsxs)(K._2,{"aria-label":L("replaceSession"),"aria-busy":y,disabled:!J||k||y,onClick:j,children:[y?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(m6.A,{className:"size-4"}),y?L("replacing"):L("replaceSession")]})]}),(0,n.jsx)(K.mB,{}),(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:L("tools")}),l({source:q,cwd:t.cwd,pluginState:eX}),(0,n.jsxs)(K._2,{"aria-label":L("toolsAndContext",{defaultValue:"工具与上下文"}),disabled:!J||ee,onClick:()=>eb(eM),children:[(0,n.jsx)(nI.A,{className:"size-4"}),L("toolsAndContext",{defaultValue:"工具与上下文"})]}),(0,n.jsxs)(K._2,{"aria-label":L("reloadPi"),disabled:!Y.loaded||Y.loading||!J||eR||eg||ej,title:L("reloadPiTip"),onClick:()=>void tt(!1),children:[ej?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(es.A,{className:"size-4"}),ej?L("reloadingPi"):L("reloadPi")]}),er&&!en?(0,n.jsxs)(K._2,{disabled:!J||eg||ej,onClick:()=>void e3(()=>s.setPresentation(q,"normal")),children:[(0,n.jsx)(nI.A,{className:"size-4"}),L("restorePluginPresentation")]}):null]}),ez.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(K.mB,{}),(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:L("plugins")}),ez.map(e=>(0,n.jsxs)(K._2,{onClick:()=>ep({pluginName:e.pluginName,contributionName:e.descriptor.contributionName,sourceKey:eM}),children:[(0,n.jsx)(eq,{icon:e.descriptor.icon,className:"size-4"}),(0,n.jsx)("span",{className:"truncate",children:e.descriptor.label})]},`${e.pluginName}:${e.descriptor.contributionName}`))]})]}):null]})]}),(0,n.jsx)(lG,{tooltip:L("addImage"),"aria-label":L("addImage"),disabled:Y.images.length>=10,"aria-disabled":eD||Y.images.length>=10,onClick:()=>{eD||ei.current?.click()},children:(0,n.jsx)(m8.A,{className:"size-4"})}),eZ&&eK?.contextWindow!==null?(0,n.jsx)(px,{sessionId:t.sessionId,cwd:t.cwd,tokens:eZ.tokens,contextWindow:eZ.contextWindow,contextIgnorePlugin:U.plugins["context-ignore"],ignoreDisabled:!J||e$||eg,ignorePending:ev,compactDisabled:!J||e$||eg,compactPending:ey,onIgnoreContext:e6,onCompactContext:e8}):eK?.contextWindow===null?(0,n.jsx)("span",{className:"px-1 text-xs text-muted-foreground",children:L("modelContextUnknown",{defaultValue:"上下文未知"})}):null]}),(0,n.jsxs)(lK,{"data-composer-tools":"metadata",className:p$().metadataTools,children:[(0,n.jsx)(pr,{workSession:t,runtime:d,active:u,chatReady:J,onOpen:z}),(0,n.jsx)(pR,{modes:x,value:U.capabilityMode,disabled:!J,onChange:e4}),(0,n.jsx)(pI,{source:q,runtime:i,catalog:Y.models,current:eH,label:e1,title:e2,disabled:!J||eR||eD||eg,triggerClassName:p$().modelTrigger,detailsClassName:p$().modelTriggerDetails,onOpenSettings:e},eM)]}),e$&&eD?(0,n.jsx)("span",{ref:eo,className:"min-w-0 truncate px-2 text-xs text-muted-foreground",children:L("preparingContext")}):null,(0,n.jsxs)("div",{ref:el,className:p$().submitTools,children:[(0,n.jsx)(pE,{queues:eW,disabled:!J||eg,onRestore:()=>void e3(()=>i.restoreQueue(q),L("queuesRestored"))}),e_?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(lG,{tooltip:L("steerNow"),"aria-label":L("steerNow"),variant:"secondary",disabled:!eQ||eJ,onClick:()=>void tn("auto"),children:(0,n.jsx)(P.A,{className:"size-3.5"})}),(0,n.jsx)(lG,{tooltip:L("sendFollowUp"),"aria-label":L("sendFollowUp"),variant:"outline",disabled:!eQ||eJ,onClick:()=>void tn("follow_up"),children:(0,n.jsx)(m7.A,{className:"size-3.5"})}),(0,n.jsx)(lG,{tooltip:L("stopResponse"),"aria-label":L("stopResponse"),variant:"destructive",disabled:!J||eg,onClick:()=>void e3(()=>i.interrupt(q)),children:(0,n.jsx)(m9.A,{className:"size-3.5 fill-current"})})]}):(0,n.jsx)(I.$,{type:eD?"button":"submit",size:"icon",disabled:!eD&&(!eQ||eJ),"aria-disabled":eD||!eQ||eJ,"aria-busy":eD,"aria-label":eD?L("sending"):J?L("send"):L("synchronizing"),children:eD?(0,n.jsx)(pe.A,{className:"size-4"}):J?(0,n.jsx)(pt.A,{}):(0,n.jsx)(v.A,{className:"size-4 animate-spin"})})]})]})]})]}),m&&!en?c({source:q,placement:"belowEditor"}):null,(0,n.jsx)(pF,{snapshot:Z.state.snapshot,placement:"belowEditor"}),em&&em.sourceKey===eM&&eA?o({pluginName:em.pluginName,descriptor:eA.descriptor,source:q,onClose:eh}):null,ex===eM&&J?(0,n.jsx)(pj,{open:!0,source:q,runtime:i,getContext:f,listCommands:g,nativeUi:Z,nativeBiz:s.nativeUi,commandsDisabled:eR||eD||eg,onOpenChange:e=>eb(e?eM:null),onOpenSettings:e},eM):null,eI?(0,n.jsx)(ny.k,{mode:"modal",open:!0,slides:eI.slides,index:eI.index,ariaLabel:L("imagePreviewPending"),onClose:()=>eS(null),onIndexChange:e=>eS(t=>t?{...t,index:e}:t)}):null,Y.images.length>10?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:L("tooManyImages")}):eG?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:L("imageUnsupported")}):eY>0x1400000?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:L("imagesTooLarge")}):null]})});p_.displayName="L2WorkbenchChatComposer";var pW=s(61600);function pY({svgRef:e}){let t=(0,r.useId)(),s=`${t}-head`,i=`${t}-fur`;return(0,n.jsxs)("svg",{ref:e,viewBox:"0 0 640 560",fill:"none","aria-hidden":"true",className:"pointer-events-none absolute left-1/2 top-1/2 max-w-none -translate-x-1/2 -translate-y-1/2 overflow-visible",style:{width:"144.8%",height:"168.93%"},children:[(0,n.jsxs)("g",{"data-part":"busy-dots",opacity:"0",fill:"currentColor",children:[(0,n.jsx)("circle",{cx:"294",cy:"481",r:"5.5"}),(0,n.jsx)("circle",{cx:"320",cy:"481",r:"5.5"}),(0,n.jsx)("circle",{cx:"346",cy:"481",r:"5.5"})]}),(0,n.jsx)("g",{"data-part":"head",children:(0,n.jsxs)("g",{transform:"translate(64 20)",children:[(0,n.jsxs)("defs",{children:[(0,n.jsx)("path",{id:s,d:"M256 88C190 88 132 109 90 161C62 153 35 171 35 198C35 217 45 231 61 240L54 277C47 316 64 353 104 379C144 406 195 419 256 419C317 419 368 406 408 379C448 353 465 316 458 277L451 240C467 231 477 217 477 198C477 171 450 153 422 161C380 109 322 88 256 88Z"}),(0,n.jsxs)("mask",{id:i,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"512",height:"512",children:[(0,n.jsx)("rect",{width:"512",height:"512",fill:"white"}),(0,n.jsx)("path",{fill:"black",d:"M170 272C201 253 229 240 256 240C283 240 311 253 342 272C383 255 425 261 444 288C472 327 443 369 406 389C367 430 315 448 256 448C197 448 145 430 106 389C69 369 40 327 68 288C87 261 129 255 170 272Z"})]})]}),(0,n.jsx)("use",{href:`#${s}`,fill:"#F3E2C6"}),(0,n.jsx)("use",{href:`#${s}`,fill:"#B87945",mask:`url(#${i})`}),(0,n.jsxs)("g",{fill:"#303030",children:[(0,n.jsx)("path",{d:"M76 180C62 177 53 186 53 198C53 207 57 215 64 220L76 180Z"}),(0,n.jsx)("path",{d:"M436 180C450 177 459 186 459 198C459 207 455 215 448 220L436 180Z"})]}),(0,n.jsxs)("g",{"data-part":"face",children:[["left","right"].map((e,t)=>(0,n.jsxs)("g",{"data-part":`${e}-eye`,transform:`translate(${0===t?158:354} 239)`,children:[(0,n.jsx)("path",{"data-part":`${e}-eye-shape`,fill:"#303030",d:"M-26 0a26 28 0 1 0 52 0a26 28 0 1 0-52 0"}),(0,n.jsx)("circle",{"data-part":`${e}-eye-shine`,cx:"8",cy:"-11",r:"6.5",fill:"#fff"})]},e)),(0,n.jsxs)("g",{"data-part":"cheeks",fill:"#D69973",opacity:"0",children:[(0,n.jsx)("ellipse",{cx:"133",cy:"316",rx:"26",ry:"13"}),(0,n.jsx)("ellipse",{cx:"379",cy:"316",rx:"26",ry:"13"})]}),(0,n.jsx)("path",{fill:"#303030",d:"M219 269C219 254 240 254 256 254C272 254 293 254 293 269C293 282 276 299 256 303C236 299 219 282 219 269Z"}),(0,n.jsxs)("g",{"data-part":"smile",stroke:"#303030",strokeLinecap:"round",strokeWidth:"10",children:[(0,n.jsx)("path",{d:"M256 300C256 317 246 327 232 327C220 327 211 322 207 314"}),(0,n.jsx)("path",{d:"M256 300C256 317 266 327 280 327C292 327 301 322 305 314"})]}),(0,n.jsxs)("g",{"data-part":"mouth",opacity:"0",children:[(0,n.jsx)("ellipse",{cx:"256",cy:"333",rx:"16",ry:"22",fill:"#303030"}),(0,n.jsx)("ellipse",{cx:"256",cy:"347",rx:"9",ry:"5",fill:"#D69973"})]}),(0,n.jsx)("g",{stroke:"#303030",strokeLinecap:"round",strokeWidth:"9",children:(0,n.jsx)("path",{d:"M101 298C116 293 132 292 146 292M110 327C123 318 135 312 148 310M411 298C396 293 380 292 366 292M402 327C389 318 377 312 364 310"})})]})]})}),(0,n.jsxs)("g",{"data-part":"thoughts",fill:"currentColor",opacity:"0",children:[(0,n.jsx)("circle",{cx:"504",cy:"132",r:"5"}),(0,n.jsx)("circle",{cx:"524",cy:"102",r:"8"}),(0,n.jsx)("circle",{cx:"544",cy:"65",r:"11"})]}),(0,n.jsx)("g",{"data-part":"surprise",stroke:"currentColor",strokeWidth:"7",strokeLinecap:"round",opacity:"0",children:(0,n.jsx)("path",{d:"M465 91L479 66M498 113L521 100M443 69L446 44"})}),(0,n.jsxs)("g",{"data-part":"sleep",fill:"currentColor",fontFamily:"Arial,sans-serif",fontWeight:"600",opacity:"0",children:[(0,n.jsx)("text",{x:"479",y:"137",fontSize:"24",children:"z"}),(0,n.jsx)("text",{x:"522",y:"92",fontSize:"32",children:"z"})]}),(0,n.jsxs)("g",{"data-part":"sparkles",opacity:"0",fill:"#BE8656",children:[(0,n.jsx)("path",{d:"M93 158Q96 177 111 180Q96 184 93 202Q90 184 75 180Q90 177 93 158Z"}),(0,n.jsx)("path",{d:"M545 126Q550 151 570 155Q550 159 545 184Q540 159 521 155Q540 151 545 126Z"}),(0,n.jsx)("circle",{cx:"513",cy:"76",r:"5"})]})]})}let pV={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},pU=Object.keys(pV),pH={idle:.46,hello:.36,point:.45,think:.5,busy:.4,happy:.35,surprise:.2,sleep:.72};function pK(e){return Math.min(1,Math.max(0,e))}function pG(e){let t=pK(e);return t*t*t*(t*(6*t-15)+10)}function pJ(e,t){let s={...pV};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=pG(e/1.45),r=pG((e-2.15)/.65),i=Math.exp(-Math.pow((e-1.9)/.22,2));s.gazeX=-11+22*n-22*r,s.gazeY=8+2*i,s.angle=.1*s.gazeX,s.y=3+4*i,s.eye=.9+.05*i,s.sy=1-.006*i,s.busy=1,s.follow=0;break}case"happy":{let e=(1-Math.cos(5.5*t))/2;s.y=-(14*e),s.sx=1.025-.035*e,s.sy=.975+.045*e,s.angle=4*Math.sin(2.5*t),s.smile=1,s.blush=.6,s.sparkle=1,s.follow=.15;break}case"surprise":s.y=-9-6*Math.exp(-(1.5*t)),s.eye=1.2,s.mouth=1,s.sx=.96,s.sy=1.045,s.surprise=1,s.follow=.25;break;case"sleep":s.angle=11+2*Math.sin(1.25*t),s.y=6+3*Math.sin(1.25*t),s.sy=.965+.01*Math.sin(1.25*t),s.sleepy=1,s.sleep=1,s.follow=0;break;default:s.gazeX=4*Math.sin(.8*t),s.gazeY=2*Math.sin(.67*t)}return s}class pQ{setState(e,t){if(e===this.state)return;let s=this.transition&&t-this.transition.at<pH[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=pJ(this.state,t?1.2:Math.max(0,e-this.started));if(!this.transition||t)return s;let n=pK((e-this.transition.at)/pH[this.state]);if(1===n)return s;let r="pose"in this.transition?this.transition.pose:pJ(this.transition.state,Math.max(0,e-this.transition.started)),i=1-(1-n)**5;for(let e of pU)s[e]=r[e]+(s[e]-r[e])*i;return s}constructor(){this.state="idle",this.started=0,this.transition=null}}let pX=["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 pZ(e,t=0,s=1){return Math.min(s,Math.max(t,e))}function p0(e){return e.toFixed(3)}function p1({state:e,active:t=!0,size:s=100,className:i}){let a=(0,r.useRef)(null),l=(0,r.useRef)(null);return(0,r.useEffect)(()=>{let e=function(e){let t=Object.fromEntries(pX.map(t=>[t,e.querySelector(`[data-part="${t}"]`)])),s=e.parentElement,n=new pQ,r=matchMedia("(prefers-reduced-motion: reduce)"),i=!0,a=!1,l=0,o=null,c=0,d=-10,u=1.7,m={x:0,y:0},p={x:0,y:0};function h(e,s){t[e].setAttribute("opacity",p0(s))}function g(e,s){t[e].setAttribute("transform",s)}function f(){let e=n.sample(c,r.matches),s=r.matches?1.2:c,i=r.matches?0:.005*Math.sin(1.7*c),a=e.gazeX+(r.matches?0:m.x*e.follow),l=e.gazeY+(r.matches?0:m.y*e.follow);g("head",`translate(${p0(e.x)} ${p0(e.y)}) translate(320 274) rotate(${p0(e.angle+(r.matches?0:m.x*e.follow*.12))}) scale(${p0(e.sx)} ${p0(e.sy+i)}) translate(-320 -274)`),g("face",`translate(${p0(.16*a)} ${p0(.12*l)})`);let o=r.matches?-1:(c-d)/.19,u=o>=0&&o<=1?.07+.93*Math.abs(2*o-1):1;for(let[s,n]of[["left",158],["right",354]]){g(`${s}-eye`,`translate(${p0(n+a)} ${p0(239+l)})`);let r=1-pZ(e.smile+e.sleepy),i=(3.5+(28*e.eye-3.5)*r)*u*("left"===s?1-e.wink:1);t[`${s}-eye-shape`].setAttribute("d",function(e,t,s){let n=p0(e),r=p0(t+s),i=p0(-t+s),a=p0(.5523*e),l=p0(-(.5523*t)+s),o=p0(.5523*t+s);return`M-${n} 0C-${n} ${l} -${a} ${i} 0 ${i}C${a} ${i} ${n} ${l} ${n} 0C${n} ${o} ${a} ${r} 0 ${r}C-${a} ${r} -${n} ${o} -${n} 0Z`}(22+4*r,i,(-13*e.smile+8*e.sleepy)*u)),h(`${s}-eye-shine`,r*pZ((i-8)/16))}h("smile",1-e.mouth),h("mouth",e.mouth),h("cheeks",e.blush),h("thoughts",e.thought),Array.from(t.thoughts.children).forEach((e,t)=>{e.setAttribute("opacity",p0(.25+.75*(1+Math.sin(2.8*s-.9*t))/2)),e.setAttribute("transform",`translate(0 ${p0(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(${p0(8*n)} ${p0(-(20*n))})`),e.setAttribute("opacity",p0(Math.sin(n*Math.PI)))}),h("sparkles",e.sparkle*(.55+.45*(1+Math.sin(3*s))/2)),g("sparkles",`translate(0 ${p0(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*pZ(((s-.18*t)%1.4+1.4)%1.4/.55));e.setAttribute("opacity",p0(.26+.65*n)),e.setAttribute("transform",`translate(0 ${p0(-4*n)})`)})}function x(){return i&&a&&!document.hidden&&!r.matches}function b(e){if(l=0,!x())return;let t=null===o?0:Math.min((e-o)/1e3,.05);o=e,(c+=t)>=u&&(d=c,u=c+2.4+2.8*Math.random());let s=1-Math.exp(-(9*t));m.x+=(p.x-m.x)*s,m.y+=(p.y-m.y)*s,f(),l=requestAnimationFrame(b)}function v(){cancelAnimationFrame(l),l=0,o=null,f(),x()&&(l=requestAnimationFrame(b))}function w(e){if("mouse"!==e.pointerType||!x())return;let t=s.getBoundingClientRect();p.x=pZ((e.clientX-t.left-t.width/2)/Math.max(t.width,window.innerWidth/2)*24,-18,18),p.y=pZ((e.clientY-t.top-t.height/2)/Math.max(t.height,window.innerHeight/2)*20,-14,12)}function y(){p.x=0,p.y=0}let k=new IntersectionObserver(([e])=>{a=e.isIntersecting,v()});return k.observe(s),document.addEventListener("visibilitychange",v),r.addEventListener("change",v),document.addEventListener("pointermove",w,{passive:!0}),document.documentElement.addEventListener("pointerleave",y),window.addEventListener("blur",y),f(),{setState(e){n.setState(e,c),"point"!==e&&"think"!==e||r.matches||(d=c),f()},setActive(e){i=e,v()},dispose(){cancelAnimationFrame(l),k.disconnect(),document.removeEventListener("visibilitychange",v),r.removeEventListener("change",v),document.removeEventListener("pointermove",w),document.documentElement.removeEventListener("pointerleave",y),window.removeEventListener("blur",y)}}}(a.current);return l.current=e,()=>{e.dispose(),l.current=null}},[]),(0,r.useEffect)(()=>{l.current?.setState(e)},[e]),(0,r.useEffect)(()=>{l.current?.setActive(t)},[t]),(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("relative block shrink-0 text-muted-foreground",i),style:{width:s,height:.75*s},children:(0,n.jsx)(pY,{svgRef:a})})}let p2=Object.keys(dY.R.en).filter(e=>e.startsWith("emptyQuip")),p5=null;function p3(){let{t:e}=(0,b.Bd)("workbench"),t=(0,mG.tF)(),s=!0===(0,pW.D)(),i=(0,mJ.I)(),{state:a,textKey:l}=function(e){let[t,s]=(0,r.useState)(null),[n,i]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{let e=requestAnimationFrame(()=>{let e,t;return s((e=Math.floor(Math.random()*(null===p5?p2.length:p2.length-1)),null!==p5&&e>=p5&&(e+=1),p5=e,"emptyQuip16"===(t=p2[e])||"emptyQuip10"===t?{quip:t,waiting:"sleep",reaction:"surprise",recover:"hello",reply:"emptyWakeReply"}:"emptyQuip1"===t||"emptyQuip14"===t?{quip:t,waiting:"sleep",reaction:"hello",recover:"idle",reply:"emptyFishReply"}:"emptyQuip12"===t||"emptyQuip15"===t?{quip:t,waiting:"think",reaction:"surprise",recover:"idle",reply:"emptyCuriousReply"}:{quip:t,waiting:"idle",reaction:"happy",recover:"hello",reply:"emptyPartnerReply"}))});return()=>cancelAnimationFrame(e)},[]),(0,r.useEffect)(()=>{let t=window.setTimeout(()=>i(!e),320*!e);return()=>window.clearTimeout(t)},[e]),{state:t?e?t.waiting:n?t.recover:t.reaction:"sleep",textKey:t?e?t.quip:t.reply:null}}(t);return t||s&&!i?(0,n.jsxs)(o6.PY1.div,{"data-testid":"workbench-empty-session","data-otter-state":a,"data-leaving":t?void 0:"true",initial:!1,animate:{opacity:1,y:0},exit:{opacity:0,y:-4,transition:{delay:.55,duration:1.15,ease:"easeInOut"}},className:"flex max-w-sm flex-col items-center gap-5",children:[(0,n.jsx)(p1,{state:a,size:100}),(0,n.jsx)("p",{className:"min-h-6 text-sm leading-6 text-muted-foreground",children:l?e(l):null})]}):null}function p4({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)(mK.N,{initial:!1,custom:e&&t&&r,children:e&&t&&s?(0,n.jsx)(p3,{},"welcome"):null}),e&&!t&&s?(0,n.jsx)(mV,{variant:"loading"}):null]})}function p6({active:e,turns:t,window:s}){return e?(0,n.jsx)(oz,{turns:t,window:s}):null}function p8(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function p7(){return"visible"===document.visibilityState}function p9(){return!0}function he(e,t){e.scrollTop=t.scrollTop}function ht(e){let t=e.getBoundingClientRect().top,s=null;for(let n of e.querySelectorAll("[data-chat-scroll-anchor]")){let e=n.dataset.chatScrollAnchor;if(!e)continue;let r=n.getBoundingClientRect().top-t,i=Math.abs(r);(!s||i<s.distance)&&(s={messageId:e,offset:r,distance:i})}return s?{messageId:s.messageId,offset:s.offset}:null}function hs({active:e,visible:t=!0,running:s,ready:n,containsTail:i,latestUserAnchor:a,entrySnapshot:l,onResetToTail:o,onSaveSnapshot:c,onClearSnapshot:d}){let{isAtBottom:u,scrollRef:m,scrollToBottom:p,state:h,stopScroll:g}=(0,lT.B)(),f=(0,r.useSyncExternalStore)(p8,p7,p9),x=(0,r.useRef)(f),b=(0,r.useRef)(!1),v=(0,r.useRef)(!1),w=(0,r.useRef)(null),y=(0,r.useRef)(null),k=(0,r.useRef)(s?l:null),j=(0,r.useRef)(null);return(0,r.useLayoutEffect)(()=>{let e=m.current;if(!e||!t||!u)return;let s=e.style.overflowAnchor;return e.style.overflowAnchor="none",oc("viewport:anchor-lock",e),()=>{e.style.overflowAnchor=s}},[u,m,t]),(0,r.useLayoutEffect)(()=>{let n=m.current;if(!n)return;if(!e&&!s){v.current=!1,k.current=null,y.current=null,j.current=null,g(),oc("viewport:leave-ended",n);return}if(!t){y.current=null,v.current&&null===j.current&&(j.current=!e&&i&&h.isAtBottom?"follow":{snapshot:ht(n),scrollTop:n.scrollTop},oc("viewport:suspend",n,{follow:"follow"===j.current})),g();return}let r=j.current;if(null!==r){if("follow"===r)d(),n.scrollTop=Math.max(0,n.scrollHeight-n.clientHeight),he(h,n),p({animation:"instant"}),oc("viewport:restore-follow",n);else{g();let{snapshot:e}=r,t=e?od(n,"data-chat-scroll-anchor",e.messageId):null;e&&t?ox(n,t,e.offset,i):n.scrollTop=r.scrollTop,he(h,n),oc("viewport:restore-reading",n,{running:s,snapshot:e})}v.current=!0,w.current=a,j.current=null}},[e,i,a,d,s,m,p,h,g,t]),(0,r.useLayoutEffect)(()=>{let e=f&&!x.current;if(x.current=f,e&&t&&!s&&(v.current=!1,k.current=null,y.current=null),!n||!t||!f)return;s||d();let r=!v.current,l=null!==a&&a!==w.current,c=l?null:y.current;if(!r&&!l&&!c)return;if(r&&!s&&!i)return void o();let u=m.current;l&&(y.current=null,d(),u&&og(u));let j=null,N=null,I=null;b.current=!0;let S=()=>{let e=m.current;if(!e){b.current=!1;return}oc("viewport:initialize:start",e,{initializing:r,running:s,containsTail:i,latestUserAnchor:a});let t=null,n=12,l=c?c.anchor:r&&s?k.current:null;if(l){let s=od(e,"data-chat-scroll-anchor",l.messageId);s&&(t=s,n=l.offset)}!t&&a&&(t=od(e,"data-chat-scroll-anchor",a)),t??=od(e,"data-chat-user-message",void 0);let o=c?.follow??(null!==t&&null===l&&(s||!r)),d=c?.follow??(r&&s&&null===l),u=t;if(g(),u?ox(e,u,n,i):og(e),(d||!u)&&(e.scrollTop=Math.max(0,h.calculatedTargetScrollTop)),he(h,e),(o||!u)&&p({animation:"instant"}),oc("viewport:initialize:positioned",e,{initializing:r,running:s,target:t?.dataset.chatScrollAnchor??null,followAfterPosition:o,enterRunningAtBottom:d}),v.current=!0,w.current=a,k.current=null,r||c){let s=t?.dataset.chatScrollAnchor;y.current={anchor:s?{messageId:s,offset:n}:null,follow:o||null===t};let r=new ResizeObserver(()=>{o||!u?(of(e),e.scrollTop=Math.max(0,h.calculatedTargetScrollTop)):(h.isAtBottom&&g(),ox(e,u,n,i)),he(h,e)});r.observe(e),e.firstElementChild&&r.observe(e.firstElementChild);let a=e.parentElement,l=["wheel","touchstart","pointerdown","keydown","click"],c=e=>{for(let e of(r.disconnect(),l))a.removeEventListener(e,c,!0);e&&(y.current=null),I=null,b.current=!1};for(let e of l)a.addEventListener(e,c,{passive:!0,capture:!0});I=c}N=window.requestAnimationFrame(()=>{b.current=null!==I})};return m.current?S():j=window.requestAnimationFrame(S),()=>{null!==j&&window.cancelAnimationFrame(j),null!==N&&window.cancelAnimationFrame(N),I?.(),b.current=!1}},[i,a,d,o,f,n,s,m,p,h,g,t]),(0,r.useEffect)(()=>{let e=m.current;if(!e||!t)return;let s=()=>{if(oc("viewport:scroll",e,{positioning:b.current,isAtBottom:h.isAtBottom,escapedFromLock:h.escapedFromLock,resizeDifference:h.resizeDifference}),b.current||h.isAtBottom)return;let t=e.querySelector("[data-chat-tail-space]");!t||t.dataset.chatTailAnchor!==a||e.scrollHeight-e.scrollTop-e.clientHeight<=2&&(oc("viewport:resume-follow",e,{isAtBottom:h.isAtBottom,escapedFromLock:h.escapedFromLock}),d(),p({animation:"instant"}))};return e.addEventListener("scroll",s,{passive:!0}),()=>e.removeEventListener("scroll",s)},[a,d,m,p,h,t]),(0,r.useLayoutEffect)(()=>{if(!s||!t)return;let e=m.current;if(!e)return;let n=()=>{if(b.current)return;if(i&&h.isAtBottom)return void d();let t=ht(e);t?c(t):d()};return e.addEventListener("scroll",n,{passive:!0}),()=>{e.removeEventListener("scroll",n),n()}},[i,d,c,s,m,h,t]),null}let hn=(0,r.memo)(function({active:e,visible:t,workSession:s,chatRuntime:i,inputRuntime:a,onPreviewFile:l}){let{t:o}=(0,b.Bd)("workbench"),c=(0,r.useMemo)(()=>uE.Pi.parse({workId:s.workId,sessionId:s.sessionId,branchId:s.branchId}),[s.branchId,s.sessionId,s.workId]),d=(0,r.useMemo)(()=>i.getViewportSnapshot(c),[i,c]),u=(0,r.useCallback)(()=>i.getSourceState(c),[i,c]),m=(0,r.useSyncExternalStore)(i.subscribe,u,u),p="main_running"===s.status||"background_running"===s.status,h=(0,r.useMemo)(()=>oi({messages:m.messages,temporaryMessages:m.temporaryMessages},p),[p,m.messages,m.temporaryMessages]),g=m.messages.length>0||m.temporaryMessages.length>0,f=m.messages.some(e=>"user"===e.fixed.type)||m.temporaryMessages.some(e=>"user"===e.fixed.type),x=p||m.temporaryMessages.length>0,v=h.findLast(e=>null!==e.user)??null,w=v?.user??null,y=w?`${w.identity}:user`:null,k=(0,r.useCallback)(async e=>e.durable?void 0!==e.detail?e.detail:i.loadMessageDetail(c,e.durable.location.index,e.durable.location.entryId):null,[i,c]),j=(0,r.useCallback)((e,t)=>a.acquireMessageImage({source:c,tempId:e.tempId,entryId:e.durable?.location.entryId??null,imageIndex:t}),[a,c]),N=(0,r.useCallback)(e=>l(c,e),[l,c]),I=(0,r.useCallback)(e=>{i.saveViewportSnapshot(c,e)},[i,c]),S=(0,r.useCallback)(()=>{i.clearViewportSnapshot(c)},[i,c]),C=(0,r.useCallback)(()=>i.setPresentation(c,"basic"),[i,c]);return(0,n.jsx)(o$,{basic:"basic"===m.runtime.presentationMode,onRecover:C,children:(0,n.jsxs)(lO,{className:"min-h-0",initial:!1,resize:"instant","aria-label":o("chatMessages",{name:s.sessionTitle??s.projectName}),children:[(0,n.jsx)(oI,{turns:h,active:t,focusTurnIdentity:v?.identity??null,initialAnchor:x?d?.messageId??null:null,children:r=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cv,{children:(0,n.jsx)(lL,{scrollClassName:"pi-desk-chat-scrollbar pi-desk-chat-conversation-scroll overflow-auto",className:"mx-auto min-h-full w-full max-w-3xl gap-6 px-3 pt-3 pb-4 sm:px-5",children:r.visibleTurns.map((e,t)=>{let i=r.startIndex+t;return(0,n.jsx)(c6,{turn:e,cwd:s.cwd,logicalTail:r.containsTail&&i===h.length-1,onLoadDetail:k,onAcquireImage:j,onPreviewFile:N},e.identity)})})}),(0,n.jsx)(hs,{active:e,visible:t,running:x,ready:g,containsTail:r.containsTail,latestUserAnchor:y,entrySnapshot:d,onResetToTail:r.resetToTail,onSaveSnapshot:I,onClearSnapshot:S},`viewport:${c.sessionId}:${c.branchId}`),(0,n.jsx)(ob,{active:t}),(0,n.jsx)(p6,{active:t,turns:h,window:r},`navigation:${c.sessionId}:${c.branchId}`)]})},`window:${c.sessionId}:${c.branchId}`),(0,n.jsx)(p4,{active:t,ready:"ready"===m.syncStatus,empty:!g,hasUserMessage:f})]})})});hn.displayName="L2WorkbenchChatView";var hr=s(78653),hi=s.n(hr);function ha({error:e,copied:t,reloading:s,canReload:r,onCopy:i,onReload:a}){let{t:l}=(0,b.Bd)("workbench");return(0,n.jsxs)(eW.AM,{children:[(0,n.jsxs)(eW.Wv,{openOnHover:!0,delay:150,closeDelay:150,render:(0,n.jsx)(I.$,{variant:"ghost",size:"sm","aria-label":l("initializationDegraded"),title:l("initializationDegraded"),className:(0,C.cn)(hi().headerAction,"text-xs text-destructive hover:text-destructive")}),children:[(0,n.jsx)(Y.A,{className:(0,C.cn)(hi().headerActionIcon,"size-4"),"aria-hidden":"true"}),(0,n.jsx)("span",{className:hi().headerActionLabel,children:l("initializationDegraded")})]}),(0,n.jsxs)(eW.hl,{align:"end",alignOffset:8,className:"max-h-[min(28rem,var(--available-height))] w-[28rem] gap-0 overflow-hidden p-0",initialFocus:e=>"keyboard"===e,children:[(0,n.jsx)(eW.eO,{className:"shrink-0 border-b px-3 py-2",children:l("initializationDetails")}),(0,n.jsx)("pre",{className:"min-h-0 overflow-auto overscroll-contain whitespace-pre-wrap break-words p-3 font-mono text-sm leading-[1.6]","aria-label":l("initializationDetails"),children:e}),(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t px-3 py-2",children:[(0,n.jsxs)(I.$,{variant:"outline",size:"sm",onClick:i,children:[t?(0,n.jsx)(ep.A,{}):(0,n.jsx)(ee.A,{}),l(t?"copied":"copyInitializationError")]}),(0,n.jsxs)(I.$,{size:"sm",disabled:!r,onClick:a,children:[s?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(es.A,{}),l(s?"reloadingPi":"reloadPi")]})]})]})]})}var hl=s(4780),ho=s.n(hl);function hc({sidebarOpen:e,onOpen:t}){let{t:s}=(0,b.Bd)("workbench"),r=(0,mJ.I)();return(0,n.jsxs)("div",{"data-testid":"workbench-session-guide",className:ho().guide,children:[(0,n.jsx)(p1,{state:e?"idle":"point",size:120,className:ho().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:ho().arrow,fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)(o6.PY1.path,{d:"M30 26Q10 25 9 10",initial:!r&&{pathLength:0},animate:{pathLength:1},transition:{duration:.7*!r,ease:"easeOut"},opacity:".65"}),(0,n.jsx)("path",{d:"M4 16L9 10L15 15",opacity:".65"})]}),(0,n.jsx)(I.$,{variant:"ghost","aria-label":s("showSessionMenu"),onClick:t,className:"absolute inset-0 size-full p-0 hover:bg-foreground/5"})]})]})}var hd=s(45087);let hu=r.createContext(null);function hm(){let e=r.useContext(hu);if(!e)throw Error("useCarousel must be used within a <Carousel />");return e}function hp({orientation:e="horizontal",opts:t,setApi:s,plugins:i,className:a,children:l,...o}){let[c,d]=(0,hd.A)({...t,axis:"horizontal"===e?"x":"y"},i),[u,m]=r.useState(!1),[p,h]=r.useState(!1),g=r.useCallback(e=>{e&&(m(e.canScrollPrev()),h(e.canScrollNext()))},[]),f=r.useCallback(()=>{d?.scrollPrev()},[d]),x=r.useCallback(()=>{d?.scrollNext()},[d]),b=r.useCallback(e=>{"ArrowLeft"===e.key?(e.preventDefault(),f()):"ArrowRight"===e.key&&(e.preventDefault(),x())},[f,x]);return r.useEffect(()=>{d&&s&&s(d)},[d,s]),r.useEffect(()=>{if(!d)return;let e=!1;return queueMicrotask(()=>{e||g(d)}),d.on("reInit",g),d.on("select",g),()=>{e=!0,d.off("reInit",g),d.off("select",g)}},[d,g]),(0,n.jsx)(hu.Provider,{value:{carouselRef:c,api:d,opts:t,orientation:e||(t?.axis==="y"?"vertical":"horizontal"),scrollPrev:f,scrollNext:x,canScrollPrev:u,canScrollNext:p},children:(0,n.jsx)("div",{onKeyDownCapture:b,className:(0,C.cn)("relative",a),role:"region","aria-roledescription":"carousel","data-slot":"carousel",...o,children:l})})}function hh({className:e,...t}){let{carouselRef:s,orientation:r}=hm();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 hg({className:e,...t}){let{orientation:s}=hm();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 hf(e){let t=e.scrollWidth-e.clientWidth;return t<=1||!["auto","scroll"].includes(getComputedStyle(e).overflowX)?null:{left:e.scrollLeft,maximum:t}}function hx(e){return e.sessionTitle?`${e.projectName} \xb7 ${e.sessionTitle}`:e.projectName}function hb({items:e,activeWorkId:t,onActiveWorkSessionChange:s,children:i}){let a,l,{t:o}=(0,b.Bd)("workbench"),c=(0,mJ.I)(),d=r.Children.toArray(i),u=e[0]?.workId??null,m=e.some(e=>e.workId===t)?t:u,[p]=(0,r.useState)(()=>Math.max(0,e.findIndex(e=>e.workId===m))),h=(0,r.useRef)(null),g=(0,r.useRef)(!1),[f,x]=(0,r.useState)(),[v,w]=(0,r.useState)({index:p,position:p,visible:!1}),y=(0,r.useCallback)(()=>{null!==h.current&&(window.clearTimeout(h.current),h.current=null)},[]),k=(0,r.useCallback)(()=>{y(),h.current=window.setTimeout(()=>{h.current=null,w(e=>e.visible?{...e,visible:!1}:e)},900)},[y]),j=(0,r.useCallback)((t,s)=>{var n;let r=(n=t.scrollProgress()*(e.length-1),Math.max(0,Math.min(e.length-1,n))),i=Math.round(r);w(e=>{let t=s??e.visible;return e.index===i&&.001>Math.abs(e.position-r)&&e.visible===t?e:{index:i,position:r,visible:t}})},[e.length]),N=(0,r.useCallback)(e=>{j(e,!0),k()},[k,j]),I=(a=(0,r.useRef)(null),l=(0,r.useCallback)((e,t)=>{a.current=null;let s=t.target;if(!(s instanceof Element))return!0;if(s.closest('[data-carousel-swipe-lock],[data-testid="file-workspace"],[data-streamdown="mermaid-block"],[data-slot="plugin-scrollbar"],[data-slot="scroll-area-scrollbar"],.monaco-editor,[contenteditable="true"],[role="application"],[role="dialog"],[role="menu"],input,textarea,select,a,summary,img'))return!1;let n=s.closest("button");if(n&&(!("touches"in t)||!n.matches('[data-slot="collapsible-trigger"]')||!n.closest('[data-chat-scroll-anchor$=":tool"]')))return!1;let r=function(e){let t=[];for(let s=e;s&&!s.matches('[data-slot="carousel-item"]');s=s.parentElement){if(!(s instanceof HTMLElement))continue;let n=hf(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=hf(n);s&&t.push(s)}}return t}(s);if(!("touches"in t))return!r.length&&!s.closest('pre,table,[data-streamdown="code-block"]');if(1!==t.touches.length)return!1;if(!r.length)return!0;let i=t.touches[0];return a.current={x:i.clientX,y:i.clientY,scrolls:r,owner:"pending"},!1},[]),(0,r.useEffect)(()=>{if(!f)return;let e=f.rootNode(),t=()=>{a.current=null},s=e=>{let s=a.current;if(!s)return;if(1!==e.touches.length)return void t();let n=e.touches[0],r=n.clientX-s.x,i=n.clientY-s.y;if("pending"===s.owner){if(6>Math.max(Math.abs(r),Math.abs(i)))return;let e=s.scrolls.some(e=>r<0?e.left<e.maximum-1:e.left>1);s.owner=Math.abs(i)>=Math.abs(r)||e?"content":r<0?"next":"previous"}if("content"!==s.owner){if(!e.cancelable){s.owner="content";return}e.preventDefault()}},n=s=>{let n=a.current;if(t(),!n||"pending"===n.owner||"content"===n.owner)return;let r=s.changedTouches[0],i=r.clientX-n.x,l=r.clientY-n.y,o=Math.max(50,Math.min(225,.2*e.clientWidth));("next"===n.owner?-i:i)<o||Math.abs(l)>=Math.abs(i)||("next"===n.owner?f.canScrollNext():f.canScrollPrev())&&(N(f),"next"===n.owner?f.scrollNext():f.scrollPrev())};return e.addEventListener("touchmove",s,{passive:!1}),e.addEventListener("touchend",n),e.addEventListener("touchcancel",t),f.on("reInit",t),()=>{t(),e.removeEventListener("touchmove",s),e.removeEventListener("touchend",n),e.removeEventListener("touchcancel",t),f.off("reInit",t)}},[f,N]),l),S=(0,r.useMemo)(()=>({align:"start",containScroll:"trimSnaps",dragFree:!1,loop:!1,skipSnaps:!1,duration:25*!c,startIndex:p,watchDrag:I}),[p,c,I]);if((0,r.useEffect)(()=>{m&&m!==t&&s(m)},[t,m,s]),(0,r.useLayoutEffect)(()=>{if(!f||!m)return;let t=e.findIndex(e=>e.workId===m);t<0||f.selectedScrollSnap()===t||f.scrollTo(t,!0)},[f,m,e]),(0,r.useEffect)(()=>{if(!f)return;let n=()=>{g.current=!0},r=()=>{g.current=!1,k()},i=e=>{if(g.current){y(),j(e,!0);return}j(e)},a=n=>{let r=e[n.selectedScrollSnap()];r&&r.workId!==t&&s(r.workId),j(n)},l=e=>{j(e),k()},o=e=>{j(e,!1)};return f.on("pointerDown",n),f.on("pointerUp",r),f.on("scroll",i),f.on("select",a),f.on("settle",l),f.on("reInit",o),()=>{g.current=!1,f.off("pointerDown",n),f.off("pointerUp",r),f.off("scroll",i),f.off("select",a),f.off("settle",l),f.off("reInit",o)}},[t,f,y,e,s,k,j]),(0,r.useEffect)(()=>y,[y]),e.length<=1)return(0,n.jsx)("div",{className:"size-full min-h-0 min-w-0 overflow-hidden",children:d[0]??null});let E=e[v.index]??e[0],M=`${100/e.length}%`,z=`translate3d(${100*v.position}%, 0, 0)`;return(0,n.jsxs)(hp,{opts:S,setApi:x,"aria-label":o("sessionWindows"),onKeyDownCapture:()=>void 0,className:"size-full min-h-0 min-w-0 [&_[data-slot=carousel-content]]:h-full [&_[data-slot=carousel-content]]:touch-auto",children:[(0,n.jsx)(hh,{className:"ml-0 h-full",children:e.map((t,s)=>(0,n.jsx)(hg,{"aria-label":`${s+1} / ${e.length},${hx(t)}`,className:"h-full pl-0",children:d[s]??null},t.workId))}),(0,n.jsx)("div",{"aria-hidden":"true","data-testid":"mobile-work-session-position",className:(0,C.cn)("pointer-events-none absolute top-16 left-1/2 z-30 w-[min(82vw,20rem)] -translate-x-1/2 transition-[opacity,transform] duration-150 ease-out motion-reduce:transition-none",v.visible?"translate-y-0 opacity-100":"-translate-y-2 opacity-0"),children:(0,n.jsxs)("div",{className:"rounded-xl border bg-popover px-3 py-2 text-popover-foreground shadow-lg",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-xs",children:[(0,n.jsx)("span",{className:"shrink-0 text-muted-foreground",children:o(E.fixed?"fixedSession":"primarySession")}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:hx(E)}),(0,n.jsxs)("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:[v.index+1," / ",e.length]})]}),(0,n.jsx)("div",{className:"mt-2 h-1 overflow-hidden rounded-full bg-muted",children:(0,n.jsx)("div",{className:"h-full rounded-full bg-foreground",style:{width:M,transform:z}})})]})})]})}function hv(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function hw({sidebarOpen:e,onToggle:t}){let{t:s}=(0,b.Bd)("workbench");return(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":s(e?"hideSessionMenu":"showSessionMenu"),className:(0,C.cn)((0,I.r)({variant:"ghost",size:"icon"}),"text-muted-foreground"),children:e?(0,n.jsx)(sG.A,{className:"size-4"}):(0,n.jsx)(mU.A,{className:"size-5"})})}let hy=(0,r.memo)(function({onOpenSettings:e,workSession:t,fixed:s,focused:i,contentActive:a,composerActive:l,sidebarOpen:o,replacingWithEmpty:c,replacementDisabled:d,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,renderPluginSessionHeader:x,gitRuntime:v,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,branchPicker:S,branchPending:E,mobile:M,fileRuntime:z,onOpenFileSidebar:A,onPreviewFile:$,onAcknowledgeCompleted:R,onFocusWorkSession:P,onReplaceWithEmptyWorkSession:D,onOpenBranchPicker:T,onOpenGitBranchPicker:O,onCloseBranchPicker:L,onRetryBranchPicker:F,onSelectBranchEntry:B,onBranchAction:q,onConfirmRunningBranch:_,onCancelRunningBranch:W,onCloneWorkSession:Y,onUnpinWorkSession:U,onToggleSidebar:H}){let{t:K}=(0,b.Bd)("workbench"),G=(0,r.useRef)(null),J=function(e,t){let{t:s}=(0,b.Bd)("workbench"),n=(0,X.G)(),i=(0,r.useMemo)(()=>({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId}),[e.workId,e.sessionId,e.branchId]),a=(0,r.useCallback)(()=>t.getSourceState(i).runtime,[t,i]),l=(0,r.useSyncExternalStore)(t.subscribe,a,a),o=(0,r.useCallback)(()=>t.getSourceState(i).syncStatus,[t,i]),c=(0,r.useSyncExternalStore)(t.subscribe,o,o),d="basic"===l.extensionMode?l.initializationError:null,[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),g=!p&&"ready"===c&&"main_running"!==e.status&&"background_running"!==e.status,f=d?`${e.cwd}
|
|
154
|
+
location: ${e.path}`})}):null,(0,n.jsx)(tp,{title:t("viewSkillContent"),content:e.content,truncated:e.truncated})]},e.path)),e.prompts.map(e=>(0,n.jsxs)("article",{className:"border-b py-4 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)("code",{className:"font-semibold",children:["/",e.name]}),(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:t("manualOnly")})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:e.description}),(0,n.jsx)("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:e.path}),(0,n.jsx)(tp,{title:t("viewPromptContent"),content:e.content,truncated:e.truncated})]},e.path))]})})}function tg({capabilities:e,browserContributions:t}){let{t:s}=(0,b.Bd)("pluginManagement"),r=e.extensions.some(e=>e.events.length>0||e.commands.length>0||e.shortcuts.length>0||e.flags.length>0||e.messageRenderers.length>0||e.entryRenderers.length>0),i=e.piDesk.methods.length>0||e.piDesk.browserEntries.length>0||e.piDesk.messageDeclarations.length>0||t.length>0,a=e.themes.length>0||e.providers.length>0;return r||i||a?(0,n.jsx)(tc,{title:s("otherCapabilities"),children:(0,n.jsxs)("div",{className:"space-y-2",children:[i?(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs",children:[(0,n.jsx)("p",{className:"font-semibold",children:"Pi Desk"}),(0,n.jsxs)("div",{className:"mt-2 space-y-1.5 text-muted-foreground",children:[e.piDesk.methods.map(e=>(0,n.jsxs)("p",{children:["Method:",(0,n.jsxs)("code",{children:[e.pluginName,"/",e.method]})]},`${e.pluginName}:${e.method}`)),t.map(e=>(0,n.jsxs)("p",{children:[s(tn[e.kind]),":","message-view"===e.kind?e.viewKey:"application"===e.kind?e.title:"widget"===e.kind||"session-header-item"===e.kind?e.contributionName:e.label]},`${e.kind}:${e.contributionName}`)),e.piDesk.messageDeclarations.map(e=>(0,n.jsxs)("p",{children:[s("messageDeclarations"),(0,n.jsxs)("code",{children:[e.pluginName,"/",e.declarationName]})]},`${e.pluginName}:${e.declarationName}`))]})]}):null,r?e.extensions.map(e=>(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs",children:[(0,n.jsx)("code",{className:"block break-all font-semibold",children:e.path}),e.commands.length>0?(0,n.jsxs)("p",{className:"mt-2 leading-5 text-muted-foreground",children:["Commands:",e.commands.map(e=>`/${e.name}`).join("、")]}):null,e.shortcuts.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Shortcuts:",e.shortcuts.map(e=>e.shortcut).join("、")]}):null,e.flags.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Flags:",e.flags.map(e=>`--${e.name}`).join("、")]}):null,e.events.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Events:",e.events.map(e=>e.name).join("、")]}):null]},e.path)):null,a?(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs text-muted-foreground",children:[e.themes.length>0?(0,n.jsxs)("p",{children:["Theme:",e.themes.map(e=>e.name).join("、")]}):null,e.providers.length>0?(0,n.jsxs)("p",{className:"mt-1",children:["Provider:",e.providers.map(e=>e.name).join("、")]}):null]}):null]})}):null}function tf({plugin:e,detail:t,detailLoading:s,detailError:r,browserContributions:i,onRetry:a}){let{t:l}=(0,b.Bd)("pluginManagement"),{locale:o}=(0,eQ.i)(),c=function(e,t,s){let n=[];e.tools.length>0&&n.push({label:s("tagTools",{count:e.tools.length}),tone:"neutral"});let r=e.tools.reduce((e,t)=>"active"!==t.state?e:e+ +!!t.promptSnippet+t.promptGuidelineCount,0)+e.skills.filter(e=>e.modelVisible).length;r>0&&n.push({label:s("tagFixed",{count:r}),tone:"prompt"});let i=tr(e).reduce((e,t)=>e+t.count,0);i>0&&n.push({label:s("tagDynamic",{count:i}),tone:"dynamic"});let a=e.tools.filter(e=>"shadowed"!==e.state&&te.has(e.name)).length;a>0&&n.push({label:s("tagOverride",{count:a}),tone:"override"});let l=e.prompts.length+e.skills.filter(e=>!e.modelVisible).length;l>0&&n.push({label:s("tagManual",{count:l}),tone:"neutral"});let o=t.length+e.piDesk.methods.length+e.piDesk.messageDeclarations.length;o>0&&n.push({label:`Pi Desk ${o}`,tone:"neutral"});let c=e.providers.length+e.themes.length+e.extensions.reduce((e,t)=>e+t.commands.length+t.shortcuts.length+t.flags.length,0);return c>0&&n.push({label:s("tagInteraction",{count:c}),tone:"neutral"}),0===n.length&&e.extensions.length>0&&n.push({label:`Extension ${e.extensions.length}`,tone:"neutral"}),n}(e.capabilities,i,l);return(0,n.jsxs)("div",{className:"space-y-3 text-sm","data-testid":"plugin-capability-detail",children:[(0,n.jsx)("p",{className:"break-all font-mono text-xs text-muted-foreground",children:e.source}),c.length>0?(0,n.jsx)("div",{className:"flex flex-wrap gap-2","aria-label":l("capabilityCategories"),children:c.map(e=>(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-0.5 text-xs text-muted-foreground",children:e.label},e.label))}):null,e.capabilities.error?(0,n.jsx)("p",{className:"whitespace-pre-wrap break-words text-sm leading-5 text-status-warning",children:l("incompleteCapabilities",{error:(0,eJ.fD)(e.capabilities.error,o)})}):null,s?(0,n.jsxs)("div",{className:"flex items-center gap-2 py-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),l("loadingFullDetails")]}):r?(0,n.jsxs)("div",{className:"flex items-start gap-2",role:"alert",children:[(0,n.jsx)("p",{className:"min-w-0 flex-1 break-words text-sm text-destructive",children:r}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",onClick:a,children:[(0,n.jsx)(es.A,{"data-icon":"inline-start"}),l("retry")]})]}):t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(tm,{detail:t}),(0,n.jsx)(th,{detail:t})]}):null,(0,n.jsx)(td,{capabilities:e.capabilities}),(0,n.jsx)(tg,{capabilities:e.capabilities,browserContributions:i})]})}var tx=s(76782),tb=s(44980);function tv({className:e,size:t="default",...s}){return(0,n.jsx)(tx.l,{"data-slot":"switch","data-size":t,className:(0,C.cn)("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",e),...s,children:(0,n.jsx)(tb.p,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"})})}function tw({plugin:e,displayName:t,browserError:s,disabled:r,pending:i,browserRetryPending:a,onAction:l}){let{t:o}=(0,b.Bd)("pluginManagement"),c=e.operation?.phase,d="disabled"!==e.status;return(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-3",children:[i?(0,n.jsxs)("span",{role:"status",className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:["waiting"!==c?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):null,o(c&&"failed"!==c?`phase_${c}`:"submitting")]}):e.updateAvailable&&"extension"!==e.kind&&"failed"!==c?(0,n.jsx)(I.$,{size:"sm",disabled:r,onClick:()=>l("update"),children:o("update")}):null,"failed"===c?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||i,onClick:()=>l("retry"),children:o("retry")}):"failed"===e.status?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||i,onClick:()=>l("reload"),children:o("reloadOne")}):s&&e.pluginName?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:r||a,onClick:()=>l("retry-browser"),children:o("retryView")}):null,(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(tv,{checked:d,"aria-label":o("togglePlugin",{name:t}),disabled:r||i,onCheckedChange:e=>l(e?"enable":"disable")}),o(d?"enabled":"disabled")]}),"extension"!==e.kind?(0,n.jsx)(I.$,{size:"icon-sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive","aria-label":o("removeNamed",{name:t}),title:o("remove"),disabled:r||i,onClick:()=>l("remove"),children:(0,n.jsx)(et.A,{})}):null]})}function ty({plugin:e,requestError:t,browserError:s}){let{t:r}=(0,b.Bd)("pluginManagement"),{locale:i}=(0,eQ.i)(),a=e.operation?.phase,l=[t,"failed"===a?e.operation?.message:null,e.error?(0,eJ.fD)(e.error.message,i):null,s,e.updateError?r("itemCheckFailed",{error:e.updateError}):null].filter((e,t,s)=>!!e&&s.indexOf(e)===t);return l.length||"waiting"===a||"failed"===e.status?(0,n.jsxs)("div",{className:"space-y-1",children:[l.map(e=>(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive [overflow-wrap:anywhere]",children:e},e)),l.length||"failed"!==e.status?null:(0,n.jsx)("p",{className:"text-sm text-destructive",children:r("notLoaded")}),"waiting"===a&&e.operation?.message?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operation.message}):null]}):null}function tk(e){let t=e.startsWith("npm:")?e.slice(4):e,s=/^((?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*)(?:@([^\s/]+))?$/i.exec(t);return s?{name:s[1],...s[2]?{version:s[2]}:{}}:null}function tj(e){return e.source.startsWith("npm:")?tk(e.source)?.name??e.source:e.pluginName??("extension"===e.kind?e.source.replaceAll("\\","/").split("/").at(-1):null)??e.source}function tN(e){return`source:${tk(e)?.name??e}`}function tI(e){switch(e.kind){case"batch":return"add"===e.input.action?"batchInstall":"update"===e.input.action?"updateSelected":"del"===e.input.action?"removeSelected":"setChannel";case"add":return"actionAdd";case"update":return"actionUpdate";case"del":return"actionDelete";case"enable":return"enable";case"disable":return"disable";case"reload":return"normal"===e.mode?"restartNormal":"actionReload"}}let tS=a.Yj().trim().min(1).max(128).regex(/^[a-zA-Z][a-zA-Z0-9._-]*$/),tC=a.Yj().trim().url().max(2048).refine(e=>{let t=new URL(e);return["https:","http:"].includes(t.protocol)&&!t.username&&!t.password&&!t.search&&!t.hash},"插件源必须是 HTTP 或 HTTPS 仓库地址"),tE=a.gM("mode",[a.Ik({mode:a.eu("auto")}).strict(),a.Ik({mode:a.eu("local")}).strict(),a.Ik({mode:a.eu("official")}).strict(),a.Ik({mode:a.eu("domestic")}).strict(),a.Ik({mode:a.eu("custom"),registry:tC}).strict()]),tM=a.Ik({description:a.Yj().trim().min(1).max(4e3).optional(),readme:a.Yj().trim().min(1).max(1024).optional()});a.Ik({description:a.Yj().optional(),piDesk:a.Ik({i18n:a.g1(a.Yj().min(1).max(35),tM).optional()}).passthrough().optional()}).passthrough();let tz=a.Ik({downloadSource:tE,recommendedRegistry:tC}).strict(),tA=a.Ik({downloadSource:tE}).strict(),t$=a.Ik({query:a.Yj().trim().max(200).default(""),page:a.ai().int().min(1).max(100).default(1),kind:a.k5(["all","desk","pi"]).default("all"),registry:tC.optional()}).strict(),tR=a.Ik({name:a.Yj().trim().min(1).max(214).regex(/^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/i),version:a.Yj().trim().min(1).max(128).optional(),registry:tC.optional()}).strict(),tP=a.Ik({name:a.Yj(),description:eJ.qf.nullable(),version:a.Yj(),publisher:a.Yj().nullable(),kind:a.k5(["desk","pi","unknown"]),official:a.zM(),registry:tC}).strict(),tD=a.Ik({items:a.YO(tP),hasMore:a.zM()}).strict(),tT=tP.extend({versions:a.YO(a.Yj()),readme:eJ.qf.nullable(),homepage:a.Yj().nullable(),repository:a.Yj().nullable(),compatible:a.zM().nullable(),compatibilityNote:a.Yj().nullable()}).strict();function tO({id:e,mode:t,registry:s,recommendedRegistry:r,savedRegistry:i,loading:a,saving:l,error:o,override:c,onMode:d,onRegistry:u,onSave:m,onRetry:p}){let{t:h}=(0,b.Bd)("pluginManagement"),g="auto"===t?r:"official"===t?"https://registry.npmjs.org":"domestic"===t?"https://mirrors.cloud.tencent.com/npm":"custom"===t?i??s:null,f=[...c?[{value:"default",label:h("useDefaultSource")}]:[],...["local","auto","domestic","official","custom"].map(e=>({value:e,label:h(`download_${e}`)}))];return(0,n.jsxs)("div",{className:"min-w-0 space-y-3 text-sm",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:e,className:"font-medium",children:h(c?"installDownloadSource":"downloadSource")}),(0,n.jsxs)(ea.l6,{value:t,items:f,disabled:a,onValueChange:e=>{e&&!l&&d(e)},children:[(0,n.jsx)(ea.bq,{id:e,className:"max-w-full",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:f.map(e=>(0,n.jsx)(ea.eb,{value:e.value,disabled:l,children:e.label},e.value))})]}),l?(0,n.jsx)("span",{role:"status",className:"text-muted-foreground",children:h("saving")}):null]}),"custom"===t?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:`${e}-url`,className:"block",children:h("registryUrl")}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(em.p,{id:`${e}-url`,type:"url",value:s,placeholder:"https://registry.example.com",className:"min-w-0 flex-1 basis-48",disabled:l,onChange:e=>u(e.target.value)}),m?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:l,onClick:m,children:h("save")}):null]})]}):!c&&g?(0,n.jsx)("p",{className:"break-all text-xs text-muted-foreground",children:g}):null,o?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:o}),p?(0,n.jsx)(I.$,{variant:"outline",size:"sm",onClick:p,children:h("retry")}):null]}):null]})}var tL=s(3058),tF=s(97724),tB=s(48742);function tq({className:e,...t}){return(0,n.jsx)(tF.y,{"data-slot":"checkbox",className:(0,C.cn)("peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",e),...t,children:(0,n.jsx)(tB.P,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none [&>svg]:size-3.5",children:(0,n.jsx)(ep.A,{})})})}function t_(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=e.snapshot?.plugins??[],i=t=>e.requests.has(tN(t.source))||!!(t.operation&&"failed"!==t.operation.phase),a=r.filter(t=>("updates"!==e.statusFilter||!!t.updateAvailable)&&("disabled"!==e.statusFilter||"disabled"===t.status)&&("failed"!==e.statusFilter||!!("failed"===t.status||t.operation?.phase==="failed"||t.updateError||t.pluginName&&e.browserErrors.has(t.pluginName)))&&`${tj(t)} ${t.description?(0,eJ.fD)(t.description,s):""}`.toLocaleLowerCase().includes(e.filter.trim().toLocaleLowerCase())),l=a.filter(e=>"extension"!==e.kind),o=r.filter(t=>e.selected.has(tN(t.source))),c=r.filter(e=>!0===e.updateAvailable&&"extension"!==e.kind&&!i(e)),d=c.filter(t=>e.selected.has(tN(t.source))),u=o.filter(e=>!i(e)),m=l.length>0&&l.every(t=>e.selected.has(tN(t.source))),p=l.some(t=>e.selected.has(tN(t.source))),h=["all","updates","disabled","failed"].map(e=>({value:e,label:t(`statusFilter_${e}`)}));return(0,n.jsxs)("section",{"aria-label":t("installed"),className:"flex min-h-0 min-w-0 flex-col gap-3",children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 bg-popover pb-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(em.p,{"aria-label":t("filterInstalled"),value:e.filter,onChange:t=>e.onFilter(t.target.value),placeholder:t("filterInstalled"),className:"min-w-40 flex-1 basis-52"}),(0,n.jsxs)(ea.l6,{value:e.statusFilter,items:h,onValueChange:t=>{t&&e.onStatusFilter(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("filterStatus"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:h.map(e=>(0,n.jsx)(ea.eb,{value:e.value,children:e.label},e.value))})]}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading||e.disabled,onClick:e.onRefresh,children:t(e.loading?"checkingUpdates":"checkUpdates")}),c.length>0?(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||e.loading,onClick:e.onUpdateAll,children:t("updateAll",{count:c.length})}):null,r.some(e=>"extension"!==e.kind)?(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:()=>e.onBatchMode(!e.batchMode),children:t(e.batchMode?"finishSelection":"batchManage")}):null]}),e.batchMode?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 rounded-lg bg-muted px-3 py-2",children:[(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,n.jsxs)("span",{className:"relative flex size-4 items-center justify-center",children:[(0,n.jsx)(tq,{checked:m,indeterminate:p&&!m,className:"data-indeterminate:[&_svg]:hidden",disabled:!l.length,onCheckedChange:t=>e.onSelect(l.map(e=>tN(e.source)),t)}),p&&!m?(0,n.jsx)(tL.A,{"aria-hidden":!0,className:"pointer-events-none absolute size-3.5"}):null]}),t(e.filter||"all"!==e.statusFilter?"selectFiltered":"selectAll")]}),(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("selectedCount",{count:o.length})}),o.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled||e.loading||!d.length,onClick:e.onUpdateSelected,children:t("updateSelected")}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled||!u.length,onClick:e.onRemoveSelected,children:t("removeSelected")}),(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:()=>e.onSelect([...e.selected],!1),children:t("clearSelection")})]}):null]}):null,e.errors.list?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.errors.list}):null]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto",children:e.loading&&!e.snapshot?(0,n.jsx)("p",{role:"status",className:"py-6 text-sm text-muted-foreground",children:t("loading")}):a.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:a.map(r=>{let a=tj(r),l=tN(r.source),o=r.pluginName?e.browserErrors.get(r.pluginName)??null:null;return(0,n.jsx)("article",{"aria-label":a,className:`min-w-0 px-4 py-3 ${e.selected.has(l)&&e.batchMode?"bg-accent/40":""}`,children:(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[e.batchMode&&"extension"!==r.kind?(0,n.jsx)("div",{className:"flex min-h-8 shrink-0 items-center",children:(0,n.jsx)(tq,{checked:e.selected.has(l),"aria-label":t("selectPlugin",{name:a}),onCheckedChange:t=>e.onSelect([l],t)})}):null,(0,n.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-1 basis-64 flex-wrap items-center gap-x-2 gap-y-1",children:[(0,n.jsx)(I.$,{variant:"link",className:"h-auto min-h-8 min-w-0 max-w-full justify-start p-0 text-left text-sm font-semibold whitespace-normal no-underline hover:underline [overflow-wrap:anywhere]","aria-label":t("viewDetails",{name:a}),onClick:()=>e.onDetail(r.source),children:a}),r.version?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",r.version]}):null,r.updateAvailable?(0,n.jsx)("span",{className:"inline-flex rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:r.availableVersion?t("newVersion",{version:r.availableVersion}):t("updateAvailable")}):null,r.updateTag&&"latest"!==r.updateTag?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:"dev"===r.updateTag?t("channelDev"):r.updateTag}):null]}),(0,n.jsx)(tw,{plugin:r,displayName:a,browserError:o,disabled:e.disabled,pending:i(r),browserRetryPending:e.requests.has(`entry:${r.pluginName}`),onAction:t=>e.onAction(r,t)})]}),r.description?(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:(0,eJ.fD)(r.description,s)}):null,(0,n.jsx)(ty,{plugin:r,browserError:o,requestError:e.errors[l]??e.errors[`entry:${r.pluginName}`]})]})]})},l)})}):(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:t(e.filter||"all"!==e.statusFilter?"noMatches":"empty")})})]})}function tW(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=new Map(e.snapshot?.plugins.filter(e=>e.source.startsWith("npm:")).map(e=>[tk(e.source)?.name,e]));return(0,n.jsxs)("section",{className:"min-w-0 space-y-4","aria-label":t("searchPlugins"),children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:"plugin-catalog-query",className:"sr-only",children:t("searchPlugins")}),(0,n.jsx)(em.p,{id:"plugin-catalog-query",value:e.query,placeholder:t("searchPlaceholder"),className:"min-w-40 flex-1 basis-56",maxLength:200,onChange:t=>e.onQuery(t.target.value),onCompositionStart:e.onCompositionStart,onCompositionEnd:e.onCompositionEnd}),(0,n.jsxs)(ea.l6,{value:e.searchSource,items:[{value:"public",label:t("publicNpm")},{value:"custom",label:t("customSearchSource")}],onValueChange:t=>{t&&e.onSearchSource(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("searchSource"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"public",children:t("publicNpm")}),(0,n.jsx)(ea.eb,{value:"custom",children:t("customSearchSource")})]})]}),(0,n.jsxs)(ea.l6,{value:e.kind,items:["all","desk","pi"].map(e=>({value:e,label:t(`kind_${e}`)})),onValueChange:t=>{t&&e.onKind(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("pluginKind"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:["all","desk","pi"].map(e=>(0,n.jsx)(ea.eb,{value:e,children:t(`kind_${e}`)},e))})]}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:e.onDirectInstall,children:t("directInstall")}),"custom"===e.searchSource?(0,n.jsxs)("div",{className:"w-full space-y-1",children:[(0,n.jsx)("label",{htmlFor:"plugin-search-registry",className:"block text-sm",children:t("searchRegistryUrl")}),(0,n.jsx)(em.p,{id:"plugin-search-registry",type:"url",value:e.registry,onChange:t=>e.onRegistry(t.target.value),placeholder:"https://registry.example.com"})]}):null]}),e.error?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 text-sm text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:e.error}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:e.onRetry,children:t("retry")})]}):null,e.items.length?(0,n.jsx)("div",{className:"@container/catalog divide-y rounded-lg border bg-card",children:e.items.map(i=>{let a=r.get(i.name),l=tN(`npm:${i.name}`),o=a?.description??i.description,c=!!(a?.operation&&"failed"!==a.operation.phase),d=e.requests.has(l)||c||e.preparing.has(i.name),u=a&&(a.operation?.action!=="add"||"failed"!==a.operation.phase),m=e.installErrors[i.name]??e.errors[l]??(a?.error?(0,eJ.fD)(a.error.message,s):null);return(0,n.jsxs)("article",{"aria-label":i.name,className:"grid min-w-0 gap-x-4 gap-y-2 px-4 py-3 @xl/catalog:grid-cols-[minmax(0,1fr)_auto]",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(I.$,{variant:"link",className:"h-auto min-h-8 min-w-0 max-w-full p-0 text-left text-sm font-semibold whitespace-normal no-underline hover:underline [overflow-wrap:anywhere]",onClick:()=>e.onDetail(i),children:i.name}),(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",u&&a.version?a.version:i.version]}),u&&a.updateAvailable?(0,n.jsx)("span",{className:"rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:a.availableVersion?t("newVersion",{version:a.availableVersion}):t("updateAvailable")}):null,(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`kind_${i.kind}`)}),i.publisher?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:i.publisher}):null]}),(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:o?(0,eJ.fD)(o,s):t("noPluginDescription")})]}),(0,n.jsx)("div",{className:"flex min-h-8 items-center self-start @xl/catalog:justify-end",children:d?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:c?t(`phase_${a?.operation?.phase}`):e.preparing.has(i.name)?t("loadingPackage"):t("submitting")}):u?(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),a.updateAvailable?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onUpdate(a.source),children:t("update")}):null]}):(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onInstall(i),children:t("install")})}),m?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere] @xl/catalog:col-span-2",children:m}):null,a?.operation?.phase==="failed"&&a.operation.message?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere] @xl/catalog:col-span-2",children:a.operation.message}):null]},i.name)})}):null,e.loading?(0,n.jsx)("p",{role:"status",className:"py-4 text-sm text-muted-foreground",children:t("searching")}):e.error||!e.searched||e.items.length?null:(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:t("noSearchResults")}),e.hasMore?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onMore,children:t("loadMore")}):null]})}let tY=(0,e2.F)("flex w-fit items-stretch *:focus-visible:relative *:focus-visible:z-10 has-[>[data-slot=button-group]]:gap-2 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-lg [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1",{variants:{orientation:{horizontal:"*:data-slot:rounded-r-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-r-lg! [&>[data-slot]~[data-slot]]:rounded-l-none [&>[data-slot]~[data-slot]]:border-l-0",vertical:"flex-col *:data-slot:rounded-b-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-b-lg! [&>[data-slot]~[data-slot]]:rounded-t-none [&>[data-slot]~[data-slot]]:border-t-0"}},defaultVariants:{orientation:"horizontal"}});function tV({className:e,orientation:t,...s}){return(0,n.jsx)("div",{role:"group","data-slot":"button-group","data-orientation":t,className:(0,C.cn)(tY({orientation:t}),e),...s})}var tU=s(32892),tH=s(57445),tK=s(73028),tG=s(48318),tJ=s(93356),tQ=s(10508);let tX=({className:e,from:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("group flex w-full max-w-[95%] flex-col gap-2","user"===t?"is-user ml-auto justify-end":"is-assistant",e),...s}),tZ=({children:e,className:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("flex w-fit min-w-0 max-w-full flex-col gap-2 overflow-hidden text-base leading-[1.8]","group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground","group-[.is-assistant]:text-foreground",t),...s,children:e}),t0=({tooltip:e,children:t,label:s,variant:r="ghost",size:i="icon-sm",...a})=>{let l=(0,n.jsxs)(I.$,{size:i,type:"button",variant:r,...a,children:[t,(0,n.jsx)("span",{className:"sr-only",children:s||e})]});return e?(0,n.jsx)(tU.Bc,{children:(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:l}),(0,n.jsx)(tU.ZI,{children:(0,n.jsx)("p",{children:e})})]})}):l},t1={cjk:tH.h,code:tK.a,math:tG.D,mermaid:tJ.a},t2=(0,r.memo)(({className:e,...t})=>(0,n.jsx)(tQ.jH,{className:(0,C.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),plugins:t1,...t}),(e,t)=>e.children===t.children&&t.isAnimating===e.isAnimating);t2.displayName="MessageResponse";let t5=({className:e,children:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("mt-4 flex w-full items-center justify-between gap-4",e),...s,children:t});function t3({readme:e}){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),[i,a]=(0,r.useState)(null),l=e&&"string"!=typeof e?e.translations:{},o=Object.keys(l).filter(e=>/^(zh(?:-|$)|en(?:-|$))/.test(e)),c=i&&void 0!==l[i]?i:null,d=e?c?l[c]:(0,eJ.fD)(e,s):null;return(0,n.jsxs)("section",{className:"min-w-0 space-y-3","aria-label":t("readme"),children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:t("readme")}),o.length>0?(0,n.jsxs)("div",{className:"flex items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("readmeLanguage")}),(0,n.jsxs)(ea.l6,{value:c??"",onValueChange:e=>a(e||null),children:[(0,n.jsx)(ea.bq,{"aria-label":t("readmeLanguage"),children:(0,n.jsx)(ea.yv,{children:c?c.startsWith("zh")?"中文":"English":t("defaultLanguage")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"",children:t("defaultLanguage")}),o.map(e=>(0,n.jsx)(ea.eb,{value:e,children:e.startsWith("zh")?"中文":"English"},e))]})]})]}):null]}),d?(0,n.jsx)("div",{className:"min-w-0 overflow-x-auto text-base leading-relaxed [overflow-wrap:anywhere]",children:(0,n.jsx)(t2,{mode:"static",isAnimating:!1,skipHtml:!0,controls:!1,className:"min-w-0 [&_img]:max-w-full [&_pre]:overflow-x-auto",children:d})}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:t("noReadme")})]})}function t4({value:e,label:t,placeholder:s,disabled:r,onChange:i}){let{t:a}=(0,b.Bd)("pluginManagement"),l=[...s?[{value:"",label:s}]:[],{value:"latest",label:a("channelLatest")},{value:"dev",label:a("channelDev")},...e&&!["latest","dev"].includes(e)?[{value:e,label:e}]:[]];return(0,n.jsxs)(ea.l6,{value:e,items:l,onOpenChange:(e,t)=>{e&&r&&t.cancel()},onValueChange:e=>{null===e||r||i(e)},children:[(0,n.jsx)(ea.bq,{"aria-label":t,"aria-disabled":r,className:"max-w-full aria-disabled:opacity-50",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:l.map(e=>(0,n.jsx)(ea.eb,{value:e.value,disabled:r,children:e.label},e.value))})]})}function t6(e){if(!e)return null;try{let t=new URL(e);return["https:","http:"].includes(t.protocol)?t.href:null}catch{return null}}function t8(e){let{t}=(0,b.Bd)("pluginManagement"),{locale:s}=(0,eQ.i)(),r=e.detail,i=e.installed&&e.installedVersion===r.version,a=t6(r.homepage),l=t6(r.repository),o=[...new Set([r.version,...r.versions])];return(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:["v",r.version]}),(0,n.jsx)("span",{children:t(`kind_${r.kind}`)}),r.publisher?(0,n.jsx)("span",{className:"[overflow-wrap:anywhere]",children:r.publisher}):null]}),r.description?(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:(0,eJ.fD)(r.description,s)}):null,!1===r.compatible?(0,n.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:[t("incompatible"),r.compatibilityNote?` \xb7 ${r.compatibilityNote}`:""]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[e.pending?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:e.operationMessage??t("submitting")}):i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),e.updateAvailable?(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled,onClick:e.onUpdate,children:t("update")}):null]}):(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||!1===r.compatible,onClick:e.onInstall,children:t(e.installed?"installVersion":"install")}),a?(0,n.jsx)("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"text-sm underline underline-offset-4",children:t("homepage")}):null,l?(0,n.jsx)("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"text-sm underline underline-offset-4",children:t("repository")}):null]}),e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.error}):null]}),(0,n.jsxs)(eV.Nt,{className:"rounded-lg border",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between px-3 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"space-y-3 px-3 pb-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(t4,{value:e.channel,label:t("installChannel"),placeholder:t("defaultChannel"),disabled:e.pending,onChange:e.onChannel}),(0,n.jsxs)(ea.l6,{value:r.version,items:o.map(e=>({value:e,label:e})),onOpenChange:(t,s)=>{t&&e.pending&&s.cancel()},onValueChange:t=>{t&&!e.pending&&e.onVersion(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("version"),"aria-disabled":e.pending,children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:o.map(t=>(0,n.jsx)(ea.eb,{value:t,disabled:e.pending,children:t},t))})]})]}),(0,n.jsx)(tO,{id:"plugin-detail-download",mode:e.downloadMode,registry:e.downloadRegistry,override:!0,saving:e.pending,onMode:e.onDownloadMode,onRegistry:e.onDownloadRegistry})]})})]}),(0,n.jsx)("div",{className:"border-t pt-4",children:(0,n.jsx)(t3,{readme:r.readme},`${r.name}@${r.version}`)})]})}var t7=s(68017);function t9(e){let{t}=(0,b.Bd)("pluginManagement");return(0,n.jsxs)("section",{"aria-label":t("directInstall"),className:"min-w-0 space-y-3 rounded-lg border bg-card p-4",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:t("directInstall")}),(0,n.jsx)(I.$,{size:"sm",variant:"ghost",onClick:e.onClose,children:t("close")})]}),(0,n.jsx)("label",{htmlFor:"plugin-direct-source",className:"block text-sm font-medium",children:t("source")}),(0,n.jsx)(t7.T,{id:"plugin-direct-source",value:e.source,placeholder:t("batchSourcePlaceholder"),rows:2,disabled:e.pending,onChange:t=>e.onSource(t.target.value)}),e.isNpm||e.multiple?(0,n.jsxs)(eV.Nt,{children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-8 items-center gap-2 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"space-y-3 pt-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(t4,{value:e.tag,label:t("installChannel"),placeholder:t("defaultChannel"),disabled:e.pending,onChange:e.onTag})]}),e.isNpm?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onRead,children:t(e.loading?"loadingPackage":"readPackage")}):null,e.detail?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.detail.name}),(0,n.jsxs)(ea.l6,{value:e.selectedVersion,onOpenChange:(t,s)=>{t&&(e.loading||e.pending)&&s.cancel()},items:[{value:"",label:t("automaticVersion")},...[...new Set([e.detail.version,...e.detail.versions])].map(e=>({value:e,label:e}))],onValueChange:t=>{null===t||e.loading||e.pending||e.onVersion(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("version"),"aria-disabled":e.loading||e.pending,className:"max-w-full",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"",disabled:e.loading||e.pending,children:t("automaticVersion")}),[...new Set([e.detail.version,...e.detail.versions])].map(t=>(0,n.jsx)(ea.eb,{value:t,disabled:e.loading||e.pending,children:t},t))]})]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t("targetVersion",{version:e.detail.version})})]}):null,(0,n.jsx)(tO,{id:"plugin-direct-download",mode:e.override,registry:e.registry,override:!0,saving:e.pending,onMode:e.onMode,onRegistry:e.onRegistry})]})})]}):null,e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm whitespace-pre-wrap text-destructive [overflow-wrap:anywhere]",children:e.error}):null,e.operationMessage?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operationMessage}):null,(0,n.jsx)(I.$,{size:"sm",disabled:e.disabled||e.loading||e.pending||!e.source.trim(),onClick:e.onInstall,children:t(e.pending?"installing":e.multiple?"batchInstall":"install")})]})}function se({confirmation:e,onClose:t,onConfirm:s}){let{t:r}=(0,b.Bd)("pluginManagement"),i=e?r(tI(e)):null,a=e?.kind==="del"||e?.kind==="batch"&&"del"===e.input.action,l=e?.kind==="add"||e?.kind==="batch"&&"add"===e.input.action;return(0,n.jsx)(eN.YV,{open:!!e,onOpenChange:e=>{e||t()},children:(0,n.jsxs)(eN.hA,{className:"z-[150] max-w-lg",backdropClassName:"z-[140]",children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:r("confirmAction",{action:i})}),(0,n.jsx)(eN.uX,{children:r(a?"removeDescription":l?"thirdPartyDescription":e?.kind==="reload"?"normal"===e.mode?"restartNormalDescription":"restartDescription":"confirmChange")})]}),(0,n.jsx)(eN._Y,{className:"min-h-0",children:(0,n.jsx)("div",{className:"min-w-0 p-4 pt-0",children:e?.kind==="batch"?(0,n.jsx)("ul",{className:"space-y-2 text-sm",children:("add"===e.input.action?e.input.items.map(e=>e.source):e.input.sources).map(e=>(0,n.jsx)("li",{className:"font-medium [overflow-wrap:anywhere]",children:e.startsWith("npm:")?tk(e)?.name??e:e},e))}):e?.kind==="add"?(0,n.jsxs)("dl",{className:"space-y-3 text-sm",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("packageName")}),(0,n.jsx)("dd",{className:"mt-1 font-medium [overflow-wrap:anywhere]",children:e.package?.name??e.input.source})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("version")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.package?.version??tk(e.input.source)?.version??r("fromSource")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("publisher")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.package?.publisher??r("unknownPublisher")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("source")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.input.registry??e.package?.registry??e.input.source})]})]}):e&&"reload"!==e.kind?(0,n.jsx)("p",{className:"text-sm font-medium [overflow-wrap:anywhere]",children:e.source.startsWith("npm:")?tk(e.source)?.name??e.source:e.source}):null})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:t,children:r("cancel")}),(0,n.jsx)(I.$,{size:"sm",variant:a?"destructive":"default",onClick:()=>{e&&s(e)},children:i})]})]})})}function st({basicMode:e=!1,snapshot:t,biz:s,onSnapshot:i,onRestartScheduled:a}){let{t:l}=(0,b.Bd)("pluginManagement"),{locale:o}=(0,eQ.i)(),[c,d]=(0,r.useState)("installed"),[u,m]=(0,r.useState)(""),[p,h]=(0,r.useState)("all"),[g,f]=(0,r.useState)(!1),[x,v]=(0,r.useState)(()=>new Set);(0,r.useEffect)(()=>{if(!t)return;let e=new Set(t.plugins.map(e=>tN(e.source)));[...x].some(t=>!e.has(t))&&queueMicrotask(()=>v(t=>new Set([...t].filter(t=>e.has(t)))))},[t,x]);let[w,y]=(0,r.useState)(""),[k,j]=(0,r.useState)(!1),N=function({basicMode:e=!1,biz:t,snapshot:s,onSnapshot:n,onRestartScheduled:i}){let{t:a}=(0,b.Bd)("pluginManagement"),l=(0,Q.t4)();(0,Q.So)();let[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(()=>new Set),m=(0,r.useRef)(new Set),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)({}),[x,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(null),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(null),S=(0,r.useRef)(0),C=(0,r.useRef)(0),E=(0,r.useRef)(!0),M=(e,t)=>{t?m.current.add(e):m.current.delete(e),E.current&&u(new Set(m.current))},z=(e,t)=>{E.current&&f(s=>{let n={...s};return t?n[e]=t:delete n[e],n})},A=e=>{let t=tN(e);return m.current.has(t)||!!s?.plugins.some(e=>tN(e.source)===t&&e.operation&&"failed"!==e.operation.phase)},$=async(e=!1)=>{let s=++C.current,r=await t.list(e);E.current&&s===C.current&&n(r)},R=async(e,t)=>{if(m.current.has("check"))return;let n=e??s?.plugins.filter(e=>"package"===e.kind&&(!t||e.updateTag===t)).map(e=>e.source)??[],r=n.filter(A),i=n.filter(e=>!A(e));if(r.forEach(e=>z(tN(e),a("sourceBusy"))),!i.length)return;let l=i.map(tN);M("check",!0),l.forEach(e=>M(e,!0)),c(!0),z("list",null);try{if(e||r.length)for(let e=0;e<i.length&&(await $({checkUpdates:!0,sources:i.slice(e,e+32),...t?{tag:t}:{}}),E.current);e+=32);else await $({checkUpdates:!0,...t?{tag:t}:{}})}catch(e){z("list",e instanceof Error?e.message:a("updateCheckFailed"))}finally{M("check",!1),l.forEach(e=>M(e,!1)),E.current&&c(!1)}};(0,r.useEffect)(()=>{E.current=!0;let s=!0,r=++C.current;return queueMicrotask(()=>{s&&(c(!0),t.list(!1).then(async i=>{if(!s||r!==C.current)return;n(i);let a=i.plugins.some(e=>"package"===e.kind&&/^(npm:|git:|https?:|git@)/.test(e.source)&&null===e.updateAvailable&&!e.updateError&&!e.operation);if(!e&&a){let e=await t.list(!0);s&&r===C.current&&n(e)}}).catch(e=>{s&&z("list",e instanceof Error?e.message:a("updateCheckFailed"))}).finally(()=>{s&&c(!1)}))}),()=>{s=!1,E.current=!1,S.current+=1,C.current+=1}},[t,n,a,e]);let P=async e=>{let s="add"===e.action?e.items.map(e=>e.source):e.sources,r=s.filter(e=>!A(e));if(s.filter(A).forEach(e=>z(tN(e),a("sourceBusy"))),!r.length)return;let i=r.map(tN);i.forEach(e=>{M(e,!0),z(e,null)}),h(null);let l=[...r];try{let s=await t.list(),r=Date.now()+9e5;for(;l.length;){let i=s.plugins.filter(e=>e.operation&&"failed"!==e.operation.phase),o="tag"===e.action?32:Math.max(0,32-i.length);if(!o){if(i.some(e=>e.operation?.phase==="waiting")||Date.now()>=r){l.forEach(e=>z(tN(e),a("batchWaiting")));break}await new Promise(e=>setTimeout(e,750)),s=await t.list(),E.current&&(C.current+=1,n(s));continue}let c=l.slice(0,o),d="add"===e.action?{...e,items:e.items.filter(e=>c.includes(e.source))}:{...e,sources:c},u=await t.batch(d);s=u.snapshot,E.current&&(C.current+=1,n(s)),u.results.forEach(e=>z(tN(e.source),e.error)),c.forEach(e=>M(tN(e),!1)),l=l.slice(c.length)}}catch(t){let e=t instanceof Error?t.message:a("batchFailed");l.forEach(t=>z(tN(t),e))}finally{i.forEach(e=>M(e,!1))}},D=async e=>{if("batch"===e.kind)return void await P(e.input);if("reload"!==e.kind&&A("add"===e.kind?e.input.source:e.source))return;let s="reload"===e.kind?"reload":tN("add"===e.kind?e.input.source:e.source);if(!m.current.has(s)){M(s,!0),h(null),z(s,null);try{let s="add"===e.kind?await t.add(e.input):"update"===e.kind?await t.update(e.source):"del"===e.kind?await t.del(e.source):"enable"===e.kind||"disable"===e.kind?await t.setEnabled(e.source,"enable"===e.kind):await t.reload(e.mode);if(!E.current)return;C.current+=1,n(s),"reload"===e.kind?i():await $()}catch(t){z(s,t instanceof Error?t.message:a("actionFailed",{action:a(tI(e))}))}finally{M(s,!1)}}},T=(e,t)=>{let s={kind:"add",input:e,package:t};t?.official===!0?D(s):h(s)},O=async e=>{let s=e?.[0]?tN(e[0]):"apply";if(!m.current.has(s)){M(s,!0),z(s,null);try{let s=await t.apply(e);E.current&&(C.current+=1,n(s),await $())}catch(e){z(s,e instanceof Error?e.message:a("actionFailed",{action:a("reloadOne")}))}finally{M(s,!1)}}},L=async(e,t)=>{if(!m.current.has(e)){M(e,!0),z(e,null);try{await t()}catch(t){z(e,t instanceof Error?t.message:a("retryFailed"))}finally{M(e,!1)}}},F=async e=>{let s=++S.current;j(!0),I(null);try{let n=await t.get(e);E.current&&s===S.current&&y(n)}catch(e){E.current&&s===S.current&&I(e instanceof Error?e.message:a("detailFailed"))}finally{E.current&&s===S.current&&j(!1)}};return{loading:o,requests:d,confirmation:p,setConfirmation:h,errors:g,detailSource:x,detail:w,detailLoading:k,detailError:N,pluginHost:l,refresh:R,executeBatch:P,execute:D,requestInstall:T,applyChanges:O,loadDetail:F,openDetail:e=>{v(e),y(null),F(e)},closeDetail:()=>{S.current+=1,v(null),y(null),I(null),j(!1)},handleControlAction:(e,t)=>{switch(t){case"reload":O([e.source]);break;case"update":D({kind:"update",source:e.source});break;case"remove":h({kind:"del",source:e.source});break;case"enable":case"disable":D({kind:t,source:e.source});break;case"retry-browser":e.pluginName&&L(`entry:${e.pluginName}`,()=>l.retryEntry(e.pluginName));break;case"retry":{let t=e.operation?.action;"apply"===t?O([e.source]):"add"===t?T({source:e.source}):t&&D({kind:t,source:e.source})}}},refreshEntries:()=>L("entries",()=>l.refreshEntries())}}({biz:s,snapshot:t,onSnapshot:i,onRestartScheduled:a,basicMode:e}),S=function(e,t){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(""),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)("all"),[d,u]=(0,r.useState)("public"),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)([]),[f,x]=(0,r.useState)(!1),[v,w]=(0,r.useState)(1),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(null),[I,S]=(0,r.useState)(!1),[C,E]=(0,r.useState)(null),[M,z]=(0,r.useState)(null),[A,$]=(0,r.useState)(!1),[R,P]=(0,r.useState)(null),[D,T]=(0,r.useState)(()=>new Set),[O,L]=(0,r.useState)({}),F=(0,r.useRef)(0),B=(0,r.useRef)(0),q=(0,r.useRef)(new Set),_=(0,r.useRef)(null),[W,Y]=(0,r.useState)(!1),[V,U]=(0,r.useState)("default"),[H,K]=(0,r.useState)(""),G=(0,r.useRef)(!0);(0,r.useEffect)(()=>(G.current=!0,()=>{G.current=!1,F.current+=1,B.current+=1}),[]);let J=(0,r.useCallback)(async(t,n)=>{k(!0),N(null);try{let s=await e.searchCatalog(t);if(!G.current||n!==F.current)return;g(e=>{let n=1===t.page?s.items:[...e,...s.items],r=e=>e.official?0:"desk"===e.kind?1:"pi"===e.kind?2:3;return[...new Map(n.map(e=>[e.name,e])).values()].sort((e,t)=>r(e)-r(t))}),w(t.page),x(s.hasMore),S(!0)}catch(e){G.current&&n===F.current&&N(e instanceof Error?e.message:s("searchFailed"))}finally{G.current&&n===F.current&&k(!1)}},[e,s]);(0,r.useEffect)(()=>{t&&queueMicrotask(()=>Y(!0))},[t]),(0,r.useEffect)(()=>{if(!W||a)return;let e=++F.current;_.current=null,queueMicrotask(()=>{G.current&&e===F.current&&(k(!0),N(null),x(!1))});let t=setTimeout(()=>{let t="custom"===d?tC.safeParse(m):null;if(t&&!t.success){_.current=null,g([]),x(!1),S(!1),N(s("invalidRegistry")),k(!1);return}let r={query:n.trim(),kind:o,page:1,...t?.success?{registry:t.data}:{}};_.current=r,g([]),x(!1),S(!1),J(r,e)},300);return()=>clearTimeout(t)},[n,o,d,m,a,J,W,s]);let Q=async(t,n=t.version)=>{let r=++B.current;$(!0),P(null),L(e=>{let s={...e};return delete s[t.name],s});try{let s=await e.getCatalog({name:t.name,registry:t.registry,version:n});G.current&&r===B.current&&z(s)}catch(e){G.current&&r===B.current&&P(e instanceof Error?e.message:s("detailFailed"))}finally{G.current&&r===B.current&&$(!1)}};return{query:n,setQuery:i,composing:a,beginComposition:()=>{F.current+=1,_.current=null,k(!1),l(!0)},endComposition:()=>l(!1),kind:o,setKind:c,searchSource:d,setSearchSource:u,registry:m,setRegistry:p,items:h,loading:y,error:j,searched:I,hasMore:f,loadMore:()=>{_.current&&!y&&f&&J({..._.current,page:v+1},F.current)},retry:()=>{if(a||y)return;let e="custom"===d?tC.safeParse(m):null;if(e&&!e.success)return void N(s("invalidRegistry"));let t={query:n.trim(),kind:o,page:1,...e?.success?{registry:e.data}:{}};_.current=t,g([]),J(t,++F.current)},selection:C,detail:M,detailLoading:A,detailError:R,openDetail:e=>{E(e),z(null),U("default"),K(""),Q(e)},closeDetail:()=>{B.current+=1,E(null),z(null),$(!1),P(null)},loadDetail:Q,prepareInstall:async(t,n)=>{if(!q.current.has(t.name)){q.current.add(t.name),T(new Set(q.current)),L(e=>{let s={...e};return delete s[t.name],s});try{let r=await e.getCatalog({name:t.name,version:t.version,registry:t.registry});if(!G.current)return;if(!1===r.compatible)return void L(e=>({...e,[t.name]:s("installIncompatible")}));n(r)}catch(e){G.current&&L(n=>({...n,[t.name]:e instanceof Error?e.message:s("detailFailed")}))}finally{q.current.delete(t.name),G.current&&T(new Set(q.current))}}},preparing:D,installErrors:O,downloadMode:V,setDownloadMode:U,downloadRegistry:H,setDownloadRegistry:K,installDetail:e=>{if(!M||A)return;if(!1===M.compatible)return void L(e=>({...e,[M.name]:s("installIncompatible")}));let t="default"===V?null:tE.safeParse("custom"===V?{mode:V,registry:H}:{mode:V});t&&!t.success?L(e=>({...e,[M.name]:s("invalidRegistry")})):(L(e=>{let t={...e};return delete t[M.name],t}),e({source:`npm:${M.name}@${M.version}`,registry:M.registry,...t?.success?{downloadSource:t.data}:{}},M))}}}(s,"search"===c),C=function(e,t){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(null),[a,l]=(0,r.useState)("auto"),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(!1),[h,g]=(0,r.useState)(null),f=(0,r.useRef)(!0),x=(0,r.useRef)(!1),v=(0,r.useRef)(0),w=(0,r.useRef)("load"),y=async()=>{let t=v.current;u(!0),g(null);try{let s=await e.getCatalogSettings();if(!f.current)return;t===v.current?(i(s),l(s.downloadSource.mode),"custom"===s.downloadSource.mode&&c(s.downloadSource.registry)):i(e=>e??s)}catch(e){w.current="load",f.current&&g(e instanceof Error?e.message:s("settingsFailed"))}finally{f.current&&u(!1)}};(0,r.useEffect)(()=>{f.current=!0;let e=!0;return queueMicrotask(()=>{e&&y()}),()=>{e=!1,f.current=!1}},[e]);let k=async(n=a)=>{if(x.current)return;let r=tE.safeParse("custom"===n?{mode:n,registry:o}:{mode:n});if(!r.success){w.current="save",g(s("invalidRegistry"));return}x.current=!0,p(!0),g(null);try{let s=await e.saveCatalogSettings(r.data);f.current&&(i(s),l(s.downloadSource.mode),t())}catch(e){w.current="save",f.current&&g(e instanceof Error?e.message:s("settingsFailed"))}finally{x.current=!1,f.current&&p(!1)}};return{settings:n,mode:a,registry:o,setRegistry:e=>{v.current+=1,c(e)},loading:d,saving:m,error:h,load:y,save:k,changeMode:e=>{v.current+=1,l(e),"custom"!==e&&k(e)},retry:()=>"save"===w.current?k():y()}}(s,()=>{e||N.refresh()}),E=function(e,t=[]){let{t:s}=(0,b.Bd)("pluginManagement"),[n,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(""),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(null),[v,w]=(0,r.useState)("default"),[y,k]=(0,r.useState)(""),j=(0,r.useRef)(0),N=(0,r.useRef)(!0),I=a.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),S=1===I.length?tk(I[0]):null;(0,r.useEffect)(()=>(N.current=!0,()=>{N.current=!1,j.current+=1}),[]);let C=()=>{j.current+=1,p(null),g(!1),x(null)},E=async n=>{let r;if(!S)return null;void 0!==n&&u(n||null);let i=t.find(e=>tk(e.source)?.name===S.name)?.updateTag,a=S.version??(o||i||"latest"),l=""===n?a:n??d??a;if("custom"===v){let e=tC.safeParse(y);if(!e.success)return x(s("invalidRegistry")),null;r=e.data}else"official"===v?r="https://registry.npmjs.org":"domestic"===v&&(r="https://registry.npmmirror.com");let c=++j.current;g(!0),p(null),x(null);try{let t=await e.getCatalog({...S,...l?{version:l}:{},...r?{registry:r}:{}});if(!N.current||c!==j.current)return null;return p(t),t}catch(e){return N.current&&c===j.current&&x(e instanceof Error?e.message:s("detailFailed")),null}finally{N.current&&c===j.current&&g(!1)}},M=async(e,t)=>{if(!I.length||h)return;x(null);let n="default"===v?null:tE.safeParse("custom"===v?{mode:v,registry:y}:{mode:v});if(n&&!n.success)return void x(s("invalidRegistry"));let r={...o?{tag:o}:{},...n?.success?{downloadSource:n.data}:{}};if(I.length>1){let e=I.map(tk);if(I.length>32||e.some(e=>!e))return void x(s(I.length>32?"batchLimit":"batchNpmOnly"));let n=new Map;return e.forEach(e=>{e&&n.set(e.name,{source:`npm:${e.name}${e.version?`@${e.version}`:""}`,...r})}),void t([...n.values()])}if(!S)return void e({source:I[0]});let i=m?Promise.resolve(m):E(d??void 0),a=j.current,l=await i;if(l&&N.current&&a===j.current){if(!1===l.compatible)return void x(s("installIncompatible"));e({source:`npm:${l.name}${d||S.version?`@${d??S.version}`:""}`,registry:l.registry,...r},l)}};return{open:n,setOpen:i,source:a,sources:I,tag:o,selectedVersion:d??"",setTag:e=>{C(),u(null),c(e)},changeSource:e=>{C(),u(null),l(e)},spec:S,detail:m,loading:h,error:f,override:v,setOverride:e=>{C(),w(e)},registry:y,setRegistry:e=>{C(),k(e)},loadDetail:E,install:M}}(s,t?.plugins),M=e||N.requests.has("reload"),z=new Map(N.pluginHost.getFailedEntries().map(e=>[e.pluginName,e.error.message])),$=N.pluginHost.getEntryListError(),R=t?.plugins.find(e=>e.source===N.detailSource),P=S.selection?t?.plugins.find(e=>e.source.startsWith("npm:")&&tk(e.source)?.name===S.selection?.name):void 0,D=S.selection?tN(`npm:${S.selection.name}`):"",T=tN(E.detail?`npm:${E.detail.name}`:E.spec?`npm:${E.spec.name}`:E.source.trim()),O=t?.plugins.find(e=>tN(e.source)===T),L=e=>{let s=t?.plugins.find(t=>tN(t.source)===tN(e));return N.requests.has(tN(e))||!!(s?.operation&&"failed"!==s.operation.phase)},F=L(`npm:${S.selection?.name??""}`),B=E.sources.some(L),q=E.sources.map(e=>{let s=tN(e),n=t?.plugins.find(e=>tN(e.source)===s),r=N.errors[s]??(n?.operation?.phase==="failed"?n.operation.message:null);return r?`${e}: ${r}`:null}).filter(Boolean).join("\n"),_=!!(N.detailSource||S.selection),W=(0,r.useRef)(null),Y=(0,r.useRef)(null);(0,r.useEffect)(()=>{_?W.current?.focus():Y.current?.isConnected&&(Y.current.focus(),Y.current=null)},[_]);let V=()=>{Y.current=document.activeElement instanceof HTMLElement?document.activeElement:null},U=e=>{let s=t?.plugins.find(t=>tk(t.source)?.name===e.name);return{...e,version:s?.updateTag??"latest"}},H=e=>t?.plugins.filter(t=>"extension"!==t.kind&&!0===t.updateAvailable&&!L(t.source)&&(!e||x.has(tN(t.source)))).map(e=>e.source)??[],K=e=>e?l(`phase_${e}`):null,G=()=>{d("installed"),E.setOpen(!0)};return(0,n.jsxs)("div",{className:"flex h-full min-h-0 min-w-0 flex-col",children:[(0,n.jsxs)("header",{className:"shrink-0 space-y-3 border-b p-4 sm:px-6",children:[_?(0,n.jsxs)(I.$,{ref:W,size:"sm",variant:"ghost",className:"-ml-2",onClick:()=>{N.closeDetail(),S.closeDetail()},children:[(0,n.jsx)(A.A,{}),l("backToList")]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h2",{className:"min-w-0 text-xl font-semibold [overflow-wrap:anywhere]",children:_?R?tj(R):S.selection?.name??l("details"):l("title")}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[_?null:(0,n.jsxs)(eW.AM,{children:[(0,n.jsxs)(eW.Wv,{render:(0,n.jsx)(I.$,{size:"sm",variant:"ghost"}),children:[l("downloadSource"),":",C.loading&&!C.settings?l("loading"):l(`download_${C.settings?.downloadSource.mode??C.mode}`),(0,n.jsx)(eY.A,{className:"size-4"})]}),(0,n.jsx)(eW.hl,{align:"end",positionerClassName:"z-[150]",className:"w-80 max-w-[calc(100vw-2rem)]",children:(0,n.jsx)(tO,{id:"plugin-default-download",mode:C.mode,registry:C.registry,savedRegistry:C.settings?.downloadSource.mode==="custom"?C.settings.downloadSource.registry:void 0,recommendedRegistry:C.settings?.recommendedRegistry,loading:C.loading,saving:C.saving,error:C.error,onMode:e=>{"default"!==e&&C.changeMode(e)},onRegistry:C.setRegistry,onSave:()=>void C.save(),onRetry:()=>void C.retry()})})]}),e||t?.restartRequired?(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:N.requests.has("reload"),onClick:()=>N.setConfirmation({kind:"reload",mode:e?"normal":void 0}),children:l(e?"restartNormal":"restartApply")}):null]})]}),e?(0,n.jsx)("p",{role:"status",className:"rounded-lg bg-muted p-3 text-sm",children:l("basicModeNotice")}):null,t?.restartRequired?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("pendingRestart")}):null,t?.loadError||$?(0,n.jsxs)("div",{role:"alert",className:"max-h-32 space-y-1 overflow-y-auto text-sm text-destructive",children:[t?.loadError?(0,n.jsx)("p",{className:"[overflow-wrap:anywhere]",children:(0,eJ.fD)(t.loadError,o)}):null,$?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"min-w-0 [overflow-wrap:anywhere]",children:$}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:N.requests.has("entries"),onClick:()=>void N.refreshEntries(),children:l("retry")})]}):null]}):null,N.errors.reload||N.errors.entries?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:N.errors.reload??N.errors.entries}):null]}),(0,n.jsxs)(e5,{value:c,onValueChange:e=>d(String(e)),className:`min-h-0 flex-1 gap-0 ${_?"hidden":""}`,children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 pt-2 sm:px-6",children:(0,n.jsxs)(e4,{variant:"line","aria-label":l("title"),className:"h-9",children:[(0,n.jsxs)(e6,{value:"installed",className:"px-3",children:[l("installedTab"),t?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t.plugins.length}):null]}),(0,n.jsx)(e6,{value:"search",className:"px-3",children:l("searchPlugins")})]})}),(0,n.jsx)(e8,{value:"installed",keepMounted:!0,className:"flex min-h-0 flex-col overflow-hidden p-4 data-[hidden]:hidden sm:p-6",children:(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[E.open?(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar max-h-1/2 shrink-0 overflow-y-auto",children:(0,n.jsx)(t9,{source:E.source,isNpm:!!E.spec,multiple:E.sources.length>1,tag:E.tag,selectedVersion:E.selectedVersion,onTag:E.setTag,detail:E.detail,loading:E.loading,pending:B,disabled:M,error:E.error??(q||null),operationMessage:B?K(O?.operation?.phase)??l("submitting"):null,override:E.override,registry:E.registry,onSource:E.changeSource,onMode:E.setOverride,onRegistry:E.setRegistry,onRead:()=>void E.loadDetail(),onVersion:e=>void E.loadDetail(e),onInstall:()=>void E.install(N.requestInstall,e=>N.setConfirmation({kind:"batch",input:{action:"add",items:e}})),onClose:()=>E.setOpen(!1)})}):null,(0,n.jsx)(t_,{snapshot:t,loading:N.loading,filter:u,statusFilter:p,batchMode:g,selected:x,onStatusFilter:h,onBatchMode:e=>{f(e),e||v(new Set)},onSelect:(e,t)=>{v(s=>{let n=new Set(s);return e.forEach(e=>{t?n.add(e):n.delete(e)}),n})},onUpdateAll:()=>void N.executeBatch({action:"update",sources:H(!1)}),onUpdateSelected:()=>void N.executeBatch({action:"update",sources:H(!0)}),onRemoveSelected:()=>N.setConfirmation({kind:"batch",input:{action:"del",sources:t?.plugins.filter(e=>x.has(tN(e.source))&&!L(e.source)).map(e=>e.source)??[]}}),disabled:M,requests:N.requests,errors:N.errors,browserErrors:z,onFilter:m,onDetail:e=>{V(),S.closeDetail(),N.openDetail(e)},onAction:N.handleControlAction,onRefresh:()=>void N.refresh()}),t?.plugins.length||E.open?null:(0,n.jsx)(I.$,{size:"sm",variant:"outline",className:"shrink-0 self-start",disabled:M,onClick:G,children:l("directInstall")})]})}),(0,n.jsx)(e8,{value:"search",keepMounted:!0,className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto p-4 data-[hidden]:hidden sm:p-6",children:(0,n.jsx)(tW,{query:S.query,kind:S.kind,searchSource:S.searchSource,registry:S.registry,items:S.items,loading:S.loading,error:S.error,searched:S.searched,hasMore:S.hasMore,disabled:M,snapshot:t,requests:N.requests,preparing:S.preparing,errors:N.errors,installErrors:S.installErrors,onQuery:S.setQuery,onCompositionStart:S.beginComposition,onCompositionEnd:S.endComposition,onKind:S.setKind,onSearchSource:e=>{S.setSearchSource(e),"custom"!==e||S.registry||C.settings?.downloadSource.mode!=="custom"||S.setRegistry(C.settings.downloadSource.registry)},onRegistry:S.setRegistry,onDetail:e=>{V(),N.closeDetail(),y(""),j(!1),S.openDetail(U(e))},onInstall:e=>{S.prepareInstall(U(e),e=>N.requestInstall({source:`npm:${e.name}`,registry:e.registry},e))},onUpdate:e=>void N.execute({kind:"update",source:e}),onMore:S.loadMore,onRetry:S.retry,onDirectInstall:G})})]}),_?(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:R?(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[R.version?(0,n.jsxs)("span",{children:["v",R.version]}):null,R.updateAvailable?(0,n.jsx)("span",{className:"rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:R.availableVersion?l("newVersion",{version:R.availableVersion}):l("updateAvailable")}):null]}),(0,n.jsx)(tw,{plugin:R,displayName:tj(R),browserError:R.pluginName?z.get(R.pluginName)??null:null,disabled:M,pending:L(R.source),browserRetryPending:N.requests.has(`entry:${R.pluginName}`),onAction:e=>N.handleControlAction(R,e)})]}),R.description?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:(0,eJ.fD)(R.description,o)}):null,(0,n.jsx)(ty,{plugin:R,requestError:N.errors[tN(R.source)],browserError:R.pluginName?z.get(R.pluginName)??null:null})]}),(0,n.jsxs)(eV.Nt,{className:"rounded-lg border",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between px-3 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l("advancedOptions"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 px-3 pb-3",children:[R.source.startsWith("npm:")?(0,n.jsx)(t4,{value:R.updateTag??"latest",label:l("installChannel"),disabled:M||L(R.source),onChange:e=>void N.executeBatch({action:"tag",sources:[R.source],tag:e})}):null,(0,n.jsx)(I.$,{size:"sm",variant:"outline",disabled:M||L(R.source)&&R.operation?.phase!=="waiting",onClick:()=>N.handleControlAction(R,"reload"),children:l("reloadOne")})]})})]}),N.detailLoading?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("loadingPackage")}):null,N.detail?.readme?(0,n.jsx)(t3,{readme:N.detail.readme},R.source):null,(0,n.jsxs)(eV.Nt,{className:"border-t pt-2",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-9 w-full items-center justify-between text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l("capabilityDetails"),(0,n.jsx)(eY.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eV.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsx)(tf,{plugin:R,detail:N.detail,detailLoading:N.detailLoading,detailError:N.detailError,browserContributions:R.pluginName?N.pluginHost.getRegisteredBrowserDescriptors().find(e=>e.pluginName===R.pluginName)?.contributions??[]:[],onRetry:()=>void N.loadDetail(R.source)})})]}),N.detailError?(0,n.jsxs)("div",{role:"alert",className:"flex items-center gap-2 text-sm text-destructive",children:[(0,n.jsx)("span",{children:N.detailError}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:()=>void N.loadDetail(R.source),children:l("retry")})]}):null]}):S.selection?(0,n.jsxs)(n.Fragment,{children:[S.detailLoading?(0,n.jsx)("p",{role:"status",className:"mb-3 text-sm text-muted-foreground",children:l("loadingPackage")}):null,S.detailError?(0,n.jsxs)("div",{role:"alert",className:"mb-3 space-y-2 text-sm",children:[(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:S.detailError}),(0,n.jsx)(I.$,{size:"sm",variant:"outline",onClick:()=>void S.loadDetail(S.selection),children:l("retry")})]}):null,S.detail?(0,n.jsx)(t8,{detail:S.detail,disabled:M||!!S.detailError,pending:F||S.detailLoading,installed:!!(P&&(P.operation?.action!=="add"||"failed"!==P.operation.phase)),installedVersion:P?.version??null,updateAvailable:!!P?.updateAvailable,error:S.installErrors[S.detail.name]??N.errors[D]??(P?.operation?.phase==="failed"?P.operation.message:null),operationMessage:S.detailLoading?l("loadingPackage"):K(P?.operation?.phase),channel:w,onChannel:e=>{y(e),j(!1),S.loadDetail(S.selection,e||P?.updateTag||"latest")},downloadMode:S.downloadMode,downloadRegistry:S.downloadRegistry,onDownloadMode:S.setDownloadMode,onDownloadRegistry:S.setDownloadRegistry,onVersion:e=>{j(!0),S.loadDetail(S.selection,e)},onInstall:()=>S.installDetail((e,t)=>N.requestInstall({...e,source:k?e.source:`npm:${t.name}`,...w?{tag:w}:{}},t)),onUpdate:()=>{P&&N.execute({kind:"update",source:P.source})}}):null]}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:l("pluginRemoved")})}):null,(0,n.jsx)(se,{confirmation:N.confirmation,onClose:()=>N.setConfirmation(null),onConfirm:e=>void N.execute(e)})]})}var ss=s(99739);let sn=a.Yj().trim().min(1).max(2048),sr=a.YO(sn).min(1).max(32),si=a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:eJ.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0)}).strict(),sa=a.Yj().trim().min(1).max(4096),sl=a.Yj().trim().min(1).max(256),so=a.Yj().max(32768),sc=a.Ik({name:sl,label:so,state:a.k5(["active","inactive","shadowed"]),description:so,promptSnippet:so.nullable(),promptGuidelineCount:a.ai().int().nonnegative(),promptGuidelinePreview:so.nullable()}).strict(),sd=a.Ik({name:sl,label:so,state:a.k5(["active","inactive","shadowed"]),description:so,parameters:ss.Dz,promptSnippet:so.nullable(),promptGuidelines:a.YO(so)}).strict(),su=a.Ik({path:sa,events:a.YO(a.Ik({name:sl,count:a.ai().int().positive()}).strict()),commands:a.YO(a.Ik({name:sl,description:so.nullable()}).strict()),shortcuts:a.YO(a.Ik({shortcut:sl,description:so.nullable()}).strict()),flags:a.YO(a.Ik({name:sl,type:a.k5(["boolean","string"]),description:so.nullable(),default:a.KC([a.zM(),a.Yj(),a.ch()])}).strict()),messageRenderers:a.YO(sl),entryRenderers:a.YO(sl)}).strict(),sm=a.Ik({name:sl,description:so,path:sa}).strict(),sp=sm.extend({modelVisible:a.zM()}).strict(),sh=sm.extend({content:a.Yj().max(65536),truncated:a.zM()}).strict(),sg=sh.extend({modelVisible:a.zM()}).strict(),sf=a.Ik({name:sl,path:sa}).strict(),sx=a.Ik({name:sl,kind:a.k5(["config","native"])}).strict(),sb=a.Ik({methods:a.YO(a.Ik({pluginName:sl,method:sl}).strict()),browserEntries:a.YO(a.Ik({pluginName:sl}).strict()),messageDeclarations:a.YO(a.Ik({pluginName:sl,declarationName:sl,priority:a.ai().int().safe()}).strict())}).strict(),sv=a.Ik({error:eJ.qf.refine(e=>"string"==typeof e?e.length<=32768:[e.default,...Object.values(e.translations)].every(e=>e.length<=32768)).nullable(),extensions:a.YO(su),tools:a.YO(sc),skills:a.YO(sp),prompts:a.YO(sm),themes:a.YO(sf),providers:a.YO(sx),piDesk:sb}).strict(),sw=a.Ik({action:a.k5(["add","update","del","apply","enable","disable"]),phase:a.k5(["queued","checking","applying","waiting","failed"]),message:a.Yj().max(4e3).nullable()}).strict(),sy=(0,l._G)({path:"plugins/management-update",bodySchema:a.Ik({}).strict()}),sk=a.Ik({source:sn,kind:a.k5(["package","extension"]).default("package"),operation:sw.nullable().default(null),pluginName:a.Yj().trim().min(1).nullable(),description:eJ.qf.nullable().default(null),version:a.Yj().trim().min(1).nullable(),updateAvailable:a.zM().nullable(),updateTag:tS.nullable().optional(),availableVersion:a.Yj().min(1).nullable().optional(),updateError:a.Yj().max(4e3).nullable().optional(),status:a.k5(["ready","available","disabled","failed"]),error:si.nullable(),capabilities:sv}).strict(),sj=a.Ik({source:sn,readme:eJ.qf.nullable().default(null),tools:a.YO(sd),skills:a.YO(sg),prompts:a.YO(sh)}).strict(),sN=a.Ik({plugins:a.YO(sk),restartRequired:a.zM(),loadError:eJ.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0).nullable()}).strict(),sI=a.Ik({sources:a.YO(sn).min(1).max(32).optional()}).strict(),sS=a.Ik({}).strict().extend({mode:a.k5(["normal","basic"]).optional()}).strict(),sC=a.Ik({checkUpdates:a.zM().optional(),sources:sr.optional(),tag:tS.optional()}).strict(),sE=a.Ik({source:sn}).strict(),sM=sE.extend({downloadSource:tE.optional(),registry:tC.optional(),tag:tS.optional()}).strict(),sz=a.gM("action",[a.Ik({action:a.eu("add"),items:a.YO(sM).min(1).max(32)}).strict(),a.Ik({action:a.eu("update"),sources:sr}).strict(),a.Ik({action:a.eu("del"),sources:sr}).strict(),a.Ik({action:a.eu("tag"),sources:sr,tag:tS}).strict()]),sA=a.Ik({snapshot:sN,results:a.YO(a.Ik({source:sn,error:a.Yj().max(4e3).nullable()}).strict()).max(32)}).strict(),s$=sE.extend({enabled:a.zM()}).strict();async function sR(e,t,s,n){return eu(e,t,s,n,{fallbackMessage:"插件管理请求失败"})}function sP({pluginName:e,descriptor:t,source:s,cwd:r,onPreviewFile:i,onRevealFile:a,onHeaderActionsChange:l}){let o=`${s.workId}\u0000${s.sessionId}\u0000${s.branchId}\u0000${r}`;return(0,n.jsx)(eH,{pluginName:e,kind:"session-sidebar-tab",contributionName:t.contributionName,target:{kind:"session-sidebar-tab",source:s,cwd:r,files:{preview:i,reveal:a},setHeaderActions:l},targetKey:o,layout:"fill"})}function sD({pluginName:e,descriptor:t,onClose:s,onBeforeLeaveChange:i}){let a=(0,Q.t4)();(0,Q.So)();let l=a.getEntryState(e),o="ready"===l.status?l.runtime:l.status;(0,r.useEffect)(()=>()=>{i(null)},[o,i]);let c=(0,r.useMemo)(()=>({kind:"settings-page",close:()=>{a.getEntryState(e)===l&&s()},setBeforeLeave:t=>{a.getEntryState(e)===l&&i(t)}}),[l,i,s,e,a]);return(0,n.jsx)(eH,{pluginName:e,kind:"settings-page",contributionName:t.contributionName,target:c,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})}function sT({source:e,placement:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,Q.So)(),a=(0,r.useMemo)(()=>({kind:"widget",source:e}),[e]),l=JSON.stringify([e.workId,e.sessionId,e.branchId]),o=i.flatMap(e=>e.contributions.flatMap(s=>"widget"===s.kind&&s.placement===t?[{pluginName:e.pluginName,descriptor:s}]:[]));return 0===o.length?null:(0,n.jsx)("div",{"data-testid":`plugin-widgets-${t}`,"aria-label":s("composer"),className:"min-w-0 w-full",children:o.map(({pluginName:e,descriptor:t})=>(0,n.jsx)(eH,{pluginName:e,kind:"widget",contributionName:t.contributionName,target:a,targetKey:l,layout:"inline"},`${e}:${t.contributionName}:${l}`))})}function sO({pluginName:e,contributionName:t,presentation:s,source:i,icon:a,label:l,onSelected:o}){let c=(0,Q.t4)();(0,Q.So)();let d=c.getEntryState(e),u=(0,X.G)(),{t:m}=(0,b.Bd)("workbench"),p=(0,r.useRef)(null),h=(0,r.useRef)(!1),[g,f]=(0,r.useState)(!1);(0,r.useLayoutEffect)(()=>{let e=new AbortController;return p.current=e,h.current=!1,queueMicrotask(()=>{e.signal.aborted||f(!1)}),()=>{e.abort(),p.current===e&&(p.current=null)}},[d,s,i]);let x=async()=>{let n=p.current;if(!n||n.signal.aborted||h.current)return;let r=()=>!n.signal.aborted&&c.getEntryState(e)===d;h.current=!0,f(!0);try{await c.invokeSessionHeaderAction({pluginName:e,contributionName:t,presentation:s,source:i,signal:n.signal}),r()&&o?.()}catch(a){if(!r())return;let n=a instanceof Error?a.message:m("operationFailed");console.error("[Pi Desk][PluginHost] 会话标题操作失败",{pluginName:e,contributionName:t,presentation:s,source:i,message:n}),u.error(n)}finally{r()&&(h.current=!1,f(!1))}};return(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm","aria-label":l,"aria-busy":g,disabled:g,"data-testid":"plugin-session-header-action","data-plugin-name":e,"data-contribution-name":t,"data-presentation":s,className:(0,C.cn)("overflow"===s&&"w-full justify-start whitespace-normal text-left"),onClick:()=>void x(),children:[(0,n.jsx)(eq,{icon:a,className:"size-4"}),(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:l})]})}function sL(e){return`${e.pluginName}:${e.descriptor.contributionName}`}function sF({item:e,source:t,presentation:s,onSelected:i}){let a=e.descriptor[s],l=(0,r.useMemo)(()=>({kind:"session-header-item",source:t,presentation:s}),[s,t]),o=JSON.stringify([t.workId,t.sessionId,t.branchId,s]);return"action"===a.type?(0,n.jsx)(sO,{pluginName:e.pluginName,contributionName:e.descriptor.contributionName,presentation:s,source:t,icon:a.icon,label:a.label,onSelected:i}):(0,n.jsx)("div",{"data-testid":"plugin-session-header-custom","data-plugin-name":e.pluginName,"data-contribution-name":e.descriptor.contributionName,"data-presentation":s,className:"min-w-0 shrink-0",style:"inline"===s&&"custom"===e.descriptor.inline.type?{width:`${e.descriptor.inline.minWidthRem}rem`}:void 0,children:(0,n.jsx)(eH,{pluginName:e.pluginName,kind:"session-header-item",contributionName:e.descriptor.contributionName,target:l,targetKey:o,layout:"inline"})})}function sB({source:e,title:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,Q.So)(),a=(0,r.useMemo)(()=>i.flatMap(e=>e.contributions.flatMap(t=>"session-header-item"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[i]),l=(0,r.useRef)(null),o=(0,r.useRef)(null),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(!1),p=c?.items===a?c.count:0,h=a.slice(0,p),g=a.slice(p);return(0,r.useLayoutEffect)(()=>{let e=l.current,t=o.current;if(!e||!t||0===a.length)return;let s=[...t.querySelectorAll("[data-header-item-width]")],n=t.querySelector("[data-header-title-width]"),r=t.querySelector("[data-header-more-width]"),i=t.querySelector("[data-header-gap-width]"),c=()=>{let t=i.getBoundingClientRect().width,l=e.getBoundingClientRect().width-n.getBoundingClientRect().width-t,o=function(e,t,s,n){if(e.reduce((e,t)=>e+t,0)+Math.max(0,e.length-1)*n<=t)return e.length;let r=s,i=0;for(let s of e){if(r+n+s>t)break;r+=n+s,i+=1}return i}(s.map(e=>e.getBoundingClientRect().width),l,r.getBoundingClientRect().width,t);o===a.length&&m(!1),d(e=>e?.items===a&&e.count===o?e:{items:a,count:o})},u=new ResizeObserver(c);for(let t of(u.observe(e),[...s,n,r,i]))u.observe(t);return c(),()=>u.disconnect()},[a]),(0,n.jsxs)("div",{ref:l,className:"relative flex min-w-0 flex-1 items-center gap-1","data-testid":"plugin-session-header",children:[(0,n.jsx)("div",{className:"min-w-[3rem] flex-1",children:t}),a.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-1","data-testid":"session-header-items",children:[h.map(t=>(0,n.jsx)(sF,{item:t,source:e,presentation:"inline"},sL(t))),g.length>0?(0,n.jsxs)(eW.AM,{open:u,onOpenChange:m,children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":s("moreActions"),"data-testid":"session-header-more"}),children:(0,n.jsx)(H.A,{className:"size-4"})}),(0,n.jsxs)(eW.hl,{align:"end",finalFocus:!0,className:"pi-desk-chat-scrollbar max-h-[min(28rem,var(--available-height))] gap-1 overflow-auto p-1","data-testid":"session-header-overflow","aria-label":s("moreActions"),children:[(0,n.jsx)(eW.eO,{className:"sr-only",children:s("moreActions")}),u?g.map(t=>(0,n.jsx)(sF,{item:t,source:e,presentation:"overflow",onSelected:()=>m(!1)},sL(t))):null]})]}):null]}),(0,n.jsx)("div",{ref:o,"aria-hidden":"true",inert:!0,className:"pointer-events-none invisible absolute inset-0 overflow-hidden",children:(0,n.jsxs)("div",{className:"flex w-max items-center",children:[(0,n.jsx)("span",{"data-header-title-width":!0,className:"inline-block w-[3rem]"}),(0,n.jsx)("span",{"data-header-gap-width":!0,className:"inline-block w-1"}),(0,n.jsx)("span",{"data-header-more-width":!0,className:(0,I.r)({variant:"ghost",size:"icon-sm"}),children:(0,n.jsx)(H.A,{className:"size-4"})}),a.map(e=>"action"===e.descriptor.inline.type?(0,n.jsxs)("span",{"data-header-item-width":!0,className:(0,I.r)({variant:"ghost",size:"sm"}),children:[(0,n.jsx)(eq,{icon:e.descriptor.inline.icon,className:"size-4"}),(0,n.jsx)("span",{children:e.descriptor.inline.label})]},sL(e)):(0,n.jsx)("span",{"data-header-item-width":!0,className:"inline-block shrink-0",style:{width:`${e.descriptor.inline.minWidthRem}rem`}},sL(e)))]})})]}):null]})}var sq=s(10263),s_=s(11831),sW=s(79615),sY=s(24863),sV=s(10672);let sU="1.1.28-dev".trim()||"未知",sH="2026-10-28T01:13:51+08:00".trim()||null;var sK=s(42655),sG=s(55079),sJ=s(49667),sQ=s(61286),sX=s(33550),sZ=s(66453),s0=s(67765);let s1=a.Yj().min(1).max(s0.uV).refine(e=>!e.includes("\0")&&(e.startsWith("/")||e.startsWith("\\\\")||/^[a-zA-Z]:[\\/]/.test(e)),"必须是绝对路径"),s2=a.Ik({cwd:sZ.m4.nullable()}).strict(),s5=a.Ik({skillPath:s1,name:a.Yj().min(1),description:a.Yj(),packageSource:a.Yj().nullable()}).strict(),s3=a.Ik({skills:a.YO(s5),diagnostics:a.YO(a.Ik({path:a.Yj(),message:eJ.qf}).strict())}).strict(),s4=s2.extend({skillPath:s1}),s6=s4.extend({path:s0.rh}).strict(),s8=a.Ik({entries:a.YO(a.Ik({name:a.Yj().min(1),type:a.k5(["directory","file"])}).strict()).max(s0.xm),truncated:a.zM()}).strict(),s7=s4.extend({path:s0._g}).strict(),s9=a.gM("kind",[a.Ik({kind:a.eu("text"),content:a.Yj(),size:a.ai().int().nonnegative().max(s0.NL),readOnlyReason:eJ.qf.nullable()}).strict(),a.Ik({kind:a.eu("image"),mimeType:s0.CT,data:a.Yj(),size:a.ai().int().nonnegative()}).strict(),a.Ik({kind:a.eu("unsupported"),size:a.ai().int().nonnegative(),reason:a.Yj()}).strict()]),ne=s7.extend({content:a.Yj().max(s0.NL)}).strict(),nt=a.Ik({}).strict(),ns={path:"/api/skills/list",request:s2,response:s3},nn={path:"/api/skill-files/list",request:s6,response:s8},nr={path:"/api/skill-files/get",request:s7,response:s9},ni={path:"/api/skill-files/replace",request:ne,response:nt},na=a.Ik({code:a.ai(),msg:a.Yj(),data:a.L5(),i18n:sQ.N.optional()});async function nl(e,t,s,n){let r=await fetch(t.path,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(t.request.parse(s)),signal:n}),i=na.parse(await r.json());if(!r.ok||0!==i.code||null===i.data)throw Error(i.msg?(0,ed.B)(i):"Skills 请求失败");return t.response.parse(i.data)}function no(e){(0,sX.ZQ)({wrapLines:e})}async function nc(e){let t=e.skillPath.replaceAll("\\","/");await navigator.clipboard.writeText(t.slice(0,t.lastIndexOf("/")+1)+e.path)}var nd=s(46782);function nu(e){return(0,ed.B)({msg:nd.P["zh-CN"][e],i18n:{key:`skills:${e}`}})}function nm(e){return JSON.stringify(e)}function np(e){return JSON.stringify([e.cwd,e.skillPath,e.path])}function nh(e){return e.replace(/\r\n|\r/g,"\n")}function ng(e){return e?.file?.kind==="text"&&e.draft!==nh(e.file.content)}var nf=s(60794),nx=s(89757),nb=s(55628),nv=s(91182);function nw(e){let{t}=(0,b.Bd)("common"),{wrapLines:s}=(0,sX.TX)(),i=e.path,a=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(null),d=(0,r.useRef)(null),u=(0,r.useRef)(0),m=(0,r.useRef)(e),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{m.current=e}),(0,r.useEffect)(()=>{let e=!1,s=()=>void 0,n=()=>void 0;return(0,nv.cu)().then(r=>{if(e||!a.current)return;let i=m.current,o=r.editor.create(a.current,{model:null,theme:(0,nv.dC)(),automaticLayout:!0,readOnly:i.readOnly,domReadOnly:i.readOnly,wordWrap:(0,sX.E6)().wrapLines?"on":"off",wrappingIndent:"same",minimap:{enabled:!1},stickyScroll:{enabled:!1},scrollBeyondLastLine:!1,...(0,nv.R)(),lineNumbersMinChars:3,padding:{top:14,bottom:14},unicodeHighlight:{nonBasicASCII:!1},renderWhitespace:"selection",overviewRulerBorder:!1,ariaLabel:t("skillEditor")});l.current=o,o.addCommand(r.KeyMod.CtrlCmd|r.KeyCode.KeyS,()=>m.current.onSave()),s=(0,nv.Tr)(e=>r.editor.setTheme(e)),n=(0,nv.BK)(e=>o.updateOptions(e)),f(!0)}).catch(()=>{e||h(!0)}),()=>{e=!0,s(),n(),c.current?.dispose(),c.current=null,o.current?.dispose(),o.current=null,d.current=null,l.current?.dispose(),l.current=null}},[t]),(0,r.useEffect)(()=>{let e=!1,t=u.current+1;return u.current=t,(0,nv.cu)().then(s=>{if(e||t!==u.current||!l.current)return;let n=m.current,r=s.editor.createModel(n.content,(0,nv.ix)(n.path,n.size),(0,nv.B3)(s,n.path,"edit")),a=o.current;c.current?.dispose(),c.current=r.onDidChangeContent(()=>{m.current.onChange(r.getValue(s.editor.EndOfLinePreference.LF))}),o.current=r,d.current=i,l.current.setModel(r),a?.dispose()}),()=>{e=!0}},[i]),(0,r.useEffect)(()=>{let t=o.current;t&&d.current===e.path&&t.getValue().replace(/\r\n|\r/g,"\n")!==e.content&&t.setValue(e.content)},[e.content,e.path]),(0,r.useEffect)(()=>{l.current?.updateOptions({readOnly:e.readOnly,domReadOnly:e.readOnly,wordWrap:s?"on":"off"})},[e.readOnly,s]),(0,n.jsxs)("div",{"data-testid":"code-editor",className:"relative h-full min-h-0 w-full overflow-hidden bg-background",children:[(0,n.jsx)("div",{ref:a,className:"size-full"}),!g&&(0,n.jsx)("div",{role:"status",className:"absolute inset-0 flex items-center justify-center p-6 text-sm text-muted-foreground",children:p?t("editorFailed"):t("editorLoading")})]})}var ny=s(58840);function nk({file:e,path:t}){let{t:s}=(0,b.Bd)("skills"),i=(0,r.useMemo)(()=>[{src:`data:${e.mimeType};base64,${e.data}`,alt:t}],[e,t]);return(0,n.jsx)(ny.k,{mode:"inline",slides:i,className:"h-full w-full",ariaLabel:s("imagePreview")})}function nj(e){let{document:t,skill:s,dirty:r,loading:i,saving:a,opening:l}=e,{t:o}=(0,b.Bd)("skills"),{locale:c}=(0,eQ.i)();if(!t)return(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center",children:[(0,n.jsx)(nf.A,{className:"size-6 text-muted-foreground"}),(0,n.jsx)("h3",{className:"text-sm font-medium",children:o("chooseFile")}),(0,n.jsx)("p",{className:"max-w-xs text-sm leading-6 text-muted-foreground",children:o("chooseFileDescription")})]});let d=t.file,u=d?.kind==="text"?d.readOnlyReason:null;return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-14 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-2",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("p",{className:"truncate text-xs text-muted-foreground",title:s?.description,children:[s?.name??t.target.skillPath.split("/").at(-2),(0,n.jsx)("span",{className:"mx-1.5",children:"/"}),o(null===t.target.cwd?"global":"project"),` \xb7 ${o(s?.packageSource?"package":"local")}`]}),(0,n.jsx)("p",{className:"mt-1 truncate font-mono text-sm",title:t.target.path,children:t.target.path})]}),d?.kind==="text"&&(0,n.jsxs)("span",{role:"status","aria-label":o(a?"saving":l?"switchingFile":r?"unsavedChanges":u?"readOnlyFile":"fileSaved"),className:"hidden shrink-0 items-center gap-1 text-xs text-muted-foreground sm:flex",children:[a||l?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):r?(0,n.jsx)("span",{className:"size-1.5 rounded-full bg-status-warning"}):u?(0,n.jsx)(nx.A,{className:"size-3.5"}):(0,n.jsx)(ep.A,{className:"size-3.5"}),o(a?"saving":l?"switchingFile":r?"unsaved":u?"readOnly":"saved")]}),r&&(0,n.jsx)("span",{"aria-label":o("unsavedChanges"),className:"size-2 shrink-0 rounded-full bg-status-warning sm:hidden"}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon","aria-label":o("copySkillPath"),title:o("copyPath"),onClick:e.onCopy,children:(0,n.jsx)(ee.A,{className:"size-4"})}),(0,n.jsxs)(I.$,{"aria-label":o("saveSkill"),disabled:!r||!!u||i||a,onClick:e.onSave,children:[a?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(Z.A,{className:"size-4"}),o("save")]})]}),u&&(0,n.jsxs)("div",{role:"note",className:"flex shrink-0 items-start gap-2 border-b bg-muted px-4 py-2 text-sm leading-5 text-muted-foreground",children:[(0,n.jsx)(nx.A,{className:"mt-0.5 size-3.5 shrink-0"}),(0,n.jsx)("p",{children:(0,eJ.fD)(u,c)})]}),t.error&&(0,n.jsxs)("div",{role:"alert",className:"shrink-0 border-b bg-muted px-4 py-2 text-sm text-destructive",children:[t.error,!d&&(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:e.onReload,children:o("reload")})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:i&&!d?(0,n.jsxs)("div",{role:"status",className:"flex h-full items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),o("loadingFile")]}):d?.kind==="text"?(0,n.jsx)(nw,{path:t.target.skillPath.slice(0,t.target.skillPath.lastIndexOf("/")+1)+t.target.path,content:t.draft,size:d.size,readOnly:!!u||a||l,onChange:e.onChange,onSave:e.onSave}):d?.kind==="image"?(0,n.jsx)(nk,{file:d,path:t.target.path}):d?.kind==="unsupported"?(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-sm text-muted-foreground",children:[(0,n.jsx)(nf.A,{className:"mb-2 size-8"}),(0,n.jsx)("p",{children:d.reason}),(0,n.jsx)("p",{children:o("fileSize",{size:d.size.toLocaleString("en"===c?"en-US":"zh-CN")})})]}):null}),d?.kind==="text"&&(0,n.jsxs)("div",{className:"flex min-h-9 shrink-0 items-center justify-between gap-2 border-t px-3 py-1 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{className:"truncate",children:["UTF-8 \xb7 ",o(u?"readOnly":"saveShortcut")]}),(0,n.jsxs)(I.$,{variant:"ghost",size:"sm","aria-label":o("wrapLines"),"aria-pressed":e.wrapLines,onClick:e.onWrapLines,children:[(0,n.jsx)(nb.A,{className:"size-3.5"}),o("wrapLines")]})]})]})}function nN({open:e,saving:t,path:s,error:r,onDecide:i}){let{t:a}=(0,b.Bd)("skills");return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||t||i("cancel")},children:(0,n.jsxs)(eN.hA,{className:"z-[150]",showCloseButton:!t,children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:a("saveChangesTitle")}),(0,n.jsx)(eN.uX,{children:a("saveChangesDescription",{path:s??""})})]}),r&&(0,n.jsx)("p",{role:"alert",className:"px-4 pb-4 text-sm text-destructive",children:r}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{variant:"outline",disabled:t,onClick:()=>void i("cancel"),children:a("cancel")}),(0,n.jsx)(I.$,{variant:"ghost",disabled:t,onClick:()=>void i("discard"),children:a("discard")}),(0,n.jsx)(I.$,{disabled:t,onClick:()=>void i("save"),children:a(t?"savingChanges":"saveContinue")})]})]})})}var nI=s(19932),nS=s(43326),nC=s(17511);function nE(e,t){return!!(e&&e.cwd===t.cwd&&e.skillPath===t.skillPath&&e.path===t.path)}function nM({target:e,props:t,depth:s=0,skillName:i}){let{t:a}=(0,b.Bd)("skills"),l=t.directories[np(e)],{onLoadDirectory:o}=t;return((0,r.useEffect)(()=>{l||o(e)},[l,o,e]),l?.error)?(0,n.jsxs)("div",{className:"px-3 py-2 text-xs text-destructive",children:[l.error,(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:()=>void t.onLoadDirectory(e),children:a("retryFolder")})]}):l?.data?(0,n.jsxs)("div",{className:"relative ml-5 border-l border-border/70 py-1 pl-3",children:[l.data.entries.map(r=>{let l=e.path?`${e.path}/${r.name}`:r.name,o={...e,path:l};if("directory"===r.type)return(0,n.jsx)(nz,{target:o,props:t,depth:s,name:r.name,skillName:i},l);let c=nE(t.selected,o),d=nE(t.pending,o);return(0,n.jsxs)(I.$,{variant:"ghost","aria-label":a("skillFile",{path:`${i}/${l}`}),"aria-pressed":c,title:l,className:(0,C.cn)("min-h-9 w-full justify-start text-left font-normal text-muted-foreground",c&&"font-medium",d&&"bg-muted text-foreground"),onClick:()=>void t.onOpenFile(o),children:["SKILL.md"===r.name?(0,n.jsx)(nI.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(nf.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r.name}),d&&(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin"})]},l)}),0===l.data.entries.length&&(0,n.jsx)("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:a("emptyFolder")}),l.data.truncated&&(0,n.jsx)("p",{className:"px-3 py-2 text-sm text-status-warning",children:a("folderTruncated")})]}):(0,n.jsx)("p",{role:"status",className:"px-4 py-2 text-xs text-muted-foreground",children:a("loadingFolder")})}function nz({target:e,props:t,depth:s,name:i,skillName:a}){let{t:l}=(0,b.Bd)("skills"),[o,c]=(0,r.useState)(!1);return(0,n.jsxs)("div",{children:[(0,n.jsxs)(I.$,{variant:"ghost","aria-expanded":o,"aria-label":l("skillFolder",{path:`${a}/${e.path}`}),className:(0,C.cn)("min-h-9 w-full justify-start font-normal text-muted-foreground",o&&"bg-muted text-foreground"),onClick:()=>c(!o),children:[o?(0,n.jsx)(eY.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(e7.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)(eP.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:i})]}),o&&(0,n.jsx)("div",{className:s>3?"-ml-3":void 0,children:(0,n.jsx)(nM,{target:e,props:t,depth:s+1,skillName:a})})]})}function nA({cwd:e,skill:t,props:s}){let{t:i}=(0,b.Bd)("skills"),a=s.selected?.cwd===e&&s.selected.skillPath===t.skillPath,l=s.pending?.cwd===e&&s.pending.skillPath===t.skillPath,[o,c]=(0,r.useState)(null),d=o??a,u=async()=>{if(d)return void c(!1);let n=t.skillPath.replaceAll("\\","/").split("/").at(-1);await s.onOpenFile({cwd:e,skillPath:t.skillPath,path:n})&&c(!0)};return(0,n.jsxs)("div",{className:"py-0.5",children:[(0,n.jsxs)(I.$,{variant:"ghost","aria-label":i("skillName",{name:t.name}),"aria-expanded":d,title:`${t.description}
|
|
155
|
+
${t.skillPath}`,className:(0,C.cn)("min-h-14 w-full justify-start whitespace-normal text-left",d&&"bg-accent hover:bg-accent",a&&"text-foreground"),onClick:()=>void u(),children:[d?(0,n.jsx)(eY.A,{className:"size-3.5 shrink-0 text-muted-foreground"}):(0,n.jsx)(e7.A,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",children:t.name}),t.description&&(0,n.jsx)("p",{className:"mt-0.5 truncate text-xs font-normal text-muted-foreground",children:t.description})]}),l?(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground"}):t.packageSource?(0,n.jsx)(nS.A,{"aria-label":i("packageSkill"),className:"size-3.5 shrink-0 text-muted-foreground"}):null]}),d&&(0,n.jsx)(nM,{target:{cwd:e,skillPath:t.skillPath,path:""},props:s,skillName:t.name})]})}function n$({cwd:e,name:t,props:s}){let{t:i}=(0,b.Bd)("skills"),{locale:a}=(0,eQ.i)(),l=s.selected?.cwd===e||s.pending?.cwd===e,[o,c]=(0,r.useState)(null),{onLoadScope:d}=s,u=s.scopes[nm(e)],m=s.query.trim().toLowerCase(),p=o??(null===e||s.focusedCwd===e||l),h=p||!!m;(0,r.useEffect)(()=>{h&&!u&&d(e)},[e,h,u,d]);let g=`${t} ${e??""}`.toLowerCase().includes(m),f=u?.data?.skills.filter(e=>!m||g||`${e.name} ${e.description}`.toLowerCase().includes(m))??[];if(m&&u?.data&&!f.length&&!g&&!u.error)return null;let x=null===e;return(0,n.jsxs)("section",{className:"mx-2 mt-2 min-w-0 border-b pb-2","aria-label":x?i("globalSkills"):i("projectSkills",{name:t}),children:[(0,n.jsxs)(I.$,{variant:"ghost",className:"min-h-14 w-full justify-start text-left","aria-label":i("skillsGroup",{name:x?i("global"):t}),"aria-expanded":h,onClick:()=>c(!p),children:[h?(0,n.jsx)(eY.A,{className:"size-4 shrink-0"}):(0,n.jsx)(e7.A,{className:"size-4 shrink-0"}),x?(0,n.jsx)(eL.A,{className:"size-4 shrink-0 text-primary"}):(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-semibold",children:x?i("globalSkills"):t}),e&&(0,n.jsx)("p",{title:e,className:"mt-1 truncate text-xs font-normal text-muted-foreground",children:e})]}),u?.loading?(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground"}):u?.data?(0,n.jsx)("span",{className:"text-xs tabular-nums text-muted-foreground",children:m?f.length:u.data.skills.length}):null]}),h&&(0,n.jsxs)("div",{className:"px-1 py-1",children:[u?.error&&(0,n.jsxs)("p",{className:"px-3 py-2 text-xs text-destructive",children:[u.error,(0,n.jsx)(I.$,{variant:"ghost",size:"sm",onClick:()=>void s.onLoadScope(e),children:i("retryGroup")})]}),f.map(t=>(0,n.jsx)(nA,{cwd:e,skill:t,props:s},t.skillPath)),u?.data&&0===f.length&&!u.error&&(0,n.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground",children:i(m?"noSkillMatches":"noSkills")}),!!u?.data?.diagnostics.length&&(0,n.jsxs)("details",{className:"mx-2 mb-1 mt-2 rounded-md bg-muted p-2 text-sm text-muted-foreground",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-status-warning",children:i("diagnostics",{count:u.data.diagnostics.length})}),(0,n.jsx)("div",{className:"mt-2 space-y-3",children:u.data.diagnostics.map((e,t)=>(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"break-words",children:(0,eJ.fD)(e.message,a)}),(0,n.jsx)("p",{className:"mt-1 break-all text-xs",children:e.path})]},`${e.path}:${t}`))})]})]})]})}function nR(e){let{t}=(0,b.Bd)("skills");return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsx)("div",{className:"shrink-0 border-b p-3",children:(0,n.jsxs)(nC.MG,{children:[(0,n.jsx)(nC.Sq,{children:(0,n.jsx)(eh.A,{className:"size-4"})}),(0,n.jsx)(nC.iV,{"aria-label":t("searchSkills"),value:e.query,onChange:t=>e.onQuery(t.target.value),placeholder:t("searchSkillsPlaceholder")})]})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain pb-4",children:[(0,n.jsx)(n$,{cwd:null,name:t("global"),props:e}),(0,n.jsxs)("div",{className:"flex items-center gap-2 px-4 pb-1 pt-5",children:[(0,n.jsx)("span",{className:"h-px flex-1 bg-border"}),(0,n.jsx)("p",{className:"shrink-0 text-xs font-medium text-muted-foreground",children:t("workspaceCount",{count:e.projects.length})}),(0,n.jsx)("span",{className:"h-px flex-1 bg-border"})]}),e.projects.map(t=>(0,n.jsx)(n$,{cwd:t.cwd,name:t.projectName,props:e},t.cwd)),0===e.projects.length&&(0,n.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground",children:t("workspaceEmpty")})]})]})}function nP({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{t:i}=(0,b.Bd)("skills"),{clientId:a}=(0,ei.gM)(),l=(0,X.G)(),o=(0,r.useMemo)(()=>({list:(e,t)=>nl(a,ns,e,t),listFiles:(e,t)=>nl(a,nn,e,t),getFile:(e,t)=>nl(a,nr,e,t),async replaceFile(e){await nl(a,ni,e)}}),[a]),c=function(e,t){let[s,n]=(0,r.useState)({}),[i,a]=(0,r.useState)({}),l=(0,r.useRef)(new Map),o=(0,r.useRef)(!0);(0,r.useEffect)(()=>{o.current=!0;let e=l.current;return()=>{for(let t of(o.current=!1,e.values()))t.abort();e.clear()}},[]);let c=(0,r.useCallback)(async t=>{let s=nm(t),r=`scope:${s}`;l.current.get(r)?.abort();let i=new AbortController;l.current.set(r,i),n(e=>({...e,[s]:{data:e[s]?.data??null,loading:!0,error:null}}));try{let r=await e.list({cwd:t},i.signal);!i.signal.aborted&&o.current&&n(e=>({...e,[s]:{data:r,loading:!1,error:null}}))}catch(e){!i.signal.aborted&&o.current&&n(t=>({...t,[s]:{data:t[s]?.data??null,loading:!1,error:e instanceof Error?e.message:nu("skillsReadFailed")}}))}finally{l.current.get(r)===i&&l.current.delete(r)}},[e]),d=(0,r.useCallback)(async t=>{let s=np(t),n=`directory:${s}`;l.current.get(n)?.abort();let r=new AbortController;l.current.set(n,r),a(e=>({...e,[s]:{data:e[s]?.data??null,loading:!0,error:null}}));try{let n=await e.listFiles(t,r.signal);!r.signal.aborted&&o.current&&a(e=>({...e,[s]:{data:n,loading:!1,error:null}}))}catch(e){!r.signal.aborted&&o.current&&a(t=>({...t,[s]:{data:null,loading:!1,error:e instanceof Error?e.message:nu("directoryReadFailed")}}))}finally{l.current.get(n)===r&&l.current.delete(n)}},[e]),u=JSON.stringify(t.map(e=>e.cwd));return(0,r.useEffect)(()=>{let e=new Set([nm(null),...JSON.parse(u).map(nm)]);for(let[t,s]of(n(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),a(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(nm(JSON.parse(t)[0]))))),l.current)){let n=t.startsWith("scope:")?t.slice(6):nm(JSON.parse(t.slice(10))[0]);e.has(n)||(s.abort(),l.current.delete(t))}},[u]),{scopes:s,directories:i,loadScope:c,loadDirectory:d}}(o,e),{loadScope:d}=c,u=function(e,t){let{wrapLines:s}=(0,sX.TX)(),[n,i]=(0,r.useState)(null),a=(0,r.useRef)(null),l=(0,r.useRef)(!0),[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(!1),h=(0,r.useRef)(null),g=(0,r.useRef)(!1),f=(0,r.useRef)(null),[x,b]=(0,r.useState)(!1),v=(0,r.useRef)(null),w=(0,r.useCallback)(e=>{l.current&&(a.current=e,i(e))},[]);(0,r.useEffect)(()=>(l.current=!0,()=>{l.current=!1,f.current?.abort(),v.current?.resolve(!1),v.current=null}),[]);let y=(0,r.useCallback)(()=>{if(h.current)return h.current;let s=a.current;if(!s||s.file?.kind!=="text"||s.file.readOnlyReason)return Promise.resolve(!1);if(!ng(s))return Promise.resolve(!0);p(!0);let n=(async()=>{try{await e.replaceFile({...s.target,content:s.draft});let n=a.current;return n?.file?.kind==="text"&&n.target===s.target&&w({...n,file:{...n.file,content:s.draft},error:null}),l.current&&t(s.target.cwd),!0}catch(t){let e=a.current;return e?.target===s.target&&w({...e,error:t instanceof Error?t.message:nu("saveFailed")}),!1}finally{h.current=null,l.current&&p(!1)}})();return h.current=n,n},[w,e,t]),k=(0,r.useCallback)(async()=>{let e;if(h.current&&await h.current,!l.current)return!1;if(!ng(a.current))return!0;if(v.current)return v.current.promise;let t=new Promise(t=>{e=t});return v.current={promise:t,resolve:e},b(!0),t},[]),j=(0,r.useCallback)(async e=>{if(!v.current||h.current||"save"===e&&(!await y()||ng(a.current)))return;if("discard"===e){let e=a.current;e?.file?.kind==="text"&&w({...e,draft:nh(e.file.content),error:null})}let t=v.current;v.current=null,b(!1),t?.resolve("cancel"!==e)},[w,y]),N=(0,r.useCallback)(async t=>{if(g.current)return!1;g.current=!0;try{if(!await k()||!l.current)return!1;f.current?.abort();let s=new AbortController;f.current=s,u(t),c(!0);try{let n=await e.getFile(t,s.signal);if(s.signal.aborted||!l.current)return!1;return w({target:t,file:n,draft:"text"===n.kind?nh(n.content):"",error:null}),!0}catch(e){if(!s.signal.aborted){let s=a.current,n=e instanceof Error?e.message:nu("fileReadFailed");w(s?{...s,error:n}:{target:t,file:null,draft:"",error:n})}return!1}finally{l.current&&(u(null),c(!1))}}finally{g.current=!1}},[w,k,e]),I=(0,r.useCallback)(e=>{let t=a.current;t?.file?.kind!=="text"||t.file.readOnlyReason||t.draft===e||w({...t,draft:e})},[w]),S=ng(n);return(0,r.useEffect)(()=>{if(!S)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[S]),{document:n,dirty:S,loading:o,openingTarget:d,saving:m,confirmOpen:x,wrapLines:s,setWrapLines:no,change:I,open:N,save:y,beforeLeave:k,decide:j}}(o,(0,r.useCallback)(e=>{d(e)},[d])),{document:m,open:p}=u,[h,g]=(0,r.useState)(""),[f,x]=(0,r.useState)(!1),[w,y]=(0,r.useState)(!0),k=(0,r.useRef)(!1),j=(0,r.useRef)(t);(0,r.useEffect)(()=>(s(u.beforeLeave),()=>s(null)),[u.beforeLeave,s]),(0,r.useEffect)(()=>{if(k.current||m)return;let e=c.scopes[nm(j.current)];if(!e||e.loading)return;let t=c.scopes[nm(null)],s=e.data?.skills[0];if(!s&&(!t||t.loading))return;let n=s??t?.data?.skills[0];k.current=!0,n&&p({cwd:s?j.current:null,skillPath:n.skillPath,path:n.skillPath.split("/").at(-1)})},[c.scopes,m,p]);let N=(0,r.useCallback)(async e=>{let t=await p(e);return t&&x(!1),t},[p]),S=async()=>{if(u.document)try{await nc(u.document.target),l.success(i("pathCopied"))}catch{l.error(i("copyFailed"))}},E=u.document?.target??null,M=E?c.scopes[nm(E.cwd)]?.data?.skills.find(e=>e.skillPath===E.skillPath)??null:null,z=Object.values(c.scopes).some(e=>e.loading)||Object.values(c.directories).some(e=>e.loading),A={projects:e,focusedCwd:t,query:h,onQuery:g,scopes:c.scopes,directories:c.directories,selected:E,pending:u.openingTarget,onLoadScope:c.loadScope,onLoadDirectory:c.loadDirectory,onOpenFile:N};return(0,n.jsxs)("section",{"aria-label":i("skillsManagement"),className:"flex h-full min-h-0 flex-col bg-background",children:[(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 border-b px-4 py-2",children:[(0,n.jsx)(I.$,{variant:"ghost",size:"icon",className:"lg:hidden","aria-label":i("openSkillsFolder"),onClick:()=>x(!0),children:(0,n.jsx)(sY.A,{className:"size-4"})}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon",className:"hidden lg:inline-flex","aria-label":i(w?"collapseSkillsFolder":"expandSkillsFolder"),onClick:()=>y(!w),children:w?(0,n.jsx)(sG.A,{className:"size-4"}):(0,n.jsx)(sJ.A,{className:"size-4"})}),(0,n.jsx)("h2",{className:"text-xl font-semibold",children:"Skills"}),(0,n.jsx)("div",{className:"flex-1"}),(0,n.jsxs)(I.$,{variant:"ghost",size:"sm",disabled:z,"aria-label":i("refreshSkillsFolder"),onClick:()=>{for(let e of Object.keys(c.scopes))c.loadScope(JSON.parse(e));for(let e of Object.keys(c.directories)){let[t,s,n]=JSON.parse(e);c.loadDirectory({cwd:t,skillPath:s,path:n})}},children:[z?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(es.A,{className:"size-3.5"}),i("refreshFolder")]})]}),(0,n.jsxs)("div",{className:"flex min-h-0 flex-1",children:[(0,n.jsx)("aside",{"aria-label":i("skillsProjectFolder"),className:(0,C.cn)("hidden w-64 shrink-0 border-r bg-sidebar xl:w-72",w&&"lg:block"),children:(0,n.jsx)(nR,{...A})}),(0,n.jsx)("main",{className:"min-h-0 min-w-0 flex-1",children:(0,n.jsx)(nj,{document:u.document,skill:M,dirty:u.dirty,loading:u.loading,saving:u.saving,opening:!!u.openingTarget,wrapLines:u.wrapLines,onWrapLines:()=>u.setWrapLines(!u.wrapLines),onChange:u.change,onSave:()=>void u.save(),onReload:()=>{E&&N(E)},onCopy:()=>void S()})})]}),(0,n.jsx)(eN.YV,{open:f,onOpenChange:x,children:(0,n.jsxs)(eN.hA,{className:"left-0 top-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)(eN.Hl,{className:"shrink-0 border-b px-4 py-3 pr-12",children:(0,n.jsx)(eN.YM,{children:i("skillsFolderTitle")})}),(0,n.jsx)("div",{className:"min-h-0 flex-1",children:(0,n.jsx)(nR,{...A})})]})}),(0,n.jsx)(nN,{open:u.confirmOpen,saving:u.saving,path:E?.path??null,error:u.document?.error??null,onDecide:u.decide})]})}var nD=s(75851),nT=s(17247),nO=s(4090),nL=s(19562);function nF(){let{t:e}=(0,b.Bd)("common"),[t,s]=(0,r.useState)(null),i=(0,r.useRef)(null),a=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{i.current?.(!1),i.current=null},[]);let l=e=>{let t=i.current;i.current=null,s(null),t?.(e)};return{confirm:e=>(i.current?.(!1),s(e),new Promise(e=>{i.current=e})),dialog:t?(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||l(!1)},children:(0,n.jsxs)(eN.hA,{initialFocus:a,className:"z-[130] max-w-[27.5rem]",children:[(0,n.jsxs)(eN.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:t.title}),(0,n.jsx)(eN.uX,{className:"break-words",children:t.description})]}),t.content?(0,n.jsx)(eN._Y,{className:"grid grid-rows-[minmax(0,1fr)]",children:t.content}):null,(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{ref:a,variant:"outline",onClick:()=>l(!1),children:e("cancel")}),(0,n.jsx)(I.$,{variant:t.confirmVariant??"destructive",onClick:()=>l(!0),children:t.confirmLabel??e("delete")})]})]})}):null}}var nB=s(33941);async function nq(e,t,s,n,r){let i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s),signal:r});401===i.status&&window.location.replace("/login");let a=await i.json();if(!i.ok||0!==a.code||null===a.data)throw Error(0===a.code?(0,ed.B)({msg:"登录保护设置处理失败",i18n:{key:"auth:settingsFailed"}}):(0,ed.B)(a));return n.parse(a.data)}async function n_(e){await nq(e,"/api/auth/logout",{},nB.Xm),window.location.replace("/login")}async function nW(e,t){let s=nB.uZ.safeParse(t);if(!s.success)throw Error((0,ed.B)({msg:"密码不符合要求,请按输入框下方的规则调整。",i18n:{key:"auth:settingsInvalid"}}));await nq(e,"/api/auth-settings/replace",s.data,nB.Kc),window.location.replace(null===t.password?"/":"/login")}function nY(){let{t:e}=(0,b.Bd)("auth"),t=function(){let{t:e}=(0,b.Bd)("auth"),{clientId:t}=(0,ei.gM)(),{confirm:s,dialog:n}=nF(),[i,a]=(0,r.useState)(null),[l,o]=(0,r.useState)(!0),[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)(0),[x,v]=(0,r.useState)(""),w=(0,r.useRef)(!1);(0,r.useEffect)(()=>{var s;let n=new AbortController;return(s=n.signal,nq(t,"/api/auth-settings/get",{},nB.G6,s)).then(e=>{n.signal.aborted||(a(e),o(!1))}).catch(t=>{n.signal.aborted||(h(t instanceof Error?t.message:e("settingsFailed")),o(!1))}),()=>n.abort()},[t,g,e]);let y=async()=>{if(!w.current&&i){w.current=!0,d(!0),h(null);try{await nW(t,{password:x})}catch(t){w.current=!1,d(!1),h(t instanceof Error?t.message:e("settingsFailed"))}}},k=async()=>{if(!w.current&&i){if(w.current=!0,!await s({title:e("disableTitle"),description:e("disableDescription"),confirmLabel:e("disable")})){w.current=!1;return}d(!0),h(null);try{await nW(t,{password:null})}catch(t){w.current=!1,d(!1),h(t instanceof Error?t.message:e("settingsFailed"))}}},j=async()=>{if(!w.current&&i?.enabled){w.current=!0,m(!0),h(null);try{await n_(t)}catch(t){w.current=!1,m(!1),h(t instanceof Error?t.message:e("logoutFailed"))}}};return{settings:i,loading:l,saving:c,signingOut:u,error:p,password:x,setPassword:v,save:y,generatePassword:()=>{if(!w.current)try{v(function(){for(;;){let e=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@"[e%64]).join("");if(/[A-Z]/.test(e)&&/[a-z]/.test(e)&&/[0-9]/.test(e)&&/[!@]/.test(e))return e}}()),h(null)}catch{h(e("generatePasswordFailed"))}},disable:k,logout:j,dialog:n,retry:()=>{o(!0),h(null),f(e=>e+1)}}}(),s=t.settings?.enabled??!1,i=t.saving||t.signingOut,a=s?en.A:nD.A;return(0,n.jsxs)("section",{"aria-labelledby":"auth-settings-title",className:"@container min-w-0 space-y-6",children:[(0,n.jsx)("h2",{id:"auth-settings-title",className:"text-xl font-semibold",children:e("settings:loginProtection")}),t.loading?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",role:"status",children:e("common:loading")}):t.settings?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 rounded-xl bg-muted p-4",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[(0,n.jsx)(a,{className:"size-5 shrink-0","aria-hidden":"true"}),(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:e("protection")}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e(s?"enabled":"disabled")})]})]}),s?(0,n.jsxs)(I.$,{type:"button",variant:"outline",className:"border-destructive/50 text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:i,"aria-busy":t.signingOut,onClick:()=>void t.logout(),children:[t.signingOut?(0,n.jsx)(v.A,{className:"motion-safe:animate-spin","aria-hidden":"true"}):(0,n.jsx)(nT.A,{"aria-hidden":"true"}),e(t.signingOut?"signingOut":"logout")]}):null]}),(0,n.jsxs)("form",{className:"grid gap-4 @min-[36rem]:grid-cols-[10rem_minmax(0,1fr)] @min-[36rem]:gap-6","aria-busy":i,onSubmit:e=>{e.preventDefault(),t.save()},children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:e(s?"changePassword":"setPassword")}),s?null:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("publicAccess")})]}),(0,n.jsxs)("div",{className:"min-w-0 max-w-[40rem] space-y-4",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("label",{className:"block text-sm font-medium",htmlFor:"auth-password",children:e(s?"newPassword":"password")}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:i,title:e("generatePasswordHint"),onClick:t.generatePassword,children:[(0,n.jsx)(nO.A,{"aria-hidden":"true"}),e("generatePassword")]})]}),(0,n.jsx)(nL.k,{id:"auth-password",name:"password",className:"[&::-ms-reveal]:hidden",autoComplete:"new-password",minLength:12,maxLength:64,required:!0,disabled:i,value:t.password,"aria-describedby":`auth-password-hint${t.error?" auth-settings-error":""}`,onChange:e=>t.setPassword(e.target.value)}),(0,n.jsx)("p",{id:"auth-password-hint",className:"text-sm text-muted-foreground",children:e("passwordHint")})]}),t.error?(0,n.jsx)("p",{id:"auth-settings-error",className:"text-sm text-destructive",role:"alert",children:t.error}):null,(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("saveEffect")}),(0,n.jsxs)(I.$,{type:"submit",disabled:i,children:[t.saving?(0,n.jsx)(v.A,{className:"motion-safe:animate-spin","aria-hidden":"true"}):null,e(t.saving?"saving":s?"saveAndSignIn":"enable")]})]})]}),s?(0,n.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4 border-t pt-4",children:[(0,n.jsxs)("details",{className:"group min-w-0 flex-1 text-sm",children:[(0,n.jsxs)("summary",{className:"flex min-h-8 w-fit cursor-pointer items-center gap-1 rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring",children:[(0,n.jsx)(e7.A,{className:"size-4 shrink-0 transition-transform group-open:rotate-90","aria-hidden":"true"}),e("recovery")]}),(0,n.jsxs)("div",{className:"mt-2 space-y-2",children:[(0,n.jsx)("p",{className:"text-muted-foreground",children:e("recoveryDescription")}),(0,n.jsx)("code",{className:"block break-all text-xs",children:t.settings.configPath})]})]}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"text-muted-foreground",disabled:i,onClick:()=>void t.disable(),children:e("disable")})]}):null]}):(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:t.error}),(0,n.jsx)(I.$,{variant:"outline",onClick:t.retry,children:e("common:retry")})]}),t.dialog]})}var nV=s(60471),nU=s(62851);let nH=Object.freeze({apply:(0,l.Vc)({path:"app-runtime/apply",inputSchema:nU.$C,outputSchema:nU.Pq}),update:(0,l._G)({path:"app-runtime/update",bodySchema:nU.YT})});var nK=s(48708);async function nG(e,t,s,n){let r=(0,nK.fx)();if(!r)return"cancelled";let i=e!==r.locale;if(i&&!window.confirm(t))return"cancelled";if(i&&n&&!await n())return"blocked";try{await s.request(nH.apply,{key:"settings",update:{region:{locale:e}}})}catch{return"save-failed"}return i&&window.location.reload(),"changed"}async function nJ(e,t){try{return await t.request(nH.apply,{key:"settings",update:{region:{timeZone:e}}}),!0}catch{return!1}}function nQ({canLeave:e}){let{t}=(0,b.Bd)("settings"),s=(0,eQ.i)(),{appSocket:i}=(0,ei.gM)(),[a,l]=(0,r.useState)(null),[o,c]=(0,r.useState)(()=>new Date);(0,r.useEffect)(()=>{let e=window.setInterval(()=>c(new Date),6e4);return()=>window.clearInterval(e)},[]);let d=(0,r.useMemo)(()=>[...["UTC",...Intl.supportedValuesOf("timeZone").filter(e=>"UTC"!==e)].map(e=>({value:e,label:e.replaceAll("_"," ")}))],[]),u=async s=>{l(null);let n=await nG(s,t("common:reloadConfirm"),i,e);"save-failed"===n&&l(t("common:localeError")),"blocked"===n&&l(t("common:reloadBlocked"))},m=async e=>{l(await nJ(e,i)?null:t("common:timeZoneError"))};return(0,n.jsxs)("section",{className:"@container min-w-0 space-y-6","aria-labelledby":"region-settings-title",children:[(0,n.jsx)("h2",{id:"region-settings-title",className:"text-xl font-semibold",children:t("region")}),(0,n.jsxs)("div",{className:"grid max-w-[40rem] gap-6 @min-[32rem]:grid-cols-2",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("label",{className:"block text-sm font-medium",htmlFor:"region-language",children:t("language")}),(0,n.jsxs)(ea.l6,{value:s.localePreference,onValueChange:e=>{("zh-CN"===e||"en"===e)&&u(e)},children:[(0,n.jsx)(ea.bq,{id:"region-language",className:"w-full",children:(0,n.jsx)(ea.yv,{children:"zh-CN"===s.localePreference?t("common:chinese"):"English"})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(ea.eb,{value:"zh-CN",children:t("common:chinese")}),(0,n.jsx)(ea.eb,{value:"en",children:"English"})]})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("currentLanguage",{locale:s.locale})}),s.pendingLocale&&(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("common:languagePending")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void u(s.localePreference),children:t("reloadLanguage")})]})]}),(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("span",{className:"block text-sm font-medium",children:t("timeZone")}),(0,n.jsx)(nV.b,{value:s.timeZonePreference,options:d,onChange:e=>void m(e),ariaLabel:t("timeZone"),searchPlaceholder:t("searchTimeZones"),emptyText:t("common:unavailable"),className:"w-full"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("currentTimeZone",{timeZone:s.timeZone})})]})]}),(0,n.jsxs)("div",{className:"space-y-1 rounded-xl bg-muted p-4",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("timeExample")}),(0,n.jsx)("p",{className:"text-sm font-medium tabular-nums",children:new Intl.DateTimeFormat("en"===s.locale?"en-US":"zh-CN",{timeZone:s.timeZone,year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(o)})]}),a&&(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:a})]})}var nX=s(90772),nZ=s(90164),n0=s(52871),n1=s(96646);function n2({label:e,value:t,options:s,onChange:r,layout:i="list",disabled:a=!1}){let l=s.some(e=>e.value===t);return(0,n.jsx)("div",{role:"radiogroup","aria-label":e,onKeyDown:e=>{if(a||e.nativeEvent.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=["ArrowRight","ArrowDown"].includes(e.key)?1:["ArrowLeft","ArrowUp"].includes(e.key)?-1:0;if(!n&&"Home"!==e.key&&"End"!==e.key)return;e.preventDefault();let i=Math.max(0,s.findIndex(e=>e.value===t)),l="Home"===e.key?0:"End"===e.key?s.length-1:(i+n+s.length)%s.length,o=s[l];o&&(r(o.value),e.currentTarget.querySelectorAll('[role="radio"]')[l]?.focus())},className:(0,C.cn)("segmented"===i?"inline-flex max-w-full flex-wrap gap-0.5 rounded-lg bg-muted p-0.5":"grid gap-2"),children:s.map((e,s)=>{let o=e.value===t,c=e.icon;return(0,n.jsxs)("button",{type:"button",role:"radio","aria-checked":o,tabIndex:o||!l&&0===s?0:-1,disabled:a,"data-testid":e.testId,onClick:()=>r(e.value),className:(0,C.cn)("flex min-w-0 cursor-pointer items-center gap-2 text-left text-sm leading-5 outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset","segmented"===i?"min-h-7 rounded-md px-2 py-0.5":"min-h-9 rounded-lg border border-transparent px-3 py-2",o?"segmented"===i?"bg-card text-card-foreground shadow-sm":"border-border bg-accent text-accent-foreground":"text-muted-foreground hover:bg-foreground/8 hover:text-foreground"),children:[c?(0,n.jsx)(c,{className:"size-4 shrink-0"}):null,(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block font-medium",children:e.label}),e.description?(0,n.jsx)("span",{className:"mt-1 block text-sm font-normal text-muted-foreground",children:e.description}):null]}),"list"===i?(0,n.jsx)(ep.A,{"aria-hidden":"true",className:(0,C.cn)("size-4 shrink-0",!o&&"invisible")}):null]},e.value)})})}var n5=s(74052),n3=s(38903),n4=s(90740),n6=s(67796),n8=s(8001),n7=s(46376),n9=s.n(n7);let re={code:{copy:!0,download:!1}};function rt({href:e,children:t,...s}){return delete s.node,(0,n.jsx)("a",{...s,href:e,target:"_blank",rel:"noopener noreferrer",children:t})}function rs({src:e,alt:t,className:s,onError:i,...a}){let{t:l}=(0,b.Bd)("conversation"),[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(!1),m=t||l("image"),p=(0,r.useMemo)(()=>"string"==typeof e&&e?[{src:e,alt:m}]:[],[m,e]);if(delete a.node,0===p.length)return null;if(d)return(0,n.jsx)("span",{className:n9().imageFallback,children:l("imageUnavailable")});let h=p[0].src;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",className:n9().imageTrigger,"aria-label":l("previewImage",{name:m}),onClick:()=>c(!0),children:[(0,n.jsx)("img",{...a,src:h,alt:m,"data-streamdown":"image",className:(0,C.cn)(n9().image,s),onError:e=>{u(!0),i?.(e)}}),(0,n.jsx)("span",{className:n9().imageAction,"aria-hidden":"true",children:(0,n.jsx)(q.A,{className:"size-4"})})]}),o?(0,n.jsx)(ny.k,{mode:"modal",open:!0,slides:p,ariaLabel:l("imagePreview"),onClose:()=>c(!1)}):null]})}function rn({className:e,isAnimating:t,components:s,...r}){let i=(0,X.G)(),{t:a}=(0,b.Bd)("conversation"),{locale:l}=(0,eQ.i)();return(0,n.jsx)("div",{className:"contents",onClickCapture:e=>{if("u">typeof navigator&&"function"==typeof navigator.clipboard?.writeText)return;let t=function(e){if(!(e instanceof Element))return null;let t=e.closest('[data-streamdown="code-block-copy-button"]');return t?t.closest('[data-streamdown="code-block"]')?.querySelector('[data-streamdown="code-block-body"]')?.textContent??null:null}(e.target);null!==t&&(e.preventDefault(),e.stopPropagation(),(0,e9.x)(t).then(e=>{e||i.error(a("codeCopyFailed"))}))},children:(0,n.jsx)(t2,{className:(0,C.cn)("space-y-0",n9().markdown,n8.om,e),controls:re,isAnimating:t,lineNumbers:!1,allowedTags:n8.IV,remarkPlugins:n8.XC,components:{...n8.e6,...s,a:rt,img:rs},...r,translations:"zh-CN"===l?n6.X:void 0})})}let rr=[{value:"system",label:"common:system",icon:nX.A},{value:"light",label:"themeLight",icon:nZ.A},{value:"dark",label:"themeDark",icon:n0.A}],ri=[{value:"compact",label:"sizeCompact"},{value:"standard",label:"sizeStandard"},{value:"large",label:"sizeLarge"}];function ra(){let{t:e}=(0,b.Bd)("settings"),t=(0,r.useSyncExternalStore)(n5.Cy,n5.Is,()=>n1.Pl),s=(0,r.useSyncExternalStore)(n4.wm,n4.Ev,()=>n3.Y8);return(0,n.jsxs)("section",{"aria-labelledby":"settings-appearance-title",className:"@container grid gap-6",children:[(0,n.jsx)("h2",{id:"settings-appearance-title",className:"text-xl font-semibold",children:e("appearance")}),(0,n.jsxs)("div",{className:"grid min-w-0 gap-6 @min-[40rem]:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-4",children:[(0,n.jsxs)("div",{className:"space-y-2 border-b pb-4",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("theme")}),(0,n.jsx)(n2,{label:e("theme"),layout:"segmented",value:t,options:rr.map(t=>({...t,label:e(t.label)})),onChange:n5.VS})]}),(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("displaySize")}),(0,n.jsx)(n2,{label:e("displaySize"),layout:"segmented",value:s,options:ri.map(t=>({...t,label:e(t.label)})),onChange:n4.$y})]})]}),(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("displayPreview")}),(0,n.jsx)("div",{"aria-label":e("displayPreview"),className:"min-w-0 rounded-xl bg-muted p-4",children:(0,n.jsx)(rn,{mode:"static",isAnimating:!1,children:e("displayPreviewContent")})})]})]})]})}var rl=s(50163),ro=s(93780),rc=s(88707),rd=s(31848),ru=s(71057),rm=s(20476);let rp="pi-super:new-work-session-behavior",rh="activate",rg=new Set,rf=rh,rx=!1;function rb(){if(!rx){rx=!0;try{var e;e=window.localStorage.getItem(rp),rf="none"===e||"activate"===e||"pin"===e?e:rh}catch{rf=rh}}}function rv(){return rb(),rf}function rw(e){if(rb(),rf!==e){rf=e;try{window.localStorage.setItem(rp,e)}catch{}for(let e of[...rg])e()}}function ry(e){return rg.add(e),()=>rg.delete(e)}let rk=[{value:"none",label:"behaviorNone",description:"behaviorNoneDescription",icon:rl.A,testId:"new-work-session-behavior-none"},{value:"activate",label:"behaviorActivate",description:"behaviorActivateDescription",icon:ro.A,testId:"new-work-session-behavior-activate"},{value:"pin",label:"behaviorPin",description:"behaviorPinDescription",icon:rc.A,testId:"new-work-session-behavior-pin"}],rj=[{value:"compressed",label:"imageCompressed",description:"imageCompressedDescription",icon:rd.A,testId:"image-preview-mode-compressed"},{value:"original",label:"imageOriginal",description:"imageOriginalDescription",icon:ru.A,testId:"image-preview-mode-original"}];function rN(){let{t:e}=(0,b.Bd)("settings"),t=(0,r.useSyncExternalStore)(ry,rv,rv),s=(0,r.useSyncExternalStore)(rm.ku,rm.Wq,rm.Wq);return(0,n.jsxs)("section",{"aria-labelledby":"settings-habits-title",className:"@container grid min-w-0 gap-6",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"settings-habits-title",className:"text-xl font-semibold",children:e("habits")}),(0,n.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:e("browserOnly")})]}),(0,n.jsxs)("div",{className:"grid min-w-0 gap-6 lg:@min-[40rem]:grid-cols-2",children:[(0,n.jsxs)("section",{className:"hidden min-w-0 lg:block","aria-labelledby":"new-session-behavior-title",children:[(0,n.jsx)("h3",{id:"new-session-behavior-title",className:"mb-3 text-sm font-semibold",children:e("newSessionBehavior")}),(0,n.jsx)(n2,{label:e("newSessionBehavior"),value:t,options:rk.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:rw}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:e("desktopOnlyBehavior")})]}),(0,n.jsxs)("section",{className:"min-w-0 lg:border-t lg:pt-4 lg:@min-[40rem]:border-t-0 lg:@min-[40rem]:border-l lg:@min-[40rem]:pt-0 lg:@min-[40rem]:pl-6","aria-labelledby":"image-preview-mode-title",children:[(0,n.jsx)("h3",{id:"image-preview-mode-title",className:"mb-3 text-sm font-semibold",children:e("imagePreviewMode")}),(0,n.jsx)(n2,{label:e("imagePreviewMode"),value:s,options:rj.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:rm.lU}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:e("imagePreviewApply")})]})]})]})}var rI=s(17339);let rS={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function rC({projectDefaults:e}){let{t}=(0,b.Bd)("settings");return(0,n.jsx)("ul",{className:"space-y-3 px-4 pb-4",children:e.map(({cwd:e,from:s,to:r})=>(0,n.jsxs)("li",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"break-all font-medium",children:e}),(0,n.jsxs)("p",{className:"break-all text-muted-foreground",children:[s.provider,"/",s.modelId," \xb7 ",t(rS[s.thinkingLevel]),(0,n.jsx)("span",{className:"mx-1.5",children:"→"}),(0,n.jsx)("span",{className:"text-foreground",children:r?(0,n.jsxs)(n.Fragment,{children:[r.provider,"/",r.modelId," \xb7 ",t(rS[r.thinkingLevel])]}):t("clearProjectDefault")})]})]},e))})}var rE=s(26357),rM=s(70698);let rz=a.Yj().trim().min(1).max(128),rA=a.Yj().trim().min(1).max(256),r$=a.Yj().trim().min(1).max(256),rR=a.Yj().trim().min(1).nullable(),rP=a.g1(a.Yj().trim().min(1),a.Yj()),rD=a.Yj().trim().min(1).max(128),rT=a.g1(a.Yj(),a.Pq()),rO=a.Ik({level:rE.$,providerValue:a.Yj().trim().min(1).nullable()}).strict(),rL=a.Ik({input:a.ai().nonnegative().finite(),output:a.ai().nonnegative().finite(),cacheRead:a.ai().nonnegative().finite(),cacheWrite:a.ai().nonnegative().finite()}).strict(),rF=a.Ik({supportsDeveloperRole:a.zM().nullable(),thinkingFormat:a.Yj().trim().min(1).max(128).nullable(),requiresReasoningContentOnAssistantMessages:a.zM().nullable()}).strict(),rB=a.Ik({modelId:rA,name:r$,api:rD.nullable(),baseUrl:rR,reasoning:a.zM(),thinkingLevels:a.YO(rO).min(1).max(7),input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),cost:rL.nullable(),headers:rP,compat:rF.nullable()}).strict().superRefine((e,t)=>{let s=new Set;for(let n of e.thinkingLevels)s.has(n.level)&&t.addIssue({code:"custom",message:`思考等级 ${n.level} 重复`}),s.add(n.level),("xhigh"===n.level||"max"===n.level)&&null===n.providerValue&&t.addIssue({code:"custom",message:`${n.level} 必须配置 Provider 映射`});e.reasoning||1===e.thinkingLevels.length&&s.has("off")||t.addIssue({code:"custom",message:"非推理模型只允许 off 思考等级"})}),rq=a.Ik({provider:rz,name:rR,baseUrl:rR,api:rD.nullable(),apiKey:a.Yj().nullable(),authHeader:a.zM().nullable(),headers:rP,models:a.YO(rB)}).strict().superRefine((e,t)=>{let s=new Set;for(let n of e.models)s.has(n.modelId)&&t.addIssue({code:"custom",message:`模型 ${n.modelId} 重复`}),s.add(n.modelId)}),r_=a.Ik({provider:rz,modelId:rA,thinkingLevel:rE.$,color:a.Yj().regex(/^#[0-9a-fA-F]{6}$/).nullable()}).strict(),rW=a.Ik({provider:rz,modelId:rA,name:r$,input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),thinkingLevels:a.YO(rE.$).min(1).max(7)}).strict(),rY=a.Ik({provider:rz,modelId:rA,thinkingLevel:rE.$}).strict(),rV=a.Ik({contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),cost:rL.partial().optional()}).strict(),rU=a.Ik({provider:rz,modelId:rA,overrides:rV}).strict(),rH=a.Ik({provider:rz,name:r$,loggedIn:a.zM(),subscription:a.zM(),models:a.YO(rB)}).strict();a.Ik({}).strict();let rK=a.Ik({providers:a.YO(rq),presets:a.YO(r_),models:a.YO(rW),nativeConfig:rT,accountModels:a.YO(rU),accounts:a.YO(rH)}).strict(),rG=a.Ik({provider:rz,modelId:rA}).strict(),rJ=a.Ik({from:rG,to:rG}).strict(),rQ=a.Ik({providers:a.YO(rq).optional(),presets:a.YO(r_).optional(),accountModels:a.YO(rU).optional(),modelReplacements:a.YO(rJ).optional()}).strict().refine(e=>void 0!==e.providers||void 0!==e.presets||void 0!==e.accountModels,{message:"请提交需要保存的模型配置"}),rX=a.KC([rQ,a.Ik({nativeConfig:rT}).strict()]),rZ=a.Ik({}).strict(),r0=a.Ik({projectDefaults:a.YO(a.Ik({cwd:sZ.m4,from:rY,to:rY.nullable()}).strict())}).strict(),r1=a.Ik({query:a.Yj().trim().max(256),refresh:a.zM(),page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive().max(100)}).strict()}).strict(),r2=a.Ik({reasoning:a.zM(),thinkingLevels:a.YO(rO).min(1).max(7),input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),cost:rL.nullable()}).strict(),r5=a.Ik({provider:rz,providerName:r$,modelId:rA,official:a.zM(),defaults:r2}).strict(),r3=a.Ik({referenceId:a.Yj().trim().min(1).max(512),name:r$,match:a.k5(["exact","similar"]).nullable(),sources:a.YO(r5).min(1)}).strict(),r4=a.Ik({updatedAt:rM.k,refreshResult:a.k5(["not-requested","updated","unchanged","partial","cached"]),page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive(),total:a.ai().int().nonnegative()}).strict(),models:a.YO(r3)}).strict();a.Ik({cwd:sZ.m4}).strict();let r6=a.Ik({cwd:sZ.m4,default:rY.nullable(),models:a.YO(rW)}).strict(),r8=a.Ik({cwd:sZ.m4,default:rY.nullable()}).strict(),r7=a.Ik({}).strict();var r9=s(29029);let ie="pi-desk:pi-directories",it="pi-desk:ignored-pi-directories",is="pi-desk:pi-directory-entries",ir=!1,ii=null,ia=null,il=!1,io=new Map;function ic(e){if(null===e)return"<root>";let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function id(e){try{return JSON.parse(window.localStorage.getItem(e)??"null")}catch{return null}}function iu(){ir||(ir=!0,ii=id(ie),ia=id(it))}function im(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function ip(e){iu(),ii=e,im(ie,e)}function ih(){if(il)return;il=!0;let e=id(is);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.entries;if(!(!t||"object"!=typeof t||Array.isArray(t)))for(let[e,s]of Object.entries(t))io.set(e,s)}function ig(e){return ih(),io.get(ic(e))??null}let ix="pi-desk:project-model-defaults",ib=!1,iv=new Map;function iw(e){let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function iy(){if(!ib){ib=!0;try{let e=JSON.parse(window.localStorage.getItem(ix)??"null");if(!e||"object"!=typeof e||Array.isArray(e))return;for(let[t,s]of Object.entries(e)){let e=r6.safeParse(s);e.success&&iv.set(t,e.data)}let t=!1;for(;iv.size>64;){let e=iv.keys().next().value;if(void 0===e)break;iv.delete(e),t=!0}t&&ik()}catch{iv.clear()}}}function ik(){try{window.localStorage.setItem(ix,JSON.stringify(Object.fromEntries(iv)))}catch{}}function ij(e){let t=r6.safeParse(e);if(!t.success)return;iy();let s=iw(t.data.cwd);for(iv.delete(s),iv.set(s,t.data);iv.size>64;){let e=iv.keys().next().value;if(void 0===e)break;iv.delete(e)}ik()}function iN(e){let t=rX.safeParse(e);if(!t.success){let e=t.error.issues[0]?.path.at(-1);if("modelId"===e)throw Error("请填写模型 ID 后再保存配置。");if("provider"===e)throw Error("请填写 Provider ID 后再保存配置。");throw Error("模型配置不完整或格式不正确,请检查必填字段和数值。")}return t.data}let iI=a.KC([a.k5(["appearance","region","habits","auth","models","mcp-settings","capability-modes","skills","plugins","about"]),a.Uy(["plugin:",a.Yj(),":",a.Yj()])]),iS=a.k5(["providers","presets","project-default"]),iC="pi-super:settings:section",iE="pi-super:settings:model-tab";function iM(e,t,s){try{let n=t.safeParse(window.localStorage.getItem(e));return n.success?n.data:s}catch{return s}}function iz(e,t){try{window.localStorage.setItem(e,t)}catch(e){console.warn("[Pi Desk][Settings] 保存设置导航位置失败,仅当前窗口生效",e)}}function iA({open:e,text:t,error:s,saving:r,dirty:i,onChange:a,onClose:l,onSave:o}){let{t:c}=(0,b.Bd)("settings");return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||l()},children:(0,n.jsxs)(eN.hA,{className:"max-w-[52rem]",initialFocus:!1,showCloseButton:!r,children:[(0,n.jsxs)(eN.Hl,{className:"border-b px-4 py-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:c("nativeConfig")}),(0,n.jsx)(eN.uX,{children:c("nativeConfigScope")})]}),(0,n.jsx)(eN._Y,{className:"max-h-[70dvh]",children:(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(t7.T,{"aria-label":c("nativeConfigEditor"),value:t,disabled:r,spellCheck:!1,autoCapitalize:"none",autoCorrect:"off",className:"min-h-[min(28rem,50dvh)] resize-y font-mono text-sm",onChange:e=>a(e.target.value)}),s?(0,n.jsx)("p",{role:"alert",className:"break-words text-sm text-destructive",children:s}):null]})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",disabled:r,onClick:l,children:c("cancel",{ns:"common"})}),(0,n.jsxs)(I.$,{type:"button",disabled:r||!i,onClick:o,children:[r?(0,n.jsx)(v.A,{className:"animate-spin"}):null,c(r?"savingModels":"saveNativeConfig")]})]})]})})}var i$=s(43209),iR=s(54346),iP=s(55289),iD=s(24121),iT=s(78844);let iO=[{value:"#3b82f6",label:"presetColorBlue"},{value:"#0891b2",label:"presetColorCyan"},{value:"#16a34a",label:"presetColorGreen"},{value:"#b7791f",label:"presetColorAmber"},{value:"#ea580c",label:"presetColorOrange"},{value:"#dc2626",label:"presetColorRed"},{value:"#db2777",label:"presetColorPink"},{value:"#8b5cf6",label:"presetColorPurple"}];function iL(e){return iO.map(({value:t})=>({value:t,count:e.filter(e=>e.color?.toLowerCase()===t).length})).reduce((e,t)=>t.count<e.count?t:e).value}let iF=["OpenAI Chat Completions","OpenAI Responses","Anthropic Messages","Google Generative AI","Mistral Conversations","Azure OpenAI Responses","OpenAI Codex Responses","Amazon Bedrock","Google Vertex AI","Pi Messages"],iB=["openai-completions","openai-responses","anthropic-messages","google-generative-ai","mistral-conversations","azure-openai-responses","openai-codex-responses","bedrock-converse-stream","google-vertex","pi-messages"].map((e,t)=>({value:e,label:iF[t]})),iq=["openai","openrouter","together","deepseek","zai","qwen","chat-template","qwen-chat-template","string-thinking","ant-ling","baseten"];function i_(e){return Object.entries(e).map(([e,t])=>`${e}: ${t}`).join("\n")}function iW({headers:e,onChange:t,placeholder:s}){let[i,a]=(0,r.useState)(null);return(0,n.jsx)(t7.T,{value:i??i_(e),onFocus:()=>a(i_(e)),onChange:e=>{let s=e.target.value;a(s),t(Object.fromEntries(s.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(":");return t>0?[e.slice(0,t).trim(),e.slice(t+1).trim()]:[e,""]})))},onBlur:()=>a(null),rows:4,placeholder:s,className:"font-mono"})}function iY(e){let t=Math.floor(e/1e3),s=e%1e3;return s?`${t}.${String(s).padStart(3,"0").replace(/0+$/,"")}`:String(t)}function iV(e){if(!/^\d+(?:\.\d{0,3})?$/.test(e))return null;let[t,s=""]=e.split("."),n=1e3*Number(t)+Number(s.padEnd(3,"0"));return Number.isSafeInteger(n)&&n>0?n:null}function iU({label:e,children:t,className:s}){return(0,n.jsxs)("label",{className:(0,C.cn)("grid gap-1 text-sm text-foreground",s),children:[(0,n.jsx)("span",{className:"font-medium",children:e}),t]})}let iH="__pi-desk_empty__";function iK({value:e,options:t,onChange:s,ariaLabel:r,placeholder:i,allowEmpty:a=!0,className:l}){let{t:o}=(0,b.Bd)("settings"),c=i??o("useDefault"),d=e||(a?iH:t[0]?.value??null),u=!!e&&!t.some(t=>t.value===e);return(0,n.jsxs)(ea.l6,{value:d,onValueChange:e=>s(e===iH||null===e?"":e),children:[(0,n.jsx)(ea.bq,{"aria-label":r,className:(0,C.cn)("w-full",l),children:(0,n.jsx)(ea.yv,{children:t.find(t=>t.value===e)?.label??(e||c)})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[a?(0,n.jsx)(ea.eb,{value:iH,children:c}):null,u?(0,n.jsx)(ea.eb,{value:e,children:e}):null,t.map(e=>(0,n.jsx)(ea.eb,{value:e.value,children:e.label},e.value))]})]})}function iG({value:e,onChange:t,ariaLabel:s}){let{t:r}=(0,b.Bd)("settings");return(0,n.jsx)(iK,{value:null===e?"":String(e),ariaLabel:s,options:[{value:"true",label:r("yes")},{value:"false",label:r("no")}],onChange:e=>t(""===e?null:"true"===e)})}let iJ={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function iQ(e,t){return JSON.stringify([e,t])}function iX(e,t){return JSON.stringify([e.provider,e.modelId,e.thinkingLevel,t])}function iZ(e){return e.map(e=>({value:iQ(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider}))}function i0(e,t){return(e?.thinkingLevels??[]).map(e=>({value:e,label:t(iJ[e])}))}function i1({id:e,preset:t,model:s,models:r,canMoveUp:i,canMoveDown:a,onChange:l,onDelete:o,onMoveUp:c,onMoveDown:d}){let{t:u}=(0,b.Bd)("settings"),{attributes:m,listeners:p,setActivatorNodeRef:h,setNodeRef:g,transform:f,transition:x,isDragging:v}=(0,iR.gl)({id:e}),w=f?`translate3d(${f.x}px, ${f.y}px, 0) scaleX(${f.scaleX??1}) scaleY(${f.scaleY??1})`:void 0,y=t.color?.toLowerCase()??"none",k=iO.find(e=>e.value===y),j=k?u(k.label):u(t.color?"presetColorCustom":"presetColorNone"),N=[{value:"none",color:null,label:u("presetColorNone")},...t.color&&!k?[{value:y,color:t.color,label:u("presetColorCustom")}]:[],...iO.map(e=>({value:e.value,color:e.value,label:u(e.label)}))];return(0,n.jsxs)("div",{ref:g,style:{transform:w,transition:x},className:(0,C.cn)("grid min-w-0 items-center gap-3 border-b bg-card py-3 @[48rem]/presets:grid-cols-[auto_minmax(0,1fr)_7.5rem_4rem_auto]",v&&"z-10 opacity-70 shadow-lg"),children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(I.$,{variant:"ghost",size:"icon-sm",ref:h,type:"button",title:u("presetDrag"),"aria-label":u("presetDrag"),className:"touch-none cursor-grab text-muted-foreground active:cursor-grabbing",...m,...p,children:(0,n.jsx)(iP.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(I.$,{variant:"ghost",size:"icon-sm",type:"button",title:u("presetMoveUp"),"aria-label":u("presetMoveUp"),disabled:!i,onClick:c,children:(0,n.jsx)(iD.A,{className:"size-4"})}),(0,n.jsx)(I.$,{variant:"ghost",size:"icon-sm",type:"button",title:u("presetMoveDown"),"aria-label":u("presetMoveDown"),disabled:!a,onClick:d,children:(0,n.jsx)(eY.A,{className:"size-4"})})]})]}),(0,n.jsx)(iU,{label:u("modelsHeading"),children:(0,n.jsx)(nV.b,{value:iQ(t.provider,t.modelId),options:iZ(r),ariaLabel:u("presetModel"),searchPlaceholder:u("modelSearch"),onChange:e=>{let s=r.find(t=>iQ(t.provider,t.modelId)===e);s&&l({...t,provider:s.provider,modelId:s.modelId,thinkingLevel:s.thinkingLevels.includes(t.thinkingLevel)?t.thinkingLevel:s.thinkingLevels[0]})}})}),(0,n.jsx)(iU,{label:u("thinkingLevel"),children:(0,n.jsx)(iK,{value:t.thinkingLevel,options:i0(s,u),ariaLabel:u("presetThinking"),allowEmpty:!1,onChange:e=>l({...t,thinkingLevel:e})})}),(0,n.jsx)(iU,{label:u("presetColor"),children:(0,n.jsxs)(ea.l6,{value:y,onValueChange:e=>{null!==e&&l({...t,color:"none"===e?null:e})},children:[(0,n.jsx)(ea.bq,{"aria-label":u("presetColorLabel"),className:"w-16",children:(0,n.jsxs)(ea.yv,{children:[t.color?(0,n.jsx)("span",{"aria-hidden":"true",className:"size-4 shrink-0 rounded-full",style:{backgroundColor:t.color}}):(0,n.jsx)(iT.A,{"aria-hidden":"true",className:"size-4 text-muted-foreground"}),(0,n.jsx)("span",{className:"sr-only",children:j})]})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[120]",className:"w-40 min-w-40",align:"end",alignItemWithTrigger:!1,children:(0,n.jsx)(ea.s3,{className:"grid grid-cols-4 gap-1 p-2",children:N.map(e=>(0,n.jsx)(ea.eb,{value:e.value,label:e.label,"aria-label":e.label,className:"size-8 justify-center p-0 data-selected:bg-accent data-selected:ring-1 data-selected:ring-ring data-selected:ring-inset [&>span:first-child]:justify-center [&>span:last-child]:hidden",children:e.color?(0,n.jsx)("span",{"aria-hidden":"true",className:"size-4 shrink-0 self-center rounded-full",style:{backgroundColor:e.color}}):(0,n.jsx)(iT.A,{"aria-hidden":"true",className:"size-4 text-muted-foreground"})},e.value))})})]})}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm",title:u("presetDelete"),"aria-label":u("presetDelete"),onClick:o,children:(0,n.jsx)(et.A,{})})]})}function i2({presets:e,models:t,onChange:s}){let{t:i}=(0,b.Bd)("settings"),[a,l]=(0,r.useState)(()=>t[0]?iQ(t[0].provider,t[0].modelId):""),o=t.find(e=>iQ(e.provider,e.modelId)===a),[c,d]=(0,r.useState)(o?.thinkingLevels[0]??"off"),u=(0,i$.FR)((0,i$.MS)(i$.AN,{activationConstraint:{distance:6}}),(0,i$.MS)(i$.uN,{coordinateGetter:iR.JR})),m=(0,r.useMemo)(()=>e.map(iX),[e]);return(0,n.jsxs)("div",{className:"@container/presets space-y-4 p-4 sm:p-6",children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:i("presetDescription")}),(0,n.jsxs)("div",{className:"grid gap-3 border-b pb-4 @[32rem]/presets:grid-cols-[minmax(0,1fr)_7.5rem_auto]",children:[(0,n.jsx)(iU,{label:i("modelsHeading"),children:(0,n.jsx)(nV.b,{value:a,options:iZ(t),ariaLabel:i("presetModelNew"),searchPlaceholder:i("modelSearch"),disabled:0===t.length,onChange:e=>{l(e);let s=t.find(t=>iQ(t.provider,t.modelId)===e);s&&d(s.thinkingLevels[0])}})}),(0,n.jsx)(iU,{label:i("thinkingLevel"),children:(0,n.jsx)(iK,{value:c,options:i0(o,i),ariaLabel:i("presetThinkingNew"),allowEmpty:!1,onChange:e=>d(e)})}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",className:"self-end justify-self-start",onClick:function(){let n=t.find(e=>iQ(e.provider,e.modelId)===a);if(!n)return;let r=n.thinkingLevels.includes(c)?c:n.thinkingLevels[0];e.some(e=>e.provider===n.provider&&e.modelId===n.modelId&&e.thinkingLevel===r)||s([...e,{provider:n.provider,modelId:n.modelId,thinkingLevel:r,color:iL(e)}])},disabled:!o,children:[(0,n.jsx)(U.A,{})," ",i("presetAdd")]})]}),0===e.length?(0,n.jsx)("p",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:i("presetEmpty")}):(0,n.jsx)(i$.Mp,{sensors:u,collisionDetection:i$.fp,onDragEnd:function(t){if(!t.over||t.active.id===t.over.id)return;let n=m.indexOf(String(t.active.id)),r=m.indexOf(String(t.over.id));n>=0&&r>=0&&s((0,iR.be)(e,n,r))},children:(0,n.jsx)(iR.gB,{items:m,strategy:iR._G,children:(0,n.jsx)("div",{className:"space-y-2",children:e.map((r,i)=>{let a=t.find(e=>e.provider===r.provider&&e.modelId===r.modelId);return(0,n.jsx)(i1,{id:m[i],preset:r,model:a,models:t,canMoveUp:i>0,canMoveDown:i<e.length-1,onChange:t=>s(e.map((e,s)=>s===i?t:e)),onDelete:()=>s(e.filter((e,t)=>t!==i)),onMoveUp:()=>s((0,iR.be)(e,i,i-1)),onMoveDown:()=>s((0,iR.be)(e,i,i+1))},m[i])})})})})]})}var i5=s(72910),i3=s(61108),i4=s(46783),i6=s(89790);function i8(e){return 100*!!e.official+10*!!e.defaults.cost}let i7=[["off","thinkingOff"],["minimal","thinkingMinimal"],["low","thinkingLow"],["medium","thinkingMedium"],["high","thinkingHigh"],["xhigh","thinkingXhigh"],["max","thinkingMax"]],i9=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function ae(e){return{input:String(e.cost?.input??""),output:String(e.cost?.output??""),cacheRead:String(e.cost?.cacheRead??""),cacheWrite:String(e.cost?.cacheWrite??"")}}function at(e,t){return Object.values(e).some(e=>null===iV(e))||Object.values(t).some(e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e)))}function as({biz:e,provider:t,model:s,onChange:i,onInputState:a}){let{t:l}=(0,b.Bd)("settings"),o=(0,r.useId)(),[c,d]=(0,r.useState)({contextWindow:iY(s.contextWindow),maxTokens:iY(s.maxTokens)}),[u,m]=(0,r.useState)(()=>ae(s)),{searchText:p,setSearchText:h,catalogOpen:g,setCatalogOpen:f,loadingCatalog:x,candidates:w,visibleCandidates:y,showAllCandidates:k,setShowAllCandidates:j,selectedCandidateKey:N,setSelectedCandidateKey:S}=function(e,t){let{t:s}=(0,b.Bd)("settings"),n=(0,X.G)(),i=(0,r.useRef)(0),[a,l]=(0,r.useState)(t),[o,c]=(0,r.useState)([]),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(!1),v=(0,r.useMemo)(()=>{let e=new Map,t=o.filter(e=>"exact"===e.match);for(let s of t.length?t:o)for(let t of s.sources){let n=JSON.stringify([s.referenceId,t.modelId,t.defaults]),r=e.get(n);r?r.sources.push(t):e.set(n,{item:s,sources:[t]})}let s=a.trim().toLocaleLowerCase();return[...e.entries()].map(([e,t])=>{let s=[...t.sources].sort((e,t)=>i8(t)-i8(e)||e.providerName.localeCompare(t.providerName)),n=s[0];return{key:e,item:t.item,source:n,equivalentSourceCount:s.length,recommended:n.official}}).sort((e,t)=>("exact"===e.item.match?0:"similar"===e.item.match?1:2)-("exact"===t.item.match?0:"similar"===t.item.match?1:2)||Number(t.recommended)-Number(e.recommended)||Number(t.source.modelId.toLocaleLowerCase()===s)-Number(e.source.modelId.toLocaleLowerCase()===s)||e.source.providerName.localeCompare(t.source.providerName))},[o,a]);return(0,r.useEffect)(()=>{let t=++i.current;if(!d)return;let r=window.setTimeout(()=>{g(!0),e.listCatalog({query:a.trim(),refresh:!1,page:{index:1,size:10}}).then(e=>{i.current===t&&c(e.models)}).catch(e=>{i.current===t&&(c([]),n.error(e instanceof Error?e.message:s("catalogSearchFailed")))}).finally(()=>{i.current===t&&g(!1)})},250);return()=>{window.clearTimeout(r),i.current===t&&(i.current+=1)}},[e,d,a,n,s]),{searchText:a,setSearchText:l,catalogOpen:d,setCatalogOpen:e=>{u(e),e||g(!1)},loadingCatalog:h,candidates:v,visibleCandidates:f?v:v.slice(0,6),showAllCandidates:f,setShowAllCandidates:x,selectedCandidateKey:m,setSelectedCandidateKey:p}}(e,s.modelId),C=new Map(s.thinkingLevels.map(e=>[e.level,e])),E=iB.find(e=>e.value===t.api)?.label??t.api;function M(e){i({...s,...e})}return(0,n.jsxs)("div",{className:"@container/model-editor space-y-6",children:[(0,n.jsxs)("div",{className:"grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[(0,n.jsxs)("div",{className:"grid gap-1 text-sm @[32rem]/model-editor:col-span-2",children:[(0,n.jsx)("label",{htmlFor:o,className:"font-medium",children:l("modelId")}),(0,n.jsx)(i6.uB,{shouldFilter:!1,loop:!0,className:"h-auto w-full overflow-visible rounded-none bg-transparent p-0 [&_[data-slot=command-input-wrapper]]:p-0 [&_[data-slot=input-group-addon]]:hidden",onKeyDown:e=>{"Escape"===e.key&&g&&(e.preventDefault(),e.stopPropagation(),f(!1))},children:(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(i6.G7,{id:o,value:p,onValueChange:e=>{h(e),M({modelId:e}),S(null),j(!1),f(!0)},placeholder:l("modelIdSearch"),"aria-label":l("modelId"),"aria-autocomplete":"list",className:"pr-9"}),(0,n.jsxs)(eW.AM,{open:g,onOpenChange:e=>{f(e),e&&j(!1)},children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm",title:l("chooseModel"),"aria-label":l("chooseModel"),"aria-busy":x,className:"absolute top-0.5 right-0.5 z-10",children:x?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(i4.A,{})})}),(0,n.jsx)(eW.hl,{align:"end",sideOffset:4,initialFocus:!1,finalFocus:!1,positionerClassName:"z-[120]",className:"w-[min(32rem,calc(100vw-2rem))] gap-0 p-0",children:(0,n.jsx)(i6.oI,{className:"max-h-[min(24rem,var(--available-height))] p-1",children:x&&0===w.length?(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:l("matchingCatalog")}):0===w.length?(0,n.jsx)(i6.xL,{className:"py-6 text-sm",children:l("noCatalogMatches")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(i6.L$,{className:"p-0",children:y.map(e=>(0,n.jsx)(i6.h_,{value:e.key,"data-checked":N===e.key?"true":void 0,className:"px-3 py-2",onSelect:()=>(function(e){let{item:t,source:n}=e,r={...s,modelId:n.modelId,name:t.name,...n.defaults};i(r),d({contextWindow:iY(r.contextWindow),maxTokens:iY(r.maxTokens)}),m(ae(r)),a({dirty:!1,invalid:!1}),h(n.modelId),S(e.key),j(!1),f(!1)})(e),children:(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("span",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("span",{className:"break-all font-mono text-sm font-semibold",children:e.source.modelId}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.source.providerName})]}),(0,n.jsxs)("span",{className:"mt-1 block text-xs text-muted-foreground",children:[e.item.name," \xb7"," ",l("contextAndOutput",{context:`${iY(e.source.defaults.contextWindow)}K`,output:`${iY(e.source.defaults.maxTokens)}K`})]}),(0,n.jsx)("span",{className:"mt-1 block text-xs text-muted-foreground",children:e.source.defaults.cost?`${l("priceInput",{price:`$${e.source.defaults.cost.input}`})} \xb7 ${l("priceOutput",{price:`$${e.source.defaults.cost.output}`})}${l("perMillionTokens")}`:l("priceMissing")})]})},e.key))}),!k&&w.length>y.length?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:()=>j(!0),children:l("moreConfigurations",{count:w.length-y.length})}):null]})})})]})]})}),s.modelId.trim()?null:(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("modelIdRequired")})]}),(0,n.jsxs)(iU,{label:l("modelName"),className:"@[32rem]/model-editor:col-span-2",children:[(0,n.jsx)(em.p,{value:s.name,onChange:e=>M({name:e.target.value})}),s.name.trim()?null:(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("modelNameRequired")})]}),[["contextWindow","contextLength"],["maxTokens","maximumOutput"]].map(([e,t])=>{let s=null===iV(c[e]);return(0,n.jsxs)(iU,{label:l(t),children:[(0,n.jsxs)(nC.MG,{children:[(0,n.jsx)(nC.iV,{"aria-label":l(t),inputMode:"decimal",value:c[e],"aria-invalid":s,"aria-describedby":s?`${o}-${e}-error`:void 0,onChange:t=>{var s;let n,r,i;return s=t.target.value,d(n={...c,[e]:s}),a({dirty:r=at(n,u),invalid:r}),void(null!==(i=iV(s))&&M({[e]:i}))}}),(0,n.jsx)(nC.Sq,{align:"inline-end",children:"K"})]}),s?(0,n.jsx)("span",{id:`${o}-${e}-error`,role:"alert",className:"text-xs text-destructive",children:l("capacityInvalid")}):null]},e)})]}),(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:l("capabilities")}),(0,n.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2 text-sm",children:[s.input.map(e=>(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-1",children:l("text"===e?"textInput":"imageInput")},e)),s.reasoning?(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-1",children:l("supportsThinking")}):null]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("inputAndThinking")}),(0,n.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:[["text","image"].map(e=>{let t=s.input.includes(e);return(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline","aria-pressed":t,onClick:()=>{t&&1===s.input.length||M({input:t?s.input.filter(t=>t!==e):[...s.input,e]})},children:[t?(0,n.jsx)(ep.A,{}):null,l("text"===e?"textInput":"imageInput")]},e)}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline","aria-pressed":s.reasoning,onClick:()=>M({reasoning:!s.reasoning,thinkingLevels:s.reasoning?[{level:"off",providerValue:null}]:[{level:"high",providerValue:null}]}),children:[s.reasoning?(0,n.jsx)(ep.A,{}):null,l("supportsThinking")]})]}),s.reasoning?(0,n.jsxs)("details",{className:"mt-4 border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-medium",children:l("thinkingMapping")}),(0,n.jsx)("div",{className:"mt-2 grid max-w-[40rem] gap-x-4 @[32rem]/model-editor:grid-cols-2",children:i7.map(([e,t])=>{let r=C.get(e);return(0,n.jsxs)("div",{className:"grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-2 border-b py-2",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm","aria-pressed":!!r,className:"justify-start",onClick:()=>{let t=r?s.thinkingLevels.filter(t=>t.level!==e):[...s.thinkingLevels,{level:e,providerValue:"off"===e?null:e}];t.length&&M({thinkingLevels:t})},children:[r?(0,n.jsx)(ep.A,{}):null,l(t)]}),(0,n.jsx)(em.p,{"aria-label":l("providerMapping",{level:l(t)}),disabled:!r||"off"===e,value:"off"===e?l("noMapping"):r?.providerValue??"",placeholder:e,onChange:t=>M({thinkingLevels:s.thinkingLevels.map(s=>s.level===e?{...s,providerValue:t.target.value||null}:s)})})]},e)})})]}):null]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("price")}),(0,n.jsxs)("div",{className:"mt-3 grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[i9.map(([e,t])=>{let r=""!==u[e]&&(!Number.isFinite(Number(u[e]))||0>Number(u[e]));return(0,n.jsxs)(iU,{label:l(t),children:[(0,n.jsx)(em.p,{inputMode:"decimal",value:u[e],"aria-invalid":r,onChange:t=>(function(e,t){let n={...u,[e]:t};m(n);let r=at(c,n);if(a({dirty:r,invalid:r}),Object.values(n).every(e=>""===e))return void M({cost:null});let i=Number(t);Number.isFinite(i)&&!(i<0)&&M({cost:{input:s.cost?.input??0,output:s.cost?.output??0,cacheRead:s.cost?.cacheRead??0,cacheWrite:s.cost?.cacheWrite??0,[e]:i}})})(e,t.target.value)}),r?(0,n.jsx)("span",{role:"alert",className:"text-xs text-destructive",children:l("priceInvalid")}):null]},e)}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",className:"justify-self-start",onClick:()=>{let e={input:"",output:"",cacheRead:"",cacheWrite:""};m(e),a({dirty:!0,invalid:at(c,e)}),M({cost:null})},children:l("clearPrice")})]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("advancedCompatibility")}),(0,n.jsxs)("div",{className:"mt-3 grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[(0,n.jsx)(iU,{label:l("apiOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(iK,{value:s.api??"",ariaLabel:l("apiOverride"),options:iB,placeholder:E?l("inheritServiceValue",{value:E}):l("inheritService"),onChange:e=>M({api:e||null})})}),(0,n.jsx)(iU,{label:l("baseUrlOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(em.p,{value:s.baseUrl??"","aria-label":l("baseUrlOverride"),placeholder:t.baseUrl?l("inheritServiceValue",{value:t.baseUrl}):l("inheritService"),onChange:e=>M({baseUrl:e.target.value||null})})}),(0,n.jsx)(iU,{label:l("modelHeaders"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(iW,{headers:s.headers,onChange:e=>M({headers:e}),placeholder:l("headerPlaceholder")})}),(0,n.jsx)(iU,{label:l("developerRole"),children:(0,n.jsx)(iG,{value:s.compat?.supportsDeveloperRole??null,ariaLabel:l("developerRole"),onChange:e=>M({compat:{supportsDeveloperRole:e,thinkingFormat:s.compat?.thinkingFormat??null,requiresReasoningContentOnAssistantMessages:s.compat?.requiresReasoningContentOnAssistantMessages??null}})})}),(0,n.jsx)(iU,{label:"Thinking Format",children:(0,n.jsx)(iK,{value:s.compat?.thinkingFormat??"",ariaLabel:"Thinking Format",options:iq.map(e=>({value:e,label:e})),onChange:e=>M({compat:{supportsDeveloperRole:s.compat?.supportsDeveloperRole??null,thinkingFormat:e||null,requiresReasoningContentOnAssistantMessages:s.compat?.requiresReasoningContentOnAssistantMessages??null}})})}),(0,n.jsx)(iU,{label:l("replayReasoning"),children:(0,n.jsx)(iG,{value:s.compat?.requiresReasoningContentOnAssistantMessages??null,ariaLabel:l("replayReasoning"),onChange:e=>M({compat:{supportsDeveloperRole:s.compat?.supportsDeveloperRole??null,thinkingFormat:s.compat?.thinkingFormat??null,requiresReasoningContentOnAssistantMessages:e}})})})]})]})]})}var an=s(66153),ar=s(95929);function ai({className:e,disabled:t,id:s,...i}){let{t:a}=(0,b.Bd)("common"),[l,o]=r.useState(!1),c=a(l?"hideSecret":"revealSecret");return(0,n.jsxs)("div",{className:"relative min-w-0",children:[(0,n.jsx)(em.p,{...i,id:s,disabled:t,type:"text",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,className:(0,C.cn)("pr-9",!l&&"[-webkit-text-security:disc]",e)}),(0,n.jsx)("button",{type:"button",className:"absolute top-1/2 right-1 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50","aria-label":c,"aria-controls":s,"aria-pressed":l,title:c,disabled:t,onClick:()=>o(e=>!e),children:l?(0,n.jsx)(an.A,{className:"size-3.5"}):(0,n.jsx)(ar.A,{className:"size-3.5"})})]})}function aa({provider:e,existingIds:t,isNew:s,onApply:i,onDelete:a,onClose:l,onDirtyChange:o}){let{t:c}=(0,b.Bd)("settings"),{confirm:d,dialog:u}=nF(),[m,p]=(0,r.useState)(()=>structuredClone(e)),h=JSON.stringify(m)!==JSON.stringify(e),g=!m.provider.trim()||t.includes(m.provider.trim()),f=m.provider||c("providerUnnamed");function x(e){p(t=>({...t,...e}))}async function v(){(!h||await d({title:c("discardServiceTitle"),description:c("discardServiceDescription"),confirmLabel:c("discardModelConfirm")}))&&l()}async function w(){await d({title:c("providerDeleteTitle"),description:c("providerDeleteDescription",{name:f,count:e.models.length})})&&a()}return(0,r.useEffect)(()=>(o(h),()=>o(!1)),[h,o]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||v()},children:(0,n.jsxs)(eN.hA,{className:"max-w-[40rem]",initialFocus:!1,children:[(0,n.jsxs)(eN.Hl,{className:"border-b px-4 py-4 pr-12",children:[(0,n.jsx)(eN.YM,{children:c("serviceConnection")}),(0,n.jsx)(eN.uX,{children:c("serviceDraftScope",{count:e.models.length})})]}),(0,n.jsx)(eN._Y,{className:"max-h-[65dvh]",children:(0,n.jsxs)("div",{className:"space-y-5 p-4",children:[(0,n.jsxs)(iU,{label:c("serviceId"),children:[(0,n.jsx)(em.p,{value:m.provider,"aria-label":c("serviceId"),autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:c("providerIdExample"),"aria-invalid":g,onChange:e=>x({provider:e.target.value})}),g?(0,n.jsx)("span",{role:"alert",className:"text-xs text-destructive",children:c("serviceIdInvalid")}):null]}),(0,n.jsx)(iU,{label:c("serviceAddress"),children:(0,n.jsx)(em.p,{value:m.baseUrl??"",placeholder:"https://api.example.com/v1",onChange:e=>x({baseUrl:e.target.value||null})})}),(0,n.jsx)(iU,{label:c("providerApiType"),children:(0,n.jsx)(iK,{value:m.api??"",ariaLabel:c("providerApiType"),options:iB,onChange:e=>x({api:e||null})})}),(0,n.jsx)(iU,{label:c("serviceKey"),children:(0,n.jsx)(ai,{value:m.apiKey??"",onChange:e=>x({apiKey:e.target.value||null})})}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:c("providerAdvanced")}),(0,n.jsxs)("div",{className:"mt-3 space-y-3",children:[(0,n.jsx)(iU,{label:c("providerAuthHeader"),children:(0,n.jsx)(iG,{value:m.authHeader,ariaLabel:c("providerAuthHeader"),onChange:e=>x({authHeader:e})})}),(0,n.jsx)(iU,{label:c("providerHeaders"),children:(0,n.jsx)(iW,{headers:m.headers,onChange:e=>x({headers:e}),placeholder:c("headerPlaceholder")})})]})]})]})}),(0,n.jsxs)(eN.vu,{children:[s?null:(0,n.jsxs)(I.$,{type:"button",variant:"ghost",className:"mr-auto text-destructive hover:text-destructive",onClick:w,children:[(0,n.jsx)(et.A,{}),c("providerDelete")]}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:l,children:c("cancel",{ns:"common"})}),(0,n.jsx)(I.$,{type:"button",disabled:g||!h&&!s,onClick:()=>i(m),children:c("applyServiceDraft")})]})]})}),u]})}let al=a.Ik({}).strict(),ao=a.Yj().trim().min(1).max(128),ac=a.Yj().max(32768),ad=a.Ik({url:ac,label:ac.optional()}).strict(),au=a.Ik({provider:ao,name:ac,loggedIn:a.zM(),conflict:a.Yj().nullable()}).strict(),am=a.Ik({id:a.Yj().uuid(),type:a.k5(["text","secret","select","manual_code"]),message:ac,placeholder:ac.optional(),options:a.YO(a.Ik({id:ac,label:ac,description:ac.optional()}).strict()).optional()}).strict(),ap=a.gM("type",[a.Ik({type:a.eu("auth_url"),url:ac,instructions:ac.optional()}).strict(),a.Ik({type:a.eu("device_code"),userCode:ac,verificationUri:ac}).strict(),a.Ik({type:a.eu("info"),message:ac,links:a.YO(ad).optional()}).strict(),a.Ik({type:a.eu("progress"),message:ac}).strict()]),ah=a.Ik({loginId:a.Yj().uuid(),provider:ao,status:a.k5(["running","completed","cancelled","error"]),notice:ap.nullable(),prompt:am.nullable(),message:a.Yj().nullable()}).strict(),ag=Object.freeze({list:(0,l.Vc)({path:"model-auth/list",inputSchema:al,outputSchema:a.Ik({providers:a.YO(au)}).strict()}),start:(0,l.Vc)({path:"model-auth/start",inputSchema:a.Ik({loginId:a.Yj().uuid(),provider:ao}).strict(),outputSchema:al}),respond:(0,l.Vc)({path:"model-auth/respond",inputSchema:a.Ik({loginId:a.Yj().uuid(),promptId:a.Yj().uuid(),value:ac}).strict(),outputSchema:al}),cancel:(0,l.Vc)({path:"model-auth/cancel",inputSchema:a.Ik({loginId:a.Yj().uuid()}).strict(),outputSchema:al}),logout:(0,l.Vc)({path:"model-auth/logout",inputSchema:a.Ik({provider:ao}).strict(),outputSchema:al}),state:(0,l._G)({path:"model-auth/state",bodySchema:ah})});function af(e){try{let t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}}function ax(e){let t=af(e);t&&window.open(t,"_blank","noopener,noreferrer")}async function ab(e){await navigator.clipboard.writeText(e)}function av({prompt:e,submitting:t,onRespond:s}){let{t:i}=(0,b.Bd)("settings"),[a,l]=(0,r.useState)(""),o="select"!==e.type||a.length>0;return(0,n.jsxs)("form",{className:"grid gap-3",onSubmit:n=>{n.preventDefault(),o&&!t&&s(e.id,a)},children:[(0,n.jsx)(iU,{label:e.message,children:"select"===e.type?(0,n.jsx)(iK,{value:a,ariaLabel:e.message,placeholder:e.placeholder??i("accountChooseOption"),options:(e.options??[]).map(e=>({value:e.id,label:e.description?`${e.label} — ${e.description}`:e.label})),onChange:l}):"secret"===e.type?(0,n.jsx)(ai,{value:a,placeholder:e.placeholder,disabled:t,onChange:e=>l(e.target.value)}):(0,n.jsx)(em.p,{value:a,placeholder:e.placeholder,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,disabled:t,onChange:e=>l(e.target.value)})}),(0,n.jsx)(I.$,{type:"submit",disabled:!o||t,className:"justify-self-end",children:i("accountContinue")})]})}function aw({notice:e,onCopy:t,onOpenUrl:s}){let{t:r}=(0,b.Bd)("settings"),i="auth_url"===e.type?[{url:e.url}]:"device_code"===e.type?[{url:e.verificationUri}]:"info"===e.type?e.links??[]:[];return(0,n.jsxs)("div",{className:"space-y-3",children:["auth_url"===e.type&&e.instructions?(0,n.jsx)("p",{className:"whitespace-pre-wrap text-sm",children:e.instructions}):null,"info"===e.type||"progress"===e.type?(0,n.jsx)("p",{className:"whitespace-pre-wrap text-sm",role:"status",children:e.message}):null,"device_code"===e.type?(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-lg border p-3",children:[(0,n.jsx)("span",{className:"text-sm",children:r("accountDeviceCode")}),(0,n.jsx)("code",{className:"select-all break-all text-lg font-semibold",children:e.userCode}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void t(e.userCode),children:r("accountCopyCode")})]}):null,i.map((e,i)=>af(e.url)?(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("p",{className:"break-all text-sm text-muted-foreground",children:e.url}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>s(e.url),children:e.label??r("accountOpenLink")}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>void t(e.url),children:r("accountCopyLink")})]})]},`${i}:${e.url}`):(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:r("accountInvalidLink")},i))]})}function ay({open:e,connected:t,providers:s,state:r,loading:i,submitting:a,error:l,onClose:o,onStart:c,onRespond:d,onCopy:u,onOpenUrl:m,onRetry:p}){let{t:h}=(0,b.Bd)("settings"),g=r?.status==="running";return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{e||o()},children:(0,n.jsxs)(eN.hA,{className:"max-w-lg",children:[(0,n.jsx)(eN.Hl,{className:"border-b p-4 pr-12",children:(0,n.jsx)(eN.YM,{children:r?s.find(e=>e.provider===r.provider)?.name??r.provider:h("accountLogin")})}),(0,n.jsx)(eN._Y,{className:"max-h-[65dvh]",children:(0,n.jsxs)("div",{className:"space-y-4 p-4",children:[l?(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive",children:l}):null,r?.message?(0,n.jsx)("p",{role:"error"===r.status?"alert":"status",className:"whitespace-pre-wrap text-sm",children:r.message}):null,r&&"cancelled"!==r.status&&"error"!==r.status?null:i?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:h("accountLoadingProviders")}):(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:h("accountChooseProvider")}),s.length?null:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:h("accountNoProviders")}),s.map(e=>(0,n.jsxs)("div",{className:"grid gap-1",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",className:"h-auto min-h-10 justify-between whitespace-normal text-left",disabled:!t||!!e.conflict,onClick:()=>void c(e.provider),children:[(0,n.jsx)("span",{children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.loggedIn?h("accountRelogin"):h("accountLogin")})]}),e.conflict?(0,n.jsx)("p",{className:"text-sm text-destructive",children:e.conflict}):null]},e.provider))]}),g&&r.notice?(0,n.jsx)(aw,{notice:r.notice,onCopy:u,onOpenUrl:m}):null,g&&r.prompt?(0,n.jsx)(av,{prompt:r.prompt,submitting:a||!t,onRespond:d},r.prompt.id):null,g&&!r.prompt?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:h("accountWaiting")}):null,r?.status==="completed"?(0,n.jsx)("p",{role:"status",className:"text-sm",children:h("accountLoggedIn")}):null]})}),(0,n.jsxs)(eN.vu,{children:[l&&!g?(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:i,onClick:p,children:h("retry",{ns:"common"})}):null,(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:o,children:h(g?"cancel":"close",{ns:"common"})})]})]})})}function ak({account:e,existingIds:t,onAdd:s,onClose:i}){let{t:a}=(0,b.Bd)("settings"),[l,o]=(0,r.useState)(""),[c,d]=(0,r.useState)([]),u=e.models.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(l.toLocaleLowerCase()));return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||i()},children:(0,n.jsxs)(eN.hA,{className:"max-w-xl",children:[(0,n.jsx)(eN.Hl,{className:"border-b p-4 pr-12",children:(0,n.jsx)(eN.YM,{children:a("modelAddToService",{name:e.name})})}),(0,n.jsx)("div",{className:"p-4 pb-2",children:(0,n.jsx)(em.p,{value:l,"aria-label":a("accountModelSearch"),placeholder:a("accountModelSearch"),onChange:e=>o(e.target.value)})}),(0,n.jsx)(eN._Y,{className:"max-h-[55dvh]",children:(0,n.jsxs)("div",{className:"space-y-1 px-4 pb-4",children:[u.map(e=>{let s=t.includes(e.modelId);return(0,n.jsxs)("label",{className:"flex min-h-14 cursor-pointer items-center gap-3 rounded-lg px-3 py-2 hover:bg-accent",children:[(0,n.jsx)("input",{type:"checkbox",className:"size-4 shrink-0 accent-primary",checked:s||c.includes(e.modelId),disabled:s,onChange:t=>d(s=>t.target.checked?[...s,e.modelId]:s.filter(t=>t!==e.modelId))}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block break-words text-sm font-medium",children:e.name}),(0,n.jsxs)("span",{className:"block break-all text-xs text-muted-foreground",children:[e.modelId," \xb7 ",iY(e.contextWindow)," K"]})]}),s?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:a("accountModelAdded")}):null]},e.modelId)}),u.length?null:(0,n.jsx)("p",{className:"py-6 text-center text-sm text-muted-foreground",children:a("accountNoModels")})]})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:i,children:a("accountAddLater")}),(0,n.jsx)(I.$,{type:"button",disabled:!c.length,onClick:()=>s(c),children:a("accountAddSelected",{count:c.length})})]})]})})}let aj=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function aN({model:e,account:t,overrides:s,onChange:i,onInputState:a}){let{t:l}=(0,b.Bd)("settings"),[o,c]=(0,r.useState)(()=>({contextWindow:void 0===s.contextWindow?"":iY(s.contextWindow),maxTokens:void 0===s.maxTokens?"":iY(s.maxTokens),...Object.fromEntries(aj.map(([e])=>[e,s.cost?.[e]===void 0?"":String(s.cost[e])]))})),d=e=>""!==e&&null===iV(e),u=e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e));function m(e,t){let n={...o,[e]:t};c(n);let r=d(n.contextWindow)||d(n.maxTokens)||aj.some(([e])=>u(n[e]));if(a({dirty:r,invalid:r}),"contextWindow"===e||"maxTokens"===e){if(d(t))return;let n={...s};""===t?delete n[e]:n[e]=iV(t),i(n)}else{if(aj.some(([e])=>u(n[e])))return;let e={...s};aj.every(([e])=>""===n[e])?delete e.cost:e.cost=Object.fromEntries(aj.filter(([e])=>""!==n[e]).map(([e])=>[e,Number(n[e])])),i(e)}}if(!e)return(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("accountModelUnavailable")});let p=e.cost?{...e.cost,...s.cost}:s.cost;return(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-6",children:[(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)("span",{children:l(t?.loggedIn?"accountLoggedIn":"accountLoggedOut")}),t?.subscription?(0,n.jsx)("span",{className:"rounded-md bg-muted px-2",children:l("accountSubscription")}):null]}),(0,n.jsxs)("dl",{className:"grid gap-4 sm:grid-cols-2",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("contextLength")}),(0,n.jsxs)("dd",{className:"mt-1 text-lg font-semibold",children:[iY(s.contextWindow??e.contextWindow)," K"]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("maximumOutput")}),(0,n.jsxs)("dd",{className:"mt-1 text-lg font-semibold",children:[iY(s.maxTokens??e.maxTokens)," K"]})]}),(0,n.jsxs)("div",{className:"sm:col-span-2",children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("capabilities")}),(0,n.jsx)("dd",{className:"mt-1 text-sm",children:[...e.input.map(e=>l("image"===e?"imageInput":"textInput")),...e.reasoning?[l("supportsThinking")]:[]].join(" \xb7 ")})]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("accountReferencePrice")}),(0,n.jsx)("div",{className:"mt-3 text-sm text-muted-foreground",children:p?aj.map(([e,t])=>(0,n.jsxs)("p",{children:[l(t),": ",void 0===p[e]?"—":`$${p[e]}`]},e)):l("priceMissing")})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("accountAdjustParameters")}),(0,n.jsxs)("div",{className:"mt-4 space-y-4",children:[(0,n.jsx)("div",{className:"grid gap-3 sm:grid-cols-2",children:["contextWindow","maxTokens"].map(t=>(0,n.jsxs)(iU,{label:`${l("contextWindow"===t?"contextLength":"maximumOutput")} (K)`,children:[(0,n.jsx)(em.p,{value:o[t],placeholder:iY(e[t]),inputMode:"decimal","aria-invalid":d(o[t]),onChange:e=>m(t,e.target.value)}),d(o[t])?(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("capacityInvalid")}):null]},t))}),(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-medium",children:l("price")}),(0,n.jsx)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:aj.map(([t,s])=>(0,n.jsxs)(iU,{label:l(s),children:[(0,n.jsx)(em.p,{value:o[t],inputMode:"decimal",placeholder:String(e.cost?.[t]??""),"aria-invalid":u(o[t]),onChange:e=>m(t,e.target.value)}),u(o[t])?(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("priceInvalid")}):null]},t))})]}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>{c({contextWindow:"",maxTokens:"",input:"",output:"",cacheRead:"",cacheWrite:""}),i({}),a({dirty:!1,invalid:!1})},children:l("accountRestoreDefaults")})]})]})]})}var aI=s(34506);function aS({name:e,hasAccount:t,loggedIn:s,hasCustom:i,onCustomSettings:a,onLogin:l,onLogout:o}){let{t:c}=(0,b.Bd)("settings"),[d,u]=(0,r.useState)(!1),m=(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":c("serviceSettingsNamed",{name:e}),onClick:t?void 0:a,children:(0,n.jsx)(aI.A,{})});function p(e){u(!1),e()}return t?(0,n.jsxs)(eW.AM,{open:d,onOpenChange:u,children:[(0,n.jsx)(eW.Wv,{render:m}),(0,n.jsxs)(eW.hl,{align:"end",positionerClassName:"z-[120]",className:"w-52 gap-1 p-1",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"justify-start",onClick:()=>p(l),children:c(s?"accountRelogin":"accountLogin")}),s?(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"justify-start text-destructive",onClick:()=>p(o),children:c("accountLogout")}):null,i?(0,n.jsx)(I.$,{type:"button",variant:"ghost",className:"justify-start",onClick:()=>p(a),children:c("accountCustomSettings")}):null]})]}):m}function aC({providerId:e,custom:t,account:s,accountModels:r,query:i,modelKeys:a,selectedCustomIndex:l,selectedAccountId:o,presets:c,onSelectCustom:d,onSelectAccount:u,onCustomSettings:m,onAddCustom:p,onAddAccount:h,onLogin:g,onLogout:f,onGroupRef:x,onRowRef:v}){let{t:w}=(0,b.Bd)("settings"),y=(t?e:s?.name)||e||w("providerUnnamed"),k=r.filter(e=>!t?.models.some(t=>t.modelId===e.modelId)),j=[...(t?.models??[]).map((e,t)=>({key:a[t],modelId:e.modelId,name:e.name,model:e,selected:l===t,select:()=>d(t)})),...k.map(t=>{let n=s?.models.find(e=>e.modelId===t.modelId);return{key:`account:${e}:${t.modelId}`,modelId:t.modelId,name:n?.name??t.modelId,model:n?{...n,...t.overrides}:void 0,selected:o===t.modelId,select:()=>u(t.modelId)}})],N=j.filter(t=>`${e} ${y} ${s?.name??""} ${t.name} ${t.modelId}`.toLocaleLowerCase().includes(i.toLocaleLowerCase()));if(i&&!N.length&&!`${e} ${y} ${s?.name??""}`.toLocaleLowerCase().includes(i.toLocaleLowerCase()))return null;let S=!!s||r.length>0;return(0,n.jsxs)("section",{ref:x,className:"mb-3",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-foreground",children:[(0,n.jsx)(eE.A,{"aria-hidden":"true",className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold",title:s?.name,children:y}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:j.length}),(0,n.jsx)(aS,{name:y,hasAccount:S,loggedIn:s?.loggedIn??!1,hasCustom:!!t,onCustomSettings:m,onLogin:g,onLogout:f})]}),(0,n.jsxs)("div",{className:"space-y-1",children:[N.map(t=>(0,n.jsxs)("button",{ref:e=>v(t.key,e),type:"button","aria-current":t.selected?"true":void 0,className:(0,C.cn)("flex min-h-14 w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",t.selected&&"bg-accent text-accent-foreground"),onClick:t.select,children:[(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",children:t.name||t.modelId||w("modelUnnamed")}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:t.model?`${iY(t.model.contextWindow)} K \xb7 ${w(t.model.input.includes("image")?"imageInput":"textInput")}`:w("accountModelUnavailableShort")})]}),c.some(s=>s.provider===e&&s.modelId===t.modelId)?(0,n.jsx)(i3.A,{className:"size-4 shrink-0 text-muted-foreground"}):null]},t.key)),S?(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",className:"mt-1 w-full border border-dashed border-input","aria-label":w("modelAddToService",{name:s?.name??y}),onClick:h,children:[(0,n.jsx)(U.A,{}),w("modelAdd")]}):null,t?(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",className:"mt-1 w-full border border-dashed border-input","aria-label":w("modelAddToService",{name:y}),onClick:p,children:[(0,n.jsx)(U.A,{}),S?w("accountCustomModel"):null]}):null]})]})}let aE={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function aM({biz:e,connectionReady:t,providers:s,accounts:i,accountModels:a,onAccountModelsChange:l,onRefreshAccounts:o,savedModels:c,savedProviders:d,presets:u,resetVersion:m,onChange:p,onPresetsChange:h,onInputState:g,onServiceDirtyChange:f}){let{t:x}=(0,b.Bd)("settings"),{confirm:v,dialog:w}=nF(),y=(0,X.G)(),[k,j]=(0,r.useState)(null),[N,S]=(0,r.useState)(null),[E,M]=(0,r.useState)(!1),[z,$]=(0,r.useState)(()=>new Set),R=function(e,t){let{appSocket:s}=(0,ei.gM)(),n=(0,r.useMemo)(()=>({list:async()=>(await s.request(ag.list,{})).providers,async start(e,t){await s.request(ag.start,{loginId:e,provider:t})},async respond(e,t,n){await s.request(ag.respond,{loginId:e,promptId:t,value:n})},async cancel(e){await s.request(ag.cancel,{loginId:e})},async logout(e){await s.request(ag.logout,{provider:e})},subscribe:e=>s.subscribe(ag.state,e)}),[s]),{t:i}=(0,b.Bd)("settings"),a=(0,X.G)(),[l,o]=(0,r.useState)(!1),[c,d]=(0,r.useState)([]),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(!1),[x,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(null),k=(0,r.useRef)(e),j=(0,r.useRef)(null),N=(0,r.useRef)(null),I=(0,r.useRef)(null),S=(0,r.useRef)(null),C=(0,r.useRef)(0),E=(0,r.useRef)(t);function M(){let e=j.current;j.current=null,N.current=null,I.current=null,S.current?.(),S.current=null,e?.status==="running"&&n.cancel(e.loginId).catch(e=>{console.warn("[Pi Desk][ModelAuth] 取消登录失败",{message:e instanceof Error?e.message:String(e)})})}function z(){C.current+=1,M(),o(!1)}async function A(){let e=j.current;if(!e||"completed"!==e.status||I.current)return;I.current=e.loginId,f(!0),y(null);let t=()=>j.current?.loginId===e.loginId;try{await E.current(e.provider,t),t()&&z()}catch(e){t()&&y(e instanceof Error?e.message:i("accountRefreshFailed"))}finally{t()&&(I.current=null,f(!1))}}async function $(e){if(!k.current)return void y(i("accountConnectionNotReady"));if(j.current?.status==="running")return;M();let t={loginId:crypto.randomUUID(),provider:e,status:"running",notice:null,prompt:null,message:null};j.current=t,m(t),y(null),v(null),S.current=n.subscribe(e=>{j.current?.loginId===e.loginId&&((j.current.prompt?.id!==e.prompt?.id||"running"!==e.status)&&(N.current=null,v(null)),j.current=e,m(e),y("error"!==e.status||e.message?null:i("accountLoginFailed")),"completed"===e.status&&A())});try{await n.start(t.loginId,e)}catch(e){if(j.current?.loginId!==t.loginId||"running"!==j.current.status)return;M(),m(null),y(e instanceof Error?e.message:i("accountLoginFailed"))}}async function R(e,t){let s=j.current;if(!k.current||!s||"running"!==s.status||s.prompt?.id!==e||N.current)return;let r={loginId:s.loginId,promptId:e};N.current=r,v(e),y(null);try{await n.respond(s.loginId,e,t)}catch(t){j.current?.loginId===s.loginId&&j.current.prompt?.id===e&&y(t instanceof Error?t.message:i("accountLoginFailed"))}finally{N.current===r&&(N.current=null,v(null))}}return(0,r.useEffect)(()=>{E.current=t},[t]),(0,r.useEffect)(()=>()=>{C.current+=1;let e=j.current;j.current=null,S.current?.(),e?.status==="running"&&n.cancel(e.loginId).catch(()=>void 0)},[n]),(0,r.useEffect)(()=>{k.current=e;let t=j.current;if(e||t?.status!=="running")return;j.current=null,N.current=null,S.current?.(),S.current=null,n.cancel(t.loginId).catch(()=>void 0);let s=C.current;queueMicrotask(()=>{C.current===s&&(m(null),v(null),y(i("accountDisconnected")))})},[e,n,i]),{open:l,providers:c,state:u,loading:p||g,submitting:null!==x&&x===u?.prompt?.id,error:w,show:function(e){if(z(),m(null),y(null),v(null),f(!1),o(!0),!k.current){h(!1),y(i("accountConnectionNotReady"));return}h(!0);let t=++C.current;n.list().then(s=>{C.current===t&&(d(s),e&&s.some(t=>t.provider===e&&!t.conflict)&&$(e))}).catch(e=>{C.current===t&&y(e instanceof Error?e.message:i("accountLoginFailed"))}).finally(()=>{C.current===t&&h(!1)})},close:z,start:$,respond:R,finish:A,async logout(e){if(!k.current)throw Error(i("accountConnectionNotReady"));await n.logout(e)},async copy(e){try{await ab(e),a.success(i("accountCopied"))}catch{a.error(i("accountCopyFailed"))}},openUrl:ax}}(t,async(e,t)=>{await o(),t()&&S(e)}),P=function(e,t,s,n){let[i,a]=(0,r.useState)(()=>{let t=e.findIndex(e=>e.models.length>0);return t<0?null:{providerIndex:t,modelIndex:0}}),[l,o]=(0,r.useState)(!1),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(()=>e.map((e,t)=>e.models.map((e,s)=>`${t}:${s}`))),p=(0,r.useRef)(0),h=(0,r.useRef)(new Map(e.flatMap((e,t)=>e.models.map((s,n)=>[`${t}:${n}`,{provider:e.provider,modelId:s.modelId}])))),[g,f]=(0,r.useState)({}),[x,b]=(0,r.useState)(null),[v,w]=(0,r.useState)(!1),y=(0,r.useRef)(e);function k(e){f(t=>Object.fromEntries(Object.entries(t).filter(([t])=>!e.includes(t))))}function j(e,s=u){let n=[];e.forEach((e,t)=>{e.models.forEach((r,i)=>{let a=h.current.get(s[t][i]),l={provider:e.provider.trim(),modelId:r.modelId.trim()};a&&(a.provider!==l.provider||a.modelId!==l.modelId)&&n.push({from:a,to:l})})}),t(e,n)}function N(){b(null),w(!1)}return(0,r.useEffect)(()=>{y.current=e},[e]),(0,r.useEffect)(()=>{queueMicrotask(()=>{let e=y.current;h.current=new Map(e.flatMap((e,t)=>e.models.map((s,n)=>[`${t}:${n}`,{provider:e.provider,modelId:s.modelId}]))),f({}),m(e.map((e,t)=>e.models.map((e,s)=>`${t}:${s}`))),a(t=>{if(t&&e[t.providerIndex]?.models[t.modelIndex])return t;let s=e.findIndex(e=>e.models.length);return s<0?null:{providerIndex:s,modelIndex:0}})})},[n]),(0,r.useEffect)(()=>{let e=Object.values(g);s({dirty:e.some(e=>e.dirty),invalid:e.some(e=>e.invalid)})},[g,s]),{selection:i,mobileDetail:l,query:c,setQuery:d,modelKeys:u,serviceIndex:x,newService:v,openService:e=>{b(e),w(null===e)},closeService:N,applyService:t=>{v?(j([...e,t],[...u,[]]),m(e=>[...e,[]])):j(e.map((e,s)=>s===x?t:e)),N()},deleteService:()=>{if(null===x)return;k(u[x]);let t=e.filter((e,t)=>t!==x);j(t,u.filter((e,t)=>t!==x)),m(e=>e.filter((e,t)=>t!==x)),a(e=>{if(!e||e.providerIndex===x){let e=t.findIndex(e=>e.models.length);return e<0?null:{providerIndex:e,modelIndex:0}}return e.providerIndex>x?{...e,providerIndex:e.providerIndex-1}:e}),o(!1),N()},addModel:t=>{let s=e[t],n=`new-${++p.current}`;j(e.map((e,s)=>s===t?{...e,models:[...e.models,{modelId:"",name:"",api:null,baseUrl:null,reasoning:!1,thinkingLevels:[{level:"off",providerValue:null}],input:["text"],contextWindow:128e3,maxTokens:16384,cost:null,headers:{},compat:null}]}:e),u.map((e,s)=>s===t?[...e,n]:e)),m(e=>e.map((e,s)=>s===t?[...e,n]:e)),a({providerIndex:t,modelIndex:s.models.length}),d(""),o(!0)},selectModel:(e,t)=>{a({providerIndex:e,modelIndex:t}),o(!0)},backToList:()=>{o(!1),d("")},updateModel:function(t,s,n){j(e.map((e,r)=>r===t?{...e,models:e.models.map((e,t)=>t===s?n:e)}:e))},deleteModel:(t,s)=>{k([u[t][s]]);let n=e.map((e,n)=>n===t?{...e,models:e.models.filter((e,t)=>t!==s)}:e);j(n,u.map((e,n)=>n===t?e.filter((e,t)=>t!==s):e)),m(e=>e.map((e,n)=>n===t?e.filter((e,t)=>t!==s):e)),a(e=>{if(!e||e.providerIndex!==t)return e;if(e.modelIndex===s){if(n[t].models.length)return{providerIndex:t,modelIndex:Math.min(s,n[t].models.length-1)};let e=n.findIndex(e=>e.models.length);return e<0?null:{providerIndex:e,modelIndex:0}}return e.modelIndex>s?{...e,modelIndex:e.modelIndex-1}:e}),o(!1)},updateInputState:(e,t)=>f(s=>({...s,[e]:t}))}}(s,p,g,m),{selection:D,mobileDetail:T,query:O,setQuery:L,modelKeys:F,serviceIndex:B,newService:q}=P,_=(0,r.useRef)(new Map),W=(0,r.useRef)(new Map),[Y,V]=(0,r.useState)(!1),[H,K]=(0,r.useState)("off"),G=a.find(e=>e.provider===k?.provider&&e.modelId===k?.modelId)??(s.some(e=>e.models.length)?void 0:a[0]),J=i.find(e=>e.provider===G?.provider),Q=J?.models.find(e=>e.modelId===G?.modelId),Z=!!G,ee=!Z&&D?s[D.providerIndex]:null,es=!Z&&D?ee?.models[D.modelIndex]:null,en=Z?E:T&&!!es,er=Z?Q?.name??G?.modelId:es?.name||es?.modelId||x("modelUnnamed"),ea=G?.provider||ee?.provider||x("providerUnnamed"),el=i.find(e=>e.provider===N),eo=[...new Set([...s.map(e=>e.provider),...i.map(e=>e.provider),...a.map(e=>e.provider)])],ec=e=>`account:${e.provider}:${e.modelId}`,ed=new Set(a.map(ec)),eu=new Set([...z].filter(e=>ed.has(e)));G&&eu.add(ec(G)),(eu.size!==z.size||G&&!z.has(ec(G)))&&$(eu);let[ep,eh]=(0,r.useState)(()=>new Set),eg=D?F[D.providerIndex]?.[D.modelIndex]:void 0,ef=new Set(F.flat()),ex=new Set([...ep].filter(e=>ef.has(e)));eg&&ex.add(eg),(ex.size!==ep.size||eg&&!ep.has(eg))&&eh(ex);let eb=Z?c.find(e=>e.provider===G?.provider&&e.modelId===G.modelId):ee&&es&&d.some(e=>e.provider===ee.provider&&e.models.some(e=>e.modelId===es.modelId))?c.find(e=>e.provider===ee.provider&&e.modelId===es.modelId):void 0;async function ev(){if(G){await v({title:x("accountRemoveTitle"),description:x("accountRemoveDescription",{name:er})})&&(l(a.filter(e=>e!==G)),P.updateInputState(ec(G),{dirty:!1,invalid:!1}),j(null),M(!1));return}D&&es&&await v({title:x("modelDeleteTitle"),description:x("modelDeleteDescription",{name:es.name||es.modelId||x("modelUnnamed")})})&&P.deleteModel(D.providerIndex,D.modelIndex)}async function ew(e){if(await v({title:x("accountLogoutTitle"),description:x("accountLogoutDescription",{name:i.find(t=>t.provider===e)?.name??e}),confirmLabel:x("accountLogout")}))try{await R.logout(e),await o()}catch(e){y.error(e instanceof Error?e.message:x("accountLogoutFailed"))}}return(0,n.jsxs)("section",{className:"@container/models h-full min-h-0 overflow-hidden bg-card",children:[(0,n.jsxs)("div",{className:"grid h-full min-h-0 grid-cols-1 @[48rem]/models:grid-cols-[15rem_minmax(0,1fr)]",children:[(0,n.jsxs)("aside",{"aria-label":x("providerList"),className:(0,C.cn)("min-h-0 min-w-0 flex-col bg-sidebar @[48rem]/models:flex @[48rem]/models:border-r",en?"hidden":"flex"),children:[(0,n.jsx)("div",{className:"shrink-0 p-3",children:(0,n.jsx)(em.p,{value:O,"aria-label":x("modelSearch"),placeholder:x("modelSearch"),onChange:e=>L(e.target.value)})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto px-2 pb-3",children:[eo.map(e=>{let t=s.findIndex(t=>t.provider===e);return(0,n.jsx)(aC,{providerId:e,custom:s[t],account:i.find(t=>t.provider===e),accountModels:a.filter(t=>t.provider===e),query:O,modelKeys:F[t]??[],selectedCustomIndex:Z||D?.providerIndex!==t?null:D.modelIndex,selectedAccountId:G?.provider===e?G.modelId:null,presets:u,onSelectCustom:e=>{j(null),P.selectModel(t,e)},onSelectAccount:t=>{j({provider:e,modelId:t}),M(!0),$(s=>new Set([...s,ec({provider:e,modelId:t})]))},onCustomSettings:()=>P.openService(t),onAddCustom:()=>{j(null),P.addModel(t)},onAddAccount:()=>{let t;return t=i.find(t=>t.provider===e),void(t?.loggedIn?S(e):R.show(e))},onLogin:()=>R.show(e),onLogout:()=>void ew(e),onGroupRef:e=>{t<0||(e?_.current.set(t,e):_.current.delete(t))},onRowRef:(e,t)=>{t?W.current.set(e,t):W.current.delete(e)}},e)}),eo.length?null:(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:x("providerEmpty")})]}),(0,n.jsxs)("div",{className:"flex shrink-0 gap-2 border-t p-3",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>P.openService(null),children:[(0,n.jsx)(U.A,{}),x("accountCustomApi")]}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>R.show(),children:[(0,n.jsx)(i5.A,{}),x("accountLogin")]})]})]}),(0,n.jsx)("section",{"aria-label":x("modelsHeading"),className:(0,C.cn)("min-h-0 min-w-0 flex-col @[48rem]/models:flex",en?"flex":"hidden"),children:Z||es&&D?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2 @[48rem]/models:hidden",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":x("backModelList"),onClick:function(){if(G){M(!1),window.requestAnimationFrame(()=>{let e=W.current.get(ec(G));e?.scrollIntoView({block:"nearest"}),e?.focus({preventScroll:!0})});return}P.backToList(),window.requestAnimationFrame(()=>{if(!D)return;let e=F[D.providerIndex]?.[D.modelIndex];_.current.get(D.providerIndex)?.scrollIntoView({block:"nearest"}),W.current.get(e)?.scrollIntoView({block:"nearest"}),W.current.get(e)?.focus({preventScroll:!0})})},children:(0,n.jsx)(A.A,{})}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",title:J?.name??ea,children:J?.name??ea}),(0,n.jsx)(aS,{name:ea,hasAccount:i.some(e=>e.provider===ea)||a.some(e=>e.provider===ea),loggedIn:i.find(e=>e.provider===ea)?.loggedIn??!1,hasCustom:s.some(e=>e.provider===ea),onCustomSettings:()=>P.openService(s.findIndex(e=>e.provider===ea)),onLogin:()=>R.show(ea),onLogout:()=>void ew(ea)})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 @[48rem]/models:p-6",children:[(0,n.jsxs)("div",{className:"mb-5 flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"min-w-0 break-all text-lg font-semibold",children:er}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:!eb,title:eb?void 0:x("saveBeforePreset"),onClick:()=>{K(eb?.thinkingLevels[0]??"off"),V(!0)},children:[(0,n.jsx)(i3.A,{}),x("addModelPreset")]}),(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm",className:"text-destructive hover:text-destructive","aria-label":Z?`${x("accountRemove")} ${er}`:x("modelDeleteNamed",{name:er}),onClick:ev,children:(0,n.jsx)(et.A,{})})}),(0,n.jsx)(tU.ZI,{children:x(Z?"accountRemove":"modelDelete")})]})]})]}),a.map(e=>{let t=ec(e);if(!eu.has(t))return null;let s=i.find(t=>t.provider===e.provider);return(0,n.jsx)("div",{hidden:!Z||G!==e,children:(0,n.jsx)(aN,{account:s,model:s?.models.find(t=>t.modelId===e.modelId),overrides:e.overrides,onChange:t=>l(a.map(s=>s===e?{...e,overrides:t}:s)),onInputState:e=>P.updateInputState(t,e)})},`${t}:${m}`)}),s.flatMap((t,s)=>t.models.map((r,i)=>{let a=!Z&&D?.providerIndex===s&&D.modelIndex===i,l=F[s]?.[i];return ex.has(l)?(0,n.jsx)("div",{hidden:!a,children:(0,n.jsx)(as,{biz:e,provider:t,model:r,onChange:e=>P.updateModel(s,i,e),onInputState:e=>P.updateInputState(l,e)})},`${l}:${m}`):null}))]})]}):(0,n.jsxs)("div",{className:"flex flex-col items-center gap-3 p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(eO.A,{className:"size-6"}),x("selectModelToEdit")]})})]}),(0,n.jsx)(ay,{open:R.open,connected:t,providers:R.providers,state:R.state,loading:R.loading,submitting:R.submitting,error:R.error,onClose:R.close,onStart:R.start,onRespond:R.respond,onCopy:R.copy,onOpenUrl:R.openUrl,onRetry:()=>R.state?.status==="completed"?void R.finish():R.show()}),el?(0,n.jsx)(ak,{account:el,existingIds:[...a.filter(e=>e.provider===el.provider).map(e=>e.modelId),...s.filter(e=>e.provider===el.provider).flatMap(e=>e.models.map(e=>e.modelId))],onAdd:function(e){if(!el)return;let t=e.filter(e=>!a.some(t=>t.provider===el.provider&&t.modelId===e)&&!s.some(t=>t.provider===el.provider&&t.models.some(t=>t.modelId===e))).map(e=>({provider:el.provider,modelId:e,overrides:{}}));l([...a,...t]),S(null)},onClose:()=>S(null)},el.provider):null,q||null!==B?(0,n.jsx)(aa,{provider:q?{provider:"",name:null,baseUrl:null,api:"openai-responses",apiKey:null,authHeader:null,headers:{},models:[]}:s[B],existingIds:s.filter((e,t)=>q||t!==B).map(e=>e.provider),isNew:q,onApply:P.applyService,onDelete:P.deleteService,onClose:P.closeService,onDirtyChange:f}):null,(0,n.jsx)(eN.YV,{open:Y,onOpenChange:V,children:(0,n.jsxs)(eN.hA,{children:[(0,n.jsx)(eN.Hl,{className:"border-b px-4 py-4 pr-12",children:(0,n.jsx)(eN.YM,{children:x("addModelPreset")})}),(0,n.jsx)(eN._Y,{children:(0,n.jsx)("div",{className:"p-4",children:(0,n.jsx)(iU,{label:x("thinkingLevel"),children:(0,n.jsx)(iK,{value:H,allowEmpty:!1,ariaLabel:x("presetThinkingNew"),options:(eb?.thinkingLevels??[]).map(e=>({value:e,label:x(aE[e])})),onChange:e=>K(e)})})})}),(0,n.jsxs)(eN.vu,{children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",onClick:()=>V(!1),children:x("cancel",{ns:"common"})}),(0,n.jsx)(I.$,{type:"button",onClick:function(){eb&&(u.some(e=>e.provider===eb.provider&&e.modelId===eb.modelId&&e.thinkingLevel===H)||h([...u,{provider:eb.provider,modelId:eb.modelId,thinkingLevel:H,color:iL(u)}]),V(!1))},disabled:!eb,children:x("presetAdd")})]})]})}),w]})}let az={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function aA(e,t){return JSON.stringify([e,t])}function a$(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function aR({biz:e,presets:t,onDirtyChange:s}){let{t:i}=(0,b.Bd)("settings"),a=function(e,t){let{t:s}=(0,b.Bd)("settings"),n=(0,X.G)(),{confirm:i,dialog:a}=nF(),[l,o]=(0,r.useState)([]),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)([]),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)(!1),[x,v]=(0,r.useState)(!0),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(!1),[S,C]=(0,r.useState)(null),[E,M]=(0,r.useState)(null),[z,A]=(0,r.useState)(null),[$,R]=(0,r.useState)(0),[P,D]=(0,r.useState)(0),T=S===c&&null===z&&!w&&!k,O=(0,r.useRef)(!1),L=(0,r.useRef)(""),F=(0,r.useRef)(0),B=(0,r.useCallback)(e=>{O.current=e,t?.(e)},[t]);function q(e){m(e.models),f(null!==e.default),h(e.default??(e.models[0]?{provider:e.models[0].provider,modelId:e.models[0].modelId,thinkingLevel:e.models[0].thinkingLevels[0]}:null))}async function _(e){return!N&&(e===c||(!O.current||!!await i({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}))&&(F.current+=1,j(!0),d(e),!0))}async function W(){if(c&&T&&!w&&!k&&!N&&(!g||p)){I(!0);try{await e.replaceProjectDefault({cwd:c,default:g?p:null}),ij({cwd:c,default:g?p:null,models:u}),B(!1),n.success(g?s("projectDefaultSaved"):s("projectDefaultGlobalSaved"))}catch(e){n.error(e instanceof Error?e.message:s("projectDefaultSaveFailed"))}finally{I(!1)}}}return(0,r.useEffect)(()=>{let t=!1,n=r9.N$.safeParse((iu(),ii)),r=n.success?n.data.directories:null;return queueMicrotask(()=>{!t&&(M(null),v(!r),r&&(o(r),d(e=>e&&r.some(t=>t.cwd===e)?e:r[0]?.cwd??"")))}),(async()=>{try{let s=await e.listDirectories();if(t)return;o(s.directories),d(e=>e&&s.directories.some(t=>t.cwd===e)?e:s.directories[0]?.cwd??"")}catch(e){if(!t&&!r){let t=e instanceof Error?e.message:s("projectDirectoriesFailed");console.warn("[Pi Desk][ProjectModelDefault] 读取项目目录失败",{message:t}),M(t)}}finally{t||v(!1)}})(),()=>{t=!0}},[e,s,$]),(0,r.useEffect)(()=>{let t=!1,n=++F.current;function r(){return!t&&n===F.current}let i=L.current!==c;if(L.current=c,i&&B(!1),!c)return queueMicrotask(()=>{r()&&(m([]),h(null),f(!1),C(null),A(null),y(!1),j(!1))}),()=>{t=!0};let a=(iy(),iv.get(iw(c))??null);return queueMicrotask(()=>{r()&&(A(null),!O.current&&a&&(q(a),C(c)),y(!a&&!O.current),j(!!a||O.current))}),(async()=>{try{let t=await e.getProjectDefault(c);if(!r())return;O.current||q(t),C(c)}catch(e){if(r()){let t=e instanceof Error?e.message:s("projectDefaultFailed");console.warn("[Pi Desk][ProjectModelDefault] 读取项目模型配置失败",{cwd:c,message:t}),A(t)}}finally{r()&&(y(!1),j(!1))}})(),()=>{t=!0}},[e,c,s,B,P]),{directories:l,cwd:c,loadedCwd:S,models:u,selection:p,fixed:g,directoriesLoading:x,projectLoading:w,projectRefreshing:k,saving:N,projectReady:T,directoriesError:E,projectError:z,dialog:a,selectProject:_,changeFixed:function(e){T&&!N&&(B(!0),f(e))},selectModel:function(e){T&&!N&&(B(!0),h({provider:e.provider,modelId:e.modelId,thinkingLevel:e.thinkingLevels[0]}))},selectThinking:function(e){if(!T||N)return;let t=u.find(e=>e.provider===p?.provider&&e.modelId===p.modelId),s=t?.thinkingLevels.find(t=>t===e);p&&s&&(B(!0),h({...p,thinkingLevel:s}))},applyPreset:function(e){T&&!N&&(B(!0),h({provider:e.provider,modelId:e.modelId,thinkingLevel:e.thinkingLevel}))},retryDirectories:function(){R(e=>e+1)},retryProject:function(){F.current+=1,j(!0),D(e=>e+1)},save:W}}(e,s),[l,o]=(0,r.useState)(""),[c,d]=(0,r.useState)(!1),u=a.models.find(e=>e.provider===a.selection?.provider&&e.modelId===a.selection.modelId),m=t.filter(e=>a.models.some(t=>t.provider===e.provider&&t.modelId===e.modelId&&t.thinkingLevels.includes(e.thinkingLevel))),p=a.directories.filter(e=>e.cwd.toLocaleLowerCase().includes(l.trim().toLocaleLowerCase())),h=a.models.map(e=>({value:aA(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider})),g=!a.projectReady||a.saving,f=a.loadedCwd??a.cwd;async function x(e){await a.selectProject(e)&&d(!0)}return(0,n.jsxs)("section",{className:"@container/project-default h-full min-h-0 overflow-hidden bg-card",children:[(0,n.jsxs)("div",{className:"grid h-full min-h-0 grid-cols-1 @[48rem]/project-default:grid-cols-[18rem_minmax(0,1fr)]",children:[(0,n.jsxs)("aside",{"aria-label":i("projectList"),className:(0,C.cn)("min-h-0 min-w-0 flex-col bg-sidebar @[48rem]/project-default:flex @[48rem]/project-default:border-r",c&&a.cwd?"hidden":"flex"),children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 p-3",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:i("projectList")}),(0,n.jsx)(em.p,{value:l,"aria-label":i("projectSearch"),placeholder:i("projectSearch"),onChange:e=>o(e.target.value)})]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto px-2 pb-3",children:a.directoriesLoading&&0===a.directories.length?(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 px-3 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{"aria-hidden":"true",className:"size-4 animate-spin"}),i("projectLoading")]}):a.directoriesError?(0,n.jsxs)("div",{className:"space-y-3 px-3 py-6 text-sm",children:[(0,n.jsx)("p",{role:"alert",className:"break-words text-destructive",children:a.directoriesError}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:a.retryDirectories,children:i("retry",{ns:"common"})})]}):0===p.length?(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:i("projectEmpty")}):(0,n.jsx)("div",{className:"space-y-1",children:p.map(e=>{let t=e.cwd===a.cwd;return(0,n.jsx)(I.$,{type:"button",variant:"ghost","aria-current":t?"true":void 0,disabled:a.saving,className:(0,C.cn)("h-auto min-h-14 w-full items-start justify-start gap-2 whitespace-normal px-3 py-2 text-left",t&&"bg-accent text-accent-foreground ring-1 ring-border ring-inset"),onClick:()=>{x(e.cwd)},children:(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("span",{className:"flex items-start gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 break-all text-sm font-medium",children:a$(e.cwd)}),t?(0,n.jsx)(ep.A,{"aria-hidden":"true",className:"mt-0.5 size-4 shrink-0"}):null]}),(0,n.jsx)("span",{className:"mt-1 block break-all text-xs font-normal text-muted-foreground",children:e.cwd}),(0,n.jsx)("span",{className:"mt-1 block text-xs font-normal text-muted-foreground",children:i("projectSessionCount",{count:e.sessionCount})})]})},e.cwd)})})})]}),(0,n.jsx)("section",{"aria-label":i("projectDefaultSource"),className:(0,C.cn)("min-h-0 min-w-0 flex-col @[48rem]/project-default:flex",c&&a.cwd?"flex":"hidden"),children:a.cwd?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-2 @[48rem]/project-default:hidden",children:(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(!1),children:[(0,n.jsx)(A.A,{"aria-hidden":"true"}),i("backProjectList")]})}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 @[48rem]/project-default:p-6",children:(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-6",children:[(0,n.jsxs)("header",{className:"space-y-1",children:[(0,n.jsxs)("h3",{className:"flex items-center gap-2 text-lg font-semibold",children:[(0,n.jsx)("span",{className:"min-w-0 break-all",children:a$(f)}),(0,n.jsx)("span",{className:"inline-flex size-4 shrink-0",children:!a.projectReady&&!a.projectError&&(0,n.jsx)(v.A,{role:"status","aria-label":i("projectLoading"),className:"size-4 animate-spin text-muted-foreground"})})]}),(0,n.jsx)("p",{className:"break-all text-sm text-muted-foreground",children:f})]}),a.projectError?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("p",{role:"alert",className:"min-w-0 flex-1 break-words text-destructive",children:a.projectError}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:a.retryProject,disabled:a.projectLoading||a.projectRefreshing,children:i("retry",{ns:"common"})})]}):null,null!==a.loadedCwd?(0,n.jsxs)("fieldset",{disabled:g,className:"min-w-0 space-y-6",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:i("projectDefaultSource")}),(0,n.jsx)(n2,{label:i("projectDefaultSource"),value:a.fixed?"fixed":"global",layout:"segmented",disabled:g,options:[{value:"global",label:i("projectFollowGlobal")},{value:"fixed",label:i("projectFixed")}],onChange:e=>a.changeFixed("fixed"===e)})]}),a.fixed?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)(iU,{label:i("projectDefaultModel"),children:(0,n.jsx)(nV.b,{value:a.selection?aA(a.selection.provider,a.selection.modelId):"",options:h,ariaLabel:i("projectDefaultModel"),searchPlaceholder:i("modelSearch"),disabled:g||0===a.models.length,onChange:function(e){let t=a.models.find(t=>aA(t.provider,t.modelId)===e);t&&a.selectModel(t)}})}),(0,n.jsx)(iU,{label:i("thinkingLevel"),children:(0,n.jsx)(iK,{value:a.selection?.thinkingLevel??"",options:(u?.thinkingLevels??[]).map(e=>({value:e,label:i(az[e])})),ariaLabel:i("projectDefaultThinking"),allowEmpty:!1,onChange:a.selectThinking})}),m.length>0?(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:i("fromPreset")}),(0,n.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:m.map((e,t)=>{let s=a.models.find(t=>t.provider===e.provider&&t.modelId===e.modelId);return(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"xs",disabled:g,className:"h-auto min-h-7 max-w-full whitespace-normal text-left",onClick:()=>a.applyPreset(e),children:[(0,n.jsx)("span",{className:"size-2 shrink-0 rounded-full bg-current",style:e.color?{color:e.color}:void 0}),(0,n.jsxs)("span",{className:"min-w-0 break-all",children:[s?.name||e.modelId," \xb7"," ",i(az[e.thinkingLevel])]})]},`${e.provider}/${e.modelId}/${e.thinkingLevel}/${t}`)})})]}):null]}):null]}):null]})}),(0,n.jsx)("div",{className:"shrink-0 border-t px-4 py-3 @[48rem]/project-default:px-6",children:(0,n.jsxs)(I.$,{type:"button",onClick:a.save,disabled:!a.projectReady||g||a.fixed&&!a.selection,children:[a.saving?(0,n.jsx)(v.A,{"aria-hidden":"true",className:"animate-spin"}):(0,n.jsx)(Z.A,{"aria-hidden":"true"}),a.saving?i("savingModels"):i("saveProjectDefault")]})})]}):(0,n.jsxs)("div",{className:"flex items-center gap-2 p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(eP.A,{"aria-hidden":"true",className:"size-6 shrink-0"}),i("selectProjectToConfigure")]})})]}),a.dialog]})}let aP=[{value:"providers",label:"modelProviders"},{value:"presets",label:"modelPresets"},{value:"project-default",label:"projectDefault"}];function aD({loading:e,error:t,onRetry:s}){let{t:r}=(0,b.Bd)("settings");return(0,n.jsx)("div",{className:"flex min-h-72 flex-col items-center justify-center gap-3 p-5 text-sm text-muted-foreground",children:e?(0,n.jsxs)("span",{className:"flex items-center gap-2",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"})," ",r("loadingModels")]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{role:"alert",className:"rounded-lg bg-destructive/10 px-3 py-2 text-destructive",children:t??r("modelsUnavailable")}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:s,children:r("retry",{ns:"common"})})]})})}function aT({onBeforeLeaveChange:e,connectionReady:t=!1,initialTab:s}){let{t:i}=(0,b.Bd)("settings"),{locale:a,timeZone:l}=(0,eQ.i)(),[o,c]=(0,r.useState)(!1),{biz:d,tab:u,settings:m,providers:p,presets:h,accountModels:g,changeAccountModels:f,refreshAccounts:x,resetVersion:w,formDirty:y,formInvalid:k,serviceDirty:j,nativeOpen:N,nativeText:S,nativeError:E,nativeDirty:M,setNativeText:z,openNative:A,closeNative:$,saveNative:R,revertConfig:P,setInputState:D,setServiceDirty:T,loading:O,saving:L,refreshing:F,catalogUpdatedAt:B,loadError:q,dialog:_,setProjectDefaultDirty:W,changeProviders:Y,changePresets:V,selectTab:U,retry:K,refreshCatalog:G,saveConfig:J}=function(e,t){let{t:s}=(0,b.Bd)("settings"),{clientId:n}=(0,ei.gM)(),i=(0,X.G)(),{confirm:a,dialog:l}=nF(),o=(0,r.useMemo)(()=>{let e;return e=null,{parseNativeConfig(e){let t=JSON.parse(e);return rT.parse(t)},getSettings:()=>(e||(e=eu(n,"/api/model-settings/get",{},rK).finally(()=>{e=null})),e),previewSettings:e=>eu(n,"/api/model-settings/preview",iN(e),r0),async replaceSettings(e){await eu(n,"/api/model-settings/replace",iN(e),rZ)},listCatalog:e=>eu(n,"/api/model-catalog/list",r1.parse(e),r4),async listDirectories(){let e=await eu(n,"/api/pi/directories/list",{forceRefresh:!1},r9.N$);return ip(e),e},async getProjectDefault(e){let t=await eu(n,"/api/project-model-default/get",{cwd:e},r6);return ij(t),t},async replaceProjectDefault(e){await eu(n,"/api/project-model-default/replace",r8.parse(e),r7)}}},[n]),[c,d]=(0,r.useState)(()=>t??iM(iE,iS,"providers"));(0,r.useEffect)(()=>{iz(iE,c)},[c]);let[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)([]),[g,f]=(0,r.useState)([]),[x,v]=(0,r.useState)([]),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(!1),[S,C]=(0,r.useState)(!1),[E,M]=(0,r.useState)(!0),[z,A]=(0,r.useState)(!1),[$,R]=(0,r.useState)(!1),[P,D]=(0,r.useState)(null),[T,O]=(0,r.useState)(null),[L,F]=(0,r.useState)(0),[B,q]=(0,r.useState)(0),[_,W]=(0,r.useState)({dirty:!1,invalid:!1}),[Y,V]=(0,r.useState)(!1),[U,H]=(0,r.useState)(!1),[K,G]=(0,r.useState)(""),[J,Q]=(0,r.useState)(null),Z=(0,r.useRef)(!1),ee=(0,r.useRef)([]),et=u?JSON.stringify(u.nativeConfig,null,2):"",es=U&&K!==et,en=k||N||w||_.dirty,er=en||S||Y||es;(0,r.useEffect)(()=>(e(er?()=>!z&&a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}):null),()=>e(null)),[e,er,z,a,s]),(0,r.useEffect)(()=>{if(!er)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[er]);let ea=(0,r.useCallback)(e=>{ee.current=[],m(e),h(structuredClone(e.providers)),f(structuredClone(e.presets)),v(structuredClone(e.accountModels)),y(!1),j(!1),I(!1),W({dirty:!1,invalid:!1}),q(e=>e+1)},[]);async function el(){R(!0);try{let e=await o.listCatalog({query:"",refresh:!0,page:{index:1,size:1}});D(e.updatedAt),await ed(),i.success("cached"===e.refreshResult?s("catalogCached"):"partial"===e.refreshResult?s("catalogPartial"):"unchanged"===e.refreshResult?s("catalogUnchanged"):s("catalogUpdated"))}catch(e){i.error(e instanceof Error?e.message:s("catalogRefreshFailed"))}finally{R(!1)}}async function eo(e,t=0){let{projectDefaults:n}=await o.previewSettings(e);if(n.length>0){let e=[s("replaceProjectDefaultsDescription"),...t>0?[s("removeInvalidPresets",{count:t})]:[]].join(" ");return a({title:s("replaceProjectDefaultsTitle"),description:e,content:(0,r.createElement)(rC,{projectDefaults:n}),confirmLabel:s("confirmAndSaveModels"),confirmVariant:"default"})}return 0===t||a({title:s("removeInvalidPresetsTitle"),description:s("removeInvalidPresets",{count:t}),confirmLabel:s("removeAndSave")})}async function ec(){if(!Z.current&&!_.invalid&&!Y&&!U){if(!u||!en)return void i.success(s("modelsNoChanges"));Z.current=!0,A(!0);try{let e=new Set([...p.flatMap(e=>e.models.map(t=>`${e.provider}\u0000${t.modelId}`)),...x.map(e=>`${e.provider}\u0000${e.modelId}`)]),t=new Set([...u.providers.flatMap(e=>e.models.map(t=>`${e.provider}\u0000${t.modelId}`)),...u.accountModels.map(e=>`${e.provider}\u0000${e.modelId}`)]),n=g.filter(s=>{let n=`${s.provider}\u0000${s.modelId}`;return!t.has(n)||e.has(n)}),r=g.length-n.length,a={...k||_.dirty?{providers:p}:{},...w?{accountModels:x}:{},...N||r>0?{presets:n}:{},...ee.current.length?{modelReplacements:ee.current}:{}};if(!await eo(a,r))return;await o.replaceSettings(a),ea(await o.getSettings()),j(!1),I(!1),i.success(s("modelSaved"))}catch(e){i.error(e instanceof Error?e.message:s("modelSaveFailed"))}finally{Z.current=!1,A(!1)}}}async function ed(){let e=await o.getSettings();return m(t=>t?{...t,accounts:e.accounts,models:e.models,nativeConfig:e.nativeConfig}:e),e}async function em(){!u||Z.current||Y||await a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")})&&ea(u)}async function ep(){Z.current||(!es||await a({title:s("discardNativeTitle"),description:s("discardNativeDescription"),confirmLabel:s("discardModelConfirm")}))&&H(!1)}async function eh(){if(!Z.current&&U&&es){Z.current=!0,A(!0),Q(null);try{let e={nativeConfig:o.parseNativeConfig(K)};if(!await eo(e))return;await o.replaceSettings(e),ea(await o.getSettings()),H(!1),i.success(s("modelSaved"))}catch(t){let e=t instanceof Error?t.message:s("modelSaveFailed");console.warn("[Pi Desk][ModelSettings] 保存 Pi 配置失败",{message:e}),Q(e)}finally{Z.current=!1,A(!1)}}}return(0,r.useEffect)(()=>{let e=!1;return queueMicrotask(()=>{e||(M(!0),O(null))}),o.getSettings().then(t=>{e||ea(t)}).catch(t=>{if(e)return;let n=t instanceof Error?t.message:s("modelsLoadFailed");console.warn("[Pi Desk][ModelSettings] 读取模型配置失败",{message:n}),O(n)}).finally(()=>{e||M(!1)}),()=>{e=!0}},[o,s,L,ea]),{biz:o,tab:c,settings:u,providers:p,presets:g,accountModels:x,changeAccountModels:e=>{v(e),y(JSON.stringify(e)!==JSON.stringify(u?.accountModels))},refreshAccounts:ed,providersDirty:k,presetsDirty:N,loading:E,saving:z,refreshing:$,catalogUpdatedAt:P,loadError:T,resetVersion:B,formDirty:en,formInvalid:_.invalid,serviceDirty:Y,nativeOpen:U,nativeText:K,nativeError:J,nativeDirty:es,setNativeText:G,openNative:function(){if(u&&!Z.current){if(en||Y||S)return void i.error(s("nativeProtectDraft"));G(et),Q(null),H(!0)}},closeNative:ep,saveNative:eh,revertConfig:em,setInputState:W,setServiceDirty:V,dialog:l,setProjectDefaultDirty:C,changeProviders:(e,t)=>{ee.current=t,h(e),j(JSON.stringify(e)!==JSON.stringify(u?.providers))},changePresets:e=>{f(e),I(JSON.stringify(e)!==JSON.stringify(u?.presets))},selectTab:e=>{if(e!==c&&!Z.current){if("project-default"===c&&S)return void a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}).then(t=>{t&&(C(!1),d(e))});d(e)}},retry:()=>F(e=>e+1),refreshCatalog:el,saveConfig:ec}}(e,s);return(0,n.jsxs)("div",{className:"@container/model-settings flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center justify-between gap-2 border-b p-4",children:[(0,n.jsx)(n2,{label:i("models"),layout:"segmented",value:u,options:aP.map(e=>({...e,label:i(e.label)})),onChange:U}),(0,n.jsxs)("div",{className:"hidden gap-2 @[40rem]/model-settings:flex",children:[(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:!m||L,onClick:A,children:[(0,n.jsx)(rI.A,{}),i("nativeConfig")]}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",title:B?i("catalogUpdatedAt",{time:new Date(B).toLocaleString("en"===a?"en-US":"zh-CN",{timeZone:l,timeZoneName:"shortOffset",hourCycle:"h23"})}):i("catalogUnavailable"),onClick:G,disabled:F,children:[(0,n.jsx)(es.A,{className:(0,C.cn)(F&&"animate-spin")}),F?i("refreshingCatalog"):i("refreshCatalog")]})]}),(0,n.jsxs)(eW.AM,{open:o,onOpenChange:c,children:[(0,n.jsx)(eW.Wv,{render:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":i("modelMoreActions"),className:"shrink-0 @[40rem]/model-settings:hidden",children:(0,n.jsx)(H.A,{})})}),(0,n.jsxs)(eW.hl,{align:"end",positionerClassName:"z-[120]",className:"w-48 gap-1 p-1",children:[(0,n.jsxs)(I.$,{type:"button",variant:"ghost",className:"justify-start",disabled:!m||L,onClick:()=>{c(!1),A()},children:[(0,n.jsx)(rI.A,{}),i("nativeConfig")]}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",className:"justify-start",disabled:F,onClick:()=>{c(!1),G()},children:[(0,n.jsx)(es.A,{}),i("refreshCatalog")]})]})]})]}),(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar min-h-0 flex-1","presets"===u?"overflow-y-auto":"overflow-hidden"),children:["project-default"===u?(0,n.jsx)(aR,{biz:d,presets:m?.presets??[],onDirtyChange:W}):m?null:(0,n.jsx)(aD,{loading:O,error:q,onRetry:K}),m?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("fieldset",{disabled:L,className:(0,C.cn)("h-full min-h-0 min-w-0","providers"!==u&&"hidden"),children:(0,n.jsx)(aM,{biz:d,connectionReady:t,providers:p,accounts:m.accounts,accountModels:g,onAccountModelsChange:f,onRefreshAccounts:x,savedProviders:m.providers,savedModels:m.models,presets:h,resetVersion:w,onChange:Y,onPresetsChange:V,onInputState:D,onServiceDirtyChange:T})}),(0,n.jsx)("fieldset",{disabled:L,className:(0,C.cn)("min-w-0","presets"!==u&&"hidden"),children:(0,n.jsx)(i2,{presets:h,models:m.models,onChange:V})})]}):null]}),"project-default"!==u&&m?(0,n.jsxs)("footer",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-t bg-card px-4 py-3",children:[(0,n.jsx)("span",{className:(0,C.cn)("text-xs text-muted-foreground",k&&"text-destructive"),role:"status",children:k?i("fixModelInputs"):y?i("modelDraftPending"):i("modelDraftClean")}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:L||!y||j,onClick:P,children:i("revertModels")}),(0,n.jsxs)(I.$,{type:"button",size:"sm",onClick:J,disabled:L||!y||k||j,children:[L?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(Z.A,{}),L?i("savingModels"):i("saveModels")]})]})]}):null,(0,n.jsx)(iA,{open:N,text:S,error:E,saving:L,dirty:M,onChange:z,onClose:$,onSave:R}),_]})}function aO({render:e,input:t}){return e(t)}let aL=[{id:"appearance",label:"appearance",icon:sq.A},{id:"region",label:"region",icon:s_.A},{id:"habits",label:"habits",icon:sW.A},{id:"models",label:"models",icon:eD.A},{id:"mcp-settings",label:"mcpSettings",icon:eC.A},{id:"capability-modes",label:"capabilityModes",icon:eg.A},{id:"skills",label:"skills",icon:sY.A},{id:"plugins",label:"plugins",icon:eC.A},{id:"auth",label:"loginProtection",icon:en.A},{id:"about",label:"about",icon:sV.A}];function aF(e,t){return`plugin:${e}:${t}`}function aB(){let{t:e}=(0,b.Bd)("settings"),t=(0,eQ.i)();return(0,n.jsxs)("section",{"aria-labelledby":"settings-about-title",className:"min-w-0 space-y-6",children:[(0,n.jsx)("h2",{id:"settings-about-title",className:"text-xl font-semibold",children:e("about")}),(0,n.jsxs)("div",{className:"flex items-center gap-3 rounded-xl bg-muted p-4",children:[(0,n.jsx)(sK.V,{size:48,className:"shrink-0"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:"Pi Desk"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("webDescription")})]})]}),(0,n.jsxs)("dl",{className:"divide-y border-y text-sm",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:e("version")}),(0,n.jsxs)("dd",{className:"font-mono",children:["v",sU]})]}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:e("versionUpdated")}),(0,n.jsx)("dd",{className:"tabular-nums",children:function(e,t,s,n){if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:new Intl.DateTimeFormat(t,{timeZone:s,year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(r)}(sH,"en"===t.locale?"en-US":"zh-CN",t.timeZone,e("common:unavailable"))})]})]})]})}function aq({open:e,connectionReady:t=!1,initialModelTab:s,workSessions:i,focusedCwd:a,pluginAttention:l,renderPluginManagement:o,renderMcpSettings:c,renderCapabilityModesSettings:d,renderPluginSettingsPage:u,onOpenChange:m,onBeforeReload:p}){let{t:h}=(0,b.Bd)("settings"),g=(0,Q.So)(),f=(0,r.useMemo)(()=>{let e=new Map;for(let{cwd:t,projectName:s}of i){let n=t.replaceAll("\\","/").replace(/\/+$/,""),r=/^[a-zA-Z]:\//.test(n)||n.startsWith("//")?n.toLowerCase():n;e.has(r)||e.set(r,{cwd:t,projectName:s})}return[...e.values()]},[i]),x=(0,r.useMemo)(()=>g.flatMap(e=>e.contributions.flatMap(t=>"settings-page"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[g]),[v,w]=(0,r.useState)(()=>s?"models":iM(iC,iI,"appearance"));(0,r.useEffect)(()=>{e&&iz(iC,v)},[v,e]);let[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(!1),S=(0,r.useRef)(null),E=(0,r.useRef)(!1),M=x.find(e=>aF(e.pluginName,e.descriptor.contributionName)===v),z=v.startsWith("plugin:")&&!M?"appearance":v,A=aL.find(e=>e.id===z),$=A?.icon,R=(0,r.useCallback)(async e=>{if(!E.current){E.current=!0,N(!0);try{let t=S.current;if(t&&!await t())return;S.current=null,e()}finally{E.current=!1,N(!1)}}},[]),P=(0,r.useCallback)(()=>{R(()=>m(!1))},[m,R]),D=(0,r.useCallback)(e=>{S.current=e},[]),T=e=>{e!==z&&R(()=>w(e))};return(0,n.jsx)(eN.YV,{open:e,onOpenChange:(e,t)=>{e?m(!0):"focus-out"!==t.reason&&P()},children:(0,n.jsxs)(eN.hA,{className:"h-[min(48rem,calc(100dvh-2rem))] max-w-6xl max-sm:h-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)(eN.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsx)(eN.YM,{children:h("title")})}),(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col sm:flex-row",children:[(0,n.jsx)("div",{className:"shrink-0 border-b bg-sidebar p-3 sm:hidden",children:(0,n.jsxs)(ea.l6,{value:z,disabled:j,onValueChange:e=>{if("string"!=typeof e)return;let t=aL.find(t=>t.id===e);if(t)return void T(t.id);let s=x.find(t=>aF(t.pluginName,t.descriptor.contributionName)===e);s&&T(aF(s.pluginName,s.descriptor.contributionName))},children:[(0,n.jsx)(ea.bq,{"aria-label":h("category"),className:"w-full",children:(0,n.jsx)(ea.yv,{children:M?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eq,{icon:M.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:M.descriptor.label})]}):A&&$?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)($,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:h(A.label)})]}):null})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",align:"start",children:[aL.map(e=>{let t=e.icon;return(0,n.jsxs)(ea.eb,{value:e.id,children:[(0,n.jsxs)("span",{className:"relative shrink-0",children:[(0,n.jsx)(t,{className:"size-4"}),"plugins"===e.id&&l?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute -right-1 -top-1 size-1.5 rounded-full","error"===l?"bg-destructive":"bg-primary")}):null]}),(0,n.jsx)("span",{children:h(e.label)})]},e.id)}),x.length>0?(0,n.jsxs)(ea.s3,{children:[(0,n.jsx)(ea.TR,{children:h("pluginSettings")}),x.map(e=>{let t=aF(e.pluginName,e.descriptor.contributionName);return(0,n.jsxs)(ea.eb,{value:t,children:[(0,n.jsx)(eq,{icon:e.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{children:e.descriptor.label})]},t)})]}):null]})]})}),(0,n.jsxs)("nav",{"aria-label":h("category"),className:"pi-desk-chat-scrollbar hidden w-48 shrink-0 space-y-4 overflow-auto border-r bg-sidebar p-3 sm:block",children:[(0,n.jsx)("div",{className:"grid grid-cols-1 gap-1",children:aL.map(e=>{let t=e.icon,s=e.id===z;return(0,n.jsxs)(I.$,{variant:"ghost",disabled:j,"aria-current":s?"page":void 0,"aria-label":`${h("category")}:${h(e.label)}`,onClick:()=>T(e.id),className:(0,C.cn)("min-w-0 justify-start",s?"bg-accent text-accent-foreground hover:bg-accent":"text-muted-foreground"),children:[(0,n.jsxs)("span",{className:"relative shrink-0",children:[(0,n.jsx)(t,{className:"size-4"}),"plugins"===e.id&&l?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute -right-1 -top-1 size-1.5 rounded-full","error"===l?"bg-destructive":"bg-primary")}):null]}),(0,n.jsx)("span",{className:"truncate",children:h(e.label)})]},e.id)})}),x.length>0?(0,n.jsxs)(eV.Nt,{open:y||!!M,onOpenChange:k,className:"mt-2 border-t pt-2",children:[(0,n.jsxs)(eV.R6,{type:"button","aria-label":h("pluginSettings"),className:"flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1 text-sm font-medium text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 text-left",children:h("pluginSettings")}),(0,n.jsx)("span",{className:"tabular-nums",children:x.length}),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-3.5 transition-transform",y||M?"rotate-180":null)})]}),(0,n.jsx)(eV.Ke,{children:(0,n.jsx)("div",{className:"mt-1 grid grid-cols-1 gap-1",children:x.map(e=>{let t=aF(e.pluginName,e.descriptor.contributionName),s=t===z;return(0,n.jsxs)(I.$,{variant:"ghost",disabled:j,"aria-current":s?"page":void 0,onClick:()=>T(t),className:(0,C.cn)("min-w-0 justify-start",s?"bg-accent text-accent-foreground hover:bg-accent":"text-muted-foreground"),children:[(0,n.jsx)(eq,{icon:e.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:e.descriptor.label})]},t)})})})]}):null]}),M?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:(0,n.jsx)(aO,{render:u,input:{pluginName:M.pluginName,descriptor:M.descriptor,onClose:P,onBeforeLeaveChange:D}})}):"skills"===z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(nP,{projects:f,focusedCwd:a,onBeforeLeaveChange:D})}):"mcp-settings"===z?(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(aO,{render:c,input:{onBeforeLeaveChange:D}})}):"capability-modes"===z?(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(aO,{render:d,input:{onBeforeLeaveChange:D}})}):"models"===z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(aT,{connectionReady:t,initialTab:s,onBeforeLeaveChange:D})}):"plugins"===z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:o()}):(0,n.jsx)(eN._Y,{className:"min-w-0 max-h-none",children:(0,n.jsx)("div",{className:"p-4 sm:p-6",children:"appearance"===z?(0,n.jsx)(ra,{}):"habits"===z?(0,n.jsx)(rN,{}):"auth"===z?e&&(0,n.jsx)(nY,{}):"region"===z?(0,n.jsx)(nQ,{canLeave:p}):(0,n.jsx)(aB,{})})})]})]})})}let a_=a.Ik({cwd:a.Yj().trim().min(1).nullable()}).strict(),aW=a.g1(a.Yj(),a.Pq()),aY=a.g1(a.Yj().min(1).max(128),aW),aV=a.Ik({local:aY,inherited:aY,projectTrusted:a.zM().nullable(),diagnostics:a.YO(a.Ik({name:a.Yj().nullable(),message:a.Yj()}).strict())}).strict();a_.extend({servers:aY}).strict(),a_.extend({name:a.Yj().min(1).max(128)}).strict();let aU=a.Ik({output:a.Yj()}).strict(),aH=a.Ik({}).strict(),aK=["command","args","url","type","description","enabled","exposure"];function aG(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&Object.values(e).every(e=>"string"==typeof e)}function aJ(e){return aG(e)?Object.entries(e).map(([e,t])=>({key:e,value:t})):[]}function aQ(e){return!("command"in e)&&!("url"in e)&&!("type"in e)}function aX(e,t){let s=t??{};return{originalName:e,name:e??"",transport:t&&aQ(t)?"inherit":"url"in s?"http":"stdio",command:"string"==typeof s.command?s.command:"",args:Array.isArray(s.args)?s.args.join("\n"):"",env:aJ(s.env),headers:aJ(s.headers),url:"string"==typeof s.url?s.url:"",description:"string"==typeof s.description?s.description:"",enabled:!1!==s.enabled,exposure:"string"==typeof s.exposure?s.exposure:"",advanced:JSON.stringify(Object.fromEntries(Object.entries(s).filter(([e,t])=>!aK.includes(e)&&!(["env","headers"].includes(e)&&aG(t)))),null,2)}}class aZ extends Error{constructor(e,t){super(t),this.field=e}}function a0(e){return"string"==typeof e.url?e.url:"string"==typeof e.command?e.command:"继承全局连接"}let a1={MCP:"MCP",服务列表:"Servers",配置服务:"Configure server",服务配置:"Server configuration",手动配置:"Configure manually","导入 JSON":"Import JSON",返回服务列表:"Back to servers",服务操作:"Server actions",恢复全局配置:"Restore global configuration",删除服务:"Delete server",继承全局:"Inherited from global",项目配置:"Project configuration","项目配置 \xb7 继承全局连接":"Project configuration \xb7 inherits global connection","连接参数沿用全局,仅保存本项目的启用和工具设置。":"Connection settings are inherited from global. Only enablement and tool settings are saved for this project.",环境变量:"Environment variables",请求头:"Request headers",名称:"Name",值:"Value",添加:"Add ",删除行:"Remove row",高级设置:"Advanced settings","其他配置(JSON)":"Other configuration (JSON)",保存并测试:"Save and test",连接测试结果:"Connection test result","正在测试连接…":"Testing connection…","已保存,正在测试连接…":"Saved. Testing connection…",连接测试通过:"Connection test passed",连接测试失败:"Connection test failed",查看详细输出:"View output","已保存,连接测试通过。":"Saved. Connection test passed.","已保存,连接测试失败。":"Saved. Connection test failed.","请填写名称,或删除空白行。":"Enter a name or remove the empty row.","名称不能重复。":"Names must be unique.","环境变量和请求头不能在表单与 JSON 中重复配置。":"Do not configure environment variables or request headers in both the form and JSON.","连接请求最多等待 10 秒;凭据命令可能延长检查时间。":"Connection requests wait up to 10 seconds; credential commands may extend the check.",配置范围:"Configuration scope",全局:"Global",当前项目:"Current project",手动添加:"Add manually","添加 JSON":"Add JSON","正在读取配置…":"Loading configuration…",重试:"Retry","添加第一个 MCP 服务":"Add your first MCP server","添加服务地址或本地程序。":"Add a server URL or a local program.",已启用:"Enabled",已停用:"Disabled",启用:"Enable",停用:"Disable",编辑:"Edit",为本项目配置:"Configure for this project",独立检查:"Check independently",删除:"Delete",来自全局:"Inherited from global",本项目:"This project",覆盖全局:"Overrides global","项目设置 \xb7 继承全局连接":"Project settings \xb7 inherits global connection",继承全局连接:"Inherit global connection","本项目尚未受信任,不能执行检查;仍可编辑和保存配置。":"This project is not trusted. Checking is disabled; editing and saving remain available.","配置启用不代表已连接。保存不会自动连接或重载会话。":"Enabled configuration does not mean connected. Saving does not connect or reload sessions.","正在检查…":"Checking…",检查输出:"Check output",检查完成:"Check completed",检查失败:"Check failed","检查连接已关闭,当前聊天会话状态未改变。":"The check connection is closed. Current chat session state is unchanged.",返回编辑:"Edit configuration",关闭结果:"Dismiss result",返回:"Back",添加服务:"Add server",编辑服务:"Edit server",保存范围:"Save scope",服务名称:"Server name",连接方式:"Transport",本地程序:"Local program","HTTP 地址":"HTTP URL",启动程序:"Command","参数(每行一个)":"Arguments (one per line)","服务说明(可选)":"Description (optional)",工具使用方式:"Tool exposure",沿用默认:"Use default",通过脚本调用:"Via scripts",按需发现:"On-demand discovery",直接使用:"Direct use",隐藏:"Hidden","高级配置(JSON)":"Advanced configuration (JSON)","继承全局连接,仅保存本项目启用与曝光设置,不复制全局凭据。":"Inherits the global connection. Only project enablement and exposure settings are saved; global credentials are not copied.","本项目的完整定义会整体替换同名全局配置。":"A complete project definition replaces the global configuration of the same name.","配置 JSON":"Configuration JSON","仅接受包含 mcpServers 的标准 JSON。":"Only standard JSON with mcpServers is accepted.",解析预览:"Preview",待保存服务:"Servers to save",新增:"New",替换已有配置:"Replace existing configuration","覆盖全局(仅本项目)":"Override global (this project only)",允许替换以上同名已有配置:"Allow replacing existing configuration with the same names","重新编辑 JSON":"Edit JSON again",取消:"Cancel",保存:"Save","保存中…":"Saving…","已保存。新会话使用新配置;已有会话需重载 Pi 配置。":"Saved. New sessions use the new configuration; existing sessions must reload Pi configuration.","放弃未保存的修改?":"Discard unsaved changes?","当前修改尚未保存。放弃后将保留已保存的配置。":"Your changes have not been saved. Discarding keeps the saved configuration.",放弃修改:"Discard changes",删除配置:"Delete configuration","删除本项目配置后,将恢复使用同名全局配置。":"Deleting this project configuration restores the global configuration of the same name.","此范围内的服务配置将被删除。":"The server configuration will be deleted from this scope.","请输入有效的 JSON。":"Enter valid JSON.","仅接受包含 mcpServers 的标准配置,不允许其他根级字段。":"Only a standard mcpServers object is accepted; other root fields are not allowed.","配置中至少需要一个服务。":"At least one server is required.","服务名称需要 1–128 个字符。":"Server names must contain 1–128 characters.","高级配置需要是 JSON 对象。":"Advanced configuration must be a JSON object.","连接、说明、启用和曝光字段请在上方表单中填写。":"Set connection, description, enablement and exposure in the fields above.","继承连接只允许启用、曝光和 toolExposure 设置。":"Inherited connections only allow enablement, exposure and toolExposure settings.","请输入启动程序。":"Enter a command.","请输入有效的 HTTP 或 HTTPS 地址。":"Enter a valid HTTP or HTTPS URL.","请明确勾选替换已有配置。":"Explicitly allow replacing existing configuration.","该名称已存在,请编辑已有服务或使用其他名称。":"This name already exists. Edit that server or choose another name.","请求失败,请重试。":"The request failed. Please retry."};function a2(){let{locale:e}=(0,eQ.i)();return t=>"en"===e?a1[t]??t:t}function a5(e){return e instanceof Error?e.message:"请求失败,请重试。"}var a3=s(60454),a4=s(93750),a6=s(13464);function a8({id:e,label:t,value:s,options:r,disabled:i,onChange:a}){return(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsx)("label",{id:`${e}-label`,htmlFor:e,className:"text-sm font-medium",children:t}),(0,n.jsxs)(ea.l6,{value:s,disabled:i,onValueChange:e=>{"string"==typeof e&&a(e)},children:[(0,n.jsx)(ea.bq,{id:e,"aria-labelledby":`${e}-label`,className:"w-full min-w-0 whitespace-normal [&_[data-slot=select-value]]:line-clamp-none [&_[data-slot=select-value]]:break-all",children:(0,n.jsx)(ea.yv,{children:r.find(e=>e.value===s)?.label??s})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[125]",align:"start",children:r.map(e=>(0,n.jsx)(ea.eb,{value:e.value,className:"[&_span]:whitespace-normal [&_span]:break-all",children:e.label},e.value))})]})]})}function a7({trigger:e,children:t}){return(0,n.jsxs)(K.rI,{children:[(0,n.jsx)(K.ty,{render:e}),(0,n.jsx)(K.dc,{children:(0,n.jsx)(a3.y,{sideOffset:4,align:"end",className:"z-[125] outline-none",children:(0,n.jsx)(a4._,{className:a6.hD,children:t})})})]})}function a9({message:e,id:t}){let s=a2();return e?(0,n.jsx)("p",{id:t,role:"alert",className:"break-words text-sm text-destructive",children:s(e)}):null}function le({rows:e,selectedName:t,pending:s,onSelect:r}){let i=a2();return(0,n.jsx)("ul",{"aria-label":i("服务列表"),className:"divide-y",children:e.map(e=>{let a="string"==typeof e.config.url?eL.A:w.A;return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button","aria-label":`${i("配置服务")} \xb7 ${e.name}`,"aria-current":t===e.name?"true":void 0,disabled:s,onClick:()=>r(e),className:(0,C.cn)("flex w-full min-w-0 cursor-pointer items-center gap-3 p-4 text-left outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-default",t===e.name&&"bg-accent"),children:[(0,n.jsx)(a,{"aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1 space-y-1",children:[(0,n.jsxs)("span",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,n.jsx)("span",{className:"min-w-0 break-all text-sm font-medium",children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:i(!1===e.config.enabled?"已停用":"已启用")})]}),(0,n.jsxs)("span",{className:"block text-xs text-muted-foreground",children:[i(e.source)," \xb7"," ",i("string"==typeof e.config.url?"HTTP 地址":"本地程序")]}),(0,n.jsx)("span",{className:"block truncate font-mono text-xs text-muted-foreground",children:a0(e.config)})]}),(0,n.jsx)(e7.A,{"aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"})]})},e.name)})})}function lt({id:e,label:t,rows:s,disabled:r,error:i,onChange:a}){let l=a2();return(0,n.jsxs)("fieldset",{className:"min-w-0 space-y-2",disabled:r,children:[(0,n.jsx)("legend",{className:"text-sm font-medium",children:t}),s.length>0&&(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_2rem] gap-2 text-xs text-muted-foreground","aria-hidden":"true",children:[(0,n.jsx)("span",{children:l("名称")}),(0,n.jsx)("span",{children:l("值")})]}),s.map((o,c)=>(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_2rem] gap-2",children:[(0,n.jsx)(em.p,{"aria-label":`${t} \xb7 ${l("名称")} ${c+1}`,"aria-invalid":!!i,"aria-describedby":i?`${e}-error`:void 0,value:o.key,spellCheck:!1,className:"min-w-0 font-mono",onChange:e=>a(s.map((t,s)=>s===c?{...t,key:e.target.value}:t))}),(0,n.jsx)(em.p,{"aria-label":`${t} \xb7 ${l("值")} ${c+1}`,value:o.value,spellCheck:!1,autoComplete:"off",className:"min-w-0 font-mono",onChange:e=>a(s.map((t,s)=>s===c?{...t,value:e.target.value}:t))}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":`${l("删除行")} \xb7 ${t} ${c+1}`,disabled:r,onClick:()=>a(s.filter((e,t)=>t!==c)),children:(0,n.jsx)(et.A,{"aria-hidden":"true"})})]},c)),(0,n.jsx)(a9,{id:`${e}-error`,message:i}),(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>a([...s,{key:"",value:""}]),children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),l("添加"),t]})]})}var ls=s(27315);function ln({check:e,onRetry:t,onDismiss:s}){let r=a2(),i=e.loading?v.A:e.error?Y.A:ls.A;return(0,n.jsxs)("section",{"aria-label":r("连接测试结果"),"aria-busy":e.loading,className:"space-y-2 border-b pb-4",children:[(0,n.jsxs)("p",{role:"status",className:"flex items-center gap-2 text-sm font-medium",children:[(0,n.jsx)(i,{"aria-hidden":"true",className:`size-4 shrink-0 ${e.loading?"motion-safe:animate-spin":e.error?"text-destructive":""}`}),r(e.loading?"已保存,正在测试连接…":e.error?"已保存,连接测试失败。":"已保存,连接测试通过。")]}),(0,n.jsx)(a9,{message:e.error}),e.loading?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:r("连接请求最多等待 10 秒;凭据命令可能延长检查时间。")}):(0,n.jsxs)(n.Fragment,{children:[e.output&&(0,n.jsxs)("details",{className:"text-sm",children:[(0,n.jsx)("summary",{className:"w-fit cursor-pointer rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:r("查看详细输出")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap break-all rounded-lg bg-muted p-3 font-mono text-sm",children:e.output})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:r("检查连接已关闭,当前聊天会话状态未改变。")}),(0,n.jsxs)("div",{className:"flex gap-2",children:[e.error&&(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:t,children:r("重试")}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:s,children:r("关闭结果")})]})]})]})}function lr({editor:e,scopeLabel:t,project:s,projectTrusted:i,check:a,local:l,inherited:o,pending:c,saving:d,error:u,onDraft:m,onJson:p,onPreview:h,onOverwrite:g,onSave:f,onCancel:x,onRemove:b,onDismissCheck:v}){let w=a2(),y=(0,r.useId)(),k=(0,r.useRef)(null),[j,N]=(0,r.useState)(!1);(0,r.useEffect)(()=>{u&&k.current?.querySelector('[aria-invalid="true"]')?.focus()},[u]);let S=e=>`${y}-${e}`,C="manual"===e.kind?e.draft:null,E="json"===e.kind&&e.preview?Object.keys(e.preview).filter(e=>Object.hasOwn(l,e)):[],M="json"===e.kind?"导入 JSON":C?.originalName?"服务配置":"添加服务",z=C?.originalName,$=!!(z&&Object.hasOwn(l,z)),R=!!(s&&z&&Object.hasOwn(o,z)),P=(e,t,s)=>(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:S(e),className:"text-sm font-medium",children:w(t)}),s,(0,n.jsx)(a9,{id:S(`${e}-error`),message:u?.field===e?u.message:null})]}),D=(e,t)=>P(e,t,(0,n.jsx)(em.p,{id:S(e),value:C?.[e]??"",disabled:c||"name"===e&&!!C?.originalName,"aria-invalid":u?.field===e,"aria-describedby":u?.field===e?S(`${e}-error`):void 0,onChange:t=>m({[e]:t.target.value})}));return(0,n.jsxs)("form",{ref:k,"aria-label":w(M),className:"flex min-h-0 min-w-0 flex-1 flex-col",onSubmit:e=>{e.preventDefault(),f()},children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-1 border-b p-4 sm:px-6",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":w("返回服务列表"),disabled:c,onClick:x,children:(0,n.jsx)(A.A,{"aria-hidden":"true"})}),(0,n.jsx)("h3",{className:"min-w-0 flex-1 text-sm font-semibold",children:w(M)}),$&&z&&(0,n.jsx)(a7,{trigger:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":w("服务操作"),disabled:c,children:(0,n.jsx)(H.A,{"aria-hidden":"true"})}),children:(0,n.jsx)(K._2,{variant:R?"default":"destructive",onClick:()=>b(z),children:w(R?"恢复全局配置":"删除服务")})})]}),s&&(0,n.jsxs)("p",{className:"break-all text-xs text-muted-foreground",children:[w("保存范围"),":",t]})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:[C?(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-4",children:[a&&(0,n.jsx)(ln,{check:a,onRetry:()=>f(!0),onDismiss:v}),D("name","服务名称"),"inherit"===C.transport?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:w("继承全局连接")}),z&&o[z]&&(0,n.jsx)("p",{className:"break-all font-mono text-sm text-muted-foreground",children:a0(o[z])}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("连接参数沿用全局,仅保存本项目的启用和工具设置。")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a8,{id:S("transport"),label:w("连接方式"),value:C.transport,disabled:c,options:[{value:"stdio",label:w("本地程序")},{value:"http",label:w("HTTP 地址")}],onChange:e=>m({transport:"http"===e?"http":"stdio"})}),"stdio"===C.transport?(0,n.jsxs)(n.Fragment,{children:[D("command","启动程序"),P("args","参数(每行一个)",(0,n.jsx)(t7.T,{id:S("args"),className:"min-h-24 font-mono",value:C.args,disabled:c,onChange:e=>m({args:e.target.value})}))]}):D("url","HTTP 地址"),("stdio"===C.transport||u?.field==="env")&&(0,n.jsx)(lt,{id:S("env"),label:w("环境变量"),rows:C.env,disabled:c,error:u?.field==="env"?u.message:null,onChange:e=>m({env:e})}),("http"===C.transport||u?.field==="headers")&&(0,n.jsx)(lt,{id:S("headers"),label:w("请求头"),rows:C.headers,disabled:c,error:u?.field==="headers"?u.message:null,onChange:e=>m({headers:e})}),s&&(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("本项目的完整定义会整体替换同名全局配置。")})]}),(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",checked:C.enabled,disabled:c,onChange:e=>m({enabled:e.target.checked}),className:"size-4 shrink-0 accent-primary"}),w("已启用")]}),(0,n.jsxs)(eV.Nt,{open:j||u?.field==="advanced",onOpenChange:N,children:[(0,n.jsxs)(eV.R6,{type:"button",className:"group flex min-h-8 cursor-pointer items-center gap-2 rounded-lg px-2 text-sm font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eY.A,{"aria-hidden":"true",className:"size-4 transition-transform group-data-panel-open:rotate-180"}),w("高级设置")]}),(0,n.jsxs)(eV.Ke,{className:"space-y-3 pt-3",children:["inherit"!==C.transport&&D("description","服务说明(可选)"),(0,n.jsx)(a8,{id:S("exposure"),label:w("工具使用方式"),value:C.exposure,disabled:c,options:[{value:"",label:w("沿用默认")},{value:"codemode",label:w("通过脚本调用")},{value:"deferred",label:w("按需发现")},{value:"direct",label:w("直接使用")},{value:"hidden",label:w("隐藏")},...["","codemode","deferred","direct","hidden"].includes(C.exposure)?[]:[{value:C.exposure,label:C.exposure}]],onChange:e=>m({exposure:e})}),(0,n.jsx)("label",{htmlFor:S("advanced"),className:"block text-sm font-medium",children:w("其他配置(JSON)")}),(0,n.jsx)(t7.T,{id:S("advanced"),onFocus:()=>N(!0),value:C.advanced,disabled:c,className:"min-h-40 font-mono",spellCheck:!1,"aria-invalid":u?.field==="advanced","aria-describedby":u?.field==="advanced"?S("advanced-error"):void 0,onChange:e=>m({advanced:e.target.value})}),(0,n.jsx)(a9,{id:S("advanced-error"),message:u?.field==="advanced"?u.message:null})]})]})]}):"json"===e.kind?(0,n.jsxs)("div",{className:"space-y-3",children:[P("json","配置 JSON",(0,n.jsx)(t7.T,{id:S("json"),value:e.text,disabled:c,"aria-invalid":u?.field==="json","aria-describedby":u?.field==="json"?S("json-error"):void 0,spellCheck:!1,className:"min-h-48 font-mono",placeholder:'{ "mcpServers": { "docs": { "url": "https://example.com/mcp" } } }',onChange:e=>p(e.target.value)})),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("仅接受包含 mcpServers 的标准 JSON。")}),(0,n.jsx)(I.$,{type:"button",variant:"outline",onClick:h,disabled:c||!e.text.trim(),children:w("解析预览")}),e.preview&&(0,n.jsxs)("section",{"aria-label":w("待保存服务"),className:"space-y-3",children:[(0,n.jsx)("ul",{className:"divide-y border-y",children:Object.entries(e.preview).map(([e,t])=>(0,n.jsxs)("li",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 break-all font-medium",children:e}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(aQ(t)?"继承全局连接":"url"in t?"HTTP 地址":"本地程序")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(Object.hasOwn(l,e)?"替换已有配置":Object.hasOwn(o,e)?"覆盖全局(仅本项目)":"新增")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(!1===t.enabled?"已停用":"已启用")})]},e))}),E.length>0&&(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-start gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",checked:e.overwrite,disabled:c,className:"mt-1 size-4 shrink-0 accent-primary",onChange:e=>g(e.target.checked)}),(0,n.jsx)("span",{children:w("允许替换以上同名已有配置")})]})]})]}):null,(0,n.jsx)("div",{className:"mt-3",children:(0,n.jsx)(a9,{message:u?.field==="save"?u.message:null})})]}),(0,n.jsxs)("footer",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t bg-background px-4 py-3 sm:px-6",children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:c,onClick:x,children:w("取消")}),C&&(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:c||!C.enabled||!1===i,onClick:()=>f(!0),children:w("保存并测试")}),(0,n.jsx)(I.$,{type:"submit",disabled:c||"json"===e.kind&&(!e.preview||E.length>0&&!e.overwrite),children:w(a?.loading?"正在测试连接…":d?"保存中…":"保存")})]})]})}function li({pending:e,onAdd:t,onImport:s}){let r=a2();return(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-6",children:(0,n.jsx)("div",{className:"grid min-h-full grid-rows-[1fr_auto_2fr]",children:(0,n.jsxs)("div",{className:"row-start-2 flex flex-col items-center gap-6 text-center",children:[(0,n.jsxs)("div",{"aria-hidden":"true",className:"relative h-28 w-60 shrink-0 text-muted-foreground",children:[(0,n.jsxs)("svg",{viewBox:"0 0 240 112",fill:"none",className:"absolute inset-0 size-full text-muted-foreground/40",children:[(0,n.jsx)("path",{d:"M44 76H64Q76 76 76 64V60Q76 56 92 56M148 56H164Q180 56 180 44Q180 40 196 40M120 12V28",stroke:"currentColor"}),(0,n.jsx)("circle",{cx:"120",cy:"8",r:"3",className:"fill-background stroke-current"}),(0,n.jsx)("circle",{cx:"64",cy:"76",r:"2",className:"fill-muted-foreground"}),(0,n.jsx)("circle",{cx:"180",cy:"44",r:"2",className:"fill-muted-foreground"})]}),(0,n.jsx)("div",{className:"absolute top-14 left-1 flex size-10 items-center justify-center rounded-xl border bg-muted/50",children:(0,n.jsx)(w.A,{className:"size-4"})}),(0,n.jsx)("div",{className:"absolute top-7 left-[92px] flex size-14 items-center justify-center rounded-xl border bg-background text-foreground",children:(0,n.jsx)(eC.A,{className:"size-6"})}),(0,n.jsx)("div",{className:"absolute top-5 right-1 flex size-10 items-center justify-center rounded-xl border bg-muted/50",children:(0,n.jsx)(eL.A,{className:"size-4"})})]}),(0,n.jsx)("h3",{className:"text-lg font-semibold",children:r("添加第一个 MCP 服务")}),(0,n.jsxs)("div",{className:"flex flex-wrap justify-center gap-2",children:[(0,n.jsxs)(I.$,{disabled:e,onClick:t,children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),r("添加服务")]}),(0,n.jsx)(I.$,{variant:"outline",disabled:e,onClick:s,children:r("导入 JSON")})]})]})})})}function la({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{clientId:i}=(0,ei.gM)(),l=function(e,t){let s=a2(),n=(0,r.useMemo)(()=>({getMcp:(t,s)=>eu(e,"/api/mcp-settings/get",{cwd:t},aV,{signal:s}),replaceMcp:(t,s)=>eu(e,"/api/mcp-settings/replace",t,aH,{signal:s}),deleteMcp:(t,s,n)=>eu(e,"/api/mcp-settings/del",{cwd:t,name:s},aH,{signal:n}),checkMcp:(t,s,n)=>eu(e,"/api/mcp-check/get",{cwd:t,name:s},aU,{signal:n})}),[e]),{confirm:i,dialog:l}=nF(),[o,c]=(0,r.useState)(null),[d,u]=(0,r.useState)(null),m=d?.data??null,p=d?d.cwd:o,[h,g]=(0,r.useState)(null),[f,x]=(0,r.useState)(!0),[b,v]=(0,r.useState)(!1),[w,y]=(0,r.useState)(null),[k,j]=(0,r.useState)(null),[N,I]=(0,r.useState)(null),[S,C]=(0,r.useState)(null),E=(0,r.useRef)(null),M=(0,r.useRef)(0),z=(0,r.useRef)(0),A=(0,r.useRef)(i),$=(0,r.useRef)(s);(0,r.useEffect)(()=>{A.current=i,$.current=s},[i,s]);let R=null!==d&&d.cwd===o&&!f&&!w,P=R&&(h?.kind==="manual"&&JSON.stringify(h.draft)!==h.initial||h?.kind==="json"&&!!h.text),D=(0,r.useCallback)(()=>{g(null),j(null)},[]),T=(0,r.useCallback)(async()=>!(b||S?.loading)&&(!P||await A.current({title:$.current("放弃未保存的修改?"),description:$.current("当前修改尚未保存。放弃后将保留已保存的配置。"),confirmLabel:$.current("放弃修改")})),[P,b,S?.loading]);(0,r.useEffect)(()=>(t(T),()=>t(null)),[T,t]);let O=(0,r.useCallback)(async(e,t,s=!1)=>{x(!0),y(null);try{let r=await n.getMcp(o,e);if(e.aborted||M.current!==t)return!1;return u({cwd:o,data:r}),s&&g(null),!0}catch(s){return e.aborted||M.current!==t||(console.warn("[Pi Desk][MCP] 读取配置失败",{cwd:o,message:a5(s)}),y(a5(s))),!1}finally{e.aborted||M.current!==t||x(!1)}},[n,o]);(0,r.useEffect)(()=>{let e=new AbortController;E.current=e;let t=++M.current;return O(e.signal,t,!0),()=>e.abort()},[O]);let L=async e=>{await T()&&(D(),I(null),e())},F=async e=>{e!==o&&await T()&&(E.current?.abort(),j(null),I(null),C(null),y(null),x(!0),c(e))},B=(e,t)=>{let s=aX(e,t);j(null),I(null),C(null),g({kind:"manual",draft:s,initial:JSON.stringify(s)})},q=async(e,t)=>{let s=E.current?.signal;if(!s||!R||b||S?.loading)return!1;let n=M.current;v(!0),j(null),I(null);try{if(await e(s),s.aborted||M.current!==n)return!1;return t(),C(null),I("已保存。新会话使用新配置;已有会话需重载 Pi 配置。"),await O(s,n)}catch(e){return s.aborted||M.current!==n||j({field:e instanceof aZ?e.field:"save",message:a5(e)}),!1}finally{s.aborted||M.current!==n||v(!1)}},_=async(e=!1)=>{if(!(!h||!m||!R||b||S?.loading)&&(!e||"manual"===h.kind&&h.draft.enabled&&!1!==m.projectTrusted))try{let t="manual"===h.kind?function(e,t){let s,n=e.name.trim();if(!n||n.length>128)throw new aZ("name","服务名称需要 1–128 个字符。");try{s=aW.parse(JSON.parse(e.advanced))}catch{throw new aZ("advanced","高级配置需要是 JSON 对象。")}if(aK.some(e=>e in s))throw new aZ("advanced","连接、说明、启用和曝光字段请在上方表单中填写。");if("inherit"===e.transport&&Object.keys(s).some(e=>"toolExposure"!==e))throw new aZ("advanced","继承连接只允许启用、曝光和 toolExposure 设置。");let r={...s,enabled:e.enabled};if(e.exposure&&(r.exposure=e.exposure),"inherit"!==e.transport){for(let n of(e.description&&(r.description=e.description),["env","headers"]))if(e[n].length>0||aG(t?.[n])){if(n in s)throw new aZ("advanced","环境变量和请求头不能在表单与 JSON 中重复配置。");r[n]=function(e,t){let s=[],n=new Set;for(let r of e){if(!r.key.trim()&&!r.value)continue;if(!r.key.trim())throw new aZ(t,"请填写名称,或删除空白行。");let e=r.key.trim(),i="headers"===t?e.toLowerCase():e;if(n.has(i))throw new aZ(t,"名称不能重复。");n.add(i),s.push([e,r.value])}return Object.fromEntries(s)}(e[n],n)}}if("stdio"===e.transport){if(!e.command.trim())throw new aZ("command","请输入启动程序。");r.command=e.command.trim(),r.args=Array.isArray(t?.args)&&t.args.join("\n")===e.args?t.args:e.args?e.args.split(/\r?\n/):[],(t?.type!==void 0||!t||"url"in t)&&(r.type="stdio")}else if("http"===e.transport){try{let t=new URL(e.url.trim());if(!["https:","http:"].includes(t.protocol))throw Error()}catch{throw new aZ("url","请输入有效的 HTTP 或 HTTPS 地址。")}r.url=e.url.trim(),(t?.type!==void 0||!t||"command"in t)&&(r.type="http")}return{[n]:r}}(h.draft,h.draft.originalName?m.local[h.draft.originalName]:void 0):h.preview;if(!t)return;let s=Object.keys(t).filter(e=>Object.hasOwn(m.local,e));if("json"===h.kind&&s.length&&!h.overwrite)throw new aZ("json","请明确勾选替换已有配置。");if("manual"===h.kind&&s.some(e=>e!==h.draft.originalName))throw new aZ("name","该名称已存在,请编辑已有服务或使用其他名称。");if(await q(e=>n.replaceMcp({cwd:o,servers:t},e),()=>{if("json"===h.kind)g(null);else{let e=h.draft.name.trim(),s=aX(e,t[e]);g({kind:"manual",draft:s,initial:JSON.stringify(s)})}})&&e&&"manual"===h.kind){let e=await Y(h.draft.name.trim());E.current?.signal.aborted||I(e?"已保存,连接测试通过。":"已保存,连接测试失败。")}}catch(e){j({field:e instanceof aZ?e.field:"save",message:a5(e)})}},W=async e=>{if(!m||!R||b||!Object.hasOwn(m.local,e))return;let t=null!==o&&Object.hasOwn(m.inherited,e);await A.current({title:`${$.current(t?"恢复全局配置":"删除服务")} \xb7 ${e}`,description:$.current(t?"删除本项目配置后,将恢复使用同名全局配置。":"此范围内的服务配置将被删除。"),confirmLabel:$.current(t?"恢复全局配置":"删除服务")})&&await q(t=>n.deleteMcp(o,e,t),()=>g(null))},Y=async e=>{let t=E.current?.signal;if(!t||!m||!1===m.projectTrusted||S?.loading)return!1;let s=++z.current;C({name:e,loading:!0,output:null,error:null});try{let r=await n.checkMcp(o,e,t);return t.aborted||z.current!==s||C({name:e,loading:!1,output:r.output.slice(0,32768),error:null}),!0}catch(n){return t.aborted||z.current!==s||C({name:e,loading:!1,output:null,error:a5(n)}),!1}},V=m?[...new Set([...Object.keys(m.inherited),...Object.keys(m.local)])].map(e=>{let t=m.local[e],s=m.inherited[e],n=!!(t&&s&&aQ(t));return{name:e,config:n?{...s,...t}:t??s,local:t??null,source:null===p?"全局":t?n?"项目配置 \xb7 继承全局连接":"项目配置":"继承全局"}}):[];return{cwd:o,displayCwd:p,ready:R,mcp:m,editor:h,setEditor:g,loading:f,pending:b,loadError:w,error:k,notice:N,check:S,rows:V,dirty:P,dialog:l,retry:()=>{E.current&&O(E.current.signal,M.current,d?.cwd!==o)},navigate:L,setCwd:F,startManual:B,startInherited:(e,t)=>{B(e,{enabled:!1!==t.enabled})},updateDraft:e=>{g(t=>t?.kind==="manual"?{...t,draft:{...t.draft,...e}}:t),j(null),I(null),C(null)},updateJson:e=>{g({kind:"json",text:e,preview:null,overwrite:!1}),j(null)},previewJson:()=>{if(h?.kind==="json"&&m)try{let t=function(e){let t;try{t=JSON.parse(e)}catch{throw Error("请输入有效的 JSON。")}let s=a.Ik({mcpServers:aY}).strict().safeParse(t);if(!s.success)throw Error("仅接受包含 mcpServers 的标准配置,不允许其他根级字段。");if(0===Object.keys(s.data.mcpServers).length)throw Error("配置中至少需要一个服务。");return s.data.mcpServers}(h.text);var e=m.inherited;for(let[s,n]of Object.entries(t)){if(!s.trim()||s!==s.trim())throw new aZ("json","服务名称不能为空或带有首尾空格。");if(aQ(n)){if(null===o||!Object.hasOwn(e,s)||Object.keys(n).some(e=>!["enabled","exposure","toolExposure"].includes(e)))throw new aZ("json",`${s}:继承配置需要同名全局服务,且只允许启用和曝光设置。`)}else if("sse"===n.type)throw new aZ("json",`${s}:不支持 SSE,请使用 HTTP 连接。`);else if("string"!=typeof n.command&&"string"!=typeof n.url)throw new aZ("json",`${s}:请提供启动程序或服务地址。`)}g({...h,preview:t,overwrite:!1}),j(null)}catch(e){j({field:"json",message:a5(e)})}},saveEditor:_,remove:W,dismissCheck:()=>{C(null)},beforeLeave:T}}(i,s),o=a2(),c=(0,r.useId)(),d=(0,r.useMemo)(()=>{let s=new Map;for(let t of e){let e=t.cwd.replaceAll("\\","/").replace(/\/+$/,""),n=/^[a-zA-Z]:\//.test(e)||e.startsWith("//")?e.toLowerCase():e;s.has(n)||s.set(n,t)}return[...s.values()].sort((e,s)=>Number(s.cwd===t)-Number(e.cwd===t))},[e,t]),u=null===l.displayCwd?o("全局"):`${d.find(e=>e.cwd===l.displayCwd)?.projectName??o("当前项目")} \xb7 ${l.displayCwd}`,m=!!(l.editor&&l.mcp),p=l.pending||!!l.check?.loading,h=p||!l.ready,g=l.editor?.kind==="manual"?l.editor.draft.originalName:null,f=()=>{l.navigate(()=>l.startManual(null))},x=()=>{l.navigate(()=>l.setEditor({kind:"json",text:"",preview:null,overwrite:!1}))};return(0,n.jsxs)("section",{"aria-label":"MCP",className:"@container/mcp flex h-full min-h-0 min-w-0 flex-col",children:[l.dialog,(0,n.jsxs)("header",{className:"grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 border-b p-4 @min-[40rem]/mcp:grid-cols-[auto_minmax(0,1fr)_auto]",children:[(0,n.jsxs)("h2",{className:"flex items-center gap-2 text-xl font-semibold",children:["MCP",(0,n.jsx)("span",{className:"inline-flex size-4",children:l.loading&&(0,n.jsx)(v.A,{role:"status","aria-label":o("正在读取配置…"),className:"size-4 animate-spin text-muted-foreground"})})]}),(0,n.jsxs)("div",{className:"col-start-2 flex flex-wrap justify-end gap-2 @min-[40rem]/mcp:col-start-3 @min-[40rem]/mcp:self-end",children:[(0,n.jsxs)(I.$,{disabled:h,onClick:f,children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),o("添加服务")]}),(0,n.jsx)(I.$,{variant:"outline",disabled:h,onClick:x,children:o("导入 JSON")})]}),(0,n.jsx)("div",{className:"col-span-2 row-start-2 w-full @min-[40rem]/mcp:col-span-1 @min-[40rem]/mcp:col-start-2 @min-[40rem]/mcp:row-start-1 @min-[40rem]/mcp:max-w-80 @min-[40rem]/mcp:justify-self-end @min-[40rem]/mcp:[&_[data-slot=select-trigger]]:mb-0",children:(0,n.jsx)(a8,{id:`${c}-scope`,label:o("配置范围"),value:l.cwd??"",disabled:p,options:[{value:"",label:o("全局")},...d.map(e=>({value:e.cwd,label:`${e.projectName}${e.cwd===t?` \xb7 ${o("当前项目")}`:""}`}))],onChange:e=>{l.setCwd(e||null)}})})]}),l.notice&&!l.check&&(0,n.jsx)("p",{role:"status",className:"shrink-0 break-words border-b px-4 py-2 text-sm",children:o(l.notice)}),l.mcp?.projectTrusted===!1&&(0,n.jsx)("p",{className:"shrink-0 px-4 pt-3 text-sm text-muted-foreground",children:o("本项目尚未受信任,不能执行检查;仍可编辑和保存配置。")}),l.mcp&&l.mcp.diagnostics.length>0&&(0,n.jsx)("div",{className:"max-h-32 shrink-0 space-y-2 overflow-y-auto px-4 pt-3",children:l.mcp.diagnostics.map((e,t)=>(0,n.jsx)(a9,{message:`${e.name?`${e.name}:`:""}${e.message}`},t))}),l.loadError&&(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(a9,{message:l.loadError}),(0,n.jsx)(I.$,{variant:"outline",onClick:l.retry,disabled:l.loading,children:o("重试")})]}),l.loading&&!l.mcp?(0,n.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:o("正在读取配置…")}):l.mcp?(0,n.jsxs)("div",{"aria-busy":l.loading,className:"flex min-h-0 min-w-0 flex-1",children:[l.editor?.kind!=="json"&&l.rows.length>0&&(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar min-h-0 min-w-0 overflow-y-auto",m?"hidden @min-[48rem]/mcp:block @min-[48rem]/mcp:w-56 @min-[48rem]/mcp:shrink-0 @min-[48rem]/mcp:border-r":"flex-1"),children:[!m&&l.error&&(0,n.jsx)("div",{className:"p-4",children:(0,n.jsx)(a9,{message:l.error.message})}),(0,n.jsx)(le,{rows:l.rows,selectedName:g,pending:h,onSelect:e=>{g!==e.name&&l.navigate(()=>e.local?l.startManual(e.name,e.local):l.startInherited(e.name,e.config))}})]}),l.editor?(0,n.jsx)(lr,{editor:l.editor,scopeLabel:u,project:null!==l.displayCwd,projectTrusted:l.mcp.projectTrusted,local:l.mcp.local,inherited:l.mcp.inherited,pending:h,saving:l.pending,error:l.error,check:l.check?.name===g?l.check:null,onDraft:l.updateDraft,onJson:l.updateJson,onPreview:l.previewJson,onOverwrite:e=>l.setEditor(t=>t?.kind==="json"?{...t,overwrite:e}:t),onSave:e=>void l.saveEditor(e),onCancel:()=>void l.navigate(()=>l.setEditor(null)),onRemove:e=>void l.remove(e),onDismissCheck:l.dismissCheck},"manual"===l.editor.kind?g??"new":"json"):0===l.rows.length?(0,n.jsx)(li,{pending:h,onAdd:f,onImport:x}):null]}):null]})}var ll=s(267),lo=s(59605),lc=s(55438);let ld=a.Yj().trim().min(1).max(200),lu=a.Yj().trim().min(1).max(100).nullable(),lm=a.Yj().trim().min(1).max(100).nullable(),lp=a.Yj().trim().min(1).max(200),lh=a.Ik({label:a.Yj().trim().min(1).max(64),value:a.Yj().trim().min(1).max(500)}).strict(),lg=a.Yj().trim().min(1).max(300).nullable(),lf=a.k5(["running","completed","failed","stopped","interrupted"]),lx=a.Ik({taskId:ld,taskKind:lu,taskType:lm,title:lp,info:a.YO(lh).max(12),status:lf,activity:lg,startedAt:rM.k,endedAt:rM.k.nullable()}).strict().superRefine((e,t)=>{"running"===e.status&&null!==e.endedAt&&t.addIssue({code:"custom",message:"running task requires endedAt=null",path:["endedAt"]}),"running"!==e.status&&null===e.endedAt&&t.addIssue({code:"custom",message:"terminal task requires endedAt",path:["endedAt"]})}),lb=a.Ik({tasks:a.YO(lx)}).strict().superRefine((e,t)=>{let s=new Set;for(let[n,r]of e.tasks.entries())s.has(r.taskId)&&t.addIssue({code:"custom",message:"taskId values must be unique",path:["tasks",n,"taskId"]}),s.add(r.taskId)}),lv=a.Ik({kind:a.eu("text"),text:a.Yj(),truncated:a.zM()}).strict(),lw=lo.RX.extend({kind:a.eu("conversation"),truncated:a.zM()}).strict(),ly=a.KC([a.ch(),lv,lw]),lk=a.Ik({taskId:ld,canInterrupt:a.zM(),body:ly}).strict(),lj=lc.mv,lN=a.KC([a.Ik({type:a.eu("snapshot"),snapshot:lk}).strict(),a.Ik({type:a.eu("text_append"),text:a.Yj().min(1)}).strict(),a.Ik({type:a.eu("conversation_event"),event:lj}).strict(),a.Ik({type:a.eu("unavailable")}).strict()]);a.Ik({source:ll.R,taskId:ld,entryId:sZ.Rv}).strict().extend({imageIndex:a.ai().int().nonnegative()}).strict();let lI=a.Ik({source:ll.R,taskId:ld.nullable()}).strict(),lS=a.Ik({snapshot:lk.nullable()}).strict(),lC=a.Ik({source:ll.R,taskId:ld}).strict(),lE=a.Ik({}).strict(),lM=a.Ik({source:ll.R,taskId:ld,event:lN}).strict(),lz=Object.freeze({detailWatch:(0,l.Vc)({path:"task-center/detail-watch",inputSchema:lI,outputSchema:lS}),interrupt:(0,l.Vc)({path:"task-center/interrupt",inputSchema:lC,outputSchema:lE}),detailEvent:(0,l._G)({path:"task-center/detail-event",bodySchema:lM})});var lA=s(45811),l$=s(14510),lR=s(12019),lP=s(86075),lD=s(84571),lT=s(67011);let lO=({className:e,...t})=>(0,n.jsx)(lT.z,{className:(0,C.cn)("relative flex-1 overflow-y-hidden",e),initial:"smooth",resize:"smooth",role:"log",...t}),lL=({className:e,...t})=>(0,n.jsx)(lT.z.Content,{className:(0,C.cn)("flex flex-col gap-8 p-4",e),...t});var lF=s(47744),lB=s(30973),lq=s(14203),l_=s(26575),lW=s(11953);function lY({onOpenChange:e,...t}){let s=(0,r.useRef)(null);return(0,n.jsx)(lF.j,{"data-slot":"hover-card",...t,onOpenChange:(t,n)=>{if(e?.(t,n),n.isCanceled)return;if(t){s.current=n.trigger??null;return}let r=s.current;s.current=null,"escape-key"===n.reason&&r instanceof HTMLElement&&r.ownerDocument.activeElement===r&&r.blur()}})}function lV({...e}){return(0,n.jsx)(lB.Z,{"data-slot":"hover-card-trigger",...e})}function lU({className:e,side:t="bottom",sideOffset:s=4,align:r="center",alignOffset:i=4,...a}){return(0,n.jsx)(lq.D,{"data-slot":"hover-card-portal",children:(0,n.jsx)(l_.p,{align:r,alignOffset:i,side:t,sideOffset:s,className:"isolate z-50",children:(0,n.jsx)(lW.p,{"data-slot":"hover-card-content",className:(0,C.cn)("z-50 w-80 max-w-[calc(100vw-2rem)] origin-(--transform-origin) rounded-lg border border-border bg-popover p-3 text-sm text-popover-foreground shadow-md outline-hidden duration-100 motion-reduce:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...a})})})}let lH=({className:e,...t})=>(0,n.jsx)(nC.Sq,{align:"block-end",className:(0,C.cn)("justify-between gap-1",e),...t}),lK=({className:e,...t})=>(0,n.jsx)("div",{className:(0,C.cn)("flex min-w-0 items-center gap-1",e),...t}),lG=({variant:e="ghost",className:t,size:s,tooltip:i,...a})=>{let l=s??(r.Children.count(a.children)>1?"sm":"icon-sm"),o=(0,n.jsx)(nC.Ik,{className:(0,C.cn)(t),size:l,type:"button",variant:e,...a});if(!i)return o;let c="string"==typeof i?i:i.content,d="string"==typeof i?void 0:i.shortcut,u="string"==typeof i?"top":i.side??"top";return(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:o}),(0,n.jsxs)(tU.ZI,{side:u,children:[c,d&&(0,n.jsx)("span",{className:"ml-2 text-muted-foreground",children:d})]})]})},lJ=a.Ik({input:a.g1(a.Yj(),a.Pq())}).strict(),lQ=a.Ik({output:a.Yj()}).strict(),lX="pideskHelp",lZ=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,l0=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function l1(e){return/^[a-zA-Z0-9_./:@=+-]+$/.test(e)?e:JSON.stringify(e)}let l2=a.Ik({name:a.Yj(),scope:a.eu("global").optional(),source:a.Yj(),kind:a.k5(["package","extension"]),version:a.Yj().nullable(),status:a.k5(["ready","available","disabled","failed"]),updateTag:a.Yj().nullish(),availableVersion:a.Yj().nullish(),updateError:a.Yj().nullish(),operation:a.Ik({action:a.k5(["add","update","del","apply"]),phase:a.k5(["queued","checking","applying","waiting","failed"]),message:a.Yj().nullable()}).strict().nullish(),error:a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:eJ.qf}).strict().nullish()}).strict(),l5=a.Ik({plugins:a.YO(l2),restartRequired:a.zM(),loadError:eJ.qf.nullish()}).strict(),l3=l2.extend({detail:a.g1(a.Yj(),a.Pq())}).strict(),l4=a.Ik({version:a.Yj(),environment:a.k5(["development","production"]),mode:a.k5(["basic","normal"]),cwd:a.Yj(),agentDir:a.Yj(),docsDirectory:a.Yj()}).strict(),l6=null,l8=new WeakMap,l7=new WeakMap,l9=new WeakMap;function oe(e){switch(e.fixed.type){case"user":{let t=lo.lJ.safeParse(e.summary);return{summary:{type:"user",...t.success?t.data:{text:"",images:[]},hasDetail:!1},detail:void 0}}case"assistant":{let t="pi-desk/assistant"===e.fixed.viewKey?lo.Er.safeParse(e.summary):null,s=t?.success?t.data:{text:"",errorMessage:null},n="pi-desk/assistant"===e.fixed.viewKey?lo.Rh.safeParse(e.detail):null;return{summary:{type:"assistant",text:s.text,model:"model"in s?s.model:null,errorMessage:s.errorMessage,status:e.fixed.status,usage:e.fixed.usage,hasDetail:e.fixed.hasDetail},detail:n?.success?{type:"assistant",...n.data}:void 0}}case"tool":{let t={name:e.fixed.viewKey,reasoning:null,inputPreview:null,activity:null},s={status:e.fixed.status,usage:e.fixed.usage,hasDetail:e.fixed.hasDetail};switch(e.fixed.viewKey){case"pi-desk/codemode":{let n=lo.UT.safeParse(e.summary),r=n.success?n.data:t,i=lo.ny.safeParse(e.detail);return{summary:{type:"tool",kind:"codemode",...r,...s},detail:i.success?{type:"tool",kind:"codemode",...i.data}:void 0}}case"pi-desk/pidesk":{let n=lJ.safeParse(e.summary),r=n.success?n.data:{input:{}},i=lQ.safeParse(e.detail);return{summary:{type:"tool",kind:"pidesk",...t,...r,...s},detail:i.success?{type:"tool",kind:"pidesk",output:i.data.output}:void 0}}case"pi-desk/bash-tool":{let n=lo.Qi.safeParse(e.summary),r=n.success?n.data:{...t,timing:null},i=lo.Ok.safeParse(e.detail);return{summary:{type:"tool",kind:"bash",...r,...s},detail:i.success?{type:"tool",kind:"bash",output:i.data.output}:void 0}}case"pi-desk/read":{let n=lo.Gx.safeParse(e.summary),r=n.success?n.data:{...t,path:null},i=lo.Xj.safeParse(e.detail);return{summary:{type:"tool",kind:"read",...r,...s},detail:i.success?{type:"tool",kind:"read",content:i.data.content}:void 0}}case"pi-desk/edit":{let n=lo.aV.safeParse(e.summary),r=n.success?n.data:{...t,path:null},i=lo.Rk.safeParse(e.detail);return{summary:{type:"tool",kind:"edit",...r,...s},detail:i.success?{type:"tool",kind:"edit",contentKind:i.data.kind,content:i.data.content}:void 0}}case"pi-desk/write":{let n=lo.bN.safeParse(e.summary),r=n.success?n.data:{...t,path:null},i=lo.O_.safeParse(e.detail);return{summary:{type:"tool",kind:"write",...r,...s},detail:i.success?{type:"tool",kind:"write",contentKind:i.data.kind,content:i.data.content}:void 0}}default:{let n=lo.Px.safeParse(e.summary),r=n.success?n.data:t,i=lo.Ok.safeParse(e.detail);return{summary:{type:"tool",kind:"generic",...r,...s},detail:i.success?{type:"tool",kind:"generic",output:i.data.output}:void 0}}}}case"bash":{let t=lo.ai.safeParse(e.summary),s=t.success?t.data:{command:e.fixed.viewKey},n=lo.bG.safeParse(e.detail);return{summary:{type:"bash",command:s.command,status:e.fixed.status,hasDetail:e.fixed.hasDetail},detail:n.success?{type:"bash",...n.data}:void 0}}case"custom":{if("pi-desk/compaction"===e.fixed.viewKey){let t=lo.sL.safeParse(e.detail);return{summary:{type:"compaction",hasDetail:e.fixed.hasDetail},detail:t.success?{type:"compaction",...t.data}:void 0}}let t=lo.Rt.safeParse(e.summary);return{summary:{type:"custom",text:(t.success?t.data:{text:""}).text,hasDetail:!1},detail:void 0}}}}function ot(e){return e.temporary||"status"in e.summary&&"running"===e.summary.status}function os(e){return"assistant"===e.summary.type&&("error"===e.summary.status||!!e.summary.errorMessage||(e.detail?.type==="assistant"?e.detail.thinking.trim().length>0:e.summary.hasDetail))}function on(e,t,s){if("compaction"===s.summary.type){or(e,t),e.push({identity:s.identity,user:null,processItems:[],finalAssistant:null,compaction:s,running:ot(s),toolCount:0});return}"user"!==s.summary.type?t.body.push(s):(or(e,t),t.user=s)}function or(e,t){if(!t.user&&0===t.body.length)return;let s=t.user?.identity??t.body[0].identity;e.push(function(e,t,s){let n=function(e){for(let t=e.length-1;t>=0;t-=1){let s=e[t];if("custom"!==s.summary.type){if("assistant"!==s.summary.type)return -1;return s.summary.text.trim()||"pi-desk/assistant"!==s.viewKey?t:-1}}return -1}(s),r=n>=0?s[n]:null,i=[];for(let[e,t]of s.entries()){if(e!==n){("assistant"!==t.summary.type||"pi-desk/assistant"!==t.viewKey||t.summary.text.trim().length>0||os(t))&&i.push({message:t,hideAssistantText:!1});continue}os(t)&&i.push({message:t,hideAssistantText:!0})}return{identity:e,user:t,processItems:i,finalAssistant:r,compaction:null,running:s.some(ot),toolCount:s.filter(e=>"tool"===e.summary.type||"bash"===e.summary.type).length}}(s,t.user,t.body)),t.user=null,t.body=[]}function oi(e,t=!1){let s=function(e){let t=l9.get(e);if(t)return t;let s=[],n={user:null,body:[]},r=new Set,i=[],a=(e[0]?.location.index??0)>0;for(let t of e){if(r.has(t.location.entryId))continue;r.add(t.location.entryId);let e=function(e){let t=l8.get(e);if(t)return t;let s=oe(e),n={identity:`position:${e.location.index}`,position:e.location.index,viewKey:e.fixed.viewKey,snapshot:e,...s,temporary:!1,timestampMs:e.fixed.timestampMs,durable:e,tempId:null};return l8.set(e,n),n}(t);"compaction"===e.summary.type?(i=[],a=!1):"assistant"===t.fixed.type&&(i.push(e),"assistant"===e.summary.type&&null!==e.timestampMs&&(e.summary.text.trim()||"pi-desk/assistant"!==e.viewKey)&&(e={...e,usageCalls:i,usageIncomplete:a},i=[],a=!1)),on(s,n,e)}let l={turns:s,user:n.user,body:n.body};return l9.set(e,l),l}(e.messages),n=[...s.turns],r={user:s.user,body:[...s.body]};for(let[t,s]of e.temporaryMessages.entries())on(n,r,function(e,t){let s=l7.get(e);if(s?.position===t)return s.message;let n=oe(e),r={identity:`position:${t}`,position:t,viewKey:e.fixed.viewKey,snapshot:e,...n,temporary:!0,timestampMs:e.fixed.timestampMs,durable:null,tempId:e.location.tempId};return l7.set(e,{position:t,message:r}),r}(s,e.messages.length+t));or(n,r);let i=n.at(-1);return t&&i&&!i.compaction&&(i.running=!0),n}function oa(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}m`}function ol(e){return 0===e?"$0":e<1e-4?"<$0.0001":`$${e.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function oo(e,t=Date.now(),s="en",n="UTC"){let r=new Date(e),i=new Date(t),a=function(e,t){if(l6?.locale===e&&l6.timeZone===t)return l6;let s="en"===e?"en-US":"zh-CN";return l6={locale:e,timeZone:t,compactTime:new Intl.DateTimeFormat(s,{timeZone:t,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),compactDateTime:new Intl.DateTimeFormat(s,{timeZone:t,month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),fullDateTime:new Intl.DateTimeFormat(s,{timeZone:t,timeZoneName:"shortOffset",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}),dateKey:new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"})}}(s,n);return{compact:a.dateKey.format(r)===a.dateKey.format(i)?a.compactTime.format(r):a.compactDateTime.format(r),full:a.fullDateTime.format(r)}}function oc(e,t,s={}){if("1"!==new URLSearchParams(window.location.search).get("chatScrollDebug"))return;let n=om(t);console.info("[Pi Desk][ChatScroll]",e,{time:Math.round(10*performance.now())/10,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight,distanceFromBottom:t.scrollHeight-t.scrollTop-t.clientHeight,tailSpace:n?op(n):0,tailMinHeight:n?.style.minHeight||null,tailAnchor:n?.dataset.chatTailAnchor??null,...s})}function od(e,t,s){let n=Array.from(e.querySelectorAll(`[${t}]`));return void 0===s?n.at(-1)??null:n.find(e=>e.getAttribute(t)===s)??null}function ou(e){let t,s=(t=e.querySelectorAll("[data-chat-turn]")).item(t.length-1);return s?.hasAttribute("data-chat-logical-tail")?s:null}function om(e){return e.querySelector("[data-chat-tail-space]")}function op(e){let t=e.lastElementChild;return t instanceof HTMLElement?Math.max(0,e.getBoundingClientRect().bottom-t.getBoundingClientRect().bottom):0}function oh(e,t,s,n){let r=e.getBoundingClientRect(),i=e.scrollTop,a=Math.max(0,i+t.getBoundingClientRect().top-r.top-n),l=i+s.getBoundingClientRect().top-r.top;return{targetScrollTop:a,minHeight:Math.max(0,a+e.clientHeight-l-function(e){let t=e.parentElement;if(!t)return 0;let s=Number.parseFloat(getComputedStyle(t).paddingBottom);return Number.isFinite(s)?s:0}(s))}}function og(e){for(let t of e.querySelectorAll("[data-chat-tail-space]"))oc("tail:clear:start",e),t.style.removeProperty("min-height"),delete t.dataset.chatTailSpace,delete t.dataset.chatTailAnchor,delete t.dataset.chatTailOffset,oc("tail:clear:end",e)}function of(e){let t=om(e);if(!t)return;if(t!==ou(e))return void og(e);let s=t.dataset.chatTailAnchor,n=Number.parseFloat(t.dataset.chatTailOffset??"");if(!s||!Number.isFinite(n))return;let r=od(e,"data-chat-scroll-anchor",s);if(!r)return void og(e);let{minHeight:i}=oh(e,r,t,n),a=`${Math.ceil(i)}px`;t.style.minHeight!==a&&(oc("tail:refresh:start",e,{nextMinHeight:a}),t.style.minHeight=a,oc("tail:refresh:end",e,{nextMinHeight:a}))}function ox(e,t,s,n){oc("position:start",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n});let r=n?ou(e):null;if(r&&om(e)===r||og(e),!r){e.scrollTop=Math.max(0,e.scrollTop+t.getBoundingClientRect().top-e.getBoundingClientRect().top-s),oc("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n});return}let{targetScrollTop:i,minHeight:a}=oh(e,t,r,s),l=`${Math.ceil(a)}px`;r.style.minHeight!==l&&(r.style.minHeight=l),r.hasAttribute("data-chat-tail-space")||(r.dataset.chatTailSpace="");let o=t.dataset.chatScrollAnchor;r.dataset.chatTailAnchor!==o&&(o?r.dataset.chatTailAnchor=o:delete r.dataset.chatTailAnchor),r.dataset.chatTailOffset!==String(s)&&(r.dataset.chatTailOffset=String(s)),e.scrollTop=i,oc("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n,minHeight:a})}function ob({active:e=!0}){let{scrollRef:t,state:s}=(0,lT.B)();return(0,r.useEffect)(()=>{let n,r,i=t.current;if(!i||!e)return;let a=null,l=new Set,o=()=>{null===a&&(a=window.requestAnimationFrame(()=>{a=null,of(i)}))},c=new ResizeObserver(o),d=()=>{let e=new Set,t=om(i);if(t)for(let s of t.children)s instanceof HTMLElement&&e.add(s);for(let t of l)e.has(t)||c.unobserve(t);for(let t of e)l.has(t)||c.observe(t);l=e},u=new MutationObserver(()=>{d(),o()}),m=0,p=null,h=null,g=new ResizeObserver(([e])=>{if(!e)return;let{height:t,width:l}=e.contentRect,c=t-(n??t),d=l-(r??l);(n=t,r=l,c||d)?(oc("viewport:resize",i,{difference:c,widthDifference:d,isAtBottom:s.isAtBottom,escapedFromLock:s.escapedFromLock}),c&&(m=c,s.resizeDifference=c),null!==a&&(window.cancelAnimationFrame(a),a=null),of(i),s.isAtBottom&&(s.scrollTop=Math.max(0,s.calculatedTargetScrollTop)),oc("viewport:resize:positioned",i,{difference:c,widthDifference:d}),c&&(null!==p&&window.cancelAnimationFrame(p),null!==h&&window.clearTimeout(h),p=window.requestAnimationFrame(()=>{p=null,h=window.setTimeout(()=>{h=null,s.resizeDifference===c&&(s.resizeDifference=0),m=0},1)}))):o()});return u.observe(i,{attributes:!0,attributeFilter:["data-chat-tail-space","data-chat-logical-tail"],childList:!0,subtree:!0}),g.observe(i),d(),o(),()=>{null!==a&&window.cancelAnimationFrame(a),null!==p&&window.cancelAnimationFrame(p),null!==h&&window.clearTimeout(h),m&&s.resizeDifference===m&&(s.resizeDifference=0),u.disconnect(),c.disconnect(),g.disconnect()}},[e,t,s]),null}function ov(e){let t=[e.user,...e.processItems.map(e=>e.message),e.finalAssistant,e.compaction].filter(e=>null!==e),s=new Set;return t.filter(e=>!s.has(e.identity)&&(s.add(e.identity),!0))}function ow(e,t,s){let n=0;for(let r=t;r<s;r+=1)e[r]?.user&&(n+=1);return n}function oy(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,ow(e,0,s)),r=s,i=0,a=0,l=0;for(;r>0;){let t=e[r-1],s=ov(t).length,o=l<n;if(i>0&&!o&&(i>=30||a+s>200))break;r-=1,i+=1,a+=s,t.user&&(l+=1)}return r}function ok(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,ow(e,s,e.length)),r=s,i=0,a=0,l=0;for(;r<e.length;){let t=e[r],s=ov(t).length,o=l<n;if(i>0&&!o&&(i>=30||a+s>200))break;r+=1,i+=1,a+=s,t.user&&(l+=1)}return r}function oj(e){return{startIndex:oy(e,e.length),endIndex:e.length}}function oN(e,t){let s,n;if(0===e.length)return{startIndex:0,endIndex:0};if(!t)return oj(e);let r=(n=(s=t.lastIndexOf(":"))>0?t.slice(0,s):t,e.findIndex(e=>ov(e).some(e=>e.identity===n)));if(r<0)return oj(e);let i=Math.min(e.length,r+1+10);return{startIndex:oy(e,i),endIndex:i}}function oI({active:e=!0,turns:t,focusTurnIdentity:s,initialAnchor:i,children:a}){let{scrollRef:l}=(0,lT.B)(),[o,c]=(0,r.useState)(()=>({...oN(t,i),turnCount:t.length,focusTurnIdentity:s}));e||o.focusTurnIdentity===s||c({...o,focusTurnIdentity:s});let d=(0,r.useRef)(null),u=(0,r.useRef)(!1),m=(0,r.useMemo)(()=>{if(0===t.length)return{startIndex:0,endIndex:0};if(e&&o.focusTurnIdentity!==s)return oj(t);if(0===o.turnCount&&0===o.endIndex)return oN(t,i);let n=o.endIndex>=o.turnCount;return{startIndex:Math.min(o.startIndex,t.length),endIndex:n?t.length:Math.max(o.startIndex,Math.min(o.endIndex,t.length))}},[e,s,i,t,o]),p=(0,r.useCallback)(e=>{c({...e,turnCount:t.length,focusTurnIdentity:s})},[s,t.length]),h=(0,r.useCallback)(()=>{let e=l.current,t=e?.querySelector("[data-chat-turn]");e&&t?.dataset.chatTurn&&(d.current={turnIdentity:t.dataset.chatTurn,offset:t.getBoundingClientRect().top-e.getBoundingClientRect().top})},[l]),g=(0,r.useCallback)(()=>{if(m.startIndex<=0||u.current)return;let e=oy(t,m.startIndex);if(e>=m.startIndex)return;h();let s=l.current;s&&oc("window:expand-earlier",s,{previousStartIndex:m.startIndex,nextStartIndex:e}),u.current=!0,p({...m,startIndex:e})},[h,p,m,l,t]),f=(0,r.useCallback)(()=>{if(m.endIndex>=t.length||u.current)return;let e=ok(t,m.endIndex);e<=m.endIndex||(u.current=!0,p({...m,endIndex:e}))},[p,m,t]),x=(0,r.useCallback)(e=>{!Number.isSafeInteger(e)||e<0||e>=t.length||e>=m.startIndex&&e<m.endIndex||(e<m.startIndex?p({...m,startIndex:Math.min(e,oy(t,e+1))}):p({...m,endIndex:Math.max(e+1,ok(t,e))}))},[p,m,t]),b=(0,r.useCallback)(()=>{p(oj(t))},[p,t]);(0,r.useLayoutEffect)(()=>{var e;u.current=!1;let t=d.current;if(!t)return;let s=l.current,n=s?(e=t.turnIdentity,Array.from(s.querySelectorAll("[data-chat-turn]")).find(t=>t.dataset.chatTurn===e)??null):null;if(d.current=null,!s||!n)return;let r=n.getBoundingClientRect().top-s.getBoundingClientRect().top,i=r-t.offset;oc("window:anchor-correction:start",s,{turnIdentity:t.turnIdentity,previousOffset:t.offset,nextOffset:r,correction:i}),s.scrollTop+=i,oc("window:anchor-correction:end",s,{turnIdentity:t.turnIdentity,correction:i})},[m.endIndex,m.startIndex,l]),(0,r.useLayoutEffect)(()=>{let s=l.current;if(!s||!e)return;let n=null,r=()=>{(n=null,s.scrollTop<=24&&m.startIndex>0)?g():s.scrollHeight-s.scrollTop-s.clientHeight<=24&&m.endIndex<t.length&&f()},i=()=>{null===n&&(n=window.requestAnimationFrame(r))},a=e=>{e.deltaY<0&&s.scrollTop<=24?g():e.deltaY>0&&i()},o=()=>{s.scrollTop<=24?g():i()};return s.addEventListener("scroll",i,{passive:!0}),s.addEventListener("wheel",a,{passive:!0}),s.addEventListener("touchmove",o,{passive:!0}),()=>{s.removeEventListener("scroll",i),s.removeEventListener("wheel",a),s.removeEventListener("touchmove",o),null!==n&&window.cancelAnimationFrame(n)}},[e,m,g,f,l,t.length]);let v=(0,r.useMemo)(()=>t.slice(m.startIndex,m.endIndex),[m.endIndex,m.startIndex,t]),w=(0,r.useMemo)(()=>({...m,visibleTurns:v,containsTail:m.endIndex>=t.length,revealTurn:x,resetToTail:b}),[m,b,x,t.length,v]);return(0,n.jsx)(n.Fragment,{children:a(w)})}let oS={canMoveUp:!1,canMoveDown:!1,hasNextMessage:!1};function oC(e,t,s,n){let r=0,i=e.length;for(;r<i;){let a=Math.floor((r+i)/2),l=e[a].getBoundingClientRect().top-t;(n?l>=s:l>s)?i=a:r=a+1}return r}function oE(e){return e.user?`${e.user.identity}:user`:null}function oM(e,t,s){let n,r=Array.from(e.querySelectorAll("[data-chat-user-message]")),i=e.getBoundingClientRect().top+12,a=oC(r,i,-2,!0),l=oC(r,i,2,!1),o=s.find(e=>e>=t.startIndex&&e<t.endIndex),c=s.findLast(e=>e>=t.startIndex&&e<t.endIndex),d=0===a?s.findLast(e=>e<(o??t.startIndex))??null:null,u=l>=r.length?s.find(e=>e>(c??t.endIndex-1))??null:null,m=e.scrollHeight-e.scrollTop-e.clientHeight,p=(n=om(e))?op(n):0,h=t.containsTail&&m<=2;return oc("navigation:inspect",e,{containsTail:t.containsTail,tailSpacerHeight:p,atBottom:h,previousMessage:r[a-1]?.dataset.chatUserMessage??null,nextMessage:r[l]?.dataset.chatUserMessage??null,previousOutsideTurnIndex:d,nextOutsideTurnIndex:u}),{previousMessage:r[a-1]??null,nextMessage:r[l]??null,previousOutsideTurnIndex:d,nextOutsideTurnIndex:u,atBottom:h}}function oz({turns:e,window:t}){let{t:s}=(0,b.Bd)("conversation"),{scrollRef:i,scrollToBottom:a,stopScroll:l}=(0,lT.B)(),o=(0,r.useMemo)(()=>e.flatMap((e,t)=>e.user?[t]:[]),[e]),[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(oS),[p,h]=(0,r.useState)(null),g=(0,r.useRef)(null),f=(0,r.useRef)(!1),x=(0,r.useRef)(!1),v=(0,r.useRef)(null),w=(0,r.useRef)(null),y=(0,r.useRef)(!1),k=(0,r.useRef)(null),j=(0,r.useRef)(!1),N=(0,r.useRef)(!1),S=(0,r.useCallback)(e=>{var s;let n,r=(n=!(s=oM(e,t,o)).atBottom,{canMoveUp:null!==s.previousMessage||null!==s.previousOutsideTurnIndex,canMoveDown:n,hasNextMessage:n&&(null!==s.nextMessage||null!==s.nextOutsideTurnIndex)});y.current&&(r.canMoveDown=!1),m(e=>e.canMoveUp===r.canMoveUp&&e.canMoveDown===r.canMoveDown&&e.hasNextMessage===r.hasNextMessage?e:r)},[t,o]),C=(0,r.useCallback)(e=>{null===w.current&&(w.current=window.requestAnimationFrame(()=>{w.current=null,S(e)}))},[S]),E=(0,r.useCallback)(()=>{null!==v.current&&(window.clearTimeout(v.current),v.current=null)},[]),M=(0,r.useCallback)(()=>{E(),x.current||(v.current=window.setTimeout(()=>{v.current=null,f.current=!1,d(!1),null!==w.current&&(window.cancelAnimationFrame(w.current),w.current=null)},2e3))},[E]),z=(0,r.useCallback)(()=>{null!==g.current&&window.clearTimeout(g.current),g.current=null,h(e=>e?.visible?{...e,visible:!1}:e)},[]),A=(0,r.useCallback)(e=>{null!==g.current&&window.clearTimeout(g.current),h({index:e,visible:!0}),g.current=window.setTimeout(()=>{g.current=null,h(e=>e?.visible?{...e,visible:!1}:e)},2e3)},[]),P=(0,r.useCallback)(()=>{let e=i.current;e&&(f.current||m(oS),f.current=!0,d(!0),C(e),M())},[C,M,i]);(0,r.useLayoutEffect)(()=>{let e=i.current;if(!e)return;let s=k.current;if(s){let n=Array.from(e.querySelectorAll("[data-chat-scroll-anchor]")).find(e=>e.dataset.chatScrollAnchor===s.anchor);n&&(k.current=null,l(),ox(e,n,12,t.containsTail))}j.current&&t.containsTail&&(j.current=!1,og(e),Promise.resolve(a({animation:"instant"})).finally(()=>{y.current=!1,N.current&&f.current&&C(e)}))},[C,i,a,l,t.containsTail,t.endIndex,t.startIndex]),(0,r.useLayoutEffect)(()=>{let e=i.current;if(!e)return;N.current=!0;let t=()=>{z(),P()},s=()=>{f.current&&C(e)},n=t=>{t.target===e&&z()},r=e=>{["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(e.key)&&z()};return e.addEventListener("wheel",t,{passive:!0}),e.addEventListener("touchmove",t,{passive:!0}),e.addEventListener("pointerdown",n,{passive:!0}),e.addEventListener("keydown",r),e.addEventListener("scroll",s,{passive:!0}),()=>{e.removeEventListener("wheel",t),e.removeEventListener("touchmove",t),e.removeEventListener("pointerdown",n),e.removeEventListener("keydown",r),e.removeEventListener("scroll",s),null!==w.current&&(window.cancelAnimationFrame(w.current),w.current=null),N.current=!1}},[z,C,i,P]),(0,r.useLayoutEffect)(()=>()=>{E(),null!==g.current&&window.clearTimeout(g.current),y.current=!1,k.current=null,j.current=!1},[E]),(0,r.useLayoutEffect)(()=>{c&&(u.canMoveUp||u.canMoveDown)||(x.current=!1)},[u.canMoveDown,u.canMoveUp,c]);let D=(0,r.useCallback)((s,n)=>{let r=i.current;if(!r)return;P();let c=oM(r,t,o),d="up"===s?c.previousMessage:c.atBottom?null:c.nextMessage;if(d){let s=o.findIndex(t=>oE(e[t])===d.dataset.chatScrollAnchor);s>=0&&A(s+1),y.current=!1,l(),ox(r,d,12,t.containsTail)}else{let i="up"===s?c.previousOutsideTurnIndex:c.nextOutsideTurnIndex;if(null!==i){let s=oE(e[i]);s&&(A(o.indexOf(i)+1),y.current=!1,k.current={anchor:s},t.revealTurn(i))}else"down"===s&&(o.length>0&&A(o.length),n&&(n.disabled=!0),m(e=>e.canMoveDown?{...e,canMoveDown:!1}:e),c.atBottom||y.current||(oc("navigation:bottom:start",r,{containsTail:t.containsTail}),y.current=!0,og(r),t.containsTail?Promise.resolve(a({animation:"instant"})).finally(()=>{y.current=!1,N.current&&f.current&&C(r)}):(j.current=!0,t.resetToTail())))}C(r)},[C,i,a,P,A,l,e,t,o]),T=c&&(u.canMoveUp||u.canMoveDown),O=s(u.hasNextMessage?"nextUserMessage":"bottom");return(0,n.jsxs)(n.Fragment,{children:[p&&o.length>0?(0,n.jsxs)("div",{role:"status","aria-hidden":!p.visible,"aria-label":`${s("userNavigation")} ${p.index} / ${o.length}`,className:`pointer-events-none absolute top-1/2 left-3 z-10 -translate-y-1/2 rounded-lg border bg-background/95 px-2 py-2 shadow-sm transition-opacity duration-150 motion-reduce:transition-none sm:left-4 ${p.visible?"opacity-100":"opacity-0"}`,children:[(0,n.jsxs)("div",{className:"text-center text-sm font-medium tabular-nums",children:[p.index," / ",o.length]}),(0,n.jsx)("div",{className:"relative mx-auto mt-2 h-28 w-0.5 rounded-full bg-border",children:(0,n.jsx)("span",{className:"absolute left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground",style:{top:`${(p.index-1)/Math.max(1,o.length-1)*100}%`}})})]}):null,T?(0,n.jsxs)(tV,{orientation:"vertical",className:"absolute right-3 bottom-4 z-10 rounded-lg shadow-sm sm:right-4","aria-label":s("userNavigation"),onMouseEnter:()=>{x.current=!0,E()},onMouseLeave:()=>{x.current=!1,f.current&&M()},children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"icon",className:"size-10 bg-background/90 backdrop-blur dark:bg-background/90",disabled:!u.canMoveUp,"aria-label":s("previousUserMessage"),title:s("previousUserShort"),onClick:()=>D("up"),children:(0,n.jsx)($.A,{className:"size-4"})}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"icon",className:"size-10 bg-background/90 backdrop-blur dark:bg-background/90",disabled:!u.canMoveDown,"aria-label":O,title:O,onClick:e=>D("down",e.currentTarget),children:(0,n.jsx)(R.A,{className:"size-4"})})]}):null]})}let oA=(0,r.createContext)({basic:!1});function o$({basic:e,onRecover:t,children:s}){let i=(0,r.useMemo)(()=>({basic:e,recover:t}),[e,t]);return(0,n.jsx)(oA.Provider,{value:i,children:s})}function oR(e){return{location:e.snapshot.location,fixed:e.snapshot.fixed,summary:e.snapshot.summary,...void 0===e.snapshot.detail?{}:{detail:e.snapshot.detail}}}class oP{constructor(e,t){this.listeners=new Set,this.pending=null,this.requestEpoch=0,this.disposed=!1,this.basic=!1,this.message=e,this.snapshot=oR(e),this.loader=t,this.detailLoaded=void 0!==this.snapshot.detail||!this.snapshot.fixed.hasDetail}getSnapshot(){return this.snapshot}subscribe(e){if(this.disposed)throw Error("Message Handle has been disposed");return this.listeners.add(e),()=>{this.listeners.delete(e)}}loadDetail(){if(this.detailLoaded)return Promise.resolve(this.snapshot.detail??null);if(!this.snapshot.fixed.hasDetail)return Promise.resolve(null);if(!("entryId"in this.snapshot.location))return Promise.reject(Error("Temporary Message 不能读取 canonical Detail"));if(this.pending)return this.pending;let e=this.requestEpoch,t=this.loader(this.message).then(t=>(this.disposed||e!==this.requestEpoch||(this.detailLoaded=!0,this.snapshot={...this.snapshot,...null===t?{}:{detail:t}},this.notify()),t)).finally(()=>{this.pending===t&&(this.pending=null)});return this.pending=t,t}replace(e,t,s){if(this.disposed)return;let n=oR(e);if(this.snapshot===n)return;let r=this.basic!==s||void 0!==this.snapshot.detail&&void 0===n.detail||this.snapshot.fixed.viewKey!==n.fixed.viewKey||"entryId"in this.snapshot.location&&"entryId"in n.location&&this.snapshot.location.entryId!==n.location.entryId;this.basic=s,this.message=e,this.loader=t,this.snapshot=n,r?(this.requestEpoch+=1,this.pending=null,this.detailLoaded=void 0!==n.detail||!n.fixed.hasDetail):void 0===n.detail&&n.fixed.hasDetail||(this.detailLoaded=!0),this.notify()}dispose(){this.disposed||(this.disposed=!0,this.listeners.clear(),this.requestEpoch+=1,this.pending=null)}notify(){for(let e of[...this.listeners])e()}}function oD({message:e,pluginName:t,contributionName:s,phase:i,error:a,handle:l,fallback:o,onRetry:c}){let{t:d}=(0,b.Bd)("conversation"),[u,m]=(0,r.useState)(l.getSnapshot().detail),[p,h]=(0,r.useState)(!1),[g,f]=(0,r.useState)(null),x=(0,r.useContext)(oA),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),N=a.name,S=a.message,C=a.stack;return(0,r.useEffect)(()=>{console.error("[Pi Desk][MessageView] 消息视图无法展示",{messageId:e.identity,viewKey:e.viewKey,pluginName:t,contributionName:s,phase:i,errorName:N,message:S,stack:C})},[e.identity,e.viewKey,t,s,i,N,S,C]),(0,n.jsxs)("div",{className:"space-y-2","data-message-id":e.identity,children:[o,(0,n.jsx)("div",{role:"alert",className:"rounded-lg border border-destructive/35 bg-muted/30 p-3 text-sm",children:(0,n.jsxs)("div",{className:"flex items-start gap-2",children:[(0,n.jsx)(e_.A,{className:"mt-0.5 size-4 shrink-0 text-destructive"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"font-medium text-destructive",children:d("viewFailed")}),"pi-desk/message-declaration-error"===e.viewKey&&"string"==typeof e.snapshot.summary.text&&e.snapshot.summary.text.length>0?(0,n.jsx)("p",{className:"mt-2 whitespace-pre-wrap break-words text-foreground",children:e.snapshot.summary.text}):null,(0,n.jsxs)(eU,{error:a,children:[(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[t??"Host"," \xb7 ",s??d("reservedView")," \xb7 ",e.viewKey," ","\xb7 ",i]}),(0,n.jsxs)("details",{className:"text-sm",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:d("publicSnapshot")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto rounded-md bg-background p-3 font-mono text-sm whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(l.getSnapshot(),null,2)})]}),!e.temporary&&e.snapshot.fixed.hasDetail&&void 0===u?(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:p,onClick:()=>{h(!0),f(null),l.loadDetail().then(m,e=>{f(e instanceof Error?e.message:d("detailFailed"))}).finally(()=>h(!1))},children:[p?(0,n.jsx)(v.A,{className:"animate-spin"}):null,d("loadDetail")]}):null,g?(0,n.jsx)("p",{className:"text-sm text-destructive [overflow-wrap:anywhere]",children:g}):null,u?(0,n.jsx)("pre",{className:"max-h-48 overflow-auto rounded-md bg-background p-3 font-mono text-sm whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(u,null,2)}):null]}),x.recover?(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",className:"mt-2 mr-2",disabled:w,onClick:()=>{y(!0),x.recover().catch(e=>f(e instanceof Error?e.message:String(e))).finally(()=>y(!1))},children:[w?(0,n.jsx)(v.A,{className:"animate-spin"}):null,d("useBasicPresentation")]}):null,c?(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",className:"mt-2",disabled:k,onClick:()=>{j(!0),f(null),Promise.resolve().then(c).catch(e=>f(e instanceof Error?e.message:String(e))).finally(()=>j(!1))},children:[k?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(es.A,{}),d("retry")]}):null]})]})})]})}function oT({message:e}){let{t}=(0,b.Bd)("conversation");return(0,n.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm","aria-busy":"true",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",role:"status",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),t("viewLoading")]}),(0,n.jsxs)("details",{className:"mt-2",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:t("messageContent")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(e.snapshot.summary,null,2)})]})]})}function oO({message:e,loadDetail:t,defaultView:s}){let{t:i}=(0,b.Bd)("conversation"),a=(0,Q.t4)();(0,Q.So)();let l=(0,r.useContext)(oA),o=(0,r.useRef)(null),c=(0,r.useRef)(null),d=(0,r.useRef)(null),[u,m]=(0,r.useState)({status:"loading"}),[p]=(0,r.useState)(()=>new oP(e,t)),[h,g]=(0,r.useState)(0),f=a.getMessageViewResolution(e.viewKey),x=a.areEntriesInitialized(),v=!f&&a.isRefreshingEntries(),w=f?.status==="winner"?`${e.viewKey}\u0000${f.pluginName}\u0000${f.descriptor.contributionName}\u0000${f.descriptor.priority}`:f?.status==="conflict"?`${e.viewKey}\u0000${f.candidates.map(e=>`${e.pluginName}:${e.descriptor.contributionName}`).join(",")}`:e.viewKey,y=f?.status==="winner"?f.pluginName:null,k=f?.status==="winner"?f.descriptor.contributionName:null,j=y?a.getEntryState(y):null,N=j?.status==="ready"?j.runtime:j?.status,I=e.viewKey.startsWith("pi-desk/")&&"pi-desk/message-declaration-error"!==e.viewKey,S=I&&null===f,C=(0,r.useMemo)(()=>({attempt:h,basic:l.basic,resolutionKey:w,winnerIdentity:N}),[h,l.basic,w,N]),E=(0,r.useMemo)(()=>({kind:"message-view",message:{getSnapshot:()=>p.getSnapshot(),subscribe:e=>d.current!==C?()=>void 0:p.subscribe(()=>{if(d.current===C&&y&&a.getEntryState(y)===j)try{e()}catch(e){m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"update",generation:C})}}),loadDetail:async()=>{if(d.current!==C)throw Error("Message View 已释放");let e=await p.loadDetail();if(d.current!==C)throw Error("Message View 已释放");return e}},reportError(e){d.current===C&&y&&a.getEntryState(y)===j&&m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"report-error",generation:C})}}),[p,C,a,j,y]);if((0,r.useLayoutEffect)(()=>(d.current=C,p.replace(e,t,l.basic),()=>{d.current===C&&(d.current=null)}),[p,t,e,l.basic,C]),(0,r.useEffect)(()=>{let e={};return c.current=e,()=>{c.current===e&&(c.current=null),queueMicrotask(()=>{null===c.current&&p.dispose()})}},[p]),(0,r.useEffect)(()=>{if(l.basic)return void queueMicrotask(()=>m({status:"loading"}));if(!x||S||"pi-desk/message-declaration-error"===e.viewKey||!y||!k||j?.status!=="ready")return;let t=o.current;if(!t)return;let s=new AbortController,n=!0,r=null;queueMicrotask(()=>{n&&m({status:"loading"})});let i=Promise.resolve().then(()=>n?(r=document.createElement("div"),t.append(r),a.mountContribution({pluginName:y,kind:"message-view",contributionName:k,container:r,target:E,signal:s.signal})):null);return i.then(e=>{n&&e&&a.getEntryState(y)===j&&m(e=>"error"===e.status&&e.generation===C?e:{status:"ready",generation:C})},e=>{n&&a.getEntryState(y)===j&&m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"mount",generation:C})}),()=>{n=!1,s.abort(),r?.remove(),i.then(async e=>{await e?.()},()=>void 0)}},[h,S,x,e.viewKey,C,y,k,j,a,E,l.basic]),l.basic)return(0,n.jsx)(n.Fragment,{children:s});if("pi-desk/message-declaration-error"===e.viewKey)return(0,n.jsx)(oD,{message:e,pluginName:"pi-desk",contributionName:"message-declaration-error",phase:"declaration",error:Error(i("declarationFailed")),handle:p});if(!x)return I?(0,n.jsx)(n.Fragment,{children:s}):(0,n.jsx)(oT,{message:e});if(f?.status==="conflict")return(0,n.jsx)(oD,{message:e,pluginName:null,contributionName:null,phase:"priority-conflict",error:Error(i("viewConflict")),handle:p,fallback:I?s:void 0});if(!f)return I?(0,n.jsx)(n.Fragment,{children:s}):v?(0,n.jsx)(oT,{message:e}):(0,n.jsx)(oD,{message:e,pluginName:null,contributionName:null,phase:"missing-view",error:Error(i("viewMissing",{viewKey:e.viewKey})),handle:p,onRetry:async()=>{await a.refreshEntries(),await Promise.all(a.getFailedEntries().map(({pluginName:e})=>a.retryEntry(e)))}});if("error"===u.status&&u.generation===C)return(0,n.jsx)(oD,{message:e,pluginName:f.pluginName,contributionName:f.descriptor.contributionName,phase:u.phase,error:u.error,handle:p,fallback:I?s:void 0,onRetry:()=>{let e=a.getContributionLoadState(f.pluginName,"message-view",f.descriptor.contributionName);(m({status:"loading"}),"failed"!==e.status)?g(e=>e+1):a.retryContribution(f.pluginName,"message-view",f.descriptor.contributionName).then(()=>g(e=>e+1),e=>{m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"load",generation:C})})}});let M="ready"===u.status&&u.generation===C;return(0,n.jsxs)("div",{className:"relative","data-message-id":e.identity,"aria-busy":!M,children:[M?null:I?s:(0,n.jsx)(oT,{message:e}),(0,n.jsx)("div",{ref:o,className:M?void 0:"pointer-events-none invisible absolute inset-x-0 top-0","data-pi-desk-plugin":f.pluginName,"data-pi-desk-kind":"message-view","data-pi-desk-contribution":f.descriptor.contributionName})]})}var oL=s(41934),oF=s(4795),oB=s(33353),oq=s(15948),o_=s(7010),oW=s(64572),oY=s(50153);let oV={src:"/_next/static/media/console.fdac8a18.svg",height:16,width:16,blurWidth:0,blurHeight:0},oU={src:"/_next/static/media/docker.1e10aab8.svg",height:24,width:24,blurWidth:0,blurHeight:0},oH={src:"/_next/static/media/git.f893cb5f.svg",height:32,width:32,blurWidth:0,blurHeight:0},oK={src:"/_next/static/media/html.97f145d3.svg",height:32,width:32,blurWidth:0,blurHeight:0},oG={src:"/_next/static/media/image.69ad851c.svg",height:16,width:16,blurWidth:0,blurHeight:0},oJ={src:"/_next/static/media/javascript.9ef61c53.svg",height:16,width:16,blurWidth:0,blurHeight:0},oQ={src:"/_next/static/media/json.eb8fe488.svg",height:960,width:960,blurWidth:0,blurHeight:0},oX={src:"/_next/static/media/markdown.ee1bbe18.svg",height:32,width:32,blurWidth:0,blurHeight:0},oZ={src:"/_next/static/media/nodejs.2f5d7983.svg",height:32,width:32,blurWidth:0,blurHeight:0},o0={src:"/_next/static/media/typescript.cd97905b.svg",height:16,width:16,blurWidth:0,blurHeight:0},o1={src:"/_next/static/media/yaml.8927dd24.svg",height:24,width:24,blurWidth:0,blurHeight:0},o2=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":oZ,"package-lock.json":oZ,"npm-shrinkwrap.json":oZ,dockerfile:oU,".dockerignore":oU,".gitignore":oH,".gitattributes":oH,".gitmodules":oH})),o5=new Map(Object.entries({ts:o0,mts:o0,cts:o0,tsx:{src:"/_next/static/media/react_ts.3d16336c.svg",height:32,width:32,blurWidth:0,blurHeight:0},js:oJ,mjs:oJ,cjs:oJ,jsx:{src:"/_next/static/media/react.b5a87f7d.svg",height:32,width:32,blurWidth:0,blurHeight:0},json:oQ,jsonc:oQ,jsonl:oQ,yaml:o1,yml:o1,md:oX,mdx:oX,png:oG,jpg:oG,jpeg:oG,gif:oG,webp:oG,avif:oG,bmp:oG,ico:oG,svg:{src:"/_next/static/media/svg.4aa98763.svg",height:32,width:32,blurWidth:0,blurHeight:0},sh:oV,bash:oV,zsh:oV,fish:oV,ps1:oV,bat:oV,cmd:oV,html:oK,htm:oK,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 o3({path:e,className:t}){let s=e.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()??"",r=s.includes(".")?s.slice(s.lastIndexOf(".")+1):"",i=o2.get(s)??(s.startsWith("dockerfile.")?oU:void 0)??o5.get(r);return i?(0,n.jsx)(oY.default,{src:i,alt:"","aria-hidden":"true",width:16,height:16,className:t,unoptimized:!0}):(0,n.jsx)(nI.A,{className:t,"aria-hidden":"true"})}var o4=s(47125),o6=s(9922);let o8=new Map,o7=(0,r.memo)(({children:e,as:t="p",className:s,duration:i=2,spread:a=2})=>{let l,o=((l=o8.get(t))||(l=o6.PY1.create(t),o8.set(t,l)),l),c=(0,r.useMemo)(()=>(e?.length??0)*a,[e,a]);return(0,n.jsx)(o,{animate:{backgroundPosition:"0% center"},className:(0,C.cn)("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",s),initial:{backgroundPosition:"100% center"},style:{"--spread":`${c}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{duration:i,ease:"linear",repeat:1/0},children:e})}),o9=(0,r.createContext)(null),ce=(0,r.memo)(({className:e,isStreaming:t=!1,open:s,defaultOpen:i,onOpenChange:a,duration:l,children:o,...c})=>{let d=i??t,u=!1===i,[m,p]=(0,o4.i)({defaultProp:d,onChange:a,prop:s}),[h,g]=(0,o4.i)({defaultProp:void 0,prop:l}),f=(0,r.useRef)(t),[x,b]=(0,r.useState)(!1),v=(0,r.useRef)(null);(0,r.useEffect)(()=>{t?(f.current=!0,null===v.current&&(v.current=Date.now())):null!==v.current&&(g(Math.ceil((Date.now()-v.current)/1e3)),v.current=null)},[t,g]),(0,r.useEffect)(()=>{!t||m||u||p(!0)},[t,m,p,u]),(0,r.useEffect)(()=>{if(f.current&&!t&&m&&!x){let e=setTimeout(()=>{p(!1),b(!0)},1e3);return()=>clearTimeout(e)}},[t,m,p,x]);let w=(0,r.useCallback)(e=>{p(e)},[p]),y=(0,r.useMemo)(()=>({duration:h,isOpen:m,isStreaming:t,setIsOpen:p}),[h,m,t,p]);return(0,n.jsx)(o9.Provider,{value:y,children:(0,n.jsx)(eV.Nt,{className:(0,C.cn)("not-prose mb-4",e),onOpenChange:w,open:m,...c,children:o})})}),ct=(e,t)=>e||0===t?(0,n.jsx)(o7,{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"]}),cs=(0,r.memo)(({className:e,children:t,getThinkingMessage:s=ct,...i})=>{let{isStreaming:a,isOpen:l,duration:o}=(()=>{let e=(0,r.useContext)(o9);if(!e)throw Error("Reasoning components must be used within Reasoning");return e})();return(0,n.jsx)(eV.R6,{className:(0,C.cn)("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...i,children:t??(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oL.A,{className:"size-4"}),s(a,o),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-4 transition-transform",l?"rotate-180":"rotate-0")})]})})}),cn={cjk:tH.h,code:tK.a,math:tG.D,mermaid:tJ.a},cr=(0,r.memo)(({className:e,children:t,...s})=>(0,n.jsx)(eV.Ke,{className:(0,C.cn)("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...s,children:(0,n.jsx)(tQ.jH,{plugins:cn,children:t})}));ce.displayName="Reasoning",cs.displayName="ReasoningTrigger",cr.displayName="ReasoningContent";var ci=s(52216),ca=s.n(ci);function cl({messages:e,incomplete:t,children:s}){let{t:i}=(0,b.Bd)("conversation"),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)(!1),d=(0,r.useRef)(null),u=(0,r.useRef)(!1);return(0,n.jsxs)(eW.AM,{open:a,onOpenChange:(e,t)=>{if(!e&&"trigger-press"===t.reason&&u.current){u.current=!1,t.cancel();return}e&&"trigger-hover"===t.reason&&o||!e&&"trigger-hover"===t.reason&&(!u.current||d.current?.contains(document.activeElement))?t.cancel():(e?u.current="trigger-hover"===t.reason:"trigger-hover"!==t.reason&&(u.current=!1,c(!0)),l(e))},children:[(0,n.jsx)(eW.Wv,{openOnHover:!o,delay:250,closeDelay:180,onPointerLeave:()=>c(!1),className:"min-w-0 cursor-pointer rounded-sm text-left text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:s}),(0,n.jsxs)(eW.hl,{ref:d,align:"start",side:"top",initialFocus:()=>!u.current,className:(0,C.cn)(ca().panel,"w-[30rem] gap-0 p-2"),children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b px-1 pb-1",children:[(0,n.jsx)(eW.eO,{className:"min-w-0 flex-1 text-xs font-medium text-muted-foreground",children:i(t?"calls.loadedTitle":"calls.title")}),(0,n.jsx)("button",{type:"button","aria-label":i("calls.close"),className:"flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{u.current=!1,c(!0),l(!1)},children:(0,n.jsx)(V.A,{className:"size-3.5"})})]}),a?(0,n.jsx)("div",{className:"min-h-0 overflow-y-auto overscroll-contain",children:(0,n.jsxs)("div",{className:ca().table,children:[(0,n.jsxs)("div",{className:(0,C.cn)(ca().row,"text-muted-foreground"),children:[(0,n.jsx)("span",{children:i("calls.model")}),(0,n.jsx)("span",{children:i("calls.input")}),(0,n.jsx)("span",{children:i("calls.output")}),(0,n.jsx)("span",{children:i("calls.cached")}),(0,n.jsx)("span",{children:i("calls.cost")})]}),e.map(e=>{let t=e.snapshot.fixed;if("assistant"!==t.type)return null;let s="assistant"===e.summary.type?e.summary.model:null,r=t.usage;return(0,n.jsxs)("div",{className:ca().row,children:[(0,n.jsxs)("span",{className:"flex min-w-0 items-center gap-1",children:[(0,n.jsxs)("span",{className:"min-w-0 truncate",title:s?`${s.modelId} \xb7 ${s.provider}`:void 0,children:[s?.modelId||i("calls.unknownModel"),s?.provider?(0,n.jsxs)("span",{className:"text-muted-foreground",children:[" \xb7 ",s.provider]}):null]}),"error"===t.status||"aborted"===t.status?(0,n.jsx)("span",{className:"shrink-0 text-destructive",children:i(`calls.${t.status}`)}):null]}),(0,n.jsx)("span",{children:oa(r.inputTokens)}),(0,n.jsx)("span",{children:oa(r.outputTokens)}),(0,n.jsx)("span",{children:oa(r.cacheReadTokens)}),(0,n.jsx)("span",{children:ol(r.costUsd)})]},e.durable.location.entryId)})]})}):null]})]})}function co({nestedCalls:e}){let{t}=(0,b.Bd)("conversation");return(0,n.jsxs)("section",{className:"border-t px-3 py-3 text-sm",children:[(0,n.jsx)("h4",{className:"mb-2 font-medium",children:t(e.complete?"nestedCalls":"nestedCallsIncomplete")}),(0,n.jsx)("ol",{className:"max-h-[min(24rem,45dvh)] space-y-2 overflow-auto",children:e.calls.map((e,s)=>(0,n.jsxs)("li",{className:"border-b pb-2 last:border-0 last:pb-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,n.jsx)("span",{className:"text-xs tabular-nums text-muted-foreground",children:s+1}),(0,n.jsx)("span",{className:"min-w-0 break-words font-mono font-medium",children:e.name}),(0,n.jsx)("span",{className:"error"===e.status?"text-xs text-destructive":"text-xs text-muted-foreground",children:t(`nestedStatus.${e.status}`)}),void 0===e.durationMs?null:(0,n.jsxs)("span",{className:"ml-auto text-xs tabular-nums text-muted-foreground",children:[e.durationMs," ms"]})]}),e.arguments?(0,n.jsxs)("details",{className:"mt-1",children:[(0,n.jsx)("summary",{className:"min-h-7 cursor-pointer text-xs text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring",children:t("nestedArguments")}),(0,n.jsx)("pre",{className:"max-h-48 overflow-auto whitespace-pre-wrap break-words py-2 font-mono text-sm",children:JSON.stringify(e.arguments,null,2)})]}):null,void 0===e.argumentsBytes?null:(0,n.jsx)("p",{className:"mt-1 text-xs tabular-nums text-muted-foreground",children:t("nestedArgumentsBytes",{count:e.argumentsBytes})}),e.error?(0,n.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-destructive",children:e.error}):null]},s))})]})}function cc({plugin:e}){let{t}=(0,b.Bd)("conversation"),{locale:s}=(0,eQ.i)();return(0,n.jsxs)("div",{className:"min-w-0 space-y-1 py-2 first:pt-0 last:pb-0",role:"listitem",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.name}),(0,n.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:e.version??t("pidesk.unknownVersion")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`pidesk.status.${e.status}`)})]}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[t(`pidesk.kind.${e.kind}`)," \xb7 ",(0,n.jsx)("span",{className:"font-mono",children:e.source})]}),e.updateTag||e.availableVersion?(0,n.jsxs)("p",{className:"flex flex-wrap gap-x-3 text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e.updateTag?(0,n.jsx)("span",{children:t("pidesk.updateChannel",{tag:e.updateTag})}):null,e.availableVersion?(0,n.jsx)("span",{children:t("pidesk.targetVersion",{version:e.availableVersion})}):null]}):null,e.updateError?(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:e.updateError}):null,e.operation?(0,n.jsxs)("p",{className:"[overflow-wrap:anywhere]",children:[t(`pidesk.action.${e.operation.action}`)," \xb7 ",t(`pidesk.phase.${e.operation.phase}`),e.operation.message?` \xb7 ${e.operation.message}`:""]}):null,e.error?(0,n.jsxs)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:[t(`pidesk.errorPhase.${e.error.phase}`)," \xb7 ",(0,eJ.fD)(e.error.message,s)]}):null]})}function cd({result:e}){let{t}=(0,b.Bd)("conversation"),{locale:s}=(0,eQ.i)();return"info"===e.kind?(0,n.jsx)("dl",{className:"grid grid-cols-[max-content_minmax(0,1fr)] gap-x-4 gap-y-2",children:Object.entries(e.data).map(([e,s])=>(0,n.jsxs)("div",{className:"contents",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:t(`pidesk.info.${e}`)}),(0,n.jsx)("dd",{className:"min-w-0 [overflow-wrap:anywhere]",children:"environment"===e?t(`pidesk.environment.${s}`):"mode"===e?t(`pidesk.mode.${s}`):(0,n.jsx)("span",{className:"font-mono",children:s})})]},e))}):"plugin"===e.kind?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{role:"list",children:(0,n.jsx)(cc,{plugin:e.data})}),(0,n.jsx)("p",{className:"mt-3 mb-2 font-medium",children:t("pidesk.pluginDetail")}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono leading-relaxed",children:JSON.stringify(e.data.detail,null,2)})]}):(0,n.jsxs)(n.Fragment,{children:[e.data.restartRequired?(0,n.jsx)("p",{className:"mb-2",children:t("pidesk.restartRequired")}):null,e.data.loadError?(0,n.jsx)("p",{className:"mb-2 text-destructive [overflow-wrap:anywhere]",children:(0,eJ.fD)(e.data.loadError,s)}):null,e.data.plugins.length>0?(0,n.jsx)("div",{className:"divide-y divide-border",role:"list",children:e.data.plugins.map((e,t)=>(0,n.jsx)(cc,{plugin:e},`${e.source}:${t}`))}):(0,n.jsx)("p",{className:"text-muted-foreground",children:t("pidesk.noPlugins")})]})}function cu({identity:e,command:t,output:s,expandable:r,open:i,loading:a,error:l,onOpenChange:o,commandAction:c,outputAction:d}){let{t:u}=(0,b.Bd)("conversation"),m=t.label?[u(t.label),t.name,t.version].filter(Boolean).join(" \xb7 "):t.command,p=null===s?null:function(e,t){let s;if(!["pideskListPlugins","pideskShowPlugin","pideskInfo"].includes(e??""))return null;try{s=JSON.parse(t)}catch{return null}switch(e){case"pideskListPlugins":{let e=l5.safeParse(s);return e.success?{kind:"plugins",data:e.data}:null}case"pideskShowPlugin":{let e=l3.safeParse(s);return e.success?{kind:"plugin",data:e.data}:null}case"pideskInfo":{let e=l4.safeParse(s);return e.success?{kind:"info",data:e.data}:null}default:return null}}(t.label,s);return(0,n.jsxs)(eV.Nt,{open:r&&i,onOpenChange:o,className:"w-full min-w-0 overflow-hidden rounded-lg border border-border bg-card text-sm leading-relaxed","data-message-id":e,"data-chat-scroll-anchor":`${e}:tool`,children:[(0,n.jsxs)(eV.R6,{disabled:!r,"aria-label":r?u(i?"collapseTool":"expandTool",{name:m}):m,className:(0,C.cn)("flex min-h-9 w-full min-w-0 items-center gap-2 px-3 py-1.5 text-left",r&&"cursor-pointer hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"),children:[(0,n.jsx)(nX.A,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,n.jsx)("span",{className:(0,C.cn)("min-w-0 flex-1 truncate font-medium",!t.label&&"font-mono"),title:m,children:m}),r?(0,n.jsx)(eY.A,{className:(0,C.cn)("size-4 shrink-0 text-muted-foreground transition-transform",i&&"rotate-180"),"aria-hidden":"true"}):null]}),(0,n.jsx)(eV.Ke,{className:"h-[var(--collapsible-panel-height)] overflow-hidden transition-[height,opacity] duration-200 ease-out data-starting-style:h-0 data-starting-style:opacity-0 data-ending-style:h-0 data-ending-style:opacity-0 motion-reduce:transition-none",children:(0,n.jsxs)("div",{className:"border-t",children:[(0,n.jsxs)("section",{className:"border-b px-3 py-2","aria-label":u("pidesk.command"),children:[(0,n.jsxs)("div",{className:"mb-1 flex min-h-7 items-center justify-between gap-2",children:[(0,n.jsx)("h4",{className:"font-medium text-muted-foreground",children:u("pidesk.command")}),c]}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono leading-relaxed",children:t.command})]}),(0,n.jsxs)("section",{"aria-label":u("pidesk.output"),children:[(0,n.jsxs)("div",{className:"flex min-h-9 items-center justify-between gap-2 px-3 pt-2",children:[(0,n.jsx)("h4",{className:"font-medium text-muted-foreground",children:u("pidesk.output")}),d]}),(0,n.jsx)("div",{className:"max-h-[min(24rem,50dvh)] overflow-auto px-3 pt-1 pb-3",role:"region","aria-label":u("pidesk.output"),tabIndex:0,children:a?(0,n.jsx)("p",{className:"text-muted-foreground",children:u("loadingResult")}):l?(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:l}):s?p?(0,n.jsx)(cd,{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 cm=s(43769),cp=s.n(cm);let ch="max-h-[min(20rem,45dvh)] overflow-auto [scrollbar-gutter:stable]",cg=(0,r.createContext)(()=>void 0),cf=(0,r.createContext)(null),cx=(0,r.createContext)(null),cb="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 cv({children:e}){let{isAtBottom:t,stopScroll:s}=(0,lT.B)(),i=(0,r.useRef)(t),a=(0,r.useRef)(s);(0,r.useLayoutEffect)(()=>{i.current=t,a.current=s},[t,s]);let l=(0,r.useCallback)(()=>{i.current&&a.current()},[]);return(0,n.jsx)(cg.Provider,{value:l,children:e})}function cw(e,t){let{t:s}=(0,b.Bd)("conversation"),[n,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(null),o=(0,r.useCallback)(async()=>{if(!e.temporary&&e.durable&&e.snapshot.fixed.hasDetail&&void 0===e.detail&&!n){i(!0),l(null);try{await t(e)}catch(e){l(e instanceof Error?e.message:s("detailFailed"))}finally{i(!1)}}},[n,e,t,s]);return{loading:n,error:a,load:o}}function cy(e,t){let[s,n]=(0,r.useState)(!1),i=(0,r.useContext)(cg),{loading:a,error:l,load:o}=cw(e,t),c=!e.temporary&&(e.summary.hasDetail||"tool"===e.summary.type&&!!e.summary.images?.length);return{open:s,expandable:c,loading:a,error:l,handleOpenChange:e=>{c&&(e&&(i(),o()),n(e))}}}function ck({timestampMs:e}){let{locale:t,timeZone:s}=(0,eQ.i)(),r=oo(e,void 0,t,s);return(0,n.jsx)("time",{dateTime:new Date(e).toISOString(),title:r.full,className:"shrink-0",children:r.compact})}function cj({text:e,copyLabel:t,alwaysVisible:s=!1}){let{t:i}=(0,b.Bd)("conversation"),a=(0,X.G)(),[l,o]=(0,r.useState)(!1),c=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{null!==c.current&&window.clearTimeout(c.current)},[]);let d=(0,r.useCallback)(async()=>{let t=!1;try{t=await (0,e9.x)(e)}catch{t=!1}t?(o(!0),null!==c.current&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{c.current=null,o(!1)},1500)):a.error(i("messageCopyFailed"))},[e,a,i]);if(!e.trim())return null;let u=l?i("copied"):t??i("copyMessage");return(0,n.jsx)(t0,{tooltip:u,label:u,size:"icon-sm",className:(0,C.cn)(!s&&cp().messageCopyAction,"text-muted-foreground"),onClick:()=>void d(),children:l?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})})}function cN({usage:e,compactOnly:t=!1}){let{t:s}=(0,b.Bd)("conversation"),r=oa(e.inputTokens),i=oa(e.outputTokens),a=oa(e.cacheReadTokens),l=ol(e.costUsd),o=s("usage",{input:r,output:i,cached:a,cost:l}),c=`${r}/${i}/${a}/${l}`;return t?(0,n.jsx)("span",{className:"shrink-0 font-mono text-xs tabular-nums text-muted-foreground",title:o,"aria-label":o,children:c}):(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("span",{className:cp().usageLabeled,children:o}),(0,n.jsx)("span",{className:cp().usageCompact,children:c})]})}function cI({message:e}){if("assistant"!==e.summary.type||null===e.timestampMs)return null;let t="running"!==e.summary.status?e.summary.text:null;return(0,n.jsxs)(t5,{className:(0,C.cn)(cp().usageToolbar,"mt-1 flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground"),children:[e.usageCalls?.length?(0,n.jsx)(cl,{messages:e.usageCalls,incomplete:e.usageIncomplete??!1,children:(0,n.jsx)(cN,{usage:e.summary.usage})},e.durable.location.entryId):(0,n.jsx)(cN,{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)(cj,{text:t}),null===e.timestampMs?null:(0,n.jsx)(ck,{timestampMs:e.timestampMs})]})]})}function cS({message:e,onAcquireImage:t}){let{t:s}=(0,b.Bd)("conversation"),i="user"===e.summary.type||"tool"===e.summary.type?e.summary.images??[]:[],a=i.length,l=(0,r.useRef)(e);(0,r.useLayoutEffect)(()=>{l.current=e},[e]);let[o,c]=(0,r.useState)(()=>Array.from({length:a},()=>({status:"loading"}))),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(0);return(0,r.useLayoutEffect)(()=>{let e=!0,s=Array.from({length:a},()=>null);for(let n=0;n<a;n+=1){let r=t=>{e?(s[n]=t.release,c(e=>{let s=[...e];return s[n]={status:"ready",url:t.url},s})):t.release()},i=()=>{e&&c(e=>{let t=[...e];return t[n]={status:"error"},t})};try{let e=t(l.current,n);"then"in e?e.then(r).catch(i):r(e)}catch{i()}}return()=>{e=!1,s.forEach(e=>e?.())}},[a,e.identity,e.tempId,e.durable?.location.entryId,t,m]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"mb-2 grid grid-cols-2 gap-2 sm:grid-cols-3",children:i.map((e,t)=>{let r=o[t];return r?.status==="error"?(0,n.jsxs)("button",{type:"button",className:"flex aspect-square min-h-20 cursor-pointer flex-col items-center justify-center gap-2 rounded-md border bg-muted px-2 text-center text-xs text-muted-foreground hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{u(null),c(e=>e.map(e=>"error"===e.status?{status:"loading"}:e)),p(e=>e+1)},children:[(0,n.jsx)("span",{children:s("imageUnavailable")}),(0,n.jsx)("span",{className:"text-sm font-medium text-foreground",children:s("retry",{ns:"common"})})]},`${t}:${e.width}:${e.height}`):r?.status!=="ready"?(0,n.jsx)("div",{className:"grid aspect-square min-h-20 place-items-center rounded-md border bg-muted px-2 text-center text-xs text-muted-foreground",children:s("imageLoading")},`${t}:${e.width}:${e.height}`):(0,n.jsx)("button",{type:"button",className:"group block aspect-square w-full cursor-zoom-in overflow-hidden rounded-md border bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{let e,n;return e=[],n=-1,void(o.forEach((r,a)=>{if("ready"!==r.status)return;a===t&&(n=e.length);let l=i[a];e.push({src:r.url,alt:s("chatImage",{count:a+1}),width:l.width,height:l.height})}),n>=0&&u({slides:e,index:n}))},"aria-label":s("previewImageNumber",{count:t+1}),children:(0,n.jsx)("img",{src:r.url,alt:s("chatImage",{count:t+1}),className:"aspect-square size-full object-cover transition-transform duration-200 group-hover:scale-[1.02] motion-reduce:transition-none"})},`${t}:${e.width}:${e.height}`)})}),d?(0,n.jsx)(ny.k,{mode:"modal",open:!0,slides:d.slides,index:d.index,ariaLabel:s("chatImagePreview"),onClose:()=>u(null),onIndexChange:e=>u(t=>t?{...t,index:e}:t)}):null]})}function cC({text:e}){let{t}=(0,b.Bd)("conversation"),s=(0,r.useRef)(null),[i,a]=(0,r.useState)(!1),[l,o]=(0,r.useState)(null),c=(0,r.useContext)(cg);(0,r.useLayoutEffect)(()=>{let e=s.current;if(!e)return;let t=new ResizeObserver(([t])=>{if(!t||0===t.contentRect.height)return;let s=Number.parseFloat(getComputedStyle(e).lineHeight);o(t.contentRect.height>6*s+1)});return t.observe(e),()=>t.disconnect()},[]);let d=(0,r.useCallback)(()=>{i||c(),a(e=>!e)},[c,i]);return(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("div",{className:(0,C.cn)("relative",!i&&!1!==l&&cp().userTextCollapsed),children:[(0,n.jsx)("p",{ref:s,className:"whitespace-pre-wrap break-words",children:e}),l&&!i?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-secondary to-transparent","aria-hidden":"true"}):null]}),l?(0,n.jsxs)("button",{type:"button","aria-expanded":i,onClick:d,className:"-mb-1 ml-auto mt-1 flex min-h-7 cursor-pointer items-center gap-1 rounded-md px-1 text-xs font-medium text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t(i?"collapse":"expand"),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-3.5 transition-transform",i&&"rotate-180"),"aria-hidden":"true"})]}):null]})}function cE({message:e,onAcquireImage:t}){if("user"!==e.summary.type)throw Error("UserMessage requires a user summary");return(0,n.jsxs)(tX,{from:"user","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:user`,"data-chat-user-message":"",className:(0,C.cn)(cp().copyableMessage,"max-w-[92%] sm:max-w-[84%]"),children:[(0,n.jsxs)(tZ,{className:(0,C.cn)(cp().userText,"group-[.is-user]:px-3 group-[.is-user]:py-2"),children:[e.summary.images.length>0?(0,n.jsx)(cS,{message:e,onAcquireImage:t},`${e.tempId}:${e.durable?.location.entryId??"temporary"}`):null,e.summary.text?(0,n.jsx)(cC,{text:e.summary.text}):null]}),null===e.timestampMs?null:(0,n.jsxs)(t5,{className:"mt-0 justify-end gap-1 text-xs text-muted-foreground",children:[(0,n.jsx)(cj,{text:e.summary.text}),(0,n.jsx)(ck,{timestampMs:e.timestampMs})]})]})}function cM({message:e,text:t}){let s=e.temporary&&"assistant"===e.summary.type&&"running"===e.summary.status;return(0,n.jsxs)(tX,{from:"assistant","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:text`,className:(0,C.cn)(cp().copyableMessage,"max-w-full gap-1"),children:[(0,n.jsx)(tZ,{className:"w-full",children:(0,n.jsx)(rn,{isAnimating:s,mode:s?"streaming":"static",children:t})}),(0,n.jsx)(cI,{message:e})]})}function cz(){let{t:e}=(0,b.Bd)("conversation");return(0,n.jsxs)("div",{role:"status",className:(0,C.cn)(cp().detailText,"flex min-h-9 w-full items-center gap-2 py-1 text-muted-foreground"),children:[(0,n.jsx)(oL.A,{className:"size-4","aria-hidden":"true"}),(0,n.jsx)(o7,{as:"span",duration:1,children:e("thinking")})]})}function cA({content:e,streaming:t}){let{t:s}=(0,b.Bd)("conversation"),{scrollRef:r,contentRef:i}=(0,oW.q)({initial:!!t&&"instant",resize:"instant"}),a=e.length>5e3,l=e.slice(-5e3);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{ref:r,className:"max-h-56 overflow-y-auto pb-2 pr-2 [scrollbar-gutter:stable] sm:max-h-72",children:(0,n.jsx)("div",{ref:i,children:(0,n.jsx)(rn,{isAnimating:t,mode:t?"streaming":"static",children:l},a?e.length:void 0)})}),a?(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 pt-1",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:s("thinkingTruncated",{count:5e3})}),(0,n.jsx)(cj,{text:e,copyLabel:s("copyThinking"),alwaysVisible:!0})]}):null]})}function c$({message:e,detailLoad:t}){let{t:s}=(0,b.Bd)("conversation");if("assistant"!==e.summary.type)return null;let{loading:r,error:i,load:a}=t,l=void 0!==e.detail,o=e.detail?.type==="assistant"?e.detail:null,c=o?.thinking??"",d=c.trim().length>0,u=d&&e.temporary&&"running"===e.summary.status&&0===e.summary.text.trim().length;if(!(d||!l&&e.summary.hasDetail))return null;let m=c||(r?s("thinkingLoading"):i??s("thinkingUnavailable"));return(0,n.jsxs)(ce,{className:"mb-0 w-full",isStreaming:u,onOpenChange:e=>{e&&a()},children:[(0,n.jsx)(cs,{className:(0,C.cn)(cp().detailText,"min-h-9 justify-start py-1"),getThinkingMessage:e=>e?(0,n.jsx)(o7,{as:"span",duration:1,children:s("thinking")}):(0,n.jsx)("span",{children:s("thinkingProcess")})}),(0,n.jsx)(eV.Ke,{className:(0,C.cn)(cb,"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)(cA,{content:m,streaming:u})})})})]})}function cR({message:e}){let{t}=(0,b.Bd)("conversation"),{locale:s}=(0,eQ.i)();if("assistant"!==e.summary.type)return null;let r=function(e,t){let s=e?.trim();if(!s)return null;switch(s.toLowerCase()){case"terminated":return n6.W[t].streamInterrupted;case"request timed out":case"request timed out.":return n6.W[t].requestTimedOut;default:return e}}(e.summary.errorMessage,s)??("error"===e.summary.status?t("modelFailed"):null);return r?(0,n.jsx)("pre",{className:(0,C.cn)(cp().toolOutput,"whitespace-pre-wrap break-words rounded-lg border border-destructive/40 bg-muted p-3 font-sans text-destructive"),children:r}):null}function cP({item:e,onLoadDetail:t}){let{message:s,hideAssistantText:r}=e,i=cw(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)(c$,{message:s,detailLoad:i}),r||!s.summary.text.trim()?null:(0,n.jsx)(cM,{message:s,text:s.summary.text}),(0,n.jsx)(cR,{message:s})]})}function cD({name:e,filePath:t,className:s}){let r=e.toLowerCase().split(".").at(-1)??e.toLowerCase(),i={className:s};switch(r){case"read":return t?(0,n.jsx)(o3,{path:t,...i}):(0,n.jsx)(nI.A,{...i});case"write":return(0,n.jsx)(oF.A,{...i});case"edit":return(0,n.jsx)(oB.A,{...i});case"bash":return(0,n.jsx)(w.A,{...i});case"grep":case"find":return(0,n.jsx)(eh.A,{...i});case"ls":return(0,n.jsx)(eP.A,{...i});case"agent":case"agent_resume":return(0,n.jsx)(eD.A,{...i});default:return(0,n.jsx)(eT.A,{...i})}}function cT(e){let t=e.replaceAll("\\","/");return"/"===t||/^[A-Za-z]:\/$/.test(t)?t:t.replace(/\/+$/,"")}function cO({status:e,timing:t}){let s=t&&"startedAtMs"in t?t.startedAtMs:null,i=t&&"durationMs"in t?t.durationMs:null,[a,l]=(0,r.useState)(()=>Date.now());(0,r.useEffect)(()=>{if("running"!==e||null===s)return;let t=window.setInterval(()=>l(Date.now()),1e3);return()=>window.clearInterval(t)},[s,e]);let o=i??(null===s?null:Math.max(0,a-s));return null===o?null:(0,n.jsx)(n.Fragment,{children:function(e){let t=Math.max(0,Math.floor(e/1e3)),s=t%60,n=Math.floor(t/60);if(0===n)return`${s}s`;let r=n%60,i=Math.floor(n/60);return 0===i?`${r}m ${s}s`:`${i}h ${r}m ${s}s`}(o)})}function cL({message:e,onLoadDetail:t,previewPath:s,onPreviewFile:i,renderDetail:a}){let{t:l}=(0,b.Bd)("conversation");if("tool"!==e.summary.type&&"bash"!==e.summary.type)throw Error("ToolCardShell requires a tool or bash summary");let o=(0,r.useContext)(cf),c=(0,r.useContext)(cx),d=!e.temporary&&"tool"===e.summary.type&&!!e.summary.images?.length,{open:u,expandable:m,loading:p,error:h,handleOpenChange:g}=cy(e,t),{name:f,reasoning:x,inputPreview:v,activity:w,usage:y}="tool"===e.summary.type?{name:e.summary.name,reasoning:e.summary.reasoning,inputPreview:e.summary.inputPreview,activity:e.summary.activity,usage:e.summary.usage}:{name:"bash",reasoning:null,inputPreview:e.summary.command,activity:null,usage:null},k="tool"===e.summary.type&&"bash"===e.summary.kind?e.summary:null,j="error"===e.summary.status,N=!e.temporary&&null!==s&&void 0!==i,I=s?function(e,t){let{compactPath:s,fullPath:n}=function(e,t){let s=cT(e);if(!t)return{compactPath:s,fullPath:s};let n=cT(t);if(!(s.startsWith("/")||/^[A-Za-z]:\//.test(s))){let e=s.replace(/^(?:\.\/)+/,""),t=n.endsWith("/")?n:`${n}/`;return{compactPath:e,fullPath:`${t}${e}`}}let r=n.endsWith("/")?n:`${n}/`,i=/^[A-Za-z]:\//.test(s)&&/^[A-Za-z]:\//.test(n),a=i?s.toLowerCase():s,l=i?r.toLowerCase():r;return a.startsWith(l)?{compactPath:s.slice(r.length),fullPath:s}:{compactPath:s,fullPath:s}}(e,t),r=s.match(/^[A-Za-z]:\//)?.[0]??null??(s.startsWith("/")?"/":""),i=s.slice(r.length).split("/").filter(Boolean),a=i.pop()??s,l=a.lastIndexOf("."),o=i.length>2?`…/${i.slice(-2).join("/")}`:`${r}${i.join("/")}`;return{fileStem:l>0?a.slice(0,l):a,fileExtension:l>0?a.slice(l):"",directory:o||null,fullPath:n}}(s,o):null;return(0,n.jsxs)(eV.Nt,{open:m&&u,onOpenChange:g,className:(0,C.cn)(cp().detailText,"w-full overflow-hidden rounded-lg border bg-muted/45 dark:bg-card",j?"border-destructive":"border-border"),"data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:tool`,children:[(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsxs)(eV.R6,{disabled:!m,className:(0,C.cn)("relative grid min-h-14 w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-2 px-3 py-1.5 text-left",m&&"cursor-pointer hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"),"aria-label":l(m?u?"collapseTool":"expandTool":"tool",{name:f}),children:[(0,n.jsx)(cD,{name:f,filePath:s,className:"col-start-1 row-start-1 size-4 text-muted-foreground"}),(0,n.jsxs)("span",{className:"col-start-2 row-start-1 flex min-h-7 min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"shrink-0 font-mono font-medium",children:f}),x?(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-foreground",children:x}):null,y?(0,n.jsx)(cN,{usage:y,compactOnly:!0}):null]}),(0,n.jsxs)("span",{className:"col-start-3 row-start-1 flex min-h-7 items-center justify-end gap-2",children:[N?(0,n.jsx)("span",{className:"size-7","aria-hidden":"true"}):null,m?(0,n.jsx)("span",{className:"flex size-7 items-center justify-center","aria-hidden":"true",children:(0,n.jsx)(eY.A,{"data-tool-disclosure":"",className:(0,C.cn)("size-4 text-muted-foreground transition-transform",u&&"rotate-180")})}):null]}),I?(0,n.jsxs)("span",{className:(0,C.cn)(cp().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)(cp().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)(cO,{status:k.status,timing:k.timing})}):w?(0,n.jsx)("span",{className:"col-start-3 row-start-2 max-w-36 truncate text-right font-mono text-xs tabular-nums text-muted-foreground",title:w,children:w}):null]}),N?(0,n.jsx)("button",{type:"button",title:l("previewFile"),"aria-label":l("previewFilePath",{path:s}),onClick:()=>i(s),className:(0,C.cn)("absolute top-1.5 flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",m?"right-12":"right-3"),children:(0,n.jsx)(oq.A,{className:"size-4","aria-hidden":"true"})}):null]}),(0,n.jsx)(eV.Ke,{className:cb,children:(0,n.jsxs)("div",{className:"border-t",children:[I?(0,n.jsx)("p",{className:"border-b px-3 py-2 font-mono text-xs text-muted-foreground [overflow-wrap:anywhere]",children:I.fullPath}):null,u&&d&&c?(0,n.jsx)("div",{className:"px-3 pt-3",children:(0,n.jsx)(cS,{message:e,onAcquireImage:c})}):null,a({loading:p,error:h})]})})]})}function cF({children:e,destructive:t=!1}){return(0,n.jsx)("p",{className:(0,C.cn)(cp().detailText,"px-3 py-3",t?"text-destructive":"text-muted-foreground"),children:e})}function cB({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="bash"||e.detail?.type==="tool"&&("generic"===e.detail.kind||"bash"===e.detail.kind||"codemode"===e.detail.kind)?e.detail:null,a=i?.output??"";return t?(0,n.jsx)(cF,{children:r("loadingResult")}):s?(0,n.jsx)(cF,{destructive:!0,children:s}):a?(0,n.jsx)("pre",{role:"region","aria-label":r("toolOutput"),tabIndex:0,className:(0,C.cn)(ch,cp().toolOutput,"whitespace-pre-wrap break-words px-3 py-3 font-mono"),children:a}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(cF,{children:r("emptyResult")})}function cq({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="tool"&&"read"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(cF,{children:r("loadingRead")}):s?(0,n.jsx)(cF,{destructive:!0,children:s}):i?i.content?(0,n.jsx)("pre",{role:"region","aria-label":r("readContent"),tabIndex:0,className:(0,C.cn)(ch,cp().toolOutput,cp().toolCode,"px-3 py-3 font-mono"),children:i.content}):(0,n.jsx)(cF,{children:r("readEmpty")}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(cF,{children:r("readUnavailable")})}function c_({content:e}){let{t}=(0,b.Bd)("conversation");return(0,n.jsx)("div",{role:"region","aria-label":t("editDiff"),tabIndex:0,className:(0,C.cn)(ch,cp().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)(cp().toolCode,cp().toolCodeLine,"block px-3",s),children:e||" "},t)})})}function cW({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="tool"&&"edit"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(cF,{children:r("loadingDiff")}):s?(0,n.jsx)(cF,{destructive:!0,children:s}):i?"diff"===i.contentKind?(0,n.jsx)(c_,{content:i.content}):(0,n.jsx)("pre",{role:"region","aria-label":r("editResult"),tabIndex:0,className:(0,C.cn)(ch,cp().toolOutput,"whitespace-pre-wrap break-words px-3 py-3 font-mono","tool"===e.summary.type&&"error"===e.summary.status&&"text-destructive"),children:i.content}):(0,n.jsx)(cF,{children:r("diffUnavailable")})}function cY({message:e,loading:t,error:s}){let{t:r}=(0,b.Bd)("conversation"),i=e.detail?.type==="tool"&&"write"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(cF,{children:r("loadingWrite")}):s?(0,n.jsx)(cF,{destructive:!0,children:s}):i?"content"!==i.contentKind||i.content?(0,n.jsx)("pre",{role:"region","aria-label":r("content"===i.contentKind?"writeContent":"writeResult"),tabIndex:0,className:(0,C.cn)(ch,cp().toolOutput,"px-3 py-3 font-mono","content"===i.contentKind?cp().toolCode:"whitespace-pre-wrap break-words","output"===i.contentKind&&"tool"===e.summary.type&&"error"===e.summary.status&&"text-destructive"),children:i.content}):(0,n.jsx)(cF,{children:r("writeEmpty")}):(0,n.jsx)(cF,{children:r("writeUnavailable")})}function cV({message:e,onLoadDetail:t}){let{t:s}=(0,b.Bd)("conversation"),{open:r,expandable:i,loading:a,error:l,handleOpenChange:o}=cy(e,t);if("tool"!==e.summary.type||"pidesk"!==e.summary.kind)throw Error("PiDeskToolView requires a pidesk summary");let c=function(e){let t=e.args,s={command:0===Object.keys(e).length?"pidesk":`pidesk ${JSON.stringify(e)}`,label:null,name:null,version:null};if(1!==Object.keys(e).length||!Array.isArray(t)||t.length>32||!t.every(e=>"string"==typeof e))return s;s.command=["pidesk",...t.map(l1)].join(" ");let n=t.some(e=>/\s/.test(e))?"":t.join(" ");if(0===t.length||["--help","-h","plugins","session","plugins --help","plugins -h","session --help","session -h"].includes(n))return{...s,label:lX};if("--version"===n)return{...s,label:"pideskVersion"};if("info"===n)return{...s,label:"pideskInfo"};if("session reload"===n)return{...s,label:"pideskReload"};if(3===t.length&&["--help","-h"].includes(t[2])&&("plugins"===t[0]&&["list","show","install","remove"].includes(t[1])||"session"===t[0]&&"reload"===t[1]))return{...s,label:lX};let r=t[1];if("plugins"!==t[0]||!r||!["list","show","install","remove"].includes(r))return s;let i=null,a=[],l=null,o=null,c=!1;for(let e=2;e<t.length;e+=1){let n=t[e];if("--scope"===n&&null===i&&"global"===t[e+1])i=t[++e];else if("--version"===n&&"install"===r&&null===l&&l0.test(t[e+1]??""))l=t[++e];else if("--tag"===n&&["list","install"].includes(r)&&null===o&&(t[e+1]?.length??0)<=128&&/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(t[e+1]??""))o=t[++e];else if("--check-updates"!==n||"list"!==r||c)if(!("list"!==r&&("show"!==r||0===a.length)&&"node_modules"!==n&&lZ.test(n)))return s;else a.push(n);else c=!0}if(null!==o&&null!==l||"list"!==r&&(0===a.length||null===i))return s;let d=a.length>0?a.join("、"):null;switch(r){case"list":return{...s,label:"pideskListPlugins"};case"show":return{...s,label:"pideskShowPlugin",name:d};case"install":return{...s,label:"pideskInstallPlugin",name:d,version:l};case"remove":return{...s,label:"pideskRemovePlugin",name:d};default:return s}}(e.summary.input),d=e.detail?.type==="tool"&&"pidesk"===e.detail.kind?e.detail.output:null;return(0,n.jsx)(cu,{identity:e.identity,command:c,output:d,expandable:i,open:r,loading:a,error:l,onOpenChange:o,commandAction:(0,n.jsx)(cj,{text:c.command,copyLabel:s("pidesk.copyCommand"),alwaysVisible:!0}),outputAction:d?(0,n.jsx)(cj,{text:d,copyLabel:s("pidesk.copyOutput"),alwaysVisible:!0}):null})}function cU({message:e,onLoadDetail:t}){return(0,n.jsx)(cL,{message:e,onLoadDetail:t,previewPath:null,renderDetail:t=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cB,{message:e,...t}),e.detail?.type==="tool"&&"codemode"===e.detail.kind&&e.detail.nestedCalls?(0,n.jsx)(co,{nestedCalls:e.detail.nestedCalls}):null]})})}function cH({message:e,onLoadDetail:t}){return(0,n.jsx)(cU,{message:e,onLoadDetail:t})}function cK({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)(cL,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(cq,{message:e,...t})})}function cG({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)(cL,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(cW,{message:e,...t})})}function cJ({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)(cL,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(cY,{message:e,...t})})}function cQ({message:e}){let{t}=(0,b.Bd)("conversation");if("custom"!==e.summary.type)throw Error("CustomMessage requires a custom summary");return(0,n.jsx)("div",{"data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:custom`,className:(0,C.cn)(cp().toolOutput,"rounded-lg border-l-2 bg-muted px-3 py-2 text-muted-foreground"),children:e.summary.text||t("emptyMessage")})}function cX({message:e,onLoadDetail:t}){let{t:s}=(0,b.Bd)("conversation");if("compaction"!==e.summary.type)throw Error("CompactionMessage requires a compaction summary");let{open:r,expandable:i,loading:a,error:l,handleOpenChange:o}=cy(e,t),c=e.detail?.type==="compaction"?e.detail:null;return(0,n.jsxs)(eV.Nt,{open:i&&r,onOpenChange:o,className:"w-full py-1","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:compaction`,children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"h-px min-w-3 flex-1 bg-border/70","aria-hidden":"true"}),(0,n.jsxs)(eV.R6,{disabled:!i,"aria-label":i?`${s(r?"collapse":"expand")} ${s("compactionSummary")}`:s(e.temporary?"compactionRunning":"compactionComplete"),className:(0,C.cn)("inline-flex min-h-8 max-w-full items-center gap-2 rounded-full border border-border/70 bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground outline-none transition-colors",i?"hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring":"cursor-default"),children:[e.temporary?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin","aria-hidden":"true"}):(0,n.jsx)(o_.A,{className:"size-3.5","aria-hidden":"true"}),(0,n.jsx)("span",{children:s(e.temporary?"compactionRunning":"compactionComplete")}),i?(0,n.jsx)(eY.A,{className:(0,C.cn)("size-3.5 transition-transform",r&&"rotate-180"),"aria-hidden":"true"}):null]}),(0,n.jsx)("span",{className:"h-px min-w-3 flex-1 bg-border/70","aria-hidden":"true"})]}),(0,n.jsx)(eV.Ke,{className:cb,children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)("div",{className:"rounded-xl border border-border/70 bg-muted/20 px-3 py-3 sm:px-4",children:(0,n.jsx)("div",{role:"region","aria-label":s("compactionSummaryContent"),tabIndex:0,className:"max-h-80 overflow-y-auto pr-2 [scrollbar-gutter:stable]",children:a?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:s("compactionLoading")}):l?(0,n.jsx)("p",{className:"text-sm text-destructive",children:l}):c?.text?(0,n.jsx)(rn,{isAnimating:!1,mode:"static",children:c.text}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:s("compactionUnavailable")})})})})})]})}let cZ=(0,r.memo)(function({item:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:r}){let i=(()=>{switch(e.message.summary.type){case"assistant":return(0,n.jsx)(cP,{item:e,onLoadDetail:t});case"tool":switch(e.message.summary.kind){case"pidesk":return(0,n.jsx)(cV,{message:e.message,onLoadDetail:t});case"read":return(0,n.jsx)(cK,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"edit":return(0,n.jsx)(cG,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"write":return(0,n.jsx)(cJ,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"bash":case"codemode":case"generic":return(0,n.jsx)(cU,{message:e.message,onLoadDetail:t})}case"bash":return(0,n.jsx)(cH,{message:e.message,onLoadDetail:t});case"custom":return(0,n.jsx)(cQ,{message:e.message});case"compaction":return(0,n.jsx)(cX,{message:e.message,onLoadDetail:t});case"user":return(0,n.jsx)(cE,{message:e.message,onAcquireImage:s})}})();return(0,n.jsx)(oO,{message:e.message,loadDetail:t,defaultView:i})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&e.onPreviewFile===t.onPreviewFile&&e.item.hideAssistantText===t.item.hideAssistantText&&c2(e.item.message,t.item.message));function c0({items:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i}){let{scrollRef:a}=(0,lT.B)(),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(e.length),d=(0,r.useRef)(null),[u,m]=(0,r.useState)(()=>Math.min(64,e.length)),p=Math.max(0,e.length-u),h=p>0,g=(0,r.useCallback)(()=>{if(!h)return;let t=a.current,s=l.current?.querySelector("[data-chat-process-item]");t&&s?.dataset.chatProcessItem&&(d.current={identity:s.dataset.chatProcessItem,offset:s.getBoundingClientRect().top-t.getBoundingClientRect().top}),m(t=>Math.min(e.length,t+64))},[h,e.length,a]);return(0,r.useLayoutEffect)(()=>{let t=c.current;c.current=e.length,u>=t&&u<e.length&&m(e.length)},[u,e.length]),(0,r.useLayoutEffect)(()=>{let e=d.current;if(!e)return;let t=a.current,s=Array.from(l.current?.querySelectorAll("[data-chat-process-item]")??[]).find(t=>t.dataset.chatProcessItem===e.identity);if(d.current=null,!t||!s)return;let n=s.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=n-e.offset},[p,a]),(0,r.useEffect)(()=>{let e=a.current,t=o.current;if(!e||!t||!h)return;let s=()=>{let s=e.getBoundingClientRect().top,n=t.getBoundingClientRect().top;return n>=s-96&&n<=s+96},n=e=>{e.deltaY<0&&s()&&g()},r=()=>{s()&&g()};return e.addEventListener("wheel",n,{passive:!0}),e.addEventListener("touchmove",r,{passive:!0}),()=>{e.removeEventListener("wheel",n),e.removeEventListener("touchmove",r)}},[h,g,a]),(0,n.jsxs)("div",{ref:l,children:[h?(0,n.jsx)("div",{ref:o,className:"h-px","data-chat-process-history":!0,"aria-hidden":"true"}):null,e.slice(p).map((r,a)=>{let l=p+a,o=e[l-1],c=o?.message.summary.type==="assistant"&&!o.hideAssistantText&&!!o.message.summary.text.trim();return(0,n.jsx)("div",{"data-chat-process-item":r.message.identity,className:l>0?c?"mt-5":"mt-2":void 0,children:(0,n.jsx)(cZ,{item:r,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i})},r.message.identity)})]})}let c1=(0,r.memo)(function({turn:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i}){let{t:a}=(0,b.Bd)("conversation"),[l,o]=(0,r.useState)(!1),c=(0,r.useContext)(cg),d=(0,Q.t4)();(0,Q.So)();let u=e.processItems.filter(e=>!e.hideAssistantText||"pi-desk/assistant"===e.message.viewKey&&null===d.getMessageViewResolution(e.message.viewKey)),m=e.running||l,p=(0,r.useCallback)(t=>{e.running||(t&&c(),o(t))},[c,e.running]);return 0===u.length?null:(0,n.jsxs)(eV.Nt,{open:m,onOpenChange:p,className:"w-full",children:[(0,n.jsxs)(eV.R6,{className:(0,C.cn)(cp().detailText,"flex min-h-9 w-full cursor-pointer items-center gap-2 py-1 text-left text-muted-foreground hover:text-foreground"),children:[(0,n.jsxs)("span",{className:"flex-1",children:[a("processGroup"),e.toolCount>0?` \xb7 ${a("toolCalls",{count:e.toolCount})}`:""]}),(0,n.jsx)(eY.A,{className:(0,C.cn)("size-4 transition-transform",m&&"rotate-180")})]}),(0,n.jsx)(eV.Ke,{className:cb,children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)(c0,{items:u,onLoadDetail:t,onAcquireImage:s,onPreviewFile:i})})})]})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&e.onPreviewFile===t.onPreviewFile&&e.turn.running===t.turn.running&&e.turn.toolCount===t.turn.toolCount&&c5(e.turn.processItems,t.turn.processItems));function c2(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 c5(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&&c2(e.message,n.message)})}let c3=(0,r.memo)(function({message:e,onLoadDetail:t,onAcquireImage:s}){return(0,n.jsx)(oO,{message:e,loadDetail:t,defaultView:(0,n.jsx)(cE,{message:e,onAcquireImage:s})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&c2(e.message,t.message)),c4=(0,r.memo)(function({message:e,onLoadDetail:t}){return"assistant"!==e.summary.type?null:(0,n.jsx)(oO,{message:e,loadDetail:t,defaultView:(0,n.jsx)(cM,{message:e,text:e.summary.text})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&c2(e.message,t.message)),c6=(0,r.memo)(function({turn:e,cwd:t,logicalTail:s=!1,onLoadDetail:r,onAcquireImage:i,onPreviewFile:a}){if(e.compaction)return(0,n.jsx)("section",{className:(0,C.cn)(!e.running&&"pi-desk-chat-turn-contained"),"data-chat-turn":e.identity,"data-chat-logical-tail":s?"":void 0,children:(0,n.jsx)(oO,{message:e.compaction,loadDetail:r,defaultView:(0,n.jsx)(cX,{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)(c3,{message:e.user,onLoadDetail:r,onAcquireImage:i}):null,(0,n.jsx)(cx.Provider,{value:i,children:(0,n.jsx)(cf.Provider,{value:t,children:(0,n.jsx)(c1,{turn:e,onLoadDetail:r,onAcquireImage:i,onPreviewFile:a})})}),l?(0,n.jsx)(cz,{}):null,e.finalAssistant?(0,n.jsx)(c4,{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&&c2(s.user,n.user)&&c2(s.finalAssistant,n.finalAssistant)&&c2(s.compaction,n.compaction)&&c5(s.processItems,n.processItems))});c6.displayName="L3ConversationTurnView";let c8={running:"statusRunning",completed:"statusCompleted",failed:"statusFailed",stopped:"statusStopped",interrupted:"statusInterrupted"};function c7(e,t){return null!==e&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}function c9(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 de(e){return[e.taskKind,e.taskType].filter(e=>!!e).join(" / ")}function dt(e){switch(e){case"running":return(0,n.jsx)(v.A,{className:"size-4 animate-spin text-foreground"});case"completed":return(0,n.jsx)(ls.A,{className:"size-4 text-status-success"});case"failed":return(0,n.jsx)(lA.A,{className:"size-4 text-destructive"});case"interrupted":return(0,n.jsx)(l$.A,{className:"size-4 text-status-warning"});case"stopped":return(0,n.jsx)(lR.A,{className:"size-4 text-muted-foreground"})}}function ds({info:e}){let{t}=(0,b.Bd)("taskCenter"),s=(0,X.G)(),[i,a]=(0,r.useState)(null);if(0===e.length)return null;let l=(e,n)=>{(0,e9.x)(e.value).then(r=>{r?a(n):s.error(t("copyFailed",{name:e.label}))})};return(0,n.jsx)("div",{"data-task-info-scroll":"",className:"max-h-32 overflow-y-auto pr-1 [scrollbar-gutter:stable]",children:(0,n.jsx)("dl",{className:"flex flex-wrap gap-2",children:e.map((e,s)=>{let r=`${e.label}:${s}:${e.value}`,a=i===r;return(0,n.jsxs)("div",{role:"button",tabIndex:0,"aria-label":t(a?"copied":"copy",{name:e.label}),title:a?t("copiedShort"):t("clickToCopy",{name:e.label}),className:(0,C.cn)("flex min-h-8 min-w-0 max-w-full cursor-pointer items-start gap-2 rounded-md px-2 py-1 text-sm outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",a&&"bg-muted"),onClick:()=>l(e,r),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),l(e,r))},children:[(0,n.jsx)("dt",{className:"shrink-0 pt-0.5 font-medium text-muted-foreground",children:e.label}),(0,n.jsx)("dd",{className:"min-w-0 flex-1 break-words text-foreground",children:e.value}),(0,n.jsx)("span",{className:"shrink-0 pt-0.5 text-muted-foreground","aria-hidden":"true",children:a?(0,n.jsx)(ep.A,{className:"size-3.5 text-status-success"}):(0,n.jsx)(ee.A,{className:"size-3.5"})})]},`${e.label}:${s}`)})})})}function dn({snapshot:e,running:t,runtime:s,cwd:i}){let{t:a}=(0,b.Bd)("taskCenter"),l=(0,r.useMemo)(()=>oi(e,t),[t,e]),o=l.findLast(e=>null!==e.user)??null;return(0,n.jsx)(lO,{className:"h-full min-h-0",initial:"instant",resize:"instant","aria-label":a("conversationDetails"),children:(0,n.jsx)(oI,{turns:l,focusTurnIdentity:o?.identity??null,initialAnchor:null,children:e=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ob,{}),(0,n.jsx)(cv,{children:(0,n.jsxs)(lL,{scrollClassName:"pi-desk-chat-scrollbar",className:"mx-auto min-h-full w-full max-w-3xl gap-6 px-4 pt-3 pb-6 sm:px-6",children:[l.length>0?e.visibleTurns.map((t,r)=>{let a=e.startIndex+r;return(0,n.jsx)(c6,{turn:t,cwd:i,logicalTail:e.containsTail&&a===l.length-1,onLoadDetail:s.loadMessageDetail,onAcquireImage:s.acquireImage},t.identity)}):(0,n.jsx)("div",{className:"grid min-h-48 place-items-center text-sm text-muted-foreground",children:a("noMessages")}),(0,n.jsx)("div",{className:"h-4 shrink-0","aria-hidden":"true"})]})}),(0,n.jsx)(oz,{turns:l,window:e})]})})})}function dr({task:e,runtime:t,cwd:s}){let{t:i}=(0,b.Bd)("taskCenter"),a=(0,r.useSyncExternalStore)(t.subscribe,t.getState,t.getState),l=e?a.details[e.taskId]:void 0,[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),h=async()=>{if(!o)return void c(!0);u(!0),p(null);try{await t.interruptSelected(),c(!1)}catch(e){p(e instanceof Error?e.message:i("interruptFailed"))}finally{u(!1)}};if(!e)return(0,n.jsx)("div",{className:"grid h-full min-h-0 place-items-center px-6 text-center text-sm text-muted-foreground",children:i("selectTask")});let g=de(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:dt(e.status)}),(0,n.jsx)("h3",{className:"min-w-0 break-words text-sm font-semibold",children:g?`${g} \xb7 ${e.title}`:e.title})]}),(0,n.jsxs)("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs",children:[(0,n.jsx)("span",{className:(0,C.cn)("rounded-md px-1.5 py-0.5 font-medium",function(e){switch(e){case"running":return"bg-muted text-foreground";case"completed":return"bg-muted text-status-success";case"failed":return"bg-muted text-destructive";case"interrupted":return"bg-muted text-status-warning";case"stopped":return"bg-muted text-muted-foreground"}}(e.status)),children:i(c8[e.status])}),(0,n.jsx)("span",{className:"text-muted-foreground",children:c9(e,(e,t)=>i(e,{count:t}))}),e.activity?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"text-muted-foreground/60",children:"\xb7"}),(0,n.jsx)("span",{className:"min-w-0 break-words text-muted-foreground",children:e.activity})]}):null]})]}),l?.canInterrupt?(0,n.jsxs)(I.$,{className:"shrink-0",type:"button",size:"sm",variant:o?"destructive":"outline",disabled:d,onClick:()=>void h(),children:[d?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(lR.A,{}),o?i("confirmInterrupt"):i("interrupt")]}):null]})}),m?(0,n.jsx)("p",{role:"alert",className:"shrink-0 border-b bg-muted px-4 py-2 text-sm text-destructive",children:m}):null,e.info.length>0?(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-2",children:(0,n.jsx)(ds,{info:e.info})}):null,(0,n.jsxs)("div",{className:"relative min-h-0 flex-1",children:[l?.body?.kind==="conversation"?(0,n.jsx)(dn,{snapshot:l.body,running:"running"===e.status,runtime:t,cwd:s}):l?.body?.kind==="text"?(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("pre",{className:(0,C.cn)("whitespace-pre-wrap break-words font-mono text-sm leading-[1.6]"),children:l.body.text||i("waitingOutput")})}):l?(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("div",{className:"grid min-h-48 place-items-center px-2 text-center text-sm text-muted-foreground",children:i("noDetails")})}):(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("div",{className:"grid min-h-48 place-items-center px-2 text-center text-sm text-muted-foreground",children:a.error?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("p",{className:"text-destructive",children:a.error}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>t.selectTask(e.taskId),children:[(0,n.jsx)(lP.A,{}),i("retry")]})]}):(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),i("loadingDetail")]})})}),a.refreshing?(0,n.jsxs)("div",{className:"pointer-events-none absolute right-3 top-3 flex items-center gap-2 rounded-md border bg-popover px-2 py-1 text-xs text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-3 animate-spin"}),i("refreshing")]}):null]})]})}function di({source:e,tasks:t,runtime:s,cwd:i}){let{t:a}=(0,b.Bd)("taskCenter"),{locale:l,timeZone:o}=(0,eQ.i)(),c=(0,r.useCallback)(()=>{let e=s.getState();return JSON.stringify([e.open,e.source?.workId??null,e.source?.sessionId??null,e.source?.branchId??null,e.selectedTaskId])},[s]);(0,r.useSyncExternalStore)(s.subscribe,c,c);let d=s.getState(),[u,m]=(0,r.useState)(!1),p=t.find(e=>e.taskId===d.selectedTaskId)??null;(0,r.useEffect)(()=>{d.open&&c7(d.source,e)&&s.reconcileTasks(e,t)},[s,e,d.open,d.source,t]);let h=u&&null!==d.selectedTaskId,g=d.open&&c7(d.source,e);return(0,n.jsx)(eN.YV,{open:g,onOpenChange:e=>{e||s.close()},children:(0,n.jsxs)(eN.hA,{"aria-label":a("title"),showCloseButton:!1,className:"h-[calc(100dvh-2rem)] max-w-[70rem] flex-row bg-background max-lg:h-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",{className:(0,C.cn)("flex min-w-0 flex-1 flex-col border-r bg-sidebar lg:max-w-80",h&&"hidden lg:flex"),children:[(0,n.jsxs)("header",{className:"flex min-h-14 items-center gap-3 border-b px-4 py-3",children:[(0,n.jsx)(lD.A,{className:"size-5 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{children:a("title")}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:a("recordCount",{count:t.length})})]}),(0,n.jsx)(I.$,{className:"lg:hidden",type:"button",variant:"ghost",size:"icon","aria-label":a("close"),onClick:()=>s.close(),children:(0,n.jsx)(V.A,{})})]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-2",children:t.length>0?(0,n.jsx)("div",{className:"space-y-1",children:t.map(e=>{let t=de(e),r=c9(e,(e,t)=>a(e,{count:t})),i=oo(e.startedAt,void 0,l,o);return(0,n.jsxs)("button",{type:"button","aria-current":e.taskId===d.selectedTaskId?"true":void 0,onClick:()=>{var t;return t=e.taskId,void(s.selectTask(t),m(!0))},className:(0,C.cn)("grid min-h-14 w-full cursor-pointer grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-x-2 rounded-lg px-3 py-3 text-left outline-none transition-colors hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",e.taskId===d.selectedTaskId&&"bg-accent text-accent-foreground hover:bg-accent"),children:[(0,n.jsx)("span",{className:"mt-0.5 shrink-0",children:dt(e.status)}),(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsxs)("span",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-baseline gap-x-3",children:[(0,n.jsx)("span",{className:"truncate text-sm font-medium",children:e.title}),(0,n.jsxs)("span",{className:"whitespace-nowrap text-xs tabular-nums text-muted-foreground","aria-label":a("runningTime",{duration:r,time:i.full}),children:[r,(0,n.jsx)("span",{className:"mx-1 text-muted-foreground/50","aria-hidden":"true",children:"\xb7"}),(0,n.jsx)("time",{dateTime:new Date(e.startedAt).toISOString(),children:i.compact})]})]}),t?(0,n.jsx)("span",{className:"mt-1 block truncate text-xs text-muted-foreground",children:t}):null]}),(0,n.jsx)(e7.A,{className:"mt-1 size-4 shrink-0 text-muted-foreground lg:hidden"})]},e.taskId)})}):(0,n.jsx)("div",{className:"grid min-h-48 place-items-center text-sm text-muted-foreground",children:a("noTasks")})})]}),(0,n.jsx)("div",{className:(0,C.cn)("min-w-0 flex-1",!h&&"hidden lg:block"),children:(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-12 items-center gap-2 border-b bg-muted/10 px-3 lg:hidden",children:[(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":a("back"),onClick:()=>m(!1),children:(0,n.jsx)(A.A,{})}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-center text-xs text-muted-foreground",children:p?.title??a("detail")}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"icon","aria-label":a("close"),onClick:()=>s.close(),children:(0,n.jsx)(V.A,{})})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1",children:(0,n.jsx)(dr,{task:p,runtime:s,cwd:i},p?.taskId??"no-task")})]})}),(0,n.jsx)(I.$,{className:"absolute right-4 top-3 z-10 hidden lg:inline-flex",type:"button",variant:"ghost",size:"icon","aria-label":a("close"),onClick:()=>s.close(),children:(0,n.jsx)(V.A,{})})]})})}function da({source:e,cwd:t,tasks:s,runtime:r,variant:i}){let{t:a}=(0,b.Bd)("taskCenter"),l=s.filter(e=>"running"===e.status),o=l[0],c=()=>{r.open(e,(s.find(e=>"running"===e.status)??s[0]??null)?.taskId??null)};return"footer"===i?s.length>0?(0,n.jsx)(lG,{tooltip:a("title"),"aria-label":a("open"),onClick:c,children:(0,n.jsx)(lD.A,{className:"size-4"})}):(0,n.jsx)(n.Fragment,{}):"menu"===i?(0,n.jsxs)(K._2,{onClick:c,children:[(0,n.jsx)(lD.A,{className:"size-4"}),a("title")]}):(0,n.jsxs)(n.Fragment,{children:[o?(0,n.jsxs)("button",{type:"button",className:"mb-2 flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-md border bg-muted px-2.5 text-left text-sm text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",onClick:c,"aria-label":`${a("open")}, ${a("runningCount",{count:l.length})}`,children:[(0,n.jsx)(v.A,{className:"size-3.5 shrink-0 animate-spin text-foreground"}),(0,n.jsx)("span",{className:"shrink-0 font-medium text-foreground",children:a("runningCount",{count:l.length})}),(0,n.jsxs)("span",{className:"min-w-0 flex-1 truncate",children:[o.title,o.activity?` \xb7 ${o.activity}`:""]}),(0,n.jsx)(e7.A,{className:"size-3.5 shrink-0"})]}):null,(0,n.jsx)(di,{source:e,tasks:s,runtime:r,cwd:t})]})}function dl({source:e,cwd:t,pluginState:s,runtime:i,variant:a}){let l=(0,r.useMemo)(()=>{let e=lb.safeParse(s);return e.success?e.data.tasks:[]},[s]);return(0,n.jsx)(da,{source:e,cwd:t,tasks:l,runtime:i,variant:a})}var dc=s(74577),dd=s(85232);function du(e){return`${e.location.index}:${e.location.entryId}`}let dm={user:["viewKey","hasDetail"],assistant:["viewKey","status","hasDetail","usage"],tool:["viewKey","status","hasDetail","usage"],bash:["viewKey","status","hasDetail"],custom:["viewKey","hasDetail"]};function dp(e,t,s){if(!t)return e;let n={...e,...t};return"summary"===s?lo.Hf.parse(n):lo.D8.parse(n)}function dh(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 dg(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 dh(r,`${r.value}${s}`),lo.Hf.parse(n)}if(!Array.isArray(r.value))throw Error("Increment target is not an array");return dh(r,[...r.value,...s]),lo.Hf.parse(n)}function df(e,t,s){let n=new Map(e.messages.filter(e=>void 0!==e.detail).map(e=>[du(e),e]));return{messages:t.map(e=>{let t=n.get(du(e));return e.fixed.hasDetail&&t&&t.fixed.type===e.fixed.type&&t.fixed.viewKey===e.fixed.viewKey&&void 0!==t.detail?lo.mj.parse({...e,detail:t.detail}):e}),temporaryMessages:[...s]}}function dx(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,dm[s.type],`${s.type} fixed`),lo.q5.parse({...s,...n})):s),i=dp(e.summary,t.summary,"summary"),a=e.detail;if(void 0!==t.detail||Object.keys(t.increments??{}).some(e=>"detail"===(0,dd.U)(e).root)){if(t.fixed?.hasDetail===!1)throw Error("Realtime detail cannot be updated while explicitly clearing hasDetail");r.hasDetail||(r=lo.q5.parse({...r,hasDetail:!0}))}for(let[e,s]of(t.detail&&(a=dp(a??{},t.detail,"detail")),Object.entries(t.increments??{}))){let t=(0,dd.U)(e);"summary"===t.root?i=dg(i,t.segments,s):a=dg(a??{},t.segments,s)}return r.hasDetail||(a=void 0),lo.s4.parse({location:e.location,fixed:r,summary:i,...void 0===a?{}:{detail:a}})}(n[s],t),{...e,temporaryMessages:n}}if("message_discard"===t.type)return{...e,temporaryMessages:e.temporaryMessages.filter(e=>e.location.tempId!==t.location.tempId)};if(t.durable.index!==e.messages.length)throw Error(`Conversation commit index is not continuous: expected ${e.messages.length}, received ${t.durable.index}`);if(e.messages.some(e=>e.location.entryId===t.durable.entryId))throw Error(`Conversation commit entryId already exists: ${t.durable.entryId}`);let{detail:n,fixed:r,...i}=e.temporaryMessages[s],a=lo.mj.parse({...i,location:t.durable,fixed:{...r,timestampMs:t.fixed.timestampMs},...r.hasDetail&&void 0!==n?{detail:n}:{}});return{messages:[...e.messages,a],temporaryMessages:e.temporaryMessages.filter(e=>e.location.tempId!==t.location.tempId)}}function db(e,t){let s=e.messages.findIndex(e=>e.location.index===t.index&&e.location.entryId===t.entryId);if(s<0)throw Error(`Conversation detail target was not found: ${t.index}/${t.entryId}`);let n=e.messages[s];if(null!==t.detail&&!n.fixed.hasDetail)throw Error("Message without hasDetail cannot accept detail");let r=[...e.messages];return r[s]=lo.mj.parse({...n,...null===t.detail?{detail:void 0}:{detail:t.detail}}),{...e,messages:r}}function dv(e,t){return e.taskId!==t.taskId||e.body?.kind!=="conversation"||t.body?.kind!=="conversation"?t:lk.parse({...t,body:{kind:"conversation",truncated:t.body.truncated,...df(e.body,t.body.messages,t.body.temporaryMessages)}})}var dw=s(7237);function dy(e){return(0,ed.B)({msg:dc.U["zh-CN"][e],i18n:{key:`taskCenter:${e}`}})}let dk=Object.freeze({open:!1,source:null,selectedTaskId:null,details:{},loading:!1,refreshing:!1,error:null});function dj(e,t){return e===t||null!==e&&null!==t&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}var dN=s(15381),dI=s(94853);let dS=s0.rh,dC=s0.eC,dE=a.Ik({workId:dN.eW,cwd:dN.ik}).strict(),dM=dE.extend({path:dS}).strict(),dz=dE.extend(s0.Nu.shape).strict(),dA=dI.Ot.request.safeExtend({workId:dN.eW});dI.Ot.response;let d$=s0.p$,dR=dE.extend({path:dC,imagePreviewMode:d$}).strict();var dP=s(46117),dD=s.n(dP);function dT({mobile:e,open:t,sidebar:s,children:i,onClose:a}){let{t:l}=(0,b.Bd)("workbench"),o=(0,E.fk)(),c=(0,r.useRef)(288);return((0,r.useLayoutEffect)(()=>{if(e)return;let s=requestAnimationFrame(()=>{o.current?.resize(t?c.current:0)});return()=>cancelAnimationFrame(s)},[e,t,o]),e)?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button","aria-label":l("closeSessionMenu"),"aria-hidden":!t,tabIndex:t?0:-1,onClick:a,className:(0,C.cn)(dD().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)(dD().drawer,"fixed inset-y-0 left-0 z-50 flex w-[min(86vw,320px)] flex-col border-r bg-sidebar shadow-2xl",!t&&"pointer-events-none"),children:s}),(0,n.jsx)("div",{className:"flex min-h-0 min-w-0 flex-1",inert:t||void 0,children:i})]}):(0,n.jsxs)(S.HK,{orientation:"horizontal",disableCursor:!0,className:(0,C.cn)(dD().panelGroup,"pi-desk-workbench-resize-group min-h-0 min-w-0 flex-1"),onLayoutChanged:(e,s)=>{if(!s.isUserInteraction||!t)return;let n=o.current?.getSize().inPixels;void 0!==n&&(c.current=n)},children:[(0,n.jsx)(S.wV,{id:"work-session-sidebar",panelRef:o,defaultSize:288,minSize:224*!!t,maxSize:480*!!t,disabled:!t,"aria-hidden":!t||void 0,inert:!t||void 0,className:"flex h-full min-h-0 min-w-0 !overflow-hidden bg-sidebar",children:(0,n.jsx)("div",{className:"flex h-full w-full min-w-[224px] flex-col border-r",children:s})}),(0,n.jsx)(S.WM,{withHandle:!0,"aria-label":l("resizeSessionList"),"aria-hidden":!t||void 0,disabled:!t,className:(0,C.cn)("cursor-col-resize",!t&&"w-0 pointer-events-none opacity-0")}),(0,n.jsx)(S.wV,{id:"work-session-content",minSize:360,className:"flex h-full min-h-0 min-w-0 !overflow-hidden",children:i})]})}let dO=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 dL=s(5011),dF=s(42515),dB=s(91399),dq=s(95826),d_=s(37975),dW=s(56592),dY=s(31343);function dV(e,t){return(0,ed.B)({msg:dY.R["zh-CN"][e],i18n:{key:`workbench:${e}`,...t?{params:t}:{}}})}function dU(e){let{workId:t,sessionId:s,branchId:n}=e.source;return JSON.stringify([t,s,n,e.cwd])}function dH(e,t,s){return`${dU(e)}\u0000${s}\u0000${t}`}class dK{peek(e,t,s){let n=this.images.get(dH(e,t,s));return!n||0===n.references&&Date.now()-n.unusedAt>=6e4?null:n.url}get(e,t,s){this.trim();let n=dH(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(dU(e)))throw Error("工作会话来源已变化");let r=dH(e,t,s),i=this.images.get(r);if(i)return this.acquire(r,i);let a={url:URL.createObjectURL(n),size:n.size,references:0,unusedAt:Date.now()};return this.images.set(r,a),this.acquire(r,a)}invalidate(e,t,s){this.remove(dH(e,t,s))}reconcileWorkSessions(e){for(let t of(this.validSources=new Set(e.map(e=>dU({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 dG{constructor(e,t,s=()=>void 0){this.biz=e,this.gitBiz=t,this.onNotice=s,this.standaloneImages=new dK,this.listeners=new Set,this.workspaces=new Map,this.sources=new Map,this.previewDirectories=new Map,this.expandedWorkId=null,this.revision=0,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.getRevision=()=>this.revision}getWorkspace(e){let t=e?this.workspaces.get(e):null;return t?{...t.files.state,cwd:t.files.cwd,windowOpen:t.windowOpen,chatWidthPercent:t.chatWidthPercent,activePane:t.activePane}:null}getFileRuntime(e){return this.workspaceFor(e).files}getExpandedWorkId(){return this.expandedWorkId}getDirectories(e){return this.previewDirectories.get(e)?.directories??[]}getDirectory(e){let t=this.previewDirectories.get(e);if(!t)throw Error(dV("sourceChanged"));return t.selectedDirectory}applyPreviewDirectories(e,t){let s=this.sources.get(e.workId);if(!s||s.sessionId!==e.sessionId||s.branchId!==e.branchId)return;let n=this.previewDirectories.get(e.workId),r=new Map([[(0,d_.Yj)(s.cwd),s.cwd]]);for(let e of t.directories){let t=(0,d_.Yj)(e);r.has(t)||r.set(t,e)}let i=t.defaultDirectory?r.get((0,d_.Yj)(t.defaultDirectory))??null:null,a=(n.defaultDirectory?(0,d_.Yj)(n.defaultDirectory):null)!==(i?(0,d_.Yj)(i):null)?i??s.cwd:r.get((0,d_.Yj)(n.selectedDirectory))??s.cwd,l=[...r.values()];if(n.defaultDirectory===i&&n.selectedDirectory===a&&n.directories.length===l.length&&n.directories.every((e,t)=>e===l[t]))return;this.previewDirectories.set(e.workId,{directories:l,defaultDirectory:i,selectedDirectory:a});let o=this.workspaces.get(e.workId);if(o){for(let[e,t]of o.roots)r.has(e)||(t.unsubscribe(),t.files.dispose(),o.roots.delete(e));this.switchFiles(e.workId,o)}this.publish()}selectDirectory(e,t){let s=this.previewDirectories.get(e);if(!s)throw Error(dV("sourceChanged"));let n=s.directories.find(e=>(0,d_.Yj)(e)===(0,d_.Yj)(t));if(!n)throw Error(dV("sourceChanged"));if(s.selectedDirectory===n)return;s.selectedDirectory=n;let r=this.workspaces.get(e);r&&this.switchFiles(e,r),this.publish()}reconcileWorkSessions(e){this.standaloneImages.reconcileWorkSessions(e);let t=new Map(e.map(({workId:e,cwd:t,sessionId:s,branchId:n})=>[e,{workId:e,cwd:t,sessionId:s,branchId:n}])),s=!1;for(let[e,n]of this.sources){let r=t.get(e);if(r?.cwd===n.cwd&&r.sessionId===n.sessionId&&r.branchId===n.branchId)continue;let i=this.workspaces.get(e);i&&(this.disposeLayout(i),this.workspaces.delete(e)),this.previewDirectories.delete(e),s=!0,this.expandedWorkId===e&&(this.expandedWorkId=null)}for(let[e,s]of(this.sources.clear(),t))this.sources.set(e,s),this.previewDirectories.has(e)||this.previewDirectories.set(e,{directories:[s.cwd],defaultDirectory:null,selectedDirectory:s.cwd});s&&this.publish()}ensureRoot(e){return this.getFileRuntime(e).ensureRoot()}ensureDirectory(e,t){return this.getFileRuntime(e).ensureDirectory(t)}setExpandedPaths(e,t){this.getFileRuntime(e).setExpandedPaths(t)}setTreeScrollTop(e,t){this.workspaces.get(e)?.files.setTreeScrollTop(t)}refreshTree(e){this.getFileRuntime(e).refreshTree()}setSearchQuery(e,t){this.getFileRuntime(e).setSearchQuery(t)}search(e,t){return this.getFileRuntime(e).search(t)}openFile(e,t){let s=this.workspaceFor(e);s.windowOpen=!0,s.activePane="files",s.files.openFile(t)}async revealFile(e,t){await this.getFileRuntime(e).revealFile(t)}activateFile(e,t){this.workspaces.get(e)?.files.state.tabs.includes(t)&&this.openFile(e,t)}closeFile(e,t){this.closeTabs(e,t,"current")}closeTabs(e,t,s){this.workspaces.get(e)?.files.closeTabs(t,s)}hideWindow(e){let t=this.workspaces.get(e);t?.windowOpen&&(t.windowOpen=!1,t.activePane="chat",this.expandedWorkId===e&&(this.expandedWorkId=null),this.publish())}showWindow(e){let t=this.workspaceFor(e),{tabs:s,activeDiff:n,activePath:r}=t.files.state;(s.length||n||this.expandedWorkId===e)&&(t.windowOpen=!0,t.activePane="files",this.publish(),!n&&r&&t.files.ensureDocument(r))}setChatWidthPercent(e,t){let s=this.workspaces.get(e);!s||!Number.isFinite(t)||t<=0||t>=100||.001>Math.abs(s.chatWidthPercent-t)||(s.chatWidthPercent=t,this.publish())}setActivePane(e,t){let s=this.workspaces.get(e);s&&s.activePane!==t&&(s.activePane=t,this.publish())}expandWindow(e){this.expandedWorkId=e,this.showWindow(e)}collapseExpandedWindow(){if(!this.expandedWorkId)return;let e=this.workspaces.get(this.expandedWorkId);this.expandedWorkId=null,!e||e.files.state.tabs.length||e.files.state.activeDiff||(e.windowOpen=!1,e.activePane="chat"),this.publish()}reloadFile(e,t){this.workspaces.get(e)?.files.reloadFile(t)}openDiff(e,t,s){let n=this.workspaceFor(e);n.windowOpen=!0,n.activePane="files",n.files.openDiff(t,s)}closeDiff(e){this.closeTabs(e,null,"current")}reloadDiff(e){this.workspaces.get(e)?.files.reloadDiff()}setDiffViewMode(e,t){this.workspaces.get(e)?.files.setDiffViewMode(t)}setDiffWrapLines(e,t){this.workspaces.get(e)?.files.setDiffWrapLines(t)}setDiffCollapseUnchanged(e,t){this.workspaces.get(e)?.files.setDiffCollapseUnchanged(t)}handleGitBranchChanged(e,t){for(let s of this.workspaces.values())for(let n of s.roots.values())n.files.cwd===e&&n.files.handleGitBranchChanged(t)}saveEditorState(e,t,s){this.workspaces.get(e)?.files.saveEditorState(t,s)}setWrapLines(e,t,s){this.workspaces.get(e)?.files.setWrapLines(t,s)}setTextViewMode(e,t,s){this.workspaces.get(e)?.files.setTextViewMode(t,s)}dispose(){for(let e of(this.standaloneImages.dispose(),this.workspaces.values()))this.disposeLayout(e);this.workspaces.clear(),this.sources.clear(),this.previewDirectories.clear(),this.expandedWorkId=null,this.listeners.clear()}workspaceFor(e){if(!this.sources.get(e))throw Error(dV("sourceChanged"));let t=this.workspaces.get(e);if(t)return t;let s={files:this.createFiles(e,this.getDirectory(e)),roots:new Map,windowOpen:!1,chatWidthPercent:50,activePane:"files"};return this.attachRoot(e,s,s.files),this.workspaces.set(e,s),s}createFiles(e,t){let s={workId:e,cwd:t};return new dW.h(t,{list:(e,t)=>this.biz.list({...s,path:e},t),search:(e,t)=>this.biz.search({...s,...e},t),get:(e,t,n)=>this.biz.get({...s,path:e,imagePreviewMode:t},n),diff:(e,t,n)=>this.gitBiz.getDiff({...s,repositoryRoot:e,path:t},n)},{imagePreviewMode:rm.Wq,htmlPreview:!0,onNotice:this.onNotice,reveal:async(e,t)=>{await this.biz.reveal({...s,path:e,..."directory"===t?{targetType:t}:{}})}})}attachRoot(e,t,s){let n=s.subscribe(()=>{t.files===s&&(s.state.activePath||s.state.activeDiff||this.expandedWorkId===e||(t.windowOpen=!1,t.activePane="chat"),this.publish())});t.roots.set((0,d_.Yj)(s.cwd),{files:s,unsubscribe:n})}switchFiles(e,t){let s=this.getDirectory(e),n=(0,d_.Yj)(s);if((0,d_.Yj)(t.files.cwd)===n)return;let r=t.roots.get(n);if(!r){let i=this.createFiles(e,s);this.attachRoot(e,t,i),r=t.roots.get(n)}t.files=r.files,r.files.state.activePath||r.files.state.activeDiff||this.expandedWorkId===e||(t.windowOpen=!1,t.activePane="chat")}disposeLayout(e){for(let t of e.roots.values())t.unsubscribe(),t.files.dispose();e.roots.clear()}publish(){for(let e of(this.revision+=1,this.listeners))e()}}var dJ=s(70657);function dQ(e,t,s,n){t.reconcileWorkSessions(s,n,s.flatMap(({workId:t})=>e.getDirectories(t).map(e=>({workId:t,cwd:e}))))}var dX=s(90504),dZ=s(46487),d0=s(97921),d1=s(36510);let d2='data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/%3E';function d5({target:e,paths:t,index:s,onIndexChange:i,biz:a,images:l}){let{t:o}=(0,b.Bd)("workbench"),[c,d]=(0,r.useState)({}),u=(0,r.useRef)(new Map),m=t[s],p=c[m],h=(0,rm.Wq)(),g=l.peek(e,m,h),f=p?.status==="ready"||!p&&null!==g;return(0,r.useLayoutEffect)(()=>{let e=u.current;return()=>{for(let t of e.values())t.release();e.clear()}},[]),(0,r.useLayoutEffect)(()=>{let t,s=u.current;if(p?.status==="error"||s.has(m))return;let n=l.get(e,m,h);if(n)return void s.set(m,n);let r=new AbortController;return(async()=>{try{let n=await a.get({workId:e.source.workId,cwd:e.cwd,path:m,imagePreviewMode:h},r.signal);if(r.signal.aborted)return;if("image"!==n.kind)throw Error(o("standaloneReadFailed"));t=l.store(e,m,h,(0,dw.E)(n));let i=new Image;if(i.src=t.url,await i.decode(),r.signal.aborted)return;let c=t.url;s.set(m,t),d(e=>({...e,[m]:{status:"ready",objectUrl:c}}))}catch(n){if(t&&(t.release(),l.invalidate(e,m,h)),r.signal.aborted)return;let s=n instanceof Error?n.message:o("standaloneReadFailed");console.warn("[Pi Desk][StandaloneImageGallery] 读取图片失败",{workId:e.source.workId,path:m,error:s}),d(e=>({...e,[m]:{status:"error",message:s}}))}})(),()=>{r.abort(),s.get(m)!==t&&t?.release()}},[a,p,l,h,m,o,e]),(0,n.jsxs)("div",{className:"relative size-full","data-testid":"standalone-image-gallery",children:[(0,n.jsx)(ny.k,{mode:"inline",thumbnails:!1,slides:t.map(e=>{let t=c[e];return{src:t?.status==="ready"?t.objectUrl:e===m?g??d2:d2,alt:e}}),index:s,onIndexChange:i}),f?null:(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 z-[2] flex items-center justify-center p-6 pb-20",children:p?.status==="error"?(0,n.jsxs)("div",{className:"flex max-w-full flex-col items-center gap-3 rounded-lg bg-background/95 p-4 text-center",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:p.message}),(0,n.jsx)(I.$,{className:"pointer-events-auto",variant:"outline",onClick:()=>{l.invalidate(e,m,(0,rm.Wq)()),d(e=>{let t={...e};return delete t[m],t})},children:o("reloadFile")})]}):(0,n.jsxs)("div",{role:"status",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),o("loadingFile")]})})]})}function d3(e){return e.replaceAll("\\","/").split("/").at(-1)??e}function d4(e,t){return e instanceof Error?e.message:t}function d6({target:e,biz:t,images:s,mobile:i,onClose:a}){let{t:l}=(0,b.Bd)("workbench"),{t:o}=(0,b.Bd)("projectFiles"),c=(0,r.useRef)(null),[d,u]=(0,r.useState)({mode:"preview",scrollTop:0}),m=(0,r.useRef)(0),[p,h]=(0,r.useState)(null),[g,f]=(0,r.useState)(0),[x,v]=(0,r.useState)(()=>{let t=e&&!e.imagePaths?s.peek(e,e.path,(0,rm.Wq)()):null;return t?{status:"image",objectUrl:t}:{status:"loading"}}),[w,y]=(0,r.useState)(()=>e?.imagePaths?e.imagePaths.indexOf(e.path):0);if((0,r.useLayoutEffect)(()=>{let n;if(!e||e.imagePaths)return;let r=new AbortController,i=!0,a=(0,rm.Wq)(),o=s.get(e,e.path,a);return o?o.release:(t.get({workId:e.source.workId,cwd:e.cwd,path:e.path,imagePreviewMode:a},r.signal).then(t=>{if(!i)return;if("text"===t.kind)return void v({status:"text",content:t.content,size:t.size});let r=s.store(e,e.path,a,(0,dw.E)(t));n=r.release,v({status:"image",objectUrl:r.url})}).catch(t=>{i&&!r.signal.aborted&&(console.warn("[Pi Desk][PluginStandaloneFilePreview] 读取文件失败",{workId:e.source.workId,path:e.path,error:d4(t,l("standaloneReadFailed"))}),v({status:"error",message:d4(t,l("standaloneReadFailed"))}))}),()=>{i=!1,r.abort(),n?.()})},[t,s,g,e,l]),(0,r.useEffect)(()=>{if(!e)return;let t=e=>{e.source===c.current?.contentWindow&&"pi-desk:file-escape"===e.data&&a()};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[a,e]),!e)return null;let k=e.imagePaths?.[w]??e.path,j=(0,d0.g)(k);return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||a()},children:(0,n.jsxs)(eN.hA,{className:i?"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)(eN.YM,{className:"sr-only",children:d3(k)}),(0,n.jsxs)("section",{"data-testid":"plugin-standalone-file-preview",className:"flex size-full min-h-0 min-w-0 flex-col overflow-hidden bg-background","aria-label":l("standaloneViewer",{name:e.projectName}),children:[(0,n.jsxs)("header",{className:"flex min-h-14 shrink-0 items-center gap-3 border-b pl-3 pr-14 pt-[env(safe-area-inset-top)]",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-semibold",title:d3(k),children:d3(k)}),(0,n.jsxs)("p",{className:"truncate text-xs text-muted-foreground",title:`${e.projectName} \xb7 ${k}`,children:[e.projectName," \xb7 ",k]})]}),"markdown"===j&&"text"===x.status?(0,n.jsx)("div",{className:"flex shrink-0",role:"group","aria-label":o("markdownMode"),children:["preview","source"].map(e=>(0,n.jsx)(I.$,{size:"sm",variant:d.mode===e?"secondary":"ghost","aria-pressed":d.mode===e,onClick:()=>{d.mode!==e&&u({mode:e,scrollTop:m.current})},children:o("preview"===e?"previewMode":"sourceMode")},e))}):null]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden pb-[env(safe-area-inset-bottom)]",children:e.imagePaths?(0,n.jsx)(d5,{target:e,paths:e.imagePaths,index:w,onIndexChange:y,biz:t,images:s}):"loading"===x.status?(0,n.jsx)(d8,{}):"error"===x.status?(0,n.jsxs)("div",{className:"flex size-full flex-col items-center justify-center gap-3 p-6 text-center",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:x.message}),(0,n.jsx)(I.$,{variant:"outline",onClick:()=>{s.invalidate(e,e.path,(0,rm.Wq)()),v({status:"loading"}),f(e=>e+1)},children:l("reloadFile")})]}):"image"===x.status?(0,n.jsx)(ny.k,{mode:"inline",slides:[{src:x.objectUrl,alt:e.path}],ariaLabel:l("standaloneImage",{name:d3(e.path)})}):"markdown"===j&&"preview"===d.mode?(0,n.jsx)(dZ.n,{content:x.content,label:o("markdownPreview",{name:k}),savedScrollTop:d.scrollTop,onScroll:e=>{m.current=e}}):"html"===j?(0,n.jsx)("iframe",{ref:c,className:"block size-full border-0 bg-white",sandbox:"allow-scripts",srcDoc:(0,d1.z)(x.content),title:l("standaloneHtml",{name:e.path})}):(0,n.jsx)(dX.e,{path:e.path,content:x.content,size:x.size,savedState:p,onSaveState:(e,t)=>h(t),onEscape:a})})]})]})})}function d8(){let{t:e}=(0,b.Bd)("workbench");return(0,n.jsxs)("div",{className:"flex size-full items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),e("loadingFile")]})}var d7=s(3635),d9=s(76812),ue=s.n(d9);let ut=(0,d7.default)(()=>s.e(19991).then(s.bind(s,19991)).then(e=>e.L2FileWorkspaceView),{loadableGenerated:{webpack:()=>[19991]},ssr:!1});function us({workSession:e,runtime:t,gitRuntime:s,mobile:i,onOpenGitBranches:a,onOpenSidebar:l,children:o}){let{t:c}=(0,b.Bd)("workbench");(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let d=(0,r.useRef)(null),u=(0,E.OG)(),m=(0,r.useRef)(null),p=(0,r.useRef)(null),h=(0,r.useRef)(null),g=(0,r.useRef)(null),f=(0,r.useRef)(null),[x,v]=(0,r.useState)(!1),{workId:w}=e,y=t.getWorkspace(w),k=y?.windowOpen===!0,j=`session-chat-pane-${w}`,N=`session-file-pane-${w}`,I=y?.chatWidthPercent??50,[M]=(0,r.useState)(()=>k?I:100),z=!!(y?.tabs.length||y?.activeDiff),A=x&&!i,$=A&&k,R=t.getExpandedWorkId()===w,P=k&&($||y?.activePane==="files"),D=!P||$;(0,r.useLayoutEffect)(()=>{let e=d.current;if(!e)return;let t=new ResizeObserver(([e])=>{v((e?.contentRect.width??0)>=880)});return t.observe(e),()=>t.disconnect()},[]),(0,r.useLayoutEffect)(()=>{if(!A)return;let e=requestAnimationFrame(()=>{u.current?.setLayout({[j]:k?I:100,[N]:k?100-I:0})});return()=>cancelAnimationFrame(e)},[j,I,N,k,u,A]);let T=e=>{f.current=e};(0,r.useLayoutEffect)(()=>{let e=f.current;if(e&&("chat"===e?D:P)){let t,s;f.current=null,t="chat"===e?m.current:p.current,s="chat"===e?h.current:g.current,s?.isConnected&&t?.contains(s)&&!s.closest("[inert]")?s.focus({preventScroll:!0}):t?.querySelector("chat"===e?'textarea, [data-testid="session-files-entry"]':'[data-testid="file-workspace"]')?.focus({preventScroll:!0})}},[D,P,y?.activePane]);let O=()=>{if(!z)return;let e=t.getWorkspace(w)?.activePane==="files"?"chat":"files";T(e),"files"===e?t.showWindow(w):t.setActivePane(w,"chat")};return(0,n.jsx)("div",{ref:d,"data-testid":"session-file-layout","data-file-layout":$?"split":"single",className:"relative size-full min-h-0 min-w-0 overflow-hidden",onKeyDownCapture:e=>{"Tab"!==e.key||!e.ctrlKey||e.altKey||e.metaKey||e.repeat||e.nativeEvent.isComposing||!z||e.target instanceof Element&&e.target.closest('[role="menu"], [data-slot="app-dialog-content"]')||(e.preventDefault(),e.stopPropagation(),O())},children:(0,n.jsxs)(S.HK,{groupRef:u,className:(0,C.cn)("pi-desk-workbench-resize-group relative size-full min-h-0 min-w-0",A?[dD().panelGroup,ue().wide]:ue().single),orientation:"horizontal",disabled:!$,resizeTargetMinimumSize:{fine:8,coarse:20},onLayoutChanged:(e,s)=>{if(!$||!s.isUserInteraction)return;let n=e[j];void 0!==n&&t.setChatWidthPercent(w,n)},children:[(0,n.jsx)(S.wV,{id:j,"data-pane":"chat",defaultSize:`${M}%`,minSize:320*!!$,"aria-hidden":!D||void 0,inert:!D||void 0,className:"flex min-h-0 min-w-0 !overflow-hidden",children:(0,n.jsx)("div",{ref:m,className:"size-full min-h-0 min-w-0",onPointerDownCapture:()=>t.setActivePane(w,"chat"),onFocusCapture:e=>{h.current=e.target,t.setActivePane(w,"chat")},children:o(D)})}),(0,n.jsx)(S.WM,{id:`session-file-divider-${w}`,"aria-label":c("resizeChatFile"),"aria-hidden":!$||void 0,disabled:!$,disableDoubleClick:!0,className:(0,C.cn)("z-10 w-px cursor-col-resize bg-transparent aria-disabled:cursor-default",!$&&"hidden")}),(0,n.jsx)(S.wV,{id:N,"data-pane":"files",defaultSize:`${100-M}%`,minSize:320*!!$,maxSize:A&&!k?0:void 0,"aria-hidden":!P||void 0,inert:!P||void 0,className:"flex min-h-0 min-w-0 !overflow-hidden",children:(0,n.jsx)("div",{ref:p,className:"size-full min-h-0 min-w-0 overflow-hidden",onPointerDownCapture:()=>t.setActivePane(w,"files"),onFocusCapture:e=>{g.current=e.target,t.setActivePane(w,"files")},children:z&&!R?(0,n.jsx)(ut,{workSession:e,runtime:t,gitRuntime:s,mobile:i,presentation:A?"split":"single",onOpenGitBranches:a,onOpenSidebar:l,onHide:()=>{T("chat"),t.hideWindow(w)},onExpand:()=>t.expandWindow(w),onSwitchPane:O},`${e.sessionId}:${e.branchId}`):null})})]})})}function un({workSessions:e,runtime:t,gitRuntime:s,mobile:i,onOpenGitBranches:a,onOpenSidebar:l,onOpenTerminal:o}){let{t:c}=(0,b.Bd)("workbench");(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let d=e.find(e=>e.workId===t.getExpandedWorkId());if(!d)return null;let u=()=>{i?t.hideWindow(d.workId):t.collapseExpandedWindow()},m=()=>{let e=document.querySelector(`[data-work-id="${CSS.escape(d.workId)}"] textarea`);e&&(t.hideWindow(d.workId),requestAnimationFrame(()=>e.focus({preventScroll:!0})))};return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>{e||u()},children:(0,n.jsxs)(eN.hA,{showCloseButton:!1,onKeyDownCapture:e=>{"Tab"!==e.key||!e.ctrlKey||e.altKey||e.metaKey||e.repeat||e.nativeEvent.isComposing||e.target instanceof Element&&e.target.closest('[role="menu"]')||(e.preventDefault(),e.stopPropagation(),m())},className:i?"inset-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(d.workId)}"]`);return e?.querySelector("[data-file-expand-trigger]")??e?.querySelector('[data-testid="session-files-entry"]')??!1},children:[(0,n.jsx)(eN.YM,{className:"sr-only",children:c("fileViewer",{name:d.projectName})}),(0,n.jsx)(ut,{workSession:d,runtime:t,gitRuntime:s,mobile:i,presentation:i?"single":"expanded",onOpenGitBranches:a,onOpenSidebar:()=>{t.collapseExpandedWindow(),l(d.workId)},onSwitchPane:m,onOpenTerminal:o,onHide:()=>t.hideWindow(d.workId),onExpand:u},`${d.workId}:${d.sessionId}:${d.branchId}`)]})})}var ur=s(93320);async function ui(e,t,s){try{let n=await e.get({...t,imagePreviewMode:"compressed"},s);if("image"!==n.kind)throw Error("该文件不是可展示的图片");return(0,dw.E)(n)}catch(e){if(e instanceof ur.aw&&"errors:fileMissing"===e.errorKey)return null;throw e}}var ua=s(72114),ul=s(31761),uo=s(50479),uc=s(35989);let ud=[];function uu(e,t){let s=t.trim().toLocaleLowerCase();return s?e.filter(e=>e.toLocaleLowerCase().includes(s)):[...e]}function um({target:e,runtime:t,mobile:s,onClose:i}){let{t:a}=(0,b.Bd)("workbench"),{locale:l}=(0,eQ.i)();(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let o=(0,X.G)(),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(e?.repositoryRoot!==null),[p,h]=(0,r.useState)(""),[g,f]=(0,r.useState)(()=>({repositoryRoot:null,overrides:new Map})),[x,w]=(0,r.useState)(null),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(""),[S,E]=(0,r.useState)(null),[M,z]=(0,r.useState)(null),$=t.getWorkspace(e?.cwd??null),R=$?.heads.repositories??ud,P=e?null!==e.repositoryRoot&&R.some(t=>t.root===e.repositoryRoot)?e.repositoryRoot:R.find(e=>""===e.root)?.root??R[0]?.root??null:null,D=c??P;(0,r.useEffect)(()=>{e&&t.refreshHeads(e.cwd)},[t,e]),(0,r.useEffect)(()=>{if(!e||null===D||$?.heads.status!=="ready")return;let s=R.find(e=>e.root===D);s?.state==="ready"&&t.loadBranches(e.cwd,D)},[D,R,t,e,$?.heads.status]);let T=R.find(e=>e.root===D)??null,O=null===D?null:$?.branches.get(D)??null,L=O?.data??null,F=null!==D&&!!$?.branchOperations.has(D),B=(0,r.useMemo)(()=>uu(L?.local??[],p),[L?.local,p]),q=(0,r.useMemo)(()=>uu(L?.remote??[],p),[L?.remote,p]),_=(0,r.useMemo)(()=>uu(L?.recent??[],p),[L?.recent,p]),W=(0,r.useMemo)(()=>(0,uc.oY)(B),[B]),Y=(0,r.useMemo)(()=>(0,uc.oY)(q),[q]),V=L?.head.type==="branch"?L.head.name:null,H=(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 K=e=>{E(e),N(""),k(!0),w(null),z(null)},G=async(e,t)=>{z(null);try{await e(),o.success(t),i()}catch(e){z(e instanceof Error?e.message:a("gitOperationFailed"))}},J=R.length>1,Q=1===R.length?a("repositorySummary",{name:(0,uc.Hj)(e.projectName,R[0].root),branch:"ready"===R[0].state?(0,uc.ws)(R[0].head):a("repositoryUnavailable")}):R.length>1?a("repositoryCount",{count:R.length}):a("readingRepos"),Z=(s,r,i=s.name,l=0)=>{let o="local"===s.type&&s.name===V,c=x?.type===s.type&&x.name===s.name;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{type:"button","data-testid":"recent"===r?`git-branch-recent-${s.name}`:`git-branch-${s.type}-${s.name}`,className:(0,C.cn)("grid min-h-9 w-full cursor-pointer grid-cols-[1rem_minmax(0,1fr)_auto] items-center gap-2 rounded-lg pr-2 text-left outline-none hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-ring",o&&"font-medium text-foreground",c&&"bg-accent"),style:{paddingLeft:`${8+16*l}px`},title:s.name,onClick:()=>w(c?null:s),children:[(0,n.jsx)("span",{className:"text-muted-foreground",children:o?(0,n.jsx)(ep.A,{className:"size-4 text-foreground"}):"remote"===s.type?(0,n.jsx)(ua.A,{className:"size-3.5"}):(0,n.jsx)(ul.A,{className:"size-3.5"})}),(0,n.jsx)("span",{className:"truncate font-mono text-sm",children:i}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:o?a("current"):"recent"===r?a("recent"):""})]}),c?(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 border-l-2 border-border py-2 pl-2",style:{marginLeft:`${32+16*l}px`},children:[o?null:(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",disabled:F,onClick:()=>{null!==D&&!F&&G(()=>t.replaceBranch(e.cwd,D,s),a("remote"===s.type?"checkedOut":"switchedBranch",{name:s.name}))},children:a("remote"===s.type?"checkoutRemote":"switchGitBranch")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",disabled:F,onClick:()=>K(s),children:a("branchFromHere")})]}):null]},`${r}:${s.type}:${s.name}`)},ee=(e,t)=>{let s=`${e}:${t}`;return(g.repositoryRoot===D?g.overrides.get(s):void 0)??H.has(s)},et=(e,t,s=0)=>e.map(e=>{if(0===e.children.length&&e.branchName)return Z({type:t,name:e.branchName},t,e.name,s);let r=`${t}:${e.path}`,i=!!p.trim()||ee(t,e.path);return(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{type:"button","data-testid":`git-branch-group-${t}-${e.path}`,"aria-expanded":i,className:"grid min-h-9 w-full cursor-pointer grid-cols-[1rem_1rem_minmax(0,1fr)] items-center gap-2 rounded-lg pr-2 text-left text-muted-foreground outline-none hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",style:{paddingLeft:`${8+16*s}px`},title:e.path,onClick:()=>((e,t)=>{if(p.trim())return;let s=`${e}:${t}`,n=ee(e,t);f(e=>{let t=e.repositoryRoot===D?new Map(e.overrides):new Map;return t.set(s,!n),{repositoryRoot:D,overrides:t}})})(t,e.path),children:[(0,n.jsx)(e7.A,{className:(0,C.cn)("size-3 transition-transform",i&&"rotate-90")}),i?(0,n.jsx)(uo.A,{className:"size-4 text-muted-foreground"}):(0,n.jsx)(eP.A,{className:"size-4 text-muted-foreground"}),(0,n.jsx)("span",{className:"truncate font-mono text-sm",children:e.name})]}),i?et(e.children,t,s+1):null]},r)});return(0,n.jsx)(eN.YV,{open:!0,onOpenChange:e=>!e&&i(),children:(0,n.jsxs)(eN.hA,{"data-testid":"git-branch-picker",showCloseButton:!1,finalFocus:!1,className:"h-[min(40rem,calc(100dvh-2rem))] max-w-[45rem] gap-0",children:[(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 border-b px-3",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{children:a("gitBranches")}),(0,n.jsx)(eN.uX,{className:"truncate text-xs",children:Q})]}),(0,n.jsx)(I.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":a("refreshBranches"),disabled:$?.heads.status==="loading",onClick:()=>void t.refreshHeads(e.cwd),children:(0,n.jsx)(es.A,{className:(0,C.cn)("size-4",$?.heads.status==="loading"&&"animate-spin")})}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:i,children:a("close")})]}),(0,n.jsxs)("div",{className:(0,C.cn)("grid min-h-0 flex-1",J&&!s?"grid-cols-[220px_minmax(0,1fr)]":"grid-cols-1"),children:[!J||s&&u?null:(0,n.jsxs)("aside",{className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto border-r bg-sidebar p-2 max-sm:border-r-0",children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("repositories")}),R.map(t=>{let s=(0,uc.Hj)(e.projectName,t.root),r=t.root===D;return(0,n.jsxs)("button",{"data-testid":`git-branch-picker-repository-${t.root||"root"}`,type:"button",className:(0,C.cn)("grid min-h-12 w-full grid-cols-[minmax(0,1fr)_auto] items-center gap-2 rounded-lg px-2 text-left hover:bg-muted/70",r&&"bg-accent text-accent-foreground"),onClick:()=>{var e;d(e=t.root),m(!0),h(""),f({repositoryRoot:e,overrides:new Map}),w(null),k(!1),E(null),z(null)},children:[(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("strong",{className:"block truncate text-sm font-medium",children:s}),(0,n.jsx)("span",{className:"mt-1 block truncate font-mono text-xs text-muted-foreground",children:t.root||"."})]}),(0,n.jsx)("span",{className:"flex flex-col items-end gap-1 text-xs text-muted-foreground",children:(0,n.jsx)("span",{className:"max-w-28 truncate",children:"ready"===t.state?(0,uc.ws)(t.head):a("unavailable")})})]},t.root)})]}),s&&J&&!u?null:(0,n.jsxs)("section",{className:"flex min-h-0 min-w-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-13 shrink-0 items-center gap-2 border-b px-3",children:[s&&J?(0,n.jsx)(I.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":a("backRepositories"),onClick:()=>m(!1),children:(0,n.jsx)(A.A,{className:"size-4"})}):null,(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("p",{className:"truncate text-sm font-semibold",children:[T?(0,uc.Hj)(e.projectName,T.root):a("chooseRepository"),T?.state==="ready"?` \xb7 ${(0,uc.ws)(T.head)}`:""]}),(0,n.jsx)("p",{className:"mt-1 break-words font-mono text-xs text-muted-foreground",children:T?.root||"."})]}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",disabled:T?.state!=="ready"||F,onClick:()=>K(null),children:[(0,n.jsx)(U.A,{className:"size-3.5"})," ",a("createBranch")]})]}),$?.heads.status==="error"?(0,n.jsx)("p",{className:"border-b bg-muted px-3 py-2 text-sm text-destructive",children:$.heads.error}):null,M?(0,n.jsx)("p",{className:"border-b bg-muted px-3 py-2 text-sm text-destructive",children:M}):null,(0,n.jsx)("div",{className:"flex shrink-0 items-center gap-2 border-b p-2",children:y?(0,n.jsxs)("form",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",onSubmit:s=>{let n;s.preventDefault(),(n=j.trim())&&null!==D&&!F&&G(()=>t.addBranch(e.cwd,D,n,S),a("branchCreated",{name:n}))},children:[(0,n.jsx)(em.p,{autoFocus:!0,value:j,onChange:e=>N(e.currentTarget.value),placeholder:a("newBranchName"),"aria-label":a("newBranchName"),className:"min-w-[12rem] flex-1"}),(0,n.jsxs)(I.$,{type:"submit",size:"sm",disabled:!j.trim()||F,children:[F?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):null,a("createAndSwitch")]}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>{k(!1),E(null)},children:a("cancel")})]}):(0,n.jsx)(em.p,{value:p,onChange:e=>h(e.currentTarget.value),placeholder:a("searchBranches"),"aria-label":a("searchBranches")})}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-2",children:T?.state==="unavailable"?(0,n.jsx)("p",{className:"p-5 text-center text-xs text-destructive",children:(0,eJ.fD)(T.message,l)}):O?.status!=="loading"||L?O?.status==="error"?(0,n.jsxs)("div",{className:"flex min-h-24 flex-col items-center justify-center gap-2 text-center text-xs text-destructive",children:[(0,n.jsx)("p",{children:O.error}),null!==D?(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void t.loadBranches(e.cwd,D),children:a("retry")}):null]}):L?(0,n.jsxs)("div",{className:"space-y-3",children:[_.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("recentlyUsed")}),_.map(e=>Z({type:"local",name:e},"recent"))]}):null,B.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("localBranches")}),et(W,"local")]}):null,q.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:a("remoteBranches")}),et(Y,"remote")]}):null,0===_.length&&0===B.length&&0===q.length?(0,n.jsx)("p",{className:"p-5 text-center text-xs text-muted-foreground",children:a("noBranchMatches")}):null]}):null:(0,n.jsxs)("div",{className:"flex min-h-24 items-center justify-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"})," ",a("loadingBranches")]})})]})]})]})})}function up(e,t){return e instanceof DOMException&&"AbortError"===e.name?t:e instanceof Error?e.message:t}class uh{constructor(e,t){this.biz=e,this.onRepositoryChanged=t,this.listeners=new Set,this.workspaces=new Map,this.projectRefs=new Map,this.revision=0,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.getRevision=()=>this.revision}getWorkspace(e){return e?this.workspaces.get(e)??null:null}reconcileWorkSessions(e,t,s=[]){let n=new Map,r=t?e.find(e=>e.workId===t)??null:null;for(let t of(r&&n.set(r.cwd,{workId:r.workId,cwd:r.cwd}),e))n.has(t.cwd)||n.set(t.cwd,{workId:t.workId,cwd:t.cwd});for(let e of s)n.has(e.cwd)||n.set(e.cwd,{...e,readOnly:!0});if(n.size!==this.projectRefs.size||[...n].some(([e,t])=>this.projectRefs.get(e)?.workId!==t.workId||this.projectRefs.get(e)?.readOnly!==t.readOnly)){for(let[e,t]of(this.projectRefs.clear(),n))this.projectRefs.set(e,t);for(let[e,t]of this.workspaces)n.has(e)||(this.abortRequests(t),this.workspaces.delete(e))}}ensureSnapshot(e){let t=this.workspaceFor(e);return"ready"===t.snapshot.status||"loading"===t.snapshot.status?Promise.resolve():this.loadSnapshot(e,!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:dV("gitNoProjectStatus")},this.publish();return}let n=new AbortController,r={};t.headsRequest={controller:n,token:r},t.lastHeadsStartedAt=Date.now(),t.heads={...t.heads,status:"loading",error:null},this.publish();try{let i=await this.biz.getHeads({workId:s.workId,cwd:e},n.signal);if(t.headsRequest?.token!==r)return;t.headsRequest=null,t.heads={status:"ready",repositories:i.repositories,error:null},this.publish()}catch(e){if(t.headsRequest?.token!==r||(t.headsRequest=null,n.signal.aborted))return;t.heads={...t.heads,status:"error",error:up(e,dV("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:dV("gitNoProjectBranches")}),this.publish();return}s.branchRequests.get(t)?.controller.abort();let r=new AbortController,i={};s.branchRequests.set(t,{controller:r,token:i}),s.branches.set(t,{status:"loading",data:s.branches.get(t)?.data??null,error:null}),this.publish();try{let a=await this.biz.listBranches({workId:n.workId,cwd:e,repositoryRoot:t},r.signal);if(s.branchRequests.get(t)?.token!==i)return;s.branchRequests.delete(t),s.branches.set(t,{status:"ready",data:a,error:null}),this.publish()}catch(e){if(s.branchRequests.get(t)?.token!==i||(s.branchRequests.delete(t),r.signal.aborted))return;s.branches.set(t,{status:"error",data:null,error:up(e,dV("gitBranchesReadFailed"))}),this.publish()}}async replaceBranch(e,t,s){let n=this.requireWritableProject(e),r=this.workspaceFor(e);if(!r.branchOperations.has(t)){r.branchOperations.add(t),this.publish();try{let i=await this.biz.replaceBranch({...n,repositoryRoot:t,target:s});this.applyRepository(r,i.repository),this.clearBranches(r,t),this.onRepositoryChanged(e,t)}finally{r.branchOperations.delete(t),this.publish()}}}async addBranch(e,t,s,n){let r=this.requireWritableProject(e),i=this.workspaceFor(e);if(!i.branchOperations.has(t)){i.branchOperations.add(t),this.publish();try{let a=await this.biz.addBranch({...r,repositoryRoot:t,name:s,startPoint:n});this.applyRepository(i,a.repository),this.clearBranches(i,t),this.onRepositoryChanged(e,t)}finally{i.branchOperations.delete(t),this.publish()}}}getDiff(e,t,s,n){return this.biz.getDiff({...this.requireProject(e),repositoryRoot:t,path:s},n)}dispose(){for(let e of this.workspaces.values())this.abortRequests(e);this.workspaces.clear(),this.projectRefs.clear(),this.listeners.clear()}async loadSnapshot(e,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:dV("gitNoProjectStatus")},this.publish();return}s.snapshotRequest?.controller.abort();let r=new AbortController,i={};s.snapshotRequest={controller:r,token:i},s.snapshot={status:"loading",repositories:s.snapshot.repositories,error:null},this.publish();try{let t=await this.biz.get({workId:n.workId,cwd:e},r.signal);if(s.snapshotRequest?.token!==i)return;s.snapshotRequest=null,s.snapshot={status:"ready",repositories:t.repositories,error:null};let a=new Set(t.repositories.map(e=>e.root));for(let e of(t.repositories.length>0&&!a.has("")&&a.add(""),[...s.expandedRepositories]))a.has(e)||s.expandedRepositories.delete(e);this.publish()}catch(e){if(s.snapshotRequest?.token!==i||(s.snapshotRequest=null,r.signal.aborted))return;s.snapshot={status:"error",repositories:s.snapshot.repositories,error:up(e,dV("gitStatusReadFailed"))},this.publish()}}requireProject(e){let t=this.projectRefs.get(e);if(!t)throw Error(dV("gitNoProjectOperation"));return{workId:t.workId,cwd:t.cwd}}requireWritableProject(e){if(this.projectRefs.get(e)?.readOnly)throw Error(dV("gitNoProjectOperation"));return this.requireProject(e)}applyRepository(e,t){e.headsRequest?.controller.abort(),e.headsRequest=null,e.snapshotRequest?.controller.abort(),e.snapshotRequest=null;let s={root:t.root,state:t.state,head:t.head},n=[...e.heads.repositories],r=n.findIndex(e=>e.root===t.root);if(r>=0?n[r]=s:n.push(s),e.heads={status:"ready",repositories:n,error:null},e.lastHeadsStartedAt=Date.now(),"idle"===e.snapshot.status)return;let i="loading"===e.snapshot.status,a=[...e.snapshot.repositories],l=a.findIndex(e=>e.root===t.root);l>=0?a[l]=t:a.push(t),e.snapshot={status:"ready"===e.snapshot.status?"ready":"idle",repositories:a,error:null},i&&this.refreshSnapshot(e.cwd)}abortRequests(e){for(let t of(e.headsRequest?.controller.abort(),e.headsRequest=null,e.snapshotRequest?.controller.abort(),e.snapshotRequest=null,e.branchRequests.values()))t.controller.abort();e.branchRequests.clear()}clearBranches(e,t){e.branchRequests.get(t)?.controller.abort(),e.branchRequests.delete(t),e.branches.delete(t)}workspaceFor(e){let t=this.workspaces.get(e);if(t)return t;let s={cwd:e,heads:{status:"idle",repositories:[],error:null},headsRequest:null,lastHeadsStartedAt:0,snapshot:{status:"idle",repositories:[],error:null},snapshotRequest:null,branches:new Map,branchRequests:new Map,layout:"directory",changesOnly:!1,expandedRepositories:new Set,branchOperations:new Set};return this.workspaces.set(e,s),s}publish(){for(let e of(this.revision+=1,[...this.listeners]))e()}}var ug=s(24985);let uf=ug.y2,ux=a.Ik({workId:dN.eW,cwd:dN.ik}).strict(),ub=ug.Ww,uv=ug.cP,uw=ug.zp,uy=ug.u2;a.Ik({repositories:a.YO(uy).max(uf)}).strict();let uk=ux.extend({repositoryRoot:ub}).strict(),uj=ug.zt,uN=ux.extend({repositoryRoot:ub,target:uj}).strict(),uI=ux.extend({repositoryRoot:ub,name:uv,startPoint:uj.nullable()}).strict(),uS=a.Ik({repository:uw}).strict(),uC=ux.extend({repositoryRoot:ub,path:s0._g}).strict();var uE=s(68269);let uM=Object.freeze({messages:[],temporaryMessages:[],runtime:{extensionMode:"normal",presentationMode:"normal",initializationError:null,queues:{steering:[],followUp:[]},model:null,capabilityMode:null,contextUsage:null,plugins:{}}});function uz(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 uA=s(82639);let u$="messages",uR="source",uP="drafts",uD="outbox",uT="pi-super-chat",uO=null,uL=null;function uF(e){return Error((0,ed.B)({msg:uA.n["zh-CN"].common[e],i18n:{key:`common:${e}`}}))}function uB(e,t){e.objectStoreNames.contains(t)||e.createObjectStore(t,{keyPath:["sessionId","branchId"]})}function uq(){return new Promise((e,t)=>{let s=indexedDB.open(uT,2),n=!1,r=window.setTimeout(()=>{i(uF("dbOpenTimeout"))},1e4),i=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("upgradeneeded",()=>{let e=s.result;e.objectStoreNames.contains(u$)||e.createObjectStore(u$,{keyPath:["sessionId","branchId","index"]}).createIndex(uR,["sessionId","branchId"],{unique:!1}),uB(e,uP),uB(e,uD)},{once:!0}),s.addEventListener("blocked",()=>{i(uF("dbOpenBlocked"))},{once:!0}),s.addEventListener("success",()=>{let t=s.result;n?t.close():(n=!0,window.clearTimeout(r),e(t))},{once:!0}),s.addEventListener("error",()=>i(s.error??uF("dbOpenFailed")),{once:!0})})}async function u_(){try{return await uq()}catch(e){if(!("object"==typeof e&&null!==e&&"name"in e&&"VersionError"===e.name))throw e;return console.warn("[Pi Desk][ChatIndexedDB] 本地数据库版本高于当前版本,清空全部本地聊天数据后重建",{databaseName:uT,requestedVersion:2}),await new Promise((e,t)=>{let s=indexedDB.deleteDatabase(uT),n=!1,r=window.setTimeout(()=>{i(uF("dbDeleteTimeout"))},1e4),i=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("blocked",()=>{i(uF("dbDeleteBlocked"))},{once:!0}),s.addEventListener("success",()=>{n||(n=!0,window.clearTimeout(r),e())},{once:!0}),s.addEventListener("error",()=>i(s.error??uF("dbDeleteFailed")),{once:!0})}),uq()}}function uW(){return uL?Promise.resolve(uL):uO||(uO=u_().then(e=>(uL=e,e.addEventListener("versionchange",()=>{e.close(),uL===e&&(uL=null,uO=null),console.warn("[Pi Desk][ChatIndexedDB] 数据库版本已变化,当前连接已关闭")}),e)).catch(e=>{throw uO=null,e}))}function uY(e){return new Promise((t,s)=>{e.addEventListener("success",()=>t(e.result),{once:!0}),e.addEventListener("error",()=>s(e.error??uF("dbRequestFailed")),{once:!0})})}function uV(e,t,s){let n=e.target;return n?.error??t.error??Error(s)}function uU(e){return new Promise((t,s)=>{e.addEventListener("complete",()=>t(),{once:!0}),e.addEventListener("abort",t=>s(uV(t,e,uF("dbTransactionAborted").message)),{once:!0}),e.addEventListener("error",t=>s(uV(t,e,uF("dbTransactionFailed").message)),{once:!0})})}let uH=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:uE.ao,summary:uE.lV,detail:uE.wI.optional()}).strict();function uK(e,t){return uH.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 uG(e){let t=uH.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");uE.Y2.parse(t.summary),void 0!==t.detail&&uE.$f.parse(t.detail)}return uE.wR.parse({location:{index:t.index,entryId:t.entryId},fixed:t.fixed,summary:t.summary,...void 0===t.detail?{}:{detail:t.detail}})}function uJ(e,t){e.delete(IDBKeyRange.bound([t.sessionId,t.branchId,0],[t.sessionId,t.branchId,Number.MAX_SAFE_INTEGER]))}let uQ=a.Yj().max(65536),uX=a.Ik({id:a.Yj().uuid(),title:uQ,expiresAt:a.ai().int().nonnegative().nullable()}),uZ=a.gM("method",[uX.extend({method:a.eu("confirm"),message:uQ}).strict(),uX.extend({method:a.eu("select"),options:a.YO(uQ).max(200)}).strict(),uX.extend({method:a.eu("input"),placeholder:uQ}).strict(),uX.extend({method:a.eu("editor"),prefill:uQ}).strict()]),u0=a.Ik({requests:a.YO(uZ).max(32),statuses:a.g1(a.Yj().max(128),uQ),widgets:a.g1(a.Yj().max(128),a.Ik({lines:a.YO(uQ).max(200),placement:a.k5(["aboveEditor","belowEditor"])}).strict())}).strict(),u1=a.Ik({id:a.Yj().uuid(),value:a.KC([a.zM(),uQ,a.ch()])}).strict(),u2=a.gM("type",[a.Ik({type:a.eu("snapshot"),snapshot:u0}).strict(),a.Ik({type:a.eu("notify"),message:uQ,level:a.k5(["info","warning","error"])}).strict(),a.Ik({type:a.eu("editor_text"),text:uQ,mode:a.k5(["replace","paste"])}).strict()]),u5=a.Ik({source:ll.R}).strict(),u3=a.Ik({}).strict(),u4=Object.freeze({subscribe:(0,l.Vc)({path:"pi/ui/subscribe",inputSchema:u5,outputSchema:u0}),unsubscribe:(0,l.Vc)({path:"pi/ui/unsubscribe",inputSchema:u5,outputSchema:u3}),respond:(0,l.Vc)({path:"pi/ui/respond",inputSchema:u5.extend({response:u1}).strict(),outputSchema:u3}),event:(0,l._G)({path:"pi/ui/event",bodySchema:u5.extend({event:u2}).strict()})});function u6(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}class u8{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(u4.event,({source:e,event:t})=>{let s=this.records.get(u6(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(u6));for(let[e,s]of this.records)!t.has(e)&&(this.records.delete(e),this.connected&&this.socket.request(u4.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(u4.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:dV("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(dq.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:dV("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=u6(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(u6(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(u4.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:dV("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 u7=Object.freeze({...uM,syncStatus:"loading"});function u9(e){return uE.Pi.parse({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId})}function me(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function mt(e,t){return e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}let ms={text:"",images:[]};function mn(e){return[e.sessionId,e.branchId]}function mr(e,t){return{sessionId:e.sessionId,branchId:e.branchId,text:t.text,images:t.images}}function mi(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 ma(e,t){return t?{text:[e.text,t.text].filter(e=>e.trim()).join("\n\n"),images:[...e.images,...t.images]}:e}var ml=s(67837);let mo=new Set(["image/jpeg","image/png","image/webp","image/gif","image/bmp"]),mc=new Set(["image/jpeg","image/png","image/webp","image/gif"]),md=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function mu(e){return e.type.toLowerCase().split(";")[0]??""}async function mm(e){let t;try{t=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{throw Error(dV("imageDecodeFailed"))}if(!Number.isSafeInteger(t.width)||t.width<=0||t.height<=0)throw t.close(),Error(dV("imageInvalidDimensions"));return{bitmap:t,width:t.width,height:t.height}}function mp(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 mh(e,t,s,n,r){let i=document.createElement("canvas");i.width=t,i.height=s;let a=i.getContext("2d");if(!a)throw Error(dV("canvasUnavailable"));return a.drawImage(e,0,0,t,s),new Promise((e,t)=>{i.toBlob(s=>s?e(s):t(Error(dV("imageCompressFailed"))),n,r)})}async function mg(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(md.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 mf(e){let t=mu(e);if(!mo.has(t))throw Error(dV("imageTypeUnsupported"));let s=await mm(e);return s.bitmap.close(),{blob:e,mimeType:t,width:s.width,height:s.height,optimized:"image/gif"===t}}async function mx(e){if(e.optimized){if(e.blob.size>0xa00000)throw Error(dV("singleImageLimit"));return e}let t=await mm(e.blob);try{var s;let n=mp(t.width,t.height,2560),r=(s=e.mimeType,"image/jpeg"===s?"image/jpeg":"image/webp"),i=e.blob.size>5242880?.85:"image/jpeg"===r?.9:.92,a=await mh(t.bitmap,n.width,n.height,r,i),l=n.width,o=n.height,c=l!==t.width||o!==t.height,d="image/jpeg"===e.mimeType?await mg(e.blob):null,u="image/jpeg"===e.mimeType&&(null===d||d.width!==t.width||d.height!==t.height),m=mc.has(e.mimeType)&&!u;if(!c&&m&&a.size>=.9*e.blob.size&&(a=e.blob,l=t.width,o=t.height),a.size>0xa00000){let e=mp(t.width,t.height,2048);a=await mh(t.bitmap,e.width,e.height,r,.82),l=e.width,o=e.height}if(a.size>0xa00000)throw Error(dV("compressedImageTooLarge"));let p=mu(a);if(!mc.has(p))throw Error(dV("compressedTypeUnsupported"));return{blob:a,mimeType:p,width:l,height:o,optimized:!0}}finally{t.bitmap.close()}}async function mb(e){if(!e.optimized)throw Error(dV("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 mv(e,t,s=e.optimized?"ready":"optimizing"){return{...e,localId:(0,ml.y)(),objectUrl:URL.createObjectURL(e.blob),name:t,status:s,error:null}}function mw(e){URL.revokeObjectURL(e.objectUrl)}function my(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function mk(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 mj(e,t){return e instanceof Error&&e.message?e.message:t}function mN(e,t){return[e,t].filter(e=>e.trim()).join("\n\n")}function mI(e,t,s){return`${my(e)}\u0000temp\u0000${t}\u0000${s}`}function mS(e,t,s){return`${my(e)}\u0000entry\u0000${t}\u0000${s}`}function mC(e){for(let t of e)mw(t)}var mE=s(63273),mM=s(15104),mz=s(11039),mA=s(97906),m$=s(94411);function mR(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function mP(e){return e.trim().toLocaleLowerCase()}let mD=["title","user"],mT=[{value:"title",label:"scopeTitle"},{value:"user",label:"scopeUser"},{value:"assistant",label:"scopeAssistant"},{value:"sessionId",label:"Session ID"}];function mO(e,t,s){return"title"===e?s("scopeTitle"):"sessionId"===e?"Session ID":s("user"===e?"scopeUserMatches":"scopeAssistantMatches",{count:t})}function mL(e){switch(e){case"user":case"assistant":case"title":return"bg-muted text-foreground";case"sessionId":return"bg-muted text-muted-foreground"}}function mF(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 mB({scope:e,className:t}){switch(e){case"user":return(0,n.jsx)(mE.A,{className:t});case"assistant":return(0,n.jsx)(eD.A,{className:t});case"title":return(0,n.jsx)(mM.A,{className:t});case"sessionId":return(0,n.jsx)(mz.A,{className:t})}}function mq(e,t,s="bg-primary/20 text-foreground"){if(!t)return e;let r=e.toLocaleLowerCase(),i=[],a=0,l=r.indexOf(t);for(;l>=0;){l>a&&i.push(e.slice(a,l));let o=l+t.length;i.push((0,n.jsx)("mark",{className:`rounded-sm px-px ${s}`,children:e.slice(l,o)},`${l}-${o}`)),a=o,l=r.indexOf(t,a)}return a<e.length&&i.push(e.slice(a)),i.length?i:e}function m_({open:e,pickerMode:t,pickerView:s,pickerCwd:i,directories:a,ignoredDirectories:l,directoryBrowser:o,historySessions:c,replacementTarget:d,unavailableSessionIds:u,error:m,loading:p,creatingCwd:h,replacingSessionId:g,updatingIgnoreCwd:f,onOpenChange:x,onBack:v,onSearchHistory:w,onListSessionUserMessages:y,onRefresh:k,onOpenIgnoredDirectories:j,onOpenDirectoryBrowser:N,onNavigateDirectory:S,onSelectBrowserDirectory:C,onReplaceDirectoryIgnore:E,onSelectDirectory:M,onSelectSession:z}){let{t:$}=(0,b.Bd)("workbenchPicker"),{locale:R,timeZone:P}=(0,eQ.i)(),D=(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]),[T,O]=(0,r.useState)(""),[L,F]=(0,r.useState)(mD),[B,q]=(0,r.useState)(""),[_,W]=(0,r.useState)(null),Y=(0,r.useRef)(""),V=(0,r.useRef)(0),U=(0,r.useRef)(null),H=null!==h||null!==g||null!==f,K=(0,r.useMemo)(()=>new Set(u),[u]),G=mP(T),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),Q=/^(?:[A-Za-z]:[\\/]|[\\/]{2}|\/)/.test(J),X="ignored"===s?l:a,Z=X.filter(e=>!G||mP(`${mR(e.cwd)} ${e.cwd}`).includes(G)),ee=(o?.directories??[]).filter(e=>!G||mP(`${e.name} ${e.cwd}`).includes(G));(0,r.useEffect)(()=>{O(""),F(mD),q(""),Y.current=""},[e,t,i,s]);let et=`${G}\u0000${L.join("\0")}`;(0,r.useEffect)(()=>{if("history"!==s||!G||et===Y.current)return;let e=window.setTimeout(()=>{Y.current=et,w(G,L)},300);return()=>window.clearTimeout(e)},[et,w,s,G,L]),(0,r.useEffect)(()=>{V.current+=1,U.current?.abort(),U.current=null,W(null)},[e,i,s,G]),(0,r.useEffect)(()=>()=>{U.current?.abort()},[]);let en=async(e,t,s,n)=>{if(!i)return;let r=++V.current;U.current?.abort();let a=new AbortController;U.current=a,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:i,sessionId:e,query:t,page:{index:s,size:20}},a.signal);if(V.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(V.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{U.current===a&&(U.current=null)}},er=e=>{if(_?.sessionId===e.sessionId){V.current+=1,U.current?.abort(),U.current=null,W(null);return}let t=e.matches?.some(e=>"user"===e.scope)?G:"";en(e.sessionId,t,1,!1)},ei="ignored"===s?$("ignoredRestoreTitle"):"browser"===s?$("browseOtherTitle"):"replace"===t?$("replaceTitle"):$("createTitle"),ea="ignored"===s?$("ignoredRestoreDescription"):"browser"===s?$("browseDescription"):"replace"===t?d?$("replaceDescription",{project:d.projectName,session:d.sessionTitle??$("newSession")}):$("replaceMissingDescription"):$("createDescription"),el="history"===s?$("searchHistory"):"browser"===s?$("searchBrowser"):"ignored"===s?$("searchIgnored"):$("searchProjects"),eo="history"===s?c.length:"browser"===s?o?.directories.length??0:X.length,ec=p&&("browser"===s?null===o:0===eo),ed="history"===s?$("currentProject",{path:i??""}):"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"),ep=e=>{O(""),q(""),S(e)},eg=()=>{p||H||!Q||(O(""),S(J))};return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>{(e||!H)&&x(e)},children:(0,n.jsxs)(eN.hA,{className:"h-[min(44rem,calc(100dvh-2rem))] max-w-[45rem]",showCloseButton:!H,finalFocus:!1,children:[(0,n.jsx)(eN.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:["directories"!==s?(0,n.jsx)("button",{type:"button",disabled:H,onClick:v,"aria-label":$("backFolders"),title:$("backFolders"),className:(0,I.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(A.A,{className:"size-4"})}):(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:(0,n.jsx)(eP.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(eN.YM,{children:ei}),(0,n.jsx)(eN.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)(uo.A,{className:"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{value:B,onChange:e=>q(e.target.value),onKeyDown:e=>{"Enter"===e.key&&Q&&(e.preventDefault(),eg())},placeholder:$("pastePath"),"aria-label":$("fullPath"),disabled:p||H,className:"pl-9"})]}),(0,n.jsx)("button",{"data-testid":"workbench-picker-open-directory-path",type:"button",disabled:p||H||!Q,onClick:eg,title:Q?$("openTyped"):$("enterAbsolute"),className:(0,I.r)({variant:"outline"}),children:$("open")})]}),(0,n.jsx)("p",{className:"mt-1.5 px-0.5 text-sm text-muted-foreground",children:B.trim()&&!Q?$("absoluteExample"):$("pasteHint")})]}):null,(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(eh.A,{className:"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{value:T,onChange:e=>O(e.target.value),placeholder:el,"aria-label":el,disabled:H,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")}),mT.map(e=>{let t=L.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:H||t&&1===L.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)(eN._Y,{className:"max-h-none min-h-0",children:(0,n.jsxs)("div",{className:"p-2 sm:p-3","aria-busy":p||H,"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===d?(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,ec?(0,n.jsxs)("div",{className:"flex min-h-36 flex-col items-center justify-center gap-3 text-center text-sm text-muted-foreground",children:[(0,n.jsx)(es.A,{className:"size-5 animate-spin"}),(0,n.jsx)("p",{children:eu})]}):"history"===s?0===c.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:c.length})}):null,(0,n.jsx)("div",{className:"divide-y",children:c.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,D.format(t))}),i=d?.sessionId===e.sessionId,a=K.has(e.sessionId),l=g===e.sessionId,o=null===d,c=H||i||a||o,u=_?.sessionId===e.sessionId?_:null,m=e.matches??[],p=m.filter(e=>"title"!==e.scope),h=m.find(e=>"user"===e.scope),f=null===u&&p.length>0,x=`workbench-picker-user-message-panel-${e.sessionId}`,b=l?$("replacing"):i?$("current"):a?$("alreadyUsed"):o?$("targetUnavailable"):$("replace"),v=i?$("currentBound"):a?$("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)(mA.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)?mq(s,G,mF("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:H,"aria-label":w,"aria-expanded":null!==u,"aria-controls":x,onClick:()=>er(e),title:w,className:(0,I.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(eY.A,{className:`size-4 transition-transform${u?" rotate-180":""}`})}):null,(0,n.jsx)("button",{"data-testid":`workbench-picker-replace-${e.sessionId}`,type:"button",disabled:c,onClick:()=>z(e.sessionId),title:v,className:(0,I.r)({variant:"outline"}),children:l?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):b})]}),f?(0,n.jsx)("div",{className:"mb-2 ml-6 min-w-0 space-y-1.5 overflow-hidden",children:p.map(t=>{let s,r="user"===t.scope,i=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(mB,{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 ${mL(t.scope)}`,children:mO(t.scope,t.count,$)}),null!==t.timestampMs?(0,n.jsx)("span",{className:"truncate text-muted-foreground",children:(s=t.timestampMs,D.format(s))}):null]}),(0,n.jsx)("p",{className:"mt-1 line-clamp-2 break-words text-sm leading-5 text-foreground",children:mq(t.preview,G,mF(t.scope))})]})]}),a=`flex w-full max-w-full min-w-0 items-start gap-2 overflow-hidden rounded-md px-2.5 py-2 text-left ${mL(t.scope)}`;return r?(0,n.jsx)("button",{"data-testid":`workbench-picker-user-message-preview-${e.sessionId}`,type:"button",disabled:H,onClick:()=>er(e),"aria-label":$("viewMatch",{label:mO(t.scope,t.count,$)}),className:`${a} outline-none transition-colors hover:brightness-95 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50`,children:i},t.scope):(0,n.jsx)("div",{className:a,children:i},t.scope)})}):null,u?(0,n.jsxs)("div",{id:x,"data-testid":x,className:"mb-2 ml-6 rounded-md border bg-background px-3 py-2.5",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[(0,n.jsxs)("p",{className:"flex min-w-0 items-center gap-1.5 text-xs font-medium",children:[(0,n.jsx)(m$.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||H,onClick:()=>void en(e.sessionId,"",1,!1),className:(0,I.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)(es.A,{className:"size-4 animate-spin"})}):0===u.messages.length?(0,n.jsx)("p",{className:"py-4 text-center text-xs text-muted-foreground",children:$("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,D.format(t))}),(0,n.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-sm leading-6",children:e.text?mq(e.text,u.query):$("noText")})]},e.entryId)})}),y?(0,n.jsxs)("button",{type:"button",disabled:u.loading||H,onClick:()=>void en(e.sessionId,u.query,(u.page?.index??0)+1,!0),className:(0,I.r)({variant:"outline",className:"mt-2"}),children:[u.loading?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):null,$("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)(uo.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||H,onClick:()=>ep(e.cwd),className:"group flex min-h-15 w-full items-center gap-3 rounded-md px-2 py-2 text-left outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55 sm:px-3",children:[(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-primary"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",title:e.name,children:e.name}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),(0,n.jsx)(e7.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-foreground"})]},e.cwd))})]}):0===Z.length?null===m?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:0===X.length?"ignored"===s?$("ignoredEmpty"):$("projectsEmpty"):$("projectNoMatches")}):null:"ignored"===s?(0,n.jsx)("div",{className:"divide-y",children:Z.map(e=>{let t=mR(e.cwd),s=f===e.cwd;return(0,n.jsxs)("div",{className:"flex min-h-15 items-center gap-3 px-2 py-2 sm:px-3",children:[(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",title:t,children:t}),(0,n.jsx)("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),(0,n.jsxs)("button",{"data-testid":`workbench-picker-restore-directory-${e.cwd}`,type:"button",disabled:H,onClick:()=>E(e.cwd,!1),"aria-label":$("restoreFolder",{name:t}),title:$("restoreTip"),className:(0,I.r)({variant:"outline"}),children:[s?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(lP.A,{className:"size-3.5"}),(0,n.jsx)("span",{children:$("restore")})]})]},e.cwd)})}):(0,n.jsx)("div",{className:"divide-y",children:Z.map(e=>{let s,r=mR(e.cwd),i=$("directorySessions",{count:e.sessionCount,time:(s=e.updatedAt,D.format(s))}),a=h===e.cwd,l=f===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:H,onClick:()=>M(e.cwd),className:"group flex min-h-15 min-w-0 flex-1 items-center gap-3 rounded-md px-2 py-2 text-left outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55 sm:px-3",children:[(0,n.jsx)(eP.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-primary"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",title:r,children:r}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),a?(0,n.jsxs)("span",{className:"flex min-h-10 shrink-0 items-center gap-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}),$("creating")]}):(0,n.jsxs)("span",{className:"flex shrink-0 items-center gap-1 text-xs text-muted-foreground",title:i,children:[(0,n.jsx)("span",{children:$("directoryCount",{count:e.sessionCount})}),(0,n.jsx)(e7.A,{className:"size-4 group-hover:text-foreground"})]})]}),"create"===t?(0,n.jsx)("button",{"data-testid":`workbench-picker-ignore-directory-${e.cwd}`,type:"button",disabled:H,onClick:()=>E(e.cwd,!0),"aria-label":$("ignoreFolder",{name:r}),title:$("ignoreTip"),className:(0,I.r)({variant:"ghost",size:"icon"}),children:l?(0,n.jsx)(es.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(an.A,{className:"size-4"})}):null]},e.cwd)})})]})}),(0,n.jsxs)(eN.vu,{className:"flex-row flex-wrap items-center justify-between gap-2 px-3 py-2.5 sm:px-4",children:[(0,n.jsx)("p",{className:"min-w-24 flex-1 truncate text-xs text-muted-foreground",title:ed,children:ed}),(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||H,onClick:j,className:(0,I.r)({variant:"outline"}),children:$("ignoredFolders")}),(0,n.jsx)("button",{type:"button",disabled:p||H,onClick:N,className:(0,I.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||H,onClick:()=>C(o.cwd),className:(0,I.r)(),children:$("selectCurrent")}):null,"browser"===s&&o?.parentCwd?(0,n.jsx)("button",{type:"button",disabled:p||H,onClick:()=>ep(o.parentCwd),"aria-label":$("parentDirectory"),title:$("parentDirectory"),className:(0,I.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(A.A,{className:"size-4"})}):null,"browser"===s&&o?.cwd?(0,n.jsx)("button",{type:"button",disabled:p||H,onClick:()=>ep(null),"aria-label":$("backRoots"),title:$("backRoots"),className:(0,I.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(uo.A,{className:"size-4"})}):null,(0,n.jsx)("button",{"data-testid":"workbench-picker-refresh",type:"button",disabled:p||H,onClick:()=>k(G,L),"aria-label":$("refreshList"),title:$("refreshList"),className:(0,I.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(es.A,{className:`size-4${p?" animate-spin":""}`})})]})]})]})})}let mW="pi-super:workbench-layout";function mY(e,t,s=[]){let n=new Set(t.map(e=>e.workId)),r=new Set(s),i=e.primaryWorkId&&n.has(e.primaryWorkId)&&!r.has(e.primaryWorkId)?e.primaryWorkId:null;return e.primaryWorkId===i?e:{primaryWorkId:i}}function mV({variant:e,className:t,children:s}){let{t:r}=(0,b.Bd)("workbench");return(0,n.jsx)("div",{className:(0,C.cn)("@container/empty-state flex size-full min-h-0 flex-1 items-center justify-center overflow-hidden px-6 py-8 text-center",t),children:"select-session"===e?(0,n.jsxs)("div",{className:"relative",children:[s,(0,n.jsx)("h1",{className:"text-base font-medium text-muted-foreground",children:r("emptySelectSession")})]}):(0,n.jsxs)("div",{role:"status","aria-live":"polite",className:"flex flex-col items-center gap-3 animate-in fade-in-0 fill-mode-both delay-150 duration-150 motion-reduce:animate-none",children:[(0,n.jsx)(v.A,{className:"size-5 animate-spin text-muted-foreground motion-reduce:animate-none"}),(0,n.jsx)("p",{className:"text-sm font-medium text-muted-foreground",children:r("emptyLoading")})]})})}var mU=s(39569),mH=s(31175),mK=s(74873),mG=s(77065),mJ=s(36919);let mQ=new Set(["custom","model_change","thinking_level_change","session_info","label"]),mX=[],mZ=[{value:"default",label:"filterDefault"},{value:"no-tools",label:"filterNoTools"},{value:"user-only",label:"filterUserOnly"},{value:"labeled-only",label:"filterLabeled"},{value:"all",label:"filterAll"}],m0={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 m1(e){switch(e.action){case"tree":return"treeIntent";case"fork":return"forkIntent";case"clone":return"cloneIntent"}}function m2(e){e.preventDefault()}function m5({confirmation:e,disabled:t,onConfirm:s,onBack:i}){let{t:a}=(0,b.Bd)("workbenchPicker"),[l,o]=(0,r.useState)(0),c=(0,r.useRef)(new Map);(0,r.useEffect)(()=>{c.current.get(0)?.focus()},[]);let d=n=>{e.waiting||t&&0===n||(0===n?s():i())};return(0,n.jsxs)("div",{className:"p-3 sm:p-4",onKeyDown:e=>{if(e.stopPropagation(),"Escape"===e.key){e.preventDefault(),i();return}if("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key){e.preventDefault();let t=+(0===l);o(t),queueMicrotask(()=>c.current.get(t)?.focus());return}"Enter"===e.key&&(e.preventDefault(),d(l))},children:[(0,n.jsxs)("div",{className:"rounded-lg border bg-muted/25 px-3 py-2.5",children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:a("runningTitle")}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:"main"===e.reason?a("runningStop",{action:a(m1(e.intent))}):a("runningWait",{action:a(m1(e.intent))})})]}),(0,n.jsx)("div",{className:"mt-3 grid grid-cols-2 gap-2",children:[{label:a(e.waiting?"confirming":"confirmContinue"),confirm:!0},{label:a("back"),confirm:!1}].map((s,r)=>(0,n.jsxs)("button",{ref:e=>{e?c.current.set(r,e):c.current.delete(r)},type:"button",disabled:e.waiting||t&&s.confirm,tabIndex:l===r?0:-1,className:(0,C.cn)("flex min-h-11 items-center justify-center gap-2 rounded-lg border px-3 text-sm font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-60",l===r?"border-primary/40 bg-primary/10 text-foreground":"border-border bg-background hover:bg-muted/60"),onFocus:()=>o(r),onClick:()=>d(r),children:[e.waiting&&s.confirm?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):null,s.label]},s.label))}),(0,n.jsx)("p",{className:"mt-2 text-center text-xs text-muted-foreground",children:a("confirmHint")})]})}function m3({model:e,projectName:t,sessionTitle:s,mobile:i,onClose:a,onRetry:l,onSelectEntry:o,onAction:c,onConfirmRunning:d,onCancelRunning:u}){let{t:m}=(0,b.Bd)("workbenchPicker"),p=(0,mG.tF)(),h=(0,mJ.I)(),{locale:g,timeZone:f}=(0,eQ.i)(),x=(0,r.useMemo)(()=>new Intl.DateTimeFormat("en"===g?"en-US":"zh-CN",{timeZone:f,timeZoneName:"shortOffset",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}),[g,f]),[w,y]=(0,r.useState)(""),[k,j]=(0,r.useState)("default"),[N,S]=(0,r.useState)(!1),[E,M]=(0,r.useState)(()=>new Set),[z,A]=(0,r.useState)(null),[$,R]=(0,r.useState)(0),[P,D]=(0,r.useState)(480),T=(0,r.useRef)(null),O=(0,r.useRef)(null),L=(0,r.useRef)(null),F=(0,r.useRef)(null),B=(0,r.useRef)(!1),q=e.tree?.nodes??mX,_=(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!mQ.has(e.kind);case"no-tools":return!mQ.has(e.kind)&&"tool"!==e.kind;case"user-only":return"user"===e.kind;case"labeled-only":return null!==e.label;case"all":return!0}})(t,e.filter,e.leafEntryId)&&function(e,t){let s=t.toLocaleLowerCase().split(/\s+/).filter(Boolean);if(0===s.length)return!0;let n=[e.kind,e.preview,e.label??""].join(" ").toLocaleLowerCase();return s.every(e=>n.includes(e))}(t,e.query)).map(e=>e.entryId)),r=new Map,i=new Map;for(let e of t.values()){if(!n.has(e.node.entryId))continue;let s=e.node.parentEntryId,a=new Set;for(;s&&!n.has(s);){if(a.has(s)){s=null;break}a.add(s),s=t.get(s)?.node.parentEntryId??null}s===e.node.entryId&&(s=null),i.set(e.node.entryId,s);let l=r.get(s)??[];l.push(e),r.set(s,l)}for(let e of r.values())e.sort((e,t)=>(function(e,t,s){let n=Number(!s.has(e.node.entryId))-Number(!s.has(t.node.entryId));if(0!==n)return n;let r=e.node.timestampMs-t.node.timestampMs;return 0!==r?r:e.index-t.index})(e,t,s));let a=[],l=new Set;return(t=>{let n=[...t].reverse().map(e=>({indexed:e,depth:0,connector:!1,lastSibling:!0}));for(;n.length>0;){let t=n.pop(),o=t.indexed.node.entryId;if(l.has(o))continue;l.add(o);let c=r.get(o)??[],d=i.get(o)??null,u=null===d?[]:r.get(d)??[],m=c.length>0&&(null===d||u.length>1),p=!m||!e.foldedEntryIds.has(o);if(a.push({node:t.indexed.node,depth:t.depth,active:s.has(o),current:o===e.leafEntryId,hasChildren:c.length>0,foldable:m,expanded:p,connector:t.connector,lastSibling:t.lastSibling,visibleParentEntryId:i.get(o)??null}),!p)continue;let h=c.length>1;for(let[e,s]of[...c].reverse().entries()){let r=c.length-e-1;n.push({indexed:s,depth:t.depth+ +!!h,connector:h,lastSibling:r===c.length-1})}}})(r.get(null)??[]),a})({nodes:q,leafEntryId:e.tree?.leafEntryId??null,filter:k,query:w,foldedEntryIds:E}),[k,E,e.tree?.leafEntryId,q,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])),i=s,a=new Set;for(;i&&!a.has(i);){if(n.has(i))return i;a.add(i),i=r.get(i)?.parentEntryId??null}return t.at(-1)?.node.entryId??null}(q,_,z??e.tree?.leafEntryId??null),Y=_.findIndex(e=>e.node.entryId===W),U=Y>=0?_[Y]:null,H=Math.max(0,Math.floor($/36)-8),G=Math.min(_.length,Math.ceil(($+P)/36)+8),J=Math.min(_.length,Math.max(G,H+8)),Q=_.slice(H,J),X=e.detail?.entryId===W?e.detail:null,Z=m(mZ.find(e=>e.value===k)?.label??"filterDefault"),ee=e.runningConfirmation,et=`work-session-branch-tree-${e.workId}`,es=W?`${et}-entry-${W}`:void 0,en=(0,r.useCallback)(()=>{i?O.current?.focus({preventScroll:!0}):T.current?.focus({preventScroll:!0})},[i]),er=(0,r.useCallback)(t=>{e.pending||(B.current=t,a())},[e.pending,a]);(0,r.useEffect)(()=>{if(p)return F.current=document.activeElement instanceof HTMLElement?document.activeElement:null,B.current=!1,queueMicrotask(en),()=>{B.current&&F.current?.focus({preventScroll:!0})}},[en,p]),(0,r.useEffect)(()=>{p&&!ee&&queueMicrotask(en)},[ee,en,p]),(0,r.useEffect)(()=>{if(!p)return;let t=t=>{if(e.pending)return;let s=t.target;!(s instanceof Node)||O.current?.contains(s)||s instanceof Element&&s.closest('[data-workbench-branch-picker-popup="true"]')||er(!1)};return document.addEventListener("pointerdown",t,!0),()=>document.removeEventListener("pointerdown",t,!0)},[e.pending,p,er]),(0,r.useEffect)(()=>{let e=L.current;if(!e)return;let t=new ResizeObserver(([e])=>{D(e?.contentRect.height??0)});return t.observe(e),()=>t.disconnect()},[ee]),(0,r.useEffect)(()=>{if(!p||!W||ee)return;o(W);let e=L.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))},[ee,W,o,p,36,Y]);let ei=(0,r.useCallback)(e=>{L.current&&(L.current.scrollTop=e),R(e)},[]),ea=(0,r.useCallback)(e=>{if(0===_.length)return;let t=Math.max(0,Math.min(_.length-1,e));A(_[t].node.entryId);let s=L.current;if(!s)return;let n=36*t,r=n+36,i=s.scrollTop;n<s.scrollTop?i=n:r>s.scrollTop+s.clientHeight&&(i=r-s.clientHeight),ei(i)},[36,_,ei]),el=(0,r.useCallback)((e,t)=>{M(s=>{let n=new Set(s);return t??!n.has(e)?n.add(e):n.delete(e),n})},[]),eo=(0,r.useCallback)(e=>{j(e),M(new Set),ei(0),queueMicrotask(en)},[en,ei]),ec=(0,r.useCallback)(e=>{let t=(mZ.findIndex(e=>e.value===k)+e+mZ.length)%mZ.length;eo(mZ[t].value)},[eo,k]),ed=(0,r.useCallback)((t,s)=>{e.actionsDisabled||(B.current=!1,c(t,s))},[e.actionsDisabled,c]),eu=(0,r.useCallback)(()=>{!U||U.current||e.pending||ed(U.node.entryId,"tree")},[e.pending,ed,U]),ep=(0,r.useCallback)(()=>{if(!U?.visibleParentEntryId)return;let e=_.findIndex(e=>e.node.entryId===U.visibleParentEntryId);e>=0&&ea(e)},[_,ea,U]),eg=(0,r.useCallback)(()=>{if(!U)return;let e=_.findIndex(e=>e.visibleParentEntryId===U.node.entryId);e>=0&&ea(e)},[_,ea,U]),ef=(0,r.useCallback)(()=>{ee?u():w?(y(""),M(new Set),ei(0)):er(!0)},[ee,u,w,er,ei]);(0,r.useEffect)(()=>{if(!i||!p)return;let e=e=>{"Escape"!==e.key||e.defaultPrevented||e.isComposing||e.repeat||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||O.current?.closest("[inert]")||(e.preventDefault(),e.stopImmediatePropagation(),ef())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ef,i,p]);let ex=U?.node??null,eb=ex?m0[ex.kind]:null,ev=ee?i?"inset-x-0 bottom-0 rounded-t-2xl border-x-0 border-b-0":"inset-x-2 bottom-2 h-auto max-h-[calc(100%-4rem)] rounded-xl":i?"inset-x-0 bottom-0 top-14 rounded-t-2xl border-x-0 border-b-0":"inset-x-2 bottom-2 h-[min(82%,48rem)] rounded-xl";return(0,n.jsxs)(o6.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)(o6.PY1.section,{ref:O,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",ev),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")}),ee?null:(0,n.jsxs)("span",{className:"shrink-0 text-xs text-muted-foreground",children:[Y>=0?Y+1:0," / ",_.length]}),(0,n.jsx)("button",{type:"button",disabled:e.pending,"aria-label":m("closeBranchPicker"),className:(0,I.r)({variant:"ghost",size:"icon"}),onClick:()=>er(!0),children:(0,n.jsx)(V.A,{className:"size-4"})})]}),ee?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)(eh.A,{className:"pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(em.p,{ref:T,role:"combobox",value:w,"aria-label":m("branchSearch"),"aria-controls":et,"aria-expanded":"true","aria-activedescendant":es,placeholder:m("branchSearchPlaceholder"),className:"pl-7",onChange:e=>{y(e.currentTarget.value),M(new Set),ei(0)},onKeyDown:e=>{if(!e.nativeEvent.isComposing)switch(e.stopPropagation(),e.key){case"Tab":e.preventDefault(),ec(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||!U)return;e.preventDefault(),U.foldable&&U.expanded?el(U.node.entryId,!0):ep();return;case"ArrowRight":if(w||!U)return;e.preventDefault(),U.foldable&&!U.expanded?el(U.node.entryId,!1):eg();return;case"Enter":e.preventDefault(),eu();return;case"Escape":e.preventDefault(),ef();return}}})]}),(0,n.jsxs)(K.rI,{open:N,onOpenChange:S,onOpenChangeComplete:e=>{e||queueMicrotask(en)},children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)("button",{type:"button","aria-label":m("branchFilter",{filter:Z}),className:(0,I.r)({variant:"outline"})}),children:[Z,(0,n.jsx)(eY.A,{className:"size-3.5"})]}),(0,n.jsx)(K.SQ,{"data-workbench-branch-picker-popup":"true",align:"end",side:"bottom",className:"w-32",finalFocus:()=>i?O.current:T.current,children:mZ.map(e=>(0,n.jsxs)(K._2,{onClick:()=>eo(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)(I.$,{type:"button",size:"sm",variant:"outline",disabled:e.actionsDisabled,onClick:l,children:m("retry")})]})}):null,ee?(0,n.jsx)(m5,{confirmation:ee,disabled:e.actionsDisabled,onConfirm:d,onBack:()=>{B.current=!0,u()}},`${ee.intent.action}:${"entryId"in ee.intent?ee.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:ex&&eb?(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:eb.labelClassName,children:m(eb.label)}),ex.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:ex.label}):null,(0,n.jsx)("time",{className:"ml-auto shrink-0",children:x.format(ex.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)(v.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)(v.A,{className:"size-3.5 animate-spin text-primary"}),m("branchWorking")]}):null,e.loading&&!e.tree?(0,n.jsx)("div",{className:"grid min-h-0 flex-1 place-items-center text-sm text-muted-foreground",children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(v.A,{className:"size-4 animate-spin"}),m("branchLoading")]})}):0===_.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===q.length?m("branchEmpty"):m("branchNoMatches")}):(0,n.jsxs)("div",{ref:L,id:et,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*H}px`},"aria-hidden":"true"}),Q.map(t=>{let s=t.node.entryId===W,r=Math.min(t.depth,10),a=m0[t.node.kind];return(0,n.jsxs)("div",{id:`${et}-entry-${t.node.entryId}`,role:"treeitem","aria-level":t.depth+1,"aria-selected":s,"aria-expanded":t.foldable?t.expanded:void 0,className:(0,C.cn)("group relative flex min-w-0 items-center rounded-md outline-none transition-colors",a.rowClassName,s?"bg-accent text-accent-foreground":t.current?"bg-primary/[0.055] hover:bg-primary/[0.08]":"hover:bg-muted/50"),style:{height:"36px",paddingLeft:`${10*r}px`},children:[r>0?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("pointer-events-none absolute bottom-0 top-0 w-px",t.active?"bg-primary/25":"bg-border/60"),style:{left:`${10*r-5}px`}}):null,t.connector?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("pointer-events-none absolute h-px w-2",t.active?"bg-primary/25":"bg-border/60"),style:{left:`${10*r-5}px`}}):null,(0,n.jsx)("div",{className:"flex w-6 shrink-0 items-center justify-center",children:t.foldable?(0,n.jsx)("button",{type:"button","aria-label":m(t.expanded?"collapseBranch":"expandBranch"),className:"flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-foreground/8 hover:text-foreground",onMouseDown:m2,onClick:()=>{el(t.node.entryId),queueMicrotask(en)},children:(0,n.jsx)(e7.A,{className:(0,C.cn)("size-3 transition-transform",t.expanded&&"rotate-90")})}):null}),(0,n.jsxs)("button",{type:"button",tabIndex:-1,className:"flex h-full min-w-0 flex-1 items-center gap-1.5 overflow-hidden text-left outline-none",onMouseDown:m2,onClick:()=>{A(t.node.entryId),queueMicrotask(en)},onDoubleClick:()=>{i||t.current||ed(t.node.entryId,"tree")},children:[(0,n.jsx)("span",{className:(0,C.cn)("w-9 shrink-0 text-xs",a.labelClassName),children:m(a.label)}),t.node.label?(0,n.jsx)("span",{className:"max-w-24 shrink-0 truncate rounded-md bg-muted px-1 text-xs text-foreground",children:t.node.label}):null,(0,n.jsx)("span",{className:(0,C.cn)("min-w-0 flex-1 truncate text-sm",a.contentClassName,s&&"font-semibold text-accent-foreground"),children:t.node.preview||m("noPreview")})]}),i?(0,n.jsxs)("div",{className:"ml-2 flex shrink-0 items-center gap-1 border-l border-border/55 py-0.5 pl-1.5 pr-1",children:[(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||t.current||e.pending,"aria-label":m("switchToMessage",{kind:m(a.label)}),className:(0,I.r)({variant:"secondary",size:"sm"}),onClick:()=>ed(t.node.entryId,"tree"),children:m("switch")}),"user"===t.node.kind?(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||e.pending,"aria-label":m("forkFromUser"),className:(0,I.r)({variant:"outline",size:"sm"}),onClick:()=>ed(t.node.entryId,"fork"),children:"Fork"}):null]}):"user"===t.node.kind?(0,n.jsx)("div",{className:"ml-2 flex shrink-0 items-center border-l border-border/50 pl-2 pr-1",children:(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||e.pending,"aria-label":m("forkFromUser"),className:(0,I.r)({variant:"ghost",size:"sm"}),onMouseDown:m2,onClick:()=>ed(t.node.entryId,"fork"),children:"Fork"})}):null]},t.node.entryId)}),(0,n.jsx)("div",{style:{height:`${36*Math.max(0,_.length-J)}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," / ",_.length,i?"":` \xb7 ${m("branchShortcuts")}`]}),i?null:(0,n.jsx)(I.$,{type:"button",size:"sm",disabled:e.actionsDisabled||!U||U.current||e.loading||e.pending,onMouseDown:m2,onClick:eu,children:m("switch")})]})]})]})]})}var m4=s(15450),m6=s(31210),m8=s(66722),m7=s(40942),m9=s(61989),pe=s(63434),pt=s(26690),ps=s(2870),pn=s.n(ps);function pr({workSession:e,runtime:t,active:s,chatReady:i,onOpen:a}){let{t:l}=(0,b.Bd)("workbench"),{locale:o}=(0,eQ.i)();(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let c=t.getWorkspace(e.cwd)?.heads;(0,r.useEffect)(()=>{let n;if(!s||!i)return;let r=()=>{window.clearTimeout(n),n=void 0},a=()=>{r(),"visible"===document.visibilityState&&document.hasFocus()&&(n=window.setTimeout(()=>{n=void 0,"visible"===document.visibilityState&&document.hasFocus()&&t.refreshHeads(e.cwd)},1e3))},l=()=>{"visible"!==document.visibilityState&&r()};return a(),window.addEventListener("focus",a),window.addEventListener("blur",r),document.addEventListener("visibilitychange",l),()=>{r(),window.removeEventListener("focus",a),window.removeEventListener("blur",r),document.removeEventListener("visibilitychange",l)}},[s,i,t,e.cwd]);let d=c?.repositories??[],u=(0,uc.A_)(e.projectName,d,o);if(c?.status==="ready"&&!u)return null;let m=c?.status==="loading"&&!u,p=c?.status==="error"&&!u,h=m?null:u;return(0,n.jsxs)(lG,{"data-testid":"composer-git-branch",tooltip:p?c.error??l("gitStatusReadFailed"):h?.title??l("gitBranches"),"aria-label":l("gitBranches"),className:pn().branchTrigger,disabled:m,onClick:()=>a({workId:e.workId,cwd:e.cwd,projectName:e.projectName,repositoryRoot:null}),children:[m?(0,n.jsx)(v.A,{className:"size-4 shrink-0 animate-spin"}):(0,n.jsx)(ul.A,{className:"size-4 shrink-0 text-emerald-600 dark:text-emerald-400"}),p?(0,n.jsx)("span",{className:(0,C.cn)(pn().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)(pn().branchFull,h.diverged&&"text-amber-600 dark:text-amber-400"),children:h.full})}):null]})}let pi="l2-workbench-slash-command-menu",pa={key:"builtin:reload",name:"reload",description:"重新读取 Pi 最新配置与扩展资源",source:"builtin"},pl=[{source:"builtin",label:"Pi 内置命令"},{source:"skill",label:"Skills"},{source:"prompt",label:"提示模板"},{source:"extension",label:"扩展命令"}];function po(e){return`${pi}-option-${e}`}function pc(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function pd(e){return[...e.children].filter(e=>e instanceof HTMLElement)}function pu(e,t,s){return e.reduce((e,t)=>e+(s.get(t)??0),0)+Math.max(0,e.length-1)*t}var pm=s(64696);let pp=2*Math.PI*7;function ph(e){if(null===e)return"--";let t=Math.round(e);return t<1e3?String(t):`${Math.round(t/100)/10}K`}function pg(e){return Math.min(100,Math.max(0,e))}function pf(e){return pp-e/100*pp}function px({sessionId:e,cwd:t,tokens:s,contextWindow:i,contextIgnorePlugin:a,ignoreDisabled:l,ignorePending:o,compactDisabled:c,compactPending:d,onIgnoreContext:u,onCompactContext:m}){let p,h,g,f,x,{t:w}=(0,b.Bd)("workbench"),y=(0,r.useId)(),k=(0,r.useRef)(!1),[j,N]=(0,r.useState)(!1),[S,E]=(0,r.useState)(!1),[M,z]=(0,r.useState)(!1),A=(0,X.G)(),$=(p=!a||"object"!=typeof a||Array.isArray(a)||"number"!=typeof a.ignoredTokens||!Number.isFinite(a.ignoredTokens)||a.ignoredTokens<0||"number"!=typeof a.potentialTokens||!Number.isFinite(a.potentialTokens)||a.potentialTokens<0||void 0!==a.effectiveTokens&&null!==a.effectiveTokens&&("number"!=typeof a.effectiveTokens||!Number.isFinite(a.effectiveTokens)||a.effectiveTokens<0)?null:{ignoredTokens:a.ignoredTokens,potentialTokens:a.potentialTokens,...void 0!==a.effectiveTokens?{effectiveTokens:a.effectiveTokens}:{}},g=null===(h=p?.effectiveTokens===void 0?s:p.effectiveTokens)?0:pg(h/i*100),x=null===(f=null===h||null===p?null:Math.max(0,h-p.potentialTokens))?null:pg(f/i*100),{contextIgnore:p,currentTokens:h,usedPercent:g,projectedTokens:f,projectedPercent:x,potentialSegmentPercent:null===x?0:Math.max(0,g-x)}),R=Math.round($.usedPercent),P=null===$.projectedPercent?null:Math.round($.projectedPercent),D=R>=90?"text-destructive":R>=80?"text-status-warning":"text-muted-foreground",T=R>=90?"bg-destructive":R>=80?"bg-status-warning":"bg-primary",O=$.contextIgnore?w("contextUsageWithIgnore",{percent:R,projected:P??0,ignored:ph($.contextIgnore.ignoredTokens),potential:ph($.contextIgnore.potentialTokens)}):w("contextUsageSimple",{percent:R,limit:ph(i)});return(0,n.jsxs)(lY,{open:j,triggerId:y,onOpenChange:(e,t)=>{k.current&&"trigger-focus"===t.reason||(e||(E(!1),z(!1)),N(e))},children:[(0,n.jsx)(lV,{id:y,delay:100,closeDelay:100,render:(0,n.jsx)("button",{type:"button","aria-label":O,"aria-expanded":j,className:"inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full bg-transparent transition-colors outline-none hover:bg-accent focus-visible:ring-1 focus-visible:ring-ring/50 data-open:bg-accent",onPointerDown:e=>{k.current="mouse"!==e.pointerType},onPointerCancel:()=>{k.current=!1},onClick:e=>{k.current&&(e.preventDefault(),N(e=>!e),queueMicrotask(()=>{k.current=!1}))},children:(0,n.jsxs)("svg",{className:"pointer-events-none block size-5 -rotate-90",viewBox:"0 0 20 20","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-muted-foreground opacity-20"}),$.contextIgnore?(0,n.jsxs)(n.Fragment,{children:[$.usedPercent>0?(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2",strokeDasharray:pp,strokeDashoffset:pf($.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:pp,strokeDashoffset:pf($.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:pp,strokeDashoffset:pf($.usedPercent),className:D}):null]})})}),(0,n.jsx)(lU,{side:"top",align:"center",sideOffset:6,"aria-label":w("contextDetails"),className:"w-80 max-w-[calc(100vw-2rem)] p-4 text-sm",children:(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 text-sm",children:[(0,n.jsx)("span",{className:"whitespace-nowrap text-muted-foreground",children:w("contextMetrics")}),(0,n.jsxs)("span",{className:"whitespace-nowrap font-medium tabular-nums text-foreground",children:[ph($.currentTokens)," / ",ph(i)," / ",R,"%"]})]}),(0,n.jsx)("div",{className:"flex h-1.5 overflow-hidden rounded-full bg-muted",children:$.contextIgnore&&null!==$.projectedPercent?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"h-full bg-foreground",style:{width:`${$.projectedPercent}%`}}),(0,n.jsx)("div",{className:"h-full bg-muted-foreground",style:{width:`${$.potentialSegmentPercent}%`}})]}):(0,n.jsx)("div",{className:(0,C.cn)("h-full rounded-full",T),style:{width:`${$.usedPercent}%`}})})]}),$.contextIgnore&&null!==$.projectedTokens?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-2 rounded-full bg-foreground"}),w("afterIgnore")]}),(0,n.jsxs)("span",{className:"font-medium tabular-nums text-foreground",children:[ph($.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:ph($.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:ph($.contextIgnore.ignoredTokens)})]})]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:[(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",disabled:l||o||!$.contextIgnore||$.contextIgnore.potentialTokens<=0,"aria-label":$.contextIgnore&&$.contextIgnore.potentialTokens>0?w("ignoreNow",{amount:ph($.contextIgnore.potentialTokens)}):w("nothingToIgnore"),"aria-busy":o,onClick:()=>void u(),children:[o?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(pm.A,{}),o?w("ignoring"):w("ignore")]}),(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"outline",disabled:c||d,"aria-busy":d,onClick:()=>void m(),children:[d?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(o_.A,{}),d?w("compacting"):w("compact")]})]}),R>=80?(0,n.jsx)("p",{className:(0,C.cn)("pt-1 text-sm",R>=90?"text-destructive":"text-status-warning"),children:R>=90?w("contextCritical"):w("contextWarning")}):null,(0,n.jsx)("div",{className:"border-t border-border"}),(0,n.jsxs)("button",{type:"button","aria-label":w("copySessionId",{id:e}),className:"w-full cursor-pointer rounded-md px-1 py-1 text-left transition-colors outline-none hover:bg-muted focus-visible:ring-1 focus-visible:ring-ring/50",onClick:()=>{(0,e9.x)(e).then(e=>{e?E(!0):A.error(w("copySessionFailed"))})},children:[(0,n.jsxs)("span",{className:"flex items-center justify-between gap-3 text-muted-foreground",children:[(0,n.jsx)("span",{children:w("currentSessionId")}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-1",children:[S?w("copied"):w("clickToCopy"),S?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})]})]}),(0,n.jsx)("span",{className:"mt-1 block break-all font-mono text-xs leading-5 text-foreground",children:e})]}),(0,n.jsxs)("button",{type:"button","aria-label":w("copyCurrentPath",{path:t}),className:"w-full cursor-pointer rounded-md px-1 py-1 text-left transition-colors outline-none hover:bg-muted focus-visible:ring-1 focus-visible:ring-ring/50",onClick:()=>{(0,e9.x)(t).then(e=>{e?z(!0):A.error(w("copyPathFailed"))})},children:[(0,n.jsxs)("span",{className:"flex items-center justify-between gap-3 text-muted-foreground",children:[(0,n.jsx)("span",{children:w("currentPath")}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-1",children:[M?w("copied"):w("clickToCopy"),M?(0,n.jsx)(ep.A,{className:"size-3.5"}):(0,n.jsx)(ee.A,{className:"size-3.5"})]})]}),(0,n.jsx)("span",{className:"mt-1 block min-w-0 break-words font-mono text-xs leading-5 text-foreground",title:t,children:t})]})]})})]})}function pb(e,t){let[s,n]=(0,r.useState)({value:null,loading:!1,error:null}),[i,a]=(0,r.useState)(0);return(0,r.useEffect)(()=>{if(!e)return;let s=!0;return Promise.resolve().then(async()=>{if(s){n({value:null,loading:!0,error:null});try{let e=await t();s&&n({value:e,loading:!1,error:null})}catch(e){s&&n({value:null,loading:!1,error:e instanceof Error?e.message:String(e)})}}}),()=>{s=!1}},[i,e,t]),{...s,retry:()=>a(e=>e+1)}}let pv={direct:["toolExposureDirect","直接使用"],"model-only":["toolExposureModelOnly","仅模型调用"],codemode:["toolExposureCodemode","通过脚本调用"],deferred:["toolExposureDeferred","按需发现"],hidden:["toolExposureHidden","不可调用"]};function pw({tools:e}){let{t}=(0,b.Bd)("workbench"),[s,i]=(0,r.useState)(""),[a,l]=(0,r.useState)("all"),o=s.trim().toLocaleLowerCase(),c=e.filter(e=>(!o||`${e.name} ${e.source??""} ${e.description}`.toLocaleLowerCase().includes(o))&&("all"===a||("blocked"===a?e.blockedByMode:e.exposure===a)));return(0,n.jsxs)("section",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsxs)(nC.MG,{className:"min-w-0 flex-1 basis-56",children:[(0,n.jsx)(nC.Sq,{children:(0,n.jsx)(eh.A,{className:"size-4"})}),(0,n.jsx)(nC.iV,{"aria-label":t("searchTools"),placeholder:t("searchToolsSources",{defaultValue:"搜索名称、来源或描述"}),value:s,onChange:e=>i(e.target.value)})]}),(0,n.jsxs)(ea.l6,{value:a,onValueChange:e=>{"string"==typeof e&&l(e)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("toolFilter"),className:"max-w-full",children:(0,n.jsx)(ea.yv,{children:"all"===a?t("allTools"):"blocked"===a?t("toolBlockedByMode"):t(pv[a]?.[0]??"toolUnknown")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(ea.eb,{value:"all",children:t("allTools")}),Object.entries(pv).map(([e,[s,r]])=>(0,n.jsx)(ea.eb,{value:e,children:t(s,{defaultValue:r})},e)),(0,n.jsx)(ea.eb,{value:"blocked",children:t("toolBlockedByMode")})]})]})]}),(0,n.jsxs)("div",{className:"divide-y",children:[c.map(e=>{let s=e.exposure?pv[e.exposure]:null;return(0,n.jsxs)("article",{className:"space-y-2 py-3",children:[(0,n.jsx)("h3",{className:"wrap-anywhere font-mono text-sm font-medium",children:e.name}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:[t("toolSource",{defaultValue:"来源"}),":"," ",e.source??t("toolUnknown",{defaultValue:"未知"})]}),(0,n.jsx)("span",{children:s?t(s[0],{defaultValue:s[1]}):t("toolUnknown",{defaultValue:"未知"})}),(0,n.jsx)("span",{children:void 0===e.active?t("toolUnknown",{defaultValue:"未知"}):e.active?t("toolActive",{defaultValue:"当前已选用"}):t("toolInactive",{defaultValue:"当前未选用"})}),(0,n.jsx)("span",{children:void 0===e.blockedByMode?t("toolModeUnknown",{defaultValue:"模式限制未知"}):e.blockedByMode?t("toolBlockedByMode",{defaultValue:"受模式限制"}):t("toolNotBlocked",{defaultValue:"未受模式限制"})})]}),(0,n.jsx)("p",{className:"whitespace-pre-wrap wrap-anywhere text-sm text-muted-foreground",children:e.description}),(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{className:"min-h-7 cursor-pointer text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:t("parameterSchema")}),(0,n.jsx)("pre",{className:"mt-2 whitespace-pre-wrap wrap-anywhere rounded-lg bg-muted p-3 font-mono text-sm leading-[1.6]",children:JSON.stringify(e.parameters,null,2)})]})]},e.name)}),c.length?null:(0,n.jsxs)("div",{className:"space-y-3 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)("p",{children:o||"all"!==a?t("noMatchingTools"):t("noRegisteredTools",{defaultValue:"当前会话没有登记工具"})}),o||"all"!==a?(0,n.jsx)(I.$,{variant:"outline",size:"sm",onClick:()=>{i(""),l("all")},children:t("clearSearch")}):null]})]})]})}function py({notices:e}){let{t}=(0,b.Bd)("workbench");return(0,n.jsx)("section",{"aria-label":t("nativeCommandOutput",{defaultValue:"会话命令输出"}),className:"space-y-3",children:e.length?e.map((e,t)=>(0,n.jsx)("p",{className:`whitespace-pre-wrap wrap-anywhere font-mono text-sm leading-[1.6] ${"error"===e.level?"text-destructive":"warning"===e.level?"text-amber-700 dark:text-amber-300":""}`,children:function(e){let t=[],s=0;for(let r of e.matchAll(/https?:\/\/[^\s<>"']+/g)){let i=r.index,a=r[0].replace(/[)\]。,.;]+$/,"");t.push(e.slice(s,i)),t.push((0,n.jsx)("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-2 wrap-anywhere",children:a},i)),s=i+a.length}return t.push(e.slice(s)),t}(e.message)},t)):(0,n.jsx)("p",{className:"py-6 text-sm text-muted-foreground",children:t("nativeCommandOutputEmpty",{defaultValue:"暂无会话命令输出"})})})}function pk({available:e,state:t,disabled:s,onExecute:i}){let{t:a}=(0,b.Bd)("workbench"),[l,o]=(0,r.useState)("status"),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(!1),p="status"!==l,h=c.trim(),g=p&&!/^[a-zA-Z0-9_-]+$/.test(h);return(0,n.jsxs)("div",{className:"space-y-4",children:[e?(0,n.jsxs)("form",{className:"space-y-3",onSubmit:e=>{e.preventDefault(),s||!t.ready||t.commandPending||g||"logout"===l&&!u||i("status"===l?"":`${l} ${h}`,"login"===l)},children:[(0,n.jsx)(n2,{label:a("mcpSessionActions",{defaultValue:"MCP 会话操作"}),layout:"segmented",value:l,onChange:e=>{o(e),m(!1)},options:[{value:"status",label:a("mcpStatus",{defaultValue:"状态"})},{value:"login",label:a("mcpLogin",{defaultValue:"登录"})},{value:"reconnect",label:a("mcpReconnect",{defaultValue:"重连"})},{value:"logout",label:a("mcpLogout",{defaultValue:"退出登录"})}]}),p?(0,n.jsxs)("label",{className:"block space-y-1 text-sm font-medium",children:[(0,n.jsx)("span",{children:a("mcpServerName",{defaultValue:"服务名称"})}),(0,n.jsx)(em.p,{value:c,onChange:e=>d(e.target.value),placeholder:a("mcpServerNamePlaceholder",{defaultValue:"输入真实服务名称"}),autoComplete:"off",maxLength:128})]}):null,p&&h&&g?(0,n.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:a("mcpServerNameInvalid",{defaultValue:"服务名称只能包含字母、数字、下划线和连字符。"})}):null,"logout"===l?(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-start gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",className:"mt-1 size-4 accent-primary",checked:u,onChange:e=>m(e.target.checked)}),(0,n.jsx)("span",{children:a("mcpLogoutConfirm",{defaultValue:"删除共享登录凭据,其他会话下次访问也可能需要重新登录。"})})]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(I.$,{type:"submit",size:"sm",disabled:s||!t.ready||null!==t.commandPending||g||"logout"===l&&!u,children:a("mcpExecute",{defaultValue:"执行"})}),t.commandPending?(0,n.jsxs)("span",{role:"status",className:"wrap-anywhere text-sm text-muted-foreground",children:[a("mcpExecuting",{defaultValue:"正在执行"})," ",t.commandPending]}):null]})]}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:a("mcpCommandUnavailable",{defaultValue:"当前会话未注册 MCP 命令。"})}),(0,n.jsxs)("div",{className:"border-t pt-4",children:[(0,n.jsx)("h3",{className:"mb-3 text-sm font-medium",children:a("nativeCommandOutput",{defaultValue:"会话命令输出"})}),(0,n.jsx)(py,{notices:t.notices})]})]})}function pj({open:e,source:t,runtime:s,getContext:i,listCommands:a,nativeUi:l,nativeBiz:o,commandsDisabled:c,onOpenChange:d,onOpenSettings:u}){let{t:m,i18n:p}=(0,b.Bd)("workbench"),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)("tools"),v=(0,X.G)(),{context:w,tools:y,commands:k}=function(e){let{source:t,runtime:s,getContext:n,listCommands:i,open:a,tab:l}=e,o=(0,r.useCallback)(()=>n({source:t}),[n,t]),c=(0,r.useCallback)(()=>s.listTools(t),[s,t]),d=(0,r.useCallback)(()=>i({source:t}),[i,t]);return{context:pb(a&&"system"===l,o),tools:pb(a&&"tools"===l,c),commands:pb(a&&"mcp"===l,d)}}({source:t,open:e,tab:f,runtime:s,getContext:i,listCommands:a}),j="system"===f?w:"tools"===f?y:k,N=l.state.snapshot.requests[0]?.id;(0,r.useEffect)(()=>{e&&N&&(l.setCollapsed(!1),d(!1))},[e,N,l,d]);let S=async()=>{w.value&&(await (0,e9.x)(w.value.systemPrompt)?g(!0):v.error(m("contextCopyFailed")))};return(0,n.jsx)(eN.YV,{open:e,onOpenChange:d,children:(0,n.jsxs)(eN.hA,{className:"h-[min(42rem,calc(100dvh-2rem))] max-w-[45rem]",children:[(0,n.jsxs)(eN.Hl,{className:"border-b p-4 pr-12",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)(nI.A,{className:"size-5 shrink-0 text-muted-foreground"}),(0,n.jsx)(eN.YM,{children:m("toolsAndContext",{defaultValue:"工具与上下文"})})]}),(0,n.jsx)(eN.uX,{className:"sr-only",children:m("sessionContextDescription",{defaultValue:"当前会话的登记工具、系统提示词和 MCP 原生命令"})})]}),(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-b px-4 py-3",children:[(0,n.jsx)(n2,{label:m("contextContents"),layout:"segmented",value:f,onChange:x,options:[{value:"tools",label:m("tools")},{value:"system",label:m("systemPrompt")},{value:"mcp",label:m("mcpSession",{defaultValue:"会话 MCP"})}]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:["system"===f?(0,n.jsxs)(I.$,{variant:"ghost",size:"sm",disabled:!w.value||w.loading,onClick:()=>void S(),children:[h?(0,n.jsx)(ep.A,{}):(0,n.jsx)(ee.A,{}),h?m("copied"):m("copy")]}):null,u?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{d(!1),u()},children:m("openSettings",{defaultValue:(p.resolvedLanguage??p.language).startsWith("en")?"Open settings":"打开设置"})}):null]})]}),(0,n.jsx)(eN._Y,{children:(0,n.jsx)("div",{className:"p-4",children:!j.loading&&(j.value||j.error)?j.error?(0,n.jsxs)("div",{className:"space-y-3 py-6",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:j.error}),(0,n.jsxs)(I.$,{variant:"outline",size:"sm",onClick:j.retry,children:[(0,n.jsx)(es.A,{}),m("contextRetry")]})]}):"tools"===f&&y.value?(0,n.jsx)(pw,{tools:y.value.tools}):"system"===f&&w.value?(0,n.jsx)("section",{"aria-label":m("systemPrompt"),children:(0,n.jsx)("pre",{className:"whitespace-pre-wrap wrap-anywhere font-mono text-sm leading-[1.6]",children:w.value.systemPrompt||m("emptyContent")})}):"mcp"===f&&k.value?(0,n.jsx)(pk,{available:k.value.commands.some(e=>"mcp"===e.name&&"extension"===e.source),state:l.state,disabled:c,onExecute:(e,s)=>{o.executeCommand(t,"mcp",e),s&&(l.setCollapsed(!1),d(!1))}}):null:(0,n.jsxs)("div",{role:"status",className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)(es.A,{className:"size-4 animate-spin"}),m("contextLoading")]})})})]})})}let pN={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pI({source:e,runtime:t,catalog:s,current:i,label:a,title:l,disabled:o,triggerClassName:c,detailsClassName:d,onOpenSettings:u}){let{t:m,i18n:p}=(0,b.Bd)("workbench"),[h,g]=(0,r.useState)(null),{open:f,pending:x,error:v,changeOpen:w,refresh:y,submit:k}=function(e,t,s){let[n,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)(null),d=(0,r.useRef)(null),u=(0,r.useRef)(!1),m=(0,r.useRef)(!0);(0,r.useEffect)(()=>(m.current=!0,()=>{m.current=!1,d.current=null}),[]);let p=()=>{t.loadModels(e,!0)},h=e=>{d.current=e?{}:null,i(e),e&&(c(null),p())},g=async(n,r)=>{if(s||u.current)return;let i=d.current;u.current=!0,l(!0),c(null);try{await t.setModel(e,{provider:n.provider,modelId:n.modelId,thinkingLevel:r}),i&&d.current===i&&h(!1)}catch(e){i&&d.current===i&&c(e instanceof Error?e.message:String(e))}finally{u.current=!1,m.current&&l(!1)}};return{open:n,pending:a,error:o,changeOpen:h,refresh:p,submit:g}}(e,t,o),j=s.models.find(e=>e.provider===i?.provider&&e.modelId===i.modelId),N=s.models.some(e=>"virtual"===e.kind)?[{key:"virtual",label:m("modelAutomaticRouting",{defaultValue:"自动路由"}),models:s.models.filter(e=>"virtual"===e.kind)},{key:"physical",label:m("modelFixed",{defaultValue:"固定模型"}),models:s.models.filter(e=>"physical"===e.kind)}].filter(e=>e.models.length>0):[{key:"all",label:m("allModels"),models:s.models}];return(0,n.jsxs)(K.rI,{open:f,onOpenChange:e=>{g(null),w(e)},children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)(lG,{title:l,"aria-label":m("chooseModel"),className:c}),children:[(0,n.jsx)(eD.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{"data-model-trigger-details":!0,className:d,children:(0,n.jsxs)("span",{className:"flex min-w-0 items-center gap-2 pl-2",children:[(0,n.jsx)("span",{className:"min-w-0 truncate",children:a}),(0,n.jsx)(eY.A,{className:"size-3 shrink-0"})]})})]}),(0,n.jsxs)(K.SQ,{align:"start",side:"top",className:"flex max-h-96 w-72 flex-col overflow-hidden p-0",children:[(0,n.jsxs)(K.I,{className:"shrink-0 p-1",children:[(0,n.jsx)(K.lp,{children:m("currentModel")}),(0,n.jsxs)("div",{className:"mx-1 mb-1 flex items-center gap-2 rounded-md border bg-muted/50 px-2 py-2",children:[(0,n.jsx)(eD.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",children:j?.name||i?.modelId||m("selectModel")}),(0,n.jsx)("p",{className:"truncate text-xs text-muted-foreground",children:i?.provider||m("selectModel")})]}),i?(0,n.jsx)("span",{className:"shrink-0 rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:m("thinkingLevel",{level:m(pN[i.thinkingLevel])})}):null]}),v?(0,n.jsx)("p",{role:"alert",className:"wrap-anywhere px-2 py-1 text-sm text-destructive",children:v}):null,x?(0,n.jsx)("p",{role:"status",className:"px-2 py-1 text-sm text-muted-foreground",children:m("modelChanging",{defaultValue:"正在切换模型…"})}):null]}),(0,n.jsx)(K.mB,{className:"mx-0 my-0 shrink-0"}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-auto overflow-x-hidden overflow-y-auto overscroll-contain p-1",children:["loading"===s.status?(0,n.jsxs)(K._2,{disabled:!0,children:[(0,n.jsx)(es.A,{className:"size-4 animate-spin"}),m("modelsLoading")]}):null,"error"===s.status?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{role:"alert",className:"wrap-anywhere px-2 py-1 text-sm text-destructive",children:s.error||m("modelsFailed")}),(0,n.jsxs)(K._2,{closeOnClick:!1,onClick:y,children:[(0,n.jsx)(es.A,{className:"size-4"}),m("retry")]})]}):null,N.map(e=>(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:e.label}),e.models.map(e=>{let t=`${e.provider}:${e.modelId}`,s=i?.provider===e.provider&&i.modelId===e.modelId;return(0,n.jsxs)(K.lv,{open:h===t,onOpenChange:e=>{g(s=>e?t:s===t?null:s)},children:[(0,n.jsxs)(K.nV,{disabled:o||x,label:e.name||e.modelId,children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.name||e.modelId}),e.input.includes("image")?(0,n.jsx)(ru.A,{className:"size-3 text-muted-foreground"}):null,s?(0,n.jsx)(ep.A,{className:"size-3 text-muted-foreground"}):null]}),(0,n.jsx)(K.M5,{children:(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:m("thinkingLevels")}),e.thinkingLevels.map(t=>(0,n.jsxs)(K._2,{disabled:o||x,closeOnClick:!1,onClick:()=>{g(null),k(e,t)},children:[(0,n.jsx)("span",{className:"flex-1",children:m(pN[t])}),s&&i?.thinkingLevel===t?(0,n.jsx)(ep.A,{className:"size-3 text-muted-foreground"}):null]},t))]})})]},t)})]},e.key)),"ready"===s.status&&0===s.models.length?(0,n.jsx)(K._2,{disabled:!0,children:m("noModels")}):null,u&&("error"===s.status||"ready"===s.status&&0===s.models.length)?(0,n.jsx)(K._2,{onClick:()=>u(),children:m("openSettings",{defaultValue:(p.resolvedLanguage??p.language).startsWith("en")?"Open settings":"打开设置"})}):null]}),"ready"===s.status||s.presets.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(K.mB,{className:"mx-0 my-0 shrink-0"}),(0,n.jsxs)(K.I,{className:"shrink-0 p-1",children:[(0,n.jsx)(K.lp,{children:m("presets")}),0===s.presets.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:m("commonCombinationsEmpty")}),u?(0,n.jsxs)(K._2,{onClick:()=>{w(!1),u("model-presets")},children:[(0,n.jsx)(aI.A,{className:"size-4"}),m("configureCommonCombinations")]}):null]}):null,s.presets.map((e,t)=>(0,n.jsxs)(K._2,{disabled:o||x,closeOnClick:!1,onClick:()=>void k(e,e.thinkingLevel),children:[(0,n.jsx)("span",{className:"size-2 rounded-full bg-current",style:e.color?{color:e.color}:void 0}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:s.models.find(t=>t.provider===e.provider&&t.modelId===e.modelId)?.name||e.modelId}),(0,n.jsx)("span",{className:"text-muted-foreground",children:m(pN[e.thinkingLevel])})]},`${e.provider}:${e.modelId}:${e.thinkingLevel}:${t}`))]})]}):null]})]})}var pS=s(15824);function pC({label:e,description:t,markerClass:s,countClass:r,inputs:i}){let{t:a}=(0,b.Bd)("workbench");return 0===i.length?null:(0,n.jsxs)("section",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-3 px-1",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:`size-1.5 shrink-0 rounded-full ${s}`}),(0,n.jsx)("h3",{className:"text-sm font-medium text-foreground",children:e})]}),(0,n.jsx)("p",{className:"mt-1 pl-3.5 text-sm leading-5 text-muted-foreground",children:t})]}),(0,n.jsx)("span",{className:`shrink-0 rounded-md px-1.5 py-0.5 text-xs font-medium tabular-nums ${r}`,children:a("queueItems",{count:i.length})})]}),(0,n.jsx)("ol",{className:"divide-y divide-border overflow-hidden",children:i.map((e,t)=>{let s=e.text.trim();return(0,n.jsxs)("li",{className:"grid grid-cols-[1.25rem_minmax(0,1fr)] gap-2.5 px-3 py-2.5",children:[(0,n.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center rounded-md bg-muted text-xs tabular-nums text-muted-foreground",children:t+1}),(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsx)("p",{className:"whitespace-pre-wrap break-words text-sm leading-6 text-foreground",children:s||a(e.images.length>0?"imageOnly":"noMessageText")}),e.images.length>0?(0,n.jsxs)("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[(0,n.jsx)(ru.A,{className:"size-3"}),a("queueImages",{count:e.images.length})]}):null]})]},e.tempId)})})]})}function pE({queues:e,disabled:t,onRestore:s}){let{t:i}=(0,b.Bd)("workbench"),a=(0,r.useId)(),l=(0,r.useRef)(!1),[o,c]=(0,r.useState)(!1),d=e.steering.length+e.followUp.length;return 0===d?null:(0,n.jsxs)(lY,{open:o,triggerId:a,onOpenChange:(e,t)=>{l.current&&"trigger-focus"===t.reason||c(e)},children:[(0,n.jsx)(lV,{id:a,delay:100,closeDelay:120,render:(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",disabled:t,"aria-label":i("viewQueued",{count:d}),"aria-expanded":o,onPointerDown:e=>{l.current="mouse"!==e.pointerType},onPointerCancel:()=>{l.current=!1},onClick:e=>{l.current&&(e.preventDefault(),c(e=>!e),queueMicrotask(()=>{l.current=!1}))},children:i("queuedCount",{count:d})})}),(0,n.jsxs)(lU,{side:"top",align:"end",sideOffset:6,"aria-label":i("queueCurrent"),className:"w-[22rem] max-w-[calc(100vw-2rem)] overflow-hidden p-0",children:[(0,n.jsx)("div",{className:"border-b px-4 py-3",children:(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground",children:(0,n.jsx)(pS.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("h2",{className:"text-sm font-semibold tracking-tight text-foreground",children:i("queueCurrent")}),(0,n.jsx)("p",{className:"mt-1 text-sm leading-5 text-muted-foreground",children:i("queuePendingDescription")})]}),(0,n.jsx)("span",{className:"shrink-0 rounded-md bg-muted px-2 py-1 text-xs tabular-nums text-foreground",children:i("queueItems",{count:d})})]})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar max-h-[min(24rem,55dvh)] space-y-4 overflow-y-auto p-4",children:[(0,n.jsx)(pC,{label:i("queueSteer"),description:i("queueSteerDescription"),markerClass:"bg-foreground",countClass:"bg-muted text-muted-foreground",inputs:e.steering}),(0,n.jsx)(pC,{label:i("queueFollowUp"),description:i("queueFollowUpDescription"),markerClass:"bg-muted-foreground",countClass:"bg-muted text-muted-foreground",inputs:e.followUp})]}),(0,n.jsx)("div",{className:"border-t border-border/60 bg-muted/15 p-2",children:(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",className:"w-full text-muted-foreground hover:text-foreground",disabled:t,onClick:s,children:[(0,n.jsx)(lP.A,{}),i("queueRestore")]})})]})]})}let pM={builtin:"slashGroupBuiltin",skill:"slashGroupSkill",prompt:"slashGroupPrompt",extension:"slashGroupExtension"};function pz({open:e,loading:t,error:s,groups:i,activeIndex:a,onActiveIndexChange:l,onSelect:o}){let{t:c}=(0,b.Bd)("workbench"),d=(0,r.useRef)(null),u=i.reduce((e,t)=>e+t.commands.length,0);if((0,r.useEffect)(()=>{d.current?.scrollIntoView({block:"nearest"})},[a]),!e)return null;let m=0,p=u>0,h=t?c("slashLoadingMore"):s?c("slashMoreFailed"):null;return(0,n.jsxs)("div",{id:pi,role:"listbox","aria-label":c("slashCandidates"),"aria-busy":t,className:"absolute bottom-full left-[-1px] z-20 mb-2 flex w-[calc(100%+2px)] origin-bottom-left flex-col overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2 duration-100",children:[(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar max-h-72 overflow-x-hidden overflow-y-auto overscroll-contain p-1 scroll-py-8 max-sm:max-h-[40dvh]",children:[i.map((e,t)=>(0,n.jsxs)("section",{role:"group","aria-label":c(pM[e.source]),className:(0,C.cn)(t>0&&"mt-1 border-t pt-1"),children:[(0,n.jsxs)("div",{className:"sticky -top-1 z-10 flex h-7 items-center gap-2 bg-popover px-2 text-xs font-medium text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-1.5 rounded-full bg-muted-foreground"}),(0,n.jsx)("span",{children:c(pM[e.source])}),(0,n.jsx)("span",{className:"ml-auto font-normal tabular-nums opacity-70",children:e.commands.length})]}),e.commands.map(e=>{let t=m++,s=t===a;return(0,n.jsxs)("div",{id:po(t),ref:s?d:void 0,role:"option","aria-selected":s,"data-active":s?"true":"false",className:"grid min-h-9 cursor-pointer grid-cols-[minmax(6.75rem,0.9fr)_minmax(0,1.2fr)_0.75rem] items-center gap-2 rounded-md px-2 py-1 text-sm outline-none select-none data-[active=true]:bg-accent sm:grid-cols-[minmax(7rem,0.8fr)_minmax(0,1.5fr)_1rem]",onPointerMove:e=>{"mouse"===e.pointerType&&l(t)},onPointerDown:e=>e.preventDefault(),onClick:()=>o(t),children:[(0,n.jsxs)("span",{className:"min-w-0 truncate font-mono text-sm font-medium",children:[(0,n.jsx)("span",{className:"text-primary",children:"/"}),e.name]}),(0,n.jsx)("span",{className:"min-w-0 truncate text-sm text-muted-foreground",children:"builtin"===e.source&&"reload"===e.name?c("reloadDescription"):e.description}),(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("text-right text-sm text-muted-foreground opacity-0",s&&"opacity-80"),children:"↵"})]},e.key)})]},e.source)),p?h?(0,n.jsxs)("div",{className:"flex min-h-7 items-center gap-2 px-2 text-xs text-muted-foreground",children:[t?(0,n.jsx)(v.A,{className:"size-3 animate-spin"}):null,(0,n.jsx)("span",{children:h})]}):null:(0,n.jsxs)("div",{className:"flex min-h-20 items-center justify-center gap-2 px-4 text-xs text-muted-foreground",children:[t?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):null,(0,n.jsx)("span",{children:t?c("slashLoading"):s?c("slashFailed"):c("slashEmpty")})]})]}),(0,n.jsxs)("div",{className:"flex min-h-7 items-center justify-between gap-3 border-t px-2.5 text-xs text-muted-foreground",children:[(0,n.jsx)("span",{className:"tabular-nums",children:i.length>0?c("slashSummary",{commands:u,groups:i.length}):c("slashCount",{count:u})}),(0,n.jsxs)("span",{className:"flex items-center gap-2 max-sm:hidden","aria-hidden":"true",children:[(0,n.jsx)("span",{children:c("slashUpDown")}),(0,n.jsx)("span",{children:c("slashEnter")}),(0,n.jsx)("span",{children:c("slashEscape")})]})]})]})}var pA=s(58270),p$=s.n(pA);function pR({modes:e,value:t,disabled:s,onChange:r}){let{t:i}=(0,b.Bd)("capabilityModes");if(0===Object.keys(e).length)return null;let a=null===t?i("allEnabled"):Object.hasOwn(e,t)?e[t]:i("modeSwitching");return(0,n.jsxs)(K.rI,{children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)(I.$,{variant:"ghost",size:"sm",disabled:s,"aria-label":i("modePicker",{name:a}),className:"min-w-0 max-w-40 text-muted-foreground"}),children:[(0,n.jsx)(eg.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 truncate",children:a}),(0,n.jsx)(eY.A,{className:"size-3 shrink-0"})]}),(0,n.jsx)(K.SQ,{side:"top",align:"start",className:"max-h-80 min-w-40 overflow-y-auto",children:(0,n.jsxs)(K.Hr,{value:t??"",onValueChange:e=>r("string"==typeof e&&e?e:null),children:[(0,n.jsx)(K.Ht,{value:"",children:i("allEnabled")}),Object.entries(e).map(([e,t])=>(0,n.jsx)(K.Ht,{value:e,children:t},e))]})})]})}var pP=s(18903),pD=s(8356),pT=s(93192);function pO({request:e,model:t}){let{t:s}=(0,b.Bd)("workbench"),i=(0,r.useId)(),[a,l]=(0,r.useState)(!1),[o,c]=(0,r.useState)(()=>Date.now()),{state:d}=t,u=Object.hasOwn(d.answers,e.id),m=d.answers[e.id]??("editor"===e.method?e.prefill:""),p=null!==e.expiresAt&&e.expiresAt<=o,h=!d.ready||null!==d.submitting||null!==d.unknown||p,g=h||"select"===e.method&&!u;(0,r.useEffect)(()=>{if(null===e.expiresAt)return;let t=window.setInterval(()=>c(Date.now()),500);return()=>window.clearInterval(t)},[e.expiresAt]);let f=s=>{s?.preventDefault(),g||t.answer(e.id,"confirm"===e.method||m)},x=s=>(0,n.jsx)(t7.T,{"aria-label":e.title,"aria-labelledby":s?void 0:i,className:s?"min-h-0 flex-1 resize-none text-base":"h-32 min-h-20 resize-none text-base",value:m,disabled:null!==d.submitting,maxLength:65536,onChange:s=>t.setAnswer(e.id,s.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),f())}}),v=(r=!1)=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",disabled:!r&&!t.canStop,onClick:r?()=>l(!1):t.stop,children:r?s("nativeUiBack"):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(m9.A,{className:"size-3.5"}),s("nativeUiStop")]})}),(0,n.jsx)("span",{className:"flex-1"}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"outline",disabled:h,onClick:()=>t.answer(e.id,"confirm"!==e.method&&null),children:s("confirm"===e.method?"nativeUiReject":"nativeUiCancel")}),(0,n.jsx)(I.$,{type:r?"button":"submit",size:"sm",disabled:g,onClick:r?()=>f():void 0,children:s(d.submitting?"nativeUiSubmitting":"confirm"===e.method?"nativeUiConfirm":"nativeUiSubmit")})]});return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("section",{className:"mb-2 overflow-hidden rounded-xl border border-input bg-background","aria-label":s("nativeUiTitle"),"data-testid":"native-ui-question",onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||a||(e.preventDefault(),e.stopPropagation(),t.setCollapsed(!0))},children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 px-3 pt-2 text-xs text-muted-foreground",children:[(0,n.jsx)(pP.A,{className:"size-3.5"}),(0,n.jsx)("span",{children:s("nativeUiTitle")}),d.snapshot.requests.length>1?(0,n.jsx)("span",{children:s("nativeUiMore",{count:d.snapshot.requests.length-1})}):null,(0,n.jsx)("span",{className:"flex-1"}),"editor"===e.method?(0,n.jsxs)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>l(!0),children:[(0,n.jsx)(q.A,{className:"size-3.5"}),s("nativeUiExpand")]}):null,(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>t.setCollapsed(!0),children:s("nativeUiLater")})]}),(0,n.jsxs)("form",{onSubmit:f,children:[(0,n.jsxs)("div",{className:"max-h-[40dvh] space-y-3 overflow-y-auto px-3 pt-2 pb-3",children:[(0,n.jsx)("h3",{id:i,className:"text-base leading-6 font-medium whitespace-pre-wrap wrap-anywhere",children:e.title}),"confirm"===e.method?(0,n.jsx)("p",{className:"text-sm leading-6 whitespace-pre-wrap wrap-anywhere text-muted-foreground",children:e.message}):null,"select"===e.method?(0,n.jsx)(n2,{label:e.title,value:u?String(e.options.indexOf(m)):"",disabled:h,options:e.options.map((e,t)=>({value:String(t),label:e})),onChange:s=>t.setAnswer(e.id,e.options[Number(s)])}):null,"input"===e.method?(0,n.jsx)(em.p,{"aria-labelledby":i,value:m,placeholder:e.placeholder,maxLength:65536,className:"text-base",disabled:null!==d.submitting,onChange:s=>t.setAnswer(e.id,s.target.value)}):null,"editor"===e.method?x(!1):null,null!==e.expiresAt?(0,n.jsxs)("p",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(pD.A,{className:"size-3.5"}),s("nativeUiCountdown",{seconds:Math.max(0,Math.ceil((e.expiresAt-o)/1e3))})]}):null]}),(0,n.jsx)("div",{className:"flex flex-wrap items-center gap-2 border-t px-3 py-2",children:v()})]})]}),"editor"===e.method&&a?(0,n.jsx)(eN.YV,{open:!0,onOpenChange:l,children:(0,n.jsxs)(eN.hA,{className:"h-[min(40rem,calc(100dvh-2rem))] max-w-3xl","data-testid":"native-ui-editor-dialog",children:[(0,n.jsx)(eN.Hl,{className:"px-4 pt-4 pr-12 pb-3",children:(0,n.jsx)(eN.YM,{children:e.title})}),d.error||!d.ready?(0,n.jsx)("p",{role:"status",className:"px-4 pb-3 text-sm text-muted-foreground",children:d.error??s("nativeUiDisconnected")}):null,(0,n.jsx)("div",{className:"flex min-h-0 flex-1 px-4 pb-4",children:x(!0)}),(0,n.jsx)(eN.vu,{children:v(!0)})]})}):null]})}function pL({model:e}){let{t}=(0,b.Bd)("workbench"),{state:s}=e,r=s.snapshot.requests[0];return(0,n.jsxs)(n.Fragment,{children:[s.error||!s.ready&&r?(0,n.jsxs)("div",{role:"status",className:"mb-2 flex flex-wrap items-center gap-2 rounded-lg bg-muted px-3 py-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:s.error??t("nativeUiDisconnected")}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:s.refreshing,onClick:e.refresh,children:[s.refreshing?(0,n.jsx)(v.A,{className:"size-3.5 animate-spin"}):null,t("nativeUiRetry")]}),r?null:(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:e.dismissError,children:t("close",{ns:"common"})})]}):null,r?s.collapsed?(0,n.jsxs)("div",{className:"mb-2 flex items-center gap-2 rounded-lg border px-3 py-2","data-testid":"native-ui-collapsed",children:[(0,n.jsx)(pP.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 text-sm",children:t("nativeUiPending",{count:s.snapshot.requests.length})}),(0,n.jsx)(I.$,{type:"button",variant:"outline",size:"sm",onClick:()=>e.setCollapsed(!1),children:t("nativeUiResume")})]}):(0,n.jsx)(pO,{request:r,model:e},r.id):null,s.notices.length>0?(0,n.jsxs)(eV.Nt,{defaultOpen:!!(r||s.commandPending?.startsWith("/mcp login ")),className:"mb-2 rounded-lg border px-3 py-2","data-testid":"native-ui-output",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)(eV.R6,{className:"group flex min-h-7 min-w-0 flex-1 cursor-pointer items-center gap-2 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eY.A,{className:"size-3.5 shrink-0 transition-transform group-data-panel-open:rotate-180 motion-reduce:transition-none"}),t("nativeCommandOutput",{defaultValue:"会话命令输出"})]}),(0,n.jsx)(I.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":t("close",{ns:"common"}),onClick:e.dismissNotices,children:(0,n.jsx)(V.A,{className:"size-3.5"})})]}),(0,n.jsx)(eV.Ke,{children:(0,n.jsx)("div",{className:"mt-2 max-h-40 overflow-y-auto",children:(0,n.jsx)(py,{notices:s.notices})})})]}):null,s.prefill?(0,n.jsxs)("div",{className:"mb-2 rounded-lg border px-3 py-2","data-testid":"native-ui-prefill",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"flex-1 text-sm font-medium",children:t("nativeUiDraft")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>e.usePrefill("dismiss"),children:t("nativeUiDismiss")})]}),(0,n.jsx)("p",{className:"my-2 max-h-24 overflow-y-auto text-sm whitespace-pre-wrap wrap-anywhere",children:s.prefill.text}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"secondary",onClick:()=>e.usePrefill("append"),children:t("nativeUiAppend")}),(0,n.jsx)(I.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>e.usePrefill("replace"),children:t("nativeUiReplace")})]})]}):null]})}function pF({snapshot:e,placement:t}){let{t:s}=(0,b.Bd)("workbench"),r=Object.entries(e.widgets).filter(([,e])=>e.placement===t),i="belowEditor"===t?Object.values(e.statuses):[];return r.length||i.length?(0,n.jsxs)("div",{className:"my-1.5 space-y-1","data-testid":`native-ui-extras-${t}`,children:[r.length?(0,n.jsxs)("details",{className:"group",children:[(0,n.jsxs)("summary",{className:"flex min-h-7 cursor-pointer items-center gap-2 text-xs text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(pT.A,{className:"size-3.5"}),s("nativeUiInfo"),(0,n.jsx)("span",{children:r.length>1?r.length:""}),(0,n.jsx)(eY.A,{className:"size-3.5 transition-transform group-open:rotate-180"})]}),(0,n.jsx)("div",{className:"max-h-36 space-y-2 overflow-y-auto px-2 pb-2 text-sm leading-6",children:r.map(([e,t])=>(0,n.jsx)("p",{className:"whitespace-pre-wrap wrap-anywhere",children:t.lines.join("\n")},e))})]}):null,i.length?(0,n.jsxs)("details",{className:"group",children:[(0,n.jsxs)("summary",{className:"flex min-h-7 cursor-pointer items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-1.5 shrink-0 rounded-full bg-current"}),(0,n.jsx)("span",{className:"min-w-0 truncate group-open:hidden",children:i[0]}),(0,n.jsx)("span",{className:"hidden group-open:inline",children:s("nativeUiStatus")}),i.length>1?(0,n.jsxs)("span",{children:["+",i.length-1]}):null]}),(0,n.jsx)("div",{className:"max-h-32 space-y-1 overflow-y-auto px-2 py-1 text-sm whitespace-pre-wrap wrap-anywhere",children:i.map((e,t)=>(0,n.jsx)("p",{children:e},t))})]}):null]}):null}let pB={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pq(e){return e<1048576?`${Math.max(1,Math.round(e/1024))}KB`:`${(e/1048576).toFixed(1)}MB`}let p_=(0,r.memo)(function({onOpenSettings:e,workSession:t,chatRuntime:s,inputRuntime:i,renderTaskSummary:a,renderTaskMenu:l,renderPluginComposerPanel:o,renderPluginWidgets:c,gitRuntime:d,active:u,widgetsVisible:m,mobile:p,invokePluginMethod:h,listPiCommands:g,getChatModelContext:f,capabilityModes:x,setChatCapabilityMode:w,newSessionPending:y,newSessionDisabled:k,onNewSession:j,clonePending:N,cloneDisabled:S,onCloneWorkSession:E,onOpenBranchPicker:M,onOpenGitBranchPicker:z}){var A;let $,R,D,T,O,{t:L}=(0,b.Bd)("workbench"),F=(0,X.G)(),B=(0,Q.So)(),q=(0,r.useMemo)(()=>uE.Pi.parse({workId:t.workId,sessionId:t.sessionId,branchId:t.branchId}),[t.branchId,t.sessionId,t.workId]),_=(0,r.useCallback)(()=>i.getState(q),[i,q]),W=(0,r.useCallback)(()=>s.getSourceState(q).runtime,[s,q]),Y=(0,r.useSyncExternalStore)(i.subscribe,_,_),U=(0,r.useSyncExternalStore)(s.subscribe,W,W),G=(0,r.useCallback)(()=>s.getSourceState(q).syncStatus,[s,q]),J="ready"===(0,r.useSyncExternalStore)(s.subscribe,G,G),Z=(A=s.nativeUi,$=(0,X.G)(),R=(0,r.useCallback)(()=>A.getState(q),[A,q]),D=(0,r.useSyncExternalStore)(A.subscribe,R,R),T=(0,r.useCallback)(()=>i.getState(q),[i,q]),O=(0,r.useSyncExternalStore)(i.subscribe,T,T),(0,r.useEffect)(()=>{A.watch(q)},[A,q]),(0,r.useEffect)(()=>A.onNotice((e,t)=>{e.workId===q.workId&&e.sessionId===q.sessionId&&e.branchId===q.branchId&&$.show({level:t.level,title:t.message})}),[A,q,$]),(0,r.useEffect)(()=>{!D.prefill||!O.loaded||O.loading||O.outbox||O.text.length>0||(i.setText(q,D.prefill.text),A.edit(q,{prefill:null}))},[A,q,i,D.prefill,O.loaded,O.loading,O.outbox,O.text]),{state:D,canStop:J,setAnswer:(e,t)=>A.edit(q,{answers:{...A.getState(q).answers,[e]:t}}),setCollapsed:e=>A.edit(q,{collapsed:e}),answer:(e,t)=>{A.respond(q,{id:e,value:t})},refresh:()=>{A.refreshSource(q)},dismissError:()=>A.edit(q,{error:null}),dismissNotices:()=>A.edit(q,{notices:[]}),usePrefill:e=>{let t=A.getState(q).prefill;if(t){if("dismiss"!==e){let s=i.getState(q).text;i.setText(q,"replace"===e?t.text:`${s}${s?"\n":""}${t.text}`)}A.edit(q,{prefill:null})}},stop:()=>{i.interrupt(q).catch(e=>$.error(e instanceof Error?e.message:String(e)))}}),ee=Z.state.snapshot.requests.length>0,en="basic"===U.extensionMode,er="basic"===U.presentationMode,ei=(0,r.useRef)(null),ea=(0,r.useRef)(null),el=(0,r.useRef)(null),eo=(0,r.useRef)(null),ec=function(e,t,s,n){let[i,a]=(0,r.useState)(!1);return(0,r.useLayoutEffect)(()=>{if(e)return;let r=t.current,i=r?.querySelector('[data-composer-tools="primary"]'),l=r?.querySelector('[data-composer-tools="metadata"]'),o=s.current;if(!r||!i||!l||!o)return;let c=0,d=null,u=()=>{if(null===d){let e=window.getComputedStyle(r);c=r.clientWidth-pc(e.paddingLeft)-pc(e.paddingRight);let t=pc(e.columnGap),s=pd(i),a=pd(l),u=pd(o),m=pc(window.getComputedStyle(i).columnGap),p=pc(window.getComputedStyle(l).columnGap),h=pc(window.getComputedStyle(o).columnGap),g=n.current,f=function(e){let t=[...new Set(e)],s=t.map(e=>({element:e,flex:e.style.flex,width:e.style.width,minWidth:e.style.minWidth}));try{for(let{element:e}of s)e.style.flex="0 0 auto",e.style.width="max-content",e.style.minWidth="max-content";return new Map(t.map(e=>[e,e.getBoundingClientRect().width]))}finally{for(let{element:e,flex:t,width:n,minWidth:r}of s)e.style.flex=t,e.style.width=n,e.style.minWidth=r}}([...s,...a,...u,...g?[g]:[]]),x=[pu(s,m,f),pu(a,p,f),g?f.get(g)??0:0,pu(u,h,f)].filter(e=>e>0);d=x.reduce((e,t)=>e+t,0)+Math.max(0,x.length-1)*t}a(d>c+1)},m=null,p=()=>{null===m&&(m=window.requestAnimationFrame(()=>{m=null,u()}))},h=()=>{d=null,p()},g=new ResizeObserver(([e])=>{e&&c!==e.contentRect.width&&(c=e.contentRect.width,p())}),f=new MutationObserver(h);return g.observe(r),f.observe(r,{childList:!0,characterData:!0,subtree:!0}),window.addEventListener("resize",h),document.fonts.addEventListener("loadingdone",h),u(),()=>{g.disconnect(),f.disconnect(),window.removeEventListener("resize",h),document.fonts.removeEventListener("loadingdone",h),null!==m&&window.cancelAnimationFrame(m)}},[t,e,n,s]),i}(p,ea,el,eo),[ed,eu]=(0,r.useState)(null),[em,ep]=(0,r.useState)(null),eh=(0,r.useCallback)(()=>{ep(null)},[]),[eg,ef]=(0,r.useState)(!1),[ex,eb]=(0,r.useState)(null),[ev,ew]=(0,r.useState)(!1),[ey,ek]=(0,r.useState)(!1),[ej,eN]=(0,r.useState)(!1),[eI,eS]=(0,r.useState)(null),[eC,eE]=(0,r.useState)(null),eM=JSON.stringify([q.workId,q.sessionId,q.branchId]),ez=(0,r.useMemo)(()=>en?[]:B.flatMap(e=>e.contributions.flatMap(t=>"composer-panel"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[B,en]),eA=em?ez.find(e=>e.pluginName===em.pluginName&&e.descriptor.contributionName===em.contributionName):void 0;(0,r.useEffect)(()=>{let e=!0;return queueMicrotask(()=>{e&&(ep(e=>e&&e.sourceKey!==eM?null:e),eb(null))}),()=>{e=!1}},[eM]),(0,r.useEffect)(()=>{i.loadSource(q),i.loadModels(q)},[i,q]);let e$="main_running"===t.status,eR=e$||"background_running"===t.status,eP="completed"===t.status,eD=null!==eC,eT=eC?.text??Y.text,eO=eC?.images??Y.images,eL=0===eO.length&&eT.trim()===`/${pa.name}`,eF=eO.reduce((e,t)=>e+t.blob.size,0),eB=Y.outbox&&!(eD&&"sending"===Y.outbox.status)?Y.outbox:null,e_=e$&&!eD,eW=U.queues,eY=Y.images.reduce((e,t)=>e+t.blob.size,0),eV=Y.images.some(e=>"optimizing"===e.status),eU=Y.images.some(e=>"error"===e.status),eH=U.model,eK=eH?Y.models.models.find(e=>e.provider===eH.provider&&e.modelId===eH.modelId):null,eG=Y.images.length>0&&!eK?.input.includes("image"),eJ=eg&&!ey,eQ=J&&!ee&&Y.loaded&&!Y.outbox&&(Y.text.trim().length>0||Y.images.length>0)&&Y.images.length<=10&&!eV&&!eU&&eY<=0x1400000&&!eG,eX=U.plugins["task-center"],eZ=U.contextUsage,e0=eK?.name||eH?.modelId||L("noModelSelected"),e1=J?eH?`${e0} \xb7 ${L(pB[eH.thinkingLevel])}`:L("selectModel"):L("synchronizing"),e2=eH?L("modelTooltip",{model:e1}):L("chooseModel"),e5=ed??Y.error,e3=(0,r.useCallback)(async(e,t)=>{ef(!0),eu(null);try{await e(),t&&F.success(t)}catch(e){eu(e instanceof Error?e.message:L("operationFailed"))}finally{ef(!1)}},[L,F]),e4=(0,r.useCallback)(e=>{eu(null),w({source:q,capabilityMode:e}).catch(e=>{eu(e instanceof Error?e.message:L("modeChangeFailed"))})},[w,q,L]),e6=(0,r.useCallback)(async()=>{if(!ev&&"ready"===s.getSourceState(q).syncStatus){ew(!0);try{await e3(async()=>{await h({pluginName:"context-ignore",method:"ignore",scope:"session",source:q,input:{}})})}finally{ew(!1)}}},[s,ev,h,e3,q]),e8=(0,r.useCallback)(async()=>{if(!ey){ek(!0);try{await e3(()=>s.compact(q))}finally{ek(!1)}}},[s,ey,e3,q]),e7=(0,r.useCallback)(e=>{i.setText(q,`/${e.name} `)},[i,q]),e9=function({source:e,text:t,enabled:s,listPiCommands:n,onSelect:i}){let a=JSON.stringify([e.workId,e.sessionId,e.branchId]),[l,o]=(0,r.useState)(!1),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)({sourceKey:a,status:"idle",commands:[],error:null}),g=(0,r.useRef)(0),f=(0,r.useRef)(!0),x=s&&!l?/^\/[^\s/]*$/.test(t)?t.slice(1):null:null,b=null===x?null:`${a}\u0000${t}`,v=null!==b&&b!==c,{workId:w,sessionId:y,branchId:k}=e;(0,r.useEffect)(()=>(f.current=!0,()=>{f.current=!1,g.current+=1}),[]);let j=(0,r.useCallback)(async()=>{let e=++g.current;queueMicrotask(()=>{f.current&&g.current===e&&h(e=>e.sourceKey===a?{...e,status:"loading",error:null}:{sourceKey:a,status:"loading",commands:[],error:null})});try{let t=await n({source:{workId:w,sessionId:y,branchId:k}});if(!f.current||g.current!==e)return;h({sourceKey:a,status:"ready",commands:t.commands,error:null})}catch(t){if(!f.current||g.current!==e)return;throw console.warn("[Pi Desk][SlashCommand] 查询当前会话命令失败",{workId:w,sessionId:y,branchId:k,errorName:t instanceof Error?t.name:"UnknownError"}),h(e=>({sourceKey:a,status:"error",commands:e.sourceKey===a?e.commands:[],error:t instanceof Error?t.message:"查询命令失败"})),t}},[k,a,n,y,w]);(0,r.useEffect)(()=>{v&&j().catch(()=>void 0)},[v,j]);let N=(0,r.useMemo)(()=>[pa,...(p.sourceKey===a?p.commands:[]).filter(e=>e.name!==pa.name).map(e=>({key:`${e.source}:${e.name}`,name:e.name,description:e.description,source:e.source}))],[a,p.commands,p.sourceKey]),I=(0,r.useMemo)(()=>{let e;return e=(x??"").toLocaleLowerCase(),pl.flatMap(t=>{let s=N.map((t,s)=>({command:t,order:s,score:function(e,t){if(!t)return 3;let s=e.name.toLocaleLowerCase(),n=e.description?.toLocaleLowerCase()??"";return s===t?0:s.startsWith(t)?1:s.includes(t)?2:n.includes(t)?4:1/0}(t,e)})).filter(e=>e.command.source===t.source&&Number.isFinite(e.score)).sort((t,s)=>t.score!==s.score?t.score-s.score:e?t.order-s.order:t.command.name.localeCompare(s.command.name)).map(e=>e.command);return s.length>0?[{...t,commands:s}]:[]})},[N,x]),S=(0,r.useMemo)(()=>I.flatMap(e=>e.commands),[I]),C=b&&u?.contextKey===b?S.findIndex(e=>e.key===u.commandKey):-1,E=C>=0?C:0,M=(0,r.useCallback)(e=>{if(!b||0===S.length)return;let t=(e+S.length)%S.length,s=S[t];s&&m({contextKey:b,commandKey:s.key})},[S,b]),z=(0,r.useCallback)(()=>{b&&d(b)},[b]),A=(0,r.useCallback)(()=>{b&&d(null)},[b]),$=(0,r.useCallback)(e=>{let t=S[e];t&&(b&&d(b),i(t))},[S,b,i]),R=(0,r.useCallback)(e=>!!v&&!e.nativeEvent.isComposing&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&("Escape"===e.key?(e.preventDefault(),z(),!0):0!==S.length&&("ArrowDown"===e.key?(e.preventDefault(),M(E+1),!0):"ArrowUp"===e.key?(e.preventDefault(),M(E-1),!0):("Enter"===e.key||"Tab"===e.key)&&(e.preventDefault(),$(E),!0))),[E,S.length,z,v,$,M]),P=(0,r.useCallback)(()=>{o(!0)},[]),D=(0,r.useCallback)(()=>{o(!1),d(null)},[]);return{open:v,loading:p.sourceKey===a&&"loading"===p.status,error:p.sourceKey===a&&"error"===p.status?p.error:null,groups:I,commands:S,activeIndex:E,dismiss:z,reopen:A,refresh:j,select:$,setActiveIndex:M,handleKeyDown:R,handleCompositionStart:P,handleCompositionEnd:D}}({source:q,text:eT,enabled:u&&J&&Y.loaded&&!Y.loading&&!eD,listPiCommands:g,onSelect:e7}),te=e9.refresh,tt=(0,r.useCallback)(async e=>{if(!ej&&!eg){eN(!0);try{await e3(async()=>{await s.reload(q),await te(),await i.loadModels(q,!0),e&&i.setText(q,"")})}finally{eN(!1)}}},[eg,s,i,te,ej,e3,q]),ts=(0,r.useCallback)(e=>{eD||0===e.length||(eu(null),i.addFiles(q,e))},[eD,i,q]),tn=(0,r.useCallback)(async e=>{if("ready"!==s.getSourceState(q).syncStatus)return;if(eL){if(!Y.loaded||Y.loading)return;await tt(!0);return}if(!eQ||eJ)return;let t=e$?null:{text:Y.text,images:Y.images};t&&eE(t),eu(null);try{await i.send(q,e)}catch(e){eu(e instanceof Error?e.message:L("sendFailed"))}finally{t&&eE(null)}},[eQ,eJ,s,i,Y.images,Y.loaded,Y.loading,Y.text,eL,e$,tt,q,L]);return(0,n.jsxs)("div",{className:"mx-auto w-full max-w-3xl px-2 pb-2 sm:px-4 sm:pb-3",children:[eB?(0,n.jsx)("div",{className:(0,C.cn)("mb-2 rounded-lg border px-3 py-2 text-xs","unknown"===eB.status?"border-amber-500/50 bg-amber-500/10 text-amber-900 dark:text-amber-200":"failed"===eB.status?"border-destructive/40 bg-destructive/5 text-destructive":"border-border bg-muted/50 text-muted-foreground"),children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:"sending"===eB.status?L("confirmingSend"):"unknown"===eB.status?L("sendUnknown"):L("sendFailure",{error:eB.error??L("unknownError")})}),"sending"===eB.status?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:eg,onClick:()=>void e3(()=>i.restoreOutbox(q),L("outboxRestored")),children:[(0,n.jsx)(lP.A,{}),L("restoreDraft")]}),(0,n.jsxs)(I.$,{type:"button",variant:"ghost",size:"sm",disabled:eg,onClick:()=>void e3(()=>i.deleteOutbox(q),L("outboxDeleted")),children:[(0,n.jsx)(et.A,{}),L("delete")]})]})]})}):null,Y.notice||e5?(0,n.jsx)("div",{role:e5?"alert":"status",className:(0,C.cn)("mb-2 rounded-md px-2 py-1 text-sm",e5?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground"),children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:e5??Y.notice}),Y.loaded||Y.loading||!Y.error?Y.loaded?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{eu(null),i.dismissFeedback(q)},children:L("close",{ns:"common"})}):null:(0,n.jsxs)(I.$,{type:"button",variant:"outline",size:"sm",disabled:eg,onClick:()=>void e3(()=>i.loadSource(q)),children:[(0,n.jsx)(lP.A,{}),L("retryDraft")]})]})}):null,a({source:q,cwd:t.cwd,pluginState:eX}),(0,n.jsx)(pL,{model:Z}),(0,n.jsx)(pF,{snapshot:Z.state.snapshot,placement:"aboveEditor"}),ee?(0,n.jsx)("p",{className:"mb-1 px-1 text-xs text-muted-foreground",children:L("nativeUiComposer")}):null,m&&!en?c({source:q,placement:"aboveEditor"}):null,(0,n.jsxs)("form",{"aria-label":eR?L("composerRunning"):eP?L("composerCompleted"):L("composer"),className:p$().inputFrame,"data-composer-mobile":p?"true":"false","data-composer-metadata-row":ec?"true":"false",onSubmit:e=>{e.preventDefault(),tn("auto")},onDragOver:e=>{e.dataTransfer.types.includes("Files")&&e.preventDefault()},onDrop:e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),ts([...e.dataTransfer.files]))},children:[(0,n.jsx)(pz,{open:e9.open,loading:e9.loading,error:e9.error,groups:e9.groups,activeIndex:e9.activeIndex,onActiveIndexChange:e9.setActiveIndex,onSelect:e9.select}),(0,n.jsx)("input",{ref:ei,type:"file",accept:"image/jpeg,image/png,image/webp,image/gif,image/bmp",multiple:!0,className:"hidden",onChange:e=>{e.currentTarget.files&&ts([...e.currentTarget.files]),e.currentTarget.value=""}}),(0,n.jsxs)(nC.MG,{className:"overflow-hidden rounded-xl border-border bg-card shadow-xs transition-[background-color,border-color] duration-150 ease-out has-disabled:bg-card has-disabled:opacity-100 dark:shadow-none motion-reduce:transition-none","aria-busy":eD,children:[eO.length>0?(0,n.jsxs)(nC.Sq,{align:"block-start",className:"pi-desk-chat-scrollbar gap-2 overflow-x-auto px-3 pt-3 pb-1",children:[eO.map(e=>(0,n.jsxs)("div",{className:"relative size-16 shrink-0 overflow-hidden rounded-md border bg-muted",title:`${e.name} \xb7 ${e.width}\xd7${e.height} \xb7 ${pq(e.blob.size)}`,children:[(0,n.jsx)("button",{type:"button",disabled:"ready"!==e.status,"aria-label":L("imagePreview",{name:e.name}),className:"group size-full cursor-zoom-in outline-none disabled:cursor-default focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",onClick:()=>{var t;let s,n;return t=e.localId,void(!((n=(s=eO.filter(e=>"ready"===e.status)).findIndex(e=>e.localId===t))<0)&&eS({index:n,slides:s.map(e=>({src:e.objectUrl,alt:e.name,width:e.width,height:e.height}))}))},children:(0,n.jsx)("img",{src:e.objectUrl,alt:e.name,className:"size-full object-cover transition-transform duration-200 group-hover:scale-105 motion-reduce:transition-none"})}),"optimizing"===e.status?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 grid place-items-center bg-background/85 text-xs",children:L("imageProcessing")}):null,"error"===e.status?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 bg-popover px-1 py-0.5 text-xs text-destructive",children:L("imageFailed")}):null,(0,n.jsx)("button",{type:"button","aria-label":L("imageRemove",{name:e.name}),"aria-disabled":eD,className:"absolute right-0.5 top-0.5 z-10 grid size-6 cursor-pointer place-items-center rounded-md bg-popover text-popover-foreground shadow-sm hover:bg-accent",onClick:()=>{eD||i.removeImage(q,e.localId)},children:(0,n.jsx)(V.A,{className:"size-3"})})]},e.localId)),(0,n.jsxs)("span",{className:"self-end whitespace-nowrap text-xs text-muted-foreground",children:[eO.length,"/10 \xb7 ",pq(eF)]})]}):null,(0,n.jsx)(nC.oR,{value:eT,disabled:!Y.loaded||Y.loading,readOnly:eD,"aria-disabled":eD,"aria-autocomplete":"list","aria-controls":e9.open?pi:void 0,"aria-expanded":e9.open,"aria-activedescendant":e9.open&&e9.commands.length>0?po(e9.activeIndex):void 0,placeholder:Y.loading?L("draftLoading"):!Y.loaded&&Y.error?L("draftFailed"):L("inputPlaceholder"),className:(0,C.cn)(p$().inputText,"pi-desk-chat-scrollbar max-h-48 min-h-9 overflow-y-auto px-3 pt-3 pb-1"),onChange:e=>i.setText(q,e.currentTarget.value),onClick:e9.reopen,onBlur:e9.dismiss,onCompositionStart:e9.handleCompositionStart,onCompositionEnd:e9.handleCompositionEnd,onKeyDown:e=>{e9.handleKeyDown(e)||"Enter"!==e.key||e.shiftKey||e.nativeEvent.isComposing||null===e.currentTarget.form||(e.preventDefault(),e.currentTarget.form.requestSubmit())},onPaste:e=>{let t=[...e.clipboardData?.items??[]].flatMap(e=>{if("file"!==e.kind)return[];let t=e.getAsFile();return t?[t]:[]});0!==t.length&&(e.preventDefault(),ts(t))}}),(0,n.jsxs)(lH,{ref:ea,className:p$().footer,children:[(0,n.jsxs)(lK,{"data-composer-tools":"primary",className:p$().primaryTools,children:[(0,n.jsxs)(K.rI,{children:[(0,n.jsx)(K.ty,{render:(0,n.jsx)(lG,{tooltip:L("more"),"aria-label":L("moreActions")}),children:(0,n.jsx)(H.A,{className:"size-4"})}),(0,n.jsxs)(K.SQ,{align:"start",side:"top",className:"w-52",children:[(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:L("session")}),(0,n.jsxs)(K._2,{"aria-label":L("switchBranch"),disabled:!J||!Y.loaded||Y.loading,onClick:()=>M(t.workId),children:[(0,n.jsx)(ul.A,{className:"size-4"}),L("sessionBranch"),(0,n.jsx)("span",{className:"ml-auto text-xs text-muted-foreground",children:L("escapeTwice")})]}),(0,n.jsxs)(K._2,{"aria-label":L("clone"),disabled:!J||S||N,title:0===t.messageCounts.total?L("cloneEmpty"):L("cloneTip"),onClick:E,children:[N?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(m4.A,{className:"size-4"}),N?L("cloning"):L("clone")]}),(0,n.jsxs)(K._2,{"aria-label":L("replaceSession"),"aria-busy":y,disabled:!J||k||y,onClick:j,children:[y?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(m6.A,{className:"size-4"}),y?L("replacing"):L("replaceSession")]})]}),(0,n.jsx)(K.mB,{}),(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:L("tools")}),l({source:q,cwd:t.cwd,pluginState:eX}),(0,n.jsxs)(K._2,{"aria-label":L("toolsAndContext",{defaultValue:"工具与上下文"}),disabled:!J||ee,onClick:()=>eb(eM),children:[(0,n.jsx)(nI.A,{className:"size-4"}),L("toolsAndContext",{defaultValue:"工具与上下文"})]}),(0,n.jsxs)(K._2,{"aria-label":L("reloadPi"),disabled:!Y.loaded||Y.loading||!J||eR||eg||ej,title:L("reloadPiTip"),onClick:()=>void tt(!1),children:[ej?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):(0,n.jsx)(es.A,{className:"size-4"}),ej?L("reloadingPi"):L("reloadPi")]}),er&&!en?(0,n.jsxs)(K._2,{disabled:!J||eg||ej,onClick:()=>void e3(()=>s.setPresentation(q,"normal")),children:[(0,n.jsx)(nI.A,{className:"size-4"}),L("restorePluginPresentation")]}):null]}),ez.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(K.mB,{}),(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:L("plugins")}),ez.map(e=>(0,n.jsxs)(K._2,{onClick:()=>ep({pluginName:e.pluginName,contributionName:e.descriptor.contributionName,sourceKey:eM}),children:[(0,n.jsx)(eq,{icon:e.descriptor.icon,className:"size-4"}),(0,n.jsx)("span",{className:"truncate",children:e.descriptor.label})]},`${e.pluginName}:${e.descriptor.contributionName}`))]})]}):null]})]}),(0,n.jsx)(lG,{tooltip:L("addImage"),"aria-label":L("addImage"),disabled:Y.images.length>=10,"aria-disabled":eD||Y.images.length>=10,onClick:()=>{eD||ei.current?.click()},children:(0,n.jsx)(m8.A,{className:"size-4"})}),eZ&&eK?.contextWindow!==null?(0,n.jsx)(px,{sessionId:t.sessionId,cwd:t.cwd,tokens:eZ.tokens,contextWindow:eZ.contextWindow,contextIgnorePlugin:U.plugins["context-ignore"],ignoreDisabled:!J||e$||eg,ignorePending:ev,compactDisabled:!J||e$||eg,compactPending:ey,onIgnoreContext:e6,onCompactContext:e8}):eK?.contextWindow===null?(0,n.jsx)("span",{className:"px-1 text-xs text-muted-foreground",children:L("modelContextUnknown",{defaultValue:"上下文未知"})}):null]}),(0,n.jsxs)(lK,{"data-composer-tools":"metadata",className:p$().metadataTools,children:[(0,n.jsx)(pr,{workSession:t,runtime:d,active:u,chatReady:J,onOpen:z}),(0,n.jsx)(pR,{modes:x,value:U.capabilityMode,disabled:!J,onChange:e4}),(0,n.jsx)(pI,{source:q,runtime:i,catalog:Y.models,current:eH,label:e1,title:e2,disabled:!J||eR||eD||eg,triggerClassName:p$().modelTrigger,detailsClassName:p$().modelTriggerDetails,onOpenSettings:e},eM)]}),e$&&eD?(0,n.jsx)("span",{ref:eo,className:"min-w-0 truncate px-2 text-xs text-muted-foreground",children:L("preparingContext")}):null,(0,n.jsxs)("div",{ref:el,className:p$().submitTools,children:[(0,n.jsx)(pE,{queues:eW,disabled:!J||eg,onRestore:()=>void e3(()=>i.restoreQueue(q),L("queuesRestored"))}),e_?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(lG,{tooltip:L("steerNow"),"aria-label":L("steerNow"),variant:"secondary",disabled:!eQ||eJ,onClick:()=>void tn("auto"),children:(0,n.jsx)(P.A,{className:"size-3.5"})}),(0,n.jsx)(lG,{tooltip:L("sendFollowUp"),"aria-label":L("sendFollowUp"),variant:"outline",disabled:!eQ||eJ,onClick:()=>void tn("follow_up"),children:(0,n.jsx)(m7.A,{className:"size-3.5"})}),(0,n.jsx)(lG,{tooltip:L("stopResponse"),"aria-label":L("stopResponse"),variant:"destructive",disabled:!J||eg,onClick:()=>void e3(()=>i.interrupt(q)),children:(0,n.jsx)(m9.A,{className:"size-3.5 fill-current"})})]}):(0,n.jsx)(I.$,{type:eD?"button":"submit",size:"icon",disabled:!eD&&(!eQ||eJ),"aria-disabled":eD||!eQ||eJ,"aria-busy":eD,"aria-label":eD?L("sending"):J?L("send"):L("synchronizing"),children:eD?(0,n.jsx)(pe.A,{className:"size-4"}):J?(0,n.jsx)(pt.A,{}):(0,n.jsx)(v.A,{className:"size-4 animate-spin"})})]})]})]})]}),m&&!en?c({source:q,placement:"belowEditor"}):null,(0,n.jsx)(pF,{snapshot:Z.state.snapshot,placement:"belowEditor"}),em&&em.sourceKey===eM&&eA?o({pluginName:em.pluginName,descriptor:eA.descriptor,source:q,onClose:eh}):null,ex===eM&&J?(0,n.jsx)(pj,{open:!0,source:q,runtime:i,getContext:f,listCommands:g,nativeUi:Z,nativeBiz:s.nativeUi,commandsDisabled:eR||eD||eg,onOpenChange:e=>eb(e?eM:null),onOpenSettings:e},eM):null,eI?(0,n.jsx)(ny.k,{mode:"modal",open:!0,slides:eI.slides,index:eI.index,ariaLabel:L("imagePreviewPending"),onClose:()=>eS(null),onIndexChange:e=>eS(t=>t?{...t,index:e}:t)}):null,Y.images.length>10?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:L("tooManyImages")}):eG?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:L("imageUnsupported")}):eY>0x1400000?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:L("imagesTooLarge")}):null]})});p_.displayName="L2WorkbenchChatComposer";var pW=s(61600);function pY({svgRef:e}){let t=(0,r.useId)(),s=`${t}-head`,i=`${t}-fur`;return(0,n.jsxs)("svg",{ref:e,viewBox:"0 0 640 560",fill:"none","aria-hidden":"true",className:"pointer-events-none absolute left-1/2 top-1/2 max-w-none -translate-x-1/2 -translate-y-1/2 overflow-visible",style:{width:"144.8%",height:"168.93%"},children:[(0,n.jsxs)("g",{"data-part":"busy-dots",opacity:"0",fill:"currentColor",children:[(0,n.jsx)("circle",{cx:"294",cy:"481",r:"5.5"}),(0,n.jsx)("circle",{cx:"320",cy:"481",r:"5.5"}),(0,n.jsx)("circle",{cx:"346",cy:"481",r:"5.5"})]}),(0,n.jsx)("g",{"data-part":"head",children:(0,n.jsxs)("g",{transform:"translate(64 20)",children:[(0,n.jsxs)("defs",{children:[(0,n.jsx)("path",{id:s,d:"M256 88C190 88 132 109 90 161C62 153 35 171 35 198C35 217 45 231 61 240L54 277C47 316 64 353 104 379C144 406 195 419 256 419C317 419 368 406 408 379C448 353 465 316 458 277L451 240C467 231 477 217 477 198C477 171 450 153 422 161C380 109 322 88 256 88Z"}),(0,n.jsxs)("mask",{id:i,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"512",height:"512",children:[(0,n.jsx)("rect",{width:"512",height:"512",fill:"white"}),(0,n.jsx)("path",{fill:"black",d:"M170 272C201 253 229 240 256 240C283 240 311 253 342 272C383 255 425 261 444 288C472 327 443 369 406 389C367 430 315 448 256 448C197 448 145 430 106 389C69 369 40 327 68 288C87 261 129 255 170 272Z"})]})]}),(0,n.jsx)("use",{href:`#${s}`,fill:"#F3E2C6"}),(0,n.jsx)("use",{href:`#${s}`,fill:"#B87945",mask:`url(#${i})`}),(0,n.jsxs)("g",{fill:"#303030",children:[(0,n.jsx)("path",{d:"M76 180C62 177 53 186 53 198C53 207 57 215 64 220L76 180Z"}),(0,n.jsx)("path",{d:"M436 180C450 177 459 186 459 198C459 207 455 215 448 220L436 180Z"})]}),(0,n.jsxs)("g",{"data-part":"face",children:[["left","right"].map((e,t)=>(0,n.jsxs)("g",{"data-part":`${e}-eye`,transform:`translate(${0===t?158:354} 239)`,children:[(0,n.jsx)("path",{"data-part":`${e}-eye-shape`,fill:"#303030",d:"M-26 0a26 28 0 1 0 52 0a26 28 0 1 0-52 0"}),(0,n.jsx)("circle",{"data-part":`${e}-eye-shine`,cx:"8",cy:"-11",r:"6.5",fill:"#fff"})]},e)),(0,n.jsxs)("g",{"data-part":"cheeks",fill:"#D69973",opacity:"0",children:[(0,n.jsx)("ellipse",{cx:"133",cy:"316",rx:"26",ry:"13"}),(0,n.jsx)("ellipse",{cx:"379",cy:"316",rx:"26",ry:"13"})]}),(0,n.jsx)("path",{fill:"#303030",d:"M219 269C219 254 240 254 256 254C272 254 293 254 293 269C293 282 276 299 256 303C236 299 219 282 219 269Z"}),(0,n.jsxs)("g",{"data-part":"smile",stroke:"#303030",strokeLinecap:"round",strokeWidth:"10",children:[(0,n.jsx)("path",{d:"M256 300C256 317 246 327 232 327C220 327 211 322 207 314"}),(0,n.jsx)("path",{d:"M256 300C256 317 266 327 280 327C292 327 301 322 305 314"})]}),(0,n.jsxs)("g",{"data-part":"mouth",opacity:"0",children:[(0,n.jsx)("ellipse",{cx:"256",cy:"333",rx:"16",ry:"22",fill:"#303030"}),(0,n.jsx)("ellipse",{cx:"256",cy:"347",rx:"9",ry:"5",fill:"#D69973"})]}),(0,n.jsx)("g",{stroke:"#303030",strokeLinecap:"round",strokeWidth:"9",children:(0,n.jsx)("path",{d:"M101 298C116 293 132 292 146 292M110 327C123 318 135 312 148 310M411 298C396 293 380 292 366 292M402 327C389 318 377 312 364 310"})})]})]})}),(0,n.jsxs)("g",{"data-part":"thoughts",fill:"currentColor",opacity:"0",children:[(0,n.jsx)("circle",{cx:"504",cy:"132",r:"5"}),(0,n.jsx)("circle",{cx:"524",cy:"102",r:"8"}),(0,n.jsx)("circle",{cx:"544",cy:"65",r:"11"})]}),(0,n.jsx)("g",{"data-part":"surprise",stroke:"currentColor",strokeWidth:"7",strokeLinecap:"round",opacity:"0",children:(0,n.jsx)("path",{d:"M465 91L479 66M498 113L521 100M443 69L446 44"})}),(0,n.jsxs)("g",{"data-part":"sleep",fill:"currentColor",fontFamily:"Arial,sans-serif",fontWeight:"600",opacity:"0",children:[(0,n.jsx)("text",{x:"479",y:"137",fontSize:"24",children:"z"}),(0,n.jsx)("text",{x:"522",y:"92",fontSize:"32",children:"z"})]}),(0,n.jsxs)("g",{"data-part":"sparkles",opacity:"0",fill:"#BE8656",children:[(0,n.jsx)("path",{d:"M93 158Q96 177 111 180Q96 184 93 202Q90 184 75 180Q90 177 93 158Z"}),(0,n.jsx)("path",{d:"M545 126Q550 151 570 155Q550 159 545 184Q540 159 521 155Q540 151 545 126Z"}),(0,n.jsx)("circle",{cx:"513",cy:"76",r:"5"})]})]})}let pV={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},pU=Object.keys(pV),pH={idle:.46,hello:.36,point:.45,think:.5,busy:.4,happy:.35,surprise:.2,sleep:.72};function pK(e){return Math.min(1,Math.max(0,e))}function pG(e){let t=pK(e);return t*t*t*(t*(6*t-15)+10)}function pJ(e,t){let s={...pV};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=pG(e/1.45),r=pG((e-2.15)/.65),i=Math.exp(-Math.pow((e-1.9)/.22,2));s.gazeX=-11+22*n-22*r,s.gazeY=8+2*i,s.angle=.1*s.gazeX,s.y=3+4*i,s.eye=.9+.05*i,s.sy=1-.006*i,s.busy=1,s.follow=0;break}case"happy":{let e=(1-Math.cos(5.5*t))/2;s.y=-(14*e),s.sx=1.025-.035*e,s.sy=.975+.045*e,s.angle=4*Math.sin(2.5*t),s.smile=1,s.blush=.6,s.sparkle=1,s.follow=.15;break}case"surprise":s.y=-9-6*Math.exp(-(1.5*t)),s.eye=1.2,s.mouth=1,s.sx=.96,s.sy=1.045,s.surprise=1,s.follow=.25;break;case"sleep":s.angle=11+2*Math.sin(1.25*t),s.y=6+3*Math.sin(1.25*t),s.sy=.965+.01*Math.sin(1.25*t),s.sleepy=1,s.sleep=1,s.follow=0;break;default:s.gazeX=4*Math.sin(.8*t),s.gazeY=2*Math.sin(.67*t)}return s}class pQ{setState(e,t){if(e===this.state)return;let s=this.transition&&t-this.transition.at<pH[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=pJ(this.state,t?1.2:Math.max(0,e-this.started));if(!this.transition||t)return s;let n=pK((e-this.transition.at)/pH[this.state]);if(1===n)return s;let r="pose"in this.transition?this.transition.pose:pJ(this.transition.state,Math.max(0,e-this.transition.started)),i=1-(1-n)**5;for(let e of pU)s[e]=r[e]+(s[e]-r[e])*i;return s}constructor(){this.state="idle",this.started=0,this.transition=null}}let pX=["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 pZ(e,t=0,s=1){return Math.min(s,Math.max(t,e))}function p0(e){return e.toFixed(3)}function p1({state:e,active:t=!0,size:s=100,className:i}){let a=(0,r.useRef)(null),l=(0,r.useRef)(null);return(0,r.useEffect)(()=>{let e=function(e){let t=Object.fromEntries(pX.map(t=>[t,e.querySelector(`[data-part="${t}"]`)])),s=e.parentElement,n=new pQ,r=matchMedia("(prefers-reduced-motion: reduce)"),i=!0,a=!1,l=0,o=null,c=0,d=-10,u=1.7,m={x:0,y:0},p={x:0,y:0};function h(e,s){t[e].setAttribute("opacity",p0(s))}function g(e,s){t[e].setAttribute("transform",s)}function f(){let e=n.sample(c,r.matches),s=r.matches?1.2:c,i=r.matches?0:.005*Math.sin(1.7*c),a=e.gazeX+(r.matches?0:m.x*e.follow),l=e.gazeY+(r.matches?0:m.y*e.follow);g("head",`translate(${p0(e.x)} ${p0(e.y)}) translate(320 274) rotate(${p0(e.angle+(r.matches?0:m.x*e.follow*.12))}) scale(${p0(e.sx)} ${p0(e.sy+i)}) translate(-320 -274)`),g("face",`translate(${p0(.16*a)} ${p0(.12*l)})`);let o=r.matches?-1:(c-d)/.19,u=o>=0&&o<=1?.07+.93*Math.abs(2*o-1):1;for(let[s,n]of[["left",158],["right",354]]){g(`${s}-eye`,`translate(${p0(n+a)} ${p0(239+l)})`);let r=1-pZ(e.smile+e.sleepy),i=(3.5+(28*e.eye-3.5)*r)*u*("left"===s?1-e.wink:1);t[`${s}-eye-shape`].setAttribute("d",function(e,t,s){let n=p0(e),r=p0(t+s),i=p0(-t+s),a=p0(.5523*e),l=p0(-(.5523*t)+s),o=p0(.5523*t+s);return`M-${n} 0C-${n} ${l} -${a} ${i} 0 ${i}C${a} ${i} ${n} ${l} ${n} 0C${n} ${o} ${a} ${r} 0 ${r}C-${a} ${r} -${n} ${o} -${n} 0Z`}(22+4*r,i,(-13*e.smile+8*e.sleepy)*u)),h(`${s}-eye-shine`,r*pZ((i-8)/16))}h("smile",1-e.mouth),h("mouth",e.mouth),h("cheeks",e.blush),h("thoughts",e.thought),Array.from(t.thoughts.children).forEach((e,t)=>{e.setAttribute("opacity",p0(.25+.75*(1+Math.sin(2.8*s-.9*t))/2)),e.setAttribute("transform",`translate(0 ${p0(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(${p0(8*n)} ${p0(-(20*n))})`),e.setAttribute("opacity",p0(Math.sin(n*Math.PI)))}),h("sparkles",e.sparkle*(.55+.45*(1+Math.sin(3*s))/2)),g("sparkles",`translate(0 ${p0(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*pZ(((s-.18*t)%1.4+1.4)%1.4/.55));e.setAttribute("opacity",p0(.26+.65*n)),e.setAttribute("transform",`translate(0 ${p0(-4*n)})`)})}function x(){return i&&a&&!document.hidden&&!r.matches}function b(e){if(l=0,!x())return;let t=null===o?0:Math.min((e-o)/1e3,.05);o=e,(c+=t)>=u&&(d=c,u=c+2.4+2.8*Math.random());let s=1-Math.exp(-(9*t));m.x+=(p.x-m.x)*s,m.y+=(p.y-m.y)*s,f(),l=requestAnimationFrame(b)}function v(){cancelAnimationFrame(l),l=0,o=null,f(),x()&&(l=requestAnimationFrame(b))}function w(e){if("mouse"!==e.pointerType||!x())return;let t=s.getBoundingClientRect();p.x=pZ((e.clientX-t.left-t.width/2)/Math.max(t.width,window.innerWidth/2)*24,-18,18),p.y=pZ((e.clientY-t.top-t.height/2)/Math.max(t.height,window.innerHeight/2)*20,-14,12)}function y(){p.x=0,p.y=0}let k=new IntersectionObserver(([e])=>{a=e.isIntersecting,v()});return k.observe(s),document.addEventListener("visibilitychange",v),r.addEventListener("change",v),document.addEventListener("pointermove",w,{passive:!0}),document.documentElement.addEventListener("pointerleave",y),window.addEventListener("blur",y),f(),{setState(e){n.setState(e,c),"point"!==e&&"think"!==e||r.matches||(d=c),f()},setActive(e){i=e,v()},dispose(){cancelAnimationFrame(l),k.disconnect(),document.removeEventListener("visibilitychange",v),r.removeEventListener("change",v),document.removeEventListener("pointermove",w),document.documentElement.removeEventListener("pointerleave",y),window.removeEventListener("blur",y)}}}(a.current);return l.current=e,()=>{e.dispose(),l.current=null}},[]),(0,r.useEffect)(()=>{l.current?.setState(e)},[e]),(0,r.useEffect)(()=>{l.current?.setActive(t)},[t]),(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("relative block shrink-0 text-muted-foreground",i),style:{width:s,height:.75*s},children:(0,n.jsx)(pY,{svgRef:a})})}let p2=Object.keys(dY.R.en).filter(e=>e.startsWith("emptyQuip")),p5=null;function p3(){let{t:e}=(0,b.Bd)("workbench"),t=(0,mG.tF)(),s=!0===(0,pW.D)(),i=(0,mJ.I)(),{state:a,textKey:l}=function(e){let[t,s]=(0,r.useState)(null),[n,i]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{let e=requestAnimationFrame(()=>{let e,t;return s((e=Math.floor(Math.random()*(null===p5?p2.length:p2.length-1)),null!==p5&&e>=p5&&(e+=1),p5=e,"emptyQuip16"===(t=p2[e])||"emptyQuip10"===t?{quip:t,waiting:"sleep",reaction:"surprise",recover:"hello",reply:"emptyWakeReply"}:"emptyQuip1"===t||"emptyQuip14"===t?{quip:t,waiting:"sleep",reaction:"hello",recover:"idle",reply:"emptyFishReply"}:"emptyQuip12"===t||"emptyQuip15"===t?{quip:t,waiting:"think",reaction:"surprise",recover:"idle",reply:"emptyCuriousReply"}:{quip:t,waiting:"idle",reaction:"happy",recover:"hello",reply:"emptyPartnerReply"}))});return()=>cancelAnimationFrame(e)},[]),(0,r.useEffect)(()=>{let t=window.setTimeout(()=>i(!e),320*!e);return()=>window.clearTimeout(t)},[e]),{state:t?e?t.waiting:n?t.recover:t.reaction:"sleep",textKey:t?e?t.quip:t.reply:null}}(t);return t||s&&!i?(0,n.jsxs)(o6.PY1.div,{"data-testid":"workbench-empty-session","data-otter-state":a,"data-leaving":t?void 0:"true",initial:!1,animate:{opacity:1,y:0},exit:{opacity:0,y:-4,transition:{delay:.55,duration:1.15,ease:"easeInOut"}},className:"flex max-w-sm flex-col items-center gap-5",children:[(0,n.jsx)(p1,{state:a,size:100}),(0,n.jsx)("p",{className:"min-h-6 text-sm leading-6 text-muted-foreground",children:l?e(l):null})]}):null}function p4({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)(mK.N,{initial:!1,custom:e&&t&&r,children:e&&t&&s?(0,n.jsx)(p3,{},"welcome"):null}),e&&!t&&s?(0,n.jsx)(mV,{variant:"loading"}):null]})}function p6({active:e,turns:t,window:s}){return e?(0,n.jsx)(oz,{turns:t,window:s}):null}function p8(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function p7(){return"visible"===document.visibilityState}function p9(){return!0}function he(e,t){e.scrollTop=t.scrollTop}function ht(e){let t=e.getBoundingClientRect().top,s=null;for(let n of e.querySelectorAll("[data-chat-scroll-anchor]")){let e=n.dataset.chatScrollAnchor;if(!e)continue;let r=n.getBoundingClientRect().top-t,i=Math.abs(r);(!s||i<s.distance)&&(s={messageId:e,offset:r,distance:i})}return s?{messageId:s.messageId,offset:s.offset}:null}function hs({active:e,visible:t=!0,running:s,ready:n,containsTail:i,latestUserAnchor:a,entrySnapshot:l,onResetToTail:o,onSaveSnapshot:c,onClearSnapshot:d}){let{isAtBottom:u,scrollRef:m,scrollToBottom:p,state:h,stopScroll:g}=(0,lT.B)(),f=(0,r.useSyncExternalStore)(p8,p7,p9),x=(0,r.useRef)(f),b=(0,r.useRef)(!1),v=(0,r.useRef)(!1),w=(0,r.useRef)(null),y=(0,r.useRef)(null),k=(0,r.useRef)(s?l:null),j=(0,r.useRef)(null);return(0,r.useLayoutEffect)(()=>{let e=m.current;if(!e||!t||!u)return;let s=e.style.overflowAnchor;return e.style.overflowAnchor="none",oc("viewport:anchor-lock",e),()=>{e.style.overflowAnchor=s}},[u,m,t]),(0,r.useLayoutEffect)(()=>{let n=m.current;if(!n)return;if(!e&&!s){v.current=!1,k.current=null,y.current=null,j.current=null,g(),oc("viewport:leave-ended",n);return}if(!t){y.current=null,v.current&&null===j.current&&(j.current=!e&&i&&h.isAtBottom?"follow":{snapshot:ht(n),scrollTop:n.scrollTop},oc("viewport:suspend",n,{follow:"follow"===j.current})),g();return}let r=j.current;if(null!==r){if("follow"===r)d(),n.scrollTop=Math.max(0,n.scrollHeight-n.clientHeight),he(h,n),p({animation:"instant"}),oc("viewport:restore-follow",n);else{g();let{snapshot:e}=r,t=e?od(n,"data-chat-scroll-anchor",e.messageId):null;e&&t?ox(n,t,e.offset,i):n.scrollTop=r.scrollTop,he(h,n),oc("viewport:restore-reading",n,{running:s,snapshot:e})}v.current=!0,w.current=a,j.current=null}},[e,i,a,d,s,m,p,h,g,t]),(0,r.useLayoutEffect)(()=>{let e=f&&!x.current;if(x.current=f,e&&t&&!s&&(v.current=!1,k.current=null,y.current=null),!n||!t||!f)return;s||d();let r=!v.current,l=null!==a&&a!==w.current,c=l?null:y.current;if(!r&&!l&&!c)return;if(r&&!s&&!i)return void o();let u=m.current;l&&(y.current=null,d(),u&&og(u));let j=null,N=null,I=null;b.current=!0;let S=()=>{let e=m.current;if(!e){b.current=!1;return}oc("viewport:initialize:start",e,{initializing:r,running:s,containsTail:i,latestUserAnchor:a});let t=null,n=12,l=c?c.anchor:r&&s?k.current:null;if(l){let s=od(e,"data-chat-scroll-anchor",l.messageId);s&&(t=s,n=l.offset)}!t&&a&&(t=od(e,"data-chat-scroll-anchor",a)),t??=od(e,"data-chat-user-message",void 0);let o=c?.follow??(null!==t&&null===l&&(s||!r)),d=c?.follow??(r&&s&&null===l),u=t;if(g(),u?ox(e,u,n,i):og(e),(d||!u)&&(e.scrollTop=Math.max(0,h.calculatedTargetScrollTop)),he(h,e),(o||!u)&&p({animation:"instant"}),oc("viewport:initialize:positioned",e,{initializing:r,running:s,target:t?.dataset.chatScrollAnchor??null,followAfterPosition:o,enterRunningAtBottom:d}),v.current=!0,w.current=a,k.current=null,r||c){let s=t?.dataset.chatScrollAnchor;y.current={anchor:s?{messageId:s,offset:n}:null,follow:o||null===t};let r=new ResizeObserver(()=>{o||!u?(of(e),e.scrollTop=Math.max(0,h.calculatedTargetScrollTop)):(h.isAtBottom&&g(),ox(e,u,n,i)),he(h,e)});r.observe(e),e.firstElementChild&&r.observe(e.firstElementChild);let a=e.parentElement,l=["wheel","touchstart","pointerdown","keydown","click"],c=e=>{for(let e of(r.disconnect(),l))a.removeEventListener(e,c,!0);e&&(y.current=null),I=null,b.current=!1};for(let e of l)a.addEventListener(e,c,{passive:!0,capture:!0});I=c}N=window.requestAnimationFrame(()=>{b.current=null!==I})};return m.current?S():j=window.requestAnimationFrame(S),()=>{null!==j&&window.cancelAnimationFrame(j),null!==N&&window.cancelAnimationFrame(N),I?.(),b.current=!1}},[i,a,d,o,f,n,s,m,p,h,g,t]),(0,r.useEffect)(()=>{let e=m.current;if(!e||!t)return;let s=()=>{if(oc("viewport:scroll",e,{positioning:b.current,isAtBottom:h.isAtBottom,escapedFromLock:h.escapedFromLock,resizeDifference:h.resizeDifference}),b.current||h.isAtBottom)return;let t=e.querySelector("[data-chat-tail-space]");!t||t.dataset.chatTailAnchor!==a||e.scrollHeight-e.scrollTop-e.clientHeight<=2&&(oc("viewport:resume-follow",e,{isAtBottom:h.isAtBottom,escapedFromLock:h.escapedFromLock}),d(),p({animation:"instant"}))};return e.addEventListener("scroll",s,{passive:!0}),()=>e.removeEventListener("scroll",s)},[a,d,m,p,h,t]),(0,r.useLayoutEffect)(()=>{if(!s||!t)return;let e=m.current;if(!e)return;let n=()=>{if(b.current)return;if(i&&h.isAtBottom)return void d();let t=ht(e);t?c(t):d()};return e.addEventListener("scroll",n,{passive:!0}),()=>{e.removeEventListener("scroll",n),n()}},[i,d,c,s,m,h,t]),null}let hn=(0,r.memo)(function({active:e,visible:t,workSession:s,chatRuntime:i,inputRuntime:a,onPreviewFile:l}){let{t:o}=(0,b.Bd)("workbench"),c=(0,r.useMemo)(()=>uE.Pi.parse({workId:s.workId,sessionId:s.sessionId,branchId:s.branchId}),[s.branchId,s.sessionId,s.workId]),d=(0,r.useMemo)(()=>i.getViewportSnapshot(c),[i,c]),u=(0,r.useCallback)(()=>i.getSourceState(c),[i,c]),m=(0,r.useSyncExternalStore)(i.subscribe,u,u),p="main_running"===s.status||"background_running"===s.status,h=(0,r.useMemo)(()=>oi({messages:m.messages,temporaryMessages:m.temporaryMessages},p),[p,m.messages,m.temporaryMessages]),g=m.messages.length>0||m.temporaryMessages.length>0,f=m.messages.some(e=>"user"===e.fixed.type)||m.temporaryMessages.some(e=>"user"===e.fixed.type),x=p||m.temporaryMessages.length>0,v=h.findLast(e=>null!==e.user)??null,w=v?.user??null,y=w?`${w.identity}:user`:null,k=(0,r.useCallback)(async e=>e.durable?void 0!==e.detail?e.detail:i.loadMessageDetail(c,e.durable.location.index,e.durable.location.entryId):null,[i,c]),j=(0,r.useCallback)((e,t)=>a.acquireMessageImage({source:c,tempId:e.tempId,entryId:e.durable?.location.entryId??null,imageIndex:t}),[a,c]),N=(0,r.useCallback)(e=>l(c,e),[l,c]),I=(0,r.useCallback)(e=>{i.saveViewportSnapshot(c,e)},[i,c]),S=(0,r.useCallback)(()=>{i.clearViewportSnapshot(c)},[i,c]),C=(0,r.useCallback)(()=>i.setPresentation(c,"basic"),[i,c]);return(0,n.jsx)(o$,{basic:"basic"===m.runtime.presentationMode,onRecover:C,children:(0,n.jsxs)(lO,{className:"min-h-0",initial:!1,resize:"instant","aria-label":o("chatMessages",{name:s.sessionTitle??s.projectName}),children:[(0,n.jsx)(oI,{turns:h,active:t,focusTurnIdentity:v?.identity??null,initialAnchor:x?d?.messageId??null:null,children:r=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cv,{children:(0,n.jsx)(lL,{scrollClassName:"pi-desk-chat-scrollbar pi-desk-chat-conversation-scroll overflow-auto",className:"mx-auto min-h-full w-full max-w-3xl gap-6 px-3 pt-3 pb-4 sm:px-5",children:r.visibleTurns.map((e,t)=>{let i=r.startIndex+t;return(0,n.jsx)(c6,{turn:e,cwd:s.cwd,logicalTail:r.containsTail&&i===h.length-1,onLoadDetail:k,onAcquireImage:j,onPreviewFile:N},e.identity)})})}),(0,n.jsx)(hs,{active:e,visible:t,running:x,ready:g,containsTail:r.containsTail,latestUserAnchor:y,entrySnapshot:d,onResetToTail:r.resetToTail,onSaveSnapshot:I,onClearSnapshot:S},`viewport:${c.sessionId}:${c.branchId}`),(0,n.jsx)(ob,{active:t}),(0,n.jsx)(p6,{active:t,turns:h,window:r},`navigation:${c.sessionId}:${c.branchId}`)]})},`window:${c.sessionId}:${c.branchId}`),(0,n.jsx)(p4,{active:t,ready:"ready"===m.syncStatus,empty:!g,hasUserMessage:f})]})})});hn.displayName="L2WorkbenchChatView";var hr=s(78653),hi=s.n(hr);function ha({error:e,copied:t,reloading:s,canReload:r,onCopy:i,onReload:a}){let{t:l}=(0,b.Bd)("workbench");return(0,n.jsxs)(eW.AM,{children:[(0,n.jsxs)(eW.Wv,{openOnHover:!0,delay:150,closeDelay:150,render:(0,n.jsx)(I.$,{variant:"ghost",size:"sm","aria-label":l("initializationDegraded"),title:l("initializationDegraded"),className:(0,C.cn)(hi().headerAction,"text-xs text-destructive hover:text-destructive")}),children:[(0,n.jsx)(Y.A,{className:(0,C.cn)(hi().headerActionIcon,"size-4"),"aria-hidden":"true"}),(0,n.jsx)("span",{className:hi().headerActionLabel,children:l("initializationDegraded")})]}),(0,n.jsxs)(eW.hl,{align:"end",alignOffset:8,className:"max-h-[min(28rem,var(--available-height))] w-[28rem] gap-0 overflow-hidden p-0",initialFocus:e=>"keyboard"===e,children:[(0,n.jsx)(eW.eO,{className:"shrink-0 border-b px-3 py-2",children:l("initializationDetails")}),(0,n.jsx)("pre",{className:"min-h-0 overflow-auto overscroll-contain whitespace-pre-wrap break-words p-3 font-mono text-sm leading-[1.6]","aria-label":l("initializationDetails"),children:e}),(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t px-3 py-2",children:[(0,n.jsxs)(I.$,{variant:"outline",size:"sm",onClick:i,children:[t?(0,n.jsx)(ep.A,{}):(0,n.jsx)(ee.A,{}),l(t?"copied":"copyInitializationError")]}),(0,n.jsxs)(I.$,{size:"sm",disabled:!r,onClick:a,children:[s?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(es.A,{}),l(s?"reloadingPi":"reloadPi")]})]})]})]})}var hl=s(4780),ho=s.n(hl);function hc({sidebarOpen:e,onOpen:t}){let{t:s}=(0,b.Bd)("workbench"),r=(0,mJ.I)();return(0,n.jsxs)("div",{"data-testid":"workbench-session-guide",className:ho().guide,children:[(0,n.jsx)(p1,{state:e?"idle":"point",size:120,className:ho().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:ho().arrow,fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)(o6.PY1.path,{d:"M30 26Q10 25 9 10",initial:!r&&{pathLength:0},animate:{pathLength:1},transition:{duration:.7*!r,ease:"easeOut"},opacity:".65"}),(0,n.jsx)("path",{d:"M4 16L9 10L15 15",opacity:".65"})]}),(0,n.jsx)(I.$,{variant:"ghost","aria-label":s("showSessionMenu"),onClick:t,className:"absolute inset-0 size-full p-0 hover:bg-foreground/5"})]})]})}var hd=s(45087);let hu=r.createContext(null);function hm(){let e=r.useContext(hu);if(!e)throw Error("useCarousel must be used within a <Carousel />");return e}function hp({orientation:e="horizontal",opts:t,setApi:s,plugins:i,className:a,children:l,...o}){let[c,d]=(0,hd.A)({...t,axis:"horizontal"===e?"x":"y"},i),[u,m]=r.useState(!1),[p,h]=r.useState(!1),g=r.useCallback(e=>{e&&(m(e.canScrollPrev()),h(e.canScrollNext()))},[]),f=r.useCallback(()=>{d?.scrollPrev()},[d]),x=r.useCallback(()=>{d?.scrollNext()},[d]),b=r.useCallback(e=>{"ArrowLeft"===e.key?(e.preventDefault(),f()):"ArrowRight"===e.key&&(e.preventDefault(),x())},[f,x]);return r.useEffect(()=>{d&&s&&s(d)},[d,s]),r.useEffect(()=>{if(!d)return;let e=!1;return queueMicrotask(()=>{e||g(d)}),d.on("reInit",g),d.on("select",g),()=>{e=!0,d.off("reInit",g),d.off("select",g)}},[d,g]),(0,n.jsx)(hu.Provider,{value:{carouselRef:c,api:d,opts:t,orientation:e||(t?.axis==="y"?"vertical":"horizontal"),scrollPrev:f,scrollNext:x,canScrollPrev:u,canScrollNext:p},children:(0,n.jsx)("div",{onKeyDownCapture:b,className:(0,C.cn)("relative",a),role:"region","aria-roledescription":"carousel","data-slot":"carousel",...o,children:l})})}function hh({className:e,...t}){let{carouselRef:s,orientation:r}=hm();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 hg({className:e,...t}){let{orientation:s}=hm();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 hf(e){let t=e.scrollWidth-e.clientWidth;return t<=1||!["auto","scroll"].includes(getComputedStyle(e).overflowX)?null:{left:e.scrollLeft,maximum:t}}function hx(e){return e.sessionTitle?`${e.projectName} \xb7 ${e.sessionTitle}`:e.projectName}function hb({items:e,activeWorkId:t,onActiveWorkSessionChange:s,children:i}){let a,l,{t:o}=(0,b.Bd)("workbench"),c=(0,mJ.I)(),d=r.Children.toArray(i),u=e[0]?.workId??null,m=e.some(e=>e.workId===t)?t:u,[p]=(0,r.useState)(()=>Math.max(0,e.findIndex(e=>e.workId===m))),h=(0,r.useRef)(null),g=(0,r.useRef)(!1),[f,x]=(0,r.useState)(),[v,w]=(0,r.useState)({index:p,position:p,visible:!1}),y=(0,r.useCallback)(()=>{null!==h.current&&(window.clearTimeout(h.current),h.current=null)},[]),k=(0,r.useCallback)(()=>{y(),h.current=window.setTimeout(()=>{h.current=null,w(e=>e.visible?{...e,visible:!1}:e)},900)},[y]),j=(0,r.useCallback)((t,s)=>{var n;let r=(n=t.scrollProgress()*(e.length-1),Math.max(0,Math.min(e.length-1,n))),i=Math.round(r);w(e=>{let t=s??e.visible;return e.index===i&&.001>Math.abs(e.position-r)&&e.visible===t?e:{index:i,position:r,visible:t}})},[e.length]),N=(0,r.useCallback)(e=>{j(e,!0),k()},[k,j]),I=(a=(0,r.useRef)(null),l=(0,r.useCallback)((e,t)=>{a.current=null;let s=t.target;if(!(s instanceof Element))return!0;if(s.closest('[data-carousel-swipe-lock],[data-testid="file-workspace"],[data-streamdown="mermaid-block"],[data-slot="plugin-scrollbar"],[data-slot="scroll-area-scrollbar"],.monaco-editor,[contenteditable="true"],[role="application"],[role="dialog"],[role="menu"],input,textarea,select,a,summary,img'))return!1;let n=s.closest("button");if(n&&(!("touches"in t)||!n.matches('[data-slot="collapsible-trigger"]')||!n.closest('[data-chat-scroll-anchor$=":tool"]')))return!1;let r=function(e){let t=[];for(let s=e;s&&!s.matches('[data-slot="carousel-item"]');s=s.parentElement){if(!(s instanceof HTMLElement))continue;let n=hf(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=hf(n);s&&t.push(s)}}return t}(s);if(!("touches"in t))return!r.length&&!s.closest('pre,table,[data-streamdown="code-block"]');if(1!==t.touches.length)return!1;if(!r.length)return!0;let i=t.touches[0];return a.current={x:i.clientX,y:i.clientY,scrolls:r,owner:"pending"},!1},[]),(0,r.useEffect)(()=>{if(!f)return;let e=f.rootNode(),t=()=>{a.current=null},s=e=>{let s=a.current;if(!s)return;if(1!==e.touches.length)return void t();let n=e.touches[0],r=n.clientX-s.x,i=n.clientY-s.y;if("pending"===s.owner){if(6>Math.max(Math.abs(r),Math.abs(i)))return;let e=s.scrolls.some(e=>r<0?e.left<e.maximum-1:e.left>1);s.owner=Math.abs(i)>=Math.abs(r)||e?"content":r<0?"next":"previous"}if("content"!==s.owner){if(!e.cancelable){s.owner="content";return}e.preventDefault()}},n=s=>{let n=a.current;if(t(),!n||"pending"===n.owner||"content"===n.owner)return;let r=s.changedTouches[0],i=r.clientX-n.x,l=r.clientY-n.y,o=Math.max(50,Math.min(225,.2*e.clientWidth));("next"===n.owner?-i:i)<o||Math.abs(l)>=Math.abs(i)||("next"===n.owner?f.canScrollNext():f.canScrollPrev())&&(N(f),"next"===n.owner?f.scrollNext():f.scrollPrev())};return e.addEventListener("touchmove",s,{passive:!1}),e.addEventListener("touchend",n),e.addEventListener("touchcancel",t),f.on("reInit",t),()=>{t(),e.removeEventListener("touchmove",s),e.removeEventListener("touchend",n),e.removeEventListener("touchcancel",t),f.off("reInit",t)}},[f,N]),l),S=(0,r.useMemo)(()=>({align:"start",containScroll:"trimSnaps",dragFree:!1,loop:!1,skipSnaps:!1,duration:25*!c,startIndex:p,watchDrag:I}),[p,c,I]);if((0,r.useEffect)(()=>{m&&m!==t&&s(m)},[t,m,s]),(0,r.useLayoutEffect)(()=>{if(!f||!m)return;let t=e.findIndex(e=>e.workId===m);t<0||f.selectedScrollSnap()===t||f.scrollTo(t,!0)},[f,m,e]),(0,r.useEffect)(()=>{if(!f)return;let n=()=>{g.current=!0},r=()=>{g.current=!1,k()},i=e=>{if(g.current){y(),j(e,!0);return}j(e)},a=n=>{let r=e[n.selectedScrollSnap()];r&&r.workId!==t&&s(r.workId),j(n)},l=e=>{j(e),k()},o=e=>{j(e,!1)};return f.on("pointerDown",n),f.on("pointerUp",r),f.on("scroll",i),f.on("select",a),f.on("settle",l),f.on("reInit",o),()=>{g.current=!1,f.off("pointerDown",n),f.off("pointerUp",r),f.off("scroll",i),f.off("select",a),f.off("settle",l),f.off("reInit",o)}},[t,f,y,e,s,k,j]),(0,r.useEffect)(()=>y,[y]),e.length<=1)return(0,n.jsx)("div",{className:"size-full min-h-0 min-w-0 overflow-hidden",children:d[0]??null});let E=e[v.index]??e[0],M=`${100/e.length}%`,z=`translate3d(${100*v.position}%, 0, 0)`;return(0,n.jsxs)(hp,{opts:S,setApi:x,"aria-label":o("sessionWindows"),onKeyDownCapture:()=>void 0,className:"size-full min-h-0 min-w-0 [&_[data-slot=carousel-content]]:h-full [&_[data-slot=carousel-content]]:touch-auto",children:[(0,n.jsx)(hh,{className:"ml-0 h-full",children:e.map((t,s)=>(0,n.jsx)(hg,{"aria-label":`${s+1} / ${e.length},${hx(t)}`,className:"h-full pl-0",children:d[s]??null},t.workId))}),(0,n.jsx)("div",{"aria-hidden":"true","data-testid":"mobile-work-session-position",className:(0,C.cn)("pointer-events-none absolute top-16 left-1/2 z-30 w-[min(82vw,20rem)] -translate-x-1/2 transition-[opacity,transform] duration-150 ease-out motion-reduce:transition-none",v.visible?"translate-y-0 opacity-100":"-translate-y-2 opacity-0"),children:(0,n.jsxs)("div",{className:"rounded-xl border bg-popover px-3 py-2 text-popover-foreground shadow-lg",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-xs",children:[(0,n.jsx)("span",{className:"shrink-0 text-muted-foreground",children:o(E.fixed?"fixedSession":"primarySession")}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:hx(E)}),(0,n.jsxs)("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:[v.index+1," / ",e.length]})]}),(0,n.jsx)("div",{className:"mt-2 h-1 overflow-hidden rounded-full bg-muted",children:(0,n.jsx)("div",{className:"h-full rounded-full bg-foreground",style:{width:M,transform:z}})})]})})]})}function hv(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function hw({sidebarOpen:e,onToggle:t}){let{t:s}=(0,b.Bd)("workbench");return(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":s(e?"hideSessionMenu":"showSessionMenu"),className:(0,C.cn)((0,I.r)({variant:"ghost",size:"icon"}),"text-muted-foreground"),children:e?(0,n.jsx)(sG.A,{className:"size-4"}):(0,n.jsx)(mU.A,{className:"size-5"})})}let hy=(0,r.memo)(function({onOpenSettings:e,workSession:t,fixed:s,focused:i,contentActive:a,composerActive:l,sidebarOpen:o,replacingWithEmpty:c,replacementDisabled:d,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,renderPluginSessionHeader:x,gitRuntime:v,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,branchPicker:S,branchPending:E,mobile:M,fileRuntime:z,onOpenFileSidebar:A,onPreviewFile:$,onAcknowledgeCompleted:R,onFocusWorkSession:P,onReplaceWithEmptyWorkSession:D,onOpenBranchPicker:T,onOpenGitBranchPicker:O,onCloseBranchPicker:L,onRetryBranchPicker:F,onSelectBranchEntry:B,onBranchAction:q,onConfirmRunningBranch:_,onCancelRunningBranch:W,onCloneWorkSession:Y,onUnpinWorkSession:U,onToggleSidebar:H}){let{t:K}=(0,b.Bd)("workbench"),G=(0,r.useRef)(null),J=function(e,t){let{t:s}=(0,b.Bd)("workbench"),n=(0,X.G)(),i=(0,r.useMemo)(()=>({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId}),[e.workId,e.sessionId,e.branchId]),a=(0,r.useCallback)(()=>t.getSourceState(i).runtime,[t,i]),l=(0,r.useSyncExternalStore)(t.subscribe,a,a),o=(0,r.useCallback)(()=>t.getSourceState(i).syncStatus,[t,i]),c=(0,r.useSyncExternalStore)(t.subscribe,o,o),d="basic"===l.extensionMode?l.initializationError:null,[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),g=!p&&"ready"===c&&"main_running"!==e.status&&"background_running"!==e.status,f=d?`${e.cwd}
|
|
156
156
|
${i.sessionId}
|
|
157
157
|
|
|
158
|
-
${d}`:"";return{error:d,copied:""!==f&&u===f,reloading:p,canReload:g,onCopy:()=>{f&&(0,e9.x)(f).then(e=>{e?m(f):n.error(s("initializationCopyFailed"))})},onReload:()=>{g&&(h(!0),t.reload(i).catch(e=>{n.error(e instanceof Error?e.message:String(e))}).finally(()=>h(!1)))}}}(t,u);(0,r.useSyncExternalStore)(z.subscribe,z.getRevision,z.getRevision);let Q=z.getWorkspace(t.workId),Z=(Q?.tabs.length??0)+ +!!Q?.activeDiff,ee=(0,r.useMemo)(()=>({workId:t.workId,sessionId:t.sessionId,branchId:t.branchId}),[t.workId,t.sessionId,t.branchId]),et=(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("p",{className:(0,C.cn)("truncate text-sm transition-colors duration-150 motion-reduce:transition-none",i?"font-semibold text-foreground":"font-medium text-muted-foreground"),title:t.projectName,children:t.projectName}),(0,n.jsx)("p",{className:"truncate text-xs text-muted-foreground","data-testid":"session-header-title",title:t.sessionTitle??K("newSession"),children:t.sessionTitle??K("newSession")})]});return(0,r.useEffect)(()=>{let e=G.current;if(!e||"completed"!==t.status)return;let s=!1,n=()=>{s||(s=!0,R(t.workId))};return e.addEventListener("pointerdown",n,{once:!0}),e.addEventListener("wheel",n,{passive:!0,once:!0}),e.addEventListener("keydown",n,{once:!0}),()=>{e.removeEventListener("pointerdown",n),e.removeEventListener("wheel",n),e.removeEventListener("keydown",n)}},[R,t.status,t.workId]),(0,n.jsxs)("section",{ref:G,className:"pi-desk-workbench-resize-interactions relative flex h-full min-h-0 min-w-0 flex-1 flex-col bg-background","data-work-id":t.workId,"data-degraded":J.error?"true":void 0,onPointerDown:()=>P(t.workId),onFocusCapture:()=>P(t.workId),children:[J.error?(0,n.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-20 border border-destructive"}):null,(0,n.jsx)(us,{workSession:t,runtime:z,gitRuntime:v,mobile:M,onOpenGitBranches:O,onOpenSidebar:()=>A(t.workId),children:r=>(0,n.jsxs)("div",{className:(0,C.cn)(hi().chatContainer,"flex h-full min-h-0 min-w-0 flex-1 flex-col"),children:[(0,n.jsxs)("header",{className:(0,C.cn)(hi().sessionHeader,"flex min-h-14 shrink-0 items-center gap-3 px-3"),"data-testid":"session-header",children:[s&&!M?null:(0,n.jsx)(hw,{sidebarOpen:o,onToggle:H}),(0,n.jsx)("div",{className:"min-w-0 flex-1",children:r&&a?x({source:ee,title:et}):et}),(0,n.jsxs)("div",{className:"-mr-1 flex shrink-0 items-center",children:[J.error?(0,n.jsx)(ha,{error:J.error,copied:J.copied,reloading:J.reloading,canReload:J.canReload,onCopy:J.onCopy,onReload:J.onReload},`${t.sessionId}:${t.branchId}`):null,Z>0?(0,n.jsxs)(I.$,{variant:"ghost",className:hi().headerAction,"data-testid":"session-files-entry","aria-label":K("openSessionFiles"),title:K("sessionFiles",{count:Z}),"aria-pressed":Q?.windowOpen??!1,onClick:()=>z.showWindow(t.workId),children:[(0,n.jsx)(mH.A,{className:"size-4"}),(0,n.jsx)("span",{className:hi().headerActionLabel,children:K("sessionFiles",{count:Z})})]}):null,U?(0,n.jsx)("button",{type:"button",disabled:d,"aria-label":K("unpinWorkSession",{name:t.sessionTitle??t.projectName}),title:K("unpin"),onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),U(t.workId)},className:(0,C.cn)((0,I.r)({variant:"ghost",size:"icon-sm"}),"text-muted-foreground"),children:(0,n.jsx)(V.A,{className:"size-4"})}):null]})]}),(0,n.jsx)(hn,{active:a,visible:r&&a,workSession:t,chatRuntime:u,inputRuntime:m,onPreviewFile:$}),(0,n.jsx)("footer",{className:"bg-background pt-3","data-carousel-swipe-lock":!0,children:(0,n.jsx)(p_,{workSession:t,chatRuntime:u,inputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,widgetsVisible:r&&a,gitRuntime:v,active:l,mobile:M,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,newSessionPending:c,newSessionDisabled:d||E,onNewSession:()=>D(t.workId),clonePending:E,cloneDisabled:d||0===t.messageCounts.total,onCloneWorkSession:()=>Y(t.workId),onOpenBranchPicker:T,onOpenGitBranchPicker:O,onOpenSettings:e})})]})}),(0,n.jsx)(mK.N,{children:S?(0,n.jsx)(m3,{model:S,projectName:t.projectName,sessionTitle:t.sessionTitle,mobile:M,onClose:L,onRetry:F,onSelectEntry:B,onAction:q,onConfirmRunning:_,onCancelRunning:W},"branch-picker"):null})]})}),hk=(0,r.memo)(function({position:e,workSession:t,loading:s,onExpand:r}){let{t:i}=(0,b.Bd)("workbench"),a=t?.projectName??i("workSession"),l=t?t.sessionTitle??i("newSession"):i(s?"loading":"chooseSession"),o=`${a} \xb7 ${l}`;return(0,n.jsx)("section",{className:"relative isolate flex h-full min-h-0 min-w-0 flex-1 bg-background","data-work-id":t?.workId,children:(0,n.jsx)("button",{type:"button",title:o,"aria-label":i("expandSession",{name:o}),onClick:()=>r(e,t?.workId??null),className:"flex h-full w-full min-w-0 flex-col items-center overflow-hidden bg-background px-1 text-muted-foreground outline-none transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:z-30 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:(0,n.jsxs)("span",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-3 overflow-hidden py-3",children:[(0,n.jsx)("span",{className:(0,C.cn)(hi().collapsedText,"max-h-[38%] text-xs leading-none text-muted-foreground"),children:a}),(0,n.jsx)("span",{className:(0,C.cn)(hi().collapsedText,"max-h-[55%] text-xs font-semibold leading-none"),children:l})]})})})});function hj({loading:e,sidebarOpen:t,onToggleSidebar:s}){return(0,n.jsxs)("section",{className:"relative isolate flex h-full min-w-0 flex-1 overflow-hidden bg-background",children:[(0,n.jsx)("div",{className:"absolute left-3 top-3 z-20",children:(0,n.jsx)(hw,{sidebarOpen:t,onToggle:s})}),(0,n.jsx)(mV,{variant:e?"loading":"select-session",children:e?null:(0,n.jsx)(hc,{sidebarOpen:t,onOpen:s})})]})}function hN({onOpenSettings:e,workSessions:t,primaryWorkId:s,pinnedWorkIds:i,focusedWorkId:a,sidebarOpen:l,mobile:o,loading:c,replacingWithEmptyWorkId:d,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,renderPluginSessionHeader:x,gitRuntime:v,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,branchPicker:I,branchPendingWorkId:M,fileRuntime:z,onOpenFileSidebar:A,onPreviewFile:$,onAcknowledgeCompleted:R,onFocusWorkSession:P,onReplaceWithEmptyWorkSession:D,onOpenBranchPicker:T,onOpenGitBranchPicker:O,onCloseBranchPicker:L,onRetryBranchPicker:F,onSelectBranchEntry:B,onBranchAction:q,onConfirmRunningBranch:_,onCancelRunningBranch:W,onCloneWorkSession:Y,onUnpinWorkSession:V,onToggleSidebar:U}){let{t:H}=(0,b.Bd)("workbench"),K=(0,r.useMemo)(()=>{let e=t.find(e=>e.workId===s)??null,n=new Set(i);return[{key:"work-session-primary",workSession:e,fixed:!1},...t.filter(e=>e.workId!==s&&n.has(e.workId)).map(e=>({key:`work-session-${e.workId}`,workSession:e,fixed:!0}))]},[i,s,t]),G=(0,r.useMemo)(()=>K.flatMap(e=>e.workSession?[{workId:e.workSession.workId,projectName:e.workSession.projectName,sessionTitle:e.workSession.sessionTitle,fixed:e.fixed}]:[]),[K]),J=K.length,{containerRef:Q,expandedCount:X}=function(e){let t=(0,r.useRef)(null),s=+(e>0),n=(0,r.useRef)(s),[i,a]=(0,r.useState)(s);return(0,r.useLayoutEffect)(()=>{let s=t.current;if(!s)return;let r=t=>{let s=function(e,t){let s=hv(t);if(0===s)return 0;let n=Math.floor(((Number.isFinite(e)?Math.max(0,Math.floor(e)):0)-48*s)/252);return Math.min(s,Math.max(1,n))}(t,e);n.current!==s&&(n.current=s,a(s))};r(s.clientWidth);let i=new ResizeObserver(e=>{r(e[0]?.contentRect.width??s.clientWidth)});return i.observe(s),()=>i.disconnect()},[e]),{containerRef:t,expandedCount:i}}(J),[Z,ee]=(0,r.useState)(null),et=I?K.findIndex(e=>e.workSession?.workId===I.workId):-1,es=et>=0?et:null!==Z&&Z>=0&&Z<J?Z:null,en=(0,r.useMemo)(()=>(function(e,t,s){let n=hv(e);if(0===n)return[];let r=Math.min(n,Math.max(1,hv(t))),i=null!==s&&Number.isInteger(s)&&s>=0&&s<n?s:null,a=Array(n).fill("expanded"),l=n-r;for(let e=n-1;e>=0&&l>0;e-=1)e!==i&&(a[e]="collapsed",l-=1);return a})(J,X,es),[J,es,X]),er=(0,E.OG)(),ei=JSON.stringify(K.map(e=>e.key)),ea=en.map(e=>"expanded"===e?"e":"c").join("");(0,r.useLayoutEffect)(()=>{let e=JSON.parse(ei);if(e.length<=1||e.length!==ea.length)return;let t=null,s=0,n=()=>{let r=er.current,i=Q.current;if(!r||!i||i.clientWidth<=0)return;let a=Object.keys(r.getLayout());if(!(a.length===e.length&&e.every(e=>a.includes(e))))return void((s+=1)<8?t=window.requestAnimationFrame(n):console.warn("[Pi Desk][WorkbenchColumns] 面板拓扑未及时就绪,跳过本次均分",{expectedPanelCount:e.length,registeredPanelCount:a.length}));let l=[...ea].filter(e=>"c"===e).length,o=e.length-l;if(o<=0)return;let c=48/i.clientWidth*100,d=(100-l*c)/o;if(!Number.isFinite(d)||d<=0)return;let u={};for(let[t,s]of e.entries())u[s]="c"===ea[t]?c:d;r.setLayout(u)};return t=window.requestAnimationFrame(n),()=>{null!==t&&window.cancelAnimationFrame(t)}},[ea,Q,er,ei]);let el=K[0]?.workSession??null,eo=K.reduce((e,t)=>e+ +!!t.workSession,0),ec=a??el?.workId??null,ed=c||null!==d,eu=(0,r.useCallback)((e,t)=>{ee(e),t&&P(t)},[P]);return o?0===eo?(0,n.jsx)(hj,{loading:c,sidebarOpen:l,onToggleSidebar:U}):(0,n.jsx)(hb,{items:G,activeWorkId:ec,onActiveWorkSessionChange:P,children:K.flatMap(t=>{let s=t.workSession;return s?[(0,n.jsx)(hy,{workSession:s,fixed:t.fixed,focused:1===eo||s.workId===ec,contentActive:s.workId===ec,composerActive:s.workId===ec,sidebarOpen:l,replacingWithEmpty:d===s.workId,replacementDisabled:ed,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,renderPluginSessionHeader:x,gitRuntime:v,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,branchPicker:I?.workId===s.workId?I:null,branchPending:M===s.workId,mobile:!0,fileRuntime:z,onOpenFileSidebar:A,onPreviewFile:$,onAcknowledgeCompleted:R,onFocusWorkSession:P,onReplaceWithEmptyWorkSession:D,onOpenBranchPicker:T,onOpenGitBranchPicker:O,onOpenSettings:e,onCloseBranchPicker:L,onRetryBranchPicker:F,onSelectBranchEntry:B,onBranchAction:q,onConfirmRunningBranch:_,onCancelRunningBranch:W,onCloneWorkSession:Y,onUnpinWorkSession:t.fixed?V:null,onToggleSidebar:U},`${s.workId}:${s.sessionId}:${s.branchId}`)]:[]})}):(0,n.jsx)(S.HK,{id:"work-session-columns",orientation:"horizontal",disableCursor:!0,elementRef:Q,groupRef:er,className:(0,C.cn)(dD().sessionPanelGroup,"relative h-full min-h-0 min-w-0 flex-1 overflow-hidden",!o&&"pi-desk-workbench-resize-group"),children:K.flatMap((t,s)=>{let r=t.workSession,i="collapsed"===en[s],a=s>0&&"collapsed"===en[s-1],b=i&&a,E=(0,n.jsx)(S.wV,{id:t.key,minSize:i?48:300,maxSize:i?48:void 0,defaultSize:i?48:300,disabled:i,groupResizeBehavior:i?"preserve-pixel-size":"preserve-relative-size",className:(0,C.cn)("flex h-full min-h-0 min-w-0 !overflow-hidden bg-background",s>0&&"border-l"),children:(0,n.jsx)("div",{className:dD().columnContent,children:i?(0,n.jsx)(hk,{position:s,workSession:r,loading:c,onExpand:eu}):r?(0,n.jsx)(hy,{workSession:r,fixed:t.fixed,focused:1===eo||r.workId===ec,contentActive:!0,composerActive:r.workId===ec,sidebarOpen:l,replacingWithEmpty:d===r.workId,replacementDisabled:ed,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,renderPluginSessionHeader:x,gitRuntime:v,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,branchPicker:I?.workId===r.workId?I:null,branchPending:M===r.workId,mobile:o,fileRuntime:z,onOpenFileSidebar:A,onPreviewFile:$,onAcknowledgeCompleted:R,onFocusWorkSession:P,onReplaceWithEmptyWorkSession:D,onOpenBranchPicker:T,onOpenGitBranchPicker:O,onOpenSettings:e,onCloseBranchPicker:L,onRetryBranchPicker:F,onSelectBranchEntry:B,onBranchAction:q,onConfirmRunningBranch:_,onCancelRunningBranch:W,onCloneWorkSession:Y,onUnpinWorkSession:t.fixed?V:null,onToggleSidebar:U},`${r.workId}:${r.sessionId}:${r.branchId}`):(0,n.jsx)(hj,{loading:c,sidebarOpen:l,onToggleSidebar:U})})},t.key);return 0===s?[E]:[(0,n.jsx)(S.WM,{withHandle:!b,disabled:b,"aria-label":H("resizeColumns",{left:s,right:s+1}),className:"w-0 cursor-col-resize bg-transparent aria-disabled:cursor-default"},`${K[s-1].key}-${t.key}-resize-handle`),E]})})}let hI="work-session-pin:boundary";function hS(e,t){hE(e,t);let s=e.slice(0,t),n=e.slice(t);return s.length>0&&n.length>0?[...n,hI,...s]:[...n,...s]}function hC(e,t,s){let n=[...e],[r]=n.splice(t,1);return r&&n.splice(s,0,r),n}function hE(e,t){if(!Number.isInteger(t)||t<0||t>e.length)throw Error("Invalid work session pinnedCount")}function hM(e,t){return e instanceof Error?e.message:t}function hz(e){return e instanceof Error&&"AbortError"===e.name}function hA(e){return"main_running"===e.status||"background_running"===e.status}function h$(e){return{workId:e.workId,sessionId:e.sessionId,branchId:e.branchId}}function hR({open:e,title:t,saving:s,disabled:i,error:a,onTitleChange:l,onSave:o,onClose:c}){let{t:d}=(0,b.Bd)("workbench"),u=(0,r.useId)(),m=(0,r.useRef)(null);return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>!e&&c(),children:(0,n.jsx)(eN.hA,{"data-testid":"work-session-rename-dialog",showCloseButton:!1,initialFocus:m,className:"max-w-sm",children:(0,n.jsxs)("form",{className:"flex flex-col gap-4 overflow-y-auto p-4",onSubmit:e=>{e.preventDefault(),o()},children:[(0,n.jsx)(eN.YM,{children:d("renameSessionTitle")}),(0,n.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,n.jsx)("label",{htmlFor:u,className:"font-medium",children:d("sessionTitleLabel")}),(0,n.jsx)(em.p,{ref:m,id:u,value:t,disabled:s,onChange:e=>l(e.currentTarget.value),onFocus:e=>e.currentTarget.select(),onKeyDown:e=>{"Enter"===e.key&&e.nativeEvent.isComposing&&e.preventDefault()}})]}),a?(0,n.jsx)("p",{role:"alert",className:"break-words text-destructive",children:a}):null,(0,n.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:s,onClick:c,children:d("cancel",{ns:"common"})}),(0,n.jsxs)(I.$,{type:"submit",disabled:i||s||!t.trim(),"aria-busy":s,children:[s?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):null,d("save",{ns:"common"})]})]})]})})})}let hP=["title","user"];function hD(e){return e.length===hP.length&&hP.every(t=>e.includes(t))}var hT=s(1503),hO=s(40155),hL=s(17864),hF=s(98347),hB=s(74675),hq=s(1364),h_=s(89517),hW=s.n(h_);function hY(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)}}let hV={info:{icon:"text-muted-foreground",label:"noticeInfo"},success:{icon:"text-status-success",label:"noticeSuccess"},warning:{icon:"text-status-warning",label:"noticeWarning"},error:{icon:"text-destructive",label:"noticeError"}};function hU({level:e}){let t="size-3.5";switch(e){case"success":return(0,n.jsx)(ls.A,{className:t});case"warning":return(0,n.jsx)(e_.A,{className:t});case"error":return(0,n.jsx)(Y.A,{className:t});case"info":return(0,n.jsx)(sV.A,{className:t})}}function hH({notification:e,latest:t,mobile:s,moreCount:r,busy:i,onConsume:a,onDismiss:l,onToggleMore:o,showDismiss:c}){let{t:d}=(0,b.Bd)("workbench"),u=hV[e.level],m=null!==e.event;return(0,n.jsxs)("div",{"data-testid":`app-notification-${e.notificationId}`,"data-latest":t?"true":void 0,className:(0,C.cn)("group flex min-w-0 items-stretch overflow-hidden rounded-lg bg-foreground/[0.04]",t?"h-14":"min-h-14"),children:[(0,n.jsxs)("button",{type:"button",disabled:!m||i,onClick:a,"aria-label":d(m?"actionableNotice":"noticeLabel",{level:d(u.label),title:e.title}),className:"grid min-w-0 flex-1 grid-cols-[1.6rem_minmax(0,1fr)_auto] items-center gap-1.5 px-2 text-left outline-none transition-colors enabled:cursor-pointer enabled:hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-default",children:[(0,n.jsx)("span",{className:(0,C.cn)("grid size-6 place-items-center rounded-md",u.icon),children:(0,n.jsx)(hU,{level:e.level})}),(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium leading-5 text-foreground",children:e.title}),e.description?(0,n.jsx)("span",{className:"block truncate text-xs leading-5 text-muted-foreground",children:e.description}):null]}),!s&&t&&r>0?(0,n.jsxs)("span",{className:"px-1 text-xs tabular-nums text-muted-foreground",children:["+",r]}):null]}),s&&t&&r>0?(0,n.jsx)("button",{"data-testid":"app-notification-more",type:"button",disabled:i,onClick:o,"aria-label":d("olderNotices",{count:r}),className:"mr-1 grid size-7 shrink-0 place-items-center self-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50",children:(0,n.jsx)(H.A,{className:"size-4"})}):null,c?(0,n.jsx)("button",{type:"button",disabled:i,onClick:l,"aria-label":d("deleteNotice",{title:e.title}),title:d("dismissNotice"),className:(0,C.cn)("mr-1 grid size-7 shrink-0 place-items-center self-center rounded-md text-muted-foreground outline-none transition-[background-color,color,opacity] hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50",!s&&"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),children:(0,n.jsx)(V.A,{className:"size-3.5"})}):null]})}function hK({mobile:e,notifications:t,onConsume:s,onDismiss:i}){let a=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(null),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),h=t.at(-1)??null,g=t.slice(0,-1),f=g.length>0,x=d&&f,b=64+60*Math.min(g.length,5)+8,v=(0,r.useCallback)(()=>{o.current&&clearTimeout(o.current),o.current=null},[]),w=(0,r.useCallback)(()=>{c.current&&clearTimeout(c.current),c.current=null},[]),y=(0,r.useCallback)(()=>{v(),w(),f&&u(!0)},[f,w,v]),k=(0,r.useCallback)(()=>{v(),w(),u(!1)},[w,v]),j=(0,r.useCallback)(()=>{!e&&f&&(w(),v(),o.current=setTimeout(y,120))},[f,w,v,e,y]),N=(0,r.useCallback)(()=>{e||(v(),w(),c.current=setTimeout(k,180))},[w,v,k,e]);(0,r.useEffect)(()=>{if(!x)return;let e=l.current;e&&(e.scrollTop=e.scrollHeight)},[g.length,x]),(0,r.useEffect)(()=>{if(!e||!x)return;let t=e=>{a.current?.contains(e.target)||k()},s=e=>{"Escape"===e.key&&k()};return document.addEventListener("pointerdown",t),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",t),document.removeEventListener("keydown",s)}},[k,e,x]),(0,r.useEffect)(()=>()=>{v(),w()},[w,v]);let I=(0,r.useCallback)(async e=>{if(e.event&&!m){p(e.notificationId),u(!1);try{await s(e)}finally{p(null)}}},[m,s]),S=(0,r.useCallback)(async e=>{if(!m){p(e);try{await i(e)}finally{p(null)}}},[m,i]);return h?(0,n.jsx)("div",{"data-testid":"app-notification-slot",className:"relative z-20 h-16 shrink-0",children:(0,n.jsxs)("div",{ref:a,"data-testid":"app-notification-panel","data-expanded":x?"true":"false",onPointerEnter:e=>{"mouse"===e.pointerType&&j()},onPointerLeave:e=>{"mouse"===e.pointerType&&N()},onFocus:()=>{e||y()},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||N()},className:(0,C.cn)("absolute inset-x-0 bottom-0 flex max-h-[calc(100dvh-8rem)] flex-col overflow-hidden bg-sidebar text-sidebar-foreground transition-[height,box-shadow] duration-150 ease-out motion-reduce:transition-none",x&&"shadow-lg duration-200"),style:{height:x?b:64},children:[(0,n.jsx)("div",{ref:l,className:(0,C.cn)("pi-desk-chat-scrollbar absolute inset-x-0 bottom-16 top-0 space-y-1 overflow-y-auto px-2 pt-2",!x&&"invisible"),children:g.map(t=>(0,n.jsx)(hH,{notification:t,latest:!1,mobile:e,moreCount:0,busy:null!==m,onConsume:()=>void I(t),onDismiss:()=>void S(t.notificationId),onToggleMore:()=>void 0,showDismiss:!0},t.notificationId))}),(0,n.jsx)("div",{className:"absolute inset-x-0 bottom-0 h-16 px-2 py-1",children:(0,n.jsx)(hH,{notification:h,latest:!0,mobile:e,moreCount:g.length,busy:null!==m,onConsume:()=>void I(h),onDismiss:()=>void S(h.notificationId),onToggleMore:()=>u(e=>!e),showDismiss:!e||0===g.length||x})})]})}):null}function hG(e,t){return Math.max(0,Math.floor((t-e)/6e4))}let hJ=null;function hQ(e,t){let s=t.formatToParts(e),n=e=>Number(s.find(t=>t.type===e)?.value);return Date.UTC(n("year"),n("month")-1,n("day"))}var hX=s(20314),hZ=s.n(hX);function h0(e,t){return`plugin:${e}:${t}`}let h1=[[5,3],[11,3],[5,8],[11,8],[5,13],[11,13]],h2=(0,C.cn)((0,I.r)({variant:"ghost"}),hZ().sidebarAction,"relative h-[3.25rem] max-w-24 min-w-0 flex-1 flex-col gap-1 whitespace-normal px-1 text-xs font-normal text-muted-foreground"),h5=(0,I.r)({variant:"ghost",size:"icon"}),h3=(0,C.cn)((0,I.r)({variant:"ghost",size:"icon"}),hZ().sidebarAction,"text-muted-foreground");function h4({items:e,appearance:t,label:s,className:r}){let{t:i}=(0,b.Bd)("workbench"),a="action"===t&&e.length>3?e.slice(2):[],l=a.length>0?e.slice(0,2):e;return(0,n.jsxs)("div",{className:(0,C.cn)("flex min-w-0 items-center gap-0",r),role:"group","aria-label":s,children:[l.map(e=>{var s,r;return(0,n.jsx)("button",{"data-testid":e.testId,type:"button",disabled:e.disabled,"aria-pressed":e.pressed,"aria-busy":e.busy||void 0,"aria-label":"mode"===t?i("showSidebarMode",{name:e.label}):e.label,title:e.label,onClick:e.onSelect,className:(s=!0===e.pressed,r=!0===e.busy,"mode"===t?(0,C.cn)(h5,s?"bg-accent text-accent-foreground":(0,C.cn)(hZ().sidebarAction,"text-muted-foreground")):(0,C.cn)(h3,s&&"bg-muted text-foreground",r?"disabled:cursor-wait":"disabled:cursor-not-allowed")),children:(0,n.jsx)("span",{className:(0,C.cn)("flex shrink-0","mode"===t?"[&_svg]:size-5":"[&_svg]:size-4"),children:e.icon})},e.key)}),a.length>0?(0,n.jsxs)(K.rI,{children:[(0,n.jsx)(K.ty,{render:(0,n.jsx)("button",{type:"button","aria-label":s,title:s,className:h3,children:(0,n.jsx)(H.A,{className:"size-4"})})}),(0,n.jsx)(K.SQ,{align:"end",children:a.map(e=>(0,n.jsxs)(K._2,{disabled:e.disabled,onClick:e.onSelect,children:[(0,n.jsx)("span",{className:"shrink-0 [&_svg]:size-4",children:e.icon}),e.label]},e.key))})]}):null]})}function h6({modeItems:e,actionItems:t}){let{t:s}=(0,b.Bd)("workbench");return(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 px-2",children:[(0,n.jsx)(h4,{items:e,appearance:"mode",label:s("sidebarContents"),className:"max-w-full overflow-x-auto rounded-lg p-0.5 dark:bg-muted"}),t.length>0?(0,n.jsx)(h4,{items:t,appearance:"action",label:s("sidebarActions"),className:"ml-auto shrink-0"}):null]})}function h8(){return(0,n.jsx)("svg",{className:"block size-full",viewBox:"0 0 16 16","aria-hidden":"true",children:h1.map(([e,t])=>(0,n.jsx)("circle",{cx:e,cy:t,r:"1.15",fill:"currentColor"},`${e}-${t}`))})}let h7=(0,r.memo)(function({workSession:e,mobile:t,selected:s,pinned:i,deleting:a,disabled:l,ordering:o,now:c,onSelect:d,onTogglePin:u,onDelete:m,onRename:p,syncing:h,onReloadChat:g}){var f,x;let w=(0,r.useRef)(!1),y=(0,r.useRef)(""),k=l||o,{attributes:j,listeners:N,setNodeRef:S,setActivatorNodeRef:E,transform:M,transition:z,isDragging:A}=(0,iR.gl)({id:e.workId,disabled:k}),$=(0,X.G)(),{t:R}=(0,b.Bd)("workbench"),{locale:P,timeZone:D}=(0,eQ.i)(),T=R(function(e){switch(e.status){case"main_running":return"mainRunning";case"background_running":return"backgroundRunning";case"completed":return"completedUnread";case"idle":return"idle"}}(e)),O=e.sessionTitle??R("newSession"),L=`${e.messageCounts.user}/${e.messageCounts.total}`,F=function(e,t,s="en",n="UTC"){let r=function(e,t){if(null===e||null===t)return"old";let s=hG(e,t);return s<5?"fresh":s<60?"recent":"old"}(e,t);if(null===e)return{compact:"--",title:"en"===s?"No messages yet":"暂无消息时间",tone:r};let i=function(e,t){if(hJ?.locale===e&&hJ.timeZone===t)return hJ;let s="en"===e?"en-US":"zh-CN";return hJ={locale:e,timeZone:t,title:new Intl.DateTimeFormat(s,{timeZone:t,timeZoneName:"shortOffset",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),dateKey:new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"numeric",day:"numeric"}),compact:new Intl.DateTimeFormat(s,{timeZone:t,month:"short",day:"numeric"})}}(s,n),a=i.title.format(e);if(null===t)return{compact:a,title:a,tone:r};let l=hG(e,t);if(l<1)return{compact:"en"===s?"Just now":"刚刚",title:a,tone:r};if(l<60)return{compact:"en"===s?`${l} min ago`:`${l} 分钟前`,title:a,tone:r};let o=Math.floor(l/60);if(o<24)return{compact:"en"===s?`${o} hr ago`:`${o} 小时前`,title:a,tone:r};let c=(hQ(t,i.dateKey)-hQ(e,i.dateKey))/864e5;return 1===c?{compact:"en"===s?"Yesterday":"昨天",title:a,tone:r}:2===c?{compact:"en"===s?"2 days ago":"前天",title:a,tone:r}:{compact:i.compact.format(e),title:a,tone:r}}(e.lastMessageUpdatedAt,c,P,D),B="main_running"===e.status||"background_running"===e.status,q=(f=e.cwd,{className:hW().surface,style:hY(f)}),_=(x=e.cwd,{className:hW().identity,style:hY(x)}),W=M?`translate3d(${M.x}px, ${M.y}px, 0)`:void 0,Y=(0,r.useCallback)(()=>d(e.workId),[d,e.workId]),V=(0,r.useCallback)(()=>u(e.workId),[u,e.workId]),U=(0,r.useCallback)(()=>m(e.workId),[m,e.workId]),H=(0,r.useCallback)(()=>{(0,e9.x)(e.cwd).then(e=>{e?$.success(R("copiedProjectPath")):$.error(R("copyProjectPathFailed"))})},[$,e.cwd,R]),K=(0,n.jsxs)("div",{ref:S,"data-testid":`work-session-row-${e.workId}`,"data-dragging":A?"true":void 0,role:"button",tabIndex:0,"aria-pressed":s,onClick:Y,onKeyDown:e=>{e.target===e.currentTarget&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),Y())},className:(0,C.cn)(q.className,hZ().sessionRow,!t&&hZ().desktopRow,"grid min-h-15 min-w-0 cursor-pointer grid-cols-[1.75rem_minmax(0,1fr)] items-center rounded-lg border border-transparent px-1 py-0.5 outline-none transition-[background-color,opacity] duration-150 ease-out focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",s?"text-accent-foreground":"hover:text-foreground","completed"===e.status&&"border-[var(--pi-desk-project-color)]",A&&"cursor-grabbing opacity-30"),style:{...q.style,transform:W,transition:z},children:[B?(0,n.jsx)("svg",{"aria-hidden":"true",focusable:"false","data-testid":"work-session-running-border",className:hZ().runningBorder,children:(0,n.jsx)("rect",{x:"0.5",y:"0.5"})}):null,(0,n.jsx)("button",{ref:E,"data-testid":`work-session-drag-${e.workId}`,type:"button",...j,...N,onTouchStart:e=>{N?.onTouchStart?.(e),e.stopPropagation()},onContextMenu:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>e.stopPropagation(),disabled:k,"aria-label":R("dragSession",{name:O}),title:`${T} \xb7 ${R("dragOrder")}`,className:(0,C.cn)(_.className,"flex size-7 touch-none cursor-grab items-center justify-center outline-none transition-[color,filter] hover:brightness-125 active:cursor-grabbing focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none",l&&"opacity-50"),children:(0,n.jsx)("span",{className:"size-4",children:(0,n.jsx)(h8,{})})}),(0,n.jsxs)("div",{className:"min-w-0 py-0.5",children:[(0,n.jsx)("span",{className:"sr-only",children:T}),(0,n.jsxs)("div",{className:"flex min-w-0 items-center justify-between gap-1",children:[(0,n.jsx)("p",{className:(0,C.cn)(_.className,"truncate text-xs font-medium"),title:e.projectName,children:e.projectName}),(0,n.jsxs)("span",{className:(0,C.cn)(hZ().rowMetadata,"flex shrink-0 items-center gap-1 whitespace-nowrap text-xs leading-4 text-muted-foreground"),title:R("sessionMessages",{count:L,time:F.title}),children:[(0,n.jsx)("span",{children:L}),(0,n.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,n.jsx)("span",{className:(0,C.cn)("transition-colors","fresh"===F.tone&&"dark:text-sidebar-primary"),children:F.compact})]})]}),(0,n.jsxs)("div",{className:"relative flex min-h-7 min-w-0 items-center",children:[(0,n.jsx)("p",{className:(0,C.cn)(hZ().rowTitle,"min-w-0 flex-1 truncate pr-1 text-sm",s?"font-semibold":"font-medium"),title:O,children:O}),(0,n.jsxs)("div",{className:(0,C.cn)(hZ().rowActions,"flex shrink-0 items-center"),children:[(0,n.jsx)("button",{"data-testid":`work-session-pin-${e.workId}`,type:"button",onClick:e=>{e.stopPropagation(),V()},disabled:k,"aria-label":R(i?"unpinSession":"pinSession",{name:O}),title:R(i?"unpin":"pin"),className:(0,C.cn)((0,I.r)({variant:"ghost",size:"icon-sm"}),"text-muted-foreground",i&&_.className),children:i?(0,n.jsx)(hT.A,{className:"size-4"}):(0,n.jsx)(rc.A,{className:"size-4"})}),(0,n.jsx)("button",{"data-testid":`work-session-delete-${e.workId}`,type:"button",disabled:k||a,onClick:e=>{e.stopPropagation(),U()},"aria-label":R("deleteSession",{name:O}),title:R("deleteSessionTitle"),className:(0,C.cn)((0,I.r)({variant:"ghost",size:"icon-sm"}),"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"),children:(0,n.jsx)(et.A,{className:"size-4"})})]})]})]})]});return(0,n.jsxs)(hq.tz,{onOpenChange:(e,t)=>{e&&("touch"===y.current||t.event.type.startsWith("touch"))&&(w.current=!0)},children:[(0,n.jsx)(hq.Rc,{render:K,onPointerDown:e=>{y.current=e.pointerType,w.current=!1},onTouchEndCapture:e=>{w.current&&e.cancelable&&e.preventDefault()},onClickCapture:e=>{w.current&&(e.preventDefault(),e.stopPropagation(),w.current=!1)},onKeyDownCapture:e=>{if(e.target!==e.currentTarget||e.nativeEvent.isComposing||(y.current="keyboard",w.current=!1,"ContextMenu"!==e.key&&!("F10"===e.key&&e.shiftKey)))return;e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getBoundingClientRect();e.currentTarget.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,button:2,clientX:t.left+t.width/2,clientY:t.top+t.height/2}))}}),(0,n.jsxs)(hq.Ip,{children:[(0,n.jsxs)(hq.kt,{"data-testid":`work-session-rename-${e.workId}`,disabled:k||a,onClick:()=>p(e),children:[(0,n.jsx)(hO.A,{}),R("renameSessionTitle")]}),(0,n.jsxs)(hq.kt,{"data-testid":`work-session-reload-chat-${e.workId}`,disabled:k||a||h,onClick:()=>g(e),children:[h?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(es.A,{}),R("reloadChatData")]}),(0,n.jsxs)(hq.kt,{"data-testid":`work-session-copy-project-path-${e.workId}`,onClick:H,children:[(0,n.jsx)(ee.A,{}),R("copyProjectPath")]})]})]})});function h9({id:e,label:t}){let{setNodeRef:s,transform:r,transition:i}=(0,iR.gl)({id:e,disabled:{draggable:!0}}),a=r?`translate3d(${r.x}px, ${r.y}px, 0) scaleX(${r.scaleX??1}) scaleY(${r.scaleY??1})`:void 0;return(0,n.jsxs)("div",{ref:s,"data-testid":e,"aria-hidden":"true",className:"pointer-events-none flex h-5 items-center gap-2 px-1 text-xs text-muted-foreground",style:{transform:a,transition:i},children:[(0,n.jsx)("span",{className:"h-px flex-1 bg-border/75"}),(0,n.jsx)("span",{children:t}),(0,n.jsx)("span",{className:"h-px flex-1 bg-border/75"})]})}let ge=(0,r.memo)(function({mode:e,mobile:t,fileBrowser:s,pluginTabContent:i,pluginHeaderActions:a=[],pluginSessionTabs:l,fileRefreshLoading:o,canBrowseFiles:c,workSessions:d,focusedWorkId:u,pinnedCount:m,ordering:p,deletingWorkId:h,canReplace:g,disabled:f,pluginApplications:x,settingsAttention:y,notifications:k,onConsumeNotification:j,onDismissNotification:N,onModeChange:I,onRefreshFiles:S,onPreviewProject:E,onPreviewProjectWindow:M,onOpenTerminal:z,onCreate:A,onReplace:$,onSettings:R,onOpenPluginApplication:P,onSelect:D,onTogglePin:T,onDelete:O,onRename:L,syncingWorkIds:F,onReloadChat:B,onArrangementChange:q}){let{t:_}=(0,b.Bd)("workbench"),[W,Y]=(0,r.useState)(null),V=(0,r.useRef)(null),G=(0,r.useRef)(3),[J,Q]=(0,r.useState)(3),X=(0,i$.FR)((0,i$.MS)(i$.cA,{activationConstraint:{distance:6}}),(0,i$.MS)(i$.IG,{activationConstraint:{delay:250,tolerance:8}}),(0,i$.MS)(i$.uN,{coordinateGetter:iR.JR}));(0,r.useEffect)(()=>{let e=()=>Y(Date.now());e();let t=window.setInterval(e,6e4);return()=>window.clearInterval(t)},[]);let Z=[{key:"sessions",label:_("sidebarSessions"),icon:(0,n.jsx)(m$.A,{}),pressed:"sessions"===e,testId:"sidebar-mode-sessions",onSelect:()=>I("sessions")},{key:"files",label:_("sidebarFiles"),icon:(0,n.jsx)(sY.A,{}),pressed:"files"===e,testId:"sidebar-mode-files",onSelect:()=>I("files")},...l.map(t=>{let s=h0(t.pluginName,t.contributionName);return{key:`${t.pluginName}:${t.contributionName}`,label:t.label,icon:(0,n.jsx)(eq,{icon:t.icon}),disabled:!c,pressed:e===s,onSelect:()=>I(s)}})],ee="sessions"===e?[{key:"replace",label:_("sidebarReplaceSession"),disabled:f||!g,busy:f,testId:"sidebar-replace-work-session",icon:(0,n.jsx)(hL.A,{}),onSelect:$},{key:"create",label:_("createSession"),disabled:f,busy:f,testId:"sidebar-create-work-session",icon:(0,n.jsx)(U.A,{}),onSelect:A}]:"files"===e?[{key:"preview-project",label:_("projectPreview"),disabled:!c,icon:(0,n.jsx)(hF.A,{}),testId:"project-preview-open",onSelect:E},{key:"preview-project-window",label:_("projectPreviewWindow"),disabled:!c,icon:(0,n.jsx)(oq.A,{}),testId:"project-preview-window-open",onSelect:M},{key:"new-terminal",label:_("newTerminal"),disabled:f,icon:(0,n.jsx)(w.A,{}),testId:"project-files-terminal-open",onSelect:z},{key:"refresh-files",label:_("refreshFiles"),disabled:!c||o,icon:o?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(es.A,{}),busy:o,testId:"project-files-refresh",onSelect:S}]:a.map((e,t)=>({key:String(t),label:e.label,icon:e.busy?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(eq,{icon:e.icon}),disabled:e.disabled||e.busy,busy:e.busy,onSelect:()=>{e.onSelect()}}));(0,r.useLayoutEffect)(()=>{let e=V.current;if(!e)return;let t=e=>{let t=Math.max(1,Math.floor(e/56));G.current!==t&&(G.current=t,Q(t))};t(e.clientWidth);let s=new ResizeObserver(([s])=>{t(s?.contentRect.width??e.clientWidth)});return s.observe(e),()=>s.disconnect()},[]);let et=(0,r.useMemo)(()=>d.map(e=>e.workId),[d]),en=(0,r.useMemo)(()=>hS(et,m),[m,et]),er=(0,r.useMemo)(()=>new Map(d.map(e=>[e.workId,e])),[d]),ei=(0,r.useMemo)(()=>new Set(et.slice(0,m)),[m,et]),{visiblePluginApplications:ea,overflowPluginApplications:el,shortcutRowItemCounts:eo}=(0,r.useMemo)(()=>{var e;let s,n,r,i,a,l,o,c=t?2:3,d=(e=x.length,a=Math.ceil((i=(r=(n=e+1>(s=J*c))?Math.max(0,s-2):e)+1+ +!!n)/J),l=Math.floor(i/a),o=i%a,{visibleApplicationCount:r,rowItemCounts:Array.from({length:a},(e,t)=>l+ +(t<o))});return{visiblePluginApplications:x.slice(0,d.visibleApplicationCount),overflowPluginApplications:x.slice(d.visibleApplicationCount),shortcutRowItemCounts:d.rowItemCounts}},[t,x,J]),ec=(0,r.useCallback)(e=>{if(p||!e.over||e.active.id===e.over.id)return;let t=String(e.active.id),s=function(e,t,s,n){if(hE(e,t),s===n||s===hI)return null;let r=hS(e,t),i=r.indexOf(s),a=r.indexOf(n);if(i<0||a<0)return null;if(0>r.indexOf(hI))return{workIds:hC(r,i,a),pinnedCount:t};let l=e.indexOf(s)<t,o=n===hI?function(e,t,s){let n=[...e],[r]=n.splice(t,1);if(!r)return n;let i=n.indexOf(hI);return i<0?[...e]:(n.splice(s?i:i+1,0,r),n)}(r,i,l):hC(r,i,a),c=o.indexOf(hI);if(c<0)return null;let d=o.slice(0,c),u=o.slice(c+1),m=[...u,...d];return m.length!==e.length||new Set(m).size!==e.length?null:{workIds:m,pinnedCount:u.length}}(et,m,t,String(e.over.id));s&&q(s,t)},[q,p,m,et]),ed=en.map(e=>{if(e===hI)return(0,n.jsx)(h9,{id:e,label:_("pinnedBelow")},e);let s=er.get(e);return s?(0,n.jsx)(h7,{workSession:s,mobile:t,selected:s.workId===u,pinned:ei.has(s.workId),deleting:h===s.workId,disabled:f,ordering:p,now:W,onSelect:D,onTogglePin:T,onDelete:O,onRename:L,syncing:F.includes(s.workId),onReloadChat:B},s.workId):null}),eu=[(0,n.jsxs)("button",{type:"button",title:_("settings"),"aria-label":_("error"===y?"settingsWarning":"settings"),onClick:R,className:h2,children:[(0,n.jsx)(ez.A,{className:"size-5 shrink-0"}),(0,n.jsx)("span",{className:"w-full truncate text-center",children:_("settings")}),y?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute right-1.5 top-1.5 size-2 rounded-full ring-2 ring-sidebar","error"===y?"bg-destructive":"bg-primary")}):null]},"settings"),...ea.map(e=>(0,n.jsxs)("button",{type:"button",disabled:f,title:e.label,onClick:()=>P(e),className:h2,children:[(0,n.jsx)(eq,{icon:e.icon,className:"size-5 shrink-0"}),(0,n.jsx)("span",{className:"w-full line-clamp-2 break-words text-center leading-4",children:e.label})]},`${e.pluginName}:${e.contributionName}`))];el.length>0&&eu.push((0,n.jsxs)(K.rI,{children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)("button",{type:"button",disabled:f,title:_("more"),"aria-label":_("moreShortcuts"),className:h2}),children:[(0,n.jsx)(H.A,{className:"size-5 shrink-0"}),(0,n.jsx)("span",{className:"w-full truncate text-center",children:_("more")})]}),(0,n.jsx)(K.SQ,{align:"end",side:"top",className:"w-56",children:el.map(e=>(0,n.jsxs)(K._2,{disabled:f,onClick:()=>P(e),className:"py-2",children:[(0,n.jsx)(eq,{icon:e.icon,className:"size-4"}),(0,n.jsx)("span",{className:"min-w-0 truncate",children:e.label})]},`${e.pluginName}:${e.contributionName}`))})]},"more"));let em=eo.map((e,t)=>{let s=eo.slice(0,t).reduce((e,t)=>e+t,0);return(0,n.jsx)("div",{className:"flex justify-evenly",children:eu.slice(s,s+e)},`shortcut-row:${s}`)});return(0,n.jsxs)("aside",{className:"flex h-full w-full min-w-0 flex-col bg-sidebar text-sidebar-foreground",children:[(0,n.jsx)(h6,{modeItems:Z,actionItems:ee}),(0,n.jsx)(hB.V,{"data-testid":"work-session-list",className:(0,C.cn)("min-h-0 flex-1","sessions"!==e&&"hidden"),viewportClassName:"p-2 data-[has-overflow-y]:pr-4",children:0===d.length?(0,n.jsx)("p",{className:"px-2 py-5 text-center text-sm leading-6 text-muted-foreground",children:_("noSessions")}):(0,n.jsx)(i$.Mp,{sensors:X,collisionDetection:i$.fp,onDragEnd:ec,children:(0,n.jsx)(iR.gB,{items:en,strategy:iR._G,children:(0,n.jsx)("div",{className:"flex flex-col gap-1",children:ed})})})}),(0,n.jsx)("div",{className:(0,C.cn)("min-h-0 flex-1 overflow-hidden","files"!==e&&"hidden"),children:s??(0,n.jsx)("div",{className:"flex h-full items-center justify-center p-5 text-center text-sm text-muted-foreground",children:_("selectSessionFirst")})}),e.startsWith("plugin:")?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:i}):null,(0,n.jsx)(hK,{mobile:t,notifications:k,onConsume:j,onDismiss:N}),(0,n.jsx)("footer",{"data-testid":"sidebar-shortcuts",className:"shrink-0 px-2 py-1.5","aria-label":_("shortcuts"),children:(0,n.jsx)("div",{ref:V,className:"flex flex-col gap-1",children:em})})]})});ge.displayName="L2WorkSessionSidebar";let gt={primaryWorkId:null},gs={mode:"normal",notifications:[],plugins:{},capabilityModes:{},settings:{region:{locale:"en",timeZone:"UTC"}}};function gn(e){let t=window.matchMedia("(max-width: 1023px)");return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function gr(){return window.matchMedia("(max-width: 1023px)").matches}function gi(e,t){return e instanceof Error?e.message:t}function ga(e){let t=r9.N$.safeParse(e);return t.success?t.data.directories:null}function gl(e){let t=r9.rn.safeParse(e);return t.success?t.data:null}function go({render:e,input:t}){return e(t)}function gc({onTerminalReady:e,onTerminalDisconnected:t,onOpenTerminal:s,onOpenProjectPreviewWindow:i,renderTerminalWorkspace:a,listPluginManagement:o,subscribePluginManagementChanges:c,onTaskCenterStart:d,onTaskCenterDispose:u,onTaskCenterReconcileWorkSessions:m,onTaskCenterDisconnected:p,onTaskCenterReconnected:h,renderPluginApplication:g,renderPluginSessionSidebarTab:f,renderSettings:x,renderTaskSummary:v,renderTaskMenu:w,renderPluginComposerPanel:y,renderPluginWidgets:k,renderPluginSessionHeader:j}){var N;let{t:S}=(0,b.Bd)("workbench"),{clientId:C,appSocket:E}=(0,ei.gM)(),M=(0,X.G)(),z=(0,Q.t4)(),A=(0,Q.So)(),$=(0,r.useMemo)(()=>(function(e,t){async function s(t,n,r,i="POST"){let a=await fetch(t,{method:i,..."GET"===i?{cache:"no-store"}:{},headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},...void 0===n?{}:{body:JSON.stringify(n)},...r?{signal:r}:{}}),l=await a.json();if(!a.ok||0!==l.code||null===l.data)throw Error(l.msg?(0,ed.B)(l):"请求失败");return l.data}return{async readServerVersion(e){let t=await s("/api/health",void 0,e,"GET");return dO.parse(t).version},getChatMessageDetail:e=>s("/api/chat/messages/get",e),getChatModelContext:e=>s("/api/chat/context/get",e),getChatImage:e=>s("/api/chat/images/get",e),listModels:e=>s("/api/pi/models/list",e),listPiCommands:e=>t.request(dq.QV.commandsList,e),listPiTools:e=>t.request(dq.QV.toolsList,e),sendChat:e=>t.request(dL.P6.send,e),async interruptChat(e){await t.request(dL.P6.interrupt,e)},restoreChatQueue:e=>t.request(dL.P6.queueRestore,e),async setChatModel(e){await t.request(dL.P6.modelSet,e)},async setChatCapabilityMode(e){await t.request(dL.P6.capabilityModeSet,e)},invokePluginMethod:e=>t.request(dF.OY.invoke,e),listWorkSessions:()=>t.request(dB.kM.list,{}),async applyAppRuntimeUpdate(e){await t.request(nH.apply,e)},sortWorkSessions:e=>s("/api/work-sessions/sort",e),deleteWorkSession:e=>s("/api/work-sessions/del",{workId:e}),async renameWorkSession(e){await s("/api/work-sessions/rename",e)},async listDirectories(e){let t=await s("/api/pi/directories/list",{forceRefresh:e});return ip(t),t},async listIgnoredDirectories(e){let t=await s("/api/pi/directory-ignores/list",{forceRefresh:e});return iu(),ia=t,im(it,t),t},async replaceDirectoryIgnore(e){await s("/api/pi/directory-ignores/replace",e)},async listDirectoryEntries(e){let t=await s("/api/pi/directory-entries/list",{cwd:e});return!function(e){let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.cwd;if("string"==typeof t||null===t)return t}(e);if(void 0===t)return;ih();let s=ic(t);for(io.delete(s),io.set(s,e);io.size>64;){let e=io.keys().next().value;if(void 0===e)break;io.delete(e)}im(is,{entries:Object.fromEntries(io)})}(t),t},listSessionHistory:(e,t)=>s("/api/pi/sessions/list",e,t),listSessionUserMessages:(e,t)=>s("/api/pi/session-user-messages/list",e,t),createWorkSession:e=>s("/api/work-sessions/add",e),replaceWorkSession:e=>s("/api/work-sessions/replace",e),getWorkSessionTree:(e,t)=>s("/api/work-session-tree/get",e,t),getWorkSessionTreeEntry:(e,t)=>s("/api/work-session-tree-entry/get",e,t),branchWorkSession:e=>s("/api/work-sessions/branch",e),async acknowledgeCompleted(e){await t.request(dB.kM.acknowledgeCompleted,{workId:e})},async readWorkSessionUpdates(s,n,r,i){let a=t.subscribe(dB.kM.update,r),o=t.subscribe(nH.update,i),c=()=>void 0,d=new Promise(e=>{let t=()=>e({code:1e3,reason:"页面业务已卸载"});s.addEventListener("abort",t,{once:!0}),c=()=>s.removeEventListener("abort",t)});try{let e=await t.connect(s);if(s.aborted)return await d;let r=await t.request(dB.kM.list,{});if(s.aborted)return await d;await n(r,e);let i=await Promise.race([t.waitForClose(),d]);return s.aborted||i.code!==l.Sp||window.location.replace("/login"),i}catch(t){if(!s.aborted){let t=await fetch("/api/auth-settings/get",{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:"{}",signal:s}).catch(()=>null);t?.status===401&&window.location.replace("/login")}throw t}finally{c(),o(),a()}}}})(C,E),[E,C]),R=(0,r.useMemo)(()=>{var e,t;let s,n,r;return e=$.readServerVersion,t=()=>{window.location.reload()},s=!1,n=null,r=!1,async(i,a,l)=>{if(a.aborted)return;let o=s&&i;if(s=!0,!o||r)return;n?.abort();let c=new AbortController;n=c;let d=()=>c.abort();a.addEventListener("abort",d,{once:!0}),l.then(d,d);let u=setTimeout(d,5e3);try{let s=await e(c.signal);if(c.signal.aborted||!s||s===sU||r)return;r=!0,t()}catch(e){c.signal.aborted||console.warn("[Pi Desk][VersionRefresh] 重连版本检查失败,保留当前页面",{message:e instanceof Error?e.message:String(e)})}finally{clearTimeout(u),a.removeEventListener("abort",d),n===c&&(n=null)}}},[$]),P=(0,r.useRef)([]),D=(0,r.useRef)(0),T=(0,r.useRef)(gs),O=(0,r.useRef)(!1),L=(0,r.useRef)(null),F=(0,r.useRef)(0),B=(0,r.useRef)(!0),q=(0,r.useRef)(new Set),_=(0,r.useRef)(new Set),W=(0,r.useSyncExternalStore)(gn,gr,()=>!0),Y=(0,r.useSyncExternalStore)(ry,rv,rv),V=(0,r.useMemo)(()=>({list:(e,t)=>(0,ur.QL)(C,dI.Xe,dM.parse(e),t),search:(e,t)=>(0,ur.QL)(C,dI.fg,dz.parse(e),t),get:(e,t)=>(0,ur.QL)(C,dI.ZI,dR.parse(e),t),reveal:e=>(0,ur.QL)(C,dI.Ot,dA.parse(e))}),[C]),U=(0,r.useMemo)(()=>(function(e){async function t(t,s,n,r){let i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s),signal:r}),a=await i.json();if(!i.ok||0!==a.code||null===a.data)throw Error(a.msg?(0,ed.B)(a):"Git 请求失败");return n.parse(a.data)}return{getHeads:(t,s)=>(0,ur.QL)(e,dI._X,t,s),get:(t,s)=>(0,ur.QL)(e,dI.p0,{...ux.parse(t),refresh:!0},s),listBranches:async(t,s)=>{let{head:n,recent:r,local:i,remote:a}=await (0,ur.QL)(e,dI.ry,uk.parse(t),s);return{head:n,recent:r,local:i,remote:a}},replaceBranch:(e,s)=>t("/api/work-session-git-branch/replace",uN.parse(e),uS,s),addBranch:(e,s)=>t("/api/work-session-git-branch/add",uI.parse(e),uS,s),getDiff:async(t,s)=>{let n=await (0,ur.QL)(e,dI.OC,uC.parse(t),s);return"metadata"===n.kind?{kind:"binary"}:n}}})(C),[C]),[H]=(0,r.useState)(()=>new dG(V,U,e=>{M.show({level:"info",title:e})})),[K]=(0,r.useState)(()=>new uh(U,(e,t)=>{H.handleGitBranchChanged(e,t)}));(0,r.useSyncExternalStore)(H.subscribe.bind(H),H.getRevision,H.getRevision);let[G,J]=(0,r.useState)([]),[Z,ee]=(0,r.useState)(0),[et,es]=(0,r.useState)(gs),[en,er]=(0,r.useState)(gt),[ea,el]=(0,r.useState)(!1),[eo,ec]=(0,r.useState)(null),[eu,em]=(0,r.useState)(!0),[ep,eh]=(0,r.useState)(!1),eg=(0,r.useRef)(ep);(0,r.useEffect)(()=>{eg.current=ep},[ep]);let ef=(0,r.useCallback)(()=>{eg.current=!1,eh(!1)},[]),[ex,eb]=(0,r.useState)("sessions"),[ev,ew]=(0,r.useState)(null),[ey,ek]=(0,r.useState)(!1),[ej,eN]=(0,r.useState)(!1),[eI,eS]=(0,r.useState)(),[eC,eE]=(0,r.useState)(null),[eM,ez]=(0,r.useState)(null),[eA,e$]=(0,r.useState)(null),[eR,eP]=(0,r.useState)(null),[eD,eT]=(0,r.useState)(null),eO=(0,r.useCallback)(()=>{e$(null)},[]),[eL,eF]=(0,r.useState)("initial"),eB="ready"!==eL,eq=function(e,t){let{t:s}=(0,b.Bd)("workbench"),[n,i]=(0,r.useState)(null),[a,l]=(0,r.useState)(""),[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(null),m=(0,r.useCallback)(e=>{i({workId:e.workId,sessionId:e.sessionId}),l(e.sessionTitle??""),u(null)},[]),p=async()=>{let r=a.trim();if(n&&!o&&!t&&r){c(!0),u(null);try{await e.renameWorkSession({...n,title:r}),i(null)}catch(e){u(e instanceof Error?e.message:s("renameSessionFailed"))}finally{c(!1)}}};return{open:null!==n,title:a,saving:o,error:d,show:m,close:()=>{o||i(null)},setTitle:l,save:p}}($,eB),[e_,eW]=(0,r.useState)(!1),[eY,eV]=(0,r.useState)(null),[eU,eH]=(0,r.useState)(!1),[eK,eG]=(0,r.useState)(null),[eJ,eQ]=(0,r.useState)("directories"),[eX,eZ]=(0,r.useState)(null),[e0,e1]=(0,r.useState)(null),[e2,e5]=(0,r.useState)([]),[e3,e4]=(0,r.useState)([]),[e6,e8]=(0,r.useState)(null),[e7,e9]=(0,r.useState)(!1),[te,tt]=(0,r.useState)(!1),[ts,tn]=(0,r.useState)(!1),[tr,ti]=(0,r.useState)(null),[ta,tl]=(0,r.useState)(null),[to,tc]=(0,r.useState)(null),[td,tu]=(0,r.useState)(null),[tm,tp]=(0,r.useState)(null),{sessions:th,loading:tg,load:tf,cancel:tx,showCached:tb}=function(e,t){let{t:s}=(0,b.Bd)("workbench"),[n,i]=(0,r.useState)([]),[a,l]=(0,r.useState)(!1),o=(0,r.useRef)(0),c=(0,r.useRef)(null),d=(0,r.useRef)(new Map);(0,r.useEffect)(()=>()=>{o.current+=1,c.current?.abort(),c.current=null},[]);let u=(0,r.useCallback)(()=>{o.current+=1,c.current?.abort(),c.current=null,l(!1)},[]),m=(0,r.useCallback)(e=>{i(d.current.get(e)?.base??[])},[]);return{sessions:n,loading:a,load:(0,r.useCallback)(async(n,r="",a=hP,u=!1)=>{let m=++o.current;c.current?.abort(),c.current=null;let p=r.trim(),h=d.current.get(n),g=hD(a)&&!p?h?.base:h?.recent?.query===p&&h.recent.searchIn.length===a.length&&h.recent.searchIn.every(e=>a.includes(e))?h.recent.sessions:null;if(g&&!u){i(g),l(!1),t(null);return}g&&i(g);let f=new AbortController;c.current=f,l(!0),t(null);try{let t=await e.listSessionHistory({cwd:n,query:p,forceRefresh:u,searchIn:[...a]},f.signal);if(o.current!==m)return;let s=d.current.get(n)??{base:null,recent:null};for(hD(a)&&!p?s.base=t.sessions:s.recent={query:p,searchIn:[...a],sessions:t.sessions},d.current.delete(n),d.current.set(n,s);d.current.size>8;){let e=d.current.keys().next().value;if(!e)break;d.current.delete(e)}i(t.sessions)}catch(e){if(o.current!==m||e instanceof Error&&"AbortError"===e.name)return;t(e instanceof Error?e.message:s("historyFailed"))}finally{o.current===m&&(c.current===f&&(c.current=null),l(!1))}},[t,e,s]),cancel:u,showCached:m}}($,tp),[tv,tw]=(0,r.useState)(null),[ty,tk]=(0,r.useState)(0),tj=(0,r.useRef)(null),tN=(0,r.useRef)(0),tI=(0,r.useRef)(0),tS=(0,r.useRef)(0),tC=(0,r.useRef)(null),tE=(0,r.useRef)(0),tM=(0,r.useMemo)(()=>(function(e,t,s={async readMessages(e){let t=uE.Pi.parse(e),s=(await uW()).transaction(u$,"readonly"),n=uU(s),r=await uY(s.objectStore(u$).index(uR).getAll(IDBKeyRange.only([t.sessionId,t.branchId])));return await n,r.map(uG).sort((e,t)=>e.location.index-t.location.index)},async readLatestCursor(e){try{let t=await this.readMessages(e),s=uz(t);return null===s&&t.length>0&&await this.clearSource(e),s}catch(t){return console.warn("[Pi Desk][WorkbenchChatRepository] 本地消息缓存无效,回退全量同步",{sessionId:e.sessionId,branchId:e.branchId,errorName:t instanceof Error?t.name:"UnknownError"}),await this.clearSource(e),null}},async replaceMessages(e,t){let s=uE.Pi.parse(e),n=(await uW()).transaction(u$,"readwrite"),r=uU(n),i=n.objectStore(u$);for(let e of(uJ(i,s),t))i.put(uK(s,e));await r},async appendMessage(e,t){let s=uE.Pi.parse(e),n=uK(s,t),r=(await uW()).transaction(u$,"readwrite"),i=uU(r),a=r.objectStore(u$),l=[n.sessionId,n.branchId,n.index],o=a.get(l),c=null;if(o.addEventListener("success",()=>{if(void 0===o.result)return void a.add(n);let e=uH.safeParse(o.result);if(e.success&&e.data.entryId===n.entryId)return;let t=e.success?e.data.entryId:"invalid-record";c=Error(`IndexedDB 消息身份冲突:${n.index}/${n.entryId}/${t}`),uJ(a,s)},{once:!0}),await i,c)throw c},async saveDetail(e,t,s,n){let r=uE.Pi.parse(e),i=uE.wI.parse(n),a=(await uW()).transaction(u$,"readwrite"),l=uU(a),o=a.objectStore(u$),c=[r.sessionId,r.branchId,t],d=await uY(o.get(c)),u=uH.parse(d);if(u.entryId!==s)throw a.abort(),await l.catch(()=>void 0),Error(`IndexedDB 消息身份不匹配:${t}/${s}`);let{detail:m,...p}=u;o.put(null===i?p:{...p,detail:i}),await l},async clearSource(e){let t=uE.Pi.parse(e),s=(await uW()).transaction(u$,"readwrite"),n=uU(s);uJ(s.objectStore(u$),t),await n}}){let n=new u8(e),r=new Map,i=new Map,a=new Map,l=new Map,o=new Map,c=new Map,d=new Map,u=new Map,m=new Map,p=new Set,h=new Set,g=!1,f=0,x=null,b=()=>void 0,v=null,w=!1,y=()=>{for(let e of[...p])try{e()}catch(e){console.error("[Pi Desk][WorkbenchChat] 消息状态监听器执行失败",{errorName:e instanceof Error?e.name:"UnknownError"})}},k=(e=!1)=>{if(e){if(v)return;v=setTimeout(()=>{v=null,y()},50);return}v&&clearTimeout(v),v=null,y()},j=(e,t,s=!1)=>{a.set(me(e),t),k(s)},N=e=>{let t=r.get(e.workId),s=i.get(e.workId);return void 0!==t&&void 0!==s&&mt(t,e)&&mt(u9(s),e)},I=(e,t)=>{let s=me(e),n=(u.get(s)??Promise.resolve()).then(t,t);u.set(s,n);let r=()=>{u.get(s)===n&&u.delete(s)};return n.then(r,r),n},S=e=>{let t=`${me(e)}\u0000`;for(let e of d.keys())e.startsWith(t)&&d.delete(e)},C=async(t,n=!1)=>{if(!g||0===t.length||w)return;let r=f,i=t.filter(e=>N(e)&&!l.has(me(e))).map(e=>{let t=me(e),s={};l.set(t,s);let n=a.get(t);return n&&a.set(t,{...n,syncStatus:"syncing"}),{source:e,token:s}});if(0===i.length)return;k();let o=({source:e,token:t})=>!w&&g&&r===f&&N(e)&&l.get(me(e))===t;try{let t=(await Promise.all(i.map(async e=>({...e,cursor:n?null:await s.readLatestCursor(e.source)})))).filter(o).map(({source:e,cursor:t})=>({source:e,cursor:t}));if(0===t.length)return;await e.request(dL.P6.subscribe,{subscriptions:t})}catch(t){let e=i.filter(o);for(let{source:t}of e)l.delete(me(t));if(e.length>0)throw t}},E=async e=>{let t=me(e),n=a.get(t);return n||uE.oc.parse({messages:await s.readMessages(e),temporaryMessages:[],runtime:uM.runtime})},M=async e=>{N(e)&&g&&!w&&(l.delete(me(e)),await C([e],!0))},z=async e=>{let{epoch:t,push:n}=e,{source:r,event:i}=n,o=me(r),c=l.get(o),d=()=>!w&&g&&t===f&&N(r)&&l.get(o)===c;if(!d()||"session_sync"!==i.type&&(c||!a.has(o)))return!1;if("session_sync"===i.type&&"full"===i.mode){S(r);let e=a.get(o);e&&j(r,{...e,syncStatus:"syncing"})}let u="session_sync"===i.type&&"full"===i.mode?a.get(o)??u7:await E(r);if(!d())return!1;if("session_sync"===i.type&&"incremental"===i.mode){let e=u.messages.at(-1);if(e?.location.index!==i.baseCursor.index||e.location.entryId!==i.baseCursor.entryId){let e=await s.readMessages(r);if(!d())return!1;let t=e.slice(0,i.baseCursor.index+1),n=uz(t);if(n?.index!==i.baseCursor.index||n.entryId!==i.baseCursor.entryId)throw Error(dV("chatCacheMismatch"));u={...u,messages:t}}}let m=function(e,t){if("session_sync"===t.type){if("full"===t.mode)return{...df(e,t.messages,t.temporaryMessages),runtime:t.runtime};let s=e.messages.at(-1);if(!s||s.location.index!==t.baseCursor.index||s.location.entryId!==t.baseCursor.entryId)throw Error("Incremental chat sync does not match the current durable cursor");let n=new Set(e.messages.map(e=>e.location.entryId));for(let e of t.messages){if(n.has(e.location.entryId))throw Error(`Incremental chat sync contains a duplicate entryId: ${e.location.entryId}`);n.add(e.location.entryId)}return{messages:[...e.messages,...t.messages],temporaryMessages:t.temporaryMessages,runtime:t.runtime}}return"runtime_update"===t.type?{...e,runtime:t.runtime}:{...dx(e,t),runtime:e.runtime}}(u,i);if("session_sync"===i.type)await I(r,async()=>{d()&&await s.replaceMessages(r,m.messages)});else if("message_commit"===i.type){let e=m.messages.at(-1);if(!e||e.location.index!==i.durable.index||e.location.entryId!==i.durable.entryId)throw Error(`Chat commit result is missing: ${i.durable.index}/${i.durable.entryId}`);await I(r,async()=>{d()&&await s.appendMessage(r,e)})}if(!d())return!1;for(let e of("session_sync"===i.type&&l.delete(o),j(r,{...m,syncStatus:"session_sync"===i.type?"syncing":a.get(o).syncStatus},"message_update"===i.type),[...h]))try{e(n,m)}catch(e){console.error("[Pi Desk][WorkbenchChat] Source 事件观察器执行失败",{eventType:i.type,errorName:e instanceof Error?e.name:"UnknownError"})}return!0},A=async(e,t)=>{if(!t.processing){t.processing=!0;try{for(;!w&&c.get(e)===t;){let e=t.pushes.shift();if(!e)break;try{await z(e)&&"session_sync"===e.push.event.type&&(t.syncEpoch=e.epoch)}catch(r){if(w||e.epoch!==f||!N(e.push.source))continue;t.pushes.length=0,t.syncEpoch=null;let{push:s}=e,n="message_start"===s.event.type?s.event.snapshot.location.tempId:"location"in s.event?s.event.location.tempId:null;console.error("[Pi Desk][WorkbenchChat] 应用聊天 Source 事件失败,重新同步",{workId:s.source.workId,sessionId:s.source.sessionId,branchId:s.source.branchId,eventType:s.event.type,eventTempId:n,updateLayers:"message_update"===s.event.type?{fixed:void 0!==s.event.fixed,summary:void 0!==s.event.summary,detail:void 0!==s.event.detail,increments:void 0!==s.event.increments}:null,errorName:r instanceof Error?r.name:"UnknownError",errorMessage:r instanceof Error?r.message:String(r)});try{await M(s.source)}catch(e){b(e)}break}}}finally{if(t.processing=!1,c.get(e)!==t)return;if(0===t.pushes.length){c.delete(e);let s=a.get(e);w||!g||t.syncEpoch!==f||l.has(e)||s?.syncStatus!=="syncing"||(a.set(e,{...s,syncStatus:"ready"}),k())}else w||A(e,t)}}},$=e=>{if(w||!g||!N(e.source))return;let t=me(e.source),s=c.get(t)??{pushes:[],processing:!1,syncEpoch:null};s.pushes.push({epoch:f,push:e}),c.set(t,s),s.processing||A(t,s)},R=e=>{for(let t of(i.clear(),e))i.set(t.workId,t);let t=!1;for(let e of[...r.values()]){let s=i.get(e.workId);s&&mt(e,u9(s))||(r.delete(e.workId),a.delete(me(e)),l.delete(me(e)),o.delete(me(e)),S(e),c.delete(me(e)),t=!0)}t&&k()};return{nativeUi:n,start(t){b=t,x||(w=!1,x=e.subscribe(dL.P6.sourceEvent,$))},async applyWorkSessionsList(e){R(e),g=!0,n.ready(e.map(u9)),await C([...r.values()])},reconcileWorkSessions(e){R(e),n.reconcile(e.map(u9))},ensureDisplayedWorkSessions(e){(e=>{let t=[];for(let s of e){let e=u9(s),n=i.get(s.workId);if(!n&&g)continue;let d=n?u9(n):e;if(!mt(e,d))continue;let u=r.get(d.workId);u&&mt(u,d)||(u&&(a.delete(me(u)),l.delete(me(u)),o.delete(me(u)),S(u),c.delete(me(u))),r.set(d.workId,d),t.push(d))}0!==t.length&&(k(),g&&C(t).catch(e=>{b(e)}))})(e)},subscribe:e=>(p.add(e),()=>p.delete(e)),subscribeSourceEvents:e=>(h.add(e),()=>h.delete(e)),getSourceState(e){let t=uE.Pi.parse(e);return a.get(me(t))??u7},getViewportSnapshot(e){let t=uE.Pi.parse(e);return o.get(me(t))??null},saveViewportSnapshot(e,t){let s=uE.Pi.parse(e);t.messageId&&Number.isFinite(t.offset)&&o.set(me(s),t)},clearViewportSnapshot(e){let t=uE.Pi.parse(e);o.delete(me(t))},async loadMessageDetail(e,n,r){let i=uE.Pi.parse(e),l=(await E(i)).messages.find(e=>e.location.index===n&&e.location.entryId===r);if(!l)throw Error(dV("chatMessageMissing",{index:n,entryId:r}));if(void 0!==l.detail)return l.detail;if(!l.fixed.hasDetail)return null;if(a.get(me(i))?.syncStatus!=="ready")throw Error(dV("sourceSyncing"));let o=f,c=`${me(i)}\u0000${n}\u0000${r}`,u=d.get(c);if(u)return u;let m=(async()=>{let e=await t({sessionId:i.sessionId,branchId:i.branchId,entryId:r}),n=()=>!w&&f===o&&N(i)&&d.get(c)===m;if(await I(i,async()=>{if(!n())throw Error(dV("sourceSyncing"));await s.saveDetail(i,e.index,e.entryId,e.detail)}),!n())throw Error(dV("sourceSyncing"));if(N(i)&&!w){let t=a.get(me(i));t&&j(i,{...{...db(t,e),runtime:t.runtime},syncStatus:t.syncStatus})}return e.detail})().finally(()=>{d.get(c)===m&&d.delete(c)});return d.set(c,m),m},async compact(t){let s=uE.Pi.parse(t);if(a.get(me(s))?.syncStatus!=="ready")throw Error(dV("sourceSyncing"));await e.request(dL.P6.compact,{source:s})},async reload(t,s){let n=uE.Pi.parse(t);if(a.get(me(n))?.syncStatus!=="ready")throw Error(dV("sourceSyncing"));await e.request(dL.P6.reload,void 0===s?{source:n}:{source:n,mode:s})},async reloadMessages(t){let s=uE.Pi.parse(t),n=me(s),o=i.get(s.workId);if(!o||!mt(u9(o),s))throw Error(dV("reloadChatSourceChanged"));let d=a.get(n);if(!g||w||l.has(n)||d?.syncStatus==="syncing")throw Error(dV("sourceSyncing"));let u=f,m=c.get(n),p=m?.syncEpoch??null;m&&(m.syncEpoch=null),r.set(s.workId,s),j(s,{...d??u7,syncStatus:"syncing"});try{await e.request(dL.P6.subscribe,{subscriptions:[{source:s,cursor:null}]})}catch(e){if(!w&&u===f&&N(s)){m&&c.get(n)===m&&(m.syncEpoch=p);let e=a.get(n);e&&j(s,{...e,syncStatus:d?.syncStatus??"loading"})}throw console.error("[Pi Desk][WorkbenchChat] 重新加载聊天数据失败,保留已有缓存",{workId:s.workId,sessionId:s.sessionId,branchId:s.branchId,message:e instanceof Error?e.message:String(e)}),e}},async setPresentation(t,s){let n=uE.Pi.parse(t),r=me(n),i=a.get(r);if(!i||"ready"!==i.syncStatus)throw Error(dV("sourceSyncing"));if(i.runtime.presentationMode===s)return;let l=`${r}\u0000${s}`,o=m.get(l);if(o)return o;let c=e.request(dL.P6.presentationSet,{source:n,mode:s}).then(()=>void 0).finally(()=>{m.get(l)===c&&m.delete(l)});return m.set(l,c),c},disconnected(){for(let e of(n.disconnected(),g=!1,f+=1,d.clear(),m.clear(),l.clear(),c.values()))e.pushes.length=0;let e=!1;for(let[t,s]of a)"syncing"!==s.syncStatus&&(a.set(t,{...s,syncStatus:"syncing"}),e=!0);e&&k()},dispose(){w||(n.dispose(),w=!0,g=!1,x?.(),x=null,b=()=>void 0,r.clear(),i.clear(),a.clear(),l.clear(),o.clear(),c.clear(),d.clear(),u.clear(),m.clear(),v&&clearTimeout(v),v=null,p.clear(),h.clear())}}})(E,e=>$.getChatMessageDetail(e)),[E,$]),tz=function(e,t){let{t:s}=(0,b.Bd)("workbench"),n=(0,X.G)(),i=(0,r.useCallback)(()=>JSON.stringify(t.filter(({workId:t,sessionId:s,branchId:n})=>"syncing"===e.getSourceState({workId:t,sessionId:s,branchId:n}).syncStatus).map(e=>e.workId)),[e,t]),a=(0,r.useSyncExternalStore)(e.subscribe,i,i);return{syncingWorkIds:(0,r.useMemo)(()=>JSON.parse(a),[a]),reload:(0,r.useCallback)(t=>{let{workId:r,sessionId:i,branchId:a}=t;e.reloadMessages({workId:r,sessionId:i,branchId:a}).catch(e=>{n.error(e instanceof Error?e.message:s("reloadChatDataFailed"))})},[e,s,n])}}(tM,G),tA=(0,r.useMemo)(()=>(function(e,t,s={async recoverOutbox(e){let t=uE.Pi.parse(e),s=(await uW()).transaction([uP,uD],"readwrite"),n=uU(s),r=s.objectStore(uP),i=s.objectStore(uD),a=mn(t),[l,o]=await Promise.all([uY(r.get(a)),uY(i.get(a))]),c=mi(l),d=mi(o);if(!d)return await n,{input:c??ms,recovered:!1};let u=ma(d,c);return r.put(mr(t,u)),i.delete(a),await n,{input:u,recovered:!0}},async writeDraft(e,t){let s=uE.Pi.parse(e),n=(await uW()).transaction(uP,"readwrite"),r=uU(n),i=n.objectStore(uP);t.text||0!==t.images.length?i.put(mr(s,t)):i.delete(mn(s)),await r},async moveDraftToOutbox(e,t){let s=uE.Pi.parse(e),n=(await uW()).transaction([uP,uD],"readwrite"),r=uU(n);n.objectStore(uD).put(mr(s,t)),n.objectStore(uP).delete(mn(s)),await r},async clearOutbox(e){let t=uE.Pi.parse(e),s=(await uW()).transaction(uD,"readwrite"),n=uU(s);s.objectStore(uD).delete(mn(t)),await n},async restoreOutboxToDraft(e){let t=uE.Pi.parse(e),s=(await uW()).transaction([uP,uD],"readwrite"),n=uU(s),r=s.objectStore(uP),i=s.objectStore(uD),a=mn(t),[l,o]=await Promise.all([uY(r.get(a)),uY(i.get(a))]),c=mi(o);if(!c)throw s.abort(),await n.catch(()=>void 0),Error(dV("outboxMissing"));let d=ma(c,mi(l));return r.put(mr(t,d)),i.delete(a),await n,d},async deleteOutbox(e){await this.clearOutbox(e)},async clearSource(e){let t=uE.Pi.parse(e),s=(await uW()).transaction([uP,uD],"readwrite"),n=uU(s);s.objectStore(uP).delete(mn(t)),s.objectStore(uD).delete(mn(t)),await n}}){let n=new Map,r=new Map,i=new Set,a=new Map,l=new Set,o=0,c=new Map,d=[],u=new Map,m=new Map,p=0,h=!1,g=()=>{for(let e of[...i])try{e()}catch(e){console.error("[Pi Desk][WorkbenchChatInput] 状态监听器执行失败",{errorName:e instanceof Error?e.name:"UnknownError"})}},f=e=>{if("ready"!==t.getSourceState(e).syncStatus)throw Error(dV("sourceSyncing"))},x=e=>{let t=my(e);r.set(t,e);let s=n.get(t);return s||(s={loaded:!1,loading:!1,text:"",images:[],outbox:null,notice:null,error:null,models:{status:"idle",models:[],presets:[],error:null}},n.set(t,s)),s},b=(e,t)=>{let s=t(x(e));return n.set(my(e),s),g(),s},v=(e,t)=>{let n=my(e);o+=1;let i=(a.get(n)??Promise.resolve()).then(()=>s.writeDraft(e,t)).then(()=>{l.delete(n)}).catch(t=>{l.add(n),console.error("[Pi Desk][WorkbenchChatInput] Draft 写入失败",{workId:e.workId,errorName:t instanceof Error?t.name:"UnknownError"}),r.has(n)&&b(e,e=>({...e,error:dV("draftSaveFailed")}))}).finally(()=>{a.get(n)===i&&a.delete(n)});a.set(n,i)},w=e=>{v(e,mk(x(e)))},y=()=>{for(;!h&&p<2&&d.length>0;){let e=d.shift();p+=1,e().finally(()=>{p-=1,y()})}},k=(e,t)=>{d.push(async()=>{let s=n.get(my(e)),r=s?.images.find(e=>e.localId===t);if(r&&"optimizing"===r.status)try{let s=await mx(r),i=n.get(my(e)),a=i?.images.findIndex(e=>e.localId===t)??-1;if(!i||a<0)return;let l=URL.createObjectURL(s.blob);URL.revokeObjectURL(i.images[a].objectUrl);let o=[...i.images];o[a]={...o[a],...s,objectUrl:l,status:"ready",error:null},n.set(my(e),{...i,images:o,error:null}),w(e),g()}catch(a){let s=n.get(my(e)),r=s?.images.findIndex(e=>e.localId===t)??-1;if(!s||r<0)return;let i=[...s.images];i[r]={...i[r],status:"error",error:mj(a,dV("imageProcessFailed"))},n.set(my(e),{...s,images:i}),w(e),g()}}),y()},j=()=>{let e=[...u.values()].reduce((e,t)=>e+t.size,0);for(let[t,s]of u){if(e<=0x4000000&&u.size<=64)break;s.references>0||(URL.revokeObjectURL(s.url),u.delete(t),e-=s.size)}},N=e=>{let t=my(e),s=n.get(t);for(let e of(s&&(mC(s.images),s.outbox&&mC(s.outbox.images)),n.delete(t),r.delete(t),a.delete(t),l.delete(t),c.delete(t),m.keys()))e.startsWith(`${t}\u0000`)&&m.delete(e);for(let[e,s]of[...u])e.startsWith(`${t}\u0000`)&&(URL.revokeObjectURL(s.url),u.delete(e))},I=t.subscribeSourceEvents((e,t)=>{let{source:s,event:n}=e;if("message_commit"===n.type){let e=`${my(s)}\u0000temp\u0000${n.location.tempId}\u0000`;for(let[t,r]of[...u]){if(!t.startsWith(e))continue;let i=Number.parseInt(t.slice(e.length),10);u.delete(t),u.set(mS(s,n.durable.entryId,i),r)}g();return}if("message_discard"===n.type){let e=`${my(s)}\u0000temp\u0000${n.location.tempId}\u0000`;for(let[t,s]of[...u])t.startsWith(e)&&(URL.revokeObjectURL(s.url),u.delete(t));g();return}if("session_sync"===n.type||"runtime_update"===n.type){let e=new Set([...t.temporaryMessages.map(e=>e.location.tempId),...t.runtime.queues.steering.map(e=>e.tempId),...t.runtime.queues.followUp.map(e=>e.tempId)]),n=`${my(s)}\u0000temp\u0000`;for(let[t,s]of[...u]){if(!t.startsWith(n))continue;let r=t.slice(n.length).split("\0")[0];r&&e.has(r)||(URL.revokeObjectURL(s.url),u.delete(t))}}});return{subscribe:e=>(i.add(e),()=>i.delete(e)),getState:e=>x(e),async loadSource(e){let t=my(e);if(x(e).loaded)return;let i=c.get(t);if(i)return i;let a=(async()=>{b(e,e=>({...e,loading:!0,error:null}));try{let i,a,l=await s.recoverOutbox(e);if(h||!r.has(t))return;let o=(i=l.input.images,a=dV("draftImage"),i.map((e,t)=>mv(e,`${a} ${t+1}`)));for(let s of(n.set(t,{...x(e),loaded:!0,loading:!1,text:l.input.text,images:o,notice:l.recovered?dV("uncertainRecovered"):null,error:null}),o))s.optimized||k(e,s.localId);g()}catch(t){b(e,e=>({...e,loaded:!1,loading:!1,error:mj(t,dV("draftLoadFailed"))}))}})().finally(()=>c.delete(t));return c.set(t,a),a},dismissFeedback(e){b(e,e=>({...e,notice:null,error:null}))},setText(e,t){let s=b(e,e=>({...e,text:t,notice:null,error:null}));v(e,mk(s))},async addFiles(e,t){let s=10-x(e).images.length;if(s<=0)return void b(e,e=>({...e,error:dV("imageAddLimit")}));let n=[...t].slice(0,s),r=[];for(let t of n)try{let e=await mf(t);r.push(mv(e,t.name))}catch(s){b(e,e=>({...e,error:dV("imageFileFailed",{name:t.name,error:mj(s,dV("imageUnavailable"))})}))}if(0===r.length)return;let i=b(e,e=>({...e,images:[...e.images,...r],notice:null,error:t.length>s?dV("imageAddOverflow"):null}));for(let t of(v(e,mk(i)),r))t.optimized||k(e,t.localId)},removeImage(e,t){let s=x(e).images.find(e=>e.localId===t);if(!s)return;mw(s);let n=b(e,e=>({...e,images:e.images.filter(e=>e.localId!==t),error:null}));v(e,mk(n))},async send(t,r){f(t);let i=my(t),l=x(t);if(l.outbox)throw Error(dV("resolveOutboxFirst"));if(!l.text.trim()&&0===l.images.length)throw Error(dV("emptyInput"));if(l.images.length>10)throw Error(dV("imageSendLimit"));if(l.images.some(e=>"optimizing"===e.status))throw Error(dV("imagesPending"));let o=l.images.find(e=>"error"===e.status);if(o)throw Error(o.error??dV("imageProcessingFailed"));if(l.images.reduce((e,t)=>e+t.blob.size,0)>0x1400000)throw Error(dV("imageBytesLimit"));await (a.get(i)??Promise.resolve()),f(t);let c=mk(l);await s.moveDraftToOutbox(t,c),n.set(i,{...l,text:"",images:[],outbox:{status:"sending",text:l.text,images:l.images,error:null},notice:null,error:null}),g();try{let a=await Promise.all(l.images.map(mb)),o={source:t,mode:r,text:l.text,images:a};if(new TextEncoder().encode(JSON.stringify({head:{op:"req",path:"chat/send",requestId:"00000000-0000-4000-8000-000000000000"},body:o})).byteLength>0x1f00000)throw Error(dV("messageBytesLimit"));let c=await e.sendChat(o);if(h||n.get(i)?.outbox?.images!==l.images)return;l.images.forEach((e,s)=>{u.set(mI(t,c.tempId,s),{url:URL.createObjectURL(e.blob),size:e.blob.size,references:0})}),j(),await s.clearOutbox(t);let d=n.get(i);d?.outbox?.images===l.images&&(mC(l.images),n.set(i,{...d,outbox:null,error:null})),g()}catch(r){let e,t,s=n.get(i);throw s?.outbox?.images===l.images&&n.set(i,{...s,outbox:{...s.outbox,status:(t="string"==typeof(e=r instanceof Error&&"rawMessage"in r?r.rawMessage:null)?e:mj(r,""),/WebSocket.*(?:断开|连接|替换)|请求超时|尚未连接/.test(t))?"unknown":"failed",error:mj(r,dV("sendFailed"))}}),g(),r}},async prepareForPageReload(){let e=o;return await Promise.all([...a.values()]),o===e&&!(l.size>0)&&[...n.values()].every(e=>e.outbox?.status!=="sending"&&e.outbox?.status!=="unknown")},async restoreOutbox(e){let t=my(e);await (a.get(t)??Promise.resolve());let r=x(e);r.outbox&&(await s.restoreOutboxToDraft(e),n.set(t,{...r,text:mN(r.outbox.text,r.text),images:[...r.outbox.images,...r.images],outbox:null,notice:null,error:null}),g())},async deleteOutbox(e){let t=x(e);t.outbox&&(await s.deleteOutbox(e),mC(t.outbox.images),n.set(my(e),{...t,outbox:null,notice:null,error:null}),g())},async interrupt(t){f(t);try{await e.interruptChat({source:t}),b(t,e=>({...e,error:null}))}catch(e){throw b(t,t=>({...t,error:mj(e,dV("interruptFailed"))})),e}},async restoreQueue(t){f(t);try{let s=await e.restoreChatQueue({source:t}),n=s.images.map((e,t)=>mv({blob:(0,dw.E)(e),mimeType:e.mimeType,width:e.width,height:e.height,optimized:!0},dV("restoredImage",{count:t+1}))),r=b(t,e=>({...e,text:mN(s.text,e.text),images:[...n,...e.images],notice:null,error:null}));v(t,mk(r))}catch(e){throw b(t,t=>({...t,error:mj(e,dV("queueRestoreFailed"))})),e}},listTools:async t=>(f(t),e.listPiTools({source:t})),async loadModels(t,s=!1){let r=x(t);if("loading"===r.models.status||!s&&"ready"===r.models.status)return;let i=b(t,e=>({...e,models:{...e.models,status:"loading",error:null}})).models,a=my(t);try{let s=await e.listModels({workId:t.workId});if(h||n.get(a)?.models!==i)return;b(t,e=>({...e,models:{status:"ready",models:s.models,presets:s.presets,error:null}}))}catch(e){if(h||n.get(a)?.models!==i)return;b(t,t=>({...t,models:{...t.models,status:"error",error:mj(e,dV("modelCatalogFailed"))}}))}},async setModel(t,s){f(t);let n=my(t);x(t);try{await e.setChatModel({source:t,model:s}),!h&&r.has(n)&&b(t,e=>({...e,error:null}))}catch(e){throw!h&&r.has(n)&&b(t,t=>({...t,error:mj(e,dV("setModelFailed"))})),e}},acquireMessageImage(t){if(h)throw Error(dV("imageUnavailable"));let s=t.entryId?mS(t.source,t.entryId,t.imageIndex):t.tempId?mI(t.source,t.tempId,t.imageIndex):null;if(!s)throw Error(dV("imageIdentityInvalid"));r.set(my(t.source),t.source);let n=e=>{if(h||u.get(s)!==e)throw Error(dV("imageUnavailable"));e.references+=1,u.delete(s),u.set(s,e),j();let t=!1;return{url:e.url,release:()=>{t||(t=!0,e.references-=1,j())}}},i=u.get(s);if(i)return n(i);let a=m.get(s);if(!a){if(!t.entryId)throw Error(dV("localImagePending"));a=e.getChatImage({sessionId:t.source.sessionId,branchId:t.source.branchId,entryId:t.entryId,imageIndex:t.imageIndex}).then(e=>{if(h||m.get(s)!==a)throw Error(dV("imageUnavailable"));let t=(0,dw.E)(e),n={url:URL.createObjectURL(t),size:t.size,references:0};return u.set(s,n),n}).catch(e=>{throw console.warn("[Pi Desk][WorkbenchChatInput] 读取聊天图片失败",{entryId:t.entryId,error:mj(e,dV("imageUnavailable"))}),e}).finally(()=>{m.get(s)===a&&m.delete(s)}),m.set(s,a)}return a.then(n)},reconcileWorkSessions(e){let t=new Set(e.map(e=>my({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId})));for(let[e,n]of[...r]){if(t.has(e))continue;let r=a.get(e)??Promise.resolve();N(n),r.then(()=>s.clearSource(n),()=>s.clearSource(n)).catch(e=>{console.error("[Pi Desk][WorkbenchChatInput] 清理失效 Source 输入失败",{workId:n.workId,errorName:e instanceof Error?e.name:"UnknownError"})})}g()},dispose(){if(!h){for(let e of(h=!0,I(),d.length=0,[...r.values()]))N(e);for(let e of u.values())URL.revokeObjectURL(e.url);u.clear(),m.clear(),l.clear(),i.clear()}}}})($,tM),[tM,$]),t$=(0,r.useRef)(null),tR=(0,r.useRef)(null),tP=(0,r.useMemo)(()=>G.slice(0,Z).map(e=>e.workId),[Z,G]),tD=(0,r.useMemo)(()=>A.flatMap(e=>e.contributions.flatMap(t=>"application"===t.kind?[{pluginName:e.pluginName,contributionName:t.contributionName,label:t.label,...t.icon?{icon:t.icon}:{}}]:[])),[A]),tT=(0,r.useMemo)(()=>A.flatMap(e=>e.contributions.flatMap(t=>"session-sidebar-tab"===t.kind?[{pluginName:e.pluginName,contributionName:t.contributionName,label:t.label,...t.icon?{icon:t.icon}:{}}]:[])),[A]),tO=!!(eM||eC?.loadError||eC?.plugins.some(e=>"failed"===e.status||e.operation?.phase==="failed")||z.getEntryListError()||z.getFailedEntries().length>0),tL=!!(eC?.restartRequired||eC?.plugins.some(e=>!0===e.updateAvailable)),tF=tO?"error":tL?"notice":null,tB=eA?A.find(e=>e.pluginName===eA.pluginName)?.contributions.find(e=>"application"===e.kind&&e.contributionName===eA.contributionName):void 0,tq=G.find(e=>e.workId===eo)??null,t_=tq?.cwd??null,tW=ex.startsWith("plugin:")?tT.find(e=>h0(e.pluginName,e.contributionName)===ex):void 0,tY=tW?A.find(e=>e.pluginName===tW.pluginName)?.contributions.find(e=>"session-sidebar-tab"===e.kind&&e.contributionName===tW.contributionName):void 0,tV=tq?.workId??null,tU=tq?.sessionId??null,tH=tq?.branchId??null,tK=tV&&tU&&tH?{workId:tV,sessionId:tU,branchId:tH}:null,tG=JSON.stringify([ex,tV,tU,tH,t_]),tJ=(0,r.useCallback)(e=>{ew(t=>e.length>0?{targetKey:tG,actions:e}:t?.targetKey===tG?null:t)},[tG]),tQ=H.getWorkspace(eo);(0,r.useEffect)(()=>{if(!ex.startsWith("plugin:")||tq&&tW&&tY?.kind==="session-sidebar-tab")return;let e=!0;return queueMicrotask(()=>{e&&eb("sessions")}),()=>{e=!1}},[tW,tY,tq,ex]);let tX=(0,r.useMemo)(()=>{let e=G.find(e=>e.workId===eX);return e?{projectName:e.projectName,sessionTitle:e.sessionTitle,sessionId:e.sessionId}:null},[eX,G]),tZ=(0,r.useMemo)(()=>G.filter(e=>e.workId!==eX).map(e=>e.sessionId),[eX,G]),t0=(0,r.useCallback)(e=>{eE(e),ez(null);let t=e.plugins.some(e=>null!==e.operation&&"failed"!==e.operation.phase&&"waiting"!==e.operation.phase);t||z.refreshEntries().catch(()=>void 0),z.setEntriesMaintaining(t)},[z]),t1=(0,r.useCallback)(()=>{tC.current&&clearTimeout(tC.current);let e=++tE.current,t=15,s=n=>{tC.current=setTimeout(()=>{tC.current=null,tE.current===e&&o().then(t=>{tE.current===e&&t0(t)}).catch(n=>{if(tE.current===e){if((t-=1)>0)return void s(2e3);ez(n instanceof Error?n.message:S("pluginRestoreFailed"))}})},n)};s(1500)},[t0,o,S]),t2=(0,r.useCallback)(e=>{L.current!==e&&(L.current=e,F.current=0,ec(e))},[]),t5=(0,r.useCallback)(e=>{eB||_.current.has(e)||(_.current.add(e),$.acknowledgeCompleted(e).catch(t=>{console.warn("[Pi Desk][Workbench] 确认工作会话完成状态失败",{workId:e,message:gi(t,"请求失败")})}).finally(()=>{_.current.delete(e)}))},[eB,$]),t3=(0,r.useCallback)(e=>{var t;let s,n=(t=P.current,s=new Map(e.workSessions.map(e=>[e.workId,e])),t.flatMap(e=>{let t=s.get(e.workId);return t&&t.cwd===e.cwd&&t.sessionId===e.sessionId?[]:[e.workId]})),r=new Set(e.workSessions.map(e=>e.workId)),i=n.filter(e=>!q.current.has(e)||!r.has(e));O.current=!0,z.replaceWorkSessions(e.workSessions),P.current=e.workSessions,H.reconcileWorkSessions(e.workSessions),D.current=e.pinnedCount,eP(t=>{if(!t)return null;let s=e.workSessions.find(e=>e.workId===t.source.workId);return s?.sessionId===t.source.sessionId&&s.branchId===t.source.branchId&&s.cwd===t.cwd?t:null}),J(e.workSessions),ee(e.pinnedCount),er(t=>mY(t,e.workSessions,i));let a=L.current;a&&i.includes(a)&&(B.current=!1,t2(null))},[H,z,t2]),t4=(0,r.useCallback)(e=>{t3(e),tM.reconcileWorkSessions(e.workSessions),tA.reconcileWorkSessions(e.workSessions),m(e.workSessions)},[t3,tA,tM,m]),t6=(0,r.useCallback)(e=>{T.current=e,es(e),z.replaceGlobalPluginStates(e.plugins),(0,nK.UV)(e.settings)},[z]),t8=(0,r.useCallback)(e=>{t4(e),t6(e.appRuntime)},[t6,t4]),t7=(0,r.useCallback)(()=>{if(tj.current)return;eF(e=>"initial"===e?"initial":"refresh");let e=(async()=>{let e=await $.listWorkSessions();t8(e),await tM.applyWorkSessionsList(e.workSessions),tw(null),eF("ready")})().catch(e=>{tw(gi(e,S("syncFailed")))}).finally(()=>{tj.current===e&&(tj.current=null)});tj.current=e},[t8,tM,$,S]),t9=(0,r.useCallback)(e=>{try{let t=function(e,t){if("snapshot"===t.type)return dN.kg.parse({workSessions:t.workSessions,pinnedCount:t.pinnedCount});let s=e.workSessions.findIndex(e=>e.workId===t.workId);if(s<0){if("delete"===t.type)return e;throw Error(`WorkSession update target was not found: ${t.workId}`)}if("delete"===t.type)return{workSessions:e.workSessions.filter(e=>e.workId!==t.workId),pinnedCount:e.pinnedCount-Number(s<e.pinnedCount)};let n=[...e.workSessions];return n[s]=dN.MY.parse({...e.workSessions[s],...t.changes}),{workSessions:n,pinnedCount:e.pinnedCount}}({workSessions:P.current,pinnedCount:D.current},e);t4(t)}catch(e){tw(gi(e,S("workSessionUpdateInvalid"))),t7()}},[t4,t7,S]),se=(0,r.useCallback)(e=>{try{t6(function(e,t){if("replace"===t.type)return nU.GR.parse(t.runtime);if("notifications"===t.key)return nU.GR.parse({...e,notifications:function(e,t){if("add"===t.type){if(e.some(e=>e.notificationId===t.notification.notificationId))throw Error(`Notification already exists: ${t.notification.notificationId}`);return[...e,t.notification]}let s=e.findIndex(e=>e.notificationId===t.notificationId);if(s<0)throw Error(`Notification does not exist: ${t.notificationId}`);if("delete"===t.type)return e.filter(e=>e.notificationId!==t.notificationId);let n=[...e];return n[s]={...e[s],...t.changes},n}(e.notifications,t.update)});if("settings"===t.key)return nU.GR.parse({...e,settings:t.update});if("capabilityModes"===t.key)return nU.GR.parse({...e,capabilityModes:t.update});let s={...e.plugins};if(null===t.update.state){if(!(t.update.pluginName in s))throw Error(`Plugin global state does not exist: ${t.update.pluginName}`);delete s[t.update.pluginName]}else s[t.update.pluginName]=t.update.state;return nU.GR.parse({...e,plugins:s})}(T.current,e))}catch(e){tw(gi(e,S("appRuntimeUpdateInvalid"))),t7()}},[t6,t7,S]),st=(0,r.useCallback)(async(e=!1)=>{let t=++tN.current;e9(!0),tp(null);try{let s=await $.listDirectories(e);if(tN.current!==t)return null;return e5(s.directories),s.directories}catch(e){if(tN.current!==t)return null;return tp(gi(e,S("projectDirectoriesFailed"))),null}finally{tN.current===t&&e9(!1)}},[$,S]),ss=(0,r.useCallback)(async(e=!1)=>{let t=++tI.current;tt(!0),tp(null);try{let s=await $.listIgnoredDirectories(e);if(tI.current!==t)return;e4(s.directories)}catch(e){if(tI.current!==t)return;tp(gi(e,S("ignoredDirectoriesFailed")))}finally{tI.current===t&&tt(!1)}},[$,S]),sn=(0,r.useCallback)(async e=>{let t=++tS.current;tn(!0),tp(null);try{let s=await $.listDirectoryEntries(e);if(tS.current!==t)return;e8(s)}catch(e){if(tS.current!==t)return;tp(gi(e,S("browseDirectoryFailed")))}finally{tS.current===t&&tn(!1)}},[$,S]);N="initial"!==eL,(0,r.useEffect)(()=>{let e;if(!N)return;let t=!0,s=!1,n=!1,r=()=>{!t||(n=!0,s||(s=!0,(async()=>{try{for(;t&&n;){n=!1;let e=await o();t&&t0(e)}}catch(s){let e=s instanceof Error?s.message:String(s);t&&ez(e||"读取插件健康状态失败"),console.warn("[Pi Desk][Workbench] 读取插件健康状态失败",{message:e})}finally{s=!1}})()))},i=c(r);if("function"==typeof window.requestIdleCallback){let t=window.requestIdleCallback(r,{timeout:3e3});e=()=>{window.cancelIdleCallback(t)}}else{let t=window.setTimeout(r,1500);e=()=>{window.clearTimeout(t)}}return()=>{t=!1,i(),e()}},[ez,t0,o,N,c]),(0,r.useEffect)(()=>()=>{tE.current+=1,tC.current&&clearTimeout(tC.current)},[]),(0,r.useEffect)(()=>{let e=!0;return queueMicrotask(()=>{if(!e)return;let t=function(){var e=window.localStorage.getItem(mW)??window.sessionStorage.getItem(mW);if(!e)return{primaryWorkId:null};try{let t=JSON.parse(e);if(!t||"object"!=typeof t)return{primaryWorkId:null};return{primaryWorkId:"string"==typeof t.primaryWorkId?t.primaryWorkId:null}}catch{return{primaryWorkId:null}}}();er(O.current?mY(t,P.current):t),el(!0)}),()=>{e=!1}},[]),(0,r.useEffect)(()=>{dQ(H,K,G,eo)},[H,eo,K,G]),(0,r.useEffect)(()=>(function(e,t,s,n,r){let i=e.subscribeSourceEvents(({source:e,event:i},a)=>{("session_sync"===i.type||"runtime_update"===i.type)&&(t.applyPreviewDirectories(e,(0,d_.D)(a.runtime.plugins[d_.s6])),dQ(t,s,n(),r()))});for(let{workId:s,sessionId:r,branchId:i}of n()){let n={workId:s,sessionId:r,branchId:i},a=e.getSourceState(n);"loading"!==a.syncStatus&&t.applyPreviewDirectories(n,(0,d_.D)(a.runtime.plugins[d_.s6]))}return dQ(t,s,n(),r()),i})(tM,H,K,()=>P.current,()=>L.current),[tM,H,K]),(0,r.useEffect)(()=>{let e={};return tR.current={token:e,fileRuntime:H,gitRuntime:K},()=>{tR.current?.token===e&&(tR.current=null),queueMicrotask(()=>{let e=tR.current;e?.fileRuntime!==H&&H.dispose(),e?.gitRuntime!==K&&K.dispose()})}},[H,K]),(0,r.useEffect)(()=>{let e={};return t$.current={token:e,chatRuntime:tM,chatInputRuntime:tA,taskCenterStart:d},tM.start(e=>{tw(gi(e,S("chatSyncFailed"))),t7()}),d(e=>{tw(gi(e,S("taskSyncFailed")))}),()=>{t$.current?.token===e&&(t$.current=null),queueMicrotask(()=>{let e=t$.current;(e?.chatRuntime!==tM||e.chatInputRuntime!==tA||e.taskCenterStart!==d)&&(u(),tA.dispose(),tM.dispose())})}},[tA,tM,t7,d,u,S]),(0,r.useEffect)(()=>{let s=new AbortController,n=null,r=null,i=async()=>{eF(e=>"initial"===e?"initial":"refresh");let r=!0;try{let n=await $.readWorkSessionUpdates(s.signal,async(n,r)=>{r&&(tM.disconnected(),p(),t()),t8(n),await tM.applyWorkSessionsList(n.workSessions),h(),e(),tw(null),eF("ready"),R(r,s.signal,E.waitForClose())},t9,se);if(s.signal.aborted)return;tM.disconnected(),p(),t(),eF(e=>"initial"===e?"initial":"refresh"),n.code===l.Sp&&(r=!1),(0,ei.p)(n)&&(r=!1,tw(S("replacedConnection")))}catch(e){if(s.signal.aborted)return;tM.disconnected(),p(),t(),console.warn("[Pi Desk][Workbench] 工作会话实时连接失败,将重新连接",{message:gi(e,"连接失败")}),O.current||tw(gi(e,S("realtimeFailed")))}!s.signal.aborted&&r&&(n=setTimeout(()=>void i(),1e3))};return r=setTimeout(()=>void i(),0),()=>{s.abort(),r&&clearTimeout(r),n&&clearTimeout(n)}},[E,se,t8,t9,tM,R,p,h,e,t,$,S,ty]),(0,r.useEffect)(()=>{if(!ea||eB||null!==eo||!B.current||!en.primaryWorkId)return;let e=P.current.find(e=>e.workId===en.primaryWorkId);(B.current=!1,e)?t2(e.workId):er(e=>({...e,primaryWorkId:null}))},[eo,en.primaryWorkId,ea,eB,t2]),(0,r.useEffect)(()=>{let e;if(!ea)return;let t=new Map(G.map(e=>[e.workId,e])),s=((e=en.primaryWorkId?[en.primaryWorkId]:[]).push(...tP),Array.from(new Set(e))).map(e=>t.get(e)).filter(e=>void 0!==e);ey&&tq&&"files"===ex&&!s.some(e=>e.workId===tq.workId)&&s.push(tq),tM.ensureDisplayedWorkSessions(s)},[tq,tM,ey,en,ea,tP,ex,G]),(0,r.useEffect)(()=>{ea&&window.localStorage.setItem(mW,JSON.stringify(en))},[en,ea]);let sr=(0,r.useCallback)(e=>{if(!P.current.find(t=>t.workId===e))return;B.current=!1;let t=P.current.slice(0,D.current).map(e=>e.workId),s=L.current===e;if(t.includes(e)&&e!==en.primaryWorkId){s||t2(e),W&&eh(!1);return}en.primaryWorkId!==e&&er(t=>t.primaryWorkId===e?t:{...t,primaryWorkId:e}),s||t2(e),W&&eh(!1)},[en,W,t2]),si=(0,r.useCallback)(e=>{let t=P.current.find(t=>t.workId===e);t?.status==="completed"&&t5(e),sr(e)},[t5,sr]),sa=(0,r.useCallback)(async e=>{if(eB)throw Error(S("workSessionInitializing"));let t="workId"in e?P.current.find(t=>t.workId===e.workId):P.current.find(t=>t.sessionId===e.sessionId);if(t)return si(t.workId),t;if("workId"in e||!e.cwd)throw Error(S("sessionNotFound"));let{workSession:s}=await $.createWorkSession({cwd:e.cwd,sessionId:e.sessionId});return B.current=!1,er({primaryWorkId:s.workId}),t2(s.workId),W&&eh(!1),s},[eB,W,si,t2,$,S]),sl=(0,r.useCallback)(async(e,t)=>{if(eB||e_)return;let s={workSessions:P.current,pinnedCount:D.current},n=s.workSessions.findIndex(e=>e.workId===t),r=e.workIds.indexOf(t);if(n<0||r<0)return;let i=new Map(s.workSessions.map(e=>[e.workId,e])),a=e.workIds.map(e=>i.get(e)).filter(e=>void 0!==e);if(a.length!==s.workSessions.length)return;let l=n<s.pinnedCount,o=r<e.pinnedCount;t3({workSessions:a,pinnedCount:e.pinnedCount}),eW(!0),tw(null);let c=!1;try{t4(await $.sortWorkSessions(e)),c=!0}catch(e){t3(s),tw(gi(e,S("sortFailed")))}finally{eW(!1)}if(c&&l!==o){if(W){o||L.current!==t||t===en.primaryWorkId||t2(en.primaryWorkId);return}if(o)return void er(e=>e.primaryWorkId===t?{primaryWorkId:null}:e);L.current===t&&t2(en.primaryWorkId)}},[t4,t3,en.primaryWorkId,eB,W,e_,t2,$,S]),so=(0,r.useCallback)(e=>{if(eB||e_)return;let t=function(e,t,s){hE(e,t);let n=e.indexOf(s);if(n<0)return null;let r=e.filter(e=>e!==s),i=n<t,a=i?t-1:t+1;return r.splice(i?r.length:t,0,s),{workIds:r,pinnedCount:a}}(P.current.map(e=>e.workId),D.current,e);t&&sl(t,e)},[eB,e_,sl]),sc=(0,r.useCallback)(async e=>{if(!eB){eV(e),tw(null);try{t4(await $.deleteWorkSession(e))}catch(e){tw(gi(e,S("deleteFailed")))}finally{eV(null)}}},[t4,eB,$,S]),sd=(0,r.useCallback)(()=>{if(eB)return;let e=ga((iu(),ii));e&&e5(e),tp(null),eG("create"),eQ("directories"),eZ(null),tI.current+=1,tt(!1),tS.current+=1,tn(!1),tx(),e1(null),eH(!0),st().then(e=>{e?.length===0&&(eQ("browser"),e8(gl(ig(null))),sn(null))})},[tx,st,sn,eB]),su=(0,r.useCallback)(()=>{if(eB)return;let e=G.find(e=>e.workId===eo);e&&(tp(null),tN.current+=1,e9(!1),tI.current+=1,tt(!1),tS.current+=1,tn(!1),eG("replace"),eQ("history"),eZ(e.workId),e1(e.cwd),tb(e.cwd),eH(!0),tf(e.cwd))},[eo,tf,eB,tb,G]),sm=async(e,t)=>{if(!eB&&"create"===eK&&null===to){tc(e),tp(null);try{await $.replaceDirectoryIgnore({cwd:e,ignored:t}),await Promise.all([st(),ss()])}catch(e){tp(gi(e,S(t?"ignoreFailed":"restoreIgnoredFailed")))}finally{tc(null)}}},sp=(0,r.useCallback)(async e=>{let t=W?"activate":Y;if("activate"===t){B.current=!1,er({primaryWorkId:e.workId}),t2(e.workId),W&&eh(!1);return}if("pin"!==t)return;let s=function(e,t,s){hE(e,t);let n=e.indexOf(s);if(n>=0&&n<t)return null;let r=e.filter(e=>e!==s);return r.splice(t,0,s),{workIds:r,pinnedCount:t+1}}(P.current.map(e=>e.workId),D.current,e.workId);if(s){eW(!0);try{t4(await $.sortWorkSessions(s))}catch(e){tw(gi(e,S("autoPinFailed")))}finally{eW(!1)}}},[t4,W,Y,t2,$,S]),{model:sh,open:sg,close:sf,retry:sx,selectEntry:sb,requestAction:sv,clone:sw,confirmRunning:sy,cancelRunning:sk,pendingWorkId:sj}=function({disabled:e,workSessions:t,workbenchBiz:s,chatInputRuntime:n,applyWorkSessionSnapshot:i,applyCreatedWorkSessionBehavior:a,focusWorkSession:l,onError:o,mobile:c}){let[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(null),[b,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(null),[N,I]=(0,r.useState)(null),[S,C]=(0,r.useState)(null),E=(0,r.useRef)(0),M=(0,r.useRef)(null),z=(0,r.useRef)(0),A=(0,r.useRef)(null),$=(0,r.useRef)(new Map),R=(0,r.useRef)(null),P=(0,r.useCallback)(()=>{E.current+=1,M.current?.abort(),M.current=null,z.current+=1,A.current?.abort(),A.current=null,$.current.clear(),R.current=null,u(null),p(null),g(!1),x(null),v(null),y(!1),j(null),I(null)},[]),D=(0,r.useCallback)(()=>{S||P()},[S,P]);(0,r.useEffect)(()=>()=>{M.current?.abort(),A.current?.abort()},[]);let T=(0,r.useCallback)(async e=>{let t=++E.current;M.current?.abort();let n=new AbortController;M.current=n,z.current+=1,A.current?.abort(),A.current=null,$.current.clear(),u(e),p(null),g(!0),x(null),v(null),y(!1),j(null),I(null);try{let r=await s.getWorkSessionTree({workId:e.workId,sessionId:e.sessionId},n.signal);if(E.current!==t)return;p(r)}catch(e){if(E.current!==t||hz(e))return;x(hM(e,dV("treeLoadFailed")))}finally{E.current===t&&(M.current===n&&(M.current=null),g(!1))}},[s]),O=(0,r.useCallback)(s=>{if(e)return;let n=t.find(e=>e.workId===s);n?(l(s),T(h$(n))):o(dV("treeSourceInvalid"))},[e,l,T,o,t]),L=(0,r.useCallback)(()=>{d&&!e&&T(d)},[e,T,d]),F=(0,r.useCallback)(e=>{if(!d)return;let t=$.current.get(e);if(t){z.current+=1,A.current?.abort(),A.current=null,v(t),y(!1),j(null);return}let n=++z.current;A.current?.abort();let r=new AbortController;A.current=r,v(null),y(!0),j(null),s.getWorkSessionTreeEntry({workId:d.workId,sessionId:d.sessionId,entryId:e},r.signal).then(t=>{z.current===n&&($.current.set(e,t),v(t))}).catch(e=>{z.current!==n||hz(e)||j(hM(e,dV("treeDetailFailed")))}).finally(()=>{z.current===n&&(A.current===r&&(A.current=null),y(!1))})},[d,s]),B=(0,r.useCallback)(e=>{o(e)},[o]),q=(0,r.useCallback)(async(t,r)=>{if(e)return;let o="tree"===r.action?n.getState(t).text:null;C({source:t,intent:r,phase:"executing"}),x(null);try{let e=await s.branchWorkSession(function(e,t){let s={workId:e.workId,sessionId:e.sessionId};switch(t.action){case"tree":return{...s,action:"tree",entryId:t.entryId};case"fork":return{...s,action:"fork",entryId:t.entryId};case"clone":return{...s,action:"clone"}}}(t,r)),d={workSessions:e.workSessions,pinnedCount:e.pinnedCount};i(d);let u=e.workSessions.find(t=>t.workId===e.targetWorkId);if(!u)throw Error(dV("branchTargetMissing"));let m=h$(u);if("tree"===r.action){var c;l(u.workId),await n.loadSource(m),n.setText(m,(c=o??"",e.editorText??c))}else null!==e.editorText&&(await n.loadSource(m),n.setText(m,e.editorText)),await a(u);C(null),R.current=null,P()}catch(e){C(null),R.current=null,I(e=>e?{...e,waiting:!1}:null),B(hM(e,dV("branchOperationFailed")))}},[a,i,n,e,l,B,P,s]),_=(0,r.useCallback)((e,t,s)=>{C({source:e,intent:t,phase:"waiting"}),I(e=>e?{...e,waiting:!0}:e),"main_running"===s.status&&n.interrupt(e).catch(e=>{C(null),R.current=null,I(e=>e?{...e,waiting:!1}:e),B(hM(e,dV("interruptForBranchFailed")))})},[n,B]),W=(0,r.useCallback)((s,n)=>{if(e||S)return;R.current=null;let r=t.find(e=>e.workId===s.workId);if(!r||r.sessionId!==s.sessionId||r.branchId!==s.branchId)return void B(dV("treeChanged"));if("fork"===n.action||!hA(r))return void q(s,n);let i="main_running"===r.status?"main":"background";c?_(s,n,r):(I({intent:n,reason:i,waiting:!1}),u(s),x(null))},[e,q,c,S,B,_,t]),Y=(0,r.useCallback)((e,t)=>{d&&W(d,{action:t,entryId:e})},[W,d]),V=(0,r.useCallback)(e=>{let s=t.find(t=>t.workId===e);s?W(h$(s),{action:"clone"}):o(dV("cloneUnavailable"))},[o,W,t]),U=(0,r.useCallback)(()=>{if(e||!d||!N||N.waiting||S)return;let s=t.find(e=>e.workId===d.workId);s?hA(s)?_(d,N.intent,s):q(d,N.intent):B(dV("branchUnavailable"))},[N,e,q,S,B,d,_,t]),H=(0,r.useCallback)(()=>{if(N?.waiting||S)return;let e=N?.intent.action==="clone"&&null===m;I(null),e&&P()},[N,S,P,m]);return(0,r.useEffect)(()=>{if(e||!S||"waiting"!==S.phase)return;let s=t.find(e=>e.workId===S.source.workId);if(!s){let e=`${S.source.workId}:${S.intent.action}:missing`;if(R.current===e)return;R.current=e,queueMicrotask(()=>{C(null),R.current=null,I(e=>e?{...e,waiting:!1}:e),B(dV("branchUnavailable"))});return}if(s.sessionId!==S.source.sessionId||s.branchId!==S.source.branchId){let e=`${S.source.workId}:${S.intent.action}:changed`;if(R.current===e)return;R.current=e,queueMicrotask(()=>{C(null),R.current=null,I(e=>e?{...e,waiting:!1}:e),B(dV("branchChanged"))});return}if(hA(s))return;let n=`${S.source.workId}:${S.intent.action}:${"entryId"in S.intent?S.intent.entryId:""}`;if(R.current===n)return;R.current=n;let r=!0;return queueMicrotask(()=>{r&&q(S.source,S.intent)}),()=>{r=!1,R.current===n&&(R.current=null)}},[e,q,S,B,t]),(0,r.useEffect)(()=>{if(!d||S||N)return;let e=t.find(e=>e.workId===d.workId);if(e?.sessionId===d.sessionId&&e.branchId===d.branchId)return;let s=!0;return queueMicrotask(()=>{s&&P()}),()=>{s=!1}},[N,S,P,d,t]),{model:(0,r.useMemo)(()=>{if(!d)return null;let s=t.find(e=>e.workId===d.workId),n=s?.sessionId===d.sessionId&&s.branchId===d.branchId;return S||N||n?{workId:d.workId,tree:m,loading:h,actionsDisabled:e,pending:null!==S,error:f,detail:b,detailLoading:w,detailError:k,runningConfirmation:N}:null},[N,b,k,w,e,f,h,S,d,m,t]),open:O,close:D,retry:L,selectEntry:F,requestAction:Y,clone:V,confirmRunning:U,cancelRunning:H,pendingWorkId:S?.source.workId??null}}({disabled:eB,workSessions:G,workbenchBiz:$,chatInputRuntime:tA,applyWorkSessionSnapshot:t4,applyCreatedWorkSessionBehavior:sp,focusWorkSession:t2,onError:(0,r.useCallback)(e=>{M.error(e)},[M]),mobile:W});(0,r.useEffect)(()=>{let e=e=>{if("Escape"!==e.key)return;if(e.defaultPrevented||e.target instanceof Element&&e.target.closest('[data-testid="file-workspace"], [role="menu"], [data-slot="app-dialog-content"]')){F.current=0;return}if(e.repeat||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||e.isComposing)return;if(W&&eg.current){e.preventDefault(),F.current=0,ef();return}if(null!==sh)return;let t=L.current;if(!t)return;if(W){F.current=0;let s=H.getWorkspace(t),n=document.querySelector(`[data-work-id="${CSS.escape(t)}"]`);s?.windowOpen&&"files"===s.activePane&&n&&!n.closest("[inert]")&&(e.preventDefault(),H.hideWindow(t));return}let s=Date.now();if(s-F.current>=500){F.current=s;return}e.preventDefault(),F.current=0,sg(t)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[sh,ef,H,W,sg]),(0,r.useEffect)(()=>z.bindWorkSessionCreate(async e=>{if(eB)throw Error(S("workSessionInitializing"));let{workSession:t}=await $.createWorkSession({cwd:e});return await sp(t),t}),[sp,eB,z,$,S]),(0,r.useEffect)(()=>z.bindWorkSessionGoTo(sa),[sa,z]);let sN=async e=>{if(!eB){tN.current+=1,e9(!1),tS.current+=1,tn(!1),ti(e),tp(null);try{let{workSession:t}=await $.createWorkSession({cwd:e});tp(null),eH(!1),await sp(t)}catch(e){tp(gi(e,S("createFailed")))}finally{ti(null)}}},sI=async e=>{if(!eB&&eX&&e0){if(!P.current.some(e=>e.workId===eX))return void tp(S("replaceTargetMissing"));tx(),q.current.add(eX),tl(e),tp(null);try{let t=await $.replaceWorkSession({workId:eX,cwd:e0,sessionId:e});if(t4(t),!t.workSessions.find(e=>e.workId===eX))throw Error(S("replacementMissing"));B.current=!1,t2(eX),tp(null),eH(!1),W&&eh(!1)}catch(e){tp(gi(e,S("replaceFailed")))}finally{q.current.delete(eX),tl(null)}}},sS=(0,r.useCallback)(async e=>{if(!eB&&null===td&&P.current.some(t=>t.workId===e)){q.current.add(e),tu(e),tw(null);try{let t=await $.replaceWorkSession({workId:e});if(t4(t),!t.workSessions.find(t=>t.workId===e))throw Error(S("emptyReplacementMissing"));B.current=!1,t2(e)}catch(e){tw(gi(e,S("replaceEmptyFailed")))}finally{q.current.delete(e),tu(null)}}},[t4,eB,td,t2,$,S]),sC=(0,r.useCallback)(e=>{eb(e),"files"===e&&ek(!0)},[]),sE=(0,r.useCallback)(()=>{W&&ef(),eo&&!document.querySelector(`[data-work-id="${CSS.escape(eo)}"] [data-testid="session-file-layout"]`)&&H.expandWindow(eo)},[eo,ef,H,W]),sM=(0,r.useCallback)(()=>{t_&&eo&&(H.refreshTree(eo),K.refreshSnapshot(H.getDirectory(eo)))},[t_,eo,H,K]),sz=(0,r.useCallback)(e=>{eT(e)},[]),sA=(0,r.useCallback)(()=>{eT(null)},[]),s$=(0,r.useCallback)((e,t,s="session",n)=>{let r=P.current.find(t=>t.workId===e.workId&&t.sessionId===e.sessionId&&t.branchId===e.branchId);if(!r)return void M.error(S("sourceChanged"));if("standalone"===s){eP({source:{workId:r.workId,sessionId:r.sessionId,branchId:r.branchId},cwd:r.cwd,projectName:r.projectName,path:t,imagePaths:n}),ef();return}H.selectDirectory(r.workId,r.cwd),H.openFile(r.workId,t),sr(r.workId),ef();let i=document.querySelector(`[data-work-id="${CSS.escape(r.workId)}"] [data-testid="session-file-layout"]`);"expanded"!==s&&i?eA&&eO():H.expandWindow(r.workId)},[eA,ef,eO,H,sr,M,S]),sR=(0,r.useCallback)((e,t,s,n)=>{let r=dC.safeParse(t),i=dC.array().nonempty().optional().safeParse(n);r.success&&i.success&&(!i.data||"standalone"===s&&i.data.includes(r.data))?s$(e,r.data,s,i.data?[...new Set(i.data)]:void 0):M.error(S("invalidFilePath"))},[s$,M,S]),sP=(0,r.useCallback)((e,t)=>{let s=dC.safeParse(t);s.success?s$(e,s.data):M.error(S("invalidToolFilePath"))},[s$,M,S]);(0,r.useEffect)(()=>z.bindWorkSessionFilePreview(({source:e,path:t,mode:s,imagePaths:n})=>{sR(e,t,s??"session",n)}),[z,sR]),(0,r.useEffect)(()=>z.bindImageReader(({source:e,cwd:t,path:s},n)=>ui(V,{workId:e.workId,cwd:t,path:s},n)),[z,V]);let sD=(0,r.useCallback)(async(e,t)=>{let s=dC.safeParse(t);if(!s.success)throw Error(S("invalidFilePath"));let n=P.current.find(t=>t.workId===e.workId&&t.sessionId===e.sessionId&&t.branchId===e.branchId);if(!n)throw Error(S("sourceChanged"));await V.reveal({workId:n.workId,cwd:n.cwd,path:s.data})},[V,S]);(0,r.useEffect)(()=>z.bindWorkSessionFileReveal(({source:e,path:t})=>sD(e,t)),[z,sD]);let sT=(0,r.useCallback)((e,t)=>{tV&&tU&&tH?sR({workId:tV,sessionId:tU,branchId:tH},e,t?.mode??"session",t?.imagePaths):M.error(S("noPreviewSession"))},[tH,tU,tV,sR,M,S]),sO=(0,r.useCallback)(e=>tV&&tU&&tH?sD({workId:tV,sessionId:tU,branchId:tH},e):Promise.reject(Error(S("noRevealSession"))),[tH,tU,tV,sD,S]),sL=(0,r.useCallback)(async e=>{await $.applyAppRuntimeUpdate({key:"notifications",update:{type:"delete",notificationId:e}})},[$]),sF=(0,r.useCallback)(async e=>{if(e.event)try{await z.dispatchNotificationEvent(e.notificationId,e.event),await sL(e.notificationId)}catch(e){M.error(gi(e,S("notificationActionFailed")))}},[sL,z,M,S]),sB=(0,r.useCallback)(async e=>{try{await sL(e)}catch(e){M.error(gi(e,S("notificationDeleteFailed")))}},[sL,M,S]),sq=(0,r.useCallback)(e=>{ef(),eS(e),eN(!0)},[ef]),s_=(0,r.useCallback)(e=>{ef(),e$(e)},[ef]),sW=(0,r.useCallback)(e=>void sc(e),[sc]),sY=(0,r.useCallback)((e,t)=>void sl(e,t),[sl]),sV=(0,r.useCallback)(e=>void sS(e),[sS]),sH=(0,r.useCallback)(()=>{W?eh(e=>!e):em(e=>!e)},[W]),sK=(0,r.useCallback)(e=>{sr(e),W?eh(!0):em(!0)},[sr,W]),sG=W?ep:eu,sJ=eD&&G.some(e=>e.workId===eD.workId&&e.cwd===eD.cwd)?eD:null,sQ=(0,r.useMemo)(()=>ey&&tq?(0,n.jsx)(r.Activity,{mode:sG&&"files"===ex?"visible":"hidden",children:(0,n.jsx)(dJ.k,{workId:tq.workId,cwd:tq.cwd,projectName:tq.projectName,runtime:H,gitRuntime:K,onOpenGitBranches:sz,onFileOpened:sE},`${tq.workId}:${tq.sessionId}:${tq.branchId}`)}):null,[tq,ey,H,K,sE,sz,ex,sG]),sX=sG&&tW&&tY?.kind==="session-sidebar-tab"&&tK&&tq?(0,n.jsx)(go,{render:f,input:{pluginName:tW.pluginName,descriptor:tY,source:tK,cwd:tq.cwd,onPreviewFile:sT,onRevealFile:sO,onHeaderActionsChange:tJ}}):null,sZ=(0,n.jsx)(ge,{mode:ex,mobile:W,fileBrowser:sQ,pluginTabContent:sX,pluginHeaderActions:sG&&ev?.targetKey===tG?ev.actions:[],pluginSessionTabs:tT,fileRefreshLoading:tQ?.directories.get("")?.status==="loading",canBrowseFiles:null!==t_,workSessions:G,focusedWorkId:eo,pinnedCount:Z,ordering:e_,deletingWorkId:eY,canReplace:null!==eo,disabled:eB,pluginApplications:tD,settingsAttention:tF,notifications:et.notifications,onConsumeNotification:sF,onDismissNotification:sB,onModeChange:sC,onRefreshFiles:sM,onPreviewProject:()=>{t_&&(ef(),H.collapseExpandedWindow(),z.previewProject(eo?H.getDirectory(eo):t_))},onPreviewProjectWindow:()=>{t_&&i(eo?H.getDirectory(eo):t_)},onOpenTerminal:()=>{ef(),H.collapseExpandedWindow(),s(t_??void 0).catch(()=>void 0)},onCreate:sd,onReplace:su,onSettings:()=>sq(),onOpenPluginApplication:s_,onSelect:si,onTogglePin:so,onDelete:sW,onRename:eq.show,syncingWorkIds:tz.syncingWorkIds,onReloadChat:tz.reload,onArrangementChange:sY}),s0=(0,n.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col",children:[tv?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 border-b border-destructive/30 bg-destructive/10 px-4 py-2 text-sm text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 wrap-anywhere",children:tv}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>tk(e=>e+1),children:S("retry",{ns:"common"})}),"initial"!==eL?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>tw(null),children:S("close",{ns:"common"})}):null]}):null,(0,n.jsxs)("div",{className:"relative h-full min-h-0 min-w-0 flex-1",children:[(0,n.jsx)(hN,{workSessions:G,primaryWorkId:en.primaryWorkId,pinnedWorkIds:tP,focusedWorkId:eo,sidebarOpen:sG,mobile:W,loading:eB,replacingWithEmptyWorkId:td,chatRuntime:tM,chatInputRuntime:tA,renderTaskSummary:v,renderTaskMenu:w,renderPluginComposerPanel:y,renderPluginWidgets:k,renderPluginSessionHeader:j,gitRuntime:K,invokePluginMethod:$.invokePluginMethod,listPiCommands:$.listPiCommands,getChatModelContext:$.getChatModelContext,capabilityModes:et.capabilityModes,setChatCapabilityMode:$.setChatCapabilityMode,branchPicker:sh,branchPendingWorkId:sj,fileRuntime:H,onOpenFileSidebar:sK,onPreviewFile:sP,onAcknowledgeCompleted:t5,onFocusWorkSession:sr,onReplaceWithEmptyWorkSession:sV,onOpenBranchPicker:sg,onOpenGitBranchPicker:sz,onOpenSettings:sq,onCloseBranchPicker:sf,onRetryBranchPicker:sx,onSelectBranchEntry:sb,onBranchAction:sv,onConfirmRunningBranch:sy,onCancelRunningBranch:sk,onCloneWorkSession:sw,onUnpinWorkSession:so,onToggleSidebar:sH}),"initial"===eL?(0,n.jsx)(mV,{variant:"loading",className:"absolute inset-0 z-20 bg-background"}):null]})]}),s1=null!==eA&&tB?.kind==="application",s2=(0,n.jsxs)("div",{className:"flex min-h-0 min-w-0 flex-1",children:[(0,n.jsx)(go,{render:a,input:{mobile:W,children:s0}}),s1?(0,n.jsx)(go,{render:g,input:{pluginName:eA.pluginName,descriptor:tB,workSessions:G,preferredWorkId:eo,onClose:eO}}):null]});return(0,n.jsxs)("main",{className:"pi-desk-workbench flex h-dvh overflow-hidden bg-background",children:[(0,n.jsx)(dT,{mobile:W,open:sG,sidebar:sZ,onClose:ef,children:s2}),(0,n.jsx)(d6,{target:eR,biz:V,images:H.standaloneImages,mobile:W,onClose:()=>eP(null)},eR?`${eR.source.workId}:${eR.source.sessionId}:${eR.source.branchId}:${eR.path}`:"closed"),(0,n.jsx)(un,{workSessions:G,runtime:H,gitRuntime:K,mobile:W,onOpenGitBranches:sz,onOpenSidebar:sK,onOpenTerminal:e=>{H.collapseExpandedWindow(),ef(),s(e).catch(()=>void 0)}}),(0,n.jsx)(um,{target:sJ,runtime:K,mobile:W,onClose:sA},sJ?`${sJ.workId}:${sJ.cwd}:${sJ.repositoryRoot??""}`:"git-branch-picker-closed"),(0,n.jsx)(go,{render:x,input:{open:ej,connectionReady:"ready"===eL,initialPage:eI,capabilityModes:et.capabilityModes,workSessions:G,focusedCwd:t_,basicMode:"basic"===et.mode,pluginManagementSnapshot:eC,pluginAttention:tF,onPluginManagementSnapshot:t0,onPluginRestartScheduled:t1,onOpenChange:eN,onBeforeReload:()=>tA.prepareForPageReload()}}),(0,n.jsx)(hR,{open:eq.open,title:eq.title,saving:eq.saving,disabled:eB,error:eq.error,onTitleChange:eq.setTitle,onSave:()=>void eq.save(),onClose:eq.close}),(0,n.jsx)(m_,{open:eU,pickerMode:eK,pickerView:eJ,pickerCwd:e0,directories:e2,ignoredDirectories:e3,directoryBrowser:e6,historySessions:th,replacementTarget:"create"===eK?null:tX,unavailableSessionIds:tZ,error:tm,loading:"history"===eJ?tg:"ignored"===eJ?te:"browser"===eJ?ts:e7,creatingCwd:tr,replacingSessionId:ta,updatingIgnoreCwd:to,onOpenChange:e=>{eH(e),e||(tN.current+=1,e9(!1),tI.current+=1,tt(!1),tS.current+=1,tn(!1),tx(),eG(null),eQ("directories"),tp(null))},onBack:()=>{tp(null),tI.current+=1,tt(!1),tS.current+=1,tn(!1),tx();let e=ga((iu(),ii));e&&e5(e),eQ("directories"),e1(null),st()},onSearchHistory:(e,t)=>{"history"===eJ&&e0&&tf(e0,e,t)},onListSessionUserMessages:(e,t)=>$.listSessionUserMessages(e,t),onRefresh:(e,t)=>{"history"===eJ&&e0?tf(e0,e,t,!0):"ignored"===eJ?ss(!0):"browser"===eJ?sn(e6?.cwd??null):st(!0)},onOpenIgnoredDirectories:()=>{if(eB||"create"!==eK)return;let e=ga((iu(),ia));e?e4(e):e4([]),tp(null),tN.current+=1,e9(!1),tS.current+=1,tn(!1),eQ("ignored"),ss()},onOpenDirectoryBrowser:()=>{eB||"create"!==eK||(tp(null),tN.current+=1,e9(!1),tI.current+=1,tt(!1),eQ("browser"),e8(gl(ig(null))),sn(null))},onNavigateDirectory:e=>{if(eB||"create"!==eK)return;let t=gl(ig(e));t&&e8(t),sn(e)},onSelectBrowserDirectory:e=>void sN(e),onReplaceDirectoryIgnore:(e,t)=>void sm(e,t),onSelectDirectory:e=>{"replace"===eK?(tN.current+=1,e9(!1),eQ("history"),e1(e),tb(e),tf(e)):sN(e)},onSelectSession:e=>void sI(e)})]})}function gd(e){return(0,n.jsx)(eK,{...e},`${e.pluginName}:${e.descriptor.contributionName}`)}function gu(e){return(0,n.jsx)(sP,{...e},`${e.pluginName}:${e.descriptor.contributionName}:${e.source.workId}:${e.source.sessionId}:${e.source.branchId}`)}function gm(e){let t=JSON.stringify([e.source.workId,e.source.sessionId,e.source.branchId]);return(0,n.jsx)(eG,{...e},`${e.pluginName}:${e.descriptor.contributionName}:${t}`)}function gp(e){return(0,n.jsx)(sT,{...e},`${e.source.workId}:${e.source.sessionId}:${e.source.branchId}:${e.placement}`)}function gh(e){return(0,n.jsx)(sB,{...e},`${e.source.workId}:${e.source.sessionId}:${e.source.branchId}`)}function gg(e){return(0,n.jsx)(sD,{...e},`${e.pluginName}:${e.descriptor.contributionName}`)}function gf(){let{clientId:e,appSocket:t}=(0,ei.gM)(),s=(0,Q.t4)(),a=(0,X.G)(),l=(0,r.useMemo)(()=>new x(t,a.error),[t,a.error]);(0,r.useEffect)(()=>{l.start();let e=s.bindTerminalOpen((e,t)=>l.open(e,t));return()=>{e(),l.dispose()}},[s,l]);let o=(0,r.useCallback)(e=>(0,n.jsx)(J,{...e,biz:l}),[l]),c=(0,r.useMemo)(()=>({subscribeChanges:e=>t.subscribe(sy,e),list:(t=!1)=>sR(e,"/api/plugins/list",sC.parse("boolean"==typeof t?t?{checkUpdates:!0}:{}:t),sN),batch:t=>sR(e,"/api/plugins/batch",sz.parse(t),sA),get:t=>sR(e,"/api/plugins/get",sE.parse({source:t}),sj),add:t=>sR(e,"/api/plugins/add",sM.parse(t),sN),setEnabled:(t,s)=>sR(e,"/api/plugins/enabled-set",s$.parse({source:t,enabled:s}),sN),searchCatalog:t=>sR(e,"/api/plugin-catalog/search",t$.parse(t),tD),getCatalog:t=>sR(e,"/api/plugin-catalog/get",tR.parse(t),tT),getCatalogSettings:()=>sR(e,"/api/plugin-catalog/settings-get",{},tz),saveCatalogSettings:t=>sR(e,"/api/plugin-catalog/settings-replace",tA.parse({downloadSource:t}),tz),update:t=>sR(e,"/api/plugins/update",sE.parse({source:t}),sN),del:t=>sR(e,"/api/plugins/del",sE.parse({source:t}),sN),reload:t=>sR(e,"/api/plugins/reload",sS.parse({mode:t}),sN),apply:t=>sR(e,"/api/plugins/apply",sI.parse({sources:t}),sN)}),[e,t]),d=(0,r.useMemo)(()=>(function(e,t){async function s(t,s){let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s)}),r=await n.json();if(!n.ok||0!==r.code||null===r.data)throw Error(r.msg?(0,ed.B)(r):"请求失败");return r.data}return{watchDetail:e=>t.request(lz.detailWatch,e),async interrupt(e){await t.request(lz.interrupt,e)},subscribeDetailEvents:e=>t.subscribe(lz.detailEvent,e),getMessageDetail:e=>s("/api/task-center/messages/get",e),getImage:e=>s("/api/task-center/images/get",e)}})(e,t),[t,e]),u=(0,r.useMemo)(()=>{let e,t,s,n,r,i,a,l,o,c,u,m,p,h,g,f;return e=new Set,t=new Map,s=dk,n=0,r=0,i=!1,a=null,l=()=>void 0,o=null,c=!1,u=()=>{for(let t of[...e])try{t()}catch(e){console.error("[Pi Desk][TaskCenterClient] 状态监听器执行失败",{errorName:e instanceof Error?e.name:"UnknownError"})}},m=(e,t=!1)=>{s=e,((e=!1)=>{if(e){if(o)return;o=setTimeout(()=>{o=null,u()},16);return}o&&clearTimeout(o),o=null,u()})(t)},p=e=>{for(let[s,n]of t)(void 0===e||n.taskId===e)&&(URL.revokeObjectURL(n.url),t.delete(s))},h=()=>{if(!s.open&&null===s.source)return;let e=s.source;n+=1,i=!1,m(dk),p(),e&&d.watchDetail({source:e,taskId:null}).catch(()=>void 0)},g=e=>{if(c||!s.open||!i||!dj(s.source,e.source)||s.selectedTaskId!==e.taskId)return;let t=s.details[e.taskId];if(t)try{let n=function(e,t){var s,n;if("snapshot"===t.type)return dv(e,t.snapshot);if("unavailable"===t.type)return null;if("text_append"===t.type){if(e.body?.kind!=="text")throw Error("Text append requires a text task detail snapshot");return{...e,body:{...e.body,text:e.body.text+t.text}}}if(e.body?.kind!=="conversation")throw Error("Conversation event requires a conversation task detail snapshot");return{...e,body:{...(s=e.body,"durable_append"===(n=t.event).type?function(e,t){let s=e.messages.length;if(t.messages[0]?.location.index!==s)throw Error(`Conversation append index is not continuous: expected ${s}, received ${t.messages[0]?.location.index}`);let n=new Set(e.messages.map(e=>e.location.entryId));for(let e of t.messages){if(n.has(e.location.entryId))throw Error(`Conversation append entryId already exists: ${e.location.entryId}`);n.add(e.location.entryId)}return{...e,messages:[...e.messages,...t.messages]}}(s,n):dx(s,n)),kind:"conversation",truncated:e.body.truncated}}}(t,e.event);if(!n){let t={...s.details};delete t[e.taskId],p(e.taskId),m({...s,details:t,loading:!1,refreshing:!1,error:dy("detailUnavailable")});return}let r="text_append"===e.event.type||"conversation_event"===e.event.type&&"message_update"===e.event.event.type;m({...s,details:{...s.details,[e.taskId]:n},loading:!1,refreshing:!1,error:null},r)}catch(t){i=!1,l(t),f(e.taskId)}},f=async e=>{if(c||!s.open||!s.source)return;let t=e.trim();if(!t)return;let a=s.source,l=++n,o=r,u=s.details[t];i=!1,m({...s,selectedTaskId:t,loading:void 0===u,refreshing:void 0!==u,error:null});try{let e=await d.watchDetail({source:a,taskId:t});if(c||l!==n||o!==r||!s.open||!dj(s.source,a)||s.selectedTaskId!==t)return;if(!e.snapshot)throw Error(dy("detailResponseMissing"));let p=lk.parse(e.snapshot),h=u?dv(u,p):p;m({...s,details:{...s.details,[t]:h},loading:!1,refreshing:!1,error:null}),i=!0}catch(e){if(l!==n||!s.open||s.selectedTaskId!==t)return;m({...s,loading:!1,refreshing:!1,error:e instanceof Error?e.message:dy("detailLoadFailed")})}},{start(e){l=e,a||(c=!1,a=d.subscribeDetailEvents(g))},subscribe:t=>(e.add(t),()=>e.delete(t)),getState:()=>s,open(e,t){let r=ll.R.parse(e);s.open&&dj(s.source,r)||(n+=1,i=!1,p(),m({...dk,open:!0,source:r})),t&&f(t)},close:h,selectTask(e){f(e)},reconcileWorkSessions(e){if(!s.open||!s.source)return;let t=e.find(e=>e.workId===s.source?.workId);t&&t.sessionId===s.source.sessionId&&t.branchId===s.source.branchId||h()},reconcileTasks(e,t){let r=ll.R.parse(e);if(!s.open||!dj(s.source,r))return;let a=new Set(t.map(e=>e.taskId)),l={...s.details},o=!1;for(let e of Object.keys(l))a.has(e)||(delete l[e],p(e),o=!0);if(s.selectedTaskId&&!a.has(s.selectedTaskId)){n+=1,i=!1,m({...s,selectedTaskId:null,details:l,loading:!1,refreshing:!1,error:null});return}o&&m({...s,details:l})},async interruptSelected(){s.open&&s.source&&s.selectedTaskId&&await d.interrupt({source:s.source,taskId:s.selectedTaskId})},async loadMessageDetail(e){let t=s.source,n=s.selectedTaskId;if(!s.open||!t||!n||!e.durable)return null;let r=s.details[n];if(!r||r.body?.kind!=="conversation")return null;if(void 0!==e.detail)return e.detail;if(!e.snapshot.fixed.hasDetail)return null;let i=await d.getMessageDetail({source:t,taskId:n,entryId:e.durable.location.entryId}),a=s.details[n];return a&&m({...s,details:{...s.details,[n]:function(e,t){if(e.body?.kind!=="conversation")throw Error("Task message detail requires a conversation snapshot");return lk.parse({...e,body:{kind:"conversation",truncated:e.body.truncated,...db(e.body,t)}})}(a,i)}}),i.detail},async acquireImage(e,n){let r=s.source,i=s.selectedTaskId,a=e.durable?.location.entryId;if(!s.open||!r||!i||!a)throw Error(dy("imageDurableOnly"));let l=JSON.stringify([r.workId,r.sessionId,r.branchId,i,a,n]),o=t.get(l);if(o)return{url:o.url,release:()=>void 0};let c=await d.getImage({source:r,taskId:i,entryId:a,imageIndex:n});if(!s.open||!dj(s.source,r))throw Error(dy("centerClosed"));let u=t.get(l);if(u)return{url:u.url,release:()=>void 0};let m=URL.createObjectURL((0,dw.E)(c));return t.set(l,{taskId:i,url:m}),{url:m,release:()=>void 0}},disconnected(){r+=1,i=!1,s.open&&m({...s,loading:null!==s.selectedTaskId&&void 0===s.details[s.selectedTaskId],refreshing:null!==s.selectedTaskId&&void 0!==s.details[s.selectedTaskId]})},reconnected(){s.open&&s.selectedTaskId&&f(s.selectedTaskId)},dispose(){if(c)return;c=!0;let t=s.source;n+=1,r+=1,i=!1,a?.(),a=null,p(),t&&d.watchDetail({source:t,taskId:null}).catch(()=>void 0),s=dk,o&&clearTimeout(o),o=null,e.clear(),l=()=>void 0}}},[d]),m=(0,r.useCallback)(e=>(0,n.jsx)(dl,{...e,runtime:u,variant:"summary"}),[u]),p=(0,r.useCallback)(e=>(0,n.jsx)(dl,{...e,runtime:u,variant:"menu"}),[u]),h=(0,r.useCallback)(e=>(0,n.jsx)(aq,{open:e.open,connectionReady:e.connectionReady,initialModelTab:"model-presets"===e.initialPage?"presets":void 0,workSessions:e.workSessions,focusedCwd:e.focusedCwd,pluginAttention:e.pluginAttention,onOpenChange:e.onOpenChange,onBeforeReload:e.onBeforeReload,renderPluginSettingsPage:gg,renderMcpSettings:({onBeforeLeaveChange:t})=>(0,n.jsx)(la,{projects:e.workSessions,focusedCwd:e.focusedCwd,onBeforeLeaveChange:t}),renderCapabilityModesSettings:({onBeforeLeaveChange:t})=>(0,n.jsx)(eS,{modeNames:e.capabilityModes,onBeforeLeaveChange:t}),renderPluginManagement:()=>(0,n.jsx)(st,{basicMode:e.basicMode,snapshot:e.pluginManagementSnapshot,biz:c,onSnapshot:e.onPluginManagementSnapshot,onRestartScheduled:e.onPluginRestartScheduled})},`${e.open}:${e.initialPage??"default"}`),[c]);return(0,n.jsx)(gc,{onTerminalReady:l.connected,onTerminalDisconnected:l.disconnected,onOpenTerminal:l.open,onOpenProjectPreviewWindow:e=>{window.open((0,i.F)(e),"_blank","noopener,noreferrer")},renderTerminalWorkspace:o,listPluginManagement:c.list,subscribePluginManagementChanges:c.subscribeChanges,onTaskCenterStart:u.start,onTaskCenterDispose:u.dispose,onTaskCenterReconcileWorkSessions:u.reconcileWorkSessions,onTaskCenterDisconnected:u.disconnected,onTaskCenterReconnected:u.reconnected,renderPluginApplication:gd,renderPluginSessionSidebarTab:gu,renderPluginComposerPanel:gm,renderPluginWidgets:gp,renderPluginSessionHeader:gh,renderSettings:h,renderTaskSummary:m,renderTaskMenu:p})}},20314:e=>{e.exports={sidebarAction:"l2-work-session-sidebar_sidebarAction__9dyyW",rowMetadata:"l2-work-session-sidebar_rowMetadata__5pI6i",sessionRow:"l2-work-session-sidebar_sessionRow__gNO1s",runningBorder:"l2-work-session-sidebar_runningBorder__E7unr",rowActions:"l2-work-session-sidebar_rowActions__ioeUA",desktopRow:"l2-work-session-sidebar_desktopRow__RI8_L",rowTitle:"l2-work-session-sidebar_rowTitle__2iXeS"}},26357:(e,t,s)=>{"use strict";s.d(t,{$:()=>n});let n=s(38979).k5(["off","minimal","low","medium","high","xhigh","max"])},33941:(e,t,s)=>{"use strict";s.d(t,{G6:()=>l,Kc:()=>d,W:()=>r,Xm:()=>a,mj:()=>i,uZ:()=>c});var n=s(38979);let r=n.Ik({password:n.Yj().min(1).max(64)}).strict(),i=n.Ik({}).strict();n.Ik({}).strict();let a=n.Ik({}).strict();n.Ik({}).strict();let l=n.Ik({enabled:n.zM(),configPath:n.Yj()}).strict(),o=n.Yj().min(12).max(64).refine(e=>e===e.trim()&&!/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(e)).refine(e=>[/[A-Z]/,/[a-z]/,/[0-9]/,/[\p{P}\p{S}]/u].filter(t=>t.test(e)).length>=3),c=n.KC([r.extend({password:o}),n.Ik({password:n.ch()}).strict()]),d=n.Ik({}).strict()},37975:(e,t,s)=>{"use strict";s.d(t,{D:()=>a,Yj:()=>l,s6:()=>r});var n=s(38979);let r="project-preview",i=n.Ik({directories:n.YO(n.Yj().min(1).max(4096)).max(32),defaultDirectory:n.Yj().min(1).max(4096).nullable()}).strict();function a(e){let t=i.safeParse(e);return t.success?t.data:{directories:[],defaultDirectory:null}}function l(e){let t=e.replaceAll("\\","/").replace(/\/+$/,"")||"/";return/^[a-z]:/i.test(t)||t.startsWith("//")?t.toLowerCase():t}},42515:(e,t,s)=>{"use strict";s.d(t,{OY:()=>u});var n=s(38979),r=s(267),i=s(9626);let a=n.Yj().trim().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),l=n.g1(n.Yj(),n.Pq()),o=n.Ik({pluginName:a,method:a,scope:n.eu("global"),input:l}).strict(),c=n.Ik({pluginName:a,method:a,scope:n.eu("session"),source:r.R,input:l}).strict(),d=n.gM("scope",[o,c]),u=Object.freeze({invoke:(0,i.Vc)({path:"plugins/invoke",inputSchema:d,outputSchema:l})})},42655:(e,t,s)=>{"use strict";s.d(t,{V:()=>a});var n=s(7962),r=s(50153);let i={src:"/_next/static/media/l4-brand-icon.d4f68daf.svg",height:348,width:464,blurWidth:0,blurHeight:0};function a({size:e=40,className:t}){return(0,n.jsx)(r.default,{src:i,width:e,height:3*e/4,alt:"",className:t})}},43769:e=>{e.exports={userText:"l3-conversation-messages_userText__oC8vv",userTextCollapsed:"l3-conversation-messages_userTextCollapsed__EjqBN",detailText:"l3-conversation-messages_detailText__JzS9c",toolOutput:"l3-conversation-messages_toolOutput__qydfS",toolCode:"l3-conversation-messages_toolCode__m6mgv",toolCodeLine:"l3-conversation-messages_toolCodeLine__gVs5q",toolFilePath:"l3-conversation-messages_toolFilePath__br6R2",toolFileDirectory:"l3-conversation-messages_toolFileDirectory__8BdId",usageToolbar:"l3-conversation-messages_usageToolbar__LDQnR",messageCopyAction:"l3-conversation-messages_messageCopyAction__xfZe0",copyableMessage:"l3-conversation-messages_copyableMessage__lrg9E",usageLabeled:"l3-conversation-messages_usageLabeled__BWv7V",usageCompact:"l3-conversation-messages_usageCompact__0ukdy"}},46117:e=>{e.exports={sessionPanelGroup:"l2-workbench-motion_sessionPanelGroup__83WwS",panelGroup:"l2-workbench-motion_panelGroup__yxZEK",drawer:"l2-workbench-motion_drawer____5mR",backdrop:"l2-workbench-motion_backdrop__F0q19",columnContent:"l2-workbench-motion_columnContent__1RfUq"}},46376:e=>{e.exports={markdown:"l3-conversation-markdown_markdown__KmlPt",imageTrigger:"l3-conversation-markdown_imageTrigger__0YMnp",image:"l3-conversation-markdown_image__0h0S8",imageAction:"l3-conversation-markdown_imageAction__mBi4a",imageFallback:"l3-conversation-markdown_imageFallback__F30Mz"}},49230:(e,t,s)=>{"use strict";s.d(t,{L1AppRuntimeProvider:()=>eg});var n=s(7962),r=s(69266),i=s(48708),a=s(5011),l=s(42515),o=s(91399),c=s(38979),d=s(9626),u=s(99739);c.Yj().min(32).max(128).regex(/^[A-Za-z0-9_-]+$/);let m="/api/plugins/host-runtime/v1";Object.freeze({imports:Object.freeze({react:`${m}/base.js`,"react/jsx-runtime":`${m}/base.js`,"react/jsx-dev-runtime":`${m}/base.js`,"react-dom":`${m}/base.js`,"react-dom/client":`${m}/base.js`,"@jetcrab/pi-desk-sdk/react/base":`${m}/base.js`,"@jetcrab/pi-desk-sdk/react/markdown":`${m}/markdown.js`})}),c.eu("v1");let p=c.Ik({pluginName:u.tv,url:c.Yj().regex(/^\/api\/plugins\/browser-resources\/[A-Za-z0-9_-]{32,128}\/entry\.js$/,"Browser Entry URL 无效")}).strict(),h=c.Ik({}).strict(),g=c.Ik({entries:c.YO(p)}).strict(),f=Object.freeze({list:(0,d.Vc)({path:"plugins/browser-entries/list",inputSchema:h,outputSchema:g})}),x=c.Yj().trim().min(1).max(32768),b=c.Ik({text:c.Yj(),truncated:c.zM()}).strict(),v=c.KC([c.Ik({type:c.eu("text_append"),text:c.Yj().min(1)}).strict(),c.Ik({type:c.eu("snapshot"),snapshot:b}).strict(),c.Ik({type:c.eu("unavailable")}).strict()]),w=c.Ik({pluginName:u.tv,path:x}).strict(),y=c.Ik({snapshot:b}).strict(),k=c.Ik({}).strict(),j=c.Ik({pluginName:u.tv,path:x,event:v}).strict(),N=Object.freeze({watch:(0,d.Vc)({path:"plugins/logs/watch",inputSchema:w,outputSchema:y}),unwatch:(0,d.Vc)({path:"plugins/logs/unwatch",inputSchema:w,outputSchema:k}),event:(0,d._G)({path:"plugins/logs/event",bodySchema:j})});var I=s(95826),S=s(267);let C=c.gM("scope",[c.Ik({scope:c.eu("global")}).strict(),c.Ik({scope:c.eu("session"),source:S.R}).strict()]),E=c.Ik({pluginName:u.tv,target:C,event:u.f7,data:u.Dz}).strict(),M=(0,d._G)({path:"plugins/push",bodySchema:E});var z=s(79137),A=s(67765),$=s(74052);function R(e,t,s){let n=e=>{console.error("[Pi Desk][PluginHost] 插件回调执行失败",{pluginName:s,phase:t,message:e instanceof Error?e.message:String(e)})};try{let t=e();"object"==typeof t&&null!==t&&"then"in t&&"function"==typeof t.then&&Promise.resolve(t).catch(n)}catch(e){n(e)}}async function P(e,t,s){let n,r=Promise.resolve().then(s).catch(s=>{console.error("[Pi Desk][PluginHost] 插件资源清理失败",{pluginName:e,phase:t,message:s instanceof Error?s.message:String(s)})});try{await Promise.race([r,new Promise(s=>{n=setTimeout(()=>{console.warn("[Pi Desk][PluginHost] 插件资源清理超时",{pluginName:e,phase:t,timeoutMs:1500}),s()},1500)})])}finally{void 0!==n&&clearTimeout(n)}}let D={text:"",truncated:!1,loading:!0,error:null};function T(e,t){if(t.text!==e.snapshot.text||t.truncated!==e.snapshot.truncated||t.loading!==e.snapshot.loading||t.error!==e.snapshot.error){e.snapshot=t;for(let t of[...e.listeners])R(t,`log:${e.path}`)}}class O{constructor(e,t){this.channel=e,this.connection=t,this.records=new Map,this.connectionEpoch=0,this.disposed=!1,this.unsubscribeEvents=e.subscribe(e=>this.handleEvent(e)),this.unsubscribeConnection=t.subscribe(()=>this.handleConnectionChange())}open(e){if(this.disposed)throw Error("Plugin log host has been disposed");let t=e.trim();if(!t)throw Error("日志路径不能为空");let s=this.records.get(t);s||(s={path:t,references:0,observed:!1,blockedByError:!1,refreshRequested:!1,syncRequested:!1,syncPromise:null,snapshot:{...D},listeners:new Set},this.records.set(t,s)),s.references+=1,this.requestSync(s);let n=!0;return{getSnapshot:()=>s.snapshot,subscribe:e=>{if(!n)throw Error("Plugin log handle has been disposed");return s.listeners.add(e),()=>{s.listeners.delete(e)}},retry:()=>{n&&!this.disposed&&(s.blockedByError=!1,s.refreshRequested=!0,T(s,{...s.snapshot,loading:!0,error:null}),this.requestSync(s))},dispose:()=>{n&&(n=!1,s.references-=1,this.requestSync(s))}}}dispose(){if(!this.disposed){for(let e of(this.disposed=!0,this.unsubscribeEvents(),this.unsubscribeConnection(),this.records.values()))e.observed&&"ready"===this.connection.getSnapshot().status&&this.channel.unwatch(e.path).catch(()=>void 0),e.listeners.clear();this.records.clear()}}handleConnectionChange(){if(this.disposed)return;this.connectionEpoch+=1;let e="ready"===this.connection.getSnapshot().status;for(let t of this.records.values())t.observed=!1,t.blockedByError=!1,t.refreshRequested=e,t.references>0&&T(t,{...t.snapshot,loading:!0,error:e?null:t.snapshot.error}),this.requestSync(t)}handleEvent(e){if(this.disposed)return;let t=this.records.get(e.path);if(t&&0!==t.references){if("text_append"===e.event.type)return void T(t,{...t.snapshot,text:t.snapshot.text+e.event.text,loading:!1,error:null});if("snapshot"===e.event.type)return void T(t,{...e.event.snapshot,loading:!1,error:null});t.observed=!1,t.blockedByError=!0,T(t,{...t.snapshot,loading:!1,error:"日志暂不可用"})}}requestSync(e){this.disposed||(e.syncRequested=!0,e.syncPromise||(e.syncPromise=(async()=>{for(;e.syncRequested&&!this.disposed;)e.syncRequested=!1,await this.reconcileRecord(e)})().finally(()=>{e.syncPromise=null,e.syncRequested&&!this.disposed&&this.requestSync(e)})))}async reconcileRecord(e){if(this.records.get(e.path)!==e)return;let t="ready"===this.connection.getSnapshot().status;if(!(e.references>0&&t&&!e.blockedByError)){if(e.observed&&t){let t=this.connectionEpoch;try{await this.channel.unwatch(e.path)}catch{}t===this.connectionEpoch&&(e.observed=!1)}else e.observed=!1;0!==e.references||e.observed||this.records.delete(e.path);return}if(e.observed&&!e.refreshRequested)return;e.refreshRequested=!1,T(e,{...e.snapshot,loading:!0,error:null});let s=this.connectionEpoch;try{let t=await this.channel.watch(e.path);if(this.disposed||s!==this.connectionEpoch||this.records.get(e.path)!==e)return;e.observed=!0,e.blockedByError=!1,T(e,{...t,loading:!1,error:null})}catch(t){if(s!==this.connectionEpoch||"ready"!==this.connection.getSnapshot().status){e.syncRequested=!0;return}e.observed=!1,e.blockedByError=!0,T(e,{...e.snapshot,loading:!1,error:t instanceof Error&&t.message?t.message:"读取日志失败"})}finally{(0===e.references||e.syncRequested)&&(e.syncRequested=!0)}}}function L(e){if(null!==e&&"object"==typeof e){for(let t of Object.values(e))L(t);Object.freeze(e)}return e}let F=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,B=/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/,q=new Set(["plugin","server","rocket","settings","panel","message","terminal","file","folder","bot","wrench","database","globe"]),_=new Set(["application","composer-panel","settings-page","message-view","session-sidebar-tab"]);function W(e,t){return`${e}\u0000${t}`}function Y(e,t,s){return`${e}\u0000${W(t,s)}`}function V(e,t,s,n){let r=Y(e,t,s);if("session-header-item"!==t)return r;if("inline"!==n&&"overflow"!==n)throw Error("会话标题视图必须指定 inline 或 overflow");return`${r}\u0000${n}`}function U(e){return import(e)}function H(){return"u"<typeof document?{mode:"light"}:((0,$.Is)(),Object.freeze({mode:document.documentElement.classList.contains("dark")?"dark":"light"}))}function K(e,t){return e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}function G(e){return{source:{workId:e.workId,sessionId:e.sessionId,branchId:e.branchId},cwd:e.cwd,status:e.status}}function J(e,t){let s=e.trim();if(!s||s.length>100)throw Error(`${t} must contain 1-100 characters`);return s}function Q(e){if("string"!=typeof e)throw Error("Contribution name 必须是字符串");let t=e.trim();if(!t||t.length>64||!F.test(t))throw Error("Contribution name 必须是 1-64 字符的小写 kebab-case");return t}function X(e){if(void 0!==e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Contribution icon 无效");if("builtin"===e.type){if(2!==Object.keys(e).length||"string"!=typeof e.name||!q.has(e.name))throw Error("Contribution builtin icon 无效");return{type:"builtin",name:e.name}}if("svg"===e.type){let t="string"==typeof e.content?e.content.trim():"";if(2!==Object.keys(e).length||!t||t.length>16384)throw Error("Contribution SVG icon 无效");return{type:"svg",content:t}}throw Error("Contribution icon type 无效")}}function Z(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`会话标题 ${t} 必须提供 action 或 custom 定义`);let s="action"===e.type?["type","icon","label","onSelect"]:"inline"===t?["type","load","minWidthRem"]:["type","load"];for(let n of Object.keys(e))if(!s.includes(n))throw Error(`会话标题 ${t} ${String(e.type)} 不支持字段 ${n}`);if("action"===e.type){if("string"!=typeof e.label)throw Error("会话标题 action label 必须是字符串");let t=X(e.icon);if(!t)throw Error("会话标题 action 必须提供 icon");if("function"!=typeof e.onSelect)throw Error("会话标题 action 必须提供 onSelect()");return{type:"action",label:J(e.label,"Session Header action label"),icon:t,onSelect:e.onSelect}}if("custom"!==e.type)throw Error("会话标题表现 type 必须是 action 或 custom");if("function"!=typeof e.load)throw Error("会话标题 custom 必须提供 load()");if("inline"===t&&("number"!=typeof e.minWidthRem||!Number.isFinite(e.minWidthRem)||e.minWidthRem<=0))throw Error("会话标题 inline custom minWidthRem 必须是正数");return{type:"custom",load:e.load,..."inline"===t?{minWidthRem:e.minWidthRem}:{}}}class ee{constructor(e,t=U,s=()=>void 0){this.transport=e,this.entryImporter=t,this.notifyPlugin=s,this.entryDescriptors=[],this.entryDescriptorsByPlugin=new Map,this.entryStates=new Map,this.ownersByPlugin=new Map,this.registrations=new Map,this.contributionLoadStates=new Map,this.browserDescriptors=[],this.registrySnapshot={revision:0,descriptors:this.browserDescriptors},this.messageViewResolutions=new Map,this.logHosts=new Map,this.registryListeners=new Set,this.workSessionListeners=new Set,this.connectionListeners=new Set,this.themeListeners=new Set,this.globalPluginStates={},this.workSessions=[],this.workSessionCreate=null,this.workSessionGoTo=null,this.projectPreview=null,this.terminalOpen=null,this.workSessionFilePreview=null,this.workSessionFileReveal=null,this.imageReader=null,this.connectionSnapshot={status:"disconnected",error:null},this.themeSnapshot={mode:"light"},this.refreshPromise=null,this.refreshPending=!1,this.entriesMaintaining=!1,this.entriesInitialized=!1,this.entryListError=null,this.applicationResolveController=null,this.applicationResolveEpoch=0,this.applicationVisibility=new Map,this.disposed=!1,this.unsubscribePush=e.subscribePush(e=>this.dispatchPush(e));const n=()=>{let e=H();e.mode!==this.themeSnapshot.mode&&(this.themeSnapshot=e,this.notify(this.themeListeners))};this.themeSnapshot=H(),this.unsubscribeTheme=(0,$.Cy)(n);const r=window.matchMedia("(prefers-color-scheme: dark)");r.addEventListener("change",n),this.removeSystemThemeListener=()=>r.removeEventListener("change",n)}subscribeRegistry(e){return this.registryListeners.add(e),()=>this.registryListeners.delete(e)}getBrowserDescriptors(){return this.browserDescriptors}getRegisteredBrowserDescriptors(){return[...this.ownersByPlugin.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({pluginName:e,contributions:[...t.registrations.values()].sort((e,t)=>{let s=e.kind.localeCompare(t.kind);return 0===s?e.contributionName.localeCompare(t.contributionName):s}).map(e=>structuredClone(e.descriptor))}))}getRegistrySnapshot(){return this.registrySnapshot}areEntriesInitialized(){return this.entriesInitialized}isRefreshingEntries(){return this.entriesMaintaining||null!==this.refreshPromise}setEntriesMaintaining(e){this.disposed||this.entriesMaintaining===e||(this.entriesMaintaining=e,this.publishRegistryChange())}getEntryListError(){return this.entryListError}getEntryState(e){return this.entryStates.get(e)??{status:"unloaded"}}getFailedEntries(){return[...this.entryStates.entries()].flatMap(([e,t])=>"failed"===t.status?[{pluginName:e,error:t.error}]:[])}getContributionLoadState(e,t,s,n){return this.contributionLoadStates.get(V(e,t,s,n))??{status:"unloaded"}}getMessageViewResolution(e){return this.messageViewResolutions.get(e)??null}bindWorkSessionCreate(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(this.workSessionCreate)throw Error("Workbench WorkSession 创建能力已经绑定");this.workSessionCreate=e;let t=!0;return()=>{t&&(t=!1,this.workSessionCreate===e&&(this.workSessionCreate=null))}}bindWorkSessionGoTo(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(this.workSessionGoTo)throw Error("Workbench WorkSession 前往能力已经绑定");this.workSessionGoTo=e;let t=!0;return()=>{t&&(t=!1,this.workSessionGoTo===e&&(this.workSessionGoTo=null))}}bindTerminalOpen(e){if(this.disposed)throw Error("Plugin Host Runtime 已释放");if(this.terminalOpen)throw Error("终端创建能力已经绑定");return this.terminalOpen=e,()=>{this.terminalOpen===e&&(this.terminalOpen=null)}}bindProjectPreview(e){if(this.disposed)throw Error("Plugin Host Runtime 已释放");if(this.projectPreview)throw Error("项目预览能力已经绑定");return this.projectPreview=e,()=>{this.projectPreview===e&&(this.projectPreview=null)}}previewProject(e){if(this.disposed)throw Error("Plugin Host Runtime 已释放");if("string"!=typeof e||!e.trim())throw Error("项目预览需要有效目录");if(!this.projectPreview)throw Error("项目预览尚未准备好");this.projectPreview(e.trim())}bindWorkSessionFilePreview(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(this.workSessionFilePreview)throw Error("Workbench 文件预览能力已经绑定");this.workSessionFilePreview=e;let t=!0;return()=>{t&&(t=!1,this.workSessionFilePreview===e&&(this.workSessionFilePreview=null))}}bindImageReader(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(this.imageReader)throw Error("Workbench 图片读取能力已经绑定");return this.imageReader=e,()=>{this.imageReader===e&&(this.imageReader=null)}}bindWorkSessionFileReveal(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(this.workSessionFileReveal)throw Error("Workbench 文件定位能力已经绑定");this.workSessionFileReveal=e;let t=!0;return()=>{t&&(t=!1,this.workSessionFileReveal===e&&(this.workSessionFileReveal=null))}}replaceGlobalPluginStates(e){let t=L(structuredClone(e)),s=[...new Set([...Object.keys(this.globalPluginStates),...Object.keys(t)])].filter(e=>JSON.stringify(this.globalPluginStates[e]??null)!==JSON.stringify(t[e]??null));if(0!==s.length){for(let e of(this.globalPluginStates=t,s)){let t=this.ownersByPlugin.get(e);t&&this.notify(t.globalStateListeners)}this.entriesInitialized&&s.some(e=>[...this.ownersByPlugin.get(e)?.registrations.values()??[]].some(e=>"application"===e.kind&&e.resolve))&&this.scheduleApplicationResolution()}}async dispatchNotificationEvent(e,t){let s=this.entryStates.get(t.pluginName);if(s?.status!=="ready")throw Error(`插件 Browser Entry 尚未就绪:${t.pluginName}`);let n=s.runtime.owner,r=n.notificationEventListeners.get(t.name);if(!r)throw Error(`插件未注册通知事件:${t.pluginName}/${t.name}`);if(await r({notificationId:e,data:structuredClone(t.data)}),!n.active)throw Error("Browser Entry 已失效")}replaceWorkSessions(e){var t;let s=L(e.map(G));t=this.workSessions,!(t.length===s.length&&t.every((e,t)=>void 0!==s[t]&&K(e.source,s[t].source)&&e.cwd===s[t].cwd&&e.status===s[t].status))&&(this.workSessions=s,this.notify(this.workSessionListeners),this.entriesInitialized&&this.scheduleApplicationResolution())}markConnecting(){this.replaceConnection({status:"connecting",error:null})}markReady(){this.replaceConnection({status:"ready",error:null})}markDisconnected(e=null){this.setEntriesMaintaining(!1),this.replaceConnection({status:"disconnected",error:e})}async refreshEntries(){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");return this.refreshPromise?this.refreshPending=!0:(this.entriesInitialized||this.replaceEntriesInitialized(!1),this.refreshPromise=(async()=>{try{do{this.refreshPending=!1;let e=await this.transport.listBrowserEntries();if(this.disposed||this.entriesMaintaining||(await this.replaceEntries(e),this.disposed))return;this.replaceEntriesInitialized(!0),this.replaceEntryListError(null)}while(this.refreshPending&&!this.disposed)}catch(e){throw this.replaceEntriesInitialized(!0),this.replaceEntryListError(e instanceof Error?e.message:String(e)),this.rebuildRegistry(),e}})().finally(()=>{this.refreshPromise=null,this.disposed||this.publishRegistryChange()}),this.publishRegistryChange()),this.refreshPromise}retryEntry(e){return this.entryStates.get(e)?.status==="failed"&&(this.entryStates.delete(e),this.publishRegistryChange()),this.loadEntry(e).then(async e=>(await this.resolveApplications(),e))}retryContribution(e,t,s,n){let r=Y(e,t,s),i=V(e,t,s,n);this.contributionLoadStates.get(i)?.status==="failed"&&(this.contributionLoadStates.delete(i),this.publishRegistryChange());let a=this.registrations.get(r);return a?this.loadContribution(a,n):Promise.reject(new z.qj({pluginName:e,contributionName:s,phase:"registration",message:"插件 Contribution 不存在"}))}async invokeSessionHeaderAction(e){let t=Y(e.pluginName,"session-header-item",e.contributionName),s=this.registrations.get(t),n=s?.header?.[e.presentation];if(!s||n?.type!=="action")throw Error("会话标题 action 不存在");if(e.signal.throwIfAborted(),!s.owner.active)throw Error("Browser Entry 已失效");if(!this.workSessions.some(t=>K(t.source,e.source)))throw Error("工作会话来源已变化");let r=this.getHeaderActionScope(s,e.source,e.signal);try{if(await n.onSelect({...r}),r.signal.throwIfAborted(),!s.owner.active||this.registrations.get(t)!==s)throw Error("Browser Entry 已失效")}catch(s){let t=new z.qj({pluginName:e.pluginName,contributionName:e.contributionName,phase:"session-header-action",message:s instanceof Error?s.message:String(s),cause:s});throw r.signal.aborted||R(()=>{throw t},`header-action:${e.contributionName}:${e.presentation}`,e.pluginName),t}}getHeaderActionScope(e,t,s){let n=e.headerActionScopes??=new WeakMap,r=n.get(s);if(r){if(!K(r.source,t))throw Error("会话标题展示来源不一致");return r}let i=e.owner,a=L(structuredClone(t)),l=new AbortController,o={...i,subscriptionDisposers:new Set,get active(){return i.active&&!l.signal.aborted}},c=()=>{for(let t of(l.abort(),n.delete(s),this.workSessionListeners.delete(d),i.subscriptionDisposers.delete(c),s.removeEventListener("abort",c),o.subscriptionDisposers))R(t,"header-action-dispose",e.pluginName);o.subscriptionDisposers.clear()},d=()=>{this.workSessions.some(e=>K(e.source,a))||c()},u={source:a,host:this.createBrowserHost(o),signal:l.signal};return n.set(s,u),this.workSessionListeners.add(d),i.subscriptionDisposers.add(c),s.addEventListener("abort",c,{once:!0}),u}async mountContribution(e){let t=Y(e.pluginName,e.kind,e.contributionName),s=this.registrations.get(t);if(!s)throw new z.qj({pluginName:e.pluginName,contributionName:e.contributionName,phase:"registration",message:"插件 Contribution 不存在"});if(s.kind!==e.target.kind)throw Error("Contribution kind 与 mount target 不一致");let n=new AbortController,r=new Promise(e=>{n.signal.addEventListener("abort",()=>e(),{once:!0})}),i=e.target;("widget"===i.kind||"session-header-item"===i.kind)&&(i={...i,source:L(structuredClone(i.source))});let a="widget"===i.kind||"session-header-item"===i.kind?i.source:null,l="session-header-item"===i.kind?i.presentation:void 0,o=()=>{a&&!this.workSessions.some(e=>K(e.source,a))&&m()};if("session-sidebar-tab"===i.kind&&i.setHeaderActions){let t=i.setHeaderActions,r=[];n.signal.addEventListener("abort",()=>{r=[],t([])},{once:!0}),i={...i,setHeaderActions:i=>{if(n.signal.aborted||!s.owner.active)return;if(!Array.isArray(i))throw Error("侧栏操作必须为数组");let a=i.map(t=>{let i=J(t.label,"Sidebar action label"),l=X(t.icon),o=!0===t.disabled,c=!0===t.busy,d=t.onSelect;if("function"!=typeof d)throw Error("侧栏操作缺少 onSelect 回调");let u=!1;return{label:i,icon:l,disabled:o,busy:c,onSelect:()=>{n.signal.aborted||!s.owner.active||r!==a||o||c||u||(u=!0,R(async()=>{try{await d()}catch(e){throw!n.signal.aborted&&s.owner.active&&s.owner.host.notify({level:"error",title:i,description:e instanceof Error?e.message:String(e)}),e}finally{u=!1}},`sidebar-action:${i}`,e.pluginName))}}});r=a,t(a)}}}let c=Promise.resolve().then(async()=>{if(n.signal.aborted)throw Error("插件视图已关闭");let t=await this.loadContribution(s,l);if(n.signal.aborted||!s.owner.active)throw Error("插件视图已失效");let r=t.mount,a=await r({container:e.container,target:i,host:s.owner.host,signal:n.signal});if(void 0!==a&&"function"!=typeof a)throw Error("Contribution mount must return void or a disposer");return a??null}),d=null,u=()=>d||(s.owner.mounts.delete(u),e.signal?.removeEventListener("abort",m),this.workSessionListeners.delete(o),n.abort(),d=P(e.pluginName,`mount:${e.contributionName}`,async()=>{let e=await c.catch(()=>null);await e?.()})),m=()=>{u()};s.owner.mounts.add(u),a&&this.workSessionListeners.add(o),e.signal?.addEventListener("abort",m,{once:!0}),e.signal?.aborted&&m(),o();try{if(await Promise.race([c,r]),n.signal.aborted||!s.owner.active)throw Error("插件视图已失效");return u}catch(t){if(await u(),t instanceof z.qj)throw t;throw new z.qj({pluginName:e.pluginName,contributionName:e.contributionName,phase:"mount",message:t instanceof Error?t.message:String(t),cause:t})}}async dispose(){if(this.disposed)return;this.disposed=!0,this.applicationResolveController?.abort(),this.applicationResolveController=null,this.unsubscribePush(),this.unsubscribeTheme(),this.removeSystemThemeListener();let e=[...this.ownersByPlugin.values()].reverse();for(let t of(this.ownersByPlugin.clear(),await Promise.all(e.map(e=>this.disposeEntryOwner(e))),this.entriesMaintaining=!1,this.entryStates.clear(),this.entryDescriptorsByPlugin.clear(),this.entryDescriptors=[],this.registrations.clear(),this.contributionLoadStates.clear(),this.browserDescriptors=[],this.messageViewResolutions.clear(),this.applicationVisibility.clear(),this.logHosts.values()))t.dispose();this.logHosts.clear(),this.globalPluginStates={},this.workSessionCreate=null,this.workSessionGoTo=null,this.workSessionFilePreview=null,this.workSessionFileReveal=null,this.imageReader=null,this.projectPreview=null,this.terminalOpen=null,this.registryListeners.clear(),this.workSessionListeners.clear(),this.connectionListeners.clear(),this.themeListeners.clear()}async replaceEntries(e){var t;let s=[...e].sort((e,t)=>e.pluginName.localeCompare(t.pluginName)),n=new Map;for(let e of s){if(n.has(e.pluginName))throw Error(`重复 Plugin Browser Entry:${e.pluginName}`);n.set(e.pluginName,e)}for(let[e,t]of this.entryDescriptorsByPlugin){let s=n.get(e);s?.url!==t.url&&this.disposeEntry(e)}if(this.disposed)return;for(let[e,t]of(this.entryDescriptorsByPlugin.clear(),n))this.entryDescriptorsByPlugin.set(e,t);let r=(t=this.entryDescriptors,JSON.stringify(t)!==JSON.stringify(s));this.entryDescriptors=structuredClone(s),await Promise.allSettled(s.map(e=>this.loadEntry(e.pluginName))),await this.resolveApplications(),r&&this.publishRegistryChange()}loadEntry(e){if(this.disposed)return Promise.reject(Error("Plugin Host Runtime has been disposed"));let t=this.entryDescriptorsByPlugin.get(e);if(!t)return Promise.reject(Error(`Plugin Browser Entry 不存在:${e}`));let s=this.entryStates.get(e);if(s?.status==="ready")return Promise.resolve(s.runtime);if(s?.status==="loading")return s.promise;if(s?.status==="failed")return Promise.reject(s.error);let n=this.initializeEntry(t).then(s=>(this.disposed||this.entryDescriptorsByPlugin.get(e)?.url!==t.url?s.dispose():(this.entryStates.set(e,{status:"ready",runtime:s}),this.ownersByPlugin.set(e,s.owner),this.commitRegistrations(s.owner),this.rebuildRegistry()),this.publishRegistryChange(),s),s=>{let n=s instanceof Error?s:new z.qj({pluginName:e,phase:"entry-import",message:String(s)});throw this.disposed||this.entryDescriptorsByPlugin.get(e)?.url!==t.url||(this.entryStates.set(e,{status:"failed",error:n}),this.rebuildRegistry(),this.publishRegistryChange()),n});return this.entryStates.set(e,{status:"loading",promise:n}),this.publishRegistryChange(),n}async initializeEntry(e){let t;try{t=await this.entryImporter(e.url)}catch(t){throw new z.qj({pluginName:e.pluginName,phase:"entry-import",message:t instanceof Error?t.message:"Browser Entry import 失败",cause:t})}if(this.disposed||this.entryDescriptorsByPlugin.get(e.pluginName)?.url!==e.url)throw Error("Browser Entry 已失效");if("function"!=typeof t.default)throw new z.qj({pluginName:e.pluginName,phase:"entry-factory",message:"Browser Entry 必须 default-export defineBrowserEntry(...)"});let s={descriptor:e,registrations:new Map,pushListeners:new Set,notificationEventListeners:new Map,globalStateListeners:new Set,subscriptionDisposers:new Set,mounts:new Set,disposer:null,registrationOpen:!0,active:!0},n=Object.assign(s,{host:this.createBrowserHost(s)});try{let s=t.default(this.createBrowserFacade(e.pluginName,n));if(n.registrationOpen=!1,"object"==typeof s&&null!==s&&"function"==typeof Reflect.get(s,"then"))throw R(async()=>{let t=await s;"function"==typeof t&&await P(e.pluginName,"entry-factory",async()=>{await t()})},"entry-factory",e.pluginName),Error("Browser Entry factory must register synchronously");if(void 0!==s&&"function"!=typeof s)throw Error("Browser Entry factory must return void or a disposer");n.disposer=s??null}catch(t){throw n.registrationOpen=!1,await this.disposeEntryOwner(n),new z.qj({pluginName:e.pluginName,phase:"entry-factory",message:t instanceof Error?t.message:String(t),cause:t})}return{pluginName:e.pluginName,owner:n,dispose:()=>this.disposeEntryOwner(n)}}createBrowserFacade(e,t){let s=s=>{if(!t.active||!t.registrationOpen)throw Error("Browser Entry registration phase has ended");let n=s(),r=W(n.kind,n.contributionName);if(t.registrations.has(r))throw Error(`Browser Contribution 重复:${e}/${n.kind}/${n.contributionName}`);t.registrations.set(r,n)};return{name:e,host:t.host,notifications:{onEvent:(s,n)=>{if(!t.active)throw Error("Browser Entry owner is no longer active");let r=Q(s);if(t.notificationEventListeners.has(r))throw Error(`Browser Notification Event 重复:${e}/${r}`);return t.notificationEventListeners.set(r,n),()=>{t.notificationEventListeners.get(r)===n&&t.notificationEventListeners.delete(r)}}},notify:s=>{t.active&&this.notifyPlugin(e,structuredClone(s))},registerContribution:(n,r,i)=>{s(()=>{if(!_.has(n))throw Error(`Browser Contribution kind 无效:${String(n)}`);return this.createRegistration(e,n,r,i,t)})},registerWidget:(n,r)=>{s(()=>this.createWidgetRegistration(e,n,r,t))},registerSessionHeaderItem:(n,r)=>{s(()=>this.createHeaderRegistration(e,n,r,t))},onPush:e=>{if(!t.active)throw Error("Browser Entry owner is no longer active");return t.pushListeners.add(e),()=>{t.pushListeners.delete(e)}}}}createRegistration(e,t,s,n,r){let i=Q(s);if(!n||"object"!=typeof n||"function"!=typeof n.load)throw Error(`Browser Contribution 必须提供 load():${t}/${i}`);if("application"===t){let s=J(n.label,"Application label"),a=X(n.icon),l=n.chrome??"host";if("host"!==l&&"none"!==l)throw Error("Application chrome 必须是 host 或 none");if(void 0!==n.resolve&&"function"!=typeof n.resolve)throw Error("Application resolve 必须是函数");return{pluginName:e,kind:t,contributionName:i,descriptor:{kind:t,contributionName:i,label:s,title:J(n.title??s,"Application title"),...a?{icon:a}:{},chrome:l},load:n.load,resolve:n.resolve,owner:r}}if("composer-panel"===t){let s=X(n.icon);return{pluginName:e,kind:t,contributionName:i,descriptor:{kind:t,contributionName:i,label:J(n.label,"Composer Panel label"),...s?{icon:s}:{}},load:n.load,owner:r}}if("settings-page"===t){let s=X(n.icon);return{pluginName:e,kind:t,contributionName:i,descriptor:{kind:t,contributionName:i,label:J(n.label,"Settings Page label"),...s?{icon:s}:{}},load:n.load,owner:r}}if("message-view"===t)return{pluginName:e,kind:t,contributionName:i,descriptor:{kind:t,contributionName:i,viewKey:function(e){if("string"!=typeof e)throw Error("Message View viewKey 必须是字符串");let t=e.trim();if(t.length<3||t.length>129||!B.test(t))throw Error("Message View viewKey 必须是 plugin-name/view-name");return t}(n.viewKey),priority:function(e){if(!Number.isSafeInteger(e))throw Error("Message View priority must be a safe integer");return e}(n.priority)},load:n.load,owner:r};let a=X(n.icon);return{pluginName:e,kind:"session-sidebar-tab",contributionName:i,descriptor:{kind:"session-sidebar-tab",contributionName:i,label:J(n.label,"Session Sidebar Tab label"),...a?{icon:a}:{}},load:n.load,owner:r}}createWidgetRegistration(e,t,s,n){let r=Q(t);if(!s||"object"!=typeof s||"function"!=typeof s.load)throw Error("Browser Widget 必须提供 load()");let i=s.placement??"aboveEditor";if("aboveEditor"!==i&&"belowEditor"!==i)throw Error("Browser Widget placement 必须是 aboveEditor 或 belowEditor");return{pluginName:e,kind:"widget",contributionName:r,descriptor:{kind:"widget",contributionName:r,placement:i},load:s.load,owner:n}}createHeaderRegistration(e,t,s,n){let r=Q(t);if(!s||"object"!=typeof s||Array.isArray(s))throw Error("会话标题条目必须提供 inline 和 overflow");for(let e of Object.keys(s))if("inline"!==e&&"overflow"!==e)throw Error(`会话标题条目不支持顶层字段 ${e}`);let i=Z(s.inline,"inline"),a=Z(s.overflow,"overflow");return{pluginName:e,kind:"session-header-item",contributionName:r,descriptor:{kind:"session-header-item",contributionName:r,inline:"action"===i.type?{type:"action",icon:i.icon,label:i.label}:{type:"custom",minWidthRem:i.minWidthRem},overflow:"action"===a.type?{type:"action",icon:a.icon,label:a.label}:{type:"custom"}},header:{inline:i,overflow:a},owner:n}}commitRegistrations(e){for(let t of e.registrations.values()){let e=Y(t.pluginName,t.kind,t.contributionName);if(this.registrations.has(e))throw Error(`Browser Contribution Registry 重复:${e}`);this.registrations.set(e,t)}}loadContribution(e,t){let s=Y(e.pluginName,e.kind,e.contributionName),n=V(e.pluginName,e.kind,e.contributionName,t),r=t?e.header?.[t]:void 0,i=r?.type==="custom"?r.load:e.load;if(!i)return Promise.reject(Error("会话标题 action 不支持加载视图"));if(!e.owner.active||this.registrations.get(s)!==e)return Promise.reject(Error("Browser Contribution 已失效"));let a=this.contributionLoadStates.get(n);if(a?.status==="ready")return Promise.resolve(a.implementation);if(a?.status==="loading")return a.promise;if(a?.status==="failed")return Promise.reject(a.error);let l=Promise.resolve().then(i).then(t=>{if(!t||"function"!=typeof t.mount)throw Error("Lazy Contribution Module 必须导出 mount()");if(!e.owner.active||this.registrations.get(s)!==e)throw Error("Browser Contribution 已失效");return this.contributionLoadStates.set(n,{status:"ready",implementation:t}),this.publishRegistryChange(),t},e=>{throw e}).catch(t=>{let r=t instanceof Error?t:new z.qj({pluginName:e.pluginName,contributionName:e.contributionName,phase:"contribution-load",message:String(t)});throw e.owner.active&&this.registrations.get(s)===e&&(this.contributionLoadStates.set(n,{status:"failed",error:r}),this.publishRegistryChange()),r});return this.contributionLoadStates.set(n,{status:"loading",promise:l}),this.publishRegistryChange(),l}async resolveApplications(){if(this.disposed)return;let e=new AbortController;this.applicationResolveController?.abort(),this.applicationResolveController=e;let t=++this.applicationResolveEpoch,s=[...this.registrations.values()].filter(e=>"application"===e.kind),n=new Map;if(await Promise.all(s.map(async t=>{let s=Y(t.pluginName,t.kind,t.contributionName);if(!t.resolve)return void n.set(s,!0);try{let r=await t.resolve({workSessions:this.workSessions,host:t.owner.host,signal:e.signal});e.signal.aborted||n.set(s,!1!==r)}catch(r){if(e.signal.aborted)return;n.set(s,!1),console.warn("[Pi Desk][PluginHost] Application resolve 失败",{pluginName:t.pluginName,contributionName:t.contributionName,errorName:r instanceof Error?r.name:"UnknownError",message:r instanceof Error?r.message:String(r)})}})),!this.disposed&&!e.signal.aborted&&this.applicationResolveController===e&&this.applicationResolveEpoch===t){for(let[e,t]of(this.applicationVisibility.clear(),n))this.applicationVisibility.set(e,t);this.rebuildRegistry()}}scheduleApplicationResolution(){queueMicrotask(()=>{this.disposed||this.resolveApplications().catch(e=>{console.error("[Pi Desk][PluginHost] 刷新 Application 可见性失败",{errorName:e instanceof Error?e.name:"UnknownError",message:e instanceof Error?e.message:String(e)})})})}rebuildRegistry(){let e=[...this.ownersByPlugin.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({pluginName:e,contributions:[...t.registrations.values()].filter(e=>"application"!==e.kind||(this.applicationVisibility.get(Y(e.pluginName,e.kind,e.contributionName))??!1)).sort((e,t)=>{let s=e.kind.localeCompare(t.kind);return 0===s?e.contributionName.localeCompare(t.contributionName):s}).map(e=>structuredClone(e.descriptor))}));JSON.stringify(this.browserDescriptors)!==JSON.stringify(e)&&(this.browserDescriptors=e,this.rebuildMessageViewResolutions(),this.publishRegistryChange())}rebuildMessageViewResolutions(){this.messageViewResolutions.clear();let e=new Map;for(let t of this.browserDescriptors)for(let s of t.contributions){if("message-view"!==s.kind)continue;let n=e.get(s.viewKey)??[];n.push({pluginName:t.pluginName,descriptor:s}),e.set(s.viewKey,n)}for(let[t,s]of e){let e=Math.max(...s.map(e=>e.descriptor.priority)),n=s.filter(t=>t.descriptor.priority===e);this.messageViewResolutions.set(t,1===n.length?{status:"winner",...n[0]}:{status:"conflict",viewKey:t,candidates:n})}}disposeEntry(e){this.entryDescriptorsByPlugin.delete(e),this.entryStates.delete(e);let t=this.ownersByPlugin.get(e);this.ownersByPlugin.delete(e),t&&this.disposeEntryOwner(t),this.rebuildRegistry()}async disposeEntryOwner(e){if(!e.active)return;for(let t of(e.active=!1,e.registrationOpen=!1,e.pushListeners.clear(),e.notificationEventListeners.clear(),e.globalStateListeners.clear(),e.subscriptionDisposers))R(t,"entry-subscription-dispose",e.descriptor.pluginName);e.subscriptionDisposers.clear();let t=this.logHosts.get(e.descriptor.pluginName);for(let s of(t===e.host.logs&&(this.logHosts.delete(e.descriptor.pluginName),R(()=>t.dispose(),"logs-dispose",e.descriptor.pluginName)),e.registrations.values())){let e=Y(s.pluginName,s.kind,s.contributionName);this.registrations.get(e)===s&&(this.registrations.delete(e),this.contributionLoadStates.delete(e),"session-header-item"===s.kind&&(this.contributionLoadStates.delete(`${e}\u0000inline`),this.contributionLoadStates.delete(`${e}\u0000overflow`)),this.applicationVisibility.delete(e))}let s=[...e.mounts].reverse();e.mounts.clear();let n=e.disposer;e.disposer=null,e.registrations.clear(),await Promise.all(s.map(e=>e())),n&&await P(e.descriptor.pluginName,"entry-dispose",n)}previewWorkSessionFile(e,t,s){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if("string"!=typeof t||!t.trim())throw Error("文件预览需要有效路径");let n=function(e){if(void 0!==e&&(null===e||"object"!=typeof e||Array.isArray(e)))throw Error("文件预览选项无效");let t=e?.mode;if(void 0===t||"session"===t||"expanded"===t||"standalone"===t)return t??"session";throw Error("文件预览模式无效")}(s),r=this.workSessions.find(t=>K(t.source,e));if(!r)throw Error("工作会话来源已变化");let i=this.workSessionFilePreview;if(!i)throw Error("Workbench 尚未准备好预览文件");i({source:structuredClone(r.source),cwd:r.cwd,path:t.trim(),mode:n,...s?.imagePaths===void 0?{}:{imagePaths:s.imagePaths}})}async revealWorkSessionFile(e,t){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if("string"!=typeof t||!t.trim())throw Error("文件定位需要有效路径");let s=this.workSessions.find(t=>K(t.source,e));if(!s)throw Error("工作会话来源已变化");let n=this.workSessionFileReveal;if(!n)throw Error("Workbench 尚未准备好定位文件");await n({source:structuredClone(s.source),cwd:s.cwd,path:t.trim()})}async readImage(e,t,s){s.throwIfAborted();let n=A._g.parse(t),r=this.workSessions.find(t=>K(t.source,e));if(!r)throw Error("工作会话来源已变化");let i=this.imageReader;if(!i)throw Error("Workbench 尚未准备好读取图片");let a=await i({source:structuredClone(r.source),cwd:r.cwd,path:n},s);if(s.throwIfAborted(),!this.workSessions.some(t=>K(t.source,e)))throw Error("工作会话来源已变化");return a}async createWorkSession(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(!e||"string"!=typeof e.cwd||!e.cwd.trim())throw Error("创建工作会话需要有效 cwd");let t=this.workSessionCreate;if(!t)throw Error("Workbench 尚未准备好创建工作会话");return G(await t(e.cwd.trim()))}async goToWorkSession(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if("workId"in e){if("string"!=typeof e.workId||!e.workId.trim())throw Error("前往工作会话需要有效 workId")}else{if("string"!=typeof e.sessionId||!e.sessionId.trim())throw Error("前往工作会话需要有效 sessionId");if(void 0!==e.cwd&&("string"!=typeof e.cwd||!e.cwd.trim()))throw Error("cwd 必须是非空字符串")}let t=this.workSessionGoTo;if(!t)throw Error("Workbench 尚未准备好前往工作会话");return G(await t(e))}createBrowserHost(e){let t=e.descriptor.pluginName,s=()=>{if(!e.active||this.disposed)throw Error("Browser Entry 已失效")},n=async e=>{s();let t=await e();return s(),t},r=this.transport.createPiDeskChannel(t),a=this.transport.pi,l=(n,r,i)=>{s();let a=()=>{e.active&&R(r,i,t)},l=()=>{n.delete(a),e.subscriptionDisposers.delete(l)};return n.add(a),e.subscriptionDisposers.add(l),l},o={getSnapshot:()=>(s(),this.connectionSnapshot),subscribe:e=>l(this.connectionListeners,e,"connection")},c=this.logHosts.get(t);return c||(c=new O(this.transport.createLogChannel(t),{getSnapshot:()=>this.connectionSnapshot,subscribe:o.subscribe}),this.logHosts.set(t,c)),{settings:{getSnapshot:()=>(s(),(0,i.SJ)()),subscribe:n=>{s();let r=(0,i.ae)(()=>{e.active&&R(n,"settings",t)});return e.subscriptionDisposers.add(r),()=>{e.subscriptionDisposers.delete(r),r()}}},notify:e=>{s(),this.notifyPlugin(t,structuredClone(e))},locale:{getSnapshot:()=>(s(),(0,i.SJ)().region)},globalState:{getSnapshot:()=>(s(),this.globalPluginStates[t]??null),subscribe:t=>l(e.globalStateListeners,t,"global-state")},piDesk:{invokeGlobal:(e,t)=>n(()=>r.invokeGlobal(e,t)),invokeSession:(e,t,s)=>n(()=>r.invokeSession(e,t,s))},pi:{prompt:(e,t)=>n(()=>a.prompt(e,t)),commands:{list:e=>n(()=>a.commands.list(e)),execute:(e,t,s)=>n(()=>a.commands.execute(e,t,s))},tools:{list:e=>n(()=>a.tools.list(e))},bash:{execute:(e,t)=>n(()=>a.bash.execute(e,t)),abort:e=>n(()=>a.bash.abort(e))},interrupt:e=>n(()=>a.interrupt(e))},workSessions:{getSnapshot:()=>(s(),this.workSessions),subscribe:e=>l(this.workSessionListeners,e,"work-sessions"),create:e=>n(()=>this.createWorkSession(e)),goTo:e=>n(()=>this.goToWorkSession(e))},workSessionFiles:{preview:(e,t,n)=>{s(),this.previewWorkSessionFile(e,t,n)},reveal:(e,t)=>n(()=>this.revealWorkSessionFile(e,t)),readImage:(t,s,r)=>n(async()=>{let n=new AbortController,i=()=>n.abort();e.subscriptionDisposers.add(i);try{return await this.readImage(t,s,r?AbortSignal.any([r,n.signal]):n.signal)}finally{e.subscriptionDisposers.delete(i)}})},projects:{preview:e=>{s(),this.previewProject(e)}},terminals:{open:t=>n(async()=>{if(!t||"string"!=typeof t.cwd||!t.cwd.trim())throw Error("新建终端需要有效 cwd");let s=this.terminalOpen;if(!s)throw Error("终端创建能力尚未准备好");let n=new AbortController,r=()=>n.abort();e.subscriptionDisposers.add(r);try{await s(t.cwd,n.signal)}finally{e.subscriptionDisposers.delete(r)}})},logs:c,connection:o,theme:{getSnapshot:()=>(s(),this.themeSnapshot),subscribe:e=>l(this.themeListeners,e,"theme")}}}dispatchPush(e){let t=this.entryStates.get(e.pluginName);if(t?.status!=="ready")return;let s=t.runtime.owner;for(let t of[...s.pushListeners]){if(!s.active)break;R(()=>t(e),`push:${e.event}`,e.pluginName)}}replaceEntriesInitialized(e){this.entriesInitialized!==e&&(this.entriesInitialized=e,this.publishRegistryChange())}replaceEntryListError(e){this.entryListError!==e&&(this.entryListError=e,this.publishRegistryChange())}replaceConnection(e){(e.status!==this.connectionSnapshot.status||e.error!==this.connectionSnapshot.error)&&(this.connectionSnapshot=Object.freeze({...e}),this.notify(this.connectionListeners))}publishRegistryChange(){this.registrySnapshot={revision:this.registrySnapshot.revision+1,descriptors:this.browserDescriptors},this.notify(this.registryListeners)}notify(e){for(let t of[...e])R(t,"notify")}}var et=s(78121),es=s(24925),en=s(48155),er=s(49362),ei=s(5464),ea=s(86963),el=s(49426),eo=s(94306),ec=s(64334);function ed({clientId:e,cwd:t,onClose:s}){let{t:i}=(0,et.Bd)("projectHistory"),[a,l]=(0,r.useState)(()=>(0,ec.N1)().maximized),o=t.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??t;return(0,n.jsx)(ei.YV,{open:!0,onOpenChange:e=>{e||s()},children:(0,n.jsxs)(ei.hA,{showCloseButton:!1,"data-testid":"project-preview-dialog",className:(0,el.cn)("h-[min(94dvh,1080px)] w-[min(96dvw,1600px)] max-w-none gap-0 p-0",a&&"h-dvh max-h-none w-dvw rounded-none","max-sm:h-dvh max-sm:max-h-none max-sm:w-dvw max-sm:rounded-none"),children:[(0,n.jsx)(ei.uX,{className:"sr-only",children:i("previewDescription")}),(0,n.jsx)(eo.q,{clientId:e,cwd:t,refreshOnFocus:!0,onEscape:s,title:(0,n.jsx)(ei.YM,{className:"truncate text-sm",title:t,children:o}),actions:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ea.$,{size:"icon-sm",variant:"ghost",className:"max-md:hidden","aria-label":i(a?"restoreWindow":"maximizeWindow"),onClick:()=>{l(!a),(0,ec.Ms)({...(0,ec.N1)(),maximized:!a})},children:a?(0,n.jsx)(es.A,{className:"size-4"}):(0,n.jsx)(en.A,{className:"size-4"})}),(0,n.jsx)(ea.$,{size:"icon-sm",variant:"ghost","aria-label":i("closePreview"),onClick:s,children:(0,n.jsx)(er.A,{className:"size-4"})})]})})]})})}var eu=s(26586),em=s(74166),ep=s(51821),eh=s(67069);function eg({children:e}){let t=(0,ep.G)(),s=(0,eu.A)(),[c]=(0,r.useState)(()=>{var e,n,r;let c,d,u,m=(0,eh.YW)(s);return{clientId:s,...(e=(e,s)=>{t.show(s)},c="off"===new URL(window.location.href).searchParams.get("plugins"),d="normal",n=()=>!c&&"normal"===d,u=new ee({pi:{prompt:(e,t)=>m.request(a.P6.send,{source:e,mode:t.mode,text:t.text,images:(t.images??[]).map(e=>({...e}))}),commands:{list:async e=>(await m.request(I.QV.commandsList,{source:e})).commands.filter(e=>"extension"===e.source).map(({name:e,description:t})=>({name:e,description:t})),execute:async(e,t,s)=>{await m.request(I.QV.commandExecute,{source:e,command:t,...void 0===s?{}:{args:s}})}},tools:{list:async e=>(await m.request(I.QV.toolsList,{source:e})).tools},bash:{execute:(e,t)=>m.request(I.QV.bashExecute,{source:e,command:t.command,excludeFromContext:t.excludeFromContext}),abort:async e=>{await m.request(I.QV.bashAbort,{source:e})}},interrupt:async e=>{await m.request(a.P6.interrupt,{source:e})}},listBrowserEntries:async()=>{if(!n())return[];let{entries:e}=await m.request(f.list,{});return n()?e:[]},subscribePush:e=>m.subscribe(M,e),createPiDeskChannel:e=>({invokeGlobal:(t,s)=>m.request(l.OY.invoke,{pluginName:e,method:t,scope:"global",input:s}),invokeSession:(t,s,n)=>m.request(l.OY.invoke,{pluginName:e,method:s,scope:"session",source:t,input:n})}),createLogChannel:e=>({watch:async t=>(await m.request(N.watch,{pluginName:e,path:t})).snapshot,unwatch:async t=>{await m.request(N.unwatch,{pluginName:e,path:t})},subscribe:t=>m.subscribe(N.event,s=>{s.pluginName===e&&t({path:s.path,event:s.event})})})},void 0,e),{appSocket:(r=e=>{d=e},{async connect(e){u.markConnecting();try{return await m.connect(e)}catch(e){throw u.markDisconnected(e instanceof Error?e.message:"WebSocket 连接失败"),e}},async request(e,t){let s=await m.request(e,t);if(e.path!==o.kM.list.path)return s;let n=o.e4.parse(s);return r(n.appRuntime.mode),(0,i.UV)(n.appRuntime.settings),u.replaceGlobalPluginStates(n.appRuntime.plugins),u.replaceWorkSessions(n.workSessions),u.markReady(),u.refreshEntries().catch(e=>{console.error("[Pi Desk][PluginHost] 初始化 Browser Entry 失败",{errorName:e instanceof Error?e.name:"UnknownError",message:e instanceof Error?e.message:String(e)})}),s},subscribe:(e,t)=>m.subscribe(e,t),async waitForClose(){let e=await m.waitForClose();return u.markDisconnected(e.reason||null),e},close(){m.close()}}),pluginHost:u})}}),[d,u]=(0,r.useState)(null);(0,r.useEffect)(()=>c.pluginHost.bindProjectPreview(e=>{u(e),requestAnimationFrame(()=>document.querySelector('[data-testid="project-preview-dialog"]')?.focus())}),[c]);let m=(0,r.useRef)(null);return(0,r.useEffect)(()=>{let e={};return m.current={token:e,runtime:c},()=>{m.current?.token===e&&(m.current=null),queueMicrotask(()=>{m.current?.runtime!==c&&(c.appSocket.close(),c.pluginHost.dispose())})}},[c]),(0,n.jsx)(eh.o5.Provider,{value:c,children:(0,n.jsxs)(em.Dq.Provider,{value:c.pluginHost,children:[e,d?(0,n.jsx)(ed,{clientId:c.clientId,cwd:d,onClose:()=>u(null)},d):null]})})}},52216:e=>{e.exports={panel:"l3-conversation-call-summary_panel__sUGhX",table:"l3-conversation-call-summary_table__cf6vS",row:"l3-conversation-call-summary_row__eGK_L"}},54379:(e,t,s)=>{"use strict";s.d(t,{TR:()=>E,bq:()=>S,eb:()=>M,gC:()=>C,l6:()=>j,s3:()=>N,yv:()=>I});var n=s(7962);s(69266);var r=s(66341),i=s(91068),a=s(57160),l=s(39148),o=s(95532),c=s(34358),d=s(75970),u=s(12124),m=s(6398),p=s(15639),h=s(44788),g=s(40963),f=s(10949),x=s(46468),b=s(93282),v=s(49426),w=s(86758),y=s(90458),k=s(24121);let j=r.H;function N({className:e,...t}){return(0,n.jsx)(i.s,{"data-slot":"select-group",className:(0,v.cn)("scroll-my-1 p-1",e),...t})}function I({className:e,...t}){return(0,n.jsx)(a.y,{"data-slot":"select-value",className:(0,v.cn)("flex flex-1 text-left",e),...t})}function S({className:e,size:t="default",children:s,...r}){return(0,n.jsxs)(l.b,{"data-slot":"select-trigger","data-size":t,className:(0,v.cn)("flex w-fit cursor-pointer items-center justify-between gap-2 rounded-lg border border-input bg-card px-2.5 py-1 text-sm leading-5 whitespace-nowrap transition-colors outline-none select-none hover:bg-accent focus-visible:border-ring focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:min-h-8 data-[size=sm]:min-h-7 data-[size=sm]:rounded-md data-[size=sm]:py-0.5 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r,children:[s,(0,n.jsx)(o.w,{render:(0,n.jsx)(w.A,{className:"pointer-events-none size-4 text-muted-foreground"})})]})}function C({className:e,positionerClassName:t,children:s,side:r="bottom",sideOffset:i=4,align:a="center",alignOffset:l=0,alignItemWithTrigger:o=!0,finalFocus:p=!1,...h}){return(0,n.jsx)(c.V,{children:(0,n.jsx)(d.l,{side:r,sideOffset:i,align:a,alignOffset:l,alignItemWithTrigger:o,className:(0,v.cn)("isolate z-50",t),children:(0,n.jsxs)(u.t,{"data-slot":"select-content",finalFocus:p,"data-align-trigger":o,className:(0,v.cn)("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]: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),...h,children:[(0,n.jsx)(z,{}),(0,n.jsx)(m.B,{children:s}),(0,n.jsx)(A,{})]})})})}function E({className:e,...t}){return(0,n.jsx)(p.M,{"data-slot":"select-label",className:(0,v.cn)("px-1.5 py-1 text-xs text-muted-foreground",e),...t})}function M({className:e,children:t,...s}){return(0,n.jsxs)(h.e,{"data-slot":"select-item",className:(0,v.cn)("relative flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-md py-1 pr-8 pl-2 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...s,children:[(0,n.jsx)(g.h,{className:"flex flex-1 shrink-0 gap-2 whitespace-nowrap",children:t}),(0,n.jsx)(f.h,{render:(0,n.jsx)("span",{className:"pointer-events-none absolute right-2 flex size-4 items-center justify-center"}),children:(0,n.jsx)(y.A,{className:"pointer-events-none"})})]})}function z({className:e,...t}){return(0,n.jsx)(x.w,{"data-slot":"select-scroll-up-button",className:(0,v.cn)("top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:(0,n.jsx)(k.A,{})})}function A({className:e,...t}){return(0,n.jsx)(b.d,{"data-slot":"select-scroll-down-button",className:(0,v.cn)("bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:(0,n.jsx)(w.A,{})})}},55438:(e,t,s)=>{"use strict";s.d(t,{PS:()=>d,ef:()=>o,gK:()=>c,hS:()=>l,mv:()=>p});var n=s(38979),r=s(59605),i=s(70698),a=s(85232);let l=n.Ik({type:n.eu("message_start"),snapshot:r.s4}).strict(),o=n.Ik({type:n.eu("message_update"),location:r.fb,fixed:r.dG.optional(),summary:r.XW.optional(),detail:r.wH.optional(),increments:r.fK.optional()}).strict().superRefine((e,t)=>{if(!e.fixed&&!e.summary&&!e.detail&&!e.increments)return void t.addIssue({code:"custom",message:"message update requires a changed layer"});let s=[];for(let t of Object.keys(e.increments??{}))try{s.push({raw:t,parsed:(0,a.U)(t)})}catch{}for(let n of s){let s="summary"===n.parsed.root?Object.keys(e.summary??{}):Object.keys(e.detail??{}),r=n.parsed.segments[0];(0===n.parsed.segments.length||"string"==typeof r&&s.includes(r))&&t.addIssue({code:"custom",message:"replacement and increment paths cannot overlap",path:["increments",n.raw]})}for(let e=0;e<s.length;e+=1)for(let n=e+1;n<s.length;n+=1){let r=s[e],i=s[n];((0,a.v)(r.parsed,i.parsed)||(0,a.v)(i.parsed,r.parsed))&&t.addIssue({code:"custom",message:"increment parent and child paths cannot overlap",path:["increments",i.raw]})}}),c=n.Ik({type:n.eu("message_commit"),location:r.fb,durable:r.V6,fixed:n.Ik({timestampMs:i.k}).strict()}).strict(),d=n.Ik({type:n.eu("message_discard"),location:r.fb}).strict(),u=n.Ik({type:n.eu("durable_append"),messages:n.YO(r.mj).min(1)}).strict().superRefine((e,t)=>{let s=new Set;for(let[n,r]of e.messages.entries())n>0&&r.location.index!==e.messages[n-1].location.index+1&&t.addIssue({code:"custom",message:"durable append message indexes must be continuous",path:["messages",n,"location","index"]}),s.has(r.location.entryId)&&t.addIssue({code:"custom",message:"durable append entryId values must be unique",path:["messages",n,"location","entryId"]}),s.add(r.location.entryId)}),m=n.KC([l,o,c,d]),p=n.KC([u,m])},58270:e=>{e.exports={inputFrame:"l2-workbench-chat-composer_inputFrame__zhb9v",inputText:"l2-workbench-chat-composer_inputText__3DU2N",footer:"l2-workbench-chat-composer_footer__7wBQh",primaryTools:"l2-workbench-chat-composer_primaryTools__8KCVm",metadataTools:"l2-workbench-chat-composer_metadataTools__XEVFA",submitTools:"l2-workbench-chat-composer_submitTools__x8f4c",modelTrigger:"l2-workbench-chat-composer_modelTrigger__tDV8k",modelTriggerDetails:"l2-workbench-chat-composer_modelTriggerDetails__sdSS2"}},59605:(e,t,s)=>{"use strict";s.d(t,{D8:()=>X,Er:()=>z,Gx:()=>O,Hf:()=>Q,LJ:()=>c,OS:()=>Z,O_:()=>K,Ok:()=>V,Pc:()=>o,Px:()=>R,Qi:()=>T,RX:()=>ec,Rh:()=>_,Rk:()=>H,Rt:()=>q,UT:()=>P,V6:()=>v,XW:()=>ei,Xj:()=>U,aV:()=>L,ai:()=>B,bG:()=>G,bN:()=>F,dG:()=>er,fK:()=>eo,fb:()=>b,lJ:()=>E,mh:()=>m,mj:()=>es,ny:()=>Y,q5:()=>S,s4:()=>et,sL:()=>J,s_:()=>C,wH:()=>ea});var n=s(38979),r=s(66453),i=s(67765),a=s(70698),l=s(85232);let o=n.Yj().uuid(),c=n.ai().int().nonnegative(),d=n.Yj().trim().min(3).max(129).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/),u=n.k5(["image/jpeg","image/png","image/webp","image/gif"]),m=n.Ik({mimeType:u,width:n.ai().int().positive(),height:n.ai().int().positive()}).strict(),p=n.k5(["running","completed","error","aborted"]),h=n.k5(["running","completed","error"]),g=n.ai().int().nonnegative().max(Number.MAX_SAFE_INTEGER),f=n.Ik({inputTokens:g,outputTokens:g,cacheReadTokens:g,costUsd:n.ai().finite().nonnegative()}).strict(),x=n.Yj().trim().min(1).nullable(),b=n.Ik({tempId:o}).strict(),v=n.Ik({index:c,entryId:r.Rv}).strict(),w=n.Ik({timestampMs:a.k.nullable(),type:n.eu("user"),viewKey:d,hasDetail:n.zM()}).strict(),y=n.Ik({timestampMs:a.k.nullable(),type:n.eu("assistant"),viewKey:d,status:p,hasDetail:n.zM(),usage:f}).strict(),k=n.Ik({timestampMs:a.k.nullable(),type:n.eu("tool"),viewKey:d,status:h,hasDetail:n.zM(),usage:f.nullable()}).strict(),j=n.Ik({timestampMs:a.k.nullable(),type:n.eu("bash"),viewKey:d,status:p,hasDetail:n.zM()}).strict(),N=n.Ik({timestampMs:a.k.nullable(),type:n.eu("custom"),viewKey:d,hasDetail:n.zM()}).strict();function I(e){let t=w.extend({timestampMs:e}).strict(),s=y.extend({timestampMs:e}).strict(),r=k.extend({timestampMs:e}).strict(),i=j.extend({timestampMs:e}).strict(),a=N.extend({timestampMs:e}).strict();return{user:t,assistant:s,tool:r,bash:i,custom:a,message:n.gM("type",[t,s,r,i,a])}}n.gM("type",[w,y,k,j,N]);let S=I(n.ch()).message,C=I(a.k).message,E=n.Ik({text:n.Yj(),images:n.YO(m)}).strict(),M=n.Ik({provider:n.Yj(),modelId:n.Yj()}).strict(),z=n.Ik({text:n.Yj(),errorMessage:n.Yj().nullable().default(null),model:M.nullable().optional()}).strict(),A={name:n.Yj().trim().min(1),reasoning:x,inputPreview:x,activity:x};function $(){return n.Ik({...A,path:i.eC.nullable()}).strict()}let R=n.Ik({...A,images:n.YO(m).optional()}).strict(),P=R,D=n.KC([n.Ik({startedAtMs:a.k}).strict(),n.Ik({durationMs:n.ai().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).strict()]),T=n.Ik({...A,timing:D.nullable()}).strict(),O=$().extend({images:n.YO(m).optional()}).strict(),L=$(),F=$(),B=n.Ik({command:n.Yj().min(1)}).strict(),q=n.Ik({text:n.Yj()}).strict(),_=n.Ik({thinking:n.Yj()}).strict(),W=n.Ik({complete:n.zM(),calls:n.YO(n.Ik({name:n.Yj(),arguments:n.g1(n.Yj(),n.Pq()).optional(),argumentsBytes:n.ai().int().nonnegative().optional(),status:n.k5(["ok","error","unfinished"]),durationMs:n.ai().finite().nonnegative().optional(),error:n.Yj().optional()}).strict())}).strict(),Y=n.Ik({output:n.Yj(),nestedCalls:W.optional()}).strict(),V=n.Ik({output:n.Yj()}).strict(),U=n.Ik({content:n.Yj()}).strict(),H=n.gM("kind",[n.Ik({kind:n.eu("diff"),content:n.Yj()}).strict(),n.Ik({kind:n.eu("output"),content:n.Yj()}).strict()]),K=n.gM("kind",[n.Ik({kind:n.eu("content"),content:n.Yj()}).strict(),n.Ik({kind:n.eu("output"),content:n.Yj()}).strict()]),G=n.Ik({output:n.Yj()}).strict(),J=n.Ik({text:n.Yj().min(1)}).strict(),Q=n.g1(n.Yj(),n.Pq()),X=n.g1(n.Yj(),n.Pq()),Z=n.KC([X,n.ch()]);function ee(e,t){return n.Ik({location:e,fixed:I(t).message,summary:Q,detail:X.optional()}).strict().superRefine((e,t)=>{void 0===e.detail||e.fixed.hasDetail||t.addIssue({code:"custom",message:"message detail requires hasDetail=true",path:["detail"]})})}let et=ee(b,n.ch()),es=ee(v,a.k);function en(e,t){0===Object.keys(e).length&&t.addIssue({code:"custom",message:"patch requires at least one changed field"})}let er=n.Ik({viewKey:d.optional(),status:n.KC([p,h]).optional(),hasDetail:n.zM().optional(),usage:f.nullable().optional()}).strict().superRefine(en),ei=n.g1(n.Yj(),n.Pq()).superRefine(en),ea=n.g1(n.Yj(),n.Pq()).superRefine(en),el=n.KC([n.Yj().min(1),n.YO(n.Pq()).min(1)]),eo=n.g1(n.Yj(),el).superRefine((e,t)=>{for(let s of(en(e,t),Object.keys(e)))try{(0,l.U)(s)}catch(e){t.addIssue({code:"custom",message:e instanceof Error?e.message:"increment path is invalid",path:[s]})}}),ec=n.Ik({messages:n.YO(es),temporaryMessages:n.YO(et)}).strict();n.Ik({index:c,entryId:r.Rv,detail:Z}).strict(),n.Ik({mimeType:u,data:n.Yj().min(1)}).strict()},61286:(e,t,s)=>{"use strict";s.d(t,{N:()=>r});var n=s(38979);let r=n.Ik({key:n.Yj().min(1).max(160),params:n.g1(n.Yj().min(1).max(80),n.KC([n.Yj().max(1e3),n.ai().finite()])).optional()}).strict()},62851:(e,t,s)=>{"use strict";s.d(t,{$C:()=>S,GR:()=>f,Pq:()=>C,YT:()=>I});var n=s(38979),r=s(15710),i=s(6397),a=s(99739),l=s(70698);let o=n.Yj().uuid(),c=n.Yj().trim().min(1).max(256),d=n.k5(["info","success","warning","error"]),u=n.Yj().trim().min(1).max(120),m=n.Yj().trim().max(320).nullable(),p=n.Ik({type:n.eu("plugin"),pluginName:a.tv,name:a.f7,data:a.Dz}).strict(),h=n.Ik({notificationId:o,level:d,title:u,description:m,createdAt:l.k,event:p.nullable()}).strict(),g=n.g1(a.tv,a.Dz),f=n.Ik({mode:n.k5(["normal","basic"]).default("normal"),notifications:n.YO(h),plugins:g,capabilityModes:i.Wu,settings:r.J.default({region:{locale:"en",timeZone:"UTC"}})}).strict(),x=n.Ik({level:d.optional(),title:u.optional(),description:m.optional(),event:p.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0,{message:"notification changes cannot be empty"}),b=n.Ik({type:n.eu("add"),notification:h}).strict(),v=n.Ik({type:n.eu("update"),notificationId:o,changes:x}).strict(),w=n.Ik({type:n.eu("delete"),notificationId:o}).strict(),y=n.gM("type",[b,v,w]),k=n.Ik({pluginName:a.tv,state:a.Dz.nullable()}).strict(),j=n.Ik({key:n.eu("capabilityModes"),update:i.Wu}).strict(),N=n.Ik({key:n.eu("settings"),update:r.J}).strict();n.gM("key",[N,j,n.Ik({key:n.eu("notifications"),update:y}).strict(),n.Ik({key:n.eu("plugins"),update:k}).strict()]);let I=n.KC([N.extend({type:n.eu("update")}),j.extend({type:n.eu("update")}),n.Ik({type:n.eu("replace"),runtime:f}).strict(),n.Ik({type:n.eu("update"),key:n.eu("notifications"),update:y}).strict(),n.Ik({type:n.eu("update"),key:n.eu("plugins"),update:k}).strict()]),S=n.gM("key",[n.Ik({key:n.eu("notifications"),update:w}).strict(),n.Ik({key:n.eu("settings"),update:n.Ik({region:r.a.unwrap().partial().strict().refine(e=>Object.keys(e).length>0,"地区更新不能为空")}).strict()}).strict()]),C=n.Ik({}).strict(),E=n.Ik({name:a.f7,data:a.Dz}).strict();n.Ik({key:c.optional(),level:d,title:u,description:n.Yj().trim().max(320).optional(),event:E.optional()}).strict(),n.Ik({level:d.optional(),title:u.optional(),description:m.optional()}).strict().refine(e=>Object.keys(e).length>0,{message:"plugin notification changes cannot be empty"})},67069:(e,t,s)=>{"use strict";s.d(t,{o5:()=>d,YW:()=>p,p:()=>m,gM:()=>u});var n=s(9626),r=s(67837),i=s(73230);class a extends Error{constructor(e,t,s){super((0,i.B)({msg:e,i18n:{key:t,...s?{params:s}:{}}})),this.rawMessage=e,this.name="L4AppSocketTransportError"}}class l extends Error{constructor(e,t,s){super(s),this.code=e,this.rawMessage=t,this.name="L4AppSocketRequestError"}}class o{constructor(e,t){this.onPush=t,this.pendingRequests=new Map,this.opened=!1,this.disposed=!1,this.removeAbortListener=null,this.handleMessage=e=>{let t;if("string"!=typeof e.data)return void this.close(1003,"仅支持文本 JSON 消息");try{t=JSON.parse(e.data)}catch{this.close(1007,"JSON 格式无效");return}let s=n.hE.safeParse(t);if(s.success){let e=s.data.head.requestId,t=this.pendingRequests.get(e);if(!t)return;if(this.pendingRequests.delete(e),clearTimeout(t.timeout),s.data.head.path!==t.path){t.reject(new a("WebSocket 响应 path 与请求不一致","common:socketResponseMismatch")),this.close(1008,"响应 path 与 requestId 不匹配");return}if(0!==s.data.body.code)return void t.reject(new l(s.data.body.code,s.data.body.msg,(0,i.B)(s.data.body)));let n=t.contract.outputSchema.safeParse(s.data.body.data);if(!n.success){t.reject(new a("WebSocket 响应数据无效","common:socketResponseInvalid")),this.close(1008,"服务端响应数据无效");return}return void t.resolve(n.data)}let r=n.Od.safeParse(t);if(!r.success)return void this.close(1008,"服务端消息信封无效");try{this.onPush(r.data.head.path,r.data.body)}catch{this.close(1008,"服务端推送数据无效")}},this.handleClose=e=>{let t={code:e.code,reason:e.reason};this.dispose(),this.resolveClosed(t)},this.socket=new WebSocket(function(e){let t="https:"===window.location.protocol?"wss:":"ws:";return`${t}//${window.location.host}${n.PA}?clientId=${encodeURIComponent(e)}`}(e),n.uB),this.closedPromise=new Promise(e=>{this.resolveClosed=e}),this.socket.addEventListener("message",this.handleMessage),this.socket.addEventListener("close",this.handleClose,{once:!0})}open(e){return this.opened&&this.socket.readyState===WebSocket.OPEN?Promise.resolve():e.aborted?Promise.reject(new DOMException("Aborted","AbortError")):new Promise((t,s)=>{let n=()=>{this.socket.removeEventListener("open",i),this.socket.removeEventListener("error",l)},r=()=>this.close(1e3,"页面已卸载"),i=()=>{n(),this.removeAbortListener?.(),this.removeAbortListener=null,this.opened=!0,t()},l=()=>{n(),this.close(1e3,"WebSocket 连接失败"),s(new a("WebSocket 连接失败","common:socketConnectFailed"))};e.addEventListener("abort",r,{once:!0}),this.removeAbortListener=()=>e.removeEventListener("abort",r),this.socket.addEventListener("open",i,{once:!0}),this.socket.addEventListener("error",l,{once:!0}),this.closedPromise.then(()=>{n(),this.opened||s(new a("WebSocket 连接已断开","common:socketDisconnected"))})})}isOpen(){return!this.disposed&&this.socket.readyState===WebSocket.OPEN}request(e,t){if(!this.isOpen())return Promise.reject(new a("WebSocket 尚未连接","common:socketNotConnected"));let s=(0,r.y)(),i=n.tU.parse({head:{op:"req",path:e.path,requestId:s},body:e.inputSchema.parse(t)});return new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(s),n(new a(`WebSocket 请求超时:${e.path}`,"common:socketRequestTimeout",{path:e.path}))},e.timeoutMs??15e3);this.pendingRequests.set(s,{path:e.path,contract:e,resolve:e=>t(e),reject:n,timeout:r});try{this.socket.send(JSON.stringify(i))}catch(e){this.pendingRequests.delete(s),clearTimeout(r),n(e instanceof Error?e:new a("WebSocket 请求发送失败","common:socketSendFailed"))}})}waitForClose(){return this.closedPromise}close(e=1e3,t="客户端关闭连接"){if(!this.disposed&&this.socket.readyState!==WebSocket.CLOSED)try{this.socket.close(e,t)}catch{}}dispose(){if(!this.disposed){for(let e of(this.disposed=!0,this.removeAbortListener?.(),this.removeAbortListener=null,this.socket.removeEventListener("message",this.handleMessage),this.pendingRequests.values()))clearTimeout(e.timeout),e.reject(new a("WebSocket 连接已断开","common:socketDisconnected"));this.pendingRequests.clear()}}}var c=s(69266);let d=(0,c.createContext)(null);function u(){let e=(0,c.useContext)(d);if(!e)throw Error("AppSocket Provider is missing");return e}function m(e){return e.code===n.P9}function p(e){let t=new Map,s=null,n=Promise.resolve({code:1e3,reason:""}),r=null,i=(e,s)=>{let n=t.get(e);if(!n)return;let r=n.contract.bodySchema.parse(s);for(let t of[...n.listeners])try{t(r)}catch(t){console.error("[Pi Desk][AppSocketClient] 推送监听器执行失败",{path:e,errorName:t instanceof Error?t.name:"UnknownError"})}};return{connect:t=>s?.isOpen()?Promise.resolve(!1):r||(r=(async()=>{let r=s;if(r&&(await r.waitForClose(),s===r&&(s=null)),t.aborted)throw new DOMException("Aborted","AbortError");let a=new o(e,i);s=a,(n=a.waitForClose()).then(()=>{s===a&&(s=null)});try{await a.open(t)}catch(e){throw a.close(),await a.waitForClose(),s===a&&(s=null),e}return!0})().finally(()=>{r=null})),request(e,t){let n=s;return n?n.request(e,t):Promise.reject(Error("WebSocket 尚未连接"))},subscribe(e,s){let n=t.get(e.path);if(n&&n.contract!==e)throw Error(`WebSocket push path 使用了不同合同:${e.path}`);let r=n??{contract:e,listeners:new Set},i=e=>s(e);return r.listeners.add(i),t.set(e.path,r),()=>{r.listeners.delete(i),0===r.listeners.size&&t.delete(e.path)}},waitForClose:()=>n,close(){s?.close()}}}},68269:(e,t,s)=>{"use strict";s.d(t,{$f:()=>f,DK:()=>y,Pi:()=>w,R3:()=>m,TV:()=>z,UR:()=>k,Y2:()=>h,ao:()=>p,lV:()=>g,oc:()=>$,w$:()=>S,wI:()=>x,wR:()=>v,wf:()=>A,xh:()=>j,yI:()=>b});var n=s(38979),r=s(6397),i=s(15381),a=s(59605),l=s(26357),o=s(267);let c=a.Pc,d=a.LJ,u=a.mh,m=a.fb,p=a.s_,h=a.Er,g=a.Hf,f=a.Rh,x=a.OS,b=a.s4,v=a.mj,w=o.R,y=n.Ik({index:d,entryId:i.C3}).strict(),k=n.KC([n.ch(),y]),j=u.extend({data:n.Yj().min(1)}).strict(),N=l.$,I=n.Ik({tempId:c,text:n.Yj(),images:n.YO(u).max(10)}).strict(),S=n.Ik({provider:n.Yj().trim().min(1),modelId:n.Yj().trim().min(1),thinkingLevel:N}).strict(),C=n.Ik({tokens:n.ai().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable(),contextWindow:n.ai().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),E=n.g1(n.Yj(),n.Pq()),M=n.g1(n.Yj().min(1),E),z=n.k5(["normal","basic"]),A=n.Ik({extensionMode:z.default("normal"),presentationMode:z.default("normal"),initializationError:n.Yj().max(32e3).nullable().default(null),queues:n.Ik({steering:n.YO(I),followUp:n.YO(I)}).strict(),model:S.nullable(),capabilityMode:r.rY.nullable(),contextUsage:C.nullable(),plugins:M}).strict(),$=a.RX.extend({runtime:A}).strict();n.Ik({sessionId:i.Kx,branchId:i._A,entryId:i.C3}).strict().extend({imageIndex:n.ai().int().nonnegative()}).strict()},70657:(e,t,s)=>{"use strict";s.d(t,{k:()=>m});var n=s(7962),r=s(86758),i=s(66584),a=s(69266),l=s(78121),o=s(37975),c=s(17708),d=s(35800);function u(e){return e.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??e}function m({workId:e,cwd:t,projectName:s,runtime:p,gitRuntime:h,onOpenGitBranches:g,onFileOpened:f}){let x,{t:b}=(0,l.Bd)("projectFiles");(0,a.useSyncExternalStore)(p.subscribe,p.getRevision,p.getRevision);let v=p.getDirectory(e),w=p.getDirectories(e),y=(0,o.Yj)(t)===(0,o.Yj)(v),k=y?s:u(v);return(0,n.jsx)(d.F,{cwd:v,projectName:k,gitReadOnly:!y,rootTitle:w.length>1?(0,n.jsxs)(c.rI,{children:[(0,n.jsxs)(c.ty,{"data-testid":"project-preview-directory-trigger","aria-label":b("selectPreviewDirectory"),title:v,className:"flex min-h-7 min-w-0 flex-1 items-center gap-1 rounded-md px-1 text-left hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring",children:[(0,n.jsx)("span",{className:"max-w-[45%] truncate text-xs font-semibold",children:k}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:"\xb7"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground",children:(x=v.replaceAll("\\","/").split("/").filter(Boolean)).length<=2?v:`…/${x.slice(-2).join("/")}`}),(0,n.jsx)(r.A,{className:"size-3.5 shrink-0 text-muted-foreground"})]}),(0,n.jsx)(c.SQ,{finalFocus:!0,className:"w-[23rem] min-w-0 max-w-[calc(100vw-1.5rem)]","aria-label":b("previewDirectories"),children:(0,n.jsxs)(c.I,{children:[(0,n.jsx)(c.lp,{children:b("previewDirectories")}),(0,n.jsx)(c.Hr,{value:v,onValueChange:t=>p.selectDirectory(e,t),children:w.map(e=>(0,n.jsxs)(c.Ht,{value:e,"data-testid":"project-preview-directory-option","data-directory":e,className:"items-start py-2 data-checked:bg-muted",children:[(0,n.jsx)(i.A,{className:"mt-0.5 size-4 text-muted-foreground"}),(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",children:(0,o.Yj)(e)===(0,o.Yj)(t)?s:u(e)}),(0,o.Yj)(e)===(0,o.Yj)(t)?(0,n.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:b("sessionDirectory")}):null]}),(0,n.jsx)("span",{className:"mt-0.5 block break-all font-mono text-xs leading-5 text-muted-foreground",children:e})]})]},(0,o.Yj)(e)))})]})})]}):void 0,runtime:p.getFileRuntime(e),gitRuntime:h,onOpenGitBranches:n=>{y&&g({workId:e,cwd:t,projectName:s,repositoryRoot:n})},onFileOpened:()=>{p.showWindow(e),f?.()}})}},74166:(e,t,s)=>{"use strict";s.d(t,{Dq:()=>r,So:()=>a,t4:()=>i});var n=s(69266);let r=(0,n.createContext)(null);function i(){let e=(0,n.useContext)(r);if(!e)throw Error("Plugin Host Provider is missing");return e}function a(){let e=i(),t=(0,n.useCallback)(t=>e.subscribeRegistry(t),[e]),s=(0,n.useCallback)(()=>e.getRegistrySnapshot(),[e]);return(0,n.useSyncExternalStore)(t,s,s).descriptors}},76812:e=>{e.exports={single:"l2-work-session-file-layout_single__LVPWJ",wide:"l2-work-session-file-layout_wide__NEecW"}},78653:e=>{e.exports={chatContainer:"l2-work-session-columns_chatContainer__rLqh5",headerActionIcon:"l2-work-session-columns_headerActionIcon__sRqr8",sessionHeader:"l2-work-session-columns_sessionHeader__ZEwG_",headerAction:"l2-work-session-columns_headerAction__JlrRL",headerActionLabel:"l2-work-session-columns_headerActionLabel__bkzGB",collapsedText:"l2-work-session-columns_collapsedText__f7OAU"}},79814:e=>{e.exports={viewport:"l2-terminal-workspace_viewport__lAZHJ",canvas:"l2-terminal-workspace_canvas__h6ngK",mobile:"l2-terminal-workspace_mobile__4Ae83"}},84942:(e,t,s)=>{"use strict";s.d(t,{Dl:()=>h,Qg:()=>m,RC:()=>f,a4:()=>d,j0:()=>p});var n=s(38979);let r=n.Yj().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),i=n.Yj().trim().min(1).max(256),a=n.Ik({allow:n.YO(i).max(5e3).optional(),deny:n.YO(i).max(5e3).optional()}).strict(),l=n.Ik({value:n.Yj().trim().min(1).max(256),label:n.Yj().trim().min(1).max(120).optional(),description:n.Yj().trim().max(1e3).optional()}).strict(),o=n.Ik({label:n.Yj().trim().min(1).max(120),options:n.YO(l).max(5e3)}).strict(),c=n.g1(r,o),d=n.Yj().min(1).max(64),u=n.Ik({name:n.Yj().trim().min(1).max(64),tools:a.optional(),skills:a.optional(),plugins:n.g1(r,n.g1(r,a)).optional()}).strict(),m=n.g1(d,u).refine(e=>Object.keys(e).length<=100,"最多保存 100 个能力模式").refine(e=>new Set(Object.values(e).map(e=>e.name)).size===Object.keys(e).length,"模式名称不能重复"),p=n.g1(d,u.shape.name),h=n.Ik({tools:n.YO(l),skills:n.YO(l),plugins:n.g1(r,c)}).strict();function g(e,t){let s=0,n=0,r=-1,i=0;for(;n<t.length;)if("*"===e[s])r=s++,i=n;else if(e[s]===t[n])s+=1,n+=1;else{if(!(r>=0))return!1;s=r+1,n=++i}for(;"*"===e[s];)s+=1;return s===e.length}function f(e,t){return(e?.allow===void 0||e.allow.some(e=>g(e,t)))&&!e?.deny?.some(e=>g(e,t))}n.Ik({tools:a,skills:a,capabilities:n.g1(r,a)}).strict()},85232:(e,t,s)=>{"use strict";function n(e){if(!/^(0|[1-9]\d*)$/.test(e))return e;let t=Number(e);if(!Number.isSafeInteger(t))throw Error(`Increment array index is invalid: ${e}`);return t}function r(e){if(!e||e.length>1024)throw Error("Increment path length is invalid");let t=[],s="",r=!1;for(let n of e){if(r){if("."!==n&&"\\"!==n)throw Error(`Increment path contains an invalid escape: \\${n}`);s+=n,r=!1;continue}if("\\"===n){r=!0;continue}if("."===n){if(!s)throw Error("Increment path contains an empty segment");t.push(s),s="";continue}s+=n}if(r)throw Error("Increment path ends with an escape");if(!s)throw Error("Increment path contains an empty segment");t.push(s);let i=t.shift();if("summary"!==i&&"detail"!==i)throw Error("Increment path root must be summary or detail");return{root:i,segments:t.map(n)}}function i(e,t){return e.root===t.root&&!(e.segments.length>t.segments.length)&&e.segments.every((e,s)=>e===t.segments[s])}s.d(t,{U:()=>r,v:()=>i})},89517:e=>{e.exports={surface:"l3-work-session-visual-effects_surface__N89k0",identity:"l3-work-session-visual-effects_identity__Aujuw"}},91399:(e,t,s)=>{"use strict";s.d(t,{e4:()=>m,kM:()=>h});var n=s(38979),r=s(15381),i=s(62851),a=s(70698),l=s(9626);let o=n.Ik({}).strict(),c=n.Ik({workId:r.eW}).strict(),d=n.Ik({workId:r.eW}).strict(),u=n.Ik({cwd:r.ik.optional(),sessionId:r.Kx.optional(),branchId:n.Yj().min(1).optional(),projectName:n.Yj().trim().min(1).optional(),sessionTitle:n.Yj().trim().min(1).nullable().optional(),status:r.jw.optional(),messageCounts:r.AA.optional(),lastMessageUpdatedAt:a.k.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0,{message:"work session changes cannot be empty"}),m=n.Ik({workSessions:n.YO(r.MY),pinnedCount:r.MT,appRuntime:i.GR}).strict().refine(e=>e.pinnedCount<=e.workSessions.length,{message:"pinnedCount cannot exceed work session count",path:["pinnedCount"]}),p=n.gM("type",[n.Ik({type:n.eu("snapshot"),workSessions:n.YO(r.MY),pinnedCount:r.MT}).strict().refine(e=>e.pinnedCount<=e.workSessions.length,{message:"pinnedCount cannot exceed work session count",path:["pinnedCount"]}),n.Ik({type:n.eu("update"),workId:r.eW,changes:u}).strict(),n.Ik({type:n.eu("delete"),workId:r.eW}).strict()]),h=Object.freeze({list:(0,l.Vc)({path:"work-sessions/list",inputSchema:o,outputSchema:m}),acknowledgeCompleted:(0,l.Vc)({path:"work-sessions/ack-completed",inputSchema:c,outputSchema:d}),update:(0,l._G)({path:"work-sessions/update",bodySchema:p})})},95826:(e,t,s)=>{"use strict";s.d(t,{QV:()=>w});var n=s(38979),r=s(267),i=s(9626),a=s(99739);let l=n.k5(["extension","prompt","skill"]),o=n.Ik({name:n.Yj().trim().min(1).max(128),description:n.Yj().max(500).nullable(),source:l}).strict(),c=n.Ik({source:r.R}).strict(),d=n.Ik({commands:n.YO(o)}).strict(),u=n.Ik({source:r.R,command:n.Yj().trim().min(1).max(128),args:n.Yj().max(32768).optional()}).strict(),m=n.Ik({}).strict(),p=n.Ik({name:n.Yj().trim().min(1).max(128),description:n.Yj(),parameters:a.Dz,active:n.zM(),exposure:n.k5(["direct","model-only","codemode","deferred","hidden"]),source:n.Yj().nullable(),blockedByMode:n.zM()}).strict(),h=n.Ik({source:r.R}).strict(),g=n.Ik({tools:n.YO(p)}).strict(),f=n.Ik({source:r.R,command:n.Yj().min(1).max(32768),excludeFromContext:n.zM()}).strict(),x=n.Ik({output:n.Yj(),exitCode:n.ai().int().nullable(),cancelled:n.zM(),truncated:n.zM(),fullOutputPath:n.Yj().nullable()}).strict(),b=n.Ik({source:r.R}).strict(),v=n.Ik({}).strict(),w=Object.freeze({commandsList:(0,i.Vc)({path:"pi/commands/list",inputSchema:c,outputSchema:d}),commandExecute:(0,i.Vc)({path:"pi/commands/execute",inputSchema:u,outputSchema:m,timeoutMs:3e5}),toolsList:(0,i.Vc)({path:"pi/tools/list",inputSchema:h,outputSchema:g}),bashExecute:(0,i.Vc)({path:"pi/bash/execute",inputSchema:f,outputSchema:x,timeoutMs:12e4}),bashAbort:(0,i.Vc)({path:"pi/bash/abort",inputSchema:b,outputSchema:v})})},99739:(e,t,s)=>{"use strict";s.d(t,{Dz:()=>l,f7:()=>a,tv:()=>i});var n=s(38979);let r=n.Yj().trim().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),i=r,a=r,l=n.g1(n.Yj(),n.Pq());n.Yj().trim().min(3).max(129).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/);let o=n.k5(["plugin","server","rocket","settings","panel","message","terminal","file","folder","bot","wrench","database","globe"]);n.gM("type",[n.Ik({type:n.eu("builtin"),name:o}).strict(),n.Ik({type:n.eu("svg"),content:n.Yj().trim().min(1).max(16384)}).strict()])}},e=>{e.O(0,[82705,79405,85959,26717,94287,57235,14825,82371,79267,46270,37313,14197,51474,15302,9038,11937,4904,64444,77358],()=>e(e.s=14465)),_N_E=e.O()}]);
|
|
158
|
+
${d}`:"";return{error:d,copied:""!==f&&u===f,reloading:p,canReload:g,onCopy:()=>{f&&(0,e9.x)(f).then(e=>{e?m(f):n.error(s("initializationCopyFailed"))})},onReload:()=>{g&&(h(!0),t.reload(i).catch(e=>{n.error(e instanceof Error?e.message:String(e))}).finally(()=>h(!1)))}}}(t,u);(0,r.useSyncExternalStore)(z.subscribe,z.getRevision,z.getRevision);let Q=z.getWorkspace(t.workId),Z=(Q?.tabs.length??0)+ +!!Q?.activeDiff,ee=(0,r.useMemo)(()=>({workId:t.workId,sessionId:t.sessionId,branchId:t.branchId}),[t.workId,t.sessionId,t.branchId]),et=(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("p",{className:(0,C.cn)("truncate text-sm transition-colors duration-150 motion-reduce:transition-none",i?"font-semibold text-foreground":"font-medium text-muted-foreground"),title:t.projectName,children:t.projectName}),(0,n.jsx)("p",{className:"truncate text-xs text-muted-foreground","data-testid":"session-header-title",title:t.sessionTitle??K("newSession"),children:t.sessionTitle??K("newSession")})]});return(0,r.useEffect)(()=>{let e=G.current;if(!e||"completed"!==t.status)return;let s=!1,n=()=>{s||(s=!0,R(t.workId))};return e.addEventListener("pointerdown",n,{once:!0}),e.addEventListener("wheel",n,{passive:!0,once:!0}),e.addEventListener("keydown",n,{once:!0}),()=>{e.removeEventListener("pointerdown",n),e.removeEventListener("wheel",n),e.removeEventListener("keydown",n)}},[R,t.status,t.workId]),(0,n.jsxs)("section",{ref:G,className:"pi-desk-workbench-resize-interactions relative flex h-full min-h-0 min-w-0 flex-1 flex-col bg-background","data-work-id":t.workId,"data-degraded":J.error?"true":void 0,onPointerDown:()=>P(t.workId),onFocusCapture:()=>P(t.workId),children:[J.error?(0,n.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-20 border border-destructive"}):null,(0,n.jsx)(us,{workSession:t,runtime:z,gitRuntime:v,mobile:M,onOpenGitBranches:O,onOpenSidebar:()=>A(t.workId),children:r=>(0,n.jsxs)("div",{className:(0,C.cn)(hi().chatContainer,"flex h-full min-h-0 min-w-0 flex-1 flex-col"),children:[(0,n.jsxs)("header",{className:(0,C.cn)(hi().sessionHeader,"flex min-h-14 shrink-0 items-center gap-3 px-3"),"data-testid":"session-header",children:[s&&!M?null:(0,n.jsx)(hw,{sidebarOpen:o,onToggle:H}),(0,n.jsx)("div",{className:"min-w-0 flex-1",children:r&&a?x({source:ee,title:et}):et}),(0,n.jsxs)("div",{className:"-mr-1 flex shrink-0 items-center",children:[J.error?(0,n.jsx)(ha,{error:J.error,copied:J.copied,reloading:J.reloading,canReload:J.canReload,onCopy:J.onCopy,onReload:J.onReload},`${t.sessionId}:${t.branchId}`):null,Z>0?(0,n.jsxs)(I.$,{variant:"ghost",className:hi().headerAction,"data-testid":"session-files-entry","aria-label":K("openSessionFiles"),title:K("sessionFiles",{count:Z}),"aria-pressed":Q?.windowOpen??!1,onClick:()=>z.showWindow(t.workId),children:[(0,n.jsx)(mH.A,{className:"size-4"}),(0,n.jsx)("span",{className:hi().headerActionLabel,children:K("sessionFiles",{count:Z})})]}):null,U?(0,n.jsx)("button",{type:"button",disabled:d,"aria-label":K("unpinWorkSession",{name:t.sessionTitle??t.projectName}),title:K("unpin"),onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),U(t.workId)},className:(0,C.cn)((0,I.r)({variant:"ghost",size:"icon-sm"}),"text-muted-foreground"),children:(0,n.jsx)(V.A,{className:"size-4"})}):null]})]}),(0,n.jsx)(hn,{active:a,visible:r&&a,workSession:t,chatRuntime:u,inputRuntime:m,onPreviewFile:$}),(0,n.jsx)("footer",{className:"bg-background pt-3","data-carousel-swipe-lock":!0,children:(0,n.jsx)(p_,{workSession:t,chatRuntime:u,inputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,widgetsVisible:r&&a,gitRuntime:v,active:l,mobile:M,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,newSessionPending:c,newSessionDisabled:d||E,onNewSession:()=>D(t.workId),clonePending:E,cloneDisabled:d||0===t.messageCounts.total,onCloneWorkSession:()=>Y(t.workId),onOpenBranchPicker:T,onOpenGitBranchPicker:O,onOpenSettings:e})})]})}),(0,n.jsx)(mK.N,{children:S?(0,n.jsx)(m3,{model:S,projectName:t.projectName,sessionTitle:t.sessionTitle,mobile:M,onClose:L,onRetry:F,onSelectEntry:B,onAction:q,onConfirmRunning:_,onCancelRunning:W},"branch-picker"):null})]})}),hk=(0,r.memo)(function({position:e,workSession:t,loading:s,onExpand:r}){let{t:i}=(0,b.Bd)("workbench"),a=t?.projectName??i("workSession"),l=t?t.sessionTitle??i("newSession"):i(s?"loading":"chooseSession"),o=`${a} \xb7 ${l}`;return(0,n.jsx)("section",{className:"relative isolate flex h-full min-h-0 min-w-0 flex-1 bg-background","data-work-id":t?.workId,children:(0,n.jsx)("button",{type:"button",title:o,"aria-label":i("expandSession",{name:o}),onClick:()=>r(e,t?.workId??null),className:"flex h-full w-full min-w-0 flex-col items-center overflow-hidden bg-background px-1 text-muted-foreground outline-none transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:z-30 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:(0,n.jsxs)("span",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-3 overflow-hidden py-3",children:[(0,n.jsx)("span",{className:(0,C.cn)(hi().collapsedText,"max-h-[38%] text-xs leading-none text-muted-foreground"),children:a}),(0,n.jsx)("span",{className:(0,C.cn)(hi().collapsedText,"max-h-[55%] text-xs font-semibold leading-none"),children:l})]})})})});function hj({loading:e,sidebarOpen:t,onToggleSidebar:s}){return(0,n.jsxs)("section",{className:"relative isolate flex h-full min-w-0 flex-1 overflow-hidden bg-background",children:[(0,n.jsx)("div",{className:"absolute left-3 top-3 z-20",children:(0,n.jsx)(hw,{sidebarOpen:t,onToggle:s})}),(0,n.jsx)(mV,{variant:e?"loading":"select-session",children:e?null:(0,n.jsx)(hc,{sidebarOpen:t,onOpen:s})})]})}function hN({onOpenSettings:e,workSessions:t,primaryWorkId:s,pinnedWorkIds:i,focusedWorkId:a,sidebarOpen:l,mobile:o,loading:c,replacingWithEmptyWorkId:d,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,renderPluginSessionHeader:x,gitRuntime:v,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,branchPicker:I,branchPendingWorkId:M,fileRuntime:z,onOpenFileSidebar:A,onPreviewFile:$,onAcknowledgeCompleted:R,onFocusWorkSession:P,onReplaceWithEmptyWorkSession:D,onOpenBranchPicker:T,onOpenGitBranchPicker:O,onCloseBranchPicker:L,onRetryBranchPicker:F,onSelectBranchEntry:B,onBranchAction:q,onConfirmRunningBranch:_,onCancelRunningBranch:W,onCloneWorkSession:Y,onUnpinWorkSession:V,onToggleSidebar:U}){let{t:H}=(0,b.Bd)("workbench"),K=(0,r.useMemo)(()=>{let e=t.find(e=>e.workId===s)??null,n=new Set(i);return[{key:"work-session-primary",workSession:e,fixed:!1},...t.filter(e=>e.workId!==s&&n.has(e.workId)).map(e=>({key:`work-session-${e.workId}`,workSession:e,fixed:!0}))]},[i,s,t]),G=(0,r.useMemo)(()=>K.flatMap(e=>e.workSession?[{workId:e.workSession.workId,projectName:e.workSession.projectName,sessionTitle:e.workSession.sessionTitle,fixed:e.fixed}]:[]),[K]),J=K.length,{containerRef:Q,expandedCount:X}=function(e){let t=(0,r.useRef)(null),s=+(e>0),n=(0,r.useRef)(s),[i,a]=(0,r.useState)(s);return(0,r.useLayoutEffect)(()=>{let s=t.current;if(!s)return;let r=t=>{let s=function(e,t){let s=hv(t);if(0===s)return 0;let n=Math.floor(((Number.isFinite(e)?Math.max(0,Math.floor(e)):0)-48*s)/252);return Math.min(s,Math.max(1,n))}(t,e);n.current!==s&&(n.current=s,a(s))};r(s.clientWidth);let i=new ResizeObserver(e=>{r(e[0]?.contentRect.width??s.clientWidth)});return i.observe(s),()=>i.disconnect()},[e]),{containerRef:t,expandedCount:i}}(J),[Z,ee]=(0,r.useState)(null),et=I?K.findIndex(e=>e.workSession?.workId===I.workId):-1,es=et>=0?et:null!==Z&&Z>=0&&Z<J?Z:null,en=(0,r.useMemo)(()=>(function(e,t,s){let n=hv(e);if(0===n)return[];let r=Math.min(n,Math.max(1,hv(t))),i=null!==s&&Number.isInteger(s)&&s>=0&&s<n?s:null,a=Array(n).fill("expanded"),l=n-r;for(let e=n-1;e>=0&&l>0;e-=1)e!==i&&(a[e]="collapsed",l-=1);return a})(J,X,es),[J,es,X]),er=(0,E.OG)(),ei=JSON.stringify(K.map(e=>e.key)),ea=en.map(e=>"expanded"===e?"e":"c").join("");(0,r.useLayoutEffect)(()=>{let e=JSON.parse(ei);if(e.length<=1||e.length!==ea.length)return;let t=null,s=0,n=()=>{let r=er.current,i=Q.current;if(!r||!i||i.clientWidth<=0)return;let a=Object.keys(r.getLayout());if(!(a.length===e.length&&e.every(e=>a.includes(e))))return void((s+=1)<8?t=window.requestAnimationFrame(n):console.warn("[Pi Desk][WorkbenchColumns] 面板拓扑未及时就绪,跳过本次均分",{expectedPanelCount:e.length,registeredPanelCount:a.length}));let l=[...ea].filter(e=>"c"===e).length,o=e.length-l;if(o<=0)return;let c=48/i.clientWidth*100,d=(100-l*c)/o;if(!Number.isFinite(d)||d<=0)return;let u={};for(let[t,s]of e.entries())u[s]="c"===ea[t]?c:d;r.setLayout(u)};return t=window.requestAnimationFrame(n),()=>{null!==t&&window.cancelAnimationFrame(t)}},[ea,Q,er,ei]);let el=K[0]?.workSession??null,eo=K.reduce((e,t)=>e+ +!!t.workSession,0),ec=a??el?.workId??null,ed=c||null!==d,eu=(0,r.useCallback)((e,t)=>{ee(e),t&&P(t)},[P]);return o?0===eo?(0,n.jsx)(hj,{loading:c,sidebarOpen:l,onToggleSidebar:U}):(0,n.jsx)(hb,{items:G,activeWorkId:ec,onActiveWorkSessionChange:P,children:K.flatMap(t=>{let s=t.workSession;return s?[(0,n.jsx)(hy,{workSession:s,fixed:t.fixed,focused:1===eo||s.workId===ec,contentActive:s.workId===ec,composerActive:s.workId===ec,sidebarOpen:l,replacingWithEmpty:d===s.workId,replacementDisabled:ed,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,renderPluginSessionHeader:x,gitRuntime:v,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,branchPicker:I?.workId===s.workId?I:null,branchPending:M===s.workId,mobile:!0,fileRuntime:z,onOpenFileSidebar:A,onPreviewFile:$,onAcknowledgeCompleted:R,onFocusWorkSession:P,onReplaceWithEmptyWorkSession:D,onOpenBranchPicker:T,onOpenGitBranchPicker:O,onOpenSettings:e,onCloseBranchPicker:L,onRetryBranchPicker:F,onSelectBranchEntry:B,onBranchAction:q,onConfirmRunningBranch:_,onCancelRunningBranch:W,onCloneWorkSession:Y,onUnpinWorkSession:t.fixed?V:null,onToggleSidebar:U},`${s.workId}:${s.sessionId}:${s.branchId}`)]:[]})}):(0,n.jsx)(S.HK,{id:"work-session-columns",orientation:"horizontal",disableCursor:!0,elementRef:Q,groupRef:er,className:(0,C.cn)(dD().sessionPanelGroup,"relative h-full min-h-0 min-w-0 flex-1 overflow-hidden",!o&&"pi-desk-workbench-resize-group"),children:K.flatMap((t,s)=>{let r=t.workSession,i="collapsed"===en[s],a=s>0&&"collapsed"===en[s-1],b=i&&a,E=(0,n.jsx)(S.wV,{id:t.key,minSize:i?48:300,maxSize:i?48:void 0,defaultSize:i?48:300,disabled:i,groupResizeBehavior:i?"preserve-pixel-size":"preserve-relative-size",className:(0,C.cn)("flex h-full min-h-0 min-w-0 !overflow-hidden bg-background",s>0&&"border-l"),children:(0,n.jsx)("div",{className:dD().columnContent,children:i?(0,n.jsx)(hk,{position:s,workSession:r,loading:c,onExpand:eu}):r?(0,n.jsx)(hy,{workSession:r,fixed:t.fixed,focused:1===eo||r.workId===ec,contentActive:!0,composerActive:r.workId===ec,sidebarOpen:l,replacingWithEmpty:d===r.workId,replacementDisabled:ed,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,renderPluginWidgets:f,renderPluginSessionHeader:x,gitRuntime:v,invokePluginMethod:w,listPiCommands:y,getChatModelContext:k,capabilityModes:j,setChatCapabilityMode:N,branchPicker:I?.workId===r.workId?I:null,branchPending:M===r.workId,mobile:o,fileRuntime:z,onOpenFileSidebar:A,onPreviewFile:$,onAcknowledgeCompleted:R,onFocusWorkSession:P,onReplaceWithEmptyWorkSession:D,onOpenBranchPicker:T,onOpenGitBranchPicker:O,onOpenSettings:e,onCloseBranchPicker:L,onRetryBranchPicker:F,onSelectBranchEntry:B,onBranchAction:q,onConfirmRunningBranch:_,onCancelRunningBranch:W,onCloneWorkSession:Y,onUnpinWorkSession:t.fixed?V:null,onToggleSidebar:U},`${r.workId}:${r.sessionId}:${r.branchId}`):(0,n.jsx)(hj,{loading:c,sidebarOpen:l,onToggleSidebar:U})})},t.key);return 0===s?[E]:[(0,n.jsx)(S.WM,{withHandle:!b,disabled:b,"aria-label":H("resizeColumns",{left:s,right:s+1}),className:"w-0 cursor-col-resize bg-transparent aria-disabled:cursor-default"},`${K[s-1].key}-${t.key}-resize-handle`),E]})})}let hI="work-session-pin:boundary";function hS(e,t){hE(e,t);let s=e.slice(0,t),n=e.slice(t);return s.length>0&&n.length>0?[...n,hI,...s]:[...n,...s]}function hC(e,t,s){let n=[...e],[r]=n.splice(t,1);return r&&n.splice(s,0,r),n}function hE(e,t){if(!Number.isInteger(t)||t<0||t>e.length)throw Error("Invalid work session pinnedCount")}function hM(e,t){return e instanceof Error?e.message:t}function hz(e){return e instanceof Error&&"AbortError"===e.name}function hA(e){return"main_running"===e.status||"background_running"===e.status}function h$(e){return{workId:e.workId,sessionId:e.sessionId,branchId:e.branchId}}function hR({open:e,title:t,saving:s,disabled:i,error:a,onTitleChange:l,onSave:o,onClose:c}){let{t:d}=(0,b.Bd)("workbench"),u=(0,r.useId)(),m=(0,r.useRef)(null);return(0,n.jsx)(eN.YV,{open:e,onOpenChange:e=>!e&&c(),children:(0,n.jsx)(eN.hA,{"data-testid":"work-session-rename-dialog",showCloseButton:!1,initialFocus:m,className:"max-w-sm",children:(0,n.jsxs)("form",{className:"flex flex-col gap-4 overflow-y-auto p-4",onSubmit:e=>{e.preventDefault(),o()},children:[(0,n.jsx)(eN.YM,{children:d("renameSessionTitle")}),(0,n.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,n.jsx)("label",{htmlFor:u,className:"font-medium",children:d("sessionTitleLabel")}),(0,n.jsx)(em.p,{ref:m,id:u,value:t,disabled:s,onChange:e=>l(e.currentTarget.value),onFocus:e=>e.currentTarget.select(),onKeyDown:e=>{"Enter"===e.key&&e.nativeEvent.isComposing&&e.preventDefault()}})]}),a?(0,n.jsx)("p",{role:"alert",className:"break-words text-destructive",children:a}):null,(0,n.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,n.jsx)(I.$,{type:"button",variant:"outline",disabled:s,onClick:c,children:d("cancel",{ns:"common"})}),(0,n.jsxs)(I.$,{type:"submit",disabled:i||s||!t.trim(),"aria-busy":s,children:[s?(0,n.jsx)(v.A,{className:"size-4 animate-spin"}):null,d("save",{ns:"common"})]})]})]})})})}let hP=["title","user"];function hD(e){return e.length===hP.length&&hP.every(t=>e.includes(t))}var hT=s(1503),hO=s(40155),hL=s(17864),hF=s(98347),hB=s(74675),hq=s(1364),h_=s(89517),hW=s.n(h_);function hY(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)}}let hV={info:{icon:"text-muted-foreground",label:"noticeInfo"},success:{icon:"text-status-success",label:"noticeSuccess"},warning:{icon:"text-status-warning",label:"noticeWarning"},error:{icon:"text-destructive",label:"noticeError"}};function hU({level:e}){let t="size-3.5";switch(e){case"success":return(0,n.jsx)(ls.A,{className:t});case"warning":return(0,n.jsx)(e_.A,{className:t});case"error":return(0,n.jsx)(Y.A,{className:t});case"info":return(0,n.jsx)(sV.A,{className:t})}}function hH({notification:e,latest:t,mobile:s,moreCount:r,busy:i,onConsume:a,onDismiss:l,onToggleMore:o,showDismiss:c}){let{t:d}=(0,b.Bd)("workbench"),u=hV[e.level],m=null!==e.event;return(0,n.jsxs)("div",{"data-testid":`app-notification-${e.notificationId}`,"data-latest":t?"true":void 0,className:(0,C.cn)("group flex min-w-0 items-stretch overflow-hidden rounded-lg bg-foreground/[0.04]",t?"h-14":"min-h-14"),children:[(0,n.jsxs)("button",{type:"button",disabled:!m||i,onClick:a,"aria-label":d(m?"actionableNotice":"noticeLabel",{level:d(u.label),title:e.title}),className:"grid min-w-0 flex-1 grid-cols-[1.6rem_minmax(0,1fr)_auto] items-center gap-1.5 px-2 text-left outline-none transition-colors enabled:cursor-pointer enabled:hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-default",children:[(0,n.jsx)("span",{className:(0,C.cn)("grid size-6 place-items-center rounded-md",u.icon),children:(0,n.jsx)(hU,{level:e.level})}),(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium leading-5 text-foreground",children:e.title}),e.description?(0,n.jsx)("span",{className:"block truncate text-xs leading-5 text-muted-foreground",children:e.description}):null]}),!s&&t&&r>0?(0,n.jsxs)("span",{className:"px-1 text-xs tabular-nums text-muted-foreground",children:["+",r]}):null]}),s&&t&&r>0?(0,n.jsx)("button",{"data-testid":"app-notification-more",type:"button",disabled:i,onClick:o,"aria-label":d("olderNotices",{count:r}),className:"mr-1 grid size-7 shrink-0 place-items-center self-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50",children:(0,n.jsx)(H.A,{className:"size-4"})}):null,c?(0,n.jsx)("button",{type:"button",disabled:i,onClick:l,"aria-label":d("deleteNotice",{title:e.title}),title:d("dismissNotice"),className:(0,C.cn)("mr-1 grid size-7 shrink-0 place-items-center self-center rounded-md text-muted-foreground outline-none transition-[background-color,color,opacity] hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50",!s&&"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),children:(0,n.jsx)(V.A,{className:"size-3.5"})}):null]})}function hK({mobile:e,notifications:t,onConsume:s,onDismiss:i}){let a=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useRef)(null),c=(0,r.useRef)(null),[d,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),h=t.at(-1)??null,g=t.slice(0,-1),f=g.length>0,x=d&&f,b=64+60*Math.min(g.length,5)+8,v=(0,r.useCallback)(()=>{o.current&&clearTimeout(o.current),o.current=null},[]),w=(0,r.useCallback)(()=>{c.current&&clearTimeout(c.current),c.current=null},[]),y=(0,r.useCallback)(()=>{v(),w(),f&&u(!0)},[f,w,v]),k=(0,r.useCallback)(()=>{v(),w(),u(!1)},[w,v]),j=(0,r.useCallback)(()=>{!e&&f&&(w(),v(),o.current=setTimeout(y,120))},[f,w,v,e,y]),N=(0,r.useCallback)(()=>{e||(v(),w(),c.current=setTimeout(k,180))},[w,v,k,e]);(0,r.useEffect)(()=>{if(!x)return;let e=l.current;e&&(e.scrollTop=e.scrollHeight)},[g.length,x]),(0,r.useEffect)(()=>{if(!e||!x)return;let t=e=>{a.current?.contains(e.target)||k()},s=e=>{"Escape"===e.key&&k()};return document.addEventListener("pointerdown",t),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",t),document.removeEventListener("keydown",s)}},[k,e,x]),(0,r.useEffect)(()=>()=>{v(),w()},[w,v]);let I=(0,r.useCallback)(async e=>{if(e.event&&!m){p(e.notificationId),u(!1);try{await s(e)}finally{p(null)}}},[m,s]),S=(0,r.useCallback)(async e=>{if(!m){p(e);try{await i(e)}finally{p(null)}}},[m,i]);return h?(0,n.jsx)("div",{"data-testid":"app-notification-slot",className:"relative z-20 h-16 shrink-0",children:(0,n.jsxs)("div",{ref:a,"data-testid":"app-notification-panel","data-expanded":x?"true":"false",onPointerEnter:e=>{"mouse"===e.pointerType&&j()},onPointerLeave:e=>{"mouse"===e.pointerType&&N()},onFocus:()=>{e||y()},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||N()},className:(0,C.cn)("absolute inset-x-0 bottom-0 flex max-h-[calc(100dvh-8rem)] flex-col overflow-hidden bg-sidebar text-sidebar-foreground transition-[height,box-shadow] duration-150 ease-out motion-reduce:transition-none",x&&"shadow-lg duration-200"),style:{height:x?b:64},children:[(0,n.jsx)("div",{ref:l,className:(0,C.cn)("pi-desk-chat-scrollbar absolute inset-x-0 bottom-16 top-0 space-y-1 overflow-y-auto px-2 pt-2",!x&&"invisible"),children:g.map(t=>(0,n.jsx)(hH,{notification:t,latest:!1,mobile:e,moreCount:0,busy:null!==m,onConsume:()=>void I(t),onDismiss:()=>void S(t.notificationId),onToggleMore:()=>void 0,showDismiss:!0},t.notificationId))}),(0,n.jsx)("div",{className:"absolute inset-x-0 bottom-0 h-16 px-2 py-1",children:(0,n.jsx)(hH,{notification:h,latest:!0,mobile:e,moreCount:g.length,busy:null!==m,onConsume:()=>void I(h),onDismiss:()=>void S(h.notificationId),onToggleMore:()=>u(e=>!e),showDismiss:!e||0===g.length||x})})]})}):null}function hG(e,t){return Math.max(0,Math.floor((t-e)/6e4))}let hJ=null;function hQ(e,t){let s=t.formatToParts(e),n=e=>Number(s.find(t=>t.type===e)?.value);return Date.UTC(n("year"),n("month")-1,n("day"))}var hX=s(20314),hZ=s.n(hX);function h0(e,t){return`plugin:${e}:${t}`}let h1=[[5,3],[11,3],[5,8],[11,8],[5,13],[11,13]],h2=(0,C.cn)((0,I.r)({variant:"ghost"}),hZ().sidebarAction,"relative h-[3.25rem] max-w-24 min-w-0 flex-1 flex-col gap-1 whitespace-normal px-1 text-xs font-normal text-muted-foreground"),h5=(0,I.r)({variant:"ghost",size:"icon"}),h3=(0,C.cn)((0,I.r)({variant:"ghost",size:"icon"}),hZ().sidebarAction,"text-muted-foreground");function h4({items:e,appearance:t,label:s,className:r}){let{t:i}=(0,b.Bd)("workbench"),a="action"===t&&e.length>3?e.slice(2):[],l=a.length>0?e.slice(0,2):e;return(0,n.jsxs)("div",{className:(0,C.cn)("flex min-w-0 items-center gap-0",r),role:"group","aria-label":s,children:[l.map(e=>{var s,r;return(0,n.jsx)("button",{"data-testid":e.testId,type:"button",disabled:e.disabled,"aria-pressed":e.pressed,"aria-busy":e.busy||void 0,"aria-label":"mode"===t?i("showSidebarMode",{name:e.label}):e.label,title:e.label,onClick:e.onSelect,className:(s=!0===e.pressed,r=!0===e.busy,"mode"===t?(0,C.cn)(h5,s?"bg-accent text-accent-foreground":(0,C.cn)(hZ().sidebarAction,"text-muted-foreground")):(0,C.cn)(h3,s&&"bg-muted text-foreground",r?"disabled:cursor-wait":"disabled:cursor-not-allowed")),children:(0,n.jsx)("span",{className:(0,C.cn)("flex shrink-0","mode"===t?"[&_svg]:size-5":"[&_svg]:size-4"),children:e.icon})},e.key)}),a.length>0?(0,n.jsxs)(K.rI,{children:[(0,n.jsx)(K.ty,{render:(0,n.jsx)("button",{type:"button","aria-label":s,title:s,className:h3,children:(0,n.jsx)(H.A,{className:"size-4"})})}),(0,n.jsx)(K.SQ,{align:"end",children:a.map(e=>(0,n.jsxs)(K._2,{disabled:e.disabled,onClick:e.onSelect,children:[(0,n.jsx)("span",{className:"shrink-0 [&_svg]:size-4",children:e.icon}),e.label]},e.key))})]}):null]})}function h6({modeItems:e,actionItems:t}){let{t:s}=(0,b.Bd)("workbench");return(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 px-2",children:[(0,n.jsx)(h4,{items:e,appearance:"mode",label:s("sidebarContents"),className:"max-w-full overflow-x-auto rounded-lg p-0.5 dark:bg-muted"}),t.length>0?(0,n.jsx)(h4,{items:t,appearance:"action",label:s("sidebarActions"),className:"ml-auto shrink-0"}):null]})}function h8(){return(0,n.jsx)("svg",{className:"block size-full",viewBox:"0 0 16 16","aria-hidden":"true",children:h1.map(([e,t])=>(0,n.jsx)("circle",{cx:e,cy:t,r:"1.15",fill:"currentColor"},`${e}-${t}`))})}let h7=(0,r.memo)(function({workSession:e,mobile:t,selected:s,pinned:i,deleting:a,disabled:l,ordering:o,now:c,onSelect:d,onTogglePin:u,onDelete:m,onRename:p,syncing:h,onReloadChat:g}){var f,x;let w=(0,r.useRef)(!1),y=(0,r.useRef)(""),k=l||o,{attributes:j,listeners:N,setNodeRef:S,setActivatorNodeRef:E,transform:M,transition:z,isDragging:A}=(0,iR.gl)({id:e.workId,disabled:k}),$=(0,X.G)(),{t:R}=(0,b.Bd)("workbench"),{locale:P,timeZone:D}=(0,eQ.i)(),T=R(function(e){switch(e.status){case"main_running":return"mainRunning";case"background_running":return"backgroundRunning";case"completed":return"completedUnread";case"idle":return"idle"}}(e)),O=e.sessionTitle??R("newSession"),L=`${e.messageCounts.user}/${e.messageCounts.total}`,F=function(e,t,s="en",n="UTC"){let r=function(e,t){if(null===e||null===t)return"old";let s=hG(e,t);return s<5?"fresh":s<60?"recent":"old"}(e,t);if(null===e)return{compact:"--",title:"en"===s?"No messages yet":"暂无消息时间",tone:r};let i=function(e,t){if(hJ?.locale===e&&hJ.timeZone===t)return hJ;let s="en"===e?"en-US":"zh-CN";return hJ={locale:e,timeZone:t,title:new Intl.DateTimeFormat(s,{timeZone:t,timeZoneName:"shortOffset",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),dateKey:new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"numeric",day:"numeric"}),compact:new Intl.DateTimeFormat(s,{timeZone:t,month:"short",day:"numeric"})}}(s,n),a=i.title.format(e);if(null===t)return{compact:a,title:a,tone:r};let l=hG(e,t);if(l<1)return{compact:"en"===s?"Just now":"刚刚",title:a,tone:r};if(l<60)return{compact:"en"===s?`${l} min ago`:`${l} 分钟前`,title:a,tone:r};let o=Math.floor(l/60);if(o<24)return{compact:"en"===s?`${o} hr ago`:`${o} 小时前`,title:a,tone:r};let c=(hQ(t,i.dateKey)-hQ(e,i.dateKey))/864e5;return 1===c?{compact:"en"===s?"Yesterday":"昨天",title:a,tone:r}:2===c?{compact:"en"===s?"2 days ago":"前天",title:a,tone:r}:{compact:i.compact.format(e),title:a,tone:r}}(e.lastMessageUpdatedAt,c,P,D),B="main_running"===e.status||"background_running"===e.status,q=(f=e.cwd,{className:hW().surface,style:hY(f)}),_=(x=e.cwd,{className:hW().identity,style:hY(x)}),W=M?`translate3d(${M.x}px, ${M.y}px, 0)`:void 0,Y=(0,r.useCallback)(()=>d(e.workId),[d,e.workId]),V=(0,r.useCallback)(()=>u(e.workId),[u,e.workId]),U=(0,r.useCallback)(()=>m(e.workId),[m,e.workId]),H=(0,r.useCallback)(()=>{(0,e9.x)(e.cwd).then(e=>{e?$.success(R("copiedProjectPath")):$.error(R("copyProjectPathFailed"))})},[$,e.cwd,R]),K=(0,n.jsxs)("div",{ref:S,"data-testid":`work-session-row-${e.workId}`,"data-dragging":A?"true":void 0,role:"button",tabIndex:0,"aria-pressed":s,onClick:Y,onKeyDown:e=>{e.target===e.currentTarget&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),Y())},className:(0,C.cn)(q.className,hZ().sessionRow,!t&&hZ().desktopRow,"grid min-h-15 min-w-0 cursor-pointer grid-cols-[1.75rem_minmax(0,1fr)] items-center rounded-lg border border-transparent px-1 py-0.5 outline-none transition-[background-color,opacity] duration-150 ease-out focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",s?"text-accent-foreground":"hover:text-foreground","completed"===e.status&&"border-[var(--pi-desk-project-color)]",A&&"cursor-grabbing opacity-30"),style:{...q.style,transform:W,transition:z},children:[B?(0,n.jsx)("svg",{"aria-hidden":"true",focusable:"false","data-testid":"work-session-running-border",className:hZ().runningBorder,children:(0,n.jsx)("rect",{x:"0.5",y:"0.5"})}):null,(0,n.jsx)("button",{ref:E,"data-testid":`work-session-drag-${e.workId}`,type:"button",...j,...N,onTouchStart:e=>{N?.onTouchStart?.(e),e.stopPropagation()},onContextMenu:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>e.stopPropagation(),disabled:k,"aria-label":R("dragSession",{name:O}),title:`${T} \xb7 ${R("dragOrder")}`,className:(0,C.cn)(_.className,"flex size-7 touch-none cursor-grab items-center justify-center outline-none transition-[color,filter] hover:brightness-125 active:cursor-grabbing focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none",l&&"opacity-50"),children:(0,n.jsx)("span",{className:"size-4",children:(0,n.jsx)(h8,{})})}),(0,n.jsxs)("div",{className:"min-w-0 py-0.5",children:[(0,n.jsx)("span",{className:"sr-only",children:T}),(0,n.jsxs)("div",{className:"flex min-w-0 items-center justify-between gap-1",children:[(0,n.jsx)("p",{className:(0,C.cn)(_.className,"truncate text-xs font-medium"),title:e.projectName,children:e.projectName}),(0,n.jsxs)("span",{className:(0,C.cn)(hZ().rowMetadata,"flex shrink-0 items-center gap-1 whitespace-nowrap text-xs leading-4 text-muted-foreground"),title:R("sessionMessages",{count:L,time:F.title}),children:[(0,n.jsx)("span",{children:L}),(0,n.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,n.jsx)("span",{className:(0,C.cn)("transition-colors","fresh"===F.tone&&"dark:text-sidebar-primary"),children:F.compact})]})]}),(0,n.jsxs)("div",{className:"relative flex min-h-7 min-w-0 items-center",children:[(0,n.jsx)("p",{className:(0,C.cn)(hZ().rowTitle,"min-w-0 flex-1 truncate pr-1 text-sm",s?"font-semibold":"font-medium"),title:O,children:O}),(0,n.jsxs)("div",{className:(0,C.cn)(hZ().rowActions,"flex shrink-0 items-center"),children:[(0,n.jsx)("button",{"data-testid":`work-session-pin-${e.workId}`,type:"button",onClick:e=>{e.stopPropagation(),V()},disabled:k,"aria-label":R(i?"unpinSession":"pinSession",{name:O}),title:R(i?"unpin":"pin"),className:(0,C.cn)((0,I.r)({variant:"ghost",size:"icon-sm"}),"text-muted-foreground",i&&_.className),children:i?(0,n.jsx)(hT.A,{className:"size-4"}):(0,n.jsx)(rc.A,{className:"size-4"})}),(0,n.jsx)("button",{"data-testid":`work-session-delete-${e.workId}`,type:"button",disabled:k||a,onClick:e=>{e.stopPropagation(),U()},"aria-label":R("deleteSession",{name:O}),title:R("deleteSessionTitle"),className:(0,C.cn)((0,I.r)({variant:"ghost",size:"icon-sm"}),"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"),children:(0,n.jsx)(et.A,{className:"size-4"})})]})]})]})]});return(0,n.jsxs)(hq.tz,{onOpenChange:(e,t)=>{e&&("touch"===y.current||t.event.type.startsWith("touch"))&&(w.current=!0)},children:[(0,n.jsx)(hq.Rc,{render:K,onPointerDown:e=>{y.current=e.pointerType,w.current=!1},onTouchEndCapture:e=>{w.current&&e.cancelable&&e.preventDefault()},onClickCapture:e=>{w.current&&(e.preventDefault(),e.stopPropagation(),w.current=!1)},onKeyDownCapture:e=>{if(e.target!==e.currentTarget||e.nativeEvent.isComposing||(y.current="keyboard",w.current=!1,"ContextMenu"!==e.key&&!("F10"===e.key&&e.shiftKey)))return;e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getBoundingClientRect();e.currentTarget.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,button:2,clientX:t.left+t.width/2,clientY:t.top+t.height/2}))}}),(0,n.jsxs)(hq.Ip,{children:[(0,n.jsxs)(hq.kt,{"data-testid":`work-session-rename-${e.workId}`,disabled:k||a,onClick:()=>p(e),children:[(0,n.jsx)(hO.A,{}),R("renameSessionTitle")]}),(0,n.jsxs)(hq.kt,{"data-testid":`work-session-reload-chat-${e.workId}`,disabled:k||a||h,onClick:()=>g(e),children:[h?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(es.A,{}),R("reloadChatData")]}),(0,n.jsxs)(hq.kt,{"data-testid":`work-session-copy-project-path-${e.workId}`,onClick:H,children:[(0,n.jsx)(ee.A,{}),R("copyProjectPath")]})]})]})});function h9({id:e,label:t}){let{setNodeRef:s,transform:r,transition:i}=(0,iR.gl)({id:e,disabled:{draggable:!0}}),a=r?`translate3d(${r.x}px, ${r.y}px, 0) scaleX(${r.scaleX??1}) scaleY(${r.scaleY??1})`:void 0;return(0,n.jsxs)("div",{ref:s,"data-testid":e,"aria-hidden":"true",className:"pointer-events-none flex h-5 items-center gap-2 px-1 text-xs text-muted-foreground",style:{transform:a,transition:i},children:[(0,n.jsx)("span",{className:"h-px flex-1 bg-border/75"}),(0,n.jsx)("span",{children:t}),(0,n.jsx)("span",{className:"h-px flex-1 bg-border/75"})]})}let ge=(0,r.memo)(function({mode:e,mobile:t,fileBrowser:s,pluginTabContent:i,pluginHeaderActions:a=[],pluginSessionTabs:l,fileRefreshLoading:o,canBrowseFiles:c,workSessions:d,focusedWorkId:u,pinnedCount:m,ordering:p,deletingWorkId:h,canReplace:g,disabled:f,pluginApplications:x,settingsAttention:y,notifications:k,onConsumeNotification:j,onDismissNotification:N,onModeChange:I,onRefreshFiles:S,onPreviewProject:E,onPreviewProjectWindow:M,onOpenTerminal:z,onCreate:A,onReplace:$,onSettings:R,onOpenPluginApplication:P,onSelect:D,onTogglePin:T,onDelete:O,onRename:L,syncingWorkIds:F,onReloadChat:B,onArrangementChange:q}){let{t:_}=(0,b.Bd)("workbench"),[W,Y]=(0,r.useState)(null),V=(0,r.useRef)(null),G=(0,r.useRef)(3),[J,Q]=(0,r.useState)(3),X=(0,i$.FR)((0,i$.MS)(i$.cA,{activationConstraint:{distance:6}}),(0,i$.MS)(i$.IG,{activationConstraint:{delay:250,tolerance:8}}),(0,i$.MS)(i$.uN,{coordinateGetter:iR.JR}));(0,r.useEffect)(()=>{let e=()=>Y(Date.now());e();let t=window.setInterval(e,6e4);return()=>window.clearInterval(t)},[]);let Z=[{key:"sessions",label:_("sidebarSessions"),icon:(0,n.jsx)(m$.A,{}),pressed:"sessions"===e,testId:"sidebar-mode-sessions",onSelect:()=>I("sessions")},{key:"files",label:_("sidebarFiles"),icon:(0,n.jsx)(sY.A,{}),pressed:"files"===e,testId:"sidebar-mode-files",onSelect:()=>I("files")},...l.map(t=>{let s=h0(t.pluginName,t.contributionName);return{key:`${t.pluginName}:${t.contributionName}`,label:t.label,icon:(0,n.jsx)(eq,{icon:t.icon}),disabled:!c,pressed:e===s,onSelect:()=>I(s)}})],ee="sessions"===e?[{key:"replace",label:_("sidebarReplaceSession"),disabled:f||!g,busy:f,testId:"sidebar-replace-work-session",icon:(0,n.jsx)(hL.A,{}),onSelect:$},{key:"create",label:_("createSession"),disabled:f,busy:f,testId:"sidebar-create-work-session",icon:(0,n.jsx)(U.A,{}),onSelect:A}]:"files"===e?[{key:"preview-project",label:_("projectPreview"),disabled:!c,icon:(0,n.jsx)(hF.A,{}),testId:"project-preview-open",onSelect:E},{key:"preview-project-window",label:_("projectPreviewWindow"),disabled:!c,icon:(0,n.jsx)(oq.A,{}),testId:"project-preview-window-open",onSelect:M},{key:"new-terminal",label:_("newTerminal"),disabled:f,icon:(0,n.jsx)(w.A,{}),testId:"project-files-terminal-open",onSelect:z},{key:"refresh-files",label:_("refreshFiles"),disabled:!c||o,icon:o?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(es.A,{}),busy:o,testId:"project-files-refresh",onSelect:S}]:a.map((e,t)=>({key:String(t),label:e.label,icon:e.busy?(0,n.jsx)(v.A,{className:"animate-spin"}):(0,n.jsx)(eq,{icon:e.icon}),disabled:e.disabled||e.busy,busy:e.busy,onSelect:()=>{e.onSelect()}}));(0,r.useLayoutEffect)(()=>{let e=V.current;if(!e)return;let t=e=>{let t=Math.max(1,Math.floor(e/56));G.current!==t&&(G.current=t,Q(t))};t(e.clientWidth);let s=new ResizeObserver(([s])=>{t(s?.contentRect.width??e.clientWidth)});return s.observe(e),()=>s.disconnect()},[]);let et=(0,r.useMemo)(()=>d.map(e=>e.workId),[d]),en=(0,r.useMemo)(()=>hS(et,m),[m,et]),er=(0,r.useMemo)(()=>new Map(d.map(e=>[e.workId,e])),[d]),ei=(0,r.useMemo)(()=>new Set(et.slice(0,m)),[m,et]),{visiblePluginApplications:ea,overflowPluginApplications:el,shortcutRowItemCounts:eo}=(0,r.useMemo)(()=>{var e;let s,n,r,i,a,l,o,c=t?2:3,d=(e=x.length,a=Math.ceil((i=(r=(n=e+1>(s=J*c))?Math.max(0,s-2):e)+1+ +!!n)/J),l=Math.floor(i/a),o=i%a,{visibleApplicationCount:r,rowItemCounts:Array.from({length:a},(e,t)=>l+ +(t<o))});return{visiblePluginApplications:x.slice(0,d.visibleApplicationCount),overflowPluginApplications:x.slice(d.visibleApplicationCount),shortcutRowItemCounts:d.rowItemCounts}},[t,x,J]),ec=(0,r.useCallback)(e=>{if(p||!e.over||e.active.id===e.over.id)return;let t=String(e.active.id),s=function(e,t,s,n){if(hE(e,t),s===n||s===hI)return null;let r=hS(e,t),i=r.indexOf(s),a=r.indexOf(n);if(i<0||a<0)return null;if(0>r.indexOf(hI))return{workIds:hC(r,i,a),pinnedCount:t};let l=e.indexOf(s)<t,o=n===hI?function(e,t,s){let n=[...e],[r]=n.splice(t,1);if(!r)return n;let i=n.indexOf(hI);return i<0?[...e]:(n.splice(s?i:i+1,0,r),n)}(r,i,l):hC(r,i,a),c=o.indexOf(hI);if(c<0)return null;let d=o.slice(0,c),u=o.slice(c+1),m=[...u,...d];return m.length!==e.length||new Set(m).size!==e.length?null:{workIds:m,pinnedCount:u.length}}(et,m,t,String(e.over.id));s&&q(s,t)},[q,p,m,et]),ed=en.map(e=>{if(e===hI)return(0,n.jsx)(h9,{id:e,label:_("pinnedBelow")},e);let s=er.get(e);return s?(0,n.jsx)(h7,{workSession:s,mobile:t,selected:s.workId===u,pinned:ei.has(s.workId),deleting:h===s.workId,disabled:f,ordering:p,now:W,onSelect:D,onTogglePin:T,onDelete:O,onRename:L,syncing:F.includes(s.workId),onReloadChat:B},s.workId):null}),eu=[(0,n.jsxs)("button",{type:"button",title:_("settings"),"aria-label":_("error"===y?"settingsWarning":"settings"),onClick:R,className:h2,children:[(0,n.jsx)(ez.A,{className:"size-5 shrink-0"}),(0,n.jsx)("span",{className:"w-full truncate text-center",children:_("settings")}),y?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute right-1.5 top-1.5 size-2 rounded-full ring-2 ring-sidebar","error"===y?"bg-destructive":"bg-primary")}):null]},"settings"),...ea.map(e=>(0,n.jsxs)("button",{type:"button",disabled:f,title:e.label,onClick:()=>P(e),className:h2,children:[(0,n.jsx)(eq,{icon:e.icon,className:"size-5 shrink-0"}),(0,n.jsx)("span",{className:"w-full line-clamp-2 break-words text-center leading-4",children:e.label})]},`${e.pluginName}:${e.contributionName}`))];el.length>0&&eu.push((0,n.jsxs)(K.rI,{children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)("button",{type:"button",disabled:f,title:_("more"),"aria-label":_("moreShortcuts"),className:h2}),children:[(0,n.jsx)(H.A,{className:"size-5 shrink-0"}),(0,n.jsx)("span",{className:"w-full truncate text-center",children:_("more")})]}),(0,n.jsx)(K.SQ,{align:"end",side:"top",className:"w-56",children:el.map(e=>(0,n.jsxs)(K._2,{disabled:f,onClick:()=>P(e),className:"py-2",children:[(0,n.jsx)(eq,{icon:e.icon,className:"size-4"}),(0,n.jsx)("span",{className:"min-w-0 truncate",children:e.label})]},`${e.pluginName}:${e.contributionName}`))})]},"more"));let em=eo.map((e,t)=>{let s=eo.slice(0,t).reduce((e,t)=>e+t,0);return(0,n.jsx)("div",{className:"flex justify-evenly",children:eu.slice(s,s+e)},`shortcut-row:${s}`)});return(0,n.jsxs)("aside",{className:"flex h-full w-full min-w-0 flex-col bg-sidebar text-sidebar-foreground",children:[(0,n.jsx)(h6,{modeItems:Z,actionItems:ee}),(0,n.jsx)(hB.V,{"data-testid":"work-session-list",className:(0,C.cn)("min-h-0 flex-1","sessions"!==e&&"hidden"),viewportClassName:"p-2 data-[has-overflow-y]:pr-4",children:0===d.length?(0,n.jsx)("p",{className:"px-2 py-5 text-center text-sm leading-6 text-muted-foreground",children:_("noSessions")}):(0,n.jsx)(i$.Mp,{sensors:X,collisionDetection:i$.fp,onDragEnd:ec,children:(0,n.jsx)(iR.gB,{items:en,strategy:iR._G,children:(0,n.jsx)("div",{className:"flex flex-col gap-1",children:ed})})})}),(0,n.jsx)("div",{className:(0,C.cn)("min-h-0 flex-1 overflow-hidden","files"!==e&&"hidden"),children:s??(0,n.jsx)("div",{className:"flex h-full items-center justify-center p-5 text-center text-sm text-muted-foreground",children:_("selectSessionFirst")})}),e.startsWith("plugin:")?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:i}):null,(0,n.jsx)(hK,{mobile:t,notifications:k,onConsume:j,onDismiss:N}),(0,n.jsx)("footer",{"data-testid":"sidebar-shortcuts",className:"shrink-0 px-2 py-1.5","aria-label":_("shortcuts"),children:(0,n.jsx)("div",{ref:V,className:"flex flex-col gap-1",children:em})})]})});ge.displayName="L2WorkSessionSidebar";let gt={primaryWorkId:null},gs={mode:"normal",notifications:[],plugins:{},capabilityModes:{},settings:{region:{locale:"en",timeZone:"UTC"}}};function gn(e){let t=window.matchMedia("(max-width: 1023px)");return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function gr(){return window.matchMedia("(max-width: 1023px)").matches}function gi(e,t){return e instanceof Error?e.message:t}function ga(e){let t=r9.N$.safeParse(e);return t.success?t.data.directories:null}function gl(e){let t=r9.rn.safeParse(e);return t.success?t.data:null}function go({render:e,input:t}){return e(t)}function gc({onTerminalReady:e,onTerminalDisconnected:t,onOpenTerminal:s,onOpenProjectPreviewWindow:i,renderTerminalWorkspace:a,listPluginManagement:o,subscribePluginManagementChanges:c,onTaskCenterStart:d,onTaskCenterDispose:u,onTaskCenterReconcileWorkSessions:m,onTaskCenterDisconnected:p,onTaskCenterReconnected:h,renderPluginApplication:g,renderPluginSessionSidebarTab:f,renderSettings:x,renderTaskSummary:v,renderTaskMenu:w,renderPluginComposerPanel:y,renderPluginWidgets:k,renderPluginSessionHeader:j}){var N;let{t:S}=(0,b.Bd)("workbench"),{clientId:C,appSocket:E}=(0,ei.gM)(),M=(0,X.G)(),z=(0,Q.t4)(),A=(0,Q.So)(),$=(0,r.useMemo)(()=>(function(e,t){async function s(t,n,r,i="POST"){let a=await fetch(t,{method:i,..."GET"===i?{cache:"no-store"}:{},headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},...void 0===n?{}:{body:JSON.stringify(n)},...r?{signal:r}:{}}),l=await a.json();if(!a.ok||0!==l.code||null===l.data)throw Error(l.msg?(0,ed.B)(l):"请求失败");return l.data}return{async readServerVersion(e){let t=await s("/api/health",void 0,e,"GET");return dO.parse(t).version},getChatMessageDetail:e=>s("/api/chat/messages/get",e),getChatModelContext:e=>s("/api/chat/context/get",e),getChatImage:e=>s("/api/chat/images/get",e),listModels:e=>s("/api/pi/models/list",e),listPiCommands:e=>t.request(dq.QV.commandsList,e),listPiTools:e=>t.request(dq.QV.toolsList,e),sendChat:e=>t.request(dL.P6.send,e),async interruptChat(e){await t.request(dL.P6.interrupt,e)},restoreChatQueue:e=>t.request(dL.P6.queueRestore,e),async setChatModel(e){await t.request(dL.P6.modelSet,e)},async setChatCapabilityMode(e){await t.request(dL.P6.capabilityModeSet,e)},invokePluginMethod:e=>t.request(dF.OY.invoke,e),listWorkSessions:()=>t.request(dB.kM.list,{}),async applyAppRuntimeUpdate(e){await t.request(nH.apply,e)},sortWorkSessions:e=>s("/api/work-sessions/sort",e),deleteWorkSession:e=>s("/api/work-sessions/del",{workId:e}),async renameWorkSession(e){await s("/api/work-sessions/rename",e)},async listDirectories(e){let t=await s("/api/pi/directories/list",{forceRefresh:e});return ip(t),t},async listIgnoredDirectories(e){let t=await s("/api/pi/directory-ignores/list",{forceRefresh:e});return iu(),ia=t,im(it,t),t},async replaceDirectoryIgnore(e){await s("/api/pi/directory-ignores/replace",e)},async listDirectoryEntries(e){let t=await s("/api/pi/directory-entries/list",{cwd:e});return!function(e){let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.cwd;if("string"==typeof t||null===t)return t}(e);if(void 0===t)return;ih();let s=ic(t);for(io.delete(s),io.set(s,e);io.size>64;){let e=io.keys().next().value;if(void 0===e)break;io.delete(e)}im(is,{entries:Object.fromEntries(io)})}(t),t},listSessionHistory:(e,t)=>s("/api/pi/sessions/list",e,t),listSessionUserMessages:(e,t)=>s("/api/pi/session-user-messages/list",e,t),createWorkSession:e=>s("/api/work-sessions/add",e),replaceWorkSession:e=>s("/api/work-sessions/replace",e),getWorkSessionTree:(e,t)=>s("/api/work-session-tree/get",e,t),getWorkSessionTreeEntry:(e,t)=>s("/api/work-session-tree-entry/get",e,t),branchWorkSession:e=>s("/api/work-sessions/branch",e),async acknowledgeCompleted(e){await t.request(dB.kM.acknowledgeCompleted,{workId:e})},async readWorkSessionUpdates(s,n,r,i){let a=t.subscribe(dB.kM.update,r),o=t.subscribe(nH.update,i),c=()=>void 0,d=new Promise(e=>{let t=()=>e({code:1e3,reason:"页面业务已卸载"});s.addEventListener("abort",t,{once:!0}),c=()=>s.removeEventListener("abort",t)});try{let e=await t.connect(s);if(s.aborted)return await d;let r=await t.request(dB.kM.list,{});if(s.aborted)return await d;await n(r,e);let i=await Promise.race([t.waitForClose(),d]);return s.aborted||i.code!==l.Sp||window.location.replace("/login"),i}catch(t){if(!s.aborted){let t=await fetch("/api/auth-settings/get",{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:"{}",signal:s}).catch(()=>null);t?.status===401&&window.location.replace("/login")}throw t}finally{c(),o(),a()}}}})(C,E),[E,C]),R=(0,r.useMemo)(()=>{var e,t;let s,n,r;return e=$.readServerVersion,t=()=>{window.location.reload()},s=!1,n=null,r=!1,async(i,a,l)=>{if(a.aborted)return;let o=s&&i;if(s=!0,!o||r)return;n?.abort();let c=new AbortController;n=c;let d=()=>c.abort();a.addEventListener("abort",d,{once:!0}),l.then(d,d);let u=setTimeout(d,5e3);try{let s=await e(c.signal);if(c.signal.aborted||!s||s===sU||r)return;r=!0,t()}catch(e){c.signal.aborted||console.warn("[Pi Desk][VersionRefresh] 重连版本检查失败,保留当前页面",{message:e instanceof Error?e.message:String(e)})}finally{clearTimeout(u),a.removeEventListener("abort",d),n===c&&(n=null)}}},[$]),P=(0,r.useRef)([]),D=(0,r.useRef)(0),T=(0,r.useRef)(gs),O=(0,r.useRef)(!1),L=(0,r.useRef)(null),F=(0,r.useRef)(0),B=(0,r.useRef)(!0),q=(0,r.useRef)(new Set),_=(0,r.useRef)(new Set),W=(0,r.useSyncExternalStore)(gn,gr,()=>!0),Y=(0,r.useSyncExternalStore)(ry,rv,rv),V=(0,r.useMemo)(()=>({list:(e,t)=>(0,ur.QL)(C,dI.Xe,dM.parse(e),t),search:(e,t)=>(0,ur.QL)(C,dI.fg,dz.parse(e),t),get:(e,t)=>(0,ur.QL)(C,dI.ZI,dR.parse(e),t),reveal:e=>(0,ur.QL)(C,dI.Ot,dA.parse(e))}),[C]),U=(0,r.useMemo)(()=>(function(e){async function t(t,s,n,r){let i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s),signal:r}),a=await i.json();if(!i.ok||0!==a.code||null===a.data)throw Error(a.msg?(0,ed.B)(a):"Git 请求失败");return n.parse(a.data)}return{getHeads:(t,s)=>(0,ur.QL)(e,dI._X,t,s),get:(t,s)=>(0,ur.QL)(e,dI.p0,{...ux.parse(t),refresh:!0},s),listBranches:async(t,s)=>{let{head:n,recent:r,local:i,remote:a}=await (0,ur.QL)(e,dI.ry,uk.parse(t),s);return{head:n,recent:r,local:i,remote:a}},replaceBranch:(e,s)=>t("/api/work-session-git-branch/replace",uN.parse(e),uS,s),addBranch:(e,s)=>t("/api/work-session-git-branch/add",uI.parse(e),uS,s),getDiff:async(t,s)=>{let n=await (0,ur.QL)(e,dI.OC,uC.parse(t),s);return"metadata"===n.kind?{kind:"binary"}:n}}})(C),[C]),[H]=(0,r.useState)(()=>new dG(V,U,e=>{M.show({level:"info",title:e})})),[K]=(0,r.useState)(()=>new uh(U,(e,t)=>{H.handleGitBranchChanged(e,t)}));(0,r.useSyncExternalStore)(H.subscribe.bind(H),H.getRevision,H.getRevision);let[G,J]=(0,r.useState)([]),[Z,ee]=(0,r.useState)(0),[et,es]=(0,r.useState)(gs),[en,er]=(0,r.useState)(gt),[ea,el]=(0,r.useState)(!1),[eo,ec]=(0,r.useState)(null),[eu,em]=(0,r.useState)(!0),[ep,eh]=(0,r.useState)(!1),eg=(0,r.useRef)(ep);(0,r.useEffect)(()=>{eg.current=ep},[ep]);let ef=(0,r.useCallback)(()=>{eg.current=!1,eh(!1)},[]),[ex,eb]=(0,r.useState)("sessions"),[ev,ew]=(0,r.useState)(null),[ey,ek]=(0,r.useState)(!1),[ej,eN]=(0,r.useState)(!1),[eI,eS]=(0,r.useState)(),[eC,eE]=(0,r.useState)(null),[eM,ez]=(0,r.useState)(null),[eA,e$]=(0,r.useState)(null),[eR,eP]=(0,r.useState)(null),[eD,eT]=(0,r.useState)(null),eO=(0,r.useCallback)(()=>{e$(null)},[]),[eL,eF]=(0,r.useState)("initial"),eB="ready"!==eL,eq=function(e,t){let{t:s}=(0,b.Bd)("workbench"),[n,i]=(0,r.useState)(null),[a,l]=(0,r.useState)(""),[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(null),m=(0,r.useCallback)(e=>{i({workId:e.workId,sessionId:e.sessionId}),l(e.sessionTitle??""),u(null)},[]),p=async()=>{let r=a.trim();if(n&&!o&&!t&&r){c(!0),u(null);try{await e.renameWorkSession({...n,title:r}),i(null)}catch(e){u(e instanceof Error?e.message:s("renameSessionFailed"))}finally{c(!1)}}};return{open:null!==n,title:a,saving:o,error:d,show:m,close:()=>{o||i(null)},setTitle:l,save:p}}($,eB),[e_,eW]=(0,r.useState)(!1),[eY,eV]=(0,r.useState)(null),[eU,eH]=(0,r.useState)(!1),[eK,eG]=(0,r.useState)(null),[eJ,eQ]=(0,r.useState)("directories"),[eX,eZ]=(0,r.useState)(null),[e0,e1]=(0,r.useState)(null),[e2,e5]=(0,r.useState)([]),[e3,e4]=(0,r.useState)([]),[e6,e8]=(0,r.useState)(null),[e7,e9]=(0,r.useState)(!1),[te,tt]=(0,r.useState)(!1),[ts,tn]=(0,r.useState)(!1),[tr,ti]=(0,r.useState)(null),[ta,tl]=(0,r.useState)(null),[to,tc]=(0,r.useState)(null),[td,tu]=(0,r.useState)(null),[tm,tp]=(0,r.useState)(null),{sessions:th,loading:tg,load:tf,cancel:tx,showCached:tb}=function(e,t){let{t:s}=(0,b.Bd)("workbench"),[n,i]=(0,r.useState)([]),[a,l]=(0,r.useState)(!1),o=(0,r.useRef)(0),c=(0,r.useRef)(null),d=(0,r.useRef)(new Map);(0,r.useEffect)(()=>()=>{o.current+=1,c.current?.abort(),c.current=null},[]);let u=(0,r.useCallback)(()=>{o.current+=1,c.current?.abort(),c.current=null,l(!1)},[]),m=(0,r.useCallback)(e=>{i(d.current.get(e)?.base??[])},[]);return{sessions:n,loading:a,load:(0,r.useCallback)(async(n,r="",a=hP,u=!1)=>{let m=++o.current;c.current?.abort(),c.current=null;let p=r.trim(),h=d.current.get(n),g=hD(a)&&!p?h?.base:h?.recent?.query===p&&h.recent.searchIn.length===a.length&&h.recent.searchIn.every(e=>a.includes(e))?h.recent.sessions:null;if(g&&!u){i(g),l(!1),t(null);return}g&&i(g);let f=new AbortController;c.current=f,l(!0),t(null);try{let t=await e.listSessionHistory({cwd:n,query:p,forceRefresh:u,searchIn:[...a]},f.signal);if(o.current!==m)return;let s=d.current.get(n)??{base:null,recent:null};for(hD(a)&&!p?s.base=t.sessions:s.recent={query:p,searchIn:[...a],sessions:t.sessions},d.current.delete(n),d.current.set(n,s);d.current.size>8;){let e=d.current.keys().next().value;if(!e)break;d.current.delete(e)}i(t.sessions)}catch(e){if(o.current!==m||e instanceof Error&&"AbortError"===e.name)return;t(e instanceof Error?e.message:s("historyFailed"))}finally{o.current===m&&(c.current===f&&(c.current=null),l(!1))}},[t,e,s]),cancel:u,showCached:m}}($,tp),[tv,tw]=(0,r.useState)(null),[ty,tk]=(0,r.useState)(0),tj=(0,r.useRef)(null),tN=(0,r.useRef)(0),tI=(0,r.useRef)(0),tS=(0,r.useRef)(0),tC=(0,r.useRef)(null),tE=(0,r.useRef)(0),tM=(0,r.useMemo)(()=>(function(e,t,s={async readMessages(e){let t=uE.Pi.parse(e),s=(await uW()).transaction(u$,"readonly"),n=uU(s),r=await uY(s.objectStore(u$).index(uR).getAll(IDBKeyRange.only([t.sessionId,t.branchId])));return await n,r.map(uG).sort((e,t)=>e.location.index-t.location.index)},async readLatestCursor(e){try{let t=await this.readMessages(e),s=uz(t);return null===s&&t.length>0&&await this.clearSource(e),s}catch(t){return console.warn("[Pi Desk][WorkbenchChatRepository] 本地消息缓存无效,回退全量同步",{sessionId:e.sessionId,branchId:e.branchId,errorName:t instanceof Error?t.name:"UnknownError"}),await this.clearSource(e),null}},async replaceMessages(e,t){let s=uE.Pi.parse(e),n=(await uW()).transaction(u$,"readwrite"),r=uU(n),i=n.objectStore(u$);for(let e of(uJ(i,s),t))i.put(uK(s,e));await r},async appendMessage(e,t){let s=uE.Pi.parse(e),n=uK(s,t),r=(await uW()).transaction(u$,"readwrite"),i=uU(r),a=r.objectStore(u$),l=[n.sessionId,n.branchId,n.index],o=a.get(l),c=null;if(o.addEventListener("success",()=>{if(void 0===o.result)return void a.add(n);let e=uH.safeParse(o.result);if(e.success&&e.data.entryId===n.entryId)return;let t=e.success?e.data.entryId:"invalid-record";c=Error(`IndexedDB 消息身份冲突:${n.index}/${n.entryId}/${t}`),uJ(a,s)},{once:!0}),await i,c)throw c},async saveDetail(e,t,s,n){let r=uE.Pi.parse(e),i=uE.wI.parse(n),a=(await uW()).transaction(u$,"readwrite"),l=uU(a),o=a.objectStore(u$),c=[r.sessionId,r.branchId,t],d=await uY(o.get(c)),u=uH.parse(d);if(u.entryId!==s)throw a.abort(),await l.catch(()=>void 0),Error(`IndexedDB 消息身份不匹配:${t}/${s}`);let{detail:m,...p}=u;o.put(null===i?p:{...p,detail:i}),await l},async clearSource(e){let t=uE.Pi.parse(e),s=(await uW()).transaction(u$,"readwrite"),n=uU(s);uJ(s.objectStore(u$),t),await n}}){let n=new u8(e),r=new Map,i=new Map,a=new Map,l=new Map,o=new Map,c=new Map,d=new Map,u=new Map,m=new Map,p=new Set,h=new Set,g=!1,f=0,x=null,b=()=>void 0,v=null,w=!1,y=()=>{for(let e of[...p])try{e()}catch(e){console.error("[Pi Desk][WorkbenchChat] 消息状态监听器执行失败",{errorName:e instanceof Error?e.name:"UnknownError"})}},k=(e=!1)=>{if(e){if(v)return;v=setTimeout(()=>{v=null,y()},50);return}v&&clearTimeout(v),v=null,y()},j=(e,t,s=!1)=>{a.set(me(e),t),k(s)},N=e=>{let t=r.get(e.workId),s=i.get(e.workId);return void 0!==t&&void 0!==s&&mt(t,e)&&mt(u9(s),e)},I=(e,t)=>{let s=me(e),n=(u.get(s)??Promise.resolve()).then(t,t);u.set(s,n);let r=()=>{u.get(s)===n&&u.delete(s)};return n.then(r,r),n},S=e=>{let t=`${me(e)}\u0000`;for(let e of d.keys())e.startsWith(t)&&d.delete(e)},C=async(t,n=!1)=>{if(!g||0===t.length||w)return;let r=f,i=t.filter(e=>N(e)&&!l.has(me(e))).map(e=>{let t=me(e),s={};l.set(t,s);let n=a.get(t);return n&&a.set(t,{...n,syncStatus:"syncing"}),{source:e,token:s}});if(0===i.length)return;k();let o=({source:e,token:t})=>!w&&g&&r===f&&N(e)&&l.get(me(e))===t;try{let t=(await Promise.all(i.map(async e=>({...e,cursor:n?null:await s.readLatestCursor(e.source)})))).filter(o).map(({source:e,cursor:t})=>({source:e,cursor:t}));if(0===t.length)return;await e.request(dL.P6.subscribe,{subscriptions:t})}catch(t){let e=i.filter(o);for(let{source:t}of e)l.delete(me(t));if(e.length>0)throw t}},E=async e=>{let t=me(e),n=a.get(t);return n||uE.oc.parse({messages:await s.readMessages(e),temporaryMessages:[],runtime:uM.runtime})},M=async e=>{N(e)&&g&&!w&&(l.delete(me(e)),await C([e],!0))},z=async e=>{let{epoch:t,push:n}=e,{source:r,event:i}=n,o=me(r),c=l.get(o),d=()=>!w&&g&&t===f&&N(r)&&l.get(o)===c;if(!d()||"session_sync"!==i.type&&(c||!a.has(o)))return!1;if("session_sync"===i.type&&"full"===i.mode){S(r);let e=a.get(o);e&&j(r,{...e,syncStatus:"syncing"})}let u="session_sync"===i.type&&"full"===i.mode?a.get(o)??u7:await E(r);if(!d())return!1;if("session_sync"===i.type&&"incremental"===i.mode){let e=u.messages.at(-1);if(e?.location.index!==i.baseCursor.index||e.location.entryId!==i.baseCursor.entryId){let e=await s.readMessages(r);if(!d())return!1;let t=e.slice(0,i.baseCursor.index+1),n=uz(t);if(n?.index!==i.baseCursor.index||n.entryId!==i.baseCursor.entryId)throw Error(dV("chatCacheMismatch"));u={...u,messages:t}}}let m=function(e,t){if("session_sync"===t.type){if("full"===t.mode)return{...df(e,t.messages,t.temporaryMessages),runtime:t.runtime};let s=e.messages.at(-1);if(!s||s.location.index!==t.baseCursor.index||s.location.entryId!==t.baseCursor.entryId)throw Error("Incremental chat sync does not match the current durable cursor");let n=new Set(e.messages.map(e=>e.location.entryId));for(let e of t.messages){if(n.has(e.location.entryId))throw Error(`Incremental chat sync contains a duplicate entryId: ${e.location.entryId}`);n.add(e.location.entryId)}return{messages:[...e.messages,...t.messages],temporaryMessages:t.temporaryMessages,runtime:t.runtime}}return"runtime_update"===t.type?{...e,runtime:t.runtime}:{...dx(e,t),runtime:e.runtime}}(u,i);if("session_sync"===i.type)await I(r,async()=>{d()&&await s.replaceMessages(r,m.messages)});else if("message_commit"===i.type){let e=m.messages.at(-1);if(!e||e.location.index!==i.durable.index||e.location.entryId!==i.durable.entryId)throw Error(`Chat commit result is missing: ${i.durable.index}/${i.durable.entryId}`);await I(r,async()=>{d()&&await s.appendMessage(r,e)})}if(!d())return!1;for(let e of("session_sync"===i.type&&l.delete(o),j(r,{...m,syncStatus:"session_sync"===i.type?"syncing":a.get(o).syncStatus},"message_update"===i.type),[...h]))try{e(n,m)}catch(e){console.error("[Pi Desk][WorkbenchChat] Source 事件观察器执行失败",{eventType:i.type,errorName:e instanceof Error?e.name:"UnknownError"})}return!0},A=async(e,t)=>{if(!t.processing){t.processing=!0;try{for(;!w&&c.get(e)===t;){let e=t.pushes.shift();if(!e)break;try{await z(e)&&"session_sync"===e.push.event.type&&(t.syncEpoch=e.epoch)}catch(r){if(w||e.epoch!==f||!N(e.push.source))continue;t.pushes.length=0,t.syncEpoch=null;let{push:s}=e,n="message_start"===s.event.type?s.event.snapshot.location.tempId:"location"in s.event?s.event.location.tempId:null;console.error("[Pi Desk][WorkbenchChat] 应用聊天 Source 事件失败,重新同步",{workId:s.source.workId,sessionId:s.source.sessionId,branchId:s.source.branchId,eventType:s.event.type,eventTempId:n,updateLayers:"message_update"===s.event.type?{fixed:void 0!==s.event.fixed,summary:void 0!==s.event.summary,detail:void 0!==s.event.detail,increments:void 0!==s.event.increments}:null,errorName:r instanceof Error?r.name:"UnknownError",errorMessage:r instanceof Error?r.message:String(r)});try{await M(s.source)}catch(e){b(e)}break}}}finally{if(t.processing=!1,c.get(e)!==t)return;if(0===t.pushes.length){c.delete(e);let s=a.get(e);w||!g||t.syncEpoch!==f||l.has(e)||s?.syncStatus!=="syncing"||(a.set(e,{...s,syncStatus:"ready"}),k())}else w||A(e,t)}}},$=e=>{if(w||!g||!N(e.source))return;let t=me(e.source),s=c.get(t)??{pushes:[],processing:!1,syncEpoch:null};s.pushes.push({epoch:f,push:e}),c.set(t,s),s.processing||A(t,s)},R=e=>{for(let t of(i.clear(),e))i.set(t.workId,t);let t=!1;for(let e of[...r.values()]){let s=i.get(e.workId);s&&mt(e,u9(s))||(r.delete(e.workId),a.delete(me(e)),l.delete(me(e)),o.delete(me(e)),S(e),c.delete(me(e)),t=!0)}t&&k()};return{nativeUi:n,start(t){b=t,x||(w=!1,x=e.subscribe(dL.P6.sourceEvent,$))},async applyWorkSessionsList(e){R(e),g=!0,n.ready(e.map(u9)),await C([...r.values()])},reconcileWorkSessions(e){R(e),n.reconcile(e.map(u9))},ensureDisplayedWorkSessions(e){(e=>{let t=[];for(let s of e){let e=u9(s),n=i.get(s.workId);if(!n&&g)continue;let d=n?u9(n):e;if(!mt(e,d))continue;let u=r.get(d.workId);u&&mt(u,d)||(u&&(a.delete(me(u)),l.delete(me(u)),o.delete(me(u)),S(u),c.delete(me(u))),r.set(d.workId,d),t.push(d))}0!==t.length&&(k(),g&&C(t).catch(e=>{b(e)}))})(e)},subscribe:e=>(p.add(e),()=>p.delete(e)),subscribeSourceEvents:e=>(h.add(e),()=>h.delete(e)),getSourceState(e){let t=uE.Pi.parse(e);return a.get(me(t))??u7},getViewportSnapshot(e){let t=uE.Pi.parse(e);return o.get(me(t))??null},saveViewportSnapshot(e,t){let s=uE.Pi.parse(e);t.messageId&&Number.isFinite(t.offset)&&o.set(me(s),t)},clearViewportSnapshot(e){let t=uE.Pi.parse(e);o.delete(me(t))},async loadMessageDetail(e,n,r){let i=uE.Pi.parse(e),l=(await E(i)).messages.find(e=>e.location.index===n&&e.location.entryId===r);if(!l)throw Error(dV("chatMessageMissing",{index:n,entryId:r}));if(void 0!==l.detail)return l.detail;if(!l.fixed.hasDetail)return null;if(a.get(me(i))?.syncStatus!=="ready")throw Error(dV("sourceSyncing"));let o=f,c=`${me(i)}\u0000${n}\u0000${r}`,u=d.get(c);if(u)return u;let m=(async()=>{let e=await t({sessionId:i.sessionId,branchId:i.branchId,entryId:r}),n=()=>!w&&f===o&&N(i)&&d.get(c)===m;if(await I(i,async()=>{if(!n())throw Error(dV("sourceSyncing"));await s.saveDetail(i,e.index,e.entryId,e.detail)}),!n())throw Error(dV("sourceSyncing"));if(N(i)&&!w){let t=a.get(me(i));t&&j(i,{...{...db(t,e),runtime:t.runtime},syncStatus:t.syncStatus})}return e.detail})().finally(()=>{d.get(c)===m&&d.delete(c)});return d.set(c,m),m},async compact(t){let s=uE.Pi.parse(t);if(a.get(me(s))?.syncStatus!=="ready")throw Error(dV("sourceSyncing"));await e.request(dL.P6.compact,{source:s})},async reload(t,s){let n=uE.Pi.parse(t);if(a.get(me(n))?.syncStatus!=="ready")throw Error(dV("sourceSyncing"));await e.request(dL.P6.reload,void 0===s?{source:n}:{source:n,mode:s})},async reloadMessages(t){let s=uE.Pi.parse(t),n=me(s),o=i.get(s.workId);if(!o||!mt(u9(o),s))throw Error(dV("reloadChatSourceChanged"));let d=a.get(n);if(!g||w||l.has(n)||d?.syncStatus==="syncing")throw Error(dV("sourceSyncing"));let u=f,m=c.get(n),p=m?.syncEpoch??null;m&&(m.syncEpoch=null),r.set(s.workId,s),j(s,{...d??u7,syncStatus:"syncing"});try{await e.request(dL.P6.subscribe,{subscriptions:[{source:s,cursor:null}]})}catch(e){if(!w&&u===f&&N(s)){m&&c.get(n)===m&&(m.syncEpoch=p);let e=a.get(n);e&&j(s,{...e,syncStatus:d?.syncStatus??"loading"})}throw console.error("[Pi Desk][WorkbenchChat] 重新加载聊天数据失败,保留已有缓存",{workId:s.workId,sessionId:s.sessionId,branchId:s.branchId,message:e instanceof Error?e.message:String(e)}),e}},async setPresentation(t,s){let n=uE.Pi.parse(t),r=me(n),i=a.get(r);if(!i||"ready"!==i.syncStatus)throw Error(dV("sourceSyncing"));if(i.runtime.presentationMode===s)return;let l=`${r}\u0000${s}`,o=m.get(l);if(o)return o;let c=e.request(dL.P6.presentationSet,{source:n,mode:s}).then(()=>void 0).finally(()=>{m.get(l)===c&&m.delete(l)});return m.set(l,c),c},disconnected(){for(let e of(n.disconnected(),g=!1,f+=1,d.clear(),m.clear(),l.clear(),c.values()))e.pushes.length=0;let e=!1;for(let[t,s]of a)"syncing"!==s.syncStatus&&(a.set(t,{...s,syncStatus:"syncing"}),e=!0);e&&k()},dispose(){w||(n.dispose(),w=!0,g=!1,x?.(),x=null,b=()=>void 0,r.clear(),i.clear(),a.clear(),l.clear(),o.clear(),c.clear(),d.clear(),u.clear(),m.clear(),v&&clearTimeout(v),v=null,p.clear(),h.clear())}}})(E,e=>$.getChatMessageDetail(e)),[E,$]),tz=function(e,t){let{t:s}=(0,b.Bd)("workbench"),n=(0,X.G)(),i=(0,r.useCallback)(()=>JSON.stringify(t.filter(({workId:t,sessionId:s,branchId:n})=>"syncing"===e.getSourceState({workId:t,sessionId:s,branchId:n}).syncStatus).map(e=>e.workId)),[e,t]),a=(0,r.useSyncExternalStore)(e.subscribe,i,i);return{syncingWorkIds:(0,r.useMemo)(()=>JSON.parse(a),[a]),reload:(0,r.useCallback)(t=>{let{workId:r,sessionId:i,branchId:a}=t;e.reloadMessages({workId:r,sessionId:i,branchId:a}).catch(e=>{n.error(e instanceof Error?e.message:s("reloadChatDataFailed"))})},[e,s,n])}}(tM,G),tA=(0,r.useMemo)(()=>(function(e,t,s={async recoverOutbox(e){let t=uE.Pi.parse(e),s=(await uW()).transaction([uP,uD],"readwrite"),n=uU(s),r=s.objectStore(uP),i=s.objectStore(uD),a=mn(t),[l,o]=await Promise.all([uY(r.get(a)),uY(i.get(a))]),c=mi(l),d=mi(o);if(!d)return await n,{input:c??ms,recovered:!1};let u=ma(d,c);return r.put(mr(t,u)),i.delete(a),await n,{input:u,recovered:!0}},async writeDraft(e,t){let s=uE.Pi.parse(e),n=(await uW()).transaction(uP,"readwrite"),r=uU(n),i=n.objectStore(uP);t.text||0!==t.images.length?i.put(mr(s,t)):i.delete(mn(s)),await r},async moveDraftToOutbox(e,t){let s=uE.Pi.parse(e),n=(await uW()).transaction([uP,uD],"readwrite"),r=uU(n);n.objectStore(uD).put(mr(s,t)),n.objectStore(uP).delete(mn(s)),await r},async clearOutbox(e){let t=uE.Pi.parse(e),s=(await uW()).transaction(uD,"readwrite"),n=uU(s);s.objectStore(uD).delete(mn(t)),await n},async restoreOutboxToDraft(e){let t=uE.Pi.parse(e),s=(await uW()).transaction([uP,uD],"readwrite"),n=uU(s),r=s.objectStore(uP),i=s.objectStore(uD),a=mn(t),[l,o]=await Promise.all([uY(r.get(a)),uY(i.get(a))]),c=mi(o);if(!c)throw s.abort(),await n.catch(()=>void 0),Error(dV("outboxMissing"));let d=ma(c,mi(l));return r.put(mr(t,d)),i.delete(a),await n,d},async deleteOutbox(e){await this.clearOutbox(e)},async clearSource(e){let t=uE.Pi.parse(e),s=(await uW()).transaction([uP,uD],"readwrite"),n=uU(s);s.objectStore(uP).delete(mn(t)),s.objectStore(uD).delete(mn(t)),await n}}){let n=new Map,r=new Map,i=new Set,a=new Map,l=new Set,o=0,c=new Map,d=[],u=new Map,m=new Map,p=0,h=!1,g=()=>{for(let e of[...i])try{e()}catch(e){console.error("[Pi Desk][WorkbenchChatInput] 状态监听器执行失败",{errorName:e instanceof Error?e.name:"UnknownError"})}},f=e=>{if("ready"!==t.getSourceState(e).syncStatus)throw Error(dV("sourceSyncing"))},x=e=>{let t=my(e);r.set(t,e);let s=n.get(t);return s||(s={loaded:!1,loading:!1,text:"",images:[],outbox:null,notice:null,error:null,models:{status:"idle",models:[],presets:[],error:null}},n.set(t,s)),s},b=(e,t)=>{let s=t(x(e));return n.set(my(e),s),g(),s},v=(e,t)=>{let n=my(e);o+=1;let i=(a.get(n)??Promise.resolve()).then(()=>s.writeDraft(e,t)).then(()=>{l.delete(n)}).catch(t=>{l.add(n),console.error("[Pi Desk][WorkbenchChatInput] Draft 写入失败",{workId:e.workId,errorName:t instanceof Error?t.name:"UnknownError"}),r.has(n)&&b(e,e=>({...e,error:dV("draftSaveFailed")}))}).finally(()=>{a.get(n)===i&&a.delete(n)});a.set(n,i)},w=e=>{v(e,mk(x(e)))},y=()=>{for(;!h&&p<2&&d.length>0;){let e=d.shift();p+=1,e().finally(()=>{p-=1,y()})}},k=(e,t)=>{d.push(async()=>{let s=n.get(my(e)),r=s?.images.find(e=>e.localId===t);if(r&&"optimizing"===r.status)try{let s=await mx(r),i=n.get(my(e)),a=i?.images.findIndex(e=>e.localId===t)??-1;if(!i||a<0)return;let l=URL.createObjectURL(s.blob);URL.revokeObjectURL(i.images[a].objectUrl);let o=[...i.images];o[a]={...o[a],...s,objectUrl:l,status:"ready",error:null},n.set(my(e),{...i,images:o,error:null}),w(e),g()}catch(a){let s=n.get(my(e)),r=s?.images.findIndex(e=>e.localId===t)??-1;if(!s||r<0)return;let i=[...s.images];i[r]={...i[r],status:"error",error:mj(a,dV("imageProcessFailed"))},n.set(my(e),{...s,images:i}),w(e),g()}}),y()},j=()=>{let e=[...u.values()].reduce((e,t)=>e+t.size,0);for(let[t,s]of u){if(e<=0x4000000&&u.size<=64)break;s.references>0||(URL.revokeObjectURL(s.url),u.delete(t),e-=s.size)}},N=e=>{let t=my(e),s=n.get(t);for(let e of(s&&(mC(s.images),s.outbox&&mC(s.outbox.images)),n.delete(t),r.delete(t),a.delete(t),l.delete(t),c.delete(t),m.keys()))e.startsWith(`${t}\u0000`)&&m.delete(e);for(let[e,s]of[...u])e.startsWith(`${t}\u0000`)&&(URL.revokeObjectURL(s.url),u.delete(e))},I=t.subscribeSourceEvents((e,t)=>{let{source:s,event:n}=e;if("message_commit"===n.type){let e=`${my(s)}\u0000temp\u0000${n.location.tempId}\u0000`;for(let[t,r]of[...u]){if(!t.startsWith(e))continue;let i=Number.parseInt(t.slice(e.length),10);u.delete(t),u.set(mS(s,n.durable.entryId,i),r)}g();return}if("message_discard"===n.type){let e=`${my(s)}\u0000temp\u0000${n.location.tempId}\u0000`;for(let[t,s]of[...u])t.startsWith(e)&&(URL.revokeObjectURL(s.url),u.delete(t));g();return}if("session_sync"===n.type||"runtime_update"===n.type){let e=new Set([...t.temporaryMessages.map(e=>e.location.tempId),...t.runtime.queues.steering.map(e=>e.tempId),...t.runtime.queues.followUp.map(e=>e.tempId)]),n=`${my(s)}\u0000temp\u0000`;for(let[t,s]of[...u]){if(!t.startsWith(n))continue;let r=t.slice(n.length).split("\0")[0];r&&e.has(r)||(URL.revokeObjectURL(s.url),u.delete(t))}}});return{subscribe:e=>(i.add(e),()=>i.delete(e)),getState:e=>x(e),async loadSource(e){let t=my(e);if(x(e).loaded)return;let i=c.get(t);if(i)return i;let a=(async()=>{b(e,e=>({...e,loading:!0,error:null}));try{let i,a,l=await s.recoverOutbox(e);if(h||!r.has(t))return;let o=(i=l.input.images,a=dV("draftImage"),i.map((e,t)=>mv(e,`${a} ${t+1}`)));for(let s of(n.set(t,{...x(e),loaded:!0,loading:!1,text:l.input.text,images:o,notice:l.recovered?dV("uncertainRecovered"):null,error:null}),o))s.optimized||k(e,s.localId);g()}catch(t){b(e,e=>({...e,loaded:!1,loading:!1,error:mj(t,dV("draftLoadFailed"))}))}})().finally(()=>c.delete(t));return c.set(t,a),a},dismissFeedback(e){b(e,e=>({...e,notice:null,error:null}))},setText(e,t){let s=b(e,e=>({...e,text:t,notice:null,error:null}));v(e,mk(s))},async addFiles(e,t){let s=10-x(e).images.length;if(s<=0)return void b(e,e=>({...e,error:dV("imageAddLimit")}));let n=[...t].slice(0,s),r=[];for(let t of n)try{let e=await mf(t);r.push(mv(e,t.name))}catch(s){b(e,e=>({...e,error:dV("imageFileFailed",{name:t.name,error:mj(s,dV("imageUnavailable"))})}))}if(0===r.length)return;let i=b(e,e=>({...e,images:[...e.images,...r],notice:null,error:t.length>s?dV("imageAddOverflow"):null}));for(let t of(v(e,mk(i)),r))t.optimized||k(e,t.localId)},removeImage(e,t){let s=x(e).images.find(e=>e.localId===t);if(!s)return;mw(s);let n=b(e,e=>({...e,images:e.images.filter(e=>e.localId!==t),error:null}));v(e,mk(n))},async send(t,r){f(t);let i=my(t),l=x(t);if(l.outbox)throw Error(dV("resolveOutboxFirst"));if(!l.text.trim()&&0===l.images.length)throw Error(dV("emptyInput"));if(l.images.length>10)throw Error(dV("imageSendLimit"));if(l.images.some(e=>"optimizing"===e.status))throw Error(dV("imagesPending"));let o=l.images.find(e=>"error"===e.status);if(o)throw Error(o.error??dV("imageProcessingFailed"));if(l.images.reduce((e,t)=>e+t.blob.size,0)>0x1400000)throw Error(dV("imageBytesLimit"));await (a.get(i)??Promise.resolve()),f(t);let c=mk(l);await s.moveDraftToOutbox(t,c),n.set(i,{...l,text:"",images:[],outbox:{status:"sending",text:l.text,images:l.images,error:null},notice:null,error:null}),g();try{let a=await Promise.all(l.images.map(mb)),o={source:t,mode:r,text:l.text,images:a};if(new TextEncoder().encode(JSON.stringify({head:{op:"req",path:"chat/send",requestId:"00000000-0000-4000-8000-000000000000"},body:o})).byteLength>0x1f00000)throw Error(dV("messageBytesLimit"));let c=await e.sendChat(o);if(h||n.get(i)?.outbox?.images!==l.images)return;l.images.forEach((e,s)=>{u.set(mI(t,c.tempId,s),{url:URL.createObjectURL(e.blob),size:e.blob.size,references:0})}),j(),await s.clearOutbox(t);let d=n.get(i);d?.outbox?.images===l.images&&(mC(l.images),n.set(i,{...d,outbox:null,error:null})),g()}catch(r){let e,t,s=n.get(i);throw s?.outbox?.images===l.images&&n.set(i,{...s,outbox:{...s.outbox,status:(t="string"==typeof(e=r instanceof Error&&"rawMessage"in r?r.rawMessage:null)?e:mj(r,""),/WebSocket.*(?:断开|连接|替换)|请求超时|尚未连接/.test(t))?"unknown":"failed",error:mj(r,dV("sendFailed"))}}),g(),r}},async prepareForPageReload(){let e=o;return await Promise.all([...a.values()]),o===e&&!(l.size>0)&&[...n.values()].every(e=>e.outbox?.status!=="sending"&&e.outbox?.status!=="unknown")},async restoreOutbox(e){let t=my(e);await (a.get(t)??Promise.resolve());let r=x(e);r.outbox&&(await s.restoreOutboxToDraft(e),n.set(t,{...r,text:mN(r.outbox.text,r.text),images:[...r.outbox.images,...r.images],outbox:null,notice:null,error:null}),g())},async deleteOutbox(e){let t=x(e);t.outbox&&(await s.deleteOutbox(e),mC(t.outbox.images),n.set(my(e),{...t,outbox:null,notice:null,error:null}),g())},async interrupt(t){f(t);try{await e.interruptChat({source:t}),b(t,e=>({...e,error:null}))}catch(e){throw b(t,t=>({...t,error:mj(e,dV("interruptFailed"))})),e}},async restoreQueue(t){f(t);try{let s=await e.restoreChatQueue({source:t}),n=s.images.map((e,t)=>mv({blob:(0,dw.E)(e),mimeType:e.mimeType,width:e.width,height:e.height,optimized:!0},dV("restoredImage",{count:t+1}))),r=b(t,e=>({...e,text:mN(s.text,e.text),images:[...n,...e.images],notice:null,error:null}));v(t,mk(r))}catch(e){throw b(t,t=>({...t,error:mj(e,dV("queueRestoreFailed"))})),e}},listTools:async t=>(f(t),e.listPiTools({source:t})),async loadModels(t,s=!1){let r=x(t);if("loading"===r.models.status||!s&&"ready"===r.models.status)return;let i=b(t,e=>({...e,models:{...e.models,status:"loading",error:null}})).models,a=my(t);try{let s=await e.listModels({workId:t.workId});if(h||n.get(a)?.models!==i)return;b(t,e=>({...e,models:{status:"ready",models:s.models,presets:s.presets,error:null}}))}catch(e){if(h||n.get(a)?.models!==i)return;b(t,t=>({...t,models:{...t.models,status:"error",error:mj(e,dV("modelCatalogFailed"))}}))}},async setModel(t,s){f(t);let n=my(t);x(t);try{await e.setChatModel({source:t,model:s}),!h&&r.has(n)&&b(t,e=>({...e,error:null}))}catch(e){throw!h&&r.has(n)&&b(t,t=>({...t,error:mj(e,dV("setModelFailed"))})),e}},acquireMessageImage(t){if(h)throw Error(dV("imageUnavailable"));let s=t.entryId?mS(t.source,t.entryId,t.imageIndex):t.tempId?mI(t.source,t.tempId,t.imageIndex):null;if(!s)throw Error(dV("imageIdentityInvalid"));r.set(my(t.source),t.source);let n=e=>{if(h||u.get(s)!==e)throw Error(dV("imageUnavailable"));e.references+=1,u.delete(s),u.set(s,e),j();let t=!1;return{url:e.url,release:()=>{t||(t=!0,e.references-=1,j())}}},i=u.get(s);if(i)return n(i);let a=m.get(s);if(!a){if(!t.entryId)throw Error(dV("localImagePending"));a=e.getChatImage({sessionId:t.source.sessionId,branchId:t.source.branchId,entryId:t.entryId,imageIndex:t.imageIndex}).then(e=>{if(h||m.get(s)!==a)throw Error(dV("imageUnavailable"));let t=(0,dw.E)(e),n={url:URL.createObjectURL(t),size:t.size,references:0};return u.set(s,n),n}).catch(e=>{throw console.warn("[Pi Desk][WorkbenchChatInput] 读取聊天图片失败",{entryId:t.entryId,error:mj(e,dV("imageUnavailable"))}),e}).finally(()=>{m.get(s)===a&&m.delete(s)}),m.set(s,a)}return a.then(n)},reconcileWorkSessions(e){let t=new Set(e.map(e=>my({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId})));for(let[e,n]of[...r]){if(t.has(e))continue;let r=a.get(e)??Promise.resolve();N(n),r.then(()=>s.clearSource(n),()=>s.clearSource(n)).catch(e=>{console.error("[Pi Desk][WorkbenchChatInput] 清理失效 Source 输入失败",{workId:n.workId,errorName:e instanceof Error?e.name:"UnknownError"})})}g()},dispose(){if(!h){for(let e of(h=!0,I(),d.length=0,[...r.values()]))N(e);for(let e of u.values())URL.revokeObjectURL(e.url);u.clear(),m.clear(),l.clear(),i.clear()}}}})($,tM),[tM,$]),t$=(0,r.useRef)(null),tR=(0,r.useRef)(null),tP=(0,r.useMemo)(()=>G.slice(0,Z).map(e=>e.workId),[Z,G]),tD=(0,r.useMemo)(()=>A.flatMap(e=>e.contributions.flatMap(t=>"application"===t.kind?[{pluginName:e.pluginName,contributionName:t.contributionName,label:t.label,...t.icon?{icon:t.icon}:{}}]:[])),[A]),tT=(0,r.useMemo)(()=>A.flatMap(e=>e.contributions.flatMap(t=>"session-sidebar-tab"===t.kind?[{pluginName:e.pluginName,contributionName:t.contributionName,label:t.label,...t.icon?{icon:t.icon}:{}}]:[])),[A]),tO=!!(eM||eC?.loadError||eC?.plugins.some(e=>"failed"===e.status||e.operation?.phase==="failed")||z.getEntryListError()||z.getFailedEntries().length>0),tL=!!(eC?.restartRequired||eC?.plugins.some(e=>!0===e.updateAvailable)),tF=tO?"error":tL?"notice":null,tB=eA?A.find(e=>e.pluginName===eA.pluginName)?.contributions.find(e=>"application"===e.kind&&e.contributionName===eA.contributionName):void 0,tq=G.find(e=>e.workId===eo)??null,t_=tq?.cwd??null,tW=ex.startsWith("plugin:")?tT.find(e=>h0(e.pluginName,e.contributionName)===ex):void 0,tY=tW?A.find(e=>e.pluginName===tW.pluginName)?.contributions.find(e=>"session-sidebar-tab"===e.kind&&e.contributionName===tW.contributionName):void 0,tV=tq?.workId??null,tU=tq?.sessionId??null,tH=tq?.branchId??null,tK=tV&&tU&&tH?{workId:tV,sessionId:tU,branchId:tH}:null,tG=JSON.stringify([ex,tV,tU,tH,t_]),tJ=(0,r.useCallback)(e=>{ew(t=>e.length>0?{targetKey:tG,actions:e}:t?.targetKey===tG?null:t)},[tG]),tQ=H.getWorkspace(eo);(0,r.useEffect)(()=>{if(!ex.startsWith("plugin:")||tq&&tW&&tY?.kind==="session-sidebar-tab")return;let e=!0;return queueMicrotask(()=>{e&&eb("sessions")}),()=>{e=!1}},[tW,tY,tq,ex]);let tX=(0,r.useMemo)(()=>{let e=G.find(e=>e.workId===eX);return e?{projectName:e.projectName,sessionTitle:e.sessionTitle,sessionId:e.sessionId}:null},[eX,G]),tZ=(0,r.useMemo)(()=>G.filter(e=>e.workId!==eX).map(e=>e.sessionId),[eX,G]),t0=(0,r.useCallback)(e=>{eE(e),ez(null);let t=e.plugins.some(e=>null!==e.operation&&"failed"!==e.operation.phase&&"waiting"!==e.operation.phase);t||z.refreshEntries().catch(()=>void 0),z.setEntriesMaintaining(t)},[z]),t1=(0,r.useCallback)(()=>{tC.current&&clearTimeout(tC.current);let e=++tE.current,t=15,s=n=>{tC.current=setTimeout(()=>{tC.current=null,tE.current===e&&o().then(t=>{tE.current===e&&t0(t)}).catch(n=>{if(tE.current===e){if((t-=1)>0)return void s(2e3);ez(n instanceof Error?n.message:S("pluginRestoreFailed"))}})},n)};s(1500)},[t0,o,S]),t2=(0,r.useCallback)(e=>{L.current!==e&&(L.current=e,F.current=0,ec(e))},[]),t5=(0,r.useCallback)(e=>{eB||_.current.has(e)||(_.current.add(e),$.acknowledgeCompleted(e).catch(t=>{console.warn("[Pi Desk][Workbench] 确认工作会话完成状态失败",{workId:e,message:gi(t,"请求失败")})}).finally(()=>{_.current.delete(e)}))},[eB,$]),t3=(0,r.useCallback)(e=>{var t;let s,n=(t=P.current,s=new Map(e.workSessions.map(e=>[e.workId,e])),t.flatMap(e=>{let t=s.get(e.workId);return t&&t.cwd===e.cwd&&t.sessionId===e.sessionId?[]:[e.workId]})),r=new Set(e.workSessions.map(e=>e.workId)),i=n.filter(e=>!q.current.has(e)||!r.has(e));O.current=!0,z.replaceWorkSessions(e.workSessions),P.current=e.workSessions,H.reconcileWorkSessions(e.workSessions),D.current=e.pinnedCount,eP(t=>{if(!t)return null;let s=e.workSessions.find(e=>e.workId===t.source.workId);return s?.sessionId===t.source.sessionId&&s.branchId===t.source.branchId&&s.cwd===t.cwd?t:null}),J(e.workSessions),ee(e.pinnedCount),er(t=>mY(t,e.workSessions,i));let a=L.current;a&&i.includes(a)&&(B.current=!1,t2(null))},[H,z,t2]),t4=(0,r.useCallback)(e=>{t3(e),tM.reconcileWorkSessions(e.workSessions),tA.reconcileWorkSessions(e.workSessions),m(e.workSessions)},[t3,tA,tM,m]),t6=(0,r.useCallback)(e=>{T.current=e,es(e),z.replaceGlobalPluginStates(e.plugins),(0,nK.UV)(e.settings)},[z]),t8=(0,r.useCallback)(e=>{t4(e),t6(e.appRuntime)},[t6,t4]),t7=(0,r.useCallback)(()=>{if(tj.current)return;eF(e=>"initial"===e?"initial":"refresh");let e=(async()=>{let e=await $.listWorkSessions();t8(e),await tM.applyWorkSessionsList(e.workSessions),tw(null),eF("ready")})().catch(e=>{tw(gi(e,S("syncFailed")))}).finally(()=>{tj.current===e&&(tj.current=null)});tj.current=e},[t8,tM,$,S]),t9=(0,r.useCallback)(e=>{try{let t=function(e,t){if("snapshot"===t.type)return dN.kg.parse({workSessions:t.workSessions,pinnedCount:t.pinnedCount});let s=e.workSessions.findIndex(e=>e.workId===t.workId);if(s<0){if("delete"===t.type)return e;throw Error(`WorkSession update target was not found: ${t.workId}`)}if("delete"===t.type)return{workSessions:e.workSessions.filter(e=>e.workId!==t.workId),pinnedCount:e.pinnedCount-Number(s<e.pinnedCount)};let n=[...e.workSessions];return n[s]=dN.MY.parse({...e.workSessions[s],...t.changes}),{workSessions:n,pinnedCount:e.pinnedCount}}({workSessions:P.current,pinnedCount:D.current},e);t4(t)}catch(e){tw(gi(e,S("workSessionUpdateInvalid"))),t7()}},[t4,t7,S]),se=(0,r.useCallback)(e=>{try{t6(function(e,t){if("replace"===t.type)return nU.GR.parse(t.runtime);if("notifications"===t.key)return nU.GR.parse({...e,notifications:function(e,t){if("add"===t.type){if(e.some(e=>e.notificationId===t.notification.notificationId))throw Error(`Notification already exists: ${t.notification.notificationId}`);return[...e,t.notification]}let s=e.findIndex(e=>e.notificationId===t.notificationId);if(s<0)throw Error(`Notification does not exist: ${t.notificationId}`);if("delete"===t.type)return e.filter(e=>e.notificationId!==t.notificationId);let n=[...e];return n[s]={...e[s],...t.changes},n}(e.notifications,t.update)});if("settings"===t.key)return nU.GR.parse({...e,settings:t.update});if("capabilityModes"===t.key)return nU.GR.parse({...e,capabilityModes:t.update});let s={...e.plugins};if(null===t.update.state){if(!(t.update.pluginName in s))throw Error(`Plugin global state does not exist: ${t.update.pluginName}`);delete s[t.update.pluginName]}else s[t.update.pluginName]=t.update.state;return nU.GR.parse({...e,plugins:s})}(T.current,e))}catch(e){tw(gi(e,S("appRuntimeUpdateInvalid"))),t7()}},[t6,t7,S]),st=(0,r.useCallback)(async(e=!1)=>{let t=++tN.current;e9(!0),tp(null);try{let s=await $.listDirectories(e);if(tN.current!==t)return null;return e5(s.directories),s.directories}catch(e){if(tN.current!==t)return null;return tp(gi(e,S("projectDirectoriesFailed"))),null}finally{tN.current===t&&e9(!1)}},[$,S]),ss=(0,r.useCallback)(async(e=!1)=>{let t=++tI.current;tt(!0),tp(null);try{let s=await $.listIgnoredDirectories(e);if(tI.current!==t)return;e4(s.directories)}catch(e){if(tI.current!==t)return;tp(gi(e,S("ignoredDirectoriesFailed")))}finally{tI.current===t&&tt(!1)}},[$,S]),sn=(0,r.useCallback)(async e=>{let t=++tS.current;tn(!0),tp(null);try{let s=await $.listDirectoryEntries(e);if(tS.current!==t)return;e8(s)}catch(e){if(tS.current!==t)return;tp(gi(e,S("browseDirectoryFailed")))}finally{tS.current===t&&tn(!1)}},[$,S]);N="initial"!==eL,(0,r.useEffect)(()=>{let e;if(!N)return;let t=!0,s=!1,n=!1,r=()=>{!t||(n=!0,s||(s=!0,(async()=>{try{for(;t&&n;){n=!1;let e=await o();t&&t0(e)}}catch(s){let e=s instanceof Error?s.message:String(s);t&&ez(e||"读取插件健康状态失败"),console.warn("[Pi Desk][Workbench] 读取插件健康状态失败",{message:e})}finally{s=!1}})()))},i=c(r);if("function"==typeof window.requestIdleCallback){let t=window.requestIdleCallback(r,{timeout:3e3});e=()=>{window.cancelIdleCallback(t)}}else{let t=window.setTimeout(r,1500);e=()=>{window.clearTimeout(t)}}return()=>{t=!1,i(),e()}},[ez,t0,o,N,c]),(0,r.useEffect)(()=>()=>{tE.current+=1,tC.current&&clearTimeout(tC.current)},[]),(0,r.useEffect)(()=>{let e=!0;return queueMicrotask(()=>{if(!e)return;let t=function(){var e=window.localStorage.getItem(mW)??window.sessionStorage.getItem(mW);if(!e)return{primaryWorkId:null};try{let t=JSON.parse(e);if(!t||"object"!=typeof t)return{primaryWorkId:null};return{primaryWorkId:"string"==typeof t.primaryWorkId?t.primaryWorkId:null}}catch{return{primaryWorkId:null}}}();er(O.current?mY(t,P.current):t),el(!0)}),()=>{e=!1}},[]),(0,r.useEffect)(()=>{dQ(H,K,G,eo)},[H,eo,K,G]),(0,r.useEffect)(()=>(function(e,t,s,n,r){let i=e.subscribeSourceEvents(({source:e,event:i},a)=>{("session_sync"===i.type||"runtime_update"===i.type)&&(t.applyPreviewDirectories(e,(0,d_.D)(a.runtime.plugins[d_.s6])),dQ(t,s,n(),r()))});for(let{workId:s,sessionId:r,branchId:i}of n()){let n={workId:s,sessionId:r,branchId:i},a=e.getSourceState(n);"loading"!==a.syncStatus&&t.applyPreviewDirectories(n,(0,d_.D)(a.runtime.plugins[d_.s6]))}return dQ(t,s,n(),r()),i})(tM,H,K,()=>P.current,()=>L.current),[tM,H,K]),(0,r.useEffect)(()=>{let e={};return tR.current={token:e,fileRuntime:H,gitRuntime:K},()=>{tR.current?.token===e&&(tR.current=null),queueMicrotask(()=>{let e=tR.current;e?.fileRuntime!==H&&H.dispose(),e?.gitRuntime!==K&&K.dispose()})}},[H,K]),(0,r.useEffect)(()=>{let e={};return t$.current={token:e,chatRuntime:tM,chatInputRuntime:tA,taskCenterStart:d},tM.start(e=>{tw(gi(e,S("chatSyncFailed"))),t7()}),d(e=>{tw(gi(e,S("taskSyncFailed")))}),()=>{t$.current?.token===e&&(t$.current=null),queueMicrotask(()=>{let e=t$.current;(e?.chatRuntime!==tM||e.chatInputRuntime!==tA||e.taskCenterStart!==d)&&(u(),tA.dispose(),tM.dispose())})}},[tA,tM,t7,d,u,S]),(0,r.useEffect)(()=>{let s=new AbortController,n=null,r=null,i=async()=>{eF(e=>"initial"===e?"initial":"refresh");let r=!0;try{let n=await $.readWorkSessionUpdates(s.signal,async(n,r)=>{r&&(tM.disconnected(),p(),t()),t8(n),await tM.applyWorkSessionsList(n.workSessions),h(),e(),tw(null),eF("ready"),R(r,s.signal,E.waitForClose())},t9,se);if(s.signal.aborted)return;tM.disconnected(),p(),t(),eF(e=>"initial"===e?"initial":"refresh"),n.code===l.Sp&&(r=!1),(0,ei.p)(n)&&(r=!1,tw(S("replacedConnection")))}catch(e){if(s.signal.aborted)return;tM.disconnected(),p(),t(),console.warn("[Pi Desk][Workbench] 工作会话实时连接失败,将重新连接",{message:gi(e,"连接失败")}),O.current||tw(gi(e,S("realtimeFailed")))}!s.signal.aborted&&r&&(n=setTimeout(()=>void i(),1e3))};return r=setTimeout(()=>void i(),0),()=>{s.abort(),r&&clearTimeout(r),n&&clearTimeout(n)}},[E,se,t8,t9,tM,R,p,h,e,t,$,S,ty]),(0,r.useEffect)(()=>{if(!ea||eB||null!==eo||!B.current||!en.primaryWorkId)return;let e=P.current.find(e=>e.workId===en.primaryWorkId);(B.current=!1,e)?t2(e.workId):er(e=>({...e,primaryWorkId:null}))},[eo,en.primaryWorkId,ea,eB,t2]),(0,r.useEffect)(()=>{let e;if(!ea)return;let t=new Map(G.map(e=>[e.workId,e])),s=((e=en.primaryWorkId?[en.primaryWorkId]:[]).push(...tP),Array.from(new Set(e))).map(e=>t.get(e)).filter(e=>void 0!==e);ey&&tq&&"files"===ex&&!s.some(e=>e.workId===tq.workId)&&s.push(tq),tM.ensureDisplayedWorkSessions(s)},[tq,tM,ey,en,ea,tP,ex,G]),(0,r.useEffect)(()=>{ea&&window.localStorage.setItem(mW,JSON.stringify(en))},[en,ea]);let sr=(0,r.useCallback)(e=>{if(!P.current.find(t=>t.workId===e))return;B.current=!1;let t=P.current.slice(0,D.current).map(e=>e.workId),s=L.current===e;if(t.includes(e)&&e!==en.primaryWorkId){s||t2(e),W&&eh(!1);return}en.primaryWorkId!==e&&er(t=>t.primaryWorkId===e?t:{...t,primaryWorkId:e}),s||t2(e),W&&eh(!1)},[en,W,t2]),si=(0,r.useCallback)(e=>{let t=P.current.find(t=>t.workId===e);t?.status==="completed"&&t5(e),sr(e)},[t5,sr]),sa=(0,r.useCallback)(async e=>{if(eB)throw Error(S("workSessionInitializing"));let t="workId"in e?P.current.find(t=>t.workId===e.workId):P.current.find(t=>t.sessionId===e.sessionId);if(t)return si(t.workId),t;if("workId"in e||!e.cwd)throw Error(S("sessionNotFound"));let{workSession:s}=await $.createWorkSession({cwd:e.cwd,sessionId:e.sessionId});return B.current=!1,er({primaryWorkId:s.workId}),t2(s.workId),W&&eh(!1),s},[eB,W,si,t2,$,S]),sl=(0,r.useCallback)(async(e,t)=>{if(eB||e_)return;let s={workSessions:P.current,pinnedCount:D.current},n=s.workSessions.findIndex(e=>e.workId===t),r=e.workIds.indexOf(t);if(n<0||r<0)return;let i=new Map(s.workSessions.map(e=>[e.workId,e])),a=e.workIds.map(e=>i.get(e)).filter(e=>void 0!==e);if(a.length!==s.workSessions.length)return;let l=n<s.pinnedCount,o=r<e.pinnedCount;t3({workSessions:a,pinnedCount:e.pinnedCount}),eW(!0),tw(null);let c=!1;try{t4(await $.sortWorkSessions(e)),c=!0}catch(e){t3(s),tw(gi(e,S("sortFailed")))}finally{eW(!1)}if(c&&l!==o){if(W){o||L.current!==t||t===en.primaryWorkId||t2(en.primaryWorkId);return}if(o)return void er(e=>e.primaryWorkId===t?{primaryWorkId:null}:e);L.current===t&&t2(en.primaryWorkId)}},[t4,t3,en.primaryWorkId,eB,W,e_,t2,$,S]),so=(0,r.useCallback)(e=>{if(eB||e_)return;let t=function(e,t,s){hE(e,t);let n=e.indexOf(s);if(n<0)return null;let r=e.filter(e=>e!==s),i=n<t,a=i?t-1:t+1;return r.splice(i?r.length:t,0,s),{workIds:r,pinnedCount:a}}(P.current.map(e=>e.workId),D.current,e);t&&sl(t,e)},[eB,e_,sl]),sc=(0,r.useCallback)(async e=>{if(!eB){eV(e),tw(null);try{t4(await $.deleteWorkSession(e))}catch(e){tw(gi(e,S("deleteFailed")))}finally{eV(null)}}},[t4,eB,$,S]),sd=(0,r.useCallback)(()=>{if(eB)return;let e=ga((iu(),ii));e&&e5(e),tp(null),eG("create"),eQ("directories"),eZ(null),tI.current+=1,tt(!1),tS.current+=1,tn(!1),tx(),e1(null),eH(!0),st().then(e=>{e?.length===0&&(eQ("browser"),e8(gl(ig(null))),sn(null))})},[tx,st,sn,eB]),su=(0,r.useCallback)(()=>{if(eB)return;let e=G.find(e=>e.workId===eo);e&&(tp(null),tN.current+=1,e9(!1),tI.current+=1,tt(!1),tS.current+=1,tn(!1),eG("replace"),eQ("history"),eZ(e.workId),e1(e.cwd),tb(e.cwd),eH(!0),tf(e.cwd))},[eo,tf,eB,tb,G]),sm=async(e,t)=>{if(!eB&&"create"===eK&&null===to){tc(e),tp(null);try{await $.replaceDirectoryIgnore({cwd:e,ignored:t}),await Promise.all([st(),ss()])}catch(e){tp(gi(e,S(t?"ignoreFailed":"restoreIgnoredFailed")))}finally{tc(null)}}},sp=(0,r.useCallback)(async e=>{let t=W?"activate":Y;if("activate"===t){B.current=!1,er({primaryWorkId:e.workId}),t2(e.workId),W&&eh(!1);return}if("pin"!==t)return;let s=function(e,t,s){hE(e,t);let n=e.indexOf(s);if(n>=0&&n<t)return null;let r=e.filter(e=>e!==s);return r.splice(t,0,s),{workIds:r,pinnedCount:t+1}}(P.current.map(e=>e.workId),D.current,e.workId);if(s){eW(!0);try{t4(await $.sortWorkSessions(s))}catch(e){tw(gi(e,S("autoPinFailed")))}finally{eW(!1)}}},[t4,W,Y,t2,$,S]),{model:sh,open:sg,close:sf,retry:sx,selectEntry:sb,requestAction:sv,clone:sw,confirmRunning:sy,cancelRunning:sk,pendingWorkId:sj}=function({disabled:e,workSessions:t,workbenchBiz:s,chatInputRuntime:n,applyWorkSessionSnapshot:i,applyCreatedWorkSessionBehavior:a,focusWorkSession:l,onError:o,mobile:c}){let[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[f,x]=(0,r.useState)(null),[b,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(null),[N,I]=(0,r.useState)(null),[S,C]=(0,r.useState)(null),E=(0,r.useRef)(0),M=(0,r.useRef)(null),z=(0,r.useRef)(0),A=(0,r.useRef)(null),$=(0,r.useRef)(new Map),R=(0,r.useRef)(null),P=(0,r.useCallback)(()=>{E.current+=1,M.current?.abort(),M.current=null,z.current+=1,A.current?.abort(),A.current=null,$.current.clear(),R.current=null,u(null),p(null),g(!1),x(null),v(null),y(!1),j(null),I(null)},[]),D=(0,r.useCallback)(()=>{S||P()},[S,P]);(0,r.useEffect)(()=>()=>{M.current?.abort(),A.current?.abort()},[]);let T=(0,r.useCallback)(async e=>{let t=++E.current;M.current?.abort();let n=new AbortController;M.current=n,z.current+=1,A.current?.abort(),A.current=null,$.current.clear(),u(e),p(null),g(!0),x(null),v(null),y(!1),j(null),I(null);try{let r=await s.getWorkSessionTree({workId:e.workId,sessionId:e.sessionId},n.signal);if(E.current!==t)return;p(r)}catch(e){if(E.current!==t||hz(e))return;x(hM(e,dV("treeLoadFailed")))}finally{E.current===t&&(M.current===n&&(M.current=null),g(!1))}},[s]),O=(0,r.useCallback)(s=>{if(e)return;let n=t.find(e=>e.workId===s);n?(l(s),T(h$(n))):o(dV("treeSourceInvalid"))},[e,l,T,o,t]),L=(0,r.useCallback)(()=>{d&&!e&&T(d)},[e,T,d]),F=(0,r.useCallback)(e=>{if(!d)return;let t=$.current.get(e);if(t){z.current+=1,A.current?.abort(),A.current=null,v(t),y(!1),j(null);return}let n=++z.current;A.current?.abort();let r=new AbortController;A.current=r,v(null),y(!0),j(null),s.getWorkSessionTreeEntry({workId:d.workId,sessionId:d.sessionId,entryId:e},r.signal).then(t=>{z.current===n&&($.current.set(e,t),v(t))}).catch(e=>{z.current!==n||hz(e)||j(hM(e,dV("treeDetailFailed")))}).finally(()=>{z.current===n&&(A.current===r&&(A.current=null),y(!1))})},[d,s]),B=(0,r.useCallback)(e=>{o(e)},[o]),q=(0,r.useCallback)(async(t,r)=>{if(e)return;let o="tree"===r.action?n.getState(t).text:null;C({source:t,intent:r,phase:"executing"}),x(null);try{let e=await s.branchWorkSession(function(e,t){let s={workId:e.workId,sessionId:e.sessionId};switch(t.action){case"tree":return{...s,action:"tree",entryId:t.entryId};case"fork":return{...s,action:"fork",entryId:t.entryId};case"clone":return{...s,action:"clone"}}}(t,r)),d={workSessions:e.workSessions,pinnedCount:e.pinnedCount};i(d);let u=e.workSessions.find(t=>t.workId===e.targetWorkId);if(!u)throw Error(dV("branchTargetMissing"));let m=h$(u);if("tree"===r.action){var c;l(u.workId),await n.loadSource(m),n.setText(m,(c=o??"",e.editorText??c))}else null!==e.editorText&&(await n.loadSource(m),n.setText(m,e.editorText)),await a(u);C(null),R.current=null,P()}catch(e){C(null),R.current=null,I(e=>e?{...e,waiting:!1}:null),B(hM(e,dV("branchOperationFailed")))}},[a,i,n,e,l,B,P,s]),_=(0,r.useCallback)((e,t,s)=>{C({source:e,intent:t,phase:"waiting"}),I(e=>e?{...e,waiting:!0}:e),"main_running"===s.status&&n.interrupt(e).catch(e=>{C(null),R.current=null,I(e=>e?{...e,waiting:!1}:e),B(hM(e,dV("interruptForBranchFailed")))})},[n,B]),W=(0,r.useCallback)((s,n)=>{if(e||S)return;R.current=null;let r=t.find(e=>e.workId===s.workId);if(!r||r.sessionId!==s.sessionId||r.branchId!==s.branchId)return void B(dV("treeChanged"));if("fork"===n.action||!hA(r))return void q(s,n);let i="main_running"===r.status?"main":"background";c?_(s,n,r):(I({intent:n,reason:i,waiting:!1}),u(s),x(null))},[e,q,c,S,B,_,t]),Y=(0,r.useCallback)((e,t)=>{d&&W(d,{action:t,entryId:e})},[W,d]),V=(0,r.useCallback)(e=>{let s=t.find(t=>t.workId===e);s?W(h$(s),{action:"clone"}):o(dV("cloneUnavailable"))},[o,W,t]),U=(0,r.useCallback)(()=>{if(e||!d||!N||N.waiting||S)return;let s=t.find(e=>e.workId===d.workId);s?hA(s)?_(d,N.intent,s):q(d,N.intent):B(dV("branchUnavailable"))},[N,e,q,S,B,d,_,t]),H=(0,r.useCallback)(()=>{if(N?.waiting||S)return;let e=N?.intent.action==="clone"&&null===m;I(null),e&&P()},[N,S,P,m]);return(0,r.useEffect)(()=>{if(e||!S||"waiting"!==S.phase)return;let s=t.find(e=>e.workId===S.source.workId);if(!s){let e=`${S.source.workId}:${S.intent.action}:missing`;if(R.current===e)return;R.current=e,queueMicrotask(()=>{C(null),R.current=null,I(e=>e?{...e,waiting:!1}:e),B(dV("branchUnavailable"))});return}if(s.sessionId!==S.source.sessionId||s.branchId!==S.source.branchId){let e=`${S.source.workId}:${S.intent.action}:changed`;if(R.current===e)return;R.current=e,queueMicrotask(()=>{C(null),R.current=null,I(e=>e?{...e,waiting:!1}:e),B(dV("branchChanged"))});return}if(hA(s))return;let n=`${S.source.workId}:${S.intent.action}:${"entryId"in S.intent?S.intent.entryId:""}`;if(R.current===n)return;R.current=n;let r=!0;return queueMicrotask(()=>{r&&q(S.source,S.intent)}),()=>{r=!1,R.current===n&&(R.current=null)}},[e,q,S,B,t]),(0,r.useEffect)(()=>{if(!d||S||N)return;let e=t.find(e=>e.workId===d.workId);if(e?.sessionId===d.sessionId&&e.branchId===d.branchId)return;let s=!0;return queueMicrotask(()=>{s&&P()}),()=>{s=!1}},[N,S,P,d,t]),{model:(0,r.useMemo)(()=>{if(!d)return null;let s=t.find(e=>e.workId===d.workId),n=s?.sessionId===d.sessionId&&s.branchId===d.branchId;return S||N||n?{workId:d.workId,tree:m,loading:h,actionsDisabled:e,pending:null!==S,error:f,detail:b,detailLoading:w,detailError:k,runningConfirmation:N}:null},[N,b,k,w,e,f,h,S,d,m,t]),open:O,close:D,retry:L,selectEntry:F,requestAction:Y,clone:V,confirmRunning:U,cancelRunning:H,pendingWorkId:S?.source.workId??null}}({disabled:eB,workSessions:G,workbenchBiz:$,chatInputRuntime:tA,applyWorkSessionSnapshot:t4,applyCreatedWorkSessionBehavior:sp,focusWorkSession:t2,onError:(0,r.useCallback)(e=>{M.error(e)},[M]),mobile:W});(0,r.useEffect)(()=>{let e=e=>{if("Escape"!==e.key)return;if(e.defaultPrevented||e.target instanceof Element&&e.target.closest('[data-testid="file-workspace"], [role="menu"], [data-slot="app-dialog-content"]')){F.current=0;return}if(e.repeat||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||e.isComposing)return;if(W&&eg.current){e.preventDefault(),F.current=0,ef();return}if(null!==sh)return;let t=L.current;if(!t)return;if(W){F.current=0;let s=H.getWorkspace(t),n=document.querySelector(`[data-work-id="${CSS.escape(t)}"]`);s?.windowOpen&&"files"===s.activePane&&n&&!n.closest("[inert]")&&(e.preventDefault(),H.hideWindow(t));return}let s=Date.now();if(s-F.current>=500){F.current=s;return}e.preventDefault(),F.current=0,sg(t)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[sh,ef,H,W,sg]),(0,r.useEffect)(()=>z.bindWorkSessionCreate(async e=>{if(eB)throw Error(S("workSessionInitializing"));let{workSession:t}=await $.createWorkSession({cwd:e});return await sp(t),t}),[sp,eB,z,$,S]),(0,r.useEffect)(()=>z.bindWorkSessionGoTo(sa),[sa,z]);let sN=async e=>{if(!eB){tN.current+=1,e9(!1),tS.current+=1,tn(!1),ti(e),tp(null);try{let{workSession:t}=await $.createWorkSession({cwd:e});tp(null),eH(!1),await sp(t)}catch(e){tp(gi(e,S("createFailed")))}finally{ti(null)}}},sI=async e=>{if(!eB&&eX&&e0){if(!P.current.some(e=>e.workId===eX))return void tp(S("replaceTargetMissing"));tx(),q.current.add(eX),tl(e),tp(null);try{let t=await $.replaceWorkSession({workId:eX,cwd:e0,sessionId:e});if(t4(t),!t.workSessions.find(e=>e.workId===eX))throw Error(S("replacementMissing"));B.current=!1,t2(eX),tp(null),eH(!1),W&&eh(!1)}catch(e){tp(gi(e,S("replaceFailed")))}finally{q.current.delete(eX),tl(null)}}},sS=(0,r.useCallback)(async e=>{if(!eB&&null===td&&P.current.some(t=>t.workId===e)){q.current.add(e),tu(e),tw(null);try{let t=await $.replaceWorkSession({workId:e});if(t4(t),!t.workSessions.find(t=>t.workId===e))throw Error(S("emptyReplacementMissing"));B.current=!1,t2(e)}catch(e){tw(gi(e,S("replaceEmptyFailed")))}finally{q.current.delete(e),tu(null)}}},[t4,eB,td,t2,$,S]),sC=(0,r.useCallback)(e=>{eb(e),"files"===e&&ek(!0)},[]),sE=(0,r.useCallback)(()=>{W&&ef(),eo&&!document.querySelector(`[data-work-id="${CSS.escape(eo)}"] [data-testid="session-file-layout"]`)&&H.expandWindow(eo)},[eo,ef,H,W]),sM=(0,r.useCallback)(()=>{t_&&eo&&(H.refreshTree(eo),K.refreshSnapshot(H.getDirectory(eo)))},[t_,eo,H,K]),sz=(0,r.useCallback)(e=>{eT(e)},[]),sA=(0,r.useCallback)(()=>{eT(null)},[]),s$=(0,r.useCallback)((e,t,s="session",n)=>{let r=P.current.find(t=>t.workId===e.workId&&t.sessionId===e.sessionId&&t.branchId===e.branchId);if(!r)return void M.error(S("sourceChanged"));if("standalone"===s){eP({source:{workId:r.workId,sessionId:r.sessionId,branchId:r.branchId},cwd:r.cwd,projectName:r.projectName,path:t,imagePaths:n}),ef();return}H.selectDirectory(r.workId,r.cwd),H.openFile(r.workId,t),sr(r.workId),ef();let i=document.querySelector(`[data-work-id="${CSS.escape(r.workId)}"] [data-testid="session-file-layout"]`);"expanded"!==s&&i?eA&&eO():H.expandWindow(r.workId)},[eA,ef,eO,H,sr,M,S]),sR=(0,r.useCallback)((e,t,s,n)=>{let r=dC.safeParse(t),i=dC.array().nonempty().optional().safeParse(n);r.success&&i.success&&(!i.data||"standalone"===s&&i.data.includes(r.data))?s$(e,r.data,s,i.data?[...new Set(i.data)]:void 0):M.error(S("invalidFilePath"))},[s$,M,S]),sP=(0,r.useCallback)((e,t)=>{let s=dC.safeParse(t);s.success?s$(e,s.data):M.error(S("invalidToolFilePath"))},[s$,M,S]);(0,r.useEffect)(()=>z.bindWorkSessionFilePreview(({source:e,path:t,mode:s,imagePaths:n})=>{sR(e,t,s??"session",n)}),[z,sR]),(0,r.useEffect)(()=>z.bindImageReader(({source:e,cwd:t,path:s},n)=>ui(V,{workId:e.workId,cwd:t,path:s},n)),[z,V]);let sD=(0,r.useCallback)(async(e,t)=>{let s=dC.safeParse(t);if(!s.success)throw Error(S("invalidFilePath"));let n=P.current.find(t=>t.workId===e.workId&&t.sessionId===e.sessionId&&t.branchId===e.branchId);if(!n)throw Error(S("sourceChanged"));await V.reveal({workId:n.workId,cwd:n.cwd,path:s.data})},[V,S]);(0,r.useEffect)(()=>z.bindWorkSessionFileReveal(({source:e,path:t})=>sD(e,t)),[z,sD]);let sT=(0,r.useCallback)((e,t)=>{tV&&tU&&tH?sR({workId:tV,sessionId:tU,branchId:tH},e,t?.mode??"session",t?.imagePaths):M.error(S("noPreviewSession"))},[tH,tU,tV,sR,M,S]),sO=(0,r.useCallback)(e=>tV&&tU&&tH?sD({workId:tV,sessionId:tU,branchId:tH},e):Promise.reject(Error(S("noRevealSession"))),[tH,tU,tV,sD,S]),sL=(0,r.useCallback)(async e=>{await $.applyAppRuntimeUpdate({key:"notifications",update:{type:"delete",notificationId:e}})},[$]),sF=(0,r.useCallback)(async e=>{if(e.event)try{await z.dispatchNotificationEvent(e.notificationId,e.event),await sL(e.notificationId)}catch(e){M.error(gi(e,S("notificationActionFailed")))}},[sL,z,M,S]),sB=(0,r.useCallback)(async e=>{try{await sL(e)}catch(e){M.error(gi(e,S("notificationDeleteFailed")))}},[sL,M,S]),sq=(0,r.useCallback)(e=>{ef(),eS(e),eN(!0)},[ef]),s_=(0,r.useCallback)(e=>{ef(),e$(e)},[ef]),sW=(0,r.useCallback)(e=>void sc(e),[sc]),sY=(0,r.useCallback)((e,t)=>void sl(e,t),[sl]),sV=(0,r.useCallback)(e=>void sS(e),[sS]),sH=(0,r.useCallback)(()=>{W?eh(e=>!e):em(e=>!e)},[W]),sK=(0,r.useCallback)(e=>{sr(e),W?eh(!0):em(!0)},[sr,W]),sG=W?ep:eu,sJ=eD&&G.some(e=>e.workId===eD.workId&&e.cwd===eD.cwd)?eD:null,sQ=(0,r.useMemo)(()=>ey&&tq?(0,n.jsx)(r.Activity,{mode:sG&&"files"===ex?"visible":"hidden",children:(0,n.jsx)(dJ.k,{workId:tq.workId,cwd:tq.cwd,projectName:tq.projectName,runtime:H,gitRuntime:K,onOpenGitBranches:sz,onFileOpened:sE},`${tq.workId}:${tq.sessionId}:${tq.branchId}`)}):null,[tq,ey,H,K,sE,sz,ex,sG]),sX=sG&&tW&&tY?.kind==="session-sidebar-tab"&&tK&&tq?(0,n.jsx)(go,{render:f,input:{pluginName:tW.pluginName,descriptor:tY,source:tK,cwd:tq.cwd,onPreviewFile:sT,onRevealFile:sO,onHeaderActionsChange:tJ}}):null,sZ=(0,n.jsx)(ge,{mode:ex,mobile:W,fileBrowser:sQ,pluginTabContent:sX,pluginHeaderActions:sG&&ev?.targetKey===tG?ev.actions:[],pluginSessionTabs:tT,fileRefreshLoading:tQ?.directories.get("")?.status==="loading",canBrowseFiles:null!==t_,workSessions:G,focusedWorkId:eo,pinnedCount:Z,ordering:e_,deletingWorkId:eY,canReplace:null!==eo,disabled:eB,pluginApplications:tD,settingsAttention:tF,notifications:et.notifications,onConsumeNotification:sF,onDismissNotification:sB,onModeChange:sC,onRefreshFiles:sM,onPreviewProject:()=>{t_&&(ef(),H.collapseExpandedWindow(),z.previewProject(eo?H.getDirectory(eo):t_))},onPreviewProjectWindow:()=>{t_&&i(eo?H.getDirectory(eo):t_)},onOpenTerminal:()=>{ef(),H.collapseExpandedWindow(),s(t_??void 0).catch(()=>void 0)},onCreate:sd,onReplace:su,onSettings:()=>sq(),onOpenPluginApplication:s_,onSelect:si,onTogglePin:so,onDelete:sW,onRename:eq.show,syncingWorkIds:tz.syncingWorkIds,onReloadChat:tz.reload,onArrangementChange:sY}),s0=(0,n.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col",children:[tv?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 border-b border-destructive/30 bg-destructive/10 px-4 py-2 text-sm text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 wrap-anywhere",children:tv}),(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>tk(e=>e+1),children:S("retry",{ns:"common"})}),"initial"!==eL?(0,n.jsx)(I.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>tw(null),children:S("close",{ns:"common"})}):null]}):null,(0,n.jsxs)("div",{className:"relative h-full min-h-0 min-w-0 flex-1",children:[(0,n.jsx)(hN,{workSessions:G,primaryWorkId:en.primaryWorkId,pinnedWorkIds:tP,focusedWorkId:eo,sidebarOpen:sG,mobile:W,loading:eB,replacingWithEmptyWorkId:td,chatRuntime:tM,chatInputRuntime:tA,renderTaskSummary:v,renderTaskMenu:w,renderPluginComposerPanel:y,renderPluginWidgets:k,renderPluginSessionHeader:j,gitRuntime:K,invokePluginMethod:$.invokePluginMethod,listPiCommands:$.listPiCommands,getChatModelContext:$.getChatModelContext,capabilityModes:et.capabilityModes,setChatCapabilityMode:$.setChatCapabilityMode,branchPicker:sh,branchPendingWorkId:sj,fileRuntime:H,onOpenFileSidebar:sK,onPreviewFile:sP,onAcknowledgeCompleted:t5,onFocusWorkSession:sr,onReplaceWithEmptyWorkSession:sV,onOpenBranchPicker:sg,onOpenGitBranchPicker:sz,onOpenSettings:sq,onCloseBranchPicker:sf,onRetryBranchPicker:sx,onSelectBranchEntry:sb,onBranchAction:sv,onConfirmRunningBranch:sy,onCancelRunningBranch:sk,onCloneWorkSession:sw,onUnpinWorkSession:so,onToggleSidebar:sH}),"initial"===eL?(0,n.jsx)(mV,{variant:"loading",className:"absolute inset-0 z-20 bg-background"}):null]})]}),s1=null!==eA&&tB?.kind==="application",s2=(0,n.jsxs)("div",{className:"flex min-h-0 min-w-0 flex-1",children:[(0,n.jsx)(go,{render:a,input:{mobile:W,children:s0}}),s1?(0,n.jsx)(go,{render:g,input:{pluginName:eA.pluginName,descriptor:tB,workSessions:G,preferredWorkId:eo,onClose:eO}}):null]});return(0,n.jsxs)("main",{className:"pi-desk-workbench flex h-dvh overflow-hidden bg-background",children:[(0,n.jsx)(dT,{mobile:W,open:sG,sidebar:sZ,onClose:ef,children:s2}),(0,n.jsx)(d6,{target:eR,biz:V,images:H.standaloneImages,mobile:W,onClose:()=>eP(null)},eR?`${eR.source.workId}:${eR.source.sessionId}:${eR.source.branchId}:${eR.path}`:"closed"),(0,n.jsx)(un,{workSessions:G,runtime:H,gitRuntime:K,mobile:W,onOpenGitBranches:sz,onOpenSidebar:sK,onOpenTerminal:e=>{H.collapseExpandedWindow(),ef(),s(e).catch(()=>void 0)}}),(0,n.jsx)(um,{target:sJ,runtime:K,mobile:W,onClose:sA},sJ?`${sJ.workId}:${sJ.cwd}:${sJ.repositoryRoot??""}`:"git-branch-picker-closed"),(0,n.jsx)(go,{render:x,input:{open:ej,connectionReady:"ready"===eL,initialPage:eI,capabilityModes:et.capabilityModes,workSessions:G,focusedCwd:t_,basicMode:"basic"===et.mode,pluginManagementSnapshot:eC,pluginAttention:tF,onPluginManagementSnapshot:t0,onPluginRestartScheduled:t1,onOpenChange:eN,onBeforeReload:()=>tA.prepareForPageReload()}}),(0,n.jsx)(hR,{open:eq.open,title:eq.title,saving:eq.saving,disabled:eB,error:eq.error,onTitleChange:eq.setTitle,onSave:()=>void eq.save(),onClose:eq.close}),(0,n.jsx)(m_,{open:eU,pickerMode:eK,pickerView:eJ,pickerCwd:e0,directories:e2,ignoredDirectories:e3,directoryBrowser:e6,historySessions:th,replacementTarget:"create"===eK?null:tX,unavailableSessionIds:tZ,error:tm,loading:"history"===eJ?tg:"ignored"===eJ?te:"browser"===eJ?ts:e7,creatingCwd:tr,replacingSessionId:ta,updatingIgnoreCwd:to,onOpenChange:e=>{eH(e),e||(tN.current+=1,e9(!1),tI.current+=1,tt(!1),tS.current+=1,tn(!1),tx(),eG(null),eQ("directories"),tp(null))},onBack:()=>{tp(null),tI.current+=1,tt(!1),tS.current+=1,tn(!1),tx();let e=ga((iu(),ii));e&&e5(e),eQ("directories"),e1(null),st()},onSearchHistory:(e,t)=>{"history"===eJ&&e0&&tf(e0,e,t)},onListSessionUserMessages:(e,t)=>$.listSessionUserMessages(e,t),onRefresh:(e,t)=>{"history"===eJ&&e0?tf(e0,e,t,!0):"ignored"===eJ?ss(!0):"browser"===eJ?sn(e6?.cwd??null):st(!0)},onOpenIgnoredDirectories:()=>{if(eB||"create"!==eK)return;let e=ga((iu(),ia));e?e4(e):e4([]),tp(null),tN.current+=1,e9(!1),tS.current+=1,tn(!1),eQ("ignored"),ss()},onOpenDirectoryBrowser:()=>{eB||"create"!==eK||(tp(null),tN.current+=1,e9(!1),tI.current+=1,tt(!1),eQ("browser"),e8(gl(ig(null))),sn(null))},onNavigateDirectory:e=>{if(eB||"create"!==eK)return;let t=gl(ig(e));t&&e8(t),sn(e)},onSelectBrowserDirectory:e=>void sN(e),onReplaceDirectoryIgnore:(e,t)=>void sm(e,t),onSelectDirectory:e=>{"replace"===eK?(tN.current+=1,e9(!1),eQ("history"),e1(e),tb(e),tf(e)):sN(e)},onSelectSession:e=>void sI(e)})]})}function gd(e){return(0,n.jsx)(eK,{...e},`${e.pluginName}:${e.descriptor.contributionName}`)}function gu(e){return(0,n.jsx)(sP,{...e},`${e.pluginName}:${e.descriptor.contributionName}:${e.source.workId}:${e.source.sessionId}:${e.source.branchId}`)}function gm(e){let t=JSON.stringify([e.source.workId,e.source.sessionId,e.source.branchId]);return(0,n.jsx)(eG,{...e},`${e.pluginName}:${e.descriptor.contributionName}:${t}`)}function gp(e){return(0,n.jsx)(sT,{...e},`${e.source.workId}:${e.source.sessionId}:${e.source.branchId}:${e.placement}`)}function gh(e){return(0,n.jsx)(sB,{...e},`${e.source.workId}:${e.source.sessionId}:${e.source.branchId}`)}function gg(e){return(0,n.jsx)(sD,{...e},`${e.pluginName}:${e.descriptor.contributionName}`)}function gf(){let{clientId:e,appSocket:t}=(0,ei.gM)(),s=(0,Q.t4)(),a=(0,X.G)(),l=(0,r.useMemo)(()=>new x(t,a.error),[t,a.error]);(0,r.useEffect)(()=>{l.start();let e=s.bindTerminalOpen((e,t)=>l.open(e,t));return()=>{e(),l.dispose()}},[s,l]);let o=(0,r.useCallback)(e=>(0,n.jsx)(J,{...e,biz:l}),[l]),c=(0,r.useMemo)(()=>({subscribeChanges:e=>t.subscribe(sy,e),list:(t=!1)=>sR(e,"/api/plugins/list",sC.parse("boolean"==typeof t?t?{checkUpdates:!0}:{}:t),sN),batch:t=>sR(e,"/api/plugins/batch",sz.parse(t),sA),get:t=>sR(e,"/api/plugins/get",sE.parse({source:t}),sj),add:t=>sR(e,"/api/plugins/add",sM.parse(t),sN),setEnabled:(t,s)=>sR(e,"/api/plugins/enabled-set",s$.parse({source:t,enabled:s}),sN),searchCatalog:t=>sR(e,"/api/plugin-catalog/search",t$.parse(t),tD),getCatalog:t=>sR(e,"/api/plugin-catalog/get",tR.parse(t),tT),getCatalogSettings:()=>sR(e,"/api/plugin-catalog/settings-get",{},tz),saveCatalogSettings:t=>sR(e,"/api/plugin-catalog/settings-replace",tA.parse({downloadSource:t}),tz),update:t=>sR(e,"/api/plugins/update",sE.parse({source:t}),sN),del:t=>sR(e,"/api/plugins/del",sE.parse({source:t}),sN),reload:t=>sR(e,"/api/plugins/reload",sS.parse({mode:t}),sN),apply:t=>sR(e,"/api/plugins/apply",sI.parse({sources:t}),sN)}),[e,t]),d=(0,r.useMemo)(()=>(function(e,t){async function s(t,s){let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s)}),r=await n.json();if(!n.ok||0!==r.code||null===r.data)throw Error(r.msg?(0,ed.B)(r):"请求失败");return r.data}return{watchDetail:e=>t.request(lz.detailWatch,e),async interrupt(e){await t.request(lz.interrupt,e)},subscribeDetailEvents:e=>t.subscribe(lz.detailEvent,e),getMessageDetail:e=>s("/api/task-center/messages/get",e),getImage:e=>s("/api/task-center/images/get",e)}})(e,t),[t,e]),u=(0,r.useMemo)(()=>{let e,t,s,n,r,i,a,l,o,c,u,m,p,h,g,f;return e=new Set,t=new Map,s=dk,n=0,r=0,i=!1,a=null,l=()=>void 0,o=null,c=!1,u=()=>{for(let t of[...e])try{t()}catch(e){console.error("[Pi Desk][TaskCenterClient] 状态监听器执行失败",{errorName:e instanceof Error?e.name:"UnknownError"})}},m=(e,t=!1)=>{s=e,((e=!1)=>{if(e){if(o)return;o=setTimeout(()=>{o=null,u()},16);return}o&&clearTimeout(o),o=null,u()})(t)},p=e=>{for(let[s,n]of t)(void 0===e||n.taskId===e)&&(URL.revokeObjectURL(n.url),t.delete(s))},h=()=>{if(!s.open&&null===s.source)return;let e=s.source;n+=1,i=!1,m(dk),p(),e&&d.watchDetail({source:e,taskId:null}).catch(()=>void 0)},g=e=>{if(c||!s.open||!i||!dj(s.source,e.source)||s.selectedTaskId!==e.taskId)return;let t=s.details[e.taskId];if(t)try{let n=function(e,t){var s,n;if("snapshot"===t.type)return dv(e,t.snapshot);if("unavailable"===t.type)return null;if("text_append"===t.type){if(e.body?.kind!=="text")throw Error("Text append requires a text task detail snapshot");return{...e,body:{...e.body,text:e.body.text+t.text}}}if(e.body?.kind!=="conversation")throw Error("Conversation event requires a conversation task detail snapshot");return{...e,body:{...(s=e.body,"durable_append"===(n=t.event).type?function(e,t){let s=e.messages.length;if(t.messages[0]?.location.index!==s)throw Error(`Conversation append index is not continuous: expected ${s}, received ${t.messages[0]?.location.index}`);let n=new Set(e.messages.map(e=>e.location.entryId));for(let e of t.messages){if(n.has(e.location.entryId))throw Error(`Conversation append entryId already exists: ${e.location.entryId}`);n.add(e.location.entryId)}return{...e,messages:[...e.messages,...t.messages]}}(s,n):dx(s,n)),kind:"conversation",truncated:e.body.truncated}}}(t,e.event);if(!n){let t={...s.details};delete t[e.taskId],p(e.taskId),m({...s,details:t,loading:!1,refreshing:!1,error:dy("detailUnavailable")});return}let r="text_append"===e.event.type||"conversation_event"===e.event.type&&"message_update"===e.event.event.type;m({...s,details:{...s.details,[e.taskId]:n},loading:!1,refreshing:!1,error:null},r)}catch(t){i=!1,l(t),f(e.taskId)}},f=async e=>{if(c||!s.open||!s.source)return;let t=e.trim();if(!t)return;let a=s.source,l=++n,o=r,u=s.details[t];i=!1,m({...s,selectedTaskId:t,loading:void 0===u,refreshing:void 0!==u,error:null});try{let e=await d.watchDetail({source:a,taskId:t});if(c||l!==n||o!==r||!s.open||!dj(s.source,a)||s.selectedTaskId!==t)return;if(!e.snapshot)throw Error(dy("detailResponseMissing"));let p=lk.parse(e.snapshot),h=u?dv(u,p):p;m({...s,details:{...s.details,[t]:h},loading:!1,refreshing:!1,error:null}),i=!0}catch(e){if(l!==n||!s.open||s.selectedTaskId!==t)return;m({...s,loading:!1,refreshing:!1,error:e instanceof Error?e.message:dy("detailLoadFailed")})}},{start(e){l=e,a||(c=!1,a=d.subscribeDetailEvents(g))},subscribe:t=>(e.add(t),()=>e.delete(t)),getState:()=>s,open(e,t){let r=ll.R.parse(e);s.open&&dj(s.source,r)||(n+=1,i=!1,p(),m({...dk,open:!0,source:r})),t&&f(t)},close:h,selectTask(e){f(e)},reconcileWorkSessions(e){if(!s.open||!s.source)return;let t=e.find(e=>e.workId===s.source?.workId);t&&t.sessionId===s.source.sessionId&&t.branchId===s.source.branchId||h()},reconcileTasks(e,t){let r=ll.R.parse(e);if(!s.open||!dj(s.source,r))return;let a=new Set(t.map(e=>e.taskId)),l={...s.details},o=!1;for(let e of Object.keys(l))a.has(e)||(delete l[e],p(e),o=!0);if(s.selectedTaskId&&!a.has(s.selectedTaskId)){n+=1,i=!1,m({...s,selectedTaskId:null,details:l,loading:!1,refreshing:!1,error:null});return}o&&m({...s,details:l})},async interruptSelected(){s.open&&s.source&&s.selectedTaskId&&await d.interrupt({source:s.source,taskId:s.selectedTaskId})},async loadMessageDetail(e){let t=s.source,n=s.selectedTaskId;if(!s.open||!t||!n||!e.durable)return null;let r=s.details[n];if(!r||r.body?.kind!=="conversation")return null;if(void 0!==e.detail)return e.detail;if(!e.snapshot.fixed.hasDetail)return null;let i=await d.getMessageDetail({source:t,taskId:n,entryId:e.durable.location.entryId}),a=s.details[n];return a&&m({...s,details:{...s.details,[n]:function(e,t){if(e.body?.kind!=="conversation")throw Error("Task message detail requires a conversation snapshot");return lk.parse({...e,body:{kind:"conversation",truncated:e.body.truncated,...db(e.body,t)}})}(a,i)}}),i.detail},async acquireImage(e,n){let r=s.source,i=s.selectedTaskId,a=e.durable?.location.entryId;if(!s.open||!r||!i||!a)throw Error(dy("imageDurableOnly"));let l=JSON.stringify([r.workId,r.sessionId,r.branchId,i,a,n]),o=t.get(l);if(o)return{url:o.url,release:()=>void 0};let c=await d.getImage({source:r,taskId:i,entryId:a,imageIndex:n});if(!s.open||!dj(s.source,r))throw Error(dy("centerClosed"));let u=t.get(l);if(u)return{url:u.url,release:()=>void 0};let m=URL.createObjectURL((0,dw.E)(c));return t.set(l,{taskId:i,url:m}),{url:m,release:()=>void 0}},disconnected(){r+=1,i=!1,s.open&&m({...s,loading:null!==s.selectedTaskId&&void 0===s.details[s.selectedTaskId],refreshing:null!==s.selectedTaskId&&void 0!==s.details[s.selectedTaskId]})},reconnected(){s.open&&s.selectedTaskId&&f(s.selectedTaskId)},dispose(){if(c)return;c=!0;let t=s.source;n+=1,r+=1,i=!1,a?.(),a=null,p(),t&&d.watchDetail({source:t,taskId:null}).catch(()=>void 0),s=dk,o&&clearTimeout(o),o=null,e.clear(),l=()=>void 0}}},[d]),m=(0,r.useCallback)(e=>(0,n.jsx)(dl,{...e,runtime:u,variant:"summary"}),[u]),p=(0,r.useCallback)(e=>(0,n.jsx)(dl,{...e,runtime:u,variant:"menu"}),[u]),h=(0,r.useCallback)(e=>(0,n.jsx)(aq,{open:e.open,connectionReady:e.connectionReady,initialModelTab:"model-presets"===e.initialPage?"presets":void 0,workSessions:e.workSessions,focusedCwd:e.focusedCwd,pluginAttention:e.pluginAttention,onOpenChange:e.onOpenChange,onBeforeReload:e.onBeforeReload,renderPluginSettingsPage:gg,renderMcpSettings:({onBeforeLeaveChange:t})=>(0,n.jsx)(la,{projects:e.workSessions,focusedCwd:e.focusedCwd,onBeforeLeaveChange:t}),renderCapabilityModesSettings:({onBeforeLeaveChange:t})=>(0,n.jsx)(eS,{modeNames:e.capabilityModes,onBeforeLeaveChange:t}),renderPluginManagement:()=>(0,n.jsx)(st,{basicMode:e.basicMode,snapshot:e.pluginManagementSnapshot,biz:c,onSnapshot:e.onPluginManagementSnapshot,onRestartScheduled:e.onPluginRestartScheduled})},`${e.open}:${e.initialPage??"default"}`),[c]);return(0,n.jsx)(gc,{onTerminalReady:l.connected,onTerminalDisconnected:l.disconnected,onOpenTerminal:l.open,onOpenProjectPreviewWindow:e=>{window.open((0,i.Fj)(e),"_blank","noopener,noreferrer")},renderTerminalWorkspace:o,listPluginManagement:c.list,subscribePluginManagementChanges:c.subscribeChanges,onTaskCenterStart:u.start,onTaskCenterDispose:u.dispose,onTaskCenterReconcileWorkSessions:u.reconcileWorkSessions,onTaskCenterDisconnected:u.disconnected,onTaskCenterReconnected:u.reconnected,renderPluginApplication:gd,renderPluginSessionSidebarTab:gu,renderPluginComposerPanel:gm,renderPluginWidgets:gp,renderPluginSessionHeader:gh,renderSettings:h,renderTaskSummary:m,renderTaskMenu:p})}},20314:e=>{e.exports={sidebarAction:"l2-work-session-sidebar_sidebarAction__9dyyW",rowMetadata:"l2-work-session-sidebar_rowMetadata__5pI6i",sessionRow:"l2-work-session-sidebar_sessionRow__gNO1s",runningBorder:"l2-work-session-sidebar_runningBorder__E7unr",rowActions:"l2-work-session-sidebar_rowActions__ioeUA",desktopRow:"l2-work-session-sidebar_desktopRow__RI8_L",rowTitle:"l2-work-session-sidebar_rowTitle__2iXeS"}},26357:(e,t,s)=>{"use strict";s.d(t,{$:()=>n});let n=s(38979).k5(["off","minimal","low","medium","high","xhigh","max"])},33941:(e,t,s)=>{"use strict";s.d(t,{G6:()=>l,Kc:()=>d,W:()=>r,Xm:()=>a,mj:()=>i,uZ:()=>c});var n=s(38979);let r=n.Ik({password:n.Yj().min(1).max(64)}).strict(),i=n.Ik({}).strict();n.Ik({}).strict();let a=n.Ik({}).strict();n.Ik({}).strict();let l=n.Ik({enabled:n.zM(),configPath:n.Yj()}).strict(),o=n.Yj().min(12).max(64).refine(e=>e===e.trim()&&!/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(e)).refine(e=>[/[A-Z]/,/[a-z]/,/[0-9]/,/[\p{P}\p{S}]/u].filter(t=>t.test(e)).length>=3),c=n.KC([r.extend({password:o}),n.Ik({password:n.ch()}).strict()]),d=n.Ik({}).strict()},37975:(e,t,s)=>{"use strict";s.d(t,{D:()=>a,Yj:()=>l,s6:()=>r});var n=s(38979);let r="project-preview",i=n.Ik({directories:n.YO(n.Yj().min(1).max(4096)).max(32),defaultDirectory:n.Yj().min(1).max(4096).nullable()}).strict();function a(e){let t=i.safeParse(e);return t.success?t.data:{directories:[],defaultDirectory:null}}function l(e){let t=e.replaceAll("\\","/").replace(/\/+$/,"")||"/";return/^[a-z]:/i.test(t)||t.startsWith("//")?t.toLowerCase():t}},42515:(e,t,s)=>{"use strict";s.d(t,{OY:()=>u});var n=s(38979),r=s(267),i=s(9626);let a=n.Yj().trim().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),l=n.g1(n.Yj(),n.Pq()),o=n.Ik({pluginName:a,method:a,scope:n.eu("global"),input:l}).strict(),c=n.Ik({pluginName:a,method:a,scope:n.eu("session"),source:r.R,input:l}).strict(),d=n.gM("scope",[o,c]),u=Object.freeze({invoke:(0,i.Vc)({path:"plugins/invoke",inputSchema:d,outputSchema:l})})},42655:(e,t,s)=>{"use strict";s.d(t,{V:()=>a});var n=s(7962),r=s(50153);let i={src:"/_next/static/media/l4-brand-icon.d4f68daf.svg",height:348,width:464,blurWidth:0,blurHeight:0};function a({size:e=40,className:t}){return(0,n.jsx)(r.default,{src:i,width:e,height:3*e/4,alt:"",className:t})}},43769:e=>{e.exports={userText:"l3-conversation-messages_userText__oC8vv",userTextCollapsed:"l3-conversation-messages_userTextCollapsed__EjqBN",detailText:"l3-conversation-messages_detailText__JzS9c",toolOutput:"l3-conversation-messages_toolOutput__qydfS",toolCode:"l3-conversation-messages_toolCode__m6mgv",toolCodeLine:"l3-conversation-messages_toolCodeLine__gVs5q",toolFilePath:"l3-conversation-messages_toolFilePath__br6R2",toolFileDirectory:"l3-conversation-messages_toolFileDirectory__8BdId",usageToolbar:"l3-conversation-messages_usageToolbar__LDQnR",messageCopyAction:"l3-conversation-messages_messageCopyAction__xfZe0",copyableMessage:"l3-conversation-messages_copyableMessage__lrg9E",usageLabeled:"l3-conversation-messages_usageLabeled__BWv7V",usageCompact:"l3-conversation-messages_usageCompact__0ukdy"}},46117:e=>{e.exports={sessionPanelGroup:"l2-workbench-motion_sessionPanelGroup__83WwS",panelGroup:"l2-workbench-motion_panelGroup__yxZEK",drawer:"l2-workbench-motion_drawer____5mR",backdrop:"l2-workbench-motion_backdrop__F0q19",columnContent:"l2-workbench-motion_columnContent__1RfUq"}},46376:e=>{e.exports={markdown:"l3-conversation-markdown_markdown__KmlPt",imageTrigger:"l3-conversation-markdown_imageTrigger__0YMnp",image:"l3-conversation-markdown_image__0h0S8",imageAction:"l3-conversation-markdown_imageAction__mBi4a",imageFallback:"l3-conversation-markdown_imageFallback__F30Mz"}},49230:(e,t,s)=>{"use strict";s.d(t,{L1AppRuntimeProvider:()=>eg});var n=s(7962),r=s(69266),i=s(48708),a=s(5011),l=s(42515),o=s(91399),c=s(38979),d=s(9626),u=s(99739);c.Yj().min(32).max(128).regex(/^[A-Za-z0-9_-]+$/);let m="/api/plugins/host-runtime/v1";Object.freeze({imports:Object.freeze({react:`${m}/base.js`,"react/jsx-runtime":`${m}/base.js`,"react/jsx-dev-runtime":`${m}/base.js`,"react-dom":`${m}/base.js`,"react-dom/client":`${m}/base.js`,"@jetcrab/pi-desk-sdk/react/base":`${m}/base.js`,"@jetcrab/pi-desk-sdk/react/markdown":`${m}/markdown.js`})}),c.eu("v1");let p=c.Ik({pluginName:u.tv,url:c.Yj().regex(/^\/api\/plugins\/browser-resources\/[A-Za-z0-9_-]{32,128}\/entry\.js$/,"Browser Entry URL 无效")}).strict(),h=c.Ik({}).strict(),g=c.Ik({entries:c.YO(p)}).strict(),f=Object.freeze({list:(0,d.Vc)({path:"plugins/browser-entries/list",inputSchema:h,outputSchema:g})}),x=c.Yj().trim().min(1).max(32768),b=c.Ik({text:c.Yj(),truncated:c.zM()}).strict(),v=c.KC([c.Ik({type:c.eu("text_append"),text:c.Yj().min(1)}).strict(),c.Ik({type:c.eu("snapshot"),snapshot:b}).strict(),c.Ik({type:c.eu("unavailable")}).strict()]),w=c.Ik({pluginName:u.tv,path:x}).strict(),y=c.Ik({snapshot:b}).strict(),k=c.Ik({}).strict(),j=c.Ik({pluginName:u.tv,path:x,event:v}).strict(),N=Object.freeze({watch:(0,d.Vc)({path:"plugins/logs/watch",inputSchema:w,outputSchema:y}),unwatch:(0,d.Vc)({path:"plugins/logs/unwatch",inputSchema:w,outputSchema:k}),event:(0,d._G)({path:"plugins/logs/event",bodySchema:j})});var I=s(95826),S=s(267);let C=c.gM("scope",[c.Ik({scope:c.eu("global")}).strict(),c.Ik({scope:c.eu("session"),source:S.R}).strict()]),E=c.Ik({pluginName:u.tv,target:C,event:u.f7,data:u.Dz}).strict(),M=(0,d._G)({path:"plugins/push",bodySchema:E});var z=s(79137),A=s(67765),$=s(74052);function R(e,t,s){let n=e=>{console.error("[Pi Desk][PluginHost] 插件回调执行失败",{pluginName:s,phase:t,message:e instanceof Error?e.message:String(e)})};try{let t=e();"object"==typeof t&&null!==t&&"then"in t&&"function"==typeof t.then&&Promise.resolve(t).catch(n)}catch(e){n(e)}}async function P(e,t,s){let n,r=Promise.resolve().then(s).catch(s=>{console.error("[Pi Desk][PluginHost] 插件资源清理失败",{pluginName:e,phase:t,message:s instanceof Error?s.message:String(s)})});try{await Promise.race([r,new Promise(s=>{n=setTimeout(()=>{console.warn("[Pi Desk][PluginHost] 插件资源清理超时",{pluginName:e,phase:t,timeoutMs:1500}),s()},1500)})])}finally{void 0!==n&&clearTimeout(n)}}let D={text:"",truncated:!1,loading:!0,error:null};function T(e,t){if(t.text!==e.snapshot.text||t.truncated!==e.snapshot.truncated||t.loading!==e.snapshot.loading||t.error!==e.snapshot.error){e.snapshot=t;for(let t of[...e.listeners])R(t,`log:${e.path}`)}}class O{constructor(e,t){this.channel=e,this.connection=t,this.records=new Map,this.connectionEpoch=0,this.disposed=!1,this.unsubscribeEvents=e.subscribe(e=>this.handleEvent(e)),this.unsubscribeConnection=t.subscribe(()=>this.handleConnectionChange())}open(e){if(this.disposed)throw Error("Plugin log host has been disposed");let t=e.trim();if(!t)throw Error("日志路径不能为空");let s=this.records.get(t);s||(s={path:t,references:0,observed:!1,blockedByError:!1,refreshRequested:!1,syncRequested:!1,syncPromise:null,snapshot:{...D},listeners:new Set},this.records.set(t,s)),s.references+=1,this.requestSync(s);let n=!0;return{getSnapshot:()=>s.snapshot,subscribe:e=>{if(!n)throw Error("Plugin log handle has been disposed");return s.listeners.add(e),()=>{s.listeners.delete(e)}},retry:()=>{n&&!this.disposed&&(s.blockedByError=!1,s.refreshRequested=!0,T(s,{...s.snapshot,loading:!0,error:null}),this.requestSync(s))},dispose:()=>{n&&(n=!1,s.references-=1,this.requestSync(s))}}}dispose(){if(!this.disposed){for(let e of(this.disposed=!0,this.unsubscribeEvents(),this.unsubscribeConnection(),this.records.values()))e.observed&&"ready"===this.connection.getSnapshot().status&&this.channel.unwatch(e.path).catch(()=>void 0),e.listeners.clear();this.records.clear()}}handleConnectionChange(){if(this.disposed)return;this.connectionEpoch+=1;let e="ready"===this.connection.getSnapshot().status;for(let t of this.records.values())t.observed=!1,t.blockedByError=!1,t.refreshRequested=e,t.references>0&&T(t,{...t.snapshot,loading:!0,error:e?null:t.snapshot.error}),this.requestSync(t)}handleEvent(e){if(this.disposed)return;let t=this.records.get(e.path);if(t&&0!==t.references){if("text_append"===e.event.type)return void T(t,{...t.snapshot,text:t.snapshot.text+e.event.text,loading:!1,error:null});if("snapshot"===e.event.type)return void T(t,{...e.event.snapshot,loading:!1,error:null});t.observed=!1,t.blockedByError=!0,T(t,{...t.snapshot,loading:!1,error:"日志暂不可用"})}}requestSync(e){this.disposed||(e.syncRequested=!0,e.syncPromise||(e.syncPromise=(async()=>{for(;e.syncRequested&&!this.disposed;)e.syncRequested=!1,await this.reconcileRecord(e)})().finally(()=>{e.syncPromise=null,e.syncRequested&&!this.disposed&&this.requestSync(e)})))}async reconcileRecord(e){if(this.records.get(e.path)!==e)return;let t="ready"===this.connection.getSnapshot().status;if(!(e.references>0&&t&&!e.blockedByError)){if(e.observed&&t){let t=this.connectionEpoch;try{await this.channel.unwatch(e.path)}catch{}t===this.connectionEpoch&&(e.observed=!1)}else e.observed=!1;0!==e.references||e.observed||this.records.delete(e.path);return}if(e.observed&&!e.refreshRequested)return;e.refreshRequested=!1,T(e,{...e.snapshot,loading:!0,error:null});let s=this.connectionEpoch;try{let t=await this.channel.watch(e.path);if(this.disposed||s!==this.connectionEpoch||this.records.get(e.path)!==e)return;e.observed=!0,e.blockedByError=!1,T(e,{...t,loading:!1,error:null})}catch(t){if(s!==this.connectionEpoch||"ready"!==this.connection.getSnapshot().status){e.syncRequested=!0;return}e.observed=!1,e.blockedByError=!0,T(e,{...e.snapshot,loading:!1,error:t instanceof Error&&t.message?t.message:"读取日志失败"})}finally{(0===e.references||e.syncRequested)&&(e.syncRequested=!0)}}}function L(e){if(null!==e&&"object"==typeof e){for(let t of Object.values(e))L(t);Object.freeze(e)}return e}let F=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,B=/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/,q=new Set(["plugin","server","rocket","settings","panel","message","terminal","file","folder","bot","wrench","database","globe"]),_=new Set(["application","composer-panel","settings-page","message-view","session-sidebar-tab"]);function W(e,t){return`${e}\u0000${t}`}function Y(e,t,s){return`${e}\u0000${W(t,s)}`}function V(e,t,s,n){let r=Y(e,t,s);if("session-header-item"!==t)return r;if("inline"!==n&&"overflow"!==n)throw Error("会话标题视图必须指定 inline 或 overflow");return`${r}\u0000${n}`}function U(e){return import(e)}function H(){return"u"<typeof document?{mode:"light"}:((0,$.Is)(),Object.freeze({mode:document.documentElement.classList.contains("dark")?"dark":"light"}))}function K(e,t){return e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}function G(e){return{source:{workId:e.workId,sessionId:e.sessionId,branchId:e.branchId},cwd:e.cwd,status:e.status}}function J(e,t){let s=e.trim();if(!s||s.length>100)throw Error(`${t} must contain 1-100 characters`);return s}function Q(e){if("string"!=typeof e)throw Error("Contribution name 必须是字符串");let t=e.trim();if(!t||t.length>64||!F.test(t))throw Error("Contribution name 必须是 1-64 字符的小写 kebab-case");return t}function X(e){if(void 0!==e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Contribution icon 无效");if("builtin"===e.type){if(2!==Object.keys(e).length||"string"!=typeof e.name||!q.has(e.name))throw Error("Contribution builtin icon 无效");return{type:"builtin",name:e.name}}if("svg"===e.type){let t="string"==typeof e.content?e.content.trim():"";if(2!==Object.keys(e).length||!t||t.length>16384)throw Error("Contribution SVG icon 无效");return{type:"svg",content:t}}throw Error("Contribution icon type 无效")}}function Z(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`会话标题 ${t} 必须提供 action 或 custom 定义`);let s="action"===e.type?["type","icon","label","onSelect"]:"inline"===t?["type","load","minWidthRem"]:["type","load"];for(let n of Object.keys(e))if(!s.includes(n))throw Error(`会话标题 ${t} ${String(e.type)} 不支持字段 ${n}`);if("action"===e.type){if("string"!=typeof e.label)throw Error("会话标题 action label 必须是字符串");let t=X(e.icon);if(!t)throw Error("会话标题 action 必须提供 icon");if("function"!=typeof e.onSelect)throw Error("会话标题 action 必须提供 onSelect()");return{type:"action",label:J(e.label,"Session Header action label"),icon:t,onSelect:e.onSelect}}if("custom"!==e.type)throw Error("会话标题表现 type 必须是 action 或 custom");if("function"!=typeof e.load)throw Error("会话标题 custom 必须提供 load()");if("inline"===t&&("number"!=typeof e.minWidthRem||!Number.isFinite(e.minWidthRem)||e.minWidthRem<=0))throw Error("会话标题 inline custom minWidthRem 必须是正数");return{type:"custom",load:e.load,..."inline"===t?{minWidthRem:e.minWidthRem}:{}}}class ee{constructor(e,t=U,s=()=>void 0){this.transport=e,this.entryImporter=t,this.notifyPlugin=s,this.entryDescriptors=[],this.entryDescriptorsByPlugin=new Map,this.entryStates=new Map,this.ownersByPlugin=new Map,this.registrations=new Map,this.contributionLoadStates=new Map,this.browserDescriptors=[],this.registrySnapshot={revision:0,descriptors:this.browserDescriptors},this.messageViewResolutions=new Map,this.logHosts=new Map,this.registryListeners=new Set,this.workSessionListeners=new Set,this.connectionListeners=new Set,this.themeListeners=new Set,this.globalPluginStates={},this.workSessions=[],this.workSessionCreate=null,this.workSessionGoTo=null,this.projectPreview=null,this.terminalOpen=null,this.workSessionFilePreview=null,this.workSessionFileReveal=null,this.imageReader=null,this.connectionSnapshot={status:"disconnected",error:null},this.themeSnapshot={mode:"light"},this.refreshPromise=null,this.refreshPending=!1,this.entriesMaintaining=!1,this.entriesInitialized=!1,this.entryListError=null,this.applicationResolveController=null,this.applicationResolveEpoch=0,this.applicationVisibility=new Map,this.disposed=!1,this.unsubscribePush=e.subscribePush(e=>this.dispatchPush(e));const n=()=>{let e=H();e.mode!==this.themeSnapshot.mode&&(this.themeSnapshot=e,this.notify(this.themeListeners))};this.themeSnapshot=H(),this.unsubscribeTheme=(0,$.Cy)(n);const r=window.matchMedia("(prefers-color-scheme: dark)");r.addEventListener("change",n),this.removeSystemThemeListener=()=>r.removeEventListener("change",n)}subscribeRegistry(e){return this.registryListeners.add(e),()=>this.registryListeners.delete(e)}getBrowserDescriptors(){return this.browserDescriptors}getRegisteredBrowserDescriptors(){return[...this.ownersByPlugin.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({pluginName:e,contributions:[...t.registrations.values()].sort((e,t)=>{let s=e.kind.localeCompare(t.kind);return 0===s?e.contributionName.localeCompare(t.contributionName):s}).map(e=>structuredClone(e.descriptor))}))}getRegistrySnapshot(){return this.registrySnapshot}areEntriesInitialized(){return this.entriesInitialized}isRefreshingEntries(){return this.entriesMaintaining||null!==this.refreshPromise}setEntriesMaintaining(e){this.disposed||this.entriesMaintaining===e||(this.entriesMaintaining=e,this.publishRegistryChange())}getEntryListError(){return this.entryListError}getEntryState(e){return this.entryStates.get(e)??{status:"unloaded"}}getFailedEntries(){return[...this.entryStates.entries()].flatMap(([e,t])=>"failed"===t.status?[{pluginName:e,error:t.error}]:[])}getContributionLoadState(e,t,s,n){return this.contributionLoadStates.get(V(e,t,s,n))??{status:"unloaded"}}getMessageViewResolution(e){return this.messageViewResolutions.get(e)??null}bindWorkSessionCreate(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(this.workSessionCreate)throw Error("Workbench WorkSession 创建能力已经绑定");this.workSessionCreate=e;let t=!0;return()=>{t&&(t=!1,this.workSessionCreate===e&&(this.workSessionCreate=null))}}bindWorkSessionGoTo(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(this.workSessionGoTo)throw Error("Workbench WorkSession 前往能力已经绑定");this.workSessionGoTo=e;let t=!0;return()=>{t&&(t=!1,this.workSessionGoTo===e&&(this.workSessionGoTo=null))}}bindTerminalOpen(e){if(this.disposed)throw Error("Plugin Host Runtime 已释放");if(this.terminalOpen)throw Error("终端创建能力已经绑定");return this.terminalOpen=e,()=>{this.terminalOpen===e&&(this.terminalOpen=null)}}bindProjectPreview(e){if(this.disposed)throw Error("Plugin Host Runtime 已释放");if(this.projectPreview)throw Error("项目预览能力已经绑定");return this.projectPreview=e,()=>{this.projectPreview===e&&(this.projectPreview=null)}}previewProject(e){if(this.disposed)throw Error("Plugin Host Runtime 已释放");if("string"!=typeof e||!e.trim())throw Error("项目预览需要有效目录");if(!this.projectPreview)throw Error("项目预览尚未准备好");this.projectPreview(e.trim())}bindWorkSessionFilePreview(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(this.workSessionFilePreview)throw Error("Workbench 文件预览能力已经绑定");this.workSessionFilePreview=e;let t=!0;return()=>{t&&(t=!1,this.workSessionFilePreview===e&&(this.workSessionFilePreview=null))}}bindImageReader(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(this.imageReader)throw Error("Workbench 图片读取能力已经绑定");return this.imageReader=e,()=>{this.imageReader===e&&(this.imageReader=null)}}bindWorkSessionFileReveal(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(this.workSessionFileReveal)throw Error("Workbench 文件定位能力已经绑定");this.workSessionFileReveal=e;let t=!0;return()=>{t&&(t=!1,this.workSessionFileReveal===e&&(this.workSessionFileReveal=null))}}replaceGlobalPluginStates(e){let t=L(structuredClone(e)),s=[...new Set([...Object.keys(this.globalPluginStates),...Object.keys(t)])].filter(e=>JSON.stringify(this.globalPluginStates[e]??null)!==JSON.stringify(t[e]??null));if(0!==s.length){for(let e of(this.globalPluginStates=t,s)){let t=this.ownersByPlugin.get(e);t&&this.notify(t.globalStateListeners)}this.entriesInitialized&&s.some(e=>[...this.ownersByPlugin.get(e)?.registrations.values()??[]].some(e=>"application"===e.kind&&e.resolve))&&this.scheduleApplicationResolution()}}async dispatchNotificationEvent(e,t){let s=this.entryStates.get(t.pluginName);if(s?.status!=="ready")throw Error(`插件 Browser Entry 尚未就绪:${t.pluginName}`);let n=s.runtime.owner,r=n.notificationEventListeners.get(t.name);if(!r)throw Error(`插件未注册通知事件:${t.pluginName}/${t.name}`);if(await r({notificationId:e,data:structuredClone(t.data)}),!n.active)throw Error("Browser Entry 已失效")}replaceWorkSessions(e){var t;let s=L(e.map(G));t=this.workSessions,!(t.length===s.length&&t.every((e,t)=>void 0!==s[t]&&K(e.source,s[t].source)&&e.cwd===s[t].cwd&&e.status===s[t].status))&&(this.workSessions=s,this.notify(this.workSessionListeners),this.entriesInitialized&&this.scheduleApplicationResolution())}markConnecting(){this.replaceConnection({status:"connecting",error:null})}markReady(){this.replaceConnection({status:"ready",error:null})}markDisconnected(e=null){this.setEntriesMaintaining(!1),this.replaceConnection({status:"disconnected",error:e})}async refreshEntries(){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");return this.refreshPromise?this.refreshPending=!0:(this.entriesInitialized||this.replaceEntriesInitialized(!1),this.refreshPromise=(async()=>{try{do{this.refreshPending=!1;let e=await this.transport.listBrowserEntries();if(this.disposed||this.entriesMaintaining||(await this.replaceEntries(e),this.disposed))return;this.replaceEntriesInitialized(!0),this.replaceEntryListError(null)}while(this.refreshPending&&!this.disposed)}catch(e){throw this.replaceEntriesInitialized(!0),this.replaceEntryListError(e instanceof Error?e.message:String(e)),this.rebuildRegistry(),e}})().finally(()=>{this.refreshPromise=null,this.disposed||this.publishRegistryChange()}),this.publishRegistryChange()),this.refreshPromise}retryEntry(e){return this.entryStates.get(e)?.status==="failed"&&(this.entryStates.delete(e),this.publishRegistryChange()),this.loadEntry(e).then(async e=>(await this.resolveApplications(),e))}retryContribution(e,t,s,n){let r=Y(e,t,s),i=V(e,t,s,n);this.contributionLoadStates.get(i)?.status==="failed"&&(this.contributionLoadStates.delete(i),this.publishRegistryChange());let a=this.registrations.get(r);return a?this.loadContribution(a,n):Promise.reject(new z.qj({pluginName:e,contributionName:s,phase:"registration",message:"插件 Contribution 不存在"}))}async invokeSessionHeaderAction(e){let t=Y(e.pluginName,"session-header-item",e.contributionName),s=this.registrations.get(t),n=s?.header?.[e.presentation];if(!s||n?.type!=="action")throw Error("会话标题 action 不存在");if(e.signal.throwIfAborted(),!s.owner.active)throw Error("Browser Entry 已失效");if(!this.workSessions.some(t=>K(t.source,e.source)))throw Error("工作会话来源已变化");let r=this.getHeaderActionScope(s,e.source,e.signal);try{if(await n.onSelect({...r}),r.signal.throwIfAborted(),!s.owner.active||this.registrations.get(t)!==s)throw Error("Browser Entry 已失效")}catch(s){let t=new z.qj({pluginName:e.pluginName,contributionName:e.contributionName,phase:"session-header-action",message:s instanceof Error?s.message:String(s),cause:s});throw r.signal.aborted||R(()=>{throw t},`header-action:${e.contributionName}:${e.presentation}`,e.pluginName),t}}getHeaderActionScope(e,t,s){let n=e.headerActionScopes??=new WeakMap,r=n.get(s);if(r){if(!K(r.source,t))throw Error("会话标题展示来源不一致");return r}let i=e.owner,a=L(structuredClone(t)),l=new AbortController,o={...i,subscriptionDisposers:new Set,get active(){return i.active&&!l.signal.aborted}},c=()=>{for(let t of(l.abort(),n.delete(s),this.workSessionListeners.delete(d),i.subscriptionDisposers.delete(c),s.removeEventListener("abort",c),o.subscriptionDisposers))R(t,"header-action-dispose",e.pluginName);o.subscriptionDisposers.clear()},d=()=>{this.workSessions.some(e=>K(e.source,a))||c()},u={source:a,host:this.createBrowserHost(o),signal:l.signal};return n.set(s,u),this.workSessionListeners.add(d),i.subscriptionDisposers.add(c),s.addEventListener("abort",c,{once:!0}),u}async mountContribution(e){let t=Y(e.pluginName,e.kind,e.contributionName),s=this.registrations.get(t);if(!s)throw new z.qj({pluginName:e.pluginName,contributionName:e.contributionName,phase:"registration",message:"插件 Contribution 不存在"});if(s.kind!==e.target.kind)throw Error("Contribution kind 与 mount target 不一致");let n=new AbortController,r=new Promise(e=>{n.signal.addEventListener("abort",()=>e(),{once:!0})}),i=e.target;("widget"===i.kind||"session-header-item"===i.kind)&&(i={...i,source:L(structuredClone(i.source))});let a="widget"===i.kind||"session-header-item"===i.kind?i.source:null,l="session-header-item"===i.kind?i.presentation:void 0,o=()=>{a&&!this.workSessions.some(e=>K(e.source,a))&&m()};if("session-sidebar-tab"===i.kind&&i.setHeaderActions){let t=i.setHeaderActions,r=[];n.signal.addEventListener("abort",()=>{r=[],t([])},{once:!0}),i={...i,setHeaderActions:i=>{if(n.signal.aborted||!s.owner.active)return;if(!Array.isArray(i))throw Error("侧栏操作必须为数组");let a=i.map(t=>{let i=J(t.label,"Sidebar action label"),l=X(t.icon),o=!0===t.disabled,c=!0===t.busy,d=t.onSelect;if("function"!=typeof d)throw Error("侧栏操作缺少 onSelect 回调");let u=!1;return{label:i,icon:l,disabled:o,busy:c,onSelect:()=>{n.signal.aborted||!s.owner.active||r!==a||o||c||u||(u=!0,R(async()=>{try{await d()}catch(e){throw!n.signal.aborted&&s.owner.active&&s.owner.host.notify({level:"error",title:i,description:e instanceof Error?e.message:String(e)}),e}finally{u=!1}},`sidebar-action:${i}`,e.pluginName))}}});r=a,t(a)}}}let c=Promise.resolve().then(async()=>{if(n.signal.aborted)throw Error("插件视图已关闭");let t=await this.loadContribution(s,l);if(n.signal.aborted||!s.owner.active)throw Error("插件视图已失效");let r=t.mount,a=await r({container:e.container,target:i,host:s.owner.host,signal:n.signal});if(void 0!==a&&"function"!=typeof a)throw Error("Contribution mount must return void or a disposer");return a??null}),d=null,u=()=>d||(s.owner.mounts.delete(u),e.signal?.removeEventListener("abort",m),this.workSessionListeners.delete(o),n.abort(),d=P(e.pluginName,`mount:${e.contributionName}`,async()=>{let e=await c.catch(()=>null);await e?.()})),m=()=>{u()};s.owner.mounts.add(u),a&&this.workSessionListeners.add(o),e.signal?.addEventListener("abort",m,{once:!0}),e.signal?.aborted&&m(),o();try{if(await Promise.race([c,r]),n.signal.aborted||!s.owner.active)throw Error("插件视图已失效");return u}catch(t){if(await u(),t instanceof z.qj)throw t;throw new z.qj({pluginName:e.pluginName,contributionName:e.contributionName,phase:"mount",message:t instanceof Error?t.message:String(t),cause:t})}}async dispose(){if(this.disposed)return;this.disposed=!0,this.applicationResolveController?.abort(),this.applicationResolveController=null,this.unsubscribePush(),this.unsubscribeTheme(),this.removeSystemThemeListener();let e=[...this.ownersByPlugin.values()].reverse();for(let t of(this.ownersByPlugin.clear(),await Promise.all(e.map(e=>this.disposeEntryOwner(e))),this.entriesMaintaining=!1,this.entryStates.clear(),this.entryDescriptorsByPlugin.clear(),this.entryDescriptors=[],this.registrations.clear(),this.contributionLoadStates.clear(),this.browserDescriptors=[],this.messageViewResolutions.clear(),this.applicationVisibility.clear(),this.logHosts.values()))t.dispose();this.logHosts.clear(),this.globalPluginStates={},this.workSessionCreate=null,this.workSessionGoTo=null,this.workSessionFilePreview=null,this.workSessionFileReveal=null,this.imageReader=null,this.projectPreview=null,this.terminalOpen=null,this.registryListeners.clear(),this.workSessionListeners.clear(),this.connectionListeners.clear(),this.themeListeners.clear()}async replaceEntries(e){var t;let s=[...e].sort((e,t)=>e.pluginName.localeCompare(t.pluginName)),n=new Map;for(let e of s){if(n.has(e.pluginName))throw Error(`重复 Plugin Browser Entry:${e.pluginName}`);n.set(e.pluginName,e)}for(let[e,t]of this.entryDescriptorsByPlugin){let s=n.get(e);s?.url!==t.url&&this.disposeEntry(e)}if(this.disposed)return;for(let[e,t]of(this.entryDescriptorsByPlugin.clear(),n))this.entryDescriptorsByPlugin.set(e,t);let r=(t=this.entryDescriptors,JSON.stringify(t)!==JSON.stringify(s));this.entryDescriptors=structuredClone(s),await Promise.allSettled(s.map(e=>this.loadEntry(e.pluginName))),await this.resolveApplications(),r&&this.publishRegistryChange()}loadEntry(e){if(this.disposed)return Promise.reject(Error("Plugin Host Runtime has been disposed"));let t=this.entryDescriptorsByPlugin.get(e);if(!t)return Promise.reject(Error(`Plugin Browser Entry 不存在:${e}`));let s=this.entryStates.get(e);if(s?.status==="ready")return Promise.resolve(s.runtime);if(s?.status==="loading")return s.promise;if(s?.status==="failed")return Promise.reject(s.error);let n=this.initializeEntry(t).then(s=>(this.disposed||this.entryDescriptorsByPlugin.get(e)?.url!==t.url?s.dispose():(this.entryStates.set(e,{status:"ready",runtime:s}),this.ownersByPlugin.set(e,s.owner),this.commitRegistrations(s.owner),this.rebuildRegistry()),this.publishRegistryChange(),s),s=>{let n=s instanceof Error?s:new z.qj({pluginName:e,phase:"entry-import",message:String(s)});throw this.disposed||this.entryDescriptorsByPlugin.get(e)?.url!==t.url||(this.entryStates.set(e,{status:"failed",error:n}),this.rebuildRegistry(),this.publishRegistryChange()),n});return this.entryStates.set(e,{status:"loading",promise:n}),this.publishRegistryChange(),n}async initializeEntry(e){let t;try{t=await this.entryImporter(e.url)}catch(t){throw new z.qj({pluginName:e.pluginName,phase:"entry-import",message:t instanceof Error?t.message:"Browser Entry import 失败",cause:t})}if(this.disposed||this.entryDescriptorsByPlugin.get(e.pluginName)?.url!==e.url)throw Error("Browser Entry 已失效");if("function"!=typeof t.default)throw new z.qj({pluginName:e.pluginName,phase:"entry-factory",message:"Browser Entry 必须 default-export defineBrowserEntry(...)"});let s={descriptor:e,registrations:new Map,pushListeners:new Set,notificationEventListeners:new Map,globalStateListeners:new Set,subscriptionDisposers:new Set,mounts:new Set,disposer:null,registrationOpen:!0,active:!0},n=Object.assign(s,{host:this.createBrowserHost(s)});try{let s=t.default(this.createBrowserFacade(e.pluginName,n));if(n.registrationOpen=!1,"object"==typeof s&&null!==s&&"function"==typeof Reflect.get(s,"then"))throw R(async()=>{let t=await s;"function"==typeof t&&await P(e.pluginName,"entry-factory",async()=>{await t()})},"entry-factory",e.pluginName),Error("Browser Entry factory must register synchronously");if(void 0!==s&&"function"!=typeof s)throw Error("Browser Entry factory must return void or a disposer");n.disposer=s??null}catch(t){throw n.registrationOpen=!1,await this.disposeEntryOwner(n),new z.qj({pluginName:e.pluginName,phase:"entry-factory",message:t instanceof Error?t.message:String(t),cause:t})}return{pluginName:e.pluginName,owner:n,dispose:()=>this.disposeEntryOwner(n)}}createBrowserFacade(e,t){let s=s=>{if(!t.active||!t.registrationOpen)throw Error("Browser Entry registration phase has ended");let n=s(),r=W(n.kind,n.contributionName);if(t.registrations.has(r))throw Error(`Browser Contribution 重复:${e}/${n.kind}/${n.contributionName}`);t.registrations.set(r,n)};return{name:e,host:t.host,notifications:{onEvent:(s,n)=>{if(!t.active)throw Error("Browser Entry owner is no longer active");let r=Q(s);if(t.notificationEventListeners.has(r))throw Error(`Browser Notification Event 重复:${e}/${r}`);return t.notificationEventListeners.set(r,n),()=>{t.notificationEventListeners.get(r)===n&&t.notificationEventListeners.delete(r)}}},notify:s=>{t.active&&this.notifyPlugin(e,structuredClone(s))},registerContribution:(n,r,i)=>{s(()=>{if(!_.has(n))throw Error(`Browser Contribution kind 无效:${String(n)}`);return this.createRegistration(e,n,r,i,t)})},registerWidget:(n,r)=>{s(()=>this.createWidgetRegistration(e,n,r,t))},registerSessionHeaderItem:(n,r)=>{s(()=>this.createHeaderRegistration(e,n,r,t))},onPush:e=>{if(!t.active)throw Error("Browser Entry owner is no longer active");return t.pushListeners.add(e),()=>{t.pushListeners.delete(e)}}}}createRegistration(e,t,s,n,r){let i=Q(s);if(!n||"object"!=typeof n||"function"!=typeof n.load)throw Error(`Browser Contribution 必须提供 load():${t}/${i}`);if("application"===t){let s=J(n.label,"Application label"),a=X(n.icon),l=n.chrome??"host";if("host"!==l&&"none"!==l)throw Error("Application chrome 必须是 host 或 none");if(void 0!==n.resolve&&"function"!=typeof n.resolve)throw Error("Application resolve 必须是函数");return{pluginName:e,kind:t,contributionName:i,descriptor:{kind:t,contributionName:i,label:s,title:J(n.title??s,"Application title"),...a?{icon:a}:{},chrome:l},load:n.load,resolve:n.resolve,owner:r}}if("composer-panel"===t){let s=X(n.icon);return{pluginName:e,kind:t,contributionName:i,descriptor:{kind:t,contributionName:i,label:J(n.label,"Composer Panel label"),...s?{icon:s}:{}},load:n.load,owner:r}}if("settings-page"===t){let s=X(n.icon);return{pluginName:e,kind:t,contributionName:i,descriptor:{kind:t,contributionName:i,label:J(n.label,"Settings Page label"),...s?{icon:s}:{}},load:n.load,owner:r}}if("message-view"===t)return{pluginName:e,kind:t,contributionName:i,descriptor:{kind:t,contributionName:i,viewKey:function(e){if("string"!=typeof e)throw Error("Message View viewKey 必须是字符串");let t=e.trim();if(t.length<3||t.length>129||!B.test(t))throw Error("Message View viewKey 必须是 plugin-name/view-name");return t}(n.viewKey),priority:function(e){if(!Number.isSafeInteger(e))throw Error("Message View priority must be a safe integer");return e}(n.priority)},load:n.load,owner:r};let a=X(n.icon);return{pluginName:e,kind:"session-sidebar-tab",contributionName:i,descriptor:{kind:"session-sidebar-tab",contributionName:i,label:J(n.label,"Session Sidebar Tab label"),...a?{icon:a}:{}},load:n.load,owner:r}}createWidgetRegistration(e,t,s,n){let r=Q(t);if(!s||"object"!=typeof s||"function"!=typeof s.load)throw Error("Browser Widget 必须提供 load()");let i=s.placement??"aboveEditor";if("aboveEditor"!==i&&"belowEditor"!==i)throw Error("Browser Widget placement 必须是 aboveEditor 或 belowEditor");return{pluginName:e,kind:"widget",contributionName:r,descriptor:{kind:"widget",contributionName:r,placement:i},load:s.load,owner:n}}createHeaderRegistration(e,t,s,n){let r=Q(t);if(!s||"object"!=typeof s||Array.isArray(s))throw Error("会话标题条目必须提供 inline 和 overflow");for(let e of Object.keys(s))if("inline"!==e&&"overflow"!==e)throw Error(`会话标题条目不支持顶层字段 ${e}`);let i=Z(s.inline,"inline"),a=Z(s.overflow,"overflow");return{pluginName:e,kind:"session-header-item",contributionName:r,descriptor:{kind:"session-header-item",contributionName:r,inline:"action"===i.type?{type:"action",icon:i.icon,label:i.label}:{type:"custom",minWidthRem:i.minWidthRem},overflow:"action"===a.type?{type:"action",icon:a.icon,label:a.label}:{type:"custom"}},header:{inline:i,overflow:a},owner:n}}commitRegistrations(e){for(let t of e.registrations.values()){let e=Y(t.pluginName,t.kind,t.contributionName);if(this.registrations.has(e))throw Error(`Browser Contribution Registry 重复:${e}`);this.registrations.set(e,t)}}loadContribution(e,t){let s=Y(e.pluginName,e.kind,e.contributionName),n=V(e.pluginName,e.kind,e.contributionName,t),r=t?e.header?.[t]:void 0,i=r?.type==="custom"?r.load:e.load;if(!i)return Promise.reject(Error("会话标题 action 不支持加载视图"));if(!e.owner.active||this.registrations.get(s)!==e)return Promise.reject(Error("Browser Contribution 已失效"));let a=this.contributionLoadStates.get(n);if(a?.status==="ready")return Promise.resolve(a.implementation);if(a?.status==="loading")return a.promise;if(a?.status==="failed")return Promise.reject(a.error);let l=Promise.resolve().then(i).then(t=>{if(!t||"function"!=typeof t.mount)throw Error("Lazy Contribution Module 必须导出 mount()");if(!e.owner.active||this.registrations.get(s)!==e)throw Error("Browser Contribution 已失效");return this.contributionLoadStates.set(n,{status:"ready",implementation:t}),this.publishRegistryChange(),t},e=>{throw e}).catch(t=>{let r=t instanceof Error?t:new z.qj({pluginName:e.pluginName,contributionName:e.contributionName,phase:"contribution-load",message:String(t)});throw e.owner.active&&this.registrations.get(s)===e&&(this.contributionLoadStates.set(n,{status:"failed",error:r}),this.publishRegistryChange()),r});return this.contributionLoadStates.set(n,{status:"loading",promise:l}),this.publishRegistryChange(),l}async resolveApplications(){if(this.disposed)return;let e=new AbortController;this.applicationResolveController?.abort(),this.applicationResolveController=e;let t=++this.applicationResolveEpoch,s=[...this.registrations.values()].filter(e=>"application"===e.kind),n=new Map;if(await Promise.all(s.map(async t=>{let s=Y(t.pluginName,t.kind,t.contributionName);if(!t.resolve)return void n.set(s,!0);try{let r=await t.resolve({workSessions:this.workSessions,host:t.owner.host,signal:e.signal});e.signal.aborted||n.set(s,!1!==r)}catch(r){if(e.signal.aborted)return;n.set(s,!1),console.warn("[Pi Desk][PluginHost] Application resolve 失败",{pluginName:t.pluginName,contributionName:t.contributionName,errorName:r instanceof Error?r.name:"UnknownError",message:r instanceof Error?r.message:String(r)})}})),!this.disposed&&!e.signal.aborted&&this.applicationResolveController===e&&this.applicationResolveEpoch===t){for(let[e,t]of(this.applicationVisibility.clear(),n))this.applicationVisibility.set(e,t);this.rebuildRegistry()}}scheduleApplicationResolution(){queueMicrotask(()=>{this.disposed||this.resolveApplications().catch(e=>{console.error("[Pi Desk][PluginHost] 刷新 Application 可见性失败",{errorName:e instanceof Error?e.name:"UnknownError",message:e instanceof Error?e.message:String(e)})})})}rebuildRegistry(){let e=[...this.ownersByPlugin.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({pluginName:e,contributions:[...t.registrations.values()].filter(e=>"application"!==e.kind||(this.applicationVisibility.get(Y(e.pluginName,e.kind,e.contributionName))??!1)).sort((e,t)=>{let s=e.kind.localeCompare(t.kind);return 0===s?e.contributionName.localeCompare(t.contributionName):s}).map(e=>structuredClone(e.descriptor))}));JSON.stringify(this.browserDescriptors)!==JSON.stringify(e)&&(this.browserDescriptors=e,this.rebuildMessageViewResolutions(),this.publishRegistryChange())}rebuildMessageViewResolutions(){this.messageViewResolutions.clear();let e=new Map;for(let t of this.browserDescriptors)for(let s of t.contributions){if("message-view"!==s.kind)continue;let n=e.get(s.viewKey)??[];n.push({pluginName:t.pluginName,descriptor:s}),e.set(s.viewKey,n)}for(let[t,s]of e){let e=Math.max(...s.map(e=>e.descriptor.priority)),n=s.filter(t=>t.descriptor.priority===e);this.messageViewResolutions.set(t,1===n.length?{status:"winner",...n[0]}:{status:"conflict",viewKey:t,candidates:n})}}disposeEntry(e){this.entryDescriptorsByPlugin.delete(e),this.entryStates.delete(e);let t=this.ownersByPlugin.get(e);this.ownersByPlugin.delete(e),t&&this.disposeEntryOwner(t),this.rebuildRegistry()}async disposeEntryOwner(e){if(!e.active)return;for(let t of(e.active=!1,e.registrationOpen=!1,e.pushListeners.clear(),e.notificationEventListeners.clear(),e.globalStateListeners.clear(),e.subscriptionDisposers))R(t,"entry-subscription-dispose",e.descriptor.pluginName);e.subscriptionDisposers.clear();let t=this.logHosts.get(e.descriptor.pluginName);for(let s of(t===e.host.logs&&(this.logHosts.delete(e.descriptor.pluginName),R(()=>t.dispose(),"logs-dispose",e.descriptor.pluginName)),e.registrations.values())){let e=Y(s.pluginName,s.kind,s.contributionName);this.registrations.get(e)===s&&(this.registrations.delete(e),this.contributionLoadStates.delete(e),"session-header-item"===s.kind&&(this.contributionLoadStates.delete(`${e}\u0000inline`),this.contributionLoadStates.delete(`${e}\u0000overflow`)),this.applicationVisibility.delete(e))}let s=[...e.mounts].reverse();e.mounts.clear();let n=e.disposer;e.disposer=null,e.registrations.clear(),await Promise.all(s.map(e=>e())),n&&await P(e.descriptor.pluginName,"entry-dispose",n)}previewWorkSessionFile(e,t,s){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if("string"!=typeof t||!t.trim())throw Error("文件预览需要有效路径");let n=function(e){if(void 0!==e&&(null===e||"object"!=typeof e||Array.isArray(e)))throw Error("文件预览选项无效");let t=e?.mode;if(void 0===t||"session"===t||"expanded"===t||"standalone"===t)return t??"session";throw Error("文件预览模式无效")}(s),r=this.workSessions.find(t=>K(t.source,e));if(!r)throw Error("工作会话来源已变化");let i=this.workSessionFilePreview;if(!i)throw Error("Workbench 尚未准备好预览文件");i({source:structuredClone(r.source),cwd:r.cwd,path:t.trim(),mode:n,...s?.imagePaths===void 0?{}:{imagePaths:s.imagePaths}})}async revealWorkSessionFile(e,t){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if("string"!=typeof t||!t.trim())throw Error("文件定位需要有效路径");let s=this.workSessions.find(t=>K(t.source,e));if(!s)throw Error("工作会话来源已变化");let n=this.workSessionFileReveal;if(!n)throw Error("Workbench 尚未准备好定位文件");await n({source:structuredClone(s.source),cwd:s.cwd,path:t.trim()})}async readImage(e,t,s){s.throwIfAborted();let n=A._g.parse(t),r=this.workSessions.find(t=>K(t.source,e));if(!r)throw Error("工作会话来源已变化");let i=this.imageReader;if(!i)throw Error("Workbench 尚未准备好读取图片");let a=await i({source:structuredClone(r.source),cwd:r.cwd,path:n},s);if(s.throwIfAborted(),!this.workSessions.some(t=>K(t.source,e)))throw Error("工作会话来源已变化");return a}async createWorkSession(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if(!e||"string"!=typeof e.cwd||!e.cwd.trim())throw Error("创建工作会话需要有效 cwd");let t=this.workSessionCreate;if(!t)throw Error("Workbench 尚未准备好创建工作会话");return G(await t(e.cwd.trim()))}async goToWorkSession(e){if(this.disposed)throw Error("Plugin Host Runtime has been disposed");if("workId"in e){if("string"!=typeof e.workId||!e.workId.trim())throw Error("前往工作会话需要有效 workId")}else{if("string"!=typeof e.sessionId||!e.sessionId.trim())throw Error("前往工作会话需要有效 sessionId");if(void 0!==e.cwd&&("string"!=typeof e.cwd||!e.cwd.trim()))throw Error("cwd 必须是非空字符串")}let t=this.workSessionGoTo;if(!t)throw Error("Workbench 尚未准备好前往工作会话");return G(await t(e))}createBrowserHost(e){let t=e.descriptor.pluginName,s=()=>{if(!e.active||this.disposed)throw Error("Browser Entry 已失效")},n=async e=>{s();let t=await e();return s(),t},r=this.transport.createPiDeskChannel(t),a=this.transport.pi,l=(n,r,i)=>{s();let a=()=>{e.active&&R(r,i,t)},l=()=>{n.delete(a),e.subscriptionDisposers.delete(l)};return n.add(a),e.subscriptionDisposers.add(l),l},o={getSnapshot:()=>(s(),this.connectionSnapshot),subscribe:e=>l(this.connectionListeners,e,"connection")},c=this.logHosts.get(t);return c||(c=new O(this.transport.createLogChannel(t),{getSnapshot:()=>this.connectionSnapshot,subscribe:o.subscribe}),this.logHosts.set(t,c)),{settings:{getSnapshot:()=>(s(),(0,i.SJ)()),subscribe:n=>{s();let r=(0,i.ae)(()=>{e.active&&R(n,"settings",t)});return e.subscriptionDisposers.add(r),()=>{e.subscriptionDisposers.delete(r),r()}}},notify:e=>{s(),this.notifyPlugin(t,structuredClone(e))},locale:{getSnapshot:()=>(s(),(0,i.SJ)().region)},globalState:{getSnapshot:()=>(s(),this.globalPluginStates[t]??null),subscribe:t=>l(e.globalStateListeners,t,"global-state")},piDesk:{invokeGlobal:(e,t)=>n(()=>r.invokeGlobal(e,t)),invokeSession:(e,t,s)=>n(()=>r.invokeSession(e,t,s))},pi:{prompt:(e,t)=>n(()=>a.prompt(e,t)),commands:{list:e=>n(()=>a.commands.list(e)),execute:(e,t,s)=>n(()=>a.commands.execute(e,t,s))},tools:{list:e=>n(()=>a.tools.list(e))},bash:{execute:(e,t)=>n(()=>a.bash.execute(e,t)),abort:e=>n(()=>a.bash.abort(e))},interrupt:e=>n(()=>a.interrupt(e))},workSessions:{getSnapshot:()=>(s(),this.workSessions),subscribe:e=>l(this.workSessionListeners,e,"work-sessions"),create:e=>n(()=>this.createWorkSession(e)),goTo:e=>n(()=>this.goToWorkSession(e))},workSessionFiles:{preview:(e,t,n)=>{s(),this.previewWorkSessionFile(e,t,n)},reveal:(e,t)=>n(()=>this.revealWorkSessionFile(e,t)),readImage:(t,s,r)=>n(async()=>{let n=new AbortController,i=()=>n.abort();e.subscriptionDisposers.add(i);try{return await this.readImage(t,s,r?AbortSignal.any([r,n.signal]):n.signal)}finally{e.subscriptionDisposers.delete(i)}})},projects:{preview:e=>{s(),this.previewProject(e)}},terminals:{open:t=>n(async()=>{if(!t||"string"!=typeof t.cwd||!t.cwd.trim())throw Error("新建终端需要有效 cwd");let s=this.terminalOpen;if(!s)throw Error("终端创建能力尚未准备好");let n=new AbortController,r=()=>n.abort();e.subscriptionDisposers.add(r);try{await s(t.cwd,n.signal)}finally{e.subscriptionDisposers.delete(r)}})},logs:c,connection:o,theme:{getSnapshot:()=>(s(),this.themeSnapshot),subscribe:e=>l(this.themeListeners,e,"theme")}}}dispatchPush(e){let t=this.entryStates.get(e.pluginName);if(t?.status!=="ready")return;let s=t.runtime.owner;for(let t of[...s.pushListeners]){if(!s.active)break;R(()=>t(e),`push:${e.event}`,e.pluginName)}}replaceEntriesInitialized(e){this.entriesInitialized!==e&&(this.entriesInitialized=e,this.publishRegistryChange())}replaceEntryListError(e){this.entryListError!==e&&(this.entryListError=e,this.publishRegistryChange())}replaceConnection(e){(e.status!==this.connectionSnapshot.status||e.error!==this.connectionSnapshot.error)&&(this.connectionSnapshot=Object.freeze({...e}),this.notify(this.connectionListeners))}publishRegistryChange(){this.registrySnapshot={revision:this.registrySnapshot.revision+1,descriptors:this.browserDescriptors},this.notify(this.registryListeners)}notify(e){for(let t of[...e])R(t,"notify")}}var et=s(78121),es=s(24925),en=s(48155),er=s(49362),ei=s(5464),ea=s(86963),el=s(49426),eo=s(57252),ec=s(64334);function ed({clientId:e,cwd:t,onClose:s}){let{t:i}=(0,et.Bd)("projectHistory"),[a,l]=(0,r.useState)(()=>(0,ec.N1)().maximized),o=t.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??t;return(0,n.jsx)(ei.YV,{open:!0,onOpenChange:e=>{e||s()},children:(0,n.jsxs)(ei.hA,{showCloseButton:!1,"data-testid":"project-preview-dialog",className:(0,el.cn)("h-[min(94dvh,1080px)] w-[min(96dvw,1600px)] max-w-none gap-0 p-0",a&&"h-dvh max-h-none w-dvw rounded-none","max-sm:h-dvh max-sm:max-h-none max-sm:w-dvw max-sm:rounded-none"),children:[(0,n.jsx)(ei.uX,{className:"sr-only",children:i("previewDescription")}),(0,n.jsx)(eo.q,{clientId:e,cwd:t,refreshOnFocus:!0,onEscape:s,title:(0,n.jsx)(ei.YM,{className:"truncate text-sm",title:t,children:o}),actions:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ea.$,{size:"icon-sm",variant:"ghost",className:"max-md:hidden","aria-label":i(a?"restoreWindow":"maximizeWindow"),onClick:()=>{l(!a),(0,ec.Ms)({...(0,ec.N1)(),maximized:!a})},children:a?(0,n.jsx)(es.A,{className:"size-4"}):(0,n.jsx)(en.A,{className:"size-4"})}),(0,n.jsx)(ea.$,{size:"icon-sm",variant:"ghost","aria-label":i("closePreview"),onClick:s,children:(0,n.jsx)(er.A,{className:"size-4"})})]})})]})})}var eu=s(26586),em=s(74166),ep=s(51821),eh=s(67069);function eg({children:e}){let t=(0,ep.G)(),s=(0,eu.A)(),[c]=(0,r.useState)(()=>{var e,n,r;let c,d,u,m=(0,eh.YW)(s);return{clientId:s,...(e=(e,s)=>{t.show(s)},c="off"===new URL(window.location.href).searchParams.get("plugins"),d="normal",n=()=>!c&&"normal"===d,u=new ee({pi:{prompt:(e,t)=>m.request(a.P6.send,{source:e,mode:t.mode,text:t.text,images:(t.images??[]).map(e=>({...e}))}),commands:{list:async e=>(await m.request(I.QV.commandsList,{source:e})).commands.filter(e=>"extension"===e.source).map(({name:e,description:t})=>({name:e,description:t})),execute:async(e,t,s)=>{await m.request(I.QV.commandExecute,{source:e,command:t,...void 0===s?{}:{args:s}})}},tools:{list:async e=>(await m.request(I.QV.toolsList,{source:e})).tools},bash:{execute:(e,t)=>m.request(I.QV.bashExecute,{source:e,command:t.command,excludeFromContext:t.excludeFromContext}),abort:async e=>{await m.request(I.QV.bashAbort,{source:e})}},interrupt:async e=>{await m.request(a.P6.interrupt,{source:e})}},listBrowserEntries:async()=>{if(!n())return[];let{entries:e}=await m.request(f.list,{});return n()?e:[]},subscribePush:e=>m.subscribe(M,e),createPiDeskChannel:e=>({invokeGlobal:(t,s)=>m.request(l.OY.invoke,{pluginName:e,method:t,scope:"global",input:s}),invokeSession:(t,s,n)=>m.request(l.OY.invoke,{pluginName:e,method:s,scope:"session",source:t,input:n})}),createLogChannel:e=>({watch:async t=>(await m.request(N.watch,{pluginName:e,path:t})).snapshot,unwatch:async t=>{await m.request(N.unwatch,{pluginName:e,path:t})},subscribe:t=>m.subscribe(N.event,s=>{s.pluginName===e&&t({path:s.path,event:s.event})})})},void 0,e),{appSocket:(r=e=>{d=e},{async connect(e){u.markConnecting();try{return await m.connect(e)}catch(e){throw u.markDisconnected(e instanceof Error?e.message:"WebSocket 连接失败"),e}},async request(e,t){let s=await m.request(e,t);if(e.path!==o.kM.list.path)return s;let n=o.e4.parse(s);return r(n.appRuntime.mode),(0,i.UV)(n.appRuntime.settings),u.replaceGlobalPluginStates(n.appRuntime.plugins),u.replaceWorkSessions(n.workSessions),u.markReady(),u.refreshEntries().catch(e=>{console.error("[Pi Desk][PluginHost] 初始化 Browser Entry 失败",{errorName:e instanceof Error?e.name:"UnknownError",message:e instanceof Error?e.message:String(e)})}),s},subscribe:(e,t)=>m.subscribe(e,t),async waitForClose(){let e=await m.waitForClose();return u.markDisconnected(e.reason||null),e},close(){m.close()}}),pluginHost:u})}}),[d,u]=(0,r.useState)(null);(0,r.useEffect)(()=>c.pluginHost.bindProjectPreview(e=>{u(e),requestAnimationFrame(()=>document.querySelector('[data-testid="project-preview-dialog"]')?.focus())}),[c]);let m=(0,r.useRef)(null);return(0,r.useEffect)(()=>{let e={};return m.current={token:e,runtime:c},()=>{m.current?.token===e&&(m.current=null),queueMicrotask(()=>{m.current?.runtime!==c&&(c.appSocket.close(),c.pluginHost.dispose())})}},[c]),(0,n.jsx)(eh.o5.Provider,{value:c,children:(0,n.jsxs)(em.Dq.Provider,{value:c.pluginHost,children:[e,d?(0,n.jsx)(ed,{clientId:c.clientId,cwd:d,onClose:()=>u(null)},d):null]})})}},52216:e=>{e.exports={panel:"l3-conversation-call-summary_panel__sUGhX",table:"l3-conversation-call-summary_table__cf6vS",row:"l3-conversation-call-summary_row__eGK_L"}},54379:(e,t,s)=>{"use strict";s.d(t,{TR:()=>E,bq:()=>S,eb:()=>M,gC:()=>C,l6:()=>j,s3:()=>N,yv:()=>I});var n=s(7962);s(69266);var r=s(66341),i=s(91068),a=s(57160),l=s(39148),o=s(95532),c=s(34358),d=s(75970),u=s(12124),m=s(6398),p=s(15639),h=s(44788),g=s(40963),f=s(10949),x=s(46468),b=s(93282),v=s(49426),w=s(86758),y=s(90458),k=s(24121);let j=r.H;function N({className:e,...t}){return(0,n.jsx)(i.s,{"data-slot":"select-group",className:(0,v.cn)("scroll-my-1 p-1",e),...t})}function I({className:e,...t}){return(0,n.jsx)(a.y,{"data-slot":"select-value",className:(0,v.cn)("flex flex-1 text-left",e),...t})}function S({className:e,size:t="default",children:s,...r}){return(0,n.jsxs)(l.b,{"data-slot":"select-trigger","data-size":t,className:(0,v.cn)("flex w-fit cursor-pointer items-center justify-between gap-2 rounded-lg border border-input bg-card px-2.5 py-1 text-sm leading-5 whitespace-nowrap transition-colors outline-none select-none hover:bg-accent focus-visible:border-ring focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:min-h-8 data-[size=sm]:min-h-7 data-[size=sm]:rounded-md data-[size=sm]:py-0.5 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r,children:[s,(0,n.jsx)(o.w,{render:(0,n.jsx)(w.A,{className:"pointer-events-none size-4 text-muted-foreground"})})]})}function C({className:e,positionerClassName:t,children:s,side:r="bottom",sideOffset:i=4,align:a="center",alignOffset:l=0,alignItemWithTrigger:o=!0,finalFocus:p=!1,...h}){return(0,n.jsx)(c.V,{children:(0,n.jsx)(d.l,{side:r,sideOffset:i,align:a,alignOffset:l,alignItemWithTrigger:o,className:(0,v.cn)("isolate z-50",t),children:(0,n.jsxs)(u.t,{"data-slot":"select-content",finalFocus:p,"data-align-trigger":o,className:(0,v.cn)("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]: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),...h,children:[(0,n.jsx)(z,{}),(0,n.jsx)(m.B,{children:s}),(0,n.jsx)(A,{})]})})})}function E({className:e,...t}){return(0,n.jsx)(p.M,{"data-slot":"select-label",className:(0,v.cn)("px-1.5 py-1 text-xs text-muted-foreground",e),...t})}function M({className:e,children:t,...s}){return(0,n.jsxs)(h.e,{"data-slot":"select-item",className:(0,v.cn)("relative flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-md py-1 pr-8 pl-2 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...s,children:[(0,n.jsx)(g.h,{className:"flex flex-1 shrink-0 gap-2 whitespace-nowrap",children:t}),(0,n.jsx)(f.h,{render:(0,n.jsx)("span",{className:"pointer-events-none absolute right-2 flex size-4 items-center justify-center"}),children:(0,n.jsx)(y.A,{className:"pointer-events-none"})})]})}function z({className:e,...t}){return(0,n.jsx)(x.w,{"data-slot":"select-scroll-up-button",className:(0,v.cn)("top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:(0,n.jsx)(k.A,{})})}function A({className:e,...t}){return(0,n.jsx)(b.d,{"data-slot":"select-scroll-down-button",className:(0,v.cn)("bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:(0,n.jsx)(w.A,{})})}},55438:(e,t,s)=>{"use strict";s.d(t,{PS:()=>d,ef:()=>o,gK:()=>c,hS:()=>l,mv:()=>p});var n=s(38979),r=s(59605),i=s(70698),a=s(85232);let l=n.Ik({type:n.eu("message_start"),snapshot:r.s4}).strict(),o=n.Ik({type:n.eu("message_update"),location:r.fb,fixed:r.dG.optional(),summary:r.XW.optional(),detail:r.wH.optional(),increments:r.fK.optional()}).strict().superRefine((e,t)=>{if(!e.fixed&&!e.summary&&!e.detail&&!e.increments)return void t.addIssue({code:"custom",message:"message update requires a changed layer"});let s=[];for(let t of Object.keys(e.increments??{}))try{s.push({raw:t,parsed:(0,a.U)(t)})}catch{}for(let n of s){let s="summary"===n.parsed.root?Object.keys(e.summary??{}):Object.keys(e.detail??{}),r=n.parsed.segments[0];(0===n.parsed.segments.length||"string"==typeof r&&s.includes(r))&&t.addIssue({code:"custom",message:"replacement and increment paths cannot overlap",path:["increments",n.raw]})}for(let e=0;e<s.length;e+=1)for(let n=e+1;n<s.length;n+=1){let r=s[e],i=s[n];((0,a.v)(r.parsed,i.parsed)||(0,a.v)(i.parsed,r.parsed))&&t.addIssue({code:"custom",message:"increment parent and child paths cannot overlap",path:["increments",i.raw]})}}),c=n.Ik({type:n.eu("message_commit"),location:r.fb,durable:r.V6,fixed:n.Ik({timestampMs:i.k}).strict()}).strict(),d=n.Ik({type:n.eu("message_discard"),location:r.fb}).strict(),u=n.Ik({type:n.eu("durable_append"),messages:n.YO(r.mj).min(1)}).strict().superRefine((e,t)=>{let s=new Set;for(let[n,r]of e.messages.entries())n>0&&r.location.index!==e.messages[n-1].location.index+1&&t.addIssue({code:"custom",message:"durable append message indexes must be continuous",path:["messages",n,"location","index"]}),s.has(r.location.entryId)&&t.addIssue({code:"custom",message:"durable append entryId values must be unique",path:["messages",n,"location","entryId"]}),s.add(r.location.entryId)}),m=n.KC([l,o,c,d]),p=n.KC([u,m])},58270:e=>{e.exports={inputFrame:"l2-workbench-chat-composer_inputFrame__zhb9v",inputText:"l2-workbench-chat-composer_inputText__3DU2N",footer:"l2-workbench-chat-composer_footer__7wBQh",primaryTools:"l2-workbench-chat-composer_primaryTools__8KCVm",metadataTools:"l2-workbench-chat-composer_metadataTools__XEVFA",submitTools:"l2-workbench-chat-composer_submitTools__x8f4c",modelTrigger:"l2-workbench-chat-composer_modelTrigger__tDV8k",modelTriggerDetails:"l2-workbench-chat-composer_modelTriggerDetails__sdSS2"}},59605:(e,t,s)=>{"use strict";s.d(t,{D8:()=>X,Er:()=>z,Gx:()=>O,Hf:()=>Q,LJ:()=>c,OS:()=>Z,O_:()=>K,Ok:()=>V,Pc:()=>o,Px:()=>R,Qi:()=>T,RX:()=>ec,Rh:()=>_,Rk:()=>H,Rt:()=>q,UT:()=>P,V6:()=>v,XW:()=>ei,Xj:()=>U,aV:()=>L,ai:()=>B,bG:()=>G,bN:()=>F,dG:()=>er,fK:()=>eo,fb:()=>b,lJ:()=>E,mh:()=>m,mj:()=>es,ny:()=>Y,q5:()=>S,s4:()=>et,sL:()=>J,s_:()=>C,wH:()=>ea});var n=s(38979),r=s(66453),i=s(67765),a=s(70698),l=s(85232);let o=n.Yj().uuid(),c=n.ai().int().nonnegative(),d=n.Yj().trim().min(3).max(129).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/),u=n.k5(["image/jpeg","image/png","image/webp","image/gif"]),m=n.Ik({mimeType:u,width:n.ai().int().positive(),height:n.ai().int().positive()}).strict(),p=n.k5(["running","completed","error","aborted"]),h=n.k5(["running","completed","error"]),g=n.ai().int().nonnegative().max(Number.MAX_SAFE_INTEGER),f=n.Ik({inputTokens:g,outputTokens:g,cacheReadTokens:g,costUsd:n.ai().finite().nonnegative()}).strict(),x=n.Yj().trim().min(1).nullable(),b=n.Ik({tempId:o}).strict(),v=n.Ik({index:c,entryId:r.Rv}).strict(),w=n.Ik({timestampMs:a.k.nullable(),type:n.eu("user"),viewKey:d,hasDetail:n.zM()}).strict(),y=n.Ik({timestampMs:a.k.nullable(),type:n.eu("assistant"),viewKey:d,status:p,hasDetail:n.zM(),usage:f}).strict(),k=n.Ik({timestampMs:a.k.nullable(),type:n.eu("tool"),viewKey:d,status:h,hasDetail:n.zM(),usage:f.nullable()}).strict(),j=n.Ik({timestampMs:a.k.nullable(),type:n.eu("bash"),viewKey:d,status:p,hasDetail:n.zM()}).strict(),N=n.Ik({timestampMs:a.k.nullable(),type:n.eu("custom"),viewKey:d,hasDetail:n.zM()}).strict();function I(e){let t=w.extend({timestampMs:e}).strict(),s=y.extend({timestampMs:e}).strict(),r=k.extend({timestampMs:e}).strict(),i=j.extend({timestampMs:e}).strict(),a=N.extend({timestampMs:e}).strict();return{user:t,assistant:s,tool:r,bash:i,custom:a,message:n.gM("type",[t,s,r,i,a])}}n.gM("type",[w,y,k,j,N]);let S=I(n.ch()).message,C=I(a.k).message,E=n.Ik({text:n.Yj(),images:n.YO(m)}).strict(),M=n.Ik({provider:n.Yj(),modelId:n.Yj()}).strict(),z=n.Ik({text:n.Yj(),errorMessage:n.Yj().nullable().default(null),model:M.nullable().optional()}).strict(),A={name:n.Yj().trim().min(1),reasoning:x,inputPreview:x,activity:x};function $(){return n.Ik({...A,path:i.eC.nullable()}).strict()}let R=n.Ik({...A,images:n.YO(m).optional()}).strict(),P=R,D=n.KC([n.Ik({startedAtMs:a.k}).strict(),n.Ik({durationMs:n.ai().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).strict()]),T=n.Ik({...A,timing:D.nullable()}).strict(),O=$().extend({images:n.YO(m).optional()}).strict(),L=$(),F=$(),B=n.Ik({command:n.Yj().min(1)}).strict(),q=n.Ik({text:n.Yj()}).strict(),_=n.Ik({thinking:n.Yj()}).strict(),W=n.Ik({complete:n.zM(),calls:n.YO(n.Ik({name:n.Yj(),arguments:n.g1(n.Yj(),n.Pq()).optional(),argumentsBytes:n.ai().int().nonnegative().optional(),status:n.k5(["ok","error","unfinished"]),durationMs:n.ai().finite().nonnegative().optional(),error:n.Yj().optional()}).strict())}).strict(),Y=n.Ik({output:n.Yj(),nestedCalls:W.optional()}).strict(),V=n.Ik({output:n.Yj()}).strict(),U=n.Ik({content:n.Yj()}).strict(),H=n.gM("kind",[n.Ik({kind:n.eu("diff"),content:n.Yj()}).strict(),n.Ik({kind:n.eu("output"),content:n.Yj()}).strict()]),K=n.gM("kind",[n.Ik({kind:n.eu("content"),content:n.Yj()}).strict(),n.Ik({kind:n.eu("output"),content:n.Yj()}).strict()]),G=n.Ik({output:n.Yj()}).strict(),J=n.Ik({text:n.Yj().min(1)}).strict(),Q=n.g1(n.Yj(),n.Pq()),X=n.g1(n.Yj(),n.Pq()),Z=n.KC([X,n.ch()]);function ee(e,t){return n.Ik({location:e,fixed:I(t).message,summary:Q,detail:X.optional()}).strict().superRefine((e,t)=>{void 0===e.detail||e.fixed.hasDetail||t.addIssue({code:"custom",message:"message detail requires hasDetail=true",path:["detail"]})})}let et=ee(b,n.ch()),es=ee(v,a.k);function en(e,t){0===Object.keys(e).length&&t.addIssue({code:"custom",message:"patch requires at least one changed field"})}let er=n.Ik({viewKey:d.optional(),status:n.KC([p,h]).optional(),hasDetail:n.zM().optional(),usage:f.nullable().optional()}).strict().superRefine(en),ei=n.g1(n.Yj(),n.Pq()).superRefine(en),ea=n.g1(n.Yj(),n.Pq()).superRefine(en),el=n.KC([n.Yj().min(1),n.YO(n.Pq()).min(1)]),eo=n.g1(n.Yj(),el).superRefine((e,t)=>{for(let s of(en(e,t),Object.keys(e)))try{(0,l.U)(s)}catch(e){t.addIssue({code:"custom",message:e instanceof Error?e.message:"increment path is invalid",path:[s]})}}),ec=n.Ik({messages:n.YO(es),temporaryMessages:n.YO(et)}).strict();n.Ik({index:c,entryId:r.Rv,detail:Z}).strict(),n.Ik({mimeType:u,data:n.Yj().min(1)}).strict()},61286:(e,t,s)=>{"use strict";s.d(t,{N:()=>r});var n=s(38979);let r=n.Ik({key:n.Yj().min(1).max(160),params:n.g1(n.Yj().min(1).max(80),n.KC([n.Yj().max(1e3),n.ai().finite()])).optional()}).strict()},62851:(e,t,s)=>{"use strict";s.d(t,{$C:()=>S,GR:()=>f,Pq:()=>C,YT:()=>I});var n=s(38979),r=s(15710),i=s(6397),a=s(99739),l=s(70698);let o=n.Yj().uuid(),c=n.Yj().trim().min(1).max(256),d=n.k5(["info","success","warning","error"]),u=n.Yj().trim().min(1).max(120),m=n.Yj().trim().max(320).nullable(),p=n.Ik({type:n.eu("plugin"),pluginName:a.tv,name:a.f7,data:a.Dz}).strict(),h=n.Ik({notificationId:o,level:d,title:u,description:m,createdAt:l.k,event:p.nullable()}).strict(),g=n.g1(a.tv,a.Dz),f=n.Ik({mode:n.k5(["normal","basic"]).default("normal"),notifications:n.YO(h),plugins:g,capabilityModes:i.Wu,settings:r.J.default({region:{locale:"en",timeZone:"UTC"}})}).strict(),x=n.Ik({level:d.optional(),title:u.optional(),description:m.optional(),event:p.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0,{message:"notification changes cannot be empty"}),b=n.Ik({type:n.eu("add"),notification:h}).strict(),v=n.Ik({type:n.eu("update"),notificationId:o,changes:x}).strict(),w=n.Ik({type:n.eu("delete"),notificationId:o}).strict(),y=n.gM("type",[b,v,w]),k=n.Ik({pluginName:a.tv,state:a.Dz.nullable()}).strict(),j=n.Ik({key:n.eu("capabilityModes"),update:i.Wu}).strict(),N=n.Ik({key:n.eu("settings"),update:r.J}).strict();n.gM("key",[N,j,n.Ik({key:n.eu("notifications"),update:y}).strict(),n.Ik({key:n.eu("plugins"),update:k}).strict()]);let I=n.KC([N.extend({type:n.eu("update")}),j.extend({type:n.eu("update")}),n.Ik({type:n.eu("replace"),runtime:f}).strict(),n.Ik({type:n.eu("update"),key:n.eu("notifications"),update:y}).strict(),n.Ik({type:n.eu("update"),key:n.eu("plugins"),update:k}).strict()]),S=n.gM("key",[n.Ik({key:n.eu("notifications"),update:w}).strict(),n.Ik({key:n.eu("settings"),update:n.Ik({region:r.a.unwrap().partial().strict().refine(e=>Object.keys(e).length>0,"地区更新不能为空")}).strict()}).strict()]),C=n.Ik({}).strict(),E=n.Ik({name:a.f7,data:a.Dz}).strict();n.Ik({key:c.optional(),level:d,title:u,description:n.Yj().trim().max(320).optional(),event:E.optional()}).strict(),n.Ik({level:d.optional(),title:u.optional(),description:m.optional()}).strict().refine(e=>Object.keys(e).length>0,{message:"plugin notification changes cannot be empty"})},67069:(e,t,s)=>{"use strict";s.d(t,{o5:()=>d,YW:()=>p,p:()=>m,gM:()=>u});var n=s(9626),r=s(67837),i=s(73230);class a extends Error{constructor(e,t,s){super((0,i.B)({msg:e,i18n:{key:t,...s?{params:s}:{}}})),this.rawMessage=e,this.name="L4AppSocketTransportError"}}class l extends Error{constructor(e,t,s){super(s),this.code=e,this.rawMessage=t,this.name="L4AppSocketRequestError"}}class o{constructor(e,t){this.onPush=t,this.pendingRequests=new Map,this.opened=!1,this.disposed=!1,this.removeAbortListener=null,this.handleMessage=e=>{let t;if("string"!=typeof e.data)return void this.close(1003,"仅支持文本 JSON 消息");try{t=JSON.parse(e.data)}catch{this.close(1007,"JSON 格式无效");return}let s=n.hE.safeParse(t);if(s.success){let e=s.data.head.requestId,t=this.pendingRequests.get(e);if(!t)return;if(this.pendingRequests.delete(e),clearTimeout(t.timeout),s.data.head.path!==t.path){t.reject(new a("WebSocket 响应 path 与请求不一致","common:socketResponseMismatch")),this.close(1008,"响应 path 与 requestId 不匹配");return}if(0!==s.data.body.code)return void t.reject(new l(s.data.body.code,s.data.body.msg,(0,i.B)(s.data.body)));let n=t.contract.outputSchema.safeParse(s.data.body.data);if(!n.success){t.reject(new a("WebSocket 响应数据无效","common:socketResponseInvalid")),this.close(1008,"服务端响应数据无效");return}return void t.resolve(n.data)}let r=n.Od.safeParse(t);if(!r.success)return void this.close(1008,"服务端消息信封无效");try{this.onPush(r.data.head.path,r.data.body)}catch{this.close(1008,"服务端推送数据无效")}},this.handleClose=e=>{let t={code:e.code,reason:e.reason};this.dispose(),this.resolveClosed(t)},this.socket=new WebSocket(function(e){let t="https:"===window.location.protocol?"wss:":"ws:";return`${t}//${window.location.host}${n.PA}?clientId=${encodeURIComponent(e)}`}(e),n.uB),this.closedPromise=new Promise(e=>{this.resolveClosed=e}),this.socket.addEventListener("message",this.handleMessage),this.socket.addEventListener("close",this.handleClose,{once:!0})}open(e){return this.opened&&this.socket.readyState===WebSocket.OPEN?Promise.resolve():e.aborted?Promise.reject(new DOMException("Aborted","AbortError")):new Promise((t,s)=>{let n=()=>{this.socket.removeEventListener("open",i),this.socket.removeEventListener("error",l)},r=()=>this.close(1e3,"页面已卸载"),i=()=>{n(),this.removeAbortListener?.(),this.removeAbortListener=null,this.opened=!0,t()},l=()=>{n(),this.close(1e3,"WebSocket 连接失败"),s(new a("WebSocket 连接失败","common:socketConnectFailed"))};e.addEventListener("abort",r,{once:!0}),this.removeAbortListener=()=>e.removeEventListener("abort",r),this.socket.addEventListener("open",i,{once:!0}),this.socket.addEventListener("error",l,{once:!0}),this.closedPromise.then(()=>{n(),this.opened||s(new a("WebSocket 连接已断开","common:socketDisconnected"))})})}isOpen(){return!this.disposed&&this.socket.readyState===WebSocket.OPEN}request(e,t){if(!this.isOpen())return Promise.reject(new a("WebSocket 尚未连接","common:socketNotConnected"));let s=(0,r.y)(),i=n.tU.parse({head:{op:"req",path:e.path,requestId:s},body:e.inputSchema.parse(t)});return new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(s),n(new a(`WebSocket 请求超时:${e.path}`,"common:socketRequestTimeout",{path:e.path}))},e.timeoutMs??15e3);this.pendingRequests.set(s,{path:e.path,contract:e,resolve:e=>t(e),reject:n,timeout:r});try{this.socket.send(JSON.stringify(i))}catch(e){this.pendingRequests.delete(s),clearTimeout(r),n(e instanceof Error?e:new a("WebSocket 请求发送失败","common:socketSendFailed"))}})}waitForClose(){return this.closedPromise}close(e=1e3,t="客户端关闭连接"){if(!this.disposed&&this.socket.readyState!==WebSocket.CLOSED)try{this.socket.close(e,t)}catch{}}dispose(){if(!this.disposed){for(let e of(this.disposed=!0,this.removeAbortListener?.(),this.removeAbortListener=null,this.socket.removeEventListener("message",this.handleMessage),this.pendingRequests.values()))clearTimeout(e.timeout),e.reject(new a("WebSocket 连接已断开","common:socketDisconnected"));this.pendingRequests.clear()}}}var c=s(69266);let d=(0,c.createContext)(null);function u(){let e=(0,c.useContext)(d);if(!e)throw Error("AppSocket Provider is missing");return e}function m(e){return e.code===n.P9}function p(e){let t=new Map,s=null,n=Promise.resolve({code:1e3,reason:""}),r=null,i=(e,s)=>{let n=t.get(e);if(!n)return;let r=n.contract.bodySchema.parse(s);for(let t of[...n.listeners])try{t(r)}catch(t){console.error("[Pi Desk][AppSocketClient] 推送监听器执行失败",{path:e,errorName:t instanceof Error?t.name:"UnknownError"})}};return{connect:t=>s?.isOpen()?Promise.resolve(!1):r||(r=(async()=>{let r=s;if(r&&(await r.waitForClose(),s===r&&(s=null)),t.aborted)throw new DOMException("Aborted","AbortError");let a=new o(e,i);s=a,(n=a.waitForClose()).then(()=>{s===a&&(s=null)});try{await a.open(t)}catch(e){throw a.close(),await a.waitForClose(),s===a&&(s=null),e}return!0})().finally(()=>{r=null})),request(e,t){let n=s;return n?n.request(e,t):Promise.reject(Error("WebSocket 尚未连接"))},subscribe(e,s){let n=t.get(e.path);if(n&&n.contract!==e)throw Error(`WebSocket push path 使用了不同合同:${e.path}`);let r=n??{contract:e,listeners:new Set},i=e=>s(e);return r.listeners.add(i),t.set(e.path,r),()=>{r.listeners.delete(i),0===r.listeners.size&&t.delete(e.path)}},waitForClose:()=>n,close(){s?.close()}}}},68269:(e,t,s)=>{"use strict";s.d(t,{$f:()=>f,DK:()=>y,Pi:()=>w,R3:()=>m,TV:()=>z,UR:()=>k,Y2:()=>h,ao:()=>p,lV:()=>g,oc:()=>$,w$:()=>S,wI:()=>x,wR:()=>v,wf:()=>A,xh:()=>j,yI:()=>b});var n=s(38979),r=s(6397),i=s(15381),a=s(59605),l=s(26357),o=s(267);let c=a.Pc,d=a.LJ,u=a.mh,m=a.fb,p=a.s_,h=a.Er,g=a.Hf,f=a.Rh,x=a.OS,b=a.s4,v=a.mj,w=o.R,y=n.Ik({index:d,entryId:i.C3}).strict(),k=n.KC([n.ch(),y]),j=u.extend({data:n.Yj().min(1)}).strict(),N=l.$,I=n.Ik({tempId:c,text:n.Yj(),images:n.YO(u).max(10)}).strict(),S=n.Ik({provider:n.Yj().trim().min(1),modelId:n.Yj().trim().min(1),thinkingLevel:N}).strict(),C=n.Ik({tokens:n.ai().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable(),contextWindow:n.ai().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),E=n.g1(n.Yj(),n.Pq()),M=n.g1(n.Yj().min(1),E),z=n.k5(["normal","basic"]),A=n.Ik({extensionMode:z.default("normal"),presentationMode:z.default("normal"),initializationError:n.Yj().max(32e3).nullable().default(null),queues:n.Ik({steering:n.YO(I),followUp:n.YO(I)}).strict(),model:S.nullable(),capabilityMode:r.rY.nullable(),contextUsage:C.nullable(),plugins:M}).strict(),$=a.RX.extend({runtime:A}).strict();n.Ik({sessionId:i.Kx,branchId:i._A,entryId:i.C3}).strict().extend({imageIndex:n.ai().int().nonnegative()}).strict()},70657:(e,t,s)=>{"use strict";s.d(t,{k:()=>m});var n=s(7962),r=s(86758),i=s(66584),a=s(69266),l=s(78121),o=s(37975),c=s(17708),d=s(35800);function u(e){return e.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??e}function m({workId:e,cwd:t,projectName:s,runtime:p,gitRuntime:h,onOpenGitBranches:g,onFileOpened:f}){let x,{t:b}=(0,l.Bd)("projectFiles");(0,a.useSyncExternalStore)(p.subscribe,p.getRevision,p.getRevision);let v=p.getDirectory(e),w=p.getDirectories(e),y=(0,o.Yj)(t)===(0,o.Yj)(v),k=y?s:u(v);return(0,n.jsx)(d.F,{cwd:v,projectName:k,gitReadOnly:!y,rootTitle:w.length>1?(0,n.jsxs)(c.rI,{children:[(0,n.jsxs)(c.ty,{"data-testid":"project-preview-directory-trigger","aria-label":b("selectPreviewDirectory"),title:v,className:"flex min-h-7 min-w-0 flex-1 items-center gap-1 rounded-md px-1 text-left hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring",children:[(0,n.jsx)("span",{className:"max-w-[45%] truncate text-xs font-semibold",children:k}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:"\xb7"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground",children:(x=v.replaceAll("\\","/").split("/").filter(Boolean)).length<=2?v:`…/${x.slice(-2).join("/")}`}),(0,n.jsx)(r.A,{className:"size-3.5 shrink-0 text-muted-foreground"})]}),(0,n.jsx)(c.SQ,{finalFocus:!0,className:"w-[23rem] min-w-0 max-w-[calc(100vw-1.5rem)]","aria-label":b("previewDirectories"),children:(0,n.jsxs)(c.I,{children:[(0,n.jsx)(c.lp,{children:b("previewDirectories")}),(0,n.jsx)(c.Hr,{value:v,onValueChange:t=>p.selectDirectory(e,t),children:w.map(e=>(0,n.jsxs)(c.Ht,{value:e,"data-testid":"project-preview-directory-option","data-directory":e,className:"items-start py-2 data-checked:bg-muted",children:[(0,n.jsx)(i.A,{className:"mt-0.5 size-4 text-muted-foreground"}),(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",children:(0,o.Yj)(e)===(0,o.Yj)(t)?s:u(e)}),(0,o.Yj)(e)===(0,o.Yj)(t)?(0,n.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:b("sessionDirectory")}):null]}),(0,n.jsx)("span",{className:"mt-0.5 block break-all font-mono text-xs leading-5 text-muted-foreground",children:e})]})]},(0,o.Yj)(e)))})]})})]}):void 0,runtime:p.getFileRuntime(e),gitRuntime:h,onOpenGitBranches:n=>{y&&g({workId:e,cwd:t,projectName:s,repositoryRoot:n})},onFileOpened:()=>{p.showWindow(e),f?.()}})}},74166:(e,t,s)=>{"use strict";s.d(t,{Dq:()=>r,So:()=>a,t4:()=>i});var n=s(69266);let r=(0,n.createContext)(null);function i(){let e=(0,n.useContext)(r);if(!e)throw Error("Plugin Host Provider is missing");return e}function a(){let e=i(),t=(0,n.useCallback)(t=>e.subscribeRegistry(t),[e]),s=(0,n.useCallback)(()=>e.getRegistrySnapshot(),[e]);return(0,n.useSyncExternalStore)(t,s,s).descriptors}},76812:e=>{e.exports={single:"l2-work-session-file-layout_single__LVPWJ",wide:"l2-work-session-file-layout_wide__NEecW"}},78653:e=>{e.exports={chatContainer:"l2-work-session-columns_chatContainer__rLqh5",headerActionIcon:"l2-work-session-columns_headerActionIcon__sRqr8",sessionHeader:"l2-work-session-columns_sessionHeader__ZEwG_",headerAction:"l2-work-session-columns_headerAction__JlrRL",headerActionLabel:"l2-work-session-columns_headerActionLabel__bkzGB",collapsedText:"l2-work-session-columns_collapsedText__f7OAU"}},79814:e=>{e.exports={viewport:"l2-terminal-workspace_viewport__lAZHJ",canvas:"l2-terminal-workspace_canvas__h6ngK",mobile:"l2-terminal-workspace_mobile__4Ae83"}},84942:(e,t,s)=>{"use strict";s.d(t,{Dl:()=>h,Qg:()=>m,RC:()=>f,a4:()=>d,j0:()=>p});var n=s(38979);let r=n.Yj().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),i=n.Yj().trim().min(1).max(256),a=n.Ik({allow:n.YO(i).max(5e3).optional(),deny:n.YO(i).max(5e3).optional()}).strict(),l=n.Ik({value:n.Yj().trim().min(1).max(256),label:n.Yj().trim().min(1).max(120).optional(),description:n.Yj().trim().max(1e3).optional()}).strict(),o=n.Ik({label:n.Yj().trim().min(1).max(120),options:n.YO(l).max(5e3)}).strict(),c=n.g1(r,o),d=n.Yj().min(1).max(64),u=n.Ik({name:n.Yj().trim().min(1).max(64),tools:a.optional(),skills:a.optional(),plugins:n.g1(r,n.g1(r,a)).optional()}).strict(),m=n.g1(d,u).refine(e=>Object.keys(e).length<=100,"最多保存 100 个能力模式").refine(e=>new Set(Object.values(e).map(e=>e.name)).size===Object.keys(e).length,"模式名称不能重复"),p=n.g1(d,u.shape.name),h=n.Ik({tools:n.YO(l),skills:n.YO(l),plugins:n.g1(r,c)}).strict();function g(e,t){let s=0,n=0,r=-1,i=0;for(;n<t.length;)if("*"===e[s])r=s++,i=n;else if(e[s]===t[n])s+=1,n+=1;else{if(!(r>=0))return!1;s=r+1,n=++i}for(;"*"===e[s];)s+=1;return s===e.length}function f(e,t){return(e?.allow===void 0||e.allow.some(e=>g(e,t)))&&!e?.deny?.some(e=>g(e,t))}n.Ik({tools:a,skills:a,capabilities:n.g1(r,a)}).strict()},85232:(e,t,s)=>{"use strict";function n(e){if(!/^(0|[1-9]\d*)$/.test(e))return e;let t=Number(e);if(!Number.isSafeInteger(t))throw Error(`Increment array index is invalid: ${e}`);return t}function r(e){if(!e||e.length>1024)throw Error("Increment path length is invalid");let t=[],s="",r=!1;for(let n of e){if(r){if("."!==n&&"\\"!==n)throw Error(`Increment path contains an invalid escape: \\${n}`);s+=n,r=!1;continue}if("\\"===n){r=!0;continue}if("."===n){if(!s)throw Error("Increment path contains an empty segment");t.push(s),s="";continue}s+=n}if(r)throw Error("Increment path ends with an escape");if(!s)throw Error("Increment path contains an empty segment");t.push(s);let i=t.shift();if("summary"!==i&&"detail"!==i)throw Error("Increment path root must be summary or detail");return{root:i,segments:t.map(n)}}function i(e,t){return e.root===t.root&&!(e.segments.length>t.segments.length)&&e.segments.every((e,s)=>e===t.segments[s])}s.d(t,{U:()=>r,v:()=>i})},89517:e=>{e.exports={surface:"l3-work-session-visual-effects_surface__N89k0",identity:"l3-work-session-visual-effects_identity__Aujuw"}},91399:(e,t,s)=>{"use strict";s.d(t,{e4:()=>m,kM:()=>h});var n=s(38979),r=s(15381),i=s(62851),a=s(70698),l=s(9626);let o=n.Ik({}).strict(),c=n.Ik({workId:r.eW}).strict(),d=n.Ik({workId:r.eW}).strict(),u=n.Ik({cwd:r.ik.optional(),sessionId:r.Kx.optional(),branchId:n.Yj().min(1).optional(),projectName:n.Yj().trim().min(1).optional(),sessionTitle:n.Yj().trim().min(1).nullable().optional(),status:r.jw.optional(),messageCounts:r.AA.optional(),lastMessageUpdatedAt:a.k.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0,{message:"work session changes cannot be empty"}),m=n.Ik({workSessions:n.YO(r.MY),pinnedCount:r.MT,appRuntime:i.GR}).strict().refine(e=>e.pinnedCount<=e.workSessions.length,{message:"pinnedCount cannot exceed work session count",path:["pinnedCount"]}),p=n.gM("type",[n.Ik({type:n.eu("snapshot"),workSessions:n.YO(r.MY),pinnedCount:r.MT}).strict().refine(e=>e.pinnedCount<=e.workSessions.length,{message:"pinnedCount cannot exceed work session count",path:["pinnedCount"]}),n.Ik({type:n.eu("update"),workId:r.eW,changes:u}).strict(),n.Ik({type:n.eu("delete"),workId:r.eW}).strict()]),h=Object.freeze({list:(0,l.Vc)({path:"work-sessions/list",inputSchema:o,outputSchema:m}),acknowledgeCompleted:(0,l.Vc)({path:"work-sessions/ack-completed",inputSchema:c,outputSchema:d}),update:(0,l._G)({path:"work-sessions/update",bodySchema:p})})},95826:(e,t,s)=>{"use strict";s.d(t,{QV:()=>w});var n=s(38979),r=s(267),i=s(9626),a=s(99739);let l=n.k5(["extension","prompt","skill"]),o=n.Ik({name:n.Yj().trim().min(1).max(128),description:n.Yj().max(500).nullable(),source:l}).strict(),c=n.Ik({source:r.R}).strict(),d=n.Ik({commands:n.YO(o)}).strict(),u=n.Ik({source:r.R,command:n.Yj().trim().min(1).max(128),args:n.Yj().max(32768).optional()}).strict(),m=n.Ik({}).strict(),p=n.Ik({name:n.Yj().trim().min(1).max(128),description:n.Yj(),parameters:a.Dz,active:n.zM(),exposure:n.k5(["direct","model-only","codemode","deferred","hidden"]),source:n.Yj().nullable(),blockedByMode:n.zM()}).strict(),h=n.Ik({source:r.R}).strict(),g=n.Ik({tools:n.YO(p)}).strict(),f=n.Ik({source:r.R,command:n.Yj().min(1).max(32768),excludeFromContext:n.zM()}).strict(),x=n.Ik({output:n.Yj(),exitCode:n.ai().int().nullable(),cancelled:n.zM(),truncated:n.zM(),fullOutputPath:n.Yj().nullable()}).strict(),b=n.Ik({source:r.R}).strict(),v=n.Ik({}).strict(),w=Object.freeze({commandsList:(0,i.Vc)({path:"pi/commands/list",inputSchema:c,outputSchema:d}),commandExecute:(0,i.Vc)({path:"pi/commands/execute",inputSchema:u,outputSchema:m,timeoutMs:3e5}),toolsList:(0,i.Vc)({path:"pi/tools/list",inputSchema:h,outputSchema:g}),bashExecute:(0,i.Vc)({path:"pi/bash/execute",inputSchema:f,outputSchema:x,timeoutMs:12e4}),bashAbort:(0,i.Vc)({path:"pi/bash/abort",inputSchema:b,outputSchema:v})})},99739:(e,t,s)=>{"use strict";s.d(t,{Dz:()=>l,f7:()=>a,tv:()=>i});var n=s(38979);let r=n.Yj().trim().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),i=r,a=r,l=n.g1(n.Yj(),n.Pq());n.Yj().trim().min(3).max(129).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/);let o=n.k5(["plugin","server","rocket","settings","panel","message","terminal","file","folder","bot","wrench","database","globe"]);n.gM("type",[n.Ik({type:n.eu("builtin"),name:o}).strict(),n.Ik({type:n.eu("svg"),content:n.Yj().trim().min(1).max(16384)}).strict()])}},e=>{e.O(0,[82705,79405,85959,26717,94287,57235,14825,82371,79267,46270,37313,14197,51474,15302,65232,11937,4904,64444,77358],()=>e(e.s=14465)),_N_E=e.O()}]);
|