@av-pi-studio/web-client 0.0.32 → 0.0.34
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/.tsbuildinfo +1 -1
- package/dist/web/assets/{BinaryFallbackViewer-D45LvgRU.js → BinaryFallbackViewer-HicqzbWd.js} +2 -2
- package/dist/web/assets/{BinaryFallbackViewer-D45LvgRU.js.map → BinaryFallbackViewer-HicqzbWd.js.map} +1 -1
- package/dist/web/assets/ChatPanel-CTnpkb2U.css +1 -0
- package/dist/web/assets/ChatPanel-XI36Imum.js +3 -0
- package/dist/web/assets/ChatPanel-XI36Imum.js.map +1 -0
- package/dist/web/assets/{CodeView-DKjlpq-m.js → CodeView-z3x4ATgx.js} +2 -2
- package/dist/web/assets/{CodeView-DKjlpq-m.js.map → CodeView-z3x4ATgx.js.map} +1 -1
- package/dist/web/assets/{FilePanel-CGmR13VT.js → FilePanel-VOhIehHw.js} +3 -3
- package/dist/web/assets/{FilePanel-CGmR13VT.js.map → FilePanel-VOhIehHw.js.map} +1 -1
- package/dist/web/assets/{ImageViewer-g8uyibCK.js → ImageViewer-BivcSG2D.js} +2 -2
- package/dist/web/assets/{ImageViewer-g8uyibCK.js.map → ImageViewer-BivcSG2D.js.map} +1 -1
- package/dist/web/assets/{MarkdownFileViewer-Cjch4tHP.js → MarkdownFileViewer-CcfSk7Qc.js} +2 -2
- package/dist/web/assets/{MarkdownFileViewer-Cjch4tHP.js.map → MarkdownFileViewer-CcfSk7Qc.js.map} +1 -1
- package/dist/web/assets/{TerminalPanel-D21QoVnF.js → TerminalPanel-KNfHGYYL.js} +2 -2
- package/dist/web/assets/{TerminalPanel-D21QoVnF.js.map → TerminalPanel-KNfHGYYL.js.map} +1 -1
- package/dist/web/assets/{TextViewer-BVDA29H4.js → TextViewer-DlvdoBEv.js} +2 -2
- package/dist/web/assets/{TextViewer-BVDA29H4.js.map → TextViewer-DlvdoBEv.js.map} +1 -1
- package/dist/web/assets/{VideoViewer-Bj8wu5hl.js → VideoViewer-BmTmnaOQ.js} +2 -2
- package/dist/web/assets/{VideoViewer-Bj8wu5hl.js.map → VideoViewer-BmTmnaOQ.js.map} +1 -1
- package/dist/web/assets/index-C5SpA_B-.js +3 -0
- package/dist/web/assets/index-C5SpA_B-.js.map +1 -0
- package/dist/web/assets/{index-ZP_-GPM5.css → index-D_2xgUa4.css} +1 -1
- package/dist/web/assets/{use-file-download-B8_UiD_5.js → use-file-download-t12JJGKT.js} +2 -2
- package/dist/web/assets/{use-file-download-B8_UiD_5.js.map → use-file-download-t12JJGKT.js.map} +1 -1
- package/dist/web/assets/{vendor-icons-DwowToH7.js → vendor-icons-BouiMPVM.js} +72 -37
- package/dist/web/assets/vendor-icons-BouiMPVM.js.map +1 -0
- package/dist/web/index.html +3 -3
- package/package.json +3 -3
- package/dist/web/assets/ChatPanel-CG_Yz_QI.js +0 -3
- package/dist/web/assets/ChatPanel-CG_Yz_QI.js.map +0 -1
- package/dist/web/assets/ChatPanel-Cz7YoXXW.css +0 -1
- package/dist/web/assets/index-CM7PrEq0.js +0 -3
- package/dist/web/assets/index-CM7PrEq0.js.map +0 -1
- package/dist/web/assets/vendor-icons-DwowToH7.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@av-pi-studio/web-client",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.34",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist"
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
"clean": "rm -rf dist *.tsbuildinfo"
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@av-pi-studio/client": "^0.0.
|
|
18
|
-
"@av-pi-studio/protocol": "^0.0.
|
|
17
|
+
"@av-pi-studio/client": "^0.0.34",
|
|
18
|
+
"@av-pi-studio/protocol": "^0.0.34",
|
|
19
19
|
"@codemirror/language": "^6.12.4",
|
|
20
20
|
"@codemirror/language-data": "^6.5.2",
|
|
21
21
|
"@codemirror/state": "^6.7.1",
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{j as t,r as h}from"./vendor-react-BoIQBqDW.js";import{c as z,d as ee,m as te}from"./vendor-query-AtKBh_Yt.js";import{t as M,u as x,a as O,D as ne,T as se,B as S}from"./index-CM7PrEq0.js";import{k as re,l as ae,m as oe,n as ie,o as le,p as ce,T as U,C as ue,q as de,r as me,s as he}from"./vendor-icons-DwowToH7.js";import{M as H}from"./markdown-D9FuaV1m.js";import{C}from"./vendor--os7hw7d.js";import{D as ge}from"./DiffView-DlVCPvLc.js";import"./vendor-overlays-UwLNGk04.js";import"./vendor-dnd-D9kA7FgH.js";import"./vendor-highlight-DCzuSv8g.js";import"./vendor-markdown-B8HSIhaA.js";const pe="_badge_jtokc_3",_e={badge:pe};function fe(e){switch(e){case"success":return{token:"statusSuccess"};case"error":return{token:"statusDanger"};case"muted":return{token:"foregroundMuted"}}}function xe({label:e,variant:n,className:s}){const{token:i}=fe(n),a=`var(--pi-color-${i})`;return t.jsx("span",{className:`${_e.badge}${s?` ${s}`:""}`,style:{backgroundColor:`color-mix(in srgb, ${a} 18%, transparent)`,borderColor:`color-mix(in srgb, ${a} 45%, transparent)`,color:a},children:e})}const ye={shell:U,read:ce,edit:le,write:ie,search:oe,fetch:ae,task:re};function je(e){return ye[e.kind]??U}function ve(e){return e.kind}function ke(e){switch(e.kind){case"read":case"write":case"edit":return e.path??null;default:return null}}function be(e){return e.kind==="write"||e.kind==="edit"||e.kind==="shell"}function we(e){const n=[];if(e.kind==="edit"&&e.diff)n.push({kind:"diff",patch:e.diff});else{const s=M(e);s&&n.push({kind:"code",text:s})}return e.output&&n.push({kind:"code",text:e.output}),n}function Ne(e){const n=M(e);if(!n)return"";switch(e.kind){case"read":case"write":case"edit":{const s=n.split("/");return s[s.length-1]||n}case"shell":return n.split(`
|
|
2
|
-
`,1)[0]??n;default:return n}}const Ie=500;let D;function Se(e,n,s,i){clearTimeout(D),D=setTimeout(()=>{D=void 0,e.invalidateQueries({queryKey:["file"]}),e.invalidateQueries({queryKey:["explorer"]}),n&&s&&n.connection.request("checkout_refresh_request",{cwd:s}).catch(()=>{})},Ie)}function Ce(e){let n=null;return s=>{if(n===null){if(s.event.kind!=="user_message"||s.event.messageId!==e)return!1;n=s.agentId}return s.agentId===n}}function L({sessionId:e,event:n,client:s,queryClient:i}){const a=x.getState();switch(a.applyStreamEvent(e,n),n.kind){case"turn_started":a.setStatus(e,"running");break;case"turn_completed":a.setStatus(e,"idle");break;case"turn_failed":a.setStatus(e,"error");break;case"turn_canceled":a.setStatus(e,"idle");break;case"tool_call":{if(n.status==="completed"&&be(n.tool)){const c=a.sessions[e],u=(c==null?void 0:c.cwd)||null;Se(i,s,u,ke(n.tool))}break}}}function De(e){const n=O(a=>a.client),s=x(a=>{var c;return((c=a.sessions[e])==null?void 0:c.agentId)??null}),i=z();h.useEffect(()=>!n||!s?void 0:n.agent(s).timeline.subscribe(c=>{L({sessionId:e,event:c,client:n,queryClient:i})}),[n,s,e,i])}const Te="_row_10uhr_3",$e="_who_10uhr_13",Ee="_user_10uhr_24",Re="_userPending_10uhr_31",Ae="_userFailed_10uhr_35",Be="_userImages_10uhr_41",Fe="_userImage_10uhr_41",Pe="_imageDialog_10uhr_57",ze="_imageDialogPreview_10uhr_61",Me="_assistant_10uhr_70",Oe="_streaming_10uhr_77",Ue="_streamingText_10uhr_81",He="_cursor_10uhr_86",Le="_blink_10uhr_1",Ke="_reasoning_10uhr_101",qe="_tool_10uhr_111",We="_toolHeader_10uhr_121",Ge="_toolChevron_10uhr_139",Ve="_toolChevronOpen_10uhr_145",Qe="_toolInlineDetail_10uhr_149",Xe="_toolBody_10uhr_159",Ye="_toolCode_10uhr_165",Je="_toolIcon_10uhr_176",Ze="_running_10uhr_182",et="_pulse_10uhr_1",tt="_completed_10uhr_187",nt="_error_10uhr_191",st="_toolLabel_10uhr_201",rt="_toolBadge_10uhr_206",at="_system_10uhr_219",r={row:Te,who:$e,user:Ee,userPending:Re,userFailed:Ae,userImages:Be,userImage:Fe,imageDialog:Pe,imageDialogPreview:ze,assistant:Me,streaming:Oe,streamingText:Ue,cursor:He,blink:Le,reasoning:Ke,tool:qe,toolHeader:We,toolChevron:Ge,toolChevronOpen:Ve,toolInlineDetail:Qe,toolBody:Xe,toolCode:Ye,toolIcon:Je,running:Ze,pulse:et,completed:tt,error:nt,toolLabel:st,toolBadge:rt,system:at};function ot({row:e}){return t.jsxs("div",{className:`${r.row} ${r.assistant}${e.streaming?` ${r.streaming}`:""}`,children:[t.jsx("span",{className:r.who,children:"assistant"}),e.streaming?t.jsxs("span",{className:r.streamingText,children:[e.text,t.jsx("span",{className:r.cursor,children:"▍"})]}):t.jsx(H,{text:e.text})]})}function it({row:e}){return t.jsxs("div",{className:`${r.row} ${r.reasoning}`,children:[t.jsx("span",{className:r.who,children:"thinking"}),e.streaming?t.jsxs("span",{className:r.streamingText,children:[e.text,t.jsx("span",{className:r.cursor,children:"▍"})]}):t.jsx(H,{text:e.text})]})}const lt={running:"muted",completed:"success",error:"error"};function ct({row:e}){const[n,s]=h.useState(!1),i=je(e.tool),a=Ne(e.tool),c=we(e.tool),u=c.length>0;return t.jsxs("div",{className:C(r.row,r.tool),children:[t.jsxs("button",{type:"button",className:r.toolHeader,onClick:()=>u&&s(d=>!d),"aria-expanded":u?n:void 0,disabled:!u,children:[u&&t.jsx(ue,{size:12,className:C(r.toolChevron,n&&r.toolChevronOpen)}),t.jsx("span",{className:C(r.toolIcon,r[e.status]),children:t.jsx(i,{size:14})}),t.jsx("span",{className:r.toolLabel,children:ve(e.tool)}),a&&t.jsx("span",{className:r.toolInlineDetail,title:a,children:a}),t.jsx(xe,{className:r.toolBadge,label:e.status,variant:lt[e.status]})]}),n&&u&&t.jsx("div",{className:r.toolBody,children:c.map((d,l)=>d.kind==="diff"?t.jsx(ge,{patch:d.patch},l):t.jsx("pre",{className:r.toolCode,children:d.text},l))})]})}function ut({row:e}){const[n,s]=h.useState(null),i=e.failed?r.userFailed:e.pending?r.userPending:"";return t.jsxs("div",{className:`${r.row} ${r.user}${i?` ${i}`:""}`,children:[t.jsxs("span",{className:r.who,children:["you",e.failed?" · failed to send":""]}),e.text,e.images&&e.images.length>0&&t.jsx("div",{className:r.userImages,children:e.images.map((a,c)=>{const u=`data:${a.mimeType??"image/png"};base64,${a.data??""}`;return t.jsx("img",{className:r.userImage,src:u,alt:"",role:"button",tabIndex:0,onClick:()=>s(u),onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&s(u)}},c)})}),t.jsx(ne,{open:n!==null,onOpenChange:a=>{a||s(null)},title:"Image",width:"auto",bare:!0,className:r.imageDialog,children:n&&t.jsx("img",{className:r.imageDialogPreview,src:n,alt:""})})]})}function dt({row:e}){return t.jsxs("div",{className:`${r.row} ${r.error}`,children:[t.jsx("span",{className:r.who,children:"error"}),e.text]})}function mt({row:e}){return t.jsx("div",{className:`${r.row} ${r.system}`,children:e.text})}const ht="_viewport_1byko_3",gt="_inner_1byko_10",pt="_rowWrap_1byko_15",_t="_empty_1byko_25",ft="_working_1byko_34",xt="_workingDots_1byko_43",f={viewport:ht,inner:gt,rowWrap:pt,empty:_t,working:ft,workingDots:xt},yt=40;function jt(e){switch(e.kind){case"user":return t.jsx(ut,{row:e});case"assistant":return t.jsx(ot,{row:e});case"reasoning":return t.jsx(it,{row:e});case"tool":return t.jsx(ct,{row:e});case"error":return t.jsx(dt,{row:e});case"system":return t.jsx(mt,{row:e})}}function vt({session:e}){const n=e.timeline.rows,s=e.status==="running",i=h.useRef(null),a=h.useRef(!0),c=h.useRef(0),u=ee({count:n.length,getScrollElement:()=>i.current,estimateSize:()=>48,overscan:8,getItemKey:l=>{var m;return((m=n[l])==null?void 0:m.id)??l},measureElement:(l,m,p)=>{if(l.offsetParent!==null)return te(l,m,p);const y=p.indexFromElement(l),w=p.options.getItemKey(y);return p.itemSizeCache.get(w)??p.options.estimateSize(y)}});function d(){const l=i.current;if(!l)return;const m=l.scrollHeight-l.scrollTop-l.clientHeight;a.current=m<yt}return h.useEffect(()=>{const l=n.length>c.current;c.current=n.length,l&&a.current&&u.scrollToIndex(n.length-1,{align:"end"})},[n.length,u]),n.length===0?t.jsx("div",{className:f.viewport,ref:i,children:s?t.jsxs("div",{className:f.working,role:"status","aria-live":"polite",children:[t.jsxs("span",{className:f.workingDots,"aria-hidden":"true",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]}),"Agent is working…"]}):t.jsx("div",{className:f.empty,children:"No messages yet — say something to start."})}):t.jsxs("div",{className:f.viewport,ref:i,onScroll:d,children:[t.jsx("div",{className:f.inner,style:{height:u.getTotalSize()},children:u.getVirtualItems().map(l=>{const m=n[l.index];return m?t.jsx("div",{ref:u.measureElement,"data-index":l.index,className:f.rowWrap,style:{transform:`translateY(${l.start}px)`},children:jt(m)},l.key):null})}),s&&t.jsxs("div",{className:f.working,role:"status","aria-live":"polite",children:[t.jsxs("span",{className:f.workingDots,"aria-hidden":"true",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]}),"Agent is working…"]})]})}const kt="_strip_5sm81_4",bt="_thumb_5sm81_11",wt="_remove_5sm81_28",T={strip:kt,thumb:bt,remove:wt};function Nt({images:e,onRemove:n}){return e.length===0?null:t.jsx("div",{className:T.strip,children:e.map((s,i)=>t.jsxs("div",{className:T.thumb,children:[t.jsx("img",{src:s.thumbUrl,alt:""}),t.jsx("button",{type:"button",className:T.remove,title:"Remove",onClick:()=>n(i),children:"×"})]},i))})}function It(e){const{promise:n,resolve:s,reject:i}=Promise.withResolvers(),a=new FileReader;return a.onload=()=>{const c=a.result;if(typeof c!="string"){i(new Error("Unexpected FileReader result"));return}const u=c.indexOf(","),d=u>=0?c.slice(u+1):c;s({mimeType:e.type,data:d,thumbUrl:c})},a.onerror=()=>i(a.error??new Error("Failed to read file")),a.readAsDataURL(e),n}const St="_composer_1ll3p_1",Ct="_inputArea_1ll3p_13",Dt="_textarea_1ll3p_21",Tt="_attachBtn_1ll3p_28",$t="_hiddenFileInput_1ll3p_32",Et="_actions_1ll3p_36",j={composer:St,inputArea:Ct,textarea:Dt,attachBtn:Tt,hiddenFileInput:$t,actions:Et},Rt=160;function P(e){e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,Rt)}px`}function At(e){return typeof e!="object"||e===null||!("type"in e)||e.type!=="agent_stream"?!1:"agentId"in e&&typeof e.agentId=="string"&&"event"in e}function Bt({sessionId:e}){const n=O(o=>o.client),s=x(o=>o.sessions[e]),i=x(o=>o.bindAgent),a=x(o=>o.addOptimisticUserMessage),c=x(o=>o.markUserMessageFailed),u=x(o=>o.setCwd),d=z(),[l,m]=h.useState(""),[p,y]=h.useState([]),[w,E]=h.useState(!1),N=h.useRef(null),R=h.useRef(null),K=(s==null?void 0:s.status)==="running",q=!!n&&!w&&(l.trim().length>0||p.length>0);async function A(o){if(o.type.startsWith("image/"))try{const g=await It(o);y(_=>[..._,g])}catch{}}function W(o){for(const g of o.target.files??[])A(g);o.target.value=""}function G(o){for(const g of o.clipboardData.items)if(g.type.startsWith("image/")){o.preventDefault();const _=g.getAsFile();_&&A(_)}}function V(o){y(g=>g.filter((_,v)=>v!==o))}function Q(o){m(o.target.value),P(o.target)}function X(o){o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),B())}async function B(){if(!n||!s||w)return;const o=l.trim();if(!o&&p.length===0)return;m(""),N.current&&P(N.current);const g=p;y([]);const _=o||"Describe this image",v=g.length>0?g.map(b=>({mimeType:b.mimeType,data:b.data})):void 0,k=crypto.randomUUID();a(e,k,_,v),E(!0);try{if(s.agentId)await n.agent(s.agentId).send(_,{clientMessageId:k,images:v});else{const b=s.cwd||"~";u(e,b);const J=Ce(k),Z=n.connection.onSessionMessage(I=>{!At(I)||!J(I)||L({sessionId:e,event:I.event,client:n,queryClient:d})});let F;try{F=await n.createAgent({config:{provider:"pi",cwd:b},initialPrompt:_,clientMessageId:k,images:v,labels:{}})}finally{Z()}i(e,F.agentId)}}catch{c(e,k)}finally{E(!1)}}function Y(){s!=null&&s.agentId&&(n==null||n.agent(s.agentId).interrupt())}return t.jsxs("div",{className:j.composer,children:[t.jsxs("div",{className:j.inputArea,children:[t.jsx(se,{ref:N,className:j.textarea,rows:1,value:l,placeholder:"Ask anything… (Enter to send, Shift+Enter for newline)",onChange:Q,onKeyDown:X,onPaste:G}),t.jsx(Nt,{images:p,onRemove:V})]}),t.jsx(S,{className:j.attachBtn,variant:"ghost",size:"md",iconOnly:!0,title:"Attach image",onClick:()=>{var o;return(o=R.current)==null?void 0:o.click()},children:t.jsx(de,{size:16})}),t.jsx("input",{ref:R,className:j.hiddenFileInput,type:"file",accept:"image/*",multiple:!0,onChange:W}),t.jsxs("div",{className:j.actions,children:[t.jsx(S,{size:"sm",disabled:!q,onClick:()=>void B(),leftIcon:t.jsx(me,{size:14}),children:"Send"}),K&&t.jsx(S,{size:"sm",variant:"destructive",onClick:Y,leftIcon:t.jsx(he,{size:14}),children:"Stop"})]})]})}const Ft="_panel_12s9l_1",Pt="_empty_12s9l_8",$={panel:Ft,empty:Pt};function Qt({tab:e}){const{sessionId:n}=e.data,s=x(i=>i.sessions[n]);return De(n),s?t.jsxs("div",{className:$.panel,children:[t.jsx(vt,{session:s}),t.jsx(Bt,{sessionId:s.id})]}):t.jsx("div",{className:$.panel,children:t.jsx("div",{className:$.empty,children:"Session not found."})})}export{Qt as ChatPanel};
|
|
3
|
-
//# sourceMappingURL=ChatPanel-CG_Yz_QI.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ChatPanel-CG_Yz_QI.js","sources":["../../../src/ui/status-badge.ts","../../../src/components/primitives/StatusBadge.tsx","../../../src/timeline/tool-mapping.ts","../../../src/lib/connection/files-changed.ts","../../../src/hooks/agent-stream-events.ts","../../../src/hooks/use-agent-stream.ts","../../../src/features/chat/rows/AssistantRow.tsx","../../../src/features/chat/rows/ReasoningRow.tsx","../../../src/features/chat/rows/ToolCard.tsx","../../../src/features/chat/rows/UserRow.tsx","../../../src/features/chat/rows/ErrorRow.tsx","../../../src/features/chat/rows/SystemRow.tsx","../../../src/features/chat/Timeline.tsx","../../../src/features/chat/Attachments.tsx","../../../src/features/chat/Composer.tsx","../../../src/features/chat/ChatPanel.tsx"],"sourcesContent":["// StatusBadge + Alert variant contracts.\n// ui-components.md § Surfaces / badges / chips / avatars\n\nexport type StatusBadgeVariant = \"success\" | \"error\" | \"muted\";\n\n// Single semantic token per variant — text color AND a translucent tint of the SAME token as\n// background (matches `ChangesPanel.module.css`'s `.added`/`.modified`/`.deleted` convention).\n// Never split bg/border/text across different token families (e.g. `success` vs `statusSuccess`)\n// — they can diverge in the theme (dark mode's `success` aliases the blue accent, not green),\n// producing a badge with mismatched border/background colors.\nexport type BadgeTokens = {\n token: string;\n};\n\nexport function statusBadgeTokens(variant: StatusBadgeVariant): BadgeTokens {\n switch (variant) {\n case \"success\":\n return { token: \"statusSuccess\" };\n case \"error\":\n return { token: \"statusDanger\" };\n case \"muted\":\n return { token: \"foregroundMuted\" };\n }\n}\n\nexport type AlertVariant = \"default\" | \"info\" | \"success\" | \"warning\" | \"error\";\n\nexport type AlertIconInfo = {\n /** Lucide icon name string for the alert variant. */\n icon: string;\n /** Theme token key for the icon/border/title accent color. */\n accentToken: string;\n};\n\nexport function alertIconInfo(variant: AlertVariant): AlertIconInfo {\n switch (variant) {\n case \"default\":\n return { icon: \"info\", accentToken: \"foregroundMuted\" };\n case \"info\":\n return { icon: \"info\", accentToken: \"accent\" };\n case \"success\":\n return { icon: \"check-circle\", accentToken: \"success\" };\n case \"warning\":\n return { icon: \"triangle-alert\", accentToken: \"statusWarning\" };\n case \"error\":\n return { icon: \"circle-x\", accentToken: \"destructive\" };\n }\n}\n\n// AttachmentPill remove-button visibility — mirrors hover-to-show pattern.\nexport function attachmentPillRemoveVisible(\n isNativeCtx: boolean,\n isCompact: boolean,\n hovered: boolean,\n): boolean {\n return isNativeCtx || isCompact || hovered;\n}\n","/**\n * StatusBadge — small rounded pill with variant coloring.\n * ui-components.md § Surfaces / badges / chips / avatars\n */\n\nimport { type ReactNode } from \"react\";\nimport styles from \"./StatusBadge.module.css\";\nimport { statusBadgeTokens, type StatusBadgeVariant } from \"@pi-studio-ui/ui/status-badge.js\";\n\nexport interface StatusBadgeProps {\n label: ReactNode;\n variant: StatusBadgeVariant;\n className?: string;\n}\n\nexport function StatusBadge({ label, variant, className }: StatusBadgeProps) {\n const { token } = statusBadgeTokens(variant);\n const color = `var(--pi-color-${token})`;\n return (\n <span\n className={`${styles.badge}${className ? ` ${className}` : \"\"}`}\n style={{\n backgroundColor: `color-mix(in srgb, ${color} 18%, transparent)`,\n borderColor: `color-mix(in srgb, ${color} 45%, transparent)`,\n color,\n }}\n >\n {label}\n </span>\n );\n}\n","/**\n * tool.kind → display label + icon. Scoped to the protocol's `ToolCallDetail` union\n * (shell/read/edit/write/search/fetch/task) — POC_TO_APP_PLAN_UI.md §3 `timeline/tool-mapping.ts`.\n */\n\nimport type { ToolCallDetail } from \"@av-pi-studio/protocol\";\nimport {\n Terminal,\n Eye,\n Pencil,\n FilePlus,\n Search,\n Globe,\n ListTree,\n type LucideIcon,\n} from \"lucide-react\";\nimport { toolDetailText } from \"./row-model.js\";\n\nconst ICON_BY_KIND: Record<ToolCallDetail[\"kind\"], LucideIcon> = {\n shell: Terminal,\n read: Eye,\n edit: Pencil,\n write: FilePlus,\n search: Search,\n fetch: Globe,\n task: ListTree,\n};\n\nexport function toolIcon(tool: ToolCallDetail): LucideIcon {\n return ICON_BY_KIND[tool.kind] ?? Terminal;\n}\n\n/** Human label for a tool card header, e.g. \"shell\", \"edit\". */\nexport function toolLabel(tool: ToolCallDetail): string {\n return tool.kind;\n}\n\n/** One-line detail summary for a tool card (POC: `t.command || t.path || t.query || …`). */\nexport function toolSummary(tool: ToolCallDetail): string {\n return toolDetailText(tool);\n}\n\n/** File path a tool touched, if any — used to target `filesChanged` invalidation (§4.5). */\nexport function toolFilePath(tool: ToolCallDetail): string | null {\n switch (tool.kind) {\n case \"read\":\n case \"write\":\n case \"edit\":\n return tool.path ?? null;\n default:\n return null;\n }\n}\n\n/** True for tool kinds whose completion should invalidate open file/diff/explorer/git queries. */\nexport function toolMutatesFiles(tool: ToolCallDetail): boolean {\n return tool.kind === \"write\" || tool.kind === \"edit\" || tool.kind === \"shell\";\n}\n\n/**\n * Expandable detail body for a tool card, as an ordered list of sections. `diff` renders as a\n * `<DiffView>`; `code` renders in a monospace block. Order: input detail (command/path/query/…)\n * first, then tool output (stdout, file content, etc.) if present. Empty array = header-only card\n * with nothing worth expanding.\n */\nexport type ToolBodySection = { kind: \"diff\"; patch: string } | { kind: \"code\"; text: string };\n\nexport function toolBody(tool: ToolCallDetail): ToolBodySection[] {\n const sections: ToolBodySection[] = [];\n if (tool.kind === \"edit\" && tool.diff) sections.push({ kind: \"diff\", patch: tool.diff });\n else {\n const text = toolDetailText(tool);\n if (text) sections.push({ kind: \"code\", text });\n }\n if (tool.output) sections.push({ kind: \"code\", text: tool.output });\n return sections;\n}\n\n/** Concise inline label shown in the collapsed header (basename for paths, first line for commands). */\nexport function toolInlineDetail(tool: ToolCallDetail): string {\n const text = toolDetailText(tool);\n if (!text) return \"\";\n switch (tool.kind) {\n case \"read\":\n case \"write\":\n case \"edit\": {\n const parts = text.split(\"/\");\n return parts[parts.length - 1] || text;\n }\n case \"shell\": {\n const firstLine = text.split(\"\\n\", 1)[0] ?? text;\n return firstLine;\n }\n default:\n return text;\n }\n}\n","/**\n * `filesChanged` signal — invalidates the file/diff/explorer query caches after a completed\n * write/edit/shell tool call (POC `scheduleFileRefresh`/`reloadOpenFileTabs`, chat.html\n * ~line 1070-1092, POC_TO_APP_PLAN_UI.md §4.3/§4.5/§5). Debounced ~500ms to coalesce a burst of\n * tool completions (POC used `setTimeout(...,600)`/`400`).\n *\n * The daemon does NOT push a `checkout_status_update` automatically after a git-affecting tool\n * completion, so this module also fires an explicit `checkout_refresh_request` for the active\n * cwd — `ChangesPanel`/`FileExplorer` then pick up the resulting push/refetch reactively, since\n * they're already subscribed (`use-checkout-status.ts`) or query-cache-driven (`use-explorer.ts`).\n *\n * NOTE (follow-up, cross-slice): this module only *exports* the invalidation function. The actual\n * call site — wiring this into the timeline reducer's `tool_call` handling on `status:\"completed\"`\n * for `toolMutatesFiles(tool) === true` — belongs to the chat/session-store slice (built in\n * parallel) or the top-level app wiring; do not import/call it from `timeline/reducer.ts` here,\n * that file is a shared contract file owned across slices.\n */\n\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport type { PiStudioClient } from \"@av-pi-studio/client\";\n\nconst DEBOUNCE_MS = 500;\nlet pendingTimer: ReturnType<typeof setTimeout> | undefined;\n\n/**\n * Invalidate file/diff/explorer TanStack Query caches and refresh git status for `cwd`.\n * Debounced: repeated calls within `DEBOUNCE_MS` coalesce into a single invalidation pass.\n *\n * `toolFilePath` is accepted for future path-scoped invalidation (POC `reloadOpenFileTabs`\n * matched by path suffix) but the current pass invalidates the whole `file`/`explorer` query\n * families — TanStack Query dedupes refetches for inactive queries, so this is cheap and correct\n * even when the path is unknown.\n */\nexport function invalidateAfterToolCompletion(\n queryClient: QueryClient,\n client: PiStudioClient | null,\n cwd: string | null,\n _toolFilePath: string | null,\n): void {\n clearTimeout(pendingTimer);\n pendingTimer = setTimeout(() => {\n pendingTimer = undefined;\n void queryClient.invalidateQueries({ queryKey: [\"file\"] });\n void queryClient.invalidateQueries({ queryKey: [\"explorer\"] });\n if (client && cwd) {\n void client.connection.request(\"checkout_refresh_request\", { cwd }).catch(() => {});\n }\n }, DEBOUNCE_MS);\n}\n","/**\n * Shared `AgentStreamEvent` → store-update logic, used both by the live subscription\n * (`use-agent-stream.ts`) and by the live first-turn apply in `Composer.tsx` (see its comment for\n * why: `create_agent_request` blocks until the whole first turn completes, so the timeline is fed\n * from the raw broadcast as events arrive rather than from a not-yet-attached subscription).\n */\n\nimport type { PiStudioClient } from \"@av-pi-studio/client\";\nimport type { AgentStreamEvent } from \"@av-pi-studio/protocol\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport { useSessionStore } from \"@pi-studio-ui/stores/session-store.js\";\nimport { toolMutatesFiles, toolFilePath } from \"@pi-studio-ui/timeline/tool-mapping.js\";\nimport { invalidateAfterToolCompletion } from \"@pi-studio-ui/lib/connection/files-changed.js\";\n\nexport interface ApplyAgentStreamEventArgs {\n sessionId: string;\n event: AgentStreamEvent;\n client: PiStudioClient;\n queryClient: QueryClient;\n}\n\n/**\n * Correlates first-turn `agent_stream` broadcasts with the agent a specific `createAgent` call\n * just spawned. `create_agent_request` doesn't resolve with the new `agentId` until the whole\n * first turn completes, so `Composer.handleSend` watches the raw broadcast and applies frames as\n * they arrive — but the socket is shared across every open session, and another session's agent\n * can be mid-turn concurrently. The first `agent_stream` frame observed after subscribing is\n * therefore NOT necessarily this call's own agent. Only latch onto an `agentId` once its\n * canonical `user_message` echo is seen (`messageId === clientMessageId`, minted by this call and\n * echoed back verbatim by the daemon — `agent-service.ts` `runTurn`), then accept only further\n * frames carrying that same `agentId`. Returns a predicate reporting whether a given frame belongs\n * to this turn and should be applied.\n */\nexport function createFirstTurnGate(\n clientMessageId: string,\n): (msg: { agentId: string; event: AgentStreamEvent }) => boolean {\n let liveAgentId: string | null = null;\n return (msg) => {\n if (liveAgentId === null) {\n if (msg.event.kind !== \"user_message\" || msg.event.messageId !== clientMessageId) return false;\n liveAgentId = msg.agentId;\n }\n return msg.agentId === liveAgentId;\n };\n}\n\nexport function applyAgentStreamEvent({\n sessionId,\n event,\n client,\n queryClient,\n}: ApplyAgentStreamEventArgs): void {\n const sessionStore = useSessionStore.getState();\n sessionStore.applyStreamEvent(sessionId, event);\n switch (event.kind) {\n case \"turn_started\":\n sessionStore.setStatus(sessionId, \"running\");\n break;\n case \"turn_completed\":\n sessionStore.setStatus(sessionId, \"idle\");\n break;\n case \"turn_failed\":\n sessionStore.setStatus(sessionId, \"error\");\n break;\n case \"turn_canceled\":\n sessionStore.setStatus(sessionId, \"idle\");\n break;\n case \"tool_call\": {\n if (event.status === \"completed\" && toolMutatesFiles(event.tool)) {\n const session = sessionStore.sessions[sessionId];\n const cwd = session?.cwd || null;\n invalidateAfterToolCompletion(queryClient, client, cwd, toolFilePath(event.tool));\n }\n break;\n }\n default:\n break;\n }\n}\n","/**\n * Live timeline subscription for a chat session. Subscribes to\n * `client.agent(agentId).timeline.subscribe` whenever both the connection's `client` and the\n * session's `agentId` are available, routing every event through `applyAgentStreamEvent`\n * (POC_TO_APP_PLAN_UI.md §4.3). Also mirrors the POC's `handleAgentStream` turn-lifecycle →\n * `session.status` transitions so the Composer's Stop button and the session-list status dot\n * stay live.\n *\n * NOTE: this only covers events that arrive *after* the subscription attaches, which requires a\n * bound `agentId`. The daemon runs the whole first turn of a brand-new agent *before*\n * `create_agent_request` resolves, so `Composer.handleSend` applies that first turn live from the\n * raw broadcast (latching the agent id from the first `agent_stream` frame it sees) and only\n * calls `bindAgent` once the RPC resolves — after the turn is already applied. This hook therefore\n * attaches only in time for *follow-up* turns, which is exactly what avoids double-applying the\n * first turn (the reducer is not event-id-idempotent).\n */\n\nimport { useEffect } from \"react\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { useConnectionStore } from \"@pi-studio-ui/lib/connection/connection-store.js\";\nimport { useSessionStore } from \"@pi-studio-ui/stores/session-store.js\";\nimport { applyAgentStreamEvent } from \"./agent-stream-events.js\";\n\nexport function useAgentStream(sessionId: string): void {\n const client = useConnectionStore((s) => s.client);\n const agentId = useSessionStore((s) => s.sessions[sessionId]?.agentId ?? null);\n const queryClient = useQueryClient();\n\n useEffect(() => {\n if (!client || !agentId) return;\n\n const unsubscribe = client.agent(agentId).timeline.subscribe((event) => {\n applyAgentStreamEvent({ sessionId, event, client, queryClient });\n });\n\n return unsubscribe;\n }, [client, agentId, sessionId, queryClient]);\n}\n","/**\n * Assistant message row (POC `.msg.assistant`, POC_TO_APP_PLAN_UI.md §4.3). While streaming,\n * renders plain text with a blinking cursor — re-parsing markdown on every token would be\n * wasteful (§6 Performance strategy). Once `turn_completed` finalizes the row (`streaming:\n * false`), it renders through `<Markdown>`.\n */\n\nimport type { AssistantRow as AssistantRowModel } from \"@pi-studio-ui/timeline/row-model.js\";\nimport { Markdown } from \"@pi-studio-ui/timeline/markdown.js\";\nimport styles from \"./rows.module.css\";\n\nexport interface AssistantRowProps {\n row: AssistantRowModel;\n}\n\nexport function AssistantRow({ row }: AssistantRowProps) {\n return (\n <div className={`${styles.row} ${styles.assistant}${row.streaming ? ` ${styles.streaming}` : \"\"}`}>\n <span className={styles.who}>assistant</span>\n {row.streaming ? (\n <span className={styles.streamingText}>\n {row.text}\n <span className={styles.cursor}>▍</span>\n </span>\n ) : (\n <Markdown text={row.text} />\n )}\n </div>\n );\n}\n","/**\n * Reasoning row — dimmer/italic styling, visually distinct from assistant replies (POC\n * `.msg.reasoning`, POC_TO_APP_PLAN_UI.md §4.3). Streams as plain text with a cursor, same\n * rationale as `AssistantRow`.\n */\n\nimport type { ReasoningRow as ReasoningRowModel } from \"@pi-studio-ui/timeline/row-model.js\";\nimport { Markdown } from \"@pi-studio-ui/timeline/markdown.js\";\nimport styles from \"./rows.module.css\";\n\nexport interface ReasoningRowProps {\n row: ReasoningRowModel;\n}\n\nexport function ReasoningRow({ row }: ReasoningRowProps) {\n return (\n <div className={`${styles.row} ${styles.reasoning}`}>\n <span className={styles.who}>thinking</span>\n {row.streaming ? (\n <span className={styles.streamingText}>\n {row.text}\n <span className={styles.cursor}>▍</span>\n </span>\n ) : (\n <Markdown text={row.text} />\n )}\n </div>\n );\n}\n","/**\n * Tool call card — icon + label + inline detail + status badge header, with an expandable body\n * (POC `.msg.tool`, POC_TO_APP_PLAN_UI.md §4.3). Collapsed by default; clicking the header reveals\n * the full detail as an ordered list of sections: input detail (`edit` diffs render through the\n * shared `<DiffView>`; shell command/path/query/url/task description render in a monospace block)\n * followed by tool output (stdout, file content, etc.), when present. Cards with no expandable\n * sections (`toolBody` → `[]`) show only the header. The virtualized timeline re-measures on\n * expand via `measureElement`, so height changes need no special handling here.\n */\n\nimport { useState } from \"react\";\nimport { ChevronRight } from \"lucide-react\";\nimport { clsx } from \"clsx\";\nimport { StatusBadge } from \"@pi-studio-ui/components/primitives/StatusBadge.js\";\nimport { DiffView } from \"@pi-studio-ui/features/files/DiffView.js\";\nimport { toolIcon, toolLabel, toolInlineDetail, toolBody } from \"@pi-studio-ui/timeline/tool-mapping.js\";\nimport type { ToolRow } from \"@pi-studio-ui/timeline/row-model.js\";\nimport styles from \"./rows.module.css\";\n\nexport interface ToolCardProps {\n row: ToolRow;\n}\n\nconst BADGE_VARIANT = {\n running: \"muted\",\n completed: \"success\",\n error: \"error\",\n} as const;\n\nexport function ToolCard({ row }: ToolCardProps) {\n const [expanded, setExpanded] = useState(false);\n const Icon = toolIcon(row.tool);\n const inlineDetail = toolInlineDetail(row.tool);\n const body = toolBody(row.tool);\n const hasBody = body.length > 0;\n\n return (\n <div className={clsx(styles.row, styles.tool)}>\n <button\n type=\"button\"\n className={styles.toolHeader}\n onClick={() => hasBody && setExpanded((v) => !v)}\n aria-expanded={hasBody ? expanded : undefined}\n disabled={!hasBody}\n >\n {hasBody && (\n <ChevronRight\n size={12}\n className={clsx(styles.toolChevron, expanded && styles.toolChevronOpen)}\n />\n )}\n <span className={clsx(styles.toolIcon, styles[row.status])}>\n <Icon size={14} />\n </span>\n <span className={styles.toolLabel}>{toolLabel(row.tool)}</span>\n {inlineDetail && (\n <span className={styles.toolInlineDetail} title={inlineDetail}>\n {inlineDetail}\n </span>\n )}\n <StatusBadge className={styles.toolBadge} label={row.status} variant={BADGE_VARIANT[row.status]} />\n </button>\n {expanded && hasBody && (\n <div className={styles.toolBody}>\n {body.map((section, i) =>\n section.kind === \"diff\" ? (\n <DiffView key={i} patch={section.patch} />\n ) : (\n <pre key={i} className={styles.toolCode}>\n {section.text}\n </pre>\n ),\n )}\n </div>\n )}\n </div>\n );\n}\n","/**\n * User message row — plain text + optional image thumbnails (POC `.msg.user`,\n * POC_TO_APP_PLAN_UI.md §4.3/§4.4). Images render at up to 200×150, matching the POC's inline\n * `userBubble.appendChild(img)` styling. Clicking a thumbnail opens it full-size in a `Dialog`.\n *\n * `row.pending` (optimistic echo not yet confirmed by the server's `user_message` broadcast —\n * see Composer.tsx) dims the row via CSS; `row.failed` (the RPC rejected before confirmation\n * ever arrived) tints it toward the error color and appends a \"failed to send\" label instead.\n * Both are terminal states set once by the reducer — this component only reflects them.\n */\n\nimport { useState } from \"react\";\nimport { Dialog } from \"@pi-studio-ui/components/primitives/Dialog.js\";\nimport type { UserRow as UserRowModel } from \"@pi-studio-ui/timeline/row-model.js\";\nimport styles from \"./rows.module.css\";\n\nexport interface UserRowProps {\n row: UserRowModel;\n}\n\nexport function UserRow({ row }: UserRowProps) {\n const [openedSrc, setOpenedSrc] = useState<string | null>(null);\n\n const stateClass = row.failed ? styles.userFailed : row.pending ? styles.userPending : \"\";\n\n return (\n <div className={`${styles.row} ${styles.user}${stateClass ? ` ${stateClass}` : \"\"}`}>\n <span className={styles.who}>you{row.failed ? \" · failed to send\" : \"\"}</span>\n {row.text}\n {row.images && row.images.length > 0 && (\n <div className={styles.userImages}>\n {row.images.map((img, i) => {\n const src = `data:${img.mimeType ?? \"image/png\"};base64,${img.data ?? \"\"}`;\n return (\n <img\n key={i}\n className={styles.userImage}\n src={src}\n alt=\"\"\n role=\"button\"\n tabIndex={0}\n onClick={() => setOpenedSrc(src)}\n onKeyDown={(ev) => {\n if (ev.key === \"Enter\" || ev.key === \" \") setOpenedSrc(src);\n }}\n />\n );\n })}\n </div>\n )}\n <Dialog\n open={openedSrc !== null}\n onOpenChange={(open) => {\n if (!open) setOpenedSrc(null);\n }}\n title=\"Image\"\n width=\"auto\"\n bare\n className={styles.imageDialog}\n >\n {openedSrc && <img className={styles.imageDialogPreview} src={openedSrc} alt=\"\" />}\n </Dialog>\n </div>\n );\n}\n","/**\n * Error row — red-tinted block (POC `.msg.err`, POC_TO_APP_PLAN_UI.md §4.3), used for\n * `turn_failed`/`error` stream events.\n */\n\nimport type { ErrorRow as ErrorRowModel } from \"@pi-studio-ui/timeline/row-model.js\";\nimport styles from \"./rows.module.css\";\n\nexport interface ErrorRowProps {\n row: ErrorRowModel;\n}\n\nexport function ErrorRow({ row }: ErrorRowProps) {\n return (\n <div className={`${styles.row} ${styles.error}`}>\n <span className={styles.who}>error</span>\n {row.text}\n </div>\n );\n}\n","/**\n * System row — muted/italic styling (POC's `turn_canceled` \"(canceled)\" reasoning-styled bubble,\n * POC_TO_APP_PLAN_UI.md §4.3), used for canceled-turn markers and other system notices.\n */\n\nimport type { SystemRow as SystemRowModel } from \"@pi-studio-ui/timeline/row-model.js\";\nimport styles from \"./rows.module.css\";\n\nexport interface SystemRowProps {\n row: SystemRowModel;\n}\n\nexport function SystemRow({ row }: SystemRowProps) {\n return <div className={`${styles.row} ${styles.system}`}>{row.text}</div>;\n}\n","/**\n * Virtualized timeline viewport — TanStack Virtual over `session.timeline.rows` with\n * variable-size rows (POC `.chat-area`, POC_TO_APP_PLAN_UI.md §4.3/§6). Auto-scrolls to the\n * bottom on new rows unless the user has scrolled up more than 40px from the bottom; re-sticks\n * whenever the row count grows from a user's own send (POC's forced `scrollTop = scrollHeight`,\n * fixed to respect manual scroll-up).\n */\n\nimport { useEffect, useRef } from \"react\";\nimport { measureElement as measureElementDefault, useVirtualizer } from \"@tanstack/react-virtual\";\nimport type { SessionEntry } from \"@pi-studio-ui/stores/session-store.js\";\nimport type { TimelineRow } from \"@pi-studio-ui/timeline/row-model.js\";\nimport { AssistantRow } from \"./rows/AssistantRow.js\";\nimport { ReasoningRow } from \"./rows/ReasoningRow.js\";\nimport { ToolCard } from \"./rows/ToolCard.js\";\nimport { UserRow } from \"./rows/UserRow.js\";\nimport { ErrorRow } from \"./rows/ErrorRow.js\";\nimport { SystemRow } from \"./rows/SystemRow.js\";\nimport styles from \"./Timeline.module.css\";\n\nexport interface TimelineProps {\n session: SessionEntry;\n}\n\nconst STICK_THRESHOLD_PX = 40;\n\nfunction renderRow(row: TimelineRow) {\n switch (row.kind) {\n case \"user\":\n return <UserRow row={row} />;\n case \"assistant\":\n return <AssistantRow row={row} />;\n case \"reasoning\":\n return <ReasoningRow row={row} />;\n case \"tool\":\n return <ToolCard row={row} />;\n case \"error\":\n return <ErrorRow row={row} />;\n case \"system\":\n return <SystemRow row={row} />;\n }\n}\n\nexport function Timeline({ session }: TimelineProps) {\n const rows = session.timeline.rows;\n const running = session.status === \"running\";\n const scrollRef = useRef<HTMLDivElement>(null);\n const stickToBottomRef = useRef(true);\n // Init to 0 (not `rows.length`) so a freshly-mounted tab with existing history — a brand-new\n // chat tab switch or a session restored from disk — still counts as \"grew\" on its first effect\n // run and scrolls to the last message, instead of opening at the top.\n const prevRowCountRef = useRef(0);\n\n const virtualizer = useVirtualizer({\n count: rows.length,\n getScrollElement: () => scrollRef.current,\n estimateSize: () => 48,\n overscan: 8,\n getItemKey: (index) => rows[index]?.id ?? index,\n // `TabPanelHost` keeps inactive chat tabs mounted under `display:none` rather than\n // unmounting them (so switching tabs preserves scroll position — see its own doc comment).\n // But a `display:none` ancestor collapses every row to a 0×0 border box, and the default\n // `measureElement` would cache that bogus 0 height — shrinking `.inner`'s total height to\n // ~0 and permanently clamping the scroll container's `scrollTop` to 0 in the process, which\n // survives the tab becoming visible again (the browser never un-clamps a scroll offset just\n // because content grows back). Skip the measurement while hidden and keep whatever size is\n // already cached (or the `estimateSize` default on first mount) instead.\n measureElement: (element, entry, instance) => {\n if ((element as HTMLElement).offsetParent !== null) return measureElementDefault(element, entry, instance);\n const index = instance.indexFromElement(element);\n const key = instance.options.getItemKey(index);\n return instance.itemSizeCache.get(key) ?? instance.options.estimateSize(index);\n },\n });\n\n function handleScroll(): void {\n const el = scrollRef.current;\n if (!el) return;\n const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;\n stickToBottomRef.current = distanceFromBottom < STICK_THRESHOLD_PX;\n }\n\n useEffect(() => {\n const grew = rows.length > prevRowCountRef.current;\n prevRowCountRef.current = rows.length;\n if (!grew) return;\n if (!stickToBottomRef.current) return;\n virtualizer.scrollToIndex(rows.length - 1, { align: \"end\" });\n }, [rows.length, virtualizer]);\n\n if (rows.length === 0) {\n return (\n <div className={styles.viewport} ref={scrollRef}>\n {running ? (\n <div className={styles.working} role=\"status\" aria-live=\"polite\">\n <span className={styles.workingDots} aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n Agent is working…\n </div>\n ) : (\n <div className={styles.empty}>No messages yet — say something to start.</div>\n )}\n </div>\n );\n }\n\n return (\n <div className={styles.viewport} ref={scrollRef} onScroll={handleScroll}>\n <div className={styles.inner} style={{ height: virtualizer.getTotalSize() }}>\n {virtualizer.getVirtualItems().map((virtualRow) => {\n const row = rows[virtualRow.index];\n if (!row) return null;\n return (\n <div\n key={virtualRow.key}\n ref={virtualizer.measureElement}\n data-index={virtualRow.index}\n className={styles.rowWrap}\n style={{ transform: `translateY(${virtualRow.start}px)` }}\n >\n {renderRow(row)}\n </div>\n );\n })}\n </div>\n {running && (\n <div className={styles.working} role=\"status\" aria-live=\"polite\">\n <span className={styles.workingDots} aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n Agent is working…\n </div>\n )}\n </div>\n );\n}\n","/**\n * Attachment preview strip — presentational thumbnail row with remove buttons (POC\n * `renderAttachments`, POC_TO_APP_PLAN_UI.md §4.4). Pending-image state lives in `Composer`;\n * this component only renders `images` and forwards `onRemove(index)`.\n */\n\nimport styles from \"./Attachments.module.css\";\n\nexport interface PendingImage {\n mimeType: string;\n /** Base64 payload, no `data:...;base64,` prefix — sent to the daemon as-is. */\n data: string;\n /** Full data URL, for the thumbnail `<img src>`. */\n thumbUrl: string;\n}\n\nexport interface AttachmentsProps {\n images: PendingImage[];\n onRemove: (index: number) => void;\n}\n\nexport function Attachments({ images, onRemove }: AttachmentsProps) {\n if (images.length === 0) return null;\n\n return (\n <div className={styles.strip}>\n {images.map((img, i) => (\n <div key={i} className={styles.thumb}>\n <img src={img.thumbUrl} alt=\"\" />\n <button\n type=\"button\"\n className={styles.remove}\n title=\"Remove\"\n onClick={() => onRemove(i)}\n >\n ×\n </button>\n </div>\n ))}\n </div>\n );\n}\n\n/** `FileReader.readAsDataURL` wrapped as a promise (POC `addImageFile`). */\nexport function readImageFile(file: File): Promise<PendingImage> {\n const { promise, resolve, reject } = Promise.withResolvers<PendingImage>();\n const reader = new FileReader();\n reader.onload = () => {\n const result = reader.result;\n if (typeof result !== \"string\") {\n reject(new Error(\"Unexpected FileReader result\"));\n return;\n }\n const commaIndex = result.indexOf(\",\");\n const data = commaIndex >= 0 ? result.slice(commaIndex + 1) : result;\n resolve({ mimeType: file.type, data, thumbUrl: result });\n };\n reader.onerror = () => reject(reader.error ?? new Error(\"Failed to read file\"));\n reader.readAsDataURL(file);\n return promise;\n}\n","/**\n * Composer — autosizing textarea + attach/send/stop (POC `initChatPanel`/`send()`,\n * POC_TO_APP_PLAN_UI.md §4.4). Send routing: no `agentId` yet → `client.createAgent(...)` then\n * `sessionStore.bindAgent` on success (the race-free binding point `useAgentStream` reacts to);\n * else → `client.agent(agentId).send(...)`. Stop → `client.agent(agentId).interrupt()`.\n *\n * OPTIMISTIC ECHO: `create_agent_request`/`send_agent_prompt` block server-side until the whole\n * turn finishes, and even the *first* broadcast event for that turn (the canonical `user_message`)\n * only fires once the agent process is booted/warm — for a brand-new session that means a real\n * process-spawn+handshake before anything appears (see AGENTS.md \"First-message latency\"). To hide\n * that, `handleSend` mints a `clientMessageId` and inserts the user's row into the timeline\n * *synchronously*, before the RPC is even issued. The daemon echoes the same id back verbatim as\n * the `user_message` event's `messageId` (`packages/server/src/agent/agent-service.ts` `runTurn`);\n * the reducer (`timeline/reducer.ts` `onUserMessage`) matches it against the pending row and\n * confirms it in place instead of appending a duplicate.\n *\n * A brand-new agent has no live subscription yet when the first turn's events start arriving —\n * `useAgentStream` only attaches once `bindAgent` sets `agentId`, which happens *after*\n * `createAgent()` resolves. So for the first turn `handleSend` subscribes to the raw broadcast\n * directly and applies each `agent_stream` event *as it arrives*, latching the new agent's id\n * from *its own* `user_message` echo (`messageId === clientMessageId`) — never from \"the first\n * such event\", since another session's agent can be mid-turn on the same socket concurrently and\n * its frames would otherwise be misattributed here (agent_update frames are top-level and never\n * reach `onSessionMessage`; agent_stream frames are session-wrapped and do). That includes the\n * `user_message` event that reconciles the optimistic row above.\n * `bindAgent` is deferred until the RPC resolves so `useAgentStream` attaches only for follow-up\n * turns and never re-applies the first turn (the reducer is not event-id-idempotent).\n */\n\nimport { useRef, useState, type ChangeEvent, type ClipboardEvent, type KeyboardEvent } from \"react\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { Paperclip, Send, Square } from \"lucide-react\";\nimport type { AgentStreamEvent } from \"@av-pi-studio/protocol\";\nimport { Button } from \"@pi-studio-ui/components/primitives/Button.js\";\nimport { TextArea } from \"@pi-studio-ui/components/primitives/TextInput.js\";\nimport { useConnectionStore } from \"@pi-studio-ui/lib/connection/connection-store.js\";\nimport { useSessionStore } from \"@pi-studio-ui/stores/session-store.js\";\nimport { applyAgentStreamEvent, createFirstTurnGate } from \"@pi-studio-ui/hooks/agent-stream-events.js\";\nimport { Attachments, readImageFile, type PendingImage } from \"./Attachments.js\";\nimport styles from \"./Composer.module.css\";\n\nconst MAX_TEXTAREA_HEIGHT = 160;\n\nexport interface ComposerProps {\n sessionId: string;\n}\n\nfunction autoResize(el: HTMLTextAreaElement): void {\n el.style.height = \"auto\";\n el.style.height = `${Math.min(el.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;\n}\n\ninterface AgentStreamMessage {\n type: \"agent_stream\";\n agentId: string;\n event: AgentStreamEvent;\n}\n\nfunction isAgentStreamMessage(msg: unknown): msg is AgentStreamMessage {\n if (typeof msg !== \"object\" || msg === null) return false;\n if (!(\"type\" in msg) || msg.type !== \"agent_stream\") return false;\n return \"agentId\" in msg && typeof msg.agentId === \"string\" && \"event\" in msg;\n}\n\nexport function Composer({ sessionId }: ComposerProps) {\n const client = useConnectionStore((s) => s.client);\n const session = useSessionStore((s) => s.sessions[sessionId]);\n const bindAgent = useSessionStore((s) => s.bindAgent);\n const addOptimisticUserMessage = useSessionStore((s) => s.addOptimisticUserMessage);\n const markUserMessageFailed = useSessionStore((s) => s.markUserMessageFailed);\n const setCwd = useSessionStore((s) => s.setCwd);\n const queryClient = useQueryClient();\n\n const [text, setText] = useState(\"\");\n const [images, setImages] = useState<PendingImage[]>([]);\n const [sending, setSending] = useState(false);\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n const running = session?.status === \"running\";\n const canSend = Boolean(client) && !sending && (text.trim().length > 0 || images.length > 0);\n\n async function addImageFile(file: File): Promise<void> {\n if (!file.type.startsWith(\"image/\")) return;\n try {\n const image = await readImageFile(file);\n setImages((prev) => [...prev, image]);\n } catch {\n // Best-effort attachment read — ignore unreadable files (POC has no error UI here either).\n }\n }\n\n function handleFileInputChange(ev: ChangeEvent<HTMLInputElement>): void {\n for (const file of ev.target.files ?? []) void addImageFile(file);\n ev.target.value = \"\";\n }\n\n function handlePaste(ev: ClipboardEvent<HTMLTextAreaElement>): void {\n for (const item of ev.clipboardData.items) {\n if (item.type.startsWith(\"image/\")) {\n ev.preventDefault();\n const file = item.getAsFile();\n if (file) void addImageFile(file);\n }\n }\n }\n\n function handleRemoveImage(index: number): void {\n setImages((prev) => prev.filter((_, i) => i !== index));\n }\n\n function handleTextareaChange(ev: ChangeEvent<HTMLTextAreaElement>): void {\n setText(ev.target.value);\n autoResize(ev.target);\n }\n\n function handleKeyDown(ev: KeyboardEvent<HTMLTextAreaElement>): void {\n if (ev.key === \"Enter\" && !ev.shiftKey) {\n ev.preventDefault();\n void handleSend();\n }\n }\n\n async function handleSend(): Promise<void> {\n if (!client || !session || sending) return;\n const trimmed = text.trim();\n if (!trimmed && images.length === 0) return;\n\n setText(\"\");\n if (textareaRef.current) autoResize(textareaRef.current);\n const sentImages = images;\n setImages([]);\n\n const prompt = trimmed || \"Describe this image\";\n const rpcImages =\n sentImages.length > 0\n ? sentImages.map((img) => ({ mimeType: img.mimeType, data: img.data }))\n : undefined;\n\n // Optimistic echo: render the user's row synchronously instead of waiting for the daemon's\n // `user_message` broadcast (see file header). `clientMessageId` is round-tripped through the\n // RPC below and echoed back verbatim as the broadcast event's `messageId`, which is how the\n // reducer reconciles this row instead of appending a duplicate once the server confirms it.\n const clientMessageId = crypto.randomUUID();\n addOptimisticUserMessage(sessionId, clientMessageId, prompt, rpcImages);\n\n setSending(true);\n try {\n if (!session.agentId) {\n const cwd = session.cwd || \"~\";\n setCwd(sessionId, cwd);\n // The daemon runs the entire first turn *before* `createAgent()` resolves, broadcasting\n // every `agent_stream` event for it in the meantime (agent-service.ts `runTurn`). If we\n // waited for the RPC to learn our agentId the timeline would stay empty (and show no\n // running indicator) until the whole turn finished — the reported bug. Instead we watch\n // the live broadcast during the call and apply events as they arrive.\n //\n // We latch the agent id from *our own* canonical `user_message` echo (`messageId ===\n // clientMessageId`), never from \"the first `agent_stream` frame we happen to observe\":\n // another session's agent can be mid-turn on this same socket right now, so the first\n // frame to arrive after we subscribe may belong to THAT agent, not ours. Latching onto it\n // would misattribute its events into this session's timeline and then silently drop this\n // turn's real events (mismatched agentId) once they start arriving. `agent_update` frames\n // are broadcast bare/top-level and never reach `onSessionMessage` (only `session`-wrapped\n // frames do), but every `agent_stream` frame IS session-wrapped, including the\n // `user_message` echo — so this key is always observable here.\n //\n // `bindAgent` is deferred until *after* the RPC resolves: binding attaches\n // `useAgentStream`, and since the reducer isn't event-id-idempotent, a mid-turn attach\n // would double every remaining row. Binding post-resolve means this handler is the sole\n // applier for the first turn and `useAgentStream` only ever sees follow-up turns.\n const isOwnTurnEvent = createFirstTurnGate(clientMessageId);\n const unsubscribeLive = client.connection.onSessionMessage((msg) => {\n if (!isAgentStreamMessage(msg) || !isOwnTurnEvent(msg)) return;\n applyAgentStreamEvent({ sessionId, event: msg.event, client, queryClient });\n });\n\n let result: { agentId: string };\n try {\n result = await client.createAgent({\n config: { provider: \"pi\", cwd },\n initialPrompt: prompt,\n clientMessageId,\n images: rpcImages,\n labels: {},\n });\n } finally {\n unsubscribeLive();\n }\n\n bindAgent(sessionId, result.agentId);\n } else {\n await client.agent(session.agentId).send(prompt, { clientMessageId, images: rpcImages });\n }\n } catch {\n // RPC rejection before any `user_message` broadcast arrived (e.g. dropped connection) —\n // the optimistic row would otherwise stay pending forever with no feedback. If the server\n // *did* manage to broadcast `user_message` first (the row is already reconciled), this is\n // a no-op — `markUserMessageFailed` only touches a still-pending row. Turn-level failures\n // that occur after that point still surface via `agent_stream` `error`/`turn_failed`\n // events (POC swallows the RPC rejection the same way; the stream is the source of truth\n // for those).\n markUserMessageFailed(sessionId, clientMessageId);\n } finally {\n setSending(false);\n }\n }\n\n function handleStop(): void {\n if (!session?.agentId) return;\n void client?.agent(session.agentId).interrupt();\n }\n\n return (\n <div className={styles.composer}>\n <div className={styles.inputArea}>\n <TextArea\n ref={textareaRef}\n className={styles.textarea}\n rows={1}\n value={text}\n placeholder=\"Ask anything… (Enter to send, Shift+Enter for newline)\"\n onChange={handleTextareaChange}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n />\n <Attachments images={images} onRemove={handleRemoveImage} />\n </div>\n <Button\n className={styles.attachBtn}\n variant=\"ghost\"\n size=\"md\"\n iconOnly\n title=\"Attach image\"\n onClick={() => fileInputRef.current?.click()}\n >\n <Paperclip size={16} />\n </Button>\n <input\n ref={fileInputRef}\n className={styles.hiddenFileInput}\n type=\"file\"\n accept=\"image/*\"\n multiple\n onChange={handleFileInputChange}\n />\n <div className={styles.actions}>\n <Button size=\"sm\" disabled={!canSend} onClick={() => void handleSend()} leftIcon={<Send size={14} />}>\n Send\n </Button>\n {running && (\n <Button size=\"sm\" variant=\"destructive\" onClick={handleStop} leftIcon={<Square size={14} />}>\n Stop\n </Button>\n )}\n </div>\n </div>\n );\n}\n","/**\n * ChatPanel — the tab content mounted by `panel-registry.ts` for `kind: \"chat\"` tabs. Looks up\n * the session by `tab.data.sessionId`, keeps its timeline live via `useAgentStream`, and renders\n * the virtualized `Timeline` + `Composer` (POC_TO_APP_PLAN_UI.md §4.3/§4.4).\n */\n\nimport { useAgentStream } from \"@pi-studio-ui/hooks/use-agent-stream.js\";\nimport { useSessionStore } from \"@pi-studio-ui/stores/session-store.js\";\nimport type { Tab, ChatTabData } from \"@pi-studio-ui/stores/tab-store.js\";\nimport { Timeline } from \"./Timeline.js\";\nimport { Composer } from \"./Composer.js\";\nimport styles from \"./ChatPanel.module.css\";\n\nexport interface ChatPanelProps {\n tab: Tab;\n}\n\nexport function ChatPanel({ tab }: ChatPanelProps) {\n // `panel-registry.ts` only ever mounts this component for `tab.kind === \"chat\"`, whose `data`\n // is always `ChatTabData` — narrowed here since `Tab[\"data\"]` is a union at the type level.\n const { sessionId } = tab.data as ChatTabData;\n const session = useSessionStore((s) => s.sessions[sessionId]);\n\n useAgentStream(sessionId);\n\n if (!session) {\n return (\n <div className={styles.panel}>\n <div className={styles.empty}>Session not found.</div>\n </div>\n );\n }\n\n return (\n <div className={styles.panel}>\n <Timeline session={session} />\n <Composer sessionId={session.id} />\n </div>\n );\n}\n"],"names":["statusBadgeTokens","variant","StatusBadge","label","className","token","color","jsx","styles","ICON_BY_KIND","Terminal","Eye","Pencil","FilePlus","Search","Globe","ListTree","toolIcon","tool","toolLabel","toolFilePath","toolMutatesFiles","toolBody","sections","text","toolDetailText","toolInlineDetail","parts","DEBOUNCE_MS","pendingTimer","invalidateAfterToolCompletion","queryClient","client","cwd","_toolFilePath","createFirstTurnGate","clientMessageId","liveAgentId","msg","applyAgentStreamEvent","sessionId","event","sessionStore","useSessionStore","session","useAgentStream","useConnectionStore","s","agentId","_a","useQueryClient","useEffect","AssistantRow","row","jsxs","Markdown","ReasoningRow","BADGE_VARIANT","ToolCard","expanded","setExpanded","useState","Icon","inlineDetail","body","hasBody","clsx","v","ChevronRight","section","i","DiffView","UserRow","openedSrc","setOpenedSrc","stateClass","img","src","ev","Dialog","open","ErrorRow","SystemRow","STICK_THRESHOLD_PX","renderRow","Timeline","rows","running","scrollRef","useRef","stickToBottomRef","prevRowCountRef","virtualizer","useVirtualizer","index","element","entry","instance","measureElementDefault","key","handleScroll","el","distanceFromBottom","grew","virtualRow","Attachments","images","onRemove","readImageFile","file","promise","resolve","reject","reader","result","commaIndex","data","MAX_TEXTAREA_HEIGHT","autoResize","isAgentStreamMessage","Composer","bindAgent","addOptimisticUserMessage","markUserMessageFailed","setCwd","setText","setImages","sending","setSending","textareaRef","fileInputRef","canSend","addImageFile","image","prev","handleFileInputChange","handlePaste","item","handleRemoveImage","handleTextareaChange","handleKeyDown","handleSend","trimmed","sentImages","prompt","rpcImages","isOwnTurnEvent","unsubscribeLive","handleStop","TextArea","Button","Paperclip","Send","Square","ChatPanel","tab"],"mappings":"wnBAcO,SAASA,GAAkBC,EAA0C,CAC1E,OAAQA,EAAA,CACN,IAAK,UACH,MAAO,CAAE,MAAO,eAAA,EAClB,IAAK,QACH,MAAO,CAAE,MAAO,cAAA,EAClB,IAAK,QACH,MAAO,CAAE,MAAO,iBAAA,CAAkB,CAExC,CCRO,SAASC,GAAY,CAAE,MAAAC,EAAO,QAAAF,EAAS,UAAAG,GAA+B,CAC3E,KAAM,CAAE,MAAAC,CAAA,EAAUL,GAAkBC,CAAO,EACrCK,EAAQ,kBAAkBD,CAAK,IACrC,OACEE,EAAAA,IAAC,OAAA,CACC,UAAW,GAAGC,GAAO,KAAK,GAAGJ,EAAY,IAAIA,CAAS,GAAK,EAAE,GAC7D,MAAO,CACL,gBAAiB,sBAAsBE,CAAK,qBAC5C,YAAa,sBAAsBA,CAAK,qBACxC,MAAAA,CAAA,EAGD,SAAAH,CAAA,CAAA,CAGP,CCZA,MAAMM,GAA2D,CAC/D,MAAOC,EACP,KAAMC,GACN,KAAMC,GACN,MAAOC,GACP,OAAQC,GACR,MAAOC,GACP,KAAMC,EACR,EAEO,SAASC,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UAAW9C,EAAO,MACrB,SAAA,CAAAD,MAAC8E,IAAS,QAAAzC,EAAkB,EAC5BrC,EAAAA,IAACiH,GAAA,CAAS,UAAW5E,EAAQ,EAAA,CAAI,CAAA,EACnC,EAVErC,EAAAA,IAAC,MAAA,CAAI,UAAWC,EAAO,MACrB,SAAAD,EAAAA,IAAC,MAAA,CAAI,UAAWC,EAAO,MAAO,SAAA,oBAAA,CAAkB,EAClD,CAUN"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
._badge_jtokc_3{display:inline-flex;align-items:center;justify-content:center;padding:1px 6px;border-radius:9999px;border:1px solid;font-size:var(--pi-font-size-xs, 12px);font-family:var(--pi-font-ui, system-ui, sans-serif);font-weight:500;white-space:nowrap;line-height:1.5}._row_10uhr_3{padding:8px 12px;border-radius:var(--pi-borderRadius-md, 6px);max-width:85%;white-space:pre-wrap;word-break:break-word;line-height:1.5;font-size:13px}._who_10uhr_13{display:block;font-size:10px;color:var(--pi-color-foregroundMuted, #7a8394);margin-bottom:3px;text-transform:uppercase;letter-spacing:.03em}._user_10uhr_24{background:var(--pi-color-accentMuted, #1e3a5f);color:var(--pi-color-foreground, #dbe9ff);align-self:flex-end;border-bottom-right-radius:2px}._userPending_10uhr_31{opacity:.6}._userFailed_10uhr_35{background:var(--pi-color-destructive, #3a1515);color:var(--pi-color-destructiveForeground, #ff8a80);opacity:1}._userImages_10uhr_41{display:flex;gap:6px;flex-wrap:wrap;margin-top:6px}._userImage_10uhr_41{max-width:200px;max-height:150px;border-radius:4px;display:block;object-fit:cover;cursor:pointer}._imageDialog_10uhr_57{max-width:90vw}._imageDialogPreview_10uhr_61{display:block;max-width:90vw;max-height:80vh;object-fit:contain}._assistant_10uhr_70{background:var(--pi-color-surface, #1c1f26);color:var(--pi-color-foreground, #d6dae0);align-self:flex-start;border-bottom-left-radius:2px}._assistant_10uhr_70._streaming_10uhr_77{border-left:2px solid var(--pi-color-accent, #2e5cb8)}._streamingText_10uhr_81{white-space:pre-wrap;word-break:break-word}._cursor_10uhr_86{display:inline-block;margin-left:1px;animation:_blink_10uhr_1 1s step-start infinite;color:var(--pi-color-accentBright, #a2b4d7)}@keyframes _blink_10uhr_1{50%{opacity:0}}._reasoning_10uhr_101{background:var(--pi-color-background, #0f1115);color:var(--pi-color-foregroundMuted, #7a8394);font-style:italic;font-size:12px;align-self:flex-start}._tool_10uhr_111{background:var(--pi-color-surface, #1c1f26);border:1px solid var(--pi-color-border, #2c313b);align-self:flex-start;font-size:12px;max-width:90%;padding:0;overflow:hidden}._toolHeader_10uhr_121{display:flex;align-items:center;gap:6px;width:100%;padding:8px 12px;background:none;border:none;color:inherit;font:inherit;text-align:left;cursor:pointer}._toolHeader_10uhr_121:disabled{cursor:default}._toolChevron_10uhr_139{flex-shrink:0;color:var(--pi-color-foregroundMuted, #7a8394);transition:transform .12s ease}._toolChevronOpen_10uhr_145{transform:rotate(90deg)}._toolInlineDetail_10uhr_149{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--pi-color-foregroundMuted, #9aa0a6);font-family:var(--pi-font-mono, ui-monospace, monospace);min-width:0;flex:1}._toolBody_10uhr_159{border-top:1px solid var(--pi-color-border, #2c313b);max-height:420px;overflow:auto}._toolCode_10uhr_165{margin:0;padding:8px 12px;font-family:var(--pi-font-mono, ui-monospace, monospace);font-size:12px;line-height:1.5;white-space:pre-wrap;word-break:break-word;color:var(--pi-color-foreground, #dbe3f0)}._toolIcon_10uhr_176{display:flex;align-items:center;flex-shrink:0}._toolIcon_10uhr_176._running_10uhr_182{color:var(--pi-color-accentBright, #a2b4d7);animation:_pulse_10uhr_1 1.2s ease-in-out infinite}._toolIcon_10uhr_176._completed_10uhr_187{color:var(--pi-color-statusSuccess, #27ae60)}._toolIcon_10uhr_176._error_10uhr_191{color:var(--pi-color-statusDanger, #c0392b)}@keyframes _pulse_10uhr_1{50%{opacity:.5}}._toolLabel_10uhr_201{font-weight:600;text-transform:capitalize}._toolBadge_10uhr_206{margin-left:auto}._error_10uhr_191{background:var(--pi-color-destructive, #3a1515);color:var(--pi-color-destructiveForeground, #ff8a80);align-self:flex-start}._system_10uhr_219{background:transparent;color:var(--pi-color-foregroundMuted, #7a8394);font-style:italic;align-self:flex-start;padding:4px 12px}._viewport_1byko_3{flex:1 1 auto;overflow-y:auto;min-height:0;padding:16px 20px}._inner_1byko_10{position:relative;width:100%}._rowWrap_1byko_15{position:absolute;top:0;left:0;width:100%;display:flex;flex-direction:column;padding-bottom:4px}._empty_1byko_25{display:flex;align-items:center;justify-content:center;height:100%;color:var(--pi-color-foregroundMuted, #7a8394);font-size:13px}._working_1byko_34{display:flex;align-items:center;gap:8px;padding:8px 2px 4px;color:var(--pi-color-foregroundMuted, #7a8394);font-size:13px}._workingDots_1byko_43{display:inline-flex;gap:4px}._workingDots_1byko_43 span{width:6px;height:6px;border-radius:50%;background:var(--pi-color-accentBright, #a2b4d7);animation:_workingBounce_1byko_1 1.2s ease-in-out infinite}._workingDots_1byko_43 span:nth-child(2){animation-delay:.16s}._workingDots_1byko_43 span:nth-child(3){animation-delay:.32s}@keyframes _workingBounce_1byko_1{0%,80%,to{opacity:.3;transform:translateY(0)}40%{opacity:1;transform:translateY(-3px)}}._strip_5sm81_4{display:flex;gap:6px;flex-wrap:wrap;padding:6px 0 0}._thumb_5sm81_11{position:relative;width:48px;height:48px;border-radius:4px;overflow:hidden;border:1px solid var(--pi-color-border, #2c313b);flex-shrink:0}._thumb_5sm81_11 img{width:100%;height:100%;object-fit:cover;display:block}._remove_5sm81_28{position:absolute;top:-2px;right:-2px;width:16px;height:16px;background:var(--pi-color-statusDanger, #c0392b);color:#fff;border:none;border-radius:50%;font-size:10px;line-height:16px;text-align:center;cursor:pointer;padding:0}._composer_1ll3p_1{padding:10px 16px;border-top:1px solid var(--pi-color-border, #2c313b);background:var(--pi-color-surface, #14161a);display:flex;gap:8px;align-items:center;flex-shrink:0}._inputArea_1ll3p_13{flex:1;display:flex;flex-direction:column;gap:0;min-width:0}._textarea_1ll3p_21{resize:none;min-height:38px;max-height:160px;overflow-y:auto}._attachBtn_1ll3p_28{flex-shrink:0}._hiddenFileInput_1ll3p_32{display:none}._actions_1ll3p_36{display:flex;flex-direction:column;gap:4px;flex-shrink:0}._panel_12s9l_1{display:flex;flex-direction:column;height:100%;min-height:0}._empty_12s9l_8{display:flex;align-items:center;justify-content:center;height:100%;color:var(--pi-color-foregroundMuted, #7a8394);font-size:13px}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChatPanel-CG_Yz_QI.js","assets/vendor-react-BoIQBqDW.js","assets/vendor-query-AtKBh_Yt.js","assets/vendor-icons-DwowToH7.js","assets/markdown-D9FuaV1m.js","assets/vendor-highlight-DCzuSv8g.js","assets/vendor-markdown-B8HSIhaA.js","assets/vendor--os7hw7d.js","assets/markdown-BQwXm0MF.css","assets/DiffView-DlVCPvLc.js","assets/DiffView-CRbeRztO.css","assets/vendor-overlays-UwLNGk04.js","assets/vendor-dnd-D9kA7FgH.js","assets/ChatPanel-Cz7YoXXW.css","assets/FilePanel-CGmR13VT.js","assets/FilePanel-DIInFr3h.css","assets/TerminalPanel-D21QoVnF.js","assets/vendor-terminal-BhzX2_ts.js","assets/vendor-terminal-DYP7pi_n.css","assets/TerminalPanel-BQj62G6N.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var sn=Object.defineProperty;var on=(t,e,n)=>e in t?sn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var I=(t,e,n)=>on(t,typeof e!="symbol"?e+"":e,n);import{r as w,j as i,d as rn}from"./vendor-react-BoIQBqDW.js";import{Q as an,a as cn,u as ln,b as dn,c as Le,d as un}from"./vendor-query-AtKBh_Yt.js";import{A as c,B as u,C as B,D as mt,E as C,F as ye,G as K,H as R,I as m,J as M,K as W,L as Te,M as ie,N as ce}from"./vendor--os7hw7d.js";import{L as pn,P as fn,a as hn,b as gn,c as mn,E as _t,C as yt,d as _n,F as yn,e as bt,f as bn,S as wt,G as wn,g as Sn,M as St,X as Me,h as xt,i as xn,U as vn,R as kn,j as In,A as Cn}from"./vendor-icons-DwowToH7.js";import{R as Ue,T as Ke,P as Ve,C as Ge,I as J,S as vt,D as Tn,a as jn,b as En,c as Nn,d as et,e as $e}from"./vendor-overlays-UwLNGk04.js";import{u as Rn,a as qn,D as Bn,c as An,S as Mn,h as $n,P as Dn,b as On,C as Fn}from"./vendor-dnd-D9kA7FgH.js";import{_ as Je}from"./vendor-highlight-DCzuSv8g.js";import"./vendor-markdown-B8HSIhaA.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const a of r.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&s(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=n(o);fetch(o.href,r)}})();const Pn=new an;function kt(t){const e=t.trim().replace(/^#/,""),n=e.length===3?e.split("").map(s=>s+s).join(""):e;if(n.length!==6||/[^0-9a-fA-F]/.test(n))throw new Error(`Invalid hex color: ${t}`);return{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16)}}function Hn(t){return Math.max(0,Math.min(255,Math.round(t)))}function zn({r:t,g:e,b:n}){const s=o=>Hn(o).toString(16).padStart(2,"0");return`#${s(t)}${s(e)}${s(n)}`}function Wn(t){const{r:e,g:n,b:s}=kt(t),o=r=>{const a=r/255;return a<=.03928?a/12.92:((a+.055)/1.055)**2.4};return .2126*o(e)+.7152*o(n)+.0722*o(s)}function Xe(t,e="#18181b",n="#ffffff"){return Wn(t)>.45?e:n}function Ln(t,e){const{r:n,g:s,b:o}=kt(t),r=Math.max(0,Math.min(1,e));return zn({r:n+(255-n)*r,g:s+(255-s)*r,b:o+(255-o)*r})}function we(t){const e=t.trim().replace(/^#/,"");return(e.length===3||e.length===6)&&!/[^0-9a-fA-F]/.test(e)}const P=(t,e,n,s,o,r,a,l,d,p,h)=>({50:t,100:e,200:n,300:s,400:o,500:r,600:a,700:l,800:d,900:p,950:h}),g={zinc:P("#fafafa","#f4f4f5","#e4e4e7","#d4d4d8","#a1a1aa","#71717a","#52525b","#3f3f46","#27272a","#18181b","#09090b"),gray:P("#f9fafb","#f3f4f6","#e5e7eb","#d1d5db","#9ca3af","#6b7280","#4b5563","#374151","#1f2937","#111827","#030712"),slate:P("#f8fafc","#f1f5f9","#e2e8f0","#cbd5e1","#94a3b8","#64748b","#475569","#334155","#1e293b","#0f172a","#020617"),blue:P("#eff6ff","#dbeafe","#bfdbfe","#93c5fd","#60a5fa","#3b82f6","#2563eb","#1d4ed8","#1e40af","#1e3a8a","#172554"),green:P("#f0fdf4","#dcfce7","#bbf7d0","#86efac","#4ade80","#22c55e","#16a34a","#15803d","#166534","#14532d","#052e16"),red:P("#fef2f2","#fee2e2","#fecaca","#fca5a5","#f87171","#ef4444","#dc2626","#b91c1c","#991b1b","#7f1d1d","#450a0a"),teal:P("#f0fdfa","#ccfbf1","#99f6e4","#5eead4","#2dd4bf","#14b8a6","#0d9488","#0f766e","#115e59","#134e4a","#042f2e"),amber:P("#fffbeb","#fef3c7","#fde68a","#fcd34d","#fbbf24","#f59e0b","#d97706","#b45309","#92400e","#78350f","#451a03"),yellow:P("#fefce8","#fef9c3","#fef08a","#fde047","#facc15","#eab308","#ca8a04","#a16207","#854d0e","#713f12","#422006"),purple:P("#faf5ff","#f3e8ff","#e9d5ff","#d8b4fe","#c084fc","#a855f7","#9333ea","#7e22ce","#6b21a8","#581c87","#3b0764"),orange:P("#fff7ed","#ffedd5","#fed7aa","#fdba74","#fb923c","#f97316","#ea580c","#c2410c","#9a3412","#7c2d12","#431407"),white:"#ffffff",black:"#000000"},Un={statusSuccess:"#16a34a",statusDanger:"#dc2626",statusWarning:"#f59e0b",statusMerged:"#9333ea"},Kn={statusSuccess:"#15803d",statusDanger:"#b91c1c",statusWarning:"#d97706",statusMerged:"#7c3aed"};function Vn(){return{keyword:g.purple[300],string:g.green[300],number:g.orange[300],boolean:g.orange[300],comment:g.zinc[500],function:g.blue[300],variable:g.zinc[200],type:g.teal[300],class:g.amber[300],constant:g.orange[300],operator:g.zinc[400],punctuation:g.zinc[400],tag:g.red[300],attribute:g.amber[300],property:g.blue[200],regexp:g.teal[300],escape:g.orange[200],heading:g.blue[300],link:g.blue[400],deleted:g.red[400],inserted:g.green[400]}}function Gn(){return{keyword:g.purple[700],string:g.green[700],number:g.orange[700],boolean:g.orange[700],comment:g.zinc[500],function:g.blue[700],variable:g.zinc[800],type:g.teal[700],class:g.amber[700],constant:g.orange[700],operator:g.zinc[600],punctuation:g.zinc[600],tag:g.red[700],attribute:g.amber[700],property:g.blue[700],regexp:g.teal[700],escape:g.orange[700],heading:g.blue[700],link:g.blue[600],deleted:g.red[700],inserted:g.green[700]}}function It(t,e,n){return{background:t,foreground:e,cursor:n,cursorAccent:t,selectionBackground:"rgba(255,255,255,0.18)",black:g.zinc[900],red:g.red[500],green:g.green[500],yellow:g.amber[500],blue:g.blue[500],magenta:g.purple[500],cyan:g.teal[500],white:g.zinc[300],brightBlack:g.zinc[600],brightRed:g.red[400],brightGreen:g.green[400],brightYellow:g.amber[400],brightBlue:g.blue[400],brightMagenta:g.purple[400],brightCyan:g.teal[400],brightWhite:g.zinc[50]}}function de(t){const e=g.zinc[50],n=Xe(t.accent);return{surface0:t.surface0,surface1:t.surface1,surface2:t.surface2,surface3:t.surface3,surface4:t.surface4,surfaceDiffEmpty:t.surfaceDiffEmpty,surfaceSidebar:t.surfaceSidebar,surfaceSidebarHover:t.surfaceSidebarHover,surfaceWorkspace:t.surface1,foreground:e,foregroundMuted:t.mutedForeground,accent:t.accent,accentBright:t.accentBright,accentForeground:n,destructive:t.destructive,destructiveForeground:g.white,success:t.accent,successForeground:g.white,border:t.border,borderAccent:t.borderAccent,...Un,diffAddition:g.green[400],diffDeletion:g.red[500],scrollbarHandle:t.scrollbarHandle,background:t.surface0,popover:t.surface2,popoverForeground:e,primary:t.accent,secondary:t.surface2,muted:t.surface2,mutedForeground:t.mutedForeground,input:t.surface2,ring:t.accent,palette:g,syntax:Vn(),terminal:It(t.surface0,e,t.accent)}}function Jn(){const t="#1a1a1e",e="#253e6f";return{surface0:"#ffffff",surface1:"#fafafa",surface2:"#f4f4f5",surface3:"#e4e4e7",surface4:"#d4d4d8",surfaceDiffEmpty:"#f6f6f6",surfaceSidebar:"#f4f4f5",surfaceSidebarHover:"#e9e9ec",surfaceWorkspace:"#ffffff",foreground:t,foregroundMuted:"#71717a",accent:e,accentBright:"#2f4f8e",accentForeground:Xe(e),destructive:"#b04138",destructiveForeground:"#ffffff",success:e,successForeground:"#ffffff",border:"#e4e4e7",borderAccent:"#ececf1",...Kn,diffAddition:"#15803d",diffDeletion:"#b91c1c",scrollbarHandle:"#3f3f46",background:"#ffffff",popover:"#ffffff",popoverForeground:t,primary:e,secondary:"#f4f4f5",muted:"#f4f4f5",mutedForeground:"#71717a",input:"#f4f4f5",ring:e,palette:g,syntax:Gn(),terminal:{...It("#ffffff",t,e),selectionBackground:"rgba(0,0,0,0.15)",white:"#ffffff",brightWhite:"#fafafa"}}}const Xn={light:"#ffffff",dark:"#3b62b0",zinc:"#808080",midnight:"#4A6BA8",claude:"#D97757",ghostty:"#8caaee"},Ct=["light","dark","zinc","midnight","claude","ghostty"];function Yn(t){if(t==="light")return Jn();switch(t){case"dark":return de({surface0:"#181B1A",surface1:"#1E2120",surface2:"#272A29",surface3:"#434645",surface4:"#595B5B",surfaceDiffEmpty:"#252827",surfaceSidebar:"#141716",surfaceSidebarHover:"#1c1f1e",mutedForeground:"#A1A5A4",scrollbarHandle:"#717574",border:"#252B2A",borderAccent:"#2f3135",accent:"#2e5cb8",accentBright:"#a2b4d7",destructive:"#c64f43"});case"zinc":return de({surface0:"#18181b",surface1:"#1f1f22",surface2:"#27272a",surface3:"#3f3f46",surface4:"#52525b",surfaceDiffEmpty:"#242427",surfaceSidebar:"#131316",surfaceSidebarHover:"#1b1b1e",mutedForeground:"#a1a1aa",scrollbarHandle:"#71717a",border:"#27272a",borderAccent:"#303036",accent:"#e4e4e7",accentBright:"#fafafa",destructive:"#c44a4a"});case"midnight":return de({surface0:"#161820",surface1:"#1c1e27",surface2:"#252731",surface3:"#3c3e4c",surface4:"#535564",surfaceDiffEmpty:"#222430",surfaceSidebar:"#121420",surfaceSidebarHover:"#1a1c28",mutedForeground:"#9a9db0",scrollbarHandle:"#6b6e82",border:"#242636",borderAccent:"#2e3040",accent:"#3b6fcf",accentBright:"#7eaaeb",destructive:"#c44a52"});case"claude":return de({surface0:"#1f1f1e",surface1:"#262523",surface2:"#2f2d2b",surface3:"#4a4745",surface4:"#605d5b",surfaceDiffEmpty:"#2a2826",surfaceSidebar:"#1a1918",surfaceSidebarHover:"#222120",mutedForeground:"#ada9a5",scrollbarHandle:"#78746f",border:"#2c2a27",borderAccent:"#36332f",accent:"#d97757",accentBright:"#e89a7f",destructive:"#cf513e"});case"ghostty":return de({surface0:"#282c34",surface1:"#2f333d",surface2:"#383c48",surface3:"#4a4f5e",surface4:"#5b6175",surfaceDiffEmpty:"#323643",surfaceSidebar:"#21252d",surfaceSidebarHover:"#292d36",mutedForeground:"#c8ccd8",scrollbarHandle:"#a0a4b2",border:"#353a47",borderAccent:"#3f4454",accent:"#89b4fa",accentBright:"#b4d0fc",destructive:"#c44a55"})}}const Tt={};for(const t of Ct){const e=t==="light"?"light":"dark";Tt[t]={name:t,colorScheme:e,colors:Yn(t),swatch:Xn[t]}}const Qn=Tt,Zn={0:0,1:4,"1.5":6,2:8,3:12,4:16,6:24,8:32,12:48,16:64,20:80,24:96,32:128},jt={xs:12,code:12,sm:14,base:16,lg:18,xl:20,"2xl":22,"3xl":26,"4xl":34},es={normal:"400",medium:"500",semibold:"600",bold:"700"},ts={none:0,sm:2,base:4,md:6,lg:8,xl:12,"2xl":16,full:9999},ns={0:0,1:1,2:2},ss={0:0,50:.5,100:1},os={xs:12,sm:14,md:16,lg:20},rs={diff:22},Et='system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',Nt='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace';function as(t){const e=t==="dark"?"rgba(0,0,0,0.55)":"rgba(24,24,27,0.12)";return{sm:{color:e,offsetX:0,offsetY:1,radius:2,elevation:1},md:{color:e,offsetX:0,offsetY:3,radius:8,elevation:4},lg:{color:e,offsetX:0,offsetY:10,radius:24,elevation:12}}}function Rt(t){const e=Qn[t];return{name:t,colorScheme:e.colorScheme,colors:e.colors,spacing:Zn,fontSize:{...jt},fontFamily:{ui:Et,mono:Nt},lineHeight:{...rs},iconSize:os,fontWeight:es,borderRadius:ts,borderWidth:ns,opacity:ss,shadow:as(e.colorScheme),swatch:e.swatch}}const is=16,cs=10,ls=24;function ds(t,e){const n=e.themeName??t.name,s=Rt(n),o=e.uiFont&&e.uiFont.trim()!==""?e.uiFont:Et,r=e.monoFont&&e.monoFont.trim()!==""?e.monoFont:Nt;let a={...s.fontSize};if(e.fontSize!=null){const d=Math.max(cs,Math.min(ls,e.fontSize))/is,p=["xs","code","sm","base","lg","xl","2xl","3xl","4xl"];for(const h of p){const _=jt[h];a[h]=Math.round(_*d)}}return{...s,fontSize:a,fontFamily:{ui:o,mono:r}}}function us(t){return Rt(t)}const ps="dark";function fs(t){const e={};hs(t.colors,e);for(const[n,s]of Object.entries(t.spacing))e[`--pi-spacing-${n}`]=`${s}px`;for(const[n,s]of Object.entries(t.fontSize))e[`--pi-font-size-${n}`]=`${s}px`;e["--pi-font-ui"]=t.fontFamily.ui,e["--pi-font-mono"]=t.fontFamily.mono,e["--pi-line-height-diff"]=`${t.lineHeight.diff}px`;for(const[n,s]of Object.entries(t.iconSize))e[`--pi-icon-size-${n}`]=`${s}px`;for(const[n,s]of Object.entries(t.fontWeight))e[`--pi-font-weight-${n}`]=String(s);for(const[n,s]of Object.entries(t.borderRadius))e[`--pi-radius-${n}`]=s===9999?"9999px":`${s}px`;for(const[n,s]of Object.entries(t.borderWidth))e[`--pi-border-width-${n}`]=`${s}px`;for(const[n,s]of Object.entries(t.opacity))e[`--pi-opacity-${n}`]=String(s);for(const[n,s]of Object.entries(t.shadow))if(typeof s=="string")e[`--pi-shadow-${n}`]=s;else if(s&&typeof s=="object"){const o=s;e[`--pi-shadow-${n}`]=`${o.offsetX}px ${o.offsetY}px ${o.radius}px ${o.color}`}return e["--pi-color-scheme"]=t.colorScheme,e}function hs(t,e){const{palette:n,syntax:s,terminal:o,...r}=t;for(const[a,l]of Object.entries(r))typeof l=="string"&&(e[`--pi-color-${a}`]=l);s&&gs(s,e),o&&(e["--pi-terminal-bg"]=o.background,e["--pi-terminal-fg"]=o.foreground)}function gs(t,e){for(const[n,s]of Object.entries(t))typeof s=="string"&&(e[`--syntax-${ms(n)}`]=s)}function ms(t){return t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function _s(t){if(typeof document>"u")return;const e=document.documentElement.style;for(const[s,o]of Object.entries(t))e.setProperty(s,o);const n=t["--pi-color-scheme"];n&&document.documentElement.style.setProperty("color-scheme",n)}function ys(t){const e=fs(t);_s(e)}const ue=c().min(1,"Asset path must not be empty"),bs=u({accent:c().refine(we,{message:"accent must be a valid #rrggbb hex color"}),accentBright:c().refine(we,{message:"accentBright must be a valid #rrggbb hex color"}).optional(),accentForeground:c().refine(we,{message:"accentForeground must be a valid #rrggbb hex color"}).optional(),swatch:c().refine(we,{message:"swatch must be a valid #rrggbb hex color"}).optional()}),ws=u({logoLight:ue,logoDark:ue,logoMark:ue.optional(),icon:ue,splash:ue.optional()}),Ss=u({docs:c().url().optional(),support:c().url().optional(),issues:c().url().optional(),website:c().url().optional()}).optional(),xs=u({copyright:c().optional(),companyName:c().optional()}).optional();u({productName:c().min(1,"productName is required"),shortName:c().optional(),tagline:c().optional(),colors:bs,assets:ws,links:Ss,legal:xs});function vs(t){const e=t.accent,n=t.accentBright??Ln(e,.35),s=t.accentForeground??Xe(e),o=t.swatch??e;return{accent:e,accentBright:n,accentForeground:s,swatch:o}}function ks(t,e){return{...t,colors:{...t.colors,accent:e.accent,accentBright:e.accentBright,accentForeground:e.accentForeground,primary:e.accent,ring:e.accent},swatch:e.swatch}}const tt="pi-studio-appearance";function Is(t,e){let n=l(t),s=null;function o(h){return h==="system"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":h}function r(h,_){const f=o(h),x=us(f);let S=ds(x,{..._,themeName:f});if(e!=null&&e.colors){const y=vs(e.colors);S=ks(S,y)}return S}function a(){const h=JSON.stringify({mode:n.mode,settings:n.settings});t.set(tt,h)}function l(h){const _=h.get(tt);let f=ps,x={};if(_)try{const y=JSON.parse(_);y.mode&&(Ct.includes(y.mode)||y.mode==="system")&&(f=y.mode),y.settings&&typeof y.settings=="object"&&(x=y.settings)}catch{}const S=r(f,x);return{mode:f,settings:x,resolvedTheme:S}}function d(){n={...n,resolvedTheme:r(n.mode,n.settings)},a()}const p={getState(){return n},setMode(h){n={...n,mode:h},d(),p.apply()},updateSettings(h){n={...n,settings:{...n.settings,...h}},d(),p.apply()},apply(){ys(n.resolvedTheme)},listen(){if(typeof window>"u")return()=>{};const h=window.matchMedia("(prefers-color-scheme: dark)"),_=()=>{n.mode==="system"&&(d(),p.apply())};return h.addEventListener("change",_),s=()=>h.removeEventListener("change",_),s}};return p}function Cs({store:t,brandConfig:e,children:n}){const s=w.useRef(null);return s.current||(s.current=Is(t,e),s.current.apply()),w.useEffect(()=>s.current.listen(),[]),i.jsx(i.Fragment,{children:n})}const Ts={get(t){var e;try{return((e=globalThis.localStorage)==null?void 0:e.getItem(t))??null}catch{return null}},set(t,e){var n;try{(n=globalThis.localStorage)==null||n.setItem(t,e)}catch{}}};function js({children:t}){return i.jsx(Cs,{store:Ts,children:i.jsx(cn,{client:Pn,children:t})})}const Es="_btn_1chbg_4",Ns="_secondary_1chbg_44",Rs="_outline_1chbg_53",qs="_ghost_1chbg_62",Bs="_destructive_1chbg_72",As="_iconOnly_1chbg_82",Ms="_loadingSpinner_1chbg_89",$s="_piSpin_1chbg_1",Se={btn:Es,default:"_default_1chbg_35",secondary:Ns,outline:Rs,ghost:qs,destructive:Bs,iconOnly:As,loadingSpinner:Ms,piSpin:$s},nt={xs:28,sm:32,md:36,lg:40},Ds={xs:12,sm:14,md:16,lg:20},st={xs:8,sm:10,md:12,lg:16},Os={xs:12,sm:13,md:14,lg:15};function Fs(t){const{disabled:e,loading:n}=t;return e||n?{opacity:.5,isGhostHover:!1}:{opacity:1,isGhostHover:!1}}function H({variant:t="default",size:e="md",loading:n=!1,disabled:s=!1,leftIcon:o,trailing:r,iconOnly:a=!1,children:l,style:d,className:p,...h}){const{opacity:_}=Fs({disabled:s??!1,loading:n}),f=s||n,x=Ds[e];return i.jsxs("button",{className:B(Se.btn,Se[t],a&&Se.iconOnly,p),disabled:f,"aria-busy":n||void 0,style:{minHeight:nt[e],paddingLeft:a?void 0:st[e],paddingRight:a?void 0:st[e],fontSize:Os[e],opacity:_,...a?{width:nt[e]}:{},...d},...h,children:[n?i.jsx(pn,{className:Se.loadingSpinner,size:x,"aria-hidden":!0}):o?i.jsx("span",{"aria-hidden":!0,style:{display:"flex",alignItems:"center",flexShrink:0},children:o}):null,l,r&&!n&&i.jsx("span",{"aria-hidden":!0,style:{display:"flex",alignItems:"center",flexShrink:0},children:r})]})}const Ps="_input_a7qyq_3",Hs="_textarea_a7qyq_32",De={input:Ps,textarea:Hs},Oe=w.forwardRef(function({className:e,...n},s){return i.jsx("input",{ref:s,className:B(De.input,e),...n})}),vl=w.forwardRef(function({className:e,...n},s){return i.jsx("textarea",{ref:s,className:B(De.input,De.textarea,e),...n})}),qt=c().datetime({offset:!0});c().uuid();c().regex(/^[A-Za-z0-9_-]+$/,"expected base64url");const _e=mt([C(),qt]),zs=ye(["mobile","browser","cli","mcp"]),Ws=u({type:m("hello"),clientId:c(),clientType:zs,protocolVersion:C(),appVersion:c().optional(),capabilities:K(c(),R()).optional()}),Ls=u({status:m("server_info"),serverId:c(),hostname:c().optional(),version:c().optional(),capabilities:K(c(),M()),features:K(c(),M())}),Us=u({type:m("status"),payload:Ls}),Ks=u({type:m("ping"),requestId:c(),clientSentAt:_e.optional()}),Vs=u({type:m("pong"),requestId:c(),clientSentAt:_e.optional(),serverReceivedAt:_e,serverSentAt:_e}),Bt=ye(["initializing","idle","running","error","closed"]),At=u({mimeType:c().optional(),data:c().optional()}).passthrough(),Gs=u({prs:W(M()).optional(),issues:W(M()).optional()}).passthrough(),Js=u({provider:c(),cwd:c(),modeId:c().optional(),model:c().optional(),thinkingOptionId:c().optional(),featureValues:K(c(),M()).optional(),title:c().nullable().optional(),approvalPolicy:c().optional(),sandboxMode:c().optional(),networkAccess:R().optional(),webSearch:R().optional(),extra:u({pi:M().optional()}).passthrough().optional(),systemPrompt:c().optional(),mcpServers:K(c(),M()).optional()}),Xs=u({type:m("create_agent_request"),requestId:c(),config:Js,env:K(c(),c()).optional(),workspaceId:c().optional(),worktreeName:c().optional(),initialPrompt:c().optional(),clientMessageId:c().optional(),outputSchema:K(c(),M()).optional(),images:W(At).optional(),attachments:Gs.optional(),git:M().optional(),worktree:M().optional(),autoArchive:R().optional(),labels:K(c(),c()).default({})}),Ys=u({type:m("create_agent_response"),requestId:c(),payload:u({agentId:c()}).passthrough()}),Qs=u({type:m("agent_update"),agentId:c(),status:Bt.optional(),title:c().nullable().optional(),labels:K(c(),c()).optional()}),Zs=u({type:m("agent_status"),agentId:c(),status:Bt}),eo=u({type:m("agent_list"),agents:W(u({id:c()}).passthrough())}),to=u({type:m("agent_deleted"),agentId:c()}),no=u({type:m("agent_archived"),agentId:c(),archivedAt:qt.optional()}),Mt=Te("kind",[u({kind:m("shell"),command:c().optional(),output:c().optional()}),u({kind:m("read"),path:c().optional(),output:c().optional()}),u({kind:m("edit"),path:c().optional(),diff:c().optional(),output:c().optional()}),u({kind:m("write"),path:c().optional(),output:c().optional()}),u({kind:m("search"),query:c().optional(),output:c().optional()}),u({kind:m("fetch"),url:c().optional(),output:c().optional()}),u({kind:m("task"),description:c().optional(),output:c().optional()})]),so=Te("kind",[u({kind:m("user_message"),messageId:c().optional(),text:c().optional(),images:W(At).optional()}),u({kind:m("assistant_message"),messageId:c().optional(),text:c().optional()}),u({kind:m("reasoning"),text:c().optional()}),u({kind:m("tool_call"),callId:c().optional(),tool:Mt,status:c().optional()}),u({kind:m("turn_started"),turnId:c().optional()}),u({kind:m("turn_completed"),turnId:c().optional()}),u({kind:m("turn_failed"),turnId:c().optional(),error:c().optional()}),u({kind:m("turn_canceled"),turnId:c().optional()}),u({kind:m("error"),message:c().optional()})]),oo=u({type:m("agent_stream"),agentId:c(),seq:C().optional(),timestamp:_e.optional(),event:so}),ro=ye(["before","after"]),ao=u({start:C(),end:C()}),io=u({type:m("fetch_agent_timeline_request"),requestId:c(),agentId:c(),cursor:c().nullable().optional(),direction:ro,limit:C().optional()}),co=u({type:m("fetch_agent_timeline_response"),requestId:c(),agentId:c().optional(),items:W(M()),seqStart:C(),seqEnd:C(),sourceSeqRanges:W(ao),collapsed:R(),hasNewer:R(),startCursor:c().nullable().optional(),endCursor:c().nullable().optional()}),lo=u({type:m("agent_permission_request"),requestId:c(),agentId:c(),toolName:c().optional(),tool:Mt.optional(),action:M().optional(),responses:W(c()).optional()}),uo=u({type:m("agent_permission_resolved"),requestId:c(),agentId:c(),decision:c().optional()}),po=u({type:m("agent.permission.respond.request"),requestId:c(),permissionRequestId:c(),response:M()}),fo=u({type:m("agent.permission.respond.response"),requestId:c(),payload:u({resolved:R()}).passthrough()}),ho=u({type:m("respond_to_permission"),requestId:c(),permissionRequestId:c(),response:M()}),$t=ye(["conversation","files","both"]),go=u({type:m("agent.rewind.request"),requestId:c(),agentId:c(),messageId:c(),mode:$t}).passthrough(),mo=u({type:m("agent.rewind.response"),requestId:c(),payload:u({agentId:c(),messageId:c(),mode:$t,truncatedAt:c().optional()}).passthrough()}).passthrough(),_o=u({input:C().optional(),output:C().optional(),cacheRead:C().optional(),cacheWrite:C().optional(),total:C().optional()}).passthrough(),yo=u({tokens:C().nullable().optional(),contextWindow:C().optional(),percent:C().nullable().optional()}).passthrough(),bo=u({type:m("agent_session_stats_request"),requestId:c(),agentId:c()}).passthrough(),wo=u({type:m("agent_session_stats_response"),requestId:c(),payload:u({sessionId:c().optional(),sessionFile:c().optional(),userMessages:C().optional(),assistantMessages:C().optional(),toolCalls:C().optional(),toolResults:C().optional(),totalMessages:C().optional(),tokens:_o.optional(),cost:C().optional(),contextUsage:yo.optional()}).passthrough()}).passthrough(),So=u({type:m("agent_compact_request"),requestId:c(),agentId:c(),customInstructions:c().optional()}).passthrough(),xo=u({type:m("agent_compact_response"),requestId:c(),payload:u({summary:c().optional(),firstKeptEntryId:c().optional(),tokensBefore:C().optional(),details:M().optional()}).passthrough()}).passthrough(),vo=u({type:m("agent_new_session_request"),requestId:c(),agentId:c()}).passthrough(),ko=u({type:m("agent_new_session_response"),requestId:c(),payload:u({cancelled:R()}).passthrough()}).passthrough(),Io=u({type:m("agent_switch_session_request"),requestId:c(),agentId:c(),sessionPath:c()}).passthrough(),Co=u({type:m("agent_switch_session_response"),requestId:c(),payload:u({cancelled:R()}).passthrough()}).passthrough(),To=u({type:m("agent_fork_request"),requestId:c(),agentId:c(),entryId:c()}).passthrough(),jo=u({type:m("agent_fork_response"),requestId:c(),payload:u({text:c(),cancelled:R()}).passthrough()}).passthrough(),Eo=u({type:m("agent_fork_messages_request"),requestId:c(),agentId:c()}).passthrough(),No=u({type:m("agent_fork_messages_response"),requestId:c(),payload:u({messages:W(u({entryId:c(),text:c()}).passthrough())}).passthrough()}).passthrough(),Ro=u({type:m("agent_clone_request"),requestId:c(),agentId:c()}).passthrough(),qo=u({type:m("agent_clone_response"),requestId:c(),payload:u({cancelled:R()}).passthrough()}).passthrough(),Bo=u({type:m("agent_set_session_name_request"),requestId:c(),agentId:c(),name:c()}).passthrough(),Ao=u({type:m("agent_set_session_name_response"),requestId:c(),payload:u({}).passthrough().optional()}).passthrough(),Mo=u({type:m("agent_export_html_request"),requestId:c(),agentId:c(),outputPath:c().optional()}).passthrough(),$o=u({type:m("agent_export_html_response"),requestId:c(),payload:u({path:c()}).passthrough()}).passthrough(),Do=u({type:m("agent_set_model_request"),requestId:c(),agentId:c(),provider:c(),modelId:c()}).passthrough(),Oo=u({type:m("agent_set_model_response"),requestId:c(),payload:u({}).passthrough()}).passthrough(),Fo=u({type:m("agent_cycle_model_request"),requestId:c(),agentId:c()}).passthrough(),Po=u({type:m("agent_cycle_model_response"),requestId:c(),payload:u({model:M().nullable().optional(),thinkingLevel:c().optional(),isScoped:R().optional()}).passthrough()}).passthrough(),Ho=u({type:m("agent_last_assistant_text_request"),requestId:c(),agentId:c()}).passthrough(),zo=u({type:m("agent_last_assistant_text_response"),requestId:c(),payload:u({text:c().nullable()}).passthrough()}).passthrough(),Wo=u({type:m("rpc_error"),requestId:c(),code:c().optional(),message:c().optional(),error:c().optional()}),Lo=Te("type",[Xs,Ys,Qs,Zs,eo,to,no,oo,io,co,lo,uo,po,fo,ho,go,mo,bo,wo,So,xo,vo,ko,Io,Co,To,jo,Eo,No,Ro,qo,Bo,Ao,Mo,$o,Do,Oo,Fo,Po,Ho,zo,Wo]),Uo=u({type:c()}).passthrough(),Ko=u({type:m("session"),message:mt([Lo,Uo])});Te("type",[Ws,Us,Ks,Vs,Ko]);const oe={Output:1,Input:2,Resize:3,Snapshot:4,Restore:5},Vo=Object.fromEntries(Object.entries(oe).map(([t,e])=>[e,t])),Dt=u({rows:C().int().nonnegative(),cols:C().int().nonnegative()});class he extends Error{constructor(e){super(e),this.name="TerminalFrameError"}}const Go=new TextEncoder,Jo=new TextDecoder;function Xo(t){if(!Number.isInteger(t)||t<0||t>255)throw new he(`slot must be an integer 0–255, got ${t}`)}function pe(t,e,n){const s=new Uint8Array(2+n.length);return s[0]=t,s[1]=e,s.set(n,2),s}function kl(t){switch(Xo(t.slot),t.opcode){case"Output":return pe(oe.Output,t.slot,t.data);case"Input":return pe(oe.Input,t.slot,t.data);case"Snapshot":return pe(oe.Snapshot,t.slot,t.data);case"Restore":return pe(oe.Restore,t.slot,t.data);case"Resize":{const e=JSON.stringify(Dt.parse({rows:t.rows,cols:t.cols}));return pe(oe.Resize,t.slot,Go.encode(e))}}}function Yo(t){if(t.length<2)throw new he(`frame too short: ${t.length} bytes (need ≥ 2)`);const e=t[0],n=t[1],s=Vo[e];if(!s)throw new he(`unknown terminal opcode 0x${e.toString(16)}`);const o=t.subarray(2);if(s==="Resize"){let r;try{r=JSON.parse(Jo.decode(o))}catch{throw new he("resize payload is not valid JSON")}const a=Dt.safeParse(r);if(!a.success)throw new he("resize payload is not { rows, cols }");return{opcode:"Resize",slot:n,rows:a.data.rows,cols:a.data.cols}}return{opcode:s,slot:n,data:o.slice()}}const ae={Begin:16,Chunk:17,End:18,Error:19},Qo=Object.fromEntries(Object.entries(ae).map(([t,e])=>[e,t])),Ot=u({transferId:c(),fileName:c().optional(),mimeType:c().optional(),totalBytes:C().int().nonnegative().optional()});class ge extends Error{constructor(e){super(e),this.name="FileTransferFrameError"}}const ot=new TextEncoder,rt=new TextDecoder;function Zo(t){if(!Number.isInteger(t)||t<0||t>255)throw new ge(`stream must be an integer 0–255, got ${t}`)}function xe(t,e,n){const s=new Uint8Array(2+n.length);return s[0]=t,s[1]=e,s.set(n,2),s}function Re(t){switch(Zo(t.stream),t.opcode){case"Begin":return xe(ae.Begin,t.stream,ot.encode(JSON.stringify(Ot.parse(t.meta))));case"Chunk":return xe(ae.Chunk,t.stream,t.data);case"End":return xe(ae.End,t.stream,new Uint8Array([t.ok?1:0]));case"Error":return xe(ae.Error,t.stream,ot.encode(t.message))}}function er(t){if(t.length<2)throw new ge(`frame too short: ${t.length} bytes (need ≥ 2)`);const e=t[0],n=t[1],s=Qo[e];if(!s)throw new ge(`unknown file-transfer opcode 0x${e.toString(16)}`);const o=t.subarray(2);switch(s){case"Begin":{let r;try{r=JSON.parse(rt.decode(o))}catch{throw new ge("begin payload is not valid JSON")}const a=Ot.safeParse(r);if(!a.success)throw new ge("begin payload is not a valid transfer header");return{opcode:"Begin",stream:n,meta:a.data}}case"Chunk":return{opcode:"Chunk",stream:n,data:o.slice()};case"End":return{opcode:"End",stream:n,ok:(o[0]??1)!==0};case"Error":return{opcode:"Error",stream:n,message:rt.decode(o)}}}function tr(t){try{return er(t)}catch{return null}}const nr=c().regex(/^[a-z][a-z0-9-]*$/,"invalid provider id"),sr=ye(["safe","moderate","dangerous","planning"]),or=u({supportsStreaming:R(),supportsSessionPersistence:R(),supportsDynamicModes:R(),supportsMcpServers:R(),supportsReasoningStream:R(),supportsToolInvocations:R(),supportsRewindConversation:R().optional(),supportsRewindFiles:R().optional(),supportsRewindBoth:R().optional()}).passthrough(),rr=u({id:c(),label:c().optional(),description:c().optional(),icon:c().optional(),colorTier:sr});u({id:nr,label:c(),description:c().optional(),extends:c().optional(),modes:W(rr),capabilities:or});function Fe(t){return typeof t=="string"?t:t instanceof Uint8Array||Buffer.isBuffer(t)?t.toString("utf8"):String(t??"")}function Ft(t){let e=null;const n={onMessage:null,onClose:null,onError:null,get isOpen(){return e!==null&&e.readyState===1},connect(s){return new Promise((o,r)=>{const a=t??(()=>new WebSocket(s));try{e=t?a(s):new WebSocket(s)}catch(l){r(l);return}e.onopen=()=>o(),e.onerror=l=>{var d;(e==null?void 0:e.readyState)!==1&&r(l),(d=n.onError)==null||d.call(n,l)},e.onclose=l=>{var d;(d=n.onClose)==null||d.call(n,l.code,Fe(l.reason))},e.onmessage=l=>{var p,h,_,f;const{data:d}=l;d instanceof ArrayBuffer||d instanceof Uint8Array?(p=n.onMessage)==null||p.call(n,d):typeof d=="string"?(h=n.onMessage)==null||h.call(n,d):typeof Blob<"u"&&d instanceof Blob?(_=n.onMessage)==null||_.call(n,d):Buffer.isBuffer(d)&&((f=n.onMessage)==null||f.call(n,d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength)))}})},sendText(s){e==null||e.send(s)},sendBinary(s){e==null||e.send(s)},close(s=1e3,o=""){e==null||e.close(s,o),e=null}};return n}const me="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Pt(t){let e="";for(let n=0;n<t.length;n+=3){const s=t[n],o=n+1<t.length,r=n+2<t.length,a=o?t[n+1]:0,l=r?t[n+2]:0;e+=me[s>>2],e+=me[(s&3)<<4|a>>4],e+=o?me[(a&15)<<2|l>>6]:"=",e+=r?me[l&63]:"="}return e}function Ht(t){const e=t.replace(/=+$/,""),n=[];let s=0,o=0;for(const r of e){const a=me.indexOf(r);if(a===-1)throw new Error(`invalid base64 character: ${JSON.stringify(r)}`);s=s<<6|a,o+=6,o>=8&&(o-=8,n.push(s>>o&255))}return new Uint8Array(n)}function ar(t){try{const e=JSON.parse(t);return!e||typeof e.type!="string"?null:e}catch{return null}}const Ce=24;function zt(t,e){const n=ie.randomBytes(Ce),s=ie.box.after(t,n,e),o=new Uint8Array(n.length+s.length);return o.set(n,0),o.set(s,n.length),Pt(o)}function Wt(t,e){let n;try{n=Ht(t)}catch{return null}if(n.length<Ce)return null;const s=n.slice(0,Ce),o=n.slice(Ce);return ie.box.open.after(o,s,e)}function ir(t,e){return zt(new TextEncoder().encode(t),e)}function cr(t,e){const n=Wt(t,e);return n?new TextDecoder().decode(n):null}function lr(t,e,n,s,o,r){let a=!1;return n.onClose(l=>{var d;a=!0,(d=s.onClose)==null||d.call(s,l)}),{handleAppFrame(l){var h,_;if(a)return;const d=o();if(!r()||!d)return;const p=cr(l.frame,d);if(p===null){(h=s.onAuthError)==null||h.call(s,new Error(`relay ${t} channel: message failed authentication`));return}(_=s.onMessage)==null||_.call(s,p)},handleBinaryFrame(l){var h,_;if(a)return;const d=o();if(!r()||!d)return;const p=Wt(l.frame,d);if(p===null){(h=s.onAuthError)==null||h.call(s,new Error(`relay ${t} channel: binary message failed authentication`));return}(_=s.onBinaryMessage)==null||_.call(s,p)},send(l){if(a)throw new Error(`relay ${t} channel: cannot send after close()`);const d=o();if(!r()||!d)throw new Error(`relay ${t} channel: cannot send before the E2EE handshake completes`);n.send(JSON.stringify({type:"e2ee_app",frame:ir(l,d)}))},sendBinary(l){if(a)throw new Error(`relay ${t} channel: cannot send after close()`);const d=o();if(!r()||!d)throw new Error(`relay ${t} channel: cannot send before the E2EE handshake completes`);n.send(JSON.stringify({type:"e2ee_bin",frame:zt(l,d)}))},close(){a||(a=!0,n.close())}}}function dr(t){const{transport:e,attachment:n,daemonPublicKey:s}=t,o=t.events??{},r=ie.box.keyPair(),a=ie.box.before(s,r.secretKey);let l=!1;const d=lr("client",n,e,o,()=>a,()=>l);return e.onMessage(p=>{var _;const h=ar(p);if(h){if(h.type==="e2ee_ready"){if(l)return;l=!0,(_=o.onReady)==null||_.call(o);return}if(h.type==="e2ee_app"){d.handleAppFrame(h);return}h.type==="e2ee_bin"&&d.handleBinaryFrame(h)}}),e.send(JSON.stringify({type:"e2ee_hello",ephemeralPublicKey:Pt(r.publicKey)})),{role:"client",attachment:n,get ready(){return l},send:d.send,sendBinary:d.sendBinary,close:d.close}}const ur=16;function pr(t){const e=ie.hash(t);let n="";for(let s=0;s<ur;s++)n+=e[s].toString(16).padStart(2,"0");return n}function fr(t){const e=t.useTls?"wss":"ws",n=t.endpoint.replace(/^(?:https?|wss?):\/\//,"").replace(/\/+$/,"");return`${e}://${n}`}function hr(t){let e=null,n=null;const s=t.sessionId??pr(t.daemonPublicKey),o={onMessage:null,onClose:null,onError:null,get isOpen(){return e!==null&&e.readyState===1&&n!==null&&n.ready},connect(r){return new Promise((a,l)=>{const d=t.factory??(()=>new WebSocket(r));try{e=t.factory?d(r):new WebSocket(r)}catch(f){l(f);return}const p=e,h=[],_=[];p.onopen=()=>{p.send(JSON.stringify({type:"relay_register",sessionId:s})),n=dr({transport:{send:f=>p.send(f),onMessage:f=>h.push(f),onClose:f=>_.push(f),close:()=>p.close()},attachment:{sessionId:s},daemonPublicKey:t.daemonPublicKey,events:{onReady:()=>a(),onMessage:f=>{var x;return(x=o.onMessage)==null?void 0:x.call(o,f)},onBinaryMessage:f=>{var x;return(x=o.onMessage)==null?void 0:x.call(o,f.slice().buffer)},onAuthError:f=>{var x;return(x=o.onError)==null?void 0:x.call(o,f)}}})},p.onerror=f=>{var x;p.readyState!==1&&l(f),(x=o.onError)==null||x.call(o,f)},p.onclose=f=>{var x;for(const S of _)S(Fe(f.reason));(x=o.onClose)==null||x.call(o,f.code,Fe(f.reason))},p.onmessage=f=>{const{data:x}=f;if(typeof x=="string")for(const S of h)S(x)}})},sendText(r){if(!n||!n.ready)throw new Error("relay transport: cannot send before the E2EE handshake completes");n.send(r)},sendBinary(r){if(!n||!n.ready)throw new Error("relay transport: cannot send before the E2EE handshake completes");n.sendBinary(r)},close(r=1e3,a=""){n==null||n.close(),n=null,e==null||e.close(r,a),e=null}};return o}function gr(t){const e=t.indexOf("#"),n=e===-1?t:t.slice(e+1),s=new URLSearchParams(n),o=s.get("offer");if(!o)return null;let r;try{r=Ht(o)}catch{return null}const a=s.get("relay");if(a){const d={endpoint:a,useTls:s.get("relayTls")==="1"};return{publicKeyB64:o,publicKey:r,relay:d}}const l=s.get("host")??void 0;return{publicKeyB64:o,publicKey:r,...l?{host:l}:{}}}const mr=1;function Pe(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`id-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}class _r extends Error{constructor(e,n,s){super(e),this.requestId=n,this.code=s,this.name="RpcError"}}class at extends Error{constructor(e){super(`RPC ${e} timed out`),this.requestId=e,this.name="RpcTimeoutError"}}class yr{constructor(e){I(this,"transport");I(this,"rpcTimeoutMs");I(this,"now");I(this,"_state","idle");I(this,"_serverId",null);I(this,"_features",{});I(this,"_serverCapabilities",{});I(this,"pending",new Map);I(this,"sessionHandlers",new Set);I(this,"terminalHandlers",new Set);I(this,"fileTransferHandlers",new Set);I(this,"stateHandlers",new Set);I(this,"helloResolve",null);I(this,"helloReject",null);this.options=e,this.transport=e.transport??Ft(),this.rpcTimeoutMs=e.rpcTimeoutMs??3e4,this.now=e.now??(()=>Date.now()),this.transport.onMessage=n=>this.handleIncoming(n),this.transport.onClose=(n,s)=>this.handleClose(n,s),this.transport.onError=()=>{}}get state(){return this._state}get serverId(){return this._serverId}get features(){return this._features}get serverCapabilities(){return this._serverCapabilities}hasFeature(e){return!!this._features[e]}async connect(){this.setState("connecting"),await this.transport.connect(this.options.url);const e=new Promise((s,o)=>{this.helloResolve=s,this.helloReject=o});this.transport.sendText(JSON.stringify({type:"hello",clientId:this.options.clientId,clientType:this.options.clientType,protocolVersion:this.options.protocolVersion??mr,appVersion:this.options.appVersion,capabilities:this.options.capabilities}));const n=await e;return this._serverId=n.serverId,this._features=n.features,this._serverCapabilities=n.capabilities,this.setState("open"),n}close(e=1e3,n=""){this.setState("closing"),this.transport.close(e,n)}request(e,n={},s){const o=n.requestId??Pe();return new Promise((r,a)=>{const l=s??this.rpcTimeoutMs,d=l>0?setTimeout(()=>{this.pending.delete(o),a(new at(o))},l):null;this.pending.set(o,{resolve:p=>r(p),reject:a,timer:d}),this.sendSession({type:e,...n,requestId:o})})}sendSession(e){this.transport.sendText(JSON.stringify({type:"session",message:e}))}sendBinary(e){this.transport.sendBinary(e)}ping(e=1e4){const n=Pe();return new Promise((s,o)=>{const r=e>0?setTimeout(()=>{this.pending.delete(n),o(new at(n))},e):null;this.pending.set(n,{resolve:()=>s(),reject:o,timer:r}),this.transport.sendText(JSON.stringify({type:"ping",requestId:n,clientSentAt:this.now()}))})}onSessionMessage(e){return this.sessionHandlers.add(e),()=>this.sessionHandlers.delete(e)}onTerminalFrame(e){return this.terminalHandlers.add(e),()=>this.terminalHandlers.delete(e)}onFileTransferFrame(e){return this.fileTransferHandlers.add(e),()=>this.fileTransferHandlers.delete(e)}onStateChange(e){return this.stateHandlers.add(e),()=>this.stateHandlers.delete(e)}setState(e){if(this._state!==e){this._state=e;for(const n of this.stateHandlers)n(e)}}handleClose(e,n){this.helloReject&&(this.helloReject(new Error(`socket closed during handshake: ${n}`)),this.helloResolve=null,this.helloReject=null);for(const[,s]of this.pending)s.timer&&clearTimeout(s.timer),s.reject(new Error(`socket closed: ${n}`));this.pending.clear(),this.setState("closed")}handleIncoming(e){if(typeof e=="string"){this.handleTextFrame(e);return}if(e instanceof ArrayBuffer){this.handleBinaryFrame(new Uint8Array(e));return}typeof e.arrayBuffer=="function"&&e.arrayBuffer().then(n=>this.handleBinaryFrame(new Uint8Array(n)))}handleBinaryFrame(e){const n=e[0];if(n!==void 0&&Object.values(ae).includes(n)){const r=tr(e);if(!r)return;for(const a of this.fileTransferHandlers)a(r);return}const o=Yo(e);for(const r of this.terminalHandlers)r(o)}handleTextFrame(e){let n;try{n=JSON.parse(e)}catch{return}const s=n;switch(s.type){case"status":this.handleStatus(s);return;case"pong":this.resolvePending(s.requestId,void 0);return;case"ping":this.transport.sendText(JSON.stringify({type:"pong",requestId:s.requestId,serverReceivedAt:this.now(),serverSentAt:this.now()}));return;case"session":this.handleSession(s.message);return;default:return}}handleStatus(e){const n=e.payload;(n==null?void 0:n.status)==="server_info"&&this.helloResolve&&(this.helloResolve(n),this.helloResolve=null,this.helloReject=null)}handleSession(e){if(!e||typeof e!="object")return;const n=e;if(n.type==="rpc_error"&&typeof n.requestId=="string"){const s=this.pending.get(n.requestId);s&&(s.timer&&clearTimeout(s.timer),this.pending.delete(n.requestId),s.reject(new _r(n.message??n.error??"RPC failed",n.requestId,n.code)));return}if(typeof n.requestId=="string"&&this.pending.has(n.requestId)){const s="payload"in n?n.payload:n;this.resolvePending(n.requestId,s)}for(const s of this.sessionHandlers)s(e)}resolvePending(e,n){const s=this.pending.get(e);s&&(s.timer&&clearTimeout(s.timer),this.pending.delete(e),s.resolve(n))}}class br{constructor(e){this.daemon=e}get connection(){return this.daemon}async createAgent(e){return await this.daemon.request("create_agent_request",{...e})}agent(e){return new Sr(this.daemon,e)}workspace(e){return new xr(this.daemon,e)}get providers(){return new vr(this.daemon)}onAgentUpdate(e){return this.daemon.onSessionMessage(n=>{n.type==="agent_update"&&e(n)})}onWorkspaceUpdate(e){return this.daemon.onSessionMessage(n=>{n.type==="workspace_update"&&e(n)})}}class wr{constructor(e,n){this.daemon=e,this.agentId=n}fetch(e={}){return this.daemon.request("fetch_agent_timeline_request",{agentId:this.agentId,cursor:e.cursor,direction:e.direction,limit:e.limit})}subscribe(e){return this.daemon.onSessionMessage(n=>{const s=n;s.type==="agent_stream"&&s.agentId===this.agentId&&s.event&&e(s.event)})}}class Sr{constructor(e,n){I(this,"timeline");this.daemon=e,this.agentId=n,this.timeline=new wr(e,n)}send(e,n={}){return this.daemon.request("send_agent_prompt",{agentId:this.agentId,prompt:e,clientMessageId:n.clientMessageId,images:n.images})}run(e,n){return this.send(e,n)}interrupt(){return this.daemon.request("interrupt_agent",{agentId:this.agentId})}update(e){return this.daemon.request("update_agent",{agentId:this.agentId,...e})}resume(){return this.daemon.request("resume_agent",{agentId:this.agentId})}archive(){return this.daemon.request("archive_agent",{agentId:this.agentId})}delete(){return this.daemon.request("delete_agent",{agentId:this.agentId})}onUpdate(e){return this.daemon.onSessionMessage(n=>{const s=n;s.type==="agent_update"&&s.agentId===this.agentId&&e(s)})}sessionStats(){return this.daemon.request("agent_session_stats_request",{agentId:this.agentId})}compact(e){return this.daemon.request("agent_compact_request",{agentId:this.agentId,customInstructions:e})}newSession(){return this.daemon.request("agent_new_session_request",{agentId:this.agentId})}switchSession(e){return this.daemon.request("agent_switch_session_request",{agentId:this.agentId,sessionPath:e})}fork(e){return this.daemon.request("agent_fork_request",{agentId:this.agentId,entryId:e})}forkMessages(){return this.daemon.request("agent_fork_messages_request",{agentId:this.agentId})}clone(){return this.daemon.request("agent_clone_request",{agentId:this.agentId})}setSessionName(e){return this.daemon.request("agent_set_session_name_request",{agentId:this.agentId,name:e})}exportHtml(e){return this.daemon.request("agent_export_html_request",{agentId:this.agentId,outputPath:e})}setModel(e,n){return this.daemon.request("agent_set_model_request",{agentId:this.agentId,provider:e,modelId:n})}cycleModel(){return this.daemon.request("agent_cycle_model_request",{agentId:this.agentId})}lastAssistantText(){return this.daemon.request("agent_last_assistant_text_request",{agentId:this.agentId})}}class xr{constructor(e,n){this.daemon=e,this.workspaceId=n}onUpdate(e){return this.daemon.onSessionMessage(n=>{const s=n;s.type==="workspace_update"&&s.workspaceId===this.workspaceId&&e(s)})}}class vr{constructor(e){this.daemon=e}listProviders(){return this.daemon.request("list_providers",{})}listModels(e){return this.daemon.request("list_provider_models",{provider:e})}listModes(e){return this.daemon.request("list_provider_modes",{provider:e})}refreshSnapshot(){return this.daemon.request("providers.snapshot.refresh.request",{})}}const it=32*1024;function kr(t){const e=t.reduce((o,r)=>o+r.length,0),n=new Uint8Array(e);let s=0;for(const o of t)n.set(o,s),s+=o.length;return n}class Ir{constructor(e){I(this,"pending",new Map);I(this,"nextStream",1);I(this,"detach",null);this.daemon=e}start(){this.detach||(this.detach=this.daemon.onFileTransferFrame(e=>this.dispatch(e)))}stop(){var e;(e=this.detach)==null||e.call(this),this.detach=null;for(const[n,s]of this.pending)s.reject(new Error("file transfer router stopped")),this.pending.delete(n)}async download(e){const n=await this.daemon.request("file_download_token_request",{path:e});if(!n.ok||!n.token)throw new Error(n.error??"failed to issue download token");const s=this.nextStream++,o=new Promise((a,l)=>{this.pending.set(s,{chunks:[],meta:{},resolve:a,reject:l})}),r=await this.daemon.request("file_download_request",{token:n.token,stream:s});if(!r.ok)throw this.pending.delete(s),new Error(r.error??"download request failed");return o}async upload(e,n){const s=Pe(),o=await this.daemon.request("file_upload_request",{path:e,transferId:s});if(!o.ok||o.stream===void 0)throw new Error(o.error??"upload request failed");const r=o.stream;this.daemon.sendBinary(Re({opcode:"Begin",stream:r,meta:{transferId:s}}));for(let a=0;a<n.length;a+=it){const l=n.subarray(a,a+it);this.daemon.sendBinary(Re({opcode:"Chunk",stream:r,data:l}))}this.daemon.sendBinary(Re({opcode:"End",stream:r,ok:!0}))}dispatch(e){const n=this.pending.get(e.stream);if(n)switch(e.opcode){case"Begin":n.meta.fileName=e.meta.fileName,n.meta.mimeType=e.meta.mimeType;return;case"Chunk":n.chunks.push(e.data);return;case"End":this.pending.delete(e.stream),e.ok?n.resolve({bytes:kr(n.chunks),...n.meta}):n.reject(new Error("download failed"));return;case"Error":this.pending.delete(e.stream),n.reject(new Error(e.message));return}}}class Cr{constructor(e,n={}){I(this,"initialDelayMs");I(this,"maxDelayMs");I(this,"factor");I(this,"jitter");I(this,"maxAttempts");I(this,"setTimer");I(this,"clearTimer");I(this,"random");I(this,"attempt",0);I(this,"timer",null);I(this,"active",!1);I(this,"detachState",null);I(this,"reconnectedHandlers",new Set);I(this,"failedHandlers",new Set);this.daemon=e,this.initialDelayMs=n.initialDelayMs??500,this.maxDelayMs=n.maxDelayMs??3e4,this.factor=n.factor??2,this.jitter=n.jitter??.2,this.maxAttempts=n.maxAttempts??Number.POSITIVE_INFINITY,this.setTimer=n.setTimer??((s,o)=>setTimeout(s,o)),this.clearTimer=n.clearTimer??(s=>clearTimeout(s)),this.random=n.random??Math.random}delayForAttempt(e){const n=Math.min(this.maxDelayMs,this.initialDelayMs*this.factor**(e-1)),s=n*this.jitter*(this.random()*2-1);return Math.max(0,Math.round(n+s))}onReconnected(e){return this.reconnectedHandlers.add(e),()=>this.reconnectedHandlers.delete(e)}onReconnectFailed(e){return this.failedHandlers.add(e),()=>this.failedHandlers.delete(e)}start(){this.active||(this.active=!0,this.detachState=this.daemon.onStateChange(e=>{e==="closed"&&this.active&&this.scheduleReconnect(),e==="open"&&(this.attempt=0)}))}stop(){var e;this.active=!1,this.timer&&this.clearTimer(this.timer),this.timer=null,(e=this.detachState)==null||e.call(this),this.detachState=null}get attemptCount(){return this.attempt}scheduleReconnect(){if(!this.active||this.attempt>=this.maxAttempts)return;this.attempt+=1;const e=this.delayForAttempt(this.attempt);this.timer=this.setTimer(()=>{this.timer=null,this.tryReconnect()},e)}async tryReconnect(){if(!this.active)return;const e=this.attempt;try{await this.daemon.connect();for(const n of this.reconnectedHandlers)n({attempt:e,serverId:this.daemon.serverId})}catch(n){for(const s of this.failedHandlers)s(n,e);this.scheduleReconnect()}}}function ct(t){const e=t.trim();if(e==="")return e;const n=e.match(/^([a-z][a-z0-9+.-]*):\/\//i);if(!n)return`ws://${e.replace(/\/+$/,"")}`;const s=n[1].toLowerCase(),o=e.slice(n[0].length).replace(/\/+$/,"");switch(s){case"http":return`ws://${o}`;case"https":return`wss://${o}`;case"ws":case"wss":return`${s}://${o}`;default:return e}}function Tr(t){const e=gr(t);return e!=null&&e.relay?{mode:"relay",url:fr(e.relay),daemonPublicKey:e.publicKey}:e!=null&&e.host?{mode:"direct",url:ct(e.host)}:{mode:"direct",url:ct(t)}}function jr(){return"web-"+Math.random().toString(36).slice(2,10)}const j=ce()((t,e)=>({status:"idle",serverInfo:null,error:null,daemon:null,client:null,reconnection:null,async connect(n){e().disconnect();const s=Tr(n.url);let o;s.mode==="relay"?o=hr({daemonPublicKey:s.daemonPublicKey}):n.password&&(o=Ft(d=>new WebSocket(d,[`pi-studio.bearer.${n.password}`])));const r=new yr({url:s.url,clientId:n.clientId??jr(),clientType:"browser",capabilities:{},transport:o,rpcTimeoutMs:1800*1e3}),a=new br(r),l=new Cr(r);r.onStateChange(d=>t({status:d})),l.onReconnected(()=>t({error:null})),l.onReconnectFailed(d=>{t({error:d instanceof Error?d.message:String(d)})}),t({daemon:r,client:a,reconnection:l,error:null,status:"connecting"});try{const d=await r.connect();t({serverInfo:d}),l.start()}catch(d){throw t({error:d instanceof Error?d.message:String(d)}),d}},disconnect(){const{daemon:n,reconnection:s}=e();s==null||s.stop(),n==null||n.close(),t({status:"idle",serverInfo:null,daemon:null,client:null,reconnection:null})}})),Er=100,Nr=480,Rr=220,qr=280;function ve(t){return Math.min(Nr,Math.max(Er,t))}const v=ce()(t=>({host:"ws://127.0.0.1:6767",password:"",cwd:"~",cwdPickerOpen:!1,sessionMenu:null,fileMenu:null,rightSidebarTab:"files",collapsedWorkspaces:new Set,leftSidebarCollapsed:!1,rightSidebarCollapsed:!1,leftSidebarWidth:Rr,rightSidebarWidth:qr,setHost:e=>t({host:e}),setPassword:e=>t({password:e}),setCwd:e=>t({cwd:e}),openCwdPicker:()=>t({cwdPickerOpen:!0}),closeCwdPicker:()=>t({cwdPickerOpen:!1}),openSessionMenu:(e,n,s)=>t({sessionMenu:{sessionId:e,x:n,y:s}}),closeSessionMenu:()=>t({sessionMenu:null}),openFileMenu:(e,n,s,o)=>t({fileMenu:{path:e,isDirectory:n,x:s,y:o}}),closeFileMenu:()=>t({fileMenu:null}),setRightSidebarTab:e=>t({rightSidebarTab:e}),toggleWorkspaceCollapsed:e=>t(n=>{const s=new Set(n.collapsedWorkspaces);return s.has(e)?s.delete(e):s.add(e),{collapsedWorkspaces:s}}),toggleLeftSidebar:()=>t(e=>({leftSidebarCollapsed:!e.leftSidebarCollapsed})),toggleRightSidebar:()=>t(e=>({rightSidebarCollapsed:!e.rightSidebarCollapsed})),setLeftSidebarWidth:e=>t({leftSidebarWidth:ve(e)}),setRightSidebarWidth:e=>t({rightSidebarWidth:ve(e)}),resizeLeftSidebar:e=>t(n=>({leftSidebarWidth:ve(n.leftSidebarWidth+e)})),resizeRightSidebar:e=>t(n=>({rightSidebarWidth:ve(n.rightSidebarWidth+e)}))})),Br="_wrap_emmus_1",Ar="_dot_emmus_8",Mr="_open_emmus_15",$r="_connecting_emmus_18",Dr="_closed_emmus_21",Or="_idle_emmus_22",Fr="_closing_emmus_23",qe={wrap:Br,dot:Ar,open:Mr,connecting:$r,closed:Dr,idle:Or,closing:Fr},Pr={idle:"disconnected",connecting:"connecting…",open:"connected",closing:"disconnecting…",closed:"disconnected"};function Hr(){const t=j(n=>n.status),e=j(n=>n.error);return i.jsxs("span",{className:qe.wrap,title:e??void 0,children:[i.jsx("span",{className:B(qe.dot,qe[t])}),Pr[t]??t]})}const zr="_toolbar_i9hmh_1",Wr="_brand_i9hmh_10",Lr="_version_i9hmh_16",Ur="_sep_i9hmh_22",Kr="_host_i9hmh_28",Vr="_password_i9hmh_31",Gr="_sidebarToggles_i9hmh_34",Q={toolbar:zr,brand:Wr,version:Lr,sep:Ur,host:Kr,password:Vr,sidebarToggles:Gr};function Jr(){const t=j(f=>f.status),e=j(f=>f.connect),n=j(f=>f.disconnect),s=v(f=>f.host),o=v(f=>f.setHost),r=v(f=>f.password),a=v(f=>f.setPassword),l=v(f=>f.leftSidebarCollapsed),d=v(f=>f.toggleLeftSidebar),p=v(f=>f.rightSidebarCollapsed),h=v(f=>f.toggleRightSidebar),_=t==="open"||t==="connecting";return i.jsxs("div",{className:Q.toolbar,children:[i.jsx("span",{className:Q.brand,children:"Pi-Studio"}),i.jsxs("span",{className:Q.version,children:["v","0.0.32"]}),i.jsx(Hr,{}),i.jsx("div",{className:Q.sep}),i.jsx(Oe,{className:Q.host,value:s,onChange:f=>o(f.target.value),placeholder:"host:port, ws://…/http://…, or a pasted pairing link",disabled:_}),i.jsx(Oe,{className:Q.password,type:"password",value:r,onChange:f=>a(f.target.value),placeholder:"password",disabled:_}),t==="open"||t==="connecting"||t==="closing"?i.jsx(H,{size:"sm",onClick:()=>n(),children:"Disconnect"}):i.jsx(H,{size:"sm",variant:"default",onClick:()=>void e({url:s,password:r||void 0}),children:"Connect"}),i.jsxs("div",{className:Q.sidebarToggles,children:[i.jsx(H,{size:"sm",variant:"ghost",iconOnly:!0,title:l?"Show sessions sidebar":"Hide sessions sidebar",onClick:()=>d(),children:l?i.jsx(fn,{size:16}):i.jsx(hn,{size:16})}),i.jsx(H,{size:"sm",variant:"ghost",iconOnly:!0,title:p?"Show files/changes sidebar":"Hide files/changes sidebar",onClick:()=>h(),children:p?i.jsx(gn,{size:16}):i.jsx(mn,{size:16})})]})]})}const He={rows:[],streamingAssistantIndex:null,streamingReasoningIndex:null,toolIndexByCallId:{}};let lt=0;function X(){return lt+=1,`row-${lt}`}function Xr(t){switch(t.kind){case"shell":return t.command??"";case"read":case"write":return t.path??"";case"edit":return t.path??"";case"search":return t.query??"";case"fetch":return t.url??"";case"task":return t.description??"";default:return""}}function Yr(t,e){return t??`${e.kind}:${Xr(e)}`}function Qr(t){return{...t,streamingAssistantIndex:null,streamingReasoningIndex:null}}function Zr(t,e){var r;const n=t.rows.slice();let s=t.streamingAssistantIndex;if(s===null||((r=n[s])==null?void 0:r.kind)!=="assistant"){const a={kind:"assistant",id:X(),text:"",streaming:!0};n.push(a),s=n.length-1}const o=n[s];return!o||o.kind!=="assistant"?t:(n[s]={...o,text:o.text+e},{...t,rows:n,streamingAssistantIndex:s,streamingReasoningIndex:null})}function ea(t,e){var r;const n=t.rows.slice();let s=t.streamingReasoningIndex;if(s===null||((r=n[s])==null?void 0:r.kind)!=="reasoning"){const a={kind:"reasoning",id:X(),text:"",streaming:!0};n.push(a),s=n.length-1}const o=n[s];return!o||o.kind!=="reasoning"?t:(n[s]={...o,text:o.text+e},{...t,rows:n,streamingReasoningIndex:s,streamingAssistantIndex:null})}function ta(t,e){if(t.kind!==e.kind)return e;const n={...t};for(const[s,o]of Object.entries(e))o!==void 0&&o!==""&&(n[s]=o);return n}function na(t,e){var l;const n=Yr(e.callId,e.tool),s=e.status==="completed"||e.status==="error"?e.status:"running",o=t.toolIndexByCallId[n],r=t.rows.slice();if(o!==void 0&&((l=r[o])==null?void 0:l.kind)==="tool"){const d=r[o];return d.kind!=="tool"?t:(r[o]={...d,tool:ta(d.tool,e.tool),status:s},{...t,rows:r,streamingAssistantIndex:null,streamingReasoningIndex:null})}const a={kind:"tool",id:X(),callId:n,tool:e.tool,status:s};return r.push(a),{...t,rows:r,toolIndexByCallId:{...t.toolIndexByCallId,[n]:r.length-1},streamingAssistantIndex:null,streamingReasoningIndex:null}}function Ye(t){const e=t.rows.slice();if(t.streamingAssistantIndex!==null){const n=e[t.streamingAssistantIndex];(n==null?void 0:n.kind)==="assistant"&&(e[t.streamingAssistantIndex]={...n,streaming:!1})}if(t.streamingReasoningIndex!==null){const n=e[t.streamingReasoningIndex];(n==null?void 0:n.kind)==="reasoning"&&(e[t.streamingReasoningIndex]={...n,streaming:!1})}return{...t,rows:e,streamingAssistantIndex:null,streamingReasoningIndex:null}}function sa(t,e){const n=Ye(t),s={kind:"error",id:X(),text:e||"turn failed"};return{...n,rows:[...n.rows,s]}}function oa(t){const e=Ye(t),n={kind:"system",id:X(),text:"(canceled)"};return{...e,rows:[...e.rows,n]}}function ra(t,e){const n={kind:"error",id:X(),text:e||"error"};return{...t,rows:[...t.rows,n]}}function aa(t,e,n,s){if(s!==void 0){const r=t.rows.findIndex(a=>a.kind==="user"&&a.pending&&a.clientMessageId===s);if(r!==-1){const a=t.rows.slice(),l=a[r];if((l==null?void 0:l.kind)==="user")return a[r]={...l,text:e,images:n,pending:!1},{...t,rows:a}}}const o={kind:"user",id:X(),text:e,images:n,clientMessageId:s};return{...t,rows:[...t.rows,o]}}function Lt(t,e){switch(e.kind){case"turn_started":return Qr(t);case"user_message":return aa(t,e.text??"",e.images,e.messageId);case"assistant_message":return Zr(t,e.text??"");case"reasoning":return ea(t,e.text??"");case"tool_call":return na(t,e);case"turn_completed":return Ye(t);case"turn_failed":return sa(t,e.error);case"turn_canceled":return oa(t);case"error":return ra(t,e.message);default:return t}}function ia(t,e,n,s){const o={kind:"user",id:X(),text:n,images:s,clientMessageId:e,pending:!0};return{...t,rows:[...t.rows,o]}}function ca(t,e){const n=t.rows.findIndex(r=>r.kind==="user"&&r.pending&&r.clientMessageId===e);if(n===-1)return t;const s=t.rows.slice(),o=s[n];return(o==null?void 0:o.kind)!=="user"?t:(s[n]={...o,pending:!1,failed:!0},{...t,rows:s})}let dt=0;function la(){return dt+=1,`s-${Date.now().toString(36)}-${dt}`}const $=ce()((t,e)=>({sessions:{},order:[],activeSessionId:null,createSession(n){const s=la(),o={id:s,agentId:null,title:"New chat",status:"idle",cwd:n,timeline:He,userMessageCount:0};return t(r=>({sessions:{...r.sessions,[s]:o},order:[s,...r.order],activeSessionId:s})),s},hydrate(n){t(s=>s.sessions[n.id]?s:{sessions:{...s.sessions,[n.id]:n},order:[...s.order,n.id]})},bindAgent(n,s){t(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,agentId:s}}}:o})},setStatus(n,s){t(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,status:s}}}:o})},setStatusByAgentId(n,s){const o=e().findByAgentId(n);o&&e().setStatus(o.id,s)},setTitle(n,s){t(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,title:s}}}:o})},setCwd(n,s){t(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,cwd:s}}}:o})},applyStreamEvent(n,s){t(o=>{const r=o.sessions[n];if(!r)return o;const a=Lt(r.timeline,s);let l=r.title;if(s.kind==="turn_completed"&&l==="New chat"){const d=a.rows.slice().reverse().find(p=>p.kind==="assistant");d&&d.kind==="assistant"&&d.text&&(l=d.text.slice(0,40)+(d.text.length>40?"…":""))}return{sessions:{...o.sessions,[n]:{...r,timeline:a,title:l}}}})},addOptimisticUserMessage(n,s,o,r){t(a=>{const l=a.sessions[n];if(!l)return a;const d=ia(l.timeline,s,o,r);return{sessions:{...a.sessions,[n]:{...l,timeline:d,userMessageCount:l.userMessageCount+1}}}})},markUserMessageFailed(n,s){t(o=>{const r=o.sessions[n];if(!r)return o;const a=ca(r.timeline,s);return{sessions:{...o.sessions,[n]:{...r,timeline:a}}}})},activate(n){t({activeSessionId:n})},remove(n){t(s=>{const{[n]:o,...r}=s.sessions,a=s.order.filter(d=>d!==n),l=s.activeSessionId===n?a[0]??null:s.activeSessionId;return{sessions:r,order:a,activeSessionId:l}})},findByAgentId(n){return Object.values(e().sessions).find(s=>s.agentId===n)}}));function Be(t,e){return t.filter(n=>n.workspaceCwd===e)}const T=ce()((t,e)=>({tabs:[],activeTabId:null,activeWorkspaceCwd:null,lastActiveTabByWorkspace:{},open(n){const s=e().tabs.find(o=>o.id===n.id);if(s){e().activate(s.id);return}t(o=>({tabs:[...o.tabs,n],activeTabId:n.id,activeWorkspaceCwd:n.workspaceCwd,lastActiveTabByWorkspace:{...o.lastActiveTabByWorkspace,[n.workspaceCwd]:n.id}}))},close(n){t(s=>{const o=s.tabs.find(p=>p.id===n);if(!o)return s;const r=s.tabs.findIndex(p=>p.id===n),a=s.tabs.filter(p=>p.id!==n);let l=s.activeTabId;const d={...s.lastActiveTabByWorkspace};if(l===n){const p=Be(a,o.workspaceCwd),h=Math.min(r,p.length-1),_=p[h];l=(_==null?void 0:_.id)??null}if(d[o.workspaceCwd]===n){const p=Be(a,o.workspaceCwd)[0];p?d[o.workspaceCwd]=p.id:delete d[o.workspaceCwd]}return{tabs:a,activeTabId:l,lastActiveTabByWorkspace:d}})},activate(n){t(s=>{const o=s.tabs.find(r=>r.id===n);return o?{activeTabId:n,activeWorkspaceCwd:o.workspaceCwd,lastActiveTabByWorkspace:{...s.lastActiveTabByWorkspace,[o.workspaceCwd]:n}}:s})},switchWorkspace(n){t(s=>{var d;const o=Be(s.tabs,n),r=s.lastActiveTabByWorkspace[n],l=r&&o.some(p=>p.id===r)?r:((d=o[0])==null?void 0:d.id)??null;return{activeWorkspaceCwd:n,activeTabId:l,lastActiveTabByWorkspace:l?{...s.lastActiveTabByWorkspace,[n]:l}:s.lastActiveTabByWorkspace}})},reorder(n,s){t(o=>{const r=o.tabs.findIndex(p=>p.id===n),a=o.tabs.findIndex(p=>p.id===s);if(r===-1||a===-1||r===a)return o;const l=o.tabs.slice(),[d]=l.splice(r,1);return d?(l.splice(a,0,d),{tabs:l}):o})},updateLabel(n,s){t(o=>({tabs:o.tabs.map(r=>r.id===n?{...r,label:s}:r)}))},updateData(n,s){t(o=>({tabs:o.tabs.map(r=>r.id===n?{...r,data:{...r.data,...s}}:r)}))}})),L={chat:t=>`chat-${t}`,file:t=>`file-${t}`,diff:(t,e)=>`diff-${t}${e?"-staged":""}`,terminal:t=>`term-${t}`};let Ae=0;function Ut(t){Ae+=1,T.getState().open({id:L.terminal(`new-${Ae}`),kind:"terminal",label:`Terminal ${Ae}`,closable:!0,data:{slot:null,cwd:t},workspaceCwd:t})}function je(t){const e=$.getState().createSession(t);T.getState().open({id:L.chat(e),kind:"chat",label:"New chat",closable:!0,data:{sessionId:e},workspaceCwd:t})}const ke=ce()(t=>({rootPath:"",expanded:new Set,expandedByRoot:new Map,setRoot:e=>t(n=>{const s=new Map(n.expandedByRoot);n.rootPath&&s.set(n.rootPath,n.expanded);const o=s.get(e),r=new Set(o);return r.add(e),{rootPath:e,expanded:r,expandedByRoot:s}}),toggle:e=>t(n=>{if(e===n.rootPath)return n;const s=new Set(n.expanded);s.has(e)?s.delete(e):s.add(e);const o=new Map(n.expandedByRoot);return o.set(n.rootPath,s),{expanded:s,expandedByRoot:o}})}));let re=null;const ze=new Set;function da(t){return ze.add(t),()=>ze.delete(t)}async function Ee(t){var e;if(re)return re;try{const n=await t.connection.request("file_explorer_request",{path:"/home"}),o=(((e=n.result)==null?void 0:e.entries)??n.entries??[]).find(r=>r.kind==="directory"||r.type==="directory");re="/home/"+((o==null?void 0:o.name)||"user")}catch{return"/tmp"}for(const n of ze)n(re);return re}function ua(){return re}async function pa(t,e){return e==="~"||e.startsWith("~/")?await Ee(t)+e.slice(1):e}function Kt(){const t=j(o=>o.client),e=j(o=>o.status),[n,s]=w.useState(ua());return w.useEffect(()=>da(s),[]),w.useEffect(()=>{!t||e!=="open"||n||Ee(t)},[t,e,n]),n}const fa="_dot_202py_3",ha={dot:fa};function ga(t){const{status:e,requiresAttention:n,attentionReason:s,showInactive:o}=t;if(!e)return null;if(n)switch(s){case"permission":return"statusWarning";case"error":return"statusDanger";case"finished":default:return"statusSuccess"}switch(e){case"running":case"queued":return"accent";case"waiting":return"statusWarning";case"finished":return"statusSuccess";case"error":return"statusDanger";case"idle":case"archived":return o?"foregroundMuted":null}}const ut=8,ma={accent:"var(--pi-color-accent)",statusSuccess:"var(--pi-color-statusSuccess)",statusDanger:"var(--pi-color-statusDanger)",statusWarning:"var(--pi-color-statusWarning)",foregroundMuted:"var(--pi-color-foregroundMuted)"};function _a({className:t,...e}){const n=ga(e);return n?i.jsx("span",{className:`${ha.dot}${t?` ${t}`:""}`,style:{width:ut,height:ut,backgroundColor:ma[n]??"currentColor"},role:"presentation"}):null}const ya={initializing:"queued",idle:"idle",running:"running",error:"error",closed:"finished"};function ba(t){return ya[t]??"idle"}const wa="_wrap_sqws5_1",Sa="_header_sqws5_7",xa="_list_sqws5_23",va="_item_sqws5_28",ka="_active_sqws5_37",Ia="_title_sqws5_40",Ca="_meta_sqws5_49",Ta="_menuBtn_sqws5_57",ja="_workspaceGroup_sqws5_75",Ea="_workspaceHeader_sqws5_78",Na="_workspaceChevron_sqws5_91",Ra="_workspaceIcon_sqws5_102",qa="_workspaceLabel_sqws5_106",Ba="_workspaceCount_sqws5_112",Aa="_newSessionBtn_sqws5_117",Ma="_workspaceSessions_sqws5_129",A={wrap:wa,header:Sa,list:xa,item:va,active:ka,title:Ia,meta:Ca,menuBtn:Ta,workspaceGroup:ja,workspaceHeader:Ea,workspaceChevron:Na,workspaceIcon:Ra,workspaceLabel:qa,workspaceCount:Ba,newSessionBtn:Aa,workspaceSessions:Ma};function $a({session:t,active:e,onSelect:n,onOpenMenu:s}){return i.jsxs("div",{className:B(A.item,e&&A.active),onClick:n,onContextMenu:o=>{o.preventDefault(),s(o.clientX,o.clientY)},children:[i.jsxs("div",{className:A.title,children:[i.jsx(_a,{status:ba(t.status),showInactive:!0}),i.jsx("span",{children:t.title})]}),i.jsxs("div",{className:A.meta,children:[t.cwd||"~"," · ",t.agentId?t.agentId.slice(0,8):"new"," ·"," ",t.userMessageCount," msgs"]}),i.jsx("button",{type:"button",className:A.menuBtn,title:"Actions",onClick:o=>{o.stopPropagation();const r=o.currentTarget.getBoundingClientRect();s(r.left,r.bottom)},children:i.jsx(_t,{size:14})})]})}const Da="_trigger_16o4s_1",Oa="_content_16o4s_7",Fa="_item_16o4s_16",Pa="_danger_16o4s_33",Ha="_sep_16o4s_36",U={trigger:Da,content:Oa,item:Fa,danger:Pa,sep:Ha};function za(){const t=v(S=>S.sessionMenu),e=v(S=>S.closeSessionMenu),n=j(S=>S.client),s=w.useRef(null),[o,r]=w.useState(!1);w.useEffect(()=>{r(t!==null)},[t]);const a=$(S=>t?S.sessions[t.sessionId]:void 0);if(!t)return null;const l=!!(a!=null&&a.agentId)&&(a==null?void 0:a.status)==="running";function d(S){r(S),S||e()}function p(){if(!a)return;const S=window.prompt("Rename:",a.title);if(S!=null&&S.trim()){const y=S.trim();$.getState().setTitle(a.id,y),T.getState().updateLabel(L.chat(a.id),y),a.agentId&&(n==null||n.agent(a.agentId).update({title:y}).catch(()=>{}))}e()}function h(){a!=null&&a.agentId&&(n==null||n.agent(a.agentId).interrupt().catch(()=>{})),e()}function _(S){$.getState().remove(S),T.getState().close(L.chat(S))}async function f(){if(a){if(!window.confirm("Archive this agent? It can be resumed later."))return e();if(e(),!a.agentId){_(a.id);return}if(!n){window.alert("Not connected — cannot archive remotely.");return}try{await n.agent(a.agentId).archive(),_(a.id)}catch(S){window.alert(`Failed to archive: ${S instanceof Error?S.message:String(S)}`)}}}async function x(){if(a){if(!window.confirm("Permanently delete this agent? This cannot be undone."))return e();if(e(),!a.agentId){_(a.id);return}if(!n){window.alert("Not connected — cannot delete remotely.");return}try{await n.agent(a.agentId).delete(),_(a.id)}catch(S){window.alert(`Failed to delete: ${S instanceof Error?S.message:String(S)}`)}}}return i.jsxs(Ue,{open:o,onOpenChange:d,modal:!1,children:[i.jsx(Ke,{asChild:!0,children:i.jsx("button",{ref:s,type:"button",className:U.trigger,style:{left:t.x,top:t.y},"aria-hidden":!0,tabIndex:-1})}),i.jsx(Ve,{children:i.jsxs(Ge,{className:U.content,align:"start",sideOffset:2,children:[i.jsx(J,{className:U.item,onSelect:p,children:"Rename"}),i.jsx(J,{className:U.item,disabled:!l,onSelect:h,children:"Stop agent"}),i.jsx(vt,{className:U.sep}),i.jsx(J,{className:`${U.item} ${U.danger}`,onSelect:f,children:"Archive"}),i.jsx(J,{className:`${U.item} ${U.danger}`,onSelect:x,children:"Delete permanently"})]})})]})}function Wa({label:t,cwd:e,sessionCount:n,collapsed:s,onToggleCollapsed:o,onNewSession:r}){return i.jsxs("div",{className:A.workspaceHeader,onClick:o,title:e,children:[i.jsx("button",{type:"button",className:A.workspaceChevron,"aria-label":s?"Expand workspace":"Collapse workspace",onClick:a=>{a.stopPropagation(),o()},children:s?i.jsx(yt,{size:13}):i.jsx(_n,{size:13})}),i.jsx(yn,{size:13,className:B(A.workspaceIcon)}),i.jsx("span",{className:A.workspaceLabel,children:t}),i.jsx("span",{className:A.workspaceCount,children:n}),i.jsx(H,{size:"xs",variant:"ghost",iconOnly:!0,title:"New conversation",className:A.newSessionBtn,onClick:a=>{a.stopPropagation(),r()},children:i.jsx(bt,{size:13})})]})}function te(t,e){return e&&(t==="~"||t.startsWith("~/"))?e+t.slice(1):t}function Vt(t,e,n){const s=new Map;for(const o of t){const r=e[o];if(!r)continue;const a=te(r.cwd||"~",n),l=s.get(a);l?l.push(r):s.set(a,[r])}return Array.from(s,([o,r])=>({cwd:o,sessions:r}))}function La(t){return!t||t==="~"?"~":t.split("/").filter(Boolean).pop()||t}function Ua(){const t=$(y=>y.order),e=$(y=>y.sessions),n=$(y=>y.activeSessionId),s=$(y=>y.activate),o=T(y=>y.open),r=j(y=>y.status),a=v(y=>y.openSessionMenu),l=v(y=>y.setCwd),d=v(y=>y.openCwdPicker),p=v(y=>y.collapsedWorkspaces),h=v(y=>y.toggleWorkspaceCollapsed),_=Kt();function f(y){const E=te(y||"~",_);je(E)}function x(y){s(y);const E=e[y],D=te((E==null?void 0:E.cwd)||"~",_);E!=null&&E.cwd&&l(E.cwd),o({id:L.chat(y),kind:"chat",label:(E==null?void 0:E.title)??"Chat",closable:!0,data:{sessionId:y},workspaceCwd:D})}const S=Vt(t,e,_);return i.jsxs("div",{className:A.wrap,children:[i.jsxs("div",{className:A.header,children:[i.jsx("h3",{children:"Workspaces"}),i.jsx(H,{size:"xs",variant:"ghost",iconOnly:!0,title:r!=="open"?"Connect to open a workspace":"Open a workspace folder",disabled:r!=="open",onClick:()=>d(),children:i.jsx(bn,{size:14})})]}),i.jsx("div",{className:A.list,children:S.map(y=>{const E=p.has(y.cwd);return i.jsxs("div",{className:A.workspaceGroup,children:[i.jsx(Wa,{label:La(y.cwd),cwd:y.cwd,sessionCount:y.sessions.length,collapsed:E,onToggleCollapsed:()=>h(y.cwd),onNewSession:()=>f(y.cwd)}),!E&&i.jsx("div",{className:A.workspaceSessions,children:y.sessions.map(D=>i.jsx($a,{session:D,active:D.id===n,onSelect:()=>x(D.id),onOpenMenu:(k,ne)=>a(D.id,k,ne)},D.id))})]},y.cwd)})}),i.jsx(za,{})]})}const Ka="_strip_8jveh_1",Va="_tab_8jveh_10",Ga="_active_8jveh_26",Ja="_icon_8jveh_30",Xa="_label_8jveh_35",Ya="_close_8jveh_40",Qa="_newTab_8jveh_50",Za="_content_8jveh_73",ei="_item_8jveh_82",ti="_itemIcon_8jveh_96",F={strip:Ka,tab:Va,active:Ga,icon:Ja,label:Xa,close:Ya,newTab:Qa,content:Za,item:ei,itemIcon:ti},ni={chat:St,file:Sn,diff:wn,terminal:wt};function si({tab:t}){const e=T(_=>_.activeTabId),n=T(_=>_.activate),s=T(_=>_.close),o=ni[t.kind],{attributes:r,listeners:a,setNodeRef:l,transform:d,transition:p,isDragging:h}=On({id:t.id});return i.jsxs("div",{ref:l,className:B(F.tab,t.id===e&&F.active),style:{transform:Fn.Transform.toString(d),transition:p,opacity:h?.5:1},onClick:()=>n(t.id),onAuxClick:_=>{_.button===1&&t.closable&&s(t.id)},title:t.label,...r,...a,children:[i.jsx("span",{className:F.icon,children:i.jsx(o,{size:13})}),i.jsx("span",{className:F.label,children:t.label}),t.closable&&i.jsx("span",{className:F.close,onClick:_=>{_.stopPropagation(),s(t.id)},children:i.jsx(Me,{size:12})})]})}function oi({workspaceCwd:t}){const e=t??"~";return i.jsxs(Ue,{children:[i.jsx(Ke,{asChild:!0,children:i.jsx("button",{type:"button",className:F.newTab,title:"New tab",disabled:!t,children:i.jsx(bt,{size:14})})}),i.jsx(Ve,{children:i.jsxs(Ge,{className:F.content,align:"start",sideOffset:4,children:[i.jsxs(J,{className:F.item,onSelect:()=>je(e),children:[i.jsx(St,{size:13,className:F.itemIcon}),"New chat"]}),i.jsxs(J,{className:F.item,onSelect:()=>Ut(e),children:[i.jsx(wt,{size:13,className:F.itemIcon}),"New terminal"]})]})})]})}function ri(){const t=T(a=>a.tabs),e=T(a=>a.activeWorkspaceCwd),n=T(a=>a.reorder),s=t.filter(a=>a.workspaceCwd===e),o=Rn(qn(Dn,{activationConstraint:{distance:4}}));function r(a){const{active:l,over:d}=a;!d||l.id===d.id||n(String(l.id),String(d.id))}return i.jsxs("div",{className:F.strip,children:[i.jsx(Bn,{sensors:o,collisionDetection:An,onDragEnd:r,children:i.jsx(Mn,{items:s.map(a=>a.id),strategy:$n,children:s.map(a=>i.jsx(si,{tab:a},a.id))})}),i.jsx(oi,{workspaceCwd:e})]})}const ai="_spinner_1tgzp_3",ii={spinner:ai},ci={xs:12,sm:16,md:20,lg:24},li={xs:1,sm:2,md:2,lg:3};function di({size:t="md",color:e="currentColor",className:n,"aria-label":s="Loading"}){const o=typeof t=="number"?t:ci[t],r=typeof t=="number"?2:li[t];return i.jsx("span",{className:`${ii.spinner}${n?` ${n}`:""}`,role:"status","aria-label":s,style:{width:o,height:o,borderWidth:r,color:e}})}const ui=w.lazy(()=>Je(()=>import("./ChatPanel-CG_Yz_QI.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(t=>({default:t.ChatPanel}))),pt=w.lazy(()=>Je(()=>import("./FilePanel-CGmR13VT.js").then(t=>t.F),__vite__mapDeps([14,1,7,6,5,2,9,10,15])).then(t=>({default:t.FilePanel}))),pi=w.lazy(()=>Je(()=>import("./TerminalPanel-D21QoVnF.js"),__vite__mapDeps([16,1,17,18,7,6,5,2,3,11,12,19])).then(t=>({default:t.TerminalPanel}))),fi={chat:ui,file:pt,diff:pt,terminal:pi},hi="_area_1vzxd_1",gi="_panel_1vzxd_7",mi="_active_1vzxd_14",_i="_empty_1vzxd_17",fe={area:hi,panel:gi,active:mi,empty:_i};function yi(){const t=T(o=>o.tabs),e=T(o=>o.activeTabId),n=T(o=>o.activeWorkspaceCwd);return t.some(o=>o.workspaceCwd===n)?i.jsx("div",{className:fe.area,children:t.map(o=>{const r=fi[o.kind];return i.jsx("div",{className:B(fe.panel,o.id===e&&fe.active),children:i.jsx(w.Suspense,{fallback:i.jsx(di,{size:"md"}),children:i.jsx(r,{tab:o})})},o.id)})}):i.jsx("div",{className:fe.area,children:i.jsx("div",{className:fe.empty,children:"No open tabs in this workspace"})})}const Gt={fileRead:t=>["file","read",t],fileDownload:t=>["file","download",t],fileDiff:(t,e,n)=>["file","diff",t,e,n],explorer:t=>["explorer",t],agentList:()=>["agents","list"],agentTimeline:t=>["agents","timeline",t]};function bi(t){const e=t.kind==="directory"||t.type==="directory"?"directory":"file";return{name:t.name??"",kind:e,size:t.size,mtimeMs:t.mtimeMs}}function wi(t){return t.slice().sort((e,n)=>e.kind!==n.kind?e.kind==="directory"?-1:1:e.name.localeCompare(n.name))}async function Jt(t,e){const s=(await t.connection.request("file_explorer_request",{path:e})).result;if(!s||s.ok===!1)throw new Error(s&&"error"in s?s.error:"explorer request failed");const o="entries"in s?s.entries??[]:[];return{path:s.resolvedPath??e,entries:wi(o.map(bi))}}function Si(t,e=!0){const n=j(s=>s.client);return ln({queryKey:Gt.explorer(t),queryFn:()=>{if(!n)throw new Error("not connected");return Jt(n,t)},enabled:!!n&&!!t&&e})}function xi(t){const e=j(o=>o.client),n=w.useMemo(()=>Array.from(t),[t]),s=dn({queries:n.map(o=>({queryKey:Gt.explorer(o),queryFn:()=>{if(!e)throw new Error("not connected");return Jt(e,o)},enabled:!!e&&!!o}))});return w.useMemo(()=>{const o=new Map;return n.forEach((r,a)=>{const l=s[a];o.set(r,{listing:l==null?void 0:l.data,isLoading:!!(l!=null&&l.isLoading),isError:!!(l!=null&&l.isError),error:l==null?void 0:l.error})}),o},[n,s])}const ft=new WeakMap;function ht(t){let e=ft.get(t);return e||(e=new Ir(t),e.start(),ft.set(t,e)),e}function vi(t,e,n){const s=new Blob([Uint8Array.from(t)],{type:n||"application/octet-stream"}),o=URL.createObjectURL(s),r=document.createElement("a");r.href=o,r.download=e,r.rel="noopener",document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(o),0)}function Xt(){const t=j(o=>o.daemon),e=Le(),n=w.useCallback(async(o,r)=>{if(!t)throw new Error("not connected");const a=o?`${o}/${r.name}`:r.name,l=new Uint8Array(await r.arrayBuffer());await ht(t).upload(a,l),await e.invalidateQueries({queryKey:["explorer"]})},[t,e]),s=w.useCallback(async o=>{if(!t)throw new Error("not connected");const r=await ht(t).download(o);vi(r.bytes,r.fileName||o.split("/").pop()||"download",r.mimeType)},[t]);return{upload:n,saveToDisk:s}}function ki(t,e){return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}function Yt(t,e,n,s,o){var a;const r=o.get(e);if(!r||r.isLoading){t.push({kind:"loading",path:e,depth:n});return}if(r.isError){const l=r.error instanceof Error?r.error.message:"failed to load";t.push({kind:"error",path:e,depth:n,message:l});return}for(const l of((a=r.listing)==null?void 0:a.entries)??[])Ii(t,e,l,n,s,o)}function Ii(t,e,n,s,o,r){const a=ki(e,n.name);if(n.kind!=="directory"){t.push({kind:"file",path:a,name:n.name,depth:s});return}const l=o.has(a);t.push({kind:"directory",path:a,name:n.name,depth:s,expanded:l}),l&&Yt(t,a,s+1,o,r)}function Ci(t,e,n){if(!t)return[];const s=[];return Yt(s,t,0,e,n),s}const Ti="_container_yg965_1",ji="_header_yg965_7",Ei="_uploadButton_yg965_13",Ni="_hiddenInput_yg965_32",Ri="_status_yg965_35",qi="_statusError_yg965_36",Bi="_rowAction_yg965_49",Ai="_item_yg965_64",Mi="_dropOverlay_yg965_67",$i="_list_yg965_82",Di="_chevronSlot_yg965_101",Oi="_chevron_yg965_101",Fi="_chevronOpen_yg965_112",Pi="_icon_yg965_115",Hi="_name_yg965_122",zi="_dirName_yg965_127",Wi="_statusRow_yg965_133",Li="_statusRowError_yg965_144",Ui="_emptyState_yg965_147",N={container:Ti,header:ji,uploadButton:Ei,hiddenInput:Ni,status:Ri,statusError:qi,rowAction:Bi,item:Ai,dropOverlay:Mi,list:$i,chevronSlot:Di,chevron:Oi,chevronOpen:Fi,icon:Pi,name:Hi,dirName:zi,statusRow:Wi,statusRowError:Li,emptyState:Ui},Ki=14;function Vi({row:t,onToggle:e,onOpenFile:n,onContextMenu:s}){const o={paddingLeft:8+t.depth*Ki};if(t.kind==="loading")return i.jsx("div",{className:N.statusRow,style:o,children:"Loading…"});if(t.kind==="error")return i.jsx("div",{className:B(N.statusRow,N.statusRowError),style:o,children:t.message??"failed to load"});const r=t.kind==="directory";return i.jsxs("div",{className:N.item,style:o,onClick:()=>r?e(t.path):n(t.path),onContextMenu:a=>{a.preventDefault(),s(t.path,r,a.clientX,a.clientY)},children:[i.jsx("span",{className:N.chevronSlot,children:r&&i.jsx(yt,{size:12,className:B(N.chevron,t.expanded&&N.chevronOpen)})}),i.jsx("span",{className:N.icon,children:r?i.jsx(xt,{size:14}):i.jsx(xn,{size:14})}),i.jsx("span",{className:r?N.dirName:N.name,children:t.name}),i.jsx("button",{type:"button",className:N.rowAction,title:"Actions",onClick:a=>{a.stopPropagation();const l=a.currentTarget.getBoundingClientRect();s(t.path,r,l.left,l.bottom)},children:i.jsx(_t,{size:12})})]})}const Gi="_trigger_g81d7_1",Ji="_content_g81d7_7",Xi="_item_g81d7_16",Yi="_danger_g81d7_29",Qi="_sep_g81d7_32",se={trigger:Gi,content:Ji,item:Xi,danger:Yi,sep:Qi};function Zi(){const t=v(f=>f.fileMenu),e=v(f=>f.closeFileMenu),n=j(f=>f.client),{saveToDisk:s}=Xt(),o=Le(),r=w.useRef(null),[a,l]=w.useState(!1);if(w.useEffect(()=>{l(t!==null)},[t]),!t)return null;const d=t.path.split("/").pop()||t.path;function p(f){l(f),f||e()}async function h(){if(t){e();try{await s(t.path)}catch(f){window.alert(`Failed to download: ${f instanceof Error?f.message:String(f)}`)}}}async function _(){if(!t)return;const f=t.isDirectory?"folder (and everything inside it)":"file";if(!window.confirm(`Permanently delete this ${f}? "${d}" — this cannot be undone.`))return e();if(e(),!n){window.alert("Not connected — cannot delete remotely.");return}try{const x=await n.connection.request("file_delete_request",{path:t.path});if(!x.ok)throw new Error(x.error??"delete failed");await o.invalidateQueries({queryKey:["explorer"]})}catch(x){window.alert(`Failed to delete: ${x instanceof Error?x.message:String(x)}`)}}return i.jsxs(Ue,{open:a,onOpenChange:p,modal:!1,children:[i.jsx(Ke,{asChild:!0,children:i.jsx("button",{ref:r,type:"button",className:se.trigger,style:{left:t.x,top:t.y},"aria-hidden":!0,tabIndex:-1})}),i.jsx(Ve,{children:i.jsxs(Ge,{className:se.content,align:"start",sideOffset:2,children:[!t.isDirectory&&i.jsx(J,{className:se.item,onSelect:h,children:"Download"}),i.jsx(vt,{className:se.sep}),i.jsx(J,{className:`${se.item} ${se.danger}`,onSelect:_,children:"Delete"})]})})]})}const ec=24;function tc(){const t=j(b=>b.client),e=ke(b=>b.rootPath),n=ke(b=>b.expanded),s=ke(b=>b.setRoot),o=ke(b=>b.toggle),r=T(b=>b.activeWorkspaceCwd),a=T(b=>b.open),{upload:l}=Xt(),d=v(b=>b.openFileMenu),[p,h]=w.useState(null),[_,f]=w.useState(!1),[x,S]=w.useState(null),y=w.useRef(null),E=w.useRef(null),D=w.useRef(null);w.useEffect(()=>{if(!t)return;const b=r||"~";D.current!==b&&(D.current=b,pa(t,b).then(q=>s(q)))},[t,r,s]);const k=xi(n),ne=w.useMemo(()=>Ci(e,n,k),[e,n,k]),Qe=un({count:ne.length,getScrollElement:()=>E.current,estimateSize:()=>ec,overscan:12,getItemKey:b=>{var q;return((q=ne[b])==null?void 0:q.path)??b}});function Zt(b){a({id:L.file(b),kind:"file",label:b.split("/").pop()||b,closable:!0,data:{path:b},workspaceCwd:r||"~"})}async function Ze(b,q){var be;if(!q.length||!b)return;const Y=(be=k.get(b))==null?void 0:be.listing,Ne=new Set((Y==null?void 0:Y.entries.map(z=>z.name))??[]),le=q.filter(z=>Ne.has(z.name));if(le.length>0){const z=le.map(nn=>nn.name).join(", ");if(!window.confirm(`Overwrite ${le.length>1?"these files":"this file"}? ${z}`))return}h({text:`Uploading ${q.length} file${q.length>1?"s":""}…`,error:!1});try{for(const z of q)await l(b,z);h({text:`Uploaded ${q.length} file${q.length>1?"s":""}`,error:!1})}catch(z){h({text:`Upload failed: ${z instanceof Error?z.message:"unknown"}`,error:!0})}}function en(b){b.preventDefault(),f(!1);const q=x??e;S(null);const Y=Array.from(b.dataTransfer.files);Ze(q,Y)}function tn(b){b.dataTransfer.types.includes("Files")&&(b.preventDefault(),f(!0))}return t?i.jsxs("div",{className:N.container,onDragOver:tn,onDragLeave:()=>f(!1),onDrop:en,children:[i.jsxs("div",{className:N.header,children:[i.jsxs("button",{type:"button",className:N.uploadButton,onClick:()=>{var b;return(b=y.current)==null?void 0:b.click()},disabled:!e,title:"Upload files to the workspace root",children:[i.jsx(vn,{size:12}),i.jsx("span",{children:"Upload"})]}),i.jsx("input",{ref:y,type:"file",multiple:!0,className:N.hiddenInput,onChange:b=>{Ze(e,Array.from(b.target.files??[])),b.target.value=""}})]}),p&&i.jsx("div",{className:p.error?N.statusError:N.status,children:p.text}),i.jsxs("div",{className:N.list,ref:E,children:[ne.length===0&&i.jsx("div",{className:N.emptyState,children:"No files loaded"}),i.jsx("div",{style:{position:"relative",height:Qe.getTotalSize()},children:Qe.getVirtualItems().map(b=>{const q=ne[b.index];return q?i.jsx("div",{"data-index":b.index,style:{position:"absolute",top:0,left:0,width:"100%",height:b.size,transform:`translateY(${b.start}px)`},onDragEnter:()=>{q.kind==="directory"&&S(q.path)},children:i.jsx(Vi,{row:q,onToggle:o,onOpenFile:Zt,onContextMenu:(Y,Ne,le,be)=>d(Y,Ne,le,be)})},b.key):null})})]}),_&&i.jsx("div",{className:N.dropOverlay,children:"Drop to upload"}),i.jsx(Zi,{})]}):i.jsx("div",{className:N.emptyState,children:"Connect to browse files"})}const We=ce()(t=>({subscribedCwd:null,changes:[],setSubscribedCwd:e=>t({subscribedCwd:e}),applyProjection:e=>{if(!e||!e.available){t({changes:[]});return}const n=[];for(const s of e.staged)n.push({path:s.path,status:s.indexStatus==="A"?"added":s.indexStatus==="D"?"deleted":"modified",staged:!0});for(const s of e.unstaged)n.push({path:s.path,status:s.worktreeStatus==="D"?"deleted":"modified",staged:!1});for(const s of e.untracked)n.push({path:s,status:"added",staged:!1});t({changes:n})}}));function nc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="checkout_status_update"&&"cwd"in t&&typeof t.cwd=="string"&&"projection"in t&&typeof t.projection=="object"&&t.projection!==null}function sc(t){const e=j(r=>r.client),n=We(r=>r.applyProjection),s=We(r=>r.setSubscribedCwd),o=w.useRef(e);return o.current=e,w.useEffect(()=>{if(!e||!t)return;let r=!1;e.connection.request("checkout_status_subscribe",{cwd:t}).catch(()=>{}),s(t);const a=e.connection.onSessionMessage(l=>{if(r)return;const d=l;nc(d)&&d.cwd===t&&n(d.projection)});return e.connection.request("checkout_refresh_request",{cwd:t}).catch(()=>{}),()=>{r=!0,a(),e.connection.request("checkout_status_unsubscribe",{cwd:t}).catch(()=>{}),s(null)}},[e,t,n,s]),{refresh(){const r=o.current;!r||!t||r.connection.request("checkout_refresh_request",{cwd:t}).catch(()=>{})}}}const oc="_list_1pgby_1",rc="_summary_1pgby_4",ac="_item_1pgby_11",ic="_badge_1pgby_23",cc="_added_1pgby_30",lc="_modified_1pgby_34",dc="_deleted_1pgby_38",uc="_name_1pgby_42",pc="_emptyState_1pgby_47",Z={list:oc,summary:rc,item:ac,badge:ic,added:cc,modified:lc,deleted:dc,name:uc,emptyState:pc},fc={added:"A",modified:"M",deleted:"D"};function hc(){const e=T(r=>r.activeWorkspaceCwd)||"~";sc(e);const n=We(r=>r.changes),s=T(r=>r.open);function o(r,a){s({id:L.diff(r,a),kind:"diff",label:r.split("/").pop()||r,closable:!0,data:{path:r,staged:a},workspaceCwd:e})}return n.length===0?i.jsx("div",{className:Z.emptyState,children:"No changes detected"}):i.jsxs("div",{className:Z.list,children:[i.jsxs("div",{className:Z.summary,children:[n.length," changed file",n.length===1?"":"s"]}),n.map((r,a)=>i.jsxs("div",{className:Z.item,onClick:()=>o(r.path,r.staged),children:[i.jsx("span",{className:B(Z.badge,Z[r.status]),children:fc[r.status]}),i.jsx("span",{className:Z.name,children:r.path})]},`${r.path}-${r.staged}-${a}`))]})}const gc="_wrap_r37ok_1",mc="_tabBar_r37ok_7",_c="_tabBtn_r37ok_13",yc="_active_r37ok_26",bc="_refreshBtn_r37ok_30",wc="_content_r37ok_34",V={wrap:gc,tabBar:mc,tabBtn:_c,active:yc,refreshBtn:bc,content:wc};function Sc(){const t=v(l=>l.rightSidebarTab),e=v(l=>l.setRightSidebarTab),s=T(l=>l.activeWorkspaceCwd)||"~",o=j(l=>l.client),r=Le();function a(){r.invalidateQueries({queryKey:["explorer"]}),o&&s&&o.connection.request("checkout_refresh_request",{cwd:s}).catch(()=>{})}return i.jsxs("div",{className:V.wrap,children:[i.jsxs("div",{className:V.tabBar,children:[i.jsx("button",{type:"button",className:B(V.tabBtn,t==="files"&&V.active),onClick:()=>e("files"),children:"Files"}),i.jsx("button",{type:"button",className:B(V.tabBtn,t==="changes"&&V.active),onClick:()=>e("changes"),children:"Changes"}),i.jsx(H,{size:"xs",variant:"ghost",iconOnly:!0,title:"Refresh",className:V.refreshBtn,onClick:a,children:i.jsx(kn,{size:13})})]}),i.jsx("div",{className:V.content,children:t==="files"?i.jsx(tc,{}):i.jsx(hc,{})})]})}const xc="_wrapper_131x2_3",vc="_box_131x2_18",kc="_checkmark_131x2_36",Ic="_nativeInput_131x2_41",Ie={wrapper:xc,box:vc,checkmark:kc,nativeInput:Ic};w.forwardRef(function({label:e,checked:n=!1,disabled:s,className:o,onChange:r,...a},l){return i.jsxs("label",{className:Ie.wrapper,"data-disabled":s||void 0,children:[i.jsx("input",{ref:l,type:"checkbox",className:Ie.nativeInput,checked:n,disabled:s,onChange:r,...a}),i.jsx("span",{className:Ie.box,"data-checked":n,"aria-hidden":!0,children:n&&i.jsx(In,{size:12,className:Ie.checkmark})}),e&&i.jsx("span",{children:e})]})});const Cc="_select_vj45v_3",Tc={select:Cc};w.forwardRef(function({options:e,placeholder:n,className:s,...o},r){return i.jsxs("select",{ref:r,className:B(Tc.select,s),...o,children:[n&&i.jsx("option",{value:"",disabled:!0,children:n}),e.map(a=>i.jsx("option",{value:a.value,children:a.label},a.value))]})});const jc="_overlay_1yaef_1",Ec="_contentWrapper_1yaef_7",Nc="_dialog_1yaef_16",Rc="_header_1yaef_28",qc="_title_1yaef_36",Bc="_closeBtn_1yaef_43",Ac="_body_1yaef_57",Mc="_footer_1yaef_63",$c="_bare_1yaef_72",Dc="_bareBody_1yaef_78",Oc="_bareCloseBtn_1yaef_82",Fc="_visuallyHidden_1yaef_101",O={overlay:jc,contentWrapper:Ec,dialog:Nc,header:Rc,title:qc,closeBtn:Bc,body:Ac,footer:Mc,bare:$c,bareBody:Dc,bareCloseBtn:Oc,visuallyHidden:Fc},Pc=$e;function Hc({open:t,onOpenChange:e,title:n,children:s,footer:o,width:r,className:a,bare:l=!1}){return i.jsx(Tn,{open:t,onOpenChange:e,children:i.jsxs(jn,{children:[i.jsx(En,{className:O.overlay}),i.jsx("div",{className:O.contentWrapper,children:i.jsxs(Nn,{className:B(O.dialog,l&&O.bare,a),style:r!==void 0?{width:r}:void 0,children:[l?i.jsx(et,{className:O.visuallyHidden,children:n}):i.jsxs("div",{className:O.header,children:[i.jsx(et,{className:O.title,children:n}),i.jsx($e,{asChild:!0,children:i.jsx("button",{type:"button",className:O.closeBtn,"aria-label":"Close",children:i.jsx(Me,{size:16})})})]}),i.jsx("div",{className:B(O.body,l&&O.bareBody),children:s}),l&&i.jsx($e,{asChild:!0,children:i.jsx("button",{type:"button",className:O.bareCloseBtn,"aria-label":"Close",children:i.jsx(Me,{size:16})})}),o&&i.jsx("div",{className:O.footer,children:o})]})})]})})}const zc="_handle_1ocv1_1",Wc={handle:zc};function gt({side:t,onResize:e,className:n}){const s=w.useRef(0),o=w.useCallback(l=>{const d=l.clientX-s.current;s.current=l.clientX,e(t==="left"?d:-d)},[e,t]),r=w.useCallback(l=>{var d,p;window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",r),document.body.style.cursor="",document.body.style.userSelect="",(p=(d=l.target)==null?void 0:d.releasePointerCapture)==null||p.call(d,l.pointerId)},[o]);function a(l){l.preventDefault(),s.current=l.clientX,document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("pointermove",o),window.addEventListener("pointerup",r)}return i.jsx("div",{className:B(Wc.handle,n),onPointerDown:a,role:"separator","aria-orientation":"vertical"})}function Lc(t,e){const{order:n,sessions:s}=$.getState(),r=Vt(n,s,e).find(a=>a.cwd===t);if(r!=null&&r.sessions[0]){const a=r.sessions[0].id;$.getState().activate(a);const l=$.getState().sessions[a];T.getState().open({id:L.chat(a),kind:"chat",label:(l==null?void 0:l.title)??"New chat",closable:!0,data:{sessionId:a},workspaceCwd:t})}else je(t);v.getState().setCwd(t)}const Uc="_pathRow_9xphl_1",Kc="_pathInput_9xphl_9",Vc="_list_9xphl_13",Gc="_item_9xphl_20",Jc="_name_9xphl_32",Xc="_emptyState_9xphl_37",G={pathRow:Uc,pathInput:Kc,list:Vc,item:Gc,name:Jc,emptyState:Xc};function Yc(){const t=v(k=>k.cwdPickerOpen),e=v(k=>k.closeCwdPicker),n=T(k=>k.activeWorkspaceCwd),s=j(k=>k.client),o=Kt(),[r,a]=w.useState("/"),[l,d]=w.useState("/");w.useEffect(()=>{if(!t)return;const k=te(n||"~",o);a(k),d(k)},[t,s,n]);const{data:p,isLoading:h,isError:_,error:f}=Si(r,t&&!!s),x=((p==null?void 0:p.entries)??[]).filter(k=>k.kind==="directory");function S(k){a(k),d(k)}function y(){S(r.split("/").slice(0,-1).join("/")||"/")}function E(){S(l.trim())}function D(){Lc(r,o),e()}return i.jsxs(Hc,{open:t,onOpenChange:k=>!k&&e(),title:"Open Workspace",footer:i.jsxs(i.Fragment,{children:[i.jsx(Pc,{asChild:!0,children:i.jsx(H,{size:"sm",variant:"secondary",children:"Cancel"})}),i.jsx(H,{size:"sm",onClick:D,children:"Open this folder"})]}),children:[i.jsxs("div",{className:G.pathRow,children:[i.jsx(H,{size:"xs",variant:"ghost",iconOnly:!0,title:"Up",onClick:y,children:i.jsx(Cn,{size:13})}),i.jsx(Oe,{className:G.pathInput,value:l,onChange:k=>d(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),E())}}),i.jsx(H,{size:"xs",onClick:E,children:"Go"})]}),i.jsx("div",{className:G.list,children:h?i.jsx("div",{className:G.emptyState,children:"Loading..."}):_?i.jsxs("div",{className:G.emptyState,children:["Error: ",f instanceof Error?f.message:"unknown error"]}):x.length===0?i.jsx("div",{className:G.emptyState,children:"No subdirectories"}):x.map(k=>i.jsxs("div",{className:G.item,onClick:()=>S(r==="/"?`/${k.name}`:`${r}/${k.name}`),children:[i.jsx(xt,{size:14}),i.jsx("span",{className:G.name,children:k.name})]},k.name))})]})}const Qc="_shell_1m1nv_1",Zc="_main_1m1nv_7",el="_sidebarLeft_1m1nv_13",tl="_leftHandle_1m1nv_21",nl="_center_1m1nv_24",sl="_sidebarRight_1m1nv_31",ol="_rightHandle_1m1nv_39",ee={shell:Qc,main:Zc,sidebarLeft:el,leftHandle:tl,center:nl,sidebarRight:sl,rightHandle:ol};function rl(){const t=v(a=>a.leftSidebarCollapsed),e=v(a=>a.rightSidebarCollapsed),n=v(a=>a.leftSidebarWidth),s=v(a=>a.rightSidebarWidth),o=v(a=>a.resizeLeftSidebar),r=v(a=>a.resizeRightSidebar);return i.jsxs("div",{className:ee.shell,children:[i.jsx(Jr,{}),i.jsxs("div",{className:ee.main,children:[!t&&i.jsxs("aside",{className:ee.sidebarLeft,style:{width:n},children:[i.jsx(Ua,{}),i.jsx(gt,{side:"left",className:ee.leftHandle,onResize:o})]}),i.jsxs("div",{className:ee.center,children:[i.jsx(ri,{}),i.jsx(yi,{})]}),!e&&i.jsxs("aside",{className:ee.sidebarRight,style:{width:s},children:[i.jsx(gt,{side:"right",className:ee.rightHandle,onResize:r}),i.jsx(Sc,{})]})]}),i.jsx(Yc,{})]})}function al(){const t=w.useRef(!1);w.useEffect(()=>{if(t.current)return;if(t.current=!0,window.location.hash.includes("offer=")){const d=window.location.href;v.getState().setHost(d),j.getState().connect({url:d});return}const e=new URLSearchParams(window.location.search),n=e.get("host"),s=e.get("pair"),o=e.get("password"),r=e.get("cwd"),a=e.get("connect")==="1",l=v.getState();if(s?l.setHost(s):n&&l.setHost(n),o&&l.setPassword(o),r&&l.setCwd(r),s)j.getState().connect({url:s});else if(a){const{host:d,password:p}=v.getState();j.getState().connect({url:d,password:p||void 0})}},[])}function il(t){return typeof t=="object"&&t!==null&&"kind"in t}function cl(t){const e=[];for(const n of t)if(il(n))if(n.kind==="other")n.event&&e.push(n.event);else for(const s of n.events??[])e.push(s);return e}function ll(){const t=j(s=>s.client),e=j(s=>s.status),n=w.useRef(!1);w.useEffect(()=>{e!=="open"||!t||n.current||(n.current=!0,(async()=>{var d;let s=[];try{s=(await t.connection.request("list_agents_request",{all:!1})).agents??[]}catch{s=[]}s.sort((p,h)=>(h.lastActivity??0)-(p.lastActivity??0));const o=$.getState();for(const p of s){if(o.findByAgentId(p.agentId))continue;let h=He;try{const _=await t.agent(p.agentId).timeline.fetch({direction:"after",limit:200});h=cl(_.items).reduce(Lt,He)}catch{}o.hydrate({id:`s-${p.agentId.slice(0,12)}`,agentId:p.agentId,title:p.title||((d=p.cwd)==null?void 0:d.split("/").pop())||"Restored",status:p.status??"idle",cwd:p.cwd||"~",timeline:h,userMessageCount:h.rows.filter(_=>_.kind==="user").length})}const r=await Ee(t).catch(()=>null),{order:a,sessions:l}=$.getState();if(a.length>0){const p=l[a[0]??""];if(p){const h=te(p.cwd||"~",r);$.getState().activate(p.id),v.getState().setCwd(p.cwd),T.getState().open({id:L.chat(p.id),kind:"chat",label:p.title,closable:!0,data:{sessionId:p.id},workspaceCwd:h})}}else{const p=v.getState().cwd||"~",h=te(p,r);je(h)}})())},[e,t])}function dl(){const t=j(s=>s.client),e=j(s=>s.status),n=w.useRef(!1);w.useEffect(()=>{e!=="open"||!t||n.current||(n.current=!0,(async()=>{let s=[];try{s=(await t.connection.request("list_terminals_request",{})).terminals??[]}catch{s=[]}if(s.length===0)return;const o=await Ee(t).catch(()=>null),r=T.getState().open;for(const a of s){if(a.closed)continue;const l=te(a.cwd||"~",o);r({id:L.terminal(a.slot),kind:"terminal",label:a.name,closable:!0,data:{slot:a.slot,cwd:l},workspaceCwd:l})}})())},[e,t])}function ul(){w.useEffect(()=>{function t(e){const n=v.getState();if(e.key==="Escape"){n.closeCwdPicker(),n.closeSessionMenu();return}const s=e.ctrlKey||e.metaKey;if(s&&e.key.toLowerCase()==="t"){e.preventDefault(),Ut(T.getState().activeWorkspaceCwd||"~");return}if(s&&e.key.toLowerCase()==="w"){const{activeTabId:o,tabs:r,close:a}=T.getState();if(!o)return;const l=r.find(d=>d.id===o);(l==null?void 0:l.closable)!==!1&&(e.preventDefault(),a(o))}}return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[])}function pl(){return al(),ll(),dl(),ul(),null}function fl(){return i.jsxs(js,{children:[i.jsx(pl,{}),i.jsx(rl,{})]})}const Qt=document.getElementById("root");if(!Qt)throw new Error("Missing #root element");rn.createRoot(Qt).render(i.jsx(w.StrictMode,{children:i.jsx(fl,{})}));export{H as B,Hc as D,di as S,vl as T,j as a,T as b,ht as c,kl as e,Gt as r,Xr as t,$ as u};
|
|
3
|
-
//# sourceMappingURL=index-CM7PrEq0.js.map
|