@clawos-dev/clawd 0.2.741 → 0.2.742
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/dist/cli.cjs
CHANGED
|
@@ -76120,7 +76120,7 @@ function computeMethodAccess(args) {
|
|
|
76120
76120
|
}
|
|
76121
76121
|
|
|
76122
76122
|
// src/version.ts
|
|
76123
|
-
var version = "0.2.
|
|
76123
|
+
var version = "0.2.742".length > 0 ? "0.2.742" : "dev";
|
|
76124
76124
|
|
|
76125
76125
|
// src/cli-probe/probe.ts
|
|
76126
76126
|
var fs87 = __toESM(require("fs"), 1);
|
|
@@ -952,4 +952,4 @@ npx @clawos-dev/clawd@latest --tunnel # 远程(输出 Connect: 一行整粘
|
|
|
952
952
|
`;function vot({rows:e,activity:t,ownerName:n,onExit:r,onPick:s}){p.useEffect(()=>{const h=f=>{f.key==="Escape"&&(f.stopPropagation(),r())};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[r]);const i=sot(xot),o=tot(e),{running:l,awaiting:c,unread:u}=o,d=a.jsx("main",{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",children:a.jsx("div",{className:`flex min-h-0 w-full flex-1 flex-col overflow-y-auto ${i?"":"mx-auto"}`,style:{maxWidth:k2,paddingTop:i?28:void 0},children:e.length===0?a.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3",children:[a.jsx("div",{style:{fontSize:22,color:"#8E949B"},children:"今天还没有 agent 干活"}),a.jsx("div",{className:"font-mono",style:{fontSize:13,color:"#4A4F55"},children:"派点活给它们,这里就会热闹起来"})]}):e.map((h,f)=>a.jsx(got,{row:h,activity:t.get(h.sessionId),index:f,onPick:s,maxHeight:i?fot:void 0},h.sessionId))})});return i?a.jsxs("div",{"data-testid":"hive-board",className:"dark relative flex h-full w-full overflow-hidden",style:{background:"#08090A"},children:[a.jsx("style",{children:QB}),a.jsxs("div",{className:"mx-auto flex h-full w-full",style:{maxWidth:Rte+k2},children:[a.jsx(uot,{rows:e,summary:o,ownerName:n,onExit:r}),d]})]}):a.jsxs("div",{"data-testid":"hive-board",className:"dark relative flex h-full w-full flex-col overflow-hidden",style:{background:"#08090A"},children:[a.jsx("style",{children:QB}),a.jsxs("header",{"data-testid":"hive-header",className:"mx-auto flex w-full shrink-0 items-start justify-between px-8 pb-5 pt-7",style:{maxWidth:k2},children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"font-medium leading-none",style:{fontSize:42,letterSpacing:".02em",color:"#F4F6F8"},children:n}),a.jsx("button",{type:"button","data-testid":"hive-exit",onClick:r,"aria-label":"退出 Hive",className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-full transition-colors",style:{background:"rgb(255 255 255 / .06)",color:"#8E949B"},children:a.jsx(en,{className:"h-4 w-4",strokeWidth:2.25})})]}),a.jsx("div",{className:"mt-3.5 flex items-center gap-2.5",children:l>0?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"h-[10px] w-[10px] shrink-0 rounded-full animate-pulse",style:{background:`rgb(${vo.running.color})`,boxShadow:`0 0 12px rgb(${vo.running.color})`}}),a.jsxs("span",{style:{fontSize:27,color:`rgb(${vo.running.color})`},children:[a.jsx("span",{className:"font-mono tabular-nums font-medium",children:l})," 个 agent 正在运行"]})]}):c>0?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"h-[10px] w-[10px] shrink-0 rounded-full animate-pulse",style:{background:`rgb(${vo.awaiting.color})`}}),a.jsxs("span",{style:{fontSize:27,color:`rgb(${vo.awaiting.color})`},children:[a.jsx("span",{className:"font-mono tabular-nums font-medium",children:c})," 个 agent 在等我"]})]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"h-[10px] w-[10px] shrink-0 rounded-full",style:{background:"#4A4F55"}}),a.jsx("span",{style:{fontSize:27,color:"#8E949B"},children:"今天没有 agent 在跑"})]})})]}),a.jsxs("div",{className:"flex items-center gap-10",children:[a.jsxs("div",{className:"text-right",children:[a.jsx("div",{className:"font-mono tabular-nums leading-none",style:{fontSize:44,color:u>0?"rgb(var(--error-color))":"#3A3F45"},children:String(u).padStart(2,"0")}),a.jsx("div",{className:"mt-2 font-mono uppercase",style:{fontSize:10,letterSpacing:".22em",color:u>0?"rgb(var(--error-color) / .75)":"#3A3F45"},children:"unread"})]}),a.jsxs("div",{className:"text-right",children:[a.jsx("div",{className:"font-mono tabular-nums leading-none",style:{fontSize:44,color:c>0?"rgb(var(--warning-color))":"#3A3F45"},children:String(c).padStart(2,"0")}),a.jsx("div",{className:"mt-2 font-mono uppercase",style:{fontSize:10,letterSpacing:".22em",color:c>0?"rgb(var(--warning-color) / .75)":"#3A3F45"},children:"waiting me"})]}),a.jsx(Tte,{rows:e})]})]}),d]})}function yot({sessions:e,pool:t,deviceNames:n,unreadIds:r,ownerName:s,onExit:i,onPick:o}){const l=not(e,t,n,r),c=Git(l,t);return a.jsx(vot,{rows:l,activity:c,ownerName:s,onExit:i,onPick:o})}const bot=3;function cy({text:e,query:t}){const n=t.trim(),r=n===""?-1:e.toLowerCase().indexOf(n.toLowerCase());return r<0?a.jsx(a.Fragment,{children:e}):a.jsxs(a.Fragment,{children:[e.slice(0,r),a.jsx("span",{className:"text-text-100 font-medium",children:e.slice(r,r+n.length)}),e.slice(r+n.length)]})}function Ud({children:e}){return a.jsx("span",{className:"shrink-0 px-1.5 py-0.5 rounded border border-border text-[11px] text-text-400 bg-bg-100",children:e})}function wot(e){const{query:t,focus:n,groups:r,sessions:s,personas:i,contacts:o,sessionsLoading:l}=e,c=p.useRef(null),u=p.useRef(null);p.useEffect(()=>{var g;(g=c.current)==null||g.focus()},[]),p.useEffect(()=>{var g,x;try{(x=(g=u.current)==null?void 0:g.querySelector('[data-active="true"]'))==null||x.scrollIntoView({block:"nearest"})}catch{}},[n.group,n.row]);const d=g=>{if(!(g.metaKey||g.ctrlKey)){if(g.key==="ArrowDown"||g.key==="ArrowUp"){g.preventDefault(),e.onMoveRow(g.key==="ArrowDown"?1:-1);return}if(g.key==="Enter"){g.preventDefault(),e.onOpenFocused();return}g.key==="Escape"&&(g.preventDefault(),e.onClose())}},h=(g,x)=>({"data-active":n.group===g&&n.row===x,"data-testid":`search-row-${g}-${x}`,onMouseEnter:()=>e.onFocusChange({group:g,row:x}),className:`w-full text-left px-3 py-2 rounded-md cursor-pointer ${n.group===g&&n.row===x?"bg-text-100/10":"hover:bg-text-100/5"}`}),f=(g,x)=>n.group===g&&x<9?a.jsxs(Ud,{children:["⌘",x+1]}):null,m=t.trim()!=="";return a.jsx("div",{"data-testid":"search-overlay",className:"fixed inset-0 z-50 flex items-start justify-center pt-[12vh] bg-black/40 backdrop-blur-sm",onClick:e.onClose,children:a.jsxs("div",{role:"dialog","aria-label":"全局搜索",className:"w-[640px] max-w-[92vw] max-h-[70vh] flex flex-col rounded-xl border border-border bg-elevated shadow-2xl overflow-hidden",onClick:g=>g.stopPropagation(),onKeyDown:d,children:[a.jsxs("div",{className:"flex items-center gap-2.5 px-4 h-14 border-b border-border shrink-0",children:[a.jsx(di,{className:"w-4 h-4 text-text-400 shrink-0"}),a.jsx("input",{ref:c,"data-testid":"search-input",value:t,onChange:g=>e.onQueryChange(g.target.value),placeholder:"搜索会话内容、persona、联系人",className:"flex-1 bg-transparent outline-none text-[14px] text-text-100 placeholder:text-text-400"}),a.jsx(Ud,{children:"esc"})]}),r.length>0&&a.jsxs("div",{"data-testid":"search-tabs",className:"flex items-center gap-1 px-3 py-1.5 border-b border-border shrink-0",children:[r.map(g=>a.jsxs("button",{type:"button","data-testid":`search-tab-${g.key}`,onClick:()=>e.onFocusChange({group:g.key,row:0}),className:`flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[12px] ${n.group===g.key?"bg-text-100/10 text-text-100":"text-text-400 hover:text-text-200 hover:bg-text-100/5"}`,children:[g.title,a.jsx("span",{className:n.group===g.key?"text-text-300":"text-text-400/70",children:g.count})]},g.key)),a.jsx("div",{className:"flex-1"}),r.length>1&&a.jsx("span",{className:"text-[11px] text-text-400 pr-1",children:"⌘←→ 切换"})]}),a.jsxs("div",{ref:u,className:"flex-1 min-h-0 overflow-y-auto py-2",children:[!m&&a.jsx("div",{className:"px-4 py-8 text-center text-[13px] text-text-400",children:"输入关键词开始搜索"}),m&&n.group==="session"&&a.jsx("div",{className:"px-2",children:l&&s.length===0?Array.from({length:bot},(g,x)=>a.jsxs("div",{"data-testid":"search-session-skeleton",className:"px-3 py-2",children:[a.jsx("div",{className:"h-3.5 w-1/2 rounded bg-text-100/10 mb-1.5"}),a.jsx("div",{className:"h-3 w-4/5 rounded bg-text-100/5"})]},x)):s.map((g,x)=>a.jsxs("div",{...h("session",x),onClick:()=>e.onSelectSession(g),children:[a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx("span",{className:"text-[13px] text-text-100 truncate flex-1",children:a.jsx(cy,{text:g.title,query:t})}),a.jsx("span",{className:"text-[11px] text-text-400 truncate max-w-[160px]",children:g.contextLabel}),f("session",x)]}),g.snippet!==""&&a.jsx("div",{className:"mt-0.5 text-[12px] text-text-400 line-clamp-1",children:a.jsx(cy,{text:g.snippet,query:t})})]},g.sessionId))}),m&&n.group==="persona"&&a.jsx("div",{className:"px-2",children:i.map((g,x)=>a.jsx("div",{...h("persona",x),onClick:()=>e.onSelectPersona(g),children:a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx(oa,{className:"w-4 h-4 text-text-300 shrink-0"}),a.jsx("span",{className:"text-[13px] text-text-100 truncate",children:a.jsx(cy,{text:g.name,query:t})}),a.jsx("span",{className:"text-[11px] text-text-400 truncate",children:g.personaId}),a.jsx("div",{className:"flex-1"}),f("persona",x)]})},g.personaId))}),m&&n.group==="contact"&&a.jsx("div",{className:"px-2",children:o.map((g,x)=>a.jsx("div",{...h("contact",x),onClick:()=>e.onSelectContact(g),children:a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx(xT,{className:"w-4 h-4 text-text-300 shrink-0"}),a.jsx("span",{className:"text-[13px] text-text-100 truncate",children:a.jsx(cy,{text:g.name,query:t})}),a.jsx("div",{className:"flex-1"}),g.deviceCount>1&&a.jsxs("span",{className:"text-[11px] text-text-400",children:[g.deviceCount," 台"]}),f("contact",x)]})},g.deviceId))}),m&&!l&&r.length===0&&a.jsx("div",{"data-testid":"search-empty",className:"px-4 py-8 text-center text-[13px] text-text-400",children:"没有匹配"})]}),a.jsxs("div",{className:"flex items-center gap-3 px-4 h-9 border-t border-border shrink-0 text-[11px] text-text-400",children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Ud,{children:"↑↓"})," 组内移动"]}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Ud,{children:"⌘←→"})," 切换组"]}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Ud,{children:"⌘1-9"})," 打开当前组第 N 条"]}),a.jsx("div",{className:"flex-1"}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Ud,{children:"↵"})," 打开"]})]})]})})}const _ot=250;function Sot(e){const{api:t,query:n,enabled:r}=e,[s,i]=p.useState({query:"",matches:[]}),o=p.useRef(e.candidateIds);o.current=e.candidateIds;const l=p.useRef(t);l.current=t;const c=p.useRef(0),u=n.trim(),d=r&&u!=="",h=s.query===u;return p.useEffect(()=>{if(!d){c.current++;return}const f=++c.current,m=setTimeout(()=>{l.current.searchSessionContent({query:u,sessionIds:o.current}).then(g=>{c.current===f&&i({query:u,matches:g.matches})}).catch(()=>{c.current===f&&i({query:u,matches:[]})})},_ot);return()=>clearTimeout(m)},[u,d]),{matches:d&&h?s.matches:[],loading:d&&!h}}const G1=9,j3=e=>e.trim().toLowerCase(),Y1=(e,t)=>e.toLowerCase().includes(t);function kot(e){const{visible:t}=Qm(e.filter(_3));return[...t].sort((n,r)=>(r.updatedAt??"").localeCompare(n.updatedAt??""))}function Cot(e){const t=j3(e.query);if(t==="")return[];const n=new Map(e.candidates.map(l=>[l.sessionId,l])),r=new Map;for(const l of e.contentMatches)n.has(l.sessionId)&&r.set(l.sessionId,l.snippet);const s=l=>{const c=e.topicByMasterSessionId.get(l.sessionId),u=l.ownerPersonaId?e.personaLabelById.get(l.ownerPersonaId):void 0,d=(c==null?void 0:c.title)??u??l.cwd.split("/").filter(Boolean).pop()??"";return{sessionId:l.sessionId,title:_h(l)||l.sessionId,contextLabel:d,snippet:r.get(l.sessionId)??"",...c?{topicId:c.topicId}:{}}},i=[],o=new Set;for(const l of e.candidates){if(i.length>=G1)return i;Y1(_h(l),t)&&(o.add(l.sessionId),i.push(s(l)))}for(const l of e.contentMatches){if(i.length>=G1)break;if(o.has(l.sessionId))continue;const c=n.get(l.sessionId);c&&(o.add(l.sessionId),i.push(s(c)))}return i}function Not(e,t){const n=j3(t);return n===""?[]:e.filter(r=>Y1(r.personaId,n)||Y1(r.label,n)).slice(0,G1).map(r=>({personaId:r.personaId,name:r.label||r.personaId}))}function jot(e,t){const n=j3(t);if(n==="")return[];const r=[];for(const s of e){if(r.length>=G1)break;if(s.disconnected)continue;const i=s.devices[0];i&&Y1(s.displayName,n)&&r.push({deviceId:i.deviceId,name:s.displayName,deviceCount:s.devices.length})}return r}const Eot=[{key:"session",title:"会话"},{key:"persona",title:"persona"},{key:"contact",title:"联系人"}];function Iot(e){return Eot.filter(({key:t})=>e[t]>0).map(({key:t,title:n})=>({key:t,title:n,count:e[t]}))}function Wd(e,t){switch(t.kind){case"query-changed":return{group:"session",row:0};case"results-changed":return t.sessionsLoading||t.groups.length===0||t.groups.includes(e.group)?e:{group:t.groups[0],row:0};case"move-row":{if(t.rowCount<=0)return e;const n=Math.min(Math.max(e.row+t.delta,0),t.rowCount-1);return n===e.row?e:{...e,row:n}}case"move-group":{if(t.groups.length===0)return e;const n=t.groups.indexOf(e.group),r=n<0?0:n+t.delta,s=Math.min(Math.max(r,0),t.groups.length-1);return{group:t.groups[s],row:0}}case"select-group":return{group:t.group,row:0}}}const Tot=1e3;function Rot(e=Tot){const[t,n]=p.useState(!1);return p.useEffect(()=>{const r=uv()?"Meta":"Control";let s=null;const i=()=>{s!=null&&(clearTimeout(s),s=null),n(!1)},o=c=>{c.key===r&&s==null&&(s=setTimeout(()=>n(!0),e))},l=c=>{c.key===r&&i()};return window.addEventListener("keydown",o,!0),window.addEventListener("keyup",l,!0),window.addEventListener("blur",i),()=>{window.removeEventListener("keydown",o,!0),window.removeEventListener("keyup",l,!0),window.removeEventListener("blur",i),s!=null&&clearTimeout(s)}},[e]),t}function Mot({sessionLabel:e,onConfirm:t,onCancel:n}){return p.useEffect(()=>{const r=s=>{s.isComposing||s.keyCode===229||(s.key==="Enter"?(s.preventDefault(),s.stopPropagation(),t()):s.key==="Escape"&&(s.preventDefault(),s.stopPropagation(),n()))};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[t,n]),a.jsx("div",{role:"dialog","aria-modal":"true","data-testid":"archive-confirm",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40",onClick:n,children:a.jsxs("div",{className:"max-w-sm w-[92%] rounded-lg border border-border bg-bg-0 p-4 shadow-xl",onClick:r=>r.stopPropagation(),children:[a.jsxs("div",{className:"flex items-start gap-2 mb-1",children:[a.jsx(Iu,{className:"w-5 h-5 text-text-300 shrink-0 mt-0.5"}),a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"text-[14px] text-text-100",children:["归档「",a.jsx("span",{className:"font-medium break-all",children:e}),"」?"]}),a.jsx("div",{className:"mt-1 text-[12px] text-text-400",children:"可在 设置 → 已归档的聊天 中随时取消归档"})]})]}),a.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[a.jsxs("button",{type:"button","data-testid":"archive-confirm-cancel",onClick:n,className:"h-8 px-3 rounded-md text-[12px] text-text-300 hover:bg-text-100/5 cursor-pointer",children:["取消 ",a.jsx("span",{className:"text-text-400/70",children:"Esc"})]}),a.jsxs("button",{type:"button","data-testid":"archive-confirm-ok",onClick:t,className:"h-8 px-3 rounded-md bg-accent text-white text-[12px] font-medium hover:opacity-90 cursor-pointer",children:["归档 ",a.jsx("span",{className:"text-white/70",children:"⏎"})]})]})]})})}const C2={},Pot=2e3,Aot="clawd:sidebar:bulk-archive-hint-dismissed",Oot="clawd:session-info:collapsed",Dot=new Map;function $ot(){const e=dl();return a.jsx(Zxe,{host:e,children:a.jsx(Fot,{host:e})})}function Lot(e,t){if(!e)return null;for(const[n,r]of t){const s=r.find(i=>Q5(i.extId,n)===e);if(s&&s.state.kind==="installed-with-update")return{ownerPrincipalId:n,slug:s.extId,localExtId:e,extName:s.name,fromVersion:s.state.installedVersion,toVersion:s.publishedVersion,snapshotHash:s.publishedHash}}return null}function Fot({host:e}){const t=Xn(),n=p.useMemo(()=>fZ(t),[t]),r=(C2==null?void 0:C2.VITE_APP_VERSION)??"dev";return $et(r),a.jsx(mq,{cache:n.cache,children:a.jsx(fG,{children:a.jsx(Bot,{host:e})})})}function Bot({host:e}){var bP,wP;const t=Xn(),n=ZU(),r=p.useMemo(()=>new Kt(t),[t]),s=Ws(),i=Wet(t),{sessions:o,loaded:l,refresh:c}=qet(i),{capabilities:u}=jo("claude"),d=O_("claude"),{ownerPrincipalId:h,ownerId:f,ownerDisplayName:m}=Oee(t),g=hq(t),x=Fet(t,g.identity!==null),b={loggedIn:g.identity!==null,apiKey:x.apiKey,gatewayUrl:x.gatewayUrl,onRegenerate:x.regenerate,onRevoke:x.revoke,loadError:x.loadError,onReload:x.reload},y=Het(g.identity,f),v={identity:g.identity,loading:g.loading,error:g.error,active:y,onLogin:g.login,onLogout:g.logout},w=p.useMemo(()=>{if(!(!y||!g.deviceId))return frt({deviceId:g.deviceId})},[y,g.deviceId]);Vet(t,e);const _=p.useMemo(()=>h&&m?{principalId:h,displayName:m}:void 0,[h,m]),S=p.useMemo(()=>new mrt(t,_),[t,_]);p.useEffect(()=>()=>S.disposeAll(),[S]);const k=rrt(t),C=k.contacts,{visitors:j}=srt(t,y),T=p.useCallback($=>{var U;return(U=C.find(G=>G.deviceId===$))==null?void 0:U.displayName},[C]),E=p.useMemo(()=>AB(C,j),[C,j]),R=p.useCallback($=>E.get($),[E]),[P,A]=p.useState(!1),[O,F]=p.useState(!1),[z,W]=p.useState(!1),L=irt(t),D=art(t,O),I=n.getActive(),V=(I==null?void 0:I.mode)==="localhost",H=Yxe(),[M,Y]=p.useState(!1),X=lrt(t,y),K=p.useMemo(()=>crt(X.devices,h,new Set(C.map($=>$.deviceId))),[X.devices,h,C]),te=p.useMemo(()=>j.map(drt),[j]),ce=p.useMemo(()=>j.map($=>k3($.visitorId)),[j]),ee=Znt(S,C,h??"",ce),de=p.useMemo(()=>te.filter($=>{var U;return(((U=ee.messagesByPeerDeviceId.get($.deviceId))==null?void 0:U.length)??0)>0}),[te,ee.messagesByPeerDeviceId]),{byOwnerId:be,loadingOwnerIds:se,errorByOwnerId:ae,ensureLoaded:Z}=Qnt(C,S),fe=p.useMemo(()=>({spawnableContacts:ETe(C),ensureRemotePersonas:$=>Z($),remotePersonasByDeviceId:ITe(be)}),[C,Z,be]),{byOwnerId:xe,ensureLoaded:Te,upsertSession:Je,removeSession:ve}=trt(C,S),{byOwnerId:Ne,ensureLoaded:Be,refreshLocal:Re}=Jnt(C,S,t),ze=p.useCallback(async $=>{await Promise.all([ee.ensurePeerLoaded($),Z($),Te($),Be($)])},[ee,Z,Te,Be]),wt=p.useCallback($=>{ze($)},[ze]),St=p.useCallback(async $=>{const U=C.find(at=>at.deviceId===$.ownerPrincipalId);if(!(U!=null&&U.remoteUrl)||!U.connectToken)return{kind:"rolled-back",rolledBackTo:$.fromVersion,reason:"owner offline (no remoteUrl/token)"};const G=S.ensureRemoteForDevice($.ownerPrincipalId,U.remoteUrl,U.connectToken);if(!G)return{kind:"rolled-back",rolledBackTo:$.fromVersion,reason:"owner connection not available"};const{zipBase64:ie}=await G.request("extension.fetchBundle",{extId:$.slug,snapshotHash:$.snapshotHash}),He=await t.request("extension.update-from-channel",{channelRef:{kind:"p2p-tunnel",ownerPrincipalId:$.ownerPrincipalId,extId:$.slug},snapshotHash:$.snapshotHash,zipBase64:ie});return await Re(),He.kind==="updated"?{kind:"updated",installedVersion:He.installedVersion}:{kind:"rolled-back",rolledBackTo:He.rolledBackTo,reason:He.reason}},[C,S,t,Re]),oe=p.useCallback(async($,U,G)=>{const ie=C.find(at=>at.deviceId===$);if(!(ie!=null&&ie.remoteUrl)||!ie.connectToken)return;const He=S.ensureRemoteForDevice($,ie.remoteUrl,ie.connectToken);if(He)try{const{zipBase64:at}=await He.request("extension.fetchBundle",{extId:U,snapshotHash:G});await t.request("extension.install-from-channel",{channelRef:{kind:"p2p-tunnel",ownerPrincipalId:$,extId:U},snapshotHash:G,zipBase64:at}),await Re()}catch(at){Ae("app","install remote extension failed",{ownerPrincipalId:$,extId:U,err:at.message})}},[C,S,t,Re]),[le,me]=p.useState(My),Ke=p.useRef(le);p.useEffect(()=>{Ke.current=le},[le]);const Ge=le.tabs[le.focused]??null,ut=(Ge==null?void 0:Ge.kind)==="session"?Ge.sid:null,tn=(Ge==null?void 0:Ge.kind)==="ext"?Ge.extId:null,qe=p.useRef(!1),Zt=p.useRef(new Set),[Se,Pe]=p.useState(!1),[dt,Pt]=p.useState(null),[hn,we]=p.useState({signal:0,sessionId:null}),ne=p.useCallback($=>{we(U=>({signal:U.signal+1,sessionId:$}))},[]),Oe=p.useRef(!1);p.useEffect(()=>{Oe.current=Se},[Se]);const[it,nt]=p.useState(!1),[kt,At]=p.useState(!1),[zt,sn]=p.useState(null),[$n,Lt]=p.useState(!1),[xn,yn]=p.useState(null),[Sn,Qt]=p.useState(0),[_e,vt]=p.useState(!1),[Ct,Ut]=p.useState(!1),[hr,rr]=p.useState(()=>new Set),[fr,eo]=p.useState(null),[wi,to]=p.useState(!1),[ja,no]=p.useState(!1),ro=ZY(),{personas:Wt,refresh:Oc}=j_();p.useEffect(()=>{Ct&&Oc().catch(()=>{})},[Ct,Oc]);const{projects:qs,reload:ye}=bit(r),[Qe,lt]=p.useState(!1),[Vt,qn]=p.useState(!1),[dd,ap]=p.useState(void 0),gS=p.useCallback($=>{r&&(qn(!0),ap(void 0),r.projectCreate({name:$}).then(async()=>{await ye(),lt(!1)}).catch(U=>ap(U instanceof Error?U.message:String(U))).finally(()=>qn(!1)))},[r,ye]),Lo=p.useMemo(()=>qs.map($=>$.path),[qs]),Ea=p.useCallback($=>{var U;return(U=Wt.find(G=>G.personaId===$))==null?void 0:U.label},[Wt]),[dv,yl]=p.useState(!1),[Dc,hv]=p.useState(!1),[fv,_i]=p.useState(!1),[lp,hd]=p.useState(!1),$c=vrt(),fd=mit(),pv=xit(),mv=yit(),[gv,xS]=p.useState(null);p.useEffect(()=>{},[mv]);const xv=XU(),[pd,md]=p.useState(null),[vv,so]=p.useState(null),gd=p.useRef(null),Fo=p.useCallback($=>{so($),gd.current&&clearTimeout(gd.current),!($.kind==="error"&&$.action||$.kind==="progress")&&(gd.current=setTimeout(()=>so(null),5e3))},[]),Ia=p.useCallback(()=>Fo({kind:"archived"}),[Fo]),{channels:io,loading:yv,create:bv,update:wv,remove:cp,error:up}=bnt(t),{topicsByChannel:Ks,linesByTopic:re,loaded:De,reload:ht}=_nt(r,io,o,t),Ot=p.useMemo(()=>ove(re),[re]),Kn=p.useMemo(()=>{if((Ge==null?void 0:Ge.kind)!=="topic")return null;for(const $ of Object.values(Ks)){const U=$.find(G=>G.id===Ge.topicId);if(U)return U.masterSessionId}return null},[Ge,Ks]),pr=!yv&&De;p.useEffect(()=>{if(qe.current||!l)return;const $=G=>!G||G.tabs.some(He=>He.kind==="session")&&o.length===0?!1:(me(G),qe.current=!0,!0);if($(Cit()))return;let U=!1;return(async()=>{const G=await e.kv.get(GB).catch(ln=>(Ae("view-kv","get failed",ln),null));if(Ae("view-kv","get →",G),U)return;const ie=G&&typeof G=="object"&&"value"in G?G.value:G,He=typeof ie=="string"?Cte(ie):null;if($(He)||!pr)return;const at=Qm(o.filter(yB)).visible.find(ln=>!Ot.has(ln.sessionId));at&&me({tabs:[{kind:"session",sid:at.sessionId}],focused:0}),qe.current=!0})(),()=>{U=!0}},[l,o,e,pr,Ot]),p.useEffect(()=>{if(!qe.current)return;Nit(le);const $=Nte(le);Ae("view-kv","set →",$),e.kv.set(GB,$).catch(U=>{Ae("view-kv","set failed",U)})},[le,e]);const Zr=p.useRef("");p.useEffect(()=>{const $=le.tabs.map(Ag).join(" | ");Zr.current!==""&&$!==Zr.current&&console.log(`[tab-debug] tabs changed
|
|
953
953
|
prev:`,Zr.current,`
|
|
954
954
|
next:`,$,`
|
|
955
|
-
focused:`,le.focused),Zr.current=$},[le]);const Lc=p.useRef(new Set);p.useEffect(()=>{if(!qe.current)return;const $=U=>{Lc.current.has(U)||C.some(G=>G.deviceId===U)&&(Lc.current.add(U),ze(U))};for(const U of le.tabs)if(U.kind==="dm")$(U.peerDeviceId);else if(U.kind==="session"){const G=o.find(ie=>ie.sessionId===U.sid);G!=null&&G.originOwnerPrincipalId&&$(G.originOwnerPrincipalId)}},[le,C,o,ze]),p.useEffect(()=>{if(!qe.current||o.length===0)return;const $=new Set(o.map(G=>G.sessionId));for(const G of $)Zt.current.add(G);const U=Zt.current;me(G=>{const ie=G.tabs.filter(at=>at.kind!=="session"?!0:!U.has(at.sid)||$.has(at.sid));if(ie.length===G.tabs.length)return G;if(ie.length===0)return My;const He=Math.min(G.focused,ie.length-1);return{tabs:ie,focused:Math.max(0,He)}})},[o]);const{prune:_v}=$c;p.useEffect(()=>{l&&_v(new Set(o.map($=>$.sessionId)))},[l,o,_v]);const Qn=ut?o.find($=>$.sessionId===ut)??null:null,{visible:Fc,archivedRoots:Dte,archivedChildrenByRoot:$te}=p.useMemo(()=>Qm(o.filter(yB)),[o]),I3=p.useMemo(()=>new Map(Fc.map($=>[$.sessionId,lv($)])),[Fc]),T3=p.useCallback($=>I3.get($),[I3]),vS=p.useMemo(()=>Qm(o.filter(_3)).visible,[o]),yS=p.useMemo(()=>vS.filter($=>cS($,h??void 0)).map($=>({sid:$.sessionId,originOwnerPrincipalId:$.originOwnerPrincipalId??null})),[vS,h]),R3=$ee(yS,S),oo=p.useCallback(($,U)=>{const G=$.tabs.findIndex(ie=>ie.kind==="session"&&ie.sid===U);return G>=0?am($,G):$},[]),Lte=p.useSyncExternalStore(p.useCallback($=>S.onOwnersChanged($),[S]),()=>S.listRemoteDeviceIds().sort().join("|"),()=>""),M3=!k.loading;p.useEffect(()=>{if(!M3)return;const $=[];for(const U of le.tabs){if(U.kind!=="session")continue;const G=o.find(ln=>ln.sessionId===U.sid);if(!(G!=null&&G.originOwnerPrincipalId))continue;const ie=G.originOwnerPrincipalId,He=S.getRemoteForDevice(ie)!==null,at=C.some(ln=>ln.deviceId===ie);!He&&!at&&$.push(U.sid)}$.length!==0&&me(U=>{let G=U;for(const ie of $)G=oo(G,ie);return G})},[M3,le,o,C,S,Lte,oo]);const bl=Jet({entries:yS,sessions:vS,activeId:ut??Kn,pool:S}),xd=Lee(yS,S),Si=p.useMemo(()=>{const $=new Set;for(const[U,G]of R3)G==="turn-running"&&$.add(U);return $},[R3]),P3=p.useMemo(()=>{let $=0;for(const U of ee.unreadByPeer.values())$+=U;return $},[ee.unreadByPeer]),bS=p.useMemo(()=>{const $=new Set;for(const[U,G]of ee.unreadByPeer)G>0&&$.add(U);return $},[ee.unreadByPeer]),A3=i.kind==="disconnected"||i.kind==="auth-failed"||i.kind==="version-mismatch"||i.kind==="reconnecting",Fte=i.kind==="connecting"||i.kind==="idle",dp=qU(),vd=dp?$xe(i):null,O3=(vd==null?void 0:vd.kind)==="reopen"&&vd.reason==="expired";p.useEffect(()=>{O3&&(dp==null||dp.invalidate())},[O3,dp]);const Ta=p.useCallback($=>{_i(!1);const U=o.find(ie=>ie.sessionId===$);U!=null&&U.originOwnerPrincipalId&&ze(U.originOwnerPrincipalId);const G=U==null?void 0:U.cwd;G&&!(U!=null&&U.originOwnerPrincipalId)?Promise.all([r.getGitRoot(G),r.getGitBranch(G)]).then(([ie,He])=>{Ae("app","selectSession",{sessionId:$,cwd:G,gitRoot:ie.gitRoot,branch:He.branch})}).catch(ie=>{Ae("app","selectSession git probe failed",{sessionId:$,err:ie})}):Ae("app","selectSession",{sessionId:$,cwd:null}),me(ie=>Es(ie,{kind:"session",sid:$})),Oe.current||ne($)},[o,r,ze,ne]),Bc=p.useCallback(async $=>{const U=await r.sessionCreate(oD($));return await c(),Ta(U.sessionId),{sessionId:U.sessionId}},[r,c,Ta]),wS=p.useCallback(async({personaId:$,text:U,config:G})=>{const ie=zq(U)??"新建 session",{sessionId:He}=await Bc({ownerPersonaId:$,aiLabel:ie,...G.model?{model:G.model}:{},...G.effort?{effort:G.effort}:{}});await r.sessionSubscribe(He),await r.sessionSend(He,U),At(!1),me(at=>{const ln=at.tabs.findIndex(Bo=>Bo.kind==="landing");return ln>=0?am(at,ln):at})},[r,Bc]),Bte=p.useCallback(()=>{r.onboardingComplete().catch(()=>{}),nt(!0),At(!0),me($=>Es($,{kind:"landing"}))},[r]),zte=p.useCallback(async $=>{await Bc({cwd:$})},[Bc]),Hte=p.useCallback(async $=>{const U=await r.sessionCreate(oD({cwd:$}));await c(),me(G=>Es(G,{kind:"session",sid:U.sessionId}))},[r,c]),_S=p.useRef(!1),Ute=p.useCallback(async($,U)=>{const G=mu($.tool);if(G){if(_S.current)return;_S.current=!0,Fo({kind:"progress",text:"正在分叉云会话…"})}try{const ie=await Hq(r,$,U);if(G&&so(null),!ie)return;await c(),me(He=>Es(He,{kind:"session",sid:ie.sessionId}))}catch(ie){if(!G)throw ie;Fo({kind:"error",text:ie instanceof Error?ie.message:String(ie)})}finally{G&&(_S.current=!1)}},[r,c,Fo]),SS=p.useCallback(async $=>{const U=ny(o,$);for(const ie of U)await r.sessionDelete(ie);await r.sessionDelete($);const G=new Set([$,...U]);me(ie=>aO(ie,He=>He.kind==="session"&&G.has(He.sid))),await c()},[r,o,c]),D3=p.useCallback(async($,U)=>{U.label&&(await r.sessionUpdate($,{label:U.label}),await c())},[r,c]),Wte=p.useCallback(async($,U)=>{await r.pinSession($,U),await c()},[r,c]),{width:kS,onDragStart:Vte}=krt(),[wl,$3]=bm(Pnt,!1),[qte,CS]=p.useState(!1),hp=p.useRef(null),yd=p.useCallback(($,U)=>{hp.current&&clearTimeout(hp.current),hp.current=setTimeout(()=>CS($),U)},[]);p.useEffect(()=>()=>{hp.current&&clearTimeout(hp.current)},[]);const L3=Ct||_e,F3=p.useCallback(()=>yd(!0,MB),[yd]),B3=p.useCallback(()=>{L3||yd(!1,g2)},[yd,L3]),an=p.useCallback(()=>{Ut(!1),vt(!1),wl&&yd(!1,g2)},[wl,yd]),Kte=p.useMemo(()=>nve({channels:io,topicsByChannel:Ks,linesByTopic:re,sessions:o,runningSessionIds:Si}),[io,Ks,re,o,Si]),Gte=p.useMemo(()=>rve({channels:io,topicsByChannel:Ks,linesByTopic:re,sessions:o,runningSessionIds:Si}),[io,Ks,re,o,Si]),z3=p.useMemo(()=>ive({linesByTopic:re,sessions:o}),[re,o]),Sv=ut??Kn,NS=p.useMemo(()=>Sv?o.find($=>$.sessionId===Sv)??null:null,[Sv,o]),H3=knt(r,Sv,NS==null?void 0:NS.updatedAt),Yte=p.useMemo(()=>({resolve:Snt({records:H3,selfDeviceId:h??void 0,lineIndex:z3,sessions:o,personas:Wt,contacts:C}),onOpenSession:Ta,...r?{onAnswer:async($,U)=>{await r.a2aAnswer({taskId:$,text:U})}}:{}}),[H3,z3,o,Wt,C,Ta,r]),Xte=p.useMemo(()=>sve({channels:io,topicsByChannel:Ks,linesByTopic:re,sessions:o,runningSessionIds:Si}),[io,Ks,re,o,Si]),fp=p.useMemo(()=>Object.values(Ks).flat(),[Ks]),Zte=p.useCallback($=>{rr(U=>{const G=new Set(U);return G.has($)?G.delete($):G.add($),G})},[]),kv=p.useCallback($=>{me(U=>Es(U,{kind:"topic",topicId:$}))},[]),[Qte,U3]=p.useState(null),[Jte,W3]=p.useState(null),[ene,V3]=p.useState(null),tne=Qte??ene??(fr===null?Jte:null),nne=p.useCallback(async $=>{if(r){U3(null);try{const{topicId:U}=await r.topicCreate({channelId:$});ht(),kv(U)}catch(U){Ae("app","topicCreate failed",{channelId:$,err:String(U)}),U3({channelId:$,message:U instanceof Error?U.message:String(U)})}}},[r,kv,ht]),bd=p.useCallback($=>fp.find(U=>U.id===$)??null,[fp]),q3=p.useCallback($=>{var U;return((U=bd($))==null?void 0:U.channelId)??null},[bd]),_l=p.useCallback(async($,U,G)=>{V3(null);try{await G(),ht()}catch(ie){Ae("app",`${U} failed`,{topicId:$,err:String(ie)});const He=q3($);He&&V3({channelId:He,message:ie instanceof Error?ie.message:String(ie)})}},[q3,ht]),rne=p.useCallback($=>{var G;const U=(G=bd($))==null?void 0:G.masterSessionId;U&&_l($,"topicArchive",()=>r.archiveSession(U,!0))},[r,bd,_l]),sne=p.useCallback($=>{r.archiveSession($,!1).then(()=>c())},[r,c]),ine=p.useCallback(($,U)=>void _l($,"topicRename",()=>r.topicRename({topicId:$,title:U})),[r,_l]),K3=p.useCallback($=>void _l($,"topicDelete",async()=>{const U=await r.topicDelete({topicId:$}),G=new Set([...U.removedMasterSessionId?[U.removedMasterSessionId]:[],...U.removedWorkerSessionIds]);me(ie=>aO(ie,He=>He.kind==="topic"&&He.topicId===$||He.kind==="session"&&G.has(He.sid)))}),[r,_l]),one=p.useCallback(($,U)=>{var ie;const G=(ie=bd($))==null?void 0:ie.masterSessionId;G&&_l($,"topicPin",()=>r.pinSession(G,U))},[r,bd,_l]),ane=p.useCallback(async $=>{W3(null);try{await cp($)}catch(U){W3({channelId:$,message:U instanceof Error?U.message:String(U)})}},[cp]),[Ra,jS]=bm(Oot,!0),[Cv,lne]=bm("clawd:workspace-cards-collapsed",!1),[cne,une]=p.useState(null),pp=!!(Qn&&mu(Qn.tool)&&!Qn.larkChatId),ES=!!(Qn&&!Qn.larkChatId&&(pp?!Cv:Ra)),[dne,hne]=p.useState(null),[IS,fne]=p.useState(null),[G3,Nv]=p.useState(!1),mp=p.useRef(null),{initialSize:Y3,setSize:pne}=Uq("clawd:panel:session-info-px",320),jv=p.useCallback(($,U)=>{mp.current&&clearTimeout(mp.current),mp.current=setTimeout(()=>Nv($),U)},[]),Ev=p.useCallback(()=>jv(!0,MB),[jv]),Iv=p.useCallback(()=>jv(!1,g2),[jv]);p.useEffect(()=>()=>{mp.current&&clearTimeout(mp.current)},[]);const wd=["session","topic"].includes(((bP=le.tabs[le.focused])==null?void 0:bP.kind)??""),mne=wd?Ra?G3?IS:null:dne:null;p.useEffect(()=>{wd||Nv(!1)},[wd]),p.useEffect(()=>{const $=IS;if($)return $.addEventListener("mouseenter",Ev),$.addEventListener("mouseleave",Iv),()=>{$.removeEventListener("mouseenter",Ev),$.removeEventListener("mouseleave",Iv)}},[IS,Ev,Iv]);const TS=Rot(),[RS,gne]=wf(Ltt,"priority"),[xne,vne]=wf(Btt,"archive"),MS=p.useMemo(()=>_it(Fc,{ownerPrincipalId:h??void 0,sortMode:RS,attention:{awaitingIds:xd,runningIds:Si,unreadIds:bl},projectPaths:Lo,topicSessionIds:Ot}).slice(0,9),[Fc,h,RS,xd,Si,bl,Lo,Ot]),yne=p.useMemo(()=>({held:TS,indexBySessionId:new Map(MS.map(($,U)=>[$,U+1]))}),[TS,MS]),[PS,X3]=p.useState(null),Tv=p.useRef(null),_d=p.useRef(null),gp=p.useCallback(()=>{_d.current!=null&&(clearTimeout(_d.current),_d.current=null),Tv.current=null,X3(null)},[]);p.useEffect(()=>gp,[gp]);const Sd=p.useCallback(()=>{const $=Tv.current;if(gp(),$==null)return;me(G=>lO(G,$));const U=Ke.current.tabs[$];(U==null?void 0:U.kind)==="session"&&ne(U.sid)},[gp,ne]),Z3=p.useCallback($=>{const U=Ke.current.tabs.length;if(U===0)return;const ie=((Tv.current??Ke.current.focused)+$+U)%U;Tv.current=ie,X3(ie),_d.current!=null&&clearTimeout(_d.current),_d.current=setTimeout(Sd,Pot)},[Sd]);p.useEffect(()=>{if(PS==null)return;const $=U=>{(U.key==="Meta"||U.key==="Control"||U.key==="Shift")&&Sd()};return window.addEventListener("keyup",$,!0),window.addEventListener("blur",Sd),()=>{window.removeEventListener("keyup",$,!0),window.removeEventListener("blur",Sd)}},[PS,Sd]);const[xp,Rv]=p.useState(!1),[Ma,AS]=p.useState(""),[kd,Sl]=p.useState({group:"session",row:0}),[bne,Q3]=p.useState(null),[wne,OS]=p.useState(null),Mv=p.useMemo(()=>kot(o),[o]),_ne=p.useMemo(()=>Mv.map($=>$.sessionId),[Mv]),{matches:J3,loading:DS}=Sot({api:r,query:Ma,candidateIds:_ne,enabled:xp}),eP=p.useMemo(()=>{const $=new Map(o.map(U=>[U.sessionId,U]));return new Map(fp.map(U=>[U.masterSessionId,{topicId:U.id,title:Vw(U.title,$.get(U.masterSessionId)??null)}]))},[fp,o]),tP=p.useMemo(()=>new Map(Wt.map($=>[$.personaId,$.label])),[Wt]),vp=p.useMemo(()=>Cot({candidates:Mv,query:Ma,contentMatches:J3,topicByMasterSessionId:eP,personaLabelById:tP}),[Mv,Ma,J3,eP,tP]),yp=p.useMemo(()=>Not(Wt,Ma),[Wt,Ma]),bp=p.useMemo(()=>{const $=S3(C,Dot);return jot([...$.pinned,...$.main],Ma)},[C,Ma]),$S=p.useMemo(()=>Iot({session:vp.length,persona:yp.length,contact:bp.length}),[vp.length,yp.length,bp.length]),wp=p.useMemo(()=>$S.map($=>$.key),[$S]),Sne=kd.group==="session"?vp.length:kd.group==="persona"?yp.length:bp.length;p.useEffect(()=>{Sl($=>Wd($,{kind:"query-changed"}))},[Ma]),p.useEffect(()=>{Sl($=>Wd($,{kind:"results-changed",groups:wp,sessionsLoading:DS}))},[wp,DS]);const nP=p.useCallback(()=>{an(),AS(""),Sl({group:"session",row:0}),Rv(!0)},[an]),[LS,Pv]=p.useState(!1),rP=p.useCallback(()=>{an(),Rv(!1),Pv(!0)},[an]),kne=p.useMemo(()=>AB(C.map($=>({deviceId:$.deviceId,displayName:$.displayName})),[]),[C]),sP={"toggle-hive":()=>{if(LS){Pv(!1);return}rP()},"new-session":()=>{an(),Pe(!0)},"open-search":()=>{if(xp){Rv(!1);return}nP()},...xp?{"search-tab-prev":()=>Sl($=>Wd($,{kind:"move-group",delta:-1,groups:wp})),"search-tab-next":()=>Sl($=>Wd($,{kind:"move-group",delta:1,groups:wp}))}:{},...Object.fromEntries(Array.from({length:9},($,U)=>[`switch-session-${U+1}`,()=>{if(xp){fP(U);return}const G=MS[U];G&&(an(),Sp(G))}])),"tab-prev":()=>Z3(-1),"tab-next":()=>Z3(1),...le.tabs.length>0?{"close-tab":()=>me($=>am($,$.focused))}:{},"archive-session":()=>{const $=Ke.current.tabs[Ke.current.focused];if(($==null?void 0:$.kind)!=="session")return;const U=o.find(ie=>ie.sessionId===$.sid);if(!U)return;const G=cv(U);G&&o.some(ie=>ie.sessionId===G)||FS($.sid)}};wtt(LS?{"toggle-hive":sP["toggle-hive"]}:sP);const[Av,FS]=p.useState(null),[iP,Cne,oP]=bm(Aot,!1),aP=p.useRef(!1),[Nne,BS]=p.useState(null);p.useEffect(()=>{if(aP.current||!l||h==null||!oP||(aP.current=!0,iP))return;const $=h2(o,h,10,Lo,Ot).length;$>0&&BS($)},[o,l,h,Lo,Ot,iP,oP]);const zS=p.useCallback(async($,U)=>{if(U){const G=[$,...ny(o,$)];me(ie=>G.reduce((He,at)=>oo(He,at),ie))}await r.archiveSession($,U),await c(),U&&Ia()},[r,c,oo,o,Ia]),jne=p.useCallback(async $=>{await r.reorderPins($),await c()},[r,c]),HS=p.useCallback($=>{_i(!1),sn({kind:"config",personaId:$})},[]),Ene=p.useCallback($=>{an(),me(U=>Es(U,{kind:"deploy",personaId:$}))},[an]),Ine=p.useCallback(($,U)=>{an(),me(G=>Es(G,{kind:"deploy-history",personaId:$,head:U}))},[an]),Tne=p.useCallback(async $=>{var G;const U=((G=Wt.find(ie=>ie.personaId===$))==null?void 0:G.label)??$;confirm(`删除 persona "${U}"?`)&&(await ro($),sn(ie=>(ie==null?void 0:ie.personaId)===$?null:ie))},[ro,Wt]),Rne=p.useCallback(async($,U)=>{_i(!1),sn(null);const G={ownerPersonaId:$},ie=U.trim();ie&&(G.label=ie);try{const He=await r.sessionCreate(G);await c(),Ta(He.sessionId)}catch(He){Ae("persona","sessionCreate(ownerPersonaId) failed",He)}},[r,c,Ta,Wt]),Mne=p.useCallback(async($,U,G)=>{try{const{sessionId:ie}=await Bc({ownerPersonaId:$,label:G});await r.sessionSubscribe(ie),await r.sessionSend(ie,U)}catch(ie){throw Ae("pr-inbox","open chat failed",ie),ie}},[r,Bc]),kl=p.useCallback(async($,U)=>{const G=SI(U,$);try{await r.peerSessionUpsert(G)}catch(ie){Ae("mirror","peerSession:upsert failed",G.sessionId,ie)}s.setData("sessions",ie=>{const He=[...ie??[]],at=He.findIndex(ln=>ln.sessionId===G.sessionId);return at>=0?He[at]=G:He.unshift(G),He})},[r,s]),Ov=p.useCallback(async $=>{try{await r.peerSessionRemove($)}catch(U){Ae("mirror","peerSession:remove failed",$,U)}s.setData("sessions",U=>(U??[]).filter(G=>G.sessionId!==$))},[r,s]),Pne=p.useCallback(async($,U,G)=>{await ze($);const ie=S.getRemoteForDevice($);if(!ie)throw new Error("remote daemon unreachable");const He=new Kt(ie),at={ownerPersonaId:U},ln=G.trim();ln&&(at.label=ln);try{const Bo=await He.sessionCreate(at),Lv=Bo;Je($,Lv),me(kp=>Es(kp,{kind:"session",sid:Bo.sessionId})),kl($,Lv).catch(kp=>{Ae("persona","upsertMirrorLocally (remote create) failed",kp)})}catch(Bo){Ae("persona","sessionCreate(remote) failed",{ownerId:$,personaId:U,err:Bo})}},[S,be,ze,Je,kl]),Cl=p.useCallback($=>{const U=S.getRemoteForDevice($);if(U)return U;const G=C.find(ie=>ie.deviceId===$);return!(G!=null&&G.remoteUrl)||!G.connectToken?null:S.ensureRemoteForDevice($,G.remoteUrl,G.connectToken)},[S,C]),ao=p.useCallback(($,U,G,ie)=>{Fo({kind:"error",text:iit(T($),U,G),...ie?{action:ie}:{}})},[Fo,T]),US=p.useCallback(async($,U)=>{const G=async()=>{ve($,U),me(at=>oo(at,U)),await Ov(U)},ie=Cl($);if(!ie){await G();return}const He=new Kt(ie);try{await He.sessionDelete(U),G().catch(at=>{Ae("persona","removeMirrorLocally (remote delete) failed",at)})}catch(at){Ae("persona","sessionDelete(remote) failed",at),ao($,"删除",at,{label:"只从我这儿移除",onClick:()=>{so(null),G().catch(ln=>{Ae("persona","removeMirrorLocally (drop from my side) failed",ln)})}})}},[Cl,ao,ve,Ov,oo]),Ane=p.useCallback(async($,U,G)=>{const ie=G?"置顶":"取消置顶",He=Cl($);if(!He){ao($,ie,null);return}const at=new Kt(He);try{const ln=await at.pinSession(U,G);await kl($,ln),so(null)}catch(ln){Ae("persona","pinSession(remote) failed",ln),ao($,ie,ln)}},[Cl,ao,kl]),_p=p.useCallback(async($,U,G)=>{const ie=G?"归档":"取消归档",He=Cl($);if(!He)return ao($,ie,null),!1;const at=new Kt(He);try{if(G){const Bo=[U,...ny(o,U)];me(Lv=>Bo.reduce((kp,Xne)=>oo(kp,Xne),Lv))}const ln=await at.archiveSession(U,G);return await kl($,ln),G&&Ia(),!0}catch(ln){return Ae("persona","archiveSession(remote) failed",ln),ao($,ie,ln),!1}},[Cl,ao,kl,oo,o,Ia]),One=p.useCallback(async $=>{const U=h2(o,h??void 0,$,Lo,Ot);let G=0;for(const ie of U){if(ie.originOwnerPrincipalId){await _p(ie.originOwnerPrincipalId,ie.sessionId,!0)||(G+=1);continue}const He=[ie.sessionId,...ny(o,ie.sessionId)];me(at=>He.reduce((ln,Bo)=>oo(ln,Bo),at));try{await r.archiveSession(ie.sessionId,!0)}catch(at){Ae("persona","bulkArchive: archiveSession failed",at),G+=1}}await c(),BS(null),U.length>0&&G===0&&Ia()},[o,h,Lo,Ot,r,c,oo,_p,Ia]),Dne=p.useCallback($=>h2(o,h??void 0,$,Lo,Ot).length>0,[o,h,Lo,Ot]),lP=p.useCallback(async($,U,G)=>{if(!G.label)return;const ie=Cl($);if(!ie){ao($,"改名",null);return}const He=new Kt(ie);try{const at=await He.sessionUpdate(U,{label:G.label});await kl($,at),so(null)}catch(at){Ae("persona","sessionUpdate(remote) failed",at),ao($,"改名",at)}},[Cl,ao,kl]),cP=p.useCallback(()=>{_i(!1),yn(null),Lt(!0)},[]),$ne=p.useCallback(async $=>{no(!0),yn(null);try{await wS({personaId:ei,text:Ort($),config:{model:"",effort:"",permissionMode:""}}),Lt(!1),Qt(U=>U+1),an()}catch(U){yn(U.message??String(U))}finally{no(!1)}},[wS,an]),Lne=p.useCallback(async()=>{const $=n.getActive();$&&await n.activate($.id)},[n]),Sp=p.useCallback($=>{sn(null),Ta($)},[Ta]),Dv=()=>{Rv(!1),AS("")},uP=$=>{if(Dv(),$.topicId!==void 0){kv($.topicId);return}Sp($.sessionId)},dP=$=>{Dv(),Q3($),vt(!1),Ut(!0)},Pa=Mnt(),Fne=p.useMemo(()=>{const $=new Map(C.map(U=>[U.deviceId,U]));return Pa.favorites.flatMap(U=>{var He;const G=U.deviceId?$.get(U.deviceId):void 0;if(!U.deviceId||!G)return[];const ie=(He=be.get(U.deviceId))==null?void 0:He.find(at=>at.personaId===U.personaId);return[{deviceId:U.deviceId,personaId:U.personaId,label:(ie==null?void 0:ie.label)??U.label??U.personaId,tool:(ie==null?void 0:ie.tool)??U.tool,contactName:G.displayName||G.deviceId}]})},[Pa.favorites,C,be]),Bne=$=>{OS($),Ut(!1),vt(!0),ze($)},hP=$=>{Dv(),OS($),Ut(!1),vt(!0),ze($)},fP=$=>{if(kd.group==="session"){const G=vp[$];G&&uP(G);return}if(kd.group==="persona"){const G=yp[$];G&&dP(G.personaId);return}const U=bp[$];U&&hP(U.deviceId)},pP=A3||Dc;if(pP&&vd)return a.jsx(KU,{view:vd});if(pP)return a.jsx(Tst,{state:i,onClose:A3?void 0:()=>hv(!1),remoteHosts:H});if(Fte||!l)return a.jsx("div",{"data-testid":"app-bootstrapping",className:"h-screen flex items-center justify-center bg-bg-0",children:a.jsx(st,{className:"w-5 h-5 text-text-400 animate-spin"})});if(i.kind==="connected"&&i.mode!=="remote"&&i.onboardingCompletedAt===null&&!it)return a.jsx(ost,{api:r,feishuIdentity:g.identity,feishuError:g.error,onFeishuLogin:g.login,personas:Wt.map($=>({personaId:$.personaId,label:$.label})),onFinished:Bte});const zne=(Qn==null?void 0:Qn.label)||(Qn==null?void 0:Qn.aiLabel)||(Qn!=null&&Qn.cwd?Qn.cwd.split("/").filter(Boolean).pop()??"Clawd":"Clawd"),mP=wl?nu+kS:kS,gP=wl?x2:0,xP=wl?nu:0,$v=(wP=le.tabs[le.focused])==null?void 0:wP.kind,Hne=_e?"people":Ct?"persona":$v==="exts"||$v==="shift"||$v==="prs"?$v:null,Une=$=>{if(_i(!1),$==="people"){OS(null),Ut(!1),vt(G=>!G);return}if($==="persona"){Q3(null),vt(!1),Ut(G=>!G);return}if(an(),$==="new"){me(G=>Es(G,{kind:"landing"}));return}const U=$==="shift"?{kind:"shift"}:$==="prs"?{kind:"prs"}:{kind:"exts"};me(G=>Es(G,U))},Wne=a.jsxs(a.Fragment,{children:[H,a.jsx(fit,{identity:g.identity,loading:g.loading,error:g.error,onLogin:g.login}),a.jsxs("div",{className:"flex items-center gap-1 pr-1",children:[a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx(dit,{onClick:()=>md("about")})}),a.jsx(hit,{})]})]}),Vne=a.jsx(rb.Provider,{value:$c,children:a.jsx(vnt,{client:t,open:_e,initialSelectedId:wne,onClose:an,sidebarWidth:mP,insetTop:gP,insetBottom:xP,contacts:C,publicDevices:K,onConnectPublicDevice:async $=>{await X.connect($)},remoteGated:!y,onAddContact:()=>A(!0),visitors:de,visitorUnreadIds:bS,unreadDeviceIds:bS,isRemotePersonaFavorite:Pa.isFavorite,onToggleRemotePersonaFavorite:($,U)=>Pa.toggleFavorite({personaId:U.personaId,deviceId:$,label:U.label,tool:U.tool}),onOpenVisitor:$=>{an(),me(U=>Es(U,{kind:"dm",peerDeviceId:$}))},loginCardNode:a.jsx(gB,{...v}),onEnsureContactLoaded:wt,personasByOwnerId:be,personaLoadingOwnerIds:se,personaErrorByOwnerId:ae,onRetryPersonas:wt,onReconnectContact:async $=>{await X.connect({deviceId:$.deviceId,url:$.remoteUrl||void 0})},sessionsByOwnerId:xe,extensionsByOwnerId:Ne,activeSessionId:zt?null:ut,awaitingIds:xd,runningIds:Si,unreadIds:bl,onMessage:$=>{an(),ze($),me(U=>Es(U,{kind:"dm",peerDeviceId:$}))},onPinContact:($,U)=>void k.pin($,U),onSetContactRemoteAccess:($,U)=>k.setRemoteAccess($.deviceId,{remoteAccessAllowed:U}),onSetContactNote:($,U)=>void k.setNote($,U),onRemoveContact:$=>{const U=$.deviceId;for(const G of o)G.originOwnerPrincipalId===U&&Ov(G.sessionId);k.remove(U)},onCreateRemoteSession:($,U)=>(an(),Pne($,U,"")),onSelectSession:$=>{an(),Ta($)},onDeleteRemoteSession:($,U)=>void US($,U),onEditRemoteSession:($,U,G)=>void lP($,U,G),onInstallExtension:($,U,G)=>{G&&oe($,U,G)},onOpenInstalledExtension:($,U)=>{an(),me(G=>Es(G,{kind:"ext",extId:Q5(U,$)}))}})}),qne=a.jsx("div",{className:"h-full w-full overflow-y-auto bg-bg-100",children:a.jsx("div",{className:"max-w-[480px] h-full border-r border-border",children:a.jsx(qnt,{client:t,activeExtId:tn,onOpenInMain:$=>me(U=>Es(U,{kind:"ext",extId:$})),onExtensionsMutated:()=>void Re()})})}),Kne=fr?a.jsx(ynt,{open:!0,submitting:wi,mode:fr.mode,...fr.mode==="edit"?(()=>{const $=io.find(U=>U.id===fr.channelId);return $?{initial:{name:$.name,memberPersonas:[...$.memberPersonas],memberContactDeviceIds:[...$.memberContactDeviceIds]}}:{}})():{},personas:Wt.map($=>({id:$.personaId,label:$.label||$.personaId})),contactGroups:C.map($=>{const U=be.get($.deviceId),G=ae.get($.deviceId);return{deviceId:$.deviceId,displayName:$.displayName,...U?{personas:U.map(ie=>({id:ie.personaId,label:ie.label||ie.personaId}))}:{},...se.has($.deviceId)?{loading:!0}:{},...G?{errorText:G}:{},...zf($)?{}:{brokenLink:!0}}}),onExpandContact:$=>void Z($),...up?{error:up}:{},onCancel:()=>eo(null),onSubmit:$=>{const U=()=>{to(!1),eo(null)},G=()=>to(!1);to(!0),fr.mode==="create"?bv($).then(U).catch(G):wv({channelId:fr.channelId,...$}).then(U).catch(G)}}):null,Gne=a.jsx(rb.Provider,{value:$c,children:a.jsx(Ent,{open:Ct,initialSelectedId:bne,onClose:an,sidebarWidth:mP,insetTop:gP,insetBottom:xP,personas:Wt,sessions:Fc,activeSessionId:zt?null:ut,awaitingIds:xd,runningIds:Si,unreadIds:bl,ownerPrincipalId:h??void 0,getCreatorDisplayName:R,getSessionDisplayName:T3,onNewPersona:cP,onCreateSession:$=>{an(),Rne($,"")},onOpenPersonaSettings:$=>{an(),HS($)},onDeployPersona:Ene,renderDeployStatus:$=>{var U;return a.jsx(xst,{personaId:$,tool:(U=Wt.find(G=>G.personaId===$))==null?void 0:U.tool})},renderDeployHistory:$=>{var U;return a.jsx(yst,{personaId:$,tool:(U=Wt.find(G=>G.personaId===$))==null?void 0:U.tool,onOpenRelease:G=>Ine($,G)})},renderCloudConnectors:($,U)=>a.jsx(Sst,{personaId:$,render:U}),renderCloudApiKey:$=>a.jsx(mB,{...b,personaId:$}),renderCloudLarkBot:$=>a.jsx(pst,{personaId:$}),favorites:{isFavorite:$=>Pa.isFavorite($),onToggle:$=>Pa.toggleFavorite({personaId:$.personaId}),filter:Pa.filter,onFilterChange:Pa.setFilter,contactFavorites:Fne,onToggleContact:$=>Pa.toggleFavorite({personaId:$.personaId,deviceId:$.deviceId}),onOpenContact:Bne},onDeletePersona:$=>void Tne($),renderSettings:$=>a.jsx(fst,{personaId:$,onOpenMore:()=>{an(),HS($)},onOpenLarkBot:()=>{an(),HS($)}}),onSelectSession:$=>{an(),Sp($)},onEditSession:($,U)=>void D3($,U),onDeleteSession:$=>void SS($)})}),vP=$=>a.jsx(rb.Provider,{value:$c,children:a.jsx(Utt,{channelTree:Kte,expandedTopicIds:hr,onToggleTopic:Zte,onSelectTopic:U=>{_i(!1),an(),kv(U)},onCreateChannel:()=>eo({mode:"create"}),onCreateTopic:U=>void nne(U),onEditChannel:U=>eo({mode:"edit",channelId:U}),onDeleteChannel:U=>void ane(U),onArchiveTopic:rne,onRenameTopic:ine,onDeleteTopic:K3,onPinTopic:one,pinnedTopics:Gte,channelError:tne,topicSessionIds:Ot,floating:$,width:kS,onResizeStart:Vte,projects:qs,onNewInProject:U=>{Pt(U),Pe(!0)},onRefreshProjects:()=>void ye(),onCreateProject:()=>{ap(void 0),lt(!0)},onPatchProject:(U,G)=>{r==null||r.projectPatch({path:U,...G}).then(()=>ye()).catch(ie=>Ae("app","projectPatch failed",{path:U,err:String(ie)}))},onRevealProject:U=>{r==null||r.projectReveal(U).catch(G=>Ae("app","projectReveal failed",{path:U,err:String(G)}))},getPersonaDisplayName:Ea,sessions:Fc,activeId:zt?null:ut??Kn,awaitingIds:xd,runningIds:Si,unreadIds:bl,onSelect:U=>{_i(!1),an(),Sp(U)},onEdit:(U,G)=>{const ie=o.find(at=>at.sessionId===U),He=ie==null?void 0:ie.originOwnerPrincipalId;He?lP(He,U,G):D3(U,G)},onDelete:U=>{const G=o.find(He=>He.sessionId===U),ie=G==null?void 0:G.originOwnerPrincipalId;ie?US(ie,U):SS(U)},onPin:(U,G)=>{const ie=o.find(at=>at.sessionId===U),He=ie==null?void 0:ie.originOwnerPrincipalId;He?Ane(He,U,G):Wte(U,G)},sortMode:RS,onChangeSortMode:gne,quickAction:xne,onChangeQuickAction:vne,bulkArchiveHintCount:Nne,onDismissBulkHint:()=>{BS(null),Cne(!0)},onBulkArchive:U=>void One(U),bulkArchiveAvailable:Dne,onArchive:(U,G)=>{const ie=o.find(at=>at.sessionId===U),He=ie==null?void 0:ie.originOwnerPrincipalId;He?_p(He,U,G):zS(U,G)},onReorderPins:U=>void jne(U),ownerPrincipalId:h??void 0,getContactDisplayName:T,getCreatorDisplayName:R,getSessionDisplayName:T3,onNewPersona:cP,onCollapse:()=>{$3(!0),CS(!1),an()},onOpenHive:rP,onOpenSearch:nP,onFixedEntryClick:Une,activeEntry:Hne,peopleUnreadCount:P3,footer:a.jsx("div",{className:"flex flex-col px-2 py-2",children:Wne})})}),yP=vP(!1),Yne=vP(!0);return a.jsx(Pst,{api:fd,children:a.jsx(rTe,{value:hn,children:a.jsx(Vee.Provider,{value:yne,children:a.jsx(tX.Provider,{value:Yte,children:a.jsxs("div",{className:"h-screen flex flex-col bg-bg-100 text-text-100","data-testid":"app-root",children:[LS&&a.jsx("div",{className:"fixed inset-0 z-50","data-testid":"hive-overlay",children:a.jsx(yot,{sessions:Fc,pool:S,deviceNames:kne,unreadIds:bl,ownerName:m??"me",onExit:()=>Pv(!1),onPick:$=>{Pv(!1),an(),Sp($)}})}),a.jsx(Nrt,{state:i,onRetryNow:Lne}),H,a.jsxs("div",{className:"md:hidden flex items-center gap-2 h-11 px-2 border-b border-border shrink-0",style:{paddingTop:"env(safe-area-inset-top)",minHeight:"calc(2.75rem + env(safe-area-inset-top))"},"data-testid":"app-mobile-topbar",children:[a.jsx("button",{type:"button",onClick:()=>_i(!0),className:"flex items-center justify-center w-9 h-9 rounded-md text-text-300 hover:text-text-100 hover:bg-text-100/5 transition-colors cursor-pointer","aria-label":"Open sessions","data-testid":"app-mobile-nav-trigger",children:a.jsx(Kfe,{className:"w-5 h-5"})}),a.jsx("div",{className:"flex-1 truncate text-sm font-medium text-text-200",children:zne})]}),a.jsxs("div",{className:"relative flex-1 flex min-h-0",children:[!wl&&a.jsx("aside",{className:"hidden md:flex shrink-0 flex-row","data-testid":"app-sidebar",children:yP}),wl&&a.jsxs("div",{className:"hidden md:block",children:[a.jsx(Ont,{hasUnread:P3>0||bl.size>0,onExpand:()=>{$3(!1),CS(!1)},onMouseEnter:F3,onMouseLeave:B3}),qte&&a.jsx("div",{"data-testid":"sidebar-float-layer",className:"absolute z-40 shadow-2xl rounded-xl bg-bg-100",style:{left:nu,top:x2,bottom:nu},onMouseEnter:F3,onMouseLeave:B3,children:Yne})]}),a.jsx(prt,{open:P,onClose:()=>A(!1),connect:X.connect,myDeviceLink:w,onLogin:g.login}),a.jsx(Pit,{open:O,onClose:()=>F(!1),tunnelUrl:L,token:I==null?void 0:I.token,connections:D,onOpenRemoteHosts:void 0}),z&&a.jsx(Ait,{api:r,onClose:()=>W(!1)}),Kne,a.jsx(wit,{open:Qe,submitting:Vt,error:dd,onSubmit:gS,onCancel:()=>lt(!1)}),a.jsx(Ry,{open:fv,onOpenChange:_i,children:a.jsxs(Om,{side:"left",hideBuiltInClose:!0,className:"md:hidden p-0 w-[288px]","data-testid":"app-mobile-nav-drawer","aria-describedby":void 0,children:[a.jsx(Dm,{className:"sr-only",children:"Sessions"}),a.jsx("div",{className:"flex flex-col h-full",children:yP})]})}),a.jsxs(c_,{orientation:"horizontal",className:`flex-1 flex min-w-0${wl?" md:pl-10":""}${pp?" md:[&_.chrome-tab-strip]:pr-20":ES?" md:[&:has(+aside:not(:empty))_[data-cc-chat-root]]:pr-[316px]":wd&&Ra?" md:pr-10":""}`,children:[a.jsx(Jh,{id:"main",children:a.jsx("main",{className:`flex-1 flex min-w-0 flex-col md:flex-row h-full${pp&&!Cv&&Ra?" md:[&_[data-cc-chat-root]]:pr-[316px]":""}`,"data-testid":"app-main",children:a.jsx(LG,{container:mne,workspaceContainer:ES?cne:null,...Ra?{}:{onCollapse:()=>jS(!0)},children:a.jsx(NTe,{value:fe,children:a.jsx(Det,{view:le,sessions:o,topics:fp,contacts:C,visitorContacts:te,remoteSessionsByOwnerId:xe,clientPool:S,client:t,im:ee,api:r,myOwnerPrincipalId:h??"",myOwnerDisplayName:m??"我",cloud:{apiKey:x.apiKey,gatewayUrl:x.gatewayUrl},onFocusTab:$=>{gp(),me(G=>lO(G,$));const U=le.tabs[$];(U==null?void 0:U.kind)==="session"&&ne(U.sid)},onCloseTab:$=>me(U=>am(U,$)),onCloseOtherTabs:$=>me(U=>cve(U,$)),onCloseAllTabs:()=>me(My),onReorderTab:($,U)=>{console.log("[tab-debug] onReorderTab dispatch",{from:$,to:U}),me(G=>uve(G,$,U))},onSelectCwdForNew:zte,onNewSession:Hte,onOpenPrChat:Mne,onFork:Ute,onOpenMobileConfig:()=>yl(!0),onMirrorOrphan:($,U)=>{Ov($),Ae("mirror","orphan auto-cleanup",{sessionId:$,ownerId:U}),me(G=>oo(G,$))},extensionUpdateInfo:Lot(tn,Ne),onApplyExtensionUpdate:St,awaitingIds:xd,runningIds:Si,unreadIds:bl,unreadDmPeerDeviceIds:bS,pendingTabIndex:PS,extensionsListNode:qne,landingNode:a.jsx(Hrt,{firstRun:kt,personas:Wt.filter($=>$.personaId!==Fi).map($=>({personaId:$.personaId,name:$.label,tool:$.tool,...$.cloud?{cloud:!0}:{}})),initialPersonaId:ei,api:r,modelList:d,modes:(u==null?void 0:u.permissionModes)??[],configSchema:(u==null?void 0:u.configSchema)??[],defaultsByPersonaId:Object.fromEntries(Wt.map($=>[$.personaId,{...$.model?{model:$.model}:{},...$.effort?{effort:$.effort}:{}}])),onCreate:$=>void wS($)})})})})})}),wd&&!Ra?a.jsxs(a.Fragment,{children:[a.jsx(xR,{className:"w-1 bg-text-100/10 hover:bg-text-100/25 transition-colors cursor-col-resize"}),a.jsx(Jh,{id:"session-info",defaultSize:`${Y3}px`,minSize:"280px",maxSize:"480px",onResize:$=>pne($.inPixels),children:a.jsx("div",{ref:hne,"data-testid":"session-info-column",className:"hidden md:flex h-full min-w-0 flex-col"})})]}):null]}),ES&&a.jsx("aside",{ref:une,"aria-label":"工作区卡片",className:"absolute right-0 top-10 z-30 hidden max-h-[calc(100%-2.5rem)] w-[316px] overflow-y-auto p-2 md:flex md:flex-col md:gap-3 md:empty:hidden"}),pp&&a.jsxs("div",{className:"absolute right-2 top-2 z-50 hidden items-center gap-1 rounded-md bg-bg-100 md:flex",children:[a.jsx("button",{"aria-label":"显示或隐藏工作区卡片",title:"工作区卡片","aria-pressed":!Cv,onClick:()=>lne(!Cv),className:"rounded-md p-1.5 text-text-300 hover:bg-text-100/10",children:a.jsx(Afe,{className:"h-4 w-4"})}),a.jsx("button",{"aria-label":"切换会话侧栏",title:"会话侧栏","aria-pressed":!Ra,onClick:()=>{jS(!Ra),Nv(!1)},className:"rounded-md p-1.5 text-text-300 hover:bg-text-100/10",children:a.jsx(Kb,{className:"h-4 w-4"})})]}),wd&&Ra&&!pp&&a.jsxs("div",{className:"hidden md:block",children:[a.jsx(Dnt,{onExpand:()=>{jS(!1),Nv(!1)},onMouseEnter:Ev,onMouseLeave:Iv}),G3&&a.jsx("div",{"data-testid":"session-info-float",className:"absolute z-40 shadow-2xl rounded-xl overflow-hidden",style:{right:nu,top:x2,bottom:nu,width:Y3},ref:fne})]}),Vne,Gne,xp&&a.jsx(wot,{query:Ma,onQueryChange:AS,sessionsLoading:DS,sessions:vp,personas:yp,contacts:bp,groups:$S,focus:kd,onFocusChange:Sl,onMoveRow:$=>Sl(U=>Wd(U,{kind:"move-row",delta:$,rowCount:Sne})),onMoveGroup:$=>Sl(U=>Wd(U,{kind:"move-group",delta:$,groups:wp})),onOpenFocused:()=>fP(kd.row),onSelectSession:uP,onSelectPersona:$=>dP($.personaId),onSelectContact:$=>hP($.deviceId),onClose:Dv}),fd,a.jsx(Lst,{open:TS}),Av?a.jsx(Mot,{sessionLabel:(()=>{const $=o.find(U=>U.sessionId===Av);return($==null?void 0:$.label)||($==null?void 0:$.aiLabel)||($==null?void 0:$.larkChatName)||($==null?void 0:$.larkChatId)||($==null?void 0:$.cwd)||Av.slice(0,8)})(),onConfirm:()=>{const $=Av;FS(null);const U=o.find(G=>G.sessionId===$);U&&(U.originOwnerPrincipalId?_p(U.originOwnerPrincipalId,$,!0):zS($,!0))},onCancel:()=>FS(null)}):null,a.jsx(rit,{toast:vv,onOpenArchived:()=>{so(null),md("archived")},onClose:()=>so(null)}),pd&&a.jsx(Wst,{initialNav:pd,onBack:()=>md(null),api:fd,ownerPrincipalId:h,daemonScanApi:pv,daemonVersion:i.kind==="connected"?i.daemonVersion:null,daemonSource:i.kind==="connected"?i.daemonSource:null,globalCliVersion:i.kind==="connected"?i.globalCliVersion:null,ccMode:gv,effectiveCcMode:xv,onChangeCcMode:void 0,onAddMobile:V?()=>F(!0):void 0,onImportExternalSessions:i.kind==="connected"&&i.mode!=="remote"?()=>W(!0):void 0,feishuSlot:a.jsx(gB,{variant:"settings",...v}),cloudApiKeySlot:a.jsx(mB,{...b}),githubSlot:a.jsx(xI,{}),channelsSlot:a.jsx(nit,{}),engineSlot:a.jsx(Jst,{}),dashboardSlot:a.jsx(zet,{tunnelReady:!!L,onOpen:$=>y_e(async()=>(await r.dashboardOpenUrl($)).url)}),archivedTopicsSlot:a.jsx(uit,{groups:Xte,onUnarchive:sne,onDelete:K3}),archivedSlot:a.jsx(lit,{sessions:Dte,childrenByRoot:$te,personaLabelOf:$=>{var U;return(U=Wt.find(G=>G.personaId===$))==null?void 0:U.label},contactNameOf:$=>T($),onUnarchive:$=>{const U=o.find(ie=>ie.sessionId===$),G=U==null?void 0:U.originOwnerPrincipalId;G?_p(G,$,!1):zS($,!1)},onDelete:$=>{const U=o.find(ie=>ie.sessionId===$),G=U==null?void 0:U.originOwnerPrincipalId;G?US(G,$):SS($)}})},pd),Qn?a.jsx(Ry,{open:dv,onOpenChange:yl,children:a.jsxs(Om,{side:"right",className:"md:hidden p-0 w-[320px] max-w-[85vw]","data-testid":"app-mobile-config-drawer","aria-describedby":void 0,children:[a.jsx(Dm,{className:"sr-only",children:"Session Info"}),a.jsx(Rst,{open:dv,onOpenChange:yl,session:Qn,embedded:!0})]})}):null,(zt==null?void 0:zt.kind)==="config"&&a.jsx(Ry,{open:!0,onOpenChange:$=>{$||lp&&!window.confirm("修改未保存,确定关闭?")||(sn(null),hd(!1))},children:a.jsxs(Om,{side:"right",className:"p-0 w-[420px] max-w-[90vw]","data-testid":"app-persona-config-drawer","aria-describedby":void 0,hideBuiltInClose:!0,children:[a.jsx(Dm,{className:"sr-only",children:"Persona 设置"}),a.jsx(eX,{personaId:zt.personaId,open:!0,onClose:()=>{lp&&!window.confirm("修改未保存,确定关闭?")||(sn(null),hd(!1))},api:r,embedded:!0,onDirtyChange:hd},zt.personaId)]})})]}),a.jsx(Drt,{open:Se,onOpenChange:$=>{Pe($),$||Pt(null),!$&&ut&&ne(ut)},onCreate:Bc,api:r,projects:qs,presetProject:dt,onProjectsChanged:()=>void ye()}),a.jsx(lst,{open:$n,onOpenChange:$=>{Lt($),$||yn(null)},onCreate:$ne,loadRepos:($,U)=>r.githubRepos({page:$,search:U}),githubLink:$=>a.jsx(xI,{compact:!0,onAuthorized:$}),submitting:ja,submitError:xn},Sn)]})})})})})}const Mte="(prefers-color-scheme: dark)",zot=["light","dark","system"],Pte="clawd-standalone:theme-source",Hot="light",Uot={colorPrimary:"#1677ff",colorBgContainer:"#fff",colorText:"#000",colorBorder:"#d9d9d9"};function Wot(){try{const e=localStorage.getItem(Pte);if(e!==null&&zot.includes(e))return e}catch{}return Hot}function Vot(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Mte).matches}function JB(e){return{mode:e==="dark"||e==="system"&&Vot()?"dark":"light",...Uot}}function qot(e){let t=Wot();const n=new Set,r=()=>{const i=JB(t);for(const o of n)o(i)};typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Mte).addEventListener("change",()=>{t==="system"&&r()});const s={gateway:{call:()=>Promise.reject(new Error("standalone-host: gateway.call not supported"))},self:{call:()=>Promise.reject(new Error("standalone-host: self.call removed; use useDaemonClient()"))},kv:{get:async i=>{const o=localStorage.getItem(`clawd-standalone:kv:${i}`);if(o==null)return null;try{return JSON.parse(o)}catch{return null}},set:async(i,o)=>{localStorage.setItem(`clawd-standalone:kv:${i}`,JSON.stringify(o))}},logger:{info:(i,o)=>{var l;console.info("[ext]",i,o??""),(l=e.logClient)==null||l.push({level:"info",msg:String(i),meta:o})},warn:(i,o)=>{var l;console.warn("[ext]",i,o??""),(l=e.logClient)==null||l.push({level:"warn",msg:String(i),meta:o})},error:(i,o)=>{var l;console.error("[ext]",i,o??""),(l=e.logClient)==null||l.push({level:"error",msg:String(i),meta:o})}},get theme(){return JB(t)},on(){return()=>{}},onThemeChange(i){return n.add(i),()=>{n.delete(i)}}};return s.getThemeSource=()=>t,s.setThemeSource=i=>{t=i;try{localStorage.setItem(Pte,i)}catch{}r()},e.notifier&&(s.notifier=e.notifier),s}var Kot={maxRecords:100,maxBytes:512*1024,maxWaitMs:5e3},Got=5e3,Ate={debug:0,info:1,warn:1,error:1},ez=1024,tz=2048,Yot=/token|secret|password|auth(?!or)|apikey|signsecret/i,Xot="[REDACTED]",Ote="…[truncated]";function Zot(e,t){const n=EI(e,t,0),r=Qot(n);return r.length<=tz?n:{__truncated__:r.slice(0,tz)+Ote}}function EI(e,t,n){if(n>10)return"[depth-limit]";if(e==null)return e;if(typeof e=="string")return t?e.split(t).join("~"):e;if(typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>EI(s,t,n+1));const r={};for(const[s,i]of Object.entries(e))Yot.test(s)?r[s]=Xot:r[s]=EI(i,t,n+1);return r}function Qot(e){try{return JSON.stringify(e)??""}catch{return'"[serialize-failed]"'}}function Jot(e){return e.length<=ez?e:e.slice(0,ez)+Ote}function eat(e,t,n){const r=t[e]??Ate[e];return r<=0?!1:r>=1?!0:n()<r}var tat=class{constructor(e){Gs(this,"deps");Gs(this,"queue",[]);Gs(this,"bytes",0);Gs(this,"droppedSinceFlush",0);Gs(this,"identityReady",!1);Gs(this,"timer",null);Gs(this,"disposed",!1);Gs(this,"pendingSends",[]);this.deps=e}enqueue(e){if(this.disposed)return;const t=nat(e);for(;this.queue.length>=this.deps.bufferCap;)this.queue.shift(),this.droppedSinceFlush++;this.queue.push(e),this.bytes+=t,this.identityReady&&this.maybeTrigger()}setIdentityReady(e){this.identityReady=e,e&&this.queue.length>0&&this.maybeTrigger()}async flush(){this.queue.length>0&&this.fire("flush"),await Promise.allSettled(this.pendingSends)}stats(){return{queued:this.queue.length,dropped:this.droppedSinceFlush}}async dispose(){this.disposed||(this.disposed=!0,this.timer&&(clearTimeout(this.timer),this.timer=null),await this.flush())}maybeTrigger(){const{maxRecords:e,maxBytes:t,maxWaitMs:n}=this.deps.batch;if(this.queue.length>=e){this.fire("records");return}if(this.bytes>=t){this.fire("bytes");return}this.timer==null&&(this.timer=setTimeout(()=>{this.timer=null,this.queue.length>0&&this.identityReady&&this.fire("time")},n))}fire(e){this.timer&&(clearTimeout(this.timer),this.timer=null);const t=this.queue,n=this.droppedSinceFlush;this.queue=[],this.bytes=0,this.droppedSinceFlush=0;const r=this.deps.onBatch({reason:e,records:t,droppedCarryover:n}).catch(()=>{});this.pendingSends.push(r),r.finally(()=>{this.pendingSends=this.pendingSends.filter(s=>s!==r)})}};function nat(e){var t,n;return(((t=e.msg)==null?void 0:t.length)??0)+(((n=e.meta_json)==null?void 0:n.length)??0)+200}var nz=[1e3,2e3,4e3];async function rat(e,t){const n=t.records.map(sat),r=JSON.stringify({__topic__:"clawd",__source__:e.source,__logs__:n,...t.droppedCarryover>0?{__tags__:{dropped:String(t.droppedCarryover)}}:{}});for(let s=0;s<nz.length;s++){s>0&&await iat(nz[s-1]);try{const i=await e.fetchImpl(e.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:r});if(i.status>=200&&i.status<300)return{sent:t.records.length,failed:0};if(i.status>=400&&i.status<500)return{sent:0,failed:t.records.length}}catch{}}return{sent:0,failed:t.records.length}}function sat(e){const t={};for(const[n,r]of Object.entries(e))r!=null&&(t[n]=typeof r=="string"?r:String(r));return t}function iat(e){return new Promise(t=>setTimeout(t,e))}function oat(e){const t={sent:0,dropped:0,queued:0,failed:0},n=e.fetchImpl??globalThis.fetch.bind(globalThis),r=e.now??Date.now,s={...Ate,...e.sampling??{}},i=e.homeDir===void 0?null:e.homeDir,o={...Kot,...e.batch??{}},l=e.bufferCap??Got;let c=e.identity,u=!1;if(e.endpoint==null)return{push:()=>{u||t.dropped++},flush:async()=>{},setIdentity:f=>{c=f},stats:()=>({...t}),dispose:async()=>{u=!0}};const d=e.endpoint,h=new tat({batch:o,bufferCap:l,now:r,onBatch:async f=>{const m=await rat({endpoint:d,source:e.source,fetchImpl:n},f);t.sent+=m.sent,t.failed+=m.failed}});return h.setIdentityReady(c!=null),{push(f){if(!u)try{if(!eat(f.level,s,Math.random)){t.dropped++;return}const m=aat(f,c,e.source,i,r);h.enqueue(m)}catch{}},async flush(){try{await h.flush()}catch{}},setIdentity(f){c=f,h.setIdentityReady(f!=null)},stats(){const f=h.stats();return{...t,queued:f.queued,dropped:t.dropped+f.dropped}},async dispose(){u=!0;try{await h.dispose()}catch{}}}}function aat(e,t,n,r,s){const i=e.meta?Zot(e.meta,r):void 0,o=i?JSON.stringify(i):void 0;return{ts:e.ts??s(),source:n,level:e.level,msg:Jot(e.msg),ownerPrincipalId:(t==null?void 0:t.ownerPrincipalId)??"__pending__",deviceId:(t==null?void 0:t.deviceId)??"__pending__",appVersion:(t==null?void 0:t.appVersion)??"__pending__",daemonVersion:t==null?void 0:t.daemonVersion,os:(t==null?void 0:t.os)??"unknown",meta_json:o,sessionId:e.sessionId}}function lat(e){const t=n=>{document.documentElement.classList.toggle("dark",n==="dark")};return t(e.theme.mode),e.onThemeChange(n=>t(n.mode))}function cat({filePath:e,oldString:t,newString:n,content:r}){const s=p.useMemo(()=>r!=null?r.split(/\r?\n/).map(i=>({type:"add",text:i})):uat(t??"",n??""),[t,n,r]);return a.jsxs("div",{"data-testid":"inline-diff",className:"min-w-0 max-w-full rounded-lg border border-bg-300/60 bg-bg-50 overflow-hidden text-[12px] font-mono",children:[a.jsx("div",{className:"flex min-w-0 items-center gap-2 px-3 py-1.5 border-b border-bg-300/40 bg-bg-100/30",children:a.jsx("span",{className:"min-w-0 text-text-400 truncate",title:e,children:e})}),a.jsx("div",{className:"max-h-[320px] max-w-full overflow-auto",children:s.map((i,o)=>a.jsxs("div",{"data-testid":`diff-line-${i.type}`,className:J("flex min-w-max gap-2 px-3 py-0.5 whitespace-pre",i.type==="add"?"bg-success/10 text-success":i.type==="remove"?"bg-error/10 text-error":"text-text-300"),children:[a.jsx("span",{className:"w-3 shrink-0 select-none opacity-60",children:i.type==="add"?"+":i.type==="remove"?"-":" "}),a.jsx("span",{className:"flex-1",children:i.text||" "})]},o))})]})}function uat(e,t){const n=e.split(/\r?\n/),r=t.split(/\r?\n/),s=n.length,i=r.length,o=Array.from({length:s+1},()=>new Array(i+1).fill(0));for(let d=s-1;d>=0;d--)for(let h=i-1;h>=0;h--)o[d][h]=n[d]===r[h]?o[d+1][h+1]+1:Math.max(o[d+1][h],o[d][h+1]);const l=[];let c=0,u=0;for(;c<s&&u<i;)n[c]===r[u]?(l.push({type:"equal",text:n[c]}),c++,u++):o[c+1][u]>=o[c][u+1]?(l.push({type:"remove",text:n[c]}),c++):(l.push({type:"add",text:r[u]}),u++);for(;c<s;)l.push({type:"remove",text:n[c++]});for(;u<i;)l.push({type:"add",text:r[u++]});return l}function dat({items:e}){return e.length===0?null:a.jsxs("div",{"data-testid":"todo-checklist",className:"rounded-lg border border-bg-300/60 bg-bg-50 px-3 py-2 text-[13px]",children:[a.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-text-400/70 mb-1.5",children:"Todos"}),a.jsx("ul",{className:"flex flex-col gap-1",children:e.map((t,n)=>{const r=t.status==="in_progress"&&t.activeForm||t.content;return a.jsxs("li",{"data-testid":`todo-item-${t.status}`,className:"flex items-start gap-2",children:[a.jsx(hat,{status:t.status}),a.jsx("span",{className:J("flex-1 leading-snug",t.status==="completed"?"text-text-400 line-through":t.status==="in_progress"?"text-text-100 font-medium":"text-text-200"),children:r})]},n)})})]})}function hat({status:e}){return e==="completed"?a.jsx(ui,{className:"w-3.5 h-3.5 text-success mt-0.5 shrink-0"}):e==="in_progress"?a.jsx(st,{className:"w-3.5 h-3.5 text-warning mt-0.5 shrink-0 animate-spin"}):a.jsx(OH,{className:"w-3.5 h-3.5 text-text-400 mt-0.5 shrink-0"})}function fat(e){const t=e??{};return Array.isArray(t.todos)?t.todos.map(n=>{if(!n||typeof n!="object")return null;const r=n,s=typeof r.content=="string"?r.content:"",i=r.status==="pending"||r.status==="in_progress"||r.status==="completed"?r.status:"pending",o=typeof r.activeForm=="string"?r.activeForm:void 0;return{content:s,status:i,activeForm:o}}).filter(n=>n!==null):[]}function pat({description:e,prompt:t,subagentType:n}){return a.jsxs("div",{"data-testid":"task-checklist",className:"rounded-lg border border-bg-300/60 bg-bg-50 px-3 py-2 text-[13px]",children:[a.jsxs("div",{className:"flex items-center gap-2 text-text-200 font-medium",children:[a.jsx(oa,{className:"w-3.5 h-3.5 text-accent shrink-0"}),a.jsx("span",{className:"truncate",children:e||"subagent task"}),n?a.jsx("span",{className:"shrink-0 px-1.5 py-0.5 rounded-md text-[10px] font-mono bg-accent/10 text-accent",children:n}):null]}),t?a.jsx("div",{className:"mt-1 text-[12px] text-text-400 leading-snug line-clamp-3",children:t}):null]})}function mat(e){const t=e??{};return{description:typeof t.description=="string"?t.description:"",prompt:typeof t.prompt=="string"?t.prompt:void 0,subagentType:typeof t.subagent_type=="string"?t.subagent_type:void 0}}const gat={render:({input:e})=>q.createElement(dat,{items:fat(e)})},xat={render:({input:e})=>{const{description:t,prompt:n,subagentType:r}=mat(e);return q.createElement(pat,{description:t,prompt:n,subagentType:r})}},rz={render:({input:e,output:t,error:n,pending:r,fileScope:s,onShareFile:i,onOpenInTab:o,onPreviewMarkdown:l})=>{const c=yat(e),u=c?q.createElement(cat,{filePath:c.filePath,oldString:c.oldString,newString:c.newString,content:c.content}):void 0;return q.createElement(gG,{tool:vat(e),input:e,output:t,error:n,pending:r,expandedBody:u,...s?{fileScope:s}:{},...i?{onShareFile:i}:{},...o?{onOpenInTab:o}:{},...l?{onPreviewMarkdown:l}:{}})}};function vat(e){const t=e??{};return"content"in t&&t.content!==void 0?"Write":("old_string"in t&&t.old_string!==void 0,"Edit")}function yat(e){const t=e??{},n=typeof t.file_path=="string"?t.file_path:null;if(!n)return null;const r=typeof t.old_string=="string"?t.old_string:void 0,s=typeof t.new_string=="string"?t.new_string:void 0,i=typeof t.content=="string"?t.content:void 0;return r==null&&s==null&&i==null?null:{filePath:n,oldString:r,newString:s,content:i}}for(const e of["claude",Ace])uh.register(e,"TodoWrite",gat),uh.register(e,"Task",xat),uh.register(e,"Edit",rz),uh.register(e,"Write",rz);const N2={};function bat({urlSource:e,hostOverride:t,notifier:n,credentialSource:r}){const[s]=p.useState(()=>{if(t)return null;const d=N2==null?void 0:N2.VITE_CLAWD_LOG_ENDPOINT;return oat({endpoint:d==="off"?null:d??"https://clawd-prod.cn-hangzhou.log.aliyuncs.com/logstores/app-logs/track",identity:null,source:"renderer",homeDir:null})}),[i]=p.useState(()=>t??qot({notifier:n,...s?{logClient:s}:{}})),[o,l]=p.useState(null),[c,u]=p.useState(null);return p.useEffect(()=>{let d=!1;return Promise.resolve(e.getUrl(i)).then(h=>{d||l(h)}).catch(h=>{d||u(h instanceof Error?h.message:String(h))}),()=>{d=!0}},[e,i]),p.useEffect(()=>lat(i),[i]),c?a.jsxs("div",{className:"p-8 max-w-xl font-sans text-text-100","data-testid":"standalone-error",children:[a.jsx("h2",{className:"text-lg font-semibold mb-2",children:"无法发现 daemon"}),a.jsx("p",{className:"text-destructive mb-3",children:c}),a.jsxs("p",{className:"text-text-400 mb-3",children:["请确认 ",a.jsx("code",{className:"font-mono",children:"clawd"})," 已启动 (",a.jsx("code",{className:"font-mono",children:"cd clawd && pnpm dev"}),"),它会写入"," ",a.jsx("code",{className:"font-mono",children:"~/.clawd/state.json"}),"。"]}),a.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-1.5 text-sm rounded-md border border-border bg-elevated hover:bg-bg-100",children:"重试"})]}):o?a.jsx("div",{"data-testid":"standalone-root","data-mode":"url"in o?"has-url":"needs-setup",children:a.jsx(q.StrictMode,{children:a.jsx(VU.Provider,{value:r??null,children:a.jsx(awe,{client:s,children:a.jsx(Nie,{host:i,children:a.jsx(Tle,{children:a.jsx($ot,{})})})})})})}):a.jsx("div",{className:"p-8 font-sans text-text-400","data-testid":"standalone-resolving",children:"正在发现 daemon…"})}function wat(e,t){const r=`${e.protocol==="https:"?"wss:":"ws:"}//${e.host}`;return t!=null&&t.devPath?`${r}${t.devPath}`:r}const E3="clawd-owner-web:session",sz="owner-web",_at="/app/session",Sat="ticket";class II extends Error{constructor(t){super(t),this.reason=t,this.name="OwnerSessionError"}}function kat(e){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(Sat);return n&&n.length>0?n:null}function iz(e){try{const t=JSON.parse(e.storage.getItem(E3)??"null");if(t&&typeof t.token=="string"&&typeof t.expiresAt=="number"&&t.expiresAt>e.now())return{token:t.token,expiresAt:t.expiresAt}}catch{}return null}async function Cat(e,t){try{const n=await e.fetch(_at,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:t}),cache:"no-store",credentials:"omit"});if(!n.ok)return null;const r=await n.json();if(typeof r.token=="string"&&typeof r.expiresAt=="number")return{token:r.token,expiresAt:r.expiresAt}}catch{}return null}async function Nat(e){const t=kat(e.location.hash);if(t){e.history.replaceState(null,"",`${e.location.pathname}${e.location.search}`);const r=await Cat(e,t);if(r)return e.storage.setItem(E3,JSON.stringify(r)),r;const s=iz(e);if(s)return s;throw new II("ticket-invalid")}const n=iz(e);if(n)return n;throw new II("no-session")}function jat(e){let t,n=null;const r=()=>(n??(n=Nat(e).then(s=>(t=s.token,s))),n);return{session:r,credentials:{profileId:sz,getToken:()=>t,invalidate:()=>{t=void 0;try{e.storage.removeItem(E3)}catch{}}},urlSource:{async getUrl(s){await r();const i=wat(e.location);return await GU(s).upsert({id:sz,name:"本机",mode:"localhost",url:i}),{url:i}}}}}function Eat({web:e}){const[t,n]=p.useState({kind:"connecting"});return p.useEffect(()=>{let r=!1;return e.session().then(()=>!r&&n("ready")).catch(s=>{r||n({kind:"reopen",reason:s instanceof II?s.reason:"no-session"})}),()=>{r=!0}},[e]),t!=="ready"?a.jsx(KU,{view:t}):a.jsx(bat,{urlSource:e.urlSource,credentialSource:e.credentials})}const oz=document.getElementById("root");if(oz){Xxe({name:"clawd-web",version:"unknown"});const e=jat({storage:window.sessionStorage,location:window.location,history:window.history,fetch:window.fetch.bind(window),now:()=>Date.now()});j2.createRoot(oz).render(a.jsx(q.StrictMode,{children:a.jsx(Eat,{web:e})}))}
|
|
955
|
+
focused:`,le.focused),Zr.current=$},[le]);const Lc=p.useRef(new Set);p.useEffect(()=>{if(!qe.current)return;const $=U=>{Lc.current.has(U)||C.some(G=>G.deviceId===U)&&(Lc.current.add(U),ze(U))};for(const U of le.tabs)if(U.kind==="dm")$(U.peerDeviceId);else if(U.kind==="session"){const G=o.find(ie=>ie.sessionId===U.sid);G!=null&&G.originOwnerPrincipalId&&$(G.originOwnerPrincipalId)}},[le,C,o,ze]),p.useEffect(()=>{if(!qe.current||o.length===0)return;const $=new Set(o.map(G=>G.sessionId));for(const G of $)Zt.current.add(G);const U=Zt.current;me(G=>{const ie=G.tabs.filter(at=>at.kind!=="session"?!0:!U.has(at.sid)||$.has(at.sid));if(ie.length===G.tabs.length)return G;if(ie.length===0)return My;const He=Math.min(G.focused,ie.length-1);return{tabs:ie,focused:Math.max(0,He)}})},[o]);const{prune:_v}=$c;p.useEffect(()=>{l&&_v(new Set(o.map($=>$.sessionId)))},[l,o,_v]);const Qn=ut?o.find($=>$.sessionId===ut)??null:null,{visible:Fc,archivedRoots:Dte,archivedChildrenByRoot:$te}=p.useMemo(()=>Qm(o.filter(yB)),[o]),I3=p.useMemo(()=>new Map(Fc.map($=>[$.sessionId,lv($)])),[Fc]),T3=p.useCallback($=>I3.get($),[I3]),vS=p.useMemo(()=>Qm(o.filter(_3)).visible,[o]),yS=p.useMemo(()=>vS.filter($=>cS($,h??void 0)).map($=>({sid:$.sessionId,originOwnerPrincipalId:$.originOwnerPrincipalId??null})),[vS,h]),R3=$ee(yS,S),oo=p.useCallback(($,U)=>{const G=$.tabs.findIndex(ie=>ie.kind==="session"&&ie.sid===U);return G>=0?am($,G):$},[]),Lte=p.useSyncExternalStore(p.useCallback($=>S.onOwnersChanged($),[S]),()=>S.listRemoteDeviceIds().sort().join("|"),()=>""),M3=!k.loading;p.useEffect(()=>{if(!M3)return;const $=[];for(const U of le.tabs){if(U.kind!=="session")continue;const G=o.find(ln=>ln.sessionId===U.sid);if(!(G!=null&&G.originOwnerPrincipalId))continue;const ie=G.originOwnerPrincipalId,He=S.getRemoteForDevice(ie)!==null,at=C.some(ln=>ln.deviceId===ie);!He&&!at&&$.push(U.sid)}$.length!==0&&me(U=>{let G=U;for(const ie of $)G=oo(G,ie);return G})},[M3,le,o,C,S,Lte,oo]);const bl=Jet({entries:yS,sessions:vS,activeId:ut??Kn,pool:S}),xd=Lee(yS,S),Si=p.useMemo(()=>{const $=new Set;for(const[U,G]of R3)G==="turn-running"&&$.add(U);return $},[R3]),P3=p.useMemo(()=>{let $=0;for(const U of ee.unreadByPeer.values())$+=U;return $},[ee.unreadByPeer]),bS=p.useMemo(()=>{const $=new Set;for(const[U,G]of ee.unreadByPeer)G>0&&$.add(U);return $},[ee.unreadByPeer]),A3=i.kind==="disconnected"||i.kind==="auth-failed"||i.kind==="version-mismatch"||i.kind==="reconnecting",Fte=i.kind==="connecting"||i.kind==="idle",dp=qU(),vd=dp?$xe(i):null,O3=(vd==null?void 0:vd.kind)==="reopen"&&vd.reason==="expired";p.useEffect(()=>{O3&&(dp==null||dp.invalidate())},[O3,dp]);const Ta=p.useCallback($=>{_i(!1);const U=o.find(ie=>ie.sessionId===$);U!=null&&U.originOwnerPrincipalId&&ze(U.originOwnerPrincipalId);const G=U==null?void 0:U.cwd;G&&!(U!=null&&U.originOwnerPrincipalId)?Promise.all([r.getGitRoot(G),r.getGitBranch(G)]).then(([ie,He])=>{Ae("app","selectSession",{sessionId:$,cwd:G,gitRoot:ie.gitRoot,branch:He.branch})}).catch(ie=>{Ae("app","selectSession git probe failed",{sessionId:$,err:ie})}):Ae("app","selectSession",{sessionId:$,cwd:null}),me(ie=>Es(ie,{kind:"session",sid:$})),Oe.current||ne($)},[o,r,ze,ne]),Bc=p.useCallback(async $=>{const U=await r.sessionCreate(oD($));return await c(),Ta(U.sessionId),{sessionId:U.sessionId}},[r,c,Ta]),wS=p.useCallback(async({personaId:$,text:U,config:G})=>{const ie=zq(U)??"新建 session",{sessionId:He}=await Bc({ownerPersonaId:$,aiLabel:ie,...G.model?{model:G.model}:{},...G.effort?{effort:G.effort}:{}});await r.sessionSubscribe(He),await r.sessionSend(He,U),At(!1),me(at=>{const ln=at.tabs.findIndex(Bo=>Bo.kind==="landing");return ln>=0?am(at,ln):at})},[r,Bc]),Bte=p.useCallback(()=>{r.onboardingComplete().catch(()=>{}),nt(!0),At(!0),me($=>Es($,{kind:"landing"}))},[r]),zte=p.useCallback(async $=>{await Bc({cwd:$})},[Bc]),Hte=p.useCallback(async $=>{const U=await r.sessionCreate(oD({cwd:$}));await c(),me(G=>Es(G,{kind:"session",sid:U.sessionId}))},[r,c]),_S=p.useRef(!1),Ute=p.useCallback(async($,U)=>{const G=mu($.tool);if(G){if(_S.current)return;_S.current=!0,Fo({kind:"progress",text:"正在分叉云会话…"})}try{const ie=await Hq(r,$,U);if(G&&so(null),!ie)return;await c(),me(He=>Es(He,{kind:"session",sid:ie.sessionId}))}catch(ie){if(!G)throw ie;Fo({kind:"error",text:ie instanceof Error?ie.message:String(ie)})}finally{G&&(_S.current=!1)}},[r,c,Fo]),SS=p.useCallback(async $=>{const U=ny(o,$);for(const ie of U)await r.sessionDelete(ie);await r.sessionDelete($);const G=new Set([$,...U]);me(ie=>aO(ie,He=>He.kind==="session"&&G.has(He.sid))),await c()},[r,o,c]),D3=p.useCallback(async($,U)=>{U.label&&(await r.sessionUpdate($,{label:U.label}),await c())},[r,c]),Wte=p.useCallback(async($,U)=>{await r.pinSession($,U),await c()},[r,c]),{width:kS,onDragStart:Vte}=krt(),[wl,$3]=bm(Pnt,!1),[qte,CS]=p.useState(!1),hp=p.useRef(null),yd=p.useCallback(($,U)=>{hp.current&&clearTimeout(hp.current),hp.current=setTimeout(()=>CS($),U)},[]);p.useEffect(()=>()=>{hp.current&&clearTimeout(hp.current)},[]);const L3=Ct||_e,F3=p.useCallback(()=>yd(!0,MB),[yd]),B3=p.useCallback(()=>{L3||yd(!1,g2)},[yd,L3]),an=p.useCallback(()=>{Ut(!1),vt(!1),wl&&yd(!1,g2)},[wl,yd]),Kte=p.useMemo(()=>nve({channels:io,topicsByChannel:Ks,linesByTopic:re,sessions:o,runningSessionIds:Si}),[io,Ks,re,o,Si]),Gte=p.useMemo(()=>rve({channels:io,topicsByChannel:Ks,linesByTopic:re,sessions:o,runningSessionIds:Si}),[io,Ks,re,o,Si]),z3=p.useMemo(()=>ive({linesByTopic:re,sessions:o}),[re,o]),Sv=ut??Kn,NS=p.useMemo(()=>Sv?o.find($=>$.sessionId===Sv)??null:null,[Sv,o]),H3=knt(r,Sv,NS==null?void 0:NS.updatedAt),Yte=p.useMemo(()=>({resolve:Snt({records:H3,selfDeviceId:h??void 0,lineIndex:z3,sessions:o,personas:Wt,contacts:C}),onOpenSession:Ta,...r?{onAnswer:async($,U)=>{await r.a2aAnswer({taskId:$,text:U})}}:{}}),[H3,z3,o,Wt,C,Ta,r]),Xte=p.useMemo(()=>sve({channels:io,topicsByChannel:Ks,linesByTopic:re,sessions:o,runningSessionIds:Si}),[io,Ks,re,o,Si]),fp=p.useMemo(()=>Object.values(Ks).flat(),[Ks]),Zte=p.useCallback($=>{rr(U=>{const G=new Set(U);return G.has($)?G.delete($):G.add($),G})},[]),kv=p.useCallback($=>{me(U=>Es(U,{kind:"topic",topicId:$}))},[]),[Qte,U3]=p.useState(null),[Jte,W3]=p.useState(null),[ene,V3]=p.useState(null),tne=Qte??ene??(fr===null?Jte:null),nne=p.useCallback(async $=>{if(r){U3(null);try{const{topicId:U}=await r.topicCreate({channelId:$});ht(),kv(U)}catch(U){Ae("app","topicCreate failed",{channelId:$,err:String(U)}),U3({channelId:$,message:U instanceof Error?U.message:String(U)})}}},[r,kv,ht]),bd=p.useCallback($=>fp.find(U=>U.id===$)??null,[fp]),q3=p.useCallback($=>{var U;return((U=bd($))==null?void 0:U.channelId)??null},[bd]),_l=p.useCallback(async($,U,G)=>{V3(null);try{await G(),ht()}catch(ie){Ae("app",`${U} failed`,{topicId:$,err:String(ie)});const He=q3($);He&&V3({channelId:He,message:ie instanceof Error?ie.message:String(ie)})}},[q3,ht]),rne=p.useCallback($=>{var G;const U=(G=bd($))==null?void 0:G.masterSessionId;U&&_l($,"topicArchive",()=>r.archiveSession(U,!0))},[r,bd,_l]),sne=p.useCallback($=>{r.archiveSession($,!1).then(()=>c())},[r,c]),ine=p.useCallback(($,U)=>void _l($,"topicRename",()=>r.topicRename({topicId:$,title:U})),[r,_l]),K3=p.useCallback($=>void _l($,"topicDelete",async()=>{const U=await r.topicDelete({topicId:$}),G=new Set([...U.removedMasterSessionId?[U.removedMasterSessionId]:[],...U.removedWorkerSessionIds]);me(ie=>aO(ie,He=>He.kind==="topic"&&He.topicId===$||He.kind==="session"&&G.has(He.sid)))}),[r,_l]),one=p.useCallback(($,U)=>{var ie;const G=(ie=bd($))==null?void 0:ie.masterSessionId;G&&_l($,"topicPin",()=>r.pinSession(G,U))},[r,bd,_l]),ane=p.useCallback(async $=>{W3(null);try{await cp($)}catch(U){W3({channelId:$,message:U instanceof Error?U.message:String(U)})}},[cp]),[Ra,jS]=bm(Oot,!0),[Cv,lne]=bm("clawd:workspace-cards-collapsed",!1),[cne,une]=p.useState(null),pp=!!(Qn&&mu(Qn.tool)&&!Qn.larkChatId),ES=!!(Qn&&!Qn.larkChatId&&(pp?!Cv:Ra)),[dne,hne]=p.useState(null),[IS,fne]=p.useState(null),[G3,Nv]=p.useState(!1),mp=p.useRef(null),{initialSize:Y3,setSize:pne}=Uq("clawd:panel:session-info-px",320),jv=p.useCallback(($,U)=>{mp.current&&clearTimeout(mp.current),mp.current=setTimeout(()=>Nv($),U)},[]),Ev=p.useCallback(()=>jv(!0,MB),[jv]),Iv=p.useCallback(()=>jv(!1,g2),[jv]);p.useEffect(()=>()=>{mp.current&&clearTimeout(mp.current)},[]);const wd=["session","topic"].includes(((bP=le.tabs[le.focused])==null?void 0:bP.kind)??""),mne=wd?Ra?G3?IS:null:dne:null;p.useEffect(()=>{wd||Nv(!1)},[wd]),p.useEffect(()=>{const $=IS;if($)return $.addEventListener("mouseenter",Ev),$.addEventListener("mouseleave",Iv),()=>{$.removeEventListener("mouseenter",Ev),$.removeEventListener("mouseleave",Iv)}},[IS,Ev,Iv]);const TS=Rot(),[RS,gne]=wf(Ltt,"priority"),[xne,vne]=wf(Btt,"archive"),MS=p.useMemo(()=>_it(Fc,{ownerPrincipalId:h??void 0,sortMode:RS,attention:{awaitingIds:xd,runningIds:Si,unreadIds:bl},projectPaths:Lo,topicSessionIds:Ot}).slice(0,9),[Fc,h,RS,xd,Si,bl,Lo,Ot]),yne=p.useMemo(()=>({held:TS,indexBySessionId:new Map(MS.map(($,U)=>[$,U+1]))}),[TS,MS]),[PS,X3]=p.useState(null),Tv=p.useRef(null),_d=p.useRef(null),gp=p.useCallback(()=>{_d.current!=null&&(clearTimeout(_d.current),_d.current=null),Tv.current=null,X3(null)},[]);p.useEffect(()=>gp,[gp]);const Sd=p.useCallback(()=>{const $=Tv.current;if(gp(),$==null)return;me(G=>lO(G,$));const U=Ke.current.tabs[$];(U==null?void 0:U.kind)==="session"&&ne(U.sid)},[gp,ne]),Z3=p.useCallback($=>{const U=Ke.current.tabs.length;if(U===0)return;const ie=((Tv.current??Ke.current.focused)+$+U)%U;Tv.current=ie,X3(ie),_d.current!=null&&clearTimeout(_d.current),_d.current=setTimeout(Sd,Pot)},[Sd]);p.useEffect(()=>{if(PS==null)return;const $=U=>{(U.key==="Meta"||U.key==="Control"||U.key==="Shift")&&Sd()};return window.addEventListener("keyup",$,!0),window.addEventListener("blur",Sd),()=>{window.removeEventListener("keyup",$,!0),window.removeEventListener("blur",Sd)}},[PS,Sd]);const[xp,Rv]=p.useState(!1),[Ma,AS]=p.useState(""),[kd,Sl]=p.useState({group:"session",row:0}),[bne,Q3]=p.useState(null),[wne,OS]=p.useState(null),Mv=p.useMemo(()=>kot(o),[o]),_ne=p.useMemo(()=>Mv.map($=>$.sessionId),[Mv]),{matches:J3,loading:DS}=Sot({api:r,query:Ma,candidateIds:_ne,enabled:xp}),eP=p.useMemo(()=>{const $=new Map(o.map(U=>[U.sessionId,U]));return new Map(fp.map(U=>[U.masterSessionId,{topicId:U.id,title:Vw(U.title,$.get(U.masterSessionId)??null)}]))},[fp,o]),tP=p.useMemo(()=>new Map(Wt.map($=>[$.personaId,$.label])),[Wt]),vp=p.useMemo(()=>Cot({candidates:Mv,query:Ma,contentMatches:J3,topicByMasterSessionId:eP,personaLabelById:tP}),[Mv,Ma,J3,eP,tP]),yp=p.useMemo(()=>Not(Wt,Ma),[Wt,Ma]),bp=p.useMemo(()=>{const $=S3(C,Dot);return jot([...$.pinned,...$.main],Ma)},[C,Ma]),$S=p.useMemo(()=>Iot({session:vp.length,persona:yp.length,contact:bp.length}),[vp.length,yp.length,bp.length]),wp=p.useMemo(()=>$S.map($=>$.key),[$S]),Sne=kd.group==="session"?vp.length:kd.group==="persona"?yp.length:bp.length;p.useEffect(()=>{Sl($=>Wd($,{kind:"query-changed"}))},[Ma]),p.useEffect(()=>{Sl($=>Wd($,{kind:"results-changed",groups:wp,sessionsLoading:DS}))},[wp,DS]);const nP=p.useCallback(()=>{an(),AS(""),Sl({group:"session",row:0}),Rv(!0)},[an]),[LS,Pv]=p.useState(!1),rP=p.useCallback(()=>{an(),Rv(!1),Pv(!0)},[an]),kne=p.useMemo(()=>AB(C.map($=>({deviceId:$.deviceId,displayName:$.displayName})),[]),[C]),sP={"toggle-hive":()=>{if(LS){Pv(!1);return}rP()},"new-session":()=>{an(),Pe(!0)},"open-search":()=>{if(xp){Rv(!1);return}nP()},...xp?{"search-tab-prev":()=>Sl($=>Wd($,{kind:"move-group",delta:-1,groups:wp})),"search-tab-next":()=>Sl($=>Wd($,{kind:"move-group",delta:1,groups:wp}))}:{},...Object.fromEntries(Array.from({length:9},($,U)=>[`switch-session-${U+1}`,()=>{if(xp){fP(U);return}const G=MS[U];G&&(an(),Sp(G))}])),"tab-prev":()=>Z3(-1),"tab-next":()=>Z3(1),...le.tabs.length>0?{"close-tab":()=>me($=>am($,$.focused))}:{},"archive-session":()=>{const $=Ke.current.tabs[Ke.current.focused];if(($==null?void 0:$.kind)!=="session")return;const U=o.find(ie=>ie.sessionId===$.sid);if(!U)return;const G=cv(U);G&&o.some(ie=>ie.sessionId===G)||FS($.sid)}};wtt(LS?{"toggle-hive":sP["toggle-hive"]}:sP);const[Av,FS]=p.useState(null),[iP,Cne,oP]=bm(Aot,!1),aP=p.useRef(!1),[Nne,BS]=p.useState(null);p.useEffect(()=>{if(aP.current||!l||h==null||!oP||(aP.current=!0,iP))return;const $=h2(o,h,10,Lo,Ot).length;$>0&&BS($)},[o,l,h,Lo,Ot,iP,oP]);const zS=p.useCallback(async($,U)=>{if(U){const G=[$,...ny(o,$)];me(ie=>G.reduce((He,at)=>oo(He,at),ie))}await r.archiveSession($,U),await c(),U&&Ia()},[r,c,oo,o,Ia]),jne=p.useCallback(async $=>{await r.reorderPins($),await c()},[r,c]),HS=p.useCallback($=>{_i(!1),sn({kind:"config",personaId:$})},[]),Ene=p.useCallback($=>{an(),me(U=>Es(U,{kind:"deploy",personaId:$}))},[an]),Ine=p.useCallback(($,U)=>{an(),me(G=>Es(G,{kind:"deploy-history",personaId:$,head:U}))},[an]),Tne=p.useCallback(async $=>{var G;const U=((G=Wt.find(ie=>ie.personaId===$))==null?void 0:G.label)??$;confirm(`删除 persona "${U}"?`)&&(await ro($),sn(ie=>(ie==null?void 0:ie.personaId)===$?null:ie))},[ro,Wt]),Rne=p.useCallback(async($,U)=>{_i(!1),sn(null);const G={ownerPersonaId:$},ie=U.trim();ie&&(G.label=ie);try{const He=await r.sessionCreate(G);await c(),Ta(He.sessionId)}catch(He){Ae("persona","sessionCreate(ownerPersonaId) failed",He)}},[r,c,Ta,Wt]),Mne=p.useCallback(async($,U,G)=>{try{const{sessionId:ie}=await Bc({ownerPersonaId:$,label:G});await r.sessionSubscribe(ie),await r.sessionSend(ie,U)}catch(ie){throw Ae("pr-inbox","open chat failed",ie),ie}},[r,Bc]),kl=p.useCallback(async($,U)=>{const G=SI(U,$);try{await r.peerSessionUpsert(G)}catch(ie){Ae("mirror","peerSession:upsert failed",G.sessionId,ie)}s.setData("sessions",ie=>{const He=[...ie??[]],at=He.findIndex(ln=>ln.sessionId===G.sessionId);return at>=0?He[at]=G:He.unshift(G),He})},[r,s]),Ov=p.useCallback(async $=>{try{await r.peerSessionRemove($)}catch(U){Ae("mirror","peerSession:remove failed",$,U)}s.setData("sessions",U=>(U??[]).filter(G=>G.sessionId!==$))},[r,s]),Pne=p.useCallback(async($,U,G)=>{await ze($);const ie=S.getRemoteForDevice($);if(!ie)throw new Error("remote daemon unreachable");const He=new Kt(ie),at={ownerPersonaId:U},ln=G.trim();ln&&(at.label=ln);try{const Bo=await He.sessionCreate(at),Lv=Bo;Je($,Lv),me(kp=>Es(kp,{kind:"session",sid:Bo.sessionId})),kl($,Lv).catch(kp=>{Ae("persona","upsertMirrorLocally (remote create) failed",kp)})}catch(Bo){Ae("persona","sessionCreate(remote) failed",{ownerId:$,personaId:U,err:Bo})}},[S,be,ze,Je,kl]),Cl=p.useCallback($=>{const U=S.getRemoteForDevice($);if(U)return U;const G=C.find(ie=>ie.deviceId===$);return!(G!=null&&G.remoteUrl)||!G.connectToken?null:S.ensureRemoteForDevice($,G.remoteUrl,G.connectToken)},[S,C]),ao=p.useCallback(($,U,G,ie)=>{Fo({kind:"error",text:iit(T($),U,G),...ie?{action:ie}:{}})},[Fo,T]),US=p.useCallback(async($,U)=>{const G=async()=>{ve($,U),me(at=>oo(at,U)),await Ov(U)},ie=Cl($);if(!ie){await G();return}const He=new Kt(ie);try{await He.sessionDelete(U),G().catch(at=>{Ae("persona","removeMirrorLocally (remote delete) failed",at)})}catch(at){Ae("persona","sessionDelete(remote) failed",at),ao($,"删除",at,{label:"只从我这儿移除",onClick:()=>{so(null),G().catch(ln=>{Ae("persona","removeMirrorLocally (drop from my side) failed",ln)})}})}},[Cl,ao,ve,Ov,oo]),Ane=p.useCallback(async($,U,G)=>{const ie=G?"置顶":"取消置顶",He=Cl($);if(!He){ao($,ie,null);return}const at=new Kt(He);try{const ln=await at.pinSession(U,G);await kl($,ln),so(null)}catch(ln){Ae("persona","pinSession(remote) failed",ln),ao($,ie,ln)}},[Cl,ao,kl]),_p=p.useCallback(async($,U,G)=>{const ie=G?"归档":"取消归档",He=Cl($);if(!He)return ao($,ie,null),!1;const at=new Kt(He);try{if(G){const Bo=[U,...ny(o,U)];me(Lv=>Bo.reduce((kp,Xne)=>oo(kp,Xne),Lv))}const ln=await at.archiveSession(U,G);return await kl($,ln),G&&Ia(),!0}catch(ln){return Ae("persona","archiveSession(remote) failed",ln),ao($,ie,ln),!1}},[Cl,ao,kl,oo,o,Ia]),One=p.useCallback(async $=>{const U=h2(o,h??void 0,$,Lo,Ot);let G=0;for(const ie of U){if(ie.originOwnerPrincipalId){await _p(ie.originOwnerPrincipalId,ie.sessionId,!0)||(G+=1);continue}const He=[ie.sessionId,...ny(o,ie.sessionId)];me(at=>He.reduce((ln,Bo)=>oo(ln,Bo),at));try{await r.archiveSession(ie.sessionId,!0)}catch(at){Ae("persona","bulkArchive: archiveSession failed",at),G+=1}}await c(),BS(null),U.length>0&&G===0&&Ia()},[o,h,Lo,Ot,r,c,oo,_p,Ia]),Dne=p.useCallback($=>h2(o,h??void 0,$,Lo,Ot).length>0,[o,h,Lo,Ot]),lP=p.useCallback(async($,U,G)=>{if(!G.label)return;const ie=Cl($);if(!ie){ao($,"改名",null);return}const He=new Kt(ie);try{const at=await He.sessionUpdate(U,{label:G.label});await kl($,at),so(null)}catch(at){Ae("persona","sessionUpdate(remote) failed",at),ao($,"改名",at)}},[Cl,ao,kl]),cP=p.useCallback(()=>{_i(!1),yn(null),Lt(!0)},[]),$ne=p.useCallback(async $=>{no(!0),yn(null);try{await wS({personaId:ei,text:Ort($),config:{model:"",effort:"",permissionMode:""}}),Lt(!1),Qt(U=>U+1),an()}catch(U){yn(U.message??String(U))}finally{no(!1)}},[wS,an]),Lne=p.useCallback(async()=>{const $=n.getActive();$&&await n.activate($.id)},[n]),Sp=p.useCallback($=>{sn(null),Ta($)},[Ta]),Dv=()=>{Rv(!1),AS("")},uP=$=>{if(Dv(),$.topicId!==void 0){kv($.topicId);return}Sp($.sessionId)},dP=$=>{Dv(),Q3($),vt(!1),Ut(!0)},Pa=Mnt(),Fne=p.useMemo(()=>{const $=new Map(C.map(U=>[U.deviceId,U]));return Pa.favorites.flatMap(U=>{var He;const G=U.deviceId?$.get(U.deviceId):void 0;if(!U.deviceId||!G)return[];const ie=(He=be.get(U.deviceId))==null?void 0:He.find(at=>at.personaId===U.personaId);return[{deviceId:U.deviceId,personaId:U.personaId,label:(ie==null?void 0:ie.label)??U.label??U.personaId,tool:(ie==null?void 0:ie.tool)??U.tool,contactName:G.displayName||G.deviceId}]})},[Pa.favorites,C,be]),Bne=$=>{OS($),Ut(!1),vt(!0),ze($)},hP=$=>{Dv(),OS($),Ut(!1),vt(!0),ze($)},fP=$=>{if(kd.group==="session"){const G=vp[$];G&&uP(G);return}if(kd.group==="persona"){const G=yp[$];G&&dP(G.personaId);return}const U=bp[$];U&&hP(U.deviceId)},pP=A3||Dc;if(pP&&vd)return a.jsx(KU,{view:vd});if(pP)return a.jsx(Tst,{state:i,onClose:A3?void 0:()=>hv(!1),remoteHosts:H});if(Fte||!l)return a.jsx("div",{"data-testid":"app-bootstrapping",className:"h-screen flex items-center justify-center bg-bg-0",children:a.jsx(st,{className:"w-5 h-5 text-text-400 animate-spin"})});if(i.kind==="connected"&&i.mode!=="remote"&&i.onboardingCompletedAt===null&&!it)return a.jsx(ost,{api:r,feishuIdentity:g.identity,feishuError:g.error,onFeishuLogin:g.login,personas:Wt.map($=>({personaId:$.personaId,label:$.label})),onFinished:Bte});const zne=(Qn==null?void 0:Qn.label)||(Qn==null?void 0:Qn.aiLabel)||(Qn!=null&&Qn.cwd?Qn.cwd.split("/").filter(Boolean).pop()??"Clawd":"Clawd"),mP=wl?nu+kS:kS,gP=wl?x2:0,xP=wl?nu:0,$v=(wP=le.tabs[le.focused])==null?void 0:wP.kind,Hne=_e?"people":Ct?"persona":$v==="exts"||$v==="shift"||$v==="prs"?$v:null,Une=$=>{if(_i(!1),$==="people"){OS(null),Ut(!1),vt(G=>!G);return}if($==="persona"){Q3(null),vt(!1),Ut(G=>!G);return}if(an(),$==="new"){me(G=>Es(G,{kind:"landing"}));return}const U=$==="shift"?{kind:"shift"}:$==="prs"?{kind:"prs"}:{kind:"exts"};me(G=>Es(G,U))},Wne=a.jsxs(a.Fragment,{children:[H,a.jsx(fit,{identity:g.identity,loading:g.loading,error:g.error,onLogin:g.login}),a.jsxs("div",{className:"flex items-center gap-1 pr-1",children:[a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx(dit,{onClick:()=>md("about")})}),a.jsx(hit,{})]})]}),Vne=a.jsx(rb.Provider,{value:$c,children:a.jsx(vnt,{client:t,open:_e,initialSelectedId:wne,onClose:an,sidebarWidth:mP,insetTop:gP,insetBottom:xP,contacts:C,publicDevices:K,onConnectPublicDevice:async $=>{await X.connect($)},remoteGated:!y,onAddContact:()=>A(!0),visitors:de,visitorUnreadIds:bS,unreadDeviceIds:bS,isRemotePersonaFavorite:($,U)=>Pa.isFavorite(U,$),onToggleRemotePersonaFavorite:($,U)=>Pa.toggleFavorite({personaId:U.personaId,deviceId:$,label:U.label,tool:U.tool}),onOpenVisitor:$=>{an(),me(U=>Es(U,{kind:"dm",peerDeviceId:$}))},loginCardNode:a.jsx(gB,{...v}),onEnsureContactLoaded:wt,personasByOwnerId:be,personaLoadingOwnerIds:se,personaErrorByOwnerId:ae,onRetryPersonas:wt,onReconnectContact:async $=>{await X.connect({deviceId:$.deviceId,url:$.remoteUrl||void 0})},sessionsByOwnerId:xe,extensionsByOwnerId:Ne,activeSessionId:zt?null:ut,awaitingIds:xd,runningIds:Si,unreadIds:bl,onMessage:$=>{an(),ze($),me(U=>Es(U,{kind:"dm",peerDeviceId:$}))},onPinContact:($,U)=>void k.pin($,U),onSetContactRemoteAccess:($,U)=>k.setRemoteAccess($.deviceId,{remoteAccessAllowed:U}),onSetContactNote:($,U)=>void k.setNote($,U),onRemoveContact:$=>{const U=$.deviceId;for(const G of o)G.originOwnerPrincipalId===U&&Ov(G.sessionId);k.remove(U)},onCreateRemoteSession:($,U)=>(an(),Pne($,U,"")),onSelectSession:$=>{an(),Ta($)},onDeleteRemoteSession:($,U)=>void US($,U),onEditRemoteSession:($,U,G)=>void lP($,U,G),onInstallExtension:($,U,G)=>{G&&oe($,U,G)},onOpenInstalledExtension:($,U)=>{an(),me(G=>Es(G,{kind:"ext",extId:Q5(U,$)}))}})}),qne=a.jsx("div",{className:"h-full w-full overflow-y-auto bg-bg-100",children:a.jsx("div",{className:"max-w-[480px] h-full border-r border-border",children:a.jsx(qnt,{client:t,activeExtId:tn,onOpenInMain:$=>me(U=>Es(U,{kind:"ext",extId:$})),onExtensionsMutated:()=>void Re()})})}),Kne=fr?a.jsx(ynt,{open:!0,submitting:wi,mode:fr.mode,...fr.mode==="edit"?(()=>{const $=io.find(U=>U.id===fr.channelId);return $?{initial:{name:$.name,memberPersonas:[...$.memberPersonas],memberContactDeviceIds:[...$.memberContactDeviceIds]}}:{}})():{},personas:Wt.map($=>({id:$.personaId,label:$.label||$.personaId})),contactGroups:C.map($=>{const U=be.get($.deviceId),G=ae.get($.deviceId);return{deviceId:$.deviceId,displayName:$.displayName,...U?{personas:U.map(ie=>({id:ie.personaId,label:ie.label||ie.personaId}))}:{},...se.has($.deviceId)?{loading:!0}:{},...G?{errorText:G}:{},...zf($)?{}:{brokenLink:!0}}}),onExpandContact:$=>void Z($),...up?{error:up}:{},onCancel:()=>eo(null),onSubmit:$=>{const U=()=>{to(!1),eo(null)},G=()=>to(!1);to(!0),fr.mode==="create"?bv($).then(U).catch(G):wv({channelId:fr.channelId,...$}).then(U).catch(G)}}):null,Gne=a.jsx(rb.Provider,{value:$c,children:a.jsx(Ent,{open:Ct,initialSelectedId:bne,onClose:an,sidebarWidth:mP,insetTop:gP,insetBottom:xP,personas:Wt,sessions:Fc,activeSessionId:zt?null:ut,awaitingIds:xd,runningIds:Si,unreadIds:bl,ownerPrincipalId:h??void 0,getCreatorDisplayName:R,getSessionDisplayName:T3,onNewPersona:cP,onCreateSession:$=>{an(),Rne($,"")},onOpenPersonaSettings:$=>{an(),HS($)},onDeployPersona:Ene,renderDeployStatus:$=>{var U;return a.jsx(xst,{personaId:$,tool:(U=Wt.find(G=>G.personaId===$))==null?void 0:U.tool})},renderDeployHistory:$=>{var U;return a.jsx(yst,{personaId:$,tool:(U=Wt.find(G=>G.personaId===$))==null?void 0:U.tool,onOpenRelease:G=>Ine($,G)})},renderCloudConnectors:($,U)=>a.jsx(Sst,{personaId:$,render:U}),renderCloudApiKey:$=>a.jsx(mB,{...b,personaId:$}),renderCloudLarkBot:$=>a.jsx(pst,{personaId:$}),favorites:{isFavorite:$=>Pa.isFavorite($),onToggle:$=>Pa.toggleFavorite({personaId:$.personaId}),filter:Pa.filter,onFilterChange:Pa.setFilter,contactFavorites:Fne,onToggleContact:$=>Pa.toggleFavorite({personaId:$.personaId,deviceId:$.deviceId}),onOpenContact:Bne},onDeletePersona:$=>void Tne($),renderSettings:$=>a.jsx(fst,{personaId:$,onOpenMore:()=>{an(),HS($)},onOpenLarkBot:()=>{an(),HS($)}}),onSelectSession:$=>{an(),Sp($)},onEditSession:($,U)=>void D3($,U),onDeleteSession:$=>void SS($)})}),vP=$=>a.jsx(rb.Provider,{value:$c,children:a.jsx(Utt,{channelTree:Kte,expandedTopicIds:hr,onToggleTopic:Zte,onSelectTopic:U=>{_i(!1),an(),kv(U)},onCreateChannel:()=>eo({mode:"create"}),onCreateTopic:U=>void nne(U),onEditChannel:U=>eo({mode:"edit",channelId:U}),onDeleteChannel:U=>void ane(U),onArchiveTopic:rne,onRenameTopic:ine,onDeleteTopic:K3,onPinTopic:one,pinnedTopics:Gte,channelError:tne,topicSessionIds:Ot,floating:$,width:kS,onResizeStart:Vte,projects:qs,onNewInProject:U=>{Pt(U),Pe(!0)},onRefreshProjects:()=>void ye(),onCreateProject:()=>{ap(void 0),lt(!0)},onPatchProject:(U,G)=>{r==null||r.projectPatch({path:U,...G}).then(()=>ye()).catch(ie=>Ae("app","projectPatch failed",{path:U,err:String(ie)}))},onRevealProject:U=>{r==null||r.projectReveal(U).catch(G=>Ae("app","projectReveal failed",{path:U,err:String(G)}))},getPersonaDisplayName:Ea,sessions:Fc,activeId:zt?null:ut??Kn,awaitingIds:xd,runningIds:Si,unreadIds:bl,onSelect:U=>{_i(!1),an(),Sp(U)},onEdit:(U,G)=>{const ie=o.find(at=>at.sessionId===U),He=ie==null?void 0:ie.originOwnerPrincipalId;He?lP(He,U,G):D3(U,G)},onDelete:U=>{const G=o.find(He=>He.sessionId===U),ie=G==null?void 0:G.originOwnerPrincipalId;ie?US(ie,U):SS(U)},onPin:(U,G)=>{const ie=o.find(at=>at.sessionId===U),He=ie==null?void 0:ie.originOwnerPrincipalId;He?Ane(He,U,G):Wte(U,G)},sortMode:RS,onChangeSortMode:gne,quickAction:xne,onChangeQuickAction:vne,bulkArchiveHintCount:Nne,onDismissBulkHint:()=>{BS(null),Cne(!0)},onBulkArchive:U=>void One(U),bulkArchiveAvailable:Dne,onArchive:(U,G)=>{const ie=o.find(at=>at.sessionId===U),He=ie==null?void 0:ie.originOwnerPrincipalId;He?_p(He,U,G):zS(U,G)},onReorderPins:U=>void jne(U),ownerPrincipalId:h??void 0,getContactDisplayName:T,getCreatorDisplayName:R,getSessionDisplayName:T3,onNewPersona:cP,onCollapse:()=>{$3(!0),CS(!1),an()},onOpenHive:rP,onOpenSearch:nP,onFixedEntryClick:Une,activeEntry:Hne,peopleUnreadCount:P3,footer:a.jsx("div",{className:"flex flex-col px-2 py-2",children:Wne})})}),yP=vP(!1),Yne=vP(!0);return a.jsx(Pst,{api:fd,children:a.jsx(rTe,{value:hn,children:a.jsx(Vee.Provider,{value:yne,children:a.jsx(tX.Provider,{value:Yte,children:a.jsxs("div",{className:"h-screen flex flex-col bg-bg-100 text-text-100","data-testid":"app-root",children:[LS&&a.jsx("div",{className:"fixed inset-0 z-50","data-testid":"hive-overlay",children:a.jsx(yot,{sessions:Fc,pool:S,deviceNames:kne,unreadIds:bl,ownerName:m??"me",onExit:()=>Pv(!1),onPick:$=>{Pv(!1),an(),Sp($)}})}),a.jsx(Nrt,{state:i,onRetryNow:Lne}),H,a.jsxs("div",{className:"md:hidden flex items-center gap-2 h-11 px-2 border-b border-border shrink-0",style:{paddingTop:"env(safe-area-inset-top)",minHeight:"calc(2.75rem + env(safe-area-inset-top))"},"data-testid":"app-mobile-topbar",children:[a.jsx("button",{type:"button",onClick:()=>_i(!0),className:"flex items-center justify-center w-9 h-9 rounded-md text-text-300 hover:text-text-100 hover:bg-text-100/5 transition-colors cursor-pointer","aria-label":"Open sessions","data-testid":"app-mobile-nav-trigger",children:a.jsx(Kfe,{className:"w-5 h-5"})}),a.jsx("div",{className:"flex-1 truncate text-sm font-medium text-text-200",children:zne})]}),a.jsxs("div",{className:"relative flex-1 flex min-h-0",children:[!wl&&a.jsx("aside",{className:"hidden md:flex shrink-0 flex-row","data-testid":"app-sidebar",children:yP}),wl&&a.jsxs("div",{className:"hidden md:block",children:[a.jsx(Ont,{hasUnread:P3>0||bl.size>0,onExpand:()=>{$3(!1),CS(!1)},onMouseEnter:F3,onMouseLeave:B3}),qte&&a.jsx("div",{"data-testid":"sidebar-float-layer",className:"absolute z-40 shadow-2xl rounded-xl bg-bg-100",style:{left:nu,top:x2,bottom:nu},onMouseEnter:F3,onMouseLeave:B3,children:Yne})]}),a.jsx(prt,{open:P,onClose:()=>A(!1),connect:X.connect,myDeviceLink:w,onLogin:g.login}),a.jsx(Pit,{open:O,onClose:()=>F(!1),tunnelUrl:L,token:I==null?void 0:I.token,connections:D,onOpenRemoteHosts:void 0}),z&&a.jsx(Ait,{api:r,onClose:()=>W(!1)}),Kne,a.jsx(wit,{open:Qe,submitting:Vt,error:dd,onSubmit:gS,onCancel:()=>lt(!1)}),a.jsx(Ry,{open:fv,onOpenChange:_i,children:a.jsxs(Om,{side:"left",hideBuiltInClose:!0,className:"md:hidden p-0 w-[288px]","data-testid":"app-mobile-nav-drawer","aria-describedby":void 0,children:[a.jsx(Dm,{className:"sr-only",children:"Sessions"}),a.jsx("div",{className:"flex flex-col h-full",children:yP})]})}),a.jsxs(c_,{orientation:"horizontal",className:`flex-1 flex min-w-0${wl?" md:pl-10":""}${pp?" md:[&_.chrome-tab-strip]:pr-20":ES?" md:[&:has(+aside:not(:empty))_[data-cc-chat-root]]:pr-[316px]":wd&&Ra?" md:pr-10":""}`,children:[a.jsx(Jh,{id:"main",children:a.jsx("main",{className:`flex-1 flex min-w-0 flex-col md:flex-row h-full${pp&&!Cv&&Ra?" md:[&_[data-cc-chat-root]]:pr-[316px]":""}`,"data-testid":"app-main",children:a.jsx(LG,{container:mne,workspaceContainer:ES?cne:null,...Ra?{}:{onCollapse:()=>jS(!0)},children:a.jsx(NTe,{value:fe,children:a.jsx(Det,{view:le,sessions:o,topics:fp,contacts:C,visitorContacts:te,remoteSessionsByOwnerId:xe,clientPool:S,client:t,im:ee,api:r,myOwnerPrincipalId:h??"",myOwnerDisplayName:m??"我",cloud:{apiKey:x.apiKey,gatewayUrl:x.gatewayUrl},onFocusTab:$=>{gp(),me(G=>lO(G,$));const U=le.tabs[$];(U==null?void 0:U.kind)==="session"&&ne(U.sid)},onCloseTab:$=>me(U=>am(U,$)),onCloseOtherTabs:$=>me(U=>cve(U,$)),onCloseAllTabs:()=>me(My),onReorderTab:($,U)=>{console.log("[tab-debug] onReorderTab dispatch",{from:$,to:U}),me(G=>uve(G,$,U))},onSelectCwdForNew:zte,onNewSession:Hte,onOpenPrChat:Mne,onFork:Ute,onOpenMobileConfig:()=>yl(!0),onMirrorOrphan:($,U)=>{Ov($),Ae("mirror","orphan auto-cleanup",{sessionId:$,ownerId:U}),me(G=>oo(G,$))},extensionUpdateInfo:Lot(tn,Ne),onApplyExtensionUpdate:St,awaitingIds:xd,runningIds:Si,unreadIds:bl,unreadDmPeerDeviceIds:bS,pendingTabIndex:PS,extensionsListNode:qne,landingNode:a.jsx(Hrt,{firstRun:kt,personas:Wt.filter($=>$.personaId!==Fi).map($=>({personaId:$.personaId,name:$.label,tool:$.tool,...$.cloud?{cloud:!0}:{}})),initialPersonaId:ei,api:r,modelList:d,modes:(u==null?void 0:u.permissionModes)??[],configSchema:(u==null?void 0:u.configSchema)??[],defaultsByPersonaId:Object.fromEntries(Wt.map($=>[$.personaId,{...$.model?{model:$.model}:{},...$.effort?{effort:$.effort}:{}}])),onCreate:$=>void wS($)})})})})})}),wd&&!Ra?a.jsxs(a.Fragment,{children:[a.jsx(xR,{className:"w-1 bg-text-100/10 hover:bg-text-100/25 transition-colors cursor-col-resize"}),a.jsx(Jh,{id:"session-info",defaultSize:`${Y3}px`,minSize:"280px",maxSize:"480px",onResize:$=>pne($.inPixels),children:a.jsx("div",{ref:hne,"data-testid":"session-info-column",className:"hidden md:flex h-full min-w-0 flex-col"})})]}):null]}),ES&&a.jsx("aside",{ref:une,"aria-label":"工作区卡片",className:"absolute right-0 top-10 z-30 hidden max-h-[calc(100%-2.5rem)] w-[316px] overflow-y-auto p-2 md:flex md:flex-col md:gap-3 md:empty:hidden"}),pp&&a.jsxs("div",{className:"absolute right-2 top-2 z-50 hidden items-center gap-1 rounded-md bg-bg-100 md:flex",children:[a.jsx("button",{"aria-label":"显示或隐藏工作区卡片",title:"工作区卡片","aria-pressed":!Cv,onClick:()=>lne(!Cv),className:"rounded-md p-1.5 text-text-300 hover:bg-text-100/10",children:a.jsx(Afe,{className:"h-4 w-4"})}),a.jsx("button",{"aria-label":"切换会话侧栏",title:"会话侧栏","aria-pressed":!Ra,onClick:()=>{jS(!Ra),Nv(!1)},className:"rounded-md p-1.5 text-text-300 hover:bg-text-100/10",children:a.jsx(Kb,{className:"h-4 w-4"})})]}),wd&&Ra&&!pp&&a.jsxs("div",{className:"hidden md:block",children:[a.jsx(Dnt,{onExpand:()=>{jS(!1),Nv(!1)},onMouseEnter:Ev,onMouseLeave:Iv}),G3&&a.jsx("div",{"data-testid":"session-info-float",className:"absolute z-40 shadow-2xl rounded-xl overflow-hidden",style:{right:nu,top:x2,bottom:nu,width:Y3},ref:fne})]}),Vne,Gne,xp&&a.jsx(wot,{query:Ma,onQueryChange:AS,sessionsLoading:DS,sessions:vp,personas:yp,contacts:bp,groups:$S,focus:kd,onFocusChange:Sl,onMoveRow:$=>Sl(U=>Wd(U,{kind:"move-row",delta:$,rowCount:Sne})),onMoveGroup:$=>Sl(U=>Wd(U,{kind:"move-group",delta:$,groups:wp})),onOpenFocused:()=>fP(kd.row),onSelectSession:uP,onSelectPersona:$=>dP($.personaId),onSelectContact:$=>hP($.deviceId),onClose:Dv}),fd,a.jsx(Lst,{open:TS}),Av?a.jsx(Mot,{sessionLabel:(()=>{const $=o.find(U=>U.sessionId===Av);return($==null?void 0:$.label)||($==null?void 0:$.aiLabel)||($==null?void 0:$.larkChatName)||($==null?void 0:$.larkChatId)||($==null?void 0:$.cwd)||Av.slice(0,8)})(),onConfirm:()=>{const $=Av;FS(null);const U=o.find(G=>G.sessionId===$);U&&(U.originOwnerPrincipalId?_p(U.originOwnerPrincipalId,$,!0):zS($,!0))},onCancel:()=>FS(null)}):null,a.jsx(rit,{toast:vv,onOpenArchived:()=>{so(null),md("archived")},onClose:()=>so(null)}),pd&&a.jsx(Wst,{initialNav:pd,onBack:()=>md(null),api:fd,ownerPrincipalId:h,daemonScanApi:pv,daemonVersion:i.kind==="connected"?i.daemonVersion:null,daemonSource:i.kind==="connected"?i.daemonSource:null,globalCliVersion:i.kind==="connected"?i.globalCliVersion:null,ccMode:gv,effectiveCcMode:xv,onChangeCcMode:void 0,onAddMobile:V?()=>F(!0):void 0,onImportExternalSessions:i.kind==="connected"&&i.mode!=="remote"?()=>W(!0):void 0,feishuSlot:a.jsx(gB,{variant:"settings",...v}),cloudApiKeySlot:a.jsx(mB,{...b}),githubSlot:a.jsx(xI,{}),channelsSlot:a.jsx(nit,{}),engineSlot:a.jsx(Jst,{}),dashboardSlot:a.jsx(zet,{tunnelReady:!!L,onOpen:$=>y_e(async()=>(await r.dashboardOpenUrl($)).url)}),archivedTopicsSlot:a.jsx(uit,{groups:Xte,onUnarchive:sne,onDelete:K3}),archivedSlot:a.jsx(lit,{sessions:Dte,childrenByRoot:$te,personaLabelOf:$=>{var U;return(U=Wt.find(G=>G.personaId===$))==null?void 0:U.label},contactNameOf:$=>T($),onUnarchive:$=>{const U=o.find(ie=>ie.sessionId===$),G=U==null?void 0:U.originOwnerPrincipalId;G?_p(G,$,!1):zS($,!1)},onDelete:$=>{const U=o.find(ie=>ie.sessionId===$),G=U==null?void 0:U.originOwnerPrincipalId;G?US(G,$):SS($)}})},pd),Qn?a.jsx(Ry,{open:dv,onOpenChange:yl,children:a.jsxs(Om,{side:"right",className:"md:hidden p-0 w-[320px] max-w-[85vw]","data-testid":"app-mobile-config-drawer","aria-describedby":void 0,children:[a.jsx(Dm,{className:"sr-only",children:"Session Info"}),a.jsx(Rst,{open:dv,onOpenChange:yl,session:Qn,embedded:!0})]})}):null,(zt==null?void 0:zt.kind)==="config"&&a.jsx(Ry,{open:!0,onOpenChange:$=>{$||lp&&!window.confirm("修改未保存,确定关闭?")||(sn(null),hd(!1))},children:a.jsxs(Om,{side:"right",className:"p-0 w-[420px] max-w-[90vw]","data-testid":"app-persona-config-drawer","aria-describedby":void 0,hideBuiltInClose:!0,children:[a.jsx(Dm,{className:"sr-only",children:"Persona 设置"}),a.jsx(eX,{personaId:zt.personaId,open:!0,onClose:()=>{lp&&!window.confirm("修改未保存,确定关闭?")||(sn(null),hd(!1))},api:r,embedded:!0,onDirtyChange:hd},zt.personaId)]})})]}),a.jsx(Drt,{open:Se,onOpenChange:$=>{Pe($),$||Pt(null),!$&&ut&&ne(ut)},onCreate:Bc,api:r,projects:qs,presetProject:dt,onProjectsChanged:()=>void ye()}),a.jsx(lst,{open:$n,onOpenChange:$=>{Lt($),$||yn(null)},onCreate:$ne,loadRepos:($,U)=>r.githubRepos({page:$,search:U}),githubLink:$=>a.jsx(xI,{compact:!0,onAuthorized:$}),submitting:ja,submitError:xn},Sn)]})})})})})}const Mte="(prefers-color-scheme: dark)",zot=["light","dark","system"],Pte="clawd-standalone:theme-source",Hot="light",Uot={colorPrimary:"#1677ff",colorBgContainer:"#fff",colorText:"#000",colorBorder:"#d9d9d9"};function Wot(){try{const e=localStorage.getItem(Pte);if(e!==null&&zot.includes(e))return e}catch{}return Hot}function Vot(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Mte).matches}function JB(e){return{mode:e==="dark"||e==="system"&&Vot()?"dark":"light",...Uot}}function qot(e){let t=Wot();const n=new Set,r=()=>{const i=JB(t);for(const o of n)o(i)};typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Mte).addEventListener("change",()=>{t==="system"&&r()});const s={gateway:{call:()=>Promise.reject(new Error("standalone-host: gateway.call not supported"))},self:{call:()=>Promise.reject(new Error("standalone-host: self.call removed; use useDaemonClient()"))},kv:{get:async i=>{const o=localStorage.getItem(`clawd-standalone:kv:${i}`);if(o==null)return null;try{return JSON.parse(o)}catch{return null}},set:async(i,o)=>{localStorage.setItem(`clawd-standalone:kv:${i}`,JSON.stringify(o))}},logger:{info:(i,o)=>{var l;console.info("[ext]",i,o??""),(l=e.logClient)==null||l.push({level:"info",msg:String(i),meta:o})},warn:(i,o)=>{var l;console.warn("[ext]",i,o??""),(l=e.logClient)==null||l.push({level:"warn",msg:String(i),meta:o})},error:(i,o)=>{var l;console.error("[ext]",i,o??""),(l=e.logClient)==null||l.push({level:"error",msg:String(i),meta:o})}},get theme(){return JB(t)},on(){return()=>{}},onThemeChange(i){return n.add(i),()=>{n.delete(i)}}};return s.getThemeSource=()=>t,s.setThemeSource=i=>{t=i;try{localStorage.setItem(Pte,i)}catch{}r()},e.notifier&&(s.notifier=e.notifier),s}var Kot={maxRecords:100,maxBytes:512*1024,maxWaitMs:5e3},Got=5e3,Ate={debug:0,info:1,warn:1,error:1},ez=1024,tz=2048,Yot=/token|secret|password|auth(?!or)|apikey|signsecret/i,Xot="[REDACTED]",Ote="…[truncated]";function Zot(e,t){const n=EI(e,t,0),r=Qot(n);return r.length<=tz?n:{__truncated__:r.slice(0,tz)+Ote}}function EI(e,t,n){if(n>10)return"[depth-limit]";if(e==null)return e;if(typeof e=="string")return t?e.split(t).join("~"):e;if(typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>EI(s,t,n+1));const r={};for(const[s,i]of Object.entries(e))Yot.test(s)?r[s]=Xot:r[s]=EI(i,t,n+1);return r}function Qot(e){try{return JSON.stringify(e)??""}catch{return'"[serialize-failed]"'}}function Jot(e){return e.length<=ez?e:e.slice(0,ez)+Ote}function eat(e,t,n){const r=t[e]??Ate[e];return r<=0?!1:r>=1?!0:n()<r}var tat=class{constructor(e){Gs(this,"deps");Gs(this,"queue",[]);Gs(this,"bytes",0);Gs(this,"droppedSinceFlush",0);Gs(this,"identityReady",!1);Gs(this,"timer",null);Gs(this,"disposed",!1);Gs(this,"pendingSends",[]);this.deps=e}enqueue(e){if(this.disposed)return;const t=nat(e);for(;this.queue.length>=this.deps.bufferCap;)this.queue.shift(),this.droppedSinceFlush++;this.queue.push(e),this.bytes+=t,this.identityReady&&this.maybeTrigger()}setIdentityReady(e){this.identityReady=e,e&&this.queue.length>0&&this.maybeTrigger()}async flush(){this.queue.length>0&&this.fire("flush"),await Promise.allSettled(this.pendingSends)}stats(){return{queued:this.queue.length,dropped:this.droppedSinceFlush}}async dispose(){this.disposed||(this.disposed=!0,this.timer&&(clearTimeout(this.timer),this.timer=null),await this.flush())}maybeTrigger(){const{maxRecords:e,maxBytes:t,maxWaitMs:n}=this.deps.batch;if(this.queue.length>=e){this.fire("records");return}if(this.bytes>=t){this.fire("bytes");return}this.timer==null&&(this.timer=setTimeout(()=>{this.timer=null,this.queue.length>0&&this.identityReady&&this.fire("time")},n))}fire(e){this.timer&&(clearTimeout(this.timer),this.timer=null);const t=this.queue,n=this.droppedSinceFlush;this.queue=[],this.bytes=0,this.droppedSinceFlush=0;const r=this.deps.onBatch({reason:e,records:t,droppedCarryover:n}).catch(()=>{});this.pendingSends.push(r),r.finally(()=>{this.pendingSends=this.pendingSends.filter(s=>s!==r)})}};function nat(e){var t,n;return(((t=e.msg)==null?void 0:t.length)??0)+(((n=e.meta_json)==null?void 0:n.length)??0)+200}var nz=[1e3,2e3,4e3];async function rat(e,t){const n=t.records.map(sat),r=JSON.stringify({__topic__:"clawd",__source__:e.source,__logs__:n,...t.droppedCarryover>0?{__tags__:{dropped:String(t.droppedCarryover)}}:{}});for(let s=0;s<nz.length;s++){s>0&&await iat(nz[s-1]);try{const i=await e.fetchImpl(e.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:r});if(i.status>=200&&i.status<300)return{sent:t.records.length,failed:0};if(i.status>=400&&i.status<500)return{sent:0,failed:t.records.length}}catch{}}return{sent:0,failed:t.records.length}}function sat(e){const t={};for(const[n,r]of Object.entries(e))r!=null&&(t[n]=typeof r=="string"?r:String(r));return t}function iat(e){return new Promise(t=>setTimeout(t,e))}function oat(e){const t={sent:0,dropped:0,queued:0,failed:0},n=e.fetchImpl??globalThis.fetch.bind(globalThis),r=e.now??Date.now,s={...Ate,...e.sampling??{}},i=e.homeDir===void 0?null:e.homeDir,o={...Kot,...e.batch??{}},l=e.bufferCap??Got;let c=e.identity,u=!1;if(e.endpoint==null)return{push:()=>{u||t.dropped++},flush:async()=>{},setIdentity:f=>{c=f},stats:()=>({...t}),dispose:async()=>{u=!0}};const d=e.endpoint,h=new tat({batch:o,bufferCap:l,now:r,onBatch:async f=>{const m=await rat({endpoint:d,source:e.source,fetchImpl:n},f);t.sent+=m.sent,t.failed+=m.failed}});return h.setIdentityReady(c!=null),{push(f){if(!u)try{if(!eat(f.level,s,Math.random)){t.dropped++;return}const m=aat(f,c,e.source,i,r);h.enqueue(m)}catch{}},async flush(){try{await h.flush()}catch{}},setIdentity(f){c=f,h.setIdentityReady(f!=null)},stats(){const f=h.stats();return{...t,queued:f.queued,dropped:t.dropped+f.dropped}},async dispose(){u=!0;try{await h.dispose()}catch{}}}}function aat(e,t,n,r,s){const i=e.meta?Zot(e.meta,r):void 0,o=i?JSON.stringify(i):void 0;return{ts:e.ts??s(),source:n,level:e.level,msg:Jot(e.msg),ownerPrincipalId:(t==null?void 0:t.ownerPrincipalId)??"__pending__",deviceId:(t==null?void 0:t.deviceId)??"__pending__",appVersion:(t==null?void 0:t.appVersion)??"__pending__",daemonVersion:t==null?void 0:t.daemonVersion,os:(t==null?void 0:t.os)??"unknown",meta_json:o,sessionId:e.sessionId}}function lat(e){const t=n=>{document.documentElement.classList.toggle("dark",n==="dark")};return t(e.theme.mode),e.onThemeChange(n=>t(n.mode))}function cat({filePath:e,oldString:t,newString:n,content:r}){const s=p.useMemo(()=>r!=null?r.split(/\r?\n/).map(i=>({type:"add",text:i})):uat(t??"",n??""),[t,n,r]);return a.jsxs("div",{"data-testid":"inline-diff",className:"min-w-0 max-w-full rounded-lg border border-bg-300/60 bg-bg-50 overflow-hidden text-[12px] font-mono",children:[a.jsx("div",{className:"flex min-w-0 items-center gap-2 px-3 py-1.5 border-b border-bg-300/40 bg-bg-100/30",children:a.jsx("span",{className:"min-w-0 text-text-400 truncate",title:e,children:e})}),a.jsx("div",{className:"max-h-[320px] max-w-full overflow-auto",children:s.map((i,o)=>a.jsxs("div",{"data-testid":`diff-line-${i.type}`,className:J("flex min-w-max gap-2 px-3 py-0.5 whitespace-pre",i.type==="add"?"bg-success/10 text-success":i.type==="remove"?"bg-error/10 text-error":"text-text-300"),children:[a.jsx("span",{className:"w-3 shrink-0 select-none opacity-60",children:i.type==="add"?"+":i.type==="remove"?"-":" "}),a.jsx("span",{className:"flex-1",children:i.text||" "})]},o))})]})}function uat(e,t){const n=e.split(/\r?\n/),r=t.split(/\r?\n/),s=n.length,i=r.length,o=Array.from({length:s+1},()=>new Array(i+1).fill(0));for(let d=s-1;d>=0;d--)for(let h=i-1;h>=0;h--)o[d][h]=n[d]===r[h]?o[d+1][h+1]+1:Math.max(o[d+1][h],o[d][h+1]);const l=[];let c=0,u=0;for(;c<s&&u<i;)n[c]===r[u]?(l.push({type:"equal",text:n[c]}),c++,u++):o[c+1][u]>=o[c][u+1]?(l.push({type:"remove",text:n[c]}),c++):(l.push({type:"add",text:r[u]}),u++);for(;c<s;)l.push({type:"remove",text:n[c++]});for(;u<i;)l.push({type:"add",text:r[u++]});return l}function dat({items:e}){return e.length===0?null:a.jsxs("div",{"data-testid":"todo-checklist",className:"rounded-lg border border-bg-300/60 bg-bg-50 px-3 py-2 text-[13px]",children:[a.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-text-400/70 mb-1.5",children:"Todos"}),a.jsx("ul",{className:"flex flex-col gap-1",children:e.map((t,n)=>{const r=t.status==="in_progress"&&t.activeForm||t.content;return a.jsxs("li",{"data-testid":`todo-item-${t.status}`,className:"flex items-start gap-2",children:[a.jsx(hat,{status:t.status}),a.jsx("span",{className:J("flex-1 leading-snug",t.status==="completed"?"text-text-400 line-through":t.status==="in_progress"?"text-text-100 font-medium":"text-text-200"),children:r})]},n)})})]})}function hat({status:e}){return e==="completed"?a.jsx(ui,{className:"w-3.5 h-3.5 text-success mt-0.5 shrink-0"}):e==="in_progress"?a.jsx(st,{className:"w-3.5 h-3.5 text-warning mt-0.5 shrink-0 animate-spin"}):a.jsx(OH,{className:"w-3.5 h-3.5 text-text-400 mt-0.5 shrink-0"})}function fat(e){const t=e??{};return Array.isArray(t.todos)?t.todos.map(n=>{if(!n||typeof n!="object")return null;const r=n,s=typeof r.content=="string"?r.content:"",i=r.status==="pending"||r.status==="in_progress"||r.status==="completed"?r.status:"pending",o=typeof r.activeForm=="string"?r.activeForm:void 0;return{content:s,status:i,activeForm:o}}).filter(n=>n!==null):[]}function pat({description:e,prompt:t,subagentType:n}){return a.jsxs("div",{"data-testid":"task-checklist",className:"rounded-lg border border-bg-300/60 bg-bg-50 px-3 py-2 text-[13px]",children:[a.jsxs("div",{className:"flex items-center gap-2 text-text-200 font-medium",children:[a.jsx(oa,{className:"w-3.5 h-3.5 text-accent shrink-0"}),a.jsx("span",{className:"truncate",children:e||"subagent task"}),n?a.jsx("span",{className:"shrink-0 px-1.5 py-0.5 rounded-md text-[10px] font-mono bg-accent/10 text-accent",children:n}):null]}),t?a.jsx("div",{className:"mt-1 text-[12px] text-text-400 leading-snug line-clamp-3",children:t}):null]})}function mat(e){const t=e??{};return{description:typeof t.description=="string"?t.description:"",prompt:typeof t.prompt=="string"?t.prompt:void 0,subagentType:typeof t.subagent_type=="string"?t.subagent_type:void 0}}const gat={render:({input:e})=>q.createElement(dat,{items:fat(e)})},xat={render:({input:e})=>{const{description:t,prompt:n,subagentType:r}=mat(e);return q.createElement(pat,{description:t,prompt:n,subagentType:r})}},rz={render:({input:e,output:t,error:n,pending:r,fileScope:s,onShareFile:i,onOpenInTab:o,onPreviewMarkdown:l})=>{const c=yat(e),u=c?q.createElement(cat,{filePath:c.filePath,oldString:c.oldString,newString:c.newString,content:c.content}):void 0;return q.createElement(gG,{tool:vat(e),input:e,output:t,error:n,pending:r,expandedBody:u,...s?{fileScope:s}:{},...i?{onShareFile:i}:{},...o?{onOpenInTab:o}:{},...l?{onPreviewMarkdown:l}:{}})}};function vat(e){const t=e??{};return"content"in t&&t.content!==void 0?"Write":("old_string"in t&&t.old_string!==void 0,"Edit")}function yat(e){const t=e??{},n=typeof t.file_path=="string"?t.file_path:null;if(!n)return null;const r=typeof t.old_string=="string"?t.old_string:void 0,s=typeof t.new_string=="string"?t.new_string:void 0,i=typeof t.content=="string"?t.content:void 0;return r==null&&s==null&&i==null?null:{filePath:n,oldString:r,newString:s,content:i}}for(const e of["claude",Ace])uh.register(e,"TodoWrite",gat),uh.register(e,"Task",xat),uh.register(e,"Edit",rz),uh.register(e,"Write",rz);const N2={};function bat({urlSource:e,hostOverride:t,notifier:n,credentialSource:r}){const[s]=p.useState(()=>{if(t)return null;const d=N2==null?void 0:N2.VITE_CLAWD_LOG_ENDPOINT;return oat({endpoint:d==="off"?null:d??"https://clawd-prod.cn-hangzhou.log.aliyuncs.com/logstores/app-logs/track",identity:null,source:"renderer",homeDir:null})}),[i]=p.useState(()=>t??qot({notifier:n,...s?{logClient:s}:{}})),[o,l]=p.useState(null),[c,u]=p.useState(null);return p.useEffect(()=>{let d=!1;return Promise.resolve(e.getUrl(i)).then(h=>{d||l(h)}).catch(h=>{d||u(h instanceof Error?h.message:String(h))}),()=>{d=!0}},[e,i]),p.useEffect(()=>lat(i),[i]),c?a.jsxs("div",{className:"p-8 max-w-xl font-sans text-text-100","data-testid":"standalone-error",children:[a.jsx("h2",{className:"text-lg font-semibold mb-2",children:"无法发现 daemon"}),a.jsx("p",{className:"text-destructive mb-3",children:c}),a.jsxs("p",{className:"text-text-400 mb-3",children:["请确认 ",a.jsx("code",{className:"font-mono",children:"clawd"})," 已启动 (",a.jsx("code",{className:"font-mono",children:"cd clawd && pnpm dev"}),"),它会写入"," ",a.jsx("code",{className:"font-mono",children:"~/.clawd/state.json"}),"。"]}),a.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-1.5 text-sm rounded-md border border-border bg-elevated hover:bg-bg-100",children:"重试"})]}):o?a.jsx("div",{"data-testid":"standalone-root","data-mode":"url"in o?"has-url":"needs-setup",children:a.jsx(q.StrictMode,{children:a.jsx(VU.Provider,{value:r??null,children:a.jsx(awe,{client:s,children:a.jsx(Nie,{host:i,children:a.jsx(Tle,{children:a.jsx($ot,{})})})})})})}):a.jsx("div",{className:"p-8 font-sans text-text-400","data-testid":"standalone-resolving",children:"正在发现 daemon…"})}function wat(e,t){const r=`${e.protocol==="https:"?"wss:":"ws:"}//${e.host}`;return t!=null&&t.devPath?`${r}${t.devPath}`:r}const E3="clawd-owner-web:session",sz="owner-web",_at="/app/session",Sat="ticket";class II extends Error{constructor(t){super(t),this.reason=t,this.name="OwnerSessionError"}}function kat(e){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(Sat);return n&&n.length>0?n:null}function iz(e){try{const t=JSON.parse(e.storage.getItem(E3)??"null");if(t&&typeof t.token=="string"&&typeof t.expiresAt=="number"&&t.expiresAt>e.now())return{token:t.token,expiresAt:t.expiresAt}}catch{}return null}async function Cat(e,t){try{const n=await e.fetch(_at,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:t}),cache:"no-store",credentials:"omit"});if(!n.ok)return null;const r=await n.json();if(typeof r.token=="string"&&typeof r.expiresAt=="number")return{token:r.token,expiresAt:r.expiresAt}}catch{}return null}async function Nat(e){const t=kat(e.location.hash);if(t){e.history.replaceState(null,"",`${e.location.pathname}${e.location.search}`);const r=await Cat(e,t);if(r)return e.storage.setItem(E3,JSON.stringify(r)),r;const s=iz(e);if(s)return s;throw new II("ticket-invalid")}const n=iz(e);if(n)return n;throw new II("no-session")}function jat(e){let t,n=null;const r=()=>(n??(n=Nat(e).then(s=>(t=s.token,s))),n);return{session:r,credentials:{profileId:sz,getToken:()=>t,invalidate:()=>{t=void 0;try{e.storage.removeItem(E3)}catch{}}},urlSource:{async getUrl(s){await r();const i=wat(e.location);return await GU(s).upsert({id:sz,name:"本机",mode:"localhost",url:i}),{url:i}}}}}function Eat({web:e}){const[t,n]=p.useState({kind:"connecting"});return p.useEffect(()=>{let r=!1;return e.session().then(()=>!r&&n("ready")).catch(s=>{r||n({kind:"reopen",reason:s instanceof II?s.reason:"no-session"})}),()=>{r=!0}},[e]),t!=="ready"?a.jsx(KU,{view:t}):a.jsx(bat,{urlSource:e.urlSource,credentialSource:e.credentials})}const oz=document.getElementById("root");if(oz){Xxe({name:"clawd-web",version:"unknown"});const e=jat({storage:window.sessionStorage,location:window.location,history:window.history,fetch:window.fetch.bind(window),now:()=>Date.now()});j2.createRoot(oz).render(a.jsx(q.StrictMode,{children:a.jsx(Eat,{web:e})}))}
|
package/dist/owner-ui/owner.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<meta name="referrer" content="no-referrer" />
|
|
7
7
|
<title>Clawd</title>
|
|
8
|
-
<script type="module" crossorigin src="/app/assets/owner-
|
|
8
|
+
<script type="module" crossorigin src="/app/assets/owner-wSPUawJR.js"></script>
|
|
9
9
|
<link rel="stylesheet" crossorigin href="/app/assets/owner-DkZN0eik.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body style="margin: 0">
|